OXYGENHUB
# acc85ac0f70b oxygenhub / crates / hub / src / web / proposals.rs
71.1 KiB · Rust · last changed Issues close from changes landing on the default bookmark, however they arrive 24 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;
542
        if let Ok(l) = load(app, &repo, p).await {
543
            if l.row.state == "landed" && l.row.landed_by.is_empty() {
544
                pdb::set_landed(&app.db, id, &l.target_state, actor, "push").await.ok();
545
            }
546
        }
547
    }
de505df5 Andy McCall ↶ 548
}
549
550
/// Reviews, approvals and blockers.
551
pub struct Verdict {
552
    pub reviews: Vec<ReviewView>,
553
    pub approvals: Vec<Approval>,
554
    pub blockers: Vec<String>,
555
    pub depends_on: Vec<i64>,
556
    pub requirements: pdb::Requirements,
557
}
558
559
pub async fn verdict(app: &Shared, loaded: &Loaded, repo_id: i64) -> Result<Verdict, sqlx::Error> {
560
    let rows = pdb::reviews(&app.db, loaded.row.id).await?;
561
    let links = accounts::identity_accounts(&app.db).await?;
562
    let sealed_accounts: Vec<String> = links.iter().filter(|(k, _)| loaded.sealing_keys.contains(k)).map(|(_, u)| u.clone()).collect();
563
    // Latest verdict per reviewer.
564
    let mut latest: BTreeMap<String, &pdb::ReviewRow> = BTreeMap::new();
7d2eb590 Andy McCall ↶ 565
    for r in rows.iter().filter(|r| r.via.is_empty()) {
566
        // An assistant's answer is never the person's own verdict.
de505df5 Andy McCall ↶ 567
        latest.insert(r.author.clone(), r);
568
    }
569
    let mut approvals = Vec::new();
570
    for (who, r) in &latest {
571
        if r.verdict == "approve" {
572
            let sealed = sealed_accounts.contains(who);
573
            let key = links.iter().find(|(k, u)| u == who && loaded.sealing_keys.contains(k)).map(|(k, _)| k.clone());
574
            approvals.push(Approval { account: who.clone(), sealed, key });
575
        }
576
    }
577
    let reviews = rows
578
        .iter()
579
        .map(|r| ReviewView {
580
            row: r.clone(),
581
            body_html: render::markdown::render(&r.body, "/", "/"),
582
            sealed: r.verdict == "approve" && sealed_accounts.contains(&r.author),
583
        })
584
        .collect();
585
    let requirements = pdb::requirements(&app.db, repo_id).await?;
586
    let mut blockers = Vec::new();
0b20f1ec Andy McCall ↶ 587
    // Only an open proposal can be held back.
588
    if !loaded.row.is_open() {
589
        return Ok(Verdict { reviews, approvals, blockers, depends_on: vec![], requirements });
590
    }
de505df5 Andy McCall ↶ 591
    if loaded.row.state == "draft" {
592
        blockers.push("the proposal is a draft".into());
593
    }
594
    if loaded.hashes.is_empty() {
595
        blockers.push("the proposal adds no changes".into());
596
    }
597
    let sealed_count = approvals.iter().filter(|a| a.sealed).count() as i64;
598
    if sealed_count < requirements.required_approvals {
599
        blockers.push(format!("{sealed_count} of {} required sealed approvals", requirements.required_approvals));
600
    }
601
    if requirements.require_owners {
602
        let missing: Vec<&String> = loaded.owners.iter().filter(|o| !approvals.iter().any(|a| a.sealed && &a.account == *o)).collect();
603
        if !missing.is_empty() {
604
            blockers.push(format!("code owners still to approve: {}", missing.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")));
605
        }
606
    }
607
    if loaded.conflicted && !requirements.allow_conflicts {
608
        blockers.push("landing would carry conflicts, which this repository refuses".into());
609
    }
b64e2537 Andy McCall ↶ 610
    let required = db::hooks::required_checks(&app.db, repo_id).await?;
611
    if !required.is_empty() {
612
        let checks = db::hooks::checks_for_state(&app.db, repo_id, &loaded.state).await?;
613
        let missing: Vec<String> =
614
            required.iter().filter(|n| !checks.iter().any(|c| &c.name == *n && c.status == "passed")).cloned().collect();
615
        if !missing.is_empty() {
616
            blockers.push(format!("required checks not passed on the projected state: {}", missing.join(", ")));
617
        }
618
    }
de505df5 Andy McCall ↶ 619
    let requesting: Vec<&String> = latest.iter().filter(|(_, r)| r.verdict == "changes").map(|(who, _)| who).collect();
620
    if !requesting.is_empty() {
621
        blockers.push(format!("changes requested by {}", requesting.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")));
622
    }
623
    // Stacking: another open, earlier proposal whose changes this one includes.
624
    let mut depends_on = Vec::new();
625
    for other in pdb::list(&app.db, repo_id, &["open", "draft"]).await? {
626
        if other.id == loaded.row.id || other.number > loaded.row.number {
627
            continue;
628
        }
629
        let theirs = other.projected_changes();
630
        if !theirs.is_empty() && theirs.iter().all(|h| loaded.hashes.iter().any(|m| m.to_hex() == *h)) {
631
            depends_on.push(other.number);
632
        }
633
    }
634
    if !depends_on.is_empty() {
635
        blockers.push(format!("depends on {}", depends_on.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", ")));
636
    }
637
    Ok(Verdict { reviews, approvals, blockers, depends_on, requirements })
638
}
639
640
#[derive(Template)]
641
#[template(path = "proposal.html")]
642
pub struct ProposalPage {
643
    shell: Shell,
644
    repo: RepoShell,
645
    p: pdb::ProposalRow,
38833ed7 Andy McCall ↶ 646
    /// Issues it closes, from its description and its changes.
647
    closes: Vec<super::chain::Link>,
a1b98695 Andy McCall ↶ 648
    /// Projects the viewer may add it to.
649
    project_choices: Option<Vec<db::projects::Project>>,
650
    /// Comments (not anchored to a line), reviews and events, oldest first.
651
    timeline: Vec<Entry>,
652
    /// The viewer may set labels (triage or above).
653
    can_triage: bool,
de505df5 Andy McCall ↶ 654
    body_html: String,
655
    tab: String,
656
    changes: Vec<ChangeView>,
657
    files: Vec<FileRows>,
9df855f2 Andy McCall ↶ 658
    diffs: Vec<oxy_core::repo::FileDiff>,
659
    bases: std::collections::BTreeMap<String, Vec<u8>>,
660
    /// Whitespace-only changes are hidden (`?w=1`).
661
    ignore_ws: bool,
de505df5 Andy McCall ↶ 662
    conflicts: Vec<ConflictView>,
663
    conflicted: bool,
664
    comments: Vec<CommentView>,
665
    /// Anchored comments by (path, current line).
666
    placed: HashMap<(String, usize), Vec<usize>>,
667
    outdated: Vec<usize>,
668
    reviews: Vec<ReviewView>,
669
    approvals: Vec<Approval>,
670
    blockers: Vec<String>,
671
    depends_on: Vec<i64>,
672
    events: Vec<pdb::EventRow>,
673
    owners: Vec<String>,
674
    requirements: pdb::Requirements,
675
    landed_already: bool,
676
    can_edit: bool,
4f37afcc Andy McCall ↶ 677
    /// The landed proposal's source bookmark, when it is this repository's,
678
    /// still there, and the viewer may delete it (oxygenhub#86).
679
    deletable_source: Option<String>,
de505df5 Andy McCall ↶ 680
    can_land: bool,
681
    hub_can_land: bool,
682
    notice: Option<String>,
683
    error: Option<String>,
684
    heads: Vec<String>,
685
    state_hash: String,
686
    source_label: String,
687
    api_url: String,
18e381ea Andy McCall ↶ 688
    labels: Vec<db::issues::Label>,
689
    all_labels: Vec<db::issues::Label>,
b64e2537 Andy McCall ↶ 690
    checks: Vec<db::hooks::Check>,
691
    required_checks: Vec<String>,
e1ec9fbf Andy McCall ↶ 692
    /// Projects this proposal is on that the viewer may see, with the column.
693
    projects: Vec<(db::projects::Project, String)>,
cc1cd197 Andy McCall ↶ 694
    /// Asked to review and not yet reviewing.
695
    requested: Vec<String>,
8e96499f Andy McCall ↶ 696
    /// Who can be asked to review, for the sidebar's menu (oxygenhub#84).
697
    reviewable: Vec<String>,
cc1cd197 Andy McCall ↶ 698
    /// The viewer may ask for reviews (the author, or a writer).
699
    can_request: bool,
7d2eb590 Andy McCall ↶ 700
    /// AI assistants the viewer may ask, by name (hub spec §13.4).
701
    assistants: Vec<String>,
702
    /// A description an assistant just drafted, for the editor.
703
    draft: Option<String>,
de505df5 Andy McCall ↶ 704
}
705
706
#[derive(Deserialize)]
707
pub struct DetailQuery {
708
    tab: Option<String>,
a1b98695 Andy McCall ↶ 709
    /// What an action said, after it redirected here.
9df855f2 Andy McCall ↶ 710
    #[serde(default)]
a1b98695 Andy McCall ↶ 711
    notice: Option<String>,
712
    #[serde(default)]
713
    error: Option<String>,
714
    #[serde(default)]
9df855f2 Andy McCall ↶ 715
    w: Option<String>,
de505df5 Andy McCall ↶ 716
}
717
718
/// The page assembler every action ends in; its arguments are the route
719
/// plus what to say, and a struct would only rename them.
720
#[allow(clippy::too_many_arguments)]
721
async fn detail(
722
    app: &Shared,
723
    shell: Shell,
724
    viewer: &Viewer,
725
    owner: &str,
726
    name: &str,
727
    number: i64,
728
    tab: String,
729
    notice: Option<String>,
730
    error: Option<String>,
731
) -> Result<Page<ProposalPage>, Error> {
732
    let (repo, row, role) = lookup(app, &shell, viewer, owner, name).await?;
733
    let p = pdb::get(&app.db, row.id, number)
734
        .await
735
        .map_err(|e| Error::from_db(shell.clone(), e))?
736
        .ok_or_else(|| Error::not_found(shell.clone()))?;
737
    let loaded = load(app, &repo, p).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
738
    // A proposal whose changes all reached the target landed by another route.
739
    if loaded.landed_already && loaded.row.is_open() {
740
        pdb::set_state(&app.db, loaded.row.id, "landed", &loaded.target_state).await.ok();
741
        pdb::add_event(&app.db, loaded.row.id, "", "landed", "every change reached the target").await.ok();
742
    }
743
    let p = pdb::get(&app.db, row.id, number).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(loaded.row.clone());
744
    let v = verdict(app, &loaded, row.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
745
    let comment_rows = pdb::comments(&app.db, loaded.row.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
746
    let events = pdb::events(&app.db, loaded.row.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
747
    // Place anchored comments at their atom's current line.
748
    let mut by_atom: HashMap<(String, String, u32), usize> = HashMap::new();
749
    for ((path, line), (h, i)) in &loaded.atoms {
750
        by_atom.insert((path.clone(), h.clone(), *i), *line);
751
    }
752
    let mut comments = Vec::new();
753
    let mut placed: HashMap<(String, usize), Vec<usize>> = HashMap::new();
754
    let mut outdated = Vec::new();
755
    for (idx, c) in comment_rows.into_iter().enumerate() {
756
        let line = if c.anchor_change.is_empty() {
757
            None
758
        } else {
759
            by_atom.get(&(c.path.clone(), c.anchor_change.clone(), c.anchor_index as u32)).copied()
760
        };
761
        if !c.anchor_change.is_empty() {
762
            match line {
763
                Some(l) => placed.entry((c.path.clone(), l)).or_default().push(idx),
764
                None => outdated.push(idx),
765
            }
766
        }
767
        comments.push(CommentView { body_html: render::markdown::render(&c.body, "/", "/"), row: c, line });
768
    }
769
    let mut changes = loaded.changes.clone();
770
    super::attribute(app, &mut changes.iter_mut().collect::<Vec<_>>()).await;
771
    let me = viewer.account();
772
    let can_edit = me.is_some_and(|a| Some(a.id) == p.author_id || role >= Role::Maintain);
4f37afcc Andy McCall ↶ 773
    let deletable_source =
774
        if p.state == "landed" && p.source_kind == "bookmark" && role >= Role::Write && p.source_bookmark != row.default_bookmark {
775
            let b = p.source_bookmark.clone();
776
            app.repos
777
                .read(&repo, move |r, _| Ok(r.view()?.bookmarks.contains_key(&b)))
778
                .await
779
                .unwrap_or(false)
780
                .then(|| p.source_bookmark.clone())
781
        } else {
782
            None
783
        };
de505df5 Andy McCall ↶ 784
    let can_land = role >= Role::Write && p.is_open() && v.blockers.is_empty();
cc1cd197 Andy McCall ↶ 785
    let can_request = p.is_open() && me.is_some_and(|a| Some(a.id) == p.author_id || role >= Role::Write);
8e96499f Andy McCall ↶ 786
    let requested = pdb::review_requests(&app.db, p.id).await.unwrap_or_default();
787
    let mut reviewable: Vec<String> = if can_request {
788
        accounts::assignable(&app.db, row.id, &row.owner).await.unwrap_or_default().into_iter().filter(|u| *u != p.author).collect()
789
    } else {
790
        Vec::new()
791
    };
792
    for r in &requested {
793
        if !reviewable.iter().any(|x| x.eq_ignore_ascii_case(r)) {
794
            reviewable.push(r.clone());
795
        }
796
    }
7d2eb590 Andy McCall ↶ 797
    let assistants: Vec<String> = if (can_request || can_edit) && p.is_open() { assistant_names(app, &row).await } else { Vec::new() };
14530604 Andy McCall ↶ 798
    let delegated = match viewer.account() {
799
        Some(a) => super::edit::delegated_identity(app, a.id).await.is_some(),
800
        None => false,
801
    };
802
    let hub_can_land = delegated || app.repos.read(&repo, |r, _| Ok(r.current_policy()?.is_none())).await.unwrap_or(false);
de505df5 Andy McCall ↶ 803
    let source_label = match p.source_kind.as_str() {
804
        "fork" => format!(
805
            "fork {}",
806
            db::repos::get_by_id(&app.db, p.source_repo_id.unwrap_or(0))
807
                .await
808
                .ok()
809
                .flatten()
810
                .map(|r| format!("{}:{}", r.slug(), p.source_bookmark))
811
                .unwrap_or_default()
812
        ),
813
        "changes" => format!("{} changes", p.source_changes().len()),
814
        _ => p.source_bookmark.clone(),
815
    };
e1ec9fbf Andy McCall ↶ 816
    let projects = super::projects::placements_for(app, viewer, &row, p.number).await;
38833ed7 Andy McCall ↶ 817
    let texts: Vec<String> = std::iter::once(p.body.clone()).chain(changes.iter().map(|c| format!("{}\n{}", c.title, c.body))).collect();
818
    let closes = super::chain::issues_closed_by(app, &row, &texts.iter().map(String::as_str).collect::<Vec<_>>()).await;
a1b98695 Andy McCall ↶ 819
    let project_choices = super::projects::project_choices(app, viewer, &row, &projects).await;
820
    let mut dated: Vec<(i64, Entry)> = Vec::new();
821
    for (index, c) in comments.iter().enumerate() {
822
        if c.row.anchor_change.is_empty() {
823
            dated.push((c.row.created_ms, Entry { kind: "comment", index }));
824
        }
825
    }
826
    for (index, r) in v.reviews.iter().enumerate() {
827
        dated.push((r.row.created_ms, Entry { kind: "review", index }));
828
    }
829
    for (index, e) in events.iter().enumerate() {
830
        dated.push((e.at_ms, Entry { kind: "event", index }));
831
    }
832
    dated.sort_by_key(|(at, _)| *at);
833
    let timeline: Vec<Entry> = dated.into_iter().map(|(_, e)| e).collect();
de505df5 Andy McCall ↶ 834
    Ok(Page(ProposalPage {
a1b98695 Andy McCall ↶ 835
        can_triage: role >= Role::Triage,
836
        timeline,
38833ed7 Andy McCall ↶ 837
        closes,
a1b98695 Andy McCall ↶ 838
        project_choices,
e1ec9fbf Andy McCall ↶ 839
        projects,
de505df5 Andy McCall ↶ 840
        shell,
841
        repo: RepoShell::new(app, &row, "proposals").with_role(role),
c79a1111 Andy McCall ↶ 842
        body_html: super::issues::markdown(app, &row, &row.default_bookmark, &p.body).await,
de505df5 Andy McCall ↶ 843
        p,
844
        tab,
845
        changes,
846
        files: loaded.files,
9df855f2 Andy McCall ↶ 847
        diffs: loaded.diffs,
848
        bases: loaded.bases,
849
        ignore_ws: false,
de505df5 Andy McCall ↶ 850
        conflicts: loaded.conflicts,
851
        conflicted: loaded.conflicted,
852
        comments,
853
        placed,
854
        outdated,
855
        reviews: v.reviews,
856
        approvals: v.approvals,
857
        blockers: v.blockers,
858
        depends_on: v.depends_on,
859
        events,
860
        owners: loaded.owners,
861
        requirements: v.requirements,
862
        landed_already: loaded.landed_already,
863
        can_edit,
4f37afcc Andy McCall ↶ 864
        deletable_source,
de505df5 Andy McCall ↶ 865
        can_land,
866
        hub_can_land,
867
        notice,
868
        error,
869
        heads: loaded.heads.iter().map(|h| h.to_hex()).collect(),
b64e2537 Andy McCall ↶ 870
        state_hash: loaded.state.clone(),
de505df5 Andy McCall ↶ 871
        source_label,
872
        api_url: format!("{}/api/v1/repos/{owner}/{name}/proposals/{number}", app.config.base_url()),
18e381ea Andy McCall ↶ 873
        labels: db::issues::proposal_labels(&app.db, loaded.row.id).await.unwrap_or_default(),
874
        all_labels: db::issues::labels(&app.db, row.id).await.unwrap_or_default(),
b64e2537 Andy McCall ↶ 875
        checks: db::hooks::checks_for_state(&app.db, row.id, &loaded.state).await.unwrap_or_default(),
876
        required_checks: db::hooks::required_checks(&app.db, row.id).await.unwrap_or_default(),
8e96499f Andy McCall ↶ 877
        requested,
878
        reviewable,
7d2eb590 Andy McCall ↶ 879
        assistants,
880
        draft: None,
cc1cd197 Andy McCall ↶ 881
        can_request,
de505df5 Andy McCall ↶ 882
    }))
883
}
884
a1b98695 Andy McCall ↶ 885
/// Back to the proposal after an action, with what to say: a redirect, so
886
/// reloading the page (the checks script does) never repeats the action.
887
fn back(owner: &str, name: &str, number: i64, tab: &str, notice: Option<String>, error: Option<String>) -> Response {
888
    let mut url = format!("/{owner}/{name}/proposal/{number}?tab={tab}");
889
    if let Some(n) = notice {
890
        url.push_str(&format!("&notice={}", super::settings::urlencode(&n)));
891
    }
892
    if let Some(e) = error {
893
        url.push_str(&format!("&error={}", super::settings::urlencode(&e)));
894
    }
895
    Redirect::to(&url).into_response()
896
}
897
de505df5 Andy McCall ↶ 898
pub async fn show(
899
    State(app): State<Shared>,
900
    viewer: Viewer,
901
    Path((owner, name, number)): Path<(String, String, i64)>,
902
    Query(q): Query<DetailQuery>,
903
) -> Result<Page<ProposalPage>, Error> {
904
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
a1b98695 Andy McCall ↶ 905
    let mut page =
906
        detail(&app, shell, &viewer, &owner, &name, number, q.tab.unwrap_or_else(|| "conversation".into()), q.notice, q.error).await?;
9df855f2 Andy McCall ↶ 907
    if q.w.as_deref() == Some("1") {
908
        // Hide whitespace-only changes: the same hunks, rendered again.
909
        page.0.files =
910
            super::history::render_files_with(&page.0.diffs, &page.0.bases, crate::render::diff::Options { ignore_whitespace: true });
911
        page.0.ignore_ws = true;
912
    }
913
    Ok(page)
de505df5 Andy McCall ↶ 914
}
915
916
// ---------------------------------------------------------------- actions
917
918
#[derive(Deserialize)]
919
pub struct CommentForm {
920
    #[serde(rename = "_csrf")]
921
    csrf_token: String,
922
    body: String,
923
    #[serde(default)]
924
    path: String,
925
    #[serde(default)]
926
    line: Option<usize>,
927
}
928
929
pub async fn comment(
930
    State(app): State<Shared>,
931
    viewer: Viewer,
932
    Path((owner, name, number)): Path<(String, String, i64)>,
933
    Form(f): Form<CommentForm>,
a1b98695 Andy McCall ↶ 934
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 935
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
936
    let me = require(&viewer, &shell)?;
937
    csrf(&viewer, &f.csrf_token, &shell)?;
938
    let (repo, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 939
    super::writable(&row, &shell)?;
de505df5 Andy McCall ↶ 940
    let p = pdb::get(&app.db, row.id, number)
941
        .await
942
        .map_err(|e| Error::from_db(shell.clone(), e))?
943
        .ok_or_else(|| Error::not_found(shell.clone()))?;
944
    if f.body.trim().is_empty() {
a1b98695 Andy McCall ↶ 945
        return Ok(back(&owner, &name, number, "conversation", None, Some("An empty comment says nothing.".into())));
de505df5 Andy McCall ↶ 946
    }
947
    let anchor = match (f.path.trim(), f.line) {
948
        ("", _) | (_, None) => None,
949
        (path, Some(line)) => {
950
            let loaded = load(&app, &repo, p.clone()).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
951
            loaded.atoms.get(&(path.to_string(), line)).cloned()
952
        }
953
    };
954
    let tab = if anchor.is_some() { "files" } else { "conversation" };
955
    pdb::add_comment(
956
        &app.db,
957
        p.id,
958
        Some(me.account.id),
959
        &me.account.username,
960
        f.body.trim(),
961
        f.path.trim(),
962
        anchor.as_ref().map(|(h, i)| (h.as_str(), *i as i64)),
963
    )
964
    .await
965
    .map_err(|e| Error::from_db(shell.clone(), e))?;
a1b98695 Andy McCall ↶ 966
    Ok(back(&owner, &name, number, tab, None, None))
de505df5 Andy McCall ↶ 967
}
968
969
#[derive(Deserialize)]
970
pub struct ReviewForm {
971
    #[serde(rename = "_csrf")]
972
    csrf_token: String,
973
    verdict: String,
974
    #[serde(default)]
975
    body: String,
976
}
977
978
pub async fn review(
979
    State(app): State<Shared>,
980
    viewer: Viewer,
981
    Path((owner, name, number)): Path<(String, String, i64)>,
982
    Form(f): Form<ReviewForm>,
a1b98695 Andy McCall ↶ 983
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 984
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
985
    let me = require(&viewer, &shell)?;
986
    csrf(&viewer, &f.csrf_token, &shell)?;
987
    let (_, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 988
    super::writable(&row, &shell)?;
de505df5 Andy McCall ↶ 989
    let p = pdb::get(&app.db, row.id, number)
990
        .await
991
        .map_err(|e| Error::from_db(shell.clone(), e))?
992
        .ok_or_else(|| Error::not_found(shell.clone()))?;
993
    if !matches!(f.verdict.as_str(), "comment" | "changes" | "approve") {
994
        return Err(Error::bad(shell, "a review is comment, changes or approve"));
995
    }
996
    if f.verdict == "approve" && Some(me.account.id) == p.author_id {
a1b98695 Andy McCall ↶ 997
        return Ok(back(&owner, &name, number, "conversation", None, Some("You cannot approve your own proposal.".into())));
de505df5 Andy McCall ↶ 998
    }
999
    pdb::add_review(&app.db, p.id, me.account.id, &me.account.username, &f.verdict, f.body.trim())
1000
        .await
1001
        .map_err(|e| Error::from_db(shell.clone(), e))?;
1002
    pdb::add_event(&app.db, p.id, &me.account.username, &format!("review.{}", f.verdict), "").await.ok();
cc1cd197 Andy McCall ↶ 1003
    reviewed(&app, &row, &p, &me.account, &f.verdict).await;
b64e2537 Andy McCall ↶ 1004
    crate::hooks::emit(&app, &row, "review", &me.account.username, serde_json::json!({ "number": number, "verdict": f.verdict })).await;
de505df5 Andy McCall ↶ 1005
    let notice = if f.verdict == "approve" {
1006
        Some(format!(
1007
            "Approval recorded. It counts once you seal the changes: oxy seal --proposal {}/{owner}/{name}/proposal/{number}",
1008
            app.config.base_url()
1009
        ))
1010
    } else {
1011
        None
1012
    };
a1b98695 Andy McCall ↶ 1013
    Ok(back(&owner, &name, number, "conversation", notice, None))
de505df5 Andy McCall ↶ 1014
}
1015
1016
#[derive(Deserialize)]
1017
pub struct EditForm {
1018
    #[serde(rename = "_csrf")]
1019
    csrf_token: String,
1020
    title: String,
1021
    #[serde(default)]
1022
    body: String,
1023
    target: String,
1024
}
1025
1026
pub async fn edit(
1027
    State(app): State<Shared>,
1028
    viewer: Viewer,
1029
    Path((owner, name, number)): Path<(String, String, i64)>,
1030
    Form(f): Form<EditForm>,
a1b98695 Andy McCall ↶ 1031
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 1032
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1033
    let me = require(&viewer, &shell)?;
1034
    csrf(&viewer, &f.csrf_token, &shell)?;
1035
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1036
    let p = pdb::get(&app.db, row.id, number)
1037
        .await
1038
        .map_err(|e| Error::from_db(shell.clone(), e))?
1039
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1040
    if Some(me.account.id) != p.author_id && role < Role::Maintain {
1041
        return Err(Error::not_found(shell));
1042
    }
1043
    let target = if crate::repos::names::valid_segment(f.target.trim()) { f.target.trim() } else { &p.target };
1044
    pdb::edit(&app.db, p.id, f.title.trim(), f.body.trim(), target).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1045
    pdb::add_event(&app.db, p.id, &me.account.username, "edited", "").await.ok();
a1b98695 Andy McCall ↶ 1046
    Ok(back(&owner, &name, number, "conversation", Some("Saved.".into()), None))
de505df5 Andy McCall ↶ 1047
}
1048
1049
#[derive(Deserialize)]
1050
pub struct StateForm {
1051
    #[serde(rename = "_csrf")]
1052
    csrf_token: String,
1053
    action: String,
1054
}
1055
1056
pub async fn state(
1057
    State(app): State<Shared>,
1058
    viewer: Viewer,
1059
    Path((owner, name, number)): Path<(String, String, i64)>,
1060
    Form(f): Form<StateForm>,
a1b98695 Andy McCall ↶ 1061
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 1062
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1063
    let me = require(&viewer, &shell)?;
1064
    csrf(&viewer, &f.csrf_token, &shell)?;
1065
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1066
    let p = pdb::get(&app.db, row.id, number)
1067
        .await
1068
        .map_err(|e| Error::from_db(shell.clone(), e))?
1069
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1070
    if Some(me.account.id) != p.author_id && role < Role::Triage {
1071
        return Err(Error::not_found(shell));
1072
    }
1073
    let new_state = match (f.action.as_str(), p.state.as_str()) {
1074
        ("close", "open" | "draft") => "closed",
1075
        ("reopen", "closed") => "open",
1076
        ("ready", "draft") => "open",
1077
        ("draft", "open") => "draft",
1078
        _ => return Err(Error::bad(shell, "that transition is not possible")),
1079
    };
1080
    pdb::set_state(&app.db, p.id, new_state, "").await.map_err(|e| Error::from_db(shell.clone(), e))?;
1081
    pdb::add_event(&app.db, p.id, &me.account.username, new_state, "").await.ok();
b64e2537 Andy McCall ↶ 1082
    crate::hooks::emit(&app, &row, &format!("proposal.{new_state}"), &me.account.username, serde_json::json!({ "number": number })).await;
a1b98695 Andy McCall ↶ 1083
    Ok(back(&owner, &name, number, "conversation", None, None))
de505df5 Andy McCall ↶ 1084
}
1085
1086
pub async fn resolve_comment(
1087
    State(app): State<Shared>,
1088
    viewer: Viewer,
1089
    Path((owner, name, number, id)): Path<(String, String, i64, i64)>,
1090
    Form(f): Form<super::session::CsrfForm>,
a1b98695 Andy McCall ↶ 1091
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 1092
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1093
    require(&viewer, &shell)?;
1094
    csrf(&viewer, &f.csrf, &shell)?;
1095
    let (_, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1096
    let p = pdb::get(&app.db, row.id, number)
1097
        .await
1098
        .map_err(|e| Error::from_db(shell.clone(), e))?
1099
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1100
    let current: Option<bool> = sqlx::query_scalar("SELECT resolved FROM proposal_comments WHERE id = ? AND proposal_id = ?")
1101
        .bind(id)
1102
        .bind(p.id)
1103
        .fetch_optional(&app.db)
1104
        .await
1105
        .map_err(|e| Error::from_db(shell.clone(), e))?;
1106
    if let Some(r) = current {
1107
        pdb::set_comment_resolved(&app.db, id, !r).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1108
    }
a1b98695 Andy McCall ↶ 1109
    Ok(back(&owner, &name, number, "files", None, None))
de505df5 Andy McCall ↶ 1110
}
1111
1112
/// Land from the hub: only when the repository has no trust policy (the
1113
/// hub never signs a reference update the policy would have to admit).
1114
pub async fn land(
1115
    State(app): State<Shared>,
1116
    viewer: Viewer,
1117
    Path((owner, name, number)): Path<(String, String, i64)>,
1118
    Form(f): Form<super::session::CsrfForm>,
a1b98695 Andy McCall ↶ 1119
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 1120
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1121
    let me = require(&viewer, &shell)?;
1122
    csrf(&viewer, &f.csrf, &shell)?;
1123
    let (repo, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
0b20f1ec Andy McCall ↶ 1124
    match land_as(&app, &repo, &row, &me.account, number, "web").await {
a1b98695 Andy McCall ↶ 1125
        Ok(_) => Ok(back(&owner, &name, number, "conversation", Some("Landed.".into()), None)),
1f1eb06a Andy McCall ↶ 1126
        Err(Landing::NotFound) => Err(Error::not_found(shell)),
a1b98695 Andy McCall ↶ 1127
        Err(Landing::Refused(m)) => Ok(back(&owner, &name, number, "conversation", None, Some(m))),
1f1eb06a Andy McCall ↶ 1128
    }
1129
}
1130
1131
/// Why a proposal did not land.
1132
pub enum Landing {
1133
    NotFound,
1134
    Refused(String),
1135
}
1136
1137
/// Land proposal `number` as `me` (hub spec §8.4), who has write access:
1138
/// refused while it is not open or has blockers. Moves the target bookmark
1139
/// (attested by the hub key on `me`'s behalf when they delegated to it),
0b20f1ec Andy McCall ↶ 1140
/// then records, announces and audits the landing, saying how it was done
1141
/// (`via`: `web`, or `api (token NAME)`). Returns the new state.
1f1eb06a Andy McCall ↶ 1142
pub async fn land_as(
1143
    app: &Shared,
1144
    repo: &RepoName,
1145
    row: &db::repos::RepoRow,
1146
    me: &accounts::Account,
1147
    number: i64,
0b20f1ec Andy McCall ↶ 1148
    via: &str,
1f1eb06a Andy McCall ↶ 1149
) -> Result<String, Landing> {
1150
    let (owner, name) = (row.owner.clone(), row.name.clone());
1151
    let refused = |e: String| Landing::Refused(e);
1152
    let p = pdb::get(&app.db, row.id, number).await.map_err(|e| refused(e.to_string()))?.ok_or(Landing::NotFound)?;
1153
    let loaded = load(app, repo, p.clone()).await.map_err(|e| refused(e.to_string()))?;
1154
    let v = verdict(app, &loaded, row.id).await.map_err(|e| refused(e.to_string()))?;
1155
    if !p.is_open() {
1156
        return Err(refused(format!("Cannot land: the proposal is {}", p.state)));
1157
    }
1158
    if !v.blockers.is_empty() {
1159
        return Err(refused(format!("Cannot land: {}", v.blockers.join("; "))));
de505df5 Andy McCall ↶ 1160
    }
1161
    let target = p.target.clone();
1162
    let heads = loaded.heads.clone();
14530604 Andy McCall ↶ 1163
    // With a delegation the landing is attested by the hub key on the
1164
    // user's behalf, which a policy accepts when it lets the user update
1165
    // the target (spec §14.5); without one, only a policy-free repository
1166
    // can be landed here.
1f1eb06a Andy McCall ↶ 1167
    let result = match super::edit::signer_for(app, me.id).await {
1168
        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 ↶ 1169
        Err(why) => {
1170
            app.repos
1f1eb06a Andy McCall ↶ 1171
                .write(repo, move |r, _| {
14530604 Andy McCall ↶ 1172
                    if r.current_policy()?.is_some() {
1173
                        return Err(crate::repos::RepoError::Oxy(oxy_core::repo::RepoError::Msg(format!(
1174
                            "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}"
1175
                        ))));
1176
                    }
1177
                    r.bookmark_set(&target, &heads)?;
1178
                    Ok(pl::state_ref(&heads).to_hex())
1179
                })
1180
                .await
1181
        }
1182
    };
1f1eb06a Andy McCall ↶ 1183
    let state = result.map_err(|e| refused(e.to_string()))?;
0b20f1ec Andy McCall ↶ 1184
    pdb::set_landed(&app.db, p.id, &state, &me.username, via).await.map_err(|e| refused(e.to_string()))?;
1185
    let how = if v.approvals.is_empty() { format!("{via}, with no approval") } else { via.to_string() };
1186
    pdb::add_event(&app.db, p.id, &me.username, "landed", &how).await.ok();
1f1eb06a Andy McCall ↶ 1187
    crate::hooks::emit(
1188
        app,
1189
        row,
1190
        "proposal.landed",
1191
        &me.username,
1192
        serde_json::json!({ "number": number, "target": p.target, "state": state }),
1193
    )
1194
    .await;
1195
    crate::notify::deliver(
1196
        app,
1197
        crate::notify::Event {
1198
            kind: "proposal.landed",
1199
            title: format!("{owner}/{name}#{number}: {} landed", p.title),
1200
            url: format!("/{owner}/{name}/proposal/{number}"),
1201
            actor: me,
1202
            repo_id: row.id,
1203
            thread: Some(("proposal", p.id)),
1204
            mention_text: "",
1205
            direct: p.author_id.into_iter().collect(),
1206
        },
1207
    )
1208
    .await;
1209
    if p.target == row.default_bookmark {
1210
        let messages: Vec<(String, String)> = loaded.changes.iter().map(|c| (c.hash.clone(), format!("{}\n{}", c.title, c.body))).collect();
1211
        super::issues::close_from_messages(app, row, &messages).await;
de505df5 Andy McCall ↶ 1212
    }
0b20f1ec Andy McCall ↶ 1213
    accounts::audit(&app.db, Some(me), "proposal.landed", &format!("{owner}/{name}#{number}"), &how).await.ok();
1f1eb06a Andy McCall ↶ 1214
    db::repos::record_push(
1215
        &app.db,
1216
        row.id,
1217
        Some((me.id, me.username.as_str())),
1218
        &[db::repos::PushOutcome {
1219
            reference: p.target.clone(),
1220
            ok: true,
0b20f1ec Andy McCall ↶ 1221
            reason: format!("landed #{number} ({how})"),
1f1eb06a Andy McCall ↶ 1222
            old_state: loaded.target_state.clone(),
1223
            new_state: state.clone(),
1224
            heads: loaded.heads.len() as i64,
1225
            changes: loaded.hashes.len() as i64,
1226
        }],
1227
    )
1228
    .await
1229
    .ok();
acc85ac0 Andy McCall ↶ 1230
    // A landing on the default bookmark closes the issues its changes (and
1231
    // its description) say they close, as a push there would.
1232
    if p.target == row.default_bookmark {
1233
        let body = (format!("proposal #{number}"), p.body.clone());
1234
        crate::web::issues::close_from_arrived(app, row, loaded.target_heads.clone(), loaded.heads.clone(), Some(body)).await;
1235
    }
757195ad Andy McCall ↶ 1236
    // Diffusion (#150): a landing moves the target as a push would, so the
1237
    // pin index follows it, and the consumers of a moved default bookmark
1238
    // are bumped.
1239
    let heads = loaded.heads.clone();
1240
    let moved = vec![(p.target.clone(), state.clone(), heads.clone())];
1241
    crate::diffusion::after_push(app, row, &moved).await;
1242
    if p.target == row.default_bookmark {
1243
        let (app, row) = (app.clone(), row.clone());
1244
        tokio::spawn(async move { crate::diffusion::propagate(&app, &row, heads, false).await });
1245
    }
1f1eb06a Andy McCall ↶ 1246
    Ok(state)
de505df5 Andy McCall ↶ 1247
}
1248
18e381ea Andy McCall ↶ 1249
#[derive(Deserialize)]
1250
pub struct LabelsForm {
1251
    #[serde(rename = "_csrf")]
1252
    csrf_token: String,
1253
    #[serde(default)]
1254
    label: Vec<i64>,
1255
}
1256
1257
pub async fn set_labels(
1258
    State(app): State<Shared>,
1259
    viewer: Viewer,
1260
    Path((owner, name, number)): Path<(String, String, i64)>,
1261
    axum_extra::extract::Form(f): axum_extra::extract::Form<LabelsForm>,
a1b98695 Andy McCall ↶ 1262
) -> Result<Response, Error> {
18e381ea Andy McCall ↶ 1263
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1264
    require(&viewer, &shell)?;
1265
    csrf(&viewer, &f.csrf_token, &shell)?;
1266
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1267
    if role < Role::Triage {
1268
        return Err(Error::not_found(shell));
1269
    }
1270
    let p = pdb::get(&app.db, row.id, number)
1271
        .await
1272
        .map_err(|e| Error::from_db(shell.clone(), e))?
1273
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1274
    for l in db::issues::labels(&app.db, row.id).await.map_err(|e| Error::from_db(shell.clone(), e))? {
1275
        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))?;
1276
    }
a1b98695 Andy McCall ↶ 1277
    Ok(back(&owner, &name, number, "conversation", None, None))
18e381ea Andy McCall ↶ 1278
}
1279
b64e2537 Andy McCall ↶ 1280
/// `GET /{owner}/{name}/proposal/{number}/events`: server-sent events for
1281
/// checks on the projected state (hub spec §13.1).
1282
pub async fn events(
1283
    State(app): State<Shared>,
1284
    viewer: Viewer,
1285
    Path((owner, name, number)): Path<(String, String, i64)>,
1286
) -> Result<axum::response::Sse<impl futures::Stream<Item = Result<axum::response::sse::Event, std::convert::Infallible>>>, Error> {
1287
    use futures::StreamExt;
1288
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1289
    let (_, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1290
    let rx = app.events.proposals.subscribe();
1291
    let repo_id = row.id;
1292
    let stream = tokio_stream::wrappers::BroadcastStream::new(rx).filter_map(move |item| async move {
1293
        match item {
1294
            Ok((id, ev)) if id == repo_id => {
1295
                Some(Ok(axum::response::sse::Event::default().event(ev.kind.clone()).data(serde_json::to_string(&ev).unwrap_or_default())))
1296
            }
1297
            _ => None,
1298
        }
1299
    });
1300
    Ok(axum::response::Sse::new(stream).keep_alive(axum::response::sse::KeepAlive::default()))
1301
}
1302
de505df5 Andy McCall ↶ 1303
// -------------------------------------------------------------------- API
1304
1305
pub async fn to_api(app: &Shared, owner: &str, name: &str, loaded: &Loaded, v: &Verdict, source_url: Option<String>) -> hub_api::Proposal {
1306
    let p = &loaded.row;
1307
    hub_api::Proposal {
1308
        number: p.number,
1309
        title: p.title.clone(),
1310
        body: p.body.clone(),
1311
        author: p.author.clone(),
1312
        state: ProposalState::parse(&p.state).unwrap_or(ProposalState::Open),
1313
        target: p.target.clone(),
1314
        source: match p.source_kind.as_str() {
1315
            "fork" => {
1316
                let (o, n) = source_url
1317
                    .as_deref()
1318
                    .and_then(|u| u.rsplit_once('/'))
1319
                    .and_then(|(b, n)| b.rsplit_once('/').map(|(_, o)| (o.to_string(), n.to_string())))
1320
                    .unwrap_or_default();
1321
                ProposalSource::Fork { owner: o, name: n, bookmark: p.source_bookmark.clone() }
1322
            }
1323
            "changes" => ProposalSource::Changes { hashes: p.source_changes() },
1324
            _ => ProposalSource::Bookmark { bookmark: p.source_bookmark.clone() },
1325
        },
1326
        changes: loaded
1327
            .changes
1328
            .iter()
1329
            .map(|c| hub_api::ChangeSummary {
1330
                hash: c.hash.clone(),
1331
                message: if c.body.is_empty() { c.title.clone() } else { format!("{}\n\n{}", c.title, c.body) },
1332
                author: hub_api::Author {
1333
                    name: c.author.name.clone(),
1334
                    email: c.author.email.clone(),
1335
                    key: c.author.key.clone(),
1336
                    account: c.author.account.clone(),
760a7dd3 Andy McCall ↶ 1337
                    note: hub_api::Author::note_for(&c.author.key, &c.author.account),
de505df5 Andy McCall ↶ 1338
                },
1339
                when_ms: c.when_ms,
1340
                deps: c.deps.clone(),
1341
                head: c.head,
8933faff Andy McCall ↶ 1342
                via: c.via.as_ref().map(|v| hub_api::Via {
1343
                    name: v.name.clone(),
1344
                    key: v.key.clone(),
1345
                    scope: v.scope.clone(),
1346
                    expires_ms: v.expires_ms,
1347
                    revoked: v.revoked,
1348
                }),
de505df5 Andy McCall ↶ 1349
                signature: match &c.signature {
1350
                    view::SigView::Unsigned => hub_api::Signature::Unsigned,
1351
                    view::SigView::Valid { key, sealed, revoked, .. } => {
1352
                        hub_api::Signature::Valid { key: key.clone(), sealed: *sealed, revoked: *revoked }
1353
                    }
1354
                    view::SigView::Invalid(why) => hub_api::Signature::Invalid { reason: why.clone() },
1355
                },
1356
            })
1357
            .collect(),
1358
        projected_heads: loaded.heads.iter().map(|h| h.to_hex()).collect(),
1359
        projected_state: Some(loaded.state.clone()),
1360
        conflicted: loaded.conflicted,
1361
        approvals: v.approvals.clone(),
1362
        landable: p.is_open() && v.blockers.is_empty(),
1363
        blockers: v.blockers.clone(),
1364
        created_ms: p.created_ms,
1365
        updated_ms: p.updated_ms,
1366
        url: format!("{}/{owner}/{name}/proposal/{}", app.config.base_url(), p.number),
1367
        repository_url: format!("{}/{owner}/{name}", app.config.base_url()),
1368
        source_url,
0b20f1ec Andy McCall ↶ 1369
        landed: (p.state == "landed" && p.landed_ms > 0).then(|| hub_api::Landed {
1370
            by: p.landed_by.clone(),
1371
            via: p.landed_via.clone(),
1372
            when_ms: p.landed_ms,
1373
        }),
cc1cd197 Andy McCall ↶ 1374
        requested_reviewers: pdb::review_requests(&app.db, p.id).await.unwrap_or_default(),
2291f8cc Andy McCall ↶ 1375
        labels: db::issues::proposal_labels(&app.db, p.id)
1376
            .await
1377
            .unwrap_or_default()
1378
            .into_iter()
1379
            .map(|l| hub_api::Label { name: l.name, colour: l.colour, description: l.description })
1380
            .collect(),
de505df5 Andy McCall ↶ 1381
    }
1382
}
1383
1384
/// The line comment form's placement key, for templates.
1385
pub fn key(path: &str, line: impl filters::Num) -> (String, usize) {
1386
    (path.to_string(), line.as_u64() as usize)
1387
}
1388
1389
#[allow(dead_code)]
1390
fn _unused(_: &diff::Line, _: &ConflictView, _: &Role) {}
cc1cd197 Andy McCall ↶ 1391
1392
// ------------------------------------------------------- review requests
1393
1394
/// Ask accounts to review a proposal (hub plan 0.4): each must exist, be
1395
/// someone other than the author, and be able to read the repository. Each
1396
/// newly asked is told, and the proposal records it. The usernames newly
1397
/// asked, or why none could be.
1398
pub async fn request_reviewers(
1399
    app: &Shared,
1400
    row: &db::repos::RepoRow,
1401
    p: &pdb::ProposalRow,
1402
    by: &accounts::Account,
1403
    names: &[String],
1404
) -> Result<Vec<String>, String> {
1405
    let mut found = Vec::new();
1406
    for name in names.iter().map(|n| n.trim().trim_start_matches('@')).filter(|n| !n.is_empty()) {
1407
        let Some(a) = accounts::account_by_name(&app.db, name).await.ok().flatten() else {
1408
            return Err(format!("There is no account {name}."));
1409
        };
1410
        if Some(a.id) == p.author_id {
1411
            return Err(format!("{name} wrote this proposal, and cannot review it."));
1412
        }
1413
        let role = crate::auth::roles::role_for(&app.db, Some(&a), row).await.ok().flatten();
1414
        if !crate::auth::roles::allows(role, crate::auth::Access::Read) {
1415
            return Err(format!("{name} cannot read this repository."));
1416
        }
1417
        found.push(a);
1418
    }
1419
    let mut asked = Vec::new();
1420
    for a in found {
1421
        if !pdb::request_review(&app.db, p.id, a.id, &by.username).await.map_err(|e| e.to_string())? {
1422
            continue;
1423
        }
1424
        pdb::add_event(&app.db, p.id, &by.username, "review requested", &a.username).await.ok();
1425
        crate::notify::deliver(
1426
            app,
1427
            crate::notify::Event {
1428
                kind: "proposal.review_requested",
1429
                title: format!("{}/{}#{}: {} (review requested from {})", row.owner, row.name, p.number, p.title, a.username),
1430
                url: format!("/{}/{}/proposal/{}", row.owner, row.name, p.number),
1431
                actor: by,
1432
                repo_id: row.id,
1433
                thread: None,
1434
                mention_text: "",
1435
                direct: vec![a.id],
1436
            },
1437
        )
1438
        .await;
1439
        asked.push(a.username);
1440
    }
1441
    Ok(asked)
1442
}
1443
1444
/// After a review: it answers the reviewer's request, if there was one, and
1445
/// the proposal's author is told.
1446
pub async fn reviewed(app: &Shared, row: &db::repos::RepoRow, p: &pdb::ProposalRow, by: &accounts::Account, verdict: &str) {
1447
    pdb::unrequest_review(&app.db, p.id, by.id).await.ok();
1448
    let what = match verdict {
1449
        "approve" => "approved",
1450
        "changes" => "changes requested",
1451
        _ => "reviewed",
1452
    };
1453
    crate::notify::deliver(
1454
        app,
1455
        crate::notify::Event {
1456
            kind: "proposal.review",
1457
            title: format!("{}/{}#{}: {} ({what} by {})", row.owner, row.name, p.number, p.title, by.username),
1458
            url: format!("/{}/{}/proposal/{}", row.owner, row.name, p.number),
1459
            actor: by,
1460
            repo_id: row.id,
1461
            thread: Some(("proposal", p.id)),
1462
            mention_text: "",
1463
            direct: p.author_id.into_iter().collect(),
1464
        },
1465
    )
1466
    .await;
1467
}
1468
1469
#[derive(Deserialize)]
1470
pub struct ReviewersForm {
1471
    #[serde(rename = "_csrf")]
1472
    csrf_token: String,
8e96499f Andy McCall ↶ 1473
    /// `add`, `remove`, or `set` (the menu: exactly these are asked).
cc1cd197 Andy McCall ↶ 1474
    action: String,
8e96499f Andy McCall ↶ 1475
    #[serde(default)]
1476
    username: Vec<String>,
cc1cd197 Andy McCall ↶ 1477
}
1478
1479
/// `POST /{owner}/{name}/proposal/{number}/reviewers`: the author or a
1480
/// writer asks someone to review, or withdraws the request.
1481
pub async fn reviewers(
1482
    State(app): State<Shared>,
1483
    viewer: Viewer,
1484
    Path((owner, name, number)): Path<(String, String, i64)>,
8e96499f Andy McCall ↶ 1485
    axum_extra::extract::Form(f): axum_extra::extract::Form<ReviewersForm>,
cc1cd197 Andy McCall ↶ 1486
) -> Result<Response, Error> {
1487
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1488
    let me = require(&viewer, &shell)?;
1489
    csrf(&viewer, &f.csrf_token, &shell)?;
1490
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1491
    let p = pdb::get(&app.db, row.id, number)
1492
        .await
1493
        .map_err(|e| Error::from_db(shell.clone(), e))?
1494
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1495
    if Some(me.account.id) != p.author_id && role < Role::Write {
1496
        return Err(Error::not_found(shell));
1497
    }
8e96499f Andy McCall ↶ 1498
    let names: Vec<String> = f.username.iter().map(|n| n.trim().trim_start_matches('@').to_string()).filter(|n| !n.is_empty()).collect();
1499
    let current = pdb::review_requests(&app.db, p.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1500
    // Withdrawn: those named (remove), or those the menu left out (set).
1501
    let withdraw: Vec<String> = match f.action.as_str() {
1502
        "remove" => names.clone(),
1503
        "set" => current.iter().filter(|c| !names.iter().any(|n| n.eq_ignore_ascii_case(c))).cloned().collect(),
1504
        _ => Vec::new(),
1505
    };
1506
    for who in &withdraw {
1507
        if let Some(a) = accounts::account_by_name(&app.db, who).await.ok().flatten() {
cc1cd197 Andy McCall ↶ 1508
            if pdb::unrequest_review(&app.db, p.id, a.id).await.map_err(|e| Error::from_db(shell.clone(), e))? {
1509
                pdb::add_event(&app.db, p.id, &me.account.username, "review request withdrawn", &a.username).await.ok();
1510
            }
1511
        }
8e96499f Andy McCall ↶ 1512
    }
1513
    let ask: Vec<String> = match f.action.as_str() {
1514
        "add" => names,
1515
        "set" => names.into_iter().filter(|n| !current.iter().any(|c| c.eq_ignore_ascii_case(n))).collect(),
1516
        _ => return Ok(back(&owner, &name, number, "conversation", None, None)),
1517
    };
1518
    if ask.is_empty() {
cc1cd197 Andy McCall ↶ 1519
        return Ok(back(&owner, &name, number, "conversation", None, None));
1520
    }
8e96499f Andy McCall ↶ 1521
    match request_reviewers(&app, &row, &p, &me.account, &ask).await {
cc1cd197 Andy McCall ↶ 1522
        Ok(asked) if asked.is_empty() => Ok(back(&owner, &name, number, "conversation", Some("Already asked.".into()), None)),
1523
        Ok(asked) => Ok(back(&owner, &name, number, "conversation", Some(format!("Asked {} to review.", asked.join(", "))), None)),
1524
        Err(e) => Ok(back(&owner, &name, number, "conversation", None, Some(e))),
7d2eb590 Andy McCall ↶ 1525
    }
1526
}
1527
1528
#[derive(Deserialize)]
1529
pub struct AssistantForm {
1530
    #[serde(rename = "_csrf")]
1531
    csrf_token: String,
1532
    assistant: String,
1533
}
1534
1535
/// `POST /{owner}/{name}/proposal/{number}/assistant`: the author or a
1536
/// writer asks an AI assistant to review (hub spec §13.4). The answer
1537
/// comes later as a review via the assistant.
1538
pub async fn assistant(
1539
    State(app): State<Shared>,
1540
    viewer: Viewer,
1541
    Path((owner, name, number)): Path<(String, String, i64)>,
1542
    Form(f): Form<AssistantForm>,
1543
) -> Result<Response, Error> {
1544
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1545
    let me = require(&viewer, &shell)?;
1546
    csrf(&viewer, &f.csrf_token, &shell)?;
1547
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 1548
    super::writable(&row, &shell)?;
7d2eb590 Andy McCall ↶ 1549
    let p = pdb::get(&app.db, row.id, number)
1550
        .await
1551
        .map_err(|e| Error::from_db(shell.clone(), e))?
1552
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1553
    if Some(me.account.id) != p.author_id && role < Role::Write {
1554
        return Err(Error::not_found(shell));
1555
    }
1556
    if !p.is_open() {
1557
        return Ok(back(&owner, &name, number, "conversation", None, Some("The proposal is not open.".into())));
1558
    }
1559
    let Some(a) = crate::assistants::enabled_for_repo(&app.db, &row)
1560
        .await
1561
        .map_err(|e| Error::from_db(shell.clone(), e))?
1562
        .into_iter()
1563
        .find(|a| a.name.eq_ignore_ascii_case(f.assistant.trim()))
1564
    else {
1565
        return Ok(back(&owner, &name, number, "conversation", None, Some(format!("No assistant called {} here.", f.assistant.trim()))));
1566
    };
1567
    let who = a.name.clone();
1568
    match crate::assistants::request_review(&app, &row, &p, &me.account, a).await {
1569
        Ok(()) => Ok(back(
1570
            &owner,
1571
            &name,
1572
            number,
1573
            "conversation",
1574
            Some(format!("Asked {who} to review; its answer appears here when it comes.")),
1575
            None,
1576
        )),
1577
        Err(e) => Ok(back(&owner, &name, number, "conversation", None, Some(format!("Not asked: {e}.")))),
1578
    }
1579
}
1580
1581
/// The assistants a repository may use, by name.
1582
async fn assistant_names(app: &Shared, row: &db::repos::RepoRow) -> Vec<String> {
1583
    crate::assistants::enabled_for_repo(&app.db, row).await.unwrap_or_default().into_iter().map(|a| a.name).collect()
1584
}
1585
1586
/// The changes and the file diffs a proposal from `source` into `target`
1587
/// would carry.
1588
async fn preview_diff(
1589
    app: &Shared,
1590
    repo: &RepoName,
1591
    target: &str,
1592
    source: &str,
1593
) -> Result<(Vec<ChangeView>, Vec<oxy_core::repo::FileDiff>), crate::repos::RepoError> {
1594
    let Some((fork, bookmark)) = parse_source(app, repo, source) else { return Ok((vec![], vec![])) };
1595
    let target = target.to_string();
1596
    let fork_dir = fork.as_ref().map(|f| app.repos.dir(f));
1597
    app.repos
1598
        .read(repo, move |r, cache| {
1599
            let projection = match &fork_dir {
1600
                Some(dir) => {
1601
                    let fork_repo = oxy_core::repo::Repo::open(dir)?;
1602
                    let heads = fork_repo.bookmarks()?.into_iter().find(|b| b.name == bookmark).map(|b| b.heads).unwrap_or_default();
1603
                    pl::project(r, cache, &target, Source::Fork { fork: &fork_repo, heads })?
1604
                }
1605
                None => {
1606
                    let heads = r.bookmarks()?.into_iter().find(|b| b.name == bookmark).map(|b| b.heads).unwrap_or_default();
1607
                    pl::project(r, cache, &target, Source::Bookmark(heads))?
1608
                }
1609
            };
1610
            Ok((projection.changes, projection.files))
1611
        })
1612
        .await
1613
}
1614
1615
/// `POST /{owner}/{name}/proposals/new/draft`: an assistant drafts the
1616
/// description from the changes the proposal would add; the form comes
1617
/// back with the draft to edit (hub spec §13.4).
1618
pub async fn new_draft(
1619
    State(app): State<Shared>,
1620
    viewer: Viewer,
1621
    Path((owner, name)): Path<(String, String)>,
1622
    Form(f): Form<NewForm>,
1623
) -> Result<Page<NewProposalPage>, Error> {
1624
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposals/new"), &viewer);
1625
    let me = require(&viewer, &shell)?;
1626
    csrf(&viewer, &f.csrf_token, &shell)?;
1627
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 1628
    super::writable(&row, &shell)?;
7d2eb590 Andy McCall ↶ 1629
    let bookmarks =
1630
        app.repos.read(&repo, |r, _| Ok(r.bookmarks()?.into_iter().map(|b| b.name).collect::<Vec<_>>())).await.unwrap_or_default();
1631
    let (preview, conflicted) = preview_for(&app, &repo, &f.target, &f.source).await.unwrap_or((vec![], false));
1632
    let assistants = if preview.is_empty() { vec![] } else { assistant_names(&app, &row).await };
1633
    let mut page = NewProposalPage {
1634
        shell,
1635
        repo: RepoShell::new(&app, &row, "proposals").with_role(role),
1636
        bookmarks,
1637
        source: f.source.clone(),
1638
        target: f.target.clone(),
1639
        error: None,
1640
        preview,
1641
        conflicted,
1642
        title: f.title.clone(),
1643
        body: f.body.clone(),
1644
        assistants,
1645
    };
1646
    let assistant = crate::assistants::enabled_for_repo(&app.db, &row)
1647
        .await
1648
        .unwrap_or_default()
1649
        .into_iter()
1650
        .find(|a| a.name.eq_ignore_ascii_case(f.assistant.trim()));
1651
    let Some(a) = assistant else {
1652
        page.error = Some(format!("No assistant called {} here.", f.assistant.trim()));
1653
        return Ok(Page(page));
1654
    };
1655
    if page.preview.is_empty() {
1656
        page.error = Some("Nothing to describe: the source adds nothing to the target.".into());
1657
        return Ok(Page(page));
1658
    }
1659
    let (changes, diffs) = match preview_diff(&app, &repo, &f.target, &f.source).await {
1660
        Ok(x) => x,
1661
        Err(e) => {
1662
            page.error = Some(e.to_string());
1663
            return Ok(Page(page));
1664
        }
1665
    };
1666
    let d = crate::assistants::Draft { slot: -row.id, title: &f.title, target: &f.target, changes: &changes, diffs: &diffs };
1667
    match crate::assistants::draft_description(&app, &row, &me.account, &a, d).await {
1668
        Ok(text) => page.body = text,
1669
        Err(why) => page.error = Some(format!("{} did not answer: {why}.", a.name)),
1670
    }
1671
    Ok(Page(page))
1672
}
1673
1674
#[derive(Deserialize)]
1675
pub struct DraftForm {
1676
    #[serde(rename = "_csrf")]
1677
    csrf_token: String,
1678
    assistant: String,
1679
    #[serde(default)]
1680
    title: String,
1681
}
1682
1683
/// `POST /{owner}/{name}/proposal/{number}/draft`: an assistant drafts the
1684
/// description of an open proposal from its changes; the editor opens
1685
/// with the draft, nothing is saved (hub spec §13.4).
1686
pub async fn draft(
1687
    State(app): State<Shared>,
1688
    viewer: Viewer,
1689
    Path((owner, name, number)): Path<(String, String, i64)>,
1690
    Form(f): Form<DraftForm>,
1691
) -> Result<Response, Error> {
1692
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1693
    let me = require(&viewer, &shell)?;
1694
    csrf(&viewer, &f.csrf_token, &shell)?;
1695
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 1696
    super::writable(&row, &shell)?;
7d2eb590 Andy McCall ↶ 1697
    let p = pdb::get(&app.db, row.id, number)
1698
        .await
1699
        .map_err(|e| Error::from_db(shell.clone(), e))?
1700
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1701
    if Some(me.account.id) != p.author_id && role < Role::Maintain {
1702
        return Err(Error::not_found(shell));
1703
    }
1704
    let Some(a) = crate::assistants::enabled_for_repo(&app.db, &row)
1705
        .await
1706
        .map_err(|e| Error::from_db(shell.clone(), e))?
1707
        .into_iter()
1708
        .find(|a| a.name.eq_ignore_ascii_case(f.assistant.trim()))
1709
    else {
1710
        return Ok(back(&owner, &name, number, "conversation", None, Some(format!("No assistant called {} here.", f.assistant.trim()))));
1711
    };
1712
    let loaded = crate::web::proposals::load(&app, &repo, p.clone()).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
1713
    let title = if f.title.trim().is_empty() { p.title.clone() } else { f.title.clone() };
1714
    let d = crate::assistants::Draft { slot: p.id, title: &title, target: &p.target, changes: &loaded.changes, diffs: &loaded.diffs };
1715
    let draft = crate::assistants::draft_description(&app, &row, &me.account, &a, d).await;
1716
    match draft {
1717
        Ok(text) => {
1718
            let mut page = detail(&app, shell, &viewer, &owner, &name, number, "conversation".into(), None, None).await?;
1719
            page.0.draft = Some(text);
1720
            Ok(page.into_response())
1721
        }
1722
        Err(why) => Ok(back(&owner, &name, number, "conversation", None, Some(format!("{} did not answer: {why}.", a.name)))),
cc1cd197 Andy McCall ↶ 1723
    }
1724
}