Files

80 lines
3.3 KiB
Python

#!/usr/bin/env python3
# Module moves (python3 -I tools/move.py [--dry] old=new ...): moves src/Rosetta/<old>(.luau | /) to <new> with
# git mv, then rewrites every reference to the module path in the repo: requires ("@rosetta/old" and
# "@rosetta/old/Sub"), contract deps ("old"), header comment lines ("-- old: ..." / "-- old/Sub: ..."), fixture
# INPUTS ("src/Rosetta/old"), docs and comments ("old" as a whole path token). Paths are module paths
# (codecs/Deflate, core/Huffman). Generated files are not edited: rerun tools/gen_registry.py afterwards.
#
# python3 -I tools/move.py codecs/Deflate=codecs/compress/Deflate core/Huffman=codecs/entropy/Huffman
import os, re, subprocess, sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = os.path.join(ROOT, "src", "Rosetta")
SCAN = ["src", "tests", "tools", "docs", "examples", "README.md", "default.project.json"]
SKIP = {os.path.join("tests", "gen"), os.path.join("tools", "move.py"), "build"}
EXTS = (".luau", ".lua", ".py", ".md", ".json", ".sh")
def files():
for top in SCAN:
p = os.path.join(ROOT, top)
if os.path.isfile(p):
yield p
continue
for d, dirs, fs in os.walk(p):
rel = os.path.relpath(d, ROOT)
dirs[:] = [x for x in dirs if os.path.join(rel, x) not in SKIP and x not in ("build", "__pycache__")]
for f in fs:
q = os.path.join(d, f)
if f.endswith(EXTS) and os.path.relpath(q, ROOT) not in SKIP:
yield q
def source(mod):
base = os.path.join(SRC, *mod.split("/"))
if os.path.isdir(base):
return base
if os.path.isfile(base + ".luau"):
return base + ".luau"
return None
def main():
dry = "--dry" in sys.argv
pairs = [a.split("=", 1) for a in sys.argv[1:] if "=" in a]
if not pairs:
print(__doc__ if __doc__ else "usage: move.py old=new ...")
sys.exit(2)
for old, new in pairs:
src = source(old)
if not src:
sys.exit("move.py: no module %s" % old)
dst = os.path.join(SRC, *new.split("/")) + ("" if os.path.isdir(src) else ".luau")
if os.path.exists(dst):
sys.exit("move.py: %s exists" % os.path.relpath(dst, ROOT))
print("move %s -> %s" % (os.path.relpath(src, ROOT), os.path.relpath(dst, ROOT)))
if not dry:
os.makedirs(os.path.dirname(dst), exist_ok=True)
subprocess.run(["git", "mv", src, dst], cwd=ROOT, check=True)
# a path token: not preceded by a word char or "."; not followed by a word char
subs = [(re.compile(r"(?<![\w.])" + re.escape(old) + r"(?![\w])"), new) for old, new in pairs]
lua_subs = [(re.compile(r"(?<![\w.])formats\." + re.escape(old.replace("/", ".")) + r"(?![\w])"),
"rosetta." + new.replace("/", ".")) for old, new in pairs]
changed = 0
for f in files():
with open(f, encoding="utf-8", errors="surrogateescape") as h:
text = h.read()
out = text
for rx, rep in subs + lua_subs:
out = rx.sub(rep, out)
if out != text:
changed += 1
if not dry:
with open(f, "w", encoding="utf-8", errors="surrogateescape") as h:
h.write(out)
print("move.py: %d files rewritten%s" % (changed, " (dry run)" if dry else ""))
if __name__ == "__main__":
main()