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
//! CLI aliases — `[aliases]` in `.gwm.toml` plus a user-level fallback
//! at `~/.config/gwm/aliases.toml` (issue #86).
//!
//! `git config` ships with `[alias]`; `gwm` mirrors the shape. Aliases
//! are string-substitution: `gwm <alias>` is expanded to argv tokens
//! before clap parses the command. Three resolution levels coexist:
//!
//! 1. **Built-in** — every `visible_alias` declared on a clap
//! subcommand (`cd → path` from issue #67, `s → switch` from
//! issue #43). Always wins, can never be shadowed by user config.
//! 2. **Repo (`.gwm.toml`)** — declared under `[aliases]`. Follows
//! the repo across machines.
//! 3. **User (`~/.config/gwm/aliases.toml`)** — same `[aliases]`
//! block; survives a machine reinstall but is invisible to the
//! rest of the team. Repo aliases win on name collision.
//!
//! ## Why expansion happens before clap parses
//!
//! Aliases must turn into argv tokens BEFORE clap reaches the
//! subcommand slot — otherwise clap rejects an unknown subcommand
//! before we get a chance to substitute it. The flow is:
//!
//! ```text
//! main() → aliases::load() → aliases::expand_argv() → Cli::parse(expanded)
//! ```
//!
//! This shape mirrors what `git` does with `[alias]` — the dispatcher
//! sees the expanded form, never the alias name.
//!
//! ## What aliases CAN'T do
//!
//! - **No shell pipelines** — `wip = "create feat 0 wip && lazygit"`
//! is rejected at load. Shell metachars (`&&`, `||`, `|`, `;`,
//! backticks) cannot be honoured by an argv-substitution path that
//! hands off to clap. Use a shell alias if that's what you need.
//! - **No recursion** — `wip = "ll"` followed by `ll = "list --
//! format names"` expands once, then dispatches. Matches git's
//! behaviour and keeps the resolution loop linear.
//! - **No shadowing of built-in subcommands** — `[aliases] list =
//! "create feat 0 wip"` is a hard config error. The check uses the
//! compile-time clap CommandFactory, so adding a new subcommand
//! automatically extends the shadow gate.
use crate;
use CommandFactory;
use BTreeMap;
use ;
/// One entry in the built-in alias snapshot. `name` is the clap
/// `visible_alias` (e.g. `cd`); `expansion` is the canonical
/// subcommand it points at (e.g. `path`). Static `&'static str` so the
/// snapshot lives in `BUILT_IN_ALIASES` as a `const` slice (no heap
/// allocation, no lazy init).
/// Built-in aliases — every `#[command(visible_alias = "…")]` declared
/// on the clap `Command` enum. Must stay in lockstep with `src/cli.rs`;
/// a regression test in `tests/aliases_tests.rs` pins the contract.
///
/// The list is short by design — clap visible aliases are the only
/// "built-ins" gwm exposes. They are reachable as bare argv tokens
/// (`gwm cd foo`, `gwm s`) so the shadow check has to know about them
/// to refuse user aliases of the same name.
pub const BUILT_IN_ALIASES: & = &;
/// Resolved alias chain — built-in + repo + user, in lookup-priority
/// order. Built by [`load`] and consumed by [`expand_argv`] (for the
/// pre-clap expansion) and by `gwm aliases list` (for the user-facing
/// summary).
/// Load and validate the alias chain. `repo_root` is the repo root
/// (where `.gwm.toml` lives) — `None` skips the repo step entirely
/// (used by `aliases load` outside a git repo). `user_path` is the
/// user-level file path — `None` falls back to the default
/// `~/.config/gwm/aliases.toml`; an explicit path is honoured even if
/// it doesn't exist (returns empty user map).
///
/// Production entry point: the repo step merges the **real** user-level
/// global config (`global_config_path()`) underneath `.gwm.toml`, exactly
/// like `Config::load_for_repo`. Tests that must not read the runner's
/// real `~/.config/gwm/` should drive [`load_layered`] instead, which
/// takes both the global and user paths explicitly (issue #194).
///
/// Errors:
/// - `GwmError::Config` when a TOML parse fails, an alias shadows a
/// built-in subcommand, an alias value contains shell pipeline
/// metachars (`&&`, `||`, `|`, `;`, backticks), or an alias value
/// is empty.
/// - `GwmError::Io` if the file exists but can't be read.
/// - `GwmError::TomlParse` propagates the underlying serde error.
/// Injectable variant of [`load`] with **no** hidden environment reads
/// (issue #194). The repo step layers `global_path` underneath the repo's
/// `.gwm.toml` via [`crate::config::Config::load_layered`]; `user_path` is
/// taken literally (no `default_user_path` fallback). Passing `None` for
/// both yields a fully hermetic, repo-only resolution — the seam tests use
/// so they never depend on the runner's real `~/.config/gwm/`. Mirrors the
/// `Config::load_for_repo` / `Config::load_layered` pair added in #190.
/// Expand `argv` in place: replace the first non-flag token in
/// `argv[1..]` with its alias expansion (if any). Single-pass — never
/// recurses, never expands a token that maps to a built-in subcommand
/// (defence-in-depth on top of `load`'s shadow check).
///
/// `argv[0]` (the binary name) is preserved unchanged. Trailing
/// arguments after the alias slot are appended after the expansion —
/// `gwm wip --no-bootstrap` with `wip = "create feat 0 wip"` becomes
/// `gwm create feat 0 wip --no-bootstrap`.
///
/// Tokenisation uses `shell_words::split` (POSIX shell quoting). A
/// malformed value (unbalanced quotes) returns the original argv
/// unchanged — the load-time validation should already have caught
/// shell metachars, so reaching this branch means the user
/// hand-edited the config to something pathological. We refuse to
/// dispatch a partial substitution and let clap report the unknown
/// subcommand verbatim.
/// `OsString` counterpart of [`expand_argv`] — accepts the raw
/// `std::env::args_os()` slice without forcing a UTF-8 round-trip on
/// every token.
///
/// Why this matters: `std::env::args()` panics on the first non-UTF-8
/// argv entry (Linux/macOS allow arbitrary bytes in argv). Clap parses
/// `OsString` natively via `args_os`, and the panic in `main` was a
/// regression vs. that default. We mirror the `expand_argv` logic on
/// `OsString` and only attempt UTF-8 conversion on the alias-slot
/// token — if it is not valid UTF-8 it cannot match an alias name
/// (alias keys are `String` by construction in `ResolvedAliases`), so
/// the argv is returned unchanged and clap surfaces the unknown
/// subcommand verbatim.
///
/// Flag detection is byte-level: a leading `b'-'` is unambiguous in
/// every valid argv encoding (the byte is ASCII, so it cannot appear
/// mid-UTF-8-sequence), which means we can scan past flags without
/// decoding them.
/// Inspect the first byte of an `OsStr` to decide whether the token
/// is a flag (leading `-`). The byte is examined in the platform's
/// native argv encoding — ASCII bytes survive both UTF-8 (Unix) and
/// WTF-8 (Windows) round-trips intact, so a simple `as_encoded_bytes`
/// check is correct on both targets.
/// Default location of the user-level alias file, resolved the same way as
/// the global config (`~/.config/gwm/config.toml`, issues #372/#374): an
/// explicit `$XDG_CONFIG_HOME` wins outright, otherwise the first existing of
/// the documented `~/.config/gwm/aliases.toml` then the platform config dir
/// (`Application Support` on macOS, `%APPDATA%` on Windows); the canonical
/// `~/.config` path when neither exists. Returns `None` on systems where no
/// home resolves (sandboxed CI, containers without `$HOME`). Delegates to the
/// shared [`crate::config::resolve_gwm_config_file`] so the alias and config
/// resolvers can't drift.
///
/// `var_os`, not `var`: a non-UTF-8 `$XDG_CONFIG_HOME` (legal on Unix) must
/// still win outright rather than be dropped and masked by `~/.config`.
/// Internal shape of the user-level alias file. Mirrors the
/// `[aliases]` block in `.gwm.toml` so the user can copy-paste
/// between the two without remembering whether the key prefix
/// differs.
/// Built-in subcommand names. Resolved from the clap `Command` factory
/// at call time — adding a new subcommand to `cli::Command` extends
/// this set automatically. Memoised inside `validate_aliases` per
/// call; the slice form here is just for the const-time lookup in
/// `ResolvedAliases::lookup` (subcommands hard-coded so the lookup
/// path doesn't need to allocate). Adding a new subcommand requires
/// adding its name here AND `tests/aliases_tests.rs` will catch a
/// miss via the canary test.
const BUILT_IN_SUBCOMMANDS: & = &;
/// Validate a user-supplied alias map. Used by both
/// [`crate::config::Config::validate_aliases`] (repo-level) and the
/// user-level loader, so the rules stay symmetric.
///
/// `source_label` is woven into the error message ("`.gwm.toml`
/// `[aliases]`" vs `"/home/x/.config/gwm/aliases.toml [aliases]"`)
/// so the user knows which file to edit.
///
/// Rules enforced (matching the issue contract):
///
/// 1. Alias name must NOT shadow a built-in subcommand or a
/// built-in visible alias. The check uses the runtime clap
/// `CommandFactory` so it's always in sync with `src/cli.rs`.
/// 2. Alias value must NOT be empty after trimming.
/// 3. Alias value must NOT contain shell pipeline metachars:
/// `&&`, `||`, `|`, `;`, backticks. These would silently lose
/// semantics under argv substitution — the user must reach for
/// a shell alias instead.
/// Forbidden shell metachars in alias values. The list intentionally
/// stays short — anything that even hints at "shell pipeline" gets
/// rejected. A user trying to do `path | pbcopy` hits the gate and
/// reads the error pointing at shell aliases as the right tool.
const SHELL_METACHARS: & = &;