znippy_plugin_git/lib.rs
1//! znippy handler for **git object stores** — the `git` package format.
2//!
3//! One archive holds one git repository (D12: one `.znippy` per repo). The
4//! consumer is `gunnar`, a pure-Rust git server whose `repack()` writes the cold
5//! tier.
6//!
7//! ## The two tiers a repository can be stored as
8//!
9//! | tier | data entries | what it preserves |
10//! |---|---|---|
11//! | **objects** | one per object, named by its **oid hex**, holding its canonical bytes `"<type> <size>\0<content>"` | the oid is checkable by re-hashing the entry |
12//! | **packs** | `pack-<id>.pack` + `pack-<id>.idx` | the client's own **deflate** and every **delta chain** |
13//!
14//! The object tier is the one this format was designed around and is what the
15//! `__gunnar_*` sub-indexes describe. **The pack tier is what gunnar actually
16//! seals**, and the reason is measured: a git object in a pack is already
17//! deflated and often a delta, so storing it inflated per oid costs an OpenZL
18//! decode plus a fresh zlib deflate on every fetch, for ever, and forecloses
19//! pack-copy permanently. gunnar measured an archive of 60000 small git objects
20//! at 3.4× *larger* than its input. See [`sections::GitIndexBuilder::pack_tier`].
21//!
22//! ## What this format adds on top of a plain archive
23//!
24//! | column / module | carries |
25//! |---|---|
26//! | `object_type` | `blob` / `tree` / `commit` / `tag` for the object tier; `packfile` / `pack-index` for the pack tier — typed listing with no reads |
27//! | `object_size` | content length, so quota gates and size analytics are index-only |
28//! | `__gunnar_oid__` | an `stree` over the first 8 bytes of every oid → its lookup row |
29//! | `__gunnar_graph__` | the commit graph as Arrow: `oid, parents[], tree, committer_time, generation` |
30//! | `__gunnar_reach__` | per-commit reachability bitmaps (roaring) over object ordinals |
31//! | `__gunnar_refs__` / `__gunnar_secrets__` | the server's push logs, on **either** tier |
32//!
33//! The last three object modules are emitted for the object tier only — a pack
34//! carries its own `.idx`, which is a better oid index than `__gunnar_oid__`
35//! because it addresses pack offsets.
36//!
37//! All of these modules are **reserved** (`znippy_common::is_reserved_module`),
38//! so `znippy list`, `decompress`, the iceberg sink and the manifest readers skip
39//! them exactly as they skip the lookup and the trie.
40//!
41//! ## Laws it honours
42//!
43//! **P-1** one archive = one ecosystem (`--format git`); **P-2** it writes only
44//! the columns it declared; **P-3** it is discovered through [`meta`]; **P-4** a
45//! malformed or hostile entry never panics — `object_type` degrades to
46//! `unknown` and the archive still writes.
47//!
48//! ## Who writes the reserved sections
49//!
50//! [`GitIndexBuilder`] does, handed to `ArrowIpcSink::with_reserved_builder` by
51//! the writer that knows the object set — gunnar's `repack()`. It is deliberately
52//! **not** wired into `znippy compress --format git`: the CLI's small-file batch
53//! pass never sees objects that take the big-file path, so a CLI-built index
54//! would be silently incomplete, and a silently incomplete oid index is worse
55//! than none. `znippy compress --format git` therefore writes the two columns and
56//! no reserved sections; `znippy run git lookup|graph` reads archives that carry
57//! them.
58//!
59//! Native builtin, registered in `znippy-cli/src/handlers.rs::builtin_handlers`.
60//! Deliberately **not** a WASM plugin: the oid index's hot path is `stree`, which
61//! needs AVX2, an mmap and prefetch, none of which wasm offers.
62
63use std::collections::HashMap;
64
65use znippy_common::arrow::datatypes::{DataType, Field};
66use znippy_common::plugin::{
67 ArchiveTypePlugin, ExtensionRow, ExtensionValue, HandlerCommand, HandlerMeta,
68};
69
70/// The measured workloads behind the `znippy.git_*` benches (feature
71/// `bench-kernels`). Not linked into a shipped archiver.
72#[cfg(feature = "bench-kernels")]
73pub mod bench_kernels;
74/// The push path's archive writer: one trait, three durability contracts
75/// ([`FastWriter`](archive_write::FastWriter),
76/// [`SafeWriter`](archive_write::SafeWriter),
77/// [`UringWriter`](uring_write::UringWriter)).
78pub mod archive_write;
79pub(crate) mod archive_map;
80/// **Which implementation of each trait a store is built on.** One selector,
81/// read once at construction, never per operation — [`arms::StoreConfig`].
82pub mod arms;
83pub mod graph;
84pub mod index_layout;
85/// The shared, off-the-ack-path index builder — one indexer per account,
86/// gatling fan-out, index tables built last.
87pub mod indexer;
88pub mod memguard;
89pub mod progress;
90pub mod object;
91pub mod oid_index;
92/// Computing a git delta, for the one entry shape this engine cannot copy: a
93/// stored delta whose base falls outside the request and whose receiver holds
94/// nothing. The only place in this crate that computes one.
95pub mod delta;
96/// One pass over a pushed packfile's entries — the split the closure check
97/// falls out of. Ours, gated against gix's grammar entry for entry.
98pub mod pack_walk;
99pub mod pushlog;
100/// The read path as one stack: Ragnar `stree` in front, the Arrow index tables
101/// it points into, and the redb un-sealed tail it falls through to.
102pub mod read_stack;
103/// Pack entries to oids: the indexer's half of the split, off the ack path.
104pub mod resolve;
105/// §14's exploded objects table: resolved content, derived from the verbatim
106/// truth, built eagerly by the same indexer, droppable at any time.
107pub mod exploded;
108pub mod exploded_arrow;
109pub mod exploded_cache;
110pub use exploded_cache::{suppress_write_back, write_back_suppressed, SuppressWriteBack};
111pub mod forest;
112pub mod reach;
113pub mod refs;
114/// Store-side replication to another gunnar. **Deliberately empty** — signature
115/// and contract only, no transport.
116pub mod replicate;
117/// One repository's stored bytes in ONE FILE: [`replicate`]'s decisions with a
118/// body, and a file instead of a transport. `archive_out` / `archive_in`.
119pub mod archive_file;
120pub mod secrets;
121pub mod store;
122/// Garbage collection: one trait, two implementations
123/// ([`gc::CompactInPlace`] in place, [`gc::NewGeneration`] into a new
124/// generation — the default).
125pub mod gc;
126/// `GitOps` — the typed API gunnar calls, and the store that implements it.
127/// Base znippy never sees this trait.
128pub mod git_ops;
129/// `GitServe` — the **reading** contract: decoded reads, the `HEAD` accessor
130/// pair, negotiation and pack emission. Layered above [`git_ops`], answered out
131/// of Arrow IPC, and **containing no gix** — see the module header for why that
132/// is a rule rather than a coincidence.
133pub mod serve;
134/// **Stock `git` as the arbiter, inside a repository.** Test support only —
135/// nothing on a serving, storing or indexing path may call it, because it forks
136/// `git`. It is `pub` because `tests/concurrent_push.rs` compiles against the
137/// library, and it exists because `git index-pack --strict` *segfaults* outside
138/// a repository, which is how an oracle came to be incapable of failing.
139pub mod git_oracle;
140/// io_uring arm of [`archive_write`]. Linux only — the module is empty
141/// elsewhere rather than substituting a `pwrite` path under an io_uring name.
142pub mod uring_write;
143pub mod sections;
144#[cfg(test)]
145mod thin_storm;
146/// **The corpus the tests run on, generated rather than found.** Test support
147/// only, and compiled only under `cfg(test)`: it exists because the fixture
148/// used to be whichever repository `read_dir` handed back first on one
149/// developer's box. See the module header for the eight guards that measured.
150#[cfg(test)]
151pub(crate) mod pack_fixture;
152
153pub use archive_write::{ArchiveWrite, Faults, FastWriter, SafeWriter};
154pub use arms::{
155 ALL_ENV, DEFAULT_REDB_CACHE_BYTES, ENV_BOUNDARY_DELTA, ENV_EMIT_WORKERS, ENV_EXPLODE, ENV_GC,
156 ENV_BASE_BUDGET_BYTES, ENV_INDEX, ENV_INDEX_BATCH_ROWS, ENV_MEM_BUDGET_BYTES, ENV_MEM_BUDGET_PCT,
157 ENV_MEMINFO, ENV_REACH_COMMITS, ENV_REDB_CACHE, ENV_WRITER, GcArm, IndexArm, StoreConfig,
158 WriterArm, env_reads, env_reads_here, redb_cache_bytes, set_graph_cache_default, ENV_GRAPH_CACHE,
159 ENV_EXPLODE_BUDGET, ENV_RESOLVE_LOOKAHEAD_BYTES, ENV_RESOLVE_WORKERS,
160};
161/// **The runtime doors beside [`arms::set_graph_cache_default`]** — the whole of what a twin
162/// turns off or turns down, set from code instead of from the environment. An explicit
163/// environment variable still wins over every one of them; see each function.
164pub use exploded_arrow::{explode_default, set_explode_default};
165pub use exploded_cache::{budget_default, set_explode_budget_default};
166pub use resolve::{set_resolve_lookahead_default, set_resolve_workers_default};
167pub use indexer::{AccountIndexer, IndexJob, IndexRow, IndexerPool, Lookup, PushPath};
168#[cfg(target_os = "linux")]
169pub use uring_write::UringWriter;
170
171pub use graph::{CommitNode, decode_graph, graph_schema, read_graph};
172pub use object::{
173 GitHashKind, GitObject, GitObjectKind, PACKFILE_TYPE, PACK_INDEX_TYPE, PackFileKind, canonical,
174 is_oid_path, pack_path_kind, parse_canonical, parse_commit, tree_entries,
175};
176pub use oid_index::{GitOidIndex, OidEntry, OidHit, OidLayout, key_for_oid};
177pub use pushlog::{
178 CompactionPolicy, CompactionReport, Finish, PushLog, PushLogScan, scan_frames,
179};
180pub use reach::{ReachEntry, ReachPolicy, decode_reach, read_reach, reach_schema};
181pub use refs::{RefLog, RefState, RefUpdate, read_refs, refs_schema};
182pub use secrets::{SecretState, SecretUpdate, SecretsLog, read_secrets, secrets_schema};
183pub use sections::GitIndexBuilder;
184pub use git_ops::{
185 GitOps, GitStore, LookupPath, Oid, RefRow, SelectedStore, Stored, TxId, lookup_path,
186 open_from_env, open_selected,
187};
188pub use serve::{Caps, GitServe, PackStats, ReachSet, HEAD};
189/// The typed ref rejection, re-exported so a consumer of this crate reaches it
190/// without also naming the contract crate. `RefRejection::of(&err)` is the only
191/// sanctioned way to ask whether a ref write lost a race — never a message.
192pub use git_storage_trait::{Observed, RefCas, RefRejection, RefTarget};
193
194/// DenseUnion / `pkg_type` discriminant. Clear of the built-ins (1–25), media
195/// (25), skidbladnir (40) and rust-toolchain (41).
196pub const GIT_TYPE_ID: i8 = 42;
197
198/// `object_type` written when the entry is not parseable as a canonical git
199/// object. A distinct, queryable state — never a silent `blob`.
200pub const UNKNOWN_OBJECT_TYPE: &str = "unknown";
201
202/// Native git-object handler.
203pub struct NativeGitPlugin;
204
205impl NativeGitPlugin {
206 pub fn new() -> Self {
207 NativeGitPlugin
208 }
209}
210
211impl Default for NativeGitPlugin {
212 fn default() -> Self {
213 Self::new()
214 }
215}
216
217impl ArchiveTypePlugin for NativeGitPlugin {
218 fn name(&self) -> &str {
219 "git"
220 }
221
222 fn type_id(&self) -> i8 {
223 GIT_TYPE_ID
224 }
225
226 fn meta(&self) -> HandlerMeta {
227 HandlerMeta {
228 name: "git".into(),
229 aliases: vec!["gunnar".into(), "git-objects".into()],
230 type_id: GIT_TYPE_ID,
231 ecosystem: "Git object store (gunnar cold tier — one archive per repository)".into(),
232 // Left empty on purpose, and it is not an oversight. A loose git
233 // object carries no extension at all — its name IS its oid — and
234 // the pack entries this handler also claims are matched on their
235 // whole `pack-<oid>.<ext>` shape, not on a suffix. An extension
236 // list here would claim every `.pack` and `.idx` in any archive,
237 // which is wider than the truth. `matches_path` is the authority.
238 extensions: Vec::new(),
239 description: "Stores a git repository: either canonical objects keyed by oid hex, \
240 with the reserved __gunnar_oid__ (stree) / __gunnar_graph__ (commit \
241 graph) / __gunnar_reach__ (reachability bitmaps) sub-indexes, or the \
242 pack tier (pack-<id>.pack / .idx) that preserves the client's deflate \
243 and its delta chains"
244 .into(),
245 commands: vec![
246 HandlerCommand::new(
247 "inspect",
248 "Print type/size/sha1/sha256 for a file of canonical git object bytes",
249 ),
250 HandlerCommand::new(
251 "lookup",
252 "Resolve an oid against an archive's __gunnar_oid__ index: `git lookup <archive> <oid>`",
253 ),
254 HandlerCommand::new(
255 "graph",
256 "Print an archive's commit graph (oid, generation, time, parents)",
257 ),
258 HandlerCommand::new(
259 "refs",
260 "Print a live store's ref namespace: `git refs <store-root>`",
261 ),
262 ],
263 }
264 }
265
266 /// **CLI-only string dispatch** (§13.3). A server never comes through here:
267 /// it holds a [`GitStore`] and calls [`GitOps`] directly, typed.
268 ///
269 /// `refs` is what that delegation looks like — open the store, call the trait
270 /// method, print what it returned, and carry no logic of its own. The three
271 /// commands beside it are older and are **archive inspection**, not store
272 /// operations: they read a *sealed* archive's sections, which is a different
273 /// thing from a live store and is deliberately not modelled as a `GitOps`
274 /// call. They are left as they are rather than bent through a trait that does
275 /// not describe them.
276 fn run_command(&self, cmd: &str, args: &[String]) -> anyhow::Result<()> {
277 match cmd {
278 "refs" => {
279 let root = args
280 .first()
281 .ok_or_else(|| anyhow::anyhow!("usage: git refs <store-root>"))?;
282 // Everything below this line is printing. The answer comes from
283 // the trait.
284 let store = GitStore::open(std::path::Path::new(root), "cli")?;
285 for r in store.refs()? {
286 println!(
287 "{}\t{}{}",
288 r.name,
289 r.oid.as_deref().map(hex::encode).unwrap_or_else(|| "-".into()),
290 match (&r.peeled, &r.symref_target) {
291 (Some(p), _) => format!("\t^{}", hex::encode(p)),
292 (None, Some(t)) => format!("\t-> {t}"),
293 (None, None) => String::new(),
294 }
295 );
296 }
297 Ok(())
298 }
299 "inspect" => {
300 let path = args
301 .first()
302 .ok_or_else(|| anyhow::anyhow!("usage: git inspect <object-file>"))?;
303 let data = std::fs::read(path)?;
304 match parse_canonical(&data) {
305 Some(obj) => {
306 println!("type: {}", obj.kind.as_str());
307 println!("size: {}", obj.payload.len());
308 println!("sha1: {}", GitHashKind::Sha1.oid_hex_of(&data));
309 println!("sha256: {}", GitHashKind::Sha256.oid_hex_of(&data));
310 Ok(())
311 }
312 None => anyhow::bail!(
313 "'{path}' is not canonical git object bytes (`<type> <size>\\0<content>`)"
314 ),
315 }
316 }
317 "lookup" => {
318 let (archive, oid) = match (args.first(), args.get(1)) {
319 (Some(a), Some(o)) => (a, o),
320 _ => anyhow::bail!("usage: git lookup <archive> <oid-hex>"),
321 };
322 let index = GitOidIndex::open(std::path::Path::new(archive))?.ok_or_else(|| {
323 anyhow::anyhow!("'{archive}' carries no __gunnar_oid__ index")
324 })?;
325 match index.lookup_hex(oid) {
326 Some(hit) => {
327 println!("oid: {oid}");
328 println!("lookup_row: {}", hit.lookup_row);
329 println!("ordinal: {}", hit.ordinal);
330 Ok(())
331 }
332 None => anyhow::bail!("oid '{oid}' is not in '{archive}'"),
333 }
334 }
335 "graph" => {
336 let archive = args
337 .first()
338 .ok_or_else(|| anyhow::anyhow!("usage: git graph <archive>"))?;
339 let nodes = read_graph(std::path::Path::new(archive))?.ok_or_else(|| {
340 anyhow::anyhow!("'{archive}' carries no __gunnar_graph__ section")
341 })?;
342 println!("commits: {}", nodes.len());
343 for n in &nodes {
344 println!(
345 " {} gen={} time={} parents=[{}]",
346 n.oid,
347 n.generation,
348 n.committer_time.map(|t| t.to_string()).unwrap_or_else(|| "-".into()),
349 n.parents.join(" ")
350 );
351 }
352 Ok(())
353 }
354 other => anyhow::bail!("git: unknown subcommand '{other}'"),
355 }
356 }
357
358 /// A git archive's entries are either **oids** — the whole `relative_path`
359 /// is 40 or 64 lowercase hex characters — or the **packs** of a repository's
360 /// cold tier, `pack-<id>.pack` / `pack-<id>.idx`.
361 ///
362 /// Both are the same ecosystem and so belong to one handler (P-1). Which of
363 /// the two an archive holds is not a variant of the format: it is what the
364 /// writer had. gunnar's `repack()` produces a consolidated pack and seals
365 /// that, because a pack preserves the pushing client's own deflate and its
366 /// delta chains, and an inflated per-oid tier destroys both permanently.
367 fn matches_path(&self, path: &str) -> bool {
368 is_oid_path(path) || pack_path_kind(path).is_some()
369 }
370
371 fn schema_fields(&self) -> Vec<Field> {
372 vec![
373 Field::new("object_type", DataType::Utf8, true),
374 // UInt32: the index's extension-column writer materialises UInt32 and
375 // Utf8 only. A git object larger than 4 GiB saturates here; its exact
376 // byte length is always available from the base `uncompressed_size`
377 // column, which is u64 and is the authority.
378 Field::new("object_size", DataType::UInt32, true),
379 ]
380 }
381
382 fn extract_metadata(&self, path: &str, data: &[u8]) -> Option<ExtensionRow> {
383 if !self.matches_path(path) {
384 return None;
385 }
386 let mut f: HashMap<String, ExtensionValue> = HashMap::new();
387
388 // A pack is typed by its magic, never by its name. A name is a claim
389 // the writer made; the magic is what the bytes are. `pack-<hex>.pack`
390 // over something that is not a packfile degrades to `unknown` exactly
391 // as malformed object bytes do (P-4) — a wrong type in the index is
392 // worse than an honest absence, because it is queried and believed.
393 if let Some(kind) = pack_path_kind(path) {
394 let typed = if data.starts_with(kind.magic()) {
395 kind.as_str()
396 } else {
397 UNKNOWN_OBJECT_TYPE
398 };
399 f.insert("object_type".into(), ExtensionValue::Str(typed.into()));
400 f.insert(
401 "object_size".into(),
402 ExtensionValue::U32(data.len().min(u32::MAX as usize) as u32),
403 );
404 return Some(ExtensionRow { fields: f });
405 }
406
407 match parse_canonical(data) {
408 Some(obj) => {
409 f.insert("object_type".into(), ExtensionValue::Str(obj.kind.as_str().into()));
410 f.insert(
411 "object_size".into(),
412 ExtensionValue::U32(obj.payload.len().min(u32::MAX as usize) as u32),
413 );
414 }
415 None => {
416 // P-4: a decompress bomb, a truncated object or plain garbage
417 // still writes a row — typed `unknown`, sized by what is there.
418 f.insert(
419 "object_type".into(),
420 ExtensionValue::Str(UNKNOWN_OBJECT_TYPE.into()),
421 );
422 f.insert(
423 "object_size".into(),
424 ExtensionValue::U32(data.len().min(u32::MAX as usize) as u32),
425 );
426 }
427 }
428 Some(ExtensionRow { fields: f })
429 }
430}
431
432#[cfg(test)]
433mod tests {
434 use super::*;
435 use crate::object::canonical;
436
437 fn get<'a>(row: &'a ExtensionRow, k: &str) -> Option<&'a ExtensionValue> {
438 row.fields.get(k)
439 }
440
441 #[test]
442 fn claims_oid_paths_and_nothing_else() {
443 let p = NativeGitPlugin::new();
444 assert!(p.matches_path(&"a1b2c3d4".repeat(5))); // 40 hex
445 assert!(p.matches_path(&"0f".repeat(32))); // 64 hex
446 assert!(!p.matches_path("refs/heads/main"));
447 assert!(!p.matches_path("objects/pack/pack-abc.pack"));
448 assert!(!p.matches_path(&"A1B2C3D4".repeat(5)));
449 }
450
451 /// The pack tier's two file names are claimed, and only in the shape git
452 /// itself writes. A bare `.pack` suffix is not enough: an archive of
453 /// arbitrary files must not have its entries retyped as git packs.
454 #[test]
455 fn claims_the_pack_tier_by_its_whole_name_not_by_a_suffix() {
456 let p = NativeGitPlugin::new();
457 let id40 = "a1b2c3d4".repeat(5);
458 let id64 = "0f".repeat(32);
459 assert_eq!(pack_path_kind(&format!("pack-{id40}.pack")), Some(PackFileKind::Data));
460 assert_eq!(pack_path_kind(&format!("pack-{id64}.idx")), Some(PackFileKind::Index));
461 assert!(p.matches_path(&format!("pack-{id64}.pack")));
462 assert!(p.matches_path(&format!("objects/pack/pack-{id40}.idx")));
463
464 for not_ours in [
465 "pack-nothex.pack",
466 "somefile.pack",
467 "pack-.pack",
468 &format!("pack-{id40}.bitmap"),
469 &format!("pack-{}.pack", "A1B2C3D4".repeat(5)),
470 &format!("{id40}.pack"),
471 ] {
472 assert_eq!(pack_path_kind(not_ours), None, "wrongly claimed {not_ours}");
473 }
474 assert!(!p.matches_path("somefile.pack"));
475 }
476
477 /// A pack is typed by its **magic**, never by the name the writer chose.
478 /// A file called `pack-….pack` that does not start with `PACK` is
479 /// `unknown` — the same honest state malformed object bytes get (P-4).
480 #[test]
481 fn a_pack_is_typed_by_its_magic_and_a_liar_is_unknown() {
482 let p = NativeGitPlugin::new();
483 let id = "0f".repeat(32);
484
485 let mut pack = b"PACK".to_vec();
486 pack.extend_from_slice(&2u32.to_be_bytes());
487 pack.extend_from_slice(&7u32.to_be_bytes());
488 let row = p.extract_metadata(&format!("pack-{id}.pack"), &pack).unwrap();
489 assert_eq!(get(&row, "object_type"), Some(&ExtensionValue::Str(PACKFILE_TYPE.into())));
490 assert_eq!(get(&row, "object_size"), Some(&ExtensionValue::U32(pack.len() as u32)));
491
492 let idx = b"\xfftOc\x00\x00\x00\x02".to_vec();
493 let row = p.extract_metadata(&format!("pack-{id}.idx"), &idx).unwrap();
494 assert_eq!(get(&row, "object_type"), Some(&ExtensionValue::Str(PACK_INDEX_TYPE.into())));
495
496 // Now the liars. Each is named as a pack and is not one.
497 for (name, bytes) in [
498 (format!("pack-{id}.pack"), &b"NOTAPACK"[..]),
499 (format!("pack-{id}.idx"), &b"PACK\0\0\0\x02"[..]),
500 (format!("pack-{id}.pack"), &b""[..]),
501 ] {
502 let row = p.extract_metadata(&name, bytes).expect("a claimed path always yields a row");
503 assert_eq!(
504 get(&row, "object_type"),
505 Some(&ExtensionValue::Str(UNKNOWN_OBJECT_TYPE.into())),
506 "{name} carries {bytes:?}, which is not that kind of file — it must not be typed \
507 from its name"
508 );
509 }
510 }
511
512 #[test]
513 fn types_and_sizes_come_from_the_stored_bytes() {
514 let p = NativeGitPlugin::new();
515 let body = b"hello world";
516 let bytes = canonical(GitObjectKind::Blob, body);
517 let oid = GitHashKind::Sha256.oid_hex_of(&bytes);
518 let row = p.extract_metadata(&oid, &bytes).unwrap();
519 assert_eq!(get(&row, "object_type"), Some(&ExtensionValue::Str("blob".into())));
520 assert_eq!(get(&row, "object_size"), Some(&ExtensionValue::U32(body.len() as u32)));
521
522 let commit = canonical(GitObjectKind::Commit, b"tree x\n\nmsg\n");
523 let coid = GitHashKind::Sha1.oid_hex_of(&commit);
524 let crow = p.extract_metadata(&coid, &commit).unwrap();
525 assert_eq!(get(&crow, "object_type"), Some(&ExtensionValue::Str("commit".into())));
526 }
527
528 #[test]
529 fn garbage_degrades_to_unknown_and_never_panics() {
530 let p = NativeGitPlugin::new();
531 let oid = "d".repeat(64);
532 for bad in [&b""[..], &b"\0\0\0"[..], &[0xffu8; 4096][..], &b"blob 99\0short"[..]] {
533 let row = p.extract_metadata(&oid, bad).expect("a claimed path always yields a row");
534 assert_eq!(
535 get(&row, "object_type"),
536 Some(&ExtensionValue::Str(UNKNOWN_OBJECT_TYPE.into())),
537 "unparseable bytes must be typed `unknown`, never guessed"
538 );
539 assert_eq!(get(&row, "object_size"), Some(&ExtensionValue::U32(bad.len() as u32)));
540 }
541 }
542
543 #[test]
544 fn a_path_that_is_not_an_oid_yields_no_row() {
545 let p = NativeGitPlugin::new();
546 assert!(p.extract_metadata("HEAD", b"ref: refs/heads/main\n").is_none());
547 }
548
549 #[test]
550 fn meta_is_the_discovery_record() {
551 let m = NativeGitPlugin::new().meta();
552 assert_eq!(m.name, "git");
553 assert_eq!(m.type_id, GIT_TYPE_ID);
554 assert!(m.aliases.contains(&"gunnar".to_string()));
555 assert_eq!(m.commands.len(), 4);
556 assert!(
557 m.commands.iter().any(|c| c.name == "refs"),
558 "the GitOps-delegating command is not advertised"
559 );
560 }
561}