mirror of
https://github.com/ankitects/anki.git
synced 2025-09-24 16:56:36 -04:00
check checksum of all filename alternatives when adding media
patch thanks to Julien Baley
This commit is contained in:
parent
3dd72ad4d6
commit
c8f4d3a582
1 changed files with 8 additions and 13 deletions
|
@ -72,31 +72,26 @@ If the same name exists, compare checksums."""
|
||||||
mdir = self.dir()
|
mdir = self.dir()
|
||||||
# remove any dangerous characters
|
# remove any dangerous characters
|
||||||
base = re.sub(r"[][<>:/\\&?\"\|]", "", os.path.basename(opath))
|
base = re.sub(r"[][<>:/\\&?\"\|]", "", os.path.basename(opath))
|
||||||
dst = os.path.join(mdir, base)
|
|
||||||
# if it doesn't exist, copy it directly
|
|
||||||
if not os.path.exists(dst):
|
|
||||||
shutil.copyfile(opath, dst)
|
|
||||||
return base
|
|
||||||
# if it's identical, reuse
|
|
||||||
if self.filesIdentical(opath, dst):
|
|
||||||
return base
|
|
||||||
# otherwise, find a unique name
|
|
||||||
(root, ext) = os.path.splitext(base)
|
(root, ext) = os.path.splitext(base)
|
||||||
def repl(match):
|
def repl(match):
|
||||||
n = int(match.group(1))
|
n = int(match.group(1))
|
||||||
return " (%d)" % (n+1)
|
return " (%d)" % (n+1)
|
||||||
|
# find the first available name
|
||||||
while True:
|
while True:
|
||||||
path = os.path.join(mdir, root + ext)
|
path = os.path.join(mdir, root + ext)
|
||||||
|
# if it doesn't exist, copy it directly
|
||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
break
|
shutil.copyfile(opath, path)
|
||||||
|
return os.path.basename(os.path.basename(path))
|
||||||
|
# if it's identical, reuse
|
||||||
|
if self.filesIdentical(opath, path):
|
||||||
|
return os.path.basename(path)
|
||||||
|
# otherwise, increment the index in the filename
|
||||||
reg = " \((\d+)\)$"
|
reg = " \((\d+)\)$"
|
||||||
if not re.search(reg, root):
|
if not re.search(reg, root):
|
||||||
root = root + " (1)"
|
root = root + " (1)"
|
||||||
else:
|
else:
|
||||||
root = re.sub(reg, repl, root)
|
root = re.sub(reg, repl, root)
|
||||||
# copy and return
|
|
||||||
shutil.copyfile(opath, path)
|
|
||||||
return os.path.basename(os.path.basename(path))
|
|
||||||
|
|
||||||
def filesIdentical(self, path1, path2):
|
def filesIdentical(self, path1, path2):
|
||||||
"True if files are the same."
|
"True if files are the same."
|
||||||
|
|
Loading…
Reference in a new issue