day-cli 0.0.6

Declarative app development API using native UI toolkits
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! Command tree (DESIGN.md §16.5). v0: new / build / launch / doctor; the remaining
//! porcelain (sign / pack / lint / script) lands with M6–M8.

use std::path::PathBuf;

use clap::{Parser, Subcommand};

use crate::meta;
use crate::ops;
use crate::targets;

#[derive(Parser)]
#[command(
    name = "day",
    version = env!("DAY_VERSION_LONG"),
    about = "Day — cross-platform apps in Rust with native toolkits"
)]
struct Cli {
    /// Project directory (default: nearest ancestor with day.yaml)
    #[arg(long, global = true)]
    project: Option<PathBuf>,
    /// Output format: plain (default) or json (NDJSON result events)
    #[arg(long, global = true, default_value = "plain")]
    format: String,
    #[command(subcommand)]
    command: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Print the version, build profile (`*` = debug), and the git ref it was built from
    Version,
    /// Scaffold a new Day project — an app, a piece, or a part (interactive when run bare)
    New {
        #[command(subcommand)]
        what: Option<NewKind>,
    },
    /// Build the app for one or more targets
    Build {
        #[arg(short = 'p', long = "platform", required = true)]
        platforms: Vec<String>,
        #[arg(long, default_value = "debug")]
        profile: String,
    },
    /// Build + launch on one or more targets (in parallel)
    Launch {
        #[arg(short = 'p', long = "platform", required = true)]
        platforms: Vec<String>,
        #[arg(long, default_value = "debug")]
        profile: String,
        /// BCP-47 locale override passed to the app
        #[arg(long)]
        locale: Option<String>,
        /// Extra environment K=V passed to the app (repeatable)
        #[arg(long = "env")]
        envs: Vec<String>,
        /// Exit after launch instead of staying attached to logs
        #[arg(long)]
        detach: bool,
        /// dayscript file(s) to execute after launch (repeatable; implies detach)
        #[arg(long = "script")]
        scripts: Vec<PathBuf>,
    },
    /// Build + sign + produce installable artifacts (.dmg / .ipa / .apk+.aab / .flatpak / .msix+setup.exe / .hap)
    Pack {
        #[arg(short = 'p', long = "platform", required = true)]
        platforms: Vec<String>,
        /// Pack defaults to release (distribution artifacts); pass debug for a dev-install pack.
        #[arg(long, default_value = "release")]
        profile: String,
        /// Comma-separated format subset (e.g. `--formats apk` to skip the aab)
        #[arg(long)]
        formats: Option<String>,
        /// Skip signing entirely (artifacts are marked unsigned)
        #[arg(long)]
        no_sign: bool,
        /// Sign but skip notarization (macOS)
        #[arg(long)]
        no_notarize: bool,
        /// Submit for notarization without waiting (check later: day sign --notarize-status <id>)
        #[arg(long)]
        no_wait: bool,
    },
    /// Signing utilities: --check validates day.yaml signing config (never prints secrets)
    Sign {
        /// Validate signing config resolvability (env vars set, files present)
        #[arg(long)]
        check: bool,
        /// Poll an async notarization submission by id
        #[arg(long = "notarize-status")]
        notarize_status: Option<String>,
    },
    /// Check the development environment, grouped by toolkit
    Doctor {
        /// Focus a toolkit (repeatable): its checks become errors + print setup help.
        /// One of: appkit, uikit, gtk, qt, winui, android, harmonyos.
        #[arg(long = "toolkit")]
        toolkits: Vec<String>,
    },
    /// Check the project for common errors (fluent coverage, ids)
    Lint {
        /// Exit non-zero (10) when findings exist
        #[arg(long)]
        strict: bool,
    },
    /// HarmonyOS / OpenHarmony helpers (emulator, …)
    Ohos {
        #[command(subcommand)]
        cmd: OhosCmd,
    },
    /// PLUMBING: invoked by the Xcode script phase (reads Xcode's env)
    #[command(name = "xcode-backend", hide = true)]
    XcodeBackend {
        #[arg(default_value = "build")]
        action: String,
    },
    /// PLUMBING: invoked by the gradle scaffold (reads DAY_* env)
    #[command(name = "gradle-backend", hide = true)]
    GradleBackend {
        #[arg(default_value = "build")]
        action: String,
    },
}

/// `day new <piece|part|app>` — scaffold an extension crate or app; `day new` (bare) walks an
/// interactive dialog. Every value-carrying flag has an equivalent question in the dialog (the dialog
/// is the fallback branch of the flags — see `new.rs`), so a value not passed on the command line is
/// asked for when a terminal is present, and defaulted (or reported as required) when it is not. The
/// meta flags `--local` (CI) and `--no-input` have no dialog fallback by design.
///
/// Scaffolds default to REMOTE (git) day dependencies so they are self-contained; the hidden
/// `--local <path>` (or `DAY_LOCAL` env) redirects to a local day checkout for CI smoke-tests of a
/// freshly-scaffolded project against the day tree under test.
#[derive(Subcommand)]
enum NewKind {
    /// Scaffold a Day PIECE crate (a reusable widget). No `--toolkits` ⇒ a COMPOSITE piece.
    Piece {
        /// Crate name (prompted if omitted in an interactive terminal).
        name: Option<String>,
        /// Comma-separated toolkits for a NATIVE piece (appkit,gtk,qt,uikit,widget,winui).
        /// Omit for a COMPOSITE piece (pure composition; works on every backend with no per-backend code).
        #[arg(long)]
        toolkits: Option<String>,
        /// Force a COMPOSITE piece even if `--toolkits` is given.
        #[arg(long)]
        composite: bool,
        /// Package id (reverse-DNS); default `dev.example.<name>`. Also the piece KIND + Java package.
        #[arg(long)]
        id: Option<String>,
        /// Scaffold `day` deps from the git remote — currently the DEFAULT (the day framework
        /// crates are not yet on crates.io); kept for forward compatibility.
        #[arg(long)]
        git: bool,
        /// Scaffold versioned `day` deps from crates.io, pinned to this CLI's version — for
        /// once the day framework crates are published.
        #[arg(long)]
        registry: bool,
        /// Use `path` deps rooted at a local day checkout (CI / framework development).
        #[arg(long, hide = true)]
        local: Option<PathBuf>,
        /// Never prompt; use flags + defaults only (also implied when stdin is not a terminal).
        #[arg(long)]
        no_input: bool,
    },
    /// Scaffold a Day PART crate (a headless, UI-less capability).
    Part {
        /// Crate name (prompted if omitted in an interactive terminal).
        name: Option<String>,
        /// Comma-separated platforms (macos,ios,android,linux,windows); default: all.
        #[arg(long)]
        platforms: Option<String>,
        /// Package id (reverse-DNS); default `dev.example.<name>`. Also the Java package.
        #[arg(long)]
        id: Option<String>,
        /// Scaffold `day` deps from the git remote — currently the DEFAULT (the day framework
        /// crates are not yet on crates.io); kept for forward compatibility.
        #[arg(long)]
        git: bool,
        /// Scaffold versioned `day` deps from crates.io, pinned to this CLI's version — for
        /// once the day framework crates are published.
        #[arg(long)]
        registry: bool,
        /// Use `path` deps rooted at a local day checkout (CI / framework development).
        #[arg(long, hide = true)]
        local: Option<PathBuf>,
        /// Never prompt; use flags + defaults only (also implied when stdin is not a terminal).
        #[arg(long)]
        no_input: bool,
    },
    /// Scaffold a new Day app (the canonical app command).
    App {
        /// App name (prompted if omitted in an interactive terminal).
        name: Option<String>,
        /// A target to support (repeatable): e.g. `--toolkit ios-uikit --toolkit macos-appkit`.
        /// Values may also be comma-separated. Omit to choose interactively.
        #[arg(long = "toolkit")]
        toolkits: Vec<String>,
        /// Application id / bundle id (reverse-DNS); default `dev.example.<name>`.
        #[arg(long)]
        appid: Option<String>,
        /// Alias for --appid (Android application id / Apple bundle id).
        #[arg(long)]
        bundleid: Option<String>,
        /// Back-compat alias for --appid.
        #[arg(long, hide = true)]
        id: Option<String>,
        /// Window / app-store display title; default: the name, title-cased (`hello-world` ⇒
        /// `Hello World`).
        #[arg(long)]
        title: Option<String>,
        /// Scaffold from a custom template instead of the built-in one: a local directory, or
        /// a git URL (optionally `#ref`). Files are rendered with {{name}}/{{title}}/{{id}}/…
        /// placeholders in contents and paths (see the docs for the full list + conventions).
        #[arg(long)]
        template: Option<String>,
        /// Back-compat: comma-separated target list (prefer repeated --toolkit).
        #[arg(long, hide = true)]
        targets: Option<String>,
        /// Scaffold `day` deps from the git remote — currently the DEFAULT (the day framework
        /// crates are not yet on crates.io); kept for forward compatibility.
        #[arg(long)]
        git: bool,
        /// Scaffold versioned `day` deps from crates.io, pinned to this CLI's version — for
        /// once the day framework crates are published.
        #[arg(long)]
        registry: bool,
        /// Use `path` deps rooted at a local day checkout (CI / framework development).
        #[arg(long, hide = true)]
        local: Option<PathBuf>,
        /// Never prompt; use flags + defaults only (also implied when stdin is not a terminal).
        #[arg(long)]
        no_input: bool,
    },
}

#[derive(clap::Subcommand)]
pub enum OhosCmd {
    /// Manage the OpenHarmony emulator
    Emulator {
        #[command(subcommand)]
        cmd: EmulatorCmd,
    },
}

#[derive(clap::Subcommand)]
pub enum EmulatorCmd {
    /// Launch the Oniro/OpenHarmony QEMU emulator as a native window (no VNC/password)
    Launch {
        /// No window (hdc-only) — for CI / headless hosts.
        #[arg(long)]
        headless: bool,
    },
}

pub fn run() -> i32 {
    let cli = Cli::parse();
    // Kick off the background crates.io update check now, so it runs while the command does. Silent for
    // the build-system plumbing callbacks (Xcode/Gradle) and for machine `--format json` output.
    let update = crate::update::spawn(
        cli.format != "json"
            && !matches!(
                cli.command,
                Cmd::XcodeBackend { .. } | Cmd::GradleBackend { .. }
            ),
    );
    let code = match cli.command {
        Cmd::Version => {
            println!("day {}", env!("DAY_VERSION_LONG"));
            0
        }
        Cmd::Doctor { toolkits } => crate::doctor::run(&toolkits),
        Cmd::Pack {
            platforms,
            profile,
            formats,
            no_sign,
            no_notarize,
            no_wait,
        } => with_project(cli.project.as_deref(), |project| {
            let opts = crate::pack::PackOptions {
                profile,
                formats: formats
                    .as_deref()
                    .map(|s| s.split(',').map(|f| f.trim().to_string()).collect()),
                no_sign,
                no_notarize,
                no_wait,
            };
            let mut outcomes = Vec::new();
            for p in &platforms {
                let Some(target) = targets::find(p) else {
                    eprintln!("error: unknown target {p:?}");
                    return 2;
                };
                match crate::pack::run(project, target, &opts) {
                    Ok(o) => outcomes.push(o),
                    Err(e) => {
                        eprintln!("error: {}", e.message());
                        return e.exit_code();
                    }
                }
            }
            if cli.format == "json" {
                print_pack_json(&outcomes);
            }
            0
        }),
        Cmd::Sign {
            check,
            notarize_status,
        } => with_project(cli.project.as_deref(), |project| {
            if let Some(id) = &notarize_status {
                return crate::sign::notarize_status(project, id);
            }
            if check {
                return crate::sign::check(project);
            }
            eprintln!("error: day sign needs --check or --notarize-status <id>");
            2
        }),
        Cmd::Lint { strict } => with_project(cli.project.as_deref(), |project| {
            crate::lint::run(project, strict)
        }),
        Cmd::Ohos {
            cmd:
                OhosCmd::Emulator {
                    cmd: EmulatorCmd::Launch { headless },
                },
        } => match crate::ohos::emulator_launch(headless) {
            Ok(()) => 0,
            Err(e) => {
                eprintln!("error: {e}");
                5
            }
        },
        Cmd::XcodeBackend { .. } => crate::mobile::xcode_backend_build(),
        Cmd::GradleBackend { .. } => crate::mobile::gradle_backend_build(),
        Cmd::New { what } => match what {
            None => crate::new::interactive(),
            Some(NewKind::Piece {
                name,
                toolkits,
                composite,
                id,
                git,
                registry,
                local,
                no_input,
            }) => crate::new::piece(
                name.as_deref(),
                toolkits.as_deref(),
                composite,
                id.as_deref(),
                local.as_deref(),
                git,
                registry,
                no_input,
            ),
            Some(NewKind::Part {
                name,
                platforms,
                id,
                git,
                registry,
                local,
                no_input,
            }) => crate::new::part(
                name.as_deref(),
                platforms.as_deref(),
                id.as_deref(),
                local.as_deref(),
                git,
                registry,
                no_input,
            ),
            Some(NewKind::App {
                name,
                toolkits,
                appid,
                bundleid,
                id,
                title,
                template,
                targets,
                git,
                registry,
                local,
                no_input,
            }) => crate::new::app(
                name.as_deref(),
                &toolkits,
                appid.as_deref(),
                bundleid.as_deref(),
                id.as_deref(),
                title.as_deref(),
                template.as_deref(),
                targets.as_deref(),
                local.as_deref(),
                git,
                registry,
                no_input,
            ),
        },
        Cmd::Build { platforms, profile } => with_project(cli.project.as_deref(), |project| {
            let mut results = Vec::new();
            for p in &platforms {
                let target = match targets::find(p) {
                    Some(t) => t,
                    None => {
                        eprintln!("error: unknown target {p:?}");
                        return 2;
                    }
                };
                match ops::build(project, target, &profile) {
                    Ok(o) => {
                        ops::status(
                            "Built",
                            &format!(
                                "{}{} ({:.1}s)",
                                o.target,
                                o.artifact.display(),
                                o.seconds
                            ),
                        );
                        results.push(o);
                    }
                    Err(e) => {
                        eprintln!("error: {e}");
                        return 4;
                    }
                }
            }
            if cli.format == "json" {
                print_result_json("build", &results);
            }
            0
        }),
        Cmd::Launch {
            platforms,
            profile,
            locale,
            envs,
            detach,
            scripts,
        } => with_project(cli.project.as_deref(), |project| {
            let script_mode = !scripts.is_empty();
            let mut spec = ops::LaunchSpec {
                locale: locale.clone(),
                envs: envs
                    .iter()
                    .filter_map(|kv| kv.split_once('=').map(|(k, v)| (k.into(), v.into())))
                    .collect(),
                attached: !detach && !script_mode,
            };
            // Ctrl-C during an attached run must take the launched apps and their log
            // watchers (simctl / adb logcat) down too — not leave them orphaned.
            if spec.attached {
                crate::signals::install();
            }
            let token = crate::script::make_token();
            let mut handles = Vec::new();
            let mut script_failures = 0usize;
            for (ti, p) in platforms.iter().enumerate() {
                let port = crate::script::pick_port(ti);
                if script_mode {
                    spec.envs
                        .retain(|(k, _)| k != "DAYSCRIPT_PORT" && k != "DAYSCRIPT_TOKEN");
                    spec.envs.push(("DAYSCRIPT_PORT".into(), port.to_string()));
                    spec.envs.push(("DAYSCRIPT_TOKEN".into(), token.clone()));
                }
                let target = match targets::find(p) {
                    Some(t) => t,
                    None => {
                        eprintln!("error: unknown target {p:?}");
                        return 2;
                    }
                };
                let outcome = match ops::build(project, target, &profile) {
                    Ok(o) => o,
                    Err(e) => {
                        eprintln!("error: {e}");
                        return 4;
                    }
                };
                match ops::launch(project, target, &outcome, &spec) {
                    Ok(h) => handles.push(h),
                    Err(e) => {
                        eprintln!("error: {e}");
                        return 1;
                    }
                }
                if script_mode {
                    match crate::script::run_scripts(
                        project,
                        target,
                        port,
                        &token,
                        &scripts,
                        locale.as_deref(),
                    ) {
                        Ok(run) => {
                            script_failures += run.steps_failed;
                            ops::status(
                                "Script",
                                &format!(
                                    "{}: {}/{} steps passed · {} screenshot(s)",
                                    target.name,
                                    run.steps_total - run.steps_failed,
                                    run.steps_total,
                                    run.screenshots.len()
                                ),
                            );
                        }
                        Err(e) => {
                            eprintln!("error: {e}");
                            return 5;
                        }
                    }
                }
            }
            if script_mode {
                return if script_failures > 0 { 5 } else { 0 };
            }
            if spec.attached {
                let mut code = 0;
                for h in handles {
                    code = code.max(h.join().unwrap_or(1));
                }
                // A target that exited on its own leaves its siblings' log watchers (and
                // any child that outlives its stream) running — reap them before we go.
                crate::signals::kill_all();
                code
            } else {
                0
            }
        }),
    };
    // Non-blocking: nudge only if the crates.io reply already arrived; never waits for it.
    crate::update::finish(update);
    code
}

fn with_project(start: Option<&std::path::Path>, f: impl FnOnce(&meta::Project) -> i32) -> i32 {
    match meta::find_project(start) {
        Ok(p) => f(&p),
        Err(e) => {
            eprintln!("error: {e}");
            2
        }
    }
}

fn print_pack_json(outcomes: &[crate::pack::PackOutcome]) {
    let targets: Vec<serde_json::Value> = outcomes
        .iter()
        .map(|o| {
            let artifacts: Vec<serde_json::Value> = o
                .artifacts
                .iter()
                .map(|a| {
                    serde_json::json!({
                        "path": a.path, "kind": a.kind,
                        "sha256": a.sha256, "signed": a.tier.as_str(),
                    })
                })
                .collect();
            serde_json::json!({
                "target": o.target, "ok": true, "code": 0,
                "artifacts": artifacts, "seconds": o.seconds,
            })
        })
        .collect();
    println!(
        "{}",
        serde_json::json!({"event": "result", "command": "pack", "ok": true, "targets": targets})
    );
}

fn print_result_json(command: &str, results: &[ops::BuildOutcome]) {
    let targets: Vec<serde_json::Value> = results
        .iter()
        .map(|o| {
            serde_json::json!({
                "target": o.target, "ok": true, "code": 0,
                "artifacts": [{"path": o.artifact}], "seconds": o.seconds,
            })
        })
        .collect();
    println!(
        "{}",
        serde_json::json!({"event": "result", "command": command, "ok": true, "targets": targets})
    );
}