forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiB2e29cbcTahinli7 hours ago333 commits

backup.rs210 lines, 6.7 KiBHistoryRawDownload
1use std::path::Path;
2
3use sha2::{Digest, Sha256};
4
5use crate::command::{GitCommand, GitEnv};
6use crate::error::{Error, Result};
7
8pub const REFS_FORMAT: &str = "--format=%(objectname) %(refname)";
9
10fn path_str(p: &Path) -> Result<&str> {
11 p.to_str()
12 .ok_or_else(|| Error::InvalidInput(format!("path is not valid UTF-8: {}", p.display())))
13}
14
15async fn refs_listing(env: &GitEnv, repo: &Path) -> Result<Vec<u8>> {
16 GitCommand::new(env, "for-each-ref")
17 .git_dir(repo)
18 .arg(REFS_FORMAT)
19 .output()
20 .await
21}
22
23pub async fn refs_checksum(env: &GitEnv, repo: &Path) -> Result<String> {
24 let out = refs_listing(env, repo).await?;
25 Ok(refs_checksum_of_listing(&out))
26}
27
28pub fn refs_checksum_of_listing(listing: &[u8]) -> String {
29 let mut lines: Vec<&[u8]> = listing
30 .split(|b| *b == b'\n')
31 .filter(|l| !l.is_empty())
32 .collect();
33 lines.sort_unstable();
34 let mut hasher = Sha256::new();
35 for line in lines {
36 hasher.update(line);
37 hasher.update(b"\n");
38 }
39 hex::encode(hasher.finalize())
40}
41
42pub async fn bundle_create(env: &GitEnv, repo: &Path, out: &Path) -> Result<bool> {
43 if std::fs::symlink_metadata(out).is_ok() {
44 return Err(Error::InvalidInput(format!(
45 "bundle target already exists: {}",
46 out.display()
47 )));
48 }
49 if refs_listing(env, repo)
50 .await?
51 .iter()
52 .all(|b| b.is_ascii_whitespace())
53 {
54 return Ok(false);
55 }
56 GitCommand::new(env, "bundle")
57 .git_dir(repo)
58 .arg("create")
59 .user_arg(path_str(out)?)?
60 .arg("--all")
61 .status()
62 .await?;
63 set_private_mode(out)?;
64 Ok(true)
65}
66
67fn set_private_mode(path: &Path) -> Result<()> {
68 use std::os::unix::fs::PermissionsExt;
69 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
70 Ok(())
71}
72
73pub async fn bundle_verify(env: &GitEnv, scratch_repo: &Path, bundle: &Path) -> Result<String> {
74 let bundle_str = path_str(bundle)?;
75 GitCommand::new(env, "bundle")
76 .git_dir(scratch_repo)
77 .arg("verify")
78 .user_arg(bundle_str)?
79 .status()
80 .await?;
81 GitCommand::new(env, "fetch")
82 .git_dir(scratch_repo)
83 .arg("--quiet")
84 .user_arg(bundle_str)?
85 .user_arg("+refs/*:refs/*")?
86 .status()
87 .await?;
88 GitCommand::new(env, "fsck")
89 .git_dir(scratch_repo)
90 .arg("--full")
91 .status()
92 .await?;
93 refs_checksum(env, scratch_repo).await
94}
95
96#[cfg(test)]
97mod tests {
98 use super::*;
99 use std::process::Command;
100
101 fn env(dir: &Path) -> GitEnv {
102 GitEnv {
103 git_bin: "git".into(),
104 data_dir: dir.to_path_buf(),
105 }
106 }
107
108 fn git(dir: &Path, args: &[&str]) {
109 let out = Command::new("git")
110 .current_dir(dir)
111 .env("GIT_AUTHOR_NAME", "t")
112 .env("GIT_AUTHOR_EMAIL", "t@example.invalid")
113 .env("GIT_COMMITTER_NAME", "t")
114 .env("GIT_COMMITTER_EMAIL", "t@example.invalid")
115 .args(args)
116 .output()
117 .expect("run git");
118 assert!(out.status.success(), "git {args:?}: {out:?}");
119 }
120
121 fn repo_with_refs(dir: &Path) -> std::path::PathBuf {
122 let work = dir.join("work");
123 std::fs::create_dir_all(&work).expect("mkdir");
124 git(&work, &["init", "-q", "-b", "main"]);
125 git(&work, &["commit", "-q", "--allow-empty", "-m", "one"]);
126 git(&work, &["branch", "feature"]);
127 git(&work, &["tag", "v1"]);
128 work.join(".git")
129 }
130
131 #[tokio::test]
132 async fn empty_repo_has_no_bundle_and_the_empty_checksum() {
133 let dir = tempfile::tempdir().expect("tempdir");
134 let env = env(dir.path());
135 let bare = dir.path().join("empty.git");
136 crate::repo::init_bare(&env, &bare, "main")
137 .await
138 .expect("init");
139 let out = dir.path().join("empty.bundle");
140 assert!(!bundle_create(&env, &bare, &out).await.expect("create"));
141 assert!(!out.exists(), "nothing is written for an empty repo");
142 assert_eq!(
143 refs_checksum(&env, &bare).await.expect("checksum"),
144 hex::encode(Sha256::digest(b""))
145 );
146 }
147
148 #[tokio::test]
149 async fn bundle_of_a_repo_with_refs_verifies_and_checksum_is_sorted_sha256() {
150 let dir = tempfile::tempdir().expect("tempdir");
151 let env = env(dir.path());
152 let git_dir = repo_with_refs(dir.path());
153 let out = dir.path().join("r.bundle");
154 assert!(bundle_create(&env, &git_dir, &out).await.expect("create"));
155 let scratch = dir.path().join("scratch.git");
156 crate::repo::init_bare(&env, &scratch, "main")
157 .await
158 .expect("scratch");
159 let imported = bundle_verify(&env, &scratch, &out).await.expect("verify");
160
161 let listing = refs_listing(&env, &git_dir).await.expect("list");
162 let mut lines: Vec<&str> = std::str::from_utf8(&listing)
163 .expect("utf8")
164 .lines()
165 .collect();
166 lines.sort_unstable();
167 let mut expected = Sha256::new();
168 for l in &lines {
169 expected.update(l.as_bytes());
170 expected.update(b"\n");
171 }
172 let source_sum = hex::encode(expected.finalize());
173 assert_eq!(
174 refs_checksum(&env, &git_dir).await.expect("checksum"),
175 source_sum
176 );
177 assert_eq!(imported, source_sum, "the imported refs match the source");
178 assert_eq!(lines.len(), 3, "main, feature and v1");
179
180 let mode = std::fs::metadata(&out).expect("meta").permissions();
181 use std::os::unix::fs::PermissionsExt;
182 assert_eq!(mode.mode() & 0o777, 0o600);
183 }
184
185 #[tokio::test]
186 async fn truncated_bundle_fails_verification() {
187 let dir = tempfile::tempdir().expect("tempdir");
188 let env = env(dir.path());
189 let git_dir = repo_with_refs(dir.path());
190 let out = dir.path().join("r.bundle");
191 bundle_create(&env, &git_dir, &out).await.expect("create");
192 let bytes = std::fs::read(&out).expect("read");
193 std::fs::write(&out, &bytes[..bytes.len() / 2]).expect("truncate");
194 let scratch = dir.path().join("scratch.git");
195 crate::repo::init_bare(&env, &scratch, "main")
196 .await
197 .expect("scratch");
198 assert!(bundle_verify(&env, &scratch, &out).await.is_err());
199 }
200
201 #[tokio::test]
202 async fn existing_bundle_target_is_refused() {
203 let dir = tempfile::tempdir().expect("tempdir");
204 let env = env(dir.path());
205 let git_dir = repo_with_refs(dir.path());
206 let out = dir.path().join("r.bundle");
207 std::fs::write(&out, b"x").expect("write");
208 assert!(bundle_create(&env, &git_dir, &out).await.is_err());
209 }
210}