gitpoulpi-cli-backend 1.3.0

GitBackend implementation that shells out to the system `git` binary, parsing only machine-readable output (porcelain v2, NUL-delimited logs).
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
//! `read_blob` and `blame` over the system `git` binary.
//!
//! Both go through `process::run`/`run_bytes`, so the `-c` config
//! overrides and the cleared `GIT_DIR` family apply.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use gitpoulpi_core::domain::{
    finish_hits, usable_terms, Blame, BlameContent, BlameLine, Blob, BlobBody, BlobBytes,
    BlobContent, BlobSource, GrepHit, LfsPointer, Oid, RepoRef, MAX_GREP_FILE_BYTES,
    MAX_TEXT_BLOB_BYTES,
};
use gitpoulpi_core::{Error, Result};

use crate::process::{run, run_bytes, run_lenient, run_z_fields};

/// See `GitBackend::read_blob`.
///
/// The size comes from `cat-file -s` (object header only), so an oversized
/// blob is rejected before any content is piped. The working tree is read
/// straight off disk, not through `git show :path`, which would apply
/// smudge filters and return a rendering instead of the editor's bytes.
pub fn read_blob(repo: &RepoRef, path: &Path, source: &BlobSource) -> Result<Blob> {
    let rel = repo_relative(path)?;
    let (size, content, image) = match source {
        BlobSource::WorkingTree => {
            let full = repo.root.join(&rel);
            let size = std::fs::metadata(&full)
                .map_err(|e| Error::Backend(format!("{rel}: {e}")))?
                .len();
            if size > MAX_TEXT_BLOB_BYTES {
                (size, BlobContent::TooLarge, None)
            } else {
                let raw =
                    std::fs::read(&full).map_err(|e| Error::Backend(format!("{rel}: {e}")))?;
                let content = BlobContent::from_bytes(&raw);
                let image = Blob::image_of(&content, &raw);
                (size, content, image)
            }
        }
        // `:<path>` is stage 0 of the index. An unmerged path has no
        // stage 0, and git says so rather than picking a side -- which is
        // the behavior wanted here too.
        BlobSource::Index => read_object(repo, &format!(":{rel}"))?,
        BlobSource::Commit(oid) => read_object(repo, &format!("{}:{rel}", oid.to_hex()))?,
        BlobSource::Stage(n) => read_object(repo, &stage_spec(*n, &rel)?)?,
    };

    Ok(Blob {
        path: PathBuf::from(rel),
        source: source.clone(),
        size,
        content,
        image,
    })
}

/// Header-then-content for one `<rev>:<path>` object spec.
fn read_object(
    repo: &RepoRef,
    spec: &str,
) -> Result<(u64, BlobContent, Option<gitpoulpi_core::domain::ImageInfo>)> {
    let size: u64 = run(&repo.root, &["cat-file", "-s", spec])?
        .trim()
        .parse()
        .map_err(|e| Error::Backend(format!("git cat-file -s {spec} gave no size: {e}")))?;
    if size > MAX_TEXT_BLOB_BYTES {
        return Ok((size, BlobContent::TooLarge, None));
    }
    // `blob` (rather than `-p`) both pins the type -- a directory at this
    // path is an error, not a tree listing -- and keeps git from applying
    // any textconv rendering on the way out.
    let raw = run_bytes(&repo.root, &["cat-file", "blob", spec])?;
    let content = BlobContent::from_bytes(&raw);
    let image = Blob::image_of(&content, &raw);
    Ok((size, content, image))
}

/// `:<n>:<path>`, one stage of an unmerged path.
fn stage_spec(stage: u8, rel: &str) -> Result<String> {
    if (1..=3).contains(&stage) {
        Ok(format!(":{stage}:{rel}"))
    } else {
        Err(Error::Backend(format!("{rel} has no stage {stage}")))
    }
}

/// See `GitBackend::read_blob_bytes`.
pub fn read_blob_bytes(
    repo: &RepoRef,
    path: &Path,
    source: &BlobSource,
    max: u64,
) -> Result<BlobBytes> {
    let rel = repo_relative(path)?;
    let spec = match source {
        BlobSource::WorkingTree => String::new(),
        BlobSource::Index => format!(":{rel}"),
        BlobSource::Commit(oid) => format!("{}:{rel}", oid.to_hex()),
        BlobSource::Stage(n) => stage_spec(*n, &rel)?,
    };
    let size = if let BlobSource::WorkingTree = source {
        std::fs::metadata(repo.root.join(&rel))
            .map_err(|e| Error::Backend(format!("{rel}: {e}")))?
            .len()
    } else {
        run(&repo.root, &["cat-file", "-s", &spec])?
            .trim()
            .parse()
            .map_err(|e| Error::Backend(format!("git cat-file -s {spec} gave no size: {e}")))?
    };
    let body = if size > max {
        BlobBody::TooLarge
    } else {
        let raw = if let BlobSource::WorkingTree = source {
            std::fs::read(repo.root.join(&rel))
                .map_err(|e| Error::Backend(format!("{rel}: {e}")))?
        } else {
            run_bytes(&repo.root, &["cat-file", "blob", &spec])?
        };
        body_of(repo, raw, max)
    };
    Ok(BlobBytes {
        path: PathBuf::from(rel),
        source: source.clone(),
        size,
        body,
    })
}

/// `raw` as a [`BlobBody`]: an LFS pointer is resolved to its local object
/// (shared with the git2 backend so both answer alike).
pub fn body_of(repo: &RepoRef, raw: Vec<u8>, max: u64) -> BlobBody {
    match LfsPointer::parse(&raw) {
        Some(pointer) => {
            let object = lfs_local_object(repo, &pointer, max);
            BlobBody::Lfs { pointer, object }
        }
        None => BlobBody::Bytes(raw),
    }
}

/// The real content of an LFS object when it sits in the local store
/// (`<storage>/objects/aa/bb/<oid>`, `lfs.storage` honoured) and is within
/// `max` bytes. Costs one `git rev-parse` and one `git config` spawn.
pub fn lfs_local_object(repo: &RepoRef, pointer: &LfsPointer, max: u64) -> Option<Vec<u8>> {
    let oid = pointer.oid.as_str();
    if oid.len() < 4 || !oid.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    let common = run(&repo.root, &["rev-parse", "--git-common-dir"]).ok()?;
    let common = repo.root.join(common.trim());
    let configured = run_lenient(&repo.root, &["config", "--get", "lfs.storage"])
        .ok()
        .filter(|(ok, _)| *ok)
        .map(|(_, v)| v.trim().to_string())
        .filter(|v| !v.is_empty());
    let storage = match configured {
        Some(p) => common.join(p),
        None => common.join("lfs"),
    };
    let file = storage
        .join("objects")
        .join(&oid[0..2])
        .join(&oid[2..4])
        .join(oid);
    if std::fs::metadata(&file).ok()?.len() > max {
        return None;
    }
    std::fs::read(file).ok()
}

/// See `GitBackend::blame`.
///
/// `--line-porcelain` (the human format is locale- and width-dependent)
/// repeats the full header per line, so each line parses independently.
/// The *lines* come from `read_blob`, not blame's TAB-prefixed records:
/// blame emits raw bytes, so a CRLF checkout would carry a trailing `\r`
/// that the file viewer (`BlobContent::from_bytes`) does not.
pub fn blame(repo: &RepoRef, path: &Path, at: Oid) -> Result<Blame> {
    let rel = repo_relative(path)?;
    let blob = read_blob(repo, path, &BlobSource::Commit(at))?;
    let lines = match &blob.content {
        BlobContent::Text { lines, .. } => lines.clone(),
        BlobContent::Binary => {
            return Ok(Blame {
                path: blob.path,
                at,
                size: blob.size,
                content: BlameContent::Binary,
            })
        }
        BlobContent::TooLarge => {
            return Ok(Blame {
                path: blob.path,
                at,
                size: blob.size,
                content: BlameContent::TooLarge,
            })
        }
        BlobContent::LfsPointer(pointer) => {
            return Ok(Blame {
                path: blob.path,
                at,
                size: blob.size,
                content: BlameContent::LfsPointer(pointer.clone()),
            })
        }
    };

    // `run` validates UTF-8, and blame echoes the file's own bytes back
    // in its `\t` records -- but a file that is not valid UTF-8 has
    // already returned `Binary` above, so anything reaching here decodes.
    let rev = at.to_hex();
    let raw = run_bytes(
        &repo.root,
        &[
            "blame",
            "--line-porcelain",
            // A `textconv` filter would have blame attribute lines of a
            // *converted* rendering (the text of a PDF, say) that have no
            // relationship to the lines the file viewer shows.
            "--no-textconv",
            "--no-ext-diff",
            &rev,
            "--",
            &rel,
        ],
    )?;
    // Only the attribution is used from this, never the file's own text
    // (`\t` records), so a non-UTF-8 file must not fail it.
    let raw = String::from_utf8_lossy(&raw);

    let entries = parse_line_porcelain(&raw);
    if entries.len() < lines.len() {
        return Err(Error::Backend(format!(
            "git blame returned {} lines for {rel}, but the file at {rev} has {}",
            entries.len(),
            lines.len()
        )));
    }

    let out = lines
        .into_iter()
        .zip(entries)
        .map(|(content, entry)| BlameLine {
            commit: entry.commit,
            author_name: entry.author_name,
            author_email: entry.author_email,
            timestamp: entry.timestamp,
            committer_time: entry.committer_time,
            summary: entry.summary,
            final_line: entry.final_line,
            orig_line: entry.orig_line,
            orig_path: PathBuf::from(entry.filename),
            previous: entry.previous,
            content,
        })
        .collect();

    Ok(Blame {
        path: blob.path,
        at,
        size: blob.size,
        content: BlameContent::Lines(out),
    })
}

/// One line's worth of `--line-porcelain` header, before the file's own
/// text is attached to it.
struct PorcelainEntry {
    commit: Oid,
    author_name: String,
    author_email: String,
    timestamp: i64,
    committer_time: i64,
    summary: String,
    final_line: u32,
    orig_line: u32,
    /// The `filename` header: the path in `commit`.
    filename: String,
    /// The `previous <parent> <path>` header, absent for a line born in a
    /// root commit or in a commit whose parent lacks the file.
    previous: Option<(Oid, PathBuf)>,
}

/// Parses `git blame --line-porcelain`.
///
/// Each record starts with `<sha> <orig-line> <final-line> [<count>]`,
/// carries `author`/`author-mail`/`author-time`/`summary` (plus
/// committer fields and optional `boundary`/`previous`, all ignored), and
/// ends with the file's own line prefixed by a literal TAB. Only that TAB
/// line is a reliable record terminator - header keys are not a fixed
/// set - so it, not a blank line, is what closes an entry here.
fn parse_line_porcelain(raw: &str) -> Vec<PorcelainEntry> {
    let mut out = Vec::new();
    let mut current: Option<PorcelainEntry> = None;
    // `summary` is per-commit in git's own output only for the first
    // occurrence in plain `--porcelain`; `--line-porcelain` repeats it,
    // but a cache keeps this correct even if that ever changes.
    let mut summaries: HashMap<Oid, String> = HashMap::new();

    for line in raw.lines() {
        if line.starts_with('\t') {
            if let Some(mut entry) = current.take() {
                if entry.summary.is_empty() {
                    entry.summary = summaries.get(&entry.commit).cloned().unwrap_or_default();
                } else {
                    summaries.insert(entry.commit, entry.summary.clone());
                }
                out.push(entry);
            }
            continue;
        }

        if let Some(entry) = current.as_mut() {
            if let Some(rest) = line.strip_prefix("author-mail ") {
                // git wraps the address in angle brackets.
                entry.author_email = rest.trim().trim_matches(['<', '>']).to_string();
            } else if let Some(rest) = line.strip_prefix("author-time ") {
                entry.timestamp = rest.trim().parse().unwrap_or_default();
            } else if let Some(rest) = line.strip_prefix("author ") {
                entry.author_name = rest.to_string();
            } else if let Some(rest) = line.strip_prefix("summary ") {
                entry.summary = rest.to_string();
            } else if let Some(rest) = line.strip_prefix("committer-time ") {
                entry.committer_time = rest.trim().parse().unwrap_or_default();
            } else if let Some(rest) = line.strip_prefix("filename ") {
                entry.filename = unquote_c(rest);
            } else if let Some(rest) = line.strip_prefix("previous ") {
                if let Some((sha, path)) = rest.split_once(' ') {
                    entry.previous =
                        Oid::from_hex(sha).map(|oid| (oid, PathBuf::from(unquote_c(path))));
                }
            }
            continue;
        }

        // A header line: `<sha> <orig> <final> [<lines-in-group>]`.
        let mut fields = line.split(' ');
        let Some(commit) = fields.next().and_then(Oid::from_hex) else {
            continue;
        };
        let Some(orig_line) = fields.next().and_then(|f| f.parse().ok()) else {
            continue;
        };
        let Some(final_line) = fields.next().and_then(|f| f.parse().ok()) else {
            continue;
        };
        current = Some(PorcelainEntry {
            commit,
            author_name: String::new(),
            author_email: String::new(),
            timestamp: 0,
            committer_time: 0,
            summary: String::new(),
            final_line,
            orig_line,
            filename: String::new(),
            previous: None,
        });
    }

    out
}

/// Undoes C-style quoting of a path in porcelain headers (a path with a
/// quote, backslash, control or non-ASCII byte is wrapped in `"` with
/// `\\`, `\"`, `\t`, `\n` and octal escapes).
fn unquote_c(raw: &str) -> String {
    let Some(inner) = raw.strip_prefix('"').and_then(|r| r.strip_suffix('"')) else {
        return raw.to_string();
    };
    let bytes = inner.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] != b'\\' || i + 1 >= bytes.len() {
            out.push(bytes[i]);
            i += 1;
            continue;
        }
        i += 1;
        match bytes[i] {
            b'n' => out.push(b'\n'),
            b't' => out.push(b'\t'),
            b'r' => out.push(b'\r'),
            c @ b'0'..=b'7' => {
                let mut value = u32::from(c - b'0');
                let mut taken = 1;
                while taken < 3 && i + 1 < bytes.len() && (b'0'..=b'7').contains(&bytes[i + 1]) {
                    i += 1;
                    value = value * 8 + u32::from(bytes[i] - b'0');
                    taken += 1;
                }
                out.push(value as u8);
            }
            other => out.push(other),
        }
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Domain paths are repo-relative and git spells them with `/` on every
/// platform; a `PathBuf` join on Windows yields backslashes no `<rev>:<path>`
/// or pathspec matches. Normalizing here is why this crate needs no
/// `cfg(windows)`.
pub(crate) fn repo_relative(path: &Path) -> Result<String> {
    let text = path
        .to_str()
        .ok_or_else(|| Error::Backend(format!("path {} is not valid utf-8", path.display())))?;
    Ok(text.replace('\\', "/").trim_start_matches("./").to_string())
}

/// Every path at `at`, sorted, with `/` separators.
///
/// `-z` because without it git quotes paths containing a space, a quote or
/// a non-ASCII byte. `ls-tree` already sorts and uses `/`; the contract
/// suite pins both.
pub fn list_tree(repo: &RepoRef, at: Oid) -> Result<Vec<PathBuf>> {
    // `<oid>^{tree}`, not the bare oid: `ls-tree` also accepts a tag or a
    // blob, and the explicit form turns "no tree here" into an error.
    let spec = format!("{}^{{tree}}", at.to_hex());
    let fields = run_z_fields(
        &repo.root,
        &["ls-tree", "-r", "-z", "--name-only", "--full-tree", &spec],
    )?;
    Ok(fields.into_iter().map(PathBuf::from).collect())
}

/// The lines of the files at `at` that contain `terms`: one `git grep -F -I`
/// per term (so each term gets its own cap), then the files the shared rules
/// exclude (symlinks, over the size cap, LFS pointers) are dropped from the
/// hits. The rules are `gitpoulpi_core::domain::grep_bytes` / `finish_hits`;
/// the contract suite holds this to the git2 backend's walk.
pub fn grep_tree(
    repo: &RepoRef,
    at: Oid,
    terms: &[String],
    max_hits: usize,
) -> Result<Vec<GrepHit>> {
    let rev = at.to_hex();
    // An unknown revision is an error, not "no hits" (`grep` exits 1 for
    // both and we read its exit status as "nothing found").
    run(
        &repo.root,
        &["rev-parse", "--verify", &format!("{rev}^{{commit}}")],
    )?;
    let terms = usable_terms(terms);
    if terms.is_empty() || max_hits == 0 {
        return Ok(Vec::new());
    }

    // Size and kind of every file, to leave out what git grep would read.
    let listing = run_bytes(
        &repo.root,
        &["ls-tree", "-r", "-l", "-z", "--full-tree", &rev],
    )?;
    let mut excluded: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut small: std::collections::HashSet<String> = std::collections::HashSet::new();
    for record in listing.split(|b| *b == 0).filter(|r| !r.is_empty()) {
        let record = String::from_utf8_lossy(record);
        let Some((meta, path)) = record.split_once('\t') else {
            continue;
        };
        let fields: Vec<&str> = meta.split_whitespace().collect();
        let (mode, size) = (fields.first().copied(), fields.get(3).copied());
        if mode == Some("120000") {
            excluded.insert(path.to_string());
        } else if let Some(size) = size.and_then(|s| s.parse::<u64>().ok()) {
            if size > MAX_GREP_FILE_BYTES {
                excluded.insert(path.to_string());
            } else if size < gitpoulpi_core::domain::LFS_POINTER_MAX_BYTES as u64 {
                small.insert(path.to_string());
            }
        }
    }

    let prefix = format!("{rev}:");
    let max_count = max_hits.to_string();
    let mut hits: Vec<GrepHit> = Vec::new();
    for term in &terms {
        let out = crate::process::run_lenient_bytes(
            &repo.root,
            &[
                "grep",
                "-n",
                "-F",
                "-I",
                "--no-color",
                "-z",
                "--max-count",
                &max_count,
                "-e",
                term,
                &rev,
                "--",
            ],
        )?;
        // `<rev>:<path> NUL <line> NUL <text> LF`
        for record in out.split(|b| *b == b'\n') {
            let mut parts = record.splitn(3, |b| *b == 0);
            let (Some(path), Some(line), Some(text)) = (parts.next(), parts.next(), parts.next())
            else {
                continue;
            };
            let path = String::from_utf8_lossy(path);
            let Some(path) = path.strip_prefix(&prefix) else {
                continue;
            };
            let Ok(line) = String::from_utf8_lossy(line).parse::<u32>() else {
                continue;
            };
            if excluded.contains(path) {
                continue;
            }
            hits.push(GrepHit {
                term: term.clone(),
                path: path.to_string(),
                line,
                text: gitpoulpi_core::domain::hit_text(&String::from_utf8_lossy(text)),
            });
        }
    }

    // A small file may be an LFS pointer: look at the few that have hits.
    let mut pointer_free: std::collections::HashMap<String, bool> =
        std::collections::HashMap::new();
    let mut kept = Vec::with_capacity(hits.len());
    for hit in hits {
        if small.contains(&hit.path) {
            let searchable = match pointer_free.get(&hit.path) {
                Some(known) => *known,
                None => {
                    let raw = run_bytes(&repo.root, &["show", &format!("{rev}:{}", hit.path)])?;
                    let ok = LfsPointer::parse(&raw).is_none();
                    pointer_free.insert(hit.path.clone(), ok);
                    ok
                }
            };
            if !searchable {
                continue;
            }
        }
        kept.push(hit);
    }
    Ok(finish_hits(kept, &terms, max_hits))
}