packer/main.py

85 lines
2.1 KiB
Python
Raw Normal View History

2020-04-16 11:50:53 +02:00
import argparse
import sys
import re
import os
from pathlib import Path
import shutil
2020-04-16 11:59:58 +02:00
# parse arguments
2020-04-16 11:50:53 +02:00
parser = argparse.ArgumentParser(description="parse netlist and pack all references to current working directory")
parser.add_argument("files", nargs="*", type=argparse.FileType("r"), default=sys.stdin)
parser.add_argument("-d", action="store_const", const=True, default=False, help="Dryrun")
args = parser.parse_args()
fileregex = re.compile(r"(?<!\w)file=\"(.*?)\"")
files = {}
2020-04-16 11:59:58 +02:00
# process all netlists
2020-04-16 11:50:53 +02:00
for file in args.files:
location = Path(file.name)
print(f"parsing {file.name}")
content = file.read()
with open(location.name, "w+") as outfile:
last = 0
2020-04-16 11:59:58 +02:00
# iterate over all matches
2020-04-16 11:50:53 +02:00
for match in fileregex.finditer(content):
start = match.start(1)
end = match.end(1)
2020-04-16 11:59:58 +02:00
2020-04-16 11:50:53 +02:00
path = Path(match.group(1))
destpath = path
2020-04-16 11:59:58 +02:00
# build the destination in the current folder
# for the retrieved file reference
2020-04-16 11:50:53 +02:00
if path.is_absolute():
try:
destpath = path.relative_to(location.parent)
except ValueError:
destpath = Path(*path.parts[-4:])
else:
path = Path.cwd() / path
print(destpath.root)
if destpath.parts[0] == "..":
destpath = Path(*destpath.parts[1:])
2020-04-16 11:59:58 +02:00
# write the new path the new netlist file
2020-04-16 11:50:53 +02:00
outfile.write(content[last:start])
outfile.write(str(destpath))
2020-04-16 11:59:58 +02:00
# remember file to be copied for later
2020-04-16 11:50:53 +02:00
files[path] = destpath
last = end
outfile.write(content[last:])
2020-04-16 11:59:58 +02:00
# do dryrun if it is wanted
2020-04-16 11:50:53 +02:00
if args.d:
for file in files:
print(f"copy {file} -> {files[file]}")
exit(0)
2020-04-16 11:59:58 +02:00
# copy all files found in netlist earlier
2020-04-16 11:50:53 +02:00
for file in files:
src = Path(file)
dst = Path(files[file])
if not src.exists():
print(f"src does not exist: {str(src)}")
continue
2020-04-16 11:59:58 +02:00
# create directory
2020-04-16 11:50:53 +02:00
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(src, dst)
2020-04-16 11:59:58 +02:00
2020-04-16 11:50:53 +02:00