feat(rit): Phase 3-4 — exchange (atomic receive-pack, delta packs, smart-HTTP) + history editing
- multi-ref ATOMIC receive-pack (two-phase ref txn, 'atomic' cap); OFS_DELTA pack gen (window=10, fsck-clean vs real git) - smart-HTTP (axum): /info/refs + /git-upload-pack|/git-receive-pack; real git clone+push verified; serve-http CLI - merge (--no-ff/--continue/--abort), sequencer rebase+cherry-pick (--continue/--abort/--skip), stash (push/list/apply/pop/drop) - deps axum+tokio (offline-compilable); cargo 0; 87 lib + 34 interop tests pass Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
a5637498ef
commit
7354d14722
386
Cargo.lock
generated
386
Cargo.lock
generated
@ -82,6 +82,78 @@ dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-trait"
|
||||
version = "0.1.92"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "atomic-waker"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "axum"
|
||||
version = "0.7.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum-core",
|
||||
"bytes",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"itoa",
|
||||
"matchit",
|
||||
"memchr",
|
||||
"mime",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"rustversion",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_path_to_error",
|
||||
"serde_urlencoded",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "axum-core"
|
||||
version = "0.4.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"mime",
|
||||
"pin-project-lite",
|
||||
"rustversion",
|
||||
"sync_wrapper",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
@ -120,6 +192,12 @@ version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.4"
|
||||
@ -293,6 +371,48 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
||||
dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-channel"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
||||
|
||||
[[package]]
|
||||
name = "futures-task"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-task",
|
||||
"pin-project-lite",
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
@ -640,6 +760,86 @@ version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"itoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http-body"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"http",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http-body-util"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"http",
|
||||
"http-body",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "httpdate"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"http",
|
||||
"http-body",
|
||||
"httparse",
|
||||
"httpdate",
|
||||
"itoa",
|
||||
"pin-project-lite",
|
||||
"smallvec",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-util"
|
||||
version = "0.1.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"http",
|
||||
"http-body",
|
||||
"hyper",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.2"
|
||||
@ -732,6 +932,12 @@ version = "0.4.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
|
||||
|
||||
[[package]]
|
||||
name = "matchit"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
@ -747,6 +953,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
version = "0.3.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
||||
|
||||
[[package]]
|
||||
name = "miniz_oxide"
|
||||
version = "0.8.9"
|
||||
@ -757,6 +969,17 @@ dependencies = [
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"wasi",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
@ -792,6 +1015,18 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic"
|
||||
version = "1.15.0"
|
||||
@ -871,6 +1106,7 @@ name = "rit"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
"clap",
|
||||
"diffy",
|
||||
"flate2",
|
||||
@ -883,6 +1119,7 @@ dependencies = [
|
||||
"sha1",
|
||||
"tempfile",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -904,6 +1141,12 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
@ -948,6 +1191,42 @@ dependencies = [
|
||||
"syn 3.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.151"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_path_to_error"
|
||||
version = "0.1.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_urlencoded"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
|
||||
dependencies = [
|
||||
"form_urlencoded",
|
||||
"itoa",
|
||||
"ryu",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.10.7"
|
||||
@ -975,12 +1254,28 @@ version = "0.3.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.15.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
@ -1015,6 +1310,12 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sync_wrapper"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
@ -1063,6 +1364,79 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"mio",
|
||||
"pin-project-lite",
|
||||
"socket2",
|
||||
"tokio-macros",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-macros"
|
||||
version = "2.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"pin-project-lite",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-layer"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
|
||||
|
||||
[[package]]
|
||||
name = "tower-service"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
||||
dependencies = [
|
||||
"log",
|
||||
"pin-project-lite",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-core"
|
||||
version = "0.1.36"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
@ -1106,6 +1480,12 @@ dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.11.1+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "winapi-util"
|
||||
version = "0.1.11"
|
||||
@ -1144,3 +1524,9 @@ name = "zlib-rs"
|
||||
version = "0.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
|
||||
@ -31,5 +31,11 @@ globset = "=0.4.20"
|
||||
sha1 = "0.10"
|
||||
thiserror = "2"
|
||||
|
||||
# Smart-HTTP transport (Phase 3 C). axum/tokio power the async listener; the
|
||||
# pkt-line/pack/negotiation logic stays in the synchronous core and is called
|
||||
# from `spawn_blocking`, so no async colours the object/ref/pack plumbing.
|
||||
axum = "0.7"
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "net"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
@ -105,14 +105,7 @@ pub fn cmd_branch_create(
|
||||
let message = format!("branch: Created from {source_desc}");
|
||||
|
||||
repo.branch_create(
|
||||
name,
|
||||
start_oid,
|
||||
force,
|
||||
&sig.name,
|
||||
&sig.email,
|
||||
sig.time,
|
||||
&sig.tz,
|
||||
&message,
|
||||
name, start_oid, force, &sig.name, &sig.email, sig.time, &sig.tz, &message,
|
||||
)
|
||||
.with_context(|| format!("creating branch {name:?}"))?;
|
||||
|
||||
@ -125,11 +118,7 @@ pub fn cmd_branch_create(
|
||||
/// (equivalent to `git branch -D`).
|
||||
///
|
||||
/// Prints a confirmation line for each deleted branch.
|
||||
pub fn cmd_branch_delete(
|
||||
repo: &Repository,
|
||||
names: &[&str],
|
||||
force: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
pub fn cmd_branch_delete(repo: &Repository, names: &[&str], force: bool) -> anyhow::Result<()> {
|
||||
if names.is_empty() {
|
||||
bail!("branch --delete requires at least one branch name");
|
||||
}
|
||||
@ -159,13 +148,7 @@ pub fn cmd_branch_rename(
|
||||
sig: &Signature,
|
||||
) -> anyhow::Result<()> {
|
||||
repo.branch_rename(
|
||||
old_name,
|
||||
new_name,
|
||||
force,
|
||||
&sig.name,
|
||||
&sig.email,
|
||||
sig.time,
|
||||
&sig.tz,
|
||||
old_name, new_name, force, &sig.name, &sig.email, sig.time, &sig.tz,
|
||||
)
|
||||
.with_context(|| format!("renaming branch {old_name:?} → {new_name:?}"))?;
|
||||
println!("Renamed branch {old_name} to {new_name}.");
|
||||
@ -177,10 +160,23 @@ pub fn cmd_branch_rename(
|
||||
/// Decoded branch operation — used by the convenience dispatcher.
|
||||
#[derive(Debug)]
|
||||
pub enum BranchOp<'a> {
|
||||
List { verbose: bool },
|
||||
Create { name: &'a str, start: Option<&'a str>, force: bool },
|
||||
Delete { names: Vec<&'a str>, force: bool },
|
||||
Rename { old: &'a str, new: &'a str, force: bool },
|
||||
List {
|
||||
verbose: bool,
|
||||
},
|
||||
Create {
|
||||
name: &'a str,
|
||||
start: Option<&'a str>,
|
||||
force: bool,
|
||||
},
|
||||
Delete {
|
||||
names: Vec<&'a str>,
|
||||
force: bool,
|
||||
},
|
||||
Rename {
|
||||
old: &'a str,
|
||||
new: &'a str,
|
||||
force: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// High-level branch dispatcher: given a decoded [`BranchOp`] and an actor
|
||||
@ -188,16 +184,10 @@ pub enum BranchOp<'a> {
|
||||
///
|
||||
/// The integrator calls this from their `cmd_branch` main.rs function after
|
||||
/// translating clap args into a `BranchOp`.
|
||||
pub fn dispatch_branch(
|
||||
repo: &Repository,
|
||||
op: BranchOp<'_>,
|
||||
sig: &Signature,
|
||||
) -> anyhow::Result<()> {
|
||||
pub fn dispatch_branch(repo: &Repository, op: BranchOp<'_>, sig: &Signature) -> anyhow::Result<()> {
|
||||
match op {
|
||||
BranchOp::List { verbose } => cmd_branch_list(repo, verbose),
|
||||
BranchOp::Create { name, start, force } => {
|
||||
cmd_branch_create(repo, name, start, force, sig)
|
||||
}
|
||||
BranchOp::Create { name, start, force } => cmd_branch_create(repo, name, start, force, sig),
|
||||
BranchOp::Delete { names, force } => cmd_branch_delete(repo, &names, force),
|
||||
BranchOp::Rename { old, new, force } => cmd_branch_rename(repo, old, new, force, sig),
|
||||
}
|
||||
|
||||
@ -90,19 +90,18 @@ pub fn cmd_switch(repo: &Repository, target: &str, create: bool) -> Result<Switc
|
||||
// Determine whether HEAD should be symbolic or detached.
|
||||
// Priority: exact local branch → full refs/heads/... → detached.
|
||||
let branch_refname = format!("refs/heads/{target}");
|
||||
let head = if validate_refname(&branch_refname).is_ok()
|
||||
&& refs.resolve(&branch_refname).is_ok()
|
||||
{
|
||||
SwitchHead::Symbolic(branch_refname)
|
||||
} else if target.starts_with("refs/heads/")
|
||||
&& validate_refname(target).is_ok()
|
||||
&& refs.resolve(target).is_ok()
|
||||
{
|
||||
SwitchHead::Symbolic(target.to_string())
|
||||
} else {
|
||||
// Raw oid, tag, or non-local-branch ref → detached HEAD.
|
||||
SwitchHead::Detached(commit_oid)
|
||||
};
|
||||
let head =
|
||||
if validate_refname(&branch_refname).is_ok() && refs.resolve(&branch_refname).is_ok() {
|
||||
SwitchHead::Symbolic(branch_refname)
|
||||
} else if target.starts_with("refs/heads/")
|
||||
&& validate_refname(target).is_ok()
|
||||
&& refs.resolve(target).is_ok()
|
||||
{
|
||||
SwitchHead::Symbolic(target.to_string())
|
||||
} else {
|
||||
// Raw oid, tag, or non-local-branch ref → detached HEAD.
|
||||
SwitchHead::Detached(commit_oid)
|
||||
};
|
||||
(head, commit_oid)
|
||||
};
|
||||
|
||||
@ -210,11 +209,20 @@ mod tests {
|
||||
let sig_raw = "Test User <test@example.com> 1700000000 +0000";
|
||||
let sig = Signature::parse(sig_raw, "test").unwrap();
|
||||
// Write an empty blob and stage it so write_tree succeeds.
|
||||
let oid = repo.hash_object(ObjectType::Blob, b"content", true).unwrap();
|
||||
let oid = repo
|
||||
.hash_object(ObjectType::Blob, b"content", true)
|
||||
.unwrap();
|
||||
// For a minimal commit, use commit_tree with the empty tree.
|
||||
let empty_tree = repo.hash_object(ObjectType::Tree, b"", true).unwrap();
|
||||
repo.commit_tree(empty_tree, vec![], sig.clone(), sig, message.as_bytes(), Some("refs/heads/main"))
|
||||
.unwrap()
|
||||
repo.commit_tree(
|
||||
empty_tree,
|
||||
vec![],
|
||||
sig.clone(),
|
||||
sig,
|
||||
message.as_bytes(),
|
||||
Some("refs/heads/main"),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -230,7 +238,10 @@ mod tests {
|
||||
assert!(repo.refs().resolve("refs/heads/feature").is_ok());
|
||||
// HEAD must now be the symbolic ref.
|
||||
let head_target = repo.refs().read_head().unwrap();
|
||||
assert_eq!(head_target, crate::RefTarget::Symbolic("refs/heads/feature".into()));
|
||||
assert_eq!(
|
||||
head_target,
|
||||
crate::RefTarget::Symbolic("refs/heads/feature".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -248,7 +259,9 @@ mod tests {
|
||||
make_commit(&repo, "initial\n");
|
||||
// Create a second branch.
|
||||
let head_oid = repo.head().unwrap();
|
||||
repo.refs().compare_and_swap("refs/heads/other", None, head_oid).unwrap();
|
||||
repo.refs()
|
||||
.compare_and_swap("refs/heads/other", None, head_oid)
|
||||
.unwrap();
|
||||
|
||||
let result = cmd_switch(&repo, "other", false).unwrap();
|
||||
assert!(matches!(result.head, SwitchHead::Symbolic(ref n) if n == "refs/heads/other"));
|
||||
@ -276,10 +289,13 @@ mod tests {
|
||||
std::fs::write(dir.path().join("file.txt"), data).unwrap();
|
||||
// add() expects paths relative to the worktree root.
|
||||
repo.add(&[std::path::PathBuf::from("file.txt")]).unwrap();
|
||||
repo.commit_index("initial\n", sig.clone(), sig.clone()).unwrap();
|
||||
repo.commit_index("initial\n", sig.clone(), sig.clone())
|
||||
.unwrap();
|
||||
|
||||
// Create "other" branch: same parent commit but tree has different file.txt.
|
||||
let new_blob = repo.hash_object(ObjectType::Blob, b"different\n", true).unwrap();
|
||||
let new_blob = repo
|
||||
.hash_object(ObjectType::Blob, b"different\n", true)
|
||||
.unwrap();
|
||||
let mut t = crate::Tree {
|
||||
entries: vec![crate::TreeEntry {
|
||||
mode: "100644".into(),
|
||||
@ -288,7 +304,9 @@ mod tests {
|
||||
}],
|
||||
};
|
||||
t.canonicalize();
|
||||
let new_tree = repo.hash_object(ObjectType::Tree, &t.serialize(), true).unwrap();
|
||||
let new_tree = repo
|
||||
.hash_object(ObjectType::Tree, &t.serialize(), true)
|
||||
.unwrap();
|
||||
let head_oid = repo.head().unwrap();
|
||||
repo.commit_tree(
|
||||
new_tree,
|
||||
|
||||
44
src/diff.rs
44
src/diff.rs
@ -83,16 +83,15 @@ pub fn diff_trees(
|
||||
new_mode: Some(new_mode.clone()),
|
||||
new_oid: Some(*new_oid),
|
||||
}),
|
||||
Some((old_mode, old_oid)) if old_oid != new_oid || old_mode != new_mode => {
|
||||
changes.push(TreeChange {
|
||||
Some((old_mode, old_oid)) if old_oid != new_oid || old_mode != new_mode => changes
|
||||
.push(TreeChange {
|
||||
path: path.clone(),
|
||||
kind: ChangeKind::Modified,
|
||||
old_mode: Some(old_mode.clone()),
|
||||
old_oid: Some(*old_oid),
|
||||
new_mode: Some(new_mode.clone()),
|
||||
new_oid: Some(*new_oid),
|
||||
})
|
||||
}
|
||||
}),
|
||||
Some(_) => {} // identical — not a change
|
||||
}
|
||||
}
|
||||
@ -161,7 +160,8 @@ mod tests {
|
||||
fn tree(repo: &Repository, entries: Vec<TreeEntry>) -> ObjectId {
|
||||
let mut t = Tree { entries };
|
||||
t.canonicalize();
|
||||
repo.hash_object(ObjectType::Tree, &t.serialize(), true).unwrap()
|
||||
repo.hash_object(ObjectType::Tree, &t.serialize(), true)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -173,8 +173,16 @@ mod tests {
|
||||
let old = tree(
|
||||
&repo,
|
||||
vec![
|
||||
TreeEntry { mode: "100644".into(), name: b"a.txt".to_vec(), oid: a1 },
|
||||
TreeEntry { mode: "100644".into(), name: b"b.txt".to_vec(), oid: b1 },
|
||||
TreeEntry {
|
||||
mode: "100644".into(),
|
||||
name: b"a.txt".to_vec(),
|
||||
oid: a1,
|
||||
},
|
||||
TreeEntry {
|
||||
mode: "100644".into(),
|
||||
name: b"b.txt".to_vec(),
|
||||
oid: b1,
|
||||
},
|
||||
],
|
||||
);
|
||||
let a2 = blob(&repo, b"two\n");
|
||||
@ -182,9 +190,21 @@ mod tests {
|
||||
let new = tree(
|
||||
&repo,
|
||||
vec![
|
||||
TreeEntry { mode: "100644".into(), name: b"a.txt".to_vec(), oid: a2 },
|
||||
TreeEntry { mode: "100644".into(), name: b"b.txt".to_vec(), oid: b1 },
|
||||
TreeEntry { mode: "100644".into(), name: b"c.txt".to_vec(), oid: c1 },
|
||||
TreeEntry {
|
||||
mode: "100644".into(),
|
||||
name: b"a.txt".to_vec(),
|
||||
oid: a2,
|
||||
},
|
||||
TreeEntry {
|
||||
mode: "100644".into(),
|
||||
name: b"b.txt".to_vec(),
|
||||
oid: b1,
|
||||
},
|
||||
TreeEntry {
|
||||
mode: "100644".into(),
|
||||
name: b"c.txt".to_vec(),
|
||||
oid: c1,
|
||||
},
|
||||
],
|
||||
);
|
||||
let changes = diff_trees(repo.odb(), Some(old), Some(new)).unwrap();
|
||||
@ -196,6 +216,8 @@ mod tests {
|
||||
|
||||
// Reverse diff sees the deletion.
|
||||
let rev = diff_trees(repo.odb(), Some(new), Some(old)).unwrap();
|
||||
assert!(rev.iter().any(|c| c.path == b"c.txt" && c.kind == ChangeKind::Deleted));
|
||||
assert!(rev
|
||||
.iter()
|
||||
.any(|c| c.path == b"c.txt" && c.kind == ChangeKind::Deleted));
|
||||
}
|
||||
}
|
||||
|
||||
@ -257,7 +257,10 @@ fn commit_or_tree_oid(repo: &Repository, oid: ObjectId) -> Result<ObjectId> {
|
||||
other => {
|
||||
return Err(ForgeError::malformed(
|
||||
"object",
|
||||
format!("{current} is a {}, expected commit or tree", other.object_type()),
|
||||
format!(
|
||||
"{current} is a {}, expected commit or tree",
|
||||
other.object_type()
|
||||
),
|
||||
))
|
||||
}
|
||||
}
|
||||
@ -482,11 +485,7 @@ fn flatten_tree(
|
||||
/// Fails with [`ForgeError::NoWorktree`] for bare repositories.
|
||||
fn repo_worktree(repo: &Repository) -> Result<PathBuf> {
|
||||
let git_dir = repo.git_dir();
|
||||
if git_dir
|
||||
.file_name()
|
||||
.map(|n| n == ".git")
|
||||
.unwrap_or(false)
|
||||
{
|
||||
if git_dir.file_name().map(|n| n == ".git").unwrap_or(false) {
|
||||
git_dir
|
||||
.parent()
|
||||
.map(|p| p.to_path_buf())
|
||||
@ -504,9 +503,7 @@ fn path_from_bytes(bytes: &[u8]) -> Result<PathBuf> {
|
||||
let s = std::str::from_utf8(bytes)
|
||||
.map_err(|_| ForgeError::UnsafePath("non-UTF-8 path in index".into()))?;
|
||||
let p = Path::new(s);
|
||||
if p.components()
|
||||
.any(|c| !matches!(c, Component::Normal(_)))
|
||||
{
|
||||
if p.components().any(|c| !matches!(c, Component::Normal(_))) {
|
||||
return Err(ForgeError::UnsafePath(s.into()));
|
||||
}
|
||||
Ok(p.to_path_buf())
|
||||
@ -516,11 +513,7 @@ fn path_from_bytes(bytes: &[u8]) -> Result<PathBuf> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn init_repo_with_file(
|
||||
dir: &Path,
|
||||
name: &str,
|
||||
content: &[u8],
|
||||
) -> (Repository, ObjectId) {
|
||||
fn init_repo_with_file(dir: &Path, name: &str, content: &[u8]) -> (Repository, ObjectId) {
|
||||
let repo = Repository::init(dir, false, Some("main")).unwrap();
|
||||
let oid = repo.hash_object(ObjectType::Blob, content, true).unwrap();
|
||||
(repo, oid)
|
||||
@ -530,7 +523,9 @@ mod tests {
|
||||
fn diff_identical_trees_produces_no_output() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let repo = Repository::init(dir.path(), true, Some("main")).unwrap();
|
||||
let blob = repo.hash_object(ObjectType::Blob, b"hello\n", true).unwrap();
|
||||
let blob = repo
|
||||
.hash_object(ObjectType::Blob, b"hello\n", true)
|
||||
.unwrap();
|
||||
|
||||
let mut entry = crate::tree::Tree {
|
||||
entries: vec![crate::TreeEntry {
|
||||
@ -540,11 +535,16 @@ mod tests {
|
||||
}],
|
||||
};
|
||||
entry.canonicalize();
|
||||
let tree_oid = repo.hash_object(ObjectType::Tree, &entry.serialize(), true).unwrap();
|
||||
let tree_oid = repo
|
||||
.hash_object(ObjectType::Tree, &entry.serialize(), true)
|
||||
.unwrap();
|
||||
|
||||
let mut out = Vec::new();
|
||||
diff_two_revs_with_trees(&repo, tree_oid, tree_oid, &mut out).unwrap();
|
||||
assert!(out.is_empty(), "identical trees should produce no diff output");
|
||||
assert!(
|
||||
out.is_empty(),
|
||||
"identical trees should produce no diff output"
|
||||
);
|
||||
}
|
||||
|
||||
fn diff_two_revs_with_trees(
|
||||
@ -564,7 +564,9 @@ mod tests {
|
||||
fn diff_addition_shows_new_file_mode_header() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let repo = Repository::init(dir.path(), true, Some("main")).unwrap();
|
||||
let blob = repo.hash_object(ObjectType::Blob, b"new content\n", true).unwrap();
|
||||
let blob = repo
|
||||
.hash_object(ObjectType::Blob, b"new content\n", true)
|
||||
.unwrap();
|
||||
|
||||
let empty_tree = repo.hash_object(ObjectType::Tree, b"", true).unwrap();
|
||||
let mut new_tree_obj = crate::tree::Tree {
|
||||
@ -575,13 +577,21 @@ mod tests {
|
||||
}],
|
||||
};
|
||||
new_tree_obj.canonicalize();
|
||||
let new_tree = repo.hash_object(ObjectType::Tree, &new_tree_obj.serialize(), true).unwrap();
|
||||
let new_tree = repo
|
||||
.hash_object(ObjectType::Tree, &new_tree_obj.serialize(), true)
|
||||
.unwrap();
|
||||
|
||||
let mut out = Vec::new();
|
||||
diff_two_revs_with_trees(&repo, empty_tree, new_tree, &mut out).unwrap();
|
||||
let text = String::from_utf8(out).unwrap();
|
||||
assert!(text.contains("new file mode 100644"), "expected 'new file mode' header: {text}");
|
||||
assert!(text.contains("+++ b/new.txt"), "expected +++ header: {text}");
|
||||
assert!(
|
||||
text.contains("new file mode 100644"),
|
||||
"expected 'new file mode' header: {text}"
|
||||
);
|
||||
assert!(
|
||||
text.contains("+++ b/new.txt"),
|
||||
"expected +++ header: {text}"
|
||||
);
|
||||
assert!(text.contains("+new content"), "expected added line: {text}");
|
||||
}
|
||||
|
||||
@ -598,13 +608,18 @@ mod tests {
|
||||
}],
|
||||
};
|
||||
old_tree_obj.canonicalize();
|
||||
let old_tree = repo.hash_object(ObjectType::Tree, &old_tree_obj.serialize(), true).unwrap();
|
||||
let old_tree = repo
|
||||
.hash_object(ObjectType::Tree, &old_tree_obj.serialize(), true)
|
||||
.unwrap();
|
||||
let empty_tree = repo.hash_object(ObjectType::Tree, b"", true).unwrap();
|
||||
|
||||
let mut out = Vec::new();
|
||||
diff_two_revs_with_trees(&repo, old_tree, empty_tree, &mut out).unwrap();
|
||||
let text = String::from_utf8(out).unwrap();
|
||||
assert!(text.contains("deleted file mode"), "expected 'deleted file mode': {text}");
|
||||
assert!(
|
||||
text.contains("deleted file mode"),
|
||||
"expected 'deleted file mode': {text}"
|
||||
);
|
||||
assert!(text.contains("-gone"), "expected removed line: {text}");
|
||||
}
|
||||
|
||||
@ -630,6 +645,9 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
let text = String::from_utf8(out).unwrap();
|
||||
assert!(text.contains("Binary files"), "expected binary marker: {text}");
|
||||
assert!(
|
||||
text.contains("Binary files"),
|
||||
"expected binary marker: {text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
18
src/http/mod.rs
Normal file
18
src/http/mod.rs
Normal file
@ -0,0 +1,18 @@
|
||||
//! HTTP transport adapters for `rit`.
|
||||
//!
|
||||
//! This module owns the network-facing surface that lets a **stock `git`
|
||||
//! client** clone, fetch, and push over HTTP against a repository served by
|
||||
//! `rit`. It is deliberately thin: every byte of protocol semantics
|
||||
//! (pkt-line framing, ref advertisement, negotiation, packfile generation,
|
||||
//! quarantine, ref CAS) already lives in the synchronous core
|
||||
//! (`upload_pack`, `receive_pack`, `wire`, `receive`). The code here only:
|
||||
//!
|
||||
//! 1. maps the Git **smart-HTTP** URL/verb grammar onto those core calls, and
|
||||
//! 2. runs them on a blocking thread pool behind an async listener.
|
||||
//!
|
||||
//! No object, ref, or pack logic is reimplemented here — the adapter calls the
|
||||
//! other modules' public functions and never reaches into their internals.
|
||||
//!
|
||||
//! See [`smart_http`] for the handlers, the router, and the listener.
|
||||
|
||||
pub mod smart_http;
|
||||
445
src/http/smart_http.rs
Normal file
445
src/http/smart_http.rs
Normal file
@ -0,0 +1,445 @@
|
||||
//! Git **smart-HTTP** server for `rit`.
|
||||
//!
|
||||
//! Implements the three endpoints a stock `git` client drives when the remote
|
||||
//! URL is `http(s)://…`:
|
||||
//!
|
||||
//! | Method + path | Purpose |
|
||||
//! |-----------------------------------|-------------------------------------------|
|
||||
//! | `GET /info/refs?service=git-upload-pack` | fetch/clone ref advertisement |
|
||||
//! | `GET /info/refs?service=git-receive-pack` | push ref advertisement |
|
||||
//! | `POST /git-upload-pack` | fetch/clone negotiation → `NAK` + packfile |
|
||||
//! | `POST /git-receive-pack` | push: pack + ref commands → report-status |
|
||||
//!
|
||||
//! ## Layering
|
||||
//!
|
||||
//! The **sync core** ([`info_refs`], [`upload_pack_rpc`], [`receive_pack_rpc`])
|
||||
//! produces the exact response bytes from a [`Repository`]; it contains no async
|
||||
//! and no socket code, so it is directly callable (and unit-testable) without a
|
||||
//! runtime. It wraps the existing [`crate::upload_pack`] / [`crate::receive_pack`]
|
||||
//! functions and adds only the smart-HTTP framing quirks: the
|
||||
//! `# service=…\n` banner on `info/refs`, gzip request-body inflation, and the
|
||||
//! `application/x-git-*` content types.
|
||||
//!
|
||||
//! The **async layer** ([`router`], [`serve`], [`serve_blocking`]) is a small
|
||||
//! `axum` front door. Each handler moves the (fully buffered) request body onto
|
||||
//! [`tokio::task::spawn_blocking`], opens the repository, and calls the sync
|
||||
//! core — so the synchronous object/ref/pack plumbing is never run on an async
|
||||
//! executor thread.
|
||||
//!
|
||||
//! ## Scope
|
||||
//!
|
||||
//! One repository per server instance (the endpoints live at the URL root). A
|
||||
//! multi-repository forge composes several routers (or nests this one under a
|
||||
//! per-repo path prefix); path-based repo routing, authentication, and TLS are
|
||||
//! the embedding forge's concern, not this transport's.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::extract::{DefaultBodyLimit, RawQuery, State};
|
||||
use axum::http::{header, HeaderMap, StatusCode};
|
||||
use axum::response::Response;
|
||||
use axum::routing::{get, post};
|
||||
use axum::Router;
|
||||
|
||||
use crate::error::{ForgeError, Result};
|
||||
use crate::receive::ReceiveLimits;
|
||||
use crate::receive_pack::{
|
||||
advertise_receive_pack, execute_receive_pack, ReceivePackPolicy, RECEIVE_PACK_CAPABILITIES,
|
||||
};
|
||||
use crate::repo::Repository;
|
||||
use crate::upload_pack::{advertise_upload_pack, upload_pack_v0};
|
||||
use crate::wire::{
|
||||
encode_packet_line, encode_receive_status, parse_receive_pack_request, PacketLine,
|
||||
PacketLineLimits, ReceiveStatus,
|
||||
};
|
||||
|
||||
/// Default ceiling on a buffered request body (1 GiB). Push packs can be large;
|
||||
/// the per-packet and per-pack limits in [`PacketLineLimits`]/[`ReceiveLimits`]
|
||||
/// bound the *processing* cost, while this caps the *buffering* cost so a single
|
||||
/// request cannot exhaust memory.
|
||||
pub const DEFAULT_MAX_BODY_BYTES: usize = 1024 * 1024 * 1024;
|
||||
|
||||
/// The two Git services reachable over smart-HTTP.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Service {
|
||||
/// `git-upload-pack` — the fetch/clone (send objects to the client) side.
|
||||
UploadPack,
|
||||
/// `git-receive-pack` — the push (receive objects from the client) side.
|
||||
ReceivePack,
|
||||
}
|
||||
|
||||
impl Service {
|
||||
/// Map a `service=…` query value to a [`Service`]. Unknown values yield
|
||||
/// `None`, which the caller turns into `403 Forbidden` (Git's convention for
|
||||
/// a service that is not enabled).
|
||||
pub fn from_query_value(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"git-upload-pack" => Some(Self::UploadPack),
|
||||
"git-receive-pack" => Some(Self::ReceivePack),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The wire service name (`git-upload-pack` / `git-receive-pack`).
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::UploadPack => "git-upload-pack",
|
||||
Self::ReceivePack => "git-receive-pack",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Server-side policy applied to pushes — never inferred from the client.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SmartHttpConfig {
|
||||
/// Branch short-names (e.g. `main`) whose direct push is refused with a
|
||||
/// per-ref `ng` status, mirroring the CLI's protected-branch enforcement.
|
||||
pub blocked_branches: Vec<String>,
|
||||
/// Allow a non-fast-forward branch update. A repository-owner decision, not
|
||||
/// a capability the pushing client can grant itself.
|
||||
pub allow_non_fast_forward: bool,
|
||||
/// Maximum buffered request-body size in bytes. Defaults to
|
||||
/// [`DEFAULT_MAX_BODY_BYTES`].
|
||||
pub max_body_bytes: usize,
|
||||
}
|
||||
|
||||
impl SmartHttpConfig {
|
||||
/// A config with the default body cap and no protected branches.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
blocked_branches: Vec::new(),
|
||||
allow_non_fast_forward: false,
|
||||
max_body_bytes: DEFAULT_MAX_BODY_BYTES,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A fully-formed HTTP response produced by the synchronous core: a status, a
|
||||
/// static content type, and a body. The async layer copies these onto the
|
||||
/// framework's response type verbatim.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SmartResponse {
|
||||
pub status: u16,
|
||||
pub content_type: &'static str,
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
impl SmartResponse {
|
||||
fn ok(content_type: &'static str, body: Vec<u8>) -> Self {
|
||||
Self {
|
||||
status: 200,
|
||||
content_type,
|
||||
body,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Synchronous core — no async, no sockets. Testable against a `Repository`.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Build the **smart-HTTP `info/refs` advertisement** for `service`.
|
||||
///
|
||||
/// Unlike the stateful (SSH/local) advertisement, smart-HTTP prefixes the ref
|
||||
/// list with a service banner and a flush:
|
||||
///
|
||||
/// ```text
|
||||
/// <pkt-line "# service=git-upload-pack\n">
|
||||
/// 0000
|
||||
/// <normal v0 ref advertisement, itself flush-terminated>
|
||||
/// ```
|
||||
///
|
||||
/// The banner and its flush are exactly what a stock client verifies before it
|
||||
/// reads the refs; the ref lines and capabilities come straight from the core
|
||||
/// [`advertise_upload_pack`] / [`advertise_receive_pack`] functions.
|
||||
pub fn info_refs(repo: &Repository, service: Service) -> Result<SmartResponse> {
|
||||
let mut body = encode_packet_line(&PacketLine::Data(
|
||||
format!("# service={}\n", service.name()).into_bytes(),
|
||||
))?;
|
||||
body.extend_from_slice(b"0000");
|
||||
match service {
|
||||
Service::UploadPack => body.extend(advertise_upload_pack(repo)?),
|
||||
Service::ReceivePack => {
|
||||
body.extend(advertise_receive_pack(repo, RECEIVE_PACK_CAPABILITIES)?)
|
||||
}
|
||||
}
|
||||
let content_type = match service {
|
||||
Service::UploadPack => "application/x-git-upload-pack-advertisement",
|
||||
Service::ReceivePack => "application/x-git-receive-pack-advertisement",
|
||||
};
|
||||
Ok(SmartResponse::ok(content_type, body))
|
||||
}
|
||||
|
||||
/// Serve a `POST /git-upload-pack` body: parse the `want`/`have`/`done`
|
||||
/// negotiation and return `NAK` followed by the packfile. `body` must already
|
||||
/// be inflated (see [`maybe_gunzip`]).
|
||||
pub fn upload_pack_rpc(repo: &Repository, body: &[u8]) -> Result<SmartResponse> {
|
||||
let out = upload_pack_v0(repo, body)?;
|
||||
Ok(SmartResponse::ok(
|
||||
"application/x-git-upload-pack-result",
|
||||
out,
|
||||
))
|
||||
}
|
||||
|
||||
/// Serve a `POST /git-receive-pack` body: enforce protected-branch policy, then
|
||||
/// quarantine the pack and apply the single ref update, returning the
|
||||
/// report-status body. `body` must already be inflated (see [`maybe_gunzip`]).
|
||||
pub fn receive_pack_rpc(
|
||||
repo: &Repository,
|
||||
body: &[u8],
|
||||
config: &SmartHttpConfig,
|
||||
) -> Result<SmartResponse> {
|
||||
let packet_limits = PacketLineLimits::default();
|
||||
let receive_limits = ReceiveLimits::default();
|
||||
|
||||
// Protected-branch enforcement mirrors the CLI receive-pack: if any command
|
||||
// targets a blocked branch, refuse the whole push with per-ref `ng` and
|
||||
// never touch objects or refs. A parse failure here falls through to
|
||||
// `execute_receive_pack`, which reports the framing error uniformly.
|
||||
if !config.blocked_branches.is_empty() {
|
||||
if let Ok(parsed) =
|
||||
parse_receive_pack_request(body, RECEIVE_PACK_CAPABILITIES, packet_limits)
|
||||
{
|
||||
let blocked = parsed.commands.iter().any(|command| {
|
||||
command
|
||||
.name()
|
||||
.strip_prefix("refs/heads/")
|
||||
.map(|branch| config.blocked_branches.iter().any(|b| b == branch))
|
||||
.unwrap_or(false)
|
||||
});
|
||||
if blocked {
|
||||
let report_status = parsed.capabilities.contains("report-status")
|
||||
|| parsed.capabilities.contains("report-status-v2");
|
||||
let out = if report_status {
|
||||
let statuses: Vec<ReceiveStatus> = parsed
|
||||
.commands
|
||||
.iter()
|
||||
.map(|command| ReceiveStatus {
|
||||
ref_name: command.name().to_string(),
|
||||
error: Some(
|
||||
"protected branch: direct push blocked, open a pull request".into(),
|
||||
),
|
||||
})
|
||||
.collect();
|
||||
encode_receive_status(None, &statuses)?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
return Ok(SmartResponse::ok(
|
||||
"application/x-git-receive-pack-result",
|
||||
out,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let execution = execute_receive_pack(
|
||||
repo,
|
||||
body,
|
||||
RECEIVE_PACK_CAPABILITIES,
|
||||
packet_limits,
|
||||
receive_limits,
|
||||
ReceivePackPolicy {
|
||||
allow_non_fast_forward: config.allow_non_fast_forward,
|
||||
},
|
||||
)?;
|
||||
Ok(SmartResponse::ok(
|
||||
"application/x-git-receive-pack-result",
|
||||
execution.response,
|
||||
))
|
||||
}
|
||||
|
||||
/// Inflate a request body if it arrived `Content-Encoding: gzip`. Stock `git`
|
||||
/// gzip-compresses the `git-upload-pack` negotiation body by default; the
|
||||
/// `git-receive-pack` body (which already carries a compressed packfile) is
|
||||
/// sent uncompressed. Returns the body unchanged when not gzip-encoded.
|
||||
pub fn maybe_gunzip(body: Vec<u8>, gzip_encoded: bool) -> Result<Vec<u8>> {
|
||||
if !gzip_encoded {
|
||||
return Ok(body);
|
||||
}
|
||||
use std::io::Read;
|
||||
let mut decoder = flate2::read::GzDecoder::new(&body[..]);
|
||||
let mut out = Vec::new();
|
||||
decoder
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|e| ForgeError::Decompress(format!("gzip request body: {e}")))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Extract the `service` value from a raw query string (`service=git-upload-pack`).
|
||||
fn service_from_query(query: Option<&str>) -> Option<Service> {
|
||||
let query = query?;
|
||||
query
|
||||
.split('&')
|
||||
.filter_map(|pair| pair.split_once('='))
|
||||
.find(|(key, _)| *key == "service")
|
||||
.and_then(|(_, value)| Service::from_query_value(value))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Async layer — axum router + listener over the sync core.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Shared handler state: where the (bare) repository lives and the push policy.
|
||||
#[derive(Clone)]
|
||||
pub struct SmartHttpState {
|
||||
git_dir: Arc<PathBuf>,
|
||||
config: Arc<SmartHttpConfig>,
|
||||
}
|
||||
|
||||
impl SmartHttpState {
|
||||
/// Serve the repository whose Git directory is `git_dir` under `config`.
|
||||
pub fn new(git_dir: impl Into<PathBuf>, config: SmartHttpConfig) -> Self {
|
||||
Self {
|
||||
git_dir: Arc::new(git_dir.into()),
|
||||
config: Arc::new(config),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the smart-HTTP [`Router`] for one repository.
|
||||
///
|
||||
/// Mount it at the URL root (a client clones `http://host/`) or nest it under a
|
||||
/// path prefix for per-repo routing. The request-body limit follows
|
||||
/// [`SmartHttpConfig::max_body_bytes`] so large pushes are accepted.
|
||||
pub fn router(state: SmartHttpState) -> Router {
|
||||
let body_limit = state.config.max_body_bytes;
|
||||
Router::new()
|
||||
.route("/info/refs", get(get_info_refs))
|
||||
.route("/git-upload-pack", post(post_upload_pack))
|
||||
.route("/git-receive-pack", post(post_receive_pack))
|
||||
.layer(DefaultBodyLimit::max(body_limit))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
/// Bind `addr` and serve the smart-HTTP router until the process exits.
|
||||
pub async fn serve(addr: SocketAddr, state: SmartHttpState) -> std::io::Result<()> {
|
||||
let listener = tokio::net::TcpListener::bind(addr).await?;
|
||||
axum::serve(listener, router(state)).await
|
||||
}
|
||||
|
||||
/// Blocking entry point for a synchronous CLI: build a multi-threaded Tokio
|
||||
/// runtime and drive [`serve`] to completion. Lets a plain `fn main` host the
|
||||
/// server without becoming async itself.
|
||||
pub fn serve_blocking(addr: SocketAddr, state: SmartHttpState) -> Result<()> {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.map_err(ForgeError::Io)?;
|
||||
runtime.block_on(serve(addr, state)).map_err(ForgeError::Io)
|
||||
}
|
||||
|
||||
/// `GET /info/refs?service=git-(upload|receive)-pack`.
|
||||
async fn get_info_refs(State(state): State<SmartHttpState>, RawQuery(query): RawQuery) -> Response {
|
||||
let Some(service) = service_from_query(query.as_deref()) else {
|
||||
// No/unknown service: this transport speaks smart-HTTP only.
|
||||
return error_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"service not enabled (smart HTTP only)",
|
||||
);
|
||||
};
|
||||
let git_dir = state.git_dir.clone();
|
||||
let produced =
|
||||
run_blocking(move || info_refs(&Repository::open_git_dir(&*git_dir)?, service)).await;
|
||||
into_response(produced)
|
||||
}
|
||||
|
||||
/// `POST /git-upload-pack` — fetch/clone negotiation.
|
||||
async fn post_upload_pack(
|
||||
State(state): State<SmartHttpState>,
|
||||
headers: HeaderMap,
|
||||
body: axum::body::Bytes,
|
||||
) -> Response {
|
||||
let gzip = is_gzip(&headers);
|
||||
let git_dir = state.git_dir.clone();
|
||||
let raw = body.to_vec();
|
||||
let produced = run_blocking(move || {
|
||||
let body = maybe_gunzip(raw, gzip)?;
|
||||
upload_pack_rpc(&Repository::open_git_dir(&*git_dir)?, &body)
|
||||
})
|
||||
.await;
|
||||
into_response(produced)
|
||||
}
|
||||
|
||||
/// `POST /git-receive-pack` — push.
|
||||
async fn post_receive_pack(
|
||||
State(state): State<SmartHttpState>,
|
||||
headers: HeaderMap,
|
||||
body: axum::body::Bytes,
|
||||
) -> Response {
|
||||
let gzip = is_gzip(&headers);
|
||||
let git_dir = state.git_dir.clone();
|
||||
let config = state.config.clone();
|
||||
let raw = body.to_vec();
|
||||
let produced = run_blocking(move || {
|
||||
let body = maybe_gunzip(raw, gzip)?;
|
||||
receive_pack_rpc(&Repository::open_git_dir(&*git_dir)?, &body, &config)
|
||||
})
|
||||
.await;
|
||||
into_response(produced)
|
||||
}
|
||||
|
||||
/// Run a blocking, `Repository`-touching closure on the blocking pool.
|
||||
async fn run_blocking<F>(f: F) -> Result<SmartResponse>
|
||||
where
|
||||
F: FnOnce() -> Result<SmartResponse> + Send + 'static,
|
||||
{
|
||||
match tokio::task::spawn_blocking(f).await {
|
||||
Ok(result) => result,
|
||||
Err(join) => Err(ForgeError::ResourceLimit(format!(
|
||||
"smart-http worker task failed: {join}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Was the request body gzip-encoded?
|
||||
fn is_gzip(headers: &HeaderMap) -> bool {
|
||||
headers
|
||||
.get(header::CONTENT_ENCODING)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(|value| value.split(',').any(|token| token.trim() == "gzip"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Map a sync-core result onto the framework response, hiding internal error
|
||||
/// detail behind a generic `500` (server-side context stays in the error type
|
||||
/// for the caller to log).
|
||||
fn into_response(produced: Result<SmartResponse>) -> Response {
|
||||
match produced {
|
||||
Ok(smart) => Response::builder()
|
||||
.status(smart.status)
|
||||
.header(header::CONTENT_TYPE, smart.content_type)
|
||||
// Advertisements and RPC results must never be cached by proxies.
|
||||
.header(
|
||||
header::CACHE_CONTROL,
|
||||
"no-cache, max-age=0, must-revalidate",
|
||||
)
|
||||
.header(header::PRAGMA, "no-cache")
|
||||
.body(Body::from(smart.body))
|
||||
.unwrap_or_else(|_| {
|
||||
error_response(StatusCode::INTERNAL_SERVER_ERROR, "response build failed")
|
||||
}),
|
||||
Err(error) => {
|
||||
let status = match error {
|
||||
ForgeError::NotARepository(_) | ForgeError::ObjectNotFound(_) => {
|
||||
StatusCode::NOT_FOUND
|
||||
}
|
||||
ForgeError::ResourceLimit(_) => StatusCode::PAYLOAD_TOO_LARGE,
|
||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
error_response(status, "smart-http request failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain-text error response with the given status.
|
||||
fn error_response(status: StatusCode, message: &str) -> Response {
|
||||
Response::builder()
|
||||
.status(status)
|
||||
.header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
|
||||
.body(Body::from(format!("{message}\n")))
|
||||
.expect("static error response is always valid")
|
||||
}
|
||||
48
src/lib.rs
48
src/lib.rs
@ -65,8 +65,10 @@ pub mod diff_render;
|
||||
pub mod error;
|
||||
pub mod fsck;
|
||||
pub mod headers;
|
||||
pub mod http;
|
||||
pub mod index;
|
||||
pub mod merge;
|
||||
pub mod merge_cmd;
|
||||
pub mod object;
|
||||
pub mod odb;
|
||||
pub mod oid;
|
||||
@ -76,9 +78,11 @@ pub mod receive_pack;
|
||||
pub mod reflog;
|
||||
pub mod refs;
|
||||
pub mod repo;
|
||||
pub mod sequencer;
|
||||
pub mod server;
|
||||
pub mod show;
|
||||
pub mod signature;
|
||||
pub mod stash;
|
||||
pub mod tag;
|
||||
pub mod tag_ops;
|
||||
pub mod tree;
|
||||
@ -87,43 +91,63 @@ pub mod wire;
|
||||
pub mod worktree;
|
||||
|
||||
pub use blob::Blob;
|
||||
pub use branch::{
|
||||
cmd_branch_create, cmd_branch_delete, cmd_branch_list, cmd_branch_rename, dispatch_branch,
|
||||
BranchOp,
|
||||
};
|
||||
pub use checkout::{cmd_switch, SwitchHead, SwitchResult};
|
||||
pub use commit::Commit;
|
||||
pub use diff::{diff_trees, ChangeKind, TreeChange};
|
||||
pub use diff_render::cmd_diff;
|
||||
pub use error::{ForgeError, Result};
|
||||
pub use fsck::{
|
||||
check_connectivity, is_ancestor, ConnectivityLimits, ConnectivityReport, ObjectReader,
|
||||
};
|
||||
pub use http::smart_http::{
|
||||
info_refs, maybe_gunzip, receive_pack_rpc, router as smart_http_router,
|
||||
serve as smart_http_serve, serve_blocking as smart_http_serve_blocking, upload_pack_rpc,
|
||||
Service, SmartHttpConfig, SmartHttpState, SmartResponse, DEFAULT_MAX_BODY_BYTES,
|
||||
};
|
||||
pub use index::{Index, IndexEntry};
|
||||
pub use merge::{merge_base, merge_bases, merge_commits, merge_trees, MergeOutcome};
|
||||
pub use merge_cmd::{abort_merge, cmd_merge, continue_merge, MergeKind, MergeResult};
|
||||
pub use object::{hash_content, parse_loose, Object, ObjectType};
|
||||
pub use odb::Odb;
|
||||
pub use oid::ObjectId;
|
||||
pub use pack::PackStore;
|
||||
pub use receive::{ReceiveLimits, ReceiveObject, ReceiveOutcome, ReceiveTransaction, RefUpdate};
|
||||
pub use receive::{
|
||||
AtomicRefResult, AtomicRefUpdate, ReceiveAtomicOutcome, ReceiveLimits, ReceiveObject,
|
||||
ReceiveOutcome, ReceiveTransaction, RefUpdate,
|
||||
};
|
||||
pub use receive_pack::{
|
||||
advertise_receive_pack, execute_receive_pack, DeletedRef, ReceivePackExecution,
|
||||
ReceivePackPolicy, RECEIVE_PACK_CAPABILITIES,
|
||||
};
|
||||
pub use refs::{validate_refname, RefTarget, Refs};
|
||||
pub use reflog::{append_reflog_file, log_path_for_ref, read_reflog, ReflogEntry, NULL_OID_HEX};
|
||||
pub use refs::{validate_refname, AtomicRefError, RefChange, RefCommand, RefTarget, Refs};
|
||||
pub use repo::Repository;
|
||||
pub use sequencer::{
|
||||
cmd_cherry_pick, cmd_rebase, cmd_sequencer_abort, cmd_sequencer_continue, cmd_sequencer_skip,
|
||||
SequencerStatus,
|
||||
};
|
||||
pub use server::{dumb_info_refs, objects_info_packs, update_server_info};
|
||||
pub use show::cmd_show;
|
||||
pub use signature::Signature;
|
||||
pub use stash::{
|
||||
cmd_stash_apply, cmd_stash_drop, cmd_stash_pop, cmd_stash_push, stash_list, StashApply,
|
||||
};
|
||||
pub use tag::Tag;
|
||||
pub use tag_ops::{
|
||||
cmd_tag_create_annotated, cmd_tag_create_lightweight, cmd_tag_delete, cmd_tag_list,
|
||||
dispatch_tag, TagOp,
|
||||
};
|
||||
pub use tree::{Tree, TreeEntry};
|
||||
pub use upload_pack::{
|
||||
advertise_upload_pack, generate_pack, parse_fetch_request, reachable_objects, upload_pack_v0,
|
||||
FetchRequest, UPLOAD_PACK_CAPABILITIES,
|
||||
advertise_upload_pack, generate_pack, generate_pack_with_options, parse_fetch_request,
|
||||
reachable_objects, upload_pack_v0, FetchRequest, PackOptions, UPLOAD_PACK_CAPABILITIES,
|
||||
};
|
||||
pub use wire::{
|
||||
decode_packet_lines, encode_packet_line, encode_receive_status, parse_receive_pack_request,
|
||||
PacketLine, PacketLineLimits, ReceivePackCommand, ReceivePackRequest, ReceiveStatus,
|
||||
};
|
||||
pub use worktree::{StatusEntry, WorktreeState};
|
||||
pub use branch::{BranchOp, dispatch_branch, cmd_branch_list, cmd_branch_create,
|
||||
cmd_branch_delete, cmd_branch_rename};
|
||||
pub use checkout::{cmd_switch, SwitchHead, SwitchResult};
|
||||
pub use diff_render::cmd_diff;
|
||||
pub use show::cmd_show;
|
||||
pub use tag_ops::{TagOp, dispatch_tag, cmd_tag_list, cmd_tag_create_lightweight,
|
||||
cmd_tag_create_annotated, cmd_tag_delete};
|
||||
pub use reflog::{ReflogEntry, read_reflog, append_reflog_file, log_path_for_ref, NULL_OID_HEX};
|
||||
|
||||
323
src/main.rs
323
src/main.rs
@ -10,10 +10,13 @@ use anyhow::{bail, Context, Result};
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
use rit::object::Object;
|
||||
use rit::{
|
||||
advertise_receive_pack, cmd_diff, cmd_show, cmd_switch, dispatch_branch, dispatch_tag,
|
||||
execute_receive_pack, parse_receive_pack_request, BranchOp, ObjectType, PacketLineLimits,
|
||||
ReceiveLimits, ReceivePackCommand, ReceivePackPolicy, Repository, Signature, SwitchHead, TagOp,
|
||||
WorktreeState, RECEIVE_PACK_CAPABILITIES,
|
||||
abort_merge, advertise_receive_pack, cmd_cherry_pick, cmd_diff, cmd_merge, cmd_rebase,
|
||||
cmd_sequencer_abort, cmd_sequencer_continue, cmd_sequencer_skip, cmd_show, cmd_stash_apply,
|
||||
cmd_stash_drop, cmd_stash_pop, cmd_stash_push, cmd_switch, continue_merge, dispatch_branch,
|
||||
dispatch_tag, execute_receive_pack, parse_receive_pack_request, smart_http_serve_blocking,
|
||||
stash_list, BranchOp, MergeKind, ObjectType, PacketLineLimits, ReceiveLimits,
|
||||
ReceivePackCommand, ReceivePackPolicy, Repository, SequencerStatus, Signature, SmartHttpConfig,
|
||||
SmartHttpState, StashApply, SwitchHead, TagOp, WorktreeState, RECEIVE_PACK_CAPABILITIES,
|
||||
};
|
||||
|
||||
#[derive(Parser)]
|
||||
@ -73,6 +76,16 @@ enum Command {
|
||||
ReceivePack(ReceivePackArgs),
|
||||
/// Serve Git upload-pack through the installed open-source Git backend.
|
||||
UploadPack(UploadPackArgs),
|
||||
/// Join another branch's history into the current one. Like `git merge`.
|
||||
Merge(MergeArgs),
|
||||
/// Reapply commits on top of another base tip. Like `git rebase`.
|
||||
Rebase(RebaseArgs),
|
||||
/// Apply the changes of existing commits. Like `git cherry-pick`.
|
||||
CherryPick(CherryPickArgs),
|
||||
/// Stash the dirty worktree/index away and restore it later. Like `git stash`.
|
||||
Stash(StashArgs),
|
||||
/// Serve one repository over the Git smart-HTTP protocol.
|
||||
ServeHttp(ServeHttpArgs),
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
@ -254,6 +267,108 @@ struct UploadPackArgs {
|
||||
git_dir: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct MergeArgs {
|
||||
/// Create a merge commit even when a fast-forward is possible. Like `git merge --no-ff`.
|
||||
#[arg(long = "no-ff")]
|
||||
no_ff: bool,
|
||||
/// Conclude a conflicted merge after resolving the worktree. Like `git merge --continue`.
|
||||
#[arg(long = "continue", conflicts_with_all = ["abort", "target"])]
|
||||
cont: bool,
|
||||
/// Abort an in-progress merge and restore the pre-merge state. Like `git merge --abort`.
|
||||
#[arg(long = "abort", conflicts_with_all = ["cont", "target"])]
|
||||
abort: bool,
|
||||
/// Merge commit message (defaults to a generated `Merge ...` line).
|
||||
#[arg(short = 'm', long = "message")]
|
||||
message: Option<String>,
|
||||
/// Branch, tag, or commit to merge into the current branch.
|
||||
target: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct RebaseArgs {
|
||||
/// Reset onto this base instead of `<upstream>`. Like `git rebase --onto`.
|
||||
#[arg(long = "onto")]
|
||||
onto: Option<String>,
|
||||
/// Resume after resolving a conflict. Like `git rebase --continue`.
|
||||
#[arg(long = "continue", conflicts_with_all = ["abort", "skip", "upstream"])]
|
||||
cont: bool,
|
||||
/// Abort and return to the pre-rebase branch tip. Like `git rebase --abort`.
|
||||
#[arg(long = "abort", conflicts_with_all = ["cont", "skip", "upstream"])]
|
||||
abort: bool,
|
||||
/// Drop the current commit and continue. Like `git rebase --skip`.
|
||||
#[arg(long = "skip", conflicts_with_all = ["cont", "abort", "upstream"])]
|
||||
skip: bool,
|
||||
/// Upstream branch/commit whose `..HEAD` commits are replayed.
|
||||
upstream: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct CherryPickArgs {
|
||||
/// Resume after resolving a conflict. Like `git cherry-pick --continue`.
|
||||
#[arg(long = "continue", conflicts_with_all = ["abort", "skip", "revs"])]
|
||||
cont: bool,
|
||||
/// Abort the in-progress cherry-pick sequence. Like `git cherry-pick --abort`.
|
||||
#[arg(long = "abort", conflicts_with_all = ["cont", "skip", "revs"])]
|
||||
abort: bool,
|
||||
/// Drop the current commit and continue. Like `git cherry-pick --skip`.
|
||||
#[arg(long = "skip", conflicts_with_all = ["cont", "abort", "revs"])]
|
||||
skip: bool,
|
||||
/// One or more commits to replay onto the current branch.
|
||||
revs: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct StashArgs {
|
||||
#[command(subcommand)]
|
||||
action: Option<StashAction>,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum StashAction {
|
||||
/// Record the dirty worktree/index and reset back to HEAD (default action).
|
||||
Push {
|
||||
/// Optional description for the stash entry.
|
||||
#[arg(short = 'm', long = "message")]
|
||||
message: Option<String>,
|
||||
},
|
||||
/// List the stash entries, newest first.
|
||||
List,
|
||||
/// Apply a stash entry without removing it from the stack.
|
||||
Apply {
|
||||
/// Stash index (0 = most recent).
|
||||
#[arg(default_value_t = 0)]
|
||||
index: usize,
|
||||
},
|
||||
/// Apply a stash entry and drop it on a clean apply.
|
||||
Pop {
|
||||
/// Stash index (0 = most recent).
|
||||
#[arg(default_value_t = 0)]
|
||||
index: usize,
|
||||
},
|
||||
/// Delete a stash entry from the stack.
|
||||
Drop {
|
||||
/// Stash index (0 = most recent).
|
||||
#[arg(default_value_t = 0)]
|
||||
index: usize,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct ServeHttpArgs {
|
||||
/// Exact bare repository/git directory to serve at the URL root.
|
||||
git_dir: PathBuf,
|
||||
/// Address to bind, e.g. `127.0.0.1:8080`.
|
||||
#[arg(long = "addr", default_value = "127.0.0.1:8080")]
|
||||
addr: String,
|
||||
/// Branch (short name) whose direct push is blocked. Repeatable.
|
||||
#[arg(long = "block-branch")]
|
||||
block_branch: Vec<String>,
|
||||
/// Allow non-fast-forward branch updates (a repository-owner decision).
|
||||
#[arg(long = "allow-non-ff")]
|
||||
allow_non_ff: bool,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if let Err(err) = run() {
|
||||
eprintln!("rit: {err:#}");
|
||||
@ -284,9 +399,187 @@ fn run() -> Result<()> {
|
||||
Command::Restore(args) => cmd_restore(&cli, args),
|
||||
Command::ReceivePack(args) => cmd_receive_pack(args),
|
||||
Command::UploadPack(args) => cmd_upload_pack(args),
|
||||
Command::Merge(args) => cmd_merge_cli(&cli, args),
|
||||
Command::Rebase(args) => cmd_rebase_cli(&cli, args),
|
||||
Command::CherryPick(args) => cmd_cherry_pick_cli(&cli, args),
|
||||
Command::Stash(args) => cmd_stash_cli(&cli, args),
|
||||
Command::ServeHttp(args) => cmd_serve_http(args),
|
||||
}
|
||||
}
|
||||
|
||||
fn cmd_merge_cli(cli: &Cli, args: &MergeArgs) -> Result<()> {
|
||||
let repo = Repository::discover(&cli.repo)
|
||||
.with_context(|| format!("opening repo at {}", cli.repo.display()))?;
|
||||
|
||||
if args.abort {
|
||||
abort_merge(&repo)?;
|
||||
println!("merge aborted");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let sig = current_signature(repo.git_dir())?;
|
||||
|
||||
if args.cont {
|
||||
let oid = continue_merge(&repo, &sig, args.message.as_deref())?;
|
||||
println!("{oid}");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let target = args
|
||||
.target
|
||||
.as_deref()
|
||||
.context("merge requires a target (or --continue/--abort)")?;
|
||||
let result = cmd_merge(&repo, target, &sig, args.message.as_deref(), args.no_ff)?;
|
||||
match result.kind {
|
||||
MergeKind::AlreadyUpToDate => println!("Already up to date."),
|
||||
MergeKind::FastForward(oid) => println!("Fast-forward to {oid}"),
|
||||
MergeKind::Merged(oid) => println!("Merge made by the three-way strategy: {oid}"),
|
||||
MergeKind::Conflicts(paths) => {
|
||||
report_conflicts("merge", &paths);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cmd_rebase_cli(cli: &Cli, args: &RebaseArgs) -> Result<()> {
|
||||
let repo = Repository::discover(&cli.repo)
|
||||
.with_context(|| format!("opening repo at {}", cli.repo.display()))?;
|
||||
|
||||
if args.abort {
|
||||
cmd_sequencer_abort(&repo)?;
|
||||
println!("rebase aborted");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let sig = current_signature(repo.git_dir())?;
|
||||
let status = if args.cont {
|
||||
cmd_sequencer_continue(&repo, &sig)?
|
||||
} else if args.skip {
|
||||
cmd_sequencer_skip(&repo, &sig)?
|
||||
} else {
|
||||
let upstream = args
|
||||
.upstream
|
||||
.as_deref()
|
||||
.context("rebase requires an upstream (or --continue/--abort/--skip)")?;
|
||||
cmd_rebase(&repo, upstream, args.onto.as_deref(), &sig)?
|
||||
};
|
||||
report_sequencer("rebase", &status)
|
||||
}
|
||||
|
||||
fn cmd_cherry_pick_cli(cli: &Cli, args: &CherryPickArgs) -> Result<()> {
|
||||
let repo = Repository::discover(&cli.repo)
|
||||
.with_context(|| format!("opening repo at {}", cli.repo.display()))?;
|
||||
|
||||
if args.abort {
|
||||
cmd_sequencer_abort(&repo)?;
|
||||
println!("cherry-pick aborted");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let sig = current_signature(repo.git_dir())?;
|
||||
let status = if args.cont {
|
||||
cmd_sequencer_continue(&repo, &sig)?
|
||||
} else if args.skip {
|
||||
cmd_sequencer_skip(&repo, &sig)?
|
||||
} else {
|
||||
if args.revs.is_empty() {
|
||||
bail!("cherry-pick requires at least one commit (or --continue/--abort/--skip)");
|
||||
}
|
||||
let revs: Vec<&str> = args.revs.iter().map(String::as_str).collect();
|
||||
cmd_cherry_pick(&repo, &revs, &sig)?
|
||||
};
|
||||
report_sequencer("cherry-pick", &status)
|
||||
}
|
||||
|
||||
/// Print a sequencer outcome, exiting non-zero when it stopped on a conflict.
|
||||
fn report_sequencer(op: &str, status: &SequencerStatus) -> Result<()> {
|
||||
match status {
|
||||
SequencerStatus::Completed => {
|
||||
println!("{op} completed");
|
||||
Ok(())
|
||||
}
|
||||
SequencerStatus::Stopped { conflicts } => {
|
||||
report_conflicts(op, conflicts);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn report_conflicts(op: &str, paths: &[String]) {
|
||||
eprintln!("{op} stopped due to conflicts in:");
|
||||
for path in paths {
|
||||
eprintln!("\t{path}");
|
||||
}
|
||||
eprintln!("resolve them, then run `rit {op} --continue` (or `--abort`)");
|
||||
}
|
||||
|
||||
fn cmd_stash_cli(cli: &Cli, args: &StashArgs) -> Result<()> {
|
||||
let repo = Repository::discover(&cli.repo)
|
||||
.with_context(|| format!("opening repo at {}", cli.repo.display()))?;
|
||||
|
||||
match args.action.as_ref() {
|
||||
Some(StashAction::List) => {
|
||||
for (index, message) in stash_list(&repo)? {
|
||||
println!("stash@{{{index}}}: {message}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Some(StashAction::Apply { index }) => report_stash_apply(cmd_stash_apply(&repo, *index)?),
|
||||
Some(StashAction::Pop { index }) => report_stash_apply(cmd_stash_pop(&repo, *index)?),
|
||||
Some(StashAction::Drop { index }) => {
|
||||
cmd_stash_drop(&repo, *index)?;
|
||||
println!("dropped stash@{{{index}}}");
|
||||
Ok(())
|
||||
}
|
||||
// `rit stash` with no subcommand defaults to push, like `git stash`.
|
||||
Some(StashAction::Push { .. }) | None => {
|
||||
let message = match args.action.as_ref() {
|
||||
Some(StashAction::Push { message }) => message.as_deref(),
|
||||
_ => None,
|
||||
};
|
||||
let sig = current_signature(repo.git_dir())?;
|
||||
match cmd_stash_push(&repo, &sig, message)? {
|
||||
Some(oid) => println!("Saved working directory and index state: {oid}"),
|
||||
None => println!("No local changes to save"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn report_stash_apply(result: StashApply) -> Result<()> {
|
||||
match result {
|
||||
StashApply::Clean => Ok(()),
|
||||
StashApply::Conflicts(paths) => {
|
||||
report_conflicts("stash apply", &paths);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve one repository over Git smart-HTTP until the process is stopped.
|
||||
fn cmd_serve_http(args: &ServeHttpArgs) -> Result<()> {
|
||||
let addr: std::net::SocketAddr = args
|
||||
.addr
|
||||
.parse()
|
||||
.with_context(|| format!("invalid --addr {:?} (expected ip:port)", args.addr))?;
|
||||
|
||||
// Validate the repository up front so a bad path fails before we bind.
|
||||
Repository::open_git_dir(&args.git_dir)
|
||||
.with_context(|| format!("opening bare repo at {}", args.git_dir.display()))?;
|
||||
|
||||
let config = SmartHttpConfig {
|
||||
blocked_branches: args.block_branch.clone(),
|
||||
allow_non_fast_forward: args.allow_non_ff,
|
||||
..SmartHttpConfig::new()
|
||||
};
|
||||
let state = SmartHttpState::new(args.git_dir.clone(), config);
|
||||
eprintln!("rit: serving {} on http://{addr}/", args.git_dir.display());
|
||||
smart_http_serve_blocking(addr, state)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Serve a **native** stateful (SSH/process) upload-pack session over
|
||||
/// stdin/stdout — no `git upload-pack` backend. Writes the v0 ref advertisement,
|
||||
/// reads the client's `want`/`have`/`done` negotiation (answering `NAK` after
|
||||
@ -410,7 +703,9 @@ fn read_pkt_line(input: &mut impl Read) -> Result<PktLine> {
|
||||
4 => Ok(PktLine::Other), // empty payload
|
||||
_ => {
|
||||
let mut payload = vec![0u8; length - 4];
|
||||
input.read_exact(&mut payload).context("reading pkt-line payload")?;
|
||||
input
|
||||
.read_exact(&mut payload)
|
||||
.context("reading pkt-line payload")?;
|
||||
let line = String::from_utf8_lossy(&payload);
|
||||
let line = line.trim_end();
|
||||
if let Some(rest) = line.strip_prefix("want ") {
|
||||
@ -449,7 +744,8 @@ fn cmd_receive_pack(args: &ReceivePackArgs) -> Result<()> {
|
||||
// targets a blocked branch, reject the whole push with a per-ref `ng` status
|
||||
// and never touch objects or refs.
|
||||
if !args.block_branch.is_empty() {
|
||||
let parsed = parse_receive_pack_request(&request, RECEIVE_PACK_CAPABILITIES, packet_limits)?;
|
||||
let parsed =
|
||||
parse_receive_pack_request(&request, RECEIVE_PACK_CAPABILITIES, packet_limits)?;
|
||||
let blocked = parsed.commands.iter().any(|cmd| {
|
||||
cmd.name()
|
||||
.strip_prefix("refs/heads/")
|
||||
@ -559,8 +855,14 @@ fn read_receive_pack_request(
|
||||
}
|
||||
|
||||
let parsed = parse_receive_pack_request(&request, RECEIVE_PACK_CAPABILITIES, packet_limits)?;
|
||||
let needs_pack = parsed.commands.len() == 1
|
||||
&& !matches!(parsed.commands[0], ReceivePackCommand::Delete { .. });
|
||||
// A pack follows whenever any command creates or updates a ref (including a
|
||||
// multi-ref push). A push made up solely of deletions carries no pack, and
|
||||
// Git keeps its write side open awaiting status, so reading for EOF there
|
||||
// would deadlock.
|
||||
let needs_pack = parsed
|
||||
.commands
|
||||
.iter()
|
||||
.any(|command| !matches!(command, ReceivePackCommand::Delete { .. }));
|
||||
if needs_pack {
|
||||
let max_pack = usize::try_from(receive_limits.max_pack_bytes)
|
||||
.context("receive pack limit does not fit this platform")?;
|
||||
@ -844,10 +1146,7 @@ fn cmd_init(args: &InitArgs) -> Result<()> {
|
||||
};
|
||||
let kind = if args.bare { "bare " } else { "" };
|
||||
let git_dir = std::fs::canonicalize(repo.git_dir()).unwrap_or_else(|_| repo.git_dir().into());
|
||||
println!(
|
||||
"{action} {kind}Git repository in {}/",
|
||||
git_dir.display()
|
||||
);
|
||||
println!("{action} {kind}Git repository in {}/", git_dir.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
120
src/merge.rs
120
src/merge.rs
@ -241,10 +241,7 @@ fn is_binary(data: &[u8]) -> bool {
|
||||
}
|
||||
|
||||
/// Flatten an optional tree; `None` → empty map.
|
||||
fn flatten_opt(
|
||||
repo: &Repository,
|
||||
tree: Option<ObjectId>,
|
||||
) -> Result<BTreeMap<Vec<u8>, Entry>> {
|
||||
fn flatten_opt(repo: &Repository, tree: Option<ObjectId>) -> Result<BTreeMap<Vec<u8>, Entry>> {
|
||||
match tree {
|
||||
Some(oid) => flatten(repo, oid),
|
||||
None => Ok(BTreeMap::new()),
|
||||
@ -405,7 +402,8 @@ mod tests {
|
||||
.collect(),
|
||||
};
|
||||
t.canonicalize();
|
||||
repo.hash_object(ObjectType::Tree, &t.serialize(), true).unwrap()
|
||||
repo.hash_object(ObjectType::Tree, &t.serialize(), true)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn tree_modes(repo: &Repository, entries: Vec<(&str, &str, ObjectId)>) -> ObjectId {
|
||||
@ -420,11 +418,13 @@ mod tests {
|
||||
.collect(),
|
||||
};
|
||||
t.canonicalize();
|
||||
repo.hash_object(ObjectType::Tree, &t.serialize(), true).unwrap()
|
||||
repo.hash_object(ObjectType::Tree, &t.serialize(), true)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn commit(repo: &Repository, tree: ObjectId, parents: Vec<ObjectId>) -> ObjectId {
|
||||
repo.commit_tree(tree, parents, sig(), sig(), b"c\n", None).unwrap()
|
||||
repo.commit_tree(tree, parents, sig(), sig(), b"c\n", None)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -441,7 +441,11 @@ mod tests {
|
||||
let ours_only = blob(&repo, b"ours\n");
|
||||
let ours_tree = tree(
|
||||
&repo,
|
||||
vec![("a.txt", a_ours), ("shared.txt", shared), ("ours.txt", ours_only)],
|
||||
vec![
|
||||
("a.txt", a_ours),
|
||||
("shared.txt", shared),
|
||||
("ours.txt", ours_only),
|
||||
],
|
||||
);
|
||||
let ours = commit(&repo, ours_tree, vec![base]);
|
||||
// theirs: change line 3 + add theirs.txt
|
||||
@ -449,7 +453,11 @@ mod tests {
|
||||
let theirs_only = blob(&repo, b"theirs\n");
|
||||
let theirs_tree = tree(
|
||||
&repo,
|
||||
vec![("a.txt", a_theirs), ("shared.txt", shared), ("theirs.txt", theirs_only)],
|
||||
vec![
|
||||
("a.txt", a_theirs),
|
||||
("shared.txt", shared),
|
||||
("theirs.txt", theirs_only),
|
||||
],
|
||||
);
|
||||
let theirs = commit(&repo, theirs_tree, vec![base]);
|
||||
|
||||
@ -497,9 +505,16 @@ mod tests {
|
||||
let g1 = commit(&repo, tree(&repo, vec![("a.txt", blob0)]), vec![root]);
|
||||
let g2 = commit(&repo, tree(&repo, vec![("a.txt", blob0)]), vec![g1]);
|
||||
// Distinct trees so the two tips are distinct commits (not the same oid).
|
||||
let ours = commit(&repo, tree(&repo, vec![("a.txt", blob(&repo, b"ours\n"))]), vec![g2]);
|
||||
let theirs =
|
||||
commit(&repo, tree(&repo, vec![("a.txt", blob(&repo, b"theirs\n"))]), vec![g2]);
|
||||
let ours = commit(
|
||||
&repo,
|
||||
tree(&repo, vec![("a.txt", blob(&repo, b"ours\n"))]),
|
||||
vec![g2],
|
||||
);
|
||||
let theirs = commit(
|
||||
&repo,
|
||||
tree(&repo, vec![("a.txt", blob(&repo, b"theirs\n"))]),
|
||||
vec![g2],
|
||||
);
|
||||
|
||||
assert_eq!(merge_bases(&repo, ours, theirs).unwrap(), vec![g2]);
|
||||
assert_eq!(merge_base(&repo, ours, theirs).unwrap(), Some(g2));
|
||||
@ -518,11 +533,27 @@ mod tests {
|
||||
let repo = Repository::init(dir.path(), true, Some("main")).unwrap();
|
||||
let blob0 = blob(&repo, b"0\n");
|
||||
let root = commit(&repo, tree(&repo, vec![("a.txt", blob0)]), vec![]);
|
||||
let a = commit(&repo, tree(&repo, vec![("a.txt", blob(&repo, b"a\n"))]), vec![root]);
|
||||
let b = commit(&repo, tree(&repo, vec![("a.txt", blob(&repo, b"b\n"))]), vec![root]);
|
||||
let a = commit(
|
||||
&repo,
|
||||
tree(&repo, vec![("a.txt", blob(&repo, b"a\n"))]),
|
||||
vec![root],
|
||||
);
|
||||
let b = commit(
|
||||
&repo,
|
||||
tree(&repo, vec![("a.txt", blob(&repo, b"b\n"))]),
|
||||
vec![root],
|
||||
);
|
||||
// Two independent merges of the same pair of branches => criss-cross.
|
||||
let m1 = commit(&repo, tree(&repo, vec![("a.txt", blob(&repo, b"m1\n"))]), vec![a, b]);
|
||||
let m2 = commit(&repo, tree(&repo, vec![("a.txt", blob(&repo, b"m2\n"))]), vec![a, b]);
|
||||
let m1 = commit(
|
||||
&repo,
|
||||
tree(&repo, vec![("a.txt", blob(&repo, b"m1\n"))]),
|
||||
vec![a, b],
|
||||
);
|
||||
let m2 = commit(
|
||||
&repo,
|
||||
tree(&repo, vec![("a.txt", blob(&repo, b"m2\n"))]),
|
||||
vec![a, b],
|
||||
);
|
||||
|
||||
let mut bases = merge_bases(&repo, m1, m2).unwrap();
|
||||
bases.sort();
|
||||
@ -543,10 +574,18 @@ mod tests {
|
||||
let repo = Repository::init(dir.path(), true, Some("main")).unwrap();
|
||||
let a0 = blob(&repo, b"base\n");
|
||||
let keep = blob(&repo, b"keep\n");
|
||||
let base = commit(&repo, tree(&repo, vec![("a.txt", a0), ("k.txt", keep)]), vec![]);
|
||||
let base = commit(
|
||||
&repo,
|
||||
tree(&repo, vec![("a.txt", a0), ("k.txt", keep)]),
|
||||
vec![],
|
||||
);
|
||||
// ours modifies a.txt; theirs deletes a.txt (tree omits it).
|
||||
let a_mod = blob(&repo, b"changed\n");
|
||||
let ours = commit(&repo, tree(&repo, vec![("a.txt", a_mod), ("k.txt", keep)]), vec![base]);
|
||||
let ours = commit(
|
||||
&repo,
|
||||
tree(&repo, vec![("a.txt", a_mod), ("k.txt", keep)]),
|
||||
vec![base],
|
||||
);
|
||||
let theirs = commit(&repo, tree(&repo, vec![("k.txt", keep)]), vec![base]);
|
||||
|
||||
match merge_commits(&repo, ours, theirs).unwrap() {
|
||||
@ -562,12 +601,23 @@ mod tests {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let repo = Repository::init(dir.path(), true, Some("main")).unwrap();
|
||||
let content = blob(&repo, b"x\n");
|
||||
let base = commit(&repo, tree_modes(&repo, vec![("s.sh", "100644", content)]), vec![]);
|
||||
let base = commit(
|
||||
&repo,
|
||||
tree_modes(&repo, vec![("s.sh", "100644", content)]),
|
||||
vec![],
|
||||
);
|
||||
// ours: chmod +x, same content. theirs: same mode, new content.
|
||||
let ours = commit(&repo, tree_modes(&repo, vec![("s.sh", "100755", content)]), vec![base]);
|
||||
let ours = commit(
|
||||
&repo,
|
||||
tree_modes(&repo, vec![("s.sh", "100755", content)]),
|
||||
vec![base],
|
||||
);
|
||||
let new_content = blob(&repo, b"y\n");
|
||||
let theirs =
|
||||
commit(&repo, tree_modes(&repo, vec![("s.sh", "100644", new_content)]), vec![base]);
|
||||
let theirs = commit(
|
||||
&repo,
|
||||
tree_modes(&repo, vec![("s.sh", "100644", new_content)]),
|
||||
vec![base],
|
||||
);
|
||||
|
||||
match merge_commits(&repo, ours, theirs).unwrap() {
|
||||
MergeOutcome::Conflict(paths) => assert_eq!(paths, vec!["s.sh".to_string()]),
|
||||
@ -586,9 +636,16 @@ mod tests {
|
||||
// new.txt is the add/add-identical path under test.
|
||||
let ours_only = blob(&repo, b"o\n");
|
||||
let theirs_only = blob(&repo, b"t\n");
|
||||
let ours = commit(&repo, tree(&repo, vec![("new.txt", same), ("o.txt", ours_only)]), vec![base]);
|
||||
let theirs =
|
||||
commit(&repo, tree(&repo, vec![("new.txt", same), ("t.txt", theirs_only)]), vec![base]);
|
||||
let ours = commit(
|
||||
&repo,
|
||||
tree(&repo, vec![("new.txt", same), ("o.txt", ours_only)]),
|
||||
vec![base],
|
||||
);
|
||||
let theirs = commit(
|
||||
&repo,
|
||||
tree(&repo, vec![("new.txt", same), ("t.txt", theirs_only)]),
|
||||
vec![base],
|
||||
);
|
||||
|
||||
match merge_commits(&repo, ours, theirs).unwrap() {
|
||||
MergeOutcome::Clean(t) => {
|
||||
@ -609,9 +666,16 @@ mod tests {
|
||||
let repo = Repository::init(dir.path(), true, Some("main")).unwrap();
|
||||
let base_bin = blob(&repo, b"\x00base");
|
||||
let base = commit(&repo, tree(&repo, vec![("a.bin", base_bin)]), vec![]);
|
||||
let ours = commit(&repo, tree(&repo, vec![("a.bin", blob(&repo, b"\x00ours"))]), vec![base]);
|
||||
let theirs =
|
||||
commit(&repo, tree(&repo, vec![("a.bin", blob(&repo, b"\x00theirs"))]), vec![base]);
|
||||
let ours = commit(
|
||||
&repo,
|
||||
tree(&repo, vec![("a.bin", blob(&repo, b"\x00ours"))]),
|
||||
vec![base],
|
||||
);
|
||||
let theirs = commit(
|
||||
&repo,
|
||||
tree(&repo, vec![("a.bin", blob(&repo, b"\x00theirs"))]),
|
||||
vec![base],
|
||||
);
|
||||
|
||||
match merge_commits(&repo, ours, theirs).unwrap() {
|
||||
MergeOutcome::Conflict(paths) => assert_eq!(paths, vec!["a.bin".to_string()]),
|
||||
|
||||
619
src/merge_cmd.rs
Normal file
619
src/merge_cmd.rs
Normal file
@ -0,0 +1,619 @@
|
||||
//! `git merge` porcelain — wire the from-scratch three-way [`crate::merge`]
|
||||
//! engine into a real command that produces a two-parent commit or surfaces
|
||||
//! conflicts (conflict-marker worktree + unmerged index + `MERGE_HEAD`).
|
||||
//!
|
||||
//! This module also owns the **shared history-editing primitives** that the
|
||||
//! [`crate::sequencer`] (rebase / cherry-pick) and [`crate::stash`] modules
|
||||
//! build on:
|
||||
//!
|
||||
//! - [`build_worktree_merge`] — a three-way tree merge that, unlike
|
||||
//! [`crate::merge::merge_trees`], also returns the conflict-marker content and
|
||||
//! the stage 1/2/3 index entries needed to *represent* a conflict on disk;
|
||||
//! - [`install_unmerged`] — install those unmerged stages into `.git/index`;
|
||||
//! - [`force_reset`] — discard worktree/index state back to a target tree
|
||||
//! (used by `--abort` / `--skip` where the safe [`Repository::checkout_tree`]
|
||||
//! would refuse because of conflict-marker "local changes");
|
||||
//! - small `.git`-directory state-file helpers (`MERGE_HEAD`, `ORIG_HEAD`, …).
|
||||
//!
|
||||
//! The CLI dispatch (clap wiring) is intentionally **not** here — the integrator
|
||||
//! calls [`cmd_merge`], [`continue_merge`], and [`abort_merge`] from `main.rs`.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::error::{ForgeError, Result};
|
||||
use crate::fsck::{is_ancestor as fsck_is_ancestor, ConnectivityLimits};
|
||||
use crate::index::{Index, IndexEntry};
|
||||
use crate::object::ObjectType;
|
||||
use crate::oid::ObjectId;
|
||||
use crate::refs::RefTarget;
|
||||
use crate::repo::Repository;
|
||||
use crate::signature::Signature;
|
||||
use crate::tree::{Tree, TreeEntry};
|
||||
|
||||
/// Bound on tree recursion while flattening for a merge.
|
||||
const MAX_MERGE_DEPTH: usize = 256;
|
||||
|
||||
// ── public command surface ──────────────────────────────────────────────────
|
||||
|
||||
/// How a completed [`cmd_merge`] resolved.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum MergeKind {
|
||||
/// `theirs` was already reachable from `HEAD`; nothing to do.
|
||||
AlreadyUpToDate,
|
||||
/// `HEAD` was an ancestor of `theirs`; the branch was fast-forwarded.
|
||||
FastForward(ObjectId),
|
||||
/// A real three-way merge produced this two-parent commit.
|
||||
Merged(ObjectId),
|
||||
/// The merge conflicted on these paths; `MERGE_HEAD` was recorded and the
|
||||
/// worktree now contains conflict markers.
|
||||
Conflicts(Vec<String>),
|
||||
}
|
||||
|
||||
/// Outcome of a [`cmd_merge`] invocation.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MergeResult {
|
||||
/// The resolution.
|
||||
pub kind: MergeKind,
|
||||
/// The other side's commit that was merged (the `theirs` tip).
|
||||
pub theirs: ObjectId,
|
||||
}
|
||||
|
||||
/// `git merge <target>` into the current branch.
|
||||
///
|
||||
/// Resolves the merge base, then:
|
||||
/// - returns [`MergeKind::AlreadyUpToDate`] when `target` is reachable from HEAD;
|
||||
/// - fast-forwards (unless `no_ff`) when HEAD is an ancestor of `target`;
|
||||
/// - otherwise performs a three-way merge, writing a two-parent commit on a
|
||||
/// clean merge or recording `MERGE_HEAD` + conflict markers on a conflict.
|
||||
///
|
||||
/// Fails closed with [`ForgeError::MergeMultipleBases`] on a criss-cross
|
||||
/// history, matching the single-base scope of [`crate::merge`].
|
||||
pub fn cmd_merge(
|
||||
repo: &Repository,
|
||||
target: &str,
|
||||
sig: &Signature,
|
||||
message: Option<&str>,
|
||||
no_ff: bool,
|
||||
) -> Result<MergeResult> {
|
||||
let git_dir = repo.git_dir();
|
||||
let head_ref = head_branch(repo)?;
|
||||
let ours = repo.head().map_err(|_| {
|
||||
ForgeError::InvalidRef("cannot merge into an empty repository (no HEAD commit)".into())
|
||||
})?;
|
||||
let theirs = repo.resolve(target)?;
|
||||
// Peel a tag/target to its commit so a two-parent merge always links commits.
|
||||
let theirs = peel_commit_oid(repo, theirs)?;
|
||||
|
||||
// ORIG_HEAD is Git's "where I was before this operation" anchor.
|
||||
write_gitdir_file(git_dir, "ORIG_HEAD", format!("{ours}\n").as_bytes())?;
|
||||
|
||||
if ours == theirs || is_ancestor(repo, theirs, ours)? {
|
||||
return Ok(MergeResult {
|
||||
kind: MergeKind::AlreadyUpToDate,
|
||||
theirs,
|
||||
});
|
||||
}
|
||||
|
||||
if !no_ff && is_ancestor(repo, ours, theirs)? {
|
||||
let tree = repo.peel_to_commit(theirs)?.tree;
|
||||
repo.checkout_tree(tree)?;
|
||||
repo.refs()
|
||||
.compare_and_swap(&head_ref, Some(ours), theirs)?;
|
||||
let msg = format!("merge {target}: Fast-forward");
|
||||
let _ = repo.refs().append_reflog(
|
||||
&head_ref,
|
||||
Some(ours),
|
||||
theirs,
|
||||
&sig.name,
|
||||
&sig.email,
|
||||
sig.time,
|
||||
&sig.tz,
|
||||
&msg,
|
||||
);
|
||||
return Ok(MergeResult {
|
||||
kind: MergeKind::FastForward(theirs),
|
||||
theirs,
|
||||
});
|
||||
}
|
||||
|
||||
// True three-way merge.
|
||||
let bases = crate::merge::merge_bases(repo, ours, theirs)?;
|
||||
if bases.len() > 1 {
|
||||
return Err(ForgeError::MergeMultipleBases(bases.len()));
|
||||
}
|
||||
let base_tree = match bases.first() {
|
||||
Some(oid) => Some(repo.peel_to_commit(*oid)?.tree),
|
||||
None => None,
|
||||
};
|
||||
let ours_tree = repo.peel_to_commit(ours)?.tree;
|
||||
let theirs_tree = repo.peel_to_commit(theirs)?.tree;
|
||||
|
||||
let message = normalize_message(message, || default_merge_msg(repo, target));
|
||||
|
||||
match build_worktree_merge(repo, base_tree, ours_tree, theirs_tree)? {
|
||||
WorktreeMerge::Clean(tree) => {
|
||||
repo.checkout_tree(tree)?;
|
||||
let new = repo.commit_tree(
|
||||
tree,
|
||||
vec![ours, theirs],
|
||||
sig.clone(),
|
||||
sig.clone(),
|
||||
message.as_bytes(),
|
||||
Some(&head_ref),
|
||||
)?;
|
||||
Ok(MergeResult {
|
||||
kind: MergeKind::Merged(new),
|
||||
theirs,
|
||||
})
|
||||
}
|
||||
WorktreeMerge::Conflict {
|
||||
tree,
|
||||
conflicts,
|
||||
stages,
|
||||
} => {
|
||||
repo.checkout_tree(tree)?;
|
||||
install_unmerged(git_dir, &stages)?;
|
||||
write_gitdir_file(git_dir, "MERGE_HEAD", format!("{theirs}\n").as_bytes())?;
|
||||
write_gitdir_file(git_dir, "MERGE_MSG", message.as_bytes())?;
|
||||
Ok(MergeResult {
|
||||
kind: MergeKind::Conflicts(conflicts),
|
||||
theirs,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `git merge --continue` / `git commit` after resolving a conflicted merge.
|
||||
///
|
||||
/// Requires a resolved (stage-0) index and a recorded `MERGE_HEAD`. Creates the
|
||||
/// two-parent merge commit from `ORIG_HEAD` (ours) and `MERGE_HEAD` (theirs),
|
||||
/// advances the branch, and clears the merge state files.
|
||||
pub fn continue_merge(
|
||||
repo: &Repository,
|
||||
sig: &Signature,
|
||||
message: Option<&str>,
|
||||
) -> Result<ObjectId> {
|
||||
let git_dir = repo.git_dir();
|
||||
let theirs = read_gitdir_oid(git_dir, "MERGE_HEAD")
|
||||
.ok_or_else(|| ForgeError::InvalidRef("no MERGE_HEAD: not in a conflicted merge".into()))?;
|
||||
let ours = repo.head()?;
|
||||
let head_ref = head_branch(repo)?;
|
||||
// write_tree fails closed if any path is still at an unmerged stage.
|
||||
let tree = repo.write_tree()?;
|
||||
let stored = read_gitdir_string(git_dir, "MERGE_MSG");
|
||||
let message = normalize_message(message.or(stored.as_deref()), || {
|
||||
format!("Merge commit '{theirs}'\n")
|
||||
});
|
||||
let new = repo.commit_tree(
|
||||
tree,
|
||||
vec![ours, theirs],
|
||||
sig.clone(),
|
||||
sig.clone(),
|
||||
message.as_bytes(),
|
||||
Some(&head_ref),
|
||||
)?;
|
||||
remove_gitdir_file(git_dir, "MERGE_HEAD");
|
||||
remove_gitdir_file(git_dir, "MERGE_MSG");
|
||||
Ok(new)
|
||||
}
|
||||
|
||||
/// `git merge --abort`: discard a conflicted merge, restoring `ORIG_HEAD`.
|
||||
pub fn abort_merge(repo: &Repository) -> Result<()> {
|
||||
let git_dir = repo.git_dir();
|
||||
let orig = read_gitdir_oid(git_dir, "ORIG_HEAD")
|
||||
.ok_or_else(|| ForgeError::InvalidRef("no ORIG_HEAD to abort to".into()))?;
|
||||
let head_ref = head_branch(repo)?;
|
||||
let current = repo.head()?;
|
||||
repo.refs()
|
||||
.compare_and_swap(&head_ref, Some(current), orig)?;
|
||||
force_reset(repo, repo.peel_to_commit(orig)?.tree)?;
|
||||
remove_gitdir_file(git_dir, "MERGE_HEAD");
|
||||
remove_gitdir_file(git_dir, "MERGE_MSG");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ── shared three-way merge (content + stages) ───────────────────────────────
|
||||
|
||||
/// One unmerged index entry (a stage-1/2/3 slot for a conflicted path).
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct StageEntry {
|
||||
pub path: Vec<u8>,
|
||||
pub stage: u8,
|
||||
pub mode: String,
|
||||
pub oid: ObjectId,
|
||||
}
|
||||
|
||||
/// The result of a three-way tree merge that carries enough detail to
|
||||
/// materialize a conflict on disk.
|
||||
pub(crate) enum WorktreeMerge {
|
||||
/// A clean merge producing this tree (all entries stage 0).
|
||||
Clean(ObjectId),
|
||||
/// A conflicting merge. `tree` is materializable into the worktree (clean
|
||||
/// paths + conflict-marker/ours blobs for conflicted paths); `stages` are
|
||||
/// the unmerged index entries to install after checkout.
|
||||
Conflict {
|
||||
tree: ObjectId,
|
||||
conflicts: Vec<String>,
|
||||
stages: Vec<StageEntry>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Three-way merge three trees, producing merged content **and** conflict
|
||||
/// representation. `base` is `None` for an empty/unrelated common ancestor.
|
||||
pub(crate) fn build_worktree_merge(
|
||||
repo: &Repository,
|
||||
base: Option<ObjectId>,
|
||||
ours: ObjectId,
|
||||
theirs: ObjectId,
|
||||
) -> Result<WorktreeMerge> {
|
||||
let base_map = match base {
|
||||
Some(oid) => flatten_tree(repo, oid)?,
|
||||
None => BTreeMap::new(),
|
||||
};
|
||||
let ours_map = flatten_tree(repo, ours)?;
|
||||
let theirs_map = flatten_tree(repo, theirs)?;
|
||||
|
||||
let mut paths: Vec<Vec<u8>> = base_map
|
||||
.keys()
|
||||
.chain(ours_map.keys())
|
||||
.chain(theirs_map.keys())
|
||||
.cloned()
|
||||
.collect();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
|
||||
let mut result: BTreeMap<Vec<u8>, Entry> = BTreeMap::new();
|
||||
let mut conflicts: Vec<String> = Vec::new();
|
||||
let mut stages: Vec<StageEntry> = Vec::new();
|
||||
|
||||
for path in paths {
|
||||
let b = base_map.get(&path);
|
||||
let o = ours_map.get(&path);
|
||||
let t = theirs_map.get(&path);
|
||||
|
||||
// Both sides identical (including both absent) → take either.
|
||||
if o == t {
|
||||
if let Some(entry) = o {
|
||||
result.insert(path, entry.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Ours unchanged vs base → take theirs' change (possibly a deletion).
|
||||
if o == b {
|
||||
if let Some(entry) = t {
|
||||
result.insert(path, entry.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Theirs unchanged vs base → take ours' change.
|
||||
if t == b {
|
||||
if let Some(entry) = o {
|
||||
result.insert(path, entry.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Genuine divergence: resolve or record a conflict.
|
||||
match (o, t) {
|
||||
(Some((omode, ooid)), Some((tmode, toid))) => {
|
||||
let base_bytes = match b {
|
||||
Some((_, boid)) => repo.blob(boid)?.data,
|
||||
None => Vec::new(),
|
||||
};
|
||||
let ours_bytes = repo.blob(ooid)?.data;
|
||||
let theirs_bytes = repo.blob(toid)?.data;
|
||||
|
||||
let text_mergeable = omode == tmode
|
||||
&& !is_binary(&base_bytes)
|
||||
&& !is_binary(&ours_bytes)
|
||||
&& !is_binary(&theirs_bytes);
|
||||
let worktree = if text_mergeable {
|
||||
match diffy::merge_bytes(&base_bytes, &ours_bytes, &theirs_bytes) {
|
||||
Ok(bytes) => {
|
||||
let oid = repo.hash_object(ObjectType::Blob, &bytes, true)?;
|
||||
result.insert(path.clone(), (omode.clone(), oid));
|
||||
continue;
|
||||
}
|
||||
// Err carries the diff3 output *with* conflict markers.
|
||||
Err(markers) => {
|
||||
let oid = repo.hash_object(ObjectType::Blob, &markers, true)?;
|
||||
(omode.clone(), oid)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Binary or mode conflict: keep ours in the worktree.
|
||||
(omode.clone(), *ooid)
|
||||
};
|
||||
result.insert(path.clone(), worktree);
|
||||
if let Some((bmode, boid)) = b {
|
||||
stages.push(stage_entry(&path, 1, bmode, *boid));
|
||||
}
|
||||
stages.push(stage_entry(&path, 2, omode, *ooid));
|
||||
stages.push(stage_entry(&path, 3, tmode, *toid));
|
||||
conflicts.push(display(&path));
|
||||
}
|
||||
// Modify/delete: ours changed, theirs removed.
|
||||
(Some((omode, ooid)), None) => {
|
||||
result.insert(path.clone(), (omode.clone(), *ooid));
|
||||
if let Some((bmode, boid)) = b {
|
||||
stages.push(stage_entry(&path, 1, bmode, *boid));
|
||||
}
|
||||
stages.push(stage_entry(&path, 2, omode, *ooid));
|
||||
conflicts.push(display(&path));
|
||||
}
|
||||
// Delete/modify: ours removed, theirs changed.
|
||||
(None, Some((tmode, toid))) => {
|
||||
result.insert(path.clone(), (tmode.clone(), *toid));
|
||||
if let Some((bmode, boid)) = b {
|
||||
stages.push(stage_entry(&path, 1, bmode, *boid));
|
||||
}
|
||||
stages.push(stage_entry(&path, 3, tmode, *toid));
|
||||
conflicts.push(display(&path));
|
||||
}
|
||||
// o == t already handled the (None, None) case.
|
||||
(None, None) => unreachable!("o != t guarantees at least one side present"),
|
||||
}
|
||||
}
|
||||
|
||||
let tree = write_tree_from_entries(repo, &result)?;
|
||||
if conflicts.is_empty() {
|
||||
Ok(WorktreeMerge::Clean(tree))
|
||||
} else {
|
||||
conflicts.sort();
|
||||
conflicts.dedup();
|
||||
Ok(WorktreeMerge::Conflict {
|
||||
tree,
|
||||
conflicts,
|
||||
stages,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Install unmerged (stage 1/2/3) entries for conflicted paths into
|
||||
/// `.git/index`, replacing whatever stage-0 entry a prior checkout left.
|
||||
pub(crate) fn install_unmerged(git_dir: &Path, stages: &[StageEntry]) -> Result<()> {
|
||||
if stages.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let conflicted: BTreeSet<Vec<u8>> = stages.iter().map(|s| s.path.clone()).collect();
|
||||
Index::mutate(git_dir, |index| {
|
||||
index
|
||||
.entries
|
||||
.retain(|entry| !conflicted.contains(&entry.path));
|
||||
for stage in stages {
|
||||
let mode = u32::from_str_radix(&stage.mode, 8).unwrap_or(0o100644);
|
||||
let flags =
|
||||
(((stage.stage & 0x3) as u16) << 12) | (stage.path.len().min(0x0fff) as u16);
|
||||
index.entries.push(IndexEntry {
|
||||
mode,
|
||||
file_size: 0,
|
||||
oid: stage.oid,
|
||||
flags,
|
||||
path: stage.path.clone(),
|
||||
});
|
||||
}
|
||||
index
|
||||
.entries
|
||||
.sort_by(|a, b| a.path.cmp(&b.path).then(a.stage().cmp(&b.stage())));
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
// ── reset / state-file primitives (shared) ──────────────────────────────────
|
||||
|
||||
/// Discard worktree + index state back to `tree`, unconditionally.
|
||||
///
|
||||
/// [`Repository::checkout_tree`] refuses to overwrite "locally modified" paths —
|
||||
/// but after a conflict the worktree *is* full of intentional local changes
|
||||
/// (conflict markers). This first restages the worktree so those changes are no
|
||||
/// longer seen as modifications, then applies `tree`. Used by `--abort` /
|
||||
/// `--skip` and `stash` reset.
|
||||
pub(crate) fn force_reset(repo: &Repository, tree: ObjectId) -> Result<()> {
|
||||
// Restage everything so tracked worktree state == index (no "local changes").
|
||||
repo.add(&[PathBuf::from(".")])?;
|
||||
repo.checkout_tree(tree)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The full ref name HEAD symbolically points at, or an error on detached HEAD.
|
||||
pub(crate) fn head_branch(repo: &Repository) -> Result<String> {
|
||||
match repo.refs().read_head()? {
|
||||
RefTarget::Symbolic(name) => Ok(name),
|
||||
RefTarget::Direct(_) => Err(ForgeError::InvalidRef(
|
||||
"HEAD is detached; this operation requires being on a branch".into(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a small `.git/<rel>` state file (fsynced), creating parent dirs.
|
||||
pub(crate) fn write_gitdir_file(git_dir: &Path, rel: &str, content: &[u8]) -> Result<()> {
|
||||
let path = git_dir.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let mut file = std::fs::File::create(&path)?;
|
||||
file.write_all(content)?;
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove a `.git/<rel>` state file if present (absence is not an error).
|
||||
pub(crate) fn remove_gitdir_file(git_dir: &Path, rel: &str) {
|
||||
let _ = std::fs::remove_file(git_dir.join(rel));
|
||||
}
|
||||
|
||||
/// Read a `.git/<rel>` file as a single object id, if present and valid.
|
||||
pub(crate) fn read_gitdir_oid(git_dir: &Path, rel: &str) -> Option<ObjectId> {
|
||||
let raw = std::fs::read_to_string(git_dir.join(rel)).ok()?;
|
||||
ObjectId::from_hex(raw.trim()).ok()
|
||||
}
|
||||
|
||||
/// Read a `.git/<rel>` file as a UTF-8 string, if present.
|
||||
pub(crate) fn read_gitdir_string(git_dir: &Path, rel: &str) -> Option<String> {
|
||||
std::fs::read_to_string(git_dir.join(rel)).ok()
|
||||
}
|
||||
|
||||
/// Peel a tag/target oid to the underlying commit oid (bounded).
|
||||
pub(crate) fn peel_commit_oid(repo: &Repository, oid: ObjectId) -> Result<ObjectId> {
|
||||
use crate::object::Object;
|
||||
let mut current = oid;
|
||||
for _ in 0..10 {
|
||||
match repo.read_object(¤t)? {
|
||||
Object::Commit(_) => return Ok(current),
|
||||
Object::Tag(tag) => current = tag.object,
|
||||
other => {
|
||||
return Err(ForgeError::malformed(
|
||||
"object",
|
||||
format!("{current} is a {}, expected a commit", other.object_type()),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(ForgeError::InvalidRef(format!(
|
||||
"{oid} does not peel to a commit"
|
||||
)))
|
||||
}
|
||||
|
||||
// ── internal helpers ────────────────────────────────────────────────────────
|
||||
|
||||
type Entry = (String, ObjectId);
|
||||
|
||||
fn is_ancestor(repo: &Repository, ancestor: ObjectId, descendant: ObjectId) -> Result<bool> {
|
||||
fsck_is_ancestor(
|
||||
repo.odb(),
|
||||
ancestor,
|
||||
descendant,
|
||||
ConnectivityLimits::default(),
|
||||
)
|
||||
}
|
||||
|
||||
fn is_binary(data: &[u8]) -> bool {
|
||||
data.contains(&0)
|
||||
}
|
||||
|
||||
fn display(path: &[u8]) -> String {
|
||||
String::from_utf8_lossy(path).into_owned()
|
||||
}
|
||||
|
||||
fn stage_entry(path: &[u8], stage: u8, mode: &str, oid: ObjectId) -> StageEntry {
|
||||
StageEntry {
|
||||
path: path.to_vec(),
|
||||
stage,
|
||||
mode: mode.to_string(),
|
||||
oid,
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_message(message: Option<&str>, default: impl FnOnce() -> String) -> String {
|
||||
match message {
|
||||
Some(msg) if msg.ends_with('\n') => msg.to_string(),
|
||||
Some(msg) => format!("{msg}\n"),
|
||||
None => default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn default_merge_msg(repo: &Repository, target: &str) -> String {
|
||||
if repo.refs().resolve(&format!("refs/heads/{target}")).is_ok() {
|
||||
format!("Merge branch '{target}'\n")
|
||||
} else {
|
||||
format!("Merge commit '{target}'\n")
|
||||
}
|
||||
}
|
||||
|
||||
/// Flatten a tree to path → (mode, oid) leaf entries (bounded recursion).
|
||||
pub(crate) fn flatten_tree(repo: &Repository, tree: ObjectId) -> Result<BTreeMap<Vec<u8>, Entry>> {
|
||||
let mut out = BTreeMap::new();
|
||||
flatten_into(repo, tree, Vec::new(), 0, &mut out)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn flatten_into(
|
||||
repo: &Repository,
|
||||
tree_oid: ObjectId,
|
||||
prefix: Vec<u8>,
|
||||
depth: usize,
|
||||
out: &mut BTreeMap<Vec<u8>, Entry>,
|
||||
) -> Result<()> {
|
||||
if depth > MAX_MERGE_DEPTH {
|
||||
return Err(ForgeError::ResourceLimit(format!(
|
||||
"merge tree depth exceeds {MAX_MERGE_DEPTH}"
|
||||
)));
|
||||
}
|
||||
for entry in repo.tree(&tree_oid)?.entries {
|
||||
let mut path = prefix.clone();
|
||||
if !path.is_empty() {
|
||||
path.push(b'/');
|
||||
}
|
||||
path.extend_from_slice(&entry.name);
|
||||
if entry.kind() == "tree" {
|
||||
flatten_into(repo, entry.oid, path, depth + 1, out)?;
|
||||
} else {
|
||||
out.insert(path, (entry.mode.clone(), entry.oid));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reconstruct a canonical Git tree from flattened path → (mode, oid) entries.
|
||||
pub(crate) fn write_tree_from_entries(
|
||||
repo: &Repository,
|
||||
entries: &BTreeMap<Vec<u8>, Entry>,
|
||||
) -> Result<ObjectId> {
|
||||
let mut root = MergeTreeNode::default();
|
||||
for (path, (mode, oid)) in entries {
|
||||
root.insert(path, mode.clone(), *oid);
|
||||
}
|
||||
root.write(repo)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MergeTreeNode {
|
||||
files: BTreeMap<Vec<u8>, Entry>,
|
||||
dirs: BTreeMap<Vec<u8>, MergeTreeNode>,
|
||||
}
|
||||
|
||||
impl MergeTreeNode {
|
||||
fn insert(&mut self, path: &[u8], mode: String, oid: ObjectId) {
|
||||
let mut parts = path.split(|b| *b == b'/').peekable();
|
||||
let mut node = self;
|
||||
while let Some(part) = parts.next() {
|
||||
if parts.peek().is_none() {
|
||||
// File/dir collision: a directory already claims this name; the
|
||||
// directory wins (a single tree cannot hold both). Rare edge —
|
||||
// three-way merge marks such paths as conflicts anyway.
|
||||
if node.dirs.contains_key(part) {
|
||||
return;
|
||||
}
|
||||
node.files.insert(part.to_vec(), (mode, oid));
|
||||
return;
|
||||
}
|
||||
// A file previously claimed this name but a deeper path needs a
|
||||
// directory here; the directory wins.
|
||||
node.files.remove(part);
|
||||
node = node.dirs.entry(part.to_vec()).or_default();
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&self, repo: &Repository) -> Result<ObjectId> {
|
||||
let mut entries = Vec::with_capacity(self.files.len() + self.dirs.len());
|
||||
for (name, (mode, oid)) in &self.files {
|
||||
entries.push(TreeEntry {
|
||||
mode: mode.clone(),
|
||||
name: name.clone(),
|
||||
oid: *oid,
|
||||
});
|
||||
}
|
||||
for (name, child) in &self.dirs {
|
||||
entries.push(TreeEntry {
|
||||
mode: "40000".into(),
|
||||
name: name.clone(),
|
||||
oid: child.write(repo)?,
|
||||
});
|
||||
}
|
||||
let mut tree = Tree { entries };
|
||||
tree.canonicalize();
|
||||
repo.hash_object(ObjectType::Tree, &tree.serialize(), true)
|
||||
}
|
||||
}
|
||||
215
src/receive.rs
215
src/receive.rs
@ -3,8 +3,10 @@
|
||||
//! Network and pack negotiation are deliberately outside this module. Once an
|
||||
//! open-source pack decoder yields typed payloads, this is the safety boundary:
|
||||
//! isolate them, verify declared identities, fsck the complete overlay graph,
|
||||
//! enforce fast-forward policy, publish immutable objects, then move one ref by
|
||||
//! compare-and-swap. A failed transaction never moves the ref.
|
||||
//! enforce fast-forward policy, publish immutable objects, then move the ref(s).
|
||||
//! [`ReceiveTransaction::finish`] moves exactly one ref by compare-and-swap;
|
||||
//! [`ReceiveTransaction::finish_atomic`] applies a whole multi-ref push as one
|
||||
//! all-or-nothing transaction. A failed transaction never moves any ref.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::io::Cursor;
|
||||
@ -20,7 +22,7 @@ use crate::fsck::{check_connectivity, is_ancestor, ConnectivityLimits, ObjectRea
|
||||
use crate::object::{Object, ObjectType, MAX_OBJECT_SIZE};
|
||||
use crate::odb::Odb;
|
||||
use crate::oid::ObjectId;
|
||||
use crate::refs::validate_refname;
|
||||
use crate::refs::{validate_refname, RefChange, RefCommand};
|
||||
use crate::Repository;
|
||||
|
||||
static NEXT_QUARANTINE: AtomicU64 = AtomicU64::new(0);
|
||||
@ -53,9 +55,9 @@ pub struct ReceiveObject {
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
/// One ref update. This first safe receive slice deliberately owns exactly one
|
||||
/// ref per transaction; multi-ref atomic transactions remain a later wire-layer
|
||||
/// capability rather than pretending sequential renames are globally atomic.
|
||||
/// One ref update for the single-ref [`ReceiveTransaction::finish`] path.
|
||||
/// Multi-ref pushes use [`AtomicRefUpdate`] with
|
||||
/// [`ReceiveTransaction::finish_atomic`] instead.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RefUpdate {
|
||||
pub name: String,
|
||||
@ -73,6 +75,58 @@ pub struct ReceiveOutcome {
|
||||
pub published_objects: usize,
|
||||
}
|
||||
|
||||
/// One ref command in an atomic multi-ref receive. `new == None` is a deletion
|
||||
/// (and then `expected_old` must be the required current value); otherwise it is
|
||||
/// a create (`expected_old == None`) or an update (`expected_old == Some`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AtomicRefUpdate {
|
||||
pub name: String,
|
||||
pub expected_old: Option<ObjectId>,
|
||||
pub new: Option<ObjectId>,
|
||||
pub allow_non_fast_forward: bool,
|
||||
}
|
||||
|
||||
/// Per-ref result of an atomic receive. `error == None` means the ref was (or
|
||||
/// would have been) accepted; every ref shares the same accept/reject verdict.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AtomicRefResult {
|
||||
pub name: String,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Outcome of [`ReceiveTransaction::finish_atomic`]: the per-ref results plus
|
||||
/// whether the batch was actually committed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ReceiveAtomicOutcome {
|
||||
pub results: Vec<AtomicRefResult>,
|
||||
pub published_objects: usize,
|
||||
pub committed: bool,
|
||||
}
|
||||
|
||||
/// Pair each update name with its per-ref error into ordered results.
|
||||
fn build_results(updates: &[AtomicRefUpdate], errors: Vec<Option<String>>) -> Vec<AtomicRefResult> {
|
||||
updates
|
||||
.iter()
|
||||
.zip(errors)
|
||||
.map(|(update, error)| AtomicRefResult {
|
||||
name: update.name.clone(),
|
||||
error,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Stable, privacy-safe report-status reason for a rejected ref transaction.
|
||||
fn atomic_ref_public_reason(error: &ForgeError) -> &'static str {
|
||||
match error {
|
||||
ForgeError::NonFastForward { .. } => "non-fast-forward",
|
||||
ForgeError::RefConflict { .. } => "stale info",
|
||||
ForgeError::RefLocked(_) => "ref locked",
|
||||
ForgeError::ReceiveRejected(_) => "receive policy rejected",
|
||||
ForgeError::ResourceLimit(_) => "resource limit",
|
||||
_ => "server error",
|
||||
}
|
||||
}
|
||||
|
||||
/// Isolated decoded-object transaction tied to one target repository.
|
||||
pub struct ReceiveTransaction<'repo> {
|
||||
repository: &'repo Repository,
|
||||
@ -368,6 +422,155 @@ impl<'repo> ReceiveTransaction<'repo> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Validate and publish the complete staged graph, then apply **every**
|
||||
/// requested ref change as one atomic transaction (the multi-ref push).
|
||||
///
|
||||
/// The whole batch is accepted or rejected together, matching Git's
|
||||
/// `--atomic` receive: object publication and connectivity are checked once
|
||||
/// over the union of all new tips, then [`Refs::atomic_update`] commits or
|
||||
/// rejects the refs in a single locked transaction.
|
||||
///
|
||||
/// Return semantics separate two failure classes so the transport can build
|
||||
/// an accurate report-status:
|
||||
/// - `Err(..)` is a whole-graph problem (bad connectivity, disconnected
|
||||
/// objects, unreadable object) that the caller maps to the same reason on
|
||||
/// every ref, exactly as the single-ref [`finish`](Self::finish) does.
|
||||
/// - `Ok(outcome)` with `committed == false` is a per-ref rejection: the
|
||||
/// offending ref(s) carry a specific reason and the rest carry a generic
|
||||
/// "atomic transaction failed", and **no** ref moved.
|
||||
pub fn finish_atomic(self, updates: Vec<AtomicRefUpdate>) -> Result<ReceiveAtomicOutcome> {
|
||||
if let Some(reason) = &self.pack_import_failed {
|
||||
return Err(ForgeError::ReceiveRejected(format!(
|
||||
"an earlier pack import failed after staging began: {reason}"
|
||||
)));
|
||||
}
|
||||
if updates.is_empty() {
|
||||
return Err(ForgeError::ReceiveRejected(
|
||||
"atomic receive requires at least one ref command".into(),
|
||||
));
|
||||
}
|
||||
for update in &updates {
|
||||
validate_refname(&update.name)?;
|
||||
if update.new.is_none() && update.expected_old.is_none() {
|
||||
return Err(ForgeError::ReceiveRejected(format!(
|
||||
"deletion of {} must specify the expected current value",
|
||||
update.name
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
let reader = OverlayReader {
|
||||
quarantine: &self.quarantine_odb,
|
||||
target: self.repository.odb(),
|
||||
staged: &self.staged,
|
||||
};
|
||||
|
||||
// Connectivity is checked once over the union of every non-delete tip.
|
||||
// A push that stages objects unreachable from any surviving tip is a
|
||||
// whole-graph rejection, just like the single-ref path.
|
||||
let tips: Vec<ObjectId> = updates.iter().filter_map(|update| update.new).collect();
|
||||
if !tips.is_empty() {
|
||||
let report = check_connectivity(&reader, &tips, self.limits.connectivity)?;
|
||||
if !self.staged.iter().all(|oid| report.reachable.contains(oid)) {
|
||||
return Err(ForgeError::ReceiveRejected(
|
||||
"quarantine contains objects disconnected from every proposed ref tip".into(),
|
||||
));
|
||||
}
|
||||
} else if !self.staged.is_empty() {
|
||||
return Err(ForgeError::ReceiveRejected(
|
||||
"received objects but no ref update would make them reachable".into(),
|
||||
));
|
||||
}
|
||||
|
||||
// Per-ref semantic checks (branch tip must be a commit; fast-forward
|
||||
// unless the server allows a rewind). These are per-ref because one bad
|
||||
// ref must not blame the others for its specific reason.
|
||||
let mut errors: Vec<Option<String>> = vec![None; updates.len()];
|
||||
let mut any_error = false;
|
||||
for (index, update) in updates.iter().enumerate() {
|
||||
let Some(new) = update.new else { continue };
|
||||
if update.name.starts_with("refs/heads/") {
|
||||
match reader.read_object(&new)? {
|
||||
Object::Commit(_) => {}
|
||||
_ => {
|
||||
errors[index] = Some("branch tip is not a commit".into());
|
||||
any_error = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(old) = update.expected_old {
|
||||
if !update.allow_non_fast_forward
|
||||
&& !is_ancestor(&reader, old, new, self.limits.connectivity)?
|
||||
{
|
||||
errors[index] = Some("non-fast-forward".into());
|
||||
any_error = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if any_error {
|
||||
return Ok(ReceiveAtomicOutcome {
|
||||
results: build_results(&updates, errors),
|
||||
published_objects: 0,
|
||||
committed: false,
|
||||
});
|
||||
}
|
||||
|
||||
// Publish immutable objects first. If the ref transaction then loses a
|
||||
// race, only unreachable objects remain — never a moved ref.
|
||||
for oid in &self.staged {
|
||||
let (object_type, payload) = self.quarantine_odb.read_raw(oid)?;
|
||||
let published = self.repository.odb().write(object_type, &payload)?;
|
||||
if published != *oid {
|
||||
return Err(ForgeError::HashMismatch {
|
||||
looked_up: oid.to_hex(),
|
||||
computed: published.to_hex(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let commands: Vec<RefCommand> = updates
|
||||
.iter()
|
||||
.map(|update| RefCommand {
|
||||
name: update.name.clone(),
|
||||
change: match update.new {
|
||||
Some(new) => RefChange::Update {
|
||||
expected: update.expected_old,
|
||||
new,
|
||||
},
|
||||
None => RefChange::Delete {
|
||||
old: update
|
||||
.expected_old
|
||||
.expect("delete validated to carry an old value"),
|
||||
},
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
|
||||
match self.repository.refs().atomic_update(&commands) {
|
||||
Ok(()) => Ok(ReceiveAtomicOutcome {
|
||||
results: build_results(&updates, vec![None; updates.len()]),
|
||||
published_objects: self.staged.len(),
|
||||
committed: true,
|
||||
}),
|
||||
Err(error) => {
|
||||
let reason = atomic_ref_public_reason(&error.source);
|
||||
for (index, update) in updates.iter().enumerate() {
|
||||
errors[index] = Some(if update.name == error.name {
|
||||
reason.to_string()
|
||||
} else {
|
||||
"atomic transaction failed".to_string()
|
||||
});
|
||||
}
|
||||
Ok(ReceiveAtomicOutcome {
|
||||
results: build_results(&updates, errors),
|
||||
published_objects: 0,
|
||||
committed: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn staged_objects(&self) -> usize {
|
||||
self.staged.len()
|
||||
}
|
||||
|
||||
@ -7,20 +7,25 @@
|
||||
//! storage transactions are implemented.
|
||||
|
||||
use crate::error::{ForgeError, Result};
|
||||
use crate::receive::{ReceiveLimits, ReceiveOutcome, ReceiveTransaction, RefUpdate};
|
||||
use crate::receive::{
|
||||
AtomicRefUpdate, ReceiveAtomicOutcome, ReceiveLimits, ReceiveOutcome, ReceiveTransaction,
|
||||
};
|
||||
use crate::refs::{AtomicRefError, RefChange, RefCommand};
|
||||
use crate::wire::{
|
||||
encode_packet_line, encode_receive_status, parse_receive_pack_request, PacketLine,
|
||||
PacketLineLimits, ReceivePackCommand, ReceivePackRequest, ReceiveStatus,
|
||||
};
|
||||
use crate::Repository;
|
||||
|
||||
/// Capabilities implemented by the current one-ref SHA-1 receive server.
|
||||
/// Unsupported features (atomic multi-ref, push-options, sideband)
|
||||
/// are intentionally absent so stock Git will not negotiate them.
|
||||
/// Capabilities implemented by the SHA-1 receive server. Every push is applied
|
||||
/// as one all-or-nothing transaction, so `atomic` is advertised and honored for
|
||||
/// multi-ref pushes. Unsupported features (push-options, sideband) are
|
||||
/// intentionally absent so stock Git will not negotiate them.
|
||||
pub const RECEIVE_PACK_CAPABILITIES: &[&str] = &[
|
||||
"report-status",
|
||||
"report-status-v2",
|
||||
"delete-refs",
|
||||
"atomic",
|
||||
"ofs-delta",
|
||||
"object-format=sha1",
|
||||
"agent=rit/0.1",
|
||||
@ -116,65 +121,41 @@ pub fn execute_receive_pack(
|
||||
let report_status = request.capabilities.contains("report-status")
|
||||
|| request.capabilities.contains("report-status-v2");
|
||||
|
||||
if request.commands.len() != 1 {
|
||||
let rejection =
|
||||
ForgeError::ReceiveRejected("atomic multi-ref receive is not implemented".into());
|
||||
return rejected_refs(
|
||||
// Whether any command carries objects (create/update) and therefore expects
|
||||
// a packfile. A push made up solely of deletions carries no pack.
|
||||
let carries_objects = request
|
||||
.commands
|
||||
.iter()
|
||||
.any(|command| !matches!(command, ReceivePackCommand::Delete { .. }));
|
||||
|
||||
if carries_objects {
|
||||
execute_with_pack(
|
||||
repository,
|
||||
input,
|
||||
&request,
|
||||
report_status,
|
||||
None,
|
||||
"atomic multi-ref receive is not supported",
|
||||
rejection,
|
||||
);
|
||||
receive_limits,
|
||||
policy,
|
||||
)
|
||||
} else {
|
||||
execute_delete_only(repository, input, &request, report_status)
|
||||
}
|
||||
}
|
||||
|
||||
let update = match &request.commands[0] {
|
||||
ReceivePackCommand::Create { new, name } => RefUpdate {
|
||||
name: name.clone(),
|
||||
expected_old: None,
|
||||
new: *new,
|
||||
allow_non_fast_forward: policy.allow_non_fast_forward,
|
||||
},
|
||||
ReceivePackCommand::Update { old, new, name } => RefUpdate {
|
||||
name: name.clone(),
|
||||
expected_old: Some(*old),
|
||||
new: *new,
|
||||
allow_non_fast_forward: policy.allow_non_fast_forward,
|
||||
},
|
||||
ReceivePackCommand::Delete { old, name } => {
|
||||
if request.pack_offset != input.len() {
|
||||
return rejected_refs(
|
||||
&request,
|
||||
report_status,
|
||||
None,
|
||||
"unexpected pack for deletion",
|
||||
ForgeError::ReceiveRejected(
|
||||
"single-ref deletion request carried unexpected pack bytes".into(),
|
||||
),
|
||||
);
|
||||
}
|
||||
return match repository.refs().compare_and_delete(name, *old) {
|
||||
Ok(()) => Ok(ReceivePackExecution {
|
||||
response: status_response(&request, report_status, None, None)?,
|
||||
outcome: None,
|
||||
deleted: Some(DeletedRef {
|
||||
name: name.clone(),
|
||||
old: *old,
|
||||
}),
|
||||
rejection: None,
|
||||
}),
|
||||
Err(error) => {
|
||||
let public_reason = public_ref_rejection(&error);
|
||||
rejected_refs(&request, report_status, None, public_reason, error)
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/// Apply a push that stages a pack (any mix of create/update, optionally with
|
||||
/// deletions) as one atomic multi-ref transaction.
|
||||
fn execute_with_pack(
|
||||
repository: &Repository,
|
||||
input: &[u8],
|
||||
request: &ReceivePackRequest,
|
||||
report_status: bool,
|
||||
receive_limits: ReceiveLimits,
|
||||
policy: ReceivePackPolicy,
|
||||
) -> Result<ReceivePackExecution> {
|
||||
let mut transaction = ReceiveTransaction::begin(repository, receive_limits)?;
|
||||
if let Err(error) = transaction.stage_pack(&input[request.pack_offset..]) {
|
||||
return rejected_refs(
|
||||
&request,
|
||||
request,
|
||||
report_status,
|
||||
Some("pack rejected"),
|
||||
"unpacker error",
|
||||
@ -182,20 +163,223 @@ pub fn execute_receive_pack(
|
||||
);
|
||||
}
|
||||
|
||||
match transaction.finish(update) {
|
||||
Ok(outcome) => Ok(ReceivePackExecution {
|
||||
response: status_response(&request, report_status, None, None)?,
|
||||
outcome: Some(outcome),
|
||||
deleted: None,
|
||||
rejection: None,
|
||||
}),
|
||||
let updates: Vec<AtomicRefUpdate> = request
|
||||
.commands
|
||||
.iter()
|
||||
.map(|command| atomic_update_from_command(command, policy))
|
||||
.collect();
|
||||
|
||||
match transaction.finish_atomic(updates) {
|
||||
Ok(outcome) => Ok(execution_from_atomic(request, report_status, outcome)?),
|
||||
Err(error) => {
|
||||
// A whole-graph failure (bad connectivity, disconnected objects):
|
||||
// report the same stable reason on every ref, as the single-ref
|
||||
// path did, and never move a ref.
|
||||
let public_reason = public_ref_rejection(&error);
|
||||
rejected_refs(&request, report_status, None, public_reason, error)
|
||||
rejected_refs(request, report_status, None, public_reason, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply a deletion-only push (no pack) as one atomic ref transaction.
|
||||
fn execute_delete_only(
|
||||
repository: &Repository,
|
||||
input: &[u8],
|
||||
request: &ReceivePackRequest,
|
||||
report_status: bool,
|
||||
) -> Result<ReceivePackExecution> {
|
||||
if request.pack_offset != input.len() {
|
||||
return rejected_refs(
|
||||
request,
|
||||
report_status,
|
||||
None,
|
||||
"unexpected pack for deletion",
|
||||
ForgeError::ReceiveRejected(
|
||||
"deletion-only request carried unexpected pack bytes".into(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
let commands: Vec<RefCommand> = request
|
||||
.commands
|
||||
.iter()
|
||||
.map(|command| match command {
|
||||
ReceivePackCommand::Delete { old, name } => RefCommand {
|
||||
name: name.clone(),
|
||||
change: RefChange::Delete { old: *old },
|
||||
},
|
||||
// `carries_objects` guaranteed every command here is a deletion.
|
||||
other => unreachable!("non-delete command in deletion-only push: {other:?}"),
|
||||
})
|
||||
.collect();
|
||||
|
||||
match repository.refs().atomic_update(&commands) {
|
||||
Ok(()) => {
|
||||
let statuses = request
|
||||
.commands
|
||||
.iter()
|
||||
.map(|command| ReceiveStatus {
|
||||
ref_name: command.name().to_string(),
|
||||
error: None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Ok(ReceivePackExecution {
|
||||
response: encode_status_body(report_status, None, &statuses)?,
|
||||
outcome: None,
|
||||
deleted: single_deleted_ref(&commands),
|
||||
rejection: None,
|
||||
})
|
||||
}
|
||||
Err(error) => atomic_failure_execution(request, report_status, error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Translate one wire command into an [`AtomicRefUpdate`], applying the server's
|
||||
/// non-fast-forward policy (never inferred from the client).
|
||||
fn atomic_update_from_command(
|
||||
command: &ReceivePackCommand,
|
||||
policy: ReceivePackPolicy,
|
||||
) -> AtomicRefUpdate {
|
||||
match command {
|
||||
ReceivePackCommand::Create { new, name } => AtomicRefUpdate {
|
||||
name: name.clone(),
|
||||
expected_old: None,
|
||||
new: Some(*new),
|
||||
allow_non_fast_forward: policy.allow_non_fast_forward,
|
||||
},
|
||||
ReceivePackCommand::Update { old, new, name } => AtomicRefUpdate {
|
||||
name: name.clone(),
|
||||
expected_old: Some(*old),
|
||||
new: Some(*new),
|
||||
allow_non_fast_forward: policy.allow_non_fast_forward,
|
||||
},
|
||||
ReceivePackCommand::Delete { old, name } => AtomicRefUpdate {
|
||||
name: name.clone(),
|
||||
expected_old: Some(*old),
|
||||
new: None,
|
||||
allow_non_fast_forward: policy.allow_non_fast_forward,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the transport execution from a finished atomic outcome, encoding the
|
||||
/// per-ref report-status and surfacing a typed rejection when nothing committed.
|
||||
fn execution_from_atomic(
|
||||
request: &ReceivePackRequest,
|
||||
report_status: bool,
|
||||
outcome: ReceiveAtomicOutcome,
|
||||
) -> Result<ReceivePackExecution> {
|
||||
let statuses = outcome
|
||||
.results
|
||||
.iter()
|
||||
.map(|result| ReceiveStatus {
|
||||
ref_name: result.name.clone(),
|
||||
error: result.error.clone(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let response = encode_status_body(report_status, None, &statuses)?;
|
||||
|
||||
if outcome.committed {
|
||||
Ok(ReceivePackExecution {
|
||||
response,
|
||||
outcome: single_receive_outcome(request, &outcome),
|
||||
deleted: None,
|
||||
rejection: None,
|
||||
})
|
||||
} else {
|
||||
let reason = outcome
|
||||
.results
|
||||
.iter()
|
||||
.find_map(|result| result.error.clone())
|
||||
.unwrap_or_else(|| "receive rejected".into());
|
||||
Ok(ReceivePackExecution {
|
||||
response,
|
||||
outcome: None,
|
||||
deleted: None,
|
||||
rejection: Some(ForgeError::ReceiveRejected(reason)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Preserve the single-ref `outcome` summary for the common one-ref update push.
|
||||
fn single_receive_outcome(
|
||||
request: &ReceivePackRequest,
|
||||
outcome: &ReceiveAtomicOutcome,
|
||||
) -> Option<ReceiveOutcome> {
|
||||
let [command] = request.commands.as_slice() else {
|
||||
return None;
|
||||
};
|
||||
match command {
|
||||
ReceivePackCommand::Create { new, name } => Some(ReceiveOutcome {
|
||||
ref_name: name.clone(),
|
||||
old: None,
|
||||
new: *new,
|
||||
published_objects: outcome.published_objects,
|
||||
}),
|
||||
ReceivePackCommand::Update { old, new, name } => Some(ReceiveOutcome {
|
||||
ref_name: name.clone(),
|
||||
old: Some(*old),
|
||||
new: *new,
|
||||
published_objects: outcome.published_objects,
|
||||
}),
|
||||
ReceivePackCommand::Delete { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Preserve the single-ref `deleted` summary for the common one-ref delete push.
|
||||
fn single_deleted_ref(commands: &[RefCommand]) -> Option<DeletedRef> {
|
||||
let [command] = commands else {
|
||||
return None;
|
||||
};
|
||||
match &command.change {
|
||||
RefChange::Delete { old } => Some(DeletedRef {
|
||||
name: command.name.clone(),
|
||||
old: *old,
|
||||
}),
|
||||
RefChange::Update { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a rejected deletion-only atomic transaction into per-ref `ng` statuses.
|
||||
fn atomic_failure_execution(
|
||||
request: &ReceivePackRequest,
|
||||
report_status: bool,
|
||||
error: AtomicRefError,
|
||||
) -> Result<ReceivePackExecution> {
|
||||
let reason = public_ref_rejection(&error.source);
|
||||
let statuses = request
|
||||
.commands
|
||||
.iter()
|
||||
.map(|command| ReceiveStatus {
|
||||
ref_name: command.name().to_string(),
|
||||
error: Some(if command.name() == error.name {
|
||||
reason.to_string()
|
||||
} else {
|
||||
"atomic transaction failed".to_string()
|
||||
}),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Ok(ReceivePackExecution {
|
||||
response: encode_status_body(report_status, None, &statuses)?,
|
||||
outcome: None,
|
||||
deleted: None,
|
||||
rejection: Some(error.source),
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode a report-status body, or an empty body when the client did not
|
||||
/// negotiate report-status/report-status-v2.
|
||||
fn encode_status_body(
|
||||
report_status: bool,
|
||||
unpack_error: Option<&str>,
|
||||
statuses: &[ReceiveStatus],
|
||||
) -> Result<Vec<u8>> {
|
||||
if !report_status {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
encode_receive_status(unpack_error, statuses)
|
||||
}
|
||||
|
||||
fn rejected_refs(
|
||||
request: &ReceivePackRequest,
|
||||
report_status: bool,
|
||||
@ -256,7 +440,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_multi_ref_before_unpacking_and_reports_every_ref() {
|
||||
fn multi_ref_push_with_invalid_pack_rejects_every_ref_atomically() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("objects")).unwrap();
|
||||
let repo = Repository::open_git_dir(dir.path()).unwrap();
|
||||
@ -285,11 +469,10 @@ mod tests {
|
||||
ReceivePackPolicy::default(),
|
||||
)
|
||||
.unwrap();
|
||||
// Multi-ref is now processed atomically, but an undecodable pack rejects
|
||||
// the whole batch: no ref moves and every ref reports `ng`.
|
||||
assert!(execution.outcome.is_none());
|
||||
assert!(matches!(
|
||||
execution.rejection,
|
||||
Some(ForgeError::ReceiveRejected(_))
|
||||
));
|
||||
assert!(matches!(execution.rejection, Some(ForgeError::Pack(_))));
|
||||
let status = decode_packet_lines(&execution.response, PacketLineLimits::default()).unwrap();
|
||||
assert_eq!(status.len(), 4);
|
||||
assert!(
|
||||
@ -333,7 +516,8 @@ mod tests {
|
||||
assert!(
|
||||
matches!(&packets[0], PacketLine::Data(line) if line.starts_with(b"0000000000000000000000000000000000000000 capabilities^{}\0"))
|
||||
);
|
||||
assert!(!empty
|
||||
// Atomic multi-ref receive is now advertised and honored.
|
||||
assert!(empty
|
||||
.windows(b"atomic".len())
|
||||
.any(|window| window == b"atomic"));
|
||||
assert!(empty
|
||||
|
||||
@ -191,7 +191,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn name_with_spaces_parses() {
|
||||
let line = "0000000000000000000000000000000000000000 1111111111111111111111111111111111111111 \
|
||||
let line =
|
||||
"0000000000000000000000000000000000000000 1111111111111111111111111111111111111111 \
|
||||
Joe Q Public <joe@example.com> 1700000001 +0100\tbranch: Created from HEAD";
|
||||
let e = ReflogEntry::parse(line).unwrap();
|
||||
assert_eq!(e.name, "Joe Q Public");
|
||||
@ -238,8 +239,14 @@ mod tests {
|
||||
// Read unbounded — should return newest first.
|
||||
let entries = read_reflog(git_dir, "refs/heads/main", 100).unwrap();
|
||||
assert_eq!(entries.len(), 2);
|
||||
assert_eq!(entries[0].new_oid, "2222222222222222222222222222222222222222");
|
||||
assert_eq!(entries[1].new_oid, "1111111111111111111111111111111111111111");
|
||||
assert_eq!(
|
||||
entries[0].new_oid,
|
||||
"2222222222222222222222222222222222222222"
|
||||
);
|
||||
assert_eq!(
|
||||
entries[1].new_oid,
|
||||
"1111111111111111111111111111111111111111"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
201
src/refs.rs
201
src/refs.rs
@ -238,6 +238,137 @@ impl Refs {
|
||||
result
|
||||
}
|
||||
|
||||
/// Apply several ref changes as one all-or-nothing transaction.
|
||||
///
|
||||
/// Phase 1 locks every ref with the same `.lock` protocol as
|
||||
/// [`compare_and_swap`](Self::compare_and_swap) and verifies each current
|
||||
/// value against its command's expectation. If any lock cannot be taken or
|
||||
/// any expectation is stale, nothing is modified and the offending ref is
|
||||
/// named in the returned [`AtomicRefError`] so the caller can report a
|
||||
/// precise per-ref status. Locks are non-blocking (`create_new`), so two
|
||||
/// conflicting transactions never deadlock — the loser observes an existing
|
||||
/// `.lock` and aborts.
|
||||
///
|
||||
/// Phase 2 publishes each change (write+rename for updates, unlink for
|
||||
/// deletes). Because every expectation was already verified under lock, this
|
||||
/// phase only fails on an unexpected filesystem error; the decision to accept
|
||||
/// or reject the batch is fully atomic even though the physical commit, like
|
||||
/// Git's own loose-ref backend, is not perfectly crash-atomic across files.
|
||||
pub fn atomic_update(
|
||||
&self,
|
||||
commands: &[RefCommand],
|
||||
) -> std::result::Result<(), AtomicRefError> {
|
||||
let fail = |name: &str, source: ForgeError| AtomicRefError {
|
||||
name: name.to_string(),
|
||||
source,
|
||||
};
|
||||
|
||||
let mut held: Vec<HeldRefLock> = Vec::new();
|
||||
for (index, command) in commands.iter().enumerate() {
|
||||
match self.lock_and_verify(index, command) {
|
||||
Ok(lock) => held.push(lock),
|
||||
Err(source) => {
|
||||
rollback_ref_locks(&held);
|
||||
return Err(fail(&command.name, source));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for position in 0..held.len() {
|
||||
let command = &commands[held[position].index];
|
||||
if let Err(source) = commit_ref_change(&mut held[position], &command.change) {
|
||||
// The physical commit failed mid-batch. Clean every remaining
|
||||
// lock so a retry is possible; earlier renames cannot be undone.
|
||||
rollback_ref_locks(&held);
|
||||
return Err(fail(&command.name, source));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Lock one ref and verify its current value matches `command`'s expectation.
|
||||
/// On success the returned guard owns the `.lock` file for the commit phase.
|
||||
fn lock_and_verify(&self, index: usize, command: &RefCommand) -> Result<HeldRefLock> {
|
||||
validate_refname(&command.name)?;
|
||||
let path = self.git_dir.join(&command.name);
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| ForgeError::UnsafePath(command.name.clone()))?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
reject_symlink_components(&self.git_dir, parent)?;
|
||||
if std::fs::symlink_metadata(&path)
|
||||
.map(|metadata| metadata.file_type().is_symlink())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err(ForgeError::UnsafePath(path.display().to_string()));
|
||||
}
|
||||
|
||||
let lock_path = PathBuf::from(format!("{}.lock", path.display()));
|
||||
let lock = match OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&lock_path)
|
||||
{
|
||||
Ok(file) => file,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
|
||||
return Err(ForgeError::RefLocked(command.name.clone()))
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
|
||||
let verify = (|| {
|
||||
let actual = match self.resolve(&command.name) {
|
||||
Ok(oid) => Some(oid),
|
||||
Err(ForgeError::InvalidRef(_)) => None,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
match &command.change {
|
||||
RefChange::Update { expected, .. } => {
|
||||
if actual != *expected {
|
||||
return Err(ForgeError::RefConflict {
|
||||
name: command.name.clone(),
|
||||
expected: expected
|
||||
.map(|oid| oid.to_hex())
|
||||
.unwrap_or_else(|| "<missing>".into()),
|
||||
actual: actual
|
||||
.map(|oid| oid.to_hex())
|
||||
.unwrap_or_else(|| "<missing>".into()),
|
||||
});
|
||||
}
|
||||
}
|
||||
RefChange::Delete { old } => {
|
||||
if actual != Some(*old) {
|
||||
return Err(ForgeError::RefConflict {
|
||||
name: command.name.clone(),
|
||||
expected: old.to_hex(),
|
||||
actual: actual
|
||||
.map(|oid| oid.to_hex())
|
||||
.unwrap_or_else(|| "<missing>".into()),
|
||||
});
|
||||
}
|
||||
if self.read_packed_refs()?.contains_key(&command.name) {
|
||||
return Err(ForgeError::ReceiveRejected(format!(
|
||||
"cannot safely delete packed ref {} with the loose-ref transaction",
|
||||
command.name
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
|
||||
if let Err(error) = verify {
|
||||
let _ = std::fs::remove_file(&lock_path);
|
||||
return Err(error);
|
||||
}
|
||||
Ok(HeldRefLock {
|
||||
index,
|
||||
path,
|
||||
lock_path,
|
||||
lock,
|
||||
})
|
||||
}
|
||||
|
||||
/// Append one reflog entry to `.git/logs/<refname>` and, when this ref is
|
||||
/// HEAD's current symbolic target, also to `.git/logs/HEAD`.
|
||||
///
|
||||
@ -323,6 +454,76 @@ impl Refs {
|
||||
}
|
||||
}
|
||||
|
||||
/// One ref change requested inside an atomic multi-ref transaction.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum RefChange {
|
||||
/// Set the ref to `new`, requiring its current value to equal `expected`
|
||||
/// (`None` means the ref must not currently exist — a creation).
|
||||
Update {
|
||||
expected: Option<ObjectId>,
|
||||
new: ObjectId,
|
||||
},
|
||||
/// Delete the ref, requiring its current value to equal `old`.
|
||||
Delete { old: ObjectId },
|
||||
}
|
||||
|
||||
/// A named [`RefChange`] for [`Refs::atomic_update`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RefCommand {
|
||||
pub name: String,
|
||||
pub change: RefChange,
|
||||
}
|
||||
|
||||
/// Failure from [`Refs::atomic_update`], naming the offending ref so a caller can
|
||||
/// report a precise per-ref status while failing every other ref generically.
|
||||
#[derive(Debug)]
|
||||
pub struct AtomicRefError {
|
||||
pub name: String,
|
||||
pub source: ForgeError,
|
||||
}
|
||||
|
||||
/// A ref lock held between the verify and commit phases of an atomic update.
|
||||
struct HeldRefLock {
|
||||
/// Position of the originating command, so the commit phase can recover it.
|
||||
index: usize,
|
||||
path: PathBuf,
|
||||
lock_path: PathBuf,
|
||||
lock: std::fs::File,
|
||||
}
|
||||
|
||||
/// Best-effort release of every acquired `.lock` file (used to abort a batch).
|
||||
fn rollback_ref_locks(held: &[HeldRefLock]) {
|
||||
for lock in held {
|
||||
let _ = std::fs::remove_file(&lock.lock_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Publish one verified change: write+rename for an update, unlink for a delete.
|
||||
fn commit_ref_change(held: &mut HeldRefLock, change: &RefChange) -> Result<()> {
|
||||
match change {
|
||||
RefChange::Update { new, .. } => {
|
||||
writeln!(held.lock, "{new}")?;
|
||||
held.lock.sync_all()?;
|
||||
std::fs::rename(&held.lock_path, &held.path)?;
|
||||
if let Some(parent) = held.path.parent() {
|
||||
std::fs::File::open(parent)?.sync_all()?;
|
||||
}
|
||||
}
|
||||
RefChange::Delete { .. } => {
|
||||
match std::fs::remove_file(&held.path) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
if let Some(parent) = held.path.parent() {
|
||||
std::fs::File::open(parent)?.sync_all()?;
|
||||
}
|
||||
std::fs::remove_file(&held.lock_path)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Interpret raw ref file / HEAD content.
|
||||
fn parse_ref_content(content: &str) -> Result<RefTarget> {
|
||||
if let Some(target) = content.strip_prefix("ref:") {
|
||||
|
||||
25
src/repo.rs
25
src/repo.rs
@ -79,7 +79,10 @@ impl Repository {
|
||||
|
||||
// HEAD points at the (not-yet-existing) default branch. Preserve an
|
||||
// existing HEAD so reinitialization does not move the current branch.
|
||||
write_if_absent(&git_dir.join("HEAD"), format!("ref: {head_ref}\n").as_bytes())?;
|
||||
write_if_absent(
|
||||
&git_dir.join("HEAD"),
|
||||
format!("ref: {head_ref}\n").as_bytes(),
|
||||
)?;
|
||||
|
||||
// Minimal but real config. `bare` reflects the requested mode so that
|
||||
// downstream tools (and `worktree_root`) behave correctly.
|
||||
@ -810,15 +813,10 @@ impl Repository {
|
||||
let mut branches: Vec<(String, ObjectId, bool)> = all
|
||||
.into_iter()
|
||||
.filter_map(|(refname, oid)| {
|
||||
refname
|
||||
.strip_prefix("refs/heads/")
|
||||
.map(|short| {
|
||||
let is_current = current
|
||||
.as_deref()
|
||||
.map(|c| c == refname)
|
||||
.unwrap_or(false);
|
||||
(short.to_string(), oid, is_current)
|
||||
})
|
||||
refname.strip_prefix("refs/heads/").map(|short| {
|
||||
let is_current = current.as_deref().map(|c| c == refname).unwrap_or(false);
|
||||
(short.to_string(), oid, is_current)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
branches.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
@ -1004,9 +1002,10 @@ impl Repository {
|
||||
pub fn tag_delete(&self, name: &str) -> Result<()> {
|
||||
let refname = format!("refs/tags/{name}");
|
||||
validate_refname(&refname)?;
|
||||
let tip = self.refs.resolve(&refname).map_err(|_| {
|
||||
ForgeError::InvalidRef(format!("tag {name} not found"))
|
||||
})?;
|
||||
let tip = self
|
||||
.refs
|
||||
.resolve(&refname)
|
||||
.map_err(|_| ForgeError::InvalidRef(format!("tag {name} not found")))?;
|
||||
self.refs.compare_and_delete(&refname, tip)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
447
src/sequencer.rs
Normal file
447
src/sequencer.rs
Normal file
@ -0,0 +1,447 @@
|
||||
//! The on-disk sequencer: rebase and cherry-pick as a resumable state machine.
|
||||
//!
|
||||
//! Git records multi-commit history edits under `.git/sequencer/` (a `todo`
|
||||
//! list and a `done` log) plus the single-pick anchors `CHERRY_PICK_HEAD` /
|
||||
//! `REBASE_HEAD`. This module reproduces that model on top of the from-scratch
|
||||
//! three-way merge in [`crate::merge_cmd`]:
|
||||
//!
|
||||
//! - **cherry-pick** replays each named commit onto HEAD (base = the commit's
|
||||
//! first parent, ours = HEAD, theirs = the commit);
|
||||
//! - **rebase** resets the branch to `onto` and replays `upstream..HEAD` on top;
|
||||
//! - a conflict stops the sequence, leaving conflict markers + an unmerged index
|
||||
//! + `CHERRY_PICK_HEAD`, so the user can resolve and `--continue`, drop the
|
||||
//! commit with `--skip`, or unwind with `--abort`.
|
||||
//!
|
||||
//! State layout (all under the repository's git dir):
|
||||
//!
|
||||
//! ```text
|
||||
//! sequencer/head original HEAD oid (the abort target)
|
||||
//! sequencer/onto rebase target oid (rebase only)
|
||||
//! sequencer/todo remaining "pick <oid>" lines, oldest first
|
||||
//! sequencer/done applied "pick <oid>" lines
|
||||
//! CHERRY_PICK_HEAD the commit currently being applied (present on conflict)
|
||||
//! MERGE_MSG that commit's message (for --continue)
|
||||
//! ```
|
||||
//!
|
||||
//! The CLI wiring lives in `main.rs`; the integrator calls [`cmd_cherry_pick`],
|
||||
//! [`cmd_rebase`], [`cmd_sequencer_continue`], [`cmd_sequencer_abort`], and
|
||||
//! [`cmd_sequencer_skip`].
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{ForgeError, Result};
|
||||
use crate::merge_cmd::{
|
||||
build_worktree_merge, force_reset, head_branch, install_unmerged, read_gitdir_oid,
|
||||
read_gitdir_string, remove_gitdir_file, write_gitdir_file, WorktreeMerge,
|
||||
};
|
||||
use crate::object::Object;
|
||||
use crate::oid::ObjectId;
|
||||
use crate::repo::Repository;
|
||||
use crate::signature::Signature;
|
||||
|
||||
const TODO: &str = "sequencer/todo";
|
||||
const DONE: &str = "sequencer/done";
|
||||
const HEAD_FILE: &str = "sequencer/head";
|
||||
const ONTO: &str = "sequencer/onto";
|
||||
const CHERRY_PICK_HEAD: &str = "CHERRY_PICK_HEAD";
|
||||
const REBASE_HEAD: &str = "REBASE_HEAD";
|
||||
const MERGE_MSG: &str = "MERGE_MSG";
|
||||
|
||||
/// Bound on the ancestry walk used to compute the rebase commit list.
|
||||
const MAX_REBASE_WALK: usize = 500_000;
|
||||
|
||||
/// Whether a sequence ran to completion or stopped on a conflict.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum SequencerStatus {
|
||||
/// Every step applied; no state remains.
|
||||
Completed,
|
||||
/// Stopped on a conflict on these paths; state is persisted for `--continue`.
|
||||
Stopped { conflicts: Vec<String> },
|
||||
}
|
||||
|
||||
// ── cherry-pick ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// `git cherry-pick <commit>...`: replay each commit onto the current branch.
|
||||
pub fn cmd_cherry_pick(
|
||||
repo: &Repository,
|
||||
revs: &[&str],
|
||||
sig: &Signature,
|
||||
) -> Result<SequencerStatus> {
|
||||
if revs.is_empty() {
|
||||
return Err(ForgeError::InvalidRef(
|
||||
"cherry-pick requires at least one commit".into(),
|
||||
));
|
||||
}
|
||||
let orig = repo.head().map_err(|_| {
|
||||
ForgeError::InvalidRef("cannot cherry-pick onto an empty repository".into())
|
||||
})?;
|
||||
head_branch(repo)?; // fail fast on detached HEAD
|
||||
|
||||
let mut oids = Vec::with_capacity(revs.len());
|
||||
for rev in revs {
|
||||
oids.push(peel_commit(repo, repo.resolve(rev)?)?);
|
||||
}
|
||||
|
||||
let git_dir = repo.git_dir();
|
||||
write_gitdir_file(git_dir, HEAD_FILE, format!("{orig}\n").as_bytes())?;
|
||||
remove_gitdir_file(git_dir, ONTO);
|
||||
write_todo(repo, &oids)?;
|
||||
write_gitdir_file(git_dir, DONE, b"")?;
|
||||
|
||||
run_todo(repo, sig)
|
||||
}
|
||||
|
||||
// ── rebase ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// `git rebase [--onto <onto>] <upstream>`: reset the current branch to `onto`
|
||||
/// (default `upstream`) and replay `upstream..HEAD` on top.
|
||||
pub fn cmd_rebase(
|
||||
repo: &Repository,
|
||||
upstream: &str,
|
||||
onto: Option<&str>,
|
||||
sig: &Signature,
|
||||
) -> Result<SequencerStatus> {
|
||||
let head_ref = head_branch(repo)?;
|
||||
let head_oid = repo
|
||||
.head()
|
||||
.map_err(|_| ForgeError::InvalidRef("cannot rebase an empty repository".into()))?;
|
||||
let upstream_oid = peel_commit(repo, repo.resolve(upstream)?)?;
|
||||
let onto_oid = match onto {
|
||||
Some(spec) => peel_commit(repo, repo.resolve(spec)?)?,
|
||||
None => upstream_oid,
|
||||
};
|
||||
|
||||
let commits = commits_to_replay(repo, upstream_oid, head_oid)?;
|
||||
|
||||
let git_dir = repo.git_dir();
|
||||
write_gitdir_file(git_dir, HEAD_FILE, format!("{head_oid}\n").as_bytes())?;
|
||||
write_gitdir_file(git_dir, ONTO, format!("{onto_oid}\n").as_bytes())?;
|
||||
write_todo(repo, &commits)?;
|
||||
write_gitdir_file(git_dir, DONE, b"")?;
|
||||
|
||||
// Detach the worktree/branch onto the new base before replaying.
|
||||
if onto_oid != head_oid {
|
||||
repo.checkout_tree(repo.peel_to_commit(onto_oid)?.tree)?;
|
||||
repo.refs()
|
||||
.compare_and_swap(&head_ref, Some(head_oid), onto_oid)?;
|
||||
let _ = repo.refs().append_reflog(
|
||||
&head_ref,
|
||||
Some(head_oid),
|
||||
onto_oid,
|
||||
&sig.name,
|
||||
&sig.email,
|
||||
sig.time,
|
||||
&sig.tz,
|
||||
"rebase: checkout onto",
|
||||
);
|
||||
}
|
||||
|
||||
run_todo(repo, sig)
|
||||
}
|
||||
|
||||
// ── continue / abort / skip ─────────────────────────────────────────────────
|
||||
|
||||
/// `--continue`: finalize the in-progress pick (from the now-resolved index),
|
||||
/// then resume the remaining todo. Also handles finishing a conflicted merge.
|
||||
pub fn cmd_sequencer_continue(repo: &Repository, sig: &Signature) -> Result<SequencerStatus> {
|
||||
let git_dir = repo.git_dir();
|
||||
|
||||
if read_gitdir_oid(git_dir, CHERRY_PICK_HEAD).is_some() {
|
||||
finalize_pick(repo, sig)?;
|
||||
} else if read_gitdir_oid(git_dir, "MERGE_HEAD").is_some() {
|
||||
// A plain `merge` conflict was resolved; complete it.
|
||||
crate::merge_cmd::continue_merge(repo, sig, None)?;
|
||||
return Ok(SequencerStatus::Completed);
|
||||
}
|
||||
|
||||
if git_dir.join(TODO).exists() {
|
||||
run_todo(repo, sig)
|
||||
} else {
|
||||
finish(repo);
|
||||
Ok(SequencerStatus::Completed)
|
||||
}
|
||||
}
|
||||
|
||||
/// `--abort`: unwind to the original HEAD recorded at the start of the sequence.
|
||||
pub fn cmd_sequencer_abort(repo: &Repository) -> Result<()> {
|
||||
let git_dir = repo.git_dir();
|
||||
let orig = read_gitdir_oid(git_dir, HEAD_FILE)
|
||||
.or_else(|| read_gitdir_oid(git_dir, "ORIG_HEAD"))
|
||||
.ok_or_else(|| ForgeError::InvalidRef("no sequencer state to abort".into()))?;
|
||||
let head_ref = head_branch(repo)?;
|
||||
let current = repo.head()?;
|
||||
if current != orig {
|
||||
repo.refs()
|
||||
.compare_and_swap(&head_ref, Some(current), orig)?;
|
||||
}
|
||||
force_reset(repo, repo.peel_to_commit(orig)?.tree)?;
|
||||
finish(repo);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `--skip`: drop the conflicted commit and resume the remaining todo.
|
||||
pub fn cmd_sequencer_skip(repo: &Repository, sig: &Signature) -> Result<SequencerStatus> {
|
||||
let git_dir = repo.git_dir();
|
||||
// Discard the half-applied worktree/index back to the current HEAD.
|
||||
let head_tree = repo.peel_to_commit(repo.head()?)?.tree;
|
||||
force_reset(repo, head_tree)?;
|
||||
remove_gitdir_file(git_dir, CHERRY_PICK_HEAD);
|
||||
remove_gitdir_file(git_dir, REBASE_HEAD);
|
||||
remove_gitdir_file(git_dir, MERGE_MSG);
|
||||
|
||||
if git_dir.join(TODO).exists() {
|
||||
run_todo(repo, sig)
|
||||
} else {
|
||||
finish(repo);
|
||||
Ok(SequencerStatus::Completed)
|
||||
}
|
||||
}
|
||||
|
||||
// ── core loop ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// Pop and apply todo entries until the list drains or a pick conflicts.
|
||||
fn run_todo(repo: &Repository, sig: &Signature) -> Result<SequencerStatus> {
|
||||
loop {
|
||||
let todo = read_todo(repo)?;
|
||||
let Some((&next, rest)) = todo.split_first() else {
|
||||
finish(repo);
|
||||
return Ok(SequencerStatus::Completed);
|
||||
};
|
||||
// Persist the remaining list *before* attempting, so a conflict leaves a
|
||||
// correct resume point (the current pick lives in CHERRY_PICK_HEAD).
|
||||
write_todo(repo, rest)?;
|
||||
|
||||
let head = repo.head()?;
|
||||
match pick_onto(repo, head, next, sig)? {
|
||||
PickOutcome::Applied | PickOutcome::Empty => {
|
||||
append_done(repo, next)?;
|
||||
}
|
||||
PickOutcome::Conflicted(conflicts) => {
|
||||
write_gitdir_file(repo.git_dir(), REBASE_HEAD, format!("{next}\n").as_bytes())?;
|
||||
return Ok(SequencerStatus::Stopped { conflicts });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum PickOutcome {
|
||||
Applied,
|
||||
/// The pick produced no change (already applied) — silently skipped.
|
||||
Empty,
|
||||
Conflicted(Vec<String>),
|
||||
}
|
||||
|
||||
/// Apply one commit on top of `head` using three-way merge semantics.
|
||||
///
|
||||
/// On a clean apply, a new commit is written (author preserved from the picked
|
||||
/// commit, committer = `sig`) and the branch advances. On a conflict, the
|
||||
/// worktree/index are left conflicted and `CHERRY_PICK_HEAD` is recorded.
|
||||
fn pick_onto(
|
||||
repo: &Repository,
|
||||
head: ObjectId,
|
||||
commit_oid: ObjectId,
|
||||
sig: &Signature,
|
||||
) -> Result<PickOutcome> {
|
||||
let commit = repo.commit(&commit_oid)?;
|
||||
let base_tree = match commit.parents.first() {
|
||||
Some(parent) => Some(repo.peel_to_commit(*parent)?.tree),
|
||||
None => None,
|
||||
};
|
||||
let ours_tree = repo.peel_to_commit(head)?.tree;
|
||||
let theirs_tree = commit.tree;
|
||||
let head_ref = head_branch(repo)?;
|
||||
|
||||
match build_worktree_merge(repo, base_tree, ours_tree, theirs_tree)? {
|
||||
WorktreeMerge::Clean(tree) => {
|
||||
if tree == ours_tree {
|
||||
return Ok(PickOutcome::Empty);
|
||||
}
|
||||
repo.checkout_tree(tree)?;
|
||||
let message = if commit.message.is_empty() {
|
||||
b"cherry-pick\n".to_vec()
|
||||
} else {
|
||||
commit.message.clone()
|
||||
};
|
||||
// The commit is written and the branch ref advanced as a side effect;
|
||||
// the sequencer resumes from the ref, so the new oid isn't needed here.
|
||||
repo.commit_tree(
|
||||
tree,
|
||||
vec![head],
|
||||
commit.author.clone(),
|
||||
sig.clone(),
|
||||
&message,
|
||||
Some(&head_ref),
|
||||
)?;
|
||||
Ok(PickOutcome::Applied)
|
||||
}
|
||||
WorktreeMerge::Conflict {
|
||||
tree,
|
||||
conflicts,
|
||||
stages,
|
||||
} => {
|
||||
repo.checkout_tree(tree)?;
|
||||
install_unmerged(repo.git_dir(), &stages)?;
|
||||
write_gitdir_file(
|
||||
repo.git_dir(),
|
||||
CHERRY_PICK_HEAD,
|
||||
format!("{commit_oid}\n").as_bytes(),
|
||||
)?;
|
||||
let message = if commit.message.is_empty() {
|
||||
b"cherry-pick\n".to_vec()
|
||||
} else {
|
||||
commit.message.clone()
|
||||
};
|
||||
write_gitdir_file(repo.git_dir(), MERGE_MSG, &message)?;
|
||||
Ok(PickOutcome::Conflicted(conflicts))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create the commit for a conflict that the user has now resolved and staged.
|
||||
fn finalize_pick(repo: &Repository, sig: &Signature) -> Result<ObjectId> {
|
||||
let git_dir = repo.git_dir();
|
||||
let cherry = read_gitdir_oid(git_dir, CHERRY_PICK_HEAD)
|
||||
.ok_or_else(|| ForgeError::InvalidRef("no CHERRY_PICK_HEAD to continue".into()))?;
|
||||
let picked = repo.commit(&cherry)?;
|
||||
let head = repo.head()?;
|
||||
let head_ref = head_branch(repo)?;
|
||||
// Fails closed unless every conflicted path has been resolved to stage 0.
|
||||
let tree = repo.write_tree()?;
|
||||
let message = read_gitdir_string(git_dir, MERGE_MSG)
|
||||
.map(String::into_bytes)
|
||||
.unwrap_or_else(|| picked.message.clone());
|
||||
let message = if message.is_empty() {
|
||||
b"cherry-pick\n".to_vec()
|
||||
} else {
|
||||
message
|
||||
};
|
||||
let new = repo.commit_tree(
|
||||
tree,
|
||||
vec![head],
|
||||
picked.author.clone(),
|
||||
sig.clone(),
|
||||
&message,
|
||||
Some(&head_ref),
|
||||
)?;
|
||||
append_done(repo, cherry)?;
|
||||
remove_gitdir_file(git_dir, CHERRY_PICK_HEAD);
|
||||
remove_gitdir_file(git_dir, REBASE_HEAD);
|
||||
remove_gitdir_file(git_dir, MERGE_MSG);
|
||||
Ok(new)
|
||||
}
|
||||
|
||||
// ── todo/done persistence ───────────────────────────────────────────────────
|
||||
|
||||
fn write_todo(repo: &Repository, oids: &[ObjectId]) -> Result<()> {
|
||||
write_gitdir_file(repo.git_dir(), TODO, &encode_list(oids))
|
||||
}
|
||||
|
||||
fn read_todo(repo: &Repository) -> Result<Vec<ObjectId>> {
|
||||
match read_gitdir_string(repo.git_dir(), TODO) {
|
||||
Some(content) => decode_list(&content),
|
||||
None => Ok(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn append_done(repo: &Repository, oid: ObjectId) -> Result<()> {
|
||||
let mut done = read_gitdir_string(repo.git_dir(), DONE).unwrap_or_default();
|
||||
done.push_str(&format!("pick {oid}\n"));
|
||||
write_gitdir_file(repo.git_dir(), DONE, done.as_bytes())
|
||||
}
|
||||
|
||||
fn encode_list(oids: &[ObjectId]) -> Vec<u8> {
|
||||
let mut out = String::new();
|
||||
for oid in oids {
|
||||
out.push_str(&format!("pick {oid}\n"));
|
||||
}
|
||||
out.into_bytes()
|
||||
}
|
||||
|
||||
fn decode_list(content: &str) -> Result<Vec<ObjectId>> {
|
||||
let mut oids = Vec::new();
|
||||
for line in content.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
// "pick <oid>" (accept a bare oid too).
|
||||
let token = line.split_whitespace().nth(1).unwrap_or(line);
|
||||
oids.push(ObjectId::from_hex(token)?);
|
||||
}
|
||||
Ok(oids)
|
||||
}
|
||||
|
||||
/// Remove every sequencer state file at the end of (or on abort of) a sequence.
|
||||
fn finish(repo: &Repository) {
|
||||
let git_dir = repo.git_dir();
|
||||
remove_gitdir_file(git_dir, TODO);
|
||||
remove_gitdir_file(git_dir, DONE);
|
||||
remove_gitdir_file(git_dir, HEAD_FILE);
|
||||
remove_gitdir_file(git_dir, ONTO);
|
||||
remove_gitdir_file(git_dir, CHERRY_PICK_HEAD);
|
||||
remove_gitdir_file(git_dir, REBASE_HEAD);
|
||||
remove_gitdir_file(git_dir, MERGE_MSG);
|
||||
let _ = std::fs::remove_dir(git_dir.join("sequencer"));
|
||||
}
|
||||
|
||||
// ── revision helpers ────────────────────────────────────────────────────────
|
||||
|
||||
fn peel_commit(repo: &Repository, oid: ObjectId) -> Result<ObjectId> {
|
||||
crate::merge_cmd::peel_commit_oid(repo, oid)
|
||||
}
|
||||
|
||||
/// The commits reachable from `head` along first-parent history but not already
|
||||
/// contained in `upstream`, ordered oldest → newest (the rebase replay order).
|
||||
fn commits_to_replay(
|
||||
repo: &Repository,
|
||||
upstream: ObjectId,
|
||||
head: ObjectId,
|
||||
) -> Result<Vec<ObjectId>> {
|
||||
let upstream_ancestors = ancestors(repo, upstream)?;
|
||||
let mut list = Vec::new();
|
||||
let mut current = head;
|
||||
loop {
|
||||
if upstream_ancestors.contains(¤t) {
|
||||
break;
|
||||
}
|
||||
let commit = match repo.read_object(¤t)? {
|
||||
Object::Commit(commit) => commit,
|
||||
_ => break,
|
||||
};
|
||||
list.push(current);
|
||||
if list.len() > MAX_REBASE_WALK {
|
||||
return Err(ForgeError::ResourceLimit(
|
||||
"rebase commit list exceeds limit".into(),
|
||||
));
|
||||
}
|
||||
match commit.parents.first() {
|
||||
Some(parent) => current = *parent,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
list.reverse();
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
/// All ancestors of `start` (inclusive), bounded.
|
||||
fn ancestors(repo: &Repository, start: ObjectId) -> Result<HashSet<ObjectId>> {
|
||||
let mut set = HashSet::new();
|
||||
let mut queue = VecDeque::from([start]);
|
||||
while let Some(oid) = queue.pop_front() {
|
||||
if !set.insert(oid) {
|
||||
continue;
|
||||
}
|
||||
if set.len() > MAX_REBASE_WALK {
|
||||
return Err(ForgeError::ResourceLimit(
|
||||
"rebase ancestry walk exceeds limit".into(),
|
||||
));
|
||||
}
|
||||
if let Ok(Object::Commit(commit)) = repo.read_object(&oid) {
|
||||
for parent in commit.parents {
|
||||
queue.push_back(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(set)
|
||||
}
|
||||
@ -83,7 +83,10 @@ pub fn update_server_info(repo: &Repository) -> Result<()> {
|
||||
|
||||
let objects_info = git_dir.join("objects").join("info");
|
||||
std::fs::create_dir_all(&objects_info)?;
|
||||
write_atomic(&objects_info.join("packs"), objects_info_packs(repo)?.as_bytes())?;
|
||||
write_atomic(
|
||||
&objects_info.join("packs"),
|
||||
objects_info_packs(repo)?.as_bytes(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@ -152,7 +155,10 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
let advertised = dumb_info_refs(&repo).unwrap();
|
||||
assert_eq!(advertised, format!("{}\trefs/heads/main\n", commit.to_hex()));
|
||||
assert_eq!(
|
||||
advertised,
|
||||
format!("{}\trefs/heads/main\n", commit.to_hex())
|
||||
);
|
||||
|
||||
// update_server_info writes the same content to disk.
|
||||
update_server_info(&repo).unwrap();
|
||||
|
||||
57
src/show.rs
57
src/show.rs
@ -176,7 +176,9 @@ mod tests {
|
||||
}],
|
||||
};
|
||||
tree_obj.canonicalize();
|
||||
let tree_oid = repo.hash_object(ObjectType::Tree, &tree_obj.serialize(), true).unwrap();
|
||||
let tree_oid = repo
|
||||
.hash_object(ObjectType::Tree, &tree_obj.serialize(), true)
|
||||
.unwrap();
|
||||
|
||||
let sig = Signature::parse("Test <t@t.com> 1700000000 +0000", "test").unwrap();
|
||||
let commit_oid = repo
|
||||
@ -204,7 +206,10 @@ mod tests {
|
||||
assert!(text.contains("commit "), "expected 'commit' header: {text}");
|
||||
assert!(text.contains("Author: Test"), "expected author: {text}");
|
||||
assert!(text.contains(" root commit"), "expected message: {text}");
|
||||
assert!(text.contains("new file mode 100644"), "expected new file: {text}");
|
||||
assert!(
|
||||
text.contains("new file mode 100644"),
|
||||
"expected new file: {text}"
|
||||
);
|
||||
assert!(text.contains("+hello"), "expected diff line: {text}");
|
||||
}
|
||||
|
||||
@ -234,7 +239,9 @@ mod tests {
|
||||
}],
|
||||
};
|
||||
tree_obj.canonicalize();
|
||||
let tree_oid = repo.hash_object(ObjectType::Tree, &tree_obj.serialize(), true).unwrap();
|
||||
let tree_oid = repo
|
||||
.hash_object(ObjectType::Tree, &tree_obj.serialize(), true)
|
||||
.unwrap();
|
||||
|
||||
let mut out = Vec::new();
|
||||
cmd_show(&repo, Some(&tree_oid.to_hex()), &mut out).unwrap();
|
||||
@ -251,7 +258,9 @@ mod tests {
|
||||
let sig = Signature::parse("Test <t@t.com> 1700000000 +0000", "test").unwrap();
|
||||
|
||||
// First commit: file.txt = "version 1\n"
|
||||
let blob1 = repo.hash_object(ObjectType::Blob, b"version 1\n", true).unwrap();
|
||||
let blob1 = repo
|
||||
.hash_object(ObjectType::Blob, b"version 1\n", true)
|
||||
.unwrap();
|
||||
let mut t1 = Tree {
|
||||
entries: vec![TreeEntry {
|
||||
mode: "100644".into(),
|
||||
@ -260,13 +269,24 @@ mod tests {
|
||||
}],
|
||||
};
|
||||
t1.canonicalize();
|
||||
let tree1 = repo.hash_object(ObjectType::Tree, &t1.serialize(), true).unwrap();
|
||||
let tree1 = repo
|
||||
.hash_object(ObjectType::Tree, &t1.serialize(), true)
|
||||
.unwrap();
|
||||
let commit1 = repo
|
||||
.commit_tree(tree1, vec![], sig.clone(), sig.clone(), b"v1\n", Some("refs/heads/main"))
|
||||
.commit_tree(
|
||||
tree1,
|
||||
vec![],
|
||||
sig.clone(),
|
||||
sig.clone(),
|
||||
b"v1\n",
|
||||
Some("refs/heads/main"),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Second commit: file.txt = "version 2\n"
|
||||
let blob2 = repo.hash_object(ObjectType::Blob, b"version 2\n", true).unwrap();
|
||||
let blob2 = repo
|
||||
.hash_object(ObjectType::Blob, b"version 2\n", true)
|
||||
.unwrap();
|
||||
let mut t2 = Tree {
|
||||
entries: vec![TreeEntry {
|
||||
mode: "100644".into(),
|
||||
@ -275,16 +295,31 @@ mod tests {
|
||||
}],
|
||||
};
|
||||
t2.canonicalize();
|
||||
let tree2 = repo.hash_object(ObjectType::Tree, &t2.serialize(), true).unwrap();
|
||||
let tree2 = repo
|
||||
.hash_object(ObjectType::Tree, &t2.serialize(), true)
|
||||
.unwrap();
|
||||
let commit2 = repo
|
||||
.commit_tree(tree2, vec![commit1], sig.clone(), sig, b"v2\n", Some("refs/heads/main"))
|
||||
.commit_tree(
|
||||
tree2,
|
||||
vec![commit1],
|
||||
sig.clone(),
|
||||
sig,
|
||||
b"v2\n",
|
||||
Some("refs/heads/main"),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut out = Vec::new();
|
||||
cmd_show(&repo, Some(&commit2.to_hex()), &mut out).unwrap();
|
||||
let text = String::from_utf8(out).unwrap();
|
||||
|
||||
assert!(text.contains("-version 1"), "expected deletion line: {text}");
|
||||
assert!(text.contains("+version 2"), "expected addition line: {text}");
|
||||
assert!(
|
||||
text.contains("-version 1"),
|
||||
"expected deletion line: {text}"
|
||||
);
|
||||
assert!(
|
||||
text.contains("+version 2"),
|
||||
"expected addition line: {text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
227
src/stash.rs
Normal file
227
src/stash.rs
Normal file
@ -0,0 +1,227 @@
|
||||
//! `git stash`: save the dirty worktree + index as commits, then restore them.
|
||||
//!
|
||||
//! A stash entry is a commit exactly as Git builds it — no bespoke format:
|
||||
//!
|
||||
//! ```text
|
||||
//! i-commit tree = staged index, parent = [HEAD]
|
||||
//! w-commit tree = full worktree, parents = [HEAD, i-commit]
|
||||
//! ```
|
||||
//!
|
||||
//! `refs/stash` points at the newest w-commit and its **reflog is the stack**:
|
||||
//! `stash@{0}` is the newest reflog entry, `stash@{1}` the next, and so on —
|
||||
//! which is why [`stash_list`] and [`stash_drop`] read and rewrite
|
||||
//! `.git/logs/refs/stash` directly.
|
||||
//!
|
||||
//! Restoring (`apply`/`pop`) is a three-way merge of the stashed worktree tree
|
||||
//! back onto the current HEAD (base = the HEAD the stash was taken against),
|
||||
//! reusing the shared engine in [`crate::merge_cmd`].
|
||||
//!
|
||||
//! The CLI wiring lives in `main.rs`; the integrator calls [`cmd_stash_push`],
|
||||
//! [`cmd_stash_pop`], [`cmd_stash_apply`], [`stash_list`], and [`cmd_stash_drop`].
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::error::{ForgeError, Result};
|
||||
use crate::merge_cmd::{
|
||||
build_worktree_merge, force_reset, head_branch, install_unmerged, WorktreeMerge,
|
||||
};
|
||||
use crate::oid::ObjectId;
|
||||
use crate::reflog::{log_path_for_ref, read_reflog, ReflogEntry};
|
||||
use crate::repo::Repository;
|
||||
use crate::signature::Signature;
|
||||
|
||||
const STASH_REF: &str = "refs/stash";
|
||||
/// Upper bound on stash entries read from the reflog stack.
|
||||
const MAX_STASH_ENTRIES: usize = 100_000;
|
||||
|
||||
/// Outcome of restoring a stash entry.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum StashApply {
|
||||
/// The stash applied cleanly.
|
||||
Clean,
|
||||
/// Applying produced conflicts on these paths (index left unmerged).
|
||||
Conflicts(Vec<String>),
|
||||
}
|
||||
|
||||
// ── push ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// `git stash push`: record the index and worktree as a stash entry, then reset
|
||||
/// the worktree + index back to HEAD. Returns `None` when there is nothing to
|
||||
/// stash (a clean worktree), or the new w-commit oid otherwise.
|
||||
pub fn cmd_stash_push(
|
||||
repo: &Repository,
|
||||
sig: &Signature,
|
||||
message: Option<&str>,
|
||||
) -> Result<Option<ObjectId>> {
|
||||
let head = repo
|
||||
.head()
|
||||
.map_err(|_| ForgeError::InvalidRef("cannot stash without an initial commit".into()))?;
|
||||
let head_commit = repo.peel_to_commit(head)?;
|
||||
let branch = head_branch(repo)
|
||||
.ok()
|
||||
.and_then(|refname| refname.strip_prefix("refs/heads/").map(String::from))
|
||||
.unwrap_or_else(|| "HEAD".to_string());
|
||||
|
||||
// The staged tree (index as it stands) becomes the i-commit.
|
||||
let index_tree = repo.write_tree()?;
|
||||
|
||||
// Stage the full worktree to capture unstaged changes; this rewrites the
|
||||
// index, but we reset it back to HEAD at the end regardless.
|
||||
repo.add(&[PathBuf::from(".")])?;
|
||||
let worktree_tree = repo.write_tree()?;
|
||||
|
||||
// Nothing changed relative to HEAD → nothing to stash.
|
||||
if worktree_tree == head_commit.tree && index_tree == head_commit.tree {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let short = &head.to_hex()[..7.min(head.to_hex().len())];
|
||||
let summary = head_commit.summary();
|
||||
let index_msg = format!("index on {branch}: {short} {summary}\n");
|
||||
let i_commit = repo.commit_tree(
|
||||
index_tree,
|
||||
vec![head],
|
||||
sig.clone(),
|
||||
sig.clone(),
|
||||
index_msg.as_bytes(),
|
||||
None,
|
||||
)?;
|
||||
|
||||
let subject = match message {
|
||||
Some(text) => format!("On {branch}: {text}"),
|
||||
None => format!("WIP on {branch}: {short} {summary}"),
|
||||
};
|
||||
let w_commit = repo.commit_tree(
|
||||
worktree_tree,
|
||||
vec![head, i_commit],
|
||||
sig.clone(),
|
||||
sig.clone(),
|
||||
format!("{subject}\n").as_bytes(),
|
||||
None,
|
||||
)?;
|
||||
|
||||
// Push onto the stack: advance refs/stash and append the reflog entry.
|
||||
let previous = repo.refs().resolve(STASH_REF).ok();
|
||||
repo.refs()
|
||||
.compare_and_swap(STASH_REF, previous, w_commit)?;
|
||||
repo.refs().append_reflog(
|
||||
STASH_REF, previous, w_commit, &sig.name, &sig.email, sig.time, &sig.tz, &subject,
|
||||
)?;
|
||||
|
||||
// Restore the working tree + index to a clean HEAD.
|
||||
force_reset(repo, head_commit.tree)?;
|
||||
Ok(Some(w_commit))
|
||||
}
|
||||
|
||||
// ── list ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// `git stash list`: the stack newest-first as `(index, "stash@{i}: <msg>")`.
|
||||
pub fn stash_list(repo: &Repository) -> Result<Vec<(usize, String)>> {
|
||||
let entries = read_reflog(repo.git_dir(), STASH_REF, MAX_STASH_ENTRIES)?;
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, entry)| (index, format!("stash@{{{index}}}: {}", entry.message)))
|
||||
.collect())
|
||||
}
|
||||
|
||||
// ── apply / pop ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// `git stash apply [<index>]`: restore a stash entry without removing it.
|
||||
pub fn cmd_stash_apply(repo: &Repository, index: usize) -> Result<StashApply> {
|
||||
let w_commit_oid = stash_commit(repo, index)?;
|
||||
apply_commit(repo, w_commit_oid)
|
||||
}
|
||||
|
||||
/// `git stash pop [<index>]`: restore a stash entry and, if it applied cleanly,
|
||||
/// drop it from the stack. A conflicting pop leaves the entry in place (like
|
||||
/// Git) so the user does not lose it.
|
||||
pub fn cmd_stash_pop(repo: &Repository, index: usize) -> Result<StashApply> {
|
||||
let outcome = cmd_stash_apply(repo, index)?;
|
||||
if matches!(outcome, StashApply::Clean) {
|
||||
cmd_stash_drop(repo, index)?;
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
fn apply_commit(repo: &Repository, w_commit_oid: ObjectId) -> Result<StashApply> {
|
||||
let w_commit = repo.commit(&w_commit_oid)?;
|
||||
// The stash's first parent is the HEAD it was taken against — the base.
|
||||
let base_tree = match w_commit.parents.first() {
|
||||
Some(parent) => Some(repo.peel_to_commit(*parent)?.tree),
|
||||
None => None,
|
||||
};
|
||||
let ours_tree = repo.peel_to_commit(repo.head()?)?.tree;
|
||||
let theirs_tree = w_commit.tree;
|
||||
|
||||
match build_worktree_merge(repo, base_tree, ours_tree, theirs_tree)? {
|
||||
WorktreeMerge::Clean(tree) => {
|
||||
repo.checkout_tree(tree)?;
|
||||
Ok(StashApply::Clean)
|
||||
}
|
||||
WorktreeMerge::Conflict {
|
||||
tree,
|
||||
conflicts,
|
||||
stages,
|
||||
} => {
|
||||
repo.checkout_tree(tree)?;
|
||||
install_unmerged(repo.git_dir(), &stages)?;
|
||||
Ok(StashApply::Conflicts(conflicts))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── drop ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// `git stash drop [<index>]`: remove one entry from the stack, rewriting the
|
||||
/// `refs/stash` reflog and repointing (or deleting) the ref.
|
||||
pub fn cmd_stash_drop(repo: &Repository, index: usize) -> Result<()> {
|
||||
let git_dir = repo.git_dir();
|
||||
let log_path = log_path_for_ref(git_dir, STASH_REF);
|
||||
let raw = std::fs::read_to_string(&log_path).map_err(|_| {
|
||||
ForgeError::InvalidRef(format!("stash@{{{index}}} not found (empty stash)"))
|
||||
})?;
|
||||
// Reflog file is oldest-first; the stack index is newest-first.
|
||||
let mut entries: Vec<ReflogEntry> = raw.lines().filter_map(ReflogEntry::parse).collect();
|
||||
let count = entries.len();
|
||||
if index >= count {
|
||||
return Err(ForgeError::InvalidRef(format!(
|
||||
"stash@{{{index}}} not found"
|
||||
)));
|
||||
}
|
||||
let file_pos = count - 1 - index;
|
||||
entries.remove(file_pos);
|
||||
|
||||
if entries.is_empty() {
|
||||
// Stack emptied: delete the ref and its log.
|
||||
if let Ok(current) = repo.refs().resolve(STASH_REF) {
|
||||
let _ = repo.refs().compare_and_delete(STASH_REF, current);
|
||||
}
|
||||
let _ = std::fs::remove_file(&log_path);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Repoint refs/stash at the new top (the last, newest reflog line).
|
||||
let new_top = ObjectId::from_hex(&entries.last().expect("non-empty").new_oid)?;
|
||||
let current = repo.refs().resolve(STASH_REF).ok();
|
||||
repo.refs().compare_and_swap(STASH_REF, current, new_top)?;
|
||||
|
||||
let mut rewritten = String::new();
|
||||
for entry in &entries {
|
||||
rewritten.push_str(&entry.format_line());
|
||||
rewritten.push('\n');
|
||||
}
|
||||
std::fs::write(&log_path, rewritten)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ── helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// The w-commit oid for `stash@{index}` (newest-first).
|
||||
fn stash_commit(repo: &Repository, index: usize) -> Result<ObjectId> {
|
||||
let entries = read_reflog(repo.git_dir(), STASH_REF, MAX_STASH_ENTRIES)?;
|
||||
let entry = entries
|
||||
.get(index)
|
||||
.ok_or_else(|| ForgeError::InvalidRef(format!("stash@{{{index}}} not found")))?;
|
||||
ObjectId::from_hex(&entry.new_oid)
|
||||
}
|
||||
@ -52,16 +52,10 @@ pub fn cmd_tag_list(repo: &Repository, show_annotation: bool) -> anyhow::Result<
|
||||
.ok()
|
||||
.and_then(|obj| match obj {
|
||||
crate::object::Object::Tag(t) => {
|
||||
t.message_str()
|
||||
.lines()
|
||||
.next()
|
||||
.map(|l| l.trim().to_string())
|
||||
t.message_str().lines().next().map(|l| l.trim().to_string())
|
||||
}
|
||||
crate::object::Object::Commit(c) => {
|
||||
c.message_str()
|
||||
.lines()
|
||||
.next()
|
||||
.map(|l| l.trim().to_string())
|
||||
c.message_str().lines().next().map(|l| l.trim().to_string())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
@ -160,10 +154,23 @@ pub fn cmd_tag_delete(repo: &Repository, names: &[&str]) -> anyhow::Result<()> {
|
||||
/// Decoded tag operation — used by the convenience dispatcher.
|
||||
#[derive(Debug)]
|
||||
pub enum TagOp<'a> {
|
||||
List { show_annotation: bool },
|
||||
CreateLightweight { name: &'a str, target: Option<&'a str>, force: bool },
|
||||
CreateAnnotated { name: &'a str, target: Option<&'a str>, message: &'a str, force: bool },
|
||||
Delete { names: Vec<&'a str> },
|
||||
List {
|
||||
show_annotation: bool,
|
||||
},
|
||||
CreateLightweight {
|
||||
name: &'a str,
|
||||
target: Option<&'a str>,
|
||||
force: bool,
|
||||
},
|
||||
CreateAnnotated {
|
||||
name: &'a str,
|
||||
target: Option<&'a str>,
|
||||
message: &'a str,
|
||||
force: bool,
|
||||
},
|
||||
Delete {
|
||||
names: Vec<&'a str>,
|
||||
},
|
||||
}
|
||||
|
||||
/// High-level tag dispatcher: given a decoded [`TagOp`] and an optional actor
|
||||
@ -178,12 +185,19 @@ pub fn dispatch_tag(
|
||||
) -> anyhow::Result<()> {
|
||||
match op {
|
||||
TagOp::List { show_annotation } => cmd_tag_list(repo, show_annotation),
|
||||
TagOp::CreateLightweight { name, target, force } => {
|
||||
cmd_tag_create_lightweight(repo, name, target, force)
|
||||
}
|
||||
TagOp::CreateAnnotated { name, target, message, force } => {
|
||||
let tagger = sig
|
||||
.ok_or_else(|| anyhow::anyhow!("annotated tag requires an actor signature"))?;
|
||||
TagOp::CreateLightweight {
|
||||
name,
|
||||
target,
|
||||
force,
|
||||
} => cmd_tag_create_lightweight(repo, name, target, force),
|
||||
TagOp::CreateAnnotated {
|
||||
name,
|
||||
target,
|
||||
message,
|
||||
force,
|
||||
} => {
|
||||
let tagger =
|
||||
sig.ok_or_else(|| anyhow::anyhow!("annotated tag requires an actor signature"))?;
|
||||
cmd_tag_create_annotated(repo, name, target, message, tagger, force)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@ -8,13 +8,15 @@
|
||||
//! haves), computed by walking commits → trees → blobs (+ tags);
|
||||
//! - [`generate_pack`] — a real, self-describing **packfile** (`PACK` header,
|
||||
//! per-object type/size varint + zlib payload, SHA-1 trailer). Objects are
|
||||
//! emitted **undeltified** (full), which is a valid pack `git index-pack`
|
||||
//! accepts and `git fsck` validates.
|
||||
//! emitted either **full** or as `OFS_DELTA` entries against a nearby base
|
||||
//! inside a bounded window (see [`generate_pack_with_options`]); either shape
|
||||
//! is a valid, self-contained pack that `git index-pack`/`git unpack-objects`
|
||||
//! decode and `git fsck` validates.
|
||||
//!
|
||||
//! [`upload_pack_v0`] ties them together for the stateless-RPC (HTTP) case:
|
||||
//! parse the request, compute the set, and return `NAK` + the pack.
|
||||
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
|
||||
use crate::error::{ForgeError, Result};
|
||||
use crate::object::{Object, ObjectType};
|
||||
@ -28,7 +30,9 @@ use std::io::Write;
|
||||
|
||||
/// Capabilities `rit` advertises for upload-pack. Intentionally minimal: no
|
||||
/// multi-ack and no side-band, so the negotiation is a single `NAK` + raw pack.
|
||||
pub const UPLOAD_PACK_CAPABILITIES: &[&str] = &["agent=rit/0.1", "object-format=sha1"];
|
||||
/// `ofs-delta` is advertised because [`generate_pack`] may emit `OFS_DELTA`
|
||||
/// entries; the offsets are always intra-pack and self-contained (never thin).
|
||||
pub const UPLOAD_PACK_CAPABILITIES: &[&str] = &["agent=rit/0.1", "object-format=sha1", "ofs-delta"];
|
||||
|
||||
/// Upper bound on objects walked/sent (fail-closed against pathological repos).
|
||||
const MAX_OBJECTS: usize = 5_000_000;
|
||||
@ -46,7 +50,10 @@ pub fn advertise_upload_pack(repo: &Repository) -> Result<Vec<u8>> {
|
||||
|
||||
// A `symref=HEAD:refs/heads/<branch>` cap lets `clone` check out the right
|
||||
// branch; derive it from the HEAD symbolic ref when present.
|
||||
let mut caps: Vec<String> = UPLOAD_PACK_CAPABILITIES.iter().map(|c| c.to_string()).collect();
|
||||
let mut caps: Vec<String> = UPLOAD_PACK_CAPABILITIES
|
||||
.iter()
|
||||
.map(|c| c.to_string())
|
||||
.collect();
|
||||
if let Ok(crate::RefTarget::Symbolic(target)) = repo.refs().read_head() {
|
||||
caps.push(format!("symref=HEAD:{target}"));
|
||||
}
|
||||
@ -154,7 +161,9 @@ fn walk(
|
||||
continue;
|
||||
}
|
||||
if seen.len() > MAX_OBJECTS {
|
||||
return Err(ForgeError::ResourceLimit("fetch object walk too large".into()));
|
||||
return Err(ForgeError::ResourceLimit(
|
||||
"fetch object walk too large".into(),
|
||||
));
|
||||
}
|
||||
out.push(oid);
|
||||
match repo.odb().read(&oid)? {
|
||||
@ -185,7 +194,9 @@ fn walk_tree(
|
||||
continue;
|
||||
}
|
||||
if seen.len() > MAX_OBJECTS {
|
||||
return Err(ForgeError::ResourceLimit("fetch tree walk too large".into()));
|
||||
return Err(ForgeError::ResourceLimit(
|
||||
"fetch tree walk too large".into(),
|
||||
));
|
||||
}
|
||||
out.push(oid);
|
||||
for entry in repo.tree(&oid)?.entries {
|
||||
@ -228,24 +239,105 @@ fn encode_object_header(type_code: u8, size: usize) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Build a full (undeltified) packfile containing exactly `oids`.
|
||||
/// The pack object type code for the `OFS_DELTA` representation.
|
||||
const OFS_DELTA: u8 = 6;
|
||||
|
||||
/// Tuning for [`generate_pack_with_options`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PackOptions {
|
||||
/// How many preceding candidates (in the type/size-sorted order) each object
|
||||
/// may be deltified against. `0` disables deltification entirely.
|
||||
pub window: usize,
|
||||
/// Hard cap on the length of any single `OFS_DELTA` base chain. Bounds the
|
||||
/// work a reader must do to reconstruct one object and keeps our own encoder
|
||||
/// from stacking pathologically deep chains.
|
||||
pub max_chain_depth: usize,
|
||||
}
|
||||
|
||||
impl Default for PackOptions {
|
||||
fn default() -> Self {
|
||||
// A window of 10 matches Git's default `pack.window`.
|
||||
Self {
|
||||
window: 10,
|
||||
max_chain_depth: 50,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One object's decoded bytes, kept in memory while we search for delta bases.
|
||||
struct RawObject {
|
||||
object_type: ObjectType,
|
||||
payload: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Build a self-contained packfile containing exactly `oids`, using the default
|
||||
/// delta [`PackOptions`]. Objects that compress better as a delta of a nearby
|
||||
/// object are emitted as `OFS_DELTA`; the rest are emitted full. The result is a
|
||||
/// valid non-thin pack (every delta base is included in the same pack).
|
||||
pub fn generate_pack(repo: &Repository, oids: &[ObjectId]) -> Result<Vec<u8>> {
|
||||
generate_pack_with_options(repo, oids, PackOptions::default())
|
||||
}
|
||||
|
||||
/// Build a self-contained packfile with an explicit delta [`PackOptions`].
|
||||
pub fn generate_pack_with_options(
|
||||
repo: &Repository,
|
||||
oids: &[ObjectId],
|
||||
options: PackOptions,
|
||||
) -> Result<Vec<u8>> {
|
||||
let count = u32::try_from(oids.len())
|
||||
.map_err(|_| ForgeError::ResourceLimit("pack object count exceeds u32".into()))?;
|
||||
|
||||
// Read every object once; delta search needs the raw bytes on hand.
|
||||
let mut objects: Vec<RawObject> = Vec::with_capacity(oids.len());
|
||||
for oid in oids {
|
||||
let (object_type, payload) = repo.odb().read_raw(oid)?;
|
||||
objects.push(RawObject {
|
||||
object_type,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
// Emit in a stable "delta-friendly" order: group by type, then largest
|
||||
// first so bigger objects become bases for their smaller, similar peers.
|
||||
let mut order: Vec<usize> = (0..objects.len()).collect();
|
||||
order.sort_by(|&a, &b| {
|
||||
type_code(objects[a].object_type)
|
||||
.cmp(&type_code(objects[b].object_type))
|
||||
.then_with(|| objects[b].payload.len().cmp(&objects[a].payload.len()))
|
||||
.then_with(|| oids[a].cmp(&oids[b]))
|
||||
});
|
||||
|
||||
// Decide a delta base (an earlier position in `order`) for each object.
|
||||
let chosen = select_deltas(&objects, &order, options);
|
||||
|
||||
let mut pack: Vec<u8> = Vec::new();
|
||||
pack.extend_from_slice(b"PACK");
|
||||
pack.extend_from_slice(&2u32.to_be_bytes());
|
||||
pack.extend_from_slice(&count.to_be_bytes());
|
||||
|
||||
for oid in oids {
|
||||
let (object_type, payload) = repo.odb().read_raw(oid)?;
|
||||
pack.extend(encode_object_header(type_code(object_type), payload.len()));
|
||||
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
|
||||
encoder.write_all(&payload)?;
|
||||
let compressed = encoder
|
||||
.finish()
|
||||
.map_err(|e| ForgeError::Decompress(format!("pack compression failed: {e}")))?;
|
||||
pack.extend(compressed);
|
||||
// Byte offset (from pack start) of each object, keyed by position in `order`,
|
||||
// so an OFS_DELTA can encode the distance back to its already-written base.
|
||||
let mut offsets = vec![0u64; order.len()];
|
||||
for position in 0..order.len() {
|
||||
offsets[position] = pack.len() as u64;
|
||||
match &chosen[position] {
|
||||
Some(delta) => {
|
||||
pack.extend(encode_object_header(OFS_DELTA, delta.instructions.len()));
|
||||
let distance = offsets[position]
|
||||
.checked_sub(offsets[delta.base_position])
|
||||
.ok_or_else(|| ForgeError::Pack("delta base must precede its object".into()))?;
|
||||
pack.extend(encode_ofs_delta_offset(distance));
|
||||
pack.extend(zlib_compress(&delta.instructions)?);
|
||||
}
|
||||
None => {
|
||||
let object = &objects[order[position]];
|
||||
pack.extend(encode_object_header(
|
||||
type_code(object.object_type),
|
||||
object.payload.len(),
|
||||
));
|
||||
pack.extend(zlib_compress(&object.payload)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Trailing SHA-1 over the whole pack (excluding the trailer itself).
|
||||
@ -255,6 +347,205 @@ pub fn generate_pack(repo: &Repository, oids: &[ObjectId]) -> Result<Vec<u8>> {
|
||||
Ok(pack)
|
||||
}
|
||||
|
||||
/// A chosen delta representation for one object at a position in the emit order.
|
||||
struct ChosenDelta {
|
||||
/// Position (in `order`) of the base object, always earlier than this one.
|
||||
base_position: usize,
|
||||
/// The uncompressed copy/insert instruction stream.
|
||||
instructions: Vec<u8>,
|
||||
}
|
||||
|
||||
/// For each object in `order`, pick the smallest delta against one of the
|
||||
/// `window` preceding same-type objects, if any beats storing it full.
|
||||
fn select_deltas(
|
||||
objects: &[RawObject],
|
||||
order: &[usize],
|
||||
options: PackOptions,
|
||||
) -> Vec<Option<ChosenDelta>> {
|
||||
let mut chosen: Vec<Option<ChosenDelta>> = (0..order.len()).map(|_| None).collect();
|
||||
let mut depth = vec![0usize; order.len()];
|
||||
if options.window == 0 {
|
||||
return chosen;
|
||||
}
|
||||
|
||||
for position in 0..order.len() {
|
||||
let target = &objects[order[position]];
|
||||
// Too small to recover the delta header overhead — always store full.
|
||||
if target.payload.len() < MIN_DELTA_TARGET {
|
||||
continue;
|
||||
}
|
||||
let window_start = position.saturating_sub(options.window);
|
||||
let mut best: Option<ChosenDelta> = None;
|
||||
for candidate in window_start..position {
|
||||
let base = &objects[order[candidate]];
|
||||
if base.object_type != target.object_type {
|
||||
continue;
|
||||
}
|
||||
if depth[candidate] >= options.max_chain_depth {
|
||||
continue;
|
||||
}
|
||||
let instructions = encode_delta(&base.payload, &target.payload);
|
||||
// Only worth it if the delta is strictly smaller than the object.
|
||||
if instructions.len() >= target.payload.len() {
|
||||
continue;
|
||||
}
|
||||
let better = best
|
||||
.as_ref()
|
||||
.map(|current| instructions.len() < current.instructions.len())
|
||||
.unwrap_or(true);
|
||||
if better {
|
||||
best = Some(ChosenDelta {
|
||||
base_position: candidate,
|
||||
instructions,
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(delta) = best {
|
||||
depth[position] = depth[delta.base_position] + 1;
|
||||
chosen[position] = Some(delta);
|
||||
}
|
||||
}
|
||||
chosen
|
||||
}
|
||||
|
||||
/// Objects below this size never delta well: two size varints plus at least one
|
||||
/// instruction already rival the object, so we skip the search.
|
||||
const MIN_DELTA_TARGET: usize = 32;
|
||||
|
||||
/// Compress `data` with zlib exactly as a pack payload requires.
|
||||
fn zlib_compress(data: &[u8]) -> Result<Vec<u8>> {
|
||||
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
|
||||
encoder.write_all(data)?;
|
||||
encoder
|
||||
.finish()
|
||||
.map_err(|e| ForgeError::Decompress(format!("pack compression failed: {e}")))
|
||||
}
|
||||
|
||||
/// Encode the negative base offset carried by an `OFS_DELTA` header: the byte
|
||||
/// distance from the delta object back to its base, in Git's big-endian
|
||||
/// base-128 form with the `-1` continuation bias.
|
||||
fn encode_ofs_delta_offset(mut offset: u64) -> Vec<u8> {
|
||||
let mut buf = vec![(offset & 0x7f) as u8];
|
||||
offset >>= 7;
|
||||
while offset != 0 {
|
||||
offset -= 1;
|
||||
buf.push(0x80 | (offset & 0x7f) as u8);
|
||||
offset >>= 7;
|
||||
}
|
||||
buf.reverse();
|
||||
buf
|
||||
}
|
||||
|
||||
/// Produce a copy/insert delta that reconstructs `target` from `base`, in Git's
|
||||
/// delta instruction encoding (LE base-128 sizes, then copy/insert opcodes).
|
||||
fn encode_delta(base: &[u8], target: &[u8]) -> Vec<u8> {
|
||||
const MIN_MATCH: usize = 4;
|
||||
// Cap how many base positions share one 4-gram bucket, bounding the search.
|
||||
const MAX_CHAIN: usize = 64;
|
||||
// A single copy encodes at most a 3-byte size field.
|
||||
const MAX_COPY: usize = 0x00ff_ffff;
|
||||
|
||||
let mut out = Vec::new();
|
||||
encode_delta_size(&mut out, base.len());
|
||||
encode_delta_size(&mut out, target.len());
|
||||
|
||||
// Index every 4-gram in the base so target windows can find copy sources.
|
||||
let mut index: HashMap<[u8; 4], Vec<usize>> = HashMap::new();
|
||||
if base.len() >= MIN_MATCH {
|
||||
for i in 0..=base.len() - MIN_MATCH {
|
||||
let key = [base[i], base[i + 1], base[i + 2], base[i + 3]];
|
||||
let bucket = index.entry(key).or_default();
|
||||
if bucket.len() < MAX_CHAIN {
|
||||
bucket.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut pending: Vec<u8> = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i < target.len() {
|
||||
let mut best_len = 0usize;
|
||||
let mut best_off = 0usize;
|
||||
if i + MIN_MATCH <= target.len() {
|
||||
let key = [target[i], target[i + 1], target[i + 2], target[i + 3]];
|
||||
if let Some(bucket) = index.get(&key) {
|
||||
for &pos in bucket {
|
||||
let limit = MAX_COPY.min(target.len() - i).min(base.len() - pos);
|
||||
let mut length = 0usize;
|
||||
while length < limit && target[i + length] == base[pos + length] {
|
||||
length += 1;
|
||||
}
|
||||
if length > best_len {
|
||||
best_len = length;
|
||||
best_off = pos;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if best_len >= MIN_MATCH {
|
||||
flush_insert(&mut out, &mut pending);
|
||||
emit_copy(&mut out, best_off, best_len);
|
||||
i += best_len;
|
||||
} else {
|
||||
pending.push(target[i]);
|
||||
i += 1;
|
||||
if pending.len() == 0x7f {
|
||||
flush_insert(&mut out, &mut pending);
|
||||
}
|
||||
}
|
||||
}
|
||||
flush_insert(&mut out, &mut pending);
|
||||
out
|
||||
}
|
||||
|
||||
/// Encode an object size in the delta header's little-endian base-128 form.
|
||||
fn encode_delta_size(out: &mut Vec<u8>, mut size: usize) {
|
||||
loop {
|
||||
let byte = (size & 0x7f) as u8;
|
||||
size >>= 7;
|
||||
if size == 0 {
|
||||
out.push(byte);
|
||||
break;
|
||||
}
|
||||
out.push(byte | 0x80);
|
||||
}
|
||||
}
|
||||
|
||||
/// Emit any buffered literal bytes as one or more insert instructions (each
|
||||
/// carries at most 127 bytes; the opcode is the length with the high bit clear).
|
||||
fn flush_insert(out: &mut Vec<u8>, pending: &mut Vec<u8>) {
|
||||
for chunk in pending.chunks(0x7f) {
|
||||
out.push(chunk.len() as u8);
|
||||
out.extend_from_slice(chunk);
|
||||
}
|
||||
pending.clear();
|
||||
}
|
||||
|
||||
/// Emit a copy instruction: high bit set, then a presence bitmap selecting which
|
||||
/// of the four offset bytes and three size bytes follow (omitting zero bytes).
|
||||
fn emit_copy(out: &mut Vec<u8>, offset: usize, size: usize) {
|
||||
let mut cmd = 0x80u8;
|
||||
let mut bytes = Vec::new();
|
||||
let offset = offset as u32;
|
||||
for shift in 0..4u32 {
|
||||
let byte = (offset >> (shift * 8)) as u8;
|
||||
if byte != 0 {
|
||||
cmd |= 1 << shift;
|
||||
bytes.push(byte);
|
||||
}
|
||||
}
|
||||
let size = size as u32;
|
||||
for shift in 0..3u32 {
|
||||
let byte = (size >> (shift * 8)) as u8;
|
||||
if byte != 0 {
|
||||
cmd |= 1 << (4 + shift);
|
||||
bytes.push(byte);
|
||||
}
|
||||
}
|
||||
out.push(cmd);
|
||||
out.extend_from_slice(&bytes);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@ -264,7 +555,9 @@ mod tests {
|
||||
fn pack_header_and_trailer_are_wellformed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let repo = Repository::init(dir.path(), true, Some("main")).unwrap();
|
||||
let a = repo.hash_object(ObjectType::Blob, b"alpha\n", true).unwrap();
|
||||
let a = repo
|
||||
.hash_object(ObjectType::Blob, b"alpha\n", true)
|
||||
.unwrap();
|
||||
let b = repo.hash_object(ObjectType::Blob, b"beta\n", true).unwrap();
|
||||
let pack = generate_pack(&repo, &[a, b]).unwrap();
|
||||
|
||||
@ -291,7 +584,9 @@ mod tests {
|
||||
}],
|
||||
};
|
||||
tree.canonicalize();
|
||||
let tree_oid = repo.hash_object(ObjectType::Tree, &tree.serialize(), true).unwrap();
|
||||
let tree_oid = repo
|
||||
.hash_object(ObjectType::Tree, &tree.serialize(), true)
|
||||
.unwrap();
|
||||
let sig = crate::Signature::parse("A <a@b.c> 1700000000 +0000", "commit").unwrap();
|
||||
let commit = repo
|
||||
.commit_tree(tree_oid, Vec::new(), sig.clone(), sig, b"c\n", None)
|
||||
|
||||
@ -1373,7 +1373,11 @@ fn rit_generated_pack_is_decoded_by_stock_git() {
|
||||
|
||||
// Object set reachable from HEAD (commit + trees + blobs), packed by rit.
|
||||
let send = rit::reachable_objects(&repo, &[head], &[]).unwrap();
|
||||
assert!(send.len() >= 4, "expected commit+trees+blobs, got {}", send.len());
|
||||
assert!(
|
||||
send.len() >= 4,
|
||||
"expected commit+trees+blobs, got {}",
|
||||
send.len()
|
||||
);
|
||||
let pack = rit::generate_pack(&repo, &send).unwrap();
|
||||
assert_eq!(&pack[0..4], b"PACK");
|
||||
|
||||
@ -1398,6 +1402,9 @@ fn rit_generated_pack_is_decoded_by_stock_git() {
|
||||
);
|
||||
|
||||
// Every object is now present and valid.
|
||||
assert_eq!(git(target.path(), &["cat-file", "-t", &head.to_hex()]), "commit");
|
||||
assert_eq!(
|
||||
git(target.path(), &["cat-file", "-t", &head.to_hex()]),
|
||||
"commit"
|
||||
);
|
||||
git(target.path(), &["fsck", "--strict"]);
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user