cargo-telar 0.2.3

Cargo subcommand for Telar apps: dev server with hot reload, and packaging into native installers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use super::*;

/// A manifest as `resolve_package` would have read it, without a directory to read it from.
fn resolved(manifest: &str) -> ResolvedPackage {
    let parsed: ManifestView = cargo_manifest(manifest).view().unwrap();
    let package = parsed.package.unwrap();
    ResolvedPackage {
        workspace_root: PathBuf::new(),
        package_dir: PathBuf::new(),
        features: parsed.features.clone(),
        name: package.name.clone(),
        version: "1.0.0".to_string(),
        package,
        workspace_package: None,
        produces_cdylib: false,
        default_run: None,
    }
}

fn selected(manifest: &str, wanted: &str) -> Vec<String> {
    let mut args = Vec::new();
    resolved(manifest)
        .frontend_feature(wanted)
        .push_to(&mut args);
    args
}

const MULTI_TARGET: &str = r#"
[package]
name = "sandbox"
[features]
default = ["desktop"]
desktop = ["telar/desktop"]
tui = ["telar/tui"]
"#;

/// The bug: `--target tui` named `telar/tui` on top of a `default` that still stood for a window, so the terminal build carried a desktop one beside it — under Termux, a `platform-desktop` that cannot be compiled there at all.
#[test]
fn asking_for_another_target_turns_the_default_one_off() {
    assert_eq!(
        selected(MULTI_TARGET, "tui"),
        vec!["--no-default-features", "--features", "sandbox/tui"],
    );
}

#[test]
fn the_target_a_package_already_defaults_to_is_left_alone() {
    assert!(
        selected(MULTI_TARGET, "desktop").is_empty(),
        "naming what `default` already says would only drop the rest of it"
    );
}

/// What lets a project reach a frontend it never declared a feature for, which is every project before it has said anything.
#[test]
fn a_package_that_declares_no_such_feature_goes_through_telar() {
    let manifest = "[package]\nname = \"solo\"\n";
    assert_eq!(selected(manifest, "tui"), vec!["--features", "telar/tui"]);
}

/// `--no-default-features` is the only lever cargo has and it takes the whole list, so everything in `default` that is not another frontend has to be named again — or `--target tui` would silently turn off half of what the project builds with.
#[test]
fn the_rest_of_the_defaults_come_back() {
    let manifest = r#"
[package]
name = "app"
[features]
default = ["desktop", "telemetry", "telar/svg"]
desktop = ["telar/desktop"]
tui = ["telar/tui"]
telemetry = []
"#;
    assert_eq!(
        selected(manifest, "tui"),
        vec![
            "--no-default-features",
            "--features",
            "app/tui,app/telemetry,telar/svg",
        ],
    );
}

/// A `default` that names one feature of its own which names the frontend is still a project that chose that frontend — both when it is the one asked for, and when it is the one that has to be left behind.
#[test]
fn a_frontend_reached_through_another_feature_still_counts() {
    let manifest = r#"
[package]
name = "app"
[features]
default = ["everything"]
everything = ["desktop", "telemetry"]
desktop = ["telar/desktop"]
tui = ["telar/tui"]
telemetry = []
"#;
    assert_eq!(
        selected(manifest, "tui"),
        vec!["--no-default-features", "--features", "app/tui"],
        "`everything` carries the window, so re-naming it would bring it back"
    );
    assert!(selected(manifest, "desktop").is_empty());
}

/// `cargo telar dev` with no flags in a terminal project used to go looking for a window to hot-reload behind, because only the flag ever said "terminal" and the manifest had already said it.
#[test]
fn a_terminal_project_is_one_without_being_told() {
    let tui = r#"
[package]
name = "app"
[features]
default = ["tui"]
desktop = ["telar/desktop"]
tui = ["telar/tui"]
"#;
    assert!(resolved(tui).defaults_to_terminal());
    assert!(
        !resolved(MULTI_TARGET).defaults_to_terminal(),
        "a default that opens a window is not a terminal project, whatever else it can compile"
    );
    assert!(
        !resolved("[package]\nname = \"solo\"\n").defaults_to_terminal(),
        "a package that named nothing keeps telar's own default, which is a window"
    );
}

fn declared_features(manifest: &str) -> BTreeMap<String, toml::Value> {
    cargo_manifest(manifest)
        .view::<ManifestView>()
        .unwrap()
        .features
}

#[test]
fn a_tooling_feature_no_member_names_is_reported_with_the_entry_that_locks_it() {
    let note = unlocked_tooling_note(
        &[declared_features("[package]\nname = \"app\"\n")],
        &["telar/dev"],
    )
    .expect("nothing in the workspace names `telar/dev`");
    assert!(note.contains("`telar/dev`"), "{note}");
    assert!(note.contains(&tooling_feature_entry()), "{note}");
}

#[test]
fn any_member_naming_it_in_either_spelling_locks_it() {
    let app = declared_features("[package]\nname = \"app\"\n");
    for spelling in ["telar/dev", "telar?/dev"] {
        let tools = declared_features(&format!(
            "[package]\nname = \"tools\"\n[features]\nlocked = [\"{spelling}\"]\n"
        ));
        assert_eq!(
            unlocked_tooling_note(&[app.clone(), tools], &["telar/dev"]),
            None,
            "`{spelling}`"
        );
    }
}

#[test]
fn only_the_features_left_unlocked_are_named() {
    let app = declared_features("[package]\nname = \"app\"\n[features]\ndev = [\"telar/dev\"]\n");
    let note = unlocked_tooling_note(&[app], &["telar/dev", "telar/hot-reload"])
        .expect("`telar/hot-reload` is named nowhere");
    assert!(note.contains("names `telar/hot-reload`, so"), "{note}");
}

#[test]
fn the_entry_cargo_telar_new_writes_locks_every_tooling_feature() {
    let manifest = format!(
        "[package]\nname = \"app\"\n[features]\n{}\n",
        tooling_feature_entry()
    );
    assert_eq!(
        unlocked_tooling_note(&[declared_features(&manifest)], &TOOLING_FEATURES),
        None
    );
}

#[test]
fn targets_web_is_true_for_either_spelling_of_the_browser_frontend() {
    assert!(resolved(MULTI_TARGET.replace("tui", "web").as_str()).targets_web());
    let dom = r#"
[package]
name = "app"
[features]
default = ["desktop"]
desktop = ["telar/desktop"]
web-dom = ["telar/web-dom"]
"#;
    assert!(resolved(dom).targets_web());
    assert!(
        !resolved(MULTI_TARGET).targets_web(),
        "a desktop/tui project names neither `web` nor `web-dom`"
    );
}

fn write_workspace_manifest(dir: &Path, contents: &str) {
    std::fs::create_dir_all(dir).unwrap();
    std::fs::write(dir.join("Cargo.toml"), contents).unwrap();
}

fn temp_dir(name: &str) -> PathBuf {
    let dir =
        std::env::temp_dir().join(format!("cargo_telar_config_{name}_{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    dir
}

#[test]
fn has_web_profile_reads_the_workspace_root_manifest() {
    let dir = temp_dir("has_profile");
    write_workspace_manifest(
        &dir,
        "[package]\nname = \"app\"\n\n[profile.web]\ninherits = \"release\"\n",
    );
    assert!(has_web_profile(&dir));
}

#[test]
fn has_web_profile_is_false_when_the_manifest_names_no_such_profile() {
    let dir = temp_dir("no_profile");
    write_workspace_manifest(&dir, "[package]\nname = \"app\"\n\n[profile.release]\n");
    assert!(!has_web_profile(&dir));
}

#[test]
fn has_web_profile_is_false_when_there_is_no_manifest_at_all() {
    assert!(!has_web_profile(Path::new(
        "/nonexistent/cargo_telar_test_path"
    )));
}

fn cargo_manifest(manifest: &str) -> CargoManifest {
    CargoManifest::parse(Path::new("/nonexistent/package"), manifest).unwrap()
}

/// Cargo's error for a feature `telar` no longer has names no fix, so the check names it: the crate each one became and the prelude line that brings the tags back. Every widget is in every `telar-components` build, so no group the old features stood for is a feature to name.
#[test]
fn the_catalogue_features_become_telar_components_with_no_feature() {
    let manifest = cargo_manifest(
        "[package]\nname = \"app\"\n[dependencies]\ntelar = { version = \"0.2\", features = [\"desktop\", \"components-overlays\", \"components-advanced\", \"components-base\"] }\n",
    );
    let moved = moved_telar_features(&manifest, None);
    assert_eq!(
        moved,
        BTreeSet::from([
            "components-advanced",
            "components-base",
            "components-overlays"
        ])
    );

    let hint = moved_features_hint("app", &moved, &[]).unwrap();
    assert!(
        hint.contains("cargo add -p app telar-components\n"),
        "{hint}"
    );
    assert!(!hint.contains("--features"), "{hint}");
    assert!(!hint.contains("telar-navigate"), "{hint}");
    assert!(hint.contains("prelude = [\"telar_components\"]"), "{hint}");
}

#[test]
fn the_whole_catalogue_is_telar_components_and_navigate_is_its_own_crate() {
    let moved = moved_telar_features(
        &cargo_manifest(
            "[package]\nname = \"app\"\n[dependencies]\ntelar = { version = \"0.2\", features = [\"components\", \"navigate\"] }\n",
        ),
        None,
    );
    let hint = moved_features_hint("app", &moved, &[]).unwrap();
    assert!(
        hint.contains("cargo add -p app telar-components\n"),
        "{hint}"
    );
    assert!(hint.contains("cargo add -p app telar-navigate"), "{hint}");
    assert!(
        hint.contains("prelude = [\"telar_components\", \"telar_navigate\"]"),
        "{hint}"
    );
}

/// Everywhere a manifest can turn a `telar` feature on: a `[features]` entry in either spelling, a target-specific dependency, a renamed one, and the workspace entry a `workspace = true` inherits.
#[test]
fn a_moved_feature_is_found_wherever_the_manifest_turns_it_on() {
    for spelling in ["telar/navigate", "telar?/navigate"] {
        let manifest = cargo_manifest(&format!(
            "[package]\nname = \"app\"\n[dependencies]\ntelar = \"0.2\"\n[features]\nroutes = [\"{spelling}\"]\n"
        ));
        assert_eq!(
            moved_telar_features(&manifest, None),
            BTreeSet::from(["navigate"]),
            "{spelling}"
        );
    }
    let target = cargo_manifest(
        "[package]\nname = \"app\"\n[target.'cfg(unix)'.dependencies]\ntelar = { version = \"0.2\", features = [\"components-chrome\"] }\n",
    );
    assert_eq!(
        moved_telar_features(&target, None),
        BTreeSet::from(["components-chrome"])
    );
    let renamed = cargo_manifest(
        "[package]\nname = \"app\"\n[dependencies]\nui = { package = \"telar\", version = \"0.2\" }\n[features]\nnav = [\"ui/navigate\"]\n",
    );
    assert_eq!(
        moved_telar_features(&renamed, None),
        BTreeSet::from(["navigate"])
    );
    let workspace = cargo_manifest(
        "[workspace.dependencies]\ntelar = { version = \"0.2\", features = [\"components\"] }\n",
    );
    let inheriting =
        cargo_manifest("[package]\nname = \"app\"\n[dependencies]\ntelar = { workspace = true }\n");
    assert_eq!(
        moved_telar_features(&inheriting, workspace.workspace_dependencies()),
        BTreeSet::from(["components"])
    );
}

#[test]
fn a_project_that_names_none_of_them_gets_no_hint() {
    let manifest = cargo_manifest(
        "[package]\nname = \"app\"\n[dependencies]\ntelar = { version = \"0.2\", features = [\"desktop\"] }\ntelar-components = \"0.2\"\n[features]\nnavigate = []\n",
    );
    let moved = moved_telar_features(&manifest, None);
    assert!(moved.is_empty(), "{moved:?}");
    assert_eq!(moved_features_hint("app", &moved, &[]), None);
}

/// A prelude that already names the crate is not told to name it again; one that names others keeps them in the line it is told to write.
#[test]
fn the_prelude_line_keeps_what_is_declared_and_is_left_out_when_complete() {
    let moved = BTreeSet::from(["components", "navigate"]);
    let declared = [telar_project::PreludeEntry::parse("my-plugin").unwrap()];
    let hint = moved_features_hint("app", &moved, &declared).unwrap();
    assert!(
        hint.contains("prelude = [\"my_plugin\", \"telar_components\", \"telar_navigate\"]"),
        "{hint}"
    );

    let complete = [
        telar_project::PreludeEntry::parse("telar-components").unwrap(),
        telar_project::PreludeEntry::parse("telar-navigate").unwrap(),
    ];
    let hint = moved_features_hint("app", &moved, &complete).unwrap();
    assert!(!hint.contains("prelude"), "{hint}");
}

#[test]
fn the_watch_feature_becomes_telar_watch_without_a_prelude_entry() {
    let moved = moved_telar_features(
        &cargo_manifest(
            "[package]\nname = \"app\"\n[dependencies]\ntelar = { version = \"0.2\", features = [\"desktop\", \"watch\"] }\n",
        ),
        None,
    );
    assert_eq!(moved, BTreeSet::from(["watch"]));

    let hint = moved_features_hint("app", &moved, &[]).unwrap();
    assert!(hint.contains("cargo add -p app telar-watch"), "{hint}");
    assert!(!hint.contains("prelude"), "{hint}");
}

fn workshop_refusal(package: &str) -> Option<String> {
    missing_workshop(&resolve_package(&["-p", package].map(str::to_string)).unwrap())
}

#[test]
fn a_package_without_the_workshop_is_refused_with_the_command_that_adds_it() {
    let refusal =
        workshop_refusal("telar-components").expect("telar-components declares no workshop");
    assert!(
        refusal.contains("`telar-components` declares no optional `telar-workshop` dependency"),
        "{refusal}"
    );
    assert!(
        refusal.contains("cargo add -p telar-components telar-workshop --optional"),
        "{refusal}"
    );
    assert_eq!(refusal.lines().count(), 1, "{refusal}");
}

#[test]
fn a_package_that_declares_the_workshop_is_not_refused() {
    assert_eq!(workshop_refusal("catalogue"), None);
}

fn package_in(manifest: &str) -> (tempfile::TempDir, Result<ResolvedPackage, PackageError>) {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("Cargo.toml"), manifest).unwrap();
    let resolved = resolve_package_in(dir.path().to_path_buf());
    (dir, resolved)
}

#[test]
fn a_package_resolves_to_its_own_name_and_version() {
    let (_dir, resolved) = package_in("[package]\nname = \"gallery\"\nversion = \"2.4.1\"\n");
    let resolved = resolved.unwrap();
    assert_eq!(resolved.name, "gallery");
    assert_eq!(resolved.version, "2.4.1");
}

#[test]
fn a_version_inherited_from_the_workspace_resolves_to_the_workspace_one() {
    let (_dir, resolved) = package_in(
        "[workspace]\n[workspace.package]\nversion = \"3.1.0\"\n[package]\nname = \"gallery\"\nversion.workspace = true\n",
    );
    assert_eq!(resolved.unwrap().version, "3.1.0");
}

#[test]
fn a_malformed_manifest_is_reported_with_its_parse_error() {
    let (dir, resolved) = package_in("[package\nname = \"gallery\"\n");
    let message = resolved.err().expect("a malformed manifest").to_string();
    assert!(
        message.contains(&dir.path().join("Cargo.toml").display().to_string()),
        "{message}"
    );
}

#[test]
fn a_package_without_a_version_is_refused_instead_of_given_one() {
    let (_dir, resolved) = package_in("[package]\nname = \"gallery\"\n");
    let message = resolved.err().expect("no version").to_string();
    assert!(message.contains("`gallery` has no `version`"), "{message}");
}

#[test]
fn a_manifest_without_a_package_is_refused() {
    let (_dir, resolved) = package_in("[workspace]\nmembers = []\n");
    assert!(matches!(resolved, Err(PackageError::NoPackage { .. })));
}

#[test]
fn a_directory_without_a_manifest_is_refused() {
    let dir = tempfile::tempdir().unwrap();
    let resolved = resolve_package_in(dir.path().to_path_buf());
    assert!(matches!(resolved, Err(PackageError::NoManifest { .. })));
}