proa-cli 0.2.2

CLI for scaffolding, inspecting, formatting, and validating Proa web projects
Documentation
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// Copyright Proa Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{env, fs, process::Command};

#[test]
fn run_scripts_chain_commands_and_use_the_cli_that_launched_them() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path();
    fs::write(root.join("Cargo.toml"), "[workspace]\n").unwrap();
    let config = r#"use proa::config::{Config, Result, ScriptsConfig};
pub async fn config() -> Result<Config> {
    Ok(Config {
        scripts: ScriptsConfig {
            dev: DEV_SCRIPT,
            build: "echo configured-build",
            named: std::collections::BTreeMap::from([("report", proa::config::ScriptConfig {
                command: vec!["proa", "--version"],
                ..Default::default()
            })]),
            ..Default::default()
        },
        ..Config::default()
    })
}
"#;
    let script = if cfg!(windows) {
        "proa --version && echo shell-arguments !content!"
    } else {
        "proa --version && echo shell-arguments; # trailing comment"
    };
    fs::write(
        root.join("proa.config.rs"),
        config.replace("DEV_SCRIPT", &format!("{script:?}")),
    )
    .unwrap();
    if cfg!(windows) {
        fs::write(root.join("proa.cmd"), "@echo wrong-cli & exit /b 99\n").unwrap();
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let wrong_cli = root.join("proa");
        fs::write(&wrong_cli, "#!/bin/sh\necho wrong-cli\nexit 99\n").unwrap();
        fs::set_permissions(wrong_cli, fs::Permissions::from_mode(0o755)).unwrap();
    }
    let mut paths = vec![root.to_path_buf()];
    paths.extend(env::split_paths(&env::var_os("PATH").unwrap_or_default()));
    let path = env::join_paths(paths).unwrap();
    let cli = |args: &[&str]| {
        Command::new(env!("CARGO_BIN_EXE_proa"))
            .current_dir(root)
            .env("PATH", &path)
            .args(args)
            .output()
            .unwrap()
    };
    let output = cli(&["run", "dev", "--port", "A & B"]);
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "{stdout}\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(stdout.contains(env!("CARGO_PKG_VERSION")), "{stdout}");
    assert!(
        stdout.contains("shell-arguments") && stdout.contains("A & B"),
        "{stdout}"
    );
    if cfg!(windows) {
        assert!(stdout.contains("!content!"), "{stdout}");
    }
    assert!(!stdout.contains("wrong-cli"), "{stdout}");

    let forwarded = cli(&["run", "dev", "--", "cargo", "run", "--bin", "app"]);
    assert!(
        forwarded.status.success(),
        "{}",
        String::from_utf8_lossy(&forwarded.stderr)
    );
    let forwarded_stdout = String::from_utf8_lossy(&forwarded.stdout);
    assert!(
        forwarded_stdout.contains("--")
            && forwarded_stdout.contains("cargo")
            && forwarded_stdout.contains("--bin"),
        "{forwarded_stdout}"
    );

    let output = cli(&["run", "dev"]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(String::from_utf8_lossy(&output.stdout).contains(env!("CARGO_PKG_VERSION")));

    let output = cli(&["run", "build"]);
    assert!(output.status.success());
    assert!(String::from_utf8_lossy(&output.stdout).contains("configured-build"));
    let output = cli(&[
        "build",
        "--root",
        ".",
        "--no-assets",
        "--no-check",
        "--offline",
    ]);
    assert!(
        !output.status.success(),
        "the empty workspace has no target"
    );
    assert!(!String::from_utf8_lossy(&output.stdout).contains("configured-build"));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("use `proa run build`"), "{stderr}");

    let output = cli(&["run", "report"]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(String::from_utf8_lossy(&output.stdout).contains(env!("CARGO_PKG_VERSION")));
    let output = cli(&["run", "--list"]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(String::from_utf8_lossy(&output.stdout).contains("report"));
}

#[cfg(unix)]
#[test]
fn terminating_a_supervised_script_stops_the_shells_children() {
    use std::{
        io::Write,
        process::Stdio,
        thread,
        time::{Duration, Instant},
    };

    let temp = tempfile::tempdir().unwrap();
    let root = temp.path();
    fs::write(root.join("Cargo.toml"), "[workspace]\n").unwrap();
    fs::write(
        root.join("proa.config.rs"),
        r#"use proa::config::{Config, Result, ScriptsConfig};
pub async fn config() -> Result<Config> {
    Ok(Config {
        scripts: ScriptsConfig { dev: "sh watcher.sh && echo finished", ..Default::default() },
        ..Default::default()
    })
}
"#,
    )
    .unwrap();
    fs::write(
        root.join("watcher.sh"),
        "trap 'touch stopped; exit' TERM\n\
         if [ -t 0 ]; then\n\
           IFS= read -r input && [ \"$input\" = start ] || exit 1\n\
         fi\n\
         printf '%s' \"$$\" > ready\n\
         while :; do sleep 1; done\n",
    )
    .unwrap();
    let ready = root.join("ready");
    let stopped = root.join("stopped");
    for interactive in [false, true] {
        let mut command = Command::new(env!("CARGO_BIN_EXE_proa"));
        command.current_dir(root).args(["run", "dev"]);
        let mut terminal = if interactive {
            Some(attach_test_terminal(&mut command))
        } else {
            command.stdin(Stdio::null());
            None
        };
        let mut cli = command.spawn().unwrap();
        drop(command);
        if let Some(terminal) = &mut terminal {
            terminal.write_all(b"start\n").unwrap();
        }
        let deadline = Instant::now() + Duration::from_secs(60);
        let watcher = loop {
            if let Some(pid) = fs::read_to_string(&ready)
                .ok()
                .and_then(|pid| pid.parse::<i32>().ok())
            {
                break pid;
            }
            if cli.try_wait().unwrap().is_some() || Instant::now() >= deadline {
                drop(terminal.take());
                let _ = cli.kill();
                let _ = cli.wait();
                panic!("script failed to start (terminal: {interactive})");
            }
            thread::sleep(Duration::from_millis(25));
        };

        assert_eq!(unsafe { libc::kill(cli.id() as i32, libc::SIGTERM) }, 0);
        let deadline = Instant::now() + Duration::from_secs(5);
        let status = loop {
            if let Some(status) = cli.try_wait().unwrap().filter(|_| stopped.exists()) {
                break status;
            }
            if Instant::now() >= deadline {
                drop(terminal.take());
                unsafe { libc::kill(watcher, libc::SIGKILL) };
                let _ = cli.kill();
                let _ = cli.wait();
                panic!("script failed to stop (terminal: {interactive})");
            }
            thread::sleep(Duration::from_millis(25));
        };
        assert_eq!(status.code(), Some(128 + libc::SIGTERM));
        fs::remove_file(&ready).unwrap();
        fs::remove_file(&stopped).unwrap();
    }
}

#[cfg(unix)]
fn attach_test_terminal(command: &mut Command) -> fs::File {
    use std::{
        io,
        os::{
            fd::{AsRawFd, FromRawFd, OwnedFd},
            unix::process::CommandExt,
        },
    };

    let mut controller_fd = -1;
    let mut terminal_fd = -1;
    unsafe {
        assert_eq!(
            libc::openpty(
                &mut controller_fd,
                &mut terminal_fd,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            ),
            0
        );
        let controller = OwnedFd::from_raw_fd(controller_fd);
        let terminal = OwnedFd::from_raw_fd(terminal_fd);
        // The test never reads tty output. Disable input echo so the OS
        // does not wait for the controller to drain echoed bytes on exit.
        let mut attributes = std::mem::zeroed();
        assert_eq!(libc::tcgetattr(terminal.as_raw_fd(), &mut attributes), 0);
        attributes.c_lflag &= !libc::ECHO;
        assert_eq!(
            libc::tcsetattr(terminal.as_raw_fd(), libc::TCSANOW, &attributes),
            0
        );
        for fd in [&controller, &terminal] {
            assert_eq!(
                libc::fcntl(fd.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC),
                0
            );
        }
        command.stdin(terminal);
        command.pre_exec(|| {
            let request = libc::TIOCSCTTY;
            #[cfg(target_vendor = "apple")]
            let request = libc::c_ulong::from(request);
            if libc::setsid() == -1
                || libc::ioctl(libc::STDIN_FILENO, request, 0) == -1
                || libc::tcsetpgrp(libc::STDIN_FILENO, libc::getpgrp()) == -1
            {
                return Err(io::Error::last_os_error());
            }
            Ok(())
        });
        fs::File::from(controller)
    }
}

#[test]
fn cargo_subcommand_dispatches_through_the_installed_executable_name() {
    let temp = tempfile::tempdir().unwrap();
    let executable = std::path::Path::new(env!("CARGO_BIN_EXE_cargo-proa"));
    let mut paths = vec![executable.parent().unwrap().to_path_buf()];
    paths.extend(env::split_paths(&env::var_os("PATH").unwrap_or_default()));
    let output = Command::new(env::var_os("CARGO").unwrap_or_else(|| "cargo".into()))
        .current_dir(temp.path())
        .env("PATH", env::join_paths(paths).unwrap())
        .args(["proa", "--version"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(String::from_utf8_lossy(&output.stdout).contains(env!("CARGO_PKG_VERSION")));
}

#[test]
fn start_launches_the_host_release_executable_and_preserves_explicit_paths() {
    let temp = tempfile::Builder::new()
        .prefix("proa start with spaces ")
        .tempdir()
        .unwrap();
    fs::write(temp.path().join("Cargo.toml"), "[workspace]\n").unwrap();
    let release = temp.path().join("target/release");
    fs::create_dir_all(&release).unwrap();
    let catalog = temp.path().join("copied catalog");
    fs::create_dir_all(&catalog).unwrap();
    fs::write(catalog.join("manifest.json"), "{}").unwrap();
    let executable = release.join(format!("server.prod{}", env::consts::EXE_SUFFIX));
    let source = temp.path().join("server.rs");
    fs::write(
        &source,
        r#"fn main() {
            let assets = std::env::var_os("PROA_PUBLIC_ASSETS");
            let assets = assets.as_deref().and_then(|path| std::path::Path::new(path).file_name());
            println!("{}|{}|{}", std::env::var("PROA_HOST").unwrap(), std::env::var("PORT").unwrap(), assets.and_then(|name| name.to_str()).unwrap_or_default());
        }"#,
    )
    .unwrap();
    let compiled = Command::new(env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()))
        .arg(&source)
        .arg("-o")
        .arg(&executable)
        .output()
        .unwrap();
    assert!(
        compiled.status.success(),
        "{}",
        String::from_utf8_lossy(&compiled.stderr)
    );

    let explicit = temp
        .path()
        .join(format!("custom.server{}", env::consts::EXE_SUFFIX));
    let mut cases = vec![("server.prod", false)];
    if cfg!(windows) {
        cases.extend([("server.prod.exe", false), ("server.prod.EXE", false)]);
    }
    cases.push(("server.prod", true));
    for (configured_binary, custom) in cases {
        fs::write(
            temp.path().join("proa.config.rs"),
            format!(
                r#"use proa::config::{{ApplicationConfig, Config, Result, ScriptsConfig}};
pub async fn config() -> Result<Config> {{
    Ok(Config {{
        scripts: ScriptsConfig {{
            dev: "cargo run",
            build: "cargo build --release",
            ..Default::default()
        }},
        application: Some(ApplicationConfig {{ binary: {configured_binary:?} }}),
        ..Config::default()
    }})
}}
"#,
            ),
        )
        .unwrap();
        if custom {
            fs::write(temp.path().join("proa.config.rs"), "invalid build config").unwrap();
            fs::rename(&executable, &explicit).unwrap();
        }
        let mut command = Command::new(env!("CARGO_BIN_EXE_proa"));
        command
            .current_dir(temp.path())
            .env_remove("CARGO_TARGET_DIR")
            .env_remove("PROA_PUBLIC_ASSETS")
            .args(["start", "--host", "127.0.0.2", "--port", "8123"]);
        if custom {
            command
                .current_dir(temp.path().parent().unwrap())
                .arg("--root")
                .arg(temp.path().file_name().unwrap())
                .arg("--bin")
                .arg(explicit.file_name().unwrap())
                .arg("--public-assets")
                .arg(catalog.file_name().unwrap());
        }
        let output = command.output().unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(
            String::from_utf8_lossy(&output.stdout).trim(),
            if custom {
                "127.0.0.2|8123|copied catalog"
            } else {
                "127.0.0.2|8123|"
            }
        );
    }
}

#[test]
fn start_auto_discovers_public_assets_from_proa_build_start_manifest() {
    let temp = tempfile::tempdir().unwrap();
    fs::write(temp.path().join("Cargo.toml"), "[workspace]\n").unwrap();
    fs::create_dir_all(temp.path().join(".cargo")).unwrap();
    fs::write(
        temp.path().join(".cargo/config.toml"),
        "[build]\ntarget-dir = \"custom-target\"\n",
    )
    .unwrap();
    let custom_target = temp.path().join("custom-target");
    let release = custom_target.join("release");
    fs::create_dir_all(&release).unwrap();
    let catalog_demo = custom_target.join("proa-output/demo/abc123");
    let catalog_admin = custom_target.join("proa-output/admin/def456");
    fs::create_dir_all(&catalog_demo).unwrap();
    fs::create_dir_all(&catalog_admin).unwrap();
    fs::write(catalog_demo.join("manifest.json"), "{}").unwrap();
    fs::write(catalog_admin.join("manifest.json"), "{}").unwrap();
    let demo_exec = release.join(format!("demo{}", env::consts::EXE_SUFFIX));
    let admin_exec = release.join(format!("admin{}", env::consts::EXE_SUFFIX));
    let cross_exec = custom_target.join("x86_64-unknown-linux-gnu/release/demo");
    fs::create_dir_all(cross_exec.parent().unwrap()).unwrap();
    fs::write(&cross_exec, b"foreign-elf").unwrap();
    let source = temp.path().join("server.rs");
    fs::write(
        &source,
        r#"fn main() {
            println!("{}", std::env::var("PROA_PUBLIC_ASSETS").unwrap_or_default());
        }"#,
    )
    .unwrap();
    for executable in [&demo_exec, &admin_exec] {
        let compiled = Command::new(env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()))
            .arg(&source)
            .arg("-o")
            .arg(executable)
            .output()
            .unwrap();
        assert!(compiled.status.success());
    }

    fs::write(
        temp.path().join("proa.config.rs"),
        r#"use proa::config::{ApplicationConfig, Config, Result};
pub async fn config() -> Result<Config> {
    Ok(Config {
        application: Some(ApplicationConfig { binary: "demo" }),
        ..Config::default()
    })
}
"#,
    )
    .unwrap();
    let manifest_dir = custom_target
        .join(if cfg!(windows) { "p" } else { "proa-rsjs" })
        .join("start-manifests");
    fs::create_dir_all(&manifest_dir).unwrap();
    for (filename, entry) in [
        (
            "demo.json",
            serde_json::json!({
                "schemaVersion": 1,
                "packageId": "pkg-demo",
                "binary": "demo",
                "profile": "release",
                "executable": demo_exec,
                "publicAssets": catalog_demo,
                "updatedAtNanos": 100,
            }),
        ),
        (
            "admin.json",
            serde_json::json!({
                "schemaVersion": 1,
                "packageId": "pkg-admin",
                "binary": "admin",
                "profile": "release",
                "executable": admin_exec,
                "publicAssets": catalog_admin,
                "updatedAtNanos": 200,
            }),
        ),
        (
            "demo-cross.json",
            serde_json::json!({
                "schemaVersion": 1,
                "packageId": "pkg-demo",
                "binary": "demo",
                "profile": "release",
                "targetTriple": "x86_64-unknown-linux-gnu",
                "executable": cross_exec,
                "publicAssets": catalog_admin,
                "updatedAtNanos": 300,
            }),
        ),
    ] {
        fs::write(manifest_dir.join(filename), entry.to_string()).unwrap();
    }

    // Bare `proa start` honors `.cargo/config.toml`'s `build.target-dir`, runs the
    // host `demo` binary (ignoring the cross-target entry), and injects `demo`'s assets.
    let output = Command::new(env!("CARGO_BIN_EXE_proa"))
        .current_dir(temp.path())
        .env_remove("CARGO_TARGET_DIR")
        .env_remove("PROA_PUBLIC_ASSETS")
        .args(["start"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(
        std::path::PathBuf::from(String::from_utf8_lossy(&output.stdout).trim())
            .canonicalize()
            .unwrap(),
        catalog_demo.canonicalize().unwrap()
    );

    // Starting the second binary keeps its own asset catalog from the same manifest.
    let admin_output = Command::new(env!("CARGO_BIN_EXE_proa"))
        .current_dir(temp.path())
        .env_remove("CARGO_TARGET_DIR")
        .env_remove("PROA_PUBLIC_ASSETS")
        .args(["start", "--bin"])
        .arg(&admin_exec)
        .output()
        .unwrap();
    assert!(
        admin_output.status.success(),
        "{}",
        String::from_utf8_lossy(&admin_output.stderr)
    );
    assert_eq!(
        std::path::PathBuf::from(String::from_utf8_lossy(&admin_output.stdout).trim())
            .canonicalize()
            .unwrap(),
        catalog_admin.canonicalize().unwrap()
    );
}