You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.4 KiB
Python

#!/usr/bin/env python3
'''
Move a document to the correct documents folder
'''
import filecmp
import os
import re
import shutil
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
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] [MESSAGE]'
def main(file_name='', dir_name='', message = ''):
file_type = file_name.split('.')[-1]
if not os.path.isfile(file_name):
print('ERROR: Cannot find file: {}'.format(file_name))
sys.exit(usage())
file_date = date.fromtimestamp(os.path.getmtime(file_name))
doc_path = os.path.expanduser('~/documents/records/{}'.format(dir_name))
if not os.path.exists(doc_path):
print('could not find path → creating directory: {}'.format(doc_path))
os.mkdir(doc_path)
path_with_year = "%s/%s".format((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'.format(path_with_year,
file_date.strftime("%Y-%m-%d"),
message,
file_type)
if not os.path.isfile(new_file_path):
print("Moving file '%s' to '%s'" % (file_name, new_file_path))
shutil.copyfile(file_name, new_file_path)
os.unlink(file_name)
else:
if filecmp.cmp(new_file_path, file_name):
print('Two files already exist and are same: {} and {}'.format(file_name, new_file_path))
else:
print('destination file already exists {}'.format(new_file_path))
if __name__ == "__main__":
try:
file_name = sys.argv[1]
dir_name = slugify(sys.argv[2])
except IndexError:
sys.exit(usage())
try:
message = slugify(sys.argv[3])
except IndexError:
message = ""
main(file_name=file_name, dir_name=dir_name, message=message)