forked from willyd/caffe-builder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
replace_absolute_paths.py
66 lines (52 loc) · 2.13 KB
/
replace_absolute_paths.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# -- coding: utf-8 --
import os
import re
# match any path of the form DRIVE_LETTER:/path/gh
pattern = r'([a-zA-Z]:/(((?![<>:"/;|?*]).)+((?<![ .])/)?)*)'
regex = re.compile(pattern)
class FileNotFoundError(Exception):
"""
Exception raised when a file is not found
"""
def replace_absolute_paths(filepath, outfilepath=None):
"""
Replaces absolute paths in a CMake exported targets file
with paths relative to that targets file in order to make
them relocatable
"""
if not os.path.exists(filepath):
raise FileNotFoundError("File not found: %s" %filepath)
# get the input file directory and make it absolute
basepath = os.path.abspath(os.path.dirname(filepath))
# make this prefix CMake compatible
prefix = basepath.replace('\\', '/')
# read the input file
with open(filepath, 'r') as f:
content = f.read()
# any path in the input file
matches = regex.findall(content)
# the first group of the match is the full file path
matches = [m[0] for m in matches]
for m in matches:
# make sure that the match and prefix are on the same drive
if m[0].upper() == basepath[0].upper():
# find the relative path
path = os.path.join(basepath, os.path.relpath(m, basepath))
# make it cmake friendly
path = path.replace('\\', '/')
# replace the prefix with a CMake variable
path = path.replace(prefix, '${CMAKE_CURRENT_LIST_DIR}')
content = content.replace(m, path)
if outfilepath is None:
outfilepath = filepath
with open(outfilepath, 'w') as f:
f.write(content)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Replace absolute paths in CMake exported targets file.')
parser.add_argument('inputfile', metavar='i', type=str,
help='Input CMake targets file')
parser.add_argument('outputfile', metavar='o', type=str, nargs='?', default=None,
help='Output CMake targets file')
args = parser.parse_args()
replace_absolute_paths(args.inputfile, args.outputfile)