Skip to content
This repository was archived by the owner on Nov 3, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
description = "Rust plugin for meta CLI to run cargo commands across Rust projects"
description = "Rust plugin for meta CLI to run any cargo command across Rust repos"

[[bin]]
name = "meta-rust"
Expand All @@ -16,10 +16,8 @@ path = "src/lib.rs"

[dependencies]
meta_plugin_protocol = { path = "../meta_plugin_protocol" }
meta_core = { path = "../meta_core" }
anyhow = "1"
shlex = "1"
colored = "2"
serde_json = "1"
indexmap = "2"

[dev-dependencies]
Expand Down
287 changes: 117 additions & 170 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,222 +1,169 @@
//! meta-rust library
//!
//! Provides Rust/Cargo commands for meta repositories.
//! Runs any cargo command across the Rust repos of a meta workspace.

pub use meta_plugin_protocol::{
output_execution_plan, CommandResult, ExecutionPlan, PlanResponse, PlannedCommand,
};
pub use meta_plugin_protocol::{CommandResult, PlannedCommand, PluginRequestOptions};
use std::path::Path;

/// Get all project directories from .meta config (including root ".")
/// If provided_projects is not empty, uses that list instead (for --recursive support)
fn get_project_directories(
provided_projects: &[String],
cwd: &Path,
) -> anyhow::Result<Vec<String>> {
// If we have provided projects from meta_cli (e.g., when --recursive is used), use them
if !provided_projects.is_empty() {
// Include root "." plus all provided project paths
let mut dirs = vec![".".to_string()];
for p in provided_projects {
dirs.push(p.clone());
}
return Ok(dirs);
}

// Use canonical config parsing (supports JSON + YAML)
let tree = match meta_core::config::walk_meta_tree(cwd, Some(0)) {
Ok(t) => t,
Err(_) => return Ok(vec![".".to_string()]),
};
let mut dirs = vec![".".to_string()];
let mut paths: Vec<String> = tree.iter().map(|n| n.info.path.clone()).collect();
paths.sort();
dirs.extend(paths);
Ok(dirs)
}

/// Filter directories to only those with Cargo.toml
fn filter_rust_projects(dirs: &[String], cwd: &Path) -> Vec<String> {
dirs.iter()
.filter(|dir| {
let cargo_path = if *dir == "." {
cwd.join("Cargo.toml")
} else {
cwd.join(dir).join("Cargo.toml")
};
cargo_path.exists()
})
.cloned()
.collect()
}

/// Execute a Rust/Cargo command and return the result
/// Plan `cargo <args>` in every selected repo that has a `Cargo.toml`.
///
/// If `provided_projects` is not empty, it will be used instead of reading from .meta file.
/// This allows meta_cli to pass in the full project list when --recursive is used.
/// `projects` is the repo list from meta_cli (it includes the meta root);
/// when it is empty the plan runs in `cwd` only. A Cargo workspace that spans
/// repos runs in each of them; plain `cargo` in its root runs it once.
pub fn execute_command(
command: &str,
args: &[String],
parallel: bool,
provided_projects: &[String],
options: &PluginRequestOptions,
projects: &[String],
cwd: &Path,
) -> CommandResult {
// Intercept --help/-h before dispatching to subcommand handlers
if command
.split_whitespace()
.chain(args.iter().map(String::as_str))
.any(|a| a == "--help" || a == "-h")
{
// `meta cargo` and any `--help`/`-h` show this plugin's help instead of
// running cargo once per repo. meta_cli sends help requests without the
// repo list, so cargo's own help could not reach each repo anyway.
if args.is_empty() || args.iter().any(|a| a == "--help" || a == "-h") {
return CommandResult::ShowHelp(None);
}

// Get all project directories
let dirs = match get_project_directories(provided_projects, cwd) {
Ok(d) => d,
Err(e) => return CommandResult::Error(format!("Failed to get project directories: {e}")),
let cmd = match command_line(args) {
Ok(cmd) => cmd,
Err(e) => return CommandResult::Error(format!("Cannot quote cargo arguments: {e}")),
};

// Filter to Rust projects only
let rust_dirs = filter_rust_projects(&dirs, cwd);
let dirs: Vec<String> = if projects.is_empty() {
vec![".".to_string()]
} else {
projects.to_vec()
};
// Notes name repos by their path from the meta root, which meta_cli lists first.
let root = cwd.join(dirs.first().map_or(".", String::as_str));
let (rust_dirs, other_dirs): (Vec<String>, Vec<String>) = filter_dirs(dirs, options)
.into_iter()
.partition(|dir| cwd.join(dir).join("Cargo.toml").is_file());

if !options.silent && !other_dirs.is_empty() {
let names: Vec<String> = other_dirs.iter().map(|dir| display(dir, &root)).collect();
eprintln!("meta-rust: skipping {} (no Cargo.toml)", names.join(", "));
}

if rust_dirs.is_empty() {
return CommandResult::Message("No Rust projects found (no Cargo.toml files)".to_string());
}

// Build the cargo command
let cargo_cmd = match command {
"cargo build" | "rust build" => {
let mut cmd = "cargo build".to_string();
for arg in args {
cmd.push(' ');
cmd.push_str(arg);
}
cmd
}
"cargo test" | "rust test" => {
let mut cmd = "cargo test".to_string();
for arg in args {
cmd.push(' ');
cmd.push_str(arg);
}
cmd
}
_ => return CommandResult::ShowHelp(Some(format!("unrecognized command '{command}'"))),
};

// Build execution plan
let commands: Vec<PlannedCommand> = rust_dirs
.iter()
let commands = rust_dirs
.into_iter()
.map(|dir| PlannedCommand {
dir: dir.clone(),
cmd: cargo_cmd.clone(),
dir,
cmd: cmd.clone(),
env: None,
})
.collect();
CommandResult::Plan(commands, Some(options.parallel))
}

CommandResult::Plan(commands, Some(parallel))
/// `cargo <args>` quoted for the `$SHELL -c` that loop_lib runs plans with.
#[cfg(not(windows))]
fn command_line(args: &[String]) -> Result<String, String> {
shlex::try_join(std::iter::once("cargo").chain(args.iter().map(String::as_str)))
.map_err(|e| e.to_string())
}

/// Get help text for the plugin
pub fn get_help_text() -> &'static str {
r#"meta rust - Rust/Cargo Plugin
/// loop_lib runs plans with `cmd.exe /c`, which has no POSIX quoting, so the
/// args are joined as given.
#[cfg(windows)]
fn command_line(args: &[String]) -> Result<String, String> {
Ok(format!("cargo {}", args.join(" ")))
}

Commands:
meta cargo build Run cargo build across all Rust projects
meta cargo test Run cargo test across all Rust projects
/// Keep the dirs loop_lib will run in (its substring match), so the skip note
/// names only selected repos.
fn filter_dirs(mut dirs: Vec<String>, options: &PluginRequestOptions) -> Vec<String> {
if let Some(includes) = options.include_filters.as_ref().filter(|f| !f.is_empty()) {
dirs.retain(|dir| includes.iter().any(|f| dir.contains(f.as_str())));
}
if let Some(excludes) = &options.exclude_filters {
dirs.retain(|dir| {
!excludes
.iter()
.any(|f| dir.contains(f.trim_end_matches('/')))
});
}
dirs
}

This plugin detects Rust projects (by presence of Cargo.toml) and runs
the specified cargo command. Non-Rust directories are skipped.
"#
fn display(dir: &str, root: &Path) -> String {
match root.join(dir).strip_prefix(root) {
Ok(rel) if rel.as_os_str().is_empty() => ".".to_string(),
Ok(rel) => rel.display().to_string(),
Err(_) => dir.to_string(),
}
}

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

#[test]
fn test_unknown_command() {
let result = execute_command("cargo unknown", &[], false, &[], Path::new("."));
match result {
CommandResult::ShowHelp(Some(msg)) => assert!(msg.contains("unrecognized command")),
_ => panic!("Expected ShowHelp result"),
}
fn write(dir: &Path, file: &str, contents: &str) {
let path = dir.join(file);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, contents).unwrap();
}

#[test]
fn test_get_help_text() {
let help = get_help_text();
assert!(help.contains("cargo build"));
assert!(help.contains("cargo test"));
fn plan(args: &[&str], projects: &[&Path], options: &PluginRequestOptions) -> Vec<String> {
let args: Vec<String> = args.iter().map(|a| a.to_string()).collect();
let projects: Vec<String> = projects.iter().map(|p| p.display().to_string()).collect();
match execute_command(&args, options, &projects, Path::new(".")) {
CommandResult::Plan(commands, _) => commands
.into_iter()
.map(|c| format!("{}: {}", c.dir, c.cmd))
.collect(),
_ => panic!("Expected Plan result"),
}
}

#[test]
fn test_no_rust_projects() {
let temp_dir = TempDir::new().unwrap();

// Create .meta with no Rust projects
std::fs::write(temp_dir.path().join(".meta"), r#"{"projects": {}}"#).unwrap();
fn any_cargo_command_runs_in_rust_repos_only() {
let temp = TempDir::new().unwrap();
let (root, rust, docs) = (
temp.path(),
temp.path().join("rust"),
temp.path().join("docs"),
);
write(&rust, "Cargo.toml", "[package]\nname = \"rust\"\n");
write(&docs, "README.md", "");

let result = execute_command("cargo build", &[], false, &[], temp_dir.path());
let args = ["fmt", "--check", "--", "--config", "a b"];
let commands = plan(&args, &[root, &rust, &docs], &Default::default());

match result {
CommandResult::Message(msg) => assert!(msg.contains("No Rust projects")),
_ => panic!("Expected Message result"),
}
let quoted = if cfg!(windows) { "a b" } else { "'a b'" };
let expected = format!("{}: cargo fmt --check -- --config {quoted}", rust.display());
assert_eq!(commands, [expected]);
}

#[test]
fn test_cargo_build_returns_plan() {
let temp_dir = TempDir::new().unwrap();

// Create a Cargo.toml in root
std::fs::write(
temp_dir.path().join("Cargo.toml"),
"[package]\nname = \"test\"\n",
)
.unwrap();
std::fs::write(temp_dir.path().join(".meta"), r#"{"projects": {}}"#).unwrap();

let result = execute_command(
"cargo build",
&["--release".to_string()],
true,
&[],
temp_dir.path(),
);
fn workspace_members_run_in_their_own_repos_within_filters() {
let temp = TempDir::new().unwrap();
let (root, member) = (temp.path(), temp.path().join("member"));
write(root, "Cargo.toml", "[workspace]\nmembers = [\"member\"]\n");
write(&member, "Cargo.toml", "[package]\nname = \"member\"\n");

let all = plan(&["run"], &[root, &member], &Default::default());
let only_member = PluginRequestOptions {
include_filters: Some(vec!["member".to_string()]),
..Default::default()
};
let filtered = plan(&["run"], &[root, &member], &only_member);

match result {
CommandResult::Plan(commands, parallel) => {
assert_eq!(commands.len(), 1);
assert_eq!(commands[0].dir, ".");
assert!(commands[0].cmd.contains("cargo build"));
assert!(commands[0].cmd.contains("--release"));
assert_eq!(parallel, Some(true));
}
_ => panic!("Expected Plan result"),
}
let run_in = |dir: &Path| format!("{}: cargo run", dir.display());
assert_eq!(all, [run_in(root), run_in(&member)]);
assert_eq!(filtered, [run_in(&member)]);
}

#[test]
fn test_execution_plan_serialization() {
let commands = vec![PlannedCommand {
dir: ".".to_string(),
cmd: "cargo test".to_string(),
env: None,
}];
let plan = ExecutionPlan {
pre_commands: vec![],
commands,
post_commands: vec![],
parallel: Some(true),
max_parallel: None,
spawn_stagger_ms: None,
};
let response = PlanResponse { plan };
let json = serde_json::to_string(&response).unwrap();
assert!(json.contains("\"plan\""));
assert!(json.contains("\"commands\""));
assert!(json.contains("cargo test"));
fn bare_or_help_shows_plugin_help() {
for args in [&[][..], &["test", "--", "--help"][..]] {
let args: Vec<String> = args.iter().map(|a| a.to_string()).collect();
let result = execute_command(&args, &Default::default(), &[], Path::new("."));
assert!(matches!(result, CommandResult::ShowHelp(None)));
}
}
}
Loading
Loading