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 printf;
70mod push;
71mod pwd;
72mod read;
73mod readlink;
74mod realpath;
75mod rm;
76mod scatter;
77mod sed;
78mod seq;
79mod split;
80mod set;
81mod sleep;
82mod sort;
83mod stat;
84mod tac;
85mod tail;
86mod tee;
87mod test;
88mod timeout;
89mod tojson;
90mod tojsonl;
91#[cfg(feature = "tokens")]
92mod tokens;
93mod touch;
94mod tr;
95mod tree;
96mod true_false;
97// Module named `type_of`, not `typeof` — `typeof` is a reserved (but unused)
98// Rust keyword, so `mod typeof;` doesn't compile. The tool name is still the
99// plain string "typeof" (see `Tool::name`).
100mod type_of;
101mod uname;
102mod uniq;
103mod unset;
104mod validate;
105mod values;
106mod vars;
107mod wait;
108mod wc;
109#[cfg(feature = "subprocess")]
110mod which;
111mod write;
112mod xxd;
113
114use super::ToolRegistry;
115use crate::validator::{IssueCode, ValidationIssue};
116
117/// Warn when a name argument is spelled in two scripts.
118///
119/// The validator walker sees an assignment target and nothing else, so the
120/// builtins that take a name as an argument word — `export`, `read`, `unset`,
121/// `push`, and `scatter --as` — report the same rule from their own
122/// `Tool::validate`. `PАTH=/bin` and `export PАTH=/bin` have to agree.
123///
124/// `<dynamic>` is the walker's placeholder for a word it cannot read before
125/// execution (`unset "$name"`). There is no spelling to judge, so it is
126/// skipped rather than reported. The placeholder is single-script Latin and
127/// would not warn on its own; the guard says it is not a name, and holds if
128/// the sentinel ever changes.
129pub(crate) fn mixed_script_issue(name: &str) -> Option<ValidationIssue> {
130    if name == "<dynamic>" {
131        return None;
132    }
133    let mixed = crate::name::mixed_script(name)?;
134    Some(
135        ValidationIssue::warning(IssueCode::MixedScriptName, mixed.to_string())
136            .with_suggestion(mixed.suggestion()),
137    )
138}
139
140/// Read a repeatable string-valued flag off the raw `ToolArgs`.
141///
142/// Repeatable value flags (clap `Append`) are accumulated by the kernel into a
143/// `Value::Json(Array)` under the flag's long name; a single occurrence may
144/// arrive as a bare `Value::String`. `to_argv()` can't round-trip the array, so
145/// the clap field isn't a reliable source — search builtins read the raw args
146/// here. Shared by grep/glob `--ftype`/`--ftype-not`; mirrors sed's
147/// `collect_expressions` (see the repeatable-flag gotcha in `arch_repeatable_flags`).
148///
149/// A non-string occurrence is a loud error, never a silent skip — a dropped
150/// filter leaves the caller running unfiltered while believing it narrowed the
151/// search. Binary never reaches here: `flag_value_to_json` stops it at the
152/// binder (GH #223), which is the only layer that can tell real bytes from a
153/// record that merely looks like the envelope.
154pub(crate) fn read_repeatable_strings(
155    args: &super::ToolArgs,
156    key: &str,
157) -> Result<Vec<String>, String> {
158    use crate::ast::Value;
159    match args.named.get(key) {
160        Some(Value::Json(serde_json::Value::Array(items))) => {
161            let mut out = Vec::with_capacity(items.len());
162            for v in items {
163                match v.as_str() {
164                    Some(s) => out.push(s.to_string()),
165                    None => {
166                        return Err(format!(
167                            "a repeatable flag value must be a string, got `{v}`"
168                        ))
169                    }
170                }
171            }
172            Ok(out)
173        }
174        Some(Value::String(s)) => Ok(vec![s.clone()]),
175        Some(other) => {
176            match crate::interpreter::value_to_text_sink_named(other, "a repeatable flag value") {
177                Ok(s) => Ok(vec![s]),
178                Err(e) => Err(e.to_string()),
179            }
180        }
181        None => Ok(Vec::new()),
182    }
183}
184
185/// Read a path-typed positional/named arg as a string, going LOUD on a
186/// `Value::Bytes` operand rather than `ToolArgs::get_string`'s silent `None`
187/// (that method lives in the `kaish-types` leaf crate, which has no
188/// `EvalError`/rich-error machinery to report *why* it returned nothing, so it
189/// just treats any non-scalar-text value as absent).
190///
191/// A caller reading `get_string` for a *path* generally treats `None` as
192/// "operand missing" and either errors or falls back to some other input
193/// (stdin, `$HOME`, …) — exactly the silent-wrong-source shape GH #93 item 1
194/// is about, just reached through `get_string`'s catch-all instead of
195/// `value_to_string`'s placeholder. `Ok(None)` here means genuinely absent;
196/// `Err` means it was present and binary.
197pub(crate) fn get_path_string(
198    args: &super::ToolArgs,
199    name: &str,
200    positional_index: usize,
201) -> Result<Option<String>, String> {
202    use crate::ast::Value;
203    match args.get(name, positional_index) {
204        Some(v @ Value::Bytes(_)) => match crate::interpreter::value_to_text_sink_named(v, "a path") {
205            Ok(s) => Ok(Some(s)),
206            Err(e) => Err(e.to_string()),
207        },
208        _ => Ok(args.get_string(name, positional_index)),
209    }
210}
211
212/// Register all built-in tools with the registry.
213pub fn register_builtins(registry: &mut ToolRegistry) {
214    registry.register(alias::Alias);
215    registry.register(alias::Unalias);
216    registry.register(assert::Assert);
217    registry.register(awk::Awk);
218    registry.register(base64_tool::Base64Tool);
219    registry.register(basename::Basename);
220    #[cfg(feature = "subprocess")]
221    registry.register(bg::Bg);
222    registry.register(cat::Cat);
223    registry.register(cd::Cd);
224    registry.register(checksum::Checksum);
225    registry.register(cmp::Cmp);
226    registry.register(cp::Cp);
227    registry.register(cut::Cut);
228    registry.register(date::Date::new());
229    registry.register(dd::Dd);
230    registry.register(diff::Diff);
231    registry.register(dirname::Dirname);
232    registry.register(echo::Echo);
233    registry.register(env::Env);
234    #[cfg(feature = "subprocess")]
235    registry.register(exec::Exec);
236    #[cfg(feature = "subprocess")]
237    registry.register(spawn::Spawn);
238    registry.register(export::Export);
239    #[cfg(feature = "subprocess")]
240    registry.register(fg::Fg);
241    registry.register(file::File);
242    registry.register(fromjson::FromJson);
243    registry.register(fromjsonl::FromJsonl);
244    registry.register(glob::Glob);
245    registry.register(find::Find);
246    registry.register(gather::Gather);
247    registry.register(grep::Grep);
248    registry.register(head::Head);
249    registry.register(help::Help);
250    registry.register(ignore::KaishIgnore);
251    #[cfg(feature = "host")]
252    registry.register(hostname::Hostname);
253    registry.register(introspect::Mounts);
254    registry.register(introspect::Tools);
255    registry.register(jobs::Jobs);
256    registry.register(jq_native::JqNative);
257    registry.register(kaish_ast::KaishAst);
258    registry.register(kaish_clear::KaishClear);
259    registry.register(kaish_last::KaishLast);
260    registry.register(kaish_trash::KaishTrash);
261    registry.register(kaish_status::KaishStatus);
262    registry.register(kaish_version::KaishVersion);
263    registry.register(kaish_vfs::KaishVfs);
264    registry.register(keys::Keys);
265    registry.register(kill::Kill);
266    registry.register(ln::Ln);
267    registry.register(ls::Ls);
268    registry.register(mkdir::Mkdir);
269    registry.register(mktemp::Mktemp);
270    registry.register(mv::Mv);
271    registry.register(output_limit::KaishOutputLimit);
272    registry.register(patch::Patch);
273    registry.register(printf::Printf);
274    registry.register(push::Push);
275    #[cfg(all(target_os = "linux", feature = "host"))]
276    registry.register(kaish_tools_host::Ps);
277    registry.register(pwd::Pwd);
278    registry.register(read::Read);
279    registry.register(readlink::Readlink);
280    registry.register(realpath::Realpath);
281    registry.register(rm::Rm);
282    registry.register(scatter::Scatter);
283    registry.register(sed::Sed);
284    registry.register(seq::Seq);
285    registry.register(set::Set);
286    registry.register(split::Split);
287    registry.register(sleep::Sleep);
288    registry.register(sort::Sort);
289    registry.register(stat::Stat);
290    registry.register(tac::Tac);
291    registry.register(tail::Tail);
292    registry.register(tee::Tee);
293    registry.register(test::Test);
294    registry.register(timeout::Timeout);
295    #[cfg(feature = "tokens")]
296    registry.register(tokens::Tokens);
297    registry.register(tojson::ToJson);
298    registry.register(tojsonl::ToJsonl);
299    registry.register(touch::Touch);
300    registry.register(tr::Tr);
301    registry.register(tree::Tree);
302    registry.register(true_false::True);
303    registry.register(true_false::False);
304    registry.register(true_false::Colon);
305    registry.register(type_of::TypeOf);
306    registry.register(uname::Uname);
307    registry.register(uniq::Uniq);
308    registry.register(unset::Unset);
309    registry.register(validate::Validate);
310    registry.register(values::Values);
311    registry.register(vars::Vars);
312    registry.register(wait::Wait);
313    registry.register(wc::Wc);
314    #[cfg(feature = "subprocess")]
315    registry.register(which::Which);
316    registry.register(write::Write);
317    registry.register(xxd::Xxd);
318}