-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
92 lines (71 loc) · 2.72 KB
/
main.py
File metadata and controls
92 lines (71 loc) · 2.72 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
from __future__ import annotations
import argparse
import shutil
import sys
from pathlib import Path
from config import DEFAULT_CONFIG_PATH, ConfigError, load_config
from logger import setup_logger
from processor import FileProcessor
from utils import ensure_dir
from watcher import FolderWatcher
def bootstrap_directories(config: dict) -> None:
for key in ["watch_dir", "processed_dir", "archive_dir", "error_dir", "log_dir"]:
ensure_dir(config[key])
def run_once(processor: FileProcessor, watch_dir: str, dry_run: bool) -> int:
files = [item for item in Path(watch_dir).iterdir() if item.is_file()]
if not files:
processor.logger.info("No files found in watch directory")
return 0
exit_code = 0
for file_path in files:
result = processor.process(file_path, dry_run=dry_run)
if result.status == "failed":
exit_code = 1
return exit_code
def init_project(target_dir: str) -> int:
destination = Path(target_dir)
destination.mkdir(parents=True, exist_ok=True)
source = Path(__file__).parent / "config_example.json"
target = destination / "config.json"
if target.exists():
print(f"config.json already exists: {target}")
return 0
shutil.copy2(source, target)
print(f"Created config: {target}")
return 0
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Folder automation tool")
parser.add_argument("--config", default=DEFAULT_CONFIG_PATH, help="Path to config JSON")
parser.add_argument("--dry-run", action="store_true", help="Preview actions without moving files")
parser.add_argument("--once", action="store_true", help="Process current files once and exit")
parser.add_argument("--init", metavar="DIR", help="Create a starter config.json in the target directory")
return parser.parse_args()
def main() -> int:
args = parse_args()
if args.init:
return init_project(args.init)
try:
config = load_config(args.config)
except ConfigError as exc:
print(f"Config error: {exc}", file=sys.stderr)
return 2
log_cfg = config.get("logging", {})
logger = setup_logger(
log_dir=config["log_dir"],
level=log_cfg.get("level", "INFO"),
json_logs=log_cfg.get("json", False),
)
bootstrap_directories(config)
processor = FileProcessor(config=config, logger=logger)
if args.once:
return run_once(processor, config["watch_dir"], dry_run=args.dry_run)
watcher = FolderWatcher(
watch_dir=config["watch_dir"],
processor=processor,
logger=logger,
dry_run=args.dry_run,
)
watcher.start()
return 0
if __name__ == "__main__":
raise SystemExit(main())