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.
85 lines
2.3 KiB
Python
85 lines
2.3 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
|
|
from unicodedata import normalize
|
|
|
|
_punctuation_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
|
|
|
|
def slugify(text, delim='-'):
|
|
"""
|
|
Generate an ASCII-only slug.
|
|
"""
|
|
|
|
result = []
|
|
for word in _punctuation_re.split(text.lower()):
|
|
word = normalize('NFKD', word) \
|
|
.encode('ascii', 'ignore') \
|
|
.decode('utf-8')
|
|
|
|
if word:
|
|
result.append(word)
|
|
|
|
return delim.join(result)
|
|
|
|
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)
|
|
|
|
year = file_date.strftime("%Y")
|
|
path_with_year = '{}/{}'.format(doc_path, year)
|
|
if not os.path.exists(path_with_year):
|
|
os.mkdir(path_with_year)
|
|
pass
|
|
|
|
new_file_path = '{}/{}_{}.{}'.format(path_with_year,
|
|
file_date,
|
|
message,
|
|
file_type)
|
|
|
|
if not os.path.isfile(new_file_path):
|
|
print("Moving file '{}' to '{}'".format(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)
|