From 7bafd4c5818355a03b657c6ceef1aee3d13a27a7 Mon Sep 17 00:00:00 2001 From: Buddy Sandidge Date: Sun, 4 Nov 2012 11:57:47 -0800 Subject: [PATCH] Add script that moves files while prepending a date --- bin/mv-to-docs | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100755 bin/mv-to-docs diff --git a/bin/mv-to-docs b/bin/mv-to-docs new file mode 100755 index 0000000..e958080 --- /dev/null +++ b/bin/mv-to-docs @@ -0,0 +1,74 @@ +#!/usr/bin/env python +""" +Move a document to the correct documents folder +""" + +import filecmp +import os +import re +import sys + +from datetime import date + +_slugify_strip_re = re.compile(r'[^\w\s-]') +_slugify_hyphenate_re = re.compile(r'[-\s]+') +def slugify(value): + """ + Normalizes string, converts to lowercase, removes non-alpha characters, + and converts spaces to hyphens. + + From Django's "django/template/defaultfilters.py". + """ + import unicodedata + if not isinstance(value, unicode): + value = unicode(value) + value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') + value = unicode(_slugify_strip_re.sub('', value).strip().lower()) + return _slugify_hyphenate_re.sub('-', value) + +def usage(): + return "Usage: mv-to-docs [SRC_DOC] [CATEGORY] [MSG]" + +if __name__ == "__main__": + try: + file_name = sys.argv[1] + dir_name = slugify(sys.argv[2]) + except IndexError: + sys.exit(usage()) + + try: + msg = slugify(sys.argv[3]) + except IndexError: + msg = "" + + file_type = file_name.split(".")[-1] + + if not os.path.isfile(file_name): + print "ERROR: Cannot find file '%s'" % file_name + sys.exit(usage()) + + file_date = date.fromtimestamp(os.path.getmtime(file_name)) + + doc_path = os.path.expanduser("~/documents/records/%s" % dir_name) + if not os.path.exists(doc_path): + print "Could not find path, creating directory '%s'" % doc_path + os.mkdir(doc_path) + + path_with_year = "%s/%s" % (doc_path, file_date.strftime("%Y")) + if not os.path.exists(path_with_year): + os.mkdir(path_with_year) + pass + + new_file_path = "%s/%s_%s.%s" % \ + (path_with_year, file_date.strftime("%Y-%m-%d"), msg, file_type) + + if not os.path.isfile(new_file_path): + print "Moving file '%s' to '%s'" % (file_name, new_file_path) + os.rename(file_name, new_file_path) + else: + if filecmp.cmp(new_file_path, file_name): + print "Two files already exist and are same: '%s' and '%s'" % \ + (file_name, new_file_path) + else: + print "Destination file '%s' already exists" % (new_file_path) +