mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Fixed track collision bug
This commit is contained in:
1 parent
b5b0fa91fe
commit
376569ec75
7 files changed
+236
-34
No files matched your search
@@ -599,7 +599,14 @@ serialization path.** It enforces:
|
||||
real flexible grids in the collection project correctly (K); and
|
||||
**removing a track from the collection** drops its `<ENTRY>` and its
|
||||
PRIMARYKEYs from exactly the playlists that held it — the only ADDED lines are
|
||||
the `ENTRIES=` recounts, every other playlist byte-identical (L).
|
||||
the `ENTRIES=` recounts, every other playlist byte-identical (L); and a
|
||||
**path remap** rewrites locations + playlist keys localized (H1/H2), re-keys
|
||||
the entry index so earlier tag edits still reach the file (H3), and is
|
||||
**refused with nothing changed** when it would give two ENTRYs one primary key
|
||||
— onto a staying track's path, or two differently-keyed entries for one file
|
||||
— which the preview reports first, while a chain (A onto B's old path, B
|
||||
onward) and a pre-existing duplicate are allowed, each track's staged art
|
||||
and edits following the TRACK (H4).
|
||||
The guard that catches serialization regressions like the lxml reformatting bug.
|
||||
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
|
||||
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched.
|
||||
|
||||
@@ -1097,10 +1097,51 @@ class TraktorStore:
|
||||
ranked = [g for g in ranked if g["prefix"]]
|
||||
return {"primary": ranked[0]["prefix"] if ranked else "", "groups": ranked[:5]}
|
||||
|
||||
def _plan_remap(self, mapping: PathMapping):
|
||||
"""Where a mapping would move each matching entry, and what that clashes
|
||||
with — computed before anything changes. Caller holds the lock.
|
||||
|
||||
Returns ``(moves, clashes)``: ``moves`` is ``[(entry, old_key, new_key,
|
||||
(volume, dir, file))]`` for every entry whose key would change, and
|
||||
``clashes`` maps each clashing NEW key to the old keys landing on it.
|
||||
|
||||
A key is a Traktor primary key, so two ENTRYs sharing one is a corrupt
|
||||
collection (`add_entry` refuses the same thing). A new key clashes when
|
||||
tracks with DIFFERENT old keys land on it, or when it is the key of an
|
||||
entry that stays where it is. A chain or swap — A onto B's old path
|
||||
while B moves on — is fine, and so is a duplicate the collection already
|
||||
had: two entries sharing one key move together, no worse than before.
|
||||
"""
|
||||
moves = []
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if not loc:
|
||||
continue
|
||||
base = resolve_path(loc.volume, loc.dir, loc.file)
|
||||
if not mapping.matches(base):
|
||||
continue
|
||||
volume, dir_, file = os_path_to_location(mapping.apply(base))
|
||||
old_key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
||||
new_key = f"{volume or ''}{dir_ or ''}{file or ''}"
|
||||
if old_key != new_key: # a no-op (e.g. from == to) stays byte-identical
|
||||
moves.append((e, old_key, new_key, (volume, dir_, file)))
|
||||
moving = {id(e) for e, *_ in moves}
|
||||
staying = {self._key_of(e) for e in self._nml.collection.entry
|
||||
if e.location and id(e) not in moving}
|
||||
landing: dict[str, set[str]] = {}
|
||||
for _e, old_key, new_key, _loc in moves:
|
||||
landing.setdefault(new_key, set()).add(old_key)
|
||||
clashes = {
|
||||
new_key: sorted(olds) for new_key, olds in landing.items()
|
||||
if len(olds) > 1 or new_key in staying
|
||||
}
|
||||
return moves, clashes
|
||||
|
||||
def remap_preview(self, mapping: PathMapping) -> dict:
|
||||
"""How a mapping would affect the collection, without changing anything:
|
||||
total tracks, how many match ``from``, and how many exist at ``to``
|
||||
(plus a few samples). Powers the mapping editor's validation line."""
|
||||
total tracks, how many match ``from``, how many exist at ``to``, and how
|
||||
many would CLASH with another track's path (which `remap_locations`
|
||||
refuses) — plus a few samples. Powers the mapping editor's validation."""
|
||||
|
||||
with self._lock:
|
||||
total = matched = existing = 0
|
||||
@@ -1119,7 +1160,17 @@ class TraktorStore:
|
||||
existing += 1
|
||||
if len(samples) < 5:
|
||||
samples.append({"from": str(base), "to": str(target), "exists": ok})
|
||||
return {"total": total, "matched": matched, "existing": existing, "samples": samples}
|
||||
_moves, clashes = self._plan_remap(mapping)
|
||||
return {
|
||||
"total": total, "matched": matched, "existing": existing, "samples": samples,
|
||||
"collisions": len(clashes),
|
||||
"collision_samples": [self._display_key(k) for k in sorted(clashes)[:5]],
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _display_key(key: str) -> str:
|
||||
"""A primary key as a readable path ("Volume/:dir/:file" -> "Volume/dir/file")."""
|
||||
return key.replace("/:", "/")
|
||||
|
||||
def remap_locations(self, mapping: PathMapping) -> dict[str, str]:
|
||||
"""Permanently rewrite matching track LOCATIONs to the mapping's ``to``
|
||||
@@ -1131,38 +1182,44 @@ class TraktorStore:
|
||||
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.
|
||||
|
||||
**Refused, with nothing changed, if any track would land on another
|
||||
track's path** (see `_plan_remap`): the collection would then hold two
|
||||
ENTRYs sharing a primary key. Every re-key below is applied AT ONCE, not
|
||||
track by track, so a chain (A onto B's old path, B onward) cannot carry
|
||||
A's staged art or edits along to B's destination.
|
||||
"""
|
||||
|
||||
if mapping.empty:
|
||||
return {}
|
||||
with self._lock:
|
||||
key_remap: dict[str, str] = {}
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if not loc:
|
||||
continue
|
||||
base = resolve_path(loc.volume, loc.dir, loc.file)
|
||||
if not mapping.matches(base):
|
||||
continue
|
||||
target = mapping.apply(base)
|
||||
volume, dir_, file = os_path_to_location(target)
|
||||
old_key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
||||
new_key = f"{volume or ''}{dir_ or ''}{file or ''}"
|
||||
if old_key == new_key:
|
||||
continue # no-op (e.g. from == to); leave byte-identical
|
||||
loc.volume, loc.dir, loc.file = volume, dir_, file
|
||||
key_remap[old_key] = new_key
|
||||
# Re-key the index too. Everything that finds an ENTRY by track
|
||||
# id goes through it — later edits, and the file-tag sync on
|
||||
# save, which would otherwise silently skip every edit made to
|
||||
# this track before the remap.
|
||||
moves, clashes = self._plan_remap(mapping)
|
||||
if clashes:
|
||||
paths = [self._display_key(k) for k in sorted(clashes)]
|
||||
shown = ", ".join(paths[:3]) + (f" and {len(paths) - 3} more" if len(paths) > 3 else "")
|
||||
raise PlaylistError(
|
||||
f"Remapping would give {len(paths)} path{'s' if len(paths) != 1 else ''} to more "
|
||||
f"than one track ({shown}). Two entries sharing a path corrupt the collection, "
|
||||
"so nothing was changed."
|
||||
)
|
||||
if not moves:
|
||||
return {}
|
||||
key_remap = {old_key: new_key for _e, old_key, new_key, _loc in moves}
|
||||
for e, _old, _new, (volume, dir_, file) in moves:
|
||||
e.location.volume, e.location.dir, e.location.file = volume, dir_, file
|
||||
# Re-key the index too. Everything that finds an ENTRY by track id
|
||||
# goes through it — later edits, and the file-tag sync on save,
|
||||
# which would otherwise silently skip every edit made to this track
|
||||
# before the remap. Drop every old key first, then add every new
|
||||
# one, so a chain cannot delete an entry another has just claimed.
|
||||
for e, old_key, _new, _loc in moves:
|
||||
if self._entry_by_key.get(old_key) is e:
|
||||
del self._entry_by_key[old_key]
|
||||
for e, _old, new_key, _loc in moves:
|
||||
self._entry_by_key[new_key] = e
|
||||
if old_key in self._track_art:
|
||||
self._track_art[new_key] = self._track_art.pop(old_key)
|
||||
if not key_remap:
|
||||
return {}
|
||||
art = {old: self._track_art.pop(old) for old in key_remap if old in self._track_art}
|
||||
for old, staged in art.items():
|
||||
self._track_art[key_remap[old]] = staged
|
||||
# Rewrite playlist entry primary keys that referenced moved tracks.
|
||||
for node in self._iter_nodes(self._root()):
|
||||
pl = node.playlist
|
||||
@@ -1174,8 +1231,7 @@ class TraktorStore:
|
||||
pk.key = key_remap[pk.key]
|
||||
# Track ids derive from the LOCATION, so a remap renames them. Carry
|
||||
# this session's journal entries across or their file-tag sync is lost.
|
||||
for old_key, new_key in key_remap.items():
|
||||
self._journal.retarget(old_key, new_key)
|
||||
self._journal.retarget_many(key_remap)
|
||||
self._note("remap", str(len(key_remap)))
|
||||
self.dirty = True
|
||||
return key_remap
|
||||
|
||||
@@ -95,11 +95,18 @@ class EditJournal:
|
||||
"""Follow a track whose id changed (a path remap rewrites LOCATIONs, and
|
||||
the id is derived from the location). Without this, edits made earlier in
|
||||
the session would silently stop syncing to the file."""
|
||||
if old_id == new_id:
|
||||
self.retarget_many({old_id: new_id})
|
||||
|
||||
def retarget_many(self, renames: dict[str, str]) -> None:
|
||||
"""`retarget` for a whole remap AT ONCE. One at a time would be wrong
|
||||
for a chain — A moving to B's old path while B moves on to C would
|
||||
carry A's edits to C along with B's."""
|
||||
renames = {o: n for o, n in renames.items() if o != n}
|
||||
if not renames:
|
||||
return
|
||||
for i, c in enumerate(self.changes):
|
||||
if c.target == old_id and c.scope in ("track", "cue", "grid", "lock"):
|
||||
self.changes[i] = Change(c.scope, c.op, new_id, c.detail, c.before, c.after)
|
||||
if c.target in renames and c.scope in ("track", "cue", "grid", "lock"):
|
||||
self.changes[i] = Change(c.scope, c.op, renames[c.target], c.detail, c.before, c.after)
|
||||
|
||||
# ---- the version-history message --------------------------------------
|
||||
def summary(self, extra_tracks: set[str] | None = None) -> str:
|
||||
|
||||
@@ -233,6 +233,10 @@ class RemapPreview(BaseModel):
|
||||
matched: int # how many match the `from` prefix
|
||||
existing: int # of matched, how many exist at the `to` target
|
||||
samples: list[RemapSample] = []
|
||||
# Target paths more than one track would land on. Non-zero means the remap
|
||||
# would be refused: two entries sharing a path corrupt the library.
|
||||
collisions: int = 0
|
||||
collision_samples: list[str] = []
|
||||
|
||||
|
||||
class PrefixGroup(BaseModel):
|
||||
|
||||
@@ -565,6 +565,114 @@ with tempfile.TemporaryDirectory() as d:
|
||||
str(tag_meta))
|
||||
check("H3: …and the staged cover art", ("cover", b"\xff\xd8H3") in written)
|
||||
|
||||
# H4: a remap that would give two ENTRYs one primary key is refused with nothing
|
||||
# changed; the preview says so first. A chain (one track onto another's OLD
|
||||
# path while that one moves on) is not a clash, and each track's staged art and
|
||||
# edits must follow IT, not the path.
|
||||
from konduktor.core.adapter import InvalidCommand # noqa: E402
|
||||
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
store = TraktorStore(work)
|
||||
entries = [e for e in store._nml.collection.entry if e.location and e.location.file]
|
||||
e1, e2, e3 = entries[0], entries[1], entries[2]
|
||||
|
||||
def put(e, path):
|
||||
e.location.volume, e.location.dir, e.location.file = os_path_to_location(Path(path))
|
||||
|
||||
def rekey(st):
|
||||
st._entry_by_key = {st._key_of(e): e for e in st._nml.collection.entry if e.location}
|
||||
|
||||
# (a) onto a path a STAYING track already has — the realistic case: a folder
|
||||
# copied to a new drive and both copies in the collection.
|
||||
put(e1, "/Volumes/H4OLD/Music/same.mp3")
|
||||
put(e2, "/Volumes/H4NEW/Music/same.mp3")
|
||||
rekey(store)
|
||||
before = store._render()
|
||||
mapping = PathMapping.make("/Volumes/H4OLD/Music", "/Volumes/H4NEW/Music")
|
||||
preview = store.remap_preview(mapping)
|
||||
check("H4: the preview reports the clash before anything is done",
|
||||
preview["collisions"] == 1 and len(preview["collision_samples"]) == 1
|
||||
and preview["collision_samples"][0].endswith("H4NEW/Music/same.mp3"), str(preview))
|
||||
try:
|
||||
store.remap_locations(mapping)
|
||||
check("H4: a remap onto a staying track's path is refused", False, "it ran")
|
||||
except PlaylistError as exc:
|
||||
check("H4: a remap onto a staying track's path is refused", "nothing was changed" in str(exc), str(exc))
|
||||
check("H4: …and nothing changed", store._render() == before and not store.dirty)
|
||||
|
||||
# (b) two DIFFERENTLY-keyed entries for one file — the boot disk spelt
|
||||
# "Macintosh HD" and blank, both resolving to /Users/… — that the mapping
|
||||
# sends to the same place.
|
||||
put(e1, "/Users/h4/one.mp3")
|
||||
e3.location.volume, e3.location.dir, e3.location.file = "", e1.location.dir, e1.location.file
|
||||
put(e2, "/Volumes/H4OTHER/two.mp3")
|
||||
rekey(store)
|
||||
check("H4: (setup) two keys, one file",
|
||||
store._key_of(e1) != store._key_of(e3)
|
||||
and resolve_path(e1.location.volume, e1.location.dir, e1.location.file)
|
||||
== resolve_path(e3.location.volume, e3.location.dir, e3.location.file))
|
||||
mapping = PathMapping.make("/Users/h4", "/Volumes/H4DEST")
|
||||
check("H4: two entries with different keys landing on one path clash",
|
||||
store.remap_preview(mapping)["collisions"] == 1, str(store.remap_preview(mapping)))
|
||||
before = store._render()
|
||||
try:
|
||||
store.remap_locations(mapping)
|
||||
check("H4: …and that remap is refused", False, "it ran")
|
||||
except PlaylistError:
|
||||
check("H4: …and that remap is refused, unchanged", store._render() == before)
|
||||
put(e3, "/Volumes/H4OTHER/unrelated.mp3")
|
||||
|
||||
# (c) a duplicate the collection ALREADY had moves as it was — refusing it
|
||||
# would make a library with one duplicate impossible to move at all.
|
||||
put(e1, "/Volumes/H4OLD/Music/same.mp3")
|
||||
put(e2, "/Volumes/H4OLD/Music/same.mp3") # e1 and e2 now share a key
|
||||
rekey(store)
|
||||
mapping = PathMapping.make("/Volumes/H4OLD/Music", "/Volumes/H4MOVED/Music")
|
||||
check("H4: an existing duplicate is not a new clash", store.remap_preview(mapping)["collisions"] == 0)
|
||||
moved = store.remap_locations(mapping)
|
||||
check("H4: …and the pair moves together", len(moved) == 1 and store._key_of(e1) == store._key_of(e2))
|
||||
|
||||
# (d) a chain from a nested prefix: x/f -> x/sub/f while x/sub/f -> x/sub/sub/f.
|
||||
put(e1, "/Volumes/H4C/x/f.mp3")
|
||||
put(e2, "/Volumes/H4C/x/sub/f.mp3")
|
||||
rekey(store)
|
||||
k1, k2 = store._key_of(e1), store._key_of(e2)
|
||||
store.set_track_metadata(k1, {"genre": "chain one"})
|
||||
store.set_track_metadata(k2, {"genre": "chain two"})
|
||||
store.set_track_art(k1, b"art-one", "image/jpeg")
|
||||
store.set_track_art(k2, b"art-two", "image/jpeg")
|
||||
mapping = PathMapping.make("/Volumes/H4C/x", "/Volumes/H4C/x/sub")
|
||||
check("H4: a chain is not a clash", store.remap_preview(mapping)["collisions"] == 0)
|
||||
moved = store.remap_locations(mapping)
|
||||
n1, n2 = store._key_of(e1), store._key_of(e2)
|
||||
check("H4: the first track takes the second's old path", n1 == k2 and moved[k1] == n1, f"{moved}")
|
||||
check("H4: the index finds each track at its new id",
|
||||
store._entry_by_key.get(n1) is e1 and store._entry_by_key.get(n2) is e2)
|
||||
check("H4: each track's staged art follows the TRACK",
|
||||
store._track_art.get(n1, (b"",))[0] == b"art-one" and store._track_art.get(n2, (b"",))[0] == b"art-two",
|
||||
str({k: v[0] for k, v in store._track_art.items()}))
|
||||
check("H4: …and so do its edits",
|
||||
store._journal.fields_for(n1) == {"genre"} and store._journal.fields_for(n2) == {"genre"}
|
||||
and store._entry_field_value(store._entry_by_key[n1], "genre") == "chain one")
|
||||
j1 = [c for c in store._journal.changes if c.target == n1 and c.scope == "track"]
|
||||
check("H4: …exactly one edit each, not both on one track", len(j1) == 1, str(j1))
|
||||
|
||||
# Through the adapter the refusal is the generic InvalidCommand (-> HTTP 400).
|
||||
shutil.copy2(REAL, work)
|
||||
ad = TraktorAdapter(work)
|
||||
a1, a2 = [e for e in ad.store._nml.collection.entry if e.location and e.location.file][:2]
|
||||
put(a1, "/Volumes/H4OLD/Music/same.mp3")
|
||||
put(a2, "/Volumes/H4NEW/Music/same.mp3")
|
||||
rekey(ad.store)
|
||||
try:
|
||||
ad.remap_locations(PathMapping.make("/Volumes/H4OLD/Music", "/Volumes/H4NEW/Music"))
|
||||
check("H4: the adapter refuses with InvalidCommand", False, "it ran")
|
||||
except InvalidCommand:
|
||||
check("H4: the adapter refuses with InvalidCommand", True)
|
||||
|
||||
|
||||
# ---- Invariant I: flexible (multi-marker) beatgrids round-trip ---------
|
||||
print("== I. flexible beatgrid: add/move/delete markers, localized + reversible ==")
|
||||
|
||||
@@ -556,6 +556,10 @@ export interface RemapPreview {
|
||||
matched: number
|
||||
existing: number
|
||||
samples: RemapSample[]
|
||||
/** Target paths more than one track would land on. Non-zero = the rewrite
|
||||
* would be refused (two entries sharing a path corrupt the library). */
|
||||
collisions: number
|
||||
collision_samples: string[]
|
||||
}
|
||||
|
||||
/** One place a stored volume's tracks were found — a mapping the user can pick. */
|
||||
|
||||
@@ -102,7 +102,10 @@ export function PathMappingDialog({ onClose, onNotify, onError }: Props) {
|
||||
}
|
||||
}
|
||||
|
||||
const canCommit = !!from.trim() && !!to.trim()
|
||||
// The backend refuses a rewrite that would give two tracks one path; say so
|
||||
// here rather than only after the click.
|
||||
const collides = (preview?.collisions ?? 0) > 0
|
||||
const canCommit = !!from.trim() && !!to.trim() && !collides
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
@@ -191,6 +194,19 @@ export function PathMappingDialog({ onClose, onNotify, onError }: Props) {
|
||||
{preview.matched} exist at the target.
|
||||
</span>
|
||||
)}
|
||||
{collides && (
|
||||
<div className="mt-1.5 text-pink">
|
||||
{preview.collisions} target path{preview.collisions === 1 ? '' : 's'} would
|
||||
belong to more than one track, so the paths can’t be rewritten:
|
||||
<ul className="mt-1 list-disc pl-4 text-muted">
|
||||
{preview.collision_samples.map((p) => (
|
||||
<li key={p} className="truncate" title={p}>
|
||||
{p}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
Reference in new issue
Block a user