OXYGENHUB
◆ v0.5.0 oxygenhub / crates / hub / src / web / proposals.rs
73.2 KiB · Rust · last changed UI polish: keys, backups, wiki, editor, bookmarks, summaries, backdrops 22 days ago source blame history raw
de505df5 Andy McCall ↶ 1
//! Proposal pages (hub spec §7): list, new, detail with conversation,
2
//! changes and files, comments anchored to atoms, reviews, landing.
3
4
use super::history::{render_files, FileRows};
5
use super::settings::{csrf, require};
6
use super::{filters, lookup, lookup_role, Error, Page, RepoShell, Shell};
7
use crate::auth::{Access, Role, Viewer};
8
use crate::db::{self, accounts, proposals as pdb};
9
use crate::render::{self, diff};
10
use crate::repos::proposals::{self as pl, Projection, Source};
11
use crate::repos::view::{self, ChangeView, ConflictView};
12
use crate::repos::RepoName;
13
use crate::Shared;
14
use askama::Template;
15
use axum::extract::{Form, Path, Query, State};
16
use axum::response::{IntoResponse, Redirect, Response};
17
use hub_api::{Approval, ProposalSource, ProposalState};
18
use oxy_core::hash::ChangeHash;
19
use serde::Deserialize;
20
use std::collections::{BTreeMap, HashMap};
21
22
// ------------------------------------------------------------------ list
23
24
#[derive(Template)]
25
#[template(path = "proposals.html")]
26
pub struct ProposalsPage {
27
    shell: Shell,
28
    repo: RepoShell,
29
    rows: Vec<pdb::ProposalRow>,
30
    filter: String,
31
    counts: (usize, usize, usize),
32
    bookmarks: Vec<String>,
1ac84c62 Andy McCall ↶ 33
    q: String,
34
    sort: String,
35
    pager: super::Pager,
36
    labels: std::collections::HashMap<i64, Vec<db::issues::Label>>,
de505df5 Andy McCall ↶ 37
}
38
1ac84c62 Andy McCall ↶ 39
impl ProposalsPage {
40
    fn labels_of(&self, id: &i64) -> &[db::issues::Label] {
41
        self.labels.get(id).map(Vec::as_slice).unwrap_or(&[])
42
    }
43
}
44
de505df5 Andy McCall ↶ 45
#[derive(Deserialize)]
46
pub struct ListQuery {
47
    state: Option<String>,
1ac84c62 Andy McCall ↶ 48
    q: Option<String>,
49
    sort: Option<String>,
50
    page: Option<usize>,
de505df5 Andy McCall ↶ 51
}
52
1ac84c62 Andy McCall ↶ 53
/// The list's sort orders.
54
pub const SORTS: &[(&str, &str)] = &[("updated", "recently updated"), ("newest", "newest"), ("oldest", "oldest")];
55
de505df5 Andy McCall ↶ 56
pub async fn list(
57
    State(app): State<Shared>,
58
    viewer: Viewer,
59
    Path((owner, name)): Path<(String, String)>,
60
    Query(q): Query<ListQuery>,
61
) -> Result<Page<ProposalsPage>, Error> {
62
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposals"), &viewer);
63
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
64
    let all = pdb::list(&app.db, row.id, &[]).await.map_err(|e| Error::from_db(shell.clone(), e))?;
65
    let counts = (
66
        all.iter().filter(|p| p.is_open()).count(),
67
        all.iter().filter(|p| p.state == "landed").count(),
68
        all.iter().filter(|p| p.state == "closed").count(),
69
    );
70
    let filter = q.state.unwrap_or_else(|| "open".into());
1ac84c62 Andy McCall ↶ 71
    let mut labels: std::collections::HashMap<i64, Vec<db::issues::Label>> = std::collections::HashMap::new();
72
    for (id, l) in db::issues::labels_by_proposal(&app.db, row.id).await.map_err(|e| Error::from_db(shell.clone(), e))? {
73
        labels.entry(id).or_default().push(l);
74
    }
75
    // `author:bob label:ui target:main words…`
76
    let qtext = q.q.clone().unwrap_or_default();
77
    let (mut authors, mut wanted, mut targets, mut words) = (vec![], vec![], vec![], vec![]);
78
    for tok in qtext.split_whitespace() {
79
        match tok.split_once(':') {
80
            Some(("author", v)) => authors.push(v.to_lowercase()),
81
            Some(("label", v)) => wanted.push(v.to_lowercase()),
82
            Some(("target", v)) => targets.push(v.to_string()),
83
            _ => words.push(tok.to_lowercase()),
84
        }
85
    }
86
    let mut rows: Vec<pdb::ProposalRow> = all
de505df5 Andy McCall ↶ 87
        .into_iter()
88
        .filter(|p| match filter.as_str() {
89
            "open" => p.is_open(),
90
            "landed" => p.state == "landed",
91
            "closed" => p.state == "closed",
92
            _ => true,
93
        })
1ac84c62 Andy McCall ↶ 94
        .filter(|p| authors.is_empty() || authors.contains(&p.author.to_lowercase()))
95
        .filter(|p| targets.is_empty() || targets.contains(&p.target))
96
        .filter(|p| wanted.iter().all(|w| labels.get(&p.id).is_some_and(|ls| ls.iter().any(|l| l.name.to_lowercase() == *w))))
97
        .filter(|p| words.iter().all(|w| p.title.to_lowercase().contains(w) || p.body.to_lowercase().contains(w)))
de505df5 Andy McCall ↶ 98
        .collect();
1ac84c62 Andy McCall ↶ 99
    let sort = q.sort.filter(|s| SORTS.iter().any(|(k, _)| k == s)).unwrap_or_else(|| "updated".into());
100
    match sort.as_str() {
101
        "newest" => rows.sort_by_key(|p| std::cmp::Reverse(p.number)),
102
        "oldest" => rows.sort_by_key(|p| p.number),
103
        _ => rows.sort_by_key(|p| std::cmp::Reverse(p.updated_ms)),
104
    }
105
    let pager = super::Pager::new(rows.len(), q.page, &[("state", &filter), ("q", &qtext), ("sort", &sort)]);
106
    let rows = pager.slice(rows);
de505df5 Andy McCall ↶ 107
    let bookmarks = app
108
        .repos
109
        .read(&repo, |r, _| Ok(r.bookmarks()?.into_iter().map(|b| b.name).collect::<Vec<_>>()))
110
        .await
111
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
1ac84c62 Andy McCall ↶ 112
    Ok(Page(ProposalsPage {
113
        shell,
114
        repo: RepoShell::new(&app, &row, "proposals").with_role(role),
115
        rows,
116
        filter,
117
        counts,
118
        bookmarks,
119
        q: qtext,
120
        sort,
121
        pager,
122
        labels,
123
    }))
de505df5 Andy McCall ↶ 124
}
125
126
// ------------------------------------------------------------------- new
127
128
#[derive(Template)]
129
#[template(path = "proposal_new.html")]
130
pub struct NewProposalPage {
131
    shell: Shell,
132
    repo: RepoShell,
133
    bookmarks: Vec<String>,
134
    source: String,
135
    target: String,
136
    error: Option<String>,
137
    /// Preview: the changes the proposal would add.
138
    preview: Vec<ChangeView>,
139
    conflicted: bool,
7d2eb590 Andy McCall ↶ 140
    /// What the form holds so far (after a failed open, or a draft).
141
    title: String,
142
    body: String,
143
    /// AI assistants that may draft the description (hub spec §13.4).
144
    assistants: Vec<String>,
de505df5 Andy McCall ↶ 145
}
146
147
#[derive(Deserialize)]
148
pub struct NewQuery {
149
    source: Option<String>,
150
    target: Option<String>,
151
}
152
153
/// `owner/name:bookmark` for a fork, else a bookmark of this repository.
0b20f1ec Andy McCall ↶ 154
/// A proposal's source: a bookmark of this repository by name (which may
155
/// hold `/`, as `feature/16-hud` does), or `owner/name:bookmark` of a fork;
156
/// `owner/name:bookmark` naming this repository is its own bookmark.
de505df5 Andy McCall ↶ 157
fn parse_source(app: &Shared, repo: &RepoName, source: &str) -> Option<(Option<RepoName>, String)> {
0b20f1ec Andy McCall ↶ 158
    let plain = |b: &str| !b.is_empty() && !b.chars().any(|c| c.is_control() || c == ':');
de505df5 Andy McCall ↶ 159
    if let Some((slug, bookmark)) = source.split_once(':') {
160
        let fork = RepoName::parse(slug)?;
0b20f1ec Andy McCall ↶ 161
        if !plain(bookmark) {
de505df5 Andy McCall ↶ 162
            return None;
0b20f1ec Andy McCall ↶ 163
        }
164
        if fork == *repo {
165
            return Some((None, bookmark.to_string()));
de505df5 Andy McCall ↶ 166
        }
0b20f1ec Andy McCall ↶ 167
        if !app.repos.exists(&fork) {
168
            return None;
169
        }
de505df5 Andy McCall ↶ 170
        return Some((Some(fork), bookmark.to_string()));
171
    }
0b20f1ec Andy McCall ↶ 172
    plain(source).then(|| (None, source.to_string()))
de505df5 Andy McCall ↶ 173
}
174
175
async fn preview_for(
176
    app: &Shared,
177
    repo: &RepoName,
178
    target: &str,
179
    source: &str,
180
) -> Result<(Vec<ChangeView>, bool), crate::repos::RepoError> {
181
    let Some((fork, bookmark)) = parse_source(app, repo, source) else { return Ok((vec![], false)) };
182
    let target = target.to_string();
183
    let fork_dir = fork.as_ref().map(|f| app.repos.dir(f));
184
    app.repos
185
        .read(repo, move |r, cache| {
186
            let projection = match &fork_dir {
187
                Some(dir) => {
188
                    let fork_repo = oxy_core::repo::Repo::open(dir)?;
189
                    let heads = fork_repo.bookmarks()?.into_iter().find(|b| b.name == bookmark).map(|b| b.heads).unwrap_or_default();
190
                    pl::project(r, cache, &target, Source::Fork { fork: &fork_repo, heads })?
191
                }
192
                None => {
193
                    let heads = r.bookmarks()?.into_iter().find(|b| b.name == bookmark).map(|b| b.heads).unwrap_or_default();
194
                    pl::project(r, cache, &target, Source::Bookmark(heads))?
195
                }
196
            };
197
            Ok((projection.changes, projection.conflicted))
198
        })
199
        .await
200
}
201
202
pub async fn new_form(
203
    State(app): State<Shared>,
204
    viewer: Viewer,
205
    Path((owner, name)): Path<(String, String)>,
206
    Query(q): Query<NewQuery>,
207
) -> Result<Page<NewProposalPage>, Error> {
208
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposals/new"), &viewer);
209
    require(&viewer, &shell)?;
210
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
211
    let bookmarks = app
212
        .repos
213
        .read(&repo, |r, _| Ok(r.bookmarks()?.into_iter().map(|b| b.name).collect::<Vec<_>>()))
214
        .await
215
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
216
    let target = q.target.unwrap_or_else(|| row.default_bookmark.clone());
217
    let source = q.source.unwrap_or_default();
218
    let (preview, conflicted) =
219
        if source.is_empty() { (vec![], false) } else { preview_for(&app, &repo, &target, &source).await.unwrap_or((vec![], false)) };
7d2eb590 Andy McCall ↶ 220
    let assistants = if preview.is_empty() { vec![] } else { assistant_names(&app, &row).await };
de505df5 Andy McCall ↶ 221
    Ok(Page(NewProposalPage {
222
        shell,
223
        repo: RepoShell::new(&app, &row, "proposals").with_role(role),
224
        bookmarks,
225
        source,
226
        target,
227
        error: None,
228
        preview,
229
        conflicted,
7d2eb590 Andy McCall ↶ 230
        title: String::new(),
231
        body: String::new(),
232
        assistants,
de505df5 Andy McCall ↶ 233
    }))
234
}
235
236
#[derive(Deserialize)]
237
pub struct NewForm {
238
    #[serde(rename = "_csrf")]
239
    csrf_token: String,
240
    title: String,
241
    #[serde(default)]
242
    body: String,
243
    target: String,
244
    source: String,
245
    #[serde(default)]
246
    draft: Option<String>,
7d2eb590 Andy McCall ↶ 247
    /// For `/proposals/new/draft`: which assistant writes the description.
248
    #[serde(default)]
249
    assistant: String,
de505df5 Andy McCall ↶ 250
}
251
b64e2537 Andy McCall ↶ 252
/// Open a proposal from a form or the API: validate, create, index, notify.
253
#[allow(clippy::too_many_arguments)]
254
pub async fn open_proposal(
255
    app: &Shared,
256
    repo: &RepoName,
257
    row: &db::repos::RepoRow,
258
    me: &accounts::Account,
259
    title: &str,
260
    body: &str,
261
    target: &str,
262
    source: &str,
263
    draft: bool,
264
) -> Result<pdb::ProposalRow, String> {
265
    if title.trim().is_empty() {
266
        return Err("Give the proposal a title.".into());
de505df5 Andy McCall ↶ 267
    }
b64e2537 Andy McCall ↶ 268
    let bookmarks =
269
        app.repos.read(repo, |r, _| Ok(r.bookmarks()?.into_iter().map(|b| b.name).collect::<Vec<_>>())).await.map_err(|e| e.to_string())?;
270
    if !bookmarks.iter().any(|b| b == target) {
271
        return Err("Pick a target bookmark of this repository.".into());
de505df5 Andy McCall ↶ 272
    }
b64e2537 Andy McCall ↶ 273
    let Some((fork, bookmark)) = parse_source(app, repo, source.trim()) else {
274
        return Err("The source is a bookmark of this repository, or owner/name:bookmark of a fork.".into());
de505df5 Andy McCall ↶ 275
    };
0b20f1ec Andy McCall ↶ 276
    if fork.is_none() && !bookmarks.contains(&bookmark) {
277
        return Err(format!("There is no bookmark {bookmark} in this repository."));
278
    }
b64e2537 Andy McCall ↶ 279
    if fork.is_none() && bookmark == target {
280
        return Err("The source and the target are the same bookmark.".into());
de505df5 Andy McCall ↶ 281
    }
b64e2537 Andy McCall ↶ 282
    let (preview, _) = preview_for(app, repo, target, source.trim()).await.map_err(|e| e.to_string())?;
de505df5 Andy McCall ↶ 283
    if preview.is_empty() {
b64e2537 Andy McCall ↶ 284
        return Err("The source adds nothing to the target.".into());
de505df5 Andy McCall ↶ 285
    }
286
    let source_repo_id = match &fork {
b64e2537 Andy McCall ↶ 287
        Some(fk) => db::repos::get(&app.db, &fk.owner, &fk.name).await.map_err(|e| e.to_string())?.map(|r| r.id),
de505df5 Andy McCall ↶ 288
        None => None,
289
    };
290
    let created = pdb::create(
291
        &app.db,
292
        pdb::NewProposal {
293
            repo_id: row.id,
b64e2537 Andy McCall ↶ 294
            title: title.trim(),
295
            body: body.trim(),
296
            author_id: Some(me.id),
297
            author: &me.username,
298
            draft,
299
            target,
de505df5 Andy McCall ↶ 300
            source_kind: if fork.is_some() { "fork" } else { "bookmark" },
301
            source_repo_id,
302
            source_bookmark: &bookmark,
303
            source_changes: "",
304
        },
305
    )
306
    .await
b64e2537 Andy McCall ↶ 307
    .map_err(|e| e.to_string())?;
308
    pdb::add_event(&app.db, created.id, &me.username, "opened", "").await.ok();
309
    accounts::audit(&app.db, Some(me), "proposal.opened", &format!("{}#{}", row.slug(), created.number), title).await.ok();
18e381ea Andy McCall ↶ 310
    db::notify::index(&app.db, "proposal", row.id, created.id, created.number, &created.title, &created.body).await.ok();
b64e2537 Andy McCall ↶ 311
    let url = format!("/{}/proposal/{}", row.slug(), created.number);
18e381ea Andy McCall ↶ 312
    crate::notify::deliver(
b64e2537 Andy McCall ↶ 313
        app,
18e381ea Andy McCall ↶ 314
        crate::notify::Event {
315
            kind: "proposal.opened",
b64e2537 Andy McCall ↶ 316
            title: format!("{}#{}: {}", row.slug(), created.number, created.title),
317
            url,
318
            actor: me,
18e381ea Andy McCall ↶ 319
            repo_id: row.id,
320
            thread: Some(("proposal", created.id)),
b64e2537 Andy McCall ↶ 321
            mention_text: body,
18e381ea Andy McCall ↶ 322
            direct: vec![],
323
        },
324
    )
325
    .await;
b64e2537 Andy McCall ↶ 326
    crate::hooks::emit(
327
        app,
328
        row,
329
        "proposal.opened",
330
        &me.username,
331
        serde_json::json!({ "number": created.number, "title": created.title, "target": target, "source": source }),
332
    )
333
    .await;
334
    Ok(created)
335
}
336
337
pub async fn create(
338
    State(app): State<Shared>,
339
    viewer: Viewer,
340
    Path((owner, name)): Path<(String, String)>,
341
    Form(f): Form<NewForm>,
342
) -> Result<Response, Error> {
343
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposals/new"), &viewer);
344
    let me = require(&viewer, &shell)?;
345
    csrf(&viewer, &f.csrf_token, &shell)?;
346
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 347
    super::writable(&row, &shell)?;
b64e2537 Andy McCall ↶ 348
    match open_proposal(&app, &repo, &row, &me.account, &f.title, &f.body, &f.target, &f.source, f.draft.is_some()).await {
349
        Ok(created) => Ok(Redirect::to(&format!("/{owner}/{name}/proposal/{}", created.number)).into_response()),
350
        Err(msg) => {
351
            let bookmarks =
352
                app.repos.read(&repo, |r, _| Ok(r.bookmarks()?.into_iter().map(|b| b.name).collect::<Vec<_>>())).await.unwrap_or_default();
353
            Ok(Page(NewProposalPage {
354
                shell,
355
                repo: RepoShell::new(&app, &row, "proposals").with_role(role),
356
                bookmarks,
357
                source: f.source.clone(),
358
                target: f.target.clone(),
359
                error: Some(msg),
360
                preview: vec![],
361
                conflicted: false,
7d2eb590 Andy McCall ↶ 362
                title: f.title.clone(),
363
                body: f.body.clone(),
364
                assistants: vec![],
b64e2537 Andy McCall ↶ 365
            })
366
            .into_response())
367
        }
368
    }
de505df5 Andy McCall ↶ 369
}
370
371
// ---------------------------------------------------------------- detail
372
373
/// A comment placed on a diff row, or general.
374
pub struct CommentView {
375
    pub row: pdb::CommentRow,
376
    pub body_html: String,
377
    pub line: Option<usize>,
378
}
379
a1b98695 Andy McCall ↶ 380
/// One entry of a proposal's conversation, in time order: what kind it
381
/// is and its index in `comments`, `reviews` or `events`.
382
pub struct Entry {
383
    pub kind: &'static str,
384
    pub index: usize,
385
}
386
de505df5 Andy McCall ↶ 387
pub struct ReviewView {
388
    pub row: pdb::ReviewRow,
389
    pub body_html: String,
390
    pub sealed: bool,
391
}
392
393
/// Everything the detail page and the API need, computed once under the lock.
394
pub struct Loaded {
395
    pub row: pdb::ProposalRow,
396
    pub changes: Vec<ChangeView>,
397
    pub hashes: Vec<ChangeHash>,
398
    pub heads: Vec<ChangeHash>,
3f02e5ea Andy McCall ↶ 399
    pub target_heads: Vec<ChangeHash>,
de505df5 Andy McCall ↶ 400
    pub state: String,
401
    pub target_state: String,
402
    pub conflicted: bool,
403
    pub conflicts: Vec<ConflictView>,
404
    pub files: Vec<FileRows>,
9df855f2 Andy McCall ↶ 405
    /// The per-file hunks and bases behind `files`, to render again with other options.
406
    pub diffs: Vec<oxy_core::repo::FileDiff>,
407
    pub bases: std::collections::BTreeMap<String, Vec<u8>>,
de505df5 Andy McCall ↶ 408
    /// Atom per (path, new line number) of the projected state.
409
    pub atoms: HashMap<(String, usize), (String, u32)>,
410
    pub sealing_keys: Vec<String>,
411
    pub touched: Vec<String>,
412
    pub owners: Vec<String>,
413
    pub landed_already: bool,
ac713df7 Andy McCall ↶ 414
    /// Whether its source has any changes at all (#141): an open proposal
415
    /// whose source has changes, none of them missing from the target, was
416
    /// landed by some other route.
417
    pub source_has_changes: bool,
de505df5 Andy McCall ↶ 418
}
419
420
/// Compute the projection and everything derived from it.
421
pub async fn load(app: &Shared, repo: &RepoName, row: pdb::ProposalRow) -> Result<Loaded, crate::repos::RepoError> {
422
    let fork_dir = match (row.source_kind.as_str(), row.source_repo_id) {
423
        ("fork", Some(id)) => {
424
            db::repos::get_by_id(&app.db, id).await.ok().flatten().and_then(|r| RepoName::new(&r.owner, &r.name)).map(|n| app.repos.dir(&n))
425
        }
426
        _ => None,
427
    };
428
    let r2 = row.clone();
429
    let loaded = app
430
        .repos
431
        .read(repo, move |r, cache| {
432
            let source = match (r2.source_kind.as_str(), &fork_dir) {
433
                ("changes", _) => Source::Changes(r2.source_changes().iter().filter_map(|h| ChangeHash::from_hex(h)).collect()),
434
                ("fork", Some(dir)) => {
435
                    let fork_repo = oxy_core::repo::Repo::open(dir)?;
436
                    let heads =
437
                        fork_repo.bookmarks()?.into_iter().find(|b| b.name == r2.source_bookmark).map(|b| b.heads).unwrap_or_default();
438
                    // Bring the fork's changes over now, so the projection below can read them.
439
                    let fork_state = fork_repo.load_state(&heads)?;
440
                    let missing: Vec<ChangeHash> = fork_state.changes().map(|(h, _)| *h).filter(|h| !r.store().has(h)).collect();
441
                    if !missing.is_empty() {
442
                        r.import_bundle(&fork_repo.bundle_for(&missing)?, r.current_policy()?.is_some())?;
443
                    }
444
                    Source::Changes(heads)
445
                }
446
                _ => {
447
                    let heads = r.bookmarks()?.into_iter().find(|b| b.name == r2.source_bookmark).map(|b| b.heads).unwrap_or_default();
448
                    Source::Bookmark(heads)
449
                }
450
            };
ac713df7 Andy McCall ↶ 451
            let source_has_changes = match &source {
452
                Source::Changes(h) | Source::Bookmark(h) | Source::Fork { heads: h, .. } => !h.is_empty(),
453
            };
de505df5 Andy McCall ↶ 454
            let p: Projection = pl::project(r, cache, &r2.target, source)?;
455
            let target_loaded = cache.load(r, &p.target_heads)?;
456
            let files = render_files(&p.files, &p.bases);
457
            let mut atoms = HashMap::new();
458
            for f in &files {
459
                for l in &f.lines {
460
                    if let Some(n) = l.new_no {
461
                        if let Some((h, i)) = pl::atom_at(&p.loaded, &f.path, n as usize) {
462
                            atoms.insert((f.path.clone(), n as usize), (h.to_hex(), i));
463
                        }
464
                    }
465
                }
466
            }
467
            let touched: Vec<String> = p.files.iter().map(|f| f.path.clone()).collect();
468
            let owners = pl::owners_for(&target_loaded, &touched);
469
            let sealing = pl::sealing_keys(r, &p.hashes)?.into_iter().map(|k| k.to_hex()).collect();
470
            let landed_already = !p.hashes.is_empty() && p.hashes.iter().all(|h| target_loaded.state.contains(h));
0b20f1ec Andy McCall ↶ 471
            // A landed proposal's changes are in its target now: it shows
472
            // the ones it landed, as recorded when it landed.
473
            let (changes, hashes) = if r2.state == "landed" && p.hashes.is_empty() {
474
                let hashes: Vec<ChangeHash> = r2.projected_changes().iter().filter_map(|h| ChangeHash::from_hex(h)).collect();
475
                let labels = HashMap::new();
476
                let changes = hashes
477
                    .iter()
478
                    .filter_map(|h| Some(view::change_view_pub(r, h, &r.store().get_change_meta(h).ok()?, false, &labels)))
479
                    .collect();
480
                (changes, hashes)
481
            } else {
482
                (p.changes, p.hashes)
483
            };
de505df5 Andy McCall ↶ 484
            Ok(Loaded {
485
                row: r2,
0b20f1ec Andy McCall ↶ 486
                changes,
487
                hashes,
de505df5 Andy McCall ↶ 488
                heads: p.heads,
3f02e5ea Andy McCall ↶ 489
                target_heads: p.target_heads.clone(),
de505df5 Andy McCall ↶ 490
                state: p.state.to_hex(),
491
                target_state: p.target_state.to_hex(),
492
                conflicted: p.conflicted,
493
                conflicts: p.conflicts,
494
                files,
9df855f2 Andy McCall ↶ 495
                diffs: p.files.clone(),
496
                bases: p.bases.clone(),
de505df5 Andy McCall ↶ 497
                atoms,
498
                sealing_keys: sealing,
499
                touched,
500
                owners,
501
                landed_already,
ac713df7 Andy McCall ↶ 502
                source_has_changes,
de505df5 Andy McCall ↶ 503
            })
504
        })
505
        .await?;
ac713df7 Andy McCall ↶ 506
    // Landed by another route (#141): `oxy proposal land` from a client (a
507
    // repository with a trust policy needs it), or the work merged and
508
    // pushed by hand. Everything it proposes is in its target, so it is
509
    // landed, not open with nothing to land.
510
    let mut loaded = loaded;
511
    if loaded.row.is_open()
512
        && loaded.source_has_changes
513
        && loaded.hashes.is_empty()
514
        && pdb::set_landed(&app.db, loaded.row.id, &loaded.target_state, "", "push").await.is_ok()
515
    {
516
        loaded.row.state = "landed".into();
517
        loaded.row.landed_via = "push".into();
518
        loaded.row.landed_state = loaded.target_state.clone();
519
        return Ok(loaded);
520
    }
0b20f1ec Andy McCall ↶ 521
    // Remember the projection for the list, the API and other proposals'
522
    // stacking checks, while the proposal is open: a landed one keeps what
523
    // it landed.
524
    if !loaded.row.is_open() {
525
        return Ok(loaded);
526
    }
de505df5 Andy McCall ↶ 527
    let heads_csv = loaded.heads.iter().map(|h| h.to_hex()).collect::<Vec<_>>().join(",");
528
    let changes_csv = loaded.hashes.iter().map(|h| h.to_hex()).collect::<Vec<_>>().join(",");
529
    pdb::set_projection(&app.db, loaded.row.id, &loaded.state, &heads_csv, &loaded.target_state, &changes_csv, loaded.conflicted)
530
        .await
531
        .ok();
532
    Ok(loaded)
ac713df7 Andy McCall ↶ 533
}
534
535
/// After a push moved `bookmark`: open proposals into it whose work it now
536
/// holds are marked landed, by the pusher (#141).
537
pub async fn settle_after_push(app: &Shared, row: &db::repos::RepoRow, bookmark: &str, actor: &str) {
538
    let Some(repo) = RepoName::new(&row.owner, &row.name) else { return };
539
    let Ok(open) = pdb::list(&app.db, row.id, &["open", "draft"]).await else { return };
540
    for p in open.into_iter().filter(|p| p.target == bookmark) {
541
        let id = p.id;
d943160d Andy McCall ↶ 542
        let number = p.number;
ac713df7 Andy McCall ↶ 543
        if let Ok(l) = load(app, &repo, p).await {
544
            if l.row.state == "landed" && l.row.landed_by.is_empty() {
545
                pdb::set_landed(&app.db, id, &l.target_state, actor, "push").await.ok();
d943160d Andy McCall ↶ 546
            } else if l.row.is_open() && !l.hashes.is_empty() && crate::flow::enabled(app, row) {
547
                // The target moved, so the proposal's projected state is
548
                // new and its checks would be for an older one (#134): run
549
                // the pipeline on it, once.
550
                let ran: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM flow_runs WHERE repo_id = ? AND state = ?")
551
                    .bind(row.id)
552
                    .bind(&l.state)
553
                    .fetch_one(&app.db)
554
                    .await
555
                    .unwrap_or(1);
556
                if ran == 0 {
557
                    let label = format!("proposal/{number}");
558
                    match crate::flow::start_run_scoped(app, row, &label, &l.state, &l.heads, actor, "proposal", None).await {
559
                        Ok(Some(n)) => tracing::info!("proposal {number}: its target moved; run #{n} checks its new projected state"),
560
                        Ok(None) => {}
561
                        Err(e) => tracing::warn!("proposal {number}: a run of its new projected state did not start: {e}"),
562
                    }
563
                }
ac713df7 Andy McCall ↶ 564
            }
565
        }
566
    }
de505df5 Andy McCall ↶ 567
}
568
569
/// Reviews, approvals and blockers.
570
pub struct Verdict {
571
    pub reviews: Vec<ReviewView>,
572
    pub approvals: Vec<Approval>,
573
    pub blockers: Vec<String>,
574
    pub depends_on: Vec<i64>,
575
    pub requirements: pdb::Requirements,
576
}
577
578
pub async fn verdict(app: &Shared, loaded: &Loaded, repo_id: i64) -> Result<Verdict, sqlx::Error> {
579
    let rows = pdb::reviews(&app.db, loaded.row.id).await?;
580
    let links = accounts::identity_accounts(&app.db).await?;
581
    let sealed_accounts: Vec<String> = links.iter().filter(|(k, _)| loaded.sealing_keys.contains(k)).map(|(_, u)| u.clone()).collect();
582
    // Latest verdict per reviewer.
583
    let mut latest: BTreeMap<String, &pdb::ReviewRow> = BTreeMap::new();
7d2eb590 Andy McCall ↶ 584
    for r in rows.iter().filter(|r| r.via.is_empty()) {
585
        // An assistant's answer is never the person's own verdict.
de505df5 Andy McCall ↶ 586
        latest.insert(r.author.clone(), r);
587
    }
588
    let mut approvals = Vec::new();
589
    for (who, r) in &latest {
590
        if r.verdict == "approve" {
591
            let sealed = sealed_accounts.contains(who);
592
            let key = links.iter().find(|(k, u)| u == who && loaded.sealing_keys.contains(k)).map(|(k, _)| k.clone());
593
            approvals.push(Approval { account: who.clone(), sealed, key });
594
        }
595
    }
596
    let reviews = rows
597
        .iter()
598
        .map(|r| ReviewView {
599
            row: r.clone(),
600
            body_html: render::markdown::render(&r.body, "/", "/"),
601
            sealed: r.verdict == "approve" && sealed_accounts.contains(&r.author),
602
        })
603
        .collect();
604
    let requirements = pdb::requirements(&app.db, repo_id).await?;
605
    let mut blockers = Vec::new();
0b20f1ec Andy McCall ↶ 606
    // Only an open proposal can be held back.
607
    if !loaded.row.is_open() {
608
        return Ok(Verdict { reviews, approvals, blockers, depends_on: vec![], requirements });
609
    }
de505df5 Andy McCall ↶ 610
    if loaded.row.state == "draft" {
611
        blockers.push("the proposal is a draft".into());
612
    }
613
    if loaded.hashes.is_empty() {
614
        blockers.push("the proposal adds no changes".into());
615
    }
616
    let sealed_count = approvals.iter().filter(|a| a.sealed).count() as i64;
617
    if sealed_count < requirements.required_approvals {
618
        blockers.push(format!("{sealed_count} of {} required sealed approvals", requirements.required_approvals));
619
    }
620
    if requirements.require_owners {
621
        let missing: Vec<&String> = loaded.owners.iter().filter(|o| !approvals.iter().any(|a| a.sealed && &a.account == *o)).collect();
622
        if !missing.is_empty() {
623
            blockers.push(format!("code owners still to approve: {}", missing.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")));
624
        }
625
    }
626
    if loaded.conflicted && !requirements.allow_conflicts {
1e23d010 Andy McCall ↶ 627
        blockers.push(format!(
628
            "landing would carry conflicts, which this repository refuses: resolve them on the source (oxy merge {} there, fix the marked files, oxy commit, push)",
629
            loaded.row.target
630
        ));
de505df5 Andy McCall ↶ 631
    }
b64e2537 Andy McCall ↶ 632
    let required = db::hooks::required_checks(&app.db, repo_id).await?;
633
    if !required.is_empty() {
634
        let checks = db::hooks::checks_for_state(&app.db, repo_id, &loaded.state).await?;
635
        let missing: Vec<String> =
636
            required.iter().filter(|n| !checks.iter().any(|c| &c.name == *n && c.status == "passed")).cloned().collect();
637
        if !missing.is_empty() {
638
            blockers.push(format!("required checks not passed on the projected state: {}", missing.join(", ")));
639
        }
640
    }
de505df5 Andy McCall ↶ 641
    let requesting: Vec<&String> = latest.iter().filter(|(_, r)| r.verdict == "changes").map(|(who, _)| who).collect();
642
    if !requesting.is_empty() {
643
        blockers.push(format!("changes requested by {}", requesting.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")));
644
    }
645
    // Stacking: another open, earlier proposal whose changes this one includes.
646
    let mut depends_on = Vec::new();
647
    for other in pdb::list(&app.db, repo_id, &["open", "draft"]).await? {
648
        if other.id == loaded.row.id || other.number > loaded.row.number {
649
            continue;
650
        }
651
        let theirs = other.projected_changes();
652
        if !theirs.is_empty() && theirs.iter().all(|h| loaded.hashes.iter().any(|m| m.to_hex() == *h)) {
653
            depends_on.push(other.number);
654
        }
655
    }
656
    if !depends_on.is_empty() {
657
        blockers.push(format!("depends on {}", depends_on.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", ")));
658
    }
659
    Ok(Verdict { reviews, approvals, blockers, depends_on, requirements })
660
}
661
662
#[derive(Template)]
663
#[template(path = "proposal.html")]
664
pub struct ProposalPage {
665
    shell: Shell,
666
    repo: RepoShell,
667
    p: pdb::ProposalRow,
38833ed7 Andy McCall ↶ 668
    /// Issues it closes, from its description and its changes.
669
    closes: Vec<super::chain::Link>,
a1b98695 Andy McCall ↶ 670
    /// Projects the viewer may add it to.
671
    project_choices: Option<Vec<db::projects::Project>>,
672
    /// Comments (not anchored to a line), reviews and events, oldest first.
673
    timeline: Vec<Entry>,
674
    /// The viewer may set labels (triage or above).
675
    can_triage: bool,
de505df5 Andy McCall ↶ 676
    body_html: String,
677
    tab: String,
678
    changes: Vec<ChangeView>,
679
    files: Vec<FileRows>,
9df855f2 Andy McCall ↶ 680
    diffs: Vec<oxy_core::repo::FileDiff>,
681
    bases: std::collections::BTreeMap<String, Vec<u8>>,
682
    /// Whitespace-only changes are hidden (`?w=1`).
683
    ignore_ws: bool,
de505df5 Andy McCall ↶ 684
    conflicts: Vec<ConflictView>,
685
    conflicted: bool,
686
    comments: Vec<CommentView>,
687
    /// Anchored comments by (path, current line).
688
    placed: HashMap<(String, usize), Vec<usize>>,
689
    outdated: Vec<usize>,
690
    reviews: Vec<ReviewView>,
691
    approvals: Vec<Approval>,
692
    blockers: Vec<String>,
693
    depends_on: Vec<i64>,
694
    events: Vec<pdb::EventRow>,
695
    owners: Vec<String>,
696
    requirements: pdb::Requirements,
697
    landed_already: bool,
698
    can_edit: bool,
4f37afcc Andy McCall ↶ 699
    /// The landed proposal's source bookmark, when it is this repository's,
700
    /// still there, and the viewer may delete it (oxygenhub#86).
701
    deletable_source: Option<String>,
de505df5 Andy McCall ↶ 702
    can_land: bool,
703
    hub_can_land: bool,
704
    notice: Option<String>,
705
    error: Option<String>,
706
    heads: Vec<String>,
707
    state_hash: String,
708
    source_label: String,
709
    api_url: String,
18e381ea Andy McCall ↶ 710
    labels: Vec<db::issues::Label>,
711
    all_labels: Vec<db::issues::Label>,
b64e2537 Andy McCall ↶ 712
    checks: Vec<db::hooks::Check>,
713
    required_checks: Vec<String>,
e1ec9fbf Andy McCall ↶ 714
    /// Projects this proposal is on that the viewer may see, with the column.
715
    projects: Vec<(db::projects::Project, String)>,
cc1cd197 Andy McCall ↶ 716
    /// Asked to review and not yet reviewing.
717
    requested: Vec<String>,
8e96499f Andy McCall ↶ 718
    /// Who can be asked to review, for the sidebar's menu (oxygenhub#84).
719
    reviewable: Vec<String>,
cc1cd197 Andy McCall ↶ 720
    /// The viewer may ask for reviews (the author, or a writer).
721
    can_request: bool,
7d2eb590 Andy McCall ↶ 722
    /// AI assistants the viewer may ask, by name (hub spec §13.4).
723
    assistants: Vec<String>,
724
    /// A description an assistant just drafted, for the editor.
725
    draft: Option<String>,
de505df5 Andy McCall ↶ 726
}
727
728
#[derive(Deserialize)]
729
pub struct DetailQuery {
730
    tab: Option<String>,
a1b98695 Andy McCall ↶ 731
    /// What an action said, after it redirected here.
9df855f2 Andy McCall ↶ 732
    #[serde(default)]
a1b98695 Andy McCall ↶ 733
    notice: Option<String>,
734
    #[serde(default)]
735
    error: Option<String>,
736
    #[serde(default)]
9df855f2 Andy McCall ↶ 737
    w: Option<String>,
de505df5 Andy McCall ↶ 738
}
739
740
/// The page assembler every action ends in; its arguments are the route
741
/// plus what to say, and a struct would only rename them.
742
#[allow(clippy::too_many_arguments)]
743
async fn detail(
744
    app: &Shared,
745
    shell: Shell,
746
    viewer: &Viewer,
747
    owner: &str,
748
    name: &str,
749
    number: i64,
750
    tab: String,
751
    notice: Option<String>,
752
    error: Option<String>,
753
) -> Result<Page<ProposalPage>, Error> {
754
    let (repo, row, role) = lookup(app, &shell, viewer, owner, name).await?;
755
    let p = pdb::get(&app.db, row.id, number)
756
        .await
757
        .map_err(|e| Error::from_db(shell.clone(), e))?
758
        .ok_or_else(|| Error::not_found(shell.clone()))?;
759
    let loaded = load(app, &repo, p).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
760
    // A proposal whose changes all reached the target landed by another route.
761
    if loaded.landed_already && loaded.row.is_open() {
762
        pdb::set_state(&app.db, loaded.row.id, "landed", &loaded.target_state).await.ok();
763
        pdb::add_event(&app.db, loaded.row.id, "", "landed", "every change reached the target").await.ok();
764
    }
765
    let p = pdb::get(&app.db, row.id, number).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(loaded.row.clone());
766
    let v = verdict(app, &loaded, row.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
767
    let comment_rows = pdb::comments(&app.db, loaded.row.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
768
    let events = pdb::events(&app.db, loaded.row.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
769
    // Place anchored comments at their atom's current line.
770
    let mut by_atom: HashMap<(String, String, u32), usize> = HashMap::new();
771
    for ((path, line), (h, i)) in &loaded.atoms {
772
        by_atom.insert((path.clone(), h.clone(), *i), *line);
773
    }
774
    let mut comments = Vec::new();
775
    let mut placed: HashMap<(String, usize), Vec<usize>> = HashMap::new();
776
    let mut outdated = Vec::new();
777
    for (idx, c) in comment_rows.into_iter().enumerate() {
778
        let line = if c.anchor_change.is_empty() {
779
            None
780
        } else {
781
            by_atom.get(&(c.path.clone(), c.anchor_change.clone(), c.anchor_index as u32)).copied()
782
        };
783
        if !c.anchor_change.is_empty() {
784
            match line {
785
                Some(l) => placed.entry((c.path.clone(), l)).or_default().push(idx),
786
                None => outdated.push(idx),
787
            }
788
        }
789
        comments.push(CommentView { body_html: render::markdown::render(&c.body, "/", "/"), row: c, line });
790
    }
791
    let mut changes = loaded.changes.clone();
792
    super::attribute(app, &mut changes.iter_mut().collect::<Vec<_>>()).await;
793
    let me = viewer.account();
794
    let can_edit = me.is_some_and(|a| Some(a.id) == p.author_id || role >= Role::Maintain);
4f37afcc Andy McCall ↶ 795
    let deletable_source =
796
        if p.state == "landed" && p.source_kind == "bookmark" && role >= Role::Write && p.source_bookmark != row.default_bookmark {
797
            let b = p.source_bookmark.clone();
798
            app.repos
799
                .read(&repo, move |r, _| Ok(r.view()?.bookmarks.contains_key(&b)))
800
                .await
801
                .unwrap_or(false)
802
                .then(|| p.source_bookmark.clone())
803
        } else {
804
            None
805
        };
de505df5 Andy McCall ↶ 806
    let can_land = role >= Role::Write && p.is_open() && v.blockers.is_empty();
cc1cd197 Andy McCall ↶ 807
    let can_request = p.is_open() && me.is_some_and(|a| Some(a.id) == p.author_id || role >= Role::Write);
8e96499f Andy McCall ↶ 808
    let requested = pdb::review_requests(&app.db, p.id).await.unwrap_or_default();
809
    let mut reviewable: Vec<String> = if can_request {
810
        accounts::assignable(&app.db, row.id, &row.owner).await.unwrap_or_default().into_iter().filter(|u| *u != p.author).collect()
811
    } else {
812
        Vec::new()
813
    };
814
    for r in &requested {
815
        if !reviewable.iter().any(|x| x.eq_ignore_ascii_case(r)) {
816
            reviewable.push(r.clone());
817
        }
818
    }
7d2eb590 Andy McCall ↶ 819
    let assistants: Vec<String> = if (can_request || can_edit) && p.is_open() { assistant_names(app, &row).await } else { Vec::new() };
14530604 Andy McCall ↶ 820
    let delegated = match viewer.account() {
821
        Some(a) => super::edit::delegated_identity(app, a.id).await.is_some(),
822
        None => false,
823
    };
824
    let hub_can_land = delegated || app.repos.read(&repo, |r, _| Ok(r.current_policy()?.is_none())).await.unwrap_or(false);
de505df5 Andy McCall ↶ 825
    let source_label = match p.source_kind.as_str() {
826
        "fork" => format!(
827
            "fork {}",
828
            db::repos::get_by_id(&app.db, p.source_repo_id.unwrap_or(0))
829
                .await
830
                .ok()
831
                .flatten()
832
                .map(|r| format!("{}:{}", r.slug(), p.source_bookmark))
833
                .unwrap_or_default()
834
        ),
835
        "changes" => format!("{} changes", p.source_changes().len()),
836
        _ => p.source_bookmark.clone(),
837
    };
e1ec9fbf Andy McCall ↶ 838
    let projects = super::projects::placements_for(app, viewer, &row, p.number).await;
38833ed7 Andy McCall ↶ 839
    let texts: Vec<String> = std::iter::once(p.body.clone()).chain(changes.iter().map(|c| format!("{}\n{}", c.title, c.body))).collect();
840
    let closes = super::chain::issues_closed_by(app, &row, &texts.iter().map(String::as_str).collect::<Vec<_>>()).await;
a1b98695 Andy McCall ↶ 841
    let project_choices = super::projects::project_choices(app, viewer, &row, &projects).await;
842
    let mut dated: Vec<(i64, Entry)> = Vec::new();
843
    for (index, c) in comments.iter().enumerate() {
844
        if c.row.anchor_change.is_empty() {
845
            dated.push((c.row.created_ms, Entry { kind: "comment", index }));
846
        }
847
    }
848
    for (index, r) in v.reviews.iter().enumerate() {
849
        dated.push((r.row.created_ms, Entry { kind: "review", index }));
850
    }
851
    for (index, e) in events.iter().enumerate() {
852
        dated.push((e.at_ms, Entry { kind: "event", index }));
853
    }
854
    dated.sort_by_key(|(at, _)| *at);
855
    let timeline: Vec<Entry> = dated.into_iter().map(|(_, e)| e).collect();
de505df5 Andy McCall ↶ 856
    Ok(Page(ProposalPage {
a1b98695 Andy McCall ↶ 857
        can_triage: role >= Role::Triage,
858
        timeline,
38833ed7 Andy McCall ↶ 859
        closes,
a1b98695 Andy McCall ↶ 860
        project_choices,
e1ec9fbf Andy McCall ↶ 861
        projects,
de505df5 Andy McCall ↶ 862
        shell,
ffb67a81 Andy McCall 863
        repo: RepoShell::new(app, &row, "proposals").with_role(role).with_sky(app, &row).await,
c79a1111 Andy McCall ↶ 864
        body_html: super::issues::markdown(app, &row, &row.default_bookmark, &p.body).await,
de505df5 Andy McCall ↶ 865
        p,
866
        tab,
867
        changes,
868
        files: loaded.files,
9df855f2 Andy McCall ↶ 869
        diffs: loaded.diffs,
870
        bases: loaded.bases,
871
        ignore_ws: false,
de505df5 Andy McCall ↶ 872
        conflicts: loaded.conflicts,
873
        conflicted: loaded.conflicted,
874
        comments,
875
        placed,
876
        outdated,
877
        reviews: v.reviews,
878
        approvals: v.approvals,
879
        blockers: v.blockers,
880
        depends_on: v.depends_on,
881
        events,
882
        owners: loaded.owners,
883
        requirements: v.requirements,
884
        landed_already: loaded.landed_already,
885
        can_edit,
4f37afcc Andy McCall ↶ 886
        deletable_source,
de505df5 Andy McCall ↶ 887
        can_land,
888
        hub_can_land,
889
        notice,
890
        error,
891
        heads: loaded.heads.iter().map(|h| h.to_hex()).collect(),
b64e2537 Andy McCall ↶ 892
        state_hash: loaded.state.clone(),
de505df5 Andy McCall ↶ 893
        source_label,
894
        api_url: format!("{}/api/v1/repos/{owner}/{name}/proposals/{number}", app.config.base_url()),
18e381ea Andy McCall ↶ 895
        labels: db::issues::proposal_labels(&app.db, loaded.row.id).await.unwrap_or_default(),
896
        all_labels: db::issues::labels(&app.db, row.id).await.unwrap_or_default(),
b64e2537 Andy McCall ↶ 897
        checks: db::hooks::checks_for_state(&app.db, row.id, &loaded.state).await.unwrap_or_default(),
898
        required_checks: db::hooks::required_checks(&app.db, row.id).await.unwrap_or_default(),
8e96499f Andy McCall ↶ 899
        requested,
900
        reviewable,
7d2eb590 Andy McCall ↶ 901
        assistants,
902
        draft: None,
cc1cd197 Andy McCall ↶ 903
        can_request,
de505df5 Andy McCall ↶ 904
    }))
905
}
906
a1b98695 Andy McCall ↶ 907
/// Back to the proposal after an action, with what to say: a redirect, so
908
/// reloading the page (the checks script does) never repeats the action.
909
fn back(owner: &str, name: &str, number: i64, tab: &str, notice: Option<String>, error: Option<String>) -> Response {
910
    let mut url = format!("/{owner}/{name}/proposal/{number}?tab={tab}");
911
    if let Some(n) = notice {
912
        url.push_str(&format!("&notice={}", super::settings::urlencode(&n)));
913
    }
914
    if let Some(e) = error {
915
        url.push_str(&format!("&error={}", super::settings::urlencode(&e)));
916
    }
917
    Redirect::to(&url).into_response()
918
}
919
de505df5 Andy McCall ↶ 920
pub async fn show(
921
    State(app): State<Shared>,
922
    viewer: Viewer,
923
    Path((owner, name, number)): Path<(String, String, i64)>,
924
    Query(q): Query<DetailQuery>,
925
) -> Result<Page<ProposalPage>, Error> {
926
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
a1b98695 Andy McCall ↶ 927
    let mut page =
928
        detail(&app, shell, &viewer, &owner, &name, number, q.tab.unwrap_or_else(|| "conversation".into()), q.notice, q.error).await?;
9df855f2 Andy McCall ↶ 929
    if q.w.as_deref() == Some("1") {
930
        // Hide whitespace-only changes: the same hunks, rendered again.
931
        page.0.files =
932
            super::history::render_files_with(&page.0.diffs, &page.0.bases, crate::render::diff::Options { ignore_whitespace: true });
933
        page.0.ignore_ws = true;
934
    }
935
    Ok(page)
de505df5 Andy McCall ↶ 936
}
937
938
// ---------------------------------------------------------------- actions
939
940
#[derive(Deserialize)]
941
pub struct CommentForm {
942
    #[serde(rename = "_csrf")]
943
    csrf_token: String,
944
    body: String,
945
    #[serde(default)]
946
    path: String,
947
    #[serde(default)]
948
    line: Option<usize>,
949
}
950
951
pub async fn comment(
952
    State(app): State<Shared>,
953
    viewer: Viewer,
954
    Path((owner, name, number)): Path<(String, String, i64)>,
955
    Form(f): Form<CommentForm>,
a1b98695 Andy McCall ↶ 956
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 957
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
958
    let me = require(&viewer, &shell)?;
959
    csrf(&viewer, &f.csrf_token, &shell)?;
960
    let (repo, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 961
    super::writable(&row, &shell)?;
de505df5 Andy McCall ↶ 962
    let p = pdb::get(&app.db, row.id, number)
963
        .await
964
        .map_err(|e| Error::from_db(shell.clone(), e))?
965
        .ok_or_else(|| Error::not_found(shell.clone()))?;
966
    if f.body.trim().is_empty() {
a1b98695 Andy McCall ↶ 967
        return Ok(back(&owner, &name, number, "conversation", None, Some("An empty comment says nothing.".into())));
de505df5 Andy McCall ↶ 968
    }
969
    let anchor = match (f.path.trim(), f.line) {
970
        ("", _) | (_, None) => None,
971
        (path, Some(line)) => {
972
            let loaded = load(&app, &repo, p.clone()).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
973
            loaded.atoms.get(&(path.to_string(), line)).cloned()
974
        }
975
    };
976
    let tab = if anchor.is_some() { "files" } else { "conversation" };
977
    pdb::add_comment(
978
        &app.db,
979
        p.id,
980
        Some(me.account.id),
981
        &me.account.username,
982
        f.body.trim(),
983
        f.path.trim(),
984
        anchor.as_ref().map(|(h, i)| (h.as_str(), *i as i64)),
985
    )
986
    .await
987
    .map_err(|e| Error::from_db(shell.clone(), e))?;
a1b98695 Andy McCall ↶ 988
    Ok(back(&owner, &name, number, tab, None, None))
de505df5 Andy McCall ↶ 989
}
990
991
#[derive(Deserialize)]
992
pub struct ReviewForm {
993
    #[serde(rename = "_csrf")]
994
    csrf_token: String,
995
    verdict: String,
996
    #[serde(default)]
997
    body: String,
998
}
999
1000
pub async fn review(
1001
    State(app): State<Shared>,
1002
    viewer: Viewer,
1003
    Path((owner, name, number)): Path<(String, String, i64)>,
1004
    Form(f): Form<ReviewForm>,
a1b98695 Andy McCall ↶ 1005
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 1006
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1007
    let me = require(&viewer, &shell)?;
1008
    csrf(&viewer, &f.csrf_token, &shell)?;
1009
    let (_, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 1010
    super::writable(&row, &shell)?;
de505df5 Andy McCall ↶ 1011
    let p = pdb::get(&app.db, row.id, number)
1012
        .await
1013
        .map_err(|e| Error::from_db(shell.clone(), e))?
1014
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1015
    if !matches!(f.verdict.as_str(), "comment" | "changes" | "approve") {
1016
        return Err(Error::bad(shell, "a review is comment, changes or approve"));
1017
    }
1018
    if f.verdict == "approve" && Some(me.account.id) == p.author_id {
a1b98695 Andy McCall ↶ 1019
        return Ok(back(&owner, &name, number, "conversation", None, Some("You cannot approve your own proposal.".into())));
de505df5 Andy McCall ↶ 1020
    }
1021
    pdb::add_review(&app.db, p.id, me.account.id, &me.account.username, &f.verdict, f.body.trim())
1022
        .await
1023
        .map_err(|e| Error::from_db(shell.clone(), e))?;
1024
    pdb::add_event(&app.db, p.id, &me.account.username, &format!("review.{}", f.verdict), "").await.ok();
cc1cd197 Andy McCall ↶ 1025
    reviewed(&app, &row, &p, &me.account, &f.verdict).await;
b64e2537 Andy McCall ↶ 1026
    crate::hooks::emit(&app, &row, "review", &me.account.username, serde_json::json!({ "number": number, "verdict": f.verdict })).await;
de505df5 Andy McCall ↶ 1027
    let notice = if f.verdict == "approve" {
1028
        Some(format!(
1029
            "Approval recorded. It counts once you seal the changes: oxy seal --proposal {}/{owner}/{name}/proposal/{number}",
1030
            app.config.base_url()
1031
        ))
1032
    } else {
1033
        None
1034
    };
a1b98695 Andy McCall ↶ 1035
    Ok(back(&owner, &name, number, "conversation", notice, None))
de505df5 Andy McCall ↶ 1036
}
1037
1038
#[derive(Deserialize)]
1039
pub struct EditForm {
1040
    #[serde(rename = "_csrf")]
1041
    csrf_token: String,
1042
    title: String,
1043
    #[serde(default)]
1044
    body: String,
1045
    target: String,
1046
}
1047
1048
pub async fn edit(
1049
    State(app): State<Shared>,
1050
    viewer: Viewer,
1051
    Path((owner, name, number)): Path<(String, String, i64)>,
1052
    Form(f): Form<EditForm>,
a1b98695 Andy McCall ↶ 1053
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 1054
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1055
    let me = require(&viewer, &shell)?;
1056
    csrf(&viewer, &f.csrf_token, &shell)?;
1057
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1058
    let p = pdb::get(&app.db, row.id, number)
1059
        .await
1060
        .map_err(|e| Error::from_db(shell.clone(), e))?
1061
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1062
    if Some(me.account.id) != p.author_id && role < Role::Maintain {
1063
        return Err(Error::not_found(shell));
1064
    }
1065
    let target = if crate::repos::names::valid_segment(f.target.trim()) { f.target.trim() } else { &p.target };
1066
    pdb::edit(&app.db, p.id, f.title.trim(), f.body.trim(), target).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1067
    pdb::add_event(&app.db, p.id, &me.account.username, "edited", "").await.ok();
a1b98695 Andy McCall ↶ 1068
    Ok(back(&owner, &name, number, "conversation", Some("Saved.".into()), None))
de505df5 Andy McCall ↶ 1069
}
1070
1071
#[derive(Deserialize)]
1072
pub struct StateForm {
1073
    #[serde(rename = "_csrf")]
1074
    csrf_token: String,
1075
    action: String,
1076
}
1077
1078
pub async fn state(
1079
    State(app): State<Shared>,
1080
    viewer: Viewer,
1081
    Path((owner, name, number)): Path<(String, String, i64)>,
1082
    Form(f): Form<StateForm>,
a1b98695 Andy McCall ↶ 1083
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 1084
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1085
    let me = require(&viewer, &shell)?;
1086
    csrf(&viewer, &f.csrf_token, &shell)?;
1087
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1088
    let p = pdb::get(&app.db, row.id, number)
1089
        .await
1090
        .map_err(|e| Error::from_db(shell.clone(), e))?
1091
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1092
    if Some(me.account.id) != p.author_id && role < Role::Triage {
1093
        return Err(Error::not_found(shell));
1094
    }
1095
    let new_state = match (f.action.as_str(), p.state.as_str()) {
1096
        ("close", "open" | "draft") => "closed",
1097
        ("reopen", "closed") => "open",
1098
        ("ready", "draft") => "open",
1099
        ("draft", "open") => "draft",
1100
        _ => return Err(Error::bad(shell, "that transition is not possible")),
1101
    };
1102
    pdb::set_state(&app.db, p.id, new_state, "").await.map_err(|e| Error::from_db(shell.clone(), e))?;
1103
    pdb::add_event(&app.db, p.id, &me.account.username, new_state, "").await.ok();
b64e2537 Andy McCall ↶ 1104
    crate::hooks::emit(&app, &row, &format!("proposal.{new_state}"), &me.account.username, serde_json::json!({ "number": number })).await;
a1b98695 Andy McCall ↶ 1105
    Ok(back(&owner, &name, number, "conversation", None, None))
de505df5 Andy McCall ↶ 1106
}
1107
1108
pub async fn resolve_comment(
1109
    State(app): State<Shared>,
1110
    viewer: Viewer,
1111
    Path((owner, name, number, id)): Path<(String, String, i64, i64)>,
1112
    Form(f): Form<super::session::CsrfForm>,
a1b98695 Andy McCall ↶ 1113
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 1114
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1115
    require(&viewer, &shell)?;
1116
    csrf(&viewer, &f.csrf, &shell)?;
1117
    let (_, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1118
    let p = pdb::get(&app.db, row.id, number)
1119
        .await
1120
        .map_err(|e| Error::from_db(shell.clone(), e))?
1121
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1122
    let current: Option<bool> = sqlx::query_scalar("SELECT resolved FROM proposal_comments WHERE id = ? AND proposal_id = ?")
1123
        .bind(id)
1124
        .bind(p.id)
1125
        .fetch_optional(&app.db)
1126
        .await
1127
        .map_err(|e| Error::from_db(shell.clone(), e))?;
1128
    if let Some(r) = current {
1129
        pdb::set_comment_resolved(&app.db, id, !r).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1130
    }
a1b98695 Andy McCall ↶ 1131
    Ok(back(&owner, &name, number, "files", None, None))
de505df5 Andy McCall ↶ 1132
}
1133
1134
/// Land from the hub: only when the repository has no trust policy (the
1135
/// hub never signs a reference update the policy would have to admit).
1136
pub async fn land(
1137
    State(app): State<Shared>,
1138
    viewer: Viewer,
1139
    Path((owner, name, number)): Path<(String, String, i64)>,
1140
    Form(f): Form<super::session::CsrfForm>,
a1b98695 Andy McCall ↶ 1141
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 1142
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1143
    let me = require(&viewer, &shell)?;
1144
    csrf(&viewer, &f.csrf, &shell)?;
1145
    let (repo, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
f4d6ef41 Andy McCall ↶ 1146
    match land_as(&app, &repo, &row, &me.account, number, "web", false).await {
a1b98695 Andy McCall ↶ 1147
        Ok(_) => Ok(back(&owner, &name, number, "conversation", Some("Landed.".into()), None)),
1f1eb06a Andy McCall ↶ 1148
        Err(Landing::NotFound) => Err(Error::not_found(shell)),
a1b98695 Andy McCall ↶ 1149
        Err(Landing::Refused(m)) => Ok(back(&owner, &name, number, "conversation", None, Some(m))),
1f1eb06a Andy McCall ↶ 1150
    }
1151
}
1152
1153
/// Why a proposal did not land.
1154
pub enum Landing {
1155
    NotFound,
1156
    Refused(String),
1157
}
1158
1159
/// Land proposal `number` as `me` (hub spec §8.4), who has write access:
1160
/// refused while it is not open or has blockers. Moves the target bookmark
1161
/// (attested by the hub key on `me`'s behalf when they delegated to it),
0b20f1ec Andy McCall ↶ 1162
/// then records, announces and audits the landing, saying how it was done
f4d6ef41 Andy McCall ↶ 1163
/// (`via`: `web`, or `api (token NAME)`). `as_hub` signs with the hub's own
1164
/// key rather than `me`'s delegation (Diffusion's auto-land). Returns the
1165
/// new state.
1f1eb06a Andy McCall ↶ 1166
pub async fn land_as(
1167
    app: &Shared,
1168
    repo: &RepoName,
1169
    row: &db::repos::RepoRow,
1170
    me: &accounts::Account,
1171
    number: i64,
0b20f1ec Andy McCall ↶ 1172
    via: &str,
f4d6ef41 Andy McCall ↶ 1173
    as_hub: bool,
1f1eb06a Andy McCall ↶ 1174
) -> Result<String, Landing> {
1175
    let (owner, name) = (row.owner.clone(), row.name.clone());
1176
    let refused = |e: String| Landing::Refused(e);
1177
    let p = pdb::get(&app.db, row.id, number).await.map_err(|e| refused(e.to_string()))?.ok_or(Landing::NotFound)?;
1178
    let loaded = load(app, repo, p.clone()).await.map_err(|e| refused(e.to_string()))?;
1179
    let v = verdict(app, &loaded, row.id).await.map_err(|e| refused(e.to_string()))?;
1180
    if !p.is_open() {
1181
        return Err(refused(format!("Cannot land: the proposal is {}", p.state)));
1182
    }
1183
    if !v.blockers.is_empty() {
1184
        return Err(refused(format!("Cannot land: {}", v.blockers.join("; "))));
de505df5 Andy McCall ↶ 1185
    }
1186
    let target = p.target.clone();
1187
    let heads = loaded.heads.clone();
14530604 Andy McCall ↶ 1188
    // With a delegation the landing is attested by the hub key on the
1189
    // user's behalf, which a policy accepts when it lets the user update
1190
    // the target (spec §14.5); without one, only a policy-free repository
1191
    // can be landed here.
f4d6ef41 Andy McCall ↶ 1192
    let signer = if as_hub { super::edit::hub_signer(app) } else { super::edit::signer_for(app, me.id).await };
1193
    let result = match signer {
1f1eb06a Andy McCall ↶ 1194
        Ok(signer) => crate::repos::edits::move_bookmark(&app.repos, repo, target.clone(), heads.clone(), signer).await.map(|_| pl::state_ref(&heads).to_hex()),
14530604 Andy McCall ↶ 1195
        Err(why) => {
1196
            app.repos
1f1eb06a Andy McCall ↶ 1197
                .write(repo, move |r, _| {
14530604 Andy McCall ↶ 1198
                    if r.current_policy()?.is_some() {
1199
                        return Err(crate::repos::RepoError::Oxy(oxy_core::repo::RepoError::Msg(format!(
1200
                            "this repository has a trust policy, so the landing must be signed by a key it authorises. Land from a client with oxy proposal land, or delegate to the hub. {why}"
1201
                        ))));
1202
                    }
1203
                    r.bookmark_set(&target, &heads)?;
1204
                    Ok(pl::state_ref(&heads).to_hex())
1205
                })
1206
                .await
1207
        }
1208
    };
1f1eb06a Andy McCall ↶ 1209
    let state = result.map_err(|e| refused(e.to_string()))?;
0b20f1ec Andy McCall ↶ 1210
    pdb::set_landed(&app.db, p.id, &state, &me.username, via).await.map_err(|e| refused(e.to_string()))?;
1211
    let how = if v.approvals.is_empty() { format!("{via}, with no approval") } else { via.to_string() };
1212
    pdb::add_event(&app.db, p.id, &me.username, "landed", &how).await.ok();
1f1eb06a Andy McCall ↶ 1213
    crate::hooks::emit(
1214
        app,
1215
        row,
1216
        "proposal.landed",
1217
        &me.username,
1218
        serde_json::json!({ "number": number, "target": p.target, "state": state }),
1219
    )
1220
    .await;
1221
    crate::notify::deliver(
1222
        app,
1223
        crate::notify::Event {
1224
            kind: "proposal.landed",
1225
            title: format!("{owner}/{name}#{number}: {} landed", p.title),
1226
            url: format!("/{owner}/{name}/proposal/{number}"),
1227
            actor: me,
1228
            repo_id: row.id,
1229
            thread: Some(("proposal", p.id)),
1230
            mention_text: "",
1231
            direct: p.author_id.into_iter().collect(),
1232
        },
1233
    )
1234
    .await;
1235
    if p.target == row.default_bookmark {
1236
        let messages: Vec<(String, String)> = loaded.changes.iter().map(|c| (c.hash.clone(), format!("{}\n{}", c.title, c.body))).collect();
1237
        super::issues::close_from_messages(app, row, &messages).await;
de505df5 Andy McCall ↶ 1238
    }
0b20f1ec Andy McCall ↶ 1239
    accounts::audit(&app.db, Some(me), "proposal.landed", &format!("{owner}/{name}#{number}"), &how).await.ok();
1f1eb06a Andy McCall ↶ 1240
    db::repos::record_push(
1241
        &app.db,
1242
        row.id,
1243
        Some((me.id, me.username.as_str())),
1244
        &[db::repos::PushOutcome {
1245
            reference: p.target.clone(),
1246
            ok: true,
0b20f1ec Andy McCall ↶ 1247
            reason: format!("landed #{number} ({how})"),
1f1eb06a Andy McCall ↶ 1248
            old_state: loaded.target_state.clone(),
1249
            new_state: state.clone(),
1250
            heads: loaded.heads.len() as i64,
1251
            changes: loaded.hashes.len() as i64,
1252
        }],
1253
    )
1254
    .await
1255
    .ok();
d943160d Andy McCall ↶ 1256
    // The target moved: its other open proposals are checked again (#134).
1257
    settle_after_push(app, row, &p.target, &me.username).await;
acc85ac0 Andy McCall ↶ 1258
    // A landing on the default bookmark closes the issues its changes (and
1259
    // its description) say they close, as a push there would.
1260
    if p.target == row.default_bookmark {
1261
        let body = (format!("proposal #{number}"), p.body.clone());
1262
        crate::web::issues::close_from_arrived(app, row, loaded.target_heads.clone(), loaded.heads.clone(), Some(body)).await;
1263
    }
757195ad Andy McCall ↶ 1264
    // Diffusion (#150): a landing moves the target as a push would, so the
1265
    // pin index follows it, and the consumers of a moved default bookmark
1266
    // are bumped.
1267
    let heads = loaded.heads.clone();
1268
    let moved = vec![(p.target.clone(), state.clone(), heads.clone())];
1269
    crate::diffusion::after_push(app, row, &moved).await;
1270
    if p.target == row.default_bookmark {
1271
        let (app, row) = (app.clone(), row.clone());
1272
        tokio::spawn(async move { crate::diffusion::propagate(&app, &row, heads, false).await });
1273
    }
1f1eb06a Andy McCall ↶ 1274
    Ok(state)
de505df5 Andy McCall ↶ 1275
}
1276
18e381ea Andy McCall ↶ 1277
#[derive(Deserialize)]
1278
pub struct LabelsForm {
1279
    #[serde(rename = "_csrf")]
1280
    csrf_token: String,
1281
    #[serde(default)]
1282
    label: Vec<i64>,
1283
}
1284
1285
pub async fn set_labels(
1286
    State(app): State<Shared>,
1287
    viewer: Viewer,
1288
    Path((owner, name, number)): Path<(String, String, i64)>,
1289
    axum_extra::extract::Form(f): axum_extra::extract::Form<LabelsForm>,
a1b98695 Andy McCall ↶ 1290
) -> Result<Response, Error> {
18e381ea Andy McCall ↶ 1291
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1292
    require(&viewer, &shell)?;
1293
    csrf(&viewer, &f.csrf_token, &shell)?;
1294
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1295
    if role < Role::Triage {
1296
        return Err(Error::not_found(shell));
1297
    }
1298
    let p = pdb::get(&app.db, row.id, number)
1299
        .await
1300
        .map_err(|e| Error::from_db(shell.clone(), e))?
1301
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1302
    for l in db::issues::labels(&app.db, row.id).await.map_err(|e| Error::from_db(shell.clone(), e))? {
1303
        db::issues::set_proposal_label(&app.db, p.id, l.id, f.label.contains(&l.id)).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1304
    }
a1b98695 Andy McCall ↶ 1305
    Ok(back(&owner, &name, number, "conversation", None, None))
18e381ea Andy McCall ↶ 1306
}
1307
b64e2537 Andy McCall ↶ 1308
/// `GET /{owner}/{name}/proposal/{number}/events`: server-sent events for
1309
/// checks on the projected state (hub spec §13.1).
1310
pub async fn events(
1311
    State(app): State<Shared>,
1312
    viewer: Viewer,
1313
    Path((owner, name, number)): Path<(String, String, i64)>,
1314
) -> Result<axum::response::Sse<impl futures::Stream<Item = Result<axum::response::sse::Event, std::convert::Infallible>>>, Error> {
1315
    use futures::StreamExt;
1316
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1317
    let (_, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1318
    let rx = app.events.proposals.subscribe();
1319
    let repo_id = row.id;
1320
    let stream = tokio_stream::wrappers::BroadcastStream::new(rx).filter_map(move |item| async move {
1321
        match item {
1322
            Ok((id, ev)) if id == repo_id => {
1323
                Some(Ok(axum::response::sse::Event::default().event(ev.kind.clone()).data(serde_json::to_string(&ev).unwrap_or_default())))
1324
            }
1325
            _ => None,
1326
        }
1327
    });
1328
    Ok(axum::response::Sse::new(stream).keep_alive(axum::response::sse::KeepAlive::default()))
1329
}
1330
de505df5 Andy McCall ↶ 1331
// -------------------------------------------------------------------- API
1332
1333
pub async fn to_api(app: &Shared, owner: &str, name: &str, loaded: &Loaded, v: &Verdict, source_url: Option<String>) -> hub_api::Proposal {
1334
    let p = &loaded.row;
1335
    hub_api::Proposal {
1336
        number: p.number,
1337
        title: p.title.clone(),
1338
        body: p.body.clone(),
1339
        author: p.author.clone(),
1340
        state: ProposalState::parse(&p.state).unwrap_or(ProposalState::Open),
1341
        target: p.target.clone(),
1342
        source: match p.source_kind.as_str() {
1343
            "fork" => {
1344
                let (o, n) = source_url
1345
                    .as_deref()
1346
                    .and_then(|u| u.rsplit_once('/'))
1347
                    .and_then(|(b, n)| b.rsplit_once('/').map(|(_, o)| (o.to_string(), n.to_string())))
1348
                    .unwrap_or_default();
1349
                ProposalSource::Fork { owner: o, name: n, bookmark: p.source_bookmark.clone() }
1350
            }
1351
            "changes" => ProposalSource::Changes { hashes: p.source_changes() },
1352
            _ => ProposalSource::Bookmark { bookmark: p.source_bookmark.clone() },
1353
        },
1354
        changes: loaded
1355
            .changes
1356
            .iter()
1357
            .map(|c| hub_api::ChangeSummary {
1358
                hash: c.hash.clone(),
1359
                message: if c.body.is_empty() { c.title.clone() } else { format!("{}\n\n{}", c.title, c.body) },
1360
                author: hub_api::Author {
1361
                    name: c.author.name.clone(),
1362
                    email: c.author.email.clone(),
1363
                    key: c.author.key.clone(),
1364
                    account: c.author.account.clone(),
760a7dd3 Andy McCall ↶ 1365
                    note: hub_api::Author::note_for(&c.author.key, &c.author.account),
de505df5 Andy McCall ↶ 1366
                },
1367
                when_ms: c.when_ms,
1368
                deps: c.deps.clone(),
1369
                head: c.head,
8933faff Andy McCall ↶ 1370
                via: c.via.as_ref().map(|v| hub_api::Via {
1371
                    name: v.name.clone(),
1372
                    key: v.key.clone(),
1373
                    scope: v.scope.clone(),
1374
                    expires_ms: v.expires_ms,
1375
                    revoked: v.revoked,
1376
                }),
de505df5 Andy McCall ↶ 1377
                signature: match &c.signature {
1378
                    view::SigView::Unsigned => hub_api::Signature::Unsigned,
1379
                    view::SigView::Valid { key, sealed, revoked, .. } => {
1380
                        hub_api::Signature::Valid { key: key.clone(), sealed: *sealed, revoked: *revoked }
1381
                    }
1382
                    view::SigView::Invalid(why) => hub_api::Signature::Invalid { reason: why.clone() },
1383
                },
1384
            })
1385
            .collect(),
1386
        projected_heads: loaded.heads.iter().map(|h| h.to_hex()).collect(),
1387
        projected_state: Some(loaded.state.clone()),
1388
        conflicted: loaded.conflicted,
1389
        approvals: v.approvals.clone(),
1390
        landable: p.is_open() && v.blockers.is_empty(),
1391
        blockers: v.blockers.clone(),
1392
        created_ms: p.created_ms,
1393
        updated_ms: p.updated_ms,
1394
        url: format!("{}/{owner}/{name}/proposal/{}", app.config.base_url(), p.number),
1395
        repository_url: format!("{}/{owner}/{name}", app.config.base_url()),
1396
        source_url,
0b20f1ec Andy McCall ↶ 1397
        landed: (p.state == "landed" && p.landed_ms > 0).then(|| hub_api::Landed {
1398
            by: p.landed_by.clone(),
1399
            via: p.landed_via.clone(),
1400
            when_ms: p.landed_ms,
1401
        }),
cc1cd197 Andy McCall ↶ 1402
        requested_reviewers: pdb::review_requests(&app.db, p.id).await.unwrap_or_default(),
2291f8cc Andy McCall ↶ 1403
        labels: db::issues::proposal_labels(&app.db, p.id)
1404
            .await
1405
            .unwrap_or_default()
1406
            .into_iter()
1407
            .map(|l| hub_api::Label { name: l.name, colour: l.colour, description: l.description })
1408
            .collect(),
de505df5 Andy McCall ↶ 1409
    }
1410
}
1411
1412
/// The line comment form's placement key, for templates.
1413
pub fn key(path: &str, line: impl filters::Num) -> (String, usize) {
1414
    (path.to_string(), line.as_u64() as usize)
1415
}
1416
1417
#[allow(dead_code)]
1418
fn _unused(_: &diff::Line, _: &ConflictView, _: &Role) {}
cc1cd197 Andy McCall ↶ 1419
1420
// ------------------------------------------------------- review requests
1421
1422
/// Ask accounts to review a proposal (hub plan 0.4): each must exist, be
1423
/// someone other than the author, and be able to read the repository. Each
1424
/// newly asked is told, and the proposal records it. The usernames newly
1425
/// asked, or why none could be.
1426
pub async fn request_reviewers(
1427
    app: &Shared,
1428
    row: &db::repos::RepoRow,
1429
    p: &pdb::ProposalRow,
1430
    by: &accounts::Account,
1431
    names: &[String],
1432
) -> Result<Vec<String>, String> {
1433
    let mut found = Vec::new();
1434
    for name in names.iter().map(|n| n.trim().trim_start_matches('@')).filter(|n| !n.is_empty()) {
1435
        let Some(a) = accounts::account_by_name(&app.db, name).await.ok().flatten() else {
1436
            return Err(format!("There is no account {name}."));
1437
        };
1438
        if Some(a.id) == p.author_id {
1439
            return Err(format!("{name} wrote this proposal, and cannot review it."));
1440
        }
1441
        let role = crate::auth::roles::role_for(&app.db, Some(&a), row).await.ok().flatten();
1442
        if !crate::auth::roles::allows(role, crate::auth::Access::Read) {
1443
            return Err(format!("{name} cannot read this repository."));
1444
        }
1445
        found.push(a);
1446
    }
1447
    let mut asked = Vec::new();
1448
    for a in found {
1449
        if !pdb::request_review(&app.db, p.id, a.id, &by.username).await.map_err(|e| e.to_string())? {
1450
            continue;
1451
        }
1452
        pdb::add_event(&app.db, p.id, &by.username, "review requested", &a.username).await.ok();
1453
        crate::notify::deliver(
1454
            app,
1455
            crate::notify::Event {
1456
                kind: "proposal.review_requested",
1457
                title: format!("{}/{}#{}: {} (review requested from {})", row.owner, row.name, p.number, p.title, a.username),
1458
                url: format!("/{}/{}/proposal/{}", row.owner, row.name, p.number),
1459
                actor: by,
1460
                repo_id: row.id,
1461
                thread: None,
1462
                mention_text: "",
1463
                direct: vec![a.id],
1464
            },
1465
        )
1466
        .await;
1467
        asked.push(a.username);
1468
    }
1469
    Ok(asked)
1470
}
1471
1472
/// After a review: it answers the reviewer's request, if there was one, and
1473
/// the proposal's author is told.
1474
pub async fn reviewed(app: &Shared, row: &db::repos::RepoRow, p: &pdb::ProposalRow, by: &accounts::Account, verdict: &str) {
1475
    pdb::unrequest_review(&app.db, p.id, by.id).await.ok();
1476
    let what = match verdict {
1477
        "approve" => "approved",
1478
        "changes" => "changes requested",
1479
        _ => "reviewed",
1480
    };
1481
    crate::notify::deliver(
1482
        app,
1483
        crate::notify::Event {
1484
            kind: "proposal.review",
1485
            title: format!("{}/{}#{}: {} ({what} by {})", row.owner, row.name, p.number, p.title, by.username),
1486
            url: format!("/{}/{}/proposal/{}", row.owner, row.name, p.number),
1487
            actor: by,
1488
            repo_id: row.id,
1489
            thread: Some(("proposal", p.id)),
1490
            mention_text: "",
1491
            direct: p.author_id.into_iter().collect(),
1492
        },
1493
    )
1494
    .await;
1495
}
1496
1497
#[derive(Deserialize)]
1498
pub struct ReviewersForm {
1499
    #[serde(rename = "_csrf")]
1500
    csrf_token: String,
8e96499f Andy McCall ↶ 1501
    /// `add`, `remove`, or `set` (the menu: exactly these are asked).
cc1cd197 Andy McCall ↶ 1502
    action: String,
8e96499f Andy McCall ↶ 1503
    #[serde(default)]
1504
    username: Vec<String>,
cc1cd197 Andy McCall ↶ 1505
}
1506
1507
/// `POST /{owner}/{name}/proposal/{number}/reviewers`: the author or a
1508
/// writer asks someone to review, or withdraws the request.
1509
pub async fn reviewers(
1510
    State(app): State<Shared>,
1511
    viewer: Viewer,
1512
    Path((owner, name, number)): Path<(String, String, i64)>,
8e96499f Andy McCall ↶ 1513
    axum_extra::extract::Form(f): axum_extra::extract::Form<ReviewersForm>,
cc1cd197 Andy McCall ↶ 1514
) -> Result<Response, Error> {
1515
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1516
    let me = require(&viewer, &shell)?;
1517
    csrf(&viewer, &f.csrf_token, &shell)?;
1518
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1519
    let p = pdb::get(&app.db, row.id, number)
1520
        .await
1521
        .map_err(|e| Error::from_db(shell.clone(), e))?
1522
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1523
    if Some(me.account.id) != p.author_id && role < Role::Write {
1524
        return Err(Error::not_found(shell));
1525
    }
8e96499f Andy McCall ↶ 1526
    let names: Vec<String> = f.username.iter().map(|n| n.trim().trim_start_matches('@').to_string()).filter(|n| !n.is_empty()).collect();
1527
    let current = pdb::review_requests(&app.db, p.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1528
    // Withdrawn: those named (remove), or those the menu left out (set).
1529
    let withdraw: Vec<String> = match f.action.as_str() {
1530
        "remove" => names.clone(),
1531
        "set" => current.iter().filter(|c| !names.iter().any(|n| n.eq_ignore_ascii_case(c))).cloned().collect(),
1532
        _ => Vec::new(),
1533
    };
1534
    for who in &withdraw {
1535
        if let Some(a) = accounts::account_by_name(&app.db, who).await.ok().flatten() {
cc1cd197 Andy McCall ↶ 1536
            if pdb::unrequest_review(&app.db, p.id, a.id).await.map_err(|e| Error::from_db(shell.clone(), e))? {
1537
                pdb::add_event(&app.db, p.id, &me.account.username, "review request withdrawn", &a.username).await.ok();
1538
            }
1539
        }
8e96499f Andy McCall ↶ 1540
    }
1541
    let ask: Vec<String> = match f.action.as_str() {
1542
        "add" => names,
1543
        "set" => names.into_iter().filter(|n| !current.iter().any(|c| c.eq_ignore_ascii_case(n))).collect(),
1544
        _ => return Ok(back(&owner, &name, number, "conversation", None, None)),
1545
    };
1546
    if ask.is_empty() {
cc1cd197 Andy McCall ↶ 1547
        return Ok(back(&owner, &name, number, "conversation", None, None));
1548
    }
8e96499f Andy McCall ↶ 1549
    match request_reviewers(&app, &row, &p, &me.account, &ask).await {
cc1cd197 Andy McCall ↶ 1550
        Ok(asked) if asked.is_empty() => Ok(back(&owner, &name, number, "conversation", Some("Already asked.".into()), None)),
1551
        Ok(asked) => Ok(back(&owner, &name, number, "conversation", Some(format!("Asked {} to review.", asked.join(", "))), None)),
1552
        Err(e) => Ok(back(&owner, &name, number, "conversation", None, Some(e))),
7d2eb590 Andy McCall ↶ 1553
    }
1554
}
1555
1556
#[derive(Deserialize)]
1557
pub struct AssistantForm {
1558
    #[serde(rename = "_csrf")]
1559
    csrf_token: String,
1560
    assistant: String,
ffb67a81 Andy McCall 1561
    /// `summary` asks for a summary comment (oxygenhub#190); otherwise a review.
1562
    #[serde(default)]
1563
    task: String,
7d2eb590 Andy McCall ↶ 1564
}
1565
1566
/// `POST /{owner}/{name}/proposal/{number}/assistant`: the author or a
1567
/// writer asks an AI assistant to review (hub spec §13.4). The answer
1568
/// comes later as a review via the assistant.
1569
pub async fn assistant(
1570
    State(app): State<Shared>,
1571
    viewer: Viewer,
1572
    Path((owner, name, number)): Path<(String, String, i64)>,
1573
    Form(f): Form<AssistantForm>,
1574
) -> Result<Response, Error> {
1575
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1576
    let me = require(&viewer, &shell)?;
1577
    csrf(&viewer, &f.csrf_token, &shell)?;
1578
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 1579
    super::writable(&row, &shell)?;
7d2eb590 Andy McCall ↶ 1580
    let p = pdb::get(&app.db, row.id, number)
1581
        .await
1582
        .map_err(|e| Error::from_db(shell.clone(), e))?
1583
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1584
    if Some(me.account.id) != p.author_id && role < Role::Write {
1585
        return Err(Error::not_found(shell));
1586
    }
1587
    if !p.is_open() {
1588
        return Ok(back(&owner, &name, number, "conversation", None, Some("The proposal is not open.".into())));
1589
    }
1590
    let Some(a) = crate::assistants::enabled_for_repo(&app.db, &row)
1591
        .await
1592
        .map_err(|e| Error::from_db(shell.clone(), e))?
1593
        .into_iter()
1594
        .find(|a| a.name.eq_ignore_ascii_case(f.assistant.trim()))
1595
    else {
1596
        return Ok(back(&owner, &name, number, "conversation", None, Some(format!("No assistant called {} here.", f.assistant.trim()))));
1597
    };
1598
    let who = a.name.clone();
ffb67a81 Andy McCall 1599
    let summary = f.task == "summary";
1600
    let asked = if summary {
1601
        crate::assistants::request_summary(&app, &row, &p, &me.account, a).await
1602
    } else {
1603
        crate::assistants::request_review(&app, &row, &p, &me.account, a).await
1604
    };
1605
    match asked {
7d2eb590 Andy McCall ↶ 1606
        Ok(()) => Ok(back(
1607
            &owner,
1608
            &name,
1609
            number,
1610
            "conversation",
ffb67a81 Andy McCall 1611
            Some(if summary {
1612
                format!("Asked {who} for a summary; its comment appears here when it comes.")
1613
            } else {
1614
                format!("Asked {who} to review; its answer appears here when it comes.")
1615
            }),
7d2eb590 Andy McCall ↶ 1616
            None,
1617
        )),
1618
        Err(e) => Ok(back(&owner, &name, number, "conversation", None, Some(format!("Not asked: {e}.")))),
1619
    }
1620
}
1621
1622
/// The assistants a repository may use, by name.
1623
async fn assistant_names(app: &Shared, row: &db::repos::RepoRow) -> Vec<String> {
1624
    crate::assistants::enabled_for_repo(&app.db, row).await.unwrap_or_default().into_iter().map(|a| a.name).collect()
1625
}
1626
1627
/// The changes and the file diffs a proposal from `source` into `target`
1628
/// would carry.
1629
async fn preview_diff(
1630
    app: &Shared,
1631
    repo: &RepoName,
1632
    target: &str,
1633
    source: &str,
1634
) -> Result<(Vec<ChangeView>, Vec<oxy_core::repo::FileDiff>), crate::repos::RepoError> {
1635
    let Some((fork, bookmark)) = parse_source(app, repo, source) else { return Ok((vec![], vec![])) };
1636
    let target = target.to_string();
1637
    let fork_dir = fork.as_ref().map(|f| app.repos.dir(f));
1638
    app.repos
1639
        .read(repo, move |r, cache| {
1640
            let projection = match &fork_dir {
1641
                Some(dir) => {
1642
                    let fork_repo = oxy_core::repo::Repo::open(dir)?;
1643
                    let heads = fork_repo.bookmarks()?.into_iter().find(|b| b.name == bookmark).map(|b| b.heads).unwrap_or_default();
1644
                    pl::project(r, cache, &target, Source::Fork { fork: &fork_repo, heads })?
1645
                }
1646
                None => {
1647
                    let heads = r.bookmarks()?.into_iter().find(|b| b.name == bookmark).map(|b| b.heads).unwrap_or_default();
1648
                    pl::project(r, cache, &target, Source::Bookmark(heads))?
1649
                }
1650
            };
1651
            Ok((projection.changes, projection.files))
1652
        })
1653
        .await
1654
}
1655
1656
/// `POST /{owner}/{name}/proposals/new/draft`: an assistant drafts the
1657
/// description from the changes the proposal would add; the form comes
1658
/// back with the draft to edit (hub spec §13.4).
1659
pub async fn new_draft(
1660
    State(app): State<Shared>,
1661
    viewer: Viewer,
1662
    Path((owner, name)): Path<(String, String)>,
1663
    Form(f): Form<NewForm>,
1664
) -> Result<Page<NewProposalPage>, Error> {
1665
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposals/new"), &viewer);
1666
    let me = require(&viewer, &shell)?;
1667
    csrf(&viewer, &f.csrf_token, &shell)?;
1668
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 1669
    super::writable(&row, &shell)?;
7d2eb590 Andy McCall ↶ 1670
    let bookmarks =
1671
        app.repos.read(&repo, |r, _| Ok(r.bookmarks()?.into_iter().map(|b| b.name).collect::<Vec<_>>())).await.unwrap_or_default();
1672
    let (preview, conflicted) = preview_for(&app, &repo, &f.target, &f.source).await.unwrap_or((vec![], false));
1673
    let assistants = if preview.is_empty() { vec![] } else { assistant_names(&app, &row).await };
1674
    let mut page = NewProposalPage {
1675
        shell,
1676
        repo: RepoShell::new(&app, &row, "proposals").with_role(role),
1677
        bookmarks,
1678
        source: f.source.clone(),
1679
        target: f.target.clone(),
1680
        error: None,
1681
        preview,
1682
        conflicted,
1683
        title: f.title.clone(),
1684
        body: f.body.clone(),
1685
        assistants,
1686
    };
1687
    let assistant = crate::assistants::enabled_for_repo(&app.db, &row)
1688
        .await
1689
        .unwrap_or_default()
1690
        .into_iter()
1691
        .find(|a| a.name.eq_ignore_ascii_case(f.assistant.trim()));
1692
    let Some(a) = assistant else {
1693
        page.error = Some(format!("No assistant called {} here.", f.assistant.trim()));
1694
        return Ok(Page(page));
1695
    };
1696
    if page.preview.is_empty() {
1697
        page.error = Some("Nothing to describe: the source adds nothing to the target.".into());
1698
        return Ok(Page(page));
1699
    }
1700
    let (changes, diffs) = match preview_diff(&app, &repo, &f.target, &f.source).await {
1701
        Ok(x) => x,
1702
        Err(e) => {
1703
            page.error = Some(e.to_string());
1704
            return Ok(Page(page));
1705
        }
1706
    };
1707
    let d = crate::assistants::Draft { slot: -row.id, title: &f.title, target: &f.target, changes: &changes, diffs: &diffs };
1708
    match crate::assistants::draft_description(&app, &row, &me.account, &a, d).await {
1709
        Ok(text) => page.body = text,
1710
        Err(why) => page.error = Some(format!("{} did not answer: {why}.", a.name)),
1711
    }
1712
    Ok(Page(page))
1713
}
1714
1715
#[derive(Deserialize)]
1716
pub struct DraftForm {
1717
    #[serde(rename = "_csrf")]
1718
    csrf_token: String,
1719
    assistant: String,
1720
    #[serde(default)]
1721
    title: String,
1722
}
1723
1724
/// `POST /{owner}/{name}/proposal/{number}/draft`: an assistant drafts the
1725
/// description of an open proposal from its changes; the editor opens
1726
/// with the draft, nothing is saved (hub spec §13.4).
1727
pub async fn draft(
1728
    State(app): State<Shared>,
1729
    viewer: Viewer,
1730
    Path((owner, name, number)): Path<(String, String, i64)>,
1731
    Form(f): Form<DraftForm>,
1732
) -> Result<Response, Error> {
1733
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1734
    let me = require(&viewer, &shell)?;
1735
    csrf(&viewer, &f.csrf_token, &shell)?;
1736
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 1737
    super::writable(&row, &shell)?;
7d2eb590 Andy McCall ↶ 1738
    let p = pdb::get(&app.db, row.id, number)
1739
        .await
1740
        .map_err(|e| Error::from_db(shell.clone(), e))?
1741
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1742
    if Some(me.account.id) != p.author_id && role < Role::Maintain {
1743
        return Err(Error::not_found(shell));
1744
    }
1745
    let Some(a) = crate::assistants::enabled_for_repo(&app.db, &row)
1746
        .await
1747
        .map_err(|e| Error::from_db(shell.clone(), e))?
1748
        .into_iter()
1749
        .find(|a| a.name.eq_ignore_ascii_case(f.assistant.trim()))
1750
    else {
1751
        return Ok(back(&owner, &name, number, "conversation", None, Some(format!("No assistant called {} here.", f.assistant.trim()))));
1752
    };
1753
    let loaded = crate::web::proposals::load(&app, &repo, p.clone()).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
1754
    let title = if f.title.trim().is_empty() { p.title.clone() } else { f.title.clone() };
1755
    let d = crate::assistants::Draft { slot: p.id, title: &title, target: &p.target, changes: &loaded.changes, diffs: &loaded.diffs };
1756
    let draft = crate::assistants::draft_description(&app, &row, &me.account, &a, d).await;
1757
    match draft {
1758
        Ok(text) => {
1759
            let mut page = detail(&app, shell, &viewer, &owner, &name, number, "conversation".into(), None, None).await?;
1760
            page.0.draft = Some(text);
1761
            Ok(page.into_response())
1762
        }
1763
        Err(why) => Ok(back(&owner, &name, number, "conversation", None, Some(format!("{} did not answer: {why}.", a.name)))),
cc1cd197 Andy McCall ↶ 1764
    }
1765
}