I plan to study VCV Rack. I want to keep track of changes by making regular timestamped backups. To do this I wrote this simple 66-line script which watches the mtime of a file and makes a copy whenever a change is detected.
#!/usr/bin/env python3
import os
import time
import argparse
from datetime import datetime
import shutil
def now():
a = datetime.now()
return a.strftime("%Y_%m_%d_%H_%M_%S")
def when(fn):
if os.path.exists(fn):
return os.path.getmtime(fn)
else:
return -1
def loop(d):
fns = list(d.keys())
for fn in fns:
cur = when(fn)
if cur > d[fn]:
d[fn] = cur
make_copy(fn)
def make_copy(fn):
n = now()
if "." in fn:
xs = fn.split(".")
ext = xs.pop()
basename = ".".join(xs)
ofn = f"{basename}_{n}.{ext}"
else:
ofn = f"{fn}_{n}"
ofn = f"{outdir}/{ofn}"
shutil.copy(fn,ofn)
print(f"{fn} => {ofn}")
def main():
global outdir
parser = argparse.ArgumentParser(prog="autobak1",
description="Automatically make timestamped copies of a watched file")
parser.add_argument("-d","--output-dir",default=".",help="Where to put the auto backups")
parser.add_argument("files",nargs="+")
ns = parser.parse_args()
outdir = ns.output_dir
fns = ns.files
d = {}
for fn in fns:
d[fn] = when(fn)
try:
while True:
loop(d)
time.sleep(1)
except KeyboardInterrupt:
print("C-c")
return
if __name__ == "__main__":
main()