handle conflicts in apkg import as well

This commit is contained in:
Damien Elmes 2012-09-21 15:42:30 +09:00
parent f13acf8c68
commit f2fffce6d1
3 changed files with 35 additions and 8 deletions

View file

@ -10,16 +10,27 @@ class AnkiPackageImporter(Anki2Importer):
def run(self):
# extract the deck from the zip file
z = zipfile.ZipFile(self.file)
self.zip = z = zipfile.ZipFile(self.file)
col = z.read("collection.anki2")
colpath = tmpfile(suffix=".anki2")
open(colpath, "wb").write(col)
# pass it to the anki2 importer
self.file = colpath
# we need the media dict in advance, and we'll need a map of fname ->
# number to use during the import
self.nameToNum = {}
for k, v in json.loads(z.read("media")).items():
self.nameToNum[v] = k
# run anki2 importer
Anki2Importer.run(self)
# import media
media = json.loads(z.read("media"))
for c, file in media.items():
# import static media
for file, c in self.nameToNum.items():
if not file.startswith("_"):
continue
path = os.path.join(self.col.media.dir(), file)
if not os.path.exists(path):
open(path, "wb").write(z.read(c))
def _srcMediaData(self, fname):
if fname in self.nameToNum:
return self.zip.read(self.nameToNum[fname])
return None

BIN
tests/support/media.apkg Normal file

Binary file not shown.

View file

@ -6,7 +6,7 @@ from anki.upgrade import Upgrader
from anki.utils import ids2str
from anki.errors import *
from anki.importing import Anki1Importer, Anki2Importer, TextImporter, \
SupermemoXmlImporter, MnemosyneImporter
SupermemoXmlImporter, MnemosyneImporter, AnkiPackageImporter
from anki.notes import Note
from anki.db import *
@ -50,7 +50,6 @@ def test_anki2():
imp.run()
check()
assert len(os.listdir(dst.media.dir())) == 1
#print dst.path
def test_anki2_mediadupes():
tmp = getEmptyDeck()
@ -97,7 +96,24 @@ def test_anki2_mediadupes():
n = empty.getNote(empty.db.scalar("select id from notes"))
assert "_" in n.fields[0]
#print dst.path
def test_apkg():
tmp = getEmptyDeck()
apkg = unicode(os.path.join(testDir, "support/media.apkg"))
imp = AnkiPackageImporter(tmp, apkg)
assert os.listdir(tmp.media.dir()) == []
imp.run()
assert os.listdir(tmp.media.dir()) == ['foo.wav']
# importing again should be idempotent in terms of media
tmp.remCards(tmp.db.list("select id from cards"))
imp = AnkiPackageImporter(tmp, apkg)
imp.run()
assert os.listdir(tmp.media.dir()) == ['foo.wav']
# but if the local file has different data, it will rename
tmp.remCards(tmp.db.list("select id from cards"))
open(os.path.join(tmp.media.dir(), "foo.wav"), "w").write("xyz")
imp = AnkiPackageImporter(tmp, apkg)
imp.run()
assert len(os.listdir(tmp.media.dir())) == 2
def test_anki1():
# get the deck path to import