- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup.py
More file actions
Latest commit
48 lines (40 loc) · 1.73 KB
/
Copy pathbackup.py
File metadata and controls
48 lines (40 loc) · 1.73 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
frompathlibimportPath
fromdatetimeimportdatetime
importargparse, zipfile, tarfile, sys
defcreate_backup(source: Path, outdir: Path, fmt: str="zip") ->Path:
"""Create a compressed archive of `source` inside `outdir`.
fmt: 'zip' or 'tar' (tar -> .tar.gz)
Returns the path to the created archive.
"""
source=Path(source)
outdir=Path(outdir)
ifnotsource.exists() ornotsource.is_dir():
print(f"ERROR: Source folder not found: {source}")
sys.exit(1)
outdir.mkdir(parents=True, exist_ok=True)
ts=datetime.now().strftime("%Y%m%d_%H%M%S")
iffmt=="zip":
archive=outdir/f"backup_{source.name}_{ts}.zip"
withzipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) aszf:
forpathinsource.rglob("*"):
zf.write(path, arcname=path.relative_to(source))
eliffmt=="tar":
archive=outdir/f"backup_{source.name}_{ts}.tar.gz"
withtarfile.open(archive, "w:gz") astf:
tf.add(source, arcname=source.name)
else:
print("ERROR: Unknown format. Use 'zip' or 'tar'.")
sys.exit(2)
print(f"✅ Backup created: {archive}")
returnarchive
defmain():
p=argparse.ArgumentParser(description="Compress a directory into zip/tar.gz")
p.add_argument("-s","--source", default="my_data", help="Folder to back up")
p.add_argument("-o","--outdir", default="backups", help="Where to store backups")
p.add_argument("-f","--format", choices=["zip","tar"], default="zip", help="Archive format")
args=p.parse_args()
src=Path(args.source).expanduser().resolve()
out=Path(args.outdir).expanduser().resolve()
create_backup(src, out, args.format)
if__name__=="__main__":
main()