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
//! The end-to-end proof that a `[telar] library` builds from the package it publishes: `plugins/telar-rsx-fixture` passes `cargo telar package --check`, is packaged by cargo, unpacked read-only, and compiled as a dependency of a generated application that the CLI transpiles while never running on the library.
//!
//! The application overrides one of the library's strings from a catalog it never installs by hand, names a theme of its own, ships the licence notice of the icons the library baked, draws the library's `.rsx` component headlessly and the icon its Rust names with `telar_icons::icon!`, once with the Plain flavour and once with the features `cargo telar dev` and `cargo telar preview` turn on, under which the library's `.rsx` previews, wired from the same Plain artifact, reach the application and build. Afterwards the unpacked library has to be byte-for-byte what cargo packaged.
//!
//! It compiles a few hundred crates into its own target directory under `target/tmp`, so it is ignored by default: run it with `cargo test -p cargo-telar --test rsx_library -- --ignored`. Every cargo it starts runs offline, so the registry has to hold what `Cargo.lock` names first (`cargo fetch`).

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;

const FIXTURE: &str = "telar-rsx-fixture";
const VERSION: &str = env!("CARGO_PKG_VERSION");

#[test]
#[ignore = "builds a generated application twice: run it with `cargo test -p cargo-telar --test rsx_library -- --ignored`"]
fn a_packaged_rsx_library_builds_as_a_read_only_dependency() {
    let repo = repo_root();
    let work = Path::new(env!("CARGO_TARGET_TMPDIR")).join("rsx-library");
    let target_dir = work.join("target");
    let run = work.join("run");
    remove_tree(&run);
    std::fs::create_dir_all(&run).expect("create the run directory");

    run_cli(&repo, &target_dir, &["package", "-p", FIXTURE, "--check"]);
    let library = unpack(&package_fixture(&repo, &target_dir), &run);
    let packaged = snapshot(&library);
    let _read_only = ReadOnlyTree::new(&library);

    let consumer = run.join("consumer");
    write_consumer(&consumer, &repo, &library);
    run_cli(&consumer, &target_dir, &["transpile"]);
    assert_notice_credits_the_library(&consumer);
    run_cargo(&consumer, &target_dir, &["test"]);
    run_cargo(
        &consumer,
        &target_dir,
        &[
            "test",
            "--features",
            "telar/hot-reload,telar/preview,telar/dev",
        ],
    );

    assert!(
        snapshot(&library) == packaged,
        "building the application changed the unpacked library at {}",
        library.display()
    );
}

/// The application draws no icon of its own, and still ships the notice of the one the library baked, read from the record the unpacked package carries.
fn assert_notice_credits_the_library(consumer: &Path) {
    let notice_path = consumer.join(".telar/ICONS-LICENSES.txt");
    let notice = std::fs::read_to_string(&notice_path)
        .unwrap_or_else(|e| panic!("the bake wrote no {}: {e}", notice_path.display()));
    assert!(
        notice.starts_with(&format!("Icons in {FIXTURE}\n")),
        "{notice}"
    );
    assert!(notice.contains("fixture — Fixture Icons\n"), "{notice}");
    assert!(notice.contains("  Licence: MIT"), "{notice}");
    assert!(notice.contains("  Icons: dot, square\n"), "{notice}");
}

fn repo_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .ancestors()
        .nth(3)
        .expect("cargo-telar sits three levels below the repository root")
        .to_path_buf()
}

fn run_cli(dir: &Path, target_dir: &Path, args: &[&str]) {
    let mut command = Command::new(env!("CARGO_BIN_EXE_cargo-telar"));
    command.args(args);
    run(command, dir, target_dir);
}

fn run_cargo(dir: &Path, target_dir: &Path, args: &[&str]) {
    let mut command = Command::new(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into()));
    command.args(args);
    run(command, dir, target_dir);
}

/// Runs `command` in `dir` offline against `target_dir`, which is never the workspace's own: the `cargo test` running this holds that one's lock until it returns.
fn run(mut command: Command, dir: &Path, target_dir: &Path) {
    let shown = format!("{command:?} in {}", dir.display());
    let output = command
        .current_dir(dir)
        .env("CARGO_TARGET_DIR", target_dir)
        .env("CARGO_NET_OFFLINE", "true")
        .output()
        .unwrap_or_else(|e| panic!("could not start {shown}: {e}"));
    assert!(
        output.status.success(),
        "{shown} failed with {}\n--- stdout\n{}\n--- stderr\n{}",
        output.status,
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
}

fn package_fixture(repo: &Path, target_dir: &Path) -> PathBuf {
    // A lockfile is read by no build that depends on the package, and writing one resolves its dependencies against the registry, which offline, or before this telar is released, has no answer.
    run_cargo(
        repo,
        target_dir,
        &[
            "package",
            "--no-verify",
            "--allow-dirty",
            "--exclude-lockfile",
            "-p",
            FIXTURE,
        ],
    );
    target_dir
        .join("package")
        .join(format!("{FIXTURE}-{VERSION}.crate"))
}

fn unpack(crate_file: &Path, into: &Path) -> PathBuf {
    let status = Command::new("tar")
        .arg("-xzf")
        .arg(crate_file)
        .arg("-C")
        .arg(into)
        .status()
        .expect("could not start tar");
    assert!(
        status.success(),
        "tar could not unpack {}",
        crate_file.display()
    );
    into.join(format!("{FIXTURE}-{VERSION}"))
}

/// Every file and directory under `root`, each file with its bytes.
fn snapshot(root: &Path) -> BTreeMap<PathBuf, Option<Vec<u8>>> {
    let mut entries = BTreeMap::new();
    let mut pending = vec![root.to_path_buf()];
    while let Some(dir) = pending.pop() {
        for entry in std::fs::read_dir(&dir).expect("read the unpacked library") {
            let path = entry.expect("read a directory entry").path();
            let relative = path.strip_prefix(root).unwrap_or(&path).to_path_buf();
            if path.is_dir() {
                entries.insert(relative, None);
                pending.push(path);
            } else {
                let bytes = std::fs::read(&path).expect("read an unpacked file");
                entries.insert(relative, Some(bytes));
            }
        }
    }
    entries
}

/// Keeps a tree read-only while it lives and writable again once it drops, even when the test panics, so `cargo clean` and the next run can always remove it.
struct ReadOnlyTree(PathBuf);

impl ReadOnlyTree {
    fn new(path: &Path) -> Self {
        set_tree_writable(path, false);
        Self(path.to_path_buf())
    }
}

impl Drop for ReadOnlyTree {
    fn drop(&mut self) {
        set_tree_writable(&self.0, true);
    }
}

/// Directories are made writable before what they hold and read-only after it, so a walk never meets a directory it cannot enter or change.
fn set_tree_writable(path: &Path, writable: bool) {
    let is_dir = path.is_dir();
    if writable {
        set_writable(path, true);
    }
    if is_dir {
        for entry in std::fs::read_dir(path).expect("read a directory to change its permissions") {
            set_tree_writable(&entry.expect("read a directory entry").path(), writable);
        }
    }
    if !writable {
        set_writable(path, false);
    }
}

fn set_writable(path: &Path, writable: bool) {
    let mut permissions = std::fs::metadata(path)
        .expect("read permissions")
        .permissions();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = permissions.mode();
        permissions.set_mode(match writable {
            true => mode | 0o200,
            false => mode & !0o222,
        });
    }
    #[cfg(not(unix))]
    permissions.set_readonly(!writable);
    std::fs::set_permissions(path, permissions).expect("change permissions");
}

fn remove_tree(path: &Path) {
    if !path.exists() {
        return;
    }
    set_tree_writable(path, true);
    std::fs::remove_dir_all(path).expect("remove the previous run");
}

fn toml_string(path: &Path) -> String {
    toml::Value::String(path.display().to_string()).to_string()
}

fn write_consumer(dir: &Path, repo: &Path, library: &Path) {
    let manifest = format!(
        r#"[package]
name = "rsx-library-consumer"
version = "0.1.0"
edition = "2024"
publish = false

[dependencies]
telar = {{ version = "={VERSION}", default-features = false, features = ["runtime", "shaper", "testing"] }}
telar-icons = {{ version = "={VERSION}" }}
telar-rsx-fixture = {{ path = {library} }}

[patch.crates-io]
telar = {{ path = {telar} }}
telar-icons = {{ path = {telar_icons} }}

[workspace]
"#,
        library = toml_string(library),
        telar = toml_string(&repo.join("crates/telar")),
        telar_icons = toml_string(&repo.join("plugins/telar-icons")),
    );
    let files = [
        ("Cargo.toml", manifest.as_str()),
        ("telar.toml", CONSUMER_TELAR_TOML),
        ("locales/en.toml", CONSUMER_LOCALE),
        ("src/lib.rs", CONSUMER_LIB_RS),
        ("src/theme.rs", CONSUMER_THEME_RS),
        ("src/welcome.rsx", CONSUMER_WELCOME_RSX),
        ("src/lib.test.rs", CONSUMER_LIB_TEST_RS),
    ];
    for (relative, contents) in files {
        let path = dir.join(relative);
        std::fs::create_dir_all(path.parent().expect("a file has a parent"))
            .expect("create a consumer directory");
        std::fs::write(&path, contents).expect("write a consumer file");
    }
    // Offline, the versions the workspace already fetched are the only ones the application can resolve to, and the same ones let it reuse what earlier runs compiled.
    std::fs::copy(repo.join("Cargo.lock"), dir.join("Cargo.lock")).expect("copy Cargo.lock");
}

const CONSUMER_TELAR_TOML: &str = r#"[telar]
theme = "crate::theme::ConsumerTheme"
prelude = ["telar_rsx_fixture"]
"#;

const CONSUMER_LOCALE: &str = r#"[telar_rsx_fixture]
greeting = "Welcome aboard, {name}!"
"#;

const CONSUMER_LIB_RS: &str = r#"telar::rsx_modules!();

#[cfg(test)]
#[path = "lib.test.rs"]
mod tests;
"#;

const CONSUMER_THEME_RS: &str = r#"use telar::{Color, ThemeTokens};

#[derive(Clone, ThemeTokens)]
pub struct ConsumerTheme {
    pub primary: Color,
    pub on_primary: Color,
    pub surface: Color,
    pub surface_alt: Color,
    pub border: Color,
    pub ink: Color,
    pub muted: Color,
    pub scrollbar: Color,
    pub success: Color,
    pub warning: Color,
    pub error: Color,
    pub on_error: Color,
    pub info: Color,
    pub highlight_low: Color,
    pub highlight_med: Color,
    pub highlight_high: Color,
    pub radius: f32,
    pub spacing: f32,
    pub icon_size: f32,
}

impl ConsumerTheme {
    pub const PRIMARY: Color = Color::rgba(0.8, 0.1, 0.5, 1.0);

    pub fn new() -> Self {
        let grey = Color::rgba(0.5, 0.5, 0.5, 1.0);
        Self {
            primary: Self::PRIMARY,
            on_primary: Color::WHITE,
            surface: Color::WHITE,
            surface_alt: grey,
            border: grey,
            ink: Color::BLACK,
            muted: grey,
            scrollbar: grey,
            success: grey,
            warning: grey,
            error: grey,
            on_error: Color::WHITE,
            info: grey,
            highlight_low: grey,
            highlight_med: grey,
            highlight_high: grey,
            radius: 6.0,
            spacing: 8.0,
            icon_size: 16.0,
        }
    }
}
"#;

const CONSUMER_WELCOME_RSX: &str = r#"[view]
col pad:16 fill:$theme.surface
    greeting_card name:"Ada"
"#;

const CONSUMER_LIB_TEST_RS: &str = r#"use telar::testing::{Scoped, mount, texts};
use telar::{ComponentList, DrawCommand, WindowRoot, reset_layout_runtime};

use crate::theme::ConsumerTheme;
use crate::welcome::{WelcomeProps, welcome};

fn render() -> Scoped<ComponentList> {
    telar::open_default_text_metrics();
    reset_layout_runtime();
    mount(|| WindowRoot::new(welcome(WelcomeProps::props().build()).expect("the page lays out")), 480, 160)
}

#[test]
fn the_library_component_draws_with_the_application_catalog_and_theme() {
    telar::set_theme(ConsumerTheme::new());

    telar::set_locale(telar::locale_tag!("en"));
    let tree = render();
    let drawn = texts(&tree);
    assert!(drawn.iter().any(|text| text == "Welcome aboard, Ada!"), "the application's override is drawn: {drawn:?}");
    let commands = tree.commands();
    assert!(
        commands.iter().any(|command| matches!(command, DrawCommand::Rect { style, .. } if style.fill.as_ref().is_some_and(|paint| paint.solid_color() == ConsumerTheme::PRIMARY))),
        "the library's `$theme.primary` reads the application's theme: {commands:?}"
    );
    assert!(
        commands.iter().any(|command| matches!(command, DrawCommand::Path { .. })),
        "the library's baked SVG is drawn: {commands:?}"
    );
    drop(commands);
    drop(tree);

    telar::set_locale(telar::locale_tag!("es"));
    let drawn = texts(&render());
    assert!(drawn.iter().any(|text| text == "¡Hola, Ada!"), "a locale the application does not override falls back to the library's catalog: {drawn:?}");
}

#[test]
fn the_binary_carries_the_notice_of_the_icons_the_library_baked() {
    let notice = telar_icons::licenses().expect("the application compiled its notice in");
    assert!(notice.starts_with("Icons in telar-rsx-fixture\n"), "{notice}");
    assert!(notice.contains("fixture — Fixture Icons\n"), "{notice}");
    assert!(notice.contains("  Icons: dot, square\n"), "{notice}");
}

#[test]
fn the_icon_the_library_names_from_rust_draws_from_its_shipped_artifact() {
    reset_layout_runtime();
    let tree = mount(|| WindowRoot::new(telar_rsx_fixture::marker().expect("the marker lays out")), 64, 64);
    let commands = tree.commands();
    assert!(commands.iter().any(|command| matches!(command, DrawCommand::Path { .. })), "{commands:?}");
}

telar::__previews! {
    #[test]
    fn the_library_rsx_previews_reach_the_application_and_build() {
        let previews = telar_rsx_fixture::telar_all_previews();
        let ids: Vec<&str> = previews.iter().map(|entry| entry.id).collect();
        for id in [
            "telar_rsx_fixture--greeting_card--ada",
            "telar_rsx_fixture--tally--rsx-literal",
            "telar_rsx_fixture--tally--rsx-bound",
        ] {
            assert!(ids.contains(&id), "the library's `.rsx` preview `{id}` is listed: {ids:?}");
        }

        telar::set_theme(ConsumerTheme::new());
        telar::set_locale(telar::locale_tag!("en"));
        telar::open_default_text_metrics();
        reset_layout_runtime();
        let ada = previews.iter().find(|entry| entry.id == "telar_rsx_fixture--greeting_card--ada").unwrap();
        let drawn = texts(&mount(|| WindowRoot::new(ada.build_root(&telar::preview::PreviewCtx::for_entry(ada).expect("the preview asks for no mode")).expect("the preview builds")), 480, 160));
        assert!(drawn.iter().any(|text| text == "Welcome aboard, Ada!"), "{drawn:?}");
    }
}
"#;