monochromatic-git-policy-cli 0.6.0

Repository-owned Git policy wrapper: forwards Git commands and checks commits against configured policies.
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
//! What:
//!  Which source paths the linked-worktree copy selects:
//!  the ignored roots Git reports under the standard exclusion stack,
//!  the ignored special entries (sockets, FIFOs, devices) Git's listing omits,
//!  and the validation every repository path passes before it touches the filesystem.
//! Why:
//!  Git decides what is ignored; the copy only adds the entries Git's index-oriented listing
//!  cannot report, and it never trusts a path that could leave the worktree.
//!
//! In TS you'd write (pseudocode):
//! ```ts
//! const roots = await readIgnoredRoots({ sourceRoot, gitPath, excludedRoots });
//! ```

use crate::transaction_git::{GitContext, GitRequest, run_git};
use crate::worktree_copy_prune::Prune;
use crate::worktree_copy_error::{WorktreeCopyError, raw_failure, raw_failure_of};
use crate::json_record::quote;
use std::cmp::Ordering;
use std::path::{Path, PathBuf};

/// What:
///  The Git directory marker that `ls-files --directory` appends to ignored directories.
/// Why:
///   The copy works on the directory itself, so the marker is removed before validation.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// const DIRECTORY_SUFFIX = '/';
/// ```
const DIRECTORY_SUFFIX: char = '/';

/// What:
///  The private stage prefix the copy reserves; no selected path may contain a component that starts with it.
/// Why:
///   A selected path that is a private stage would copy the copy into itself.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// export const STAGE_PREFIX = '.cli-git-worktree-copy-';
/// ```
pub const STAGE_PREFIX: &str = ".cli-git-worktree-copy-";

/// What:
///  Whether a repository path equals or descends from another repository path.
/// Why:
///   Comparison is by whole components, so `cache2` is not inside `cache`.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// (candidate === parent) || candidate.startsWith(`${parent}/`)
/// ```
pub fn repository_path_within(candidate: &str, parent: &str) -> bool {
    // `||` keeps the exact-equality case and the component-prefix case in one expression.
    return candidate == parent || candidate.starts_with(format!("{parent}/").as_str());
}

/// What:
///  Whether a repository path component is empty, `.` or `..`.
/// Why:
///   Such a component could leave the repository, so a path with one is unsafe.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// component === '' || component === '.' || component === '..'
/// ```
fn is_unsafe_component(component: &str) -> bool {
    return component.is_empty() || component == "." || component == "..";
}

/// What:
///  Whether a repository path is at or below any of the root paths.
/// Why:
///   A root already selected covers everything below it.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// roots.some((root) => repositoryPathWithin(candidate, root))
/// ```
fn within_any_root(candidate: &str, roots: &[String]) -> bool {
    for root in roots {
        if repository_path_within(candidate, root.as_str()) {
            return true;
        }
    }
    return false;
}

/// What:
///  Validates one slash-separated path that Git reported before it is joined to a filesystem root.
/// Why:
///   An empty, absolute, `.` or `..` component could select a path outside the worktree.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// function assertSafeRepositoryPath(repositoryPath: string): void;
/// ```
pub fn assert_safe_repository_path(repository_path: &str) -> Result<(), WorktreeCopyError> {
    let unsafe_path: bool = repository_path.is_empty()
        || repository_path.starts_with('/')
        || Path::new(repository_path).is_absolute()
        || repository_path.split('/').any(is_unsafe_component);
    if unsafe_path {
        return Err(WorktreeCopyError(format!(
            "monochromatic-git-policy-cli: Git returned unsafe ignored path {}.",
            quote(repository_path)
        )));
    }
    return Ok(());
}

/// What:
///  The native path of one validated repository path under a filesystem root.
/// Why:
///   Every filesystem access of the copy goes through this join, so the validation cannot be skipped.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// join(root, ...repositoryPath.split('/'));
/// ```
pub fn filesystem_path(root: &Path, repository_path: &str) -> Result<PathBuf, WorktreeCopyError> {
    assert_safe_repository_path(repository_path)?;
    let mut path: PathBuf = root.to_path_buf();
    for component in repository_path.split('/') {
        path.push(component);
    }
    return Ok(path);
}

/// What:
///  Sorts strings the way JavaScript's default `toSorted` does: by UTF-16 code units.
/// Why:
///   Manifest and journal order must match the incumbent's, which differs from byte order
///  only for supplementary-plane characters.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// [...values].toSorted()
/// ```
pub fn js_order(left: &str, right: &str) -> Ordering {
    return left.encode_utf16().cmp(right.encode_utf16());
}

/// What:
///  Order two names the way JavaScript's default sort does, for a sort of owned names.
/// Why:
///   `sort_by` hands its function references to the items, and a generic function over `AsRef<str>` takes them without a closure.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// names.sort()
/// ```
pub fn by_js_order<Name: AsRef<str>>(left: &Name, right: &Name) -> std::cmp::Ordering {
    return js_order(left.as_ref(), right.as_ref());
}

/// What:
///  Keeps the outermost of several ignored roots, dropping every root under another one.
/// Why:
///   Copying a parent already copies its descendants, so a second copy would duplicate work and entries.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// function collapseIgnoredRoots(paths: readonly string[]): readonly string[];
/// ```
fn collapse_ignored_roots(paths: &[String]) -> Vec<String> {
    let mut candidates: Vec<String> = paths.to_vec();
    candidates.sort_by(by_js_order);
    candidates.dedup();
    let mut roots: Vec<String> = Vec::new();
    for candidate in candidates {
        let owned: bool = within_any_root(candidate.as_str(), roots.as_slice());
        if !owned {
            roots.push(candidate);
        }
    }
    return roots;
}

/// What:
///  Whether Git's standard exclusion stack ignores one special entry.
/// Why:
///   `check-ignore --no-index` answers the same question for a path Git's listing never names;
///  exit status 1 is "not ignored" and every other failure is fatal.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// await runMetadataGit({ args: ['-C', sourceRoot, 'check-ignore', '--no-index', '--', repositoryPath] })
/// ```
fn is_ignored_special_path(
    context: &GitContext,
    source_root: &Path,
    repository_path: &str,
) -> Result<bool, WorktreeCopyError> {
    let request: GitRequest = GitRequest {
        cwd: source_root.to_path_buf(),
        arguments: vec![
            "check-ignore".into(),
            "--no-index".into(),
            "--".into(),
            repository_path.into(),
        ],
        without_prefix: true,
        ..GitRequest::default()
    };
    let output = run_git(context, &request).map_err(raw_failure_of)?;
    // `match` on the exit code: 0 is ignored, 1 is not ignored, anything else is a failure.
    match output.code {
        Some(0) => return Ok(true),
        Some(1) => return Ok(false),
        _ => {
            return Err(raw_failure(&String::from_utf8_lossy(
                output.stderr.as_slice(),
            )));
        }
    }
}

/// What:
///  Whether a byte is NUL, the end of each name in Git's `-z` output.
/// Why:
///   Git's listings are split on it, and a path may hold any other byte.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// byte === 0
/// ```
fn is_nul_byte(byte: &u8) -> bool {
    return *byte == 0;
}

/// What:
///  Whether a NUL-separated listing holds `wanted` as one of its names.
/// Why:
///   Git lists a directory's files rather than the directory, so only an exact name is a file Git ignores.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// listing.split('\0').includes(wanted)
/// ```
fn lists_exactly(listing: &[u8], wanted: &[u8]) -> bool {
    for field in listing.split(is_nul_byte) {
        if field == wanted {
            return true;
        }
    }
    return false;
}

/// What:
///  Whether a native path lies at or under one of the excluded absolute directories.
/// Why:
///   Walks skip registered worktrees and the private stage, so they never copy themselves.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// isFilesystemPathWithin({ candidate, parent })
/// ```
fn is_excluded(candidate: &Path, excluded_roots: &[PathBuf]) -> bool {
    for root in excluded_roots {
        if candidate.starts_with(root.as_path()) {
            return true;
        }
    }
    return false;
}

/// What:
///  One pending directory of the special-entry walk, with its repository path.
/// Why:
///   The walk is an explicit stack so depth cannot exhaust the call stack.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// const pending: string[] = ['.'];
/// ```
fn special_entries(
    context: &GitContext,
    source_root: &Path,
    selected_roots: &[String],
    excluded_roots: &[PathBuf],
) -> Result<Vec<String>, WorktreeCopyError> {
    let mut pending: Vec<String> = vec![String::from(".")];
    let mut special_paths: Vec<String> = Vec::new();
    while let Some(current) = pending.pop() {
        let directory_path: PathBuf = if current == "." {
            source_root.to_path_buf()
        } else {
            filesystem_path(source_root, current.as_str())?
        };
        let listing = std::fs::read_dir(directory_path.as_path())
            .map_err(raw_failure_of)?;
        for listed in listing {
            let entry: std::fs::DirEntry = listed.map_err(raw_failure_of)?;
            let name: String = entry.file_name().to_string_lossy().into_owned();
            let repository_path: String = if current == "." {
                name
            } else {
                format!("{current}/{name}")
            };
            if repository_path == ".git" {
                continue;
            }
            let source_path: PathBuf = filesystem_path(source_root, repository_path.as_str())?;
            if is_excluded(source_path.as_path(), excluded_roots) {
                continue;
            }
            let selected_ancestor: bool = within_any_root(repository_path.as_str(), selected_roots);
            if selected_ancestor {
                continue;
            }
            let file_type: std::fs::FileType = entry
                .file_type()
                .map_err(raw_failure_of)?;
            // A directory is walked; a file or symbolic link is already selected by Git's listing;
            // anything else is a special entry that needs Git's own ignore answer.
            if file_type.is_dir() {
                pending.push(repository_path);
            } else if !file_type.is_file() && !file_type.is_symlink() {
                special_paths.push(repository_path);
            }
        }
    }
    let mut ignored: Vec<String> = Vec::new();
    for repository_path in special_paths {
        if is_ignored_special_path(context, source_root, repository_path.as_str())? {
            ignored.push(repository_path);
        }
    }
    return Ok(ignored);
}

/// What:
///  Every existing source path ignored by Git's standard exclusion stack,
///  as collapsed repository paths.
/// Why:
///   This is the one selection the copy stages, so the same validation and collapse apply everywhere.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function readIgnoredRoots({ sourceRoot, gitPath, excludedRoots }): Promise<readonly string[]>;
/// ```
pub fn read_ignored_roots(
    context: &GitContext,
    source_root: &Path,
    excluded_roots: &[PathBuf],
) -> Result<Vec<String>, WorktreeCopyError> {
    let request: GitRequest = GitRequest {
        cwd: source_root.to_path_buf(),
        arguments: vec![
            "ls-files".into(),
            "--others".into(),
            "--ignored".into(),
            "--exclude-standard".into(),
            "--directory".into(),
            "-z".into(),
        ],
        without_prefix: true,
        ..GitRequest::default()
    };
    let output = run_git(context, &request).map_err(raw_failure_of)?;
    if output.code != Some(0) {
        return Err(raw_failure(&String::from_utf8_lossy(
            output.stderr.as_slice(),
        )));
    }
    let mut paths: Vec<String> = Vec::new();
    for field in output.stdout.split(is_nul_byte) {
        if field.is_empty() {
            continue;
        }
        let text: String = String::from_utf8_lossy(field).into_owned();
        // `strip_suffix` removes the directory marker only when present, as the incumbent does.
        let path: String = match text.strip_suffix(DIRECTORY_SUFFIX) {
            Some(stripped) => String::from(stripped),
            None => text,
        };
        assert_safe_repository_path(path.as_str())?;
        paths.push(path);
    }
    let selected: Vec<String> = paths.clone();
    let special: Vec<String> =
        special_entries(context, source_root, selected.as_slice(), excluded_roots)?;
    let mut all: Vec<String> = paths;
    all.extend(special);
    return Ok(collapse_ignored_roots(all.as_slice()));
}

/// What:
///  Which of a source's ignored paths one copy takes:
///  every ignored root, every ignored root minus what a main checkout leaves out, or only the named repository paths.
/// Why:
///   A linked or bare source hands over all of its ignored state, as the incumbent does;
///  a main checkout hands over the same minus its caches and every other checkout, so a worktree added from it works at once.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// type CopySelection = { kind: 'ignored' } | { kind: 'main-checkout' } | { kind: 'paths'; paths: readonly string[] };
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CopySelection {
    /// Every path Git's standard exclusion stack ignores, plus the ignored special entries.
    Ignored,
    /// The same listing, walked under the main checkout's leave-out rule (`worktree_copy_prune.rs`).
    MainCheckout,
    /// Only these repository paths, and only the ones Git ignores and the source has.
    Paths(Vec<String>),
}

/// What:
///  The named repository paths that exist in the source and that Git's standard exclusion stack ignores.
/// Why:
///   A configured file such as the forbidden-strings rules is copied by name, so the source is never enumerated;
///  a name Git does not list exactly (absent, tracked, not ignored, or a directory) selects nothing,
///  which leaves the destination without it instead of inventing it.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function readNamedIgnoredRoots({ sourceRoot, paths, gitPath }): Promise<readonly string[]>;
/// ```
pub fn read_named_ignored_roots(
    context: &GitContext,
    source_root: &Path,
    paths: &[String],
) -> Result<Vec<String>, WorktreeCopyError> {
    let mut selected: Vec<String> = Vec::new();
    for path in paths {
        assert_safe_repository_path(path.as_str())?;
        let request: GitRequest = GitRequest {
            cwd: source_root.to_path_buf(),
            arguments: vec![
                "ls-files".into(),
                "--others".into(),
                "--ignored".into(),
                "--exclude-standard".into(),
                "-z".into(),
                "--".into(),
                // `top` anchors the name at the worktree root and `literal` turns off globbing and magic.
                format!(":(top,literal){path}").into(),
            ],
            without_prefix: true,
            ..GitRequest::default()
        };
        let output = run_git(context, &request).map_err(raw_failure_of)?;
        if output.code != Some(0) {
            return Err(raw_failure(&String::from_utf8_lossy(
                output.stderr.as_slice(),
            )));
        }
        // Git lists a directory's files rather than the directory, so only an exact name is a file Git ignores.
        let listed: bool = lists_exactly(output.stdout.as_slice(), path.as_bytes());
        if listed {
            selected.push(path.clone());
        }
    }
    return Ok(collapse_ignored_roots(selected.as_slice()));
}

/// What:
///  The collapsed repository paths one copy takes from a source under the chosen selection.
/// Why:
///   Staging asks one question whichever source it copies from, so the selection mode is decided in one place.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// const roots = selection.kind === 'ignored' ? await readIgnoredRoots(...) : await readNamedIgnoredRoots(...);
/// ```
pub fn select_roots(
    context: &GitContext,
    source_root: &Path,
    excluded_roots: &[PathBuf],
    selection: &CopySelection,
) -> Result<Vec<String>, WorktreeCopyError> {
    // `match` on the selection: the full listing for linked and bare sources, the named lookup otherwise.
    match selection {
        CopySelection::Ignored | CopySelection::MainCheckout => {
            return read_ignored_roots(context, source_root, excluded_roots);
        }
        CopySelection::Paths(paths) => {
            return read_named_ignored_roots(context, source_root, paths.as_slice());
        }
    }
}

impl CopySelection {
    /// What:
    ///  The leave-out rule the selection's walk applies.
    /// Why:
    ///   The stage and the final source check must walk with the same rule, so both ask the selection.
    ///
    /// In TS you'd write (pseudocode):
    /// ```ts
    /// selection.kind === 'main-checkout' ? Prune.mainCheckout() : Prune.never
    /// ```
    pub fn prune(&self) -> Prune {
        return match self {
            CopySelection::MainCheckout => Prune::main_checkout(),
            CopySelection::Ignored | CopySelection::Paths(_) => Prune::Never,
        };
    }
}

/// Selection controls stay out of the release executable.
#[cfg(test)]
#[path = "worktree_copy_selection_tests.rs"]
mod tests;