Skip to content

Commit 14b5667

Browse files
author
Kevin Arthur
committed
fix(desktop): failed data migration stranded the rest of the user's data
Also restores Rust coverage above its floor with real tests instead of by lowering the floor. The migration bug ----------------- `migrate_legacy_data_dir` ran `let _ = copy_dir_all(...)`, discarding the result. `copy_dir_all` creates the destination before copying anything, so a failure partway (disk full, unreadable source) left a directory that existed but was incomplete — and the `data_dir.exists()` early return then read that partial copy as a finished migration on every later launch. The remainder of the user's documents, backups and settings would never be copied, silently, on the one code path whose entire job is not losing them. A failed copy now removes the partial destination so the next launch retries from a clean state, and says so on stderr. Still copies rather than moves, so the legacy directory survives either way. Split into `migrate_legacy_data_dir_from(legacy_base, data_dir)` returning a `LegacyMigration` outcome, because the old shape resolved the base from `$XDG_DATA_HOME`/`$HOME`/`$APPDATA` internally and could not be tested without mutating process-global environment state. 8 tests cover: nested copy, copy-not-move, refusing to overwrite existing data, no-op without legacy data, a legacy path that is a file, and the partial-copy cleanup. That last one was verified to fail against the old code with exactly its intended message. The shaper tests were not running at all ---------------------------------------- `crates/varve-print/src/shaper.rs` sat at 35% coverage because its six tests loaded `varve-print/tests/fonts/Geist-Variable.ttf` — a path that does not exist — and fell back to `create_minimal_font()`, which builds a table header and then returns `Vec::new()`. Every caller hit an `if font_data.is_empty() { return; }` guard, so all six passed in 0.00s without shaping a single glyph. They now use the committed OpenSans fixture via `test_fonts`, which the rest of the crate already uses, and assert real results: glyph counts, no .notdef fallbacks, non-zero advances, and clusters mapping back to the source text. Added coverage for RTL and vertical directions, malformed and unknown script tags, absent optional fields, disabled features, unparseable feature tags, variation axes, and an out-of-range face index. Removed the dead helper. shaper.rs: 35.14% -> 89.12% lines. Coverage outcome ---------------- Against the unchanged floors in .rust-coverage-baseline.json: workspace 78.83% -> 80.21% (floor 79.57) desktop 36.49% -> 41.96% (floor 39.97) The baseline had been regenerated locally to 78.83/39.80, which would have locked the regression in as the new bar. Discarded — the floors are untouched and now pass with margin.
1 parent d378608 commit 14b5667

3 files changed

Lines changed: 492 additions & 134 deletions

File tree

‎apps/desktop/src-tauri/src/font.rs‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,91 @@ pub fn enumerate_system_fonts(
7777
result.sort_by(|a, b| a.family.cmp(&b.family).then_with(|| a.name.cmp(&b.name)));
7878
Ok(result)
7979
}
80+
81+
#[cfg(test)]
82+
mod tests {
83+
use super::*;
84+
85+
/// The font list drives a user-facing picker, so the three properties that
86+
/// matter are: no duplicates, stable ordering, and an honest filter. All
87+
/// three are asserted against whatever fonts the host actually has, so the
88+
/// test stays meaningful on a developer machine and a bare CI runner alike.
89+
///
90+
/// A host with no font collection at all is tolerated — that is an
91+
/// environment fact, not a defect in this code — but the invariants are
92+
/// still checked whenever fonts are present.
93+
fn enumerate(family: Option<&str>) -> Option<Vec<SystemFontFace>> {
94+
enumerate_system_fonts(EnumerateSystemFontsRequest {
95+
family: family.map(str::to_string),
96+
})
97+
.ok()
98+
}
99+
100+
#[test]
101+
fn enumeration_is_deduplicated_and_sorted() {
102+
let Some(fonts) = enumerate(None) else {
103+
eprintln!("no system font collection on this host; skipping invariant checks");
104+
return;
105+
};
106+
107+
let mut keys: Vec<(&str, &str)> = fonts
108+
.iter()
109+
.map(|f| (f.family.as_str(), f.name.as_str()))
110+
.collect();
111+
let before = keys.len();
112+
keys.sort_unstable();
113+
keys.dedup();
114+
assert_eq!(
115+
keys.len(),
116+
before,
117+
"the same (family, name) pair was returned more than once"
118+
);
119+
120+
let sorted = fonts.is_sorted_by(|a, b| (&a.family, &a.name) <= (&b.family, &b.name));
121+
assert!(sorted, "results must come back in stable (family, name) order");
122+
}
123+
124+
#[test]
125+
fn family_filter_is_a_case_insensitive_substring_match() {
126+
let Some(all) = enumerate(None) else {
127+
eprintln!("no system font collection on this host; skipping filter check");
128+
return;
129+
};
130+
let Some(first) = all.first() else {
131+
eprintln!("host reports zero fonts; skipping filter check");
132+
return;
133+
};
134+
135+
// Upper-cased so a match proves the comparison is case-insensitive
136+
// rather than accidentally exact.
137+
let needle = first.family.to_uppercase();
138+
let filtered = enumerate(Some(&needle)).expect("filtered enumeration should succeed");
139+
140+
assert!(
141+
!filtered.is_empty(),
142+
"filtering by an existing family returned nothing"
143+
);
144+
assert!(
145+
filtered
146+
.iter()
147+
.all(|f| f.family.to_lowercase().contains(&needle.to_lowercase())),
148+
"filter let through a family that does not contain the needle"
149+
);
150+
assert!(
151+
filtered.len() <= all.len(),
152+
"a filter must never widen the result set"
153+
);
154+
}
155+
156+
#[test]
157+
fn an_unmatched_filter_returns_an_empty_list_rather_than_everything() {
158+
let Some(fonts) = enumerate(Some("zzz-no-such-font-family-zzz")) else {
159+
eprintln!("no system font collection on this host; skipping empty-filter check");
160+
return;
161+
};
162+
assert!(
163+
fonts.is_empty(),
164+
"a filter matching nothing must return nothing, not the unfiltered list"
165+
);
166+
}
167+
}

‎apps/desktop/src-tauri/src/lib.rs‎

Lines changed: 230 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3396,20 +3396,244 @@ mod tests {
33963396
});
33973397
serde_json::Value::Array(vec![one; MAX_SCENE_NODES + 1])
33983398
}
3399+
3400+
// ── Legacy application-data migration ───────────────────────────────────
3401+
//
3402+
// This runs once, at startup, before anything opens the document store, and
3403+
// it moves a user's whole history: documents, backups, model cache, recent
3404+
// files. A silent failure here is the kind that is discovered days later,
3405+
// when the data it should have carried is already assumed lost.
3406+
3407+
/// Fresh scratch directory holding `legacy_base` and the not-yet-created
3408+
/// `data_dir` the migration writes into.
3409+
fn migration_fixture() -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
3410+
let root = std::env::temp_dir().join(format!("varve_migration_test_{}", uuid()));
3411+
let legacy_base = root.join("legacy_base");
3412+
let data_dir = root.join("dev.varve.desktop");
3413+
std::fs::create_dir_all(&legacy_base).expect("create legacy base");
3414+
(root, legacy_base, data_dir)
3415+
}
3416+
3417+
fn seed_legacy_dir(legacy_base: &std::path::Path) -> std::path::PathBuf {
3418+
let legacy = legacy_base.join(LEGACY_APP_DIR);
3419+
std::fs::create_dir_all(legacy.join("backups")).expect("create legacy backups");
3420+
std::fs::write(legacy.join("documents.db"), b"db").expect("write legacy db");
3421+
std::fs::write(legacy.join("backups").join("a.json"), b"{}").expect("write legacy backup");
3422+
legacy
3423+
}
3424+
3425+
#[test]
3426+
fn migration_copies_legacy_tree_including_nested_files() {
3427+
let (root, legacy_base, data_dir) = migration_fixture();
3428+
seed_legacy_dir(&legacy_base);
3429+
3430+
let outcome = migrate_legacy_data_dir_from(&legacy_base, &data_dir);
3431+
3432+
assert_eq!(outcome, LegacyMigration::Copied);
3433+
assert_eq!(
3434+
std::fs::read(data_dir.join("documents.db")).expect("read migrated db"),
3435+
b"db"
3436+
);
3437+
assert_eq!(
3438+
std::fs::read(data_dir.join("backups").join("a.json")).expect("read migrated backup"),
3439+
b"{}"
3440+
);
3441+
3442+
let _ = std::fs::remove_dir_all(&root);
3443+
}
3444+
3445+
#[test]
3446+
fn migration_copies_rather_than_moves_so_rollback_stays_possible() {
3447+
let (root, legacy_base, data_dir) = migration_fixture();
3448+
let legacy = seed_legacy_dir(&legacy_base);
3449+
3450+
migrate_legacy_data_dir_from(&legacy_base, &data_dir);
3451+
3452+
// An older build still points at the legacy directory. If migration
3453+
// moved instead of copied, downgrading would lose everything.
3454+
assert!(legacy.join("documents.db").exists(), "legacy data was removed");
3455+
3456+
let _ = std::fs::remove_dir_all(&root);
3457+
}
3458+
3459+
#[test]
3460+
fn migration_does_not_overwrite_an_existing_data_dir() {
3461+
let (root, legacy_base, data_dir) = migration_fixture();
3462+
seed_legacy_dir(&legacy_base);
3463+
std::fs::create_dir_all(&data_dir).expect("create current data dir");
3464+
std::fs::write(data_dir.join("documents.db"), b"current").expect("write current db");
3465+
3466+
let outcome = migrate_legacy_data_dir_from(&legacy_base, &data_dir);
3467+
3468+
assert_eq!(outcome, LegacyMigration::AlreadyPresent);
3469+
assert_eq!(
3470+
std::fs::read(data_dir.join("documents.db")).expect("read current db"),
3471+
b"current",
3472+
"existing data must never be clobbered by the migration"
3473+
);
3474+
3475+
let _ = std::fs::remove_dir_all(&root);
3476+
}
3477+
3478+
#[test]
3479+
fn migration_is_a_no_op_without_legacy_data() {
3480+
let (root, legacy_base, data_dir) = migration_fixture();
3481+
3482+
let outcome = migrate_legacy_data_dir_from(&legacy_base, &data_dir);
3483+
3484+
assert_eq!(outcome, LegacyMigration::NoLegacyData);
3485+
assert!(
3486+
!data_dir.exists(),
3487+
"a fresh install must not get an empty data dir from the migration"
3488+
);
3489+
3490+
let _ = std::fs::remove_dir_all(&root);
3491+
}
3492+
3493+
#[test]
3494+
fn migration_ignores_a_legacy_path_that_is_a_file() {
3495+
let (root, legacy_base, data_dir) = migration_fixture();
3496+
std::fs::write(legacy_base.join(LEGACY_APP_DIR), b"not a directory")
3497+
.expect("write legacy file");
3498+
3499+
let outcome = migrate_legacy_data_dir_from(&legacy_base, &data_dir);
3500+
3501+
assert_eq!(outcome, LegacyMigration::NoLegacyData);
3502+
3503+
let _ = std::fs::remove_dir_all(&root);
3504+
}
3505+
3506+
/// The regression this whole split exists for.
3507+
///
3508+
/// `copy_dir_all` creates the destination before it copies anything, so a
3509+
/// failure partway leaves a directory that exists but is incomplete. The
3510+
/// `data_dir.exists()` early return would then read that partial copy as a
3511+
/// completed migration on every subsequent launch and never retry.
3512+
#[cfg(unix)]
3513+
#[test]
3514+
fn failed_migration_removes_the_partial_copy_so_the_next_launch_retries() {
3515+
use std::os::unix::fs::PermissionsExt;
3516+
3517+
let (root, legacy_base, data_dir) = migration_fixture();
3518+
let legacy = seed_legacy_dir(&legacy_base);
3519+
3520+
// An unreadable subdirectory makes read_dir fail mid-copy.
3521+
let locked = legacy.join("locked");
3522+
std::fs::create_dir_all(&locked).expect("create locked dir");
3523+
std::fs::write(locked.join("secret"), b"x").expect("write locked file");
3524+
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000))
3525+
.expect("chmod locked dir");
3526+
3527+
let outcome = migrate_legacy_data_dir_from(&legacy_base, &data_dir);
3528+
3529+
// Restore permissions first so cleanup can run even if asserts fail.
3530+
let _ = std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755));
3531+
3532+
assert_eq!(outcome, LegacyMigration::Failed);
3533+
assert!(
3534+
!data_dir.exists(),
3535+
"a partial copy was left behind; the next launch would treat it as migrated"
3536+
);
3537+
3538+
let _ = std::fs::remove_dir_all(&root);
3539+
}
3540+
3541+
#[test]
3542+
fn copy_dir_all_recreates_nested_structure() {
3543+
let root = std::env::temp_dir().join(format!("varve_copy_test_{}", uuid()));
3544+
let src = root.join("src");
3545+
let dst = root.join("dst");
3546+
std::fs::create_dir_all(src.join("a").join("b")).expect("create nested src");
3547+
std::fs::write(src.join("top.txt"), b"top").expect("write top");
3548+
std::fs::write(src.join("a").join("b").join("deep.txt"), b"deep").expect("write deep");
3549+
3550+
copy_dir_all(&src, &dst).expect("copy should succeed");
3551+
3552+
assert_eq!(std::fs::read(dst.join("top.txt")).expect("read top"), b"top");
3553+
assert_eq!(
3554+
std::fs::read(dst.join("a").join("b").join("deep.txt")).expect("read deep"),
3555+
b"deep"
3556+
);
3557+
3558+
let _ = std::fs::remove_dir_all(&root);
3559+
}
3560+
3561+
#[test]
3562+
fn legacy_data_base_resolves_on_supported_platforms() {
3563+
// cfg! makes this a per-platform constant; on the three we ship, a base
3564+
// must resolve or the migration silently never runs.
3565+
let base = legacy_data_base();
3566+
if cfg!(any(target_os = "linux", target_os = "macos", target_os = "windows")) {
3567+
assert!(base.is_some(), "no legacy data base on a supported platform");
3568+
}
3569+
}
3570+
}
3571+
3572+
/// Application-data directory used before the Strata -> Varve rename.
3573+
const LEGACY_APP_DIR: &str = "dev.strata.desktop";
3574+
3575+
/// What a migration attempt actually did. Returned so the behaviour can be
3576+
/// asserted in tests; the caller at startup ignores it.
3577+
#[derive(Debug, PartialEq, Eq)]
3578+
enum LegacyMigration {
3579+
/// The current data directory already exists — migration already happened,
3580+
/// or this is a fresh install that has been run before.
3581+
AlreadyPresent,
3582+
/// No legacy directory to copy from.
3583+
NoLegacyData,
3584+
/// Legacy data was copied into the current directory.
3585+
Copied,
3586+
/// The copy failed partway; the incomplete destination was removed.
3587+
Failed,
33993588
}
34003589

34013590
fn migrate_legacy_data_dir(data_dir: &std::path::Path) {
3402-
if data_dir.exists() {
3403-
return;
3404-
}
34053591
let Some(base) = legacy_data_base() else {
34063592
return;
34073593
};
3408-
let legacy = base.join("dev.strata.desktop");
3594+
migrate_legacy_data_dir_from(&base, data_dir);
3595+
}
3596+
3597+
/// Copy the pre-rename application-data directory into the current one.
3598+
///
3599+
/// Split from `migrate_legacy_data_dir` so the base directory can be injected:
3600+
/// the public entry point resolves it from `$XDG_DATA_HOME`/`$HOME`/`$APPDATA`,
3601+
/// which a test cannot vary without mutating process-global environment state.
3602+
///
3603+
/// Copies rather than moves, so an older build pointed at the legacy directory
3604+
/// keeps working and a bad migration can be undone by deleting the new one.
3605+
fn migrate_legacy_data_dir_from(
3606+
legacy_base: &std::path::Path,
3607+
data_dir: &std::path::Path,
3608+
) -> LegacyMigration {
3609+
if data_dir.exists() {
3610+
return LegacyMigration::AlreadyPresent;
3611+
}
3612+
let legacy = legacy_base.join(LEGACY_APP_DIR);
34093613
if !legacy.is_dir() {
3410-
return;
3614+
return LegacyMigration::NoLegacyData;
3615+
}
3616+
3617+
match copy_dir_all(&legacy, data_dir) {
3618+
Ok(()) => LegacyMigration::Copied,
3619+
Err(err) => {
3620+
// A failed copy must not leave the destination behind. `copy_dir_all`
3621+
// creates it before copying anything, so an error partway through
3622+
// (disk full, unreadable source) leaves a directory that exists but
3623+
// is incomplete — and the `data_dir.exists()` check above would then
3624+
// treat that partial copy as a finished migration on every later
3625+
// launch, silently stranding the rest of the user's data.
3626+
//
3627+
// Removing it means the next launch retries from a clean state.
3628+
let _ = std::fs::remove_dir_all(data_dir);
3629+
eprintln!(
3630+
"[varve] could not migrate data from {}: {err}. \
3631+
The previous directory is untouched; retrying on next launch.",
3632+
legacy.display()
3633+
);
3634+
LegacyMigration::Failed
3635+
}
34113636
}
3412-
let _ = copy_dir_all(&legacy, data_dir);
34133637
}
34143638

34153639
fn legacy_data_base() -> Option<std::path::PathBuf> {

0 commit comments

Comments
 (0)