Fixed crash caused by permanent path remapping

This commit is contained in:
patben8 committed 2026-09-25 22:41:08 +02:00
1 parent a3747e887b
commit b9d43dd7ea
9 files changed
+53 -28

No files matched your search

@@ -223,7 +223,7 @@ class OneLibraryAdapter:
paths = [Path(p) for p in self._store.all_audio_paths()] paths = [Path(p) for p in self._store.all_audio_paths()]
return {"total": len(paths), "matched": 0, "existing": 0, "samples": []} return {"total": len(paths), "matched": 0, "existing": 0, "samples": []}
def remap_locations(self, mapping: PathMapping) -> int: def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
raise Unsupported(self._readonly_reason("Rewriting stored paths")) raise Unsupported(self._readonly_reason("Rewriting stored paths"))
# ---- save ------------------------------------------------------------- # ---- save -------------------------------------------------------------
@@ -220,7 +220,7 @@ class RekordboxAdapter:
"samples": samples, "samples": samples,
} }
def remap_locations(self, mapping: PathMapping) -> int: def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
raise Unsupported(self._readonly_reason("Rewriting stored paths")) raise Unsupported(self._readonly_reason("Rewriting stored paths"))
# ---- commands: track metadata ---------------------------------------- # ---- commands: track metadata ----------------------------------------
@@ -369,13 +369,13 @@ class TraktorAdapter:
def remap_preview(self, mapping: PathMapping) -> dict: def remap_preview(self, mapping: PathMapping) -> dict:
return self._store.remap_preview(mapping) return self._store.remap_preview(mapping)
def remap_locations(self, mapping: PathMapping) -> int: def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
with _translate(): with _translate():
n = self._store.remap_locations(mapping) moved = self._store.remap_locations(mapping)
# A remap rewrites LOCATIONs, so track ids themselves change — there is # A remap rewrites LOCATIONs, so track ids themselves change — there is
# no per-track patch that could express this. # no per-track patch that could express this.
self._rebuild() self._rebuild()
return n return moved
# ---- save -------------------------------------------------------------- # ---- save --------------------------------------------------------------
@property @property
+7 -5
View File
@@ -1056,18 +1056,20 @@ class TraktorStore:
samples.append({"from": str(base), "to": str(target), "exists": ok}) samples.append({"from": str(base), "to": str(target), "exists": ok})
return {"total": total, "matched": matched, "existing": existing, "samples": samples} return {"total": total, "matched": matched, "existing": existing, "samples": samples}
def remap_locations(self, mapping: PathMapping) -> int: def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
"""Permanently rewrite matching track LOCATIONs to the mapping's ``to`` """Permanently rewrite matching track LOCATIONs to the mapping's ``to``
prefix — a deliberate library move (write-back). prefix — a deliberate library move (write-back).
Because ``track_id`` IS the LOCATION key (``volume+dir+file``), every Because ``track_id`` IS the LOCATION key (``volume+dir+file``), every
playlist ``PRIMARYKEY`` that referenced a moved track is rewritten too, playlist ``PRIMARYKEY`` that referenced a moved track is rewritten too,
so playlists keep pointing at their tracks. Non-matching entries are so playlists keep pointing at their tracks. Non-matching entries are
untouched. Returns the number of tracks rewritten; the caller saves. untouched. Returns ``{old track id: new track id}`` for every track
rewritten — callers holding ids (export sets) follow them with it, and
must not rebuild it from paths; the caller saves.
""" """
if mapping.empty: if mapping.empty:
return 0 return {}
with self._lock: with self._lock:
key_remap: dict[str, str] = {} key_remap: dict[str, str] = {}
for e in self._nml.collection.entry: for e in self._nml.collection.entry:
@@ -1086,7 +1088,7 @@ class TraktorStore:
loc.volume, loc.dir, loc.file = volume, dir_, file loc.volume, loc.dir, loc.file = volume, dir_, file
key_remap[old_key] = new_key key_remap[old_key] = new_key
if not key_remap: if not key_remap:
return 0 return {}
# Rewrite playlist entry primary keys that referenced moved tracks. # Rewrite playlist entry primary keys that referenced moved tracks.
for node in self._iter_nodes(self._root()): for node in self._iter_nodes(self._root()):
pl = node.playlist pl = node.playlist
@@ -1102,7 +1104,7 @@ class TraktorStore:
self._journal.retarget(old_key, new_key) self._journal.retarget(old_key, new_key)
self._note("remap", str(len(key_remap))) self._note("remap", str(len(key_remap)))
self.dirty = True self.dirty = True
return len(key_remap) return key_remap
def _entry_field_value(self, entry: Entrytype, field: str): def _entry_field_value(self, entry: Entrytype, field: str):
"""Read a single editable field's current value from the model, in the """Read a single editable field's current value from the model, in the
+3 -1
View File
@@ -106,6 +106,7 @@ class LibraryAdapter(Protocol):
def reload(self) -> None: ... def reload(self) -> None: ...
# ---- read projection ------------------------------------------------- # ---- read projection -------------------------------------------------
@property
def tracks(self) -> list[Track]: ... def tracks(self) -> list[Track]: ...
def track(self, track_id: str) -> Track | None: ... def track(self, track_id: str) -> Track | None: ...
def query_tracks(self, **kw) -> TrackPage: ... def query_tracks(self, **kw) -> TrackPage: ...
@@ -177,7 +178,8 @@ class LibraryAdapter(Protocol):
def set_path_mapping(self, mapping: PathMapping) -> None: ... def set_path_mapping(self, mapping: PathMapping) -> None: ...
def path_prefix_suggestions(self) -> dict: ... def path_prefix_suggestions(self) -> dict: ...
def remap_preview(self, mapping: PathMapping) -> dict: ... def remap_preview(self, mapping: PathMapping) -> dict: ...
def remap_locations(self, mapping: PathMapping) -> int: ... # {old track id: new track id}; ids may change because a Traktor id IS its path.
def remap_locations(self, mapping: PathMapping) -> dict[str, str]: ...
# ---- save ------------------------------------------------------------- # ---- save -------------------------------------------------------------
@property @property
+8 -14
View File
@@ -245,26 +245,20 @@ def remap_paths(body: PathMappingInfo) -> RemapResult:
raise HTTPException(400, "Both a `from` and `to` prefix are required") raise HTTPException(400, "Both a `from` and `to` prefix are required")
adapter = require_adapter() adapter = require_adapter()
# A Traktor track id IS its location, so a remap renames every matching id. # A Traktor track id IS its location, so a remap renames every matching id.
# Snapshot before/after and follow them, or every export set referencing a # Follow them, or every export set referencing a remapped track would
# remapped track would dangle — and dangle SILENTLY, still looking curated # dangle — and dangle SILENTLY, still looking curated while quietly
# while quietly exporting fewer tracks than it says. # exporting fewer tracks than it says. The adapter returns the renames
before = {t.id: t.filepath for t in adapter.tracks() if t.filepath} # itself: rebuilding them here from display paths (which omit the volume)
count = adapter.remap_locations(mapping) # could pair up two tracks with the same folder on different drives.
if count == 0: moved = adapter.remap_locations(mapping)
if not moved:
return RemapResult(rewritten=0, commit=None) return RemapResult(rewritten=0, commit=None)
after = {t.filepath: t.id for t in adapter.tracks() if t.filepath}
moved = {
old_id: after[str(mapping.apply(Path(old_path)))]
for old_id, old_path in before.items()
if str(mapping.apply(Path(old_path))) in after
and after[str(mapping.apply(Path(old_path)))] != old_id
}
if moved and STATE.library_id: if moved and STATE.library_id:
exports.retarget(STATE.library_id, moved) exports.retarget(STATE.library_id, moved)
# Through AppState, not the adapter: this is the one route besides /api/save # Through AppState, not the adapter: this is the one route besides /api/save
# that writes, and skipping it would leave a gap in the version history. # that writes, and skipping it would leave a gap in the version history.
_outcome, commit = STATE.save() _outcome, commit = STATE.save()
return RemapResult(rewritten=count, commit=commit) return RemapResult(rewritten=len(moved), commit=commit)
@app.get("/api/prefs") @app.get("/api/prefs")
+23
View File
@@ -179,6 +179,29 @@ exports.delete(LIB, s1.id)
check("the set is gone", exports.get(LIB, s1.id) is None) check("the set is gone", exports.get(LIB, s1.id) is None)
check("the destination folder is NOT touched", (dest / "already-there.txt").is_file()) check("the destination folder is NOT touched", (dest / "already-there.txt").is_file())
print("== a path rewrite carries every set's track ids with it ==")
# Through the ROUTE, not exports.retarget: the route is what joins the adapter's
# renames to the sets, and it once 500'd on every call with no test to notice.
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
ad, lib = STATE.adapter, STATE.library_id
prefix = ad.path_prefix_suggestions()["primary"]
loose = next(t.id for t in ad.tracks if str(ad.audio_path(t.id) or "").startswith(prefix))
s3 = exports.create(lib, name="Remapped", target="traktor", destination=str(work / "remapped"))
exports.add(lib, s3.id, track_ids=[loose])
r = TestClient(main.app, raise_server_exceptions=False).post(
"/api/library/remap-paths", json={"from": prefix, "to": "/Volumes/KonduktorTest"}
)
check("the route answers 200", r.status_code == 200, r.text[:300])
check("and rewrote tracks", r.status_code == 200 and r.json()["rewritten"] > 0, r.text[:300])
followed = exports.get(lib, s3.id).track_ids
check("the set no longer holds the old id", loose not in followed, str(followed))
check("it holds the track's NEW id",
len(followed) == 1 and ad.track(followed[0]) is not None
and str(ad.audio_path(followed[0])).startswith("/Volumes/KonduktorTest"), str(followed))
print("\n" + ("❌ FAILED" if failed else "✅ PASSED")) print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
_TMP.cleanup() _TMP.cleanup()
raise SystemExit(1 if failed else 0) raise SystemExit(1 if failed else 0)
+2 -2
View File
@@ -439,7 +439,7 @@ with tempfile.TemporaryDirectory() as d:
from_prefix = str(resolve_path(loc.volume, loc.dir, loc.file)) from_prefix = str(resolve_path(loc.volume, loc.dir, loc.file))
to_prefix = "/Volumes/KONDUKTOR_TEST_H1/remapped__unique__one.mp3" to_prefix = "/Volumes/KONDUKTOR_TEST_H1/remapped__unique__one.mp3"
n = store.remap_locations(PathMapping.make(from_prefix, to_prefix)) n = len(store.remap_locations(PathMapping.make(from_prefix, to_prefix)))
store.save() store.save()
edited = work.read_bytes() edited = work.read_bytes()
@@ -489,7 +489,7 @@ with tempfile.TemporaryDirectory() as d:
to_prefix = "/Volumes/KONDUKTOR_TEST_H2/remapped__playlist__one.mp3" to_prefix = "/Volumes/KONDUKTOR_TEST_H2/remapped__playlist__one.mp3"
new_key = "".join(os_path_to_location(Path(to_prefix))) new_key = "".join(os_path_to_location(Path(to_prefix)))
n = store.remap_locations(PathMapping.make(from_prefix, to_prefix)) n = len(store.remap_locations(PathMapping.make(from_prefix, to_prefix)))
store.save() store.save()
check("H2: at least one track rewritten", n >= 1) check("H2: at least one track rewritten", n >= 1)
+5 -1
View File
@@ -168,9 +168,13 @@ with tempfile.TemporaryDirectory() as d:
if (ap := adapter.audio_path(t.id)) and str(ap).startswith(prefix) if (ap := adapter.audio_path(t.id)) and str(ap).startswith(prefix)
} }
old_id = next(iter(matched)) old_id = next(iter(matched))
n = adapter.remap_locations(PathMapping.make(prefix, "/Volumes/KonduktorTest")) moved = adapter.remap_locations(PathMapping.make(prefix, "/Volumes/KonduktorTest"))
n = len(moved)
check("remap rewrote some locations", n > 0, str(n)) check("remap rewrote some locations", n > 0, str(n))
check("the old track id is gone from the index", adapter.track(old_id) is None) check("the old track id is gone from the index", adapter.track(old_id) is None)
# Export sets follow ids through a remap with exactly this mapping.
check("it reports where each track id went",
old_id in moved and adapter.track(moved[old_id]) is not None)
check("the index still holds every track", len(adapter.tracks) == 8485) check("the index still holds every track", len(adapter.tracks) == 8485)
# ---- place_cues takes the generic spec ------------------------------------ # ---- place_cues takes the generic spec ------------------------------------