-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpyrename
executable file
·70 lines (53 loc) · 2.14 KB
/
pyrename
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
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python3
# Author: github.com/danielhoherd
# License: MIT
"""Regular expression renaming of files.
This was inspired Robin Barker's prename tool. It does not handle
emoji's, so a modern implementation was needed.
"""
import argparse
import re
from pathlib import Path
from sys import exit, stderr
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--ignore-case", "-i", action="store_true", help="Ignore case in regex match")
parser.add_argument("--dry-run", "-n", action="store_true", help="Dry run (do not actually rename)")
parser.add_argument("--verbose", "-v", action="store_true", help="Be verbose", default=False)
parser.add_argument("match", help="Regex to match", type=str)
parser.add_argument("sub", help="Regex substitution", type=str)
parser.add_argument("filenames", nargs="*", help="Files to rename")
args = parser.parse_args()
def eprint(thing):
print(thing, file=stderr)
if len(args.filenames) == 0:
eprint("Error: no files given")
exit(1)
for filename in args.filenames:
try:
old_name = Path(filename)
if not old_name.exists():
eprint(f"Error: {old_name} does not exists")
continue
re_flags = re.IGNORECASE if args.ignore_case else 0
new_name = Path(re.sub(args.match, args.sub, filename, flags=re_flags))
if old_name == new_name:
print(f"No changes needed: {new_name}")
continue
if new_name.exists():
eprint(f"Error: {new_name} exists already")
continue
if args.dry_run:
eprint(f"Would rename: {filename} -> {new_name}")
continue
if args.verbose:
print(f"Renamed: {filename} -> {new_name}")
old_name.rename(new_name)
except (re.error, UnicodeEncodeError, OverflowError) as e:
eprint(e)
exit(1)
if __name__ == "__main__":
try:
exit(main())
except KeyboardInterrupt:
exit(1)