glory-cli 0.9.1

Project-local build and development tools for Glory semantic applications
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
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Output};

use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};

use crate::Result;
use crate::args::Args;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Platform {
    Web,
    Desktop,
    Server,
}

#[derive(Clone, Default, Deserialize)]
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
pub struct Config {
    pub default_platform: Option<String>,
    pub web: Host,
    pub desktop: Host,
    pub server: Host,
}

#[derive(Clone, Default, Deserialize)]
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
pub struct Host {
    pub bin: Option<String>,
    pub target: Option<String>,
    pub features: Vec<String>,
    pub no_default_features: bool,
    pub index: Option<PathBuf>,
    pub assets: Vec<PathBuf>,
    pub port: Option<u16>,
    pub bundle_identifier: Option<String>,
}

#[derive(Clone)]
pub struct Paths {
    pub root: PathBuf,
    pub cargo_home: PathBuf,
    pub target: PathBuf,
    pub temp: PathBuf,
}

impl Paths {
    pub fn new(manifest: &Path, requested: Option<&Path>) -> Result<Self> {
        let application = manifest.parent().ok_or("manifest has no parent")?;
        let metadata: Value = serde_json::from_slice(
            &capture(
                Command::new("cargo")
                    .current_dir(application)
                    .args([
                        "metadata",
                        "--no-deps",
                        "--format-version",
                        "1",
                        "--manifest-path",
                    ])
                    .arg(manifest),
            )?
            .stdout,
        )
        .map_err(|e| e.to_string())?;
        let target = compiler_path(PathBuf::from(
            metadata["target_directory"]
                .as_str()
                .ok_or("Cargo metadata has no target_directory")?,
        ));
        std::fs::create_dir_all(&target)
            .map_err(|e| format!("create {}: {e}", target.display()))?;
        let root = requested
            .map(Path::to_path_buf)
            .or_else(|| std::env::var_os("GLORY_BUILD_ROOT").map(PathBuf::from))
            .unwrap_or_else(|| target.join("glory"));
        validate_build_root(&root)?;
        std::fs::create_dir_all(&root).map_err(|e| format!("create {}: {e}", root.display()))?;
        let root = compiler_path(root.canonicalize().map_err(|e| e.to_string())?);
        validate_build_root(&root)?;
        let application = application.canonicalize().map_err(|e| e.to_string())?;
        if application.starts_with(&root) {
            return Err("build output must not overwrite the application source directory".into());
        }
        let cargo_home = std::env::var_os("CARGO_HOME")
            .map(PathBuf::from)
            .or_else(|| {
                std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
                    .map(|home| PathBuf::from(home).join(".cargo"))
            })
            .ok_or("cannot determine Cargo home")?;
        Ok(Self {
            root,
            cargo_home,
            target,
            temp: std::env::temp_dir(),
        })
    }

    pub fn apply(&self, _command: &mut Command) {
        // Child commands inherit the caller's Cargo and temporary directories.
    }
}

fn compiler_path(path: PathBuf) -> PathBuf {
    #[cfg(windows)]
    if let Some(normal) = path.to_str().and_then(|path| path.strip_prefix(r"\\?\"))
        && normal.as_bytes().get(1) == Some(&b':')
    {
        return PathBuf::from(normal);
    }
    path
}

pub fn validate_build_root(path: &Path) -> Result<()> {
    if path
        .components()
        .any(|part| matches!(part, Component::ParentDir))
    {
        return Err("build paths must not contain '..'".into());
    }
    if !path.is_absolute() || path.parent().is_none() {
        return Err("build output must be an absolute directory below a filesystem root".into());
    }
    let portable = path
        .to_string_lossy()
        .replace('\\', "/")
        .to_ascii_lowercase();
    if portable == "d:/buildcache"
        || portable.starts_with("d:/buildcache/")
        || portable.starts_with("/mnt/d/buildcache/")
        || portable.contains("/.codex/build-targets")
    {
        return Err("the retired shared build directory cannot be used".into());
    }
    Ok(())
}

#[derive(Clone)]
pub struct Project {
    pub cancel: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
    pub root: PathBuf,
    pub manifest: PathBuf,
    pub package: Value,
    pub host: Host,
    pub platform: Platform,
    pub paths: Paths,
    pub rust_host: String,
    pub build_target: String,
    pub bindgen_version: Option<String>,
    pub watch_roots: Vec<PathBuf>,
}

impl Project {
    pub fn load(manifest: &Path, args: &Args) -> Result<Self> {
        let manifest = manifest
            .canonicalize()
            .map_err(|e| format!("{}: {e}", manifest.display()))?;
        let root = manifest
            .parent()
            .ok_or("manifest has no parent")?
            .to_path_buf();
        let paths = Paths::new(&manifest, args.build_root.as_deref())?;
        let mut command = cargo(&root, &paths);
        command
            .args([
                "metadata",
                "--locked",
                "--no-deps",
                "--format-version",
                "1",
                "--manifest-path",
            ])
            .arg(&manifest);
        if args.offline {
            command.arg("--offline");
        }
        let metadata: Value = serde_json::from_slice(
            &capture_with_cancel(&mut command, args.cancel.as_deref())?.stdout,
        )
        .map_err(|e| e.to_string())?;
        verify_target(&metadata, &paths)?;
        let packages = metadata["packages"]
            .as_array()
            .ok_or("Cargo metadata has no packages")?;
        let default_member = metadata["workspace_default_members"]
            .as_array()
            .filter(|members| members.len() == 1)
            .and_then(|members| members[0].as_str());
        let selected = packages
            .iter()
            .find(|package| {
                if let Some(name) = &args.package {
                    package["name"].as_str() == Some(name)
                } else {
                    package["manifest_path"]
                        .as_str()
                        .is_some_and(|path| Path::new(path) == manifest)
                }
            })
            .or_else(|| {
                if args.package.is_none() {
                    packages
                        .iter()
                        .find(|package| package["id"].as_str() == default_member)
                } else {
                    None
                }
            })
            .ok_or("select an application with --package when using a virtual workspace")?
            .clone();
        let manifest = PathBuf::from(
            selected["manifest_path"]
                .as_str()
                .ok_or("package has no manifest")?,
        );
        let root = manifest
            .parent()
            .ok_or("manifest has no parent")?
            .to_path_buf();
        let config = match selected["metadata"].get("glory") {
            Some(value) => serde_json::from_value::<Config>(value.clone())
                .map_err(|e| format!("package.metadata.glory: {e}"))?,
            None => Config::default(),
        };
        let targets = selected["targets"]
            .as_array()
            .ok_or("package has no targets")?;
        let has_web = targets.iter().any(|target| {
            target["crate_types"]
                .as_array()
                .is_some_and(|types| types.iter().any(|kind| kind == "cdylib"))
        });
        let platform = match args
            .platform
            .as_deref()
            .or(config.default_platform.as_deref())
            .unwrap_or(if has_web { "web" } else { "desktop" })
        {
            "web" => Platform::Web,
            "desktop" => Platform::Desktop,
            "server" => Platform::Server,
            other => {
                return Err(format!(
                    "unsupported platform {other:?}; choose web, desktop or server"
                ));
            }
        };
        if platform == Platform::Web && !has_web {
            return Err(
                "Web needs a library target with crate-type = [\"cdylib\", \"rlib\"]".into(),
            );
        }
        let mut host = match platform {
            Platform::Web => config.web,
            Platform::Desktop => config.desktop,
            Platform::Server => config.server,
        };
        if platform == Platform::Web && (args.bin.is_some() || !args.app_args.is_empty()) {
            return Err("Web uses a library entry and accepts no application arguments".into());
        }
        if platform != Platform::Web && args.wasm_opt.is_some() {
            return Err("--wasm-opt is only supported for Web".into());
        }
        if let Some(bin) = &args.bin {
            host.bin = Some(bin.clone());
        }
        if platform != Platform::Web {
            let bins: Vec<_> = targets
                .iter()
                .filter(|target| {
                    target["kind"]
                        .as_array()
                        .is_some_and(|kinds| kinds.iter().any(|kind| kind == "bin"))
                })
                .collect();
            let target = if let Some(bin) = &host.bin {
                bins.iter()
                    .copied()
                    .find(|target| target["name"].as_str() == Some(bin))
            } else if bins.len() == 1 {
                Some(bins[0])
            } else {
                None
            }
            .ok_or("no matching unique binary; use --bin NAME or set the selected platform's bin in package.metadata.glory")?;
            host.bin = target["name"].as_str().map(str::to_owned);
            for feature in strings(&target["required-features"]) {
                if !host.features.contains(&feature) {
                    host.features.push(feature);
                }
            }
        } else if host.features.is_empty() && selected["features"].get("web").is_some() {
            host.features.push("web".into());
        }
        for feature in &args.features {
            if !host.features.contains(feature) {
                host.features.push(feature.clone());
            }
        }
        host.no_default_features |= args.no_default_features;
        let rust = capture(Command::new("rustc").arg("-vV").current_dir(&root))?;
        let rust = String::from_utf8_lossy(&rust.stdout);
        let rust_host = rust
            .lines()
            .find_map(|line| line.strip_prefix("host: "))
            .ok_or("rustc did not report its host")?
            .to_owned();
        let build_target = resolve_target(
            platform,
            args.target.as_deref().or(host.target.as_deref()),
            &rust_host,
        )?;
        let targets = capture(Command::new("rustc").args(["--print", "target-list"]))?;
        if !String::from_utf8_lossy(&targets.stdout)
            .lines()
            .any(|target| target == build_target)
        {
            return Err(format!(
                "unknown built-in Rust target {build_target:?}; use rustc --print target-list"
            ));
        }
        let mut project = Self {
            cancel: args.cancel.clone(),
            root,
            manifest,
            package: selected,
            host,
            platform,
            paths,
            rust_host,
            build_target,
            bindgen_version: None,
            watch_roots: Vec::new(),
        };
        let mut command = project.cargo();
        command.args([
            "metadata",
            "--locked",
            "--format-version",
            "1",
            "--filter-platform",
            project.target(),
        ]);
        project.selection(&mut command, false, args);
        let metadata: Value = serde_json::from_slice(
            &capture_with_cancel(&mut command, args.cancel.as_deref())?.stdout,
        )
        .map_err(|e| e.to_string())?;
        project.bindgen_version = compatible_dependencies(
            &metadata,
            project.package["id"].as_str().ok_or("package has no id")?,
        )?;
        let packages = metadata["packages"]
            .as_array()
            .ok_or("Cargo metadata has no packages")?;
        project.watch_roots = packages
            .iter()
            .filter(|package| package["source"].is_null())
            .filter_map(|package| package["manifest_path"].as_str())
            .filter_map(|path| Path::new(path).parent())
            .map(Path::to_path_buf)
            .filter(|path| !path.starts_with(&project.paths.root))
            .collect();
        Ok(project)
    }

    pub fn cargo(&self) -> Command {
        cargo(&self.root, &self.paths)
    }

    pub fn capture(&self, command: &mut Command) -> Result<Output> {
        capture_with_cancel(command, self.cancel.as_deref())
    }

    pub fn status(&self, command: &mut Command) -> Result<()> {
        crate::process::inherited(command, self.cancel.as_deref())
    }

    pub fn selection(&self, command: &mut Command, package: bool, args: &Args) {
        command.arg("--manifest-path").arg(&self.manifest);
        if package {
            command.arg("--package").arg(self.name());
        }
        if !self.host.features.is_empty() {
            command.arg("--features").arg(self.host.features.join(","));
        }
        if self.host.no_default_features {
            command.arg("--no-default-features");
        }
        if args.offline {
            command.arg("--offline");
        }
    }

    pub fn name(&self) -> &str {
        self.package["name"].as_str().unwrap_or("app")
    }
    pub fn target(&self) -> &str {
        &self.build_target
    }

    pub fn ensure_runnable(&self) -> Result<()> {
        if self.platform != Platform::Web && self.target() != self.rust_host {
            return Err(format!(
                "cannot run target {} on host {}; use build or bundle and run on the target system",
                self.target(),
                self.rust_host
            ));
        }
        Ok(())
    }

    pub fn plan(&self, args: &Args) -> Result<Value> {
        let command = self.build_command(args);
        let text = |value: &std::ffi::OsStr| {
            value
                .to_str()
                .map(str::to_owned)
                .ok_or_else(|| "JSON command output requires UTF-8 paths".to_owned())
        };
        let arguments = command.get_args().map(text).collect::<Result<Vec<_>>>()?;
        let environment = command
            .get_envs()
            .filter_map(|(key, value)| value.map(|value| (key, value)))
            .map(|(key, value)| Ok((text(key)?, text(value)?)))
            .collect::<Result<std::collections::BTreeMap<_, _>>>()?;
        let bindgen = args
            .bindgen
            .as_deref()
            .map(|path| text(path.as_os_str()))
            .transpose()?;
        let wasm_opt = args
            .wasm_opt
            .as_deref()
            .map(|path| text(path.as_os_str()))
            .transpose()?;
        Ok(
            json!({ "cli_version": env!("CARGO_PKG_VERSION"), "manifest": self.manifest,
            "package": self.name(), "platform": self.platform, "features": self.host.features, "rust_host": self.rust_host,
            "bin": self.host.bin, "target": self.target(), "release": args.release || args.command == crate::args::Command::Bundle,
            "no_default_features": self.host.no_default_features,
            "cargo_command": { "program": text(command.get_program())?, "args": arguments,
                "cwd": command.get_current_dir(), "env": environment },
            "build_root": self.paths.root, "cargo_home": self.paths.cargo_home,
            "target_directory": self.paths.target, "temporary_directory": self.paths.temp,
            "wasm_bindgen_version": self.bindgen_version, "bindgen_override": bindgen,
            "wasm_opt": wasm_opt, "wasm_opt_version": args.wasm_opt_version }),
        )
    }

    // This exact command drives both `print` and execution. No shell interpolation.
    pub fn build_command(&self, args: &Args) -> Command {
        let mut command = self.cargo();
        command.args([
            "build",
            "--locked",
            "--message-format=json-render-diagnostics",
            "--target",
            self.target(),
        ]);
        self.selection(&mut command, true, args);
        if args.release || args.command == crate::args::Command::Bundle {
            command.arg("--release");
        }
        if self.platform == Platform::Web {
            command.arg("--lib");
        } else if let Some(bin) = &self.host.bin {
            command.arg("--bin").arg(bin);
        }
        command
    }

    pub fn app_command(&self, executable: &Path, args: &Args) -> Command {
        let mut command = Command::new(executable);
        command.current_dir(&self.root).args(&args.app_args);
        self.paths.apply(&mut command);
        command
    }

    pub fn print(&self, args: &Args) -> Result<()> {
        println!(
            "{}",
            serde_json::to_string_pretty(&self.plan(args)?).map_err(|e| e.to_string())?
        );
        Ok(())
    }

    pub fn doctor(&self, args: &Args) -> Result<()> {
        let rust = capture(
            Command::new("rustc")
                .arg("--version")
                .current_dir(&self.root),
        )?;
        println!(
            "Glory CLI {}\nApplication: {}\n{}",
            env!("CARGO_PKG_VERSION"),
            self.name(),
            String::from_utf8_lossy(&rust.stdout).trim()
        );
        println!(
            "Host: {}\nBuild root: {}\nCargo target: {}\nCargo home: {}",
            self.rust_host,
            self.paths.root.display(),
            self.paths.target.display(),
            self.paths.cargo_home.display()
        );
        let mut command = Command::new("rustc");
        command.args(["--print", "target-libdir", "--target", self.target()]);
        self.paths.apply(&mut command);
        let output = self.capture(&mut command)?;
        let library = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
        let installed = std::fs::read_dir(&library).is_ok_and(|entries| {
            entries.filter_map(std::result::Result::ok).any(|entry| {
                let name = entry.file_name();
                let name = name.to_string_lossy();
                name.starts_with("libstd-") && name.ends_with(".rlib")
            })
        });
        println!(
            "Build target: {}\nTarget libraries: {}",
            self.target(),
            library.display()
        );
        if !installed {
            return Err(format!(
                "Rust standard library for {} is missing; install it with rustup target add {}",
                self.target(),
                self.target()
            ));
        }
        if self.platform != Platform::Web && self.target() != self.rust_host {
            println!(
                "Cross-compilation selected: configure the target linker/SDK using Cargo; run is disabled. Linker and runtime availability require a real build and target-system acceptance."
            );
        }
        if let Some(version) = &self.bindgen_version {
            println!(
                "Required wasm-bindgen: {version} (project-local installation on first Web build)"
            );
        }
        if let Some(path) = crate::wasm_opt::verify(self, args)? {
            println!(
                "Verified wasm-opt: {} (version {})",
                path.display(),
                args.wasm_opt_version.as_deref().unwrap()
            );
        }
        println!("Framework version and Cargo target verified; no global Glory CLI is used.");
        Ok(())
    }

    pub fn check(&self, args: &Args) -> Result<()> {
        for subcommand in ["check", "clippy"] {
            let mut command = self.cargo();
            command.args([subcommand, "--locked", "--target", self.target()]);
            if let Some(bin) = &args.bin {
                command.args(["--bin", bin]);
            } else {
                command.arg("--all-targets");
            }
            self.selection(&mut command, true, args);
            if args.release {
                command.arg("--release");
            }
            if subcommand == "clippy" {
                command.args(["--", "-D", "warnings"]);
            }
            self.status(&mut command)?;
        }
        Ok(())
    }

    pub fn format(&self, args: &Args) -> Result<()> {
        let mut command = self.cargo();
        command
            .args(["fmt", "--manifest-path"])
            .arg(&self.manifest)
            .args(["--package", self.name()]);
        if args.check {
            command.args(["--", "--check"]);
        }
        self.status(&mut command)
    }
}

fn resolve_target(platform: Platform, requested: Option<&str>, rust_host: &str) -> Result<String> {
    let target = requested.unwrap_or(if platform == Platform::Web {
        "wasm32-unknown-unknown"
    } else {
        rust_host
    });
    if target.is_empty()
        || !target
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
    {
        return Err(
            "--target must be a built-in Rust target triple, not a path or command option".into(),
        );
    }
    if platform == Platform::Web {
        if target != "wasm32-unknown-unknown" {
            return Err("Web requires --target wasm32-unknown-unknown".into());
        }
    } else if !(target.contains("-windows-")
        || (target.contains("-linux-") && !target.contains("android"))
        || target.ends_with("-apple-darwin"))
    {
        return Err(format!(
            "{target:?} has no configured desktop/server host; Android and iOS need dedicated application hosts and packaging"
        ));
    }
    Ok(target.to_owned())
}

fn cargo(root: &Path, paths: &Paths) -> Command {
    let mut command = Command::new("cargo");
    command.current_dir(root);
    paths.apply(&mut command);
    command
}

pub fn strings(value: &Value) -> Vec<String> {
    value
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(Value::as_str)
        .map(str::to_owned)
        .collect()
}

fn verify_target(metadata: &Value, paths: &Paths) -> Result<()> {
    let actual = metadata["target_directory"]
        .as_str()
        .ok_or("Cargo metadata has no target_directory")?;
    let actual = std::fs::canonicalize(actual).map_err(|e| e.to_string())?;
    if actual != paths.target.canonicalize().map_err(|e| e.to_string())? {
        return Err(format!(
            "Cargo target directory differs from the selected D: build root: {actual:?}"
        ));
    }
    Ok(())
}

pub fn compatible_dependencies(metadata: &Value, application: &str) -> Result<Option<String>> {
    let nodes = metadata["resolve"]["nodes"]
        .as_array()
        .ok_or("Cargo metadata has no dependency resolution")?;
    let packages = metadata["packages"]
        .as_array()
        .ok_or("Cargo metadata has no packages")?;
    let mut pending = vec![application.to_owned()];
    let mut visited = HashSet::new();
    let mut framework = false;
    let mut bindgen = None;
    while let Some(id) = pending.pop() {
        if !visited.insert(id.clone()) {
            continue;
        }
        let package = packages
            .iter()
            .find(|package| package["id"].as_str() == Some(&id))
            .ok_or("resolved dependency is missing")?;
        let name = package["name"].as_str().unwrap_or("");
        if ["glory", "glory-core", "glory-render", "glory-ui"].contains(&name) {
            framework = true;
            if package["version"].as_str() != Some(env!("CARGO_PKG_VERSION")) {
                return Err(format!(
                    "{name} {} is incompatible with glory-cli {}; update the project's tool dependency and Cargo.lock together",
                    package["version"],
                    env!("CARGO_PKG_VERSION")
                ));
            }
            verify_source(package)?;
        }
        if name == "wasm-bindgen" {
            let version = package["version"]
                .as_str()
                .ok_or("wasm-bindgen has no version")?
                .to_owned();
            if bindgen
                .as_ref()
                .is_some_and(|existing| existing != &version)
            {
                return Err("multiple wasm-bindgen versions reach the selected application".into());
            }
            bindgen = Some(version);
        }
        if let Some(node) = nodes.iter().find(|node| node["id"].as_str() == Some(&id))
            && let Some(deps) = node["deps"].as_array()
        {
            for dep in deps {
                let normal = dep["dep_kinds"]
                    .as_array()
                    .is_none_or(|kinds| kinds.iter().any(|kind| kind["kind"].is_null()));
                if normal && let Some(id) = dep["pkg"].as_str() {
                    pending.push(id.to_owned());
                }
            }
        }
    }
    if !framework {
        return Err("selected application has no active Glory dependency".into());
    }
    Ok(bindgen)
}

pub fn capture(command: &mut Command) -> Result<Output> {
    capture_with_cancel(command, None)
}

fn capture_with_cancel(
    command: &mut Command,
    cancel: Option<&std::sync::atomic::AtomicBool>,
) -> Result<Output> {
    let output = crate::process::captured(command, cancel)?;
    if !output.status.success() {
        let diagnostics = output
            .stdout
            .split(|byte| *byte == b'\n')
            .filter_map(|line| {
                let message: Value = serde_json::from_slice(line).ok()?;
                message["message"]["rendered"].as_str().map(str::to_owned)
            })
            .collect::<Vec<_>>()
            .join("");
        return Err(format!(
            "{command:?} exited with {}\n{}{diagnostics}",
            output.status,
            String::from_utf8_lossy(&output.stderr)
        ));
    }
    Ok(output)
}

fn verify_source(package: &Value) -> Result<()> {
    let tool_revision = env!("GLORY_CLI_SOURCE_REV");
    let framework_revision = if let Some(source) = package["source"].as_str() {
        if source.starts_with("git+") {
            Some(
                source
                    .rsplit('#')
                    .next()
                    .ok_or("Git dependency has no revision")?
                    .to_owned(),
            )
        } else {
            None
        }
    } else if let Some(manifest) = package["manifest_path"].as_str() {
        let output = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(
                Path::new(manifest)
                    .parent()
                    .ok_or("dependency manifest has no parent")?,
            )
            .output();
        output
            .ok()
            .filter(|output| output.status.success())
            .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
    } else {
        None
    };
    if let Some(revision) = framework_revision
        && (tool_revision.is_empty() || tool_revision != revision)
    {
        return Err(format!(
            "Glory source revision {revision} differs from CLI revision {tool_revision:?}; pin both to the same full Git commit (a matching version number is insufficient)"
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn real_cargo_overrides_print_replay_and_native_arguments_share_one_selection() {
        let scratch = crate::test_support::Scratch::new();
        // A tiny versioned stub keeps this host-tool suite independent of the
        // runtime workspace, including when testing a packaged CLI source.
        scratch.write(
            "framework/Cargo.toml",
            &format!(
                "[package]\nname = \"glory-core\"\nversion = {:?}\nedition = \"2024\"\n",
                env!("CARGO_PKG_VERSION")
            ),
        );
        scratch.write("framework/src/lib.rs", "");
        scratch.write(
            "Cargo.toml",
            r#"[package]
name = "selection-fixture"
version = "0.0.0"
edition = "2024"
[workspace]
[features]
default = ["unwanted"]
unwanted = []
entry = []
extra = []
[dependencies]
glory-core = { path = "framework" }
[package.metadata.glory.desktop]
bin = "other"
[[bin]]
name = "chosen"
path = "chosen.rs"
required-features = ["entry"]
[[bin]]
name = "other"
path = "other.rs"
"#,
        );
        scratch.write(
            "other.rs",
            "compile_error!(\"wrong binary selected\"); fn main() {}\n",
        );
        scratch.write(
            "chosen.rs",
            r#"
#[cfg(feature = "unwanted")]
compile_error!("defaults were not disabled");
#[cfg(not(feature = "extra"))]
compile_error!("extra feature was not selected");
fn main() {
    let mut args = std::env::args().skip(1);
    std::fs::write(args.next().unwrap(), args.collect::<Vec<_>>().join("\n")).unwrap();
}
"#,
        );
        let manifest = scratch.0.join("Cargo.toml");
        let output = scratch.0.join("arguments.txt");
        let args = Args::parse([
            "run".into(),
            "--offline".into(),
            "--bin".into(),
            "chosen".into(),
            "--features".into(),
            "extra".into(),
            "--no-default-features".into(),
            "--build-root".into(),
            scratch.0.join("build").into_os_string(),
            "--".into(),
            output.clone().into_os_string(),
            "a value with spaces".into(),
            "$(literal); --offline".into(),
        ])
        .unwrap();
        let paths = Paths::new(&manifest, args.build_root.as_deref()).unwrap();
        let mut lock = cargo(&scratch.0, &paths);
        lock.args(["generate-lockfile", "--offline", "--manifest-path"])
            .arg(&manifest);
        capture(&mut lock).unwrap();
        let before = std::fs::read(scratch.0.join("Cargo.lock")).unwrap();
        let project = Project::load(&manifest, &args).unwrap();
        assert_eq!(project.host.features, ["entry", "extra"]);
        assert!(project.host.no_default_features);
        let plan = project.plan(&args).unwrap();
        let description = &plan["cargo_command"];
        let mut replay = Command::new(description["program"].as_str().unwrap());
        replay
            .current_dir(description["cwd"].as_str().unwrap())
            .args(
                description["args"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .map(|arg| arg.as_str().unwrap()),
            );
        for (key, value) in description["env"].as_object().unwrap() {
            replay.env(key, value.as_str().unwrap());
        }
        project.capture(&mut replay).unwrap();
        crate::build::run(&project, &args).unwrap();
        project.check(&args).unwrap();
        assert_eq!(
            std::fs::read_to_string(output).unwrap(),
            "a value with spaces\n$(literal); --offline"
        );
        assert_eq!(std::fs::read(scratch.0.join("Cargo.lock")).unwrap(), before);
    }

    #[test]
    fn native_targets_are_explicit_and_mobile_is_not_misreported_as_desktop() {
        let host = "x86_64-pc-windows-msvc";
        assert_eq!(resolve_target(Platform::Desktop, None, host).unwrap(), host);
        assert_eq!(
            resolve_target(Platform::Web, None, host).unwrap(),
            "wasm32-unknown-unknown"
        );
        for target in [
            "aarch64-apple-darwin",
            "x86_64-unknown-linux-gnu",
            "aarch64-unknown-linux-musl",
            host,
        ] {
            assert_eq!(
                resolve_target(Platform::Desktop, Some(target), host).unwrap(),
                target
            );
            assert_eq!(
                resolve_target(Platform::Server, Some(target), host).unwrap(),
                target
            );
            assert!(resolve_target(Platform::Web, Some(target), host).is_err());
        }
        for target in [
            "aarch64-linux-android",
            "aarch64-apple-ios",
            "aarch64-apple-ios-sim",
            "wasm32-unknown-unknown",
            "../target.json",
            "--help",
            "",
            "x86_64\nlinux",
        ] {
            assert!(
                resolve_target(Platform::Desktop, Some(target), host).is_err(),
                "{target}"
            );
        }
    }

    #[test]
    fn cross_target_can_be_planned_but_cannot_run_on_the_host() {
        let scratch = crate::test_support::Scratch::new();
        let mut project = scratch.project(Platform::Desktop);
        let args = Args::parse(["print".into()]).unwrap();
        assert!(project.ensure_runnable().is_ok());
        project.build_target = "aarch64-apple-darwin".into();
        assert_eq!(
            project.plan(&args).unwrap()["target"],
            "aarch64-apple-darwin"
        );
        assert_eq!(
            project.plan(&args).unwrap()["rust_host"],
            "x86_64-pc-windows-msvc"
        );
        assert!(
            project
                .ensure_runnable()
                .unwrap_err()
                .contains("cannot run target")
        );
        // Rejection precedes Cargo or executable creation, even for a broken app.
        assert!(
            crate::build::run(&project, &args)
                .unwrap_err()
                .contains("cannot run target")
        );
    }
    #[test]
    fn accepts_project_output_and_rejects_relative_or_escaping_directories() {
        let scratch = crate::test_support::Scratch::new();
        assert!(validate_build_root(&scratch.0.join("target")).is_ok());
        for path in ["relative-output", "../other", "D:/BuildCache/app/../other"] {
            assert!(validate_build_root(Path::new(path)).is_err(), "{path}");
        }
    }

    #[test]
    fn normal_build_paths_do_not_override_the_caller_environment() {
        let scratch = crate::test_support::Scratch::new();
        scratch.write(
            "Cargo.toml",
            "[package]\nname=\"path-fixture\"\nversion=\"0.0.0\"\n[workspace]\n",
        );
        scratch.write("src/lib.rs", "");
        let paths = Paths::new(&scratch.0.join("Cargo.toml"), None).unwrap();
        let mut command = Command::new("cargo");
        paths.apply(&mut command);
        assert_eq!(command.get_envs().count(), 0);
        assert_eq!(paths.temp, std::env::temp_dir());
    }

    #[test]
    fn matching_semver_does_not_hide_a_different_git_revision() {
        assert!(verify_source(&json!({"source":"git+https://example.invalid/glory?rev=other#0000000000000000000000000000000000000000"})).is_err());
        let revision = env!("GLORY_CLI_SOURCE_REV");
        if !revision.is_empty() {
            assert!(
                verify_source(
                    &json!({"source":format!("git+https://example.invalid/glory#{revision}")})
                )
                .is_ok()
            );
        }
    }
    #[test]
    fn incompatible_framework_is_rejected_but_unrelated_workspace_versions_are_not_visited() {
        let mut metadata = json!({"packages": [{"id":"app","name":"app"}, {"id":"current","name":"glory","version":env!("CARGO_PKG_VERSION")}, {"id":"other","name":"glory","version":"0.1.0"}], "resolve":{"nodes":[{"id":"app","deps":[{"pkg":"current","dep_kinds":[{"kind":null}]}]}]}});
        assert!(compatible_dependencies(&metadata, "app").is_ok());
        metadata["resolve"]["nodes"][0]["deps"][0]["pkg"] = json!("other");
        assert!(
            compatible_dependencies(&metadata, "app")
                .unwrap_err()
                .contains("incompatible")
        );
    }
}

/// Keep project identities and artifact digests stable across SHA-2 API versions.
pub(crate) fn sha256(bytes: impl AsRef<[u8]>) -> String {
    Sha256::digest(bytes)
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

#[cfg(test)]
mod digest_tests {
    #[test]
    fn sha256_matches_the_standard_abc_vector() {
        assert_eq!(
            super::sha256(b"abc"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }
}