Skip to main content

artifactize_tools/
cli.rs

1//! Shared command-line definition and current-directory tool runner.
2
3use 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    /// Print a UTF-8 file (at most 64 KiB).
33    Read { path: PathBuf },
34    /// List a directory, as JSON.
35    List {
36        #[arg(default_value = ".")]
37        path: PathBuf,
38    },
39    /// Find logical file paths, as JSON.
40    Glob {
41        pattern: String,
42        #[arg(default_value = ".")]
43        path: PathBuf,
44    },
45    /// Search UTF-8 files, as JSON.
46    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    /// Print a Markdown section, selected by its exact heading.
56    Section { path: PathBuf, heading: String },
57    /// Run PROGRAM SUBCOMMAND... --help (10 seconds, 64 KiB).
58    Help {
59        /// Kept as the OS gave them: an argument need not be valid Unicode.
60        #[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 one scoped path or HTTP(S) URL in its default application.
64    Open { target: String },
65}
66
67/// Execute a parsed standalone tool with the current directory as its scope.
68/// The facade and standalone binary share output and exit codes, not just parsing.
69pub 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
79/// A command-line path as a validated tool path, through the platform's path layer: its
80/// names validated once, roots and traversal refused, `.` the project root.
81fn 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    let stop = crate::platform::stop_requested().map_err(|error| error.to_string())?;
88    let cancellation = CancellationToken::new();
89    let interrupt = cancellation.clone();
90    let watcher = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
91        stop.await;
92        interrupt.cancel();
93    }));
94    let result = execute_in(tool, &root, &cancellation, async |target, cancellation| {
95        crate::opener::open_cancellable(&target, cancellation).await
96    })
97    .await;
98    drop(watcher);
99    result
100}
101
102async fn execute_in(
103    tool: Tool,
104    root: &Path,
105    cancellation: &CancellationToken,
106    open: impl AsyncFnOnce(OsString, &CancellationToken) -> io::Result<()>,
107) -> Result<(), String> {
108    let owner = ArtifactId::new("cwd").expect("static identifier");
109    let scope = Scope {
110        artifacts: BTreeMap::from([(
111            owner.clone(),
112            Artifact {
113                path: PathBuf::new()
114                    .try_into()
115                    .expect("workspace root is relative"),
116                name: "cwd".into(),
117                covering_part: None,
118                nested: BTreeMap::new(),
119            },
120        )]),
121    };
122    enum Invocation {
123        Fixed(Result<FixedInput, String>),
124        Dynamic(builtin::Input),
125    }
126    let invocation = match tool {
127        Tool::Read { path } => Invocation::Fixed(FixedInput::read(logical(&path)?)),
128        Tool::List { path } => Invocation::Fixed(FixedInput::list(logical(&path)?)),
129        Tool::Section { path, heading } => {
130            Invocation::Fixed(FixedInput::section(logical(&path)?, heading))
131        }
132        Tool::Help { args } => Invocation::Fixed(FixedInput::native_help(args)),
133        Tool::Glob { pattern, path } => {
134            Invocation::Dynamic(builtin::Input::glob(&pattern, logical(&path)?)?)
135        }
136        Tool::Grep {
137            pattern,
138            path,
139            glob,
140            case_insensitive,
141        } => Invocation::Dynamic(builtin::Input::grep(
142            &pattern,
143            logical(&path)?,
144            glob.as_deref(),
145            case_insensitive,
146        )?),
147        Tool::Open { target } => {
148            let target = if builtin::is_url(&target) {
149                target.into()
150            } else {
151                // Validated once at this edge, then resolved as that path.
152                let path = crate::scope::InputPath::from_native(Path::new(&target))
153                    .map_err(|error| error.to_string())?;
154                scope
155                    .resolve_parsed(root, &owner, path)
156                    .map_err(|error| error.to_string())?
157                    .into_os_string()
158            };
159            return open(target, cancellation)
160                .await
161                .map_err(|error| error.to_string());
162        }
163    };
164    let result = match invocation {
165        Invocation::Fixed(Err(error)) => ToolResult::error(error),
166        Invocation::Fixed(Ok(input)) => {
167            builtin::fixed::execute(
168                input,
169                builtin::Context {
170                    root,
171                    scope: &scope,
172                    owner: &owner,
173                    launcher: &crate::launch::Standalone,
174                },
175                cancellation,
176            )
177            .await
178        }
179        Invocation::Dynamic(input) => {
180            // Keep the terminal listener live even during a large synchronous file scan.
181            let root = root.to_owned();
182            let cancellation = cancellation.child_token();
183            let _cancel_on_drop = cancellation.clone().drop_guard();
184            match tokio::task::spawn_blocking(move || {
185                builtin::call(input, &root, &scope, &owner, &cancellation)
186            })
187            .await
188            {
189                Ok(result) => result,
190                Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
191                Err(error) => return Err(error.to_string()),
192            }
193        }
194    };
195    let (mut stdout, mut stderr) = (std::io::stdout().lock(), std::io::stderr().lock());
196    for content in result.content() {
197        match content {
198            Content::Text { text } if result.is_error() => writeln!(stderr, "{text}"),
199            Content::Text { text } => write!(stdout, "{text}"),
200            Content::Json { data } => writeln!(
201                stdout,
202                "{}",
203                serde_json::to_string_pretty(&data).expect("builtin JSON")
204            ),
205            Content::Image { .. } => unreachable!("CLI tools produce no images"),
206        }
207        .map_err(|error| error.to_string())?;
208    }
209    if result.is_error() {
210        Err("Tool failed.".into())
211    } else {
212        Ok(())
213    }
214}
215
216#[cfg(test)]
217mod tests;