summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: 118d06ea9bfc7ee9b519bc178f423de89a1216e2 (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
use std::path::PathBuf;

use clap::{Parser, Subcommand};

use aur_build::config::Config;
use aur_build::db::{self, builds, model::*};
use aur_build::pipeline;
use aur_build::review::candidates;
use aur_build::usecase;

#[derive(Parser)]
#[command(name = "aur-build", version, about = "AUR build server: nothing is published that a human did not approve")]
struct Cli {
    #[arg(short, long, env = "AUR_BUILD_ROOT", global = true)]
    root: Option<PathBuf>,
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    Init {
        #[arg(long)]
        repo: Option<String>,
        #[arg(long)]
        signing_key: Option<String>,
    },
    Subscribe {
        pkgbase: String,
        #[arg(long)]
        url: Option<String>,
    },
    Unsubscribe { pkgbase: String },
    Detect { pkgbase: Option<String> },
    Reviews {
        #[arg(long)]
        all: bool,
    },
    Show { candidate: i64 },
    Approve {
        candidate: i64,
        #[arg(long)]
        yes: bool,
        #[arg(long)]
        note: Option<String>,
        #[arg(long)]
        identity: Option<String>,
        #[arg(long)]
        diff: Option<String>,
    },
    Reject {
        candidate: i64,
        #[arg(long)]
        note: String,
    },
    Build { candidate: i64 },
    Rebuild { pkgbase: String },
    Run { build: String },
    Builds,
    Status { build: String },
    Packages,
    Serve {
        #[arg(long)]
        bind: Option<String>,
    },
    Audit {
        #[arg(long, default_value_t = 30)]
        limit: i64,
    },
    Metrics,
    Gc {
        #[arg(long)]
        keep: Option<usize>,
        #[arg(long)]
        dry_run: bool,
    },
    Backup {
        to: PathBuf,
    },
}

fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();
    let root = cli.root.clone().unwrap_or_else(|| Config::default().root);
    let cfg = if matches!(cli.cmd, Cmd::Init { .. }) {
        Config::load(&root).unwrap_or_else(|_| Config {
            root: root.clone(),
            ..Config::default()
        })
    } else {
        Config::load(&root)?
    };
    cfg.validate()?;
    if let Cmd::Serve { bind } = &cli.cmd {
        let mut cfg = cfg;
        if let Some(b) = bind {
            cfg.bind = b.clone();
        }
        let db = usecase::serve(&cfg)?;
        // Starting the UI is the composition root's job: nothing below it may
        // know the UI exists.
        let _server = aur_build::http::spawn(cfg.clone(), db)?;
        println!("serving on http://{} — ctrl-c to stop", cfg.bind);
        loop {
            std::thread::sleep(std::time::Duration::from_secs(3600));
        }
    }
    let ctx = Ctx::open(&cfg)?;
    match cli.cmd {
        Cmd::Serve { .. } => Ok(()),
        Cmd::Init { repo, signing_key } => {
            let mut cfg = cfg;
            if let Some(r) = repo {
                cfg.repo_name = r;
            }
            if let Some(k) = signing_key {
                cfg.signing_key_id = k;
            }
            let rid = usecase::init(&cfg)?;
            println!("initialized {} (repo id {rid})", cfg.root.display());
            println!("add to pacman.conf:\n  [{}]\n  Server = {}/$repo/os/$arch", cfg.repo_name, cfg.base_url);
            Ok(())
        }
        Cmd::Subscribe { pkgbase, url } => {
            let s = usecase::subscribe(&ctx.db, &pkgbase, url)?;
            println!("subscribed {} ({})", s.pkgbase, s.url);
            Ok(())
        }
        Cmd::Unsubscribe { pkgbase } => {
            usecase::unsubscribe(&ctx.db, &pkgbase)?;
            println!("unsubscribed {pkgbase}");
            Ok(())
        }
        Cmd::Detect { pkgbase } => {
            for c in usecase::detect(&cfg, &ctx.db, pkgbase)? {
                match c.outcome {
                    Ok(o) => println!("{}: {:?}", c.pkgbase, o),
                    Err(e) => eprintln!("{}: {e}", c.pkgbase),
                }
            }
            Ok(())
        }
        Cmd::Reviews { all } => {
            let rows = if all {
                candidates::all_candidates(&ctx.db)?
            } else {
                candidates::pending_candidates(&ctx.db)?
            };
            if rows.is_empty() {
                println!("nothing pending");
            }
            for c in rows {
                println!(
                    "#{:<5} {:<28} {:<16} {:<10} rev{} {}",
                    c.id,
                    c.pkgbase,
                    aur_build::pkgver::full_version(&c.epoch, &c.pkgver, &c.pkgrel),
                    c.kind,
                    c.revision,
                    c.state
                );
            }
            Ok(())
        }
        Cmd::Show { candidate } => {
            let Some(p) = usecase::view_review(&cfg, &ctx.db, candidate)? else {
                return Err(anyhow::anyhow!("no candidate #{candidate}"));
            };
            println!("{}", p.text);
            println!("---");
            println!("identity_hash: {}", p.candidate.identity_hash);
            println!("diff_digest:   {}", p.digest);
            println!("approve with:  aur-build approve {} --yes", p.candidate.id);
            Ok(())
        }
        Cmd::Approve { candidate, yes, note, identity, diff: diff_arg } => {
            let Some(p) = usecase::prepare_review(&cfg, &ctx.db, candidate)? else {
                return Err(anyhow::anyhow!("no candidate #{candidate}"));
            };
            let identity = identity.unwrap_or_else(|| p.candidate.identity_hash.clone());
            let diff_arg = diff_arg.unwrap_or(p.digest);
            println!("{}", p.text);
            println!("---");
            if !yes {
                println!("not approved: re-run with --yes to approve exactly this");
                return Ok(());
            }
            let who = whoami();
            match usecase::approve(&cfg, &ctx.db, &who, &p.candidate, &identity, &diff_arg, note.as_deref())? {
                usecase::Approval::Recorded(a) => {
                    println!("approved #{} (approval {})", p.candidate.id, a.approval.id);
                    let id = a.queued?;
                    println!("queued build {id}");
                    println!("run it with:  aur-build run {id}");
                    Ok(())
                }
                usecase::Approval::Refused(stale) => {
                    eprintln!("refused: {stale}");
                    std::process::exit(2)
                }
            }
        }
        Cmd::Reject { candidate, note } => {
            let who = whoami();
            usecase::reject(&ctx.db, &who, candidate, &note)?;
            println!("rejected #{candidate}");
            Ok(())
        }
        Cmd::Build { candidate } => {
            let Some(c) = candidates::candidate_by_id(&ctx.db, candidate)? else {
                return Err(anyhow::anyhow!("no candidate #{candidate}"));
            };
            let id = usecase::enqueue_candidate(&cfg, &ctx.db, &c)?;
            println!("queued build {id}");
            Ok(())
        }
        Cmd::Rebuild { pkgbase } => {
            let id = usecase::manual_rebuild(&cfg, &ctx.db, &pkgbase)?;
            println!("queued rebuild {id}");
            Ok(())
        }
        Cmd::Run { build } => match pipeline::run(&cfg, &ctx.db, &build)? {
            pipeline::Outcome::Succeeded { release_id } => {
                println!("succeeded (release {release_id})");
                Ok(())
            }
            pipeline::Outcome::Blocked { on } => {
                println!("blocked on: {}", on.join(", "));
                std::process::exit(3)
            }
            pipeline::Outcome::Cancelled => {
                println!("cancelled");
                std::process::exit(0)
            }
            pipeline::Outcome::Failed { step, error, .. } => {
                eprintln!("failed at {step}: {error}");
                std::process::exit(1)
            }
        },
        Cmd::Builds => {
            for b in builds::list(&ctx.db, BuildState::active(), 50)? {
                println!("{:<66} {:<20} {}", b.id, b.state, b.current_step.unwrap_or_default());
            }
            Ok(())
        }
        Cmd::Status { build } => {
            for s in builds::steps(&ctx.db, &build)? {
                println!("{:<12} {:<12} {}", s.step, s.status, s.error.unwrap_or_default());
            }
            Ok(())
        }
        Cmd::Packages => {
            for p in db::index_packages(&ctx.db)? {
                println!("{:<28} {:<16} {}", p.name, p.version, p.arch);
            }
            Ok(())
        }
        Cmd::Audit { limit } => {
            for a in db::list_audit(&ctx.db, limit)? {
                println!("{} [{}] {} {} {} {}", a.at, a.actor_kind, a.actor, a.action, a.entity_id, a.detail_json);
            }
            Ok(())
        }
        Cmd::Metrics => {
            print!("{}", aur_build::ops::metrics(&cfg, &ctx.db)?.to_prometheus());
            Ok(())
        }
        Cmd::Gc { keep, dry_run } => {
            if dry_run {
                let plan = usecase::plan_gc(&cfg, &ctx.db, keep)?;
                println!("retention: keep {} version(s) per pkgbase", plan.keep);
                println!("  {} release(s) keep their files", plan.kept);
                for (release_id, files) in plan.evicting {
                    println!("  release {} would lose {} file(s)", release_id, files.len());
                    for f in files {
                        println!("    {}", f.display());
                    }
                }
                return Ok(());
            }
            let r = usecase::run_gc(&cfg, &ctx.db, keep)?;
            println!(
                "kept {} release(s), evicted {}, removed {} file(s), freed {} bytes, swept {} staging dir(s)",
                r.releases_kept, r.releases_evicted, r.files_removed, r.bytes_freed, r.staging_swept
            );
            Ok(())
        }
        Cmd::Backup { to } => {
            let path = usecase::backup(&ctx.db, &to)?;
            println!(
                "wrote {} bytes to {} (VACUUM INTO, single file, no WAL)",
                std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0),
                path.display()
            );
            Ok(())
        }
    }
}

struct Ctx {
    db: db::Db,
}

impl Ctx {
    fn open(cfg: &Config) -> anyhow::Result<Self> {
        Ok(Self { db: usecase::open(cfg)? })
    }
}

fn whoami() -> String {
    std::env::var("USER").or_else(|_| std::env::var("USERNAME")).unwrap_or_else(|_| "cli".into())
}