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
//! What:
//!  Find and read `monochromatic-git-policy-cli.config.jsonc` at a repository root.
//! Why:
//!  Configuration is one data file at one fixed place;
//!  legacy executable
//!      configuration is reported for migration and never read,
//!  run or silently ignored.
//!
//! In TS you'd write (pseudocode):
//! ```ts
//! // loadRepositoryConfig(root) returns { config, source, ignoredLegacy } or throws ConfigError.
//! ```

/// What:
///  `use super::...` imports sibling modules of this crate.
/// Why:
///   Loading combines the error type,
///  the document parser and the typed settings.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// import { ConfigError } from './config-error.ts';
/// ```
use crate::config_error::ConfigError;
use crate::config_parse::parse_config;
use crate::config_schema::CliGitConfig;
use crate::wrapper_names_old_and_new::SETTINGS_FILE;
/// What:
///  Import the trait that gives files `.take(..)` and `.read_to_end(..)`.
///       A trait is an interface;
///  its methods exist only while it is in scope.
/// Why:
///   The file is read through a byte cap instead of trusting its reported size.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// import { open } from 'node:fs/promises';
/// ```
use std::io::Read;
/// What:
///  `Path` is a borrowed filesystem path;
///  `PathBuf` is its owned form.
///       The same pair as `&str` and `String`,
///  but holding raw OS bytes.
/// Why:
///   Repository paths need not be UTF-8,
///  so they are never converted to text
///       except inside a diagnostic.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// import { join } from 'node:path';
/// ```
use std::path::{Path, PathBuf};

/// The configuration file the native wrapper reads.
pub const CONFIG_FILE_NAME: &str = SETTINGS_FILE.current;

/// The name an earlier release gave the configuration file;
///  read when it is the only one,
///  with a notice.
pub const EARLIER_CONFIG_FILE_NAME: &str = SETTINGS_FILE.earlier;

/// What:
///  Executable configuration names of the TypeScript wrapper,
///  in its lookup order.
///       `&[&str]` is a borrowed list of borrowed strings compiled into the executable.
/// Why:
///   Their presence must produce a migration diagnostic.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// const LEGACY_CONFIG_FILE_NAMES = ['cli-git.config.mjs', 'cli-git.config.ts'] as const;
/// ```
pub const LEGACY_CONFIG_FILE_NAMES: &[&str] = &["cli-git.config.mjs", "cli-git.config.ts"];

/// What:
///  Largest accepted configuration file,
///  one mebibyte.
///       `u64` is an unsigned 64-bit integer,
///  the type of file sizes (sibling `usize`).
/// Why:
///   A repository file must not control how much memory every Git command reads.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// const MAX_CONFIG_BYTES = 1024 * 1024;
/// ```
pub const MAX_CONFIG_BYTES: u64 = 1_048_576;

/// What:
///  The outcome of loading one repository's configuration.
///       `Option<PathBuf>` is "an owned path or nothing";
///  `Vec<PathBuf>` is an owned list.
/// Why:
///   Callers need the settings,
///  the file they came from for diagnostics,
///  and any
///       legacy file that was left beside an authoritative JSONC file so they can
///       report it instead of ignoring it silently.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// type LoadedConfig = { config: CliGitConfig; source?: string; ignoredLegacy: string[] };
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LoadedConfig {
    /// Validated settings;
    ///  `CliGitConfig::defaults()` when the repository has no file.
    pub config: CliGitConfig,
    /// The JSONC file that was read,
    ///  absent when the repository has none.
    pub source: Option<PathBuf>,
    /// Legacy files present beside the JSONC file;
    ///  never read,
    ///  to be reported.
    pub ignored_legacy: Vec<PathBuf>,
    /// One line for standard error when the repository still has the file under its earlier name,
    ///  or has both:
    ///  `None` when the settings come from the current name or from no file.
    pub earlier_name_notice: Option<String>,
}

/// What:
///  Report whether a directory entry exists,
///  without following a final symlink.
///       `Result<bool, ConfigError>` is "true/false or an error".
/// Why:
///   Only "not found" means absent;
///  any other failure (for example a permission
///       error) must stop the command instead of pretending no file exists.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function entryExists(path: string): Promise<boolean>;
/// ```
fn entry_exists(path: &Path) -> Result<bool, ConfigError> {
    // What: `match` on the metadata `Result`: `Ok(_)` ignores the metadata itself.
    //       `error.kind()` classifies the OS error; `::` walks module paths.
    // Why:  Existence is all that matters for a legacy file.
    //
    // In TS you'd write (pseudocode):
    // ```ts
    // try { await lstat(path); return true; } catch (e) { if (e.code === 'ENOENT') return false; throw e; }
    // ```
    match std::fs::symlink_metadata(path) {
        // `Ok(true)` is the success variant carrying the answer.
        Ok(_) => return Ok(true),
        Err(error) => {
            if error.kind() == std::io::ErrorKind::NotFound {
                return Ok(false);
            }
            // `Err(...)` is the failure variant; `path.display()` renders lossy text.
            return Err(ConfigError::new(
                format!("Cannot inspect {}: {error}.", path.display()).as_str(),
            ));
        }
    }
}

/// What:
///  The settings file of the repository whose top level is `repository_root`, found the way the loader finds it:
///  the current name when it exists,
///  else the earlier name when only that exists,
///  else the current name.
/// Why:
///   A control or tool that must read a repository's own file asks this, so it works before and after that file is renamed.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// function settingsFileOf(root: string): string;
/// ```
pub fn settings_file_of(repository_root: &Path) -> PathBuf {
    let current: PathBuf = repository_root.join(CONFIG_FILE_NAME);
    let earlier: PathBuf = repository_root.join(EARLIER_CONFIG_FILE_NAME);
    if !current.exists() && earlier.exists() {
        return earlier;
    }
    return current;
}

/// The line for a repository that has only the earlier settings file:
///  it is read,
///  and the new name is given.
fn earlier_only_notice() -> String {
    return format!(
        "{}: the settings file {EARLIER_CONFIG_FILE_NAME} is read under its earlier name; rename it to {CONFIG_FILE_NAME} \
         (the wrapper never renames a committed file by itself).\n",
        SETTINGS_FILE.current
    );
}

/// The line for a repository that has both settings files:
///  the new one is read and the earlier one is ignored.
fn both_files_notice() -> String {
    return format!(
        "{}: the settings file {EARLIER_CONFIG_FILE_NAME} is ignored because {CONFIG_FILE_NAME} exists; remove \
         {EARLIER_CONFIG_FILE_NAME} once nothing else reads it.\n",
        SETTINGS_FILE.current
    );
}

/// What:
///  Explain a legacy configuration file that has no JSONC replacement yet.
/// Why:
///   The author needs to know it was not run,
///  where the replacement goes and
///       which parts have no equivalent.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// function migrationRequired(legacy: string, target: string): ConfigError;
/// ```
fn migration_required(legacy: &Path, target: &Path) -> ConfigError {
    return ConfigError::new(
        format!(
            "Legacy configuration {} is not executed or read by the native monochromatic-git-policy-cli. \
             Translate its settings into {} (data only: policies, hooks, indexLock, landing), \
             then remove the legacy file. Plugins, executable paths, command arrays and trust \
             settings have no JSONC equivalent because every policy is built in.",
            legacy.display(),
            target.display()
        )
        .as_str(),
    );
}

/// What:
///  Describe a legacy file that sits beside an authoritative JSONC file.
///       `String` is owned text returned to the caller.
/// Why:
///   The executable prints this so the stale file is never ignored silently.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// function ignoredLegacyNotice(legacy: string, source: string): string;
/// ```
pub fn ignored_legacy_notice(legacy: &Path, source: &Path) -> String {
    return format!(
        "Legacy configuration {} is ignored: {} is authoritative for the native monochromatic-git-policy-cli. \
         Remove the legacy file once no TypeScript monochromatic-git-policy-cli reads it.",
        legacy.display(),
        source.display()
    );
}

/// What:
///  Read at most `MAX_CONFIG_BYTES` of a regular,
///  non-symlink file as UTF-8 text.
/// Why:
///   A symbolic link could point outside the repository,
///  a directory or device is
///       not configuration,
///  and an oversized or non-UTF-8 file is rejected by name.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function readConfigText(path: string): Promise<string>;
/// ```
fn read_config_text(path: &Path) -> Result<String, ConfigError> {
    // What: `let x = match ... { Ok(v) => v, Err(e) => return Err(...) };` unwraps or exits.
    // Why:  Metadata without following the link reveals a symlink before it is opened.
    //
    // In TS you'd write (pseudocode):
    // ```ts
    // const entry = await lstat(path);
    // ```
    let metadata: std::fs::Metadata = match std::fs::symlink_metadata(path) {
        Ok(found) => found,
        Err(error) => {
            return Err(ConfigError::new(
                format!("Cannot inspect {}: {error}.", path.display()).as_str(),
            ));
        }
    };
    if metadata.file_type().is_symlink() {
        return Err(ConfigError::new(
            format!(
                "Configuration path must not be a symbolic link: {}. Replace it with a regular file.",
                path.display()
            )
            .as_str(),
        ));
    }
    if !metadata.is_file() {
        return Err(ConfigError::new(
            format!(
                "Configuration path must be a regular file: {}.",
                path.display()
            )
            .as_str(),
        ));
    }
    let file: std::fs::File = match std::fs::File::open(path) {
        Ok(opened) => opened,
        Err(error) => {
            return Err(ConfigError::new(
                format!("Cannot open {}: {error}.", path.display()).as_str(),
            ));
        }
    };
    // What: `Vec::<u8>::new()` is an empty owned byte list (`u8` is one byte, 0 to 255).
    // Why:  Bytes are validated as UTF-8 only after the size cap has been enforced.
    //
    // In TS you'd write (pseudocode):
    // ```ts
    // const bytes = Buffer.alloc(0);
    // ```
    let mut bytes: Vec<u8> = Vec::<u8>::new();
    // What: `.take(n)` stops reading after `n` bytes; `&mut bytes` lends the buffer for
    //       appending. One byte past the cap proves the file is too large.
    // Why:  The cap holds even if the file grows after its metadata was read.
    //
    // In TS you'd write (pseudocode):
    // ```ts
    // const { bytesRead } = await handle.read(buffer, 0, MAX_CONFIG_BYTES + 1, 0);
    // ```
    if let Err(error) = file.take(MAX_CONFIG_BYTES + 1).read_to_end(&mut bytes) {
        return Err(ConfigError::new(
            format!("Cannot read {}: {error}.", path.display()).as_str(),
        ));
    }
    // `as u64` widens the list length for comparison with the byte cap.
    if bytes.len() as u64 > MAX_CONFIG_BYTES {
        return Err(ConfigError::new(
            format!(
                "Configuration file {} is larger than {MAX_CONFIG_BYTES} bytes.",
                path.display()
            )
            .as_str(),
        ));
    }
    // `String::from_utf8` takes ownership of the bytes and checks them without copying.
    match String::from_utf8(bytes) {
        Ok(text) => return Ok(text),
        Err(error) => {
            return Err(ConfigError::new(
                format!(
                    "Configuration file {} is not UTF-8 text: {error}.",
                    path.display()
                )
                .as_str(),
            ));
        }
    }
}

/// What:
///  Load the configuration of the repository whose top level is `repository_root`.
/// Why:
///   This is the single entry point for policy settings.
///  Nothing in a repository
///       is executed:
///  the JSONC file is parsed as data,
///  and legacy `.mjs`/`.ts`
///       configuration is only detected by name.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function loadRepositoryConfig(repositoryRoot: string): Promise<LoadedConfig>;
/// ```
pub fn load_repository_config(repository_root: &Path) -> Result<LoadedConfig, ConfigError> {
    // `.join(name)` appends one path segment and returns an owned path.
    let current: PathBuf = repository_root.join(CONFIG_FILE_NAME);
    let earlier: PathBuf = repository_root.join(EARLIER_CONFIG_FILE_NAME);
    // `Vec::<PathBuf>::new()` is an empty owned list; `mut` allows pushing.
    let mut legacy: Vec<PathBuf> = Vec::<PathBuf>::new();
    // `for name in LEGACY_CONFIG_FILE_NAMES` visits each compiled-in name.
    for name in LEGACY_CONFIG_FILE_NAMES {
        let candidate: PathBuf = repository_root.join(name);
        // A trailing `?` returns the helper's error to our caller, or unwraps its value.
        if entry_exists(candidate.as_path())? {
            legacy.push(candidate);
        }
    }
    let current_there: bool = entry_exists(current.as_path())?;
    let earlier_there: bool = entry_exists(earlier.as_path())?;
    if !current_there && !earlier_there {
        // `.first()` is `Some(&item)` for a non-empty list, `None` otherwise.
        if let Some(first) = legacy.first() {
            return Err(migration_required(first.as_path(), current.as_path()));
        }
        return Ok(LoadedConfig {
            config: CliGitConfig::defaults(),
            // `None` records that no file was read.
            source: None,
            ignored_legacy: legacy,
            earlier_name_notice: None,
        });
    }
    // What: The current name wins when both exist; the earlier name is read only when it is the only one.
    // Why:  The owner decided that a repository with both reads the new file, and that one with only the old file is
    //       read with a notice and never renamed.
    //
    // In TS you'd write (pseudocode):
    // ```ts
    // const [source, notice] = currentThere ? [current, earlierThere ? bothNotice : undefined] : [earlier, earlierOnlyNotice];
    // ```
    let (source, earlier_name_notice): (PathBuf, Option<String>) = if current_there && earlier_there {
        (current, Some(both_files_notice()))
    } else if current_there {
        (current, None)
    } else {
        (earlier, Some(earlier_only_notice()))
    };
    let text: String = read_config_text(source.as_path())?;
    // What: `.strip_prefix(..)` is `Some(rest)` when the text starts with the marker.
    //       `.unwrap_or(default)` picks `rest`, or the whole text when there is no marker.
    // Why:  A UTF-8 byte order mark is an editor artefact, not configuration content.
    //
    // In TS you'd write (pseudocode):
    // ```ts
    // const body = text.startsWith('') ? text.slice(1) : text;
    // ```
    let body: &str = text.strip_prefix('\u{feff}').unwrap_or(text.as_str());
    match parse_config(body) {
        Ok(config) => {
            return Ok(LoadedConfig {
                config,
                // `Some(source)` records the file the settings came from.
                source: Some(source),
                ignored_legacy: legacy,
                earlier_name_notice,
            });
        }
        Err(error) => {
            return Err(ConfigError::new(
                format!("{}: {}", source.display(), error.message).as_str(),
            ));
        }
    }
}

/// Disposable-directory controls stay out of the release executable.
#[cfg(test)]
#[path = "config_file_tests.rs"]
mod tests;

/// Controls on the two spellings of the settings file stay out of the release executable.
#[cfg(test)]
#[path = "config_file_earlier_name_tests.rs"]
mod earlier_name_tests;

/// Controls on the repository's own configuration file stay out of the release executable.
#[cfg(test)]
#[path = "config_repository_tests.rs"]
mod repository_tests;