Skip to content

Commit

Permalink
fix: create a subdir, so it can never delete an existing dir
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinBernstorff committed Dec 23, 2023
1 parent 9dc5bef commit 0978523
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 14 deletions.
9 changes: 5 additions & 4 deletions personal_mnemonic_medium/data_access/ankiconnect_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
def tempdir(tmp_path: Path) -> Iterator[Path]:
"""Context manager for a temporary directory that is deleted after use."""
try:
tmp_path.mkdir(parents=True, exist_ok=True)
yield tmp_path
except:
# If there's an error, ensure the directory is deleted before the error is propagated.
Expand Down Expand Up @@ -99,14 +100,14 @@ def update_model(self, model: genanki.Model) -> None:
)

def import_package(self, package: genanki.Package) -> None:
with tempdir(self.tmp_write_dir / "tmp_apkg_dir") as tmp_write_dir:
subdir = "tmp_apkg_dir"
with tempdir(self.tmp_write_dir / subdir) as tmp_write_subdir:
apkg_name = (
f"{datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}.apkg"
)
write_path = tmp_write_dir / apkg_name
package.write_to_file(write_path) # type: ignore
package.write_to_file(tmp_write_subdir / apkg_name) # type: ignore

read_path = self.tmp_read_dir / apkg_name
read_path = self.tmp_read_dir / subdir / apkg_name
try:
self._invoke(
AnkiConnectCommand.IMPORT_PACKAGE, path=str(read_path)
Expand Down
21 changes: 11 additions & 10 deletions personal_mnemonic_medium/data_access/test_ankiconnect_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,6 @@ class TestAnkiConnectGateway:
output_path = Path("/output")

def test_import_get_delete_happy_path(self):
gateway = AnkiConnectGateway(
ankiconnect_url=ANKICONNECT_URL,
base_deck="Test deck",
tmp_read_dir=(get_host_home_dir() / "ankidecks"),
tmp_write_dir=self.output_path,
max_deletions_per_run=1,
max_wait_seconds=0,
)

# Delete all .apkg in the output directory
for f in self.output_path.glob("*.apkg"):
f.unlink()
Expand Down Expand Up @@ -68,10 +59,20 @@ def test_import_get_delete_happy_path(self):
)
)

package = genanki.Package(deck_or_decks=deck)
tmp_read_dir = get_host_home_dir() / "ankidecks"
gateway = AnkiConnectGateway(
ankiconnect_url=ANKICONNECT_URL,
base_deck="Test deck",
tmp_read_dir=tmp_read_dir,
tmp_write_dir=self.output_path,
max_deletions_per_run=1,
max_wait_seconds=0,
)

# Phase 1: Importing
package = genanki.Package(deck_or_decks=deck)
gateway.import_package(package=package)
assert self.output_path.is_dir()
assert len(list(Path("/output").glob("*.apkg"))) == 0

# Phase 2: Getting
Expand Down

0 comments on commit 0978523

Please sign in to comment.