gwm-cli 1.6.1

git worktree manager — TUI + CLI, native libgit2, per-repo bootstrap
Documentation
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
use crate::config::{BootstrapConfig, CommandStep, Config, CopyStep, Guard, NoSymlink};
use crate::error::{GwmError, Result};
use regex::Regex;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::Command;

#[derive(Debug, Clone)]
pub struct BootstrapReport {
  pub steps: Vec<StepResult>,
}

#[derive(Debug, Clone)]
pub struct StepResult {
  pub label: String,
  pub status: StepStatus,
  pub detail: String,
}

impl StepResult {
  /// `Ok` with an empty `detail` — the most common shape (the step
  /// label alone says everything the user needs).
  pub fn ok(label: impl Into<String>) -> Self {
    Self {
      label: label.into(),
      status: StepStatus::Ok,
      detail: String::new(),
    }
  }

  /// `Ok` with an explanatory `detail` line (e.g. "copied from
  /// <src>"). Kept as a distinct constructor rather than overloading
  /// `ok(label, detail)` so the "no detail by default" semantics of
  /// `ok` stay unambiguous at the call sites.
  pub fn ok_with_detail(label: impl Into<String>, detail: impl Into<String>) -> Self {
    Self {
      label: label.into(),
      status: StepStatus::Ok,
      detail: detail.into(),
    }
  }

  /// `Skipped` with the reason the step was bypassed (e.g.
  /// "destination already exists", "when condition false").
  pub fn skipped(label: impl Into<String>, reason: impl Into<String>) -> Self {
    Self {
      label: label.into(),
      status: StepStatus::Skipped,
      detail: reason.into(),
    }
  }

  /// `Warning` with the user-visible message. Used by guards
  /// substituting from `.env.example` and the no-symlink remediation
  /// path — the step proceeded but the user should know what changed.
  pub fn warning(label: impl Into<String>, message: impl Into<String>) -> Self {
    Self {
      label: label.into(),
      status: StepStatus::Warning,
      detail: message.into(),
    }
  }

  /// `Failed` with the user-visible error detail. The detail SHOULD
  /// include enough context for the user to fix the problem without
  /// re-running with extra verbosity (filename, errno, guard name).
  pub fn failed(label: impl Into<String>, message: impl Into<String>) -> Self {
    Self {
      label: label.into(),
      status: StepStatus::Failed,
      detail: message.into(),
    }
  }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StepStatus {
  Ok,
  Skipped,
  Warning,
  Failed,
}

impl StepStatus {
  /// Canonical single-character glyph for each variant. Used by both
  /// `cli::print_report` (plain stdout) and `tui::ui::render_bootstrap`
  /// (styled `Span`); centralising the mapping here keeps the two
  /// renderers in lock-step (issue #106).
  pub fn sigil(&self) -> &'static str {
    match self {
      StepStatus::Ok => "",
      StepStatus::Skipped => "·",
      StepStatus::Warning => "!",
      StepStatus::Failed => "",
    }
  }
}

pub struct BootstrapCtx<'a> {
  pub main_repo: &'a Path,
  pub worktree: &'a Path,
  pub config: &'a Config,
}

pub fn run(ctx: &BootstrapCtx<'_>) -> Result<BootstrapReport> {
  let mut report = BootstrapReport { steps: Vec::new() };
  let bs = &ctx.config.bootstrap;

  run_core_steps(ctx, bs, &mut report);
  run_commands(ctx, bs, &mut report);

  Ok(report)
}

pub fn run_core(ctx: &BootstrapCtx<'_>) -> Result<BootstrapReport> {
  let mut report = BootstrapReport { steps: Vec::new() };
  let bs = &ctx.config.bootstrap;

  run_core_steps(ctx, bs, &mut report);

  Ok(report)
}

fn run_core_steps(ctx: &BootstrapCtx<'_>, bs: &BootstrapConfig, report: &mut BootstrapReport) {
  // Order matters (issue #93): `run_no_symlinks` strips any declared
  // symlinked targets BEFORE `run_copies` opens them for writing.
  // Reversed, an attacker-planted symlink at a copy destination
  // redirects the `fs::copy` write outside the worktree — a write-
  // anywhere primitive triggered by `gwm bootstrap` alone.
  run_no_symlinks(ctx, bs, report);
  run_copies(ctx, bs, report);
}

fn run_copies(ctx: &BootstrapCtx<'_>, bs: &BootstrapConfig, report: &mut BootstrapReport) {
  for step in &bs.copy {
    let label = format!("copy {} -> {}", step.from, step.to);
    let src = ctx.main_repo.join(&step.from);
    let dst = ctx.worktree.join(&step.to);

    // Runtime defence-in-depth (issue #94): `Config::load_for_repo`
    // rejects `..` / absolute paths in `step.to` at load time, but
    // callers can hand `bootstrap::run` a `Config` value built by
    // hand (test harnesses, future programmatic embeds). Re-check
    // here that `dst` resolves under the worktree before any write.
    if let Err(e) = ensure_within(ctx.worktree, &dst) {
      report.steps.push(StepResult::failed(
        label,
        format!("destination outside worktree: {}", e),
      ));
      continue;
    }

    // Single stat on `dst` (issue #93): `symlink_metadata` does NOT
    // follow symlinks (unlike `Path::exists`), and reusing one result
    // for every branch below avoids the TOCTOU window of a second stat.
    //
    //   Ok(symlink)     → Failed (defence in depth — symlinks at a
    //                     declared copy dst are suspicious enough to
    //                     surface, even when [[bootstrap.no_symlink]]
    //                     didn't list them)
    //   Ok(other)       → Skipped (regular file or directory already
    //                     populated — leave the user's edits alone)
    //   Err(NotFound)   → fall through to the copy / fallback chain
    //   Err(other)      → Failed (permission / IO error masking the
    //                     filesystem state — never silently swallow)
    match std::fs::symlink_metadata(&dst) {
      Ok(meta) if meta.file_type().is_symlink() => {
        report.steps.push(StepResult::failed(
          label,
          format!(
            "refusing to copy: destination {} is a symlink — would redirect the write outside the worktree (issue #93)",
            dst.display()
          ),
        ));
        continue;
      }
      Ok(_) => {
        report.steps.push(StepResult::skipped(
          label,
          "destination already exists, leaving it alone",
        ));
        continue;
      }
      Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
      Err(e) => {
        report.steps.push(StepResult::failed(
          label,
          format!(
            "failed to stat destination {}: {} — refusing to proceed with unknown filesystem state",
            dst.display(),
            e
          ),
        ));
        continue;
      }
    }

    if !src.exists() {
      match resolve_missing(step, bs, &dst) {
        Some(res) => report.steps.push(StepResult { label, ..res }),
        None => {
          if step.required {
            report.steps.push(StepResult::failed(label, "required source missing"));
          } else {
            report.steps.push(StepResult::skipped(label, "optional source missing"));
          }
        }
      }
      continue;
    }

    // Run guards before copying.
    match guard_match(step, bs, &src) {
      Ok(Some(g)) => {
        handle_guard_match(&g, &src, &dst, ctx, report, &label);
        continue;
      }
      Ok(None) => {}
      Err(detail) => {
        report.steps.push(StepResult::failed(label, detail));
        continue;
      }
    }

    match copy_no_follow(&src, &dst) {
      Ok(()) => report.steps.push(StepResult::ok_with_detail(
        label,
        format!("copied from {}", src.display()),
      )),
      Err(e) => report
        .steps
        .push(StepResult::failed(label, format!("copy failed: {}", e))),
    }
  }
}

fn resolve_missing(step: &CopyStep, bs: &BootstrapConfig, dst: &Path) -> Option<StepResult> {
  let mode = step.fallback.as_deref().unwrap_or("skip");
  match mode {
    "inline" => {
      // Find a fallback content keyed by the `to` file basename or step.fallback alias.
      let key = key_from_to(&step.to);
      let fb = bs.fallback.get(&key)?;
      match write_no_follow(dst, fb.content.as_bytes()) {
        Ok(()) => Some(StepResult::warning(
          "",
          format!("source missing — wrote inline fallback to {}", dst.display()),
        )),
        Err(e) => Some(StepResult::failed("", format!("inline fallback write failed: {}", e))),
      }
    }
    "abort" => Some(StepResult::failed("", "source missing and fallback=abort")),
    _ => None,
  }
}

fn key_from_to(to: &str) -> String {
  // ".env.testing" → "env_testing"
  to.trim_start_matches('.').replace(['.', '-'], "_")
}

/// Evaluate the configured guards against `src`'s contents.
///
/// Returns:
///   - `Ok(Some(guard))` — a guard tripped on a denied pattern; the
///     caller routes to `handle_guard_match` to apply `on_match`.
///   - `Ok(None)` — no guard tripped; copy proceeds.
///   - `Err(detail)` — a `deny_patterns` entry failed to compile.
///     `Config::load_for_repo` is supposed to have caught this at
///     load time (issue #96), so reaching this branch means the
///     `Config` value came from a code path that bypassed the
///     loader (test fixture, programmatic constructor, future API).
///     Fail-closed: the caller reports a `Failed` step and the copy
///     is refused, mirroring the abort path for a true match. A
///     refusal mechanism whose pattern set is partially broken must
///     never silently pass — see issue #96.
fn guard_match(step: &CopyStep, bs: &BootstrapConfig, src: &Path) -> std::result::Result<Option<Guard>, String> {
  if step.guards.is_empty() {
    return Ok(None);
  }
  let Ok(content) = std::fs::read_to_string(src) else {
    return Ok(None);
  };
  for guard_name in &step.guards {
    let Some(guard) = bs.guard.iter().find(|g| &g.name == guard_name) else {
      return Ok(None);
    };
    for pat in &guard.deny_patterns {
      match Regex::new(pat) {
        Ok(re) => {
          if re.is_match(&content) {
            return Ok(Some(guard.clone()));
          }
        }
        Err(e) => {
          return Err(format!(
            "guard '{}' deny_pattern {:?} failed to compile at evaluation time — \
             Config bypassed Config::load_for_repo (#96)? regex: {}",
            guard.name, pat, e
          ));
        }
      }
    }
  }
  Ok(None)
}

fn handle_guard_match(
  guard: &Guard,
  src: &Path,
  dst: &Path,
  ctx: &BootstrapCtx<'_>,
  report: &mut BootstrapReport,
  label: &str,
) {
  match guard.on_match.as_str() {
    "seed-from-example" => {
      let example_rel = guard.example_file.as_deref().unwrap_or(".env.example");
      let example_src = ctx.main_repo.join(example_rel);
      // Runtime defence-in-depth (issue #94): refuse to read an
      // example_file that resolves outside `ctx.main_repo`. Mirrors
      // the dst-side check in `run_copies`; the `Config` loader
      // rejects this at load time, this branch covers hand-built
      // configs.
      if let Err(e) = ensure_within(ctx.main_repo, &example_src) {
        report.steps.push(StepResult::failed(
          label,
          format!(
            "guard '{}' example_file outside main repo: {} (traversal rejected, issue #94)",
            guard.name, e
          ),
        ));
        return;
      }
      if example_src.exists() {
        match copy_no_follow(&example_src, dst) {
          Ok(_) => report.steps.push(StepResult::warning(
            label,
            format!(
              "guard '{}' tripped on {} — seeded {} from {} (edit before use)",
              guard.name,
              src.display(),
              dst.display(),
              example_src.display()
            ),
          )),
          Err(e) => report.steps.push(StepResult::failed(
            label,
            format!("guard '{}' seed-from-example failed: {}", guard.name, e),
          )),
        }
      } else {
        report.steps.push(StepResult::failed(
          label,
          format!(
            "guard '{}' tripped and no example_file {} available",
            guard.name,
            example_src.display()
          ),
        ));
      }
    }
    _ => {
      // abort
      report.steps.push(StepResult::failed(
        label,
        format!("guard '{}' tripped on {} — abort", guard.name, src.display()),
      ));
    }
  }
}

fn run_no_symlinks(ctx: &BootstrapCtx<'_>, bs: &BootstrapConfig, report: &mut BootstrapReport) {
  for ns in &bs.no_symlink {
    let label = format!("no-symlink {}", ns.path);
    let target: PathBuf = ctx.worktree.join(&ns.path);
    handle_no_symlink(&label, &target, report);
  }
  // Also enforce common defaults if not declared explicitly.
  for default in ["vendor", "node_modules"] {
    if bs.no_symlink.iter().any(|n: &NoSymlink| n.path == default) {
      continue;
    }
    let target = ctx.worktree.join(default);
    if target.is_symlink() {
      handle_no_symlink(&format!("no-symlink {} (auto)", default), &target, report);
    }
  }
}

fn handle_no_symlink(label: &str, target: &Path, report: &mut BootstrapReport) {
  if !target.exists() && !target.is_symlink() {
    report.steps.push(StepResult::skipped(label, "not present"));
    return;
  }
  if target.is_symlink() {
    match std::fs::remove_file(target) {
      Ok(_) => report.steps.push(StepResult::warning(
        label,
        format!("removed symlink {}", target.display()),
      )),
      Err(e) => report.steps.push(StepResult::failed(
        label,
        format!("failed to remove symlink {}: {}", target.display(), e),
      )),
    }
  } else {
    report
      .steps
      .push(StepResult::ok_with_detail(label, "real directory, ok"));
  }
}

fn run_commands(ctx: &BootstrapCtx<'_>, bs: &BootstrapConfig, report: &mut BootstrapReport) {
  for step in &bs.command {
    let label = format!("run {}", step.name);
    if let Some(ref guard) = step.when {
      if !evaluate_when(guard, ctx.worktree) {
        report
          .steps
          .push(StepResult::skipped(label, format!("when condition '{}' false", guard)));
        continue;
      }
    }
    match exec_shell(step, ctx.worktree) {
      Ok(output) => report
        .steps
        .push(StepResult::ok_with_detail(label, trailing_lines(&output, 3))),
      Err(e) => report.steps.push(StepResult::failed(label, e.to_string())),
    }
  }
}

/// Evaluate a `[[bootstrap.command]].when` expression against the given
/// worktree. Supports the keyword predicates `file_exists:`, `cmd_exists:`,
/// `env_set:`, `env_eq:`, `glob_exists:`, plus the boolean operators `!`,
/// `&&`, `||` with conventional precedence (`!` > `&&` > `||`). Unknown
/// keyword predicates default to `true` so older configs keep running while
/// the doctor surfaces them as warnings.
pub fn evaluate_when(expr: &str, cwd: &Path) -> bool {
  let tokens = tokenize_when(expr);
  let mut parser = WhenParser {
    tokens: &tokens,
    pos: 0,
    cwd,
  };
  parser.parse_or()
}

/// Return every atom string contained in a `when` expression, dropping
/// the boolean operators. Callers (e.g. `doctor::check_when_predicates`)
/// can then validate each atom independently — `w.starts_with(prefix)`
/// on the raw expression misses negated atoms (`!env_set:CI`) and
/// unsupported keywords sitting on the RHS of `&&` / `||`.
pub fn when_atoms(expr: &str) -> Vec<String> {
  tokenize_when(expr)
    .into_iter()
    .filter_map(|t| match t {
      WhenToken::Atom(s) => Some(s),
      _ => None,
    })
    .collect()
}

#[derive(Debug, PartialEq, Eq)]
enum WhenToken {
  Atom(String),
  Not,
  And,
  Or,
}

fn tokenize_when(expr: &str) -> Vec<WhenToken> {
  let bytes = expr.as_bytes();
  let mut tokens = Vec::new();
  let mut i = 0;
  while i < bytes.len() {
    let c = bytes[i];
    if c.is_ascii_whitespace() {
      i += 1;
      continue;
    }
    if c == b'!' {
      tokens.push(WhenToken::Not);
      i += 1;
      continue;
    }
    if c == b'&' && bytes.get(i + 1) == Some(&b'&') {
      tokens.push(WhenToken::And);
      i += 2;
      continue;
    }
    if c == b'|' && bytes.get(i + 1) == Some(&b'|') {
      tokens.push(WhenToken::Or);
      i += 2;
      continue;
    }
    let start = i;
    while i < bytes.len() {
      let b = bytes[i];
      if b.is_ascii_whitespace() {
        break;
      }
      if b == b'&' && bytes.get(i + 1) == Some(&b'&') {
        break;
      }
      if b == b'|' && bytes.get(i + 1) == Some(&b'|') {
        break;
      }
      i += 1;
    }
    tokens.push(WhenToken::Atom(expr[start..i].to_string()));
  }
  tokens
}

struct WhenParser<'a> {
  tokens: &'a [WhenToken],
  pos: usize,
  cwd: &'a Path,
}

impl<'a> WhenParser<'a> {
  fn peek(&self) -> Option<&WhenToken> {
    self.tokens.get(self.pos)
  }

  fn parse_or(&mut self) -> bool {
    let mut acc = self.parse_and();
    while let Some(WhenToken::Or) = self.peek() {
      self.pos += 1;
      let rhs = self.parse_and();
      acc = acc || rhs;
    }
    acc
  }

  fn parse_and(&mut self) -> bool {
    let mut acc = self.parse_not();
    while let Some(WhenToken::And) = self.peek() {
      self.pos += 1;
      let rhs = self.parse_not();
      acc = acc && rhs;
    }
    acc
  }

  fn parse_not(&mut self) -> bool {
    if let Some(WhenToken::Not) = self.peek() {
      self.pos += 1;
      return !self.parse_not();
    }
    self.parse_atom()
  }

  fn parse_atom(&mut self) -> bool {
    match self.tokens.get(self.pos) {
      Some(WhenToken::Atom(s)) => {
        self.pos += 1;
        eval_when_atom(s, self.cwd)
      }
      // Empty expression or a dangling operator: fall back to true to
      // match the "unknown predicate" contract — a config we can't
      // understand should not silently skip every command.
      _ => true,
    }
  }
}

fn eval_when_atom(atom: &str, cwd: &Path) -> bool {
  // Each atom-argument is trimmed to absorb any Unicode whitespace that
  // the ASCII-only tokenizer left glued to the value. Preserves the
  // legacy `file_exists:` tolerance from the pre-tokenizer evaluator.
  if let Some(rest) = atom.strip_prefix("file_exists:") {
    return cwd.join(rest.trim()).exists();
  }
  if let Some(rest) = atom.strip_prefix("cmd_exists:") {
    return which::which(rest.trim()).is_ok();
  }
  if let Some(rest) = atom.strip_prefix("env_set:") {
    return std::env::var(rest.trim()).is_ok();
  }
  if let Some(rest) = atom.strip_prefix("env_eq:") {
    let Some((name, value)) = rest.split_once('=') else {
      return false;
    };
    return std::env::var(name.trim()).ok().as_deref() == Some(value);
  }
  if let Some(pattern) = atom.strip_prefix("glob_exists:") {
    return glob_exists(pattern.trim(), cwd);
  }
  // Unknown keyword: default to true so we don't silently neutralise a
  // command the user clearly wanted to run.
  true
}

fn glob_exists(pattern: &str, cwd: &Path) -> bool {
  let full = cwd.join(pattern);
  let Some(full_str) = full.to_str() else {
    return false;
  };
  match glob::glob(full_str) {
    Ok(mut iter) => iter.any(|r| r.is_ok()),
    Err(_) => false,
  }
}

fn exec_shell(step: &CommandStep, cwd: &Path) -> Result<String> {
  let mut cmd = Command::new("sh");
  cmd.arg("-c").arg(&step.run).current_dir(cwd);
  for (k, v) in &step.env {
    cmd.env(k, v);
  }
  // The `bootstrap step '…'` prefix used to live in the variant's
  // Display impl; it moved into the data string when the variant was
  // generalised in #65 so other subcommands (gwm tmux / gwm zellij)
  // don't inherit a misleading "bootstrap" prefix on their own
  // spawn failures.
  // Record on the Command Logs transcript (issue #226): a bootstrap step
  // is an external command gwm ran. The logged line is the user-authored
  // shell script, not the `sh -c` wrapper, so the transcript reads like the
  // command the user wrote.
  let out = crate::command_log::run_logged(&mut cmd, step.run.clone())
    .map_err(|e| GwmError::CommandFailed(format!("bootstrap step '{}': {}", step.name, e)))?;
  let stdout = String::from_utf8_lossy(&out.stdout).to_string();
  let stderr = String::from_utf8_lossy(&out.stderr).to_string();
  if !out.status.success() {
    return Err(GwmError::CommandFailed(format!(
      "bootstrap step '{}' exited with {}\n{}",
      step.name,
      out.status,
      if stderr.is_empty() { stdout } else { stderr }
    )));
  }
  Ok(if stdout.is_empty() { stderr } else { stdout })
}

pub fn trailing_lines(s: &str, n: usize) -> String {
  let lines: Vec<&str> = s.lines().collect();
  let start = lines.len().saturating_sub(n);
  lines[start..].join("\n")
}

// --------------------------------------------------------------------------
// TOCTOU-safe write primitives (issue #93 follow-up)
// --------------------------------------------------------------------------
//
// The `symlink_metadata` guard at the top of `run_copies` closes the
// "symlink already exists at copy time" attack vector, but a small
// race window remained between the stat and the subsequent `fs::copy`
// (or `fs::write` in the inline-fallback path): an attacker with
// concurrent write access to the worktree could plant a symlink in
// the µs after the stat, redirecting the write through `O_CREAT |
// O_TRUNC` (both of which follow symlinks). These helpers close that
// window by opening `dst` with `O_NOFOLLOW | O_CREAT | O_EXCL` so
// that:
//
//   - A symlink at `dst` causes `open()` to fail with `ELOOP`.
//   - Any other entry (regular file, dir, FIFO) causes `EEXIST` —
//     `create_new(true)` maps to `O_EXCL` on unix and `CREATE_NEW`
//     on Windows.
//   - On a fresh `dst`, the file is created and truncated atomically
//     under the same fd handed to `write_all`.
//
// On non-unix platforms `O_NOFOLLOW` is unavailable in `std`; the
// `create_new(true)` half still holds, and the bug class flagged on
// #93 is unix-only anyway (Windows symlinks require admin and aren't
// the realistic attack surface for `gwm bootstrap`).

/// Copy the contents of `src` into `dst` as a fresh regular file,
/// refusing to follow any symlink at `dst`. `src` permissions are
/// preserved on unix.
///
/// Returns the standard `io::Result` so callers can format the errno
/// into their step report without losing the error kind. The `dst`
/// is opened with `O_NOFOLLOW | O_CREAT | O_EXCL` on unix; a symlink
/// (broken or live) at `dst` triggers `ELOOP`, anything else
/// pre-existing triggers `EEXIST`.
pub fn copy_no_follow(src: &Path, dst: &Path) -> std::io::Result<()> {
  let mut buf = Vec::new();
  std::fs::File::open(src)?.read_to_end(&mut buf)?;
  #[cfg(unix)]
  let src_perms = std::fs::metadata(src)?.permissions();
  write_no_follow(dst, &buf)?;
  #[cfg(unix)]
  std::fs::set_permissions(dst, src_perms)?;
  Ok(())
}

/// Verify that `path` resolves to a location inside `base` (issue
/// #94). Both `path` and `base` may contain symlinks; both are
/// canonicalized so the check operates on real on-disk identities.
///
/// `path` typically does NOT exist yet (it's a freshly-computed copy
/// destination), so we canonicalize the deepest existing ancestor
/// and check that the canonical ancestor still falls under
/// `base.canonicalize()`. This catches `..` traversal, absolute
/// paths, and symlinks in intermediate components that redirect
/// outside `base`.
///
/// Returns `Err` with `ErrorKind::InvalidInput` when the path
/// escapes `base`; surrounding code surfaces the error verbatim
/// in the step report so the user knows which field went wrong.
///
/// **TOCTOU note**: a residual window exists between this ancestor
/// canonicalization and the final write — an attacker who can plant
/// a symlink at an intermediate component between the two would
/// re-route the resolved path. That gap is closed by the
/// `O_NOFOLLOW`-based writers from issue #93 (`copy_no_follow` /
/// `write_no_follow`): even if the path mutates post-check, the
/// final `open` returns `ELOOP` / `EEXIST` rather than writing
/// through. `ensure_within` and the no-follow writers are
/// complementary; neither alone is sufficient.
fn ensure_within(base: &Path, path: &Path) -> std::io::Result<()> {
  let base_canon = base.canonicalize()?;
  let mut anc: &Path = path;
  let canon_anc = loop {
    if let Ok(c) = anc.canonicalize() {
      break c;
    }
    match anc.parent() {
      Some(p) if !p.as_os_str().is_empty() => anc = p,
      _ => {
        return Err(std::io::Error::new(
          std::io::ErrorKind::InvalidInput,
          format!("cannot resolve any ancestor of {:?}", path),
        ));
      }
    }
  };
  if !canon_anc.starts_with(&base_canon) {
    return Err(std::io::Error::new(
      std::io::ErrorKind::InvalidInput,
      format!(
        "{:?} resolves outside {:?} — '..' traversal, absolute path, or symlinked intermediate component rejected (issue #94)",
        path, base_canon
      ),
    ));
  }
  Ok(())
}

/// Companion to [`copy_no_follow`] for callers that already hold the
/// payload in memory (e.g. the inline-fallback branch in
/// [`resolve_missing`]). Same TOCTOU-closing semantics: `dst` must
/// not exist and must not be a symlink, or `open()` fails.
pub fn write_no_follow(dst: &Path, bytes: &[u8]) -> std::io::Result<()> {
  let mut opts = std::fs::OpenOptions::new();
  opts.write(true).create_new(true);
  #[cfg(unix)]
  {
    use std::os::unix::fs::OpenOptionsExt;
    opts.custom_flags(libc::O_NOFOLLOW);
  }
  let mut f = opts.open(dst)?;
  f.write_all(bytes)?;
  Ok(())
}