summaryrefslogtreecommitdiffstats
path: root/tests/common/mod.rs
blob: 6d05c3baba35b94c85eb00ca8f9eb7979ae3001e (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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
// Every test binary compiles this file, so a helper one of them uses is dead
// code in the other twenty. `the_test_helpers_are_used` in tests/architecture.rs
// fails on any item here that no test names, so the allowance below hides noise
// but cannot hide dead weight.
#![allow(dead_code)]

use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex, OnceLock};

use aur_build::config::{Config, TestHooks};
use aur_build::db::{self, Db};

pub struct Env {
    pub tmp: tempfile::TempDir,
    pub cfg: Config,
    pub db: Db,
}

impl Env {
    pub fn new() -> Self {
        let tmp = tempfile::tempdir().expect("tempdir");
        let cfg = Config { root: tmp.path().to_path_buf(), signing_key_id: "TESTKEY".into(), ..Config::default() };
        Self::with_cfg(tmp, cfg)
    }

    pub fn with_cfg(tmp: tempfile::TempDir, cfg: Config) -> Self {
        cfg.ensure_dirs().expect("ensure_dirs");
        db::migrate(&cfg.db_path()).expect("migrate");
        let db = Db::open_migrated(&cfg.db_path()).expect("open db");
        let rid = db::ensure_repo(
            &db.writer,
            &cfg.repo_name,
            &cfg.repo_arch_dir().display().to_string(),
            &cfg.arch,
            &cfg.signing_key_id,
        )
        .expect("repo row");
        assert!(rid > 0);
        Self { tmp, cfg, db }
    }

    pub fn root(&self) -> &Path {
        self.tmp.path()
    }

    pub fn path(&self, p: &str) -> PathBuf {
        self.tmp.path().join(p)
    }

    pub fn subscribe(&self, name: &str) -> i64 {
        let rid = db::repo_id(&self.db).unwrap();
        let url = format!("file://{}/aur/{}.git", self.root().display(), name);
        db::subscribe(&self.db.writer, rid, name, &url).unwrap();
        db::get_pkgbase(&self.db, name).unwrap().unwrap().id
    }

    pub fn exec(&self, sql: &str, params: &[P]) -> usize {
        let sql = sql.to_string();
        let params: Vec<P> = params.to_vec();
        self.db
            .writer
            .tx_for_tests(move |tx| {
                let refs: Vec<&dyn rusqlite::ToSql> = params
                    .iter()
                    .map(|p| match p {
                        P::I(i) => i as &dyn rusqlite::ToSql,
                        P::S(s) => s as &dyn rusqlite::ToSql,
                    })
                    .collect();
                Ok(tx.execute(&sql, rusqlite::params_from_iter(refs.iter()))?)
            })
            .unwrap()
    }

    pub fn accept_as_release(&self, candidate_id: i64) -> i64 {
        let at = "2026-01-01T00:00:00Z";
        self.db
            .writer
            .tx_for_tests(move |tx| {
                tx.execute(
                    "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision,
                                           risk_level, diff_digest, identity_hash)
                     SELECT id, base_release_id, ?2, 'approved', risk_level, diff_digest, identity_hash
                     FROM candidate WHERE id=?1",
                    rusqlite::params![candidate_id, at],
                )?;
                let approval_id = tx.last_insert_rowid();
                tx.execute(
                    "INSERT INTO release (pkgbase_id, candidate_id, approval_id, aur_commit, recipe_hash,
                                          upstream_pins_json, source_digests_json, epoch, pkgver, pkgrel,
                                          state, published_at, created_at)
                     SELECT c.pkgbase_id, c.id, ?2, s.aur_commit, s.recipe_hash, c.upstream_pins_json,
                            c.source_digests_json, c.epoch, c.pkgver, c.pkgrel,
                            'published', ?3, ?3
                     FROM candidate c JOIN snapshot s ON s.id = c.snapshot_id WHERE c.id=?1",
                    rusqlite::params![candidate_id, approval_id, at],
                )?;
                let release_id = tx.last_insert_rowid();
                tx.execute(
                    "UPDATE candidate SET state='approved', resolved_at=?1 WHERE id=?2",
                    rusqlite::params![at, candidate_id],
                )?;
                tx.execute(
                    "INSERT INTO package (repo_id, release_id, name, arch, version, state)
                     SELECT (SELECT id FROM repo ORDER BY id LIMIT 1), ?1,
                            b.name, 'x86_64', c.pkgver || '-' || c.pkgrel, 'in_index'
                     FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?2",
                    rusqlite::params![release_id, candidate_id],
                )?;
                tx.execute(
                    "UPDATE pkgbase SET current_accepted_release_id=?1
                     WHERE id=(SELECT pkgbase_id FROM candidate WHERE id=?2)",
                    rusqlite::params![release_id, candidate_id],
                )?;
                Ok(release_id)
            })
            .unwrap()
    }

    pub fn set_publish_fault(&mut self, at: &str) {
        self.cfg.hooks.publish_fault = Some(at.to_string());
    }
    pub fn clear_publish_fault(&mut self) {
        self.cfg.hooks.publish_fault = None;
    }
    pub fn set_shim_fail(&mut self, tool: &str) {
        self.cfg.hooks.shim_fail = Some(tool.to_string());
    }

    /// Run a statement the library deliberately does not expose, so a fixture
    /// can reach a state without the library growing a test-only setter.
    pub fn execute(&self, sql: &str, params: &[P]) {
        let c = rusqlite::Connection::open(self.cfg.db_path()).unwrap();
        let refs: Vec<&dyn rusqlite::ToSql> = params
            .iter()
            .map(|p| match p {
                P::I(i) => i as &dyn rusqlite::ToSql,
                P::S(s) => s as &dyn rusqlite::ToSql,
            })
            .collect();
        c.execute(sql, rusqlite::params_from_iter(refs)).unwrap();
    }

    pub fn query_i64(&self, sql: &str, params: &[P]) -> Option<i64> {
        let sql = sql.to_string();
        let params: Vec<P> = params.to_vec();
        self.db
            .read(move |c| {
                let refs: Vec<&dyn rusqlite::ToSql> = params
                    .iter()
                    .map(|p| match p {
                        P::I(i) => i as &dyn rusqlite::ToSql,
                        P::S(s) => s as &dyn rusqlite::ToSql,
                    })
                    .collect();
                use rusqlite::OptionalExtension;
                Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, i64>(0)).optional()?)
            })
            .unwrap()
    }

    pub fn query_str(&self, sql: &str, params: &[P]) -> Option<String> {
        let sql = sql.to_string();
        let params: Vec<P> = params.to_vec();
        self.db
            .read(move |c| {
                let refs: Vec<&dyn rusqlite::ToSql> = params
                    .iter()
                    .map(|p| match p {
                        P::I(i) => i as &dyn rusqlite::ToSql,
                        P::S(s) => s as &dyn rusqlite::ToSql,
                    })
                    .collect();
                use rusqlite::OptionalExtension;
                Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, String>(0)).optional()?)
            })
            .unwrap()
    }
}

#[derive(Debug, Clone)]
pub enum P {
    I(i64),
    S(String),
}

impl From<i64> for P {
    fn from(i: i64) -> Self {
        P::I(i)
    }
}
impl From<&str> for P {
    fn from(s: &str) -> Self {
        P::S(s.to_string())
    }
}
impl From<String> for P {
    fn from(s: String) -> Self {
        P::S(s)
    }
}

pub fn params(v: Vec<impl Into<P>>) -> Vec<P> {
    v.into_iter().map(Into::into).collect()
}

impl Drop for Env {
    fn drop(&mut self) {
        self.db.writer.shutdown();
    }
}

pub fn corpus_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("testcorpus")
}

pub fn shim_dir() -> PathBuf {
    Path::new(&env!("CARGO_BIN_EXE_makechrootpkg")).parent().unwrap().to_path_buf()
}

pub fn env_with_fixture(name: &str) -> (Env, Fixture) {
    let tmp = tempfile::tempdir().expect("tempdir");
    let fx = materialize_fixture(tmp.path(), name);
    let cfg = Config {
        root: tmp.path().to_path_buf(),
        signing_key_id: "TESTKEY".into(),
        hooks: TestHooks {
            path_prepend: Some(shim_dir()),
            shim_manifest: Some(fx.manifest.clone()),
            shim_dir: Some(tmp.path().join("shimlog")),
            ..TestHooks::default()
        },
        ..Config::default()
    };
    std::fs::create_dir_all(cfg.hooks.shim_dir.as_ref().unwrap()).unwrap();
    cfg.ensure_dirs().unwrap();
    let env = Env::with_cfg(tmp, cfg);
    env.subscribe(name);
    (env, fx)
}

pub fn env_with_two_fixtures(a: &str, b: &str) -> (Env, Fixture, Fixture) {
    let tmp = tempfile::tempdir().expect("tempdir");
    let fa = materialize_fixture(tmp.path(), a);
    let fb = materialize_fixture(tmp.path(), b);
    let cfg = Config {
        root: tmp.path().to_path_buf(),
        signing_key_id: "TESTKEY".into(),
        hooks: TestHooks {
            path_prepend: Some(shim_dir()),
            shim_manifest: Some(fb.manifest.clone()),
            shim_dir: Some(tmp.path().join("shimlog")),
            ..TestHooks::default()
        },
        ..Config::default()
    };
    std::fs::create_dir_all(cfg.hooks.shim_dir.as_ref().unwrap()).unwrap();
    cfg.ensure_dirs().unwrap();
    let env = Env::with_cfg(tmp, cfg);
    env.subscribe(a);
    env.subscribe(b);
    (env, fa, fb)
}

pub fn materialize_fixture(root: &Path, name: &str) -> Fixture {
    let src = corpus_root().join(name);
    assert!(src.exists(), "no fixture {name} in {}", corpus_root().display());
    let manifest = root.join("manifest.json");
    std::fs::copy(src.join("manifest.json"), &manifest).expect("copy manifest");

    let data = root.join(format!("fixture/{name}"));
    std::fs::create_dir_all(&data).unwrap();
    let aur = root.join(format!("aur/{name}.git"));
    let upstream = root.join(format!("upstream/{name}"));
    let upstream2 = root.join(format!("upstream/{name}-2"));
    let subs = [
        ("@AUR_DIR@".to_string(), data.display().to_string()),
        ("@UPSTREAM_DIR@".to_string(), upstream.display().to_string()),
        ("@UPSTREAM2_DIR@".to_string(), upstream2.display().to_string()),
    ];

    let pristine = pristine_fixture(name);
    for (fname, body) in &pristine.data_files {
        std::fs::write(data.join(fname), substitute(body, &subs)).unwrap();
    }
    copy_tree(&pristine.aur, &aur);
    if pristine.upstream.exists() {
        copy_tree(&pristine.upstream, &upstream);
    }
    if pristine.upstream2.exists() {
        copy_tree(&pristine.upstream2, &upstream2);
    }
    if pristine.path_dependent {
        // The recipe names directories this test owns, so the copied commit has
        // to speak the cache's paths.
        for (fname, body) in &pristine.recipe_files {
            std::fs::write(aur.join(fname), substitute(body, &subs)).unwrap();
        }
        git(&aur, &["add", "-A"]);
        git(&aur, &["commit", "-q", "--amend", "-m", "initial"]);
    }

    Fixture {
        name: name.to_string(),
        src,
        aur,
        data,
        manifest,
        upstream: pristine.upstream.exists().then_some(upstream),
        upstream2: pristine.upstream2.exists().then_some(upstream2),
    }
}

/// A corpus entry as it sits on disk, placeholders intact.
struct Corpus {
    recipe_files: Vec<(String, String)>,
    data_files: Vec<(String, String)>,
    upstream: bool,
    upstream2: bool,
}

fn read_corpus(name: &str) -> Corpus {
    let src = corpus_root().join(name);
    let mut corpus = Corpus { recipe_files: Vec::new(), data_files: Vec::new(), upstream: false, upstream2: false };
    for entry in std::fs::read_dir(&src).unwrap() {
        let path = entry.unwrap().path();
        let fname = path.file_name().unwrap().to_string_lossy().to_string();
        if fname == "manifest.json" {
            continue;
        }
        let body = std::fs::read_to_string(&path).unwrap_or_default();
        corpus.upstream |= body.contains("@UPSTREAM_DIR@");
        corpus.upstream2 |= body.contains("@UPSTREAM2_DIR@");
        if matches!(fname.as_str(), "payload.bin" | "data.bin") {
            corpus.data_files.push((fname, body));
        } else {
            corpus.recipe_files.push((fname, body));
        }
    }
    corpus
}

/// The fixture repos, built once per test binary rather than once per test.
#[derive(Clone)]
struct Pristine {
    aur: PathBuf,
    upstream: PathBuf,
    upstream2: PathBuf,
    recipe_files: Vec<(String, String)>,
    data_files: Vec<(String, String)>,
    path_dependent: bool,
}

static PRISTINE: LazyLock<Mutex<HashMap<String, Pristine>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
static CACHE_ROOT: OnceLock<tempfile::TempDir> = OnceLock::new();

fn pristine_fixture(name: &str) -> Pristine {
    let mut cache = PRISTINE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
    if let Some(found) = cache.get(name) {
        return found.clone();
    }
    let root = CACHE_ROOT.get_or_init(|| tempfile::tempdir().expect("fixture cache")).path().to_path_buf();
    let corpus = read_corpus(name);

    let data = root.join(format!("{name}/fixture"));
    let aur = root.join(format!("{name}/aur.git"));
    let upstream = root.join(format!("{name}/upstream"));
    let upstream2 = root.join(format!("{name}/upstream-2"));
    std::fs::create_dir_all(&data).unwrap();
    let subs = [
        ("@AUR_DIR@".to_string(), data.display().to_string()),
        ("@UPSTREAM_DIR@".to_string(), upstream.display().to_string()),
        ("@UPSTREAM2_DIR@".to_string(), upstream2.display().to_string()),
    ];
    let path_dependent = corpus
        .recipe_files
        .iter()
        .chain(corpus.data_files.iter())
        .any(|(_, b)| b.contains("@AUR_DIR@") || b.contains("@UPSTREAM_DIR@") || b.contains("@UPSTREAM2_DIR@"));

    for (fname, body) in &corpus.data_files {
        std::fs::write(data.join(fname), substitute(body, &subs)).unwrap();
    }
    if corpus.upstream {
        make_git_repo(&upstream, &[("README", "upstream\n")], "upstream: initial");
        if std::fs::read_to_string(corpus_root().join(name).join("PKGBUILD")).unwrap_or_default().contains("#tag=") {
            git(&upstream, &["tag", "v1"]);
        }
    }
    if corpus.upstream2 {
        make_git_repo(&upstream2, &[("README", "second upstream\n")], "upstream: initial");
    }
    let recipe: Vec<(&str, String)> =
        corpus.recipe_files.iter().map(|(n, b)| (n.as_str(), substitute(b, &subs))).collect();
    make_git_repo(&aur, &recipe.iter().map(|(n, b)| (*n, b.as_str())).collect::<Vec<_>>(), "initial");

    let pristine = Pristine {
        aur,
        upstream,
        upstream2,
        recipe_files: corpus.recipe_files,
        data_files: corpus.data_files,
        path_dependent,
    };
    cache.insert(name.to_string(), pristine.clone());
    pristine
}

fn substitute(body: &str, subs: &[(String, String)]) -> String {
    subs.iter().fold(body.to_string(), |b, (from, to)| b.replace(from, to))
}

fn copy_tree(from: &Path, to: &Path) {
    std::fs::create_dir_all(to).unwrap();
    for entry in std::fs::read_dir(from).unwrap() {
        let entry = entry.unwrap();
        let path = entry.path();
        let name = entry.file_name();
        // A git lock is a claim, not content: a copied `index.lock` would make
        // the copy refuse to run at all.
        if name.to_string_lossy().ends_with(".lock") {
            continue;
        }
        let target = to.join(name);
        if entry.file_type().unwrap().is_dir() {
            copy_tree(&path, &target);
        } else {
            std::fs::copy(&path, &target)
                .unwrap_or_else(|e| panic!("copying {} to {}: {e}", path.display(), target.display()));
        }
    }
}

pub struct Fixture {
    pub name: String,
    pub src: PathBuf,
    pub aur: PathBuf,
    pub data: PathBuf,
    pub manifest: PathBuf,
    pub upstream: Option<PathBuf>,
    pub upstream2: Option<PathBuf>,
}

impl Fixture {
    pub fn bump(&self, changes: &[(&str, &str)]) -> String {
        let path = self.aur.join("PKGBUILD");
        let text = std::fs::read_to_string(&path).unwrap();
        let mut out = String::new();
        for line in text.lines() {
            let key = line.split('=').next().unwrap_or("").to_string();
            match changes.iter().find(|(k, _)| *k == key) {
                Some((_, v)) => {
                    let _ = writeln!(out, "{key}={v}");
                }
                None => out.push_str(line),
            }
            out.push('\n');
        }
        std::fs::write(&path, out).unwrap();
        git(&self.aur, &["add", "-A"]);
        git(&self.aur, &["commit", "-q", "-m", "bump"]);
        git(&self.aur, &["rev-parse", "HEAD"])
    }

    pub fn swap_payload(&self, body: &str) {
        for f in ["payload.bin", "data.bin"] {
            let p = self.data.join(f);
            if p.exists() {
                std::fs::write(p, body).unwrap();
                return;
            }
        }
        panic!("fixture {} has no payload file", self.name);
    }

    pub fn upstream_commit(&self, body: &str) -> String {
        let up = self.upstream.clone().expect("fixture has no upstream repo");
        git_add_commit(&up, &[("README", body)], body);
        git(&up, &["rev-parse", "HEAD"])
    }

    pub fn upstream_head(&self) -> String {
        let up = self.upstream.clone().expect("fixture has no upstream repo");
        git(&up, &["rev-parse", "HEAD"])
    }

    pub fn upstream2_head(&self) -> String {
        let up = self.upstream2.clone().expect("fixture has no second upstream repo");
        git(&up, &["rev-parse", "HEAD"])
    }

    pub fn manifest_json(&self) -> serde_json::Value {
        serde_json::from_str(&std::fs::read_to_string(&self.manifest).unwrap()).unwrap()
    }
}

pub fn pkgbuild(pkgbase: &str, pkgver: &str, pkgrel: &str, extra: &str) -> String {
    format!(
        "pkgbase={pkgbase}\npkgver={pkgver}\npkgrel={pkgrel}\npkgdesc=test\narch=(x86_64)\nurl=https://example.invalid\nlicense=(MIT)\n{extra}\nbuild() {{ :\n}}\npackage_{pkgbase}() {{ :\n}}\n"
    )
}

pub fn make_git_repo(dir: &Path, files: &[(&str, &str)], msg: &str) -> String {
    std::fs::create_dir_all(dir).unwrap();
    git(dir, &["init", "-q", "-b", "master"]);
    for (name, body) in files {
        let p = dir.join(name);
        if let Some(parent) = p.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(p, body).unwrap();
    }
    git(dir, &["add", "-A"]);
    git(dir, &["commit", "-q", "-m", msg]);
    head_of(dir)
}

/// The tip without spawning `git rev-parse`: a repo this file made has one branch
/// and one commit, so the ref file is the answer.
pub fn head_of(dir: &Path) -> String {
    std::fs::read_to_string(dir.join(".git/refs/heads/master"))
        .or_else(|_| std::fs::read_to_string(dir.join(".git/HEAD")))
        .expect("ref")
        .trim()
        .to_string()
}

pub fn git_add_commit(dir: &Path, files: &[(&str, &str)], msg: &str) -> String {
    for (name, body) in files {
        std::fs::write(dir.join(name), body).unwrap();
    }
    git(dir, &["add", "-A"]);
    git(dir, &["commit", "-q", "-m", msg]);
    head_of(dir)
}

pub fn git(dir: &Path, args: &[&str]) -> String {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(dir)
        // A detached maintenance run outlives the command that spawned it and
        // can repack or lock a repo another test is still copying.
        .args(["-c", "maintenance.auto=false", "-c", "gc.auto=0"])
        .args(args)
        .env("GIT_AUTHOR_NAME", "t")
        .env("GIT_AUTHOR_EMAIL", "t@example.invalid")
        .env("GIT_COMMITTER_NAME", "t")
        .env("GIT_COMMITTER_EMAIL", "t@example.invalid")
        .output()
        .expect("git");
    assert!(out.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&out.stderr));
    String::from_utf8_lossy(&out.stdout).trim().to_string()
}

pub struct Web {
    pub env: Env,
    pub fx: Fixture,
    pub server: aur_build::http::Server,
    pub cookie: String,
    pub csrf: String,
}

pub struct Page {
    pub status: u16,
    pub body: String,
}

impl Web {
    pub fn new(name: &str) -> Self {
        Self::with_password(name, "")
    }

    pub fn with_password(name: &str, password: &str) -> Self {
        let (mut env, fx) = env_with_fixture(name);
        env.cfg.password = password.into();
        Self::attach(env, fx)
    }

    pub fn attach(mut env: Env, fx: Fixture) -> Self {
        env.cfg.bind = "127.0.0.1:0".into();
        let server = aur_build::http::spawn(env.cfg.clone(), env.db.clone()).unwrap();
        let mut web = Self { env, fx, server, cookie: String::new(), csrf: String::new() };
        let first = web.raw_get("/");
        web.cookie = first
            .0
            .iter()
            .find(|(k, _)| k == "set-cookie")
            .and_then(|(_, v)| v.split(';').next().map(std::string::ToString::to_string))
            .unwrap_or_default();
        let body = web.get("/");
        web.csrf = extract(&body.body, "name=\"csrf\" content=\"", "\"").unwrap_or_default();
        web
    }

    pub fn open_review(&self, name: &str) -> aur_build::db::model::CandidateRow {
        aur_build::watch::detect::check_pkgbase(&self.env.cfg, &self.env.db, name).unwrap();
        let c = aur_build::review::candidates::pending_candidates(&self.env.db).unwrap().remove(0);
        aur_build::review::diff::render_and_store(&self.env.db, &self.env.cfg, &c).unwrap();
        aur_build::review::candidates::candidate_by_id(&self.env.db, c.id).unwrap().unwrap()
    }

    pub fn publish(&self, name: &str) {
        let c = self.open_review(name);
        aur_build::review::approve::approve(&self.env.db, "test", c.id, &c.identity_hash, &c.diff_digest, None)
            .unwrap();
        let c = aur_build::review::candidates::candidate_by_id(&self.env.db, c.id).unwrap().unwrap();
        let id = aur_build::pipeline::enqueue_for_candidate(&self.env.cfg, &self.env.db, &c).unwrap();
        aur_build::pipeline::run(&self.env.cfg, &self.env.db, &id).unwrap();
    }

    pub fn url(&self, path: &str) -> String {
        format!("http://{}{}", self.server.addr, path)
    }

    pub fn raw_get(&self, path: &str) -> (Vec<(String, String)>, String) {
        let resp = ureq::get(&self.url(path)).set("Cookie", &self.cookie).call();
        let r = match resp {
            Ok(r) => r,
            Err(ureq::Error::Status(_, r)) => r,
            Err(e) => panic!("GET {path}: {e}"),
        };
        let cookie = r.header("set-cookie").map_or_default(std::string::ToString::to_string);
        let mut headers = vec![("set-cookie".to_string(), cookie)];
        for name in ["content-type", "content-encoding", "location"] {
            if let Some(v) = r.header(name) {
                headers.push((name.to_string(), v.to_string()));
            }
        }
        (headers, r.into_string().unwrap_or_default())
    }

    pub fn get(&self, path: &str) -> Page {
        let resp = ureq::get(&self.url(path)).set("Cookie", &self.cookie).call();
        Self::finish(resp, path)
    }

    pub fn post(&self, path: &str, form: &[(&str, &str)]) -> Page {
        let resp = ureq::post(&self.url(path)).set("Cookie", &self.cookie).send_form(form);
        Self::finish(resp, path)
    }

    pub fn post_bare(&self, path: &str, form: &[(&str, &str)]) -> Page {
        let resp = ureq::post(&self.url(path)).set("Cookie", &self.cookie).send_form(form);
        Self::finish(resp, path)
    }

    pub fn raw_request(&self, method: &str, path: &str, headers: &[(&str, String)], body: Option<&str>) -> Raw {
        use std::io::{Read, Write};
        let addr = self.server.addr.clone();
        let mut sock = std::net::TcpStream::connect(&addr).unwrap();
        let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n");
        for (k, v) in headers {
            let _ = writeln!(req, "{k}: {v}\r");
        }
        match body {
            Some(b) => {
                req.push_str("Content-Type: application/x-www-form-urlencoded\r\n");
                let _ = writeln!(req, "Content-Length: {}\r", b.len());
                req.push_str("\r\n");
                req.push_str(b);
            }
            None => req.push_str("\r\n"),
        }
        sock.write_all(req.as_bytes()).unwrap();
        let mut raw = Vec::new();
        sock.read_to_end(&mut raw).unwrap();
        Raw::parse(&raw)
    }

    pub fn login(&mut self, password: &str) -> Raw {
        let raw = self.raw_request("POST", "/login", &[], Some(&format!("password={}", url_encode(password))));
        if let Some(cookie) = raw.cookie() {
            self.cookie = cookie;
        }
        let page = self.get("/");
        self.csrf = extract(&page.body, "name=\"csrf\" content=\"", "\"").unwrap_or_default();
        raw
    }

    fn finish(resp: Result<ureq::Response, ureq::Error>, path: &str) -> Page {
        match resp {
            Ok(r) => Page { status: r.status(), body: r.into_string().unwrap_or_default() },
            Err(ureq::Error::Status(code, r)) => Page { status: code, body: r.into_string().unwrap_or_default() },
            Err(e) => panic!("{path}: {e}"),
        }
    }
}

pub struct Raw {
    pub status: u16,
    pub headers: Vec<(String, String)>,
    pub body: String,
}

impl Raw {
    fn parse(raw: &[u8]) -> Self {
        let split = raw.windows(4).position(|w| w == b"\r\n\r\n").unwrap_or(raw.len());
        let head = String::from_utf8_lossy(&raw[..split]).to_string();
        let mut lines = head.lines();
        let status = lines.next().and_then(|l| l.split_whitespace().nth(1)).and_then(|s| s.parse().ok()).unwrap_or(0);
        let headers = lines
            .filter_map(|l| l.split_once(':'))
            .map(|(k, v)| (k.trim().to_lowercase(), v.trim().to_string()))
            .collect();
        Self { status, headers, body: String::from_utf8_lossy(&raw[split.min(raw.len())..]).to_string() }
    }

    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
    }

    pub fn cookie(&self) -> Option<String> {
        self.header("set-cookie")
            .map(|v| v.split(';').next().unwrap_or("").to_string())
            .filter(|v| !v.is_empty() && v.contains('='))
    }
}

fn url_encode(s: &str) -> String {
    s.bytes()
        .map(|b| match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
            b' ' => "+".into(),
            _ => format!("%{b:02X}"),
        })
        .collect()
}

pub fn extract(hay: &str, open: &str, close: &str) -> Option<String> {
    let i = hay.find(open)? + open.len();
    let rest = &hay[i..];
    let j = rest.find(close)?;
    Some(unescape(&rest[..j]))
}

fn unescape(s: &str) -> String {
    s.replace("&amp;", "&").replace("&quot;", "\"").replace("&lt;", "<").replace("&gt;", ">").replace("&#39;", "'")
}