OXYGENHUB
# d943160dafeb oxygenhub / crates / hub / src / diffusion.rs
42.6 KiB · Rust · last changed Diffusion: see it, and landing refreshes the pin index 23 days ago source blame history raw
f677d627 Andy McCall ↶ 1
//! Diffusion (#148, docs/diffusion.md): an upstream's changes reach the
2
//! repositories that pin it as a subrepo.
3
//!
4
//! D1 starts with the reverse pin index (§4.1): when a push moves a
5
//! repository's default bookmark, or the bookmark its work lands on, each
6
//! Oxygen subrepo pin in the new state is recorded. That answers "who
7
//! consumes this repository, at which state, and how far behind", which
8
//! an upstream's page shows as Used by.
9
10
use crate::auth::roles;
11
use crate::db::{self, accounts::Account, repos::RepoRow, Pool};
12
use crate::repos::RepoName;
13
use crate::Shared;
14
use oxy_core::hash::ChangeHash;
15
use serde::Serialize;
16
17
/// How far back landed proposals teach where a repository's work lands.
18
pub const LEARN_DAYS: i64 = 90;
19
20
/// The bookmark a repository's work lands on (§4.3): the most common
21
/// target of its proposals landed in the last `LEARN_DAYS`, else its
22
/// default bookmark.
23
pub async fn target(pool: &Pool, row: &RepoRow) -> String {
24
    let since = db::now_ms() - LEARN_DAYS * 24 * 3600 * 1000;
25
    let learned: Option<String> = sqlx::query_scalar(
26
        "SELECT target FROM proposals WHERE repo_id = ? AND state = 'landed' AND landed_ms >= ?
27
         GROUP BY target ORDER BY COUNT(*) DESC, MAX(landed_ms) DESC LIMIT 1",
28
    )
29
    .bind(row.id)
30
    .bind(since)
31
    .fetch_optional(pool)
32
    .await
33
    .ok()
34
    .flatten();
35
    learned.filter(|t| !t.is_empty()).unwrap_or_else(|| row.default_bookmark.clone())
36
}
37
38
/// The bookmarks whose pins are indexed: the default and the learned
39
/// target (one when they are the same).
40
pub async fn followed_bookmarks(pool: &Pool, row: &RepoRow) -> Vec<String> {
41
    let mut out = vec![row.default_bookmark.clone()];
42
    let t = target(pool, row).await;
43
    if !out.contains(&t) {
44
        out.push(t);
45
    }
46
    out
47
}
48
49
/// Record `row`'s pins on `bookmark` at `heads`, replacing what was there.
50
pub async fn record(app: &Shared, row: &RepoRow, bookmark: &str, heads: &[ChangeHash]) {
51
    let Some(name) = RepoName::new(&row.owner, &row.name) else { return };
52
    let pins = if heads.is_empty() { Vec::new() } else { crate::flow::pins_in(app, name, heads.to_vec()).await };
53
    let now = db::now_ms();
757195ad Andy McCall ↶ 54
    // The upstream's repository on this hub, when it is one.
55
    let mut upstreams = Vec::new();
56
    for (_, id, _) in &pins {
57
        upstreams.push(repo_by_oxy_id(app, &hex::encode(id)).await.map(|r| r.id));
58
    }
f677d627 Andy McCall ↶ 59
    let Ok(mut tx) = app.db.begin().await else { return };
60
    let mut ok = sqlx::query("DELETE FROM diffusion_pins WHERE consumer_id = ? AND bookmark = ?")
61
        .bind(row.id)
62
        .bind(bookmark)
63
        .execute(&mut *tx)
64
        .await
65
        .is_ok();
757195ad Andy McCall ↶ 66
    for ((path, id, pinned), upstream_row) in pins.iter().zip(&upstreams) {
f677d627 Andy McCall ↶ 67
        let heads: Vec<String> = pinned.iter().map(|h| h.to_hex()).collect();
757195ad Andy McCall ↶ 68
        ok &= sqlx::query(
69
            "INSERT INTO diffusion_pins (consumer_id, bookmark, path, upstream, heads, updated_ms, upstream_repo_id) VALUES (?, ?, ?, ?, ?, ?, ?)",
70
        )
71
        .bind(row.id)
72
        .bind(bookmark)
73
        .bind(path)
74
        .bind(hex::encode(id))
75
        .bind(heads.join("+"))
76
        .bind(now)
77
        .bind(upstream_row)
78
        .execute(&mut *tx)
79
        .await
80
        .is_ok();
81
        if let Some(u) = upstream_row {
82
            mark(app, row.id);
83
            mark(app, *u);
84
        }
f677d627 Andy McCall ↶ 85
    }
86
    if ok {
87
        tx.commit().await.ok();
88
    }
89
}
90
91
/// After a push: index the pins of each moved bookmark that is followed.
92
pub async fn after_push(app: &Shared, row: &RepoRow, moved: &[(String, String, Vec<ChangeHash>)]) {
93
    let followed = followed_bookmarks(&app.db, row).await;
94
    for (bookmark, _, heads) in moved {
95
        if followed.contains(bookmark) {
96
            record(app, row, bookmark, heads).await;
97
        }
98
    }
757195ad Andy McCall ↶ 99
}
100
101
static INVOLVED: std::sync::Mutex<Option<std::collections::HashSet<String>>> = std::sync::Mutex::new(None);
102
103
fn key(app: &Shared, repo_id: i64) -> String {
104
    format!("{}#{repo_id}", app.repos.root().display())
105
}
106
107
fn mark(app: &Shared, repo_id: i64) {
108
    INVOLVED.lock().unwrap_or_else(|p| p.into_inner()).get_or_insert_with(Default::default).insert(key(app, repo_id));
f677d627 Andy McCall ↶ 109
}
110
757195ad Andy McCall ↶ 111
/// Whether a repository takes part in Diffusion, as an upstream or a
112
/// consumer on this hub: its Diffusion tab shows (#150).
113
pub fn involved(app: &Shared, repo_id: i64) -> bool {
114
    INVOLVED.lock().unwrap_or_else(|p| p.into_inner()).as_ref().is_some_and(|s| s.contains(&key(app, repo_id)))
115
}
116
f677d627 Andy McCall ↶ 117
/// Index every repository's followed bookmarks, for a hub that had no
118
/// index before (run once at start, in the background).
119
pub async fn backfill(app: &Shared) {
120
    let Ok(rows) = db::repos::list(&app.db).await else { return };
121
    for row in rows {
122
        let Some(name) = RepoName::new(&row.owner, &row.name) else { continue };
123
        for bookmark in followed_bookmarks(&app.db, &row).await {
124
            let b = bookmark.clone();
125
            let heads = app.repos.read(&name, move |r, _| heads_of(r, &b)).await;
126
            if let Ok(heads) = heads {
127
                record(app, &row, &bookmark, &heads).await;
128
            }
129
        }
130
    }
131
}
132
133
/// A bookmark's heads as the repository has them now (not a cached
134
/// list, which a push refreshes a moment later); empty when it has none.
135
fn heads_of(r: &oxy_core::repo::Repo, bookmark: &str) -> Result<Vec<ChangeHash>, crate::repos::RepoError> {
136
    Ok(r.bookmarks()?.into_iter().find(|b| b.name == bookmark).map(|b| b.heads).unwrap_or_default())
137
}
138
139
/// One consumer of an upstream, as an upstream's page and API show it.
140
#[derive(Clone, Debug, Serialize)]
141
pub struct Consumer {
142
    pub owner: String,
143
    pub name: String,
144
    pub bookmark: String,
145
    pub path: String,
146
    /// The upstream heads it pins, hex.
147
    pub pinned: Vec<String>,
148
    /// Upstream changes on its default bookmark the pin lacks; `None` when
149
    /// the hub cannot tell (the pinned changes are not in the upstream).
150
    pub behind: Option<usize>,
757195ad Andy McCall ↶ 151
    /// How it follows the upstream (from its setting, or the site's).
152
    pub follow: Follow,
153
    /// Its open bump proposal's number, if it has one.
154
    pub bump: Option<i64>,
155
    /// The newest run of its bump bookmark: number and status.
156
    pub run: Option<(i64, String)>,
157
    /// Its last landed bump: number and when.
158
    pub landed: Option<(i64, i64)>,
159
    /// What the views show (#150).
160
    pub colour: Colour,
161
}
162
163
/// A consumer's Diffusion status at a glance (#150, Andy's colours):
164
/// green when the upstream was checked and the consumer's run on the bump
165
/// passed; amber when the run passed but the upstream has no checks; red
166
/// when the run failed; grey while it runs; up to date when there is
167
/// nothing to bump; off when it does not follow.
168
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
169
#[serde(rename_all = "kebab-case")]
170
pub enum Colour {
171
    Green,
172
    Amber,
173
    Red,
174
    Grey,
175
    UpToDate,
176
    Off,
f677d627 Andy McCall ↶ 177
}
178
757195ad Andy McCall ↶ 179
impl Colour {
180
    pub fn class(&self) -> &'static str {
181
        match self {
182
            Colour::Green => "df-green",
183
            Colour::Amber => "df-amber",
184
            Colour::Red => "df-red",
185
            Colour::Grey => "df-grey",
186
            Colour::UpToDate => "df-current",
187
            Colour::Off => "df-off",
188
        }
189
    }
190
191
    pub fn label(&self) -> &'static str {
192
        match self {
193
            Colour::Green => "green",
194
            Colour::Amber => "amber: upstream unverified",
195
            Colour::Red => "red: its run failed",
196
            Colour::Grey => "testing",
197
            Colour::UpToDate => "up to date",
198
            Colour::Off => "not following",
199
        }
200
    }
201
202
    /// The colour from what is known of a consumer.
203
    pub fn of(follow: Follow, behind: Option<usize>, bump: Option<i64>, run: Option<&str>, unverified: bool) -> Colour {
204
        if follow == Follow::Off {
205
            return Colour::Off;
206
        }
207
        match (bump, run) {
208
            (Some(_), Some("passed")) if unverified => Colour::Amber,
209
            (Some(_), Some("passed")) => Colour::Green,
210
            (Some(_), Some("failed" | "error" | "cancelled")) => Colour::Red,
211
            (Some(_), _) => Colour::Grey,
212
            (None, _) if behind == Some(0) => Colour::UpToDate,
213
            (None, _) => Colour::Grey,
214
        }
215
    }
216
}
217
f677d627 Andy McCall ↶ 218
/// The consumers of `row` that `account` may read, with how far behind
219
/// the upstream's default bookmark each pin is.
220
pub async fn consumers(app: &Shared, row: &RepoRow, account: Option<&Account>) -> Result<Vec<Consumer>, crate::repos::RepoError> {
221
    let Some(name) = RepoName::new(&row.owner, &row.name) else { return Ok(Vec::new()) };
222
    let id = app.repos.read(&name, |r, _| Ok(r.id()?)).await?;
223
    let found: Vec<(i64, String, String, String)> = sqlx::query_as(
224
        "SELECT consumer_id, bookmark, path, heads FROM diffusion_pins WHERE upstream = ? ORDER BY consumer_id, bookmark, path",
225
    )
226
    .bind(hex::encode(id))
227
    .fetch_all(&app.db)
228
    .await
229
    .map_err(|e| crate::repos::RepoError::Io(std::io::Error::other(e)))?;
230
    let mut out = Vec::new();
231
    let mut pinned_sets = Vec::new();
757195ad Andy McCall ↶ 232
    let unverified = unverified(app, row).await;
f677d627 Andy McCall ↶ 233
    for (consumer_id, bookmark, path, heads) in found {
234
        let Ok(Some(c)) = db::repos::get_by_id(&app.db, consumer_id).await else { continue };
235
        if !roles::allows(roles::role_for(&app.db, account, &c).await.ok().flatten(), crate::auth::Access::Read) {
757195ad Andy McCall ↶ 236
            continue;
237
        }
238
        // One row per consumer and subrepo: the bookmark its work lands on.
239
        if bookmark != target(&app.db, &c).await {
f677d627 Andy McCall ↶ 240
            continue;
241
        }
242
        let pinned: Vec<String> = heads.split('+').filter(|h| !h.is_empty()).map(String::from).collect();
243
        pinned_sets.push(pinned.iter().filter_map(|h| ChangeHash::from_hex(h)).collect::<Vec<_>>());
757195ad Andy McCall ↶ 244
        let bump_bm = bump_bookmark(&path);
245
        let mine: Vec<db::proposals::ProposalRow> = db::proposals::list(&app.db, c.id, &[])
246
            .await
247
            .unwrap_or_default()
248
            .into_iter()
249
            .filter(|p| p.source_bookmark == bump_bm)
250
            .collect();
251
        let bump = mine.iter().find(|p| p.state == "open" || p.state == "draft").map(|p| p.number);
252
        let landed = mine.iter().filter(|p| p.state == "landed").max_by_key(|p| p.landed_ms).map(|p| (p.number, p.landed_ms));
253
        let run: Option<(i64, String)> =
254
            sqlx::query_as("SELECT number, status FROM flow_runs WHERE repo_id = ? AND bookmark = ? ORDER BY id DESC LIMIT 1")
255
                .bind(c.id)
256
                .bind(&bump_bm)
257
                .fetch_optional(&app.db)
258
                .await
259
                .ok()
260
                .flatten();
261
        let follow = rule(&app.config.diffusion.follow, &c, None, &path).follow;
262
        out.push(Consumer {
263
            owner: c.owner,
264
            name: c.name,
265
            bookmark,
266
            path,
267
            pinned,
268
            behind: None,
269
            follow,
270
            bump,
271
            run,
272
            landed,
273
            colour: Colour::Off,
274
        });
f677d627 Andy McCall ↶ 275
    }
276
    if out.is_empty() {
277
        return Ok(out);
278
    }
279
    let default = row.default_bookmark.clone();
280
    let behind = app
281
        .repos
282
        .read(&name, move |r, cache| {
283
            let tip = heads_of(r, &default)?;
284
            let tip = cache.summary(r, &tip)?;
285
            Ok(pinned_sets
286
                .iter()
287
                .map(|p| cache.summary(r, p).ok().map(|s| tip.changes.iter().filter(|c| !s.changes.contains(*c)).count()))
288
                .collect::<Vec<_>>())
289
        })
290
        .await?;
291
    for (c, b) in out.iter_mut().zip(behind) {
292
        c.behind = b;
757195ad Andy McCall ↶ 293
        c.colour = Colour::of(c.follow, b, c.bump, c.run.as_ref().map(|r| r.1.as_str()), unverified);
f677d627 Andy McCall ↶ 294
    }
295
    Ok(out)
757195ad Andy McCall ↶ 296
}
297
298
/// What `consumer` follows, as its Follows panel shows: each upstream on
299
/// this hub it pins, with its status there.
300
pub async fn follows(app: &Shared, consumer: &RepoRow, account: Option<&Account>) -> Vec<(RepoRow, Consumer)> {
301
    let ups: Vec<i64> =
302
        sqlx::query_scalar("SELECT DISTINCT upstream_repo_id FROM diffusion_pins WHERE consumer_id = ? AND upstream_repo_id IS NOT NULL")
303
            .bind(consumer.id)
304
            .fetch_all(&app.db)
305
            .await
306
            .unwrap_or_default();
307
    let mut out = Vec::new();
308
    for id in ups {
309
        let Ok(Some(up)) = db::repos::get_by_id(&app.db, id).await else { continue };
310
        if !roles::allows(roles::role_for(&app.db, account, &up).await.ok().flatten(), crate::auth::Access::Read) {
311
            continue;
312
        }
313
        for c in consumers(app, &up, account).await.unwrap_or_default() {
314
            if c.owner == consumer.owner && c.name == consumer.name {
315
                out.push((up.clone(), c));
316
            }
317
        }
318
    }
319
    out
320
}
321
322
/// Every upstream on this hub with its consumers, for Admin › Diffusion.
323
pub async fn everything(app: &Shared, account: Option<&Account>) -> Vec<(RepoRow, Vec<Consumer>, bool)> {
324
    let ups: Vec<i64> = sqlx::query_scalar("SELECT DISTINCT upstream_repo_id FROM diffusion_pins WHERE upstream_repo_id IS NOT NULL")
325
        .fetch_all(&app.db)
326
        .await
327
        .unwrap_or_default();
328
    let mut out = Vec::new();
329
    for id in ups {
330
        let Ok(Some(up)) = db::repos::get_by_id(&app.db, id).await else { continue };
331
        let list = consumers(app, &up, account).await.unwrap_or_default();
332
        let unverified = unverified(app, &up).await;
333
        out.push((up, list, unverified));
334
    }
335
    out
f677d627 Andy McCall ↶ 336
}
e7158350 Andy McCall ↶ 337
1d634f69 Andy McCall ↶ 338
/// The bookmark a consumer's bump for the subrepo at `path` lives on.
339
pub fn bump_bookmark(path: &str) -> String {
340
    format!("diffusion/{}", path.trim_matches('/'))
341
}
342
343
/// What a bump did.
344
#[derive(Clone, Debug, PartialEq, Eq)]
345
pub enum Bumped {
346
    /// The bump bookmark now holds the target plus one change moving the pin.
f01cb865 Andy McCall ↶ 347
    Moved { bookmark: String, change: ChangeHash, heads: Vec<ChangeHash>, from: Vec<ChangeHash>, state: String },
1d634f69 Andy McCall ↶ 348
    /// The pin already holds the upstream state.
349
    UpToDate,
350
    /// The bump bookmark already moves the pin to that state.
9aaa88b2 Andy McCall ↶ 351
    Already { from: Vec<ChangeHash>, to: Vec<ChangeHash> },
7a14bdae Andy McCall ↶ 352
    /// The pin names changes the upstream does not hold: not followed.
353
    Unknown,
354
    /// Taking the upstream's state with the pin's own extra changes would
355
    /// conflict.
356
    Conflicts,
1d634f69 Andy McCall ↶ 357
    /// The consumer has no Oxygen pin of that upstream at `path` on its
358
    /// target bookmark.
359
    NoPin,
360
}
361
7a14bdae Andy McCall ↶ 362
/// Where a consumer's pin `old` moves when the upstream reaches `new`,
363
/// worked out in the upstream (§4.3).
364
#[derive(Clone, Debug, PartialEq, Eq)]
365
pub enum Plan {
366
    /// To these heads, which add this many changes.
367
    To(Vec<ChangeHash>, usize),
368
    /// Nothing to add.
369
    UpToDate,
370
    /// The pin names changes the upstream does not hold (rewritten, or
371
    /// from elsewhere): not followed.
372
    Unknown,
373
    /// Taking `new` with the pin's own extra changes would conflict.
374
    Conflicts,
375
}
376
377
/// The pin `old` moved to the upstream's `new`. When the pin has changes
378
/// `new` lacks (say, from an upstream proposal not landed yet), they are
379
/// kept: changes that do not touch each other combine, so the move is to
380
/// both, never dropping what the consumer already relies on.
381
pub async fn plan(app: &Shared, upstream: &RepoName, old: Vec<ChangeHash>, new: Vec<ChangeHash>) -> Result<Plan, crate::repos::RepoError> {
1d634f69 Andy McCall ↶ 382
    app.repos
383
        .read(upstream, move |r, cache| {
7a14bdae Andy McCall ↶ 384
            let Ok(o) = cache.summary(r, &old) else { return Ok(Plan::Unknown) };
385
            let n = cache.summary(r, &new)?;
386
            if o.changes.iter().all(|c| n.changes.contains(c)) {
387
                let added = n.changes.len() - o.changes.len();
388
                return Ok(if added == 0 { Plan::UpToDate } else { Plan::To(new, added) });
389
            }
390
            let mut both = new.clone();
391
            both.extend(old.iter().copied());
392
            let heads = r.load_state(&both)?.heads();
393
            let b = cache.summary(r, &heads)?;
394
            if b.conflicted && !o.conflicted {
395
                return Ok(Plan::Conflicts);
1d634f69 Andy McCall ↶ 396
            }
7a14bdae Andy McCall ↶ 397
            let added = b.changes.len() - o.changes.len();
398
            Ok(if added == 0 { Plan::UpToDate } else { Plan::To(heads, added) })
1d634f69 Andy McCall ↶ 399
        })
400
        .await
401
}
402
403
/// Move `consumer`'s pin of `upstream` at `path` to `new_heads`, on a bump
404
/// bookmark built from `target` (§4.3): one change, signed with the hub's
405
/// key, on the target's heads. The upstream decides forwardness.
406
pub async fn bump(
407
    app: &Shared,
408
    consumer: &RepoRow,
409
    target: &str,
410
    path: &str,
411
    upstream: &RepoRow,
412
    new_heads: Vec<ChangeHash>,
413
) -> Result<Bumped, crate::repos::RepoError> {
414
    use oxy_core::identity::Domain;
415
    use oxy_core::subrepo::Pin;
416
    let (Some(cname), Some(uname)) = (RepoName::new(&consumer.owner, &consumer.name), RepoName::new(&upstream.owner, &upstream.name))
417
    else {
418
        return Ok(Bumped::NoPin);
419
    };
420
    let upstream_id = app.repos.read(&uname, |r, _| Ok(r.id()?)).await?;
421
    // The consumer's current pin at `path` on its target, and on its bump
422
    // bookmark if it has one.
423
    let (t, p) = (target.to_string(), path.trim_matches('/').to_string());
424
    let (current, bumped) = app
425
        .repos
426
        .read(&cname, move |r, cache| {
427
            let pin_on = |bookmark: &str| -> Result<Option<Pin>, crate::repos::RepoError> {
428
                let heads = heads_of(r, bookmark)?;
429
                if heads.is_empty() {
430
                    return Ok(None);
431
                }
432
                let loaded = cache.load(r, &heads)?;
433
                let Some(f) = loaded.snapshot.files.get(&p) else { return Ok(None) };
434
                let oxy_core::state::FileContent::Opaque { blobs } = &f.content else { return Ok(None) };
435
                let Some(b) = blobs.first() else { return Ok(None) };
436
                Ok(Pin::decode(&r.read_blob(b)?).ok())
437
            };
438
            Ok((pin_on(&t)?, pin_on(&bump_bookmark(&p))?))
439
        })
440
        .await?;
441
    let Some(Pin::Oxy { repo, heads: old, bookmark }) = current else { return Ok(Bumped::NoPin) };
7a14bdae Andy McCall ↶ 442
    if repo != upstream_id {
443
        return Ok(Bumped::NoPin);
444
    }
445
    let new_heads = match plan(app, &uname, old.clone(), new_heads.clone()).await? {
446
        Plan::To(heads, _) => heads,
447
        Plan::UpToDate => return Ok(Bumped::UpToDate),
448
        Plan::Unknown => return Ok(Bumped::Unknown),
449
        Plan::Conflicts => return Ok(Bumped::Conflicts),
450
    };
1d634f69 Andy McCall ↶ 451
    if let Some(Pin::Oxy { heads: b, .. }) = &bumped {
452
        let (mut b, mut n) = (b.clone(), new_heads.clone());
453
        b.sort();
454
        n.sort();
455
        if b == n {
9aaa88b2 Andy McCall ↶ 456
            return Ok(Bumped::Already { from: old, to: new_heads });
1d634f69 Andy McCall ↶ 457
        }
458
    }
459
    let (key, secret) =
460
        crate::keys::load_secret(&app.config.keys_dir()).map_err(|e| crate::repos::RepoError::Io(std::io::Error::other(e.to_string())))?;
461
    let identity = app.hub_key.identity.clone();
462
    let upstream_label = format!("{}/{}", upstream.owner, upstream.name);
463
    let (t, p) = (target.to_string(), path.trim_matches('/').to_string());
464
    let pin = Pin::Oxy { repo, heads: new_heads.clone(), bookmark };
a7e6e8e6 Andy McCall ↶ 465
    let old = old.clone();
1d634f69 Andy McCall ↶ 466
    let short: Vec<String> = new_heads.iter().map(|h| h.to_hex()[..12].to_string()).collect();
467
    let message = format!("Diffusion: move {p} to {upstream_label} {}", short.join("+"));
468
    app.repos
469
        .write(&cname, move |r, _| {
470
            let base = heads_of(r, &t)?;
471
            let change = r.build_pin_change(&base, &p, &pin, &message, key)?;
472
            let hash = change.hash();
473
            let sig = secret.sign(Domain::Change, &key, &hash);
474
            let mut state = r.load_state(&base)?;
475
            state.add(change.clone()).map_err(|e| crate::repos::RepoError::Oxy(oxy_core::repo::RepoError::Msg(e.to_string())))?;
476
            let mut candidates = base.clone();
477
            candidates.push(hash);
478
            let heads = state.maximal(&candidates);
479
            let bookmark = bump_bookmark(&p);
480
            // The bump bookmark is the hub's own and is rebuilt on the
481
            // target each time, so the bump it replaces may go.
482
            let mut update = r.host_ref_update(&bookmark, &heads, Some((&key, &secret)))?;
483
            update.force = true;
f01cb865 Andy McCall ↶ 484
            let state = update.new_state.to_hex();
1d634f69 Andy McCall ↶ 485
            let report = r.apply_hosted(Some((change, vec![sig])), &[identity], update)?;
486
            if let Some(refused) = report.results.iter().find(|x| !x.ok) {
487
                return Err(crate::repos::RepoError::Oxy(oxy_core::repo::RepoError::Msg(format!(
488
                    "the bump was refused: {}",
489
                    refused.reason
490
                ))));
491
            }
f01cb865 Andy McCall ↶ 492
            Ok(Bumped::Moved { bookmark, change: hash, heads, from: old, state })
1d634f69 Andy McCall ↶ 493
        })
494
        .await
495
}
496
a7e6e8e6 Andy McCall ↶ 497
/// The account Diffusion's proposals are opened as.
498
pub const ACCOUNT: &str = "diffusion";
499
500
/// The `diffusion` account, made on first use with no way to sign in.
501
pub async fn account(pool: &Pool) -> Option<Account> {
502
    if let Ok(Some(a)) = db::accounts::account_by_name(pool, ACCOUNT).await {
503
        return Some(a);
504
    }
505
    db::accounts::create_account(pool, ACCOUNT, "diffusion@localhost", "!", "", false).await.ok()
506
}
507
c4e432da Andy McCall ↶ 508
/// Whether `path` matches a `watch` pattern: `*` is any run of characters
509
/// within one path segment, `**` any run across segments, `?` one
510
/// character; a pattern without a wildcard also matches everything below
511
/// it, as a directory would.
512
pub fn watched(pattern: &str, path: &str) -> bool {
513
    fn m(p: &[u8], s: &[u8]) -> bool {
514
        match (p.first(), s.first()) {
515
            (None, None) => true,
516
            (Some(b'*'), _) if p.get(1) == Some(&b'*') => (0..=s.len()).any(|i| m(&p[2..], &s[i..])),
517
            (Some(b'*'), _) => (0..=s.len()).take_while(|&i| i == 0 || s[i - 1] != b'/').any(|i| m(&p[1..], &s[i..])),
518
            (Some(b'?'), Some(c)) if *c != b'/' => m(&p[1..], &s[1..]),
519
            (Some(a), Some(b)) if a == b => m(&p[1..], &s[1..]),
520
            _ => false,
521
        }
522
    }
523
    let p = pattern.trim().trim_matches('/');
524
    if p.is_empty() {
525
        return false;
526
    }
527
    m(p.as_bytes(), path.as_bytes()) || (!p.contains(['*', '?']) && path.starts_with(&format!("{p}/")))
528
}
529
530
/// What a bump brings: the upstream changes in `new` and not in `old`,
531
/// newest first, as Markdown lines linking to the upstream's change pages,
532
/// with those touching a `watch` pattern flagged (and listed again).
533
pub struct Changelog {
534
    pub lines: Vec<String>,
535
    pub watched: Vec<String>,
536
}
537
538
pub async fn changelog(app: &Shared, upstream: &RepoRow, old: Vec<ChangeHash>, new: Vec<ChangeHash>, watch: Vec<String>) -> Changelog {
539
    let Some(name) = RepoName::new(&upstream.owner, &upstream.name) else { return Changelog { lines: Vec::new(), watched: Vec::new() } };
a7e6e8e6 Andy McCall ↶ 540
    let linked: std::collections::HashMap<String, String> =
541
        db::accounts::identity_accounts(&app.db).await.unwrap_or_default().into_iter().collect();
542
    let base = format!("/{}/{}", upstream.owner, upstream.name);
543
    app.repos
544
        .read(&name, move |r, cache| {
545
            let (o, n) = (cache.summary(r, &old)?, cache.summary(r, &new)?);
c4e432da Andy McCall ↶ 546
            let mut added: Vec<(u64, ChangeHash, String, String, Vec<String>)> = Vec::new();
a7e6e8e6 Andy McCall ↶ 547
            for h in n.changes.iter().filter(|c| !o.changes.contains(*c)) {
548
                let Ok(c) = r.store().get_change(h) else { continue };
549
                let key = c.author.to_hex();
550
                let who = linked.get(&key).cloned().unwrap_or_else(|| key[..12].to_string());
551
                let first = c.message.lines().next().unwrap_or("").trim().to_string();
c4e432da Andy McCall ↶ 552
                // The watched paths it touches, when the game watches any.
553
                let hits: Vec<String> = if watch.is_empty() {
554
                    Vec::new()
555
                } else {
556
                    crate::repos::view::change(r, cache, h)
557
                        .map(|d| d.files.into_iter().map(|f| f.path).filter(|p| watch.iter().any(|w| watched(w, p))).collect())
558
                        .unwrap_or_default()
559
                };
560
                added.push((c.hlc.wall_ms, *h, first, who, hits));
a7e6e8e6 Andy McCall ↶ 561
            }
562
            added.sort_by_key(|a| std::cmp::Reverse(a.0));
c4e432da Andy McCall ↶ 563
            let line = |h: &ChangeHash, msg: &str, who: &str, flag: bool| {
564
                format!(
565
                    "- {}[`{}`]({base}/change/{}) {} ({who})",
566
                    if flag { "⚑ " } else { "" },
567
                    &h.to_hex()[..12],
568
                    h.to_hex(),
569
                    msg.replace('\n', " ")
570
                )
571
            };
572
            let watched = added
573
                .iter()
574
                .filter(|a| !a.4.is_empty())
575
                .map(|(_, h, msg, who, hits)| {
576
                    format!(
577
                        "{} — touches {}",
578
                        line(h, msg, who, true),
579
                        hits.iter().map(|p| format!("`{p}`")).collect::<Vec<_>>().join(", ")
580
                    )
a7e6e8e6 Andy McCall ↶ 581
                })
c4e432da Andy McCall ↶ 582
                .collect();
583
            let lines = added.iter().map(|(_, h, msg, who, hits)| line(h, msg, who, !hits.is_empty())).collect();
584
            Ok(Changelog { lines, watched })
a7e6e8e6 Andy McCall ↶ 585
        })
586
        .await
c4e432da Andy McCall ↶ 587
        .unwrap_or(Changelog { lines: Vec::new(), watched: Vec::new() })
a7e6e8e6 Andy McCall ↶ 588
}
589
9aaa88b2 Andy McCall ↶ 590
/// Why a bump was made, which its proposal says.
591
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
592
pub enum Why {
593
    /// The upstream's state passed its checks.
594
    Green,
595
    /// The upstream moved (the consumer follows every move).
596
    Moved,
597
    /// The upstream has no checks at all: nothing vouched for it, so the
598
    /// proposal is marked amber, `upstream unverified`.
599
    Unverified,
600
}
601
602
/// Open the bump proposal for `path`'s bump bookmark, or bring the open
603
/// one up to date: into `target`, by the `diffusion` account, labelled
604
/// `dependencies` (and `upstream unverified` while that is so), its body
605
/// the changelog from the pin `from` to `to`. Its number.
a7e6e8e6 Andy McCall ↶ 606
pub async fn propose(
607
    app: &Shared,
608
    consumer: &RepoRow,
609
    target: &str,
610
    path: &str,
611
    upstream: &RepoRow,
9aaa88b2 Andy McCall ↶ 612
    (from, to): (Vec<ChangeHash>, Vec<ChangeHash>),
c4e432da Andy McCall ↶ 613
    (why, watch): (Why, Vec<String>),
a7e6e8e6 Andy McCall ↶ 614
) -> Option<i64> {
615
    use crate::db::proposals as pdb;
616
    let bookmark = bump_bookmark(path);
617
    let bookmark = bookmark.as_str();
618
    let me = account(&app.db).await?;
c4e432da Andy McCall ↶ 619
    let log = changelog(app, upstream, from, to.clone(), watch.clone()).await;
620
    let lines = log.lines;
621
    let flagged = if log.watched.is_empty() {
622
        String::new()
623
    } else {
624
        format!(
625
            "\n\n**Touches what you watch** ({}):\n\n{}",
626
            watch.iter().map(|w| format!("`{w}`")).collect::<Vec<_>>().join(", "),
627
            log.watched.join("\n")
628
        )
629
    };
a7e6e8e6 Andy McCall ↶ 630
    let slug = format!("{}/{}", upstream.owner, upstream.name);
631
    let short: Vec<String> = to.iter().map(|h| h.to_hex()[..12].to_string()).collect();
1b6536f0 Andy McCall ↶ 632
    let ub = &upstream.default_bookmark;
633
    let count = if lines.len() == 1 { "1 change".to_string() } else { format!("{} changes", lines.len()) };
634
    let title = format!("Diffusion: {path} to {slug} {ub} ({count})");
9aaa88b2 Andy McCall ↶ 635
    let when = match why {
636
        Why::Green => "at its newest state whose checks passed",
637
        Why::Moved => "as it is now",
638
        Why::Unverified => "as it is now",
639
    };
640
    let amber = if why == Why::Unverified {
641
        format!("\n\n> **Upstream unverified.** {slug} has no checks of its own, so nothing has tested this state of it. Only this repository's pipeline tests the move; a later bump from a passing run of {slug} clears this.")
642
    } else {
643
        String::new()
644
    };
a7e6e8e6 Andy McCall ↶ 645
    let body = format!(
c4e432da Andy McCall ↶ 646
        "Moves the subrepo `{path}` to [{slug}](/{slug})'s `{ub}`, {when} (`{}`). Only the pin changes; this repository's own checks test it.{amber}{flagged}\n\n**What it brings** ({count}):\n\n{}\n\nOpened and kept up to date by Diffusion (docs/diffusion.md). It never lands by itself.",
1b6536f0 Andy McCall ↶ 647
        short.join("+"),
a7e6e8e6 Andy McCall ↶ 648
        lines.join("\n")
649
    );
650
    let open = pdb::list(&app.db, consumer.id, &["open", "draft"]).await.ok()?.into_iter().find(|p| p.source_bookmark == bookmark);
9aaa88b2 Andy McCall ↶ 651
    let (number, id) = match open {
a7e6e8e6 Andy McCall ↶ 652
        Some(p) => {
9aaa88b2 Andy McCall ↶ 653
            if p.title != title || p.body != body {
654
                pdb::edit(&app.db, p.id, &title, &body, target).await.ok()?;
655
                pdb::add_event(&app.db, p.id, ACCOUNT, "updated", &short.join("+")).await.ok();
656
            }
657
            (p.number, p.id)
a7e6e8e6 Andy McCall ↶ 658
        }
659
        None => {
660
            let p = pdb::create(
661
                &app.db,
662
                pdb::NewProposal {
663
                    repo_id: consumer.id,
664
                    title: &title,
665
                    body: &body,
666
                    author_id: Some(me.id),
667
                    author: ACCOUNT,
668
                    draft: false,
669
                    target,
670
                    source_kind: "bookmark",
671
                    source_repo_id: None,
672
                    source_bookmark: bookmark,
673
                    source_changes: "",
674
                },
675
            )
676
            .await
677
            .ok()?;
678
            pdb::add_event(&app.db, p.id, ACCOUNT, "opened", "").await.ok();
679
            db::notify::index(&app.db, "proposal", consumer.id, p.id, p.number, &p.title, &p.body).await.ok();
680
            if let Ok(label) =
681
                db::issues::upsert_label(&app.db, consumer.id, "dependencies", "#0072ff", "A subrepo moves (Diffusion)").await
682
            {
683
                db::issues::set_proposal_label(&app.db, p.id, label.id, true).await.ok();
684
            }
9aaa88b2 Andy McCall ↶ 685
            (p.number, p.id)
a7e6e8e6 Andy McCall ↶ 686
        }
687
    };
9aaa88b2 Andy McCall ↶ 688
    // Amber while the upstream has no checks; cleared by a green bump.
689
    let unverified = db::issues::label_by_name(&app.db, consumer.id, "upstream unverified").await.ok().flatten();
690
    match (why == Why::Unverified, unverified) {
691
        (true, l) => {
692
            let l = match l {
693
                Some(l) => Some(l),
694
                None => db::issues::upsert_label(
695
                    &app.db,
696
                    consumer.id,
697
                    "upstream unverified",
698
                    "#e3a008",
699
                    "The upstream has no checks (Diffusion)",
700
                )
701
                .await
702
                .ok(),
703
            };
704
            if let Some(l) = l {
705
                db::issues::set_proposal_label(&app.db, id, l.id, true).await.ok();
706
            }
707
        }
708
        (false, Some(l)) => {
709
            db::issues::set_proposal_label(&app.db, id, l.id, false).await.ok();
710
        }
711
        (false, None) => {}
712
    }
a7e6e8e6 Andy McCall ↶ 713
    Some(number)
714
}
715
f01cb865 Andy McCall ↶ 716
/// Start a bump's pipeline, as a push of it would. Boxed as `Send`, which
717
/// breaks the cycle between a bump starting runs and a passing run
718
/// starting bumps that the compiler cannot see through.
719
fn start_runs(
720
    app: Shared,
721
    row: RepoRow,
722
    bookmark: String,
723
    state: String,
724
    heads: Vec<ChangeHash>,
725
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {
726
    Box::pin(async move { crate::flow::on_push(&app, &row, &bookmark, &state, &heads, ACCOUNT).await })
727
}
728
a7e6e8e6 Andy McCall ↶ 729
/// The text of `.oxymodules` on `bookmark` of `name`, if any.
730
async fn oxymodules(app: &Shared, name: &RepoName, bookmark: &str) -> Option<String> {
731
    let b = bookmark.to_string();
732
    app.repos
733
        .read(name, move |r, cache| {
734
            let heads = heads_of(r, &b)?;
735
            if heads.is_empty() {
736
                return Ok(None);
737
            }
738
            let loaded = cache.load(r, &heads)?;
739
            Ok(match loaded.snapshot.files.get(".oxymodules").map(|f| &f.content) {
740
                Some(oxy_core::state::FileContent::Text { bytes, .. }) => Some(String::from_utf8_lossy(bytes).into_owned()),
741
                _ => None,
742
            })
743
        })
744
        .await
745
        .ok()
746
        .flatten()
747
}
748
749
/// The upstream `upstream` reached `heads` on its default bookmark: by a
750
/// push (`green` false) or a passing run of that state (`green` true).
751
/// Bump and propose in every consumer that follows it that way (§4.3).
752
pub async fn propagate(app: &Shared, upstream: &RepoRow, heads: Vec<ChangeHash>, green: bool) {
3776b70d Andy McCall ↶ 753
    propagate_to(app, upstream, heads, green, None).await
754
}
755
756
/// `propagate`, to one consumer only when `only` names it.
757
async fn propagate_to(app: &Shared, upstream: &RepoRow, heads: Vec<ChangeHash>, green: bool, only: Option<i64>) {
a7e6e8e6 Andy McCall ↶ 758
    let Some(uname) = RepoName::new(&upstream.owner, &upstream.name) else { return };
759
    let Ok(id) = app.repos.read(&uname, |r, _| Ok(r.id()?)).await else { return };
760
    let rows: Vec<(i64, String, String)> = sqlx::query_as("SELECT consumer_id, bookmark, path FROM diffusion_pins WHERE upstream = ?")
761
        .bind(hex::encode(id))
762
        .fetch_all(&app.db)
763
        .await
764
        .unwrap_or_default();
9aaa88b2 Andy McCall ↶ 765
    let unverified = unverified(app, upstream).await;
a7e6e8e6 Andy McCall ↶ 766
    for (consumer_id, indexed, path) in rows {
3776b70d Andy McCall ↶ 767
        if only.is_some_and(|o| o != consumer_id) {
768
            continue;
769
        }
a7e6e8e6 Andy McCall ↶ 770
        let Ok(Some(consumer)) = db::repos::get_by_id(&app.db, consumer_id).await else { continue };
771
        let Some(cname) = RepoName::new(&consumer.owner, &consumer.name) else { continue };
772
        let learned = target(&app.db, &consumer).await;
773
        let modules = oxymodules(app, &cname, &learned).await;
774
        let r = rule(&app.config.diffusion.follow, &consumer, modules.as_deref(), &path);
775
        let target = r.target.clone().unwrap_or(learned);
776
        if indexed != target {
777
            continue;
778
        }
9aaa88b2 Andy McCall ↶ 779
        // An upstream with no checks never turns green: its moves count
780
        // for green followers too, marked amber (unverified).
a7e6e8e6 Andy McCall ↶ 781
        let go = match r.follow {
782
            Follow::Off => false,
9aaa88b2 Andy McCall ↶ 783
            Follow::Green => green || unverified,
a7e6e8e6 Andy McCall ↶ 784
            Follow::Any => !green,
785
        };
9aaa88b2 Andy McCall ↶ 786
        let why = if green {
787
            Why::Green
788
        } else if unverified {
789
            Why::Unverified
790
        } else {
791
            Why::Moved
792
        };
a7e6e8e6 Andy McCall ↶ 793
        if !go {
794
            continue;
795
        }
796
        match bump(app, &consumer, &target, &path, upstream, heads.clone()).await {
f01cb865 Andy McCall ↶ 797
            Ok(Bumped::Moved { from, bookmark, heads: bumped, state, .. }) => {
798
                // Its pipeline runs as for a push, so the proposal is tested.
799
                tokio::spawn(start_runs(app.clone(), consumer.clone(), bookmark, state, bumped));
c4e432da Andy McCall ↶ 800
                let n = propose(app, &consumer, &target, &path, upstream, (from, heads.clone()), (why, r.watch.clone())).await;
a7e6e8e6 Andy McCall ↶ 801
                tracing::info!(
802
                    "diffusion: {}/{} {path} bumped to {}/{} (proposal {n:?})",
803
                    consumer.owner,
804
                    consumer.name,
805
                    upstream.owner,
806
                    upstream.name
807
                );
9aaa88b2 Andy McCall ↶ 808
            }
809
            Ok(Bumped::Already { from, to }) => {
810
                // Already moved: its proposal's text and labels are brought
811
                // up to date all the same.
c4e432da Andy McCall ↶ 812
                propose(app, &consumer, &target, &path, upstream, (from, to), (why, r.watch.clone())).await;
a7e6e8e6 Andy McCall ↶ 813
            }
7a14bdae Andy McCall ↶ 814
            Ok(other) => tracing::info!("diffusion: {}/{} {path}: no bump ({other:?})", consumer.owner, consumer.name),
a7e6e8e6 Andy McCall ↶ 815
            Err(e) => tracing::warn!("diffusion: bump {}/{} {path}: {e}", consumer.owner, consumer.name),
3776b70d Andy McCall ↶ 816
        }
817
    }
9aaa88b2 Andy McCall ↶ 818
}
819
820
/// Whether `upstream` has no checks of its own: Flow is off for it, or
821
/// its default bookmark has never had a run. Its moves are then
822
/// "unverified" (amber), never green.
823
pub async fn unverified(app: &Shared, upstream: &RepoRow) -> bool {
824
    if !crate::flow::enabled(app, upstream) {
825
        return true;
826
    }
827
    let runs: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM flow_runs WHERE repo_id = ? AND bookmark = ?")
828
        .bind(upstream.id)
829
        .bind(&upstream.default_bookmark)
830
        .fetch_one(&app.db)
831
        .await
832
        .unwrap_or(0);
833
    runs == 0
3776b70d Andy McCall ↶ 834
}
835
836
/// The repository on this hub with Oxygen id `id` (hex).
837
async fn repo_by_oxy_id(app: &Shared, id: &str) -> Option<RepoRow> {
838
    for row in db::repos::list(&app.db).await.ok()? {
839
        let Some(name) = RepoName::new(&row.owner, &row.name) else { continue };
840
        if app.repos.read(&name, |r, _| Ok(r.id()?)).await.ok().map(hex::encode).as_deref() == Some(id) {
841
            return Some(row);
842
        }
843
    }
844
    None
845
}
846
847
/// The newest state of `upstream`'s default bookmark whose run passed.
848
async fn last_green(app: &Shared, upstream: &RepoRow) -> Option<Vec<ChangeHash>> {
849
    let heads: String =
850
        sqlx::query_scalar("SELECT heads FROM flow_runs WHERE repo_id = ? AND bookmark = ? AND status = 'passed' ORDER BY id DESC LIMIT 1")
851
            .bind(upstream.id)
852
            .bind(&upstream.default_bookmark)
853
            .fetch_optional(&app.db)
854
            .await
855
            .ok()
856
            .flatten()?;
857
    let h: Vec<ChangeHash> = heads.split('+').filter_map(ChangeHash::from_hex).collect();
858
    (!h.is_empty()).then_some(h)
859
}
860
861
/// Bring `consumer` up to date with the upstreams it pins, at once: when
862
/// it turns Diffusion on, it is bumped to each upstream's newest state
863
/// that passed (or simply its newest, when it follows every move).
864
pub async fn catch_up(app: &Shared, consumer: &RepoRow) {
865
    let upstreams: Vec<String> = sqlx::query_scalar("SELECT DISTINCT upstream FROM diffusion_pins WHERE consumer_id = ?")
866
        .bind(consumer.id)
867
        .fetch_all(&app.db)
868
        .await
869
        .unwrap_or_default();
870
    for id in upstreams {
871
        let Some(upstream) = repo_by_oxy_id(app, &id).await else { continue };
872
        if let Some(h) = last_green(app, &upstream).await {
873
            propagate_to(app, &upstream, h, true, Some(consumer.id)).await;
874
        }
875
        let Some(name) = RepoName::new(&upstream.owner, &upstream.name) else { continue };
876
        let b = upstream.default_bookmark.clone();
877
        if let Ok(h) = app.repos.read(&name, move |r, _| heads_of(r, &b)).await {
878
            propagate_to(app, &upstream, h, false, Some(consumer.id)).await;
a7e6e8e6 Andy McCall ↶ 879
        }
880
    }
881
}
882
e7158350 Andy McCall ↶ 883
/// When a consumer takes an upstream's moves (§4.2).
884
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
885
#[serde(rename_all = "lowercase")]
886
pub enum Follow {
887
    Off,
888
    /// When the upstream state's checks pass.
889
    Green,
890
    /// On every move.
891
    Any,
892
}
893
894
impl Follow {
895
    pub fn parse(s: &str) -> Option<Follow> {
896
        match s.trim() {
897
            "off" => Some(Follow::Off),
898
            "green" => Some(Follow::Green),
899
            "any" => Some(Follow::Any),
900
            _ => None,
901
        }
902
    }
903
}
904
905
/// How one consumer follows one subrepo, from its `.oxymodules` entry, its
906
/// repository setting and the site's default, in that order.
907
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
908
pub struct Rule {
909
    pub follow: Follow,
910
    /// Land a green bump itself (D5); D1 only proposes.
911
    pub land_auto: bool,
912
    /// The bookmark to bump, when `.oxymodules` names one (else learned).
913
    pub target: Option<String>,
914
    /// Paths the consumer watches: upstream changes touching them are
915
    /// flagged in a bump's changelog.
916
    pub watch: Vec<String>,
917
    /// Where `follow` came from: `.oxymodules`, `setting` or `site`.
918
    pub from: &'static str,
919
}
920
921
/// The Diffusion keys of `path`'s entry in `.oxymodules` text: `follow`,
922
/// `land`, `target` and `watch` (comma-separated, or a TOML list).
923
pub fn module_keys(text: &str, path: &str) -> (Option<Follow>, Option<bool>, Option<String>, Vec<String>) {
924
    let (mut follow, mut land, mut target, mut watch) = (None, None, None, Vec::new());
925
    let mut here = false;
926
    for line in text.lines() {
927
        let line = line.trim();
928
        if line.is_empty() || line.starts_with('#') {
929
            continue;
930
        }
931
        if let Some(inner) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
932
            here = inner.trim().trim_matches('"').trim_end_matches('/') == path.trim_end_matches('/');
933
            continue;
934
        }
935
        let (true, Some((k, v))) = (here, line.split_once('=')) else { continue };
936
        let v = v.trim();
937
        let unquoted = v.trim_matches('"').trim();
938
        match k.trim() {
939
            "follow" => follow = Follow::parse(unquoted),
940
            "land" => land = Some(unquoted == "auto"),
941
            "target" if !unquoted.is_empty() => target = Some(unquoted.to_string()),
942
            "watch" => {
943
                watch = v
944
                    .trim_start_matches('[')
945
                    .trim_end_matches(']')
946
                    .split(',')
947
                    .map(|w| w.trim().trim_matches('"').trim().to_string())
948
                    .filter(|w| !w.is_empty())
949
                    .collect()
950
            }
951
            _ => {}
952
        }
953
    }
954
    (follow, land, target, watch)
955
}
956
957
/// How `row` follows its subrepo at `path`, given its `.oxymodules` text.
958
pub fn rule(site_default: &str, row: &RepoRow, oxymodules: Option<&str>, path: &str) -> Rule {
959
    let (follow, land, target, watch) = oxymodules.map(|t| module_keys(t, path)).unwrap_or_default();
960
    let (follow, from) = match follow {
961
        Some(f) => (f, ".oxymodules"),
962
        None => match Follow::parse(&row.diffusion) {
963
            Some(f) => (f, "setting"),
964
            None => (Follow::parse(site_default).unwrap_or(Follow::Off), "site"),
965
        },
966
    };
967
    Rule { follow, land_auto: land.unwrap_or(false), target, watch, from }
968
}
969
970
#[cfg(test)]
971
mod tests {
972
    use super::*;
973
974
    const MODULES: &str = r#"
975
[rstar-api]
976
url = https://oxygenhub.io/doomsdayone/rstar-api
977
follow = green
978
land = "propose"
979
target = develop
980
watch = ["src/x16/irq*", "src/x16/frame*"]
981
982
[other]
983
url = https://example/other
984
follow = any
985
"#;
986
987
    fn row(diffusion: &str) -> RepoRow {
988
        RepoRow {
989
            id: 1,
990
            owner: "o".into(),
991
            name: "n".into(),
992
            description: String::new(),
993
            default_bookmark: "main".into(),
994
            visibility: "public".into(),
995
            created_ms: 0,
996
            updated_ms: 0,
997
            git_mirror: false,
998
            git_mirror_state: String::new(),
999
            forked_from: None,
1000
            topics: String::new(),
1001
            flow: String::new(),
1002
            diffusion: diffusion.into(),
1003
            ..Default::default()
1004
        }
c4e432da Andy McCall ↶ 1005
    }
1006
1007
    #[test]
1008
    fn watch_patterns_match_paths() {
1009
        assert!(watched("src/x16/irq*", "src/x16/irq.s"));
1010
        assert!(watched("src/x16/irq*", "src/x16/irq_wait.c"));
1011
        assert!(!watched("src/x16/irq*", "src/x16/sub/irq.s"), "one segment");
1012
        assert!(watched("src/**/frame*.c", "src/x16/floor/frame_wait.c"));
1013
        assert!(watched("src/x16", "src/x16/bank.s"), "a directory");
1014
        assert!(!watched("src/x16", "src/x160/bank.s"));
1015
        assert!(watched("include/r?m.h", "include/rim.h"));
1016
        assert!(!watched("", "anything"));
e7158350 Andy McCall ↶ 1017
    }
1018
1019
    #[test]
1020
    fn oxymodules_keys_are_read_per_entry() {
1021
        let (f, land, target, watch) = module_keys(MODULES, "rstar-api");
1022
        assert_eq!((f, land, target.as_deref()), (Some(Follow::Green), Some(false), Some("develop")));
1023
        assert_eq!(watch, vec!["src/x16/irq*", "src/x16/frame*"]);
1024
        assert_eq!(module_keys(MODULES, "other").0, Some(Follow::Any));
1025
        assert_eq!(module_keys(MODULES, "missing"), (None, None, None, vec![]));
1026
        assert_eq!(module_keys("[a]\nwatch = x, y\n", "a").3, vec!["x", "y"]);
1027
    }
1028
1029
    #[test]
1030
    fn oxymodules_wins_then_the_setting_then_the_site() {
1031
        let r = rule("off", &row("any"), Some(MODULES), "rstar-api");
1032
        assert_eq!((r.follow, r.from), (Follow::Green, ".oxymodules"));
1033
        let r = rule("off", &row("any"), Some("[rstar-api]\nurl = x\n"), "rstar-api");
1034
        assert_eq!((r.follow, r.from), (Follow::Any, "setting"));
1035
        let r = rule("green", &row(""), None, "rstar-api");
1036
        assert_eq!((r.follow, r.from), (Follow::Green, "site"));
1037
        assert_eq!(rule("nonsense", &row(""), None, "x").follow, Follow::Off);
1038
    }
1039
}