Check if file already exists when importing

This commit is contained in:
Phyks 2014-04-24 21:19:27 +02:00
parent c304eb2578
commit 5aed10f4c5

55
main.py
View File

@ -3,12 +3,14 @@
""" """
Main app Main app
""" """
from __future__ import print_function
import sys import sys
import shutil import shutil
import requests import requests
import subprocess import subprocess
import re import re
import os
try: try:
from cStringIO import StringIO from cStringIO import StringIO
except: except:
@ -17,6 +19,13 @@ from bibtexparser.bparser import BibTexParser
import params import params
def warning(*objs):
"""
Write to stderr
"""
print("WARNING: ", *objs, file=sys.stderr)
def bibtexAppend(data): def bibtexAppend(data):
""" """
Append data to the main bibtex file Append data to the main bibtex file
@ -100,16 +109,39 @@ def doi2Bib(doi):
return r.text return r.text
_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())
return _slugify_hyphenate_re.sub('_', value)
def getExtension(filename):
"""
Get the extension of the filename
"""
return filename[filename.rfind('.'):]
def addFile(src): def addFile(src):
""" """
Add a file to the library Add a file to the library
""" """
# TODO : Handle books (ISBN) # TODO : Handle books (ISBN)
# Check file already exist
doi = findDOI(src) doi = findDOI(src)
if doi is False: if doi is False:
print("Could not determine the DOI for "+src+", switching to manual " + warning("Could not determine the DOI for "+src+", switching to manual " +
"entry.") "entry.")
doi = raw_input('DOI ? ') doi = raw_input('DOI ? ')
else: else:
@ -126,16 +158,26 @@ def addFile(src):
new_name = params.format new_name = params.format
new_name = new_name.replace("%f", authors[0].split(',')[0].strip()) new_name = new_name.replace("%f", authors[0].split(',')[0].strip())
new_name = new_name.replace("%l", authors[-1].split(',')[0].strip()) new_name = new_name.replace("%l", authors[-1].split(',')[0].strip())
new_name = new_name.replace("%j", bibtex['journal'].replace('.', '') new_name = new_name.replace("%j", bibtex['journal'])
.replace(' ', '_'))
new_name = new_name.replace("%Y", bibtex['year']) new_name = new_name.replace("%Y", bibtex['year'])
new_name = new_name.replace("%t", bibtex['title']) new_name = new_name.replace("%t", bibtex['title'])
new_name = new_name.replace("%a", ', '.join([i.split(',')[0].strip() new_name = new_name.replace("%a", ', '.join([i.split(',')[0].strip()
for i in authors])) for i in authors]))
new_name = params.folder+new_name+src[src.rfind('.'):] new_name = params.folder+_slugify(new_name)+getExtension(src)
bibtex['file'] = new_name bibtex['file'] = new_name
while os.path.exists(new_name):
warning("Error, file "+new_name+" already exists.")
default_rename = new_name.replace(getExtension(new_name),
" (2)"+getExtension(new_name))
rename = raw_input("New name ["+default_rename+"] ? ")
if rename == '':
new_name = default_rename
else:
new_name = rename
try: try:
shutil.copy2(src, new_name) shutil.copy2(src, new_name)
except IOError: except IOError:
@ -147,6 +189,7 @@ def addFile(src):
if __name__ == '__main__': if __name__ == '__main__':
try:
if len(sys.argv) < 2: if len(sys.argv) < 2:
sys.exit("Usage : TODO") sys.exit("Usage : TODO")
@ -165,3 +208,5 @@ if __name__ == '__main__':
elif sys.argv[1] == 'search': elif sys.argv[1] == 'search':
raise Exception('TODO') raise Exception('TODO')
except KeyboardInterrupt:
sys.exit()