Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Launch Go apps with a single command package (R2.7) (#1092)

Afloat464935ef96d0
diff --git a/crates/engine/src/toolchains.rs b/crates/engine/src/toolchains.rs
index 59373465..169a324b 100644
--- a/crates/engine/src/toolchains.rs
+++ b/crates/engine/src/toolchains.rs
@@ -41,7 +41,7 @@ pub struct Toolchain {
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
pub struct LaunchRecipe {
pub file: String,
- /// `{file}` expands to the matched relative filename in a single argument, without a shell.
+ /// `{file}` is the matched relative filename. `{package}` is its parent with an explicit `./`.
pub command: Vec<String>,
}
@@ -64,28 +64,37 @@ pub fn found_in(dir: &Path) -> Option<&'static Toolchain> {
.or_else(|| catalogue().iter().find(|t| t.standalone_entrypoints && t.launch(dir).is_some()))
}
-/// Bounded root-file matching, also used for launch entrypoints. Exact paths need no directory scan.
+/// Match exact files, root suffixes, or one named file below each child of a fixed directory.
fn matching_files(dir: &Path, pattern: &str) -> Vec<PathBuf> {
- match pattern.strip_prefix('*') {
- Some(suffix) => {
- let mut files = Vec::new();
- let Ok(entries) = std::fs::read_dir(dir) else { return files };
- for (i, entry) in entries.enumerate() {
- // An incomplete scan cannot establish an unambiguous launch entrypoint.
- if i >= 256 {
- return Vec::new();
- }
- let Ok(entry) = entry else { return Vec::new() };
- let p = entry.path();
- if p.is_file() && p.file_name().is_some_and(|n| n.to_string_lossy().ends_with(suffix)) {
- files.push(p);
- }
- }
- files.sort();
- files
+ if let Some((folder, filename)) = pattern.split_once("/*/") {
+ return scan_entries(&dir.join(folder), |entry| {
+ let file = entry.path().join(filename);
+ Ok((entry.file_type()?.is_dir() && file.is_file()).then_some(file))
+ });
+ }
+ if let Some(suffix) = pattern.strip_prefix('*') {
+ return scan_entries(dir, |entry| {
+ let file = entry.path();
+ Ok((entry.file_name().to_string_lossy().ends_with(suffix) && file.is_file()).then_some(file))
+ });
+ }
+ let file = dir.join(pattern);
+ file.is_file().then_some(file).into_iter().collect()
+}
+
+fn scan_entries(dir: &Path, candidate: impl Fn(std::fs::DirEntry) -> std::io::Result<Option<PathBuf>>) -> Vec<PathBuf> {
+ let mut files = Vec::new();
+ let Ok(entries) = std::fs::read_dir(dir) else { return files };
+ for (i, entry) in entries.enumerate() {
+ // A partial scan cannot establish that the entrypoint is unique.
+ if i >= 256 {
+ return Vec::new();
}
- None => dir.join(pattern).is_file().then(|| dir.join(pattern)).into_iter().collect(),
+ let Ok(file) = entry.and_then(&candidate) else { return Vec::new() };
+ files.extend(file);
}
+ files.sort();
+ files
}
impl Toolchain {
@@ -112,8 +121,17 @@ impl Toolchain {
if files.len() != 1 {
continue;
}
- let file = files.first()?.strip_prefix(app).ok()?.to_str()?;
- let command: Vec<String> = recipe.command.iter().map(|arg| arg.replace("{file}", file)).collect();
+ let relative = files.first()?.strip_prefix(app).ok()?;
+ let file = relative.to_str()?;
+ let parent = relative.parent()?;
+ let command: Vec<String> = recipe
+ .command
+ .iter()
+ .map(|arg| match arg.as_str() {
+ "{package}" => format!("./{}", parent.display()),
+ _ => arg.replace("{file}", file),
+ })
+ .collect();
return self.command(app, &command);
}
None
@@ -170,6 +188,24 @@ mod tests {
assert!(launch(dir.path(), None).is_none(), "an incomplete scan cannot prove uniqueness");
}
+ #[test]
+ fn go_launch_uses_one_command_package_and_prefers_root() {
+ let dir = tempfile::tempdir().unwrap();
+ let app = dir.path();
+ std::fs::write(app.join("go.mod"), "module fixture").unwrap();
+ for name in ["viewer", "library"] {
+ std::fs::create_dir_all(app.join("cmd").join(name)).unwrap();
+ }
+ std::fs::write(app.join("cmd/viewer/main.go"), "package main").unwrap();
+ let launch = || crate::outputs::launch(app, None);
+ let package = format!("./{}", Path::new("cmd").join("viewer").display());
+ assert_eq!(launch(), Some(("go".into(), vec!["run".into(), package])));
+ std::fs::write(app.join("cmd/library/main.go"), "package main").unwrap();
+ assert!(launch().is_none());
+ std::fs::write(app.join("main.go"), "package main").unwrap();
+ assert_eq!(launch(), Some(("go".into(), vec!["run".into(), ".".into()])));
+ }
+
/// A helper script must not override a project's explicit Go, Rust or Node.js manifest.
#[test]
fn manifest_markers_take_precedence_over_standalone_scripts() {
diff --git a/crates/engine/src/toolchains.toml b/crates/engine/src/toolchains.toml
index cf5bef84..fe998a32 100644
--- a/crates/engine/src/toolchains.toml
+++ b/crates/engine/src/toolchains.toml
@@ -37,7 +37,10 @@ name = "Go"
found_by = ["go.mod"]
build = ["go", "build", "./..."]
test = ["go", "test", "./..."]
-launch = [{ file = "main.go", command = ["go", "run", "."] }]
+launch = [
+ { file = "main.go", command = ["go", "run", "."] },
+ { file = "cmd/*/main.go", command = ["go", "run", "{package}"] },
+]
[[toolchain]]
name = ".NET"
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index fd96f1ad..6244d7c6 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -874,8 +874,10 @@ Owner: open · Status: in progress
from the same process that supplied the picture, without falling back to unrelated names — PR #950
- [x] Shared toolchain commands make project-local executables absolute before changing the
working directory, preserving virtualenv paths for relative project placements — PR #950
-- [ ] Extend launch recipes beyond conventional root entrypoints: Python package scripts, Go
- `cmd/` layouts, and Java build outputs; build checks already use their toolchain commands
+- [x] Launch a Go project with one `cmd/<name>/main.go` as a package when the root has no
+ `main.go` — claimed: Afloat16, branch feature/r2.7-go-command-layouts
+- [ ] Extend launch recipes to Python package scripts and Java build outputs; build checks already
+ use their toolchain commands
- [ ] Audit relative project placements in build, option-run and Play paths too: runtime window
capture now normalizes its request paths, but earlier runner paths can still be relative
- [x] "player" alone doesn't make a request a game: a video or music player is an app (#953)
diff --git a/docs/STATUS.md b/docs/STATUS.md
index be5bbe28..b4c84bd7 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -12,7 +12,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| Disabled chat backends | Naming a backend that is off refuses chat and either side of compare with a settings error and guidance, before API or coding-agent setup | Isolated hub regressions for disabled API and agent backends, both compare positions, and enabled/automatic controls. Invalid tunnel settings detect API setup before the guard. No live provider or agent was used |
| Request-based project kinds | Low-level tools and media players keep the app target when “level” or “player” describes the tool. Explicit game requests and game engines still select the game target | Request-classification regression cases |
| Runner-owned app windows | Runtime capture tries the launched process and its descendants; the captured window owner's PID is also used for the UI tree. Unrelated processes with matching names are excluded. Process discovery has a deadline, output cap and candidate limit | Hermetic regressions cover runner/child/grandchild ownership, unrelated windows, direct launches, cycles, malformed rows, caps and errors. A macOS process snapshot finds an owned child without opening a window. Windows and real Go GUI capture have not been run |
-| New-project toolchains | New Python, Go, .NET, Maven, Gradle and Make projects use the same build catalogue as existing projects (`engine/src/toolchains.toml`). Shared launch recipes let screenshots, self-tests and Play start Python `main.py`, `app.py` or `__main__.py`, Go with a root `main.go`, and one root `.csproj`. Python uses a project-local virtual environment when present, resolves its executable to an absolute path even for relative project folders, and forces fresh syntax compilation; .NET passes app options after `--`. Manifest markers take priority over standalone Python files. Runtime window-capture requests normalize relative project and runner paths to absolute paths. Existing packaged programs, Rust, Electron and Godot keep launch priority. Multiple `.csproj` matches or a capped scan do not choose a project. Other layouts still need a packaged program or another launch recipe | Catalogue and launch regressions cover argv boundaries, ambiguous entrypoints, scan limits and Windows/local interpreter selection, including relative project folders and unchanged argument boundaries. Capture-request tests cover relative placements and PATH results, local interpreters and optional UI-tree output without opening a window. An owned interpreter stand-in runs the full new-project build/screenshot path, rejects failed builds, and verifies a failed screenshot cannot reuse an old PNG. An opt-in real Python 3.15.2 fixture on macOS passes build/screenshot checks, ignores invalid virtualenv code, and rejects a syntax error even when its mtime matches the cached version. Without `compileall -f` that same syntax-error probe incorrectly exits zero. Real Go/.NET/Maven/Gradle runs, Windows and GUI apps have not been verified for this change |
+| New-project toolchains | New Python, Go, .NET, Maven, Gradle and Make projects use the same build catalogue as existing projects (`engine/src/toolchains.toml`). Shared launch recipes let screenshots, self-tests and Play start Python `main.py`, `app.py` or `__main__.py`, Go with a root `main.go` or a single `cmd/<name>/main.go`, and one root `.csproj`. Python uses a project-local virtual environment when present, resolves its executable to an absolute path even for relative project folders, and forces fresh syntax compilation; .NET passes app options after `--`. Manifest markers take priority over standalone Python files. Runtime window-capture requests normalize relative project and runner paths to absolute paths. Existing packaged programs, Rust, Electron and Godot keep launch priority. Multiple `.csproj` matches or a capped scan do not choose a project. Other layouts still need a packaged program or another launch recipe | Catalogue and launch regressions cover argv boundaries, ambiguous entrypoints, scan limits and Windows/local interpreter selection, including relative project folders and unchanged argument boundaries. Capture-request tests cover relative placements and PATH results, local interpreters and optional UI-tree output without opening a window. An owned interpreter stand-in runs the full new-project build/screenshot path, rejects failed builds, and verifies a failed screenshot cannot reuse an old PNG. An opt-in real Python 3.15.2 fixture on macOS passes build/screenshot checks, ignores invalid virtualenv code, and rejects a syntax error even when its mtime matches the cached version. Without `compileall -f` that same syntax-error probe incorrectly exits zero. Real Go/.NET/Maven/Gradle runs, Windows and GUI apps have not been verified for this change |
| macOS optional UI tree and screenshots | `runtime_ui_read` with `accessibility: false` skips the tree and its permission check, returns empty nodes without truncation, and records the skipped read (#307). Walkthroughs still require Accessibility. With `screenshot: true`, macOS 14+ returns one owned-by-pid window as PNG/base64, restricted by `window_id` when supplied; without it, the first matching on-screen window. Images are limited to 2048 px per side and 6 MiB PNG. Combined JSON stays within the 16 MiB helper output cap; oversized trees retain a prefix with explicit truncation and partial coverage while preserving the image. Missing Screen Recording permission, a missing window or a capture failure is an explicit screenshot limitation with partial coverage (#248). Denied Accessibility permission returns a tool error before capture when the tree is enabled (the default); set `accessibility: false` to skip the tree. Permission dialogs are never opened | Synthetic Swift serializer regression covers combined tree/image overflow, escaped Unicode values, a single oversized node, an oversized image, and unchanged small/skipped trees. Engine regressions compile/run the real Swift helper: skipped trees at node limits 0/1, screenshot-off control, and impossible-window screenshot errors propagated to evidence. Live helper probe on macOS 27.2 captured only an owned AppKit fixture: valid 320 × 192 PNG (14,400 bytes), matching window id; screenshot-off returned no image/error. No granted-permission tree read, walkthrough, macOS 14 run or MCP transport run |
| DNS service records and address announcements | SRV, SOA and CAA answers expose their wire fields. Internet addresses have checked widths. Truncated replies retain their complete records, and unsolicited address announcements keep their owner. | Synthetic DNS and mDNS captures cover bounded fields, compressed names, empty UPDATE prerequisites and legacy replies. |
| DNS question boundaries | A question is retained only when its name, type and class are complete. A missing class byte marks the DNS message incomplete; preceding complete questions remain available, and incomplete questions do not enter the query inventory | Four packet regressions cover both truncation lengths, multiple questions, complete class values and the capture summary. No live capture was used |