1use std::{
4 collections::BTreeMap,
5 ffi::OsString,
6 io::{self, Write},
7 path::{Path, PathBuf},
8};
9
10use crate::{
11 Content, ToolResult,
12 builtin::{self, fixed::FixedInput},
13 scope::{Artifact, ArtifactId, Scope},
14};
15use clap::{Parser, Subcommand};
16use tokio_util::sync::CancellationToken;
17
18#[derive(Parser)]
19#[command(
20 disable_help_subcommand = true,
21 version,
22 about = "Portable scoped tools for artifactize",
23 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."
24)]
25pub struct Cli {
26 #[command(subcommand)]
27 pub command: Tool,
28}
29
30#[derive(Debug, Subcommand)]
31pub enum Tool {
32 Read { path: PathBuf },
34 List {
36 #[arg(default_value = ".")]
37 path: PathBuf,
38 },
39 Glob {
41 pattern: String,
42 #[arg(default_value = ".")]
43 path: PathBuf,
44 },
45 Grep {
47 pattern: String,
48 #[arg(default_value = ".")]
49 path: PathBuf,
50 #[arg(long)]
51 glob: Option<String>,
52 #[arg(long)]
53 case_insensitive: bool,
54 },
55 Section { path: PathBuf, heading: String },
57 Help {
59 #[arg(required = true, num_args = 1.., trailing_var_arg = true, value_parser = clap::value_parser!(std::ffi::OsString))]
61 args: Vec<std::ffi::OsString>,
62 },
63 Open { target: String },
65}
66
67pub async fn run(tool: Tool) -> u8 {
70 match execute(tool).await {
71 Ok(()) => 0,
72 Err(error) => {
73 let _ = writeln!(std::io::stderr(), "{error}");
74 1
75 }
76 }
77}
78
79fn logical(path: &Path) -> Result<builtin::LogicalPath, String> {
82 builtin::LogicalPath::from_native(path)
83}
84
85async fn execute(tool: Tool) -> Result<(), String> {
86 let root = crate::files::current_directory().map_err(|error| error.to_string())?;
87 execute_in(tool, &root, async |target| {
88 crate::opener::open(&target).await
89 })
90 .await
91}
92
93async fn execute_in(
94 tool: Tool,
95 root: &Path,
96 open: impl AsyncFnOnce(OsString) -> io::Result<()>,
97) -> Result<(), String> {
98 let owner = ArtifactId::new("cwd").expect("static identifier");
99 let scope = Scope {
100 artifacts: BTreeMap::from([(
101 owner.clone(),
102 Artifact {
103 path: PathBuf::new()
104 .try_into()
105 .expect("workspace root is relative"),
106 name: "cwd".into(),
107 covering_part: None,
108 nested: BTreeMap::new(),
109 },
110 )]),
111 };
112 let cancellation = CancellationToken::new();
113 enum Invocation {
114 Fixed(Result<FixedInput, String>),
115 Dynamic(builtin::Input),
116 }
117 let invocation = match tool {
118 Tool::Read { path } => Invocation::Fixed(FixedInput::read(logical(&path)?)),
119 Tool::List { path } => Invocation::Fixed(FixedInput::list(logical(&path)?)),
120 Tool::Section { path, heading } => {
121 Invocation::Fixed(FixedInput::section(logical(&path)?, heading))
122 }
123 Tool::Help { args } => Invocation::Fixed(FixedInput::native_help(args)),
124 Tool::Glob { pattern, path } => {
125 Invocation::Dynamic(builtin::Input::glob(&pattern, logical(&path)?)?)
126 }
127 Tool::Grep {
128 pattern,
129 path,
130 glob,
131 case_insensitive,
132 } => Invocation::Dynamic(builtin::Input::grep(
133 &pattern,
134 logical(&path)?,
135 glob.as_deref(),
136 case_insensitive,
137 )?),
138 Tool::Open { target } => {
139 let target = if builtin::is_url(&target) {
140 target.into()
141 } else {
142 let path = crate::scope::InputPath::from_native(Path::new(&target))
144 .map_err(|error| error.to_string())?;
145 scope
146 .resolve_parsed(root, &owner, path)
147 .map_err(|error| error.to_string())?
148 .into_os_string()
149 };
150 return open(target).await.map_err(|error| error.to_string());
151 }
152 };
153 let result = match invocation {
154 Invocation::Fixed(Err(error)) => ToolResult::error(error),
155 Invocation::Fixed(Ok(input)) => {
156 let interrupt = cancellation.clone();
159 let watch = tokio::spawn(async move {
160 crate::platform::interrupted().await;
161 interrupt.cancel();
162 });
163 let result = builtin::fixed::execute(
164 input,
165 builtin::Context {
166 root,
167 scope: &scope,
168 owner: &owner,
169 launcher: &crate::launch::Standalone,
170 },
171 &cancellation,
172 )
173 .await;
174 watch.abort();
175 result
176 }
177 Invocation::Dynamic(input) => builtin::call(input, root, &scope, &owner, &cancellation),
178 };
179 let (mut stdout, mut stderr) = (std::io::stdout().lock(), std::io::stderr().lock());
180 for content in result.content() {
181 match content {
182 Content::Text { text } if result.is_error() => writeln!(stderr, "{text}"),
183 Content::Text { text } => write!(stdout, "{text}"),
184 Content::Json { data } => writeln!(
185 stdout,
186 "{}",
187 serde_json::to_string_pretty(&data).expect("builtin JSON")
188 ),
189 Content::Image { .. } => unreachable!("CLI tools produce no images"),
190 }
191 .map_err(|error| error.to_string())?;
192 }
193 if result.is_error() {
194 Err("Tool failed.".into())
195 } else {
196 Ok(())
197 }
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203
204 #[tokio::test]
205 async fn scoped_cli_open_records_exactly_one_absolute_target() {
206 let root = crate::test_os::tempdir();
207 let root = crate::files::canonicalize(root.path()).unwrap();
208 let file = crate::test_os::opener_input(&root);
209 let cli = Cli::try_parse_from([
210 "artifactize-tools",
211 "open",
212 file.file_name().unwrap().to_str().unwrap(),
213 ])
214 .unwrap();
215 let mut targets = Vec::new();
216 execute_in(cli.command, &root, async |target| {
218 targets.push(PathBuf::from(target));
219 Ok(())
220 })
221 .await
222 .unwrap();
223 assert!(crate::files::is_absolute(&file));
224 assert_eq!(targets, [file]);
225 }
226
227 #[tokio::test]
228 async fn scoped_cli_open_refuses_links_and_escapes_without_a_handoff() {
229 let fixture = crate::test_os::tempdir();
230 let root = fixture.path().join("scope");
231 std::fs::create_dir(&root).unwrap();
232 let outside = crate::test_os::opener_input(fixture.path());
233 let relative_escape = Path::new("..").join(outside.file_name().unwrap());
234 crate::test_os::symlink_file(&outside, root.join("link.md"));
235 for target in [Path::new("link.md"), &relative_escape, &outside] {
236 let cli = Cli::try_parse_from(["artifactize-tools", "open", target.to_str().unwrap()])
237 .unwrap();
238 let outcome = execute_in(cli.command, &root, async |_| {
239 panic!("rejected path reached the desktop handoff")
240 })
241 .await;
242 assert!(outcome.is_err(), "{target:?} was not rejected");
243 }
244 }
245}