-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenamer.py
More file actions
326 lines (266 loc) · 10.6 KB
/
renamer.py
File metadata and controls
326 lines (266 loc) · 10.6 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#!/usr/bin/env python3
"""
renamer -- Batch rename files with regex, preview, undo. Zero deps.
Renames files using regex patterns, sequential numbering, case changes.
Preview by default -- won't rename until you pass --execute.
Usage:
py renamer.py "(.+)\\.txt" "{1}.md" # .txt -> .md (preview)
py renamer.py "(.+)\\.txt" "{1}.md" --execute # Actually rename
py renamer.py "(\\w+)-(\\w+)" "{2}_{1}" -g "*.txt" # Swap parts
py renamer.py ".*" "{n:03d}_{name}" -g "*.jpg" # Number files: 001_photo.jpg
py renamer.py ".*" "{lower}" -g "*.PDF" # Lowercase extension
py renamer.py ".*" "prefix_{name}" # Add prefix
py renamer.py ".*" "{name}{upper_ext}" # Uppercase extension
py renamer.py "old" "new" -r # Recursive
py renamer.py --undo # Undo last rename batch
Pattern variables in replacement:
{1}, {2}, ... Regex capture groups
{name} Original filename (without extension)
{ext} Original extension (with dot)
{n} Sequential number (1, 2, 3...)
{n:03d} Zero-padded number (001, 002...)
{lower} Lowercased full filename
{upper} Uppercased full filename
{title} Title-cased full filename
{lower_ext} Lowercased extension
{upper_ext} Uppercased extension
{date} File modification date (YYYY-MM-DD)
{size} File size in bytes
"""
import argparse
import glob
import json
import os
import re
import sys
import time
from datetime import datetime
from pathlib import Path
# Colors
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
CYAN = "\033[36m"
RED = "\033[31m"
UNDO_FILE = ".renamer_undo.json"
def color_supported() -> bool:
if os.environ.get("NO_COLOR"):
return False
if sys.platform == "win32":
return bool(os.environ.get("TERM") or os.environ.get("WT_SESSION"))
return hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
USE_COLOR = color_supported()
def c(code: str, text: str) -> str:
return f"{code}{text}{RESET}" if USE_COLOR else text
def collect_files(directory: str, glob_pattern: str | None, recursive: bool) -> list[Path]:
"""Collect files matching the glob pattern."""
base = Path(directory)
if glob_pattern:
if recursive:
pattern = f"**/{glob_pattern}"
else:
pattern = glob_pattern
files = sorted(base.glob(pattern))
else:
if recursive:
files = sorted(f for f in base.rglob("*") if f.is_file())
else:
files = sorted(f for f in base.iterdir() if f.is_file())
return [f for f in files if f.is_file() and f.name != UNDO_FILE]
def build_new_name(filepath: Path, search: re.Pattern, replacement: str,
index: int) -> str | None:
"""Build new filename from pattern and replacement template."""
original_name = filepath.name
stem = filepath.stem
ext = filepath.suffix
# Try regex match
match = search.search(original_name)
if not match:
return None
# Start with the replacement template
new_name = replacement
# Substitute regex groups {1}, {2}, etc.
for i, group in enumerate(match.groups(), 1):
if group is not None:
new_name = new_name.replace(f"{{{i}}}", group)
# Also support \1, \2 style
for i, group in enumerate(match.groups(), 1):
if group is not None:
new_name = new_name.replace(f"\\{i}", group)
# Substitute named variables
try:
mtime = datetime.fromtimestamp(filepath.stat().st_mtime)
fsize = filepath.stat().st_size
except OSError:
mtime = datetime.now()
fsize = 0
replacements = {
"name": stem,
"ext": ext,
"lower": original_name.lower(),
"upper": original_name.upper(),
"title": original_name.title(),
"lower_ext": ext.lower(),
"upper_ext": ext.upper(),
"date": mtime.strftime("%Y-%m-%d"),
"datetime": mtime.strftime("%Y%m%d_%H%M%S"),
"size": str(fsize),
"n": str(index),
}
for key, val in replacements.items():
new_name = new_name.replace(f"{{{key}}}", val)
# Handle formatted numbers like {n:03d}
fmt_match = re.search(r"\{n:([^}]+)\}", new_name)
if fmt_match:
fmt = fmt_match.group(1)
try:
formatted = format(index, fmt)
new_name = new_name[:fmt_match.start()] + formatted + new_name[fmt_match.end():]
except (ValueError, TypeError):
pass
# If replacement didn't include extension and original had one, keep it
# (only if the new name doesn't already have one)
if ext and not Path(new_name).suffix and "{ext}" not in replacement:
new_name += ext
return new_name
def preview_renames(renames: list[tuple[Path, str]]) -> None:
"""Display preview of renames."""
if not renames:
print(c(DIM, " No files matched."))
return
max_old = max(len(old.name) for old, _ in renames)
print()
for old_path, new_name in renames:
old_name = old_path.name
if old_name == new_name:
print(c(DIM, f" {old_name:<{max_old}} (unchanged)"))
else:
print(f" {c(RED, old_name):<{max_old + len(RED) + len(RESET) if USE_COLOR else max_old}} -> {c(GREEN, new_name)}")
changed = sum(1 for old, new in renames if old.name != new)
print()
print(c(DIM, f" {changed} file(s) will be renamed, {len(renames) - changed} unchanged"))
def execute_renames(renames: list[tuple[Path, str]], directory: str) -> int:
"""Execute the renames and save undo log."""
undo_log = []
count = 0
errors = 0
for old_path, new_name in renames:
if old_path.name == new_name:
continue
new_path = old_path.parent / new_name
# Check for conflicts
if new_path.exists() and new_path != old_path:
print(c(RED, f" SKIP: {new_name} already exists"))
errors += 1
continue
try:
old_path.rename(new_path)
undo_log.append({"old": str(old_path), "new": str(new_path)})
print(f" {c(GREEN, 'OK')} {old_path.name} -> {new_name}")
count += 1
except OSError as e:
print(c(RED, f" FAIL: {old_path.name}: {e}"))
errors += 1
# Save undo log
if undo_log:
undo_path = Path(directory) / UNDO_FILE
undo_data = {
"timestamp": datetime.now().isoformat(),
"renames": undo_log,
}
undo_path.write_text(json.dumps(undo_data, indent=2), encoding="utf-8")
print()
print(f" {c(GREEN, f'Renamed {count} file(s)')}", end="")
if errors:
print(f", {c(RED, f'{errors} error(s)')}", end="")
print()
if undo_log:
print(c(DIM, f" Undo available: py renamer.py --undo"))
print()
return 0 if errors == 0 else 1
def undo_renames(directory: str) -> int:
"""Undo the last rename batch."""
undo_path = Path(directory) / UNDO_FILE
if not undo_path.exists():
print(c(RED, " No undo log found."))
return 1
data = json.loads(undo_path.read_text(encoding="utf-8"))
renames = data.get("renames", [])
ts = data.get("timestamp", "unknown")
print(f"\n Undoing {len(renames)} rename(s) from {ts}\n")
count = 0
for entry in reversed(renames):
old_path = Path(entry["new"]) # current name
new_path = Path(entry["old"]) # original name
if not old_path.exists():
print(c(YELLOW, f" SKIP: {old_path.name} not found"))
continue
try:
old_path.rename(new_path)
print(f" {c(GREEN, 'OK')} {old_path.name} -> {new_path.name}")
count += 1
except OSError as e:
print(c(RED, f" FAIL: {old_path.name}: {e}"))
undo_path.unlink()
print(f"\n {c(GREEN, f'Restored {count} file(s)')}\n")
return 0
def main():
parser = argparse.ArgumentParser(
description="renamer -- batch rename files with regex and preview",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("search", nargs="?", help="Regex pattern to match filenames")
parser.add_argument("replace", nargs="?", help="Replacement template")
parser.add_argument("-d", "--dir", default=".", help="Directory to search (default: .)")
parser.add_argument("-g", "--glob", help="Glob pattern to filter files (e.g. '*.txt')")
parser.add_argument("-r", "--recursive", action="store_true", help="Search directories recursively")
parser.add_argument("-x", "--execute", action="store_true", help="Actually rename (default: preview only)")
parser.add_argument("--undo", action="store_true", help="Undo last rename batch")
parser.add_argument("--start", type=int, default=1, help="Starting number for {n} (default: 1)")
args = parser.parse_args()
if args.undo:
sys.exit(undo_renames(args.dir))
if not args.search or not args.replace:
parser.print_help()
sys.exit(1)
# Compile regex
try:
search = re.compile(args.search)
except re.error as e:
print(f"Error: invalid regex '{args.search}': {e}", file=sys.stderr)
sys.exit(1)
# Collect files
files = collect_files(args.dir, args.glob, args.recursive)
if not files:
print(c(DIM, " No files found."))
sys.exit(0)
# Build rename plan
renames = []
for i, filepath in enumerate(files, args.start):
new_name = build_new_name(filepath, search, args.replace, i)
if new_name is not None:
renames.append((filepath, new_name))
if not renames:
print(c(DIM, " No files matched the pattern."))
sys.exit(0)
# Check for duplicate targets
targets = [new for _, new in renames if new != _.name for _ in [_]]
# Simpler duplicate check
seen_targets = {}
for old, new in renames:
if old.name != new:
if new in seen_targets:
print(c(RED, f" Error: multiple files would be renamed to '{new}'"))
sys.exit(1)
seen_targets[new] = old
if args.execute:
print(f"\n {c(BOLD, 'renamer')} -- executing renames\n")
sys.exit(execute_renames(renames, args.dir))
else:
print(f"\n {c(BOLD, 'renamer')} -- preview (add --execute to rename)\n")
preview_renames(renames)
print(c(YELLOW, "\n This is a PREVIEW. Add --execute to rename files.\n"))
if __name__ == "__main__":
main()