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