Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-git/tests/common/mod.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-git / tests / common / mod.rs` 292 lines ยท 10516 bytes Raw Blame History 1 //! Fixture helpers shared by the H1 tests (issue #48). The system `git` is used only as an 2 //! independent oracle and fixture builder. 3 #![allow(dead_code)] 4 5 use std::collections::{BTreeMap, BTreeSet}; 6 use std::fs; 7 use std::path::{Path, PathBuf}; 8 use std::process::{Command, Output}; 9 use synapse_core::GitOid; 10 use synapse_git::{GitHistory, GitObject}; 11 12 pub fn temp_dir(label: &str) -> PathBuf { 13 let dir = std::env::temp_dir().join(format!( 14 "synapse-h1-{label}-{}-{}", 15 std::process::id(), 16 std::time::SystemTime::now() 17 .duration_since(std::time::UNIX_EPOCH) 18 .unwrap() 19 .as_nanos() 20 )); 21 fs::create_dir_all(&dir).unwrap(); 22 dir 23 } 24 25 /// Run `git -C dir args` with no user or system configuration and fixed identities and dates, 26 /// so fixture history is the same on every host. 27 pub fn git_raw(dir: &Path, args: &[&str], stdin: Option<&[u8]>) -> Output { 28 let mut cmd = Command::new("git"); 29 cmd.arg("-C") 30 .arg(dir) 31 .args(args) 32 .env("GIT_CONFIG_NOSYSTEM", "1") 33 .env("GIT_CONFIG_GLOBAL", "/dev/null") 34 .env("GIT_AUTHOR_NAME", "Fixture Author") 35 .env("GIT_AUTHOR_EMAIL", "author@fixture.invalid") 36 .env("GIT_AUTHOR_DATE", "`1700000000` +0000") 37 .env("GIT_COMMITTER_NAME", "Fixture Committer") 38 .env("GIT_COMMITTER_EMAIL", "committer@fixture.invalid") 39 .env("GIT_COMMITTER_DATE", "`1700000000` +0000"); 40 if let Some(input) = stdin { 41 use std::io::Write; 42 cmd.stdin(std::process::Stdio::piped()) 43 .stdout(std::process::Stdio::piped()) 44 .stderr(std::process::Stdio::piped()); 45 let mut child = cmd.spawn().unwrap(); 46 child.stdin.take().unwrap().write_all(input).unwrap(); 47 child.wait_with_output().unwrap() 48 } else { 49 cmd.output().unwrap() 50 } 51 } 52 53 pub fn git(dir: &Path, args: &[&str]) -> Vec { 54 let out = git_raw(dir, args, None); 55 assert!( 56 out.status.success(), 57 "git {args:?} failed: {}", 58 String::from_utf8_lossy(&out.stderr) 59 ); 60 out.stdout 61 } 62 63 pub fn git_text(dir: &Path, args: &[&str]) -> String { 64 String::from_utf8(git(dir, args)) 65 .unwrap() 66 .trim() 67 .to_string() 68 } 69 70 pub fn write(dir: &Path, rel: &str, bytes: &[u8]) { 71 let path = dir.join(rel); 72 fs::create_dir_all(path.parent().unwrap()).unwrap(); 73 fs::write(path, bytes).unwrap(); 74 } 75 76 pub fn commit_all(dir: &Path, msg: &str) { 77 git(dir, &["add", "-A"]); 78 git(dir, &["commit", "-q", "--allow-empty", "-m", msg]); 79 } 80 81 /// Deterministic pseudo-random bytes (xorshift), so the binary blob is incompressible. 82 pub fn noise(len: usize, seed: u64) -> Vec { 83 let mut x = seed | 1; 84 (0..len) 85 .map(|_| { 86 x ^= x << 13; 87 x ^= x >> 7; 88 x ^= x << 17; 89 x as u8 90 }) 91 .collect() 92 } 93 94 /// Real Git history with every shape the bridge must carry: nested trees, executable files, 95 /// a symlink, an empty file, an incompressible binary, a large compressible file revised many 96 /// times (delta material), a two-parent merge, an octopus merge, an empty commit, annotated 97 /// tags of a commit, a tree, a blob and another tag, a lightweight tag, and a commit with a 98 /// multi-line signature header and an `encoding` header. 99 pub fn build_fixture(dir: &Path) { 100 git(dir, &["init", "-q", "-b", "main"]); 101 let mut big = String::new(); 102 for i in 0..6000 { 103 big.push_str(&format!( 104 "line {i}: the quick brown fox jumps over the lazy dog\n" 105 )); 106 } 107 write(dir, "README.md", b"# fixture\n"); 108 write(dir, "src/lib.rs", b"pub fn one() -> u32 { 1 }\n"); 109 write(dir, "src/deep/nested/mod.rs", b"// nested\n"); 110 write(dir, "data/empty.txt", b""); 111 write(dir, "data/noise.bin", &noise(40_000, 7)); 112 write(dir, "docs/big.txt", big.as_bytes()); 113 write(dir, "tools/run.sh", b"#!/bin/sh\necho run\n"); 114 let mut perms = fs::metadata(dir.join("tools/run.sh")) 115 .unwrap() 116 .permissions(); 117 std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755); 118 fs::set_permissions(dir.join("tools/run.sh"), perms).unwrap(); 119 std::os::unix::fs::symlink("../README.md", dir.join("docs/readme-link")).unwrap(); 120 commit_all(dir, "initial"); 121 for rev in 0..12 { 122 let edited = big.replace( 123 &format!("line {}:", rev * 400), 124 &format!("LINE {} (rev {rev}):", rev * 400), 125 ); 126 write(dir, "docs/big.txt", edited.as_bytes()); 127 write( 128 dir, 129 "src/lib.rs", 130 format!("pub fn one() -> u32 {{ {rev} }}\n").as_bytes(), 131 ); 132 commit_all(dir, &format!("revision {rev}")); 133 } 134 git(dir, &["tag", "-a", "v1", "-m", "release v1"]); 135 git(dir, &["tag", "light"]); 136 git(dir, &["checkout", "-q", "-b", "feature"]); 137 write(dir, "src/feature.rs", b"pub fn feature() {}\n"); 138 commit_all(dir, "feature work"); 139 git(dir, &["checkout", "-q", "main"]); 140 write(dir, "src/main_only.rs", b"fn main_only() {}\n"); 141 commit_all(dir, "main work"); 142 git( 143 dir, 144 &["merge", "-q", "--no-ff", "feature", "-m", "merge feature"], 145 ); 146 for name in ["oct-a", "oct-b"] { 147 git(dir, &["checkout", "-q", "-b", name, "main"]); 148 write(dir, &format!("{name}.txt"), name.as_bytes()); 149 commit_all(dir, name); 150 } 151 git(dir, &["checkout", "-q", "main"]); 152 git( 153 dir, 154 &["merge", "-q", "--no-ff", "oct-a", "oct-b", "-m", "octopus"], 155 ); 156 commit_all(dir, "empty commit"); 157 let tree = git_text(dir, &["rev-parse", "HEAD^{tree}"]); 158 let blob = git_text(dir, &["rev-parse", "HEAD:README.md"]); 159 git( 160 dir, 161 &["tag", "-a", "tree-tag", &tree, "-m", "a tag of a tree"], 162 ); 163 git( 164 dir, 165 &["tag", "-a", "blob-tag", &blob, "-m", "a tag of a blob"], 166 ); 167 git( 168 dir, 169 &[ 170 "tag", 171 "-a", 172 "-f", 173 "nested-tag", 174 "v1", 175 "-m", 176 "a tag of a tag", 177 ], 178 ); 179 // Objects reachable only through a tag: a blob in no tree, and an inner tag whose own 180 // reference is deleted, so only the outer tag reaches it. 181 let out = git_raw( 182 dir, 183 &["hash-object", "-w", "--stdin"], 184 Some(b"reachable only through a tag\n"), 185 ); 186 let lone_blob = String::from_utf8(out.stdout).unwrap().trim().to_string(); 187 git( 188 dir, 189 &[ 190 "tag", 191 "-a", 192 "lone-blob-tag", 193 &lone_blob, 194 "-m", 195 "tag of a lone blob", 196 ], 197 ); 198 git(dir, &["tag", "-a", "inner", "v1", "-m", "inner tag"]); 199 git( 200 dir, 201 &["tag", "-a", "-f", "outer-only", "inner", "-m", "outer tag"], 202 ); 203 git(dir, &["tag", "-d", "inner"]); 204 // A commit with a multi-line signature header and an encoding header, written as raw 205 // bytes (no signing key is involved: the header is opaque data to Git and to the bridge). 206 let head = git_text(dir, &["rev-parse", "HEAD"]); 207 let raw = format!( 208 "tree {tree}\nparent {head}\n\ 209 author Fixture Author `1700000001` +0100\n\ 210 committer Fixture Committer `1700000002` -0230\n\ 211 encoding ISO-8859-1\n\ 212 gpgsig -----BEGIN PGP SIGNATURE-----\n \n iQEzBAABCAAdFiEEfixture\n =abcd\n -----END PGP SIGNATURE-----\n\ 213 \nsigned commit with caf\u{e9}\n" 214 ); 215 let out = git_raw( 216 dir, 217 &["hash-object", "-t", "commit", "-w", "--stdin"], 218 Some(raw.as_bytes()), 219 ); 220 assert!(out.status.success()); 221 let signed = String::from_utf8(out.stdout).unwrap().trim().to_string(); 222 git(dir, &["update-ref", "refs/heads/signed", &signed]); 223 } 224 225 /// `git cat-file --batch-all-objects --batch`: every object in the database as (kind, payload). 226 pub fn git_all_objects(dir: &Path) -> BTreeMap)> { 227 let out = git(dir, &["cat-file", "--batch-all-objects", "--batch"]); 228 let mut objects = BTreeMap::new(); 229 let mut rest = &out[..]; 230 while !rest.is_empty() { 231 let nl = rest.iter().position(|&b| b == b'\n').unwrap(); 232 let header = std::str::from_utf8(&rest[..nl]).unwrap(); 233 let mut parts = header.split(' '); 234 let oid = GitOid::from_hex(parts.next().unwrap()).unwrap(); 235 let kind = parts.next().unwrap().to_string(); 236 let size: usize = parts.next().unwrap().parse().unwrap(); 237 let payload = rest[nl + 1..nl + 1 + size].to_vec(); 238 objects.insert(oid, (kind, payload)); 239 rest = &rest[nl + 1 + size + 1..]; 240 } 241 objects 242 } 243 244 pub fn git_refs(dir: &Path) -> BTreeMap { 245 git_text(dir, &["for-each-ref", "--format=%(refname) %(objectname)"]) 246 .lines() 247 .map(|l| { 248 let (name, oid) = l.split_once(' ').unwrap(); 249 (name.to_string(), GitOid::from_hex(oid).unwrap()) 250 }) 251 .collect() 252 } 253 254 pub fn assert_history_matches_git(history: &GitHistory, dir: &Path) { 255 let oracle = git_all_objects(dir); 256 let native: BTreeSet = history.objects.keys().copied().collect(); 257 let expected: BTreeSet = oracle.keys().copied().collect(); 258 assert_eq!( 259 native, expected, 260 "native reachable set != git object database" 261 ); 262 for (oid, object) in &history.objects { 263 let (kind, payload) = &oracle[oid]; 264 assert_eq!(object.kind.name(), kind, "kind of {oid}"); 265 assert_eq!(&object.payload, payload, "payload of {oid}"); 266 assert_eq!(object.oid(), *oid); 267 } 268 assert_eq!(history.refs, git_refs(dir), "references"); 269 } 270 271 pub fn assert_fsck_strict_clean(dir: &Path) { 272 let out = git_raw(dir, &["fsck", "--full", "--strict", "--no-dangling"], None); 273 let stderr = String::from_utf8_lossy(&out.stderr); 274 let stdout = String::from_utf8_lossy(&out.stdout); 275 assert!( 276 out.status.success() && !stderr.contains("error") && !stderr.contains("warning"), 277 "git fsck --full --strict failed in {}:\n{stdout}\n{stderr}", 278 dir.display() 279 ); 280 } 281 282 /// Number of entries whose pack type (`gitformat-pack`: 3 bits after the MSB of the first byte) is `t`. 283 pub fn count_entry_type(pack: &[u8], entries: &[synapse_git::PackIndexEntry], t: u8) -> usize { 284 entries 285 .iter() 286 .filter(|e| (pack[e.offset as usize] >> 4) & 0x07 == t) 287 .count() 288 } 289 290 pub fn objects_of(history: &GitHistory) -> Vec { 291 history.objects.values().cloned().collect() 292 }