diff --git a/Cargo.lock b/Cargo.lock index 1a4f567..5e5eb28 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -64,6 +64,21 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "arc-swap" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +dependencies = [ + "rustversion", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.1" @@ -79,6 +94,23 @@ dependencies = [ "generic-array", ] +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "regex-automata", + "serde_core", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "cfg-if" version = "1.0.4" @@ -116,7 +148,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 3.0.4", ] [[package]] @@ -159,6 +191,37 @@ dependencies = [ "typenum", ] +[[package]] +name = "defmt" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "defmt-parser" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +dependencies = [ + "thiserror", +] + [[package]] name = "digest" version = "0.10.7" @@ -179,6 +242,16 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "faster-hex" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7223ae2d2f179b803433d9c830478527e92b8117eab39460edae7f1614d9fb73" +dependencies = [ + "heapless", + "serde", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -193,6 +266,7 @@ checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" dependencies = [ "crc32fast", "miniz_oxide", + "zlib-rs", ] [[package]] @@ -216,6 +290,229 @@ dependencies = [ "r-efi", ] +[[package]] +name = "gix-actor" +version = "0.35.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "987a51a7e66db6ef4dc030418eb2a42af6b913a79edd8670766122d8af3ba59e" +dependencies = [ + "bstr", + "gix-date", + "gix-utils", + "itoa", + "thiserror", + "winnow", +] + +[[package]] +name = "gix-chunk" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c356b3825677cb6ff579551bb8311a81821e184453cbd105e2fc5311b288eeb" +dependencies = [ + "thiserror", +] + +[[package]] +name = "gix-date" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "661245d045aa7c16ba4244daaabd823c562c3e45f1f25b816be2c57ee09f2171" +dependencies = [ + "bstr", + "itoa", + "jiff", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-features" +version = "0.43.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1543cd9b8abcbcebaa1a666a5c168ee2cda4dea50d3961ee0e6d1c42f81e5b" +dependencies = [ + "crc32fast", + "flate2", + "gix-path", + "gix-trace", + "gix-utils", + "libc", + "prodash", + "thiserror", + "walkdir", +] + +[[package]] +name = "gix-fs" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a4d90307d064fa7230e0f87b03231be28f8ba63b913fc15346f489519d0c304" +dependencies = [ + "bstr", + "fastrand", + "gix-features", + "gix-path", + "gix-utils", + "thiserror", +] + +[[package]] +name = "gix-hash" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "251fad79796a731a2a7664d9ea95ee29a9e99474de2769e152238d4fdb69d50e" +dependencies = [ + "faster-hex", + "gix-features", + "sha1-checked", + "thiserror", +] + +[[package]] +name = "gix-hashtable" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c35300b54896153e55d53f4180460931ccd69b7e8d2f6b9d6401122cdedc4f07" +dependencies = [ + "gix-hash", + "hashbrown", + "parking_lot", +] + +[[package]] +name = "gix-object" +version = "0.50.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d69ce108ab67b65fbd4fb7e1331502429d78baeb2eee10008bdef55765397c07" +dependencies = [ + "bstr", + "gix-actor", + "gix-date", + "gix-features", + "gix-hash", + "gix-hashtable", + "gix-path", + "gix-utils", + "gix-validate", + "itoa", + "smallvec", + "thiserror", + "winnow", +] + +[[package]] +name = "gix-odb" +version = "0.70.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9d7af10fda9df0bb4f7f9bd507963560b3c66cb15a5b825caf752e0eb109ac" +dependencies = [ + "arc-swap", + "gix-date", + "gix-features", + "gix-fs", + "gix-hash", + "gix-hashtable", + "gix-object", + "gix-pack", + "gix-path", + "gix-quote", + "parking_lot", + "tempfile", + "thiserror", +] + +[[package]] +name = "gix-pack" +version = "0.60.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8571df89bfca5abb49c3e3372393f7af7e6f8b8dbe2b96303593cef5b263019" +dependencies = [ + "gix-chunk", + "gix-features", + "gix-hash", + "gix-object", + "gix-path", + "memmap2", + "smallvec", + "thiserror", +] + +[[package]] +name = "gix-path" +version = "0.10.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cb06c3e4f8eed6e24fd915fa93145e28a511f4ea0e768bae16673e05ed3f366" +dependencies = [ + "bstr", + "gix-trace", + "gix-validate", + "thiserror", +] + +[[package]] +name = "gix-quote" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96fc2ff2ec8cc0c92807f02eab1f00eb02619fc2810d13dc42679492fcc36757" +dependencies = [ + "bstr", + "gix-utils", + "thiserror", +] + +[[package]] +name = "gix-trace" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be3eb81d9dc914335923e50d52829c551feefd6a72d176c4130c546b67a60814" + +[[package]] +name = "gix-utils" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0da1c46491b49458a446cc76f0085860f8164c2290742e0aa8c653ce67240a97" +dependencies = [ + "fastrand", + "getrandom", + "unicode-normalization", +] + +[[package]] +name = "gix-validate" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b1e63a5b516e970a594f870ed4571a8fdcb8a344e7bd407a20db8bd61dbfde4" +dependencies = [ + "bstr", + "thiserror", +] + +[[package]] +name = "hash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" +dependencies = [ + "byteorder", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" + +[[package]] +name = "heapless" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" +dependencies = [ + "hash32", + "stable_deref_trait", +] + [[package]] name = "heck" version = "0.5.0" @@ -228,6 +525,65 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jiff" +version = "0.2.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "668b7183bd07af9a4885f5c35b0cc5c83c4607a913c16b7e17291832910d2dcc" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7feca88439efe53da3754500c1851dedf3cb36c524dd5cf8225cc0794de95d09" +dependencies = [ + "defmt", +] + +[[package]] +name = "jiff-static" +version = "0.2.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a69dcb3a21cfb32ce1cd056169337ca284af0766dd766e7878819b251a49204" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "libc" version = "0.2.189" @@ -240,6 +596,36 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -262,6 +648,44 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +dependencies = [ + "portable-atomic", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -271,6 +695,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "prodash" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6efc566849d3d9d737c5cb06cc50e48950ebe3d3f9d70631490fff3a07b139" +dependencies = [ + "parking_lot", +] + [[package]] name = "quote" version = "1.0.47" @@ -286,6 +719,21 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.1", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" + [[package]] name = "rit" version = "0.1.0" @@ -293,6 +741,9 @@ dependencies = [ "anyhow", "clap", "flate2", + "gix-hash", + "gix-object", + "gix-odb", "sha1", "tempfile", "thiserror", @@ -304,13 +755,63 @@ version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ - "bitflags", + "bitflags 2.13.1", "errno", "libc", "linux-raw-sys", "windows-sys", ] +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + [[package]] name = "sha1" version = "0.10.7" @@ -322,18 +823,51 @@ dependencies = [ "digest", ] +[[package]] +name = "sha1-checked" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89f599ac0c323ebb1c6082821a54962b839832b03984598375bff3975b804423" +dependencies = [ + "digest", + "sha1", +] + [[package]] name = "simd-adler32" version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.4" @@ -375,9 +909,24 @@ checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.4", ] +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + [[package]] name = "typenum" version = "1.20.1" @@ -390,6 +939,15 @@ version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + [[package]] name = "utf8parse" version = "0.2.2" @@ -402,6 +960,25 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + [[package]] name = "windows-link" version = "0.2.1" @@ -416,3 +993,18 @@ checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ "windows-link", ] + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "zlib-rs" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" diff --git a/Cargo.toml b/Cargo.toml index a41be48..98aa2e9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,9 @@ path = "src/main.rs" anyhow = "1" clap = { version = "4", features = ["derive"] } flate2 = "1" +gix-hash = "0.19.0" +gix-object = "0.50.2" +gix-odb = "0.70.0" sha1 = "0.10" thiserror = "2" diff --git a/src/error.rs b/src/error.rs index 0c27a73..ef138bc 100644 --- a/src/error.rs +++ b/src/error.rs @@ -63,6 +63,13 @@ pub enum ForgeError { /// zlib decompression of a loose object failed or exceeded the size cap. #[error("decompression failed: {0}")] Decompress(String), + + /// A packfile could not be opened or an object could not be decoded from a + /// pack (corrupt pack, broken delta chain, or an error surfaced by the + /// gitoxide `gix-pack`/`gix-odb` engine). Repository data is adversarial, so + /// pack decode errors fail **closed** as a typed error rather than a panic. + #[error("packfile error: {0}")] + Pack(String), } impl ForgeError { diff --git a/src/headers.rs b/src/headers.rs index f49a202..6389705 100644 --- a/src/headers.rs +++ b/src/headers.rs @@ -108,6 +108,9 @@ mod tests { assert_eq!(block.headers[0].key, "gpgsig"); assert_eq!(block.headers[0].value, b"line1\nline2\nline3"); // round-trips back to the on-disk continuation form - assert_eq!(serialize_value(&block.headers[0].value), b"line1\n line2\n line3"); + assert_eq!( + serialize_value(&block.headers[0].value), + b"line1\n line2\n line3" + ); } } diff --git a/src/lib.rs b/src/lib.rs index 09decc9..b059240 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,6 +15,12 @@ //! loose object kinds with byte-exact serialization. //! - [`odb`] — the loose object database under `.git/objects/xx/...` with zlib //! compression and read-time SHA-1 verification. +//! - [`pack`] — **packed** object reads, adopted from **gitoxide** (`gix-odb` / +//! `gix-pack`): objects living in `.git/objects/pack/*.pack` are resolved +//! (including delta chains) through the same [`Object`]/[`Repository`] API, so +//! callers get one interface over loose **or** packed objects. This is the +//! OSS-fork strategy — the highest-cost from-scratch subsystem is reused, not +//! rewritten, while `rit` keeps ownership of the loose path. //! - [`refs`] — `HEAD`, loose refs, symbolic refs, and `packed-refs`. //! - [`repo`] — the porcelain-ish [`Repository`] API: `hash-object`, `cat-file`, //! `rev-parse`, tree/commit traversal, and `log`. @@ -27,9 +33,10 @@ //! //! ## Deferred (per PLAN) //! -//! Packfiles/delta resolution, the index/worktree, the smart wire protocol, -//! merge/rebase, SHA-256 repositories, SHA-1 collision detection (sha1dc), and -//! the entire forge layer are out of scope for this slice. +//! The index/worktree, the smart wire protocol, merge/rebase, SHA-256 +//! repositories, SHA-1 collision detection (sha1dc), and the entire forge layer +//! are out of scope for this slice. Packfile **reads** are now covered by +//! adopting gitoxide (see [`pack`]); pack **writing** remains deferred. pub mod blob; pub mod commit; @@ -38,6 +45,7 @@ pub mod headers; pub mod object; pub mod odb; pub mod oid; +pub mod pack; pub mod refs; pub mod repo; pub mod signature; @@ -50,6 +58,7 @@ pub use error::{ForgeError, Result}; pub use object::{hash_content, parse_loose, Object, ObjectType}; pub use odb::Odb; pub use oid::ObjectId; +pub use pack::PackStore; pub use refs::{RefTarget, Refs}; pub use repo::Repository; pub use signature::Signature; diff --git a/src/odb.rs b/src/odb.rs index 0fd5b6d..b7407ad 100644 --- a/src/odb.rs +++ b/src/odb.rs @@ -8,6 +8,7 @@ use crate::error::{ForgeError, Result}; use crate::object::{self, Object, ObjectType, MAX_OBJECT_SIZE}; use crate::oid::ObjectId; +use crate::pack::PackStore; use flate2::read::ZlibDecoder; use flate2::write::ZlibEncoder; use flate2::Compression; @@ -15,17 +16,29 @@ use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; -/// A loose object database rooted at a `.git/objects` directory. +/// The object database rooted at a `.git/objects` directory. +/// +/// `rit` owns the **loose** path (write + verified read of `objects/xx/`), +/// while the **packed** path is delegated to gitoxide via an optional +/// [`PackStore`]. Reads try loose first (the `rit` code), then fall back to +/// packs (gitoxide), so every consumer sees one unified object interface. pub struct Odb { objects_dir: PathBuf, + /// Packed-object reader (gitoxide). `None` only if the store could not be + /// opened at all; a missing/empty pack directory still yields a working + /// store that simply never finds anything. + pack: Option, } impl Odb { /// Open the object database inside a `.git` directory. pub fn new(git_dir: &Path) -> Self { - Self { - objects_dir: git_dir.join("objects"), - } + let objects_dir = git_dir.join("objects"); + // Opening the gitoxide store is cheap (indices load lazily). If it fails + // we simply have no packed fallback; the loose path still works, and any + // genuinely corrupt pack surfaces as a typed error at read time. + let pack = PackStore::open(&objects_dir).ok(); + Self { objects_dir, pack } } /// The on-disk path for an object (`objects/xx/`). @@ -35,9 +48,9 @@ impl Odb { .join(oid.file_suffix()) } - /// Whether an object exists on disk. + /// Whether an object exists, loose **or** packed. pub fn contains(&self, oid: &ObjectId) -> bool { - self.loose_path(oid).exists() + self.loose_path(oid).exists() || self.pack.as_ref().is_some_and(|p| p.contains(oid)) } /// Write a payload as a loose object and return its oid. @@ -75,10 +88,22 @@ impl Odb { } /// Read an object's raw type and payload, verifying its SHA-1. + /// + /// Tries the loose store first (rit's own reader); on a loose miss, falls + /// back to the packed store (gitoxide). Both paths verify the bytes hash + /// back to `oid` before returning them. pub fn read_raw(&self, oid: &ObjectId) -> Result<(ObjectType, Vec)> { let path = self.loose_path(oid); - let compressed = std::fs::read(&path) - .map_err(|_| ForgeError::ObjectNotFound(oid.to_hex()))?; + let compressed = match std::fs::read(&path) { + Ok(bytes) => bytes, + // Not loose — try the packed path (gitoxide) if we have one. + Err(_) => { + return match &self.pack { + Some(pack) => pack.read_raw(oid), + None => Err(ForgeError::ObjectNotFound(oid.to_hex())), + }; + } + }; let full = zlib_decompress(&compressed)?; // Verify integrity before trusting the bytes. @@ -135,6 +160,26 @@ impl Odb { } } let _ = file_part; + + // Also consult packed objects (gitoxide). After `git repack`/`git gc` + // the loose copies are gone, so packed prefix resolution keeps + // abbreviated-oid lookups working on packed repositories. + if let Some(pack) = &self.pack { + match pack.resolve_prefix(prefix) { + Ok(Some(id)) => { + if !matches.contains(&id) { + matches.push(id); + } + } + Ok(None) => {} + // A prefix ambiguous within the packs is ambiguous overall. + Err(ForgeError::AmbiguousPrefix(_)) => { + return Err(ForgeError::AmbiguousPrefix(prefix.to_string())) + } + Err(e) => return Err(e), + } + } + match matches.len() { 0 => Err(ForgeError::ObjectNotFound(prefix.to_string())), 1 => Ok(matches[0]), diff --git a/src/pack.rs b/src/pack.rs new file mode 100644 index 0000000..7af0ace --- /dev/null +++ b/src/pack.rs @@ -0,0 +1,131 @@ +//! Packed-object reads, adopted from **gitoxide** (the `gix-*` crates). +//! +//! ## Why this module exists (the OSS-fork strategy) +//! +//! Packfiles + delta resolution are the single biggest from-scratch cost in a +//! Git implementation (see `ARCHITECTURE.md` §7: the `rit-pack` crate is +//! estimated at ~12,000 LOC — the largest line item). Rather than re-implement +//! the `.pack`/`.idx` format, variable-length entry headers, the `OFS_DELTA` / +//! `REF_DELTA` copy-and-insert instruction stream, delta-chain resolution, and +//! the fan-out index binary search, `rit` **adopts gitoxide**: this module is a +//! thin adapter over [`gix_odb`], whose [`gix_pack`] engine already implements +//! all of the above, correctness-tested against real Git. +//! +//! ## Division of labour +//! +//! `rit` keeps ownership of the **loose** object path — its own hand-written, +//! interop-verified reader/writer in [`crate::odb`]. gitoxide is consulted only +//! as the **packed** path: when a loose object is absent, [`PackStore`] resolves +//! it out of `.git/objects/pack/*.pack` (following delta chains across the pack, +//! including bases stored as other packed or loose objects). Callers see one +//! unified interface via [`crate::odb::Odb`] and [`crate::repo::Repository`]. +//! +//! ## Fail-closed +//! +//! Every gitoxide error is mapped to a typed [`ForgeError`] — never a panic. And +//! because a packfile is adversarial input just like a loose object, the bytes +//! gitoxide returns are **re-hashed** and checked against the requested object +//! id before being trusted, exactly mirroring the loose path's verification. + +use crate::error::{ForgeError, Result}; +use crate::object::{self, ObjectType}; +use crate::oid::ObjectId; +use gix_object::{Exists, Find}; +use std::path::Path; + +/// A read-only view over a repository's packfiles, backed by gitoxide's +/// `gix-odb` store (which drives the `gix-pack` decoder). +/// +/// Opening is cheap: gitoxide loads pack indices lazily on first access, so a +/// repository with no packs (or an empty object database) constructs a +/// `PackStore` that simply never finds anything. +pub struct PackStore { + /// The gitoxide object-database handle rooted at `.git/objects`. + handle: gix_odb::Handle, +} + +impl PackStore { + /// Open the gitoxide-backed store rooted at a `.git/objects` directory. + pub fn open(objects_dir: &Path) -> Result { + let handle = gix_odb::at(objects_dir) + .map_err(|e| ForgeError::Pack(format!("opening object store: {e}")))?; + Ok(Self { handle }) + } + + /// Convert a `rit` [`ObjectId`] into a gitoxide id (both are 20-byte SHA-1). + fn to_gix(oid: &ObjectId) -> gix_hash::ObjectId { + gix_hash::ObjectId::from(*oid.as_bytes()) + } + + /// Whether the object is resolvable through gitoxide (packed, or loose as a + /// safety net). Consulted only after `rit`'s own loose check misses. + pub fn contains(&self, oid: &ObjectId) -> bool { + let gid = Self::to_gix(oid); + self.handle.exists(gid.as_ref()) + } + + /// Read an object's type and canonical, fully-inflated payload from a pack. + /// + /// Returns [`ForgeError::ObjectNotFound`] when the object is in no pack, a + /// [`ForgeError::Pack`] on a decode failure (corrupt pack / broken delta + /// chain), and [`ForgeError::HashMismatch`] if the decoded bytes do not hash + /// back to `oid` (fail-closed integrity check). + pub fn read_raw(&self, oid: &ObjectId) -> Result<(ObjectType, Vec)> { + let gid = Self::to_gix(oid); + let mut buf = Vec::new(); + let data = self + .handle + .try_find(gid.as_ref(), &mut buf) + .map_err(|e| ForgeError::Pack(format!("decoding {oid}: {e}")))? + .ok_or_else(|| ForgeError::ObjectNotFound(oid.to_hex()))?; + + let obj_type = map_kind(data.kind); + let payload = data.data.to_vec(); + + // Re-verify: the decompressed, delta-resolved bytes must hash back to the + // requested oid — the same trust boundary the loose path enforces. + let (computed, _) = object::hash_content(obj_type, &payload); + if &computed != oid { + return Err(ForgeError::HashMismatch { + looked_up: oid.to_hex(), + computed: computed.to_hex(), + }); + } + Ok((obj_type, payload)) + } + + /// Resolve an abbreviated hex prefix against packed objects. + /// + /// Returns `Ok(None)` when no packed object matches, `Ok(Some(id))` for a + /// unique match, and [`ForgeError::AmbiguousPrefix`] when more than one + /// packed object shares the prefix. + pub fn resolve_prefix(&self, prefix: &str) -> Result> { + let gprefix = gix_hash::Prefix::from_hex(prefix) + .map_err(|e| ForgeError::Pack(format!("invalid prefix {prefix:?}: {e}")))?; + match self + .handle + .lookup_prefix(gprefix, None) + .map_err(|e| ForgeError::Pack(format!("prefix lookup {prefix:?}: {e}")))? + { + None => Ok(None), + Some(Err(())) => Err(ForgeError::AmbiguousPrefix(prefix.to_string())), + Some(Ok(id)) => { + let raw: [u8; 20] = id + .as_bytes() + .try_into() + .map_err(|_| ForgeError::Pack("unexpected hash length from pack".into()))?; + Ok(Some(ObjectId::from_bytes(raw))) + } + } + } +} + +/// Map a gitoxide object kind onto `rit`'s [`ObjectType`]. +fn map_kind(kind: gix_object::Kind) -> ObjectType { + match kind { + gix_object::Kind::Blob => ObjectType::Blob, + gix_object::Kind::Tree => ObjectType::Tree, + gix_object::Kind::Commit => ObjectType::Commit, + gix_object::Kind::Tag => ObjectType::Tag, + } +} diff --git a/src/refs.rs b/src/refs.rs index 341d4e7..c846304 100644 --- a/src/refs.rs +++ b/src/refs.rs @@ -153,11 +153,7 @@ fn parse_ref_content(content: &str) -> Result { } /// Recursively collect loose refs under `dir`, keyed by full ref name. -fn collect_loose( - root: &Path, - dir: &Path, - out: &mut HashMap, -) -> Result<()> { +fn collect_loose(root: &Path, dir: &Path, out: &mut HashMap) -> Result<()> { let read_dir = match std::fs::read_dir(dir) { Ok(rd) => rd, Err(_) => return Ok(()), diff --git a/src/repo.rs b/src/repo.rs index c68579a..7df2854 100644 --- a/src/repo.rs +++ b/src/repo.rs @@ -33,11 +33,7 @@ impl Repository { } let odb = Odb::new(&git_dir); let refs = Refs::new(&git_dir); - Ok(Self { - git_dir, - odb, - refs, - }) + Ok(Self { git_dir, odb, refs }) } /// Discover a repository by walking up from `start` looking for `.git`. diff --git a/src/signature.rs b/src/signature.rs index 39f8de7..398684e 100644 --- a/src/signature.rs +++ b/src/signature.rs @@ -80,14 +80,20 @@ mod tests { #[test] fn parses_standard_signature() { - let sig = Signature::parse("Alice Example 1700000000 +0100", "commit") - .unwrap(); + let sig = Signature::parse( + "Alice Example 1700000000 +0100", + "commit", + ) + .unwrap(); assert_eq!(sig.name, "Alice Example"); assert_eq!(sig.email, "alice@example.com"); assert_eq!(sig.time, 1700000000); assert_eq!(sig.tz, "+0100"); // raw preserved for byte-exact re-serialization - assert_eq!(sig.to_raw(), "Alice Example 1700000000 +0100"); + assert_eq!( + sig.to_raw(), + "Alice Example 1700000000 +0100" + ); } #[test] diff --git a/tests/interop.rs b/tests/interop.rs index 1c4540d..84bb33f 100644 --- a/tests/interop.rs +++ b/tests/interop.rs @@ -12,7 +12,7 @@ use std::path::Path; use std::process::Command; use rit::object::{hash_content, Object}; -use rit::{ObjectType, Repository}; +use rit::{ObjectId, ObjectType, Repository}; use tempfile::TempDir; /// Run `git` with args in `cwd`, returning trimmed stdout; panics on failure. @@ -73,10 +73,51 @@ fn init_repo_with_commit() -> TempDir { dir } +/// The deterministic `-c` identity overrides used for reproducible commits. +const ID_OVERRIDES: [&str; 4] = [ + "-c", + "user.name=Forge Tester", + "-c", + "user.email=forge@example.com", +]; + +/// Commit the current index with the fixed identity and the given message. +fn commit_all(p: &Path, message: &str) { + git(p, &["add", "."]); + let mut args: Vec<&str> = ID_OVERRIDES.to_vec(); + args.extend_from_slice(&["commit", "-q", "-m", message]); + git(p, &args); +} + +/// Force **every reachable object into a single packfile** and drop the loose +/// copies — the real-git way to move objects out of loose storage and into a +/// pack (`git repack -a -d` builds the pack; `git prune-packed` removes the now +/// redundant loose objects). After this, any object we can still read *must* +/// have come from the packfile. +fn pack_everything(p: &Path) { + git(p, &["repack", "-a", "-d"]); + git(p, &["prune-packed"]); +} + +/// Assert a packfile physically exists under `.git/objects/pack`. +fn assert_has_packfile(p: &Path) { + let pack_dir = p.join(".git").join("objects").join("pack"); + let has_pack = std::fs::read_dir(&pack_dir) + .expect("pack directory should exist after repack") + .flatten() + .any(|e| e.path().extension().map(|x| x == "pack").unwrap_or(false)); + assert!(has_pack, "expected a .pack file under {pack_dir:?}"); +} + #[test] fn blob_oid_matches_git_hash_object() { let dir = tempfile::tempdir().unwrap(); - let contents: &[&[u8]] = &[b"hello world\n", b"", b"no trailing newline", b"\x00\x01\x02binary"]; + let contents: &[&[u8]] = &[ + b"hello world\n", + b"", + b"no trailing newline", + b"\x00\x01\x02binary", + ]; for (i, content) in contents.iter().enumerate() { let file = dir.path().join(format!("f{i}.bin")); @@ -265,7 +306,10 @@ fn log_walks_multi_commit_history() { .map(str::to_string) .collect(); let ours: Vec = history.iter().map(|(oid, _)| oid.to_hex()).collect(); - assert_eq!(ours, git_list, "log order/content differs from git rev-list"); + assert_eq!( + ours, git_list, + "log order/content differs from git rev-list" + ); assert_eq!(history[0].1.summary(), "third commit"); } @@ -290,3 +334,271 @@ fn corrupt_object_is_rejected_not_panicked() { assert!(result.is_err(), "corrupt object must be rejected"); } } + +// --------------------------------------------------------------------------- +// Packfile interop — the objects are read from a PACKED repository (via the +// gitoxide-backed pack path), and every result is cross-checked against real +// `git`. Each test first proves the object is no longer loose, so a pass can +// only mean the packfile reader worked. +// --------------------------------------------------------------------------- + +#[test] +fn reads_commit_tree_blob_from_packfile() { + let dir = init_repo_with_commit(); + let p = dir.path(); + pack_everything(p); + assert_has_packfile(p); + + let repo = Repository::discover(p).unwrap(); + let head = repo.head().unwrap(); + + // Prove the object is NOT loose: it can only be served from the packfile. + assert!( + !repo.odb().loose_path(&head).exists(), + "HEAD should be packed, but a loose object still exists" + ); + assert_eq!(head.to_hex(), git(p, &["rev-parse", "HEAD"])); + + // Commit decoded from the pack matches git. + let commit = repo.commit(&head).unwrap(); + assert_eq!(commit.tree.to_hex(), git(p, &["rev-parse", "HEAD^{tree}"])); + assert_eq!(commit.author.name, "Forge Tester"); + assert_eq!(commit.summary(), "initial commit"); + + // Tree decoded from the pack matches git, and its entry oids match. + let tree = repo.tree(&commit.tree).unwrap(); + assert!( + !repo.odb().loose_path(&commit.tree).exists(), + "tree should be packed" + ); + let entry = tree.entry(b"hello.txt").expect("hello.txt in tree"); + assert_eq!(entry.oid.to_hex(), git(p, &["rev-parse", "HEAD:hello.txt"])); + + // Blob decoded from the pack matches git's content byte-for-byte. + let blob = repo.blob(&entry.oid).unwrap(); + assert!( + !repo.odb().loose_path(&entry.oid).exists(), + "blob should be packed" + ); + assert_eq!(blob.data, b"Hello, Forge!\n"); + assert_eq!( + git_bytes(p, &["cat-file", "-p", &entry.oid.to_hex()]), + blob.data + ); + + // A packed sub-tree and its nested blob also match git. + let sub = tree.entry(b"sub").expect("sub dir in tree"); + assert_eq!(sub.kind(), "tree"); + let subtree = repo.tree(&sub.oid).unwrap(); + let nested = subtree.entry(b"nested.txt").expect("nested.txt"); + assert_eq!( + nested.oid.to_hex(), + git(p, &["rev-parse", "HEAD:sub/nested.txt"]) + ); + assert_eq!(repo.blob(&nested.oid).unwrap().data, b"nested content\n"); +} + +#[test] +fn packed_objects_reserialize_to_same_oids() { + // Parsing a packed object then re-serializing must reproduce git's exact + // bytes — i.e. our oid recomputation matches, proving faithful decoding. + let dir = init_repo_with_commit(); + let p = dir.path(); + pack_everything(p); + + let repo = Repository::discover(p).unwrap(); + let head = repo.head().unwrap(); + assert!( + !repo.odb().loose_path(&head).exists(), + "HEAD should be packed" + ); + + match repo.read_object(&head).unwrap() { + Object::Commit(c) => { + let (id, _) = hash_content(ObjectType::Commit, &c.serialize()); + assert_eq!(id, head, "packed commit re-serialization is not byte-exact"); + } + other => panic!("HEAD should be a commit, got {other:?}"), + } + + let tree_oid = repo.head_commit().unwrap().tree; + let tree = repo.tree(&tree_oid).unwrap(); + let (id, _) = hash_content(ObjectType::Tree, &tree.serialize()); + assert_eq!( + id, tree_oid, + "packed tree re-serialization is not byte-exact" + ); +} + +#[test] +fn reads_deltified_blobs_across_history_from_packfile() { + // Build an evolving file across several commits so `git repack` stores the + // blob versions as a DELTA CHAIN, then read every historical version back + // from the pack and match git. This is the delta-resolution path that is + // the whole point of adopting gitoxide. + let dir = init_repo_with_commit(); + let p = dir.path(); + + let mut expected: Vec<(String, String)> = Vec::new(); + let mut content = String::new(); + for i in 0..8 { + content.push_str(&format!( + "line {i} ------------------------------------------------------------\n" + )); + std::fs::write(p.join("data.txt"), &content).unwrap(); + commit_all(p, &format!("rev {i}")); + let blob_oid = git(p, &["rev-parse", "HEAD:data.txt"]); + expected.push((blob_oid, content.clone())); + } + + // Aggressive repack to encourage deep delta chains, then drop loose copies. + git( + p, + &["repack", "-a", "-d", "-f", "--depth=50", "--window=50"], + ); + git(p, &["prune-packed"]); + assert_has_packfile(p); + + let repo = Repository::discover(p).unwrap(); + for (blob_hex, want) in &expected { + let oid = ObjectId::from_hex(blob_hex).unwrap(); + assert!( + !repo.odb().loose_path(&oid).exists(), + "blob {blob_hex} should be packed (delta chain)" + ); + let blob = repo.blob(&oid).unwrap(); + assert_eq!( + blob.data, + want.as_bytes(), + "packed/deltified blob {blob_hex} content mismatch" + ); + assert_eq!(git_bytes(p, &["cat-file", "-p", blob_hex]), want.as_bytes()); + } +} + +#[test] +fn contains_verify_and_log_work_on_packed_repo() { + let dir = init_repo_with_commit(); + let p = dir.path(); + + // Two more commits so the packed history is non-trivial. + std::fs::write(p.join("second.txt"), b"second\n").unwrap(); + commit_all(p, "second commit"); + std::fs::write(p.join("third.txt"), b"third\n").unwrap(); + commit_all(p, "third commit"); + + pack_everything(p); + assert_has_packfile(p); + + let repo = Repository::discover(p).unwrap(); + let head = repo.head().unwrap(); + assert!( + !repo.odb().loose_path(&head).exists(), + "HEAD should be packed" + ); + + // contains() and verify() both see through to the packfile. + assert!( + repo.odb().contains(&head), + "packed object must be contained" + ); + assert!(repo.verify(&head).unwrap(), "packed object must verify"); + + // Missing objects are still reported as absent, not errors. + let absent = ObjectId::from_hex("0123456789012345678901234567890123456789").unwrap(); + assert!(!repo.odb().contains(&absent)); + + // `log` walks the fully-packed history and matches `git rev-list HEAD`. + let history = repo.log(head).unwrap(); + let git_list: Vec = git(p, &["rev-list", "HEAD"]) + .lines() + .map(str::to_string) + .collect(); + let ours: Vec = history.iter().map(|(oid, _)| oid.to_hex()).collect(); + assert_eq!(ours, git_list, "packed log order differs from git rev-list"); + assert_eq!(history.len(), 3); + assert_eq!(history[0].1.summary(), "third commit"); +} + +#[test] +fn reads_annotated_tag_from_packfile() { + let dir = init_repo_with_commit(); + let p = dir.path(); + git( + p, + &[ + "-c", + "user.name=Forge Tester", + "-c", + "user.email=forge@example.com", + "tag", + "-a", + "v1.0.0", + "-m", + "first release", + ], + ); + pack_everything(p); + assert_has_packfile(p); + + let repo = Repository::discover(p).unwrap(); + let tag_oid = repo.resolve("v1.0.0").unwrap(); + assert!( + !repo.odb().loose_path(&tag_oid).exists(), + "annotated tag object should be packed" + ); + match repo.read_object(&tag_oid).unwrap() { + Object::Tag(t) => { + assert_eq!(t.tag, "v1.0.0"); + assert_eq!(t.object_type, ObjectType::Commit); + assert_eq!(t.object, repo.head().unwrap()); + assert!(t.message_str().contains("first release")); + let (id, _) = hash_content(ObjectType::Tag, &t.serialize()); + assert_eq!(id, tag_oid, "packed tag re-serialization is not byte-exact"); + } + other => panic!("expected annotated tag, got {other:?}"), + } + // Peeling the packed tag reaches the packed commit. + assert_eq!( + repo.peel_to_commit(tag_oid).unwrap().summary(), + "initial commit" + ); +} + +#[test] +fn corrupt_packfile_is_rejected_not_panicked() { + // A truncated/garbled .pack must fail closed (typed error), never panic. + let dir = init_repo_with_commit(); + let p = dir.path(); + pack_everything(p); + + let repo = Repository::discover(p).unwrap(); + let head = repo.head().unwrap(); + assert!( + !repo.odb().loose_path(&head).exists(), + "HEAD should be packed" + ); + + // Corrupt every .pack by overwriting its body with garbage (keep the file + // so the index still points into it). + let pack_dir = p.join(".git").join("objects").join("pack"); + for entry in std::fs::read_dir(&pack_dir).unwrap().flatten() { + let path = entry.path(); + if path.extension().map(|x| x == "pack").unwrap_or(false) { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)); + } + std::fs::write(&path, b"PACK\xff\xff\xff\xffnot a real packfile body").unwrap(); + } + } + + // A fresh repo handle so no cached mmap masks the corruption. + let repo2 = Repository::discover(p).unwrap(); + let result = repo2.read_object(&head); + assert!( + result.is_err(), + "reading from a corrupt packfile must return an error, not succeed or panic" + ); +}