summaryrefslogtreecommitdiffstats
path: root/tests/world.rs
blob: 3a7dd5465366aade33968112a190f5b54a0f88cd (plain)
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
mod common;

use aur_build::db;
use aur_build::pipeline;
use aur_build::pkginfo;
use common::*;

/// Build a real `.pkg.tar.zst`: zstd-compressed tar with the two metadata files
/// inside, as makepkg lays them out. `None` means the file is absent.
fn make_archive(dir: &std::path::Path, name: &str, pkginfo: Option<&str>, buildinfo: Option<&str>) -> std::path::PathBuf {
    let path = dir.join(format!("{name}.pkg.tar.zst"));
    let enc = std::io::BufWriter::new(std::fs::File::create(&path).unwrap());
    let mut enc = zstd::Encoder::new(enc, 3).unwrap();
    {
        let mut ar = tar::Builder::new(&mut enc);
        let mut add = |rel: String, body: &str| {
            let mut h = tar::Header::new_gnu();
            h.set_size(body.len() as u64);
            h.set_mode(0o644);
            h.set_mtime(0);
            ar.append_data(&mut h, rel, std::io::Cursor::new(body.as_bytes())).unwrap();
        };
        if let Some(p) = pkginfo {
            add(format!("{name}/.PKGINFO"), p);
        }
        if let Some(b) = buildinfo {
            add(format!("{name}/.BUILDINFO"), b);
        }
        add(format!("{name}/usr/bin/{name}"), "#!/bin/sh\necho hi\n");
        ar.finish().unwrap();
    }
    enc.finish().unwrap();
    path
}

const PKGINFO: &str = "\
pkgname = plain-make
pkgbase = plain-make
pkgver = 1.0-1
pkgarch = x86_64
pkgdesc = a synthetic package
url = https://example.invalid/plain-make
license = MIT
license = Apache
depend = glibc
depend = openssl>=1.1
makedepend = cmake
provides = make-thing
conflict = other-make
";

const BUILDINFO: &str = "\
format = 2
pkgname = plain-make
pkgbase = plain-make
pkgver = 1.0-1
packager = builduser
builddate = 1700000000
installed =  glibc 2.39-1 x86_64 -
 gmp 6.3.0-1 x86_64 -
 plain-make 0.9-1 x86_64 -
sigfile = /dev/null
";

#[test]
fn pkginfo_fields_are_parsed_from_the_archive_itself() {
    let dir = tempfile::tempdir().unwrap();
    let path = make_archive(dir.path(), "plain-make", Some(PKGINFO), Some(BUILDINFO));
    let bytes = std::fs::read(&path).unwrap();

    let text = pkginfo::pkginfo_text(&bytes).expect(".PKGINFO is in the archive");
    assert!(text.contains("pkgname = plain-make"));
    let meta = pkginfo::parse_pkginfo(&text);
    assert_eq!(meta.name, "plain-make");
    assert_eq!(meta.version, "1.0-1");
    assert_eq!(meta.arch, "x86_64");
    assert_eq!(meta.desc, "a synthetic package");
    // Repeated keys are lists, not last-one-wins.
    assert_eq!(meta.license, vec!["MIT", "Apache"]);
    assert_eq!(meta.depends, vec!["glibc", "openssl>=1.1"]);
    assert_eq!(meta.makedepends, vec!["cmake"]);
    assert_eq!(meta.provides, vec!["make-thing"]);
    assert_eq!(meta.conflicts, vec!["other-make"]);
}

#[test]
fn the_buildinfo_installed_block_is_parsed_line_by_line() {
    let dir = tempfile::tempdir().unwrap();
    let path = make_archive(dir.path(), "plain-make", Some(PKGINFO), Some(BUILDINFO));
    let bytes = std::fs::read(&path).unwrap();
    let text = pkginfo::buildinfo_text(&bytes).unwrap();
    let installed = pkginfo::parse_installed(&text);
    assert_eq!(
        installed.iter().map(|i| (i.name.clone(), i.version.clone())).collect::<Vec<_>>(),
        vec![
            ("glibc".to_string(), "2.39-1".to_string()),
            ("gmp".to_string(), "6.3.0-1".to_string()),
            ("plain-make".to_string(), "0.9-1".to_string()),
        ],
        "the installed block must come through exactly"
    );
    // The block ends at the first unindented line; `sigfile` is not an install.
    assert!(!installed.iter().any(|i| i.name == "sigfile"));
}

#[test]
fn a_package_without_a_pkginfo_is_refused_not_defaulted() {
    // Ingest decides what the index claims about a package. Guessing a name from
    // the filename would let a mislabeled artifact into a signed repo.
    let dir = tempfile::tempdir().unwrap();
    let path = make_archive(dir.path(), "mystery", None, Some(BUILDINFO));
    let bytes = std::fs::read(&path).unwrap();
    assert!(pkginfo::pkginfo_text(&bytes).is_err(), "an archive with no .PKGINFO must not parse");
    // And a truncated archive is an error too, not an empty success.
    assert!(pkginfo::pkginfo_text(b"not even a zstd stream").is_err());
}

#[test]
fn the_world_snapshot_is_intersected_with_our_index_at_ingest_time() {
    // §10.1 / I12. The fixture's build root contains glibc, pacman, binutils and
    // plain-make; only plain-make is ours, and only plain-make may be recorded.
    let (env, fx) = env_with_fixture("plain-make");
    // The first build has no world of ours to record — the honest answer, not an
    // empty lie about glibc.
    publish(&env, "plain-make");
    let first = world_of_last_build(&env);
    assert!(first.is_empty(), "nothing of ours existed for the first build: {first:?}");

    // Now plain-make is in the index, so a later build records it and nothing else.
    let mut manifest = fx.manifest_json();
    manifest["installed"] = serde_json::json!([
        { "name": "glibc", "version": "2.39-1", "arch": "x86_64" },
        { "name": "pacman", "version": "6.1.0-1", "arch": "x86_64" },
        { "name": "binutils", "version": "2.42-1", "arch": "x86_64" },
        { "name": "plain-make", "version": "1.0-1", "arch": "x86_64" }
    ]);
    std::fs::write(&fx.manifest, serde_json::to_string(&manifest).unwrap()).unwrap();
    fx.bump(&[("pkgver", "3.0")]);
    publish(&env, "plain-make");
    let members = world_of_last_build(&env);
    assert!(members.iter().any(|m| m.pkgbase == "plain-make"), "our own package belongs in the world: {members:?}");
    for foreign in ["glibc", "pacman", "binutils"] {
        assert!(
            !members.iter().any(|m| m.pkgbase == foreign),
            "{foreign} is not ours and must not be in the snapshot — an unfiltered world makes every package permanently stale"
        );
    }
    // And the snapshot is attached to the build, not computed later.
    assert_eq!(
        env.query_i64("SELECT count(*) FROM build WHERE state='succeeded' AND world_snapshot_id IS NULL", &[]),
        Some(0),
        "I12: a succeeded build must have a recorded world"
    );
}

#[test]
fn a_split_pkgbase_is_one_approval_and_many_index_rows() {
    // §3: one recipe, several packages, one human decision.
    let (env, _fx) = env_with_fixture("split-pkgbase");
    publish(&env, "split-pkgbase");
    let rows: Vec<String> = env
        .db
        .read(|c| {
            let mut st = c.prepare(
                "SELECT p.name, p.version, p.artifact_id FROM package p
                 JOIN release r ON r.id = p.release_id
                 WHERE p.state='in_index' ORDER BY p.name",
            )?;
            let out = st
                .query_map([], |r| Ok(format!("{} {} art={:?}", r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, Option<i64>>(2)?)))?
                .filter_map(|x| x.ok())
                .collect();
            Ok(out)
        })
        .unwrap();
    assert!(rows.len() >= 2, "a split pkgbase should produce several index rows: {rows:?}");
    assert!(
        rows.iter().all(|r| r.contains("art=Some")),
        "every index row needs its own artifact: {rows:?}"
    );
    // One approval, however many packages came out of it.
    assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1));
    assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(1));
}

fn publish(env: &Env, name: &str) {
    aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap();
    let c = aur_build::review::candidates::pending_candidates(&env.db).unwrap().remove(0);
    let dd = aur_build::review::diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
    let c = aur_build::review::candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
    aur_build::review::approve::approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap();
    let c = aur_build::review::candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
    let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
    pipeline::run(&env.cfg, &env.db, &id).unwrap();
}

fn world_of_last_build(env: &Env) -> Vec<db::WorldMember> {
    let json: String = env
        .db
        .read(|c| {
            Ok(c.query_row(
                "SELECT w.members_json FROM world_snapshot w
                 JOIN build b ON b.world_snapshot_id = w.id
                 ORDER BY b.rowid DESC LIMIT 1",
                [],
                |r| r.get(0),
            )?)
        })
        .unwrap();
    serde_json::from_str(&json).unwrap()
}