mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
feat(cli-rs): add the command tree
All 48 commands of the TypeScript CLI with clap derive, proven against the dumped Spec tree. A pre-pass and a post-parse check keep the Effect CLI behaviors scripts see: --no-<flag>, boolean literals, repeated flags, k=v values, -w without a following value, the scope of --standalone and --server, and root flags before a subcommand. Help, version, completions for six shells, exit code 1 on usage errors, and stdout that ignores EPIPE. Handlers are stubs that name their step; the root command reports that the TUI is not built yet.
This commit is contained in:
parent
ad5c8910e0
commit
01ab034b56
37 changed files with 2441 additions and 14 deletions
176
packages/cli-rs/Cargo.lock
generated
176
packages/cli-rs/Cargo.lock
generated
|
|
@ -11,6 +11,62 @@ dependencies = [
|
|||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"anstyle-parse",
|
||||
"anstyle-query",
|
||||
"anstyle-wincon",
|
||||
"colorchoice",
|
||||
"is_terminal_polyfill",
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle"
|
||||
version = "1.0.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-parse"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
|
||||
dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-query"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-wincon"
|
||||
version = "3.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"once_cell_polyfill",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "atomic-waker"
|
||||
version = "1.1.2"
|
||||
|
|
@ -108,6 +164,56 @@ dependencies = [
|
|||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
"clap_lex",
|
||||
"strsim",
|
||||
"terminal_size",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_complete"
|
||||
version = "4.6.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f"
|
||||
dependencies = [
|
||||
"clap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
|
||||
|
||||
[[package]]
|
||||
name = "cmake"
|
||||
version = "0.1.58"
|
||||
|
|
@ -117,6 +223,12 @@ dependencies = [
|
|||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||
|
||||
[[package]]
|
||||
name = "combine"
|
||||
version = "4.6.9"
|
||||
|
|
@ -362,6 +474,12 @@ version = "0.17.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
|
|
@ -590,6 +708,12 @@ version = "2.12.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
|
|
@ -672,6 +796,12 @@ version = "0.2.191"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||
|
||||
[[package]]
|
||||
name = "litemap"
|
||||
version = "0.8.3"
|
||||
|
|
@ -713,6 +843,12 @@ version = "1.21.4"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "opencode-acp"
|
||||
version = "0.1.0"
|
||||
|
|
@ -744,6 +880,9 @@ dependencies = [
|
|||
name = "opencode-cli"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
"clap_complete",
|
||||
"opencode-acp",
|
||||
"opencode-api",
|
||||
"opencode-drive",
|
||||
|
|
@ -753,6 +892,8 @@ dependencies = [
|
|||
"opencode-store",
|
||||
"opencode-tui",
|
||||
"opencode-ui",
|
||||
"serde_json",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -1101,6 +1242,19 @@ dependencies = [
|
|||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.46"
|
||||
|
|
@ -1351,6 +1505,12 @@ version = "0.1.9"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520"
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
|
|
@ -1399,6 +1559,16 @@ dependencies = [
|
|||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "terminal_size"
|
||||
version = "0.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874"
|
||||
dependencies = [
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.21"
|
||||
|
|
@ -1698,6 +1868,12 @@ dependencies = [
|
|||
"utf_types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "utf_types"
|
||||
version = "1.0.0"
|
||||
|
|
|
|||
|
|
@ -14,6 +14,10 @@ path = "src/main.rs"
|
|||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
clap = { workspace = true, features = ["string"] }
|
||||
clap_complete.workspace = true
|
||||
url.workspace = true
|
||||
opencode-acp.workspace = true
|
||||
opencode-api.workspace = true
|
||||
opencode-drive.workspace = true
|
||||
|
|
@ -23,3 +27,6 @@ opencode-service.workspace = true
|
|||
opencode-store.workspace = true
|
||||
opencode-tui.workspace = true
|
||||
opencode-ui.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json.workspace = true
|
||||
|
|
|
|||
1107
packages/cli-rs/crates/cli/src/args.rs
Normal file
1107
packages/cli-rs/crates/cli/src/args.rs
Normal file
File diff suppressed because it is too large
Load diff
1
packages/cli-rs/crates/cli/src/askpass.rs
Normal file
1
packages/cli-rs/crates/cli/src/askpass.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! SSH askpass helper mode. Step C.14.
|
||||
8
packages/cli-rs/crates/cli/src/commands/acp.rs
Normal file
8
packages/cli-rs/crates/cli/src/commands/acp.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
//! `acp`: the Agent Client Protocol server.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::AcpArgs;
|
||||
|
||||
pub fn run(_context: &Context, _args: &AcpArgs) -> anyhow::Result<()> {
|
||||
not_built("acp", "C.11")
|
||||
}
|
||||
8
packages/cli-rs/crates/cli/src/commands/api.rs
Normal file
8
packages/cli-rs/crates/cli/src/commands/api.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
//! `api`: a request to the running server.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::ApiArgs;
|
||||
|
||||
pub fn run(_context: &Context, _args: &ApiArgs) -> anyhow::Result<()> {
|
||||
not_built("api", "C.4")
|
||||
}
|
||||
16
packages/cli-rs/crates/cli/src/commands/auth.rs
Normal file
16
packages/cli-rs/crates/cli/src/commands/auth.rs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
//! `auth`: integrations and credentials.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::{AuthArgs, AuthCommand};
|
||||
|
||||
pub fn run(_context: &Context, args: &AuthArgs) -> anyhow::Result<()> {
|
||||
match &args.command {
|
||||
None => crate::help::print(&["auth"]),
|
||||
Some(AuthCommand::List(_)) => not_built("auth list", "C.5"),
|
||||
Some(AuthCommand::Login(_)) => not_built("auth login", "C.5"),
|
||||
Some(AuthCommand::Logout(_)) => not_built("auth logout", "C.5"),
|
||||
Some(AuthCommand::Export(_)) => not_built("auth export", "C.5"),
|
||||
Some(AuthCommand::Import(_)) => not_built("auth import", "C.5"),
|
||||
Some(AuthCommand::Switch(_)) => not_built("auth switch", "C.5"),
|
||||
}
|
||||
}
|
||||
14
packages/cli-rs/crates/cli/src/commands/debug.rs
Normal file
14
packages/cli-rs/crates/cli/src/commands/debug.rs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
//! `debug`: debugging and troubleshooting tools.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::{DebugArgs, DebugCommand};
|
||||
|
||||
pub fn run(_context: &Context, args: &DebugArgs) -> anyhow::Result<()> {
|
||||
match &args.command {
|
||||
None => crate::help::print(&["debug"]),
|
||||
Some(DebugCommand::Agents(_)) => not_built("debug agents", "C.1"),
|
||||
Some(DebugCommand::Config(_)) => not_built("debug config", "C.1"),
|
||||
Some(DebugCommand::HeapDump(_)) => not_built("debug heap-dump", "C.1"),
|
||||
Some(DebugCommand::Paths(_)) => not_built("debug paths", "C.1"),
|
||||
}
|
||||
}
|
||||
8
packages/cli-rs/crates/cli/src/commands/default.rs
Normal file
8
packages/cli-rs/crates/cli/src/commands/default.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
//! The root command, which opens the TUI. T.1 takes this file over, then C.13.
|
||||
|
||||
use super::Context;
|
||||
use crate::args::RootArgs;
|
||||
|
||||
pub fn run(_context: &Context, _args: &RootArgs) -> anyhow::Result<()> {
|
||||
anyhow::bail!("the TUI is not built yet (plan step T.1)")
|
||||
}
|
||||
14
packages/cli-rs/crates/cli/src/commands/mcp.rs
Normal file
14
packages/cli-rs/crates/cli/src/commands/mcp.rs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
//! `mcp`: MCP servers.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::{McpArgs, McpCommand};
|
||||
|
||||
pub fn run(_context: &Context, args: &McpArgs) -> anyhow::Result<()> {
|
||||
match &args.command {
|
||||
None => crate::help::print(&["mcp"]),
|
||||
Some(McpCommand::List(_)) => not_built("mcp list", "C.6"),
|
||||
Some(McpCommand::Add(_)) => not_built("mcp add", "C.6"),
|
||||
Some(McpCommand::Auth(_)) => not_built("mcp auth", "C.6"),
|
||||
Some(McpCommand::Logout(_)) => not_built("mcp logout", "C.6"),
|
||||
}
|
||||
}
|
||||
8
packages/cli-rs/crates/cli/src/commands/mini.rs
Normal file
8
packages/cli-rs/crates/cli/src/commands/mini.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
//! `mini`: the minimal interactive interface.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::MiniArgs;
|
||||
|
||||
pub fn run(_context: &Context, _args: &MiniArgs) -> anyhow::Result<()> {
|
||||
not_built("mini", "M.1")
|
||||
}
|
||||
64
packages/cli-rs/crates/cli/src/commands/mod.rs
Normal file
64
packages/cli-rs/crates/cli/src/commands/mod.rs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
//! One module per top-level command. Each step fills its own module (plan 8.4); a stub reports that its command
|
||||
//! is not built yet.
|
||||
|
||||
pub mod acp;
|
||||
pub mod api;
|
||||
pub mod auth;
|
||||
pub mod debug;
|
||||
pub mod default;
|
||||
pub mod mcp;
|
||||
pub mod mini;
|
||||
pub mod models;
|
||||
pub mod pair;
|
||||
pub mod plugin;
|
||||
pub mod reload;
|
||||
pub mod run;
|
||||
pub mod serve;
|
||||
pub mod service;
|
||||
pub mod session;
|
||||
pub mod stats;
|
||||
pub mod uninstall;
|
||||
pub mod upgrade;
|
||||
|
||||
use crate::args::{Cli, Command, GlobalArgs, ServerFlags};
|
||||
|
||||
/// What every handler gets besides its own arguments.
|
||||
#[allow(dead_code, reason = "read by the handlers of later steps")]
|
||||
pub struct Context {
|
||||
pub global: GlobalArgs,
|
||||
/// `--standalone` and `--server` for the selected command, wherever they were given (`args::validate`).
|
||||
pub server: ServerFlags,
|
||||
}
|
||||
|
||||
pub fn run(context: &Context, cli: &Cli) -> anyhow::Result<()> {
|
||||
let Some(command) = &cli.command else {
|
||||
return default::run(context, &cli.root);
|
||||
};
|
||||
match command {
|
||||
Command::Upgrade(args) => upgrade::run(context, args),
|
||||
Command::Uninstall(args) => uninstall::run(context, args),
|
||||
Command::Acp(args) => acp::run(context, args),
|
||||
Command::Api(args) => api::run(context, args),
|
||||
Command::Debug(args) => debug::run(context, args),
|
||||
Command::Auth(args) => auth::run(context, args),
|
||||
Command::Mcp(args) => mcp::run(context, args),
|
||||
Command::Plugin(args) => plugin::run(context, args),
|
||||
Command::Models(_) => models::run(context),
|
||||
Command::Stats(args) => stats::run(context, args),
|
||||
Command::Mini(args) => mini::run(context, args),
|
||||
Command::Run(args) => run::run(context, args),
|
||||
Command::Session(args) => session::run(context, args),
|
||||
Command::Service(args) => service::run(context, args),
|
||||
Command::Reload(_) => reload::run(context),
|
||||
Command::Pair(args) => pair::run(context, args),
|
||||
Command::Serve(args) => serve::run(context, args),
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of a command whose step has not landed yet.
|
||||
pub fn not_built(command: &str, step: &str) -> anyhow::Result<()> {
|
||||
anyhow::bail!(
|
||||
"`{} {command}` is not built yet (plan step {step})",
|
||||
crate::help::name()
|
||||
)
|
||||
}
|
||||
7
packages/cli-rs/crates/cli/src/commands/models.rs
Normal file
7
packages/cli-rs/crates/cli/src/commands/models.rs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
//! `models`: list the available models.
|
||||
|
||||
use super::{Context, not_built};
|
||||
|
||||
pub fn run(_context: &Context) -> anyhow::Result<()> {
|
||||
not_built("models", "C.1")
|
||||
}
|
||||
8
packages/cli-rs/crates/cli/src/commands/pair.rs
Normal file
8
packages/cli-rs/crates/cli/src/commands/pair.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
//! `pair`: one-time links for a browser or app.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::PairArgs;
|
||||
|
||||
pub fn run(_context: &Context, _args: &PairArgs) -> anyhow::Result<()> {
|
||||
not_built("pair", "C.9")
|
||||
}
|
||||
15
packages/cli-rs/crates/cli/src/commands/plugin.rs
Normal file
15
packages/cli-rs/crates/cli/src/commands/plugin.rs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
//! `plugin`, delegated to the TypeScript CLI.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::{PluginArgs, PluginCommand};
|
||||
|
||||
pub fn run(_context: &Context, args: &PluginArgs) -> anyhow::Result<()> {
|
||||
match &args.command {
|
||||
None => crate::help::print(&["plugin"]),
|
||||
Some(PluginCommand::List(_)) => not_built("plugin list", "D.1"),
|
||||
Some(PluginCommand::Add(_)) => not_built("plugin add", "D.1"),
|
||||
Some(PluginCommand::Check(_)) => not_built("plugin check", "D.1"),
|
||||
Some(PluginCommand::Update(_)) => not_built("plugin update", "D.1"),
|
||||
Some(PluginCommand::Remove(_)) => not_built("plugin remove", "D.1"),
|
||||
}
|
||||
}
|
||||
7
packages/cli-rs/crates/cli/src/commands/reload.rs
Normal file
7
packages/cli-rs/crates/cli/src/commands/reload.rs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
//! `reload`: reload the server configuration.
|
||||
|
||||
use super::{Context, not_built};
|
||||
|
||||
pub fn run(_context: &Context) -> anyhow::Result<()> {
|
||||
not_built("reload", "C.1")
|
||||
}
|
||||
8
packages/cli-rs/crates/cli/src/commands/run.rs
Normal file
8
packages/cli-rs/crates/cli/src/commands/run.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
//! `run`: send a message and print the reply.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::RunArgs;
|
||||
|
||||
pub fn run(_context: &Context, _args: &RunArgs) -> anyhow::Result<()> {
|
||||
not_built("run", "C.10")
|
||||
}
|
||||
8
packages/cli-rs/crates/cli/src/commands/serve.rs
Normal file
8
packages/cli-rs/crates/cli/src/commands/serve.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
//! `serve`, delegated to the TypeScript CLI.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::ServeArgs;
|
||||
|
||||
pub fn run(_context: &Context, _args: &ServeArgs) -> anyhow::Result<()> {
|
||||
not_built("serve", "D.1")
|
||||
}
|
||||
17
packages/cli-rs/crates/cli/src/commands/service.rs
Normal file
17
packages/cli-rs/crates/cli/src/commands/service.rs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
//! `service`: the background server.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::{ServiceArgs, ServiceCommand};
|
||||
|
||||
pub fn run(_context: &Context, args: &ServiceArgs) -> anyhow::Result<()> {
|
||||
match &args.command {
|
||||
None => crate::help::print(&["service"]),
|
||||
Some(ServiceCommand::Start) => not_built("service start", "C.8"),
|
||||
Some(ServiceCommand::Restart) => not_built("service restart", "C.8"),
|
||||
Some(ServiceCommand::Status) => not_built("service status", "C.8"),
|
||||
Some(ServiceCommand::Stop) => not_built("service stop", "C.8"),
|
||||
Some(ServiceCommand::Get(_)) => not_built("service get", "C.8"),
|
||||
Some(ServiceCommand::Set(_)) => not_built("service set", "C.8"),
|
||||
Some(ServiceCommand::Unset(_)) => not_built("service unset", "C.8"),
|
||||
}
|
||||
}
|
||||
14
packages/cli-rs/crates/cli/src/commands/session.rs
Normal file
14
packages/cli-rs/crates/cli/src/commands/session.rs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
//! `session`: list, delete, export, and import sessions.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::{SessionArgs, SessionCommand};
|
||||
|
||||
pub fn run(_context: &Context, args: &SessionArgs) -> anyhow::Result<()> {
|
||||
match &args.command {
|
||||
None => crate::help::print(&["session"]),
|
||||
Some(SessionCommand::List(_)) => not_built("session list", "C.2"),
|
||||
Some(SessionCommand::Delete(_)) => not_built("session delete", "C.2"),
|
||||
Some(SessionCommand::Export(_)) => not_built("session export", "C.2"),
|
||||
Some(SessionCommand::Import(_)) => not_built("session import", "C.2"),
|
||||
}
|
||||
}
|
||||
8
packages/cli-rs/crates/cli/src/commands/stats.rs
Normal file
8
packages/cli-rs/crates/cli/src/commands/stats.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
//! `stats`: usage statistics.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::StatsArgs;
|
||||
|
||||
pub fn run(_context: &Context, _args: &StatsArgs) -> anyhow::Result<()> {
|
||||
not_built("stats", "C.3")
|
||||
}
|
||||
8
packages/cli-rs/crates/cli/src/commands/uninstall.rs
Normal file
8
packages/cli-rs/crates/cli/src/commands/uninstall.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
//! `uninstall`, delegated to the TypeScript CLI.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::UninstallArgs;
|
||||
|
||||
pub fn run(_context: &Context, _args: &UninstallArgs) -> anyhow::Result<()> {
|
||||
not_built("uninstall", "D.1")
|
||||
}
|
||||
8
packages/cli-rs/crates/cli/src/commands/upgrade.rs
Normal file
8
packages/cli-rs/crates/cli/src/commands/upgrade.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
//! `upgrade` (alias `update`), delegated to the TypeScript CLI.
|
||||
|
||||
use super::{Context, not_built};
|
||||
use crate::args::UpgradeArgs;
|
||||
|
||||
pub fn run(_context: &Context, _args: &UpgradeArgs) -> anyhow::Result<()> {
|
||||
not_built("upgrade", "D.1")
|
||||
}
|
||||
1
packages/cli-rs/crates/cli/src/env.rs
Normal file
1
packages/cli-rs/crates/cli/src/env.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! Process environment: NO_PROXY and OPENCODE_CLIENT. Step C.14.
|
||||
92
packages/cli-rs/crates/cli/src/help.rs
Normal file
92
packages/cli-rs/crates/cli/src/help.rs
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
//! The clap command built from `args::Cli`, and the output of the built-in flags: help, version, completions.
|
||||
|
||||
use std::io::IsTerminal;
|
||||
|
||||
use clap::CommandFactory;
|
||||
|
||||
use crate::args::{Cli, Shell};
|
||||
use crate::output;
|
||||
|
||||
// Like the TypeScript CLI, a build without OPENCODE_VERSION reports "local".
|
||||
pub const VERSION: &str = match option_env!("OPENCODE_VERSION") {
|
||||
Some(version) => version,
|
||||
None => "local",
|
||||
};
|
||||
|
||||
/// The program name in help, version, and completions (plan 6.1).
|
||||
pub fn name() -> String {
|
||||
std::env::var("OPENCODE_CLI_NAME")
|
||||
.ok()
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "opencode-rs".into())
|
||||
}
|
||||
|
||||
/// The unbuilt tree: each command holds only the arguments it declares.
|
||||
pub fn tree() -> clap::Command {
|
||||
let name = name();
|
||||
configure(Cli::command()).name(name.clone()).bin_name(name)
|
||||
}
|
||||
|
||||
/// The tree with global flags propagated to every command, as parsing sees it.
|
||||
pub fn command() -> clap::Command {
|
||||
let mut command = tree();
|
||||
command.build();
|
||||
headings(command)
|
||||
}
|
||||
|
||||
// Like Effect CLI's help, a command's own flags come first and the global flags after them, each under a
|
||||
// heading. Propagated globals keep the root's display order, which would mix them into the command's own.
|
||||
fn headings(command: clap::Command) -> clap::Command {
|
||||
command
|
||||
.mut_args(|arg| match (arg.is_global_set(), arg.is_positional()) {
|
||||
(true, _) => {
|
||||
let order = arg.get_display_order();
|
||||
arg.help_heading("Global flags").display_order(1000 + order)
|
||||
}
|
||||
(false, true) => arg,
|
||||
(false, false) => arg.help_heading("Flags"),
|
||||
})
|
||||
.mut_subcommands(headings)
|
||||
}
|
||||
|
||||
// Effect CLI has no `help` subcommand, describes `--help` itself (args::GlobalArgs), and reads `-1` as a value.
|
||||
fn configure(command: clap::Command) -> clap::Command {
|
||||
command
|
||||
.disable_help_flag(true)
|
||||
.disable_version_flag(true)
|
||||
.disable_help_subcommand(true)
|
||||
.allow_negative_numbers(true)
|
||||
.mut_subcommands(configure)
|
||||
}
|
||||
|
||||
/// Prints the help of the command at `path` (names below the root) to stdout.
|
||||
pub fn print(path: &[&str]) -> anyhow::Result<()> {
|
||||
let mut command = command();
|
||||
let node = path.iter().fold(&mut command, |node, name| {
|
||||
node.find_subcommand_mut(name)
|
||||
.expect("help path names a command")
|
||||
});
|
||||
let help = node.render_help();
|
||||
match std::io::stdout().is_terminal() {
|
||||
true => output::print(&help.ansi().to_string()),
|
||||
false => output::print(&help.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn version() -> anyhow::Result<()> {
|
||||
output::print(&format!("{} v{VERSION}\n", name()))
|
||||
}
|
||||
|
||||
/// `sh` means bash and `pwsh` PowerShell, as in Effect CLI (GlobalFlag.ts:226-227).
|
||||
pub fn completions(shell: Shell) -> anyhow::Result<()> {
|
||||
let shell = match shell {
|
||||
Shell::Bash | Shell::Sh => clap_complete::Shell::Bash,
|
||||
Shell::Zsh => clap_complete::Shell::Zsh,
|
||||
Shell::Fish => clap_complete::Shell::Fish,
|
||||
Shell::Powershell | Shell::Pwsh => clap_complete::Shell::PowerShell,
|
||||
};
|
||||
let mut command = command();
|
||||
let mut script = Vec::new();
|
||||
clap_complete::generate(shell, &mut command, name(), &mut script);
|
||||
output::print(&String::from_utf8_lossy(&script))
|
||||
}
|
||||
|
|
@ -1,17 +1,82 @@
|
|||
//! The opencode-rs binary. C.0 replaces this with the command tree.
|
||||
//! The opencode-rs binary.
|
||||
|
||||
// Like the TypeScript CLI, a build without OPENCODE_VERSION reports "local".
|
||||
const VERSION: &str = match option_env!("OPENCODE_VERSION") {
|
||||
Some(version) => version,
|
||||
None => "local",
|
||||
};
|
||||
mod args;
|
||||
mod askpass;
|
||||
mod commands;
|
||||
mod env;
|
||||
mod help;
|
||||
mod output;
|
||||
mod prompt;
|
||||
mod signals;
|
||||
mod telemetry;
|
||||
mod update;
|
||||
mod wizard;
|
||||
|
||||
fn main() {
|
||||
match std::env::args().nth(1).as_deref() {
|
||||
Some("--version") => println!("{VERSION}"),
|
||||
_ => {
|
||||
eprintln!("usage: opencode-rs --version");
|
||||
std::process::exit(1);
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::FromArgMatches;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let command = help::command();
|
||||
let argv = match args::normalize(&command, std::env::args_os().collect()) {
|
||||
Ok(argv) => argv,
|
||||
Err(message) => return usage_error(&message),
|
||||
};
|
||||
let matches = match command.clone().try_get_matches_from(argv) {
|
||||
Ok(matches) => matches,
|
||||
Err(error) => {
|
||||
// Effect CLI exits 1 on a usage error; clap would exit 2. Help output (`--help`) exits 0.
|
||||
let _ = error.print();
|
||||
return ExitCode::from(u8::from(error.use_stderr()));
|
||||
}
|
||||
};
|
||||
let cli = match args::Cli::from_arg_matches(&matches) {
|
||||
Ok(cli) => cli,
|
||||
Err(error) => return usage_error(&error.to_string()),
|
||||
};
|
||||
let server = match args::validate(&command, &matches) {
|
||||
Ok(server) => server,
|
||||
Err(message) => return usage_error(&message),
|
||||
};
|
||||
let result = match &cli.global {
|
||||
// Effect CLI runs the first action flag given, in this order, instead of the command.
|
||||
global if global.version => help::version(),
|
||||
global if global.wizard => wizard::run(),
|
||||
args::GlobalArgs {
|
||||
completions: Some(shell),
|
||||
..
|
||||
} => help::completions(*shell),
|
||||
global => {
|
||||
if global.print_logs {
|
||||
set_print_logs();
|
||||
}
|
||||
commands::run(
|
||||
&commands::Context {
|
||||
global: global.clone(),
|
||||
server,
|
||||
},
|
||||
&cli,
|
||||
)
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(error) => ExitCode::from(output::fail(error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn usage_error(message: &str) -> ExitCode {
|
||||
eprintln!("error: {message}\n\nFor more information, try '--help'.");
|
||||
ExitCode::from(1)
|
||||
}
|
||||
|
||||
// The TypeScript CLI sets OPENCODE_PRINT_LOGS for its logger and for the servers it starts
|
||||
// (framework/runtime.ts:98).
|
||||
#[allow(unsafe_code)]
|
||||
fn set_print_logs() {
|
||||
// SAFETY: no other thread runs yet; handlers start their runtimes after this.
|
||||
unsafe { std::env::set_var("OPENCODE_PRINT_LOGS", "1") };
|
||||
}
|
||||
|
|
|
|||
38
packages/cli-rs/crates/cli/src/output.rs
Normal file
38
packages/cli-rs/crates/cli/src/output.rs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
//! Writing to stdout, and how errors end the process.
|
||||
|
||||
use std::io::{ErrorKind, Write};
|
||||
|
||||
/// Writes `text` to stdout. A closed pipe (`opencode-rs ... | head`) is not an error, as in
|
||||
/// `packages/cli/src/node/index.ts:4-7`; `print!` would panic instead.
|
||||
pub fn print(text: &str) -> anyhow::Result<()> {
|
||||
let mut stdout = std::io::stdout().lock();
|
||||
match stdout
|
||||
.write_all(text.as_bytes())
|
||||
.and_then(|()| stdout.flush())
|
||||
{
|
||||
Err(error) if error.kind() != ErrorKind::BrokenPipe => Err(error.into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// An error that ends the process with `code` after the handler has reported what happened itself.
|
||||
#[derive(Debug)]
|
||||
pub struct Exit(pub u8);
|
||||
|
||||
impl std::fmt::Display for Exit {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(formatter, "exit {}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Exit {}
|
||||
|
||||
/// The exit code for a failed handler: `Exit` keeps its code and prints nothing; any other error prints to
|
||||
/// stderr and exits 1.
|
||||
pub fn fail(error: anyhow::Error) -> u8 {
|
||||
if let Some(exit) = error.downcast_ref::<Exit>() {
|
||||
return exit.0;
|
||||
}
|
||||
eprintln!("Error: {error:#}");
|
||||
1
|
||||
}
|
||||
1
packages/cli-rs/crates/cli/src/prompt/mod.rs
Normal file
1
packages/cli-rs/crates/cli/src/prompt/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! Interactive prompts like @clack/prompts. Step C.p.
|
||||
1
packages/cli-rs/crates/cli/src/signals.rs
Normal file
1
packages/cli-rs/crates/cli/src/signals.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! Shutdown deadline and SIGHUP. Step C.14.
|
||||
1
packages/cli-rs/crates/cli/src/telemetry.rs
Normal file
1
packages/cli-rs/crates/cli/src/telemetry.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! OpenTelemetry export and log files. Step C.14.
|
||||
2
packages/cli-rs/crates/cli/src/tests/mod.rs
Normal file
2
packages/cli-rs/crates/cli/src/tests/mod.rs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
mod parse;
|
||||
mod tree;
|
||||
356
packages/cli-rs/crates/cli/src/tests/parse.rs
Normal file
356
packages/cli-rs/crates/cli/src/tests/parse.rs
Normal file
|
|
@ -0,0 +1,356 @@
|
|||
//! The Effect CLI parsing behaviors scripts can see (docs/C.0.md), one test each.
|
||||
|
||||
use clap::FromArgMatches;
|
||||
|
||||
use crate::args::{self, Cli, Command, McpCommand, ServerFlags, SessionCommand};
|
||||
use crate::help;
|
||||
|
||||
fn parse(line: &[&str]) -> Result<(Cli, ServerFlags), String> {
|
||||
let command = help::command();
|
||||
let argv = std::iter::once("opencode-rs")
|
||||
.chain(line.iter().copied())
|
||||
.map(Into::into)
|
||||
.collect();
|
||||
let argv = args::normalize(&command, argv)?;
|
||||
let matches = command
|
||||
.clone()
|
||||
.try_get_matches_from(argv)
|
||||
.map_err(|error| error.to_string())?;
|
||||
let cli = Cli::from_arg_matches(&matches).map_err(|error| error.to_string())?;
|
||||
let server = args::validate(&command, &matches)?;
|
||||
Ok((cli, server))
|
||||
}
|
||||
|
||||
fn error(line: &[&str]) -> String {
|
||||
match parse(line) {
|
||||
Ok(_) => panic!("{line:?} parsed"),
|
||||
Err(error) => error,
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! command {
|
||||
($line:expr, $pattern:pat => $value:expr) => {
|
||||
match parse($line).unwrap().0.command {
|
||||
Some($pattern) => $value,
|
||||
other => panic!("{:?} parsed as {other:?}", $line),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negation_sets_a_boolean_to_false() {
|
||||
assert_eq!(
|
||||
command!(&["mini", "--no-replay"], Command::Mini(args) => args.replay()),
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(
|
||||
command!(&["mini", "--replay"], Command::Mini(args) => args.replay()),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
command!(&["mini"], Command::Mini(args) => args.replay()),
|
||||
None
|
||||
);
|
||||
assert!(!command!(&["run", "--no-thinking", "hi"], Command::Run(args) => args.thinking));
|
||||
assert!(!parse(&["--no-print-logs"]).unwrap().0.global.print_logs);
|
||||
assert!(
|
||||
error(&["mini", "--no-replay=true"])
|
||||
.contains("omit the value and use --no-replay by itself")
|
||||
);
|
||||
assert!(error(&["mini", "--no-replay", "true"]).contains("omit the value"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boolean_takes_a_literal() {
|
||||
let run =
|
||||
|line: &[&str]| command!(line, Command::Run(args) => (args.permissions.auto, args.message));
|
||||
assert_eq!(
|
||||
run(&["run", "--auto", "false", "hi"]),
|
||||
(false, vec!["hi".to_string()])
|
||||
);
|
||||
assert_eq!(run(&["run", "--auto", "yes"]), (true, vec![]));
|
||||
assert_eq!(run(&["run", "--auto=0"]), (false, vec![]));
|
||||
assert_eq!(
|
||||
run(&["run", "--auto", "hello"]),
|
||||
(true, vec!["hello".to_string()])
|
||||
);
|
||||
assert_eq!(
|
||||
command!(&["mini", "--replay=off"], Command::Mini(args) => args.replay()),
|
||||
Some(false)
|
||||
);
|
||||
assert!(!command!(&["uninstall", "-f", "n"], Command::Uninstall(args) => args.force));
|
||||
assert!(error(&["run", "--auto=maybe"]).contains("Expected: boolean"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flag_given_twice_is_an_error() {
|
||||
assert!(error(&["uninstall", "--dry-run", "--dry-run"]).contains("2 occurrences"));
|
||||
assert!(error(&["mini", "--replay", "--no-replay"]).contains("2 occurrences"));
|
||||
assert!(error(&["run", "-c", "--continue"]).contains("2 occurrences"));
|
||||
assert!(error(&["run", "-s", "a", "-s", "b"]).contains("cannot be used multiple times"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeatable_flags_collect_in_order_up_to_their_bound() {
|
||||
let files =
|
||||
command!(&["run", "-f", "a", "--file", "b", "-f=c", "hi"], Command::Run(args) => args.file);
|
||||
assert_eq!(files, ["a", "b", "c"]);
|
||||
let headers =
|
||||
command!(&["api", "op", "-H", "a:1", "-H", "b:2"], Command::Api(args) => args.header);
|
||||
assert_eq!(headers, ["a:1", "b:2"]);
|
||||
let mut line = vec!["api", "op"];
|
||||
line.extend(std::iter::repeat_n(["-H", "x:1"], 101).flatten());
|
||||
assert!(error(&line).contains("at most 100 values"));
|
||||
let cors =
|
||||
command!(&["serve", "--cors", "a", "--cors", "b"], Command::Serve(args) => args.cors);
|
||||
assert_eq!(cors, ["a", "b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn key_value_flags_need_a_key_and_a_value() {
|
||||
let params = command!(&["api", "op", "--param", "a=1", "--param", "b==2"], Command::Api(args) => args.param);
|
||||
assert_eq!(
|
||||
params,
|
||||
[("a".into(), "1".into()), ("b".into(), "=2".into())]
|
||||
);
|
||||
let env = command!(&["mcp", "add", "x", "--env", "K=V"], Command::Mcp(args) => match args.command {
|
||||
Some(McpCommand::Add(add)) => add.env,
|
||||
other => panic!("{other:?}"),
|
||||
});
|
||||
assert_eq!(env, [("K".into(), "V".into())]);
|
||||
assert!(error(&["api", "op", "--param", "novalue"]).contains("Expected format: key=value"));
|
||||
assert!(error(&["api", "op", "--param", "=1"]).contains("must be non-empty"));
|
||||
assert!(error(&["mcp", "add", "x", "--header", "k="]).contains("must be non-empty"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktree_takes_a_value_only_with_equals() {
|
||||
let run = |line: &[&str]| command!(line, Command::Run(args) => (args.worktree().map(|name| name.map(String::from)), args.message));
|
||||
assert_eq!(
|
||||
run(&["run", "-w", "fix", "it"]),
|
||||
(Some(None), vec!["fix".into(), "it".into()])
|
||||
);
|
||||
assert_eq!(
|
||||
run(&["run", "--worktree", "fix"]),
|
||||
(Some(None), vec!["fix".into()])
|
||||
);
|
||||
assert_eq!(
|
||||
run(&["run", "-w=feature", "go"]),
|
||||
(Some(Some("feature".into())), vec!["go".into()])
|
||||
);
|
||||
assert_eq!(
|
||||
run(&["run", "--worktree=feature"]),
|
||||
(Some(Some("feature".into())), vec![])
|
||||
);
|
||||
assert_eq!(run(&["run", "--worktree="]), (Some(None), vec![]));
|
||||
assert_eq!(run(&["run", "go"]), (None, vec!["go".into()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn words_after_double_dash_are_arguments() {
|
||||
let run = command!(&["run", "a", "--", "--model", "x", "-c"], Command::Run(args) => args);
|
||||
assert_eq!(run.message, ["a", "--model", "x", "-c"]);
|
||||
assert!(run.model.is_none() && !run.continue_);
|
||||
let add = command!(&["mcp", "add", "fs", "--", "npx", "-y", "pkg"], Command::Mcp(args) => match args.command {
|
||||
Some(McpCommand::Add(add)) => add,
|
||||
other => panic!("{other:?}"),
|
||||
});
|
||||
assert_eq!(
|
||||
(add.name.as_str(), add.command),
|
||||
("fs", vec!["npx".into(), "-y".into(), "pkg".into()])
|
||||
);
|
||||
assert_eq!(
|
||||
parse(&["--", "run"]).unwrap().0.root.directory.as_deref(),
|
||||
Some("run")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_flags_parse_but_stay_out_of_help() {
|
||||
assert!(command!(&["run", "--yolo"], Command::Run(args) => args.permissions.auto()));
|
||||
assert!(
|
||||
command!(&["run", "--dangerously-skip-permissions"], Command::Run(args) => args.permissions.auto())
|
||||
);
|
||||
assert!(command!(&["mini", "--demo"], Command::Mini(args) => args.demo));
|
||||
assert!(parse(&["--yolo"]).unwrap().0.root.permissions.auto());
|
||||
let mut command = help::command();
|
||||
let run = command
|
||||
.find_subcommand_mut("run")
|
||||
.unwrap()
|
||||
.render_help()
|
||||
.to_string();
|
||||
let mini = command
|
||||
.find_subcommand_mut("mini")
|
||||
.unwrap()
|
||||
.render_help()
|
||||
.to_string();
|
||||
assert!(run.contains("--auto") && !run.contains("yolo") && !run.contains("dangerously"));
|
||||
assert!(
|
||||
mini.contains("--replay") && !mini.contains("--demo") && !mini.contains("--no-replay ")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_flags_apply_where_declared() {
|
||||
let server = |line: &[&str]| parse(line).unwrap().1;
|
||||
assert_eq!(
|
||||
server(&["--server", "http://a", "session", "list"])
|
||||
.server
|
||||
.as_deref(),
|
||||
Some("http://a")
|
||||
);
|
||||
assert_eq!(
|
||||
server(&["session", "--server", "http://a", "list"])
|
||||
.server
|
||||
.as_deref(),
|
||||
Some("http://a")
|
||||
);
|
||||
assert_eq!(
|
||||
server(&["session", "list", "--server", "http://a"])
|
||||
.server
|
||||
.as_deref(),
|
||||
Some("http://a")
|
||||
);
|
||||
assert!(server(&["--standalone", "run", "hi"]).standalone);
|
||||
assert!(server(&["run", "hi", "--standalone"]).standalone);
|
||||
assert_eq!(
|
||||
server(&["--server", "http://a"]).server.as_deref(),
|
||||
Some("http://a")
|
||||
);
|
||||
assert_eq!(
|
||||
server(&["debug", "heap-dump", "--server", "http://a"])
|
||||
.server
|
||||
.as_deref(),
|
||||
Some("http://a")
|
||||
);
|
||||
assert!(
|
||||
error(&["--server", "http://a", "upgrade"])
|
||||
.contains("Unrecognized flag: --server in command")
|
||||
);
|
||||
assert!(
|
||||
error(&["--standalone", "debug", "heap-dump"]).contains("Unrecognized flag: --standalone")
|
||||
);
|
||||
assert!(error(&["upgrade", "--server", "http://a"]).contains("--server"));
|
||||
assert!(
|
||||
error(&["--server", "a", "session", "list", "--server", "b"]).contains("2 occurrences")
|
||||
);
|
||||
assert!(error(&["--standalone", "auth", "list", "--standalone"]).contains("2 occurrences"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_flags_do_not_pass_to_subcommands() {
|
||||
assert!(
|
||||
error(&["-c", "upgrade"])
|
||||
.contains("Unrecognized flag: --continue in command opencode-rs upgrade")
|
||||
);
|
||||
assert!(error(&["--prompt", "hi", "run"]).contains("Unrecognized flag: --prompt"));
|
||||
assert!(error(&["--auto", "session", "list"]).contains("Unrecognized flag: --auto"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_flags_go_anywhere() {
|
||||
assert!(
|
||||
parse(&["--print-logs", "session", "list"])
|
||||
.unwrap()
|
||||
.0
|
||||
.global
|
||||
.print_logs
|
||||
);
|
||||
assert!(
|
||||
parse(&["session", "list", "--print-logs"])
|
||||
.unwrap()
|
||||
.0
|
||||
.global
|
||||
.print_logs
|
||||
);
|
||||
assert!(
|
||||
parse(&["debug", "paths", "--version"])
|
||||
.unwrap()
|
||||
.0
|
||||
.global
|
||||
.version
|
||||
);
|
||||
assert!(parse(&["run", "-v"]).unwrap().0.global.version);
|
||||
assert_eq!(
|
||||
parse(&["auth", "--log-level", "debug"])
|
||||
.unwrap()
|
||||
.0
|
||||
.global
|
||||
.log_level,
|
||||
Some(args::LogLevel::Debug)
|
||||
);
|
||||
assert!(
|
||||
parse(&["service", "status", "--wizard"])
|
||||
.unwrap()
|
||||
.0
|
||||
.global
|
||||
.wizard
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_flags_cluster() {
|
||||
let run = command!(&["run", "-cf", "a.txt", "hi"], Command::Run(args) => args);
|
||||
assert!(run.continue_);
|
||||
assert_eq!(
|
||||
(run.file, run.message),
|
||||
(vec!["a.txt".to_string()], vec!["hi".to_string()])
|
||||
);
|
||||
assert!(command!(&["pair", "-y"], Command::Pair(args) => args.yes));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_numbers_are_values() {
|
||||
assert_eq!(
|
||||
command!(&["mini", "--replay-limit", "-5"], Command::Mini(args) => args.replay_limit),
|
||||
Some(-5)
|
||||
);
|
||||
assert!(error(&["stats", "--days", "-1"]).contains("-1"));
|
||||
assert_eq!(
|
||||
command!(&["run", "-1.5e3"], Command::Run(args) => args.message),
|
||||
["-1.5e3"]
|
||||
);
|
||||
assert!(error(&["stats", "--year", "1969"]).contains("1969"));
|
||||
assert_eq!(command!(&["stats"], Command::Stats(args) => args.limit), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_first_word_names_a_subcommand() {
|
||||
assert_eq!(
|
||||
command!(&["run", "session", "list"], Command::Run(args) => args.message),
|
||||
["session", "list"]
|
||||
);
|
||||
assert_eq!(
|
||||
parse(&["project"]).unwrap().0.root.directory.as_deref(),
|
||||
Some("project")
|
||||
);
|
||||
assert_eq!(
|
||||
command!(&["run", "-m", "session", "hi"], Command::Run(args) => args.message),
|
||||
["hi"]
|
||||
);
|
||||
assert!(
|
||||
command!(&["session", "list", "-n", "3"], Command::Session(args) => matches!(
|
||||
args.command,
|
||||
Some(SessionCommand::List(list)) if list.max_count == Some(3)
|
||||
))
|
||||
);
|
||||
assert!(parse(&["debug", "nope"]).is_err());
|
||||
assert!(parse(&["api", "a", "b", "c"]).is_err());
|
||||
assert!(parse(&["api"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aliases_and_values_match() {
|
||||
assert!(
|
||||
command!(&["update", "1.2.3", "-m", "brew"], Command::Upgrade(args) => args.target.is_some())
|
||||
);
|
||||
assert!(error(&["upgrade", "--method", "apt"]).contains("apt"));
|
||||
let url =
|
||||
command!(&["pair", "--url", "https://example.com/base//"], Command::Pair(args) => args.url);
|
||||
assert_eq!(url.as_deref(), Some("https://example.com/base"));
|
||||
assert!(
|
||||
error(&["pair", "--url", "https://user:secret@example.com"])
|
||||
.contains("without credentials")
|
||||
);
|
||||
assert!(error(&["pair", "--url", "ftp://example.com"]).contains("HTTP(S)"));
|
||||
}
|
||||
325
packages/cli-rs/crates/cli/src/tests/tree.rs
Normal file
325
packages/cli-rs/crates/cli/src/tests/tree.rs
Normal file
|
|
@ -0,0 +1,325 @@
|
|||
//! The clap tree against `tests/fixtures/commands.json`, the TypeScript `Spec` tree dumped by
|
||||
//! `script/gen/commands.ts`: names, aliases, descriptions, arguments, and flags with their types.
|
||||
|
||||
use clap::ArgAction;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::help;
|
||||
|
||||
fn fixture() -> Value {
|
||||
serde_json::from_str(include_str!("../../tests/fixtures/commands.json")).unwrap()
|
||||
}
|
||||
|
||||
fn diff(fixture: &Value) -> Vec<String> {
|
||||
let tree = help::tree();
|
||||
let mut diffs = Vec::new();
|
||||
let builtins = tree
|
||||
.get_arguments()
|
||||
.filter(|arg| arg.is_global_set())
|
||||
.collect::<Vec<_>>();
|
||||
compare_flags("builtins", &fixture["builtins"], &builtins, &mut diffs);
|
||||
compare_command("opencode", &fixture["root"], &tree, &mut diffs);
|
||||
diffs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tree_matches_the_typescript_cli() {
|
||||
let fixture = fixture();
|
||||
let nodes = count(&fixture["root"]);
|
||||
assert_eq!(nodes, 48, "commands.ts has 48 Spec nodes");
|
||||
let diffs = diff(&fixture);
|
||||
assert!(
|
||||
diffs.is_empty(),
|
||||
"the clap tree differs from the TypeScript tree:\n{}",
|
||||
diffs.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
// The comparison sees each kind of change in the TypeScript tree.
|
||||
#[test]
|
||||
fn tree_comparison_reports_changes() {
|
||||
type Edit = fn(&mut Value);
|
||||
let edits: [(&str, Edit); 7] = [
|
||||
("description", |tree| {
|
||||
tree["root"]["commands"][0]["description"] = "changed".into()
|
||||
}),
|
||||
("alias", |tree| {
|
||||
tree["root"]["commands"][0]["aliases"] = serde_json::json!([])
|
||||
}),
|
||||
("flag", |tree| {
|
||||
tree["root"]["flags"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.pop()
|
||||
.map(drop)
|
||||
.unwrap()
|
||||
}),
|
||||
("hidden", |tree| {
|
||||
tree["root"]["flags"][3]["hidden"] = false.into()
|
||||
}),
|
||||
("type", |tree| {
|
||||
tree["root"]["commands"][3]["flags"][0]["type"] = "Int".into()
|
||||
}),
|
||||
("argument", |tree| {
|
||||
tree["root"]["arguments"][0]["optional"] = false.into()
|
||||
}),
|
||||
("command", |tree| {
|
||||
tree["root"]["commands"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.pop()
|
||||
.map(drop)
|
||||
.unwrap()
|
||||
}),
|
||||
];
|
||||
for (what, edit) in edits {
|
||||
let mut fixture = fixture();
|
||||
edit(&mut fixture);
|
||||
assert_eq!(
|
||||
diff(&fixture).len(),
|
||||
1,
|
||||
"a changed {what} gives one difference"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn count(node: &Value) -> usize {
|
||||
1 + node["commands"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(count)
|
||||
.sum::<usize>()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tree_passes_clap_checks() {
|
||||
help::command().debug_assert();
|
||||
}
|
||||
|
||||
fn compare_command(path: &str, ts: &Value, command: &clap::Command, diffs: &mut Vec<String>) {
|
||||
let mut check = |what: &str, expected: Value, actual: Value| {
|
||||
if expected != actual {
|
||||
diffs.push(format!(
|
||||
"{path}: {what}: TypeScript {expected}, Rust {actual}"
|
||||
));
|
||||
}
|
||||
};
|
||||
let root = path == "opencode";
|
||||
if !root {
|
||||
check("name", ts["name"].clone(), command.get_name().into());
|
||||
}
|
||||
let aliases: Vec<&str> = command.get_visible_aliases().collect();
|
||||
check("aliases", ts["aliases"].clone(), aliases.into());
|
||||
let about = command
|
||||
.get_about()
|
||||
.map(|about| about.to_string())
|
||||
.unwrap_or_default();
|
||||
check("description", ts["description"].clone(), about.into());
|
||||
|
||||
let globals: Vec<&str> = match root {
|
||||
// The root's built-ins are compared with the fixture's `builtins`.
|
||||
true => Vec::new(),
|
||||
false => command
|
||||
.get_arguments()
|
||||
.filter(|arg| arg.is_global_set())
|
||||
.filter_map(|arg| arg.get_long())
|
||||
.collect(),
|
||||
};
|
||||
check("global flags", ts["globalFlags"].clone(), globals.into());
|
||||
|
||||
let positionals: Vec<Value> = command.get_positionals().map(positional).collect();
|
||||
let expected: Vec<Value> = ts["arguments"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(expected_positional)
|
||||
.collect();
|
||||
check("arguments", expected.into(), positionals.into());
|
||||
|
||||
let flags: Vec<&clap::Arg> = command
|
||||
.get_arguments()
|
||||
.filter(|arg| !arg.is_positional() && !arg.is_global_set() && !is_negation(command, arg))
|
||||
.collect();
|
||||
compare_flags(path, &ts["flags"], &flags, diffs);
|
||||
|
||||
let children: Vec<&str> = command
|
||||
.get_subcommands()
|
||||
.map(|sub| sub.get_name())
|
||||
.collect();
|
||||
let expected: Vec<&str> = ts["commands"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|sub| sub["name"].as_str())
|
||||
.collect();
|
||||
if children != expected {
|
||||
diffs.push(format!(
|
||||
"{path}: subcommands: TypeScript {expected:?}, Rust {children:?}"
|
||||
));
|
||||
return;
|
||||
}
|
||||
for (ts, sub) in ts["commands"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.zip(command.get_subcommands())
|
||||
{
|
||||
compare_command(&format!("{path} {}", sub.get_name()), ts, sub, diffs);
|
||||
}
|
||||
}
|
||||
|
||||
fn compare_flags(path: &str, ts: &Value, flags: &[&clap::Arg], diffs: &mut Vec<String>) {
|
||||
let expected: Vec<Value> = ts.as_array().unwrap().iter().map(expected_flag).collect();
|
||||
let actual: Vec<Value> = flags.iter().map(|arg| flag(arg)).collect();
|
||||
let name = |flag: &Value| flag["name"].as_str().unwrap_or_default().to_string();
|
||||
let missing: Vec<String> = expected
|
||||
.iter()
|
||||
.filter(|flag| !actual.iter().any(|a| name(a) == name(flag)))
|
||||
.map(name)
|
||||
.collect();
|
||||
let extra: Vec<String> = actual
|
||||
.iter()
|
||||
.filter(|flag| !expected.iter().any(|e| name(e) == name(flag)))
|
||||
.map(name)
|
||||
.collect();
|
||||
if !missing.is_empty() || !extra.is_empty() {
|
||||
diffs.push(format!(
|
||||
"{path}: flags missing in Rust {missing:?}, only in Rust {extra:?}"
|
||||
));
|
||||
}
|
||||
for expected in &expected {
|
||||
if let Some(actual) = actual.iter().find(|actual| name(actual) == name(expected))
|
||||
&& actual != expected
|
||||
{
|
||||
diffs.push(format!(
|
||||
"{path}: flag --{}:\n TypeScript {expected}\n Rust {actual}",
|
||||
name(expected)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The facts the TypeScript dump has, in the same shape, from a clap argument.
|
||||
fn flag(arg: &clap::Arg) -> Value {
|
||||
let action = arg.get_action();
|
||||
let boolean = matches!(action, ArgAction::SetTrue | ArgAction::Help);
|
||||
let value_name = arg
|
||||
.get_value_names()
|
||||
.and_then(|names| names.first())
|
||||
.map(|name| name.to_string());
|
||||
let choices = choices(arg);
|
||||
let kind = match value_name.as_deref() {
|
||||
_ if boolean => "Boolean",
|
||||
Some("string") => "String",
|
||||
Some("integer") => "Int",
|
||||
Some("key=value") => "KeyValuePair",
|
||||
Some("choice") => "Choice",
|
||||
Some("name") => "name",
|
||||
// `--completions` and `--log-level`: Effect CLI shows the choices as the metavariable.
|
||||
_ if !choices.is_empty() => "metavar",
|
||||
_ => "unknown",
|
||||
};
|
||||
let mut aliases: Vec<String> = arg.get_short().map(String::from).into_iter().collect();
|
||||
aliases.extend(
|
||||
arg.get_visible_aliases()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(String::from),
|
||||
);
|
||||
let default = match boolean {
|
||||
true => Value::Null,
|
||||
false => arg
|
||||
.get_default_values()
|
||||
.first()
|
||||
.map_or(Value::Null, |value| value.to_string_lossy().into()),
|
||||
};
|
||||
serde_json::json!({
|
||||
"name": arg.get_long().unwrap_or_default(),
|
||||
"aliases": aliases,
|
||||
"type": kind,
|
||||
"choices": choices,
|
||||
"description": arg.get_help().map(|help| help.to_string()).unwrap_or_default(),
|
||||
"hidden": arg.is_hide_set(),
|
||||
"optional": !arg.is_required_set(),
|
||||
"repeated": matches!(action, ArgAction::Append),
|
||||
"optionalValue": arg.is_require_equals_set() && arg.get_num_args().is_some_and(|range| range.min_values() == 0),
|
||||
"default": default,
|
||||
})
|
||||
}
|
||||
|
||||
fn expected_flag(ts: &Value) -> Value {
|
||||
let kind = match ts["type"].as_str().unwrap_or_default() {
|
||||
metavar if metavar.starts_with('<') => "metavar",
|
||||
kind => kind,
|
||||
};
|
||||
let default = match &ts["default"] {
|
||||
Value::Bool(_) | Value::Null => Value::Null,
|
||||
value => value.to_string().trim_matches('"').into(),
|
||||
};
|
||||
serde_json::json!({
|
||||
"name": ts["name"],
|
||||
"aliases": ts["aliases"],
|
||||
"type": kind,
|
||||
"choices": ts["choices"],
|
||||
"description": ts["description"],
|
||||
"hidden": ts["hidden"],
|
||||
"optional": ts["optional"],
|
||||
"repeated": ts["repeated"],
|
||||
"optionalValue": ts["optionalValue"],
|
||||
"default": default,
|
||||
})
|
||||
}
|
||||
|
||||
fn positional(arg: &clap::Arg) -> Value {
|
||||
let range = arg.get_num_args();
|
||||
let variadic = matches!(arg.get_action(), ArgAction::Append)
|
||||
|| range.is_some_and(|range| range.max_values() > 1);
|
||||
let choices = choices(arg);
|
||||
serde_json::json!({
|
||||
"name": arg.get_value_names().and_then(|names| names.first()).map(|name| name.to_string()),
|
||||
"type": if choices.is_empty() { "String" } else { "Choice" },
|
||||
"choices": choices,
|
||||
"description": arg.get_help().map(|help| help.to_string()).unwrap_or_default(),
|
||||
"required": arg.is_required_set(),
|
||||
"variadic": variadic,
|
||||
"max": range.map(|range| range.max_values()).filter(|max| *max != usize::MAX),
|
||||
})
|
||||
}
|
||||
|
||||
fn expected_positional(ts: &Value) -> Value {
|
||||
let variadic = ts["variadic"].as_bool().unwrap_or(false);
|
||||
let min = ts["min"].as_u64().unwrap_or(0);
|
||||
serde_json::json!({
|
||||
"name": ts["name"],
|
||||
"type": ts["type"],
|
||||
"choices": ts["choices"],
|
||||
"description": ts["description"],
|
||||
"required": !ts["optional"].as_bool().unwrap_or(false) && (!variadic || min > 0),
|
||||
"variadic": variadic,
|
||||
"max": ts["max"],
|
||||
})
|
||||
}
|
||||
|
||||
fn choices(arg: &clap::Arg) -> Vec<String> {
|
||||
if matches!(arg.get_action(), ArgAction::SetTrue | ArgAction::Help) {
|
||||
return Vec::new();
|
||||
}
|
||||
arg.get_possible_values()
|
||||
.iter()
|
||||
.map(|value| value.get_name().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
// `--no-replay` is the hidden negation that `args::normalize` emits; Effect CLI has it built into `--replay`.
|
||||
fn is_negation(command: &clap::Command, arg: &clap::Arg) -> bool {
|
||||
arg.is_hide_set()
|
||||
&& arg
|
||||
.get_long()
|
||||
.and_then(|long| long.strip_prefix("no-"))
|
||||
.is_some_and(|long| {
|
||||
command
|
||||
.get_arguments()
|
||||
.any(|other| other.get_long() == Some(long))
|
||||
})
|
||||
}
|
||||
1
packages/cli-rs/crates/cli/src/update/mod.rs
Normal file
1
packages/cli-rs/crates/cli/src/update/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
//! Update checks and the update handoff. Step D.2.
|
||||
5
packages/cli-rs/crates/cli/src/wizard.rs
Normal file
5
packages/cli-rs/crates/cli/src/wizard.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//! `--wizard`. Step C.15; until then the flag is accepted and reports that it is not supported (O-11).
|
||||
|
||||
pub fn run() -> anyhow::Result<()> {
|
||||
anyhow::bail!("--wizard is not supported yet (plan step C.15)")
|
||||
}
|
||||
|
|
@ -10,7 +10,7 @@ the same commands, aliases, arguments, flags, and descriptions. The help layout
|
|||
`help` so they equal the TypeScript strings.
|
||||
- `script/gen/commands.ts` dumps the TypeScript `Spec` tree to `crates/cli/tests/fixtures/commands.json`: per
|
||||
node its name, aliases, description, global flags, arguments, and flags (name, aliases, type, choices,
|
||||
description, hidden, optional, repeated with bounds, optional value, default). `crates/cli/tests/tree.rs`
|
||||
description, hidden, optional, repeated with bounds, optional value, default). `crates/cli/src/tests/tree.rs`
|
||||
walks the clap `Command` and compares the same facts. A change on either side fails the test until the
|
||||
other side follows.
|
||||
- The type of a flag is carried by its clap value name, which help shows: `string`, `integer`, `key=value`,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
// Dumps the TypeScript CLI command tree (packages/cli/src/commands/commands.ts) to JSON. The Rust test
|
||||
// crates/cli/tests/tree.rs compares the clap tree against it: names, aliases, descriptions, arguments, flags.
|
||||
// crates/cli/src/tests/tree.rs compares the clap tree against it: names, aliases, descriptions, arguments, flags.
|
||||
import { Effect, Exit, Option } from "effect"
|
||||
import { GlobalFlag } from "effect/cli"
|
||||
import { Commands, PrintLogs } from "../../../cli/src/commands/commands"
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue