-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcop.py
More file actions
685 lines (539 loc) · 18 KB
/
Copy pathcop.py
File metadata and controls
685 lines (539 loc) · 18 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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
from __future__ import annotations
import fnmatch
import json
import shutil
import sys
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Iterable
CONFIG_FILE = ".file_tool_config.json"
@dataclass
class AppConfig:
base_dir: str = "."
recursive: bool = False
include_hidden: bool = False
overwrite: bool = True
dry_run: bool = False
include_dir_patterns: list[str] = field(default_factory=list)
exclude_dir_patterns: list[str] = field(default_factory=list)
def line(char: str = "-", n: int = 72) -> None:
print(char * n)
def pause() -> None:
input("\n按回车继续...")
def safe_input(prompt: str) -> str:
try:
return input(prompt)
except (EOFError, KeyboardInterrupt):
print("\n输入中断,返回上一级。")
return ""
def parse_space_list(text: str) -> list[str]:
text = text.strip()
return text.split() if text else []
def yes_no(prompt: str, default: bool | None = None) -> bool | None:
suffix = " [y/n]: "
if default is True:
suffix = " [Y/n]: "
elif default is False:
suffix = " [y/N]: "
s = safe_input(prompt + suffix).strip().lower()
if not s:
return default
if s in {"y", "yes"}:
return True
if s in {"n", "no"}:
return False
return None
def load_config() -> AppConfig:
cfg_path = Path(CONFIG_FILE)
if not cfg_path.exists():
return AppConfig()
try:
data = json.loads(cfg_path.read_text(encoding="utf-8"))
return AppConfig(**data)
except Exception:
print("配置文件读取失败,已使用默认配置。")
return AppConfig()
def save_config(cfg: AppConfig) -> None:
Path(CONFIG_FILE).write_text(
json.dumps(asdict(cfg), ensure_ascii=False, indent=2),
encoding="utf-8"
)
def get_base_path(cfg: AppConfig) -> Path:
return Path(cfg.base_dir).expanduser().resolve()
def is_hidden_relative(path: Path, base: Path) -> bool:
rel = path.relative_to(base)
return any(part.startswith(".") for part in rel.parts)
def match_any(path: Path, patterns: list[str], base: Path) -> bool:
if not patterns:
return True
name = path.name
rel = path.relative_to(base).as_posix()
for pat in patterns:
if fnmatch.fnmatch(name, pat) or fnmatch.fnmatch(rel, pat):
return True
return False
def unique_paths(paths: Iterable[Path]) -> list[Path]:
seen = set()
out = []
for p in paths:
try:
key = str(p.resolve())
except Exception:
key = str(p.absolute())
if key not in seen:
seen.add(key)
out.append(p)
return out
def collect_target_dirs(cfg: AppConfig) -> list[Path]:
base = get_base_path(cfg)
if not base.exists() or not base.is_dir():
return []
if cfg.recursive:
candidates = [p for p in base.rglob("*") if p.is_dir()]
else:
candidates = [p for p in base.iterdir() if p.is_dir()]
result = []
for d in candidates:
if d == base:
continue
if not cfg.include_hidden and is_hidden_relative(d, base):
continue
if cfg.exclude_dir_patterns and match_any(d, cfg.exclude_dir_patterns, base):
continue
if cfg.include_dir_patterns and not match_any(d, cfg.include_dir_patterns, base):
continue
result.append(d)
return unique_paths(sorted(result))
def collect_source_files(base: Path, patterns: list[str]) -> list[Path]:
found = []
for pat in patterns:
p = Path(pat)
if p.is_absolute():
if p.exists() and p.is_file():
found.append(p)
continue
matches = [x for x in base.glob(pat) if x.is_file()]
if matches:
found.extend(matches)
continue
exact = base / pat
if exact.exists() and exact.is_file():
found.append(exact)
return unique_paths(sorted(found))
def collect_files_in_dirs(dirs: list[Path], patterns: list[str]) -> list[Path]:
found = []
for d in dirs:
for pat in patterns:
found.extend([x for x in d.glob(pat) if x.is_file()])
return unique_paths(sorted(found))
def parse_index_selection(text: str, max_n: int) -> list[int]:
result = set()
parts = text.strip().split()
for part in parts:
if "-" in part:
try:
a, b = part.split("-", 1)
a, b = int(a), int(b)
if a > b:
a, b = b, a
for i in range(a, b + 1):
if 1 <= i <= max_n:
result.add(i)
except ValueError:
pass
else:
try:
i = int(part)
if 1 <= i <= max_n:
result.add(i)
except ValueError:
pass
return sorted(result)
def show_config(cfg: AppConfig) -> None:
line()
print("当前配置")
print(f"工作目录 : {get_base_path(cfg)}")
print(f"递归处理 : {'是' if cfg.recursive else '否'}")
print(f"包含隐藏目录 : {'是' if cfg.include_hidden else '否'}")
print(f"覆盖同名文件 : {'是' if cfg.overwrite else '否'}")
print(f"预演模式 : {'是' if cfg.dry_run else '否'}")
print(f"仅包含目录模式 : {cfg.include_dir_patterns if cfg.include_dir_patterns else '不限'}")
print(f"排除目录模式 : {cfg.exclude_dir_patterns if cfg.exclude_dir_patterns else '无'}")
line()
def choose_target_dirs(cfg: AppConfig) -> list[Path]:
base = get_base_path(cfg)
dirs = collect_target_dirs(cfg)
if not dirs:
print("没有找到任何符合条件的目标目录。")
return []
line()
print("可选目标目录:")
for i, d in enumerate(dirs, 1):
print(f"{i:>3}. {d}")
line()
print("选择方式:")
print("1. 全部目录")
print("2. 按目录名模式筛选")
print("3. 按编号手动选择")
print("0. 取消")
mode = safe_input("请输入数字: ").strip()
if mode == "1":
return dirs
if mode == "2":
s = safe_input('输入目录模式,多个空格分隔,例如: job_* calc* test01\n> ')
patterns = parse_space_list(s)
if not patterns:
print("未输入模式,已取消。")
return []
chosen = [d for d in dirs if match_any(d, patterns, base)]
if not chosen:
print("没有匹配到任何目录。")
return []
print(f"已选中 {len(chosen)} 个目录。")
return chosen
if mode == "3":
print("输入编号,支持空格和范围。")
print("例如: 1 3 5")
print("例如: 1-5 8 10-12")
s = safe_input("> ")
indexes = parse_index_selection(s, len(dirs))
if not indexes:
print("没有选中任何目录。")
return []
chosen = [dirs[i - 1] for i in indexes]
print(f"已选中 {len(chosen)} 个目录。")
return chosen
print("已取消。")
return []
def configure_settings(cfg: AppConfig) -> None:
while True:
show_config(cfg)
print("1. 设置工作目录")
print("2. 切换递归处理")
print("3. 切换包含隐藏目录")
print("4. 切换覆盖同名文件")
print("5. 切换预演模式")
print("6. 设置仅包含哪些目录")
print("7. 设置排除哪些目录")
print("8. 重置为默认配置")
print("0. 返回主菜单")
choice = safe_input("请输入数字: ").strip()
if choice == "1":
s = safe_input("输入工作目录,直接回车表示当前目录: ").strip()
if not s:
cfg.base_dir = "."
else:
p = Path(s).expanduser().resolve()
if p.exists() and p.is_dir():
cfg.base_dir = str(p)
else:
print("目录不存在。")
elif choice == "2":
cfg.recursive = not cfg.recursive
elif choice == "3":
cfg.include_hidden = not cfg.include_hidden
elif choice == "4":
cfg.overwrite = not cfg.overwrite
elif choice == "5":
cfg.dry_run = not cfg.dry_run
elif choice == "6":
s = safe_input('输入目录模式,多个空格分隔,例如: job_* calc/*\n> ')
cfg.include_dir_patterns = parse_space_list(s)
elif choice == "7":
s = safe_input('输入要排除的目录模式,多个空格分隔,例如: .git backup* old/*\n> ')
cfg.exclude_dir_patterns = parse_space_list(s)
elif choice == "8":
cfg.base_dir = "."
cfg.recursive = False
cfg.include_hidden = False
cfg.overwrite = True
cfg.dry_run = False
cfg.include_dir_patterns = []
cfg.exclude_dir_patterns = []
elif choice == "0":
save_config(cfg)
return
else:
print("输入无效。")
def distribute_files(cfg: AppConfig) -> None:
base = get_base_path(cfg)
show_config(cfg)
s = safe_input('输入要分发的源文件或通配符,多个空格分隔,例如: INCAR POSCAR "*.txt"\n> ')
patterns = parse_space_list(s)
if not patterns:
print("未输入源文件。")
pause()
return
sources = collect_source_files(base, patterns)
if not sources:
print("没有找到任何源文件。")
pause()
return
target_dirs = choose_target_dirs(cfg)
if not target_dirs:
pause()
return
line()
print("即将执行文件分发")
print(f"源文件数量 : {len(sources)}")
print(f"目标目录数量: {len(target_dirs)}")
print(f"总任务数 : {len(sources) * len(target_dirs)}")
line()
copied = 0
skipped = 0
failed = 0
ok = yes_no("确认执行吗", default=False)
if ok is not True:
print("已取消。")
pause()
return
for folder in target_dirs:
for src in sources:
dst = folder / src.name
try:
if dst.exists():
try:
if src.resolve() == dst.resolve():
print(f"[跳过] 同一文件: {src}")
skipped += 1
continue
except Exception:
pass
if dst.exists() and not cfg.overwrite:
print(f"[跳过] 已存在: {dst}")
skipped += 1
continue
if cfg.dry_run:
action = "覆盖" if dst.exists() else "复制"
print(f"[预演] 将{action}: {src} -> {dst}")
copied += 1
continue
shutil.copy2(src, dst)
print(f"[完成] {src.name} -> {folder}")
copied += 1
except Exception as e:
print(f"[失败] {src} -> {dst} | {e}")
failed += 1
line()
print("文件分发结束")
print(f"成功/预演: {copied}")
print(f"跳过 : {skipped}")
print(f"失败 : {failed}")
line()
pause()
def delete_files(cfg: AppConfig) -> None:
show_config(cfg)
s = safe_input('输入要删除的文件名或通配符,多个空格分隔,例如: WAVECAR CHGCAR "*.tmp"\n> ')
patterns = parse_space_list(s)
if not patterns:
print("未输入删除模式。")
pause()
return
target_dirs = choose_target_dirs(cfg)
if not target_dirs:
pause()
return
files = collect_files_in_dirs(target_dirs, patterns)
if not files:
print("没有匹配到任何待删除文件。")
pause()
return
line()
print("即将删除以下文件")
for f in files[:50]:
print(f" {f}")
if len(files) > 50:
print(f" ... 其余 {len(files) - 50} 个未显示")
line()
print(f"总数量: {len(files)}")
ok = yes_no("确认删除吗,这个操作有风险", default=False)
if ok is not True:
print("已取消。")
pause()
return
deleted = 0
failed = 0
for f in files:
try:
if cfg.dry_run:
print(f"[预演] 将删除: {f}")
deleted += 1
continue
f.unlink()
print(f"[完成] 已删除: {f}")
deleted += 1
except Exception as e:
print(f"[失败] {f} | {e}")
failed += 1
line()
print("批量删除结束")
print(f"成功/预演: {deleted}")
print(f"失败 : {failed}")
line()
pause()
def rename_files(cfg: AppConfig) -> None:
show_config(cfg)
pattern = safe_input('输入要匹配的文件模式,例如: "*.out" 或 "job_*.txt"\n> ').strip()
if not pattern:
print("未输入匹配模式。")
pause()
return
mode = safe_input("选择重命名方式:1. 前缀 2. 后缀 3. 替换字符串\n> ").strip()
if mode not in {"1", "2", "3"}:
print("输入无效。")
pause()
return
if mode == "1":
value = safe_input("输入要添加的前缀: ")
elif mode == "2":
value = safe_input("输入要添加的后缀: ")
else:
old = safe_input("输入要替换的旧字符串: ")
new = safe_input("输入新字符串: ")
value = (old, new)
target_dirs = choose_target_dirs(cfg)
if not target_dirs:
pause()
return
files = collect_files_in_dirs(target_dirs, [pattern])
if not files:
print("没有匹配到任何文件。")
pause()
return
tasks: list[tuple[Path, Path]] = []
for src in files:
if mode == "1":
dst = src.with_name(value + src.name)
elif mode == "2":
dst = src.with_name(src.stem + value + src.suffix)
else:
old, new = value
dst = src.with_name(src.name.replace(old, new))
if dst != src:
tasks.append((src, dst))
if not tasks:
print("没有需要重命名的文件。")
pause()
return
line()
print("即将执行重命名")
for src, dst in tasks[:50]:
print(f" {src.name} -> {dst.name}")
if len(tasks) > 50:
print(f" ... 其余 {len(tasks) - 50} 个未显示")
line()
print(f"总数量: {len(tasks)}")
ok = yes_no("确认执行重命名吗", default=False)
if ok is not True:
print("已取消。")
pause()
return
renamed = 0
skipped = 0
failed = 0
for src, dst in tasks:
try:
if dst.exists() and not cfg.overwrite:
print(f"[跳过] 目标已存在: {dst}")
skipped += 1
continue
if cfg.dry_run:
print(f"[预演] 将重命名: {src} -> {dst}")
renamed += 1
continue
src.rename(dst)
print(f"[完成] {src} -> {dst}")
renamed += 1
except Exception as e:
print(f"[失败] {src} -> {dst} | {e}")
failed += 1
line()
print("批量重命名结束")
print(f"成功/预演: {renamed}")
print(f"跳过 : {skipped}")
print(f"失败 : {failed}")
line()
pause()
def stats_report(cfg: AppConfig) -> None:
base = get_base_path(cfg)
target_dirs = choose_target_dirs(cfg)
if not target_dirs:
pause()
return
total_files = 0
total_subdirs = 0
total_size = 0
line()
print("目录统计")
for d in target_dirs:
files = 0
subdirs = 0
size = 0
try:
for p in d.iterdir():
if p.is_file():
files += 1
try:
size += p.stat().st_size
except Exception:
pass
elif p.is_dir():
subdirs += 1
total_files += files
total_subdirs += subdirs
total_size += size
print(f"{d}")
print(f" 文件数: {files:<6} 子目录数: {subdirs:<6} 大小: {size / 1024:.2f} KB")
except Exception as e:
print(f"{d}")
print(f" 统计失败: {e}")
line()
print(f"工作目录 : {base}")
print(f"目标目录总数 : {len(target_dirs)}")
print(f"文件总数 : {total_files}")
print(f"子目录总数 : {total_subdirs}")
print(f"总大小 : {total_size / 1024 / 1024:.2f} MB")
line()
pause()
def main_menu() -> None:
cfg = load_config()
while True:
print("\n")
line("=")
print("终端文件批处理工具")
line("=")
print("1. 文件分发到目标子目录")
print("2. 批量删除文件")
print("3. 批量重命名文件")
print("4. 目录统计")
print("5. 配置中心")
print("6. 查看当前配置")
print("7. 保存当前配置")
print("0. 退出")
line("=")
choice = safe_input("请输入数字: ").strip()
if choice == "1":
distribute_files(cfg)
elif choice == "2":
delete_files(cfg)
elif choice == "3":
rename_files(cfg)
elif choice == "4":
stats_report(cfg)
elif choice == "5":
configure_settings(cfg)
elif choice == "6":
show_config(cfg)
pause()
elif choice == "7":
save_config(cfg)
print(f"配置已保存到 {CONFIG_FILE}")
pause()
elif choice == "0":
save_config(cfg)
print("已退出。")
sys.exit(0)
else:
print("输入无效。")
if __name__ == "__main__":
main_menu()