enwiro 0.3.34

Simplify your workflow with dedicated project environments for each workspace in your window manager
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Dispatcher for `enw :<gear> <entry> [args...]` — the leading `:` is
//! sniffed pre-clap in `main` so this module sees argv directly.

use std::collections::HashMap;
use std::ffi::OsString;
use std::path::{Path, PathBuf};

use anyhow::{Context, anyhow, bail};

use enwiro_sdk::gear::{CliEntry, Gear, LoadedGear};

const ACTIVE_ENV_VAR: &str = "ENWIRO_ENV";
const NONE_PLACEHOLDER: &str = "<none>";

/// Short form of the pre-positional confirmation-bypass flag. The flag
/// is parsed in two places (the pre-clap argv sniffer in `main.rs` and
/// the dispatcher's `strip_yes_flag`) which must stay in lockstep, so
/// the spelling lives here.
pub const SHORT_YES_FLAG: &str = "-y";
pub const LONG_YES_FLAG: &str = "--yes";

/// Parsed `enw [-y] :<gear> [<entry> [args...]]` invocation (no program
/// name). `entry_name` is `None` when the user invoked `enw :<gear>` with
/// no further args — that's a request to list available entries. `yes`
/// reflects an optional pre-positional `-y`/`--yes` flag (`enw -y :gear
/// entry`), which lets the dispatcher run entries marked
/// `require_confirmation: true`.
#[derive(Debug, PartialEq, Eq)]
pub struct DispatchTarget {
    pub gear_name: String,
    pub entry_name: Option<String>,
    pub passthrough: Vec<OsString>,
    pub yes: bool,
}

/// Strip a single leading `-y`/`--yes` flag from the front of `args`.
/// Pre-positional is the only accepted shape — placing the flag after
/// `:<gear>` would let it be matched as a passthrough arg by command-
/// prefix ACLs (e.g. claude-code's `Bash(enw :*)`), defeating the gating.
fn strip_yes_flag(args: &[OsString]) -> (bool, &[OsString]) {
    let is_yes = args
        .first()
        .and_then(|a| a.to_str())
        .is_some_and(|s| s == SHORT_YES_FLAG || s == LONG_YES_FLAG);
    if is_yes {
        (true, &args[1..])
    } else {
        (false, args)
    }
}

pub fn parse_dispatch_args(args: &[OsString]) -> anyhow::Result<DispatchTarget> {
    let (yes, rest) = strip_yes_flag(args);
    let first = rest
        .first()
        .ok_or_else(|| anyhow!("missing :<gear> argument"))?;
    let first_str = first
        .to_str()
        .ok_or_else(|| anyhow!("gear name must be valid UTF-8"))?;
    let gear_name = first_str
        .strip_prefix(':')
        .ok_or_else(|| anyhow!("gear name must start with `:`, got `{first_str}`"))?;
    if gear_name.is_empty() {
        bail!("gear name is empty (got just `:`)");
    }
    let entry_name = rest
        .get(1)
        .map(|e| {
            e.to_str()
                .map(str::to_owned)
                .ok_or_else(|| anyhow!("entry name must be valid UTF-8"))
        })
        .transpose()?;
    Ok(DispatchTarget {
        gear_name: gear_name.to_owned(),
        entry_name,
        passthrough: rest.iter().skip(2).cloned().collect(),
        yes,
    })
}

/// `workspaces_directory/<name>/<name>` is the inner symlink to the
/// cooked project root; the dispatcher execs there so `just <recipe>`
/// finds the justfile.
pub fn env_project_dir(workspaces_directory: &Path, env_name: &str) -> PathBuf {
    workspaces_directory.join(env_name).join(env_name)
}

pub fn active_env_name() -> anyhow::Result<String> {
    std::env::var(ACTIVE_ENV_VAR).with_context(|| {
        format!(
            "${ACTIVE_ENV_VAR} is unset; run `enw activate <name>` first or invoke from inside a wrapped env"
        )
    })
}

/// Comma-separated alphabetical listing for "available: …" messages.
fn format_available<'a>(items: impl Iterator<Item = &'a str>) -> String {
    let mut v: Vec<&str> = items.collect();
    v.sort();
    if v.is_empty() {
        NONE_PLACEHOLDER.to_owned()
    } else {
        v.join(", ")
    }
}

pub fn resolve_entry<'a>(
    gear_map: &'a HashMap<String, Gear>,
    gear_name: &str,
    entry_name: &str,
) -> anyhow::Result<&'a CliEntry> {
    let gear = gear_map.get(gear_name).ok_or_else(|| {
        anyhow!(
            "no gear named `:{gear_name}` in this env (available: {})",
            format_available(gear_map.keys().map(String::as_str))
        )
    })?;
    gear.cli.get(entry_name).ok_or_else(|| {
        anyhow!(
            "gear `:{gear_name}` has no cli entry `{entry_name}` (available: {})",
            format_available(gear.cli.keys().map(String::as_str))
        )
    })
}

/// Reject a `require_confirmation` entry when `-y` was not passed.
/// The error embeds a ready-to-run `enw -y :<gear> <entry>` so the
/// caller can retry by appending one token.
pub fn ensure_confirmed(
    gear_name: &str,
    entry_name: &str,
    entry: &CliEntry,
    yes: bool,
) -> anyhow::Result<()> {
    if entry.require_confirmation && !yes {
        bail!(
            "gear entry `:{gear_name} {entry_name}` requires confirmation; pass `-y` (e.g. `enw -y :{gear_name} {entry_name}`) to run it"
        );
    }
    Ok(())
}

pub fn build_argv(entry: &CliEntry, passthrough: &[OsString]) -> Vec<OsString> {
    entry
        .command
        .iter()
        .map(OsString::from)
        .chain(passthrough.iter().cloned())
        .collect()
}

/// Look up a gear by name; same not-found error shape as
/// [`resolve_entry`] for consistency.
fn resolve_gear<'a>(
    gear_map: &'a HashMap<String, Gear>,
    gear_name: &str,
) -> anyhow::Result<&'a Gear> {
    gear_map.get(gear_name).ok_or_else(|| {
        anyhow!(
            "no gear named `:{gear_name}` in this env (available: {})",
            format_available(gear_map.keys().map(String::as_str))
        )
    })
}

/// Human-readable list of every cli entry on a gear; used by
/// `enw :<gear>` (no entry) to tell the user what's available. Two-space
/// indent + name; descriptions follow on the same line when present.
pub fn format_entry_list(gear_name: &str, gear: &Gear) -> String {
    use std::fmt::Write;
    let mut out = format!(":{gear_name}{}\n", gear.description);
    if gear.cli.is_empty() {
        out.push_str("  (no cli entries)\n");
        return out;
    }
    let mut names: Vec<&str> = gear.cli.keys().map(String::as_str).collect();
    names.sort();
    for name in names {
        let entry = &gear.cli[name];
        match entry.description.as_deref() {
            Some(desc) => writeln!(out, "  {name}{desc}").unwrap(),
            None => writeln!(out, "  {name}").unwrap(),
        }
    }
    out
}

/// Parse → resolve env + gear → exec. With no entry given, lists the
/// gear's cli entries and exits 0. Replaces the current process on
/// child failure (exit with child's status); other errors bubble.
pub fn dispatch(workspaces_directory: &Path, args: &[OsString]) -> anyhow::Result<()> {
    let target = parse_dispatch_args(args)?;
    let env_name = active_env_name()?;
    let env_dir = workspaces_directory.join(&env_name);
    let project_dir = env_project_dir(workspaces_directory, &env_name);

    let gear_map = LoadedGear::from_env_dir(&env_dir)
        .with_context(|| format!("could not load gear for env `{env_name}`"))?
        .into_map();

    let Some(entry_name) = target.entry_name.as_deref() else {
        let gear = resolve_gear(&gear_map, &target.gear_name)?;
        print!("{}", format_entry_list(&target.gear_name, gear));
        return Ok(());
    };

    let entry = resolve_entry(&gear_map, &target.gear_name, entry_name)?;
    ensure_confirmed(&target.gear_name, entry_name, entry, target.yes)?;
    let argv = build_argv(entry, &target.passthrough);
    let (program, rest) = argv
        .split_first()
        .ok_or_else(|| anyhow!("cli entry `{entry_name}` has empty command"))?;

    let status = std::process::Command::new(program)
        .args(rest)
        .current_dir(&project_dir)
        .status()
        .with_context(|| {
            format!(
                "failed to spawn `{}` in {}",
                program.to_string_lossy(),
                project_dir.display()
            )
        })?;
    if !status.success() {
        std::process::exit(status.code().unwrap_or(1));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use rstest::rstest;

    fn osvec(parts: &[&str]) -> Vec<OsString> {
        parts.iter().map(OsString::from).collect()
    }

    fn cli_entry(command: &[&str]) -> CliEntry {
        CliEntry {
            description: None,
            command: command.iter().map(|s| (*s).to_owned()).collect(),
            require_confirmation: false,
            ..Default::default()
        }
    }

    fn gear_with_cli(entries: &[(&str, CliEntry)]) -> HashMap<String, Gear> {
        let cli = entries
            .iter()
            .map(|(n, e)| ((*n).to_owned(), e.clone()))
            .collect();
        HashMap::from([(
            "just".to_owned(),
            Gear {
                description: "Tasks from the project's justfile".into(),
                cli,
                ..Default::default()
            },
        )])
    }

    mod parse {
        use super::*;

        #[test]
        fn extracts_gear_entry_and_passthrough() {
            let t =
                parse_dispatch_args(&osvec(&[":just", "build", "--release", "-j", "4"])).unwrap();
            assert_eq!(t.gear_name, "just");
            assert_eq!(t.entry_name.as_deref(), Some("build"));
            assert_eq!(t.passthrough, osvec(&["--release", "-j", "4"]));
        }

        #[test]
        fn passthrough_empty_when_no_extra_args() {
            let t = parse_dispatch_args(&osvec(&[":just", "build"])).unwrap();
            assert!(t.passthrough.is_empty());
        }

        #[test]
        fn entry_is_none_when_only_gear_given() {
            // `enw :just` (no entry) — dispatch turns this into a listing.
            let t = parse_dispatch_args(&osvec(&[":just"])).unwrap();
            assert_eq!(t.gear_name, "just");
            assert!(t.entry_name.is_none());
            assert!(t.passthrough.is_empty());
        }

        #[rstest]
        #[case::missing_leading_colon(&["just", "build"], "must start with `:`")]
        #[case::bare_colon(&[":", "build"], "empty")]
        #[case::empty_argv(&[], "missing :<gear>")]
        fn rejects_with_helpful_message(#[case] args: &[&str], #[case] needle: &str) {
            let err = parse_dispatch_args(&osvec(args)).expect_err("must reject");
            assert!(err.to_string().contains(needle), "got: {err}");
        }

        #[test]
        fn yes_defaults_to_false_when_flag_absent() {
            let t = parse_dispatch_args(&osvec(&[":just", "build"])).unwrap();
            assert!(!t.yes);
        }

        #[rstest]
        #[case::short(&["-y", ":just", "deploy"])]
        #[case::long(&["--yes", ":just", "deploy"])]
        fn pre_positional_yes_flag_is_consumed(#[case] args: &[&str]) {
            let t = parse_dispatch_args(&osvec(args)).unwrap();
            assert!(t.yes);
            assert_eq!(t.gear_name, "just");
            assert_eq!(t.entry_name.as_deref(), Some("deploy"));
            assert!(t.passthrough.is_empty());
        }

        #[test]
        fn yes_flag_after_gear_is_treated_as_passthrough() {
            let t = parse_dispatch_args(&osvec(&[":just", "deploy", "--yes"])).unwrap();
            assert!(!t.yes);
            assert_eq!(t.passthrough, osvec(&["--yes"]));
        }
    }

    mod resolve {
        use super::*;

        #[test]
        fn returns_entry_when_both_layers_present() {
            let map = gear_with_cli(&[("build", cli_entry(&["just", "build"]))]);
            assert_eq!(
                resolve_entry(&map, "just", "build").unwrap().command,
                vec!["just", "build"]
            );
        }

        #[test]
        fn errors_with_available_gears_when_gear_missing() {
            let map = gear_with_cli(&[("build", cli_entry(&["just", "build"]))]);
            let msg = resolve_entry(&map, "missing", "build")
                .unwrap_err()
                .to_string();
            assert!(msg.contains("no gear named `:missing`"), "{msg}");
            assert!(msg.contains("available: just"), "{msg}");
        }

        #[test]
        fn errors_with_sorted_available_entries_when_entry_missing() {
            let map = gear_with_cli(&[
                ("build", cli_entry(&["just", "build"])),
                ("test", cli_entry(&["just", "test"])),
            ]);
            let msg = resolve_entry(&map, "just", "nope").unwrap_err().to_string();
            assert!(msg.contains("no cli entry `nope`"), "{msg}");
            assert!(msg.contains("available: build, test"), "{msg}");
        }

        #[test]
        fn errors_with_none_placeholder_when_gear_has_no_cli() {
            let map = HashMap::from([(
                "web-only".to_owned(),
                Gear {
                    description: "x".into(),
                    ..Default::default()
                },
            )]);
            let msg = resolve_entry(&map, "web-only", "any")
                .unwrap_err()
                .to_string();
            assert!(msg.contains("available: <none>"), "{msg}");
        }
    }

    mod listing {
        use super::*;

        fn just_gear(entries: &[(&str, Option<&str>)]) -> Gear {
            let cli = entries
                .iter()
                .map(|(name, desc)| {
                    (
                        (*name).to_owned(),
                        CliEntry {
                            description: desc.map(str::to_owned),
                            command: vec!["just".into(), (*name).into()],
                            require_confirmation: false,
                            ..Default::default()
                        },
                    )
                })
                .collect();
            Gear {
                description: "Tasks from the project's justfile".into(),
                cli,
                ..Default::default()
            }
        }

        #[test]
        fn header_uses_gear_name_and_description() {
            let listing = format_entry_list("just", &just_gear(&[]));
            assert!(
                listing.starts_with(":just — Tasks from the project's justfile"),
                "{listing}"
            );
        }

        #[test]
        fn lists_entries_alphabetically_with_descriptions() {
            let listing = format_entry_list(
                "just",
                &just_gear(&[
                    ("test", Some("Run tests")),
                    ("build", Some("Build the project")),
                    ("deploy", None),
                ]),
            );
            let lines: Vec<&str> = listing.lines().collect();
            assert_eq!(lines[1], "  build — Build the project");
            assert_eq!(lines[2], "  deploy");
            assert_eq!(lines[3], "  test — Run tests");
        }

        #[test]
        fn empty_cli_map_renders_placeholder() {
            let listing = format_entry_list("just", &just_gear(&[]));
            assert!(listing.contains("(no cli entries)"), "{listing}");
        }
    }

    mod argv {
        use super::*;

        #[test]
        fn concatenates_command_with_passthrough() {
            let argv = build_argv(
                &cli_entry(&["just", "build"]),
                &osvec(&["--release", "-j", "4"]),
            );
            assert_eq!(argv, osvec(&["just", "build", "--release", "-j", "4"]));
        }

        #[test]
        fn passthrough_empty_yields_command_only() {
            assert_eq!(
                build_argv(&cli_entry(&["just", "build"]), &[]),
                osvec(&["just", "build"])
            );
        }
    }

    mod confirmation {
        use super::*;

        fn entry_requiring_confirmation() -> CliEntry {
            CliEntry {
                description: None,
                command: vec!["just".into(), "deploy".into()],
                require_confirmation: true,
                ..Default::default()
            }
        }

        #[test]
        fn safe_entry_runs_without_yes() {
            ensure_confirmed("just", "build", &cli_entry(&["just", "build"]), false).unwrap();
        }

        #[test]
        fn unsafe_entry_with_yes_runs() {
            ensure_confirmed("just", "deploy", &entry_requiring_confirmation(), true).unwrap();
        }

        #[test]
        fn unsafe_entry_without_yes_errors_with_retry_hint() {
            let err = ensure_confirmed("just", "deploy", &entry_requiring_confirmation(), false)
                .expect_err("must refuse");
            let msg = err.to_string();
            assert!(msg.contains(":just deploy"), "{msg}");
            assert!(msg.contains("enw -y :just deploy"), "{msg}");
        }
    }

    mod env {
        use super::*;

        #[test]
        fn project_dir_appends_inner_symlink_name() {
            assert_eq!(
                env_project_dir(Path::new("/tmp/ws"), "my-env"),
                PathBuf::from("/tmp/ws/my-env/my-env")
            );
        }

        #[test]
        fn active_env_name_errors_when_unset() {
            let prior = std::env::var(ACTIVE_ENV_VAR).ok();
            // SAFETY: serial within this file; no parallel readers of ENWIRO_ENV.
            unsafe { std::env::remove_var(ACTIVE_ENV_VAR) };
            let err = active_env_name().unwrap_err();
            assert!(err.to_string().contains("ENWIRO_ENV"));
            if let Some(v) = prior {
                unsafe { std::env::set_var(ACTIVE_ENV_VAR, v) };
            }
        }
    }
}