use std::{
collections::BTreeMap,
ffi::OsString,
io::{self, Write},
path::{Path, PathBuf},
};
use crate::{
Content, ToolResult,
builtin::{self, fixed::FixedInput},
scope::{Artifact, ArtifactId, Scope},
};
use clap::{Parser, Subcommand};
use tokio_util::sync::CancellationToken;
#[derive(Parser)]
#[command(
disable_help_subcommand = true,
version,
about = "Portable scoped tools for artifactize",
long_about = "Portable scoped tools for artifactize. Filesystem targets must be relative to the current directory and stay below it. Parent components, absolute paths, and symlinks are refused. Use '.' for the current directory. Only open accepts HTTP(S) URLs. help resolves a literal program through the system's program search path."
)]
pub struct Cli {
#[command(subcommand)]
pub command: Tool,
}
#[derive(Debug, Subcommand)]
pub enum Tool {
Read { path: PathBuf },
List {
#[arg(default_value = ".")]
path: PathBuf,
},
Glob {
pattern: String,
#[arg(default_value = ".")]
path: PathBuf,
},
Grep {
pattern: String,
#[arg(default_value = ".")]
path: PathBuf,
#[arg(long)]
glob: Option<String>,
#[arg(long)]
case_insensitive: bool,
},
Section { path: PathBuf, heading: String },
Help {
#[arg(required = true, num_args = 1.., trailing_var_arg = true, value_parser = clap::value_parser!(std::ffi::OsString))]
args: Vec<std::ffi::OsString>,
},
Open { target: String },
}
pub async fn run(tool: Tool) -> u8 {
match execute(tool).await {
Ok(()) => 0,
Err(error) => {
let _ = writeln!(std::io::stderr(), "{error}");
1
}
}
}
fn logical(path: &Path) -> Result<builtin::LogicalPath, String> {
builtin::LogicalPath::from_native(path)
}
async fn execute(tool: Tool) -> Result<(), String> {
let root = crate::files::current_directory().map_err(|error| error.to_string())?;
let stop = crate::platform::stop_requested().map_err(|error| error.to_string())?;
let cancellation = CancellationToken::new();
let interrupt = cancellation.clone();
let watcher = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
stop.await;
interrupt.cancel();
}));
let result = execute_in(tool, &root, &cancellation, async |target, cancellation| {
crate::opener::open_cancellable(&target, cancellation).await
})
.await;
drop(watcher);
result
}
async fn execute_in(
tool: Tool,
root: &Path,
cancellation: &CancellationToken,
open: impl AsyncFnOnce(OsString, &CancellationToken) -> io::Result<()>,
) -> Result<(), String> {
let owner = ArtifactId::new("cwd").expect("static identifier");
let scope = Scope {
artifacts: BTreeMap::from([(
owner.clone(),
Artifact {
path: PathBuf::new()
.try_into()
.expect("workspace root is relative"),
name: "cwd".into(),
covering_part: None,
nested: BTreeMap::new(),
},
)]),
};
enum Invocation {
Fixed(Result<FixedInput, String>),
Dynamic(builtin::Input),
}
let invocation = match tool {
Tool::Read { path } => Invocation::Fixed(FixedInput::read(logical(&path)?)),
Tool::List { path } => Invocation::Fixed(FixedInput::list(logical(&path)?)),
Tool::Section { path, heading } => {
Invocation::Fixed(FixedInput::section(logical(&path)?, heading))
}
Tool::Help { args } => Invocation::Fixed(FixedInput::native_help(args)),
Tool::Glob { pattern, path } => {
Invocation::Dynamic(builtin::Input::glob(&pattern, logical(&path)?)?)
}
Tool::Grep {
pattern,
path,
glob,
case_insensitive,
} => Invocation::Dynamic(builtin::Input::grep(
&pattern,
logical(&path)?,
glob.as_deref(),
case_insensitive,
)?),
Tool::Open { target } => {
let target = if builtin::is_url(&target) {
target.into()
} else {
let path = crate::scope::InputPath::from_native(Path::new(&target))
.map_err(|error| error.to_string())?;
scope
.resolve_parsed(root, &owner, path)
.map_err(|error| error.to_string())?
.into_os_string()
};
return open(target, cancellation)
.await
.map_err(|error| error.to_string());
}
};
let result = match invocation {
Invocation::Fixed(Err(error)) => ToolResult::error(error),
Invocation::Fixed(Ok(input)) => {
builtin::fixed::execute(
input,
builtin::Context {
root,
scope: &scope,
owner: &owner,
launcher: &crate::launch::Standalone,
},
cancellation,
)
.await
}
Invocation::Dynamic(input) => {
let root = root.to_owned();
let cancellation = cancellation.child_token();
let _cancel_on_drop = cancellation.clone().drop_guard();
match tokio::task::spawn_blocking(move || {
builtin::call(input, &root, &scope, &owner, &cancellation)
})
.await
{
Ok(result) => result,
Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
Err(error) => return Err(error.to_string()),
}
}
};
let (mut stdout, mut stderr) = (std::io::stdout().lock(), std::io::stderr().lock());
for content in result.content() {
match content {
Content::Text { text } if result.is_error() => writeln!(stderr, "{text}"),
Content::Text { text } => write!(stdout, "{text}"),
Content::Json { data } => writeln!(
stdout,
"{}",
serde_json::to_string_pretty(&data).expect("builtin JSON")
),
Content::Image { .. } => unreachable!("CLI tools produce no images"),
}
.map_err(|error| error.to_string())?;
}
if result.is_error() {
Err("Tool failed.".into())
} else {
Ok(())
}
}
#[cfg(test)]
mod tests;