Skip to main content

kaish_kernel/tools/builtin/
mod.rs

1//! Built-in tools for kaish.
2//!
3//! These tools are always available and provide core functionality.
4
5mod alias;
6mod assert;
7mod awk;
8mod base64_tool;
9mod basename;
10#[cfg(feature = "subprocess")]
11mod bg;
12mod cat;
13mod cd;
14mod checksum;
15mod cmp;
16mod cp;
17mod cut;
18mod date;
19mod dd;
20mod diff;
21mod dirname;
22mod patch;
23mod echo;
24mod env;
25#[cfg(feature = "subprocess")]
26mod exec;
27#[cfg(feature = "subprocess")]
28mod spawn;
29#[cfg(feature = "subprocess")]
30pub use spawn::{resolve_in_path, virtual_cwd_error};
31mod export;
32#[cfg(feature = "subprocess")]
33mod fg;
34mod file;
35mod fromjson;
36mod fromjsonl;
37mod glob;
38mod find;
39pub(crate) mod format_string;
40mod gather;
41mod grep;
42mod grep_engine;
43mod regex_dialect;
44mod head;
45mod ignore;
46mod help;
47// `hostname` is pure host introspection (reads /proc) — gated behind the host
48// capability. `uname` stays available and reports kaish identity instead.
49#[cfg(feature = "host")]
50mod hostname;
51mod introspect;
52mod jobs;
53mod jq_native;
54mod kaish_ast;
55mod kaish_clear;
56mod kaish_last;
57mod kaish_trash;
58mod kaish_status;
59mod kaish_version;
60mod kaish_vfs;
61mod keys;
62mod kill;
63mod ln;
64mod ls;
65mod mkdir;
66mod mktemp;
67mod mv;
68mod output_limit;
69mod plan;
70mod printf;
71mod push;
72mod pwd;
73mod read;
74mod readlink;
75mod realpath;
76mod rm;
77mod scatter;
78mod sed;
79mod seq;
80mod split;
81mod set;
82mod sleep;
83mod sort;
84mod stat;
85mod tac;
86mod tail;
87mod tee;
88mod test;
89mod timeout;
90mod tojson;
91mod tojsonl;
92#[cfg(feature = "tokens")]
93mod tokens;
94mod touch;
95mod tr;
96mod tree;
97mod true_false;
98// Module named `type_of`, not `typeof` — `typeof` is a reserved (but unused)
99// Rust keyword, so `mod typeof;` doesn't compile. The tool name is still the
100// plain string "typeof" (see `Tool::name`).
101mod type_of;
102mod uname;
103mod uniq;
104mod unset;
105mod validate;
106mod values;
107mod vars;
108mod wait;
109mod wc;
110#[cfg(feature = "subprocess")]
111mod which;
112mod write;
113mod xxd;
114
115use super::ToolRegistry;
116use crate::validator::{IssueCode, ValidationIssue};
117
118/// Warn when a name argument is spelled in two scripts.
119///
120/// The validator walker sees an assignment target and nothing else, so the
121/// builtins that take a name as an argument word — `export`, `read`, `unset`,
122/// `push`, and `scatter --as` — report the same rule from their own
123/// `Tool::validate`. `PАTH=/bin` and `export PАTH=/bin` have to agree.
124///
125/// `<dynamic>` is the walker's placeholder for a word it cannot read before
126/// execution (`unset "$name"`). There is no spelling to judge, so it is
127/// skipped rather than reported. The placeholder is single-script Latin and
128/// would not warn on its own; the guard says it is not a name, and holds if
129/// the sentinel ever changes.
130pub(crate) fn mixed_script_issue(name: &str) -> Option<ValidationIssue> {
131    if name == "<dynamic>" {
132        return None;
133    }
134    let mixed = crate::name::mixed_script(name)?;
135    Some(
136        ValidationIssue::warning(IssueCode::MixedScriptName, mixed.to_string())
137            .with_suggestion(mixed.suggestion()),
138    )
139}
140
141/// Read a repeatable string-valued flag off the raw `ToolArgs`.
142///
143/// Repeatable value flags (clap `Append`) are accumulated by the kernel into a
144/// `Value::Json(Array)` under the flag's long name; a single occurrence may
145/// arrive as a bare `Value::String`. `to_argv()` can't round-trip the array, so
146/// the clap field isn't a reliable source — search builtins read the raw args
147/// here. Shared by grep/glob `--ftype`/`--ftype-not`; mirrors sed's
148/// `collect_expressions` (see the repeatable-flag gotcha in `arch_repeatable_flags`).
149///
150/// A non-string occurrence is a loud error, never a silent skip — a dropped
151/// filter leaves the caller running unfiltered while believing it narrowed the
152/// search. Binary never reaches here: `flag_value_to_json` stops it at the
153/// binder (GH #223), which is the only layer that can tell real bytes from a
154/// record that merely looks like the envelope.
155pub(crate) fn read_repeatable_strings(
156    args: &super::ToolArgs,
157    key: &str,
158) -> Result<Vec<String>, String> {
159    use crate::ast::Value;
160    match args.named.get(key) {
161        Some(Value::Json(serde_json::Value::Array(items))) => {
162            let mut out = Vec::with_capacity(items.len());
163            for v in items {
164                match v.as_str() {
165                    Some(s) => out.push(s.to_string()),
166                    None => {
167                        return Err(format!(
168                            "a repeatable flag value must be a string, got `{v}`"
169                        ))
170                    }
171                }
172            }
173            Ok(out)
174        }
175        Some(Value::String(s)) => Ok(vec![s.clone()]),
176        Some(other) => {
177            match crate::interpreter::value_to_text_sink_named(other, "a repeatable flag value") {
178                Ok(s) => Ok(vec![s]),
179                Err(e) => Err(e.to_string()),
180            }
181        }
182        None => Ok(Vec::new()),
183    }
184}
185
186/// Read a path-typed positional/named arg as a string, going LOUD on a
187/// `Value::Bytes` operand rather than `ToolArgs::get_string`'s silent `None`
188/// (that method lives in the `kaish-types` leaf crate, which has no
189/// `EvalError`/rich-error machinery to report *why* it returned nothing, so it
190/// just treats any non-scalar-text value as absent).
191///
192/// A caller reading `get_string` for a *path* generally treats `None` as
193/// "operand missing" and either errors or falls back to some other input
194/// (stdin, `$HOME`, …) — exactly the silent-wrong-source shape GH #93 item 1
195/// is about, just reached through `get_string`'s catch-all instead of
196/// `value_to_string`'s placeholder. `Ok(None)` here means genuinely absent;
197/// `Err` means it was present and binary.
198pub(crate) fn get_path_string(
199    args: &super::ToolArgs,
200    name: &str,
201    positional_index: usize,
202) -> Result<Option<String>, String> {
203    use crate::ast::Value;
204    match args.get(name, positional_index) {
205        Some(v @ Value::Bytes(_)) => match crate::interpreter::value_to_text_sink_named(v, "a path") {
206            Ok(s) => Ok(Some(s)),
207            Err(e) => Err(e.to_string()),
208        },
209        _ => Ok(args.get_string(name, positional_index)),
210    }
211}
212
213/// Refuse to let `ls`/`find`/`glob` report a name containing a newline as
214/// TEXT. `for f in $(cmd)`, a pipe, and `OutputData::to_canonical_string()`
215/// itself all treat one newline as one path boundary; a name that already
216/// contains a newline splits into two lines that name no file that exists
217/// (measured: a 2-file directory with one `we\nird.txt` name counted as 3
218/// items under `for f in $(ls dir)`). This is [`value_to_text_sink_named`]'s
219/// sibling at the output boundary rather than the interpolation boundary —
220/// same shape (name the sink, go loud rather than corrupt silently), a
221/// different one.
222///
223/// Walks `output`'s tree (root and children, so `ls -R`'s nested listing is
224/// covered too) and returns the first offending name, with its newline
225/// rendered as the two characters `\n` so the message stays on one line.
226///
227/// Call this only after confirming `--json` was not requested
228/// (`ctx.output_format.is_none()`): `--json` serializes each name as its own
229/// JSON string and never joins names by newline, so it stays the documented,
230/// lossless way to read a newline-bearing name — named in the error below.
231///
232/// [`value_to_text_sink_named`]: crate::interpreter::value_to_text_sink_named
233pub(crate) fn guard_no_newline_names(
234    builtin: &str,
235    output: &crate::interpreter::OutputData,
236) -> Result<(), String> {
237    fn first_newline_name(nodes: &[crate::interpreter::OutputNode]) -> Option<&str> {
238        for node in nodes {
239            let name = node.display_name();
240            if name.contains('\n') {
241                return Some(name);
242            }
243            if let Some(found) = first_newline_name(&node.children) {
244                return Some(found);
245            }
246        }
247        None
248    }
249
250    if let Some(name) = first_newline_name(&output.root) {
251        let escaped = name.replace('\n', "\\n");
252        return Err(format!(
253            "{builtin}: '{escaped}': a newline in a filename cannot be reported as \
254             text — the line split would report two files that do not exist. \
255             Use `{builtin} --json` to read it losslessly, or rename the file."
256        ));
257    }
258    Ok(())
259}
260
261/// Register all built-in tools with the registry.
262pub fn register_builtins(registry: &mut ToolRegistry) {
263    registry.register(alias::Alias);
264    registry.register(alias::Unalias);
265    registry.register(assert::Assert);
266    registry.register(awk::Awk);
267    registry.register(base64_tool::Base64Tool);
268    registry.register(basename::Basename);
269    #[cfg(feature = "subprocess")]
270    registry.register(bg::Bg);
271    registry.register(cat::Cat);
272    registry.register(cd::Cd);
273    registry.register(checksum::Checksum);
274    registry.register(cmp::Cmp);
275    registry.register(cp::Cp);
276    registry.register(cut::Cut);
277    registry.register(date::Date::new());
278    registry.register(dd::Dd);
279    registry.register(diff::Diff);
280    registry.register(dirname::Dirname);
281    registry.register(echo::Echo);
282    registry.register(env::Env);
283    #[cfg(feature = "subprocess")]
284    registry.register(exec::Exec);
285    #[cfg(feature = "subprocess")]
286    registry.register(spawn::Spawn);
287    registry.register(export::Export);
288    #[cfg(feature = "subprocess")]
289    registry.register(fg::Fg);
290    registry.register(file::File);
291    registry.register(fromjson::FromJson);
292    registry.register(fromjsonl::FromJsonl);
293    registry.register(glob::Glob);
294    registry.register(find::Find);
295    registry.register(gather::Gather);
296    registry.register(grep::Grep);
297    registry.register(head::Head);
298    registry.register(help::Help);
299    registry.register(ignore::KaishIgnore);
300    #[cfg(feature = "host")]
301    registry.register(hostname::Hostname);
302    registry.register(introspect::Mounts);
303    registry.register(introspect::Tools);
304    registry.register(jobs::Jobs);
305    registry.register(jq_native::JqNative);
306    registry.register(kaish_ast::KaishAst);
307    registry.register(kaish_clear::KaishClear);
308    registry.register(kaish_last::KaishLast);
309    registry.register(kaish_trash::KaishTrash);
310    registry.register(kaish_status::KaishStatus);
311    registry.register(kaish_version::KaishVersion);
312    registry.register(kaish_vfs::KaishVfs);
313    registry.register(keys::Keys);
314    registry.register(kill::Kill);
315    registry.register(ln::Ln);
316    registry.register(ls::Ls);
317    registry.register(mkdir::Mkdir);
318    registry.register(mktemp::Mktemp);
319    registry.register(mv::Mv);
320    registry.register(output_limit::KaishOutputLimit);
321    registry.register(patch::Patch);
322    registry.register(plan::PlanTool);
323    registry.register(printf::Printf);
324    registry.register(push::Push);
325    #[cfg(all(target_os = "linux", feature = "host"))]
326    registry.register(kaish_tools_host::Ps);
327    registry.register(pwd::Pwd);
328    registry.register(read::Read);
329    registry.register(readlink::Readlink);
330    registry.register(realpath::Realpath);
331    registry.register(rm::Rm);
332    registry.register(scatter::Scatter);
333    registry.register(sed::Sed);
334    registry.register(seq::Seq);
335    registry.register(set::Set);
336    registry.register(split::Split);
337    registry.register(sleep::Sleep);
338    registry.register(sort::Sort);
339    registry.register(stat::Stat);
340    registry.register(tac::Tac);
341    registry.register(tail::Tail);
342    registry.register(tee::Tee);
343    registry.register(test::Test);
344    registry.register(timeout::Timeout);
345    #[cfg(feature = "tokens")]
346    registry.register(tokens::Tokens);
347    registry.register(tojson::ToJson);
348    registry.register(tojsonl::ToJsonl);
349    registry.register(touch::Touch);
350    registry.register(tr::Tr);
351    registry.register(tree::Tree);
352    registry.register(true_false::True);
353    registry.register(true_false::False);
354    registry.register(true_false::Colon);
355    registry.register(type_of::TypeOf);
356    registry.register(uname::Uname);
357    registry.register(uniq::Uniq);
358    registry.register(unset::Unset);
359    registry.register(validate::Validate);
360    registry.register(values::Values);
361    registry.register(vars::Vars);
362    registry.register(wait::Wait);
363    registry.register(wc::Wc);
364    #[cfg(feature = "subprocess")]
365    registry.register(which::Which);
366    registry.register(write::Write);
367    registry.register(xxd::Xxd);
368}