Skip to main content

gadk_cli/
target.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The Cargo target a deploy builds and the builder image's Rust version.
17
18use std::collections::BTreeSet;
19use std::fs;
20use std::path::{Path, PathBuf};
21
22use gadk_platform::{go_path_clean, go_quote};
23use serde::Deserialize;
24
25use crate::Env;
26
27/// The version of the compiler that built gadk-cli (`build.rs`), the third candidate
28/// of the builder-image version chain; empty when `build.rs` could not read it.
29pub const COMPILED_RUSTC_VERSION: &str = env!("GADK_CLI_RUSTC_VERSION");
30
31/// The last-resort, rolling builder tag.
32pub const DEFAULT_BUILDER_RUST_VERSION: &str = "latest";
33
34/// The resolved Cargo target.
35#[derive(Debug, Clone, Default, PartialEq, Eq)]
36pub struct CargoTarget {
37    /// The package's name (`cargo build -p`).
38    pub package: String,
39    /// The binary target's name (`cargo build --bin`, the image's `/app/<bin>`).
40    pub bin: String,
41    /// `cargo metadata`'s `workspace_root`.
42    pub workspace_root: PathBuf,
43    /// The directory of the package's `Cargo.toml`.
44    pub manifest_dir: PathBuf,
45    /// The package's `rust_version` as `cargo metadata` reports it (workspace inheritance
46    /// resolved), the second step of the builder version chain.
47    pub rust_version: Option<String>,
48    /// The directory of every `path` dependency of every workspace member.
49    pub path_dependencies: Vec<PathBuf>,
50}
51
52/// The part of `cargo metadata --format-version 1 --no-deps` that target resolution reads.
53#[derive(Deserialize)]
54struct Metadata {
55    packages: Vec<MetadataPackage>,
56    workspace_root: PathBuf,
57}
58
59#[derive(Deserialize)]
60struct MetadataPackage {
61    name: String,
62    manifest_path: PathBuf,
63    #[serde(default)]
64    targets: Vec<MetadataTarget>,
65    #[serde(default)]
66    dependencies: Vec<MetadataDependency>,
67    #[serde(default)]
68    rust_version: Option<String>,
69}
70
71#[derive(Deserialize)]
72struct MetadataTarget {
73    name: String,
74    #[serde(default)]
75    kind: Vec<String>,
76}
77
78#[derive(Deserialize)]
79struct MetadataDependency {
80    #[serde(default)]
81    path: Option<PathBuf>,
82}
83
84/// A path quoted with double quotes.
85fn quote_path(p: &Path) -> String {
86    go_quote(&p.to_string_lossy())
87}
88
89/// Whether `a` and `b` name the same file: equal as given, else equal once both resolve.
90fn same_path(a: &Path, b: &Path) -> bool {
91    if a == b {
92        return true;
93    }
94    match (fs::canonicalize(a), fs::canonicalize(b)) {
95        (Ok(a), Ok(b)) => a == b,
96        _ => false,
97    }
98}
99
100/// Resolves `-e/--entry_point_path` (a package directory or its `Cargo.toml`, relative to
101/// `env.cwd`; empty means `env.cwd`) and `--bin` through
102/// `cargo metadata --format-version 1 --no-deps --manifest-path <dir>/Cargo.toml` on
103/// `env.runner`. Errors (gadk's texts): missing package, zero binaries, unknown `--bin`,
104/// several binaries without `--bin`, no `Cargo.lock` at the workspace root.
105// The deployed entry point is a Cargo binary target found through `cargo metadata`, with a
106// required `Cargo.lock`.
107pub async fn resolve(env: &Env, entry_point: &str, bin: &str) -> Result<CargoTarget, String> {
108    let path = env.abs(entry_point);
109    let manifest = if path.file_name().is_some_and(|n| n == "Cargo.toml") {
110        path
111    } else {
112        path.join("Cargo.toml")
113    };
114    let manifest_arg = manifest.to_string_lossy().into_owned();
115    let cmd = env
116        .command(
117            "cargo",
118            &[
119                "metadata",
120                "--format-version",
121                "1",
122                "--no-deps",
123                "--manifest-path",
124                &manifest_arg,
125            ],
126        )
127        .with_dir(env.cwd.to_string_lossy().into_owned());
128    let output = env
129        .runner
130        .output(&cmd)
131        .await
132        .map_err(|e| format!("cannot run cargo metadata: {e}"))?;
133    if !output.exit.success() {
134        let stderr = String::from_utf8_lossy(&output.stderr);
135        let stderr = stderr.trim();
136        let mut msg = format!(
137            "cargo metadata failed for {}: {}",
138            quote_path(&manifest),
139            output.exit.go_error()
140        );
141        if !stderr.is_empty() {
142            msg.push_str(": ");
143            msg.push_str(stderr);
144        }
145        return Err(msg);
146    }
147    let metadata: Metadata = serde_json::from_slice(&output.stdout)
148        .map_err(|e| format!("cannot parse cargo metadata output: {e}"))?;
149
150    let Some(package) = metadata
151        .packages
152        .iter()
153        .find(|p| same_path(&p.manifest_path, &manifest))
154    else {
155        return Err(format!(
156            "no package in {}: -e/--entry_point_path must name a Cargo package directory or its Cargo.toml",
157            quote_path(&manifest)
158        ));
159    };
160
161    let bins: Vec<&str> = package
162        .targets
163        .iter()
164        .filter(|t| t.kind.iter().any(|k| k == "bin"))
165        .map(|t| t.name.as_str())
166        .collect::<BTreeSet<_>>()
167        .into_iter()
168        .collect();
169    let chosen = match (bins.as_slice(), bin) {
170        ([], _) => {
171            return Err(format!(
172                "package {} has no binary target",
173                go_quote(&package.name)
174            ));
175        }
176        ([only], "") => (*only).to_string(),
177        (_, "") => {
178            return Err(format!(
179                "package {} has several binary targets ({}); select one with --bin",
180                go_quote(&package.name),
181                bins.join(", ")
182            ));
183        }
184        (_, wanted) if bins.contains(&wanted) => wanted.to_string(),
185        (_, wanted) => {
186            return Err(format!(
187                "package {} has no binary target {} (binaries: {})",
188                go_quote(&package.name),
189                go_quote(wanted),
190                bins.join(", ")
191            ));
192        }
193    };
194
195    if !metadata.workspace_root.join("Cargo.lock").is_file() {
196        return Err(format!(
197            "no Cargo.lock in the workspace root {}: run cargo generate-lockfile",
198            quote_path(&metadata.workspace_root)
199        ));
200    }
201
202    let path_dependencies: Vec<PathBuf> = metadata
203        .packages
204        .iter()
205        .flat_map(|p| p.dependencies.iter().filter_map(|d| d.path.clone()))
206        .collect::<BTreeSet<_>>()
207        .into_iter()
208        .collect();
209
210    Ok(CargoTarget {
211        package: package.name.clone(),
212        bin: chosen,
213        workspace_root: metadata.workspace_root.clone(),
214        manifest_dir: package
215            .manifest_path
216            .parent()
217            .map(Path::to_path_buf)
218            .unwrap_or_default(),
219        rust_version: package.rust_version.clone(),
220        path_dependencies,
221    })
222}
223
224/// Whether `path` is `root` or lies under it, compared lexically (both cleaned), else once
225/// both resolve.
226fn is_within(path: &Path, root: &Path) -> bool {
227    let clean = |p: &Path| PathBuf::from(go_path_clean(&p.to_string_lossy()));
228    if clean(path).starts_with(clean(root)) {
229        return true;
230    }
231    match (fs::canonicalize(path), fs::canonicalize(root)) {
232        (Ok(p), Ok(r)) => p.starts_with(r),
233        _ => false,
234    }
235}
236
237/// Rejects a `path` dependency of a workspace member outside `staged_root` (it would not
238/// be staged).
239// The check runs before the temp dir exists and rejects a build context that
240// `cargo build --locked` could not build.
241pub fn check_path_dependencies(target: &CargoTarget, staged_root: &Path) -> Result<(), String> {
242    match target
243        .path_dependencies
244        .iter()
245        .find(|dep| !is_within(dep, staged_root))
246    {
247        Some(dep) => Err(format!(
248            "path dependency {} is outside {} and would not be staged",
249            quote_path(dep),
250            quote_path(staged_root)
251        )),
252        None => Ok(()),
253    }
254}
255
256/// The `[toolchain] channel` of `rust-toolchain.toml` contents when it is a version number,
257/// else `""`. A minimal line reader (no TOML parser):
258/// section headers, `channel = "<v>"` or `'<v>'`, trailing `#` comments.
259pub fn channel_from_toolchain_file(data: &str) -> String {
260    let mut in_toolchain = false;
261    for line in data.lines() {
262        let line = line.trim();
263        if let Some(header) = line.strip_prefix('[') {
264            let header = header.split('#').next().unwrap_or_default().trim();
265            in_toolchain = header.strip_suffix(']').map(str::trim) == Some("toolchain");
266            continue;
267        }
268        if !in_toolchain {
269            continue;
270        }
271        let Some(rest) = line.strip_prefix("channel") else {
272            continue;
273        };
274        let Some(value) = rest.trim_start().strip_prefix('=') else {
275            continue;
276        };
277        let value = value.trim_start();
278        let Some(quote) = value.chars().next().filter(|c| *c == '"' || *c == '\'') else {
279            continue;
280        };
281        let inner = &value[1..];
282        let Some(end) = inner.find(quote) else {
283            continue;
284        };
285        let after = inner[end + 1..].trim_start();
286        if !after.is_empty() && !after.starts_with('#') {
287            continue;
288        }
289        let v = inner[..end].trim();
290        if is_rust_version(v) {
291            return v.to_string();
292        }
293    }
294    String::new()
295}
296
297/// `<workspace_root>/rust-toolchain.toml` `[toolchain] channel` → `target.rust_version` →
298/// `compiled` (callers pass [`COMPILED_RUSTC_VERSION`]) → [`DEFAULT_BUILDER_RUST_VERSION`];
299/// each candidate is used only when [`is_rust_version`].
300// `rust-version` is as cargo metadata resolves it. The legacy plain-text `rust-toolchain` file
301// is not read (rustup in the builder image still honours it).
302pub fn builder_rust_version(target: &CargoTarget, compiled: &str) -> String {
303    if let Ok(data) = fs::read_to_string(target.workspace_root.join("rust-toolchain.toml")) {
304        let v = channel_from_toolchain_file(&data);
305        if !v.is_empty() {
306            return v;
307        }
308    }
309    if let Some(v) = target.rust_version.as_deref().map(str::trim)
310        && is_rust_version(v)
311    {
312        return v.to_string();
313    }
314    if is_rust_version(compiled) {
315        return compiled.to_string();
316    }
317    DEFAULT_BUILDER_RUST_VERSION.to_string()
318}
319
320/// A Rust version number: `^[0-9]+(\.[0-9]+){0,2}$`.
321pub fn is_rust_version(s: &str) -> bool {
322    let parts: Vec<&str> = s.split('.').collect();
323    parts.len() <= 3
324        && parts
325            .iter()
326            .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
327}
328
329/// `rust:<version>-bookworm`, or `rust:bookworm` for `latest`.
330// The Debian 12 `rust:<ver>-bookworm` image matches the `distroless/cc-debian12` runtime.
331pub fn builder_image(version: &str) -> String {
332    if version == DEFAULT_BUILDER_RUST_VERSION {
333        "rust:bookworm".to_string()
334    } else {
335        format!("rust:{version}-bookworm")
336    }
337}
338
339#[cfg(test)]
340mod tests {
341    use std::fs;
342    use std::path::{Path, PathBuf};
343
344    use pretty_assertions::assert_eq;
345    use serde_json::{Value, json};
346
347    use super::*;
348    use crate::runner::Exit;
349    use crate::testutil::{Canned, RecordingRunner, TestEnv};
350
351    /// A trimmed copy of a real `cargo metadata --format-version 1 --no-deps` run on a
352    /// two-member workspace (`agent` with binaries `agent` and `tool`, path dependencies on
353    /// the member `lib` and on `outside` beyond the workspace; `rust-version.workspace = true`
354    /// with `[workspace.package] rust-version = "1.95"`). `{ROOT}` is the fixture's parent dir.
355    const TWO_MEMBER_METADATA: &str = r#"{
356  "packages": [
357    {
358      "name": "agent",
359      "version": "0.1.0",
360      "id": "path+file://{ROOT}/ws/agent#0.1.0",
361      "dependencies": [
362        {"name": "lib", "source": null, "req": "*", "kind": null, "path": "{ROOT}/ws/lib"},
363        {"name": "out", "source": null, "req": "*", "kind": null, "path": "{ROOT}/outside"}
364      ],
365      "targets": [
366        {"kind": ["bin"], "crate_types": ["bin"], "name": "agent", "src_path": "{ROOT}/ws/agent/src/main.rs"},
367        {"kind": ["bin"], "crate_types": ["bin"], "name": "tool", "src_path": "{ROOT}/ws/agent/src/bin/tool.rs"}
368      ],
369      "manifest_path": "{ROOT}/ws/agent/Cargo.toml",
370      "edition": "2024",
371      "rust_version": "1.95"
372    },
373    {
374      "name": "lib",
375      "version": "0.1.0",
376      "id": "path+file://{ROOT}/ws/lib#0.1.0",
377      "dependencies": [],
378      "targets": [
379        {"kind": ["lib"], "crate_types": ["lib"], "name": "lib", "src_path": "{ROOT}/ws/lib/src/lib.rs"}
380      ],
381      "manifest_path": "{ROOT}/ws/lib/Cargo.toml",
382      "edition": "2024",
383      "rust_version": null
384    }
385  ],
386  "workspace_members": ["path+file://{ROOT}/ws/agent#0.1.0", "path+file://{ROOT}/ws/lib#0.1.0"],
387  "resolve": null,
388  "target_directory": "{ROOT}/ws/target",
389  "version": 1,
390  "workspace_root": "{ROOT}/ws",
391  "metadata": null
392}"#;
393
394    /// A fixture dir: `ws/` (with `Cargo.lock` unless `lock` is false), `ws/agent`, `ws/lib`.
395    fn fixture(lock: bool) -> tempfile::TempDir {
396        let dir = tempfile::tempdir().unwrap();
397        let ws = dir.path().join("ws");
398        fs::create_dir_all(ws.join("agent/src")).unwrap();
399        fs::create_dir_all(ws.join("lib/src")).unwrap();
400        fs::write(ws.join("Cargo.toml"), "[workspace]\n").unwrap();
401        if lock {
402            fs::write(ws.join("Cargo.lock"), "version = 4\n").unwrap();
403        }
404        dir
405    }
406
407    fn two_member_metadata(root: &Path) -> String {
408        TWO_MEMBER_METADATA.replace("{ROOT}", &root.to_string_lossy())
409    }
410
411    /// Metadata for one package `name` at `<root>/ws/<dir>` with the given targets
412    /// (`(kind, name)`), workspace root `<root>/ws`.
413    fn one_package_metadata(
414        root: &Path,
415        dir: &str,
416        name: &str,
417        targets: &[(&str, &str)],
418    ) -> String {
419        let ws = root.join("ws");
420        let targets: Vec<Value> = targets
421            .iter()
422            .map(|(kind, name)| json!({"kind": [kind], "crate_types": [kind], "name": name}))
423            .collect();
424        json!({
425            "packages": [{
426                "name": name,
427                "dependencies": [],
428                "targets": targets,
429                "manifest_path": ws.join(dir).join("Cargo.toml"),
430                "rust_version": null,
431            }],
432            "workspace_root": ws,
433            "version": 1,
434        })
435        .to_string()
436    }
437
438    /// A [`TestEnv`] in `cwd` whose runner answers every command with `stdout`.
439    fn env_answering(cwd: &Path, stdout: String) -> TestEnv {
440        TestEnv::builder(cwd)
441            .runner(RecordingRunner::with_responder(move |_| {
442                Canned::success(stdout.clone())
443            }))
444            .build()
445    }
446
447    fn metadata_args(manifest: &Path) -> Vec<String> {
448        [
449            "cargo",
450            "metadata",
451            "--format-version",
452            "1",
453            "--no-deps",
454            "--manifest-path",
455        ]
456        .iter()
457        .map(|s| s.to_string())
458        .chain([manifest.to_string_lossy().into_owned()])
459        .collect()
460    }
461
462    #[tokio::test]
463    async fn resolve_package_dir_with_one_binary() {
464        let dir = fixture(true);
465        let ws = dir.path().join("ws");
466        let t = env_answering(
467            &ws,
468            one_package_metadata(
469                dir.path(),
470                "agent",
471                "agent",
472                &[("lib", "agent"), ("bin", "agent")],
473            ),
474        );
475
476        let got = resolve(&t.env, "agent", "").await.unwrap();
477
478        assert_eq!(
479            got,
480            CargoTarget {
481                package: "agent".into(),
482                bin: "agent".into(),
483                workspace_root: ws.clone(),
484                manifest_dir: ws.join("agent"),
485                rust_version: None,
486                path_dependencies: vec![],
487            }
488        );
489        let calls = t.runner.calls();
490        assert_eq!(calls.len(), 1);
491        assert_eq!(calls[0].args, metadata_args(&ws.join("agent/Cargo.toml")));
492        assert_eq!(calls[0].dir, ws.to_string_lossy());
493    }
494
495    #[tokio::test]
496    async fn resolve_accepts_the_cargo_toml_path() {
497        let dir = fixture(true);
498        let ws = dir.path().join("ws");
499        let t = env_answering(
500            &ws,
501            one_package_metadata(dir.path(), "agent", "agent", &[("bin", "agent")]),
502        );
503
504        let got = resolve(&t.env, "./agent/Cargo.toml", "").await.unwrap();
505
506        assert_eq!(got.package, "agent");
507        assert_eq!(got.manifest_dir, ws.join("agent"));
508        assert_eq!(
509            t.runner.calls()[0].args,
510            metadata_args(&ws.join("agent/Cargo.toml"))
511        );
512    }
513
514    #[tokio::test]
515    async fn resolve_omitted_entry_point_is_the_working_directory() {
516        let dir = fixture(true);
517        let ws = dir.path().join("ws");
518        let t = env_answering(
519            &ws.join("agent"),
520            one_package_metadata(dir.path(), "agent", "agent", &[("bin", "agent")]),
521        );
522
523        let got = resolve(&t.env, "", "").await.unwrap();
524
525        assert_eq!(got.bin, "agent");
526        assert_eq!(
527            t.runner.calls()[0].args,
528            metadata_args(&ws.join("agent/Cargo.toml"))
529        );
530    }
531
532    #[tokio::test]
533    async fn resolve_member_crate_with_bin_flag() {
534        let dir = fixture(true);
535        let ws = dir.path().join("ws");
536        let t = env_answering(&ws, two_member_metadata(dir.path()));
537
538        let got = resolve(&t.env, "agent", "tool").await.unwrap();
539
540        assert_eq!(
541            got,
542            CargoTarget {
543                package: "agent".into(),
544                bin: "tool".into(),
545                workspace_root: ws.clone(),
546                manifest_dir: ws.join("agent"),
547                rust_version: Some("1.95".into()),
548                path_dependencies: vec![dir.path().join("outside"), ws.join("lib")],
549            }
550        );
551    }
552
553    #[tokio::test]
554    async fn resolve_several_binaries_without_bin_is_an_error() {
555        let dir = fixture(true);
556        let ws = dir.path().join("ws");
557        let t = env_answering(&ws, two_member_metadata(dir.path()));
558
559        let err = resolve(&t.env, "agent", "").await.unwrap_err();
560
561        assert_eq!(
562            err,
563            r#"package "agent" has several binary targets (agent, tool); select one with --bin"#
564        );
565    }
566
567    #[tokio::test]
568    async fn resolve_unknown_bin_is_an_error() {
569        let dir = fixture(true);
570        let ws = dir.path().join("ws");
571        let t = env_answering(&ws, two_member_metadata(dir.path()));
572
573        let err = resolve(&t.env, "agent", "nope").await.unwrap_err();
574
575        assert_eq!(
576            err,
577            r#"package "agent" has no binary target "nope" (binaries: agent, tool)"#
578        );
579    }
580
581    #[tokio::test]
582    async fn resolve_unknown_bin_is_an_error_with_one_binary() {
583        let dir = fixture(true);
584        let ws = dir.path().join("ws");
585        let t = env_answering(
586            &ws,
587            one_package_metadata(dir.path(), "agent", "agent", &[("bin", "agent")]),
588        );
589
590        let err = resolve(&t.env, "agent", "other").await.unwrap_err();
591
592        assert_eq!(
593            err,
594            r#"package "agent" has no binary target "other" (binaries: agent)"#
595        );
596    }
597
598    #[tokio::test]
599    async fn resolve_package_without_binary_is_an_error() {
600        let dir = fixture(true);
601        let ws = dir.path().join("ws");
602        let t = env_answering(&ws, two_member_metadata(dir.path()));
603
604        let err = resolve(&t.env, "lib", "").await.unwrap_err();
605
606        assert_eq!(err, r#"package "lib" has no binary target"#);
607    }
608
609    #[tokio::test]
610    async fn resolve_missing_package_is_an_error() {
611        let dir = fixture(true);
612        let ws = dir.path().join("ws");
613        let t = env_answering(&ws, two_member_metadata(dir.path()));
614
615        // The virtual workspace manifest is no package.
616        let err = resolve(&t.env, ".", "").await.unwrap_err();
617
618        assert_eq!(
619            err,
620            format!(
621                "no package in {}: -e/--entry_point_path must name a Cargo package directory or its Cargo.toml",
622                go_quote(&ws.join("Cargo.toml").to_string_lossy())
623            )
624        );
625    }
626
627    #[tokio::test]
628    async fn resolve_without_cargo_lock_is_an_error() {
629        let dir = fixture(false);
630        let ws = dir.path().join("ws");
631        let t = env_answering(&ws, two_member_metadata(dir.path()));
632
633        let err = resolve(&t.env, "agent", "tool").await.unwrap_err();
634
635        assert_eq!(
636            err,
637            format!(
638                "no Cargo.lock in the workspace root {}: run cargo generate-lockfile",
639                go_quote(&ws.to_string_lossy())
640            )
641        );
642    }
643
644    #[tokio::test]
645    async fn resolve_reports_a_failing_cargo_metadata() {
646        let dir = fixture(true);
647        let ws = dir.path().join("ws");
648        let t = TestEnv::builder(&ws)
649            .runner(RecordingRunner::with_responder(|_| Canned {
650                stdout: Vec::new(),
651                stderr: b"error: manifest path `x` does not exist\n".to_vec(),
652                result: Ok(Exit::Code(101)),
653            }))
654            .build();
655
656        let err = resolve(&t.env, "missing", "").await.unwrap_err();
657
658        assert_eq!(
659            err,
660            format!(
661                "cargo metadata failed for {}: exit status 101: error: manifest path `x` does not exist",
662                go_quote(&ws.join("missing/Cargo.toml").to_string_lossy())
663            )
664        );
665    }
666
667    #[tokio::test]
668    async fn resolve_reports_a_cargo_that_does_not_start() {
669        let dir = fixture(true);
670        let ws = dir.path().join("ws");
671        let t = TestEnv::builder(&ws)
672            .runner(RecordingRunner::with_responder(|_| {
673                Canned::start_error(r#"exec: "cargo": executable file not found in $PATH"#)
674            }))
675            .build();
676
677        let err = resolve(&t.env, "agent", "").await.unwrap_err();
678
679        assert_eq!(
680            err,
681            r#"cannot run cargo metadata: exec: "cargo": executable file not found in $PATH"#
682        );
683    }
684
685    #[tokio::test]
686    async fn resolve_reports_unparsable_metadata() {
687        let dir = fixture(true);
688        let ws = dir.path().join("ws");
689        let t = env_answering(&ws, "not json".into());
690
691        let err = resolve(&t.env, "agent", "").await.unwrap_err();
692
693        assert!(
694            err.starts_with("cannot parse cargo metadata output: "),
695            "{err}"
696        );
697    }
698
699    #[test]
700    fn check_path_dependencies_accepts_deps_inside_the_staged_root() {
701        let target = CargoTarget {
702            path_dependencies: vec![PathBuf::from("/src/ws/lib"), PathBuf::from("/src/vendor/x")],
703            ..CargoTarget::default()
704        };
705
706        assert_eq!(check_path_dependencies(&target, Path::new("/src")), Ok(()));
707        assert_eq!(check_path_dependencies(&target, Path::new("/src/")), Ok(()));
708    }
709
710    #[test]
711    fn check_path_dependencies_rejects_a_dep_outside_the_staged_root() {
712        let target = CargoTarget {
713            path_dependencies: vec![PathBuf::from("/src/outside"), PathBuf::from("/src/ws/lib")],
714            ..CargoTarget::default()
715        };
716
717        assert_eq!(
718            check_path_dependencies(&target, Path::new("/src/ws")),
719            Err(
720                r#"path dependency "/src/outside" is outside "/src/ws" and would not be staged"#
721                    .to_string()
722            )
723        );
724        // A sibling whose name merely starts with the root's is outside too.
725        let sibling = CargoTarget {
726            path_dependencies: vec![PathBuf::from("/src/ws-extra")],
727            ..CargoTarget::default()
728        };
729        assert!(check_path_dependencies(&sibling, Path::new("/src/ws")).is_err());
730    }
731
732    // Adapted from Go TestGoVersionFromModFile's cases (agentengine_test.go): the version
733    // directive, a trailing comment, absent and malformed values.
734    #[test]
735    fn channel_from_toolchain_file_cases() {
736        let cases = [
737            ("pinned", "[toolchain]\nchannel = \"1.99.1\"\n", "1.99.1"),
738            ("single quotes", "[toolchain]\nchannel = '1.95'\n", "1.95"),
739            ("major only", "[toolchain]\nchannel=\"1\"\n", "1"),
740            (
741                "trailing comment",
742                "[toolchain]\nchannel = \"1.99.1\" # pinned\ncomponents = [\"clippy\"]\n",
743                "1.99.1",
744            ),
745            (
746                "after other keys",
747                "# top\n[toolchain]\nprofile = \"minimal\"\nchannel = \"1.90.0\"\n",
748                "1.90.0",
749            ),
750            ("named channel", "[toolchain]\nchannel = \"stable\"\n", ""),
751            (
752                "dated nightly",
753                "[toolchain]\nchannel = \"nightly-2026-01-01\"\n",
754                "",
755            ),
756            ("other section", "[other]\nchannel = \"1.99.1\"\n", ""),
757            ("no channel", "[toolchain]\nprofile = \"minimal\"\n", ""),
758            ("four parts", "[toolchain]\nchannel = \"1.2.3.4\"\n", ""),
759            ("unterminated", "[toolchain]\nchannel = \"1.99.1\n", ""),
760            ("empty", "", ""),
761        ];
762        for (name, data, want) in cases {
763            assert_eq!(channel_from_toolchain_file(data), want, "{name}");
764        }
765    }
766
767    #[test]
768    fn is_rust_version_cases() {
769        for v in ["1", "1.95", "1.99.1", "10.200.3000"] {
770            assert!(is_rust_version(v), "{v}");
771        }
772        for v in [
773            "",
774            "latest",
775            "stable",
776            "1.",
777            ".1",
778            "1..2",
779            "1.2.3.4",
780            "1.99.1-nightly",
781            " 1.95",
782            "v1",
783        ] {
784            assert!(!is_rust_version(v), "{v:?}");
785        }
786    }
787
788    #[test]
789    fn builder_image_tags() {
790        assert_eq!(builder_image("1.99.1"), "rust:1.99.1-bookworm");
791        assert_eq!(builder_image("1.95"), "rust:1.95-bookworm");
792        assert_eq!(builder_image("latest"), "rust:bookworm");
793    }
794
795    #[test]
796    fn default_builder_rust_version_is_not_pinned() {
797        assert!(!is_rust_version(DEFAULT_BUILDER_RUST_VERSION));
798        assert_eq!(builder_image(DEFAULT_BUILDER_RUST_VERSION), "rust:bookworm");
799    }
800
801    fn target_in(root: &Path, rust_version: Option<&str>) -> CargoTarget {
802        CargoTarget {
803            workspace_root: root.to_path_buf(),
804            rust_version: rust_version.map(str::to_string),
805            ..CargoTarget::default()
806        }
807    }
808
809    #[test]
810    fn builder_rust_version_prefers_the_toolchain_file() {
811        let dir = tempfile::tempdir().unwrap();
812        fs::write(
813            dir.path().join("rust-toolchain.toml"),
814            "[toolchain]\nchannel = \"1.99.1\"\n",
815        )
816        .unwrap();
817
818        let got = builder_rust_version(&target_in(dir.path(), Some("1.95")), "1.98.0");
819
820        assert_eq!(got, "1.99.1");
821    }
822
823    #[test]
824    fn builder_rust_version_falls_back_to_rust_version() {
825        let dir = tempfile::tempdir().unwrap();
826        fs::write(
827            dir.path().join("rust-toolchain.toml"),
828            "[toolchain]\nchannel = \"stable\"\n",
829        )
830        .unwrap();
831
832        let got = builder_rust_version(&target_in(dir.path(), Some("1.95")), "1.98.0");
833
834        assert_eq!(got, "1.95");
835    }
836
837    #[test]
838    fn builder_rust_version_falls_back_to_the_compiled_rustc() {
839        let dir = tempfile::tempdir().unwrap();
840
841        assert_eq!(
842            builder_rust_version(&target_in(dir.path(), None), "1.98.0"),
843            "1.98.0"
844        );
845        assert_eq!(
846            builder_rust_version(&target_in(dir.path(), Some("1.95-beta")), "1.98.0"),
847            "1.98.0"
848        );
849    }
850
851    #[test]
852    fn builder_rust_version_last_resort_is_latest() {
853        let dir = tempfile::tempdir().unwrap();
854
855        assert_eq!(
856            builder_rust_version(&target_in(dir.path(), None), ""),
857            "latest"
858        );
859        assert_eq!(
860            builder_rust_version(&target_in(dir.path(), None), "1.100.0-nightly"),
861            "latest"
862        );
863    }
864}