RoboHome / code /robohome /src /tools /relocate_paths.py
RoboParty Release
Unify robohome source, assets and scenes delivery
3f15e9f
Raw History Blame Contribute Delete
4.41 kB
#!/usr/bin/env python3
"""Rewrite recorded machine paths in data files when the data lives somewhere else.
Some JSON files and notes record where external data (RPLAN, the asset library, curated releases) was found on the machine they were made
on. This tool writes copies of such files with the path prefixes replaced; it never changes the inputs.
relocate_paths.py --map /old/prefix=/new/prefix [--map ...] --out DIR [--report] PATH [PATH ...]
relocate_paths.py --map ... --check PATH [PATH ...] # writes nothing; exit status 1 if a machine path is left that no --map covers
Directories are searched recursively for text files (.json .jsonl .md .txt .sh .yaml .yml .toml .csv); the relative layout is kept under --out.
The longest matching --map wins. A rewritten .json file must still parse, otherwise the tool stops.
"""
import argparse
import json
import re
import sys
from pathlib import Path
TEXT_SUFFIXES = {'.json', '.jsonl', '.md', '.txt', '.sh', '.yaml', '.yml', '.toml', '.csv'}
MACHINE_PATH = re.compile(r'(?<![\w./-])/(?:mnt|data|home)/[\w.-]+(?:/[\w.@+-]+)*')
def parse_maps(values):
pairs = []
for value in values:
old, sep, new = value.partition('=')
if not sep or not old.startswith('/') or not new:
raise SystemExit('--map needs OLD=NEW with an absolute OLD prefix, got %r' % value)
pairs.append((old.rstrip('/'), new.rstrip('/')))
return sorted(pairs, key=lambda p: -len(p[0]))
def rewrite(text, pairs):
"""Return (new text, number of replaced path prefixes). Only whole path components are replaced."""
count = 0
for old, new in pairs:
pattern = re.compile(re.escape(old) + r'(?=/|["\'\s,;:)\]}]|$)')
text, n = pattern.subn(new.replace('\\', '\\\\'), text)
count += n
return text, count
def files_under(paths):
for path in paths:
path = Path(path)
if path.is_dir():
for child in sorted(path.rglob('*')):
if child.is_file() and child.suffix in TEXT_SUFFIXES and '.git' not in child.parts:
yield child, child.relative_to(path)
elif path.is_file():
yield path, Path(path.name)
else:
raise SystemExit('no such file or directory: %s' % path)
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument('--map', action='append', default=[], help='OLD=NEW path prefix (repeatable)')
ap.add_argument('--out', type=Path, help='directory that receives the rewritten copies')
ap.add_argument('--check', action='store_true', help='write nothing; fail if an unmapped machine path remains')
ap.add_argument('--report', action='store_true', help='print the replacements per file')
ap.add_argument('paths', nargs='+')
args = ap.parse_args(argv)
if not args.check and not args.out:
ap.error('--out is required unless --check is given')
pairs = parse_maps(args.map)
total, leftovers = 0, {}
for source, relative in files_under(args.paths):
original = source.read_text(encoding='utf-8', errors='surrogateescape')
text, count = rewrite(original, pairs)
total += count
if source.suffix == '.json' and count:
try:
json.loads(text)
except ValueError as exc:
raise SystemExit('%s is no longer valid JSON after the rewrite: %s' % (source, exc))
for match in MACHINE_PATH.findall(text):
leftovers.setdefault(match, set()).add(str(source))
if args.report and count:
print('%5d %s' % (count, source))
if not args.check:
target = args.out / relative
if target.resolve() == source.resolve():
raise SystemExit('refusing to overwrite the input %s; choose another --out' % source)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(text, encoding='utf-8', errors='surrogateescape')
print('%d path prefixes rewritten' % total)
if leftovers:
print('machine paths no --map covers (%d distinct):' % len(leftovers))
for path in sorted(leftovers)[:40]:
print(' %s (%s)' % (path, ', '.join(sorted(leftovers[path])[:2])))
return 1 if args.check and leftovers else 0
if __name__ == '__main__':
sys.exit(main())