jao 0.3.4

Discover and run workspace scripts from a simple CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! `jao` is a small CLI for discovering and running workspace scripts.
//!
//! It is meant for repositories that already have shell or batch scripts and
//! want a thin command layer on top, without adopting a bigger task runner.
//!
//! # What it does
//!
//! - Recursively discovers `.sh` scripts on Unix-like systems and `.bat`
//!   scripts on Windows
//! - Resolves a command like `jao db reset local` to a script selected by
//!   `.jaofolder` path markers plus the script file stem
//! - Respects `.gitignore` during discovery
//! - Honors recursive `.jaoignore` files to skip ignored scripts and directories
//! - Runs the script from the script's own directory
//! - Supports SHA-256 fingerprint checks for CI-safe execution
//! - Optionally keeps a local trust manifest for interactive runs
//! - Prints shell completion scripts for Bash and Zsh
//!
//! # Practical examples
//!
//! ```text
//! # basic use
//! jao --list
//! jao check
//! jao test integration
//! jao db reset local
//! ```
//!
//! ```text
//! # .jaofolder in a multi-project repo
//! jao apps frontend dev
//! jao apps backend build
//! ```
//!
//! ```text
//! # fingerprinting in CI
//! jao --fingerprint db reset local
//! jao --ci --require-fingerprint <FINGERPRINT> db reset local
//! ```
//!
//! ```text
//! # shell completion
//! source <(jao --completions bash)
//! jao m<TAB>    -> myapp
//! jao myapp <TAB> -> backend frontend
//! ```
//!
//! # Completions
//!
//! `jao` supports two completion surfaces:
//!
//! - static completion script output via `jao --completions <bash|zsh>`
//! - dynamic candidate generation via the hidden `jao __complete` protocol
//!
//! The generated shell scripts call:
//!
//! ```text
//! jao __complete --index <CURRENT_WORD_INDEX> -- <WORDS_AFTER_JAO...>
//! ```
//!
//! The internal protocol then returns one completion candidate per line.
//! Suggestions are context-aware and include:
//!
//! - top-level options (`--help`, `--list`, etc.)
//! - shell names after `--completions`
//! - script command parts discovered from the current working directory
//!
//! Dynamic script-part completion respects the same discovery rules as command
//! execution, including `.jaofolder` path markers and recursive `.jaoignore`.
//!
//! # `.jaofolder` and `.jaoignore`
//!
//! `.jaofolder` files mark directories that should appear in the command name.
//! If `apps/`, `frontend/`, and `backend/` contain `.jaofolder`, then scripts
//! with the same stem can stay distinct without forcing long commands everywhere.
//!
//! `.jaoignore` files work recursively like `.gitignore` and can hide
//! throwaway or internal-only scripts from discovery.
//!
//! # Trust behavior
//!
//! In the default build, `jao` keeps a trust manifest under `~/.jao/`.
//!
//! - Unknown scripts prompt before first run
//! - Modified scripts prompt again
//! - `--ci` disables prompting
//! - CI runs require `--require-fingerprint`
//!
//! If the crate is built without the `trust-manifest` feature, interactive
//! trust is disabled and runs require an explicit fingerprint.
//!
//! # Fingerprints and trust manifests
//!
//! `jao` fingerprints a script by hashing two things together:
//!
//! - the script's canonical path
//! - the script file contents
//!
//! This means moving a script to a different real path changes the
//! fingerprint, even if the bytes are identical. That is intentional: trust is
//! attached to the exact file at the exact resolved location.
//!
//! When the `trust-manifest` feature is enabled, trusted scripts are stored in
//! a local trust manifest keyed by canonical path. Each entry records the last
//! trusted fingerprint for that script. If the current fingerprint differs from
//! the stored one, `jao` treats the script as modified and asks for trust again
//! in interactive mode.
//!
//! # Features
//!
//! - `trust-manifest` (default): Enables local trust tracking for interactive
//!   runs
//! - `config`: Enables config file support used by `trust-manifest`
//!
//! See the repository README for a fuller overview and examples aimed at end
//! users.

use std::ffi::{OsStr, OsString};
use std::io::ErrorKind as IoErrorKind;
use std::path::PathBuf;
use std::process::ExitStatus;

use clap::builder::OsStringValueParser;
use clap::{Arg, ArgAction, ArgMatches, Command};
use ignore::Error as IgnoreError;
use thiserror::Error;

use crate::actions::{CompletionRequest, Shell};

mod actions;
mod platform;
mod script_discovery;
mod trust;

#[cfg(feature = "config")]
// Currently, the config is only used for trust-manifest.
// hence config specific calls are only called in trust manifest code, causing
// dead code if only the config feature is on. So we allow it.
#[cfg_attr(not(feature = "trust-manifest"), allow(dead_code))]
mod config;

#[cfg(feature = "config")]
// See above
#[cfg_attr(not(feature = "trust-manifest"), allow(dead_code))]
mod storage;

#[doc(hidden)]
fn main() {
    __exit(__main())
}

const GENERATE_COMPLETION_SPECIAL_ARG: &'static str = "__complete";

#[doc(hidden)]
fn __main() -> JaoResult<()> {
    let raw_args = std::env::args_os().collect::<Vec<OsString>>();

    if raw_args
        .get(1)
        .is_some_and(|arg| arg == GENERATE_COMPLETION_SPECIAL_ARG)
    {
        // .skip(2) to skip `jao __complete`
        let complete_args = parse_internal_completion_args(
            raw_args
                .iter()
                .skip(2)
                .map(AsRef::as_ref),
        )?;

        // Jao resolution happens in working directory
        let root = std::env::current_dir()?;

        return actions::complete(root, complete_args);
    }

    let matches = clap_command().try_get_matches_from(&raw_args)?;

    let context = CliContext::from(&matches);

    match CliAction::try_from(&matches)? {
        CliAction::Help => actions::print_help(),
        CliAction::PrintCompletionsForShell(shell) => actions::print_shell_completion(shell),
        #[cfg(not(feature = "trust-manifest"))]
        CliAction::List => {
            let root = std::env::current_dir()?;
            actions::list_scripts(root)
        }
        #[cfg(feature = "trust-manifest")]
        CliAction::List => {
            let root = std::env::current_dir()?;
            let config = config::load_or_init()?;
            let trusted_manifest = trust::manifest::load_or_init(&config)?;
            actions::list_scripts_with_trust_status(root, &trusted_manifest)
        }
        CliAction::Fingerprint { parts } => {
            let root = std::env::current_dir()?;
            let script_path = script_discovery::resolve_script(root, parts)?;
            actions::fingerprint_script(script_path)
        }
        CliAction::RunFingerprinted { parts, required_fingerprint } => {
            let root = std::env::current_dir()?;
            let script_path = script_discovery::resolve_script(root, parts)?;
            actions::run_script_with_fingerprint(script_path, required_fingerprint)
        }
        CliAction::RunUntrusted { .. } if context.ci => Err(JaoError::CiRunRequiresFingerprint),
        #[cfg(not(feature = "trust-manifest"))]
        CliAction::RunUntrusted { .. } => Err(JaoError::RunWithoutTrustManifestRequiresFingerprint),
        #[cfg(feature = "trust-manifest")]
        CliAction::RunUntrusted { parts } => {
            let root = std::env::current_dir()?;
            let script_path = script_discovery::resolve_script(root, parts)?;
            let config = config::load_or_init()?;
            let mut trusted_manifest = trust::manifest::load_or_init(&config)?;
            actions::run_script_with_trust(script_path, &config, &mut trusted_manifest)
        }
    }
}

fn __exit(final_result: JaoResult<()>) -> ! {
    match &final_result {
        Err(JaoError::Clap(clap_err)) => {
            clap_err
                .print()
                .unwrap();
        }
        Err(error) => eprintln!("error: {error}"),
        _ => (),
    }

    let exit_code = match final_result {
        Ok(_) => 0,
        // not our fault
        Err(JaoError::Io(io_err)) if io_err.kind() == IoErrorKind::BrokenPipe => 0,
        Err(JaoError::InvalidArguments(_)) | Err(JaoError::Clap(_)) => 2,
        Err(_) => 1,
    };

    std::process::exit(exit_code)
}

fn parse_internal_completion_args<'a>(mut remaining_args: impl Iterator<Item = &'a OsStr>) -> JaoResult<CompletionRequest<'a>> {
    if remaining_args.next() != Some(OsStr::new("--index")) {
        return Err(JaoError::InvalidArguments("missing --index arg"));
    }

    let index_to_complete = if let Some(index_as_str) = remaining_args.next() {
        index_as_str
            .to_string_lossy()
            .parse::<usize>()
            .map_err(|_| JaoError::InvalidArguments("given index is not a valid number"))?
    } else {
        return Err(JaoError::InvalidArguments("missing index"));
    };

    if remaining_args.next() != Some(OsStr::new("--")) {
        return Err(JaoError::InvalidArguments("missing -- after index"));
    }

    let completion_args = CompletionRequest {
        index_to_complete,
        given_arguments: remaining_args.collect(),
    };

    return Ok(completion_args);
}

#[derive(Debug, Clone, Copy)]
struct CliContext {
    ci: bool,
}

impl From<&ArgMatches> for CliContext {
    fn from(matches: &ArgMatches) -> Self {
        Self { ci: matches.get_flag("ci") }
    }
}

#[derive(Debug)]
enum CliAction<'a> {
    Help,
    PrintCompletionsForShell(Shell),
    List,
    Fingerprint {
        parts: Vec<&'a OsStr>,
    },
    RunFingerprinted {
        parts: Vec<&'a OsStr>,
        required_fingerprint: &'a OsStr,
    },
    RunUntrusted {
        #[cfg_attr(not(feature = "trust-manifest"), allow(dead_code))]
        parts: Vec<&'a OsStr>,
    },
}

impl<'a> TryFrom<&'a ArgMatches> for CliAction<'a> {
    type Error = JaoError;

    fn try_from(matches: &'a ArgMatches) -> Result<Self, Self::Error> {
        if let Some(shell_str) = matches
            .get_raw("completions")
            .and_then(|mut values| values.next())
        {
            let shell = Shell::try_from(shell_str)?;
            return Ok(CliAction::PrintCompletionsForShell(shell));
        };

        if matches.get_flag("list") {
            return Ok(CliAction::List);
        }

        if let Some(parts) = matches.get_raw("fingerprint") {
            return Ok(CliAction::Fingerprint { parts: parts.collect() });
        }

        match (
            matches
                .get_raw("require_fingerprint")
                .and_then(|mut values| values.next()),
            matches.get_raw("script_command"),
        ) {
            (Some(required_fingerprint), Some(parts)) => Ok(CliAction::RunFingerprinted {
                parts: parts.collect(),
                required_fingerprint,
            }),
            (None, Some(parts)) => Ok(CliAction::RunUntrusted { parts: parts.collect() }),
            (None, None) => Ok(CliAction::Help),
            (Some(_), None) => Err(JaoError::InvalidArguments("missing script command after --require-fingerprint")),
        }
    }
}

fn clap_command() -> Command {
    Command::new("jao")
        .version(env!("CARGO_PKG_VERSION"))
        .disable_help_subcommand(true)
        .arg(
            Arg::new("ci")
                .long("ci")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("list")
                .long("list")
                .action(ArgAction::SetTrue)
                .conflicts_with_all(["completions", "script_command", "fingerprint", "require_fingerprint"]),
        )
        .arg(
            Arg::new("fingerprint")
                .long("fingerprint")
                .num_args(1..)
                .value_parser(OsStringValueParser::new())
                .conflicts_with_all(["list", "completions", "script_command", "require_fingerprint"]),
        )
        .arg(
            Arg::new("require_fingerprint")
                .long("require-fingerprint")
                .value_parser(OsStringValueParser::new())
                .conflicts_with_all(["list", "fingerprint", "completions"]),
        )
        .arg(
            Arg::new("completions")
                .long("completions")
                .value_parser(OsStringValueParser::new())
                .conflicts_with_all(["ci", "fingerprint", "require_fingerprint", "list", "script_command"]),
        )
        .arg(
            Arg::new("script_command")
                .num_args(1..)
                .trailing_var_arg(true)
                .value_parser(OsStringValueParser::new()),
        )
}

type JaoResult<T> = Result<T, JaoError>;

#[derive(Debug, Error)]
enum JaoError {
    #[error(transparent)]
    Clap(#[from] clap::Error),

    #[error("{0}")]
    InvalidArguments(&'static str),

    #[cfg(feature = "config")]
    #[error("unable to determine user storage directory")]
    StorageDirUnavailable,

    #[error(transparent)]
    Io(#[from] std::io::Error),

    #[error(transparent)]
    Ignore(#[from] IgnoreError),

    #[cfg(feature = "config")]
    #[error(transparent)]
    TomlDeserialize(#[from] toml::de::Error),

    #[cfg(feature = "config")]
    #[error(transparent)]
    TomlSerialize(#[from] toml::ser::Error),

    #[cfg(feature = "config")]
    #[error("invalid storage path: {path}")]
    InvalidStoragePath { path: PathBuf },

    #[error("script {script_name} not found")]
    ScriptNotFound { script_name: String },

    #[error("script {path} has no parent directory")]
    ScriptHasNoParent { path: PathBuf },

    #[error("script {path} has no file name")]
    ScriptHasNoFileName { path: PathBuf },

    #[cfg(unix)]
    #[error("script is not executable and has no shebang: {path}")]
    ScriptNotExecutableAndNoShebang { path: PathBuf },

    #[error("script exited with status {status}")]
    ScriptFailed { status: ExitStatus },

    #[cfg(feature = "trust-manifest")]
    #[error("unknown script trust requires interactive confirmation: {path}")]
    UnknownScriptNonInteractive { path: PathBuf },

    #[error("--ci run requires --require-fingerprint <FINGERPRINT>")]
    CiRunRequiresFingerprint,

    #[cfg(not(feature = "trust-manifest"))]
    #[error("run requires --require-fingerprint <FINGERPRINT> when built without trust-manifest feature")]
    RunWithoutTrustManifestRequiresFingerprint,

    #[error("invalid --require-fingerprint value (expected 64 hex chars): {fingerprint}")]
    InvalidRequiredFingerprint { fingerprint: String },

    #[error("fingerprint mismatch for {path}: expected {expected}, got {actual}")]
    FingerprintMismatch { path: PathBuf, expected: String, actual: String },

    #[cfg(feature = "trust-manifest")]
    #[error("script was not trusted by user: {path}")]
    ScriptNotTrusted { path: PathBuf },
}