brygge 0.5.0

Carry version-control history out of Git, Mercurial, Subversion and CVS into an intermediate representation (IR), with every inference marked and every loss recorded: decode, inspect and verify.
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
//! A small hand-rolled argument parser for brygge's three-verb command surface (external design v0.3
//! CL-01…CL-08, handoff `cli-and-verify-handoff-v2.md`). No `clap`: the surface is small and brygge keeps
//! its dependency surface small (RFC 009).
//!
//! `decode`, `inspect`, `verify` — one noun per concept, nothing silently ignored. Every usage problem
//! (an unknown command, an unknown or missing flag, a missing value, a missing positional, a repeated
//! flag, or an option given to a source kind it does not apply to) is a parse error that `main` turns into
//! exit `USAGE` (2), naming the problem and pointing to `brygge <command> --help`.

use std::path::PathBuf;

/// Report rendering (CL-07): human by default, machine for CI gating.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
    /// The human-facing form.
    Human,
    /// The stable, versioned, line-oriented form.
    Machine,
}

/// A source kind for `decode` (external design CL-01: the set is open by design).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceKind {
    /// Git (`brygge-decode-git`).
    Git,
    /// Mercurial (`brygge-decode-hg`).
    Hg,
    /// Subversion (`brygge-decode-svn`) — a repository directory or a dumpfile.
    Svn,
    /// CVS (`brygge-decode-cvs`) — a local repository directory of RCS `,v` files.
    Cvs,
}

impl SourceKind {
    /// The lowercase label used on the command line and in messages.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Git => "git",
            Self::Hg => "hg",
            Self::Svn => "svn",
            Self::Cvs => "cvs",
        }
    }
}

/// A parsed command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Command {
    /// `decode <git|hg|svn|cvs> <source> --out <artifact> [--infer-renames | --reconstruct-refs] [--spill-dir <DIR>] [--format …]`
    Decode {
        /// Which source decoder to use.
        kind: SourceKind,
        /// The source repository path (for svn: a repository directory or a dumpfile).
        source: PathBuf,
        /// Where to write the IR artifact. Required (CL-01: `decode` never runs without producing it).
        out: PathBuf,
        /// Turn on opt-in, always-marked rename inference (git only; Mercurial records its renames).
        infer_renames: bool,
        /// Reconstruct branch/tag refs by convention or symbol, marking each `Derived` (svn/cvs only).
        reconstruct_refs: bool,
        /// Where to keep file content while decoding, instead of in memory (RFC 015 D-3/D-3a). Must
        /// already exist and be a directory; `None` means the output artifact's own directory.
        spill_dir: Option<PathBuf>,
        /// Output format.
        format: Format,
    },
    /// `inspect <artifact> [--atoms] [--format …]`
    Inspect {
        /// The IR artifact to read.
        artifact: PathBuf,
        /// Append the per-atom listing (the reviewer's detail) to the default fidelity report.
        atoms: bool,
        /// Output format.
        format: Format,
    },
    /// `verify <artifact> [--against-source <source>] [--spill-dir <DIR>] [--format …]`
    Verify {
        /// The IR artifact to check.
        artifact: PathBuf,
        /// If given, additionally re-derive from this source and confirm correspondence (VF-2).
        against_source: Option<PathBuf>,
        /// Where `--against-source`'s re-decode keeps file content while decoding, instead of in
        /// memory (RFC 015 D-4, as `decode`'s own `--spill-dir`). Must already exist and be a
        /// directory; `None` means the artifact's own directory. Meaningless, and rejected, without
        /// `--against-source`.
        spill_dir: Option<PathBuf>,
        /// Output format.
        format: Format,
    },
    /// `--version`.
    Version,
    /// `--help`, `<command> --help`, or no arguments.
    Help,
}

/// The top-level usage text. Lists only commands that exist (CL-06).
pub const USAGE: &str = "\
brygge — carry version-control history into an intermediate representation (IR).

USAGE:
  brygge decode <git|hg|svn|cvs> <source> --out <artifact> [--infer-renames | --reconstruct-refs] [--spill-dir <DIR>] [--format human|machine]
  brygge inspect <artifact> [--atoms] [--format human|machine]
  brygge verify <artifact> [--against-source <source> [--spill-dir <DIR>]] [--format human|machine]
  brygge --version | --help | <command> --help

COMMANDS:
  decode   read a source into an IR artifact (git, hg, svn, or cvs in this build). --out is required.
           For svn, <source> is a repository directory (dumped read-only via `svnadmin dump`) or a
           dumpfile; for cvs, a local repository directory of RCS ,v files. --infer-renames (git) and
           --reconstruct-refs (svn/cvs) each turn on an opt-in, always-marked derived layer; giving either
           to a source kind it does not apply to is a usage error. File content is kept on disk while
           decoding, in a private file removed when brygge exits — --spill-dir <DIR> chooses where (it
           must already exist); the default is --out's own directory. The option never changes the
           artifact; a RAM-backed directory (tmpfs) moves the memory cost rather than removing it
  inspect  print the fidelity report an artifact alone reproduces; --atoms adds the per-atom
           listing: epistemic status, source ids, derived parameters, and the loss boundary
  verify   the honesty checks any reader can run with no source (always); with --against-source, also
           re-derive from the source and confirm correspondence — the two results are reported
           separately, never merged. The re-derive's own file content is kept on disk the same way
           decode's is; --spill-dir <DIR> chooses where (it must already exist, and only applies with
           --against-source); the default is the artifact's own directory

VOCABULARY: artifact, source, stated, derived, dropped, flagged, refused, Unverifiable.";

fn usage_error(command: &str, problem: impl std::fmt::Display) -> String {
    format!("{problem}\n\nrun `brygge {command} --help` for usage")
}

fn inapplicable_option(option: &str, kinds: &str, kind: SourceKind) -> String {
    format!("--{option} applies to {kinds}, not to {}", kind.label())
}

/// Parse arguments (those after the program name) into a [`Command`].
///
/// # Errors
/// Returns a usage message — the problem, then a pointer to `brygge <command> --help` — on a malformed or
/// unknown invocation. The caller exits `USAGE` (2) on this path.
pub fn parse(args: &[String]) -> Result<Command, String> {
    let mut it = args.iter();
    let Some(first) = it.next() else {
        return Ok(Command::Help);
    };
    match first.as_str() {
        "--version" | "-V" => Ok(Command::Version),
        "--help" | "-h" => Ok(Command::Help),
        "decode" => parse_decode(args.get(1..).unwrap_or(&[])),
        "inspect" => parse_inspect(args.get(1..).unwrap_or(&[])),
        "verify" => parse_verify(args.get(1..).unwrap_or(&[])),
        "encode" => Err(
            "'encode' is not available yet: the prikk encoder follows prikk's import foundations \
             (see ROADMAP)"
                .to_string(),
        ),
        other => Err(format!(
            "unknown command '{other}'\n\nrun `brygge --help` for usage"
        )),
    }
}

fn wants_help(args: &[String]) -> bool {
    args.iter().any(|a| a == "--help" || a == "-h")
}

fn parse_format(rest: &mut std::slice::Iter<'_, String>, command: &str) -> Result<Format, String> {
    match rest.next().map(String::as_str) {
        Some("human") => Ok(Format::Human),
        Some("machine") => Ok(Format::Machine),
        Some(other) => Err(usage_error(
            command,
            format!("--format expects 'human' or 'machine', got '{other}'"),
        )),
        None => Err(usage_error(
            command,
            "--format needs a value ('human' or 'machine')",
        )),
    }
}

fn need_value(
    rest: &mut std::slice::Iter<'_, String>,
    flag: &str,
    command: &str,
) -> Result<PathBuf, String> {
    rest.next()
        .map(PathBuf::from)
        .ok_or_else(|| usage_error(command, format!("{flag} needs a value")))
}

fn parse_decode(args: &[String]) -> Result<Command, String> {
    if wants_help(args) {
        return Ok(Command::Help);
    }
    let mut it = args.iter();
    let kind = match it.next().map(String::as_str) {
        Some("git") => SourceKind::Git,
        Some("hg") => SourceKind::Hg,
        Some("svn") => SourceKind::Svn,
        Some("cvs") => SourceKind::Cvs,
        Some(other) => {
            return Err(usage_error(
                "decode",
                format!(
                    "source kind '{other}' is not supported (git, hg, svn, or cvs in this build)"
                ),
            ));
        }
        None => {
            return Err(usage_error(
                "decode",
                "decode needs a source kind and a source: decode <git|hg|svn|cvs> <source> --out <artifact>",
            ));
        }
    };
    let mut source: Option<PathBuf> = None;
    let mut out: Option<PathBuf> = None;
    let mut out_seen = false;
    let mut infer_renames = false;
    let mut infer_renames_seen = false;
    let mut reconstruct_refs = false;
    let mut reconstruct_refs_seen = false;
    let mut spill_dir: Option<PathBuf> = None;
    let mut spill_dir_seen = false;
    let mut format = Format::Human;
    let mut format_seen = false;
    while let Some(arg) = it.next() {
        match arg.as_str() {
            "--out" => {
                if out_seen {
                    return Err(usage_error("decode", "--out given more than once"));
                }
                out_seen = true;
                out = Some(need_value(&mut it, "--out", "decode")?);
            }
            "--spill-dir" => {
                if spill_dir_seen {
                    return Err(usage_error("decode", "--spill-dir given more than once"));
                }
                spill_dir_seen = true;
                spill_dir = Some(need_value(&mut it, "--spill-dir", "decode")?);
            }
            "--infer-renames" => {
                if infer_renames_seen {
                    return Err(usage_error(
                        "decode",
                        "--infer-renames given more than once",
                    ));
                }
                infer_renames_seen = true;
                infer_renames = true;
            }
            "--reconstruct-refs" => {
                if reconstruct_refs_seen {
                    return Err(usage_error(
                        "decode",
                        "--reconstruct-refs given more than once",
                    ));
                }
                reconstruct_refs_seen = true;
                reconstruct_refs = true;
            }
            "--format" => {
                if format_seen {
                    return Err(usage_error("decode", "--format given more than once"));
                }
                format_seen = true;
                format = parse_format(&mut it, "decode")?;
            }
            other if other.starts_with('-') => {
                return Err(usage_error("decode", format!("unknown flag '{other}'")));
            }
            other => {
                if source.is_some() {
                    return Err(usage_error(
                        "decode",
                        format!("unexpected extra argument '{other}'"),
                    ));
                }
                source = Some(PathBuf::from(other));
            }
        }
    }
    let source = source
        .ok_or_else(|| usage_error("decode", "decode needs a source: <git|hg|svn|cvs> <source>"))?;
    let out = out.ok_or_else(|| usage_error("decode", "decode needs --out <artifact>"))?;

    if infer_renames && !matches!(kind, SourceKind::Git) {
        return Err(usage_error(
            "decode",
            inapplicable_option("infer-renames", "git", kind),
        ));
    }
    if reconstruct_refs && !matches!(kind, SourceKind::Svn | SourceKind::Cvs) {
        return Err(usage_error(
            "decode",
            inapplicable_option("reconstruct-refs", "svn, cvs", kind),
        ));
    }

    Ok(Command::Decode {
        kind,
        source,
        out,
        infer_renames,
        reconstruct_refs,
        spill_dir,
        format,
    })
}

fn parse_inspect(args: &[String]) -> Result<Command, String> {
    if wants_help(args) {
        return Ok(Command::Help);
    }
    let mut it = args.iter();
    let mut artifact: Option<PathBuf> = None;
    let mut atoms = false;
    let mut atoms_seen = false;
    let mut format = Format::Human;
    let mut format_seen = false;
    while let Some(arg) = it.next() {
        match arg.as_str() {
            "--atoms" => {
                if atoms_seen {
                    return Err(usage_error("inspect", "--atoms given more than once"));
                }
                atoms_seen = true;
                atoms = true;
            }
            "--format" => {
                if format_seen {
                    return Err(usage_error("inspect", "--format given more than once"));
                }
                format_seen = true;
                format = parse_format(&mut it, "inspect")?;
            }
            other if other.starts_with('-') => {
                return Err(usage_error("inspect", format!("unknown flag '{other}'")));
            }
            other => {
                if artifact.is_some() {
                    return Err(usage_error(
                        "inspect",
                        format!("unexpected extra argument '{other}'"),
                    ));
                }
                artifact = Some(PathBuf::from(other));
            }
        }
    }
    let artifact = artifact.ok_or_else(|| usage_error("inspect", "inspect needs an <artifact>"))?;
    Ok(Command::Inspect {
        artifact,
        atoms,
        format,
    })
}

fn parse_verify(args: &[String]) -> Result<Command, String> {
    if wants_help(args) {
        return Ok(Command::Help);
    }
    let mut it = args.iter();
    let mut artifact: Option<PathBuf> = None;
    let mut against_source: Option<PathBuf> = None;
    let mut against_source_seen = false;
    let mut spill_dir: Option<PathBuf> = None;
    let mut spill_dir_seen = false;
    let mut format = Format::Human;
    let mut format_seen = false;
    while let Some(arg) = it.next() {
        match arg.as_str() {
            "--against-source" => {
                if against_source_seen {
                    return Err(usage_error(
                        "verify",
                        "--against-source given more than once",
                    ));
                }
                against_source_seen = true;
                against_source = Some(need_value(&mut it, "--against-source", "verify")?);
            }
            "--spill-dir" => {
                if spill_dir_seen {
                    return Err(usage_error("verify", "--spill-dir given more than once"));
                }
                spill_dir_seen = true;
                spill_dir = Some(need_value(&mut it, "--spill-dir", "verify")?);
            }
            "--format" => {
                if format_seen {
                    return Err(usage_error("verify", "--format given more than once"));
                }
                format_seen = true;
                format = parse_format(&mut it, "verify")?;
            }
            other if other.starts_with('-') => {
                return Err(usage_error("verify", format!("unknown flag '{other}'")));
            }
            other => {
                if artifact.is_some() {
                    return Err(usage_error(
                        "verify",
                        format!("unexpected extra argument '{other}'"),
                    ));
                }
                artifact = Some(PathBuf::from(other));
            }
        }
    }
    let artifact = artifact.ok_or_else(|| usage_error("verify", "verify needs an <artifact>"))?;
    if spill_dir.is_some() && against_source.is_none() {
        return Err(usage_error(
            "verify",
            "--spill-dir only applies with --against-source",
        ));
    }
    Ok(Command::Verify {
        artifact,
        against_source,
        spill_dir,
        format,
    })
}

#[cfg(test)]
mod tests;