Skip to content

Instantly share code, notes, and snippets.

@alexflint
Created March 13, 2014 21:30
Show Gist options
  • Save alexflint/9537383 to your computer and use it in GitHub Desktop.
Save alexflint/9537383 to your computer and use it in GitHub Desktop.
Command line tool to copy directory snapshots to a timestamped worklog database
#!/usr/local/bin/python
import os
import sys
import shutil
import datetime
WORKLOG_DIR = 'Worklogs'
datetime_fmt = '%Y %m %d %I.%M%p' # eg: "2014 01 03 11.45AM"
dir_name = datetime.datetime.now().strftime(datetime_fmt)
dest_dir = os.path.join(os.environ.get('HOME'), WORKLOG_DIR, dir_name)
if not os.path.exists(dest_dir):
os.mkdir(dest_dir)
print 'Created %s' % dest_dir
# Update symlink
latest = os.path.join(os.environ.get('HOME'), WORKLOG_DIR, 'latest')
if os.path.exists(latest):
assert os.path.islink(latest)
os.remove(latest)
os.symlink(dest_dir, latest)
assert os.path.isdir(dest_dir)
if len(sys.argv) <= 1:
print 'Usage: worklog <item1> <item2> ...'
sys.exit(-1)
paths = sys.argv[1:]
# If there was just one argument and it was a directory then copy
# its contents, not the directory itself
if len(paths) == 1 and os.path.isdir(paths[0]):
paths = list(os.path.join(paths[0], item) for item in os.listdir(paths[0]))
for src in paths:
if not os.path.exists(src):
print 'Path does not exist: %s' % src
continue
if src.endswith('/'):
src = src[:-1] # because os.path.basename('foo/bar/') == ''
dest = os.path.join(dest_dir, os.path.basename(src))
if os.path.exists(dest):
head,tail = os.path.splitext(dest)
suffix = 2
while os.path.exists(head + ' ' + str(suffix) + tail):
suffix += 1
dest = head + ' ' + str(suffix) + tail
print '%s -> %s' % (src, dest)
if os.path.isdir(src):
shutil.copytree(src, dest)
else:
shutil.copy(src, dest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment