|
| 1 | +import argparse |
| 2 | +import os |
| 3 | +import shlex |
| 4 | +import tempfile |
| 5 | +import subprocess |
| 6 | +import sys |
| 7 | + |
| 8 | +__version__ = "1.1.0" |
| 9 | + |
| 10 | + |
| 11 | +def main(): |
| 12 | + parser = argparse.ArgumentParser(description="Bulk rename files via a text editor.") |
| 13 | + parser.add_argument( |
| 14 | + "-V", |
| 15 | + "--version", |
| 16 | + action="version", |
| 17 | + version=f"%(prog)s {__version__}", |
| 18 | + ) |
| 19 | + parser.add_argument( |
| 20 | + "-r", |
| 21 | + "--recursive", |
| 22 | + action="store_true", |
| 23 | + help="Recursively list files in the current directory tree.", |
| 24 | + ) |
| 25 | + parser.add_argument("files", nargs="*", help="Files to rename.") |
| 26 | + args = parser.parse_args() |
| 27 | + |
| 28 | + files = args.files |
| 29 | + |
| 30 | + with tempfile.NamedTemporaryFile( |
| 31 | + mode="w+t", delete=False, encoding="utf-8" |
| 32 | + ) as tmpfile: |
| 33 | + filenames_file = tmpfile.name |
| 34 | + |
| 35 | + if files: |
| 36 | + src = files |
| 37 | + elif args.recursive: |
| 38 | + src = [] |
| 39 | + for root, _, filenames in os.walk("."): |
| 40 | + for f in filenames: |
| 41 | + path = os.path.relpath(os.path.join(root, f), ".") |
| 42 | + src.append(path.replace(os.sep, "/")) |
| 43 | + src.sort() |
| 44 | + else: |
| 45 | + src = [f for f in os.listdir(".") if os.path.isfile(f)] |
| 46 | + tmpfile.write("\n".join(src)) |
| 47 | + |
| 48 | + editor = os.environ.get("EDITOR", "notepad.exe") |
| 49 | + editor_cmd = shlex.split(editor) + [filenames_file] |
| 50 | + subprocess.call(editor_cmd) |
| 51 | + |
| 52 | + with open(filenames_file, "r", encoding="utf-8") as tmpfile: |
| 53 | + dest = tmpfile.read().splitlines() |
| 54 | + |
| 55 | + os.remove(filenames_file) |
| 56 | + |
| 57 | + if len(src) != len(dest): |
| 58 | + print( |
| 59 | + "WARN: Number of files changed. Did you delete a line by accident? Aborting..", |
| 60 | + file=sys.stderr, |
| 61 | + ) |
| 62 | + sys.exit(1) |
| 63 | + |
| 64 | + count = 0 |
| 65 | + for s, d in zip(src, dest): |
| 66 | + if s != d: |
| 67 | + dd = os.path.dirname(d) |
| 68 | + |
| 69 | + if dd: |
| 70 | + os.makedirs(dd, exist_ok=True) |
| 71 | + if os.path.exists(d): |
| 72 | + print(f"SKIP: '{d}' already exists, skipping.", file=sys.stderr) |
| 73 | + continue |
| 74 | + os.rename(s, d) |
| 75 | + count += 1 |
| 76 | + |
| 77 | + print(f"{count} files renamed.") |
0 commit comments