1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
|
use std::collections::BTreeMap;
use std::path::Path;
use crate::config::Config;
use crate::db::{self, Db};
use crate::error::{Error, Missing, Result};
use crate::git;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Sync {
Gone,
Unchanged { head: String },
Fetched { head: String, previous: Option<String> },
Cloned { head: String },
}
/// Detection calls it to move the mirror; the test that pins it drives a real sync.
///
/// Module-internal in a production build, `pub` only under `test-support`:
/// one body behind two visibility declarations, exactly one of which compiles.
#[cfg(feature = "test-support")]
pub fn sync_mirror(cfg: &Config, db: &Db, name: &str, url: &str) -> Result<Sync> {
sync_mirror_impl(cfg, db, name, url)
}
#[cfg(not(feature = "test-support"))]
pub(crate) fn sync_mirror(cfg: &Config, db: &Db, name: &str, url: &str) -> Result<Sync> {
sync_mirror_impl(cfg, db, name, url)
}
fn sync_mirror_impl(cfg: &Config, db: &Db, name: &str, url: &str) -> Result<Sync> {
let mirror = cfg.mirror_path(name);
let known_head = db::get_pkgbase(db, name)?.and_then(|p| p.aur_head.clone());
if !mirror.exists() {
git::clone(url, &mirror)?;
let head = git::head(&mirror)?;
record(db, name, &head, &mirror)?;
return Ok(Sync::Cloned { head });
}
let remote = match git::ls_remote_head(url)? {
Some(h) => h,
None => return Ok(Sync::Gone),
};
let local = git::head(&mirror).ok();
if let Some(l) = &local {
if *l == remote {
return Ok(Sync::Unchanged { head: remote });
}
}
let head = git::fetch_head(&mirror)?;
record(db, name, &head, &mirror)?;
Ok(Sync::Fetched { head, previous: known_head })
}
fn record(db: &Db, name: &str, head: &str, mirror: &Path) -> Result<()> {
let pb = db::get_pkgbase(db, name)?.ok_or_else(|| Error::not_found(Missing::Pkgbase(name.to_string())))?;
db::set_aur_head(&db.writer, pb.id, head, &mirror.display().to_string())
}
#[derive(Debug, Clone)]
pub(crate) struct Tree {
pub blobs: Vec<(String, String)>,
pub files: BTreeMap<String, String>,
}
impl Tree {
pub fn recipe_hash(&self) -> String {
crate::hash::recipe_hash(&self.blobs)
}
pub fn json_list(&self) -> String {
serde_json::to_string(&self.blobs).unwrap_or_else(|_| "[]".into())
}
}
pub(crate) fn read_tree(mirror: &Path, commit: &str) -> Result<Tree> {
// One `ls-tree` and one `cat-file --batch` for the whole tree, so the number
// of files a recipe ships does not decide how many processes a read costs.
// A commit that is gone from the mirror surfaces here, from `ls-tree`, rather
// than from a separate `cat-file -e` probe first.
let blobs = match git::ls_tree(mirror, commit) {
Ok(blobs) => blobs,
Err(e) => {
let text = e.to_string().to_lowercase();
if text.contains("not a tree object") || text.contains("not a valid object name") {
return Err(Error::fail_closed(format!(
"commit {commit} is missing from the local mirror; history was rewritten"
)));
}
return Err(e);
}
};
let oids: Vec<String> = blobs.iter().map(|(_, sha)| sha.clone()).collect();
let contents = git::cat_file_batch(mirror, &oids)?;
let mut files = BTreeMap::new();
for (path, sha) in &blobs {
let bytes = contents
.get(sha)
.ok_or_else(|| Error::not_found(Missing::MirrorPath(path.to_string())))?;
if bytes.len() > 4 * 1024 * 1024 || !looks_textual(bytes) {
continue;
}
files.insert(path.clone(), String::from_utf8_lossy(bytes).into_owned());
}
Ok(Tree { blobs, files })
}
fn looks_textual(b: &[u8]) -> bool {
!b[..b.len().min(512)].contains(&0)
}
pub(crate) fn read_file(mirror: &Path, commit: &str, path: &str) -> Result<Vec<u8>> {
git::read_blob(mirror, commit, path)
}
#[cfg(test)]
mod tests {
use super::*;
/// A throwaway repo with these files committed, and its tip.
///
/// Deliberately minimal: `read_tree` only ever needs a directory git will
/// answer for, so the test does not stand up a mirror, a database or a
/// config to ask it a question about one tree.
fn repo(files: &[(&str, &[u8])]) -> (std::path::PathBuf, String) {
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let dir = std::env::temp_dir().join(format!("aur-read-tree-{}-{}", std::process::id(), nonce));
std::fs::create_dir_all(&dir).unwrap();
let git = |args: &[&str]| {
let out = std::process::Command::new("git")
.arg("-C")
.arg(&dir)
.args(args)
.env("GIT_CONFIG_NOSYSTEM", "1")
.env("HOME", &dir)
.output()
.unwrap();
assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
};
git(&["init", "-q", "-b", "master"]);
git(&["config", "user.email", "test@example.invalid"]);
git(&["config", "user.name", "test"]);
for (name, body) in files {
std::fs::write(dir.join(name), body).unwrap();
}
git(&["add", "-A"]);
git(&["commit", "-q", "-m", "initial"]);
let head = std::fs::read_to_string(dir.join(".git/refs/heads/master")).unwrap();
(dir, head.trim().to_string())
}
#[test]
fn read_tree_returns_every_blob_from_one_batch_read() {
let (dir, head) = repo(&[
("PKGBUILD", b"pkgbase=foo
pkgver=1.0
pkgrel=1
"),
("empty.txt", b""),
("blob.bin", b"\x00not text"),
]);
let tree = read_tree(&dir, &head).unwrap();
assert!(tree.files["PKGBUILD"].contains("pkgver=1.0"));
assert_eq!(tree.files["empty.txt"], "", "an empty blob is a file, not a miss");
assert!(
!tree.files.contains_key("blob.bin"),
"a NUL in the first block means it is not text: {:?}",
tree.files.keys().collect::<Vec<_>>()
);
assert!(tree.blobs.iter().any(|(p, _)| p == "blob.bin"), "binary blobs are still listed");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn read_tree_fails_closed_when_the_commit_is_gone_from_the_mirror() {
let (dir, _head) = repo(&[("PKGBUILD", b"pkgbase=foo
")]);
for gone in ["0123456789012345678901234567890123456789", "deadbeef"] {
let err = read_tree(&dir, gone).unwrap_err().to_string();
assert!(err.contains("missing from the local mirror"), "{gone}: {err}");
}
std::fs::remove_dir_all(&dir).ok();
}
}
|