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