OXYGENHUB
◆ main oxygenhub / crates / hub / src / repo_setup.rs
19.8 KiB · Rust · last changed New repository page in sections, with OxygenFlow, the wiki and a default bookmark 14 hours ago source blame history raw
40a43921 Andy McCall ↶ 1
//! What a new repository starts with (oxygenhub#360), shared by the New
2
//! repository page and the API: a name check before anything is made, the
3
//! files it starts with (a README, a licence, an `.oxyignore` for a
4
//! language), committed as its creator the way the starter's are (#347),
5
//! and a project board made or chosen with it, which then takes its issues
1062a0f8 Andy McCall ↶ 6
//! and proposals as they open. OxygenFlow switched on and the wiki
7
//! started with a Home page come with it too (#371).
40a43921 Andy McCall ↶ 8
9
use crate::auth::roles;
10
use crate::db::{self, projects as pdb};
11
use crate::repos::RepoName;
12
use crate::Shared;
13
use oxy_core::repo::FileEdit;
14
15
/// Whether `owner/name` may be made by `account`: `Ok` with its address,
16
/// or why not, said as the page and the API say it.
17
pub async fn check_name(app: &Shared, account: &db::accounts::Account, owner: &str, name: &str) -> Result<RepoName, String> {
18
    let Some(n) = RepoName::new(owner.trim(), name.trim()) else {
19
        return Err("A repository name is letters, digits, dots, dashes and underscores, up to 64.".into());
20
    };
21
    if n.name.ends_with(crate::wiki::SUFFIX) {
22
        return Err("A name cannot end in .wiki: that is the address of a repository's wiki.".into());
23
    }
24
    if !roles::may_create_under(&app.db, account, &n.owner).await.map_err(|e| e.to_string())? {
25
        return Err(format!("You cannot create repositories under {}.", n.owner));
26
    }
27
    if db::repos::get(&app.db, &n.owner, &n.name).await.map_err(|e| e.to_string())?.is_some() || app.repos.exists(&n) {
28
        return Err(format!("{n} exists."));
29
    }
30
    Ok(n)
31
}
32
33
/// A board for a new repository: none, a new one under its owner with this
34
/// title, or the owner's board of this number.
35
#[derive(Clone, Debug, PartialEq, Eq)]
36
pub enum Board {
37
    None,
38
    New(String),
39
    Existing(i64),
40
}
41
42
impl Board {
43
    /// The form's or the API's choice: `new` with a title (the
44
    /// repository's name when empty), a board number, or nothing.
45
    pub fn parse(choice: &str, title: &str, repo: &str) -> Result<Board, String> {
46
        match choice.trim() {
47
            "" | "none" => Ok(Board::None),
48
            "new" => {
49
                let t: String = title.trim().chars().take(100).collect();
50
                Ok(Board::New(if t.is_empty() { repo.to_string() } else { t }))
51
            }
52
            n => n.parse().map(Board::Existing).map_err(|_| format!("No board {n}.")),
53
        }
54
    }
55
}
56
57
/// Checked before the repository is made: a chosen board must be the
58
/// owner's, open, and one `account` may change.
59
pub async fn check_board(app: &Shared, account: &db::accounts::Account, owner: &str, board: &Board) -> Result<(), String> {
60
    match board {
61
        Board::None => Ok(()),
62
        Board::New(_) => match crate::web::projects::rights_of(app, Some(account), owner).await.map_err(|e| e.to_string())? {
63
            Some(r) if r.edit => Ok(()),
64
            _ => Err(format!("You cannot make boards under {owner}.")),
65
        },
66
        Board::Existing(n) => {
67
            let p = pdb::get(&app.db, owner, *n).await.map_err(|e| e.to_string())?.ok_or(format!("{owner} has no board {n}."))?;
68
            if p.closed {
69
                return Err(format!("Board {n} is closed."));
70
            }
71
            match crate::web::projects::rights_of(app, Some(account), owner).await.map_err(|e| e.to_string())? {
72
                Some(r) if r.edit => Ok(()),
73
                _ => Err(format!("You cannot change {owner}'s boards.")),
74
            }
75
        }
76
    }
77
}
78
79
/// Make or find the board and link it to the repository; its number.
80
pub async fn link_board(app: &Shared, row: &db::repos::RepoRow, board: &Board, public: bool) -> sqlx::Result<Option<i64>> {
81
    let p = match board {
82
        Board::None => return Ok(None),
83
        Board::New(title) => pdb::create(&app.db, &row.owner, title, &format!("Work on {}/{}", row.owner, row.name), public).await?,
84
        Board::Existing(n) => match pdb::get(&app.db, &row.owner, *n).await? {
85
            Some(p) => p,
86
            None => return Ok(None),
87
        },
88
    };
89
    pdb::link_repo(&app.db, p.id, row.id).await?;
90
    Ok(Some(p.number))
91
}
92
1062a0f8 Andy McCall ↶ 93
/// Where a new repository's default bookmark comes from (#371): the
94
/// owner's own choice (a user's or an organisation's), else the site's,
95
/// else `main`. Kept in the settings table, so nothing else changes.
96
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97
pub enum BookmarkScope {
98
    Site,
99
    Account(i64),
100
    Org(i64),
101
}
102
103
/// The bookmark a repository has when nothing else is chosen.
104
pub const MAIN: &str = "main";
105
106
impl BookmarkScope {
107
    fn key(self) -> String {
108
        match self {
109
            BookmarkScope::Site => "default_bookmark".into(),
110
            BookmarkScope::Account(id) => format!("default_bookmark.account.{id}"),
111
            BookmarkScope::Org(id) => format!("default_bookmark.org.{id}"),
112
        }
113
    }
114
}
115
116
/// The default bookmark set at `scope`, if one is.
117
pub async fn bookmark_setting(pool: &db::Pool, scope: BookmarkScope) -> sqlx::Result<Option<String>> {
118
    Ok(db::accounts::setting(pool, &scope.key()).await?.filter(|v| !v.is_empty()))
119
}
120
121
/// Set (or, empty, clear) the default bookmark at `scope`.
122
pub async fn set_bookmark_setting(pool: &db::Pool, scope: BookmarkScope, value: &str) -> Result<(), String> {
123
    let v = value.trim();
124
    if !v.is_empty() {
125
        check_bookmark(v)?;
126
    }
127
    db::accounts::set_setting(pool, &scope.key(), v).await.map_err(|e| e.to_string())
128
}
129
130
/// A bookmark name a repository may default to.
131
pub fn check_bookmark(name: &str) -> Result<(), String> {
132
    if crate::repos::names::valid_segment(name) {
133
        Ok(())
134
    } else {
135
        Err(format!(
136
            "{name:?} is not a bookmark name: letters, digits, dots, dashes and underscores, up to 64, starting with a letter or digit."
137
        ))
138
    }
139
}
140
141
/// The default bookmark a new repository under `owner` takes, and where
142
/// it comes from (for the page: "develop, from doomsdayone's settings").
143
pub async fn default_bookmark_for(app: &Shared, owner: &str) -> (String, String) {
144
    let own = match db::accounts::org_by_name(&app.db, owner).await.ok().flatten() {
145
        Some(org) => Some(BookmarkScope::Org(org.id)),
146
        None => db::accounts::account_by_name(&app.db, owner).await.ok().flatten().map(|a| BookmarkScope::Account(a.id)),
147
    };
148
    if let Some(scope) = own {
149
        if let Ok(Some(b)) = bookmark_setting(&app.db, scope).await {
150
            return (b, format!("{owner}'s default"));
151
        }
152
    }
153
    match bookmark_setting(&app.db, BookmarkScope::Site).await {
154
        Ok(Some(b)) => (b, "this site's default".into()),
155
        _ => (MAIN.into(), "the usual default".into()),
156
    }
157
}
158
159
/// The new repository's default bookmark: the one asked for, or its
160
/// owner's, the site's or `main`; set on its row when it is not `main`.
161
pub async fn set_default_bookmark(app: &Shared, row: db::repos::RepoRow, asked: &str) -> sqlx::Result<db::repos::RepoRow> {
162
    let asked = asked.trim();
163
    let b = if asked.is_empty() { default_bookmark_for(app, &row.owner).await.0 } else { asked.to_string() };
164
    if b == row.default_bookmark {
165
        return Ok(row);
166
    }
167
    db::repos::set_default_bookmark(&app.db, row.id, &b).await?;
168
    Ok(db::repos::get_by_id(&app.db, row.id).await?.unwrap_or(row))
169
}
170
171
/// OxygenFlow for a new repository (#371): left to the site's default,
172
/// on the site's runners (a site administrator's choice), or on the
173
/// owner's own runners.
174
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
175
pub enum Flow {
176
    Default,
177
    On,
178
    Own,
179
}
180
181
impl Flow {
182
    pub fn parse(choice: &str) -> Result<Flow, String> {
183
        match choice.trim() {
184
            "" | "default" | "off" => Ok(Flow::Default),
185
            "on" => Ok(Flow::On),
186
            "own" => Ok(Flow::Own),
187
            other => Err(format!("OxygenFlow is on, own or left to the default, not {other}.")),
188
        }
189
    }
190
191
    /// The repository's `flow` setting, as Settings › Pipelines writes it.
192
    pub fn setting(self) -> &'static str {
193
        match self {
194
            Flow::Default => "",
195
            Flow::On => "on",
196
            Flow::Own => "own",
197
        }
198
    }
199
}
200
201
/// Whether `owner` has runners of its own (not the site's), which
202
/// [`Flow::Own`] needs before its repository exists.
203
pub async fn owner_has_runner(app: &Shared, owner: &str) -> sqlx::Result<bool> {
204
    Ok(db::runners::serving_owner(&app.db, owner).await?.iter().any(|r| !r.scope().is_site()))
205
}
206
207
/// Checked before the repository is made, as Settings › Pipelines checks.
208
pub async fn check_flow(app: &Shared, account: &db::accounts::Account, owner: &str, flow: Flow) -> Result<(), String> {
209
    match flow {
210
        Flow::Default => Ok(()),
211
        Flow::On if account.is_admin => Ok(()),
212
        Flow::On => Err("Only site administrators let the site's runners take a repository's jobs.".into()),
213
        Flow::Own => match owner_has_runner(app, owner).await.map_err(|e| e.to_string())? {
214
            true => Ok(()),
215
            false => {
216
                Err(format!("{owner} has no runners of its own yet: register one, then switch OxygenFlow on in Settings › Pipelines."))
217
            }
218
        },
219
    }
220
}
221
222
/// Switch OxygenFlow on for the new repository, as chosen.
223
pub async fn set_flow(app: &Shared, row: &db::repos::RepoRow, by: &db::accounts::Account, flow: Flow) -> sqlx::Result<()> {
224
    if flow == Flow::Default {
225
        return Ok(());
226
    }
227
    db::repos::set_flow(&app.db, row.id, flow.setting()).await?;
228
    db::accounts::audit(&app.db, Some(by), "repo.flow", &format!("{}/{}", row.owner, row.name), flow.setting()).await.ok();
229
    Ok(())
230
}
231
232
/// A new wiki's Home page: the repository's name and description.
233
pub fn wiki_home(name: &RepoName, description: &str) -> String {
234
    let about = description.trim();
235
    let about = if about.is_empty() { String::new() } else { format!("{about}\n\n") };
236
    format!("# {}\n\n{about}This is the wiki's home page. Edit it, or add pages beside it.\n", name.name)
237
}
238
239
/// Start the repository's wiki with its Home page, written as `by` and
240
/// signed as their delegate, as a wiki edit on the site is.
241
pub async fn start_wiki(app: &Shared, row: &db::repos::RepoRow, by: &db::accounts::Account, description: &str) -> Result<(), String> {
242
    let name = RepoName::new(&row.owner, &row.name).ok_or("bad repository name")?;
243
    let signer = crate::web::edit::signer_for(app, by.id).await?;
244
    let edit = FileEdit { path: crate::wiki::path_of(crate::wiki::HOME), content: Some(wiki_home(&name, description).into_bytes()) };
245
    crate::wiki::commit(app, &name, vec![edit], "Start the wiki".into(), signer).await.map_err(|e| e.to_string())?;
246
    db::accounts::audit(&app.db, Some(by), "wiki.started", &name.to_string(), "Home").await.ok();
247
    Ok(())
248
}
249
40a43921 Andy McCall ↶ 250
/// The licences offered, with what each allows, for the page.
251
pub const LICENCES: &[(&str, &str)] = &[
252
    ("MIT", "use, change and share it freely, keeping the notice"),
253
    ("BSD-2-Clause", "as MIT, in the BSD's words"),
254
    ("ISC", "as MIT, in fewer words"),
255
];
256
257
/// The languages an `.oxyignore` is offered for.
258
pub const IGNORES: &[&str] = &["Rust", "Node", "Python", "Go", "Java and Kotlin"];
259
260
/// What a new repository starts with: the files, by path.
261
#[derive(Clone, Debug, Default, PartialEq, Eq)]
262
pub struct Start {
263
    pub readme: bool,
264
    /// One of [`LICENCES`], or empty.
265
    pub licence: String,
266
    /// One of [`IGNORES`], or empty.
267
    pub ignore: String,
268
}
269
270
impl Start {
271
    pub fn is_empty(&self) -> bool {
272
        !self.readme && self.licence.is_empty() && self.ignore.is_empty()
273
    }
274
275
    /// The files, for a repository `name` described as `description`,
276
    /// whose copyright `holder` keeps in `year`.
277
    pub fn files(&self, name: &RepoName, description: &str, holder: &str, year: i32) -> Result<Vec<(String, String)>, String> {
278
        let mut out = Vec::new();
279
        if self.readme {
280
            let about = if description.trim().is_empty() { String::new() } else { format!("{}\n\n", description.trim()) };
281
            out.push(("README.md".to_string(), format!("# {}\n\n{about}", name.name)));
282
        }
283
        if !self.licence.is_empty() {
284
            let text = licence(&self.licence, holder, year).ok_or(format!("No licence {}.", self.licence))?;
285
            out.push(("LICENSE".to_string(), text));
286
        }
287
        if !self.ignore.is_empty() {
288
            let text = ignore(&self.ignore).ok_or(format!("No .oxyignore for {}.", self.ignore))?;
289
            out.push((".oxyignore".to_string(), text.to_string()));
290
        }
291
        Ok(out)
292
    }
293
}
294
295
fn licence(id: &str, holder: &str, year: i32) -> Option<String> {
296
    Some(match id {
297
        "MIT" => format!(
298
            "MIT License\n\nCopyright (c) {year} {holder}\n\n\
299
Permission is hereby granted, free of charge, to any person obtaining a copy\n\
300
of this software and associated documentation files (the \"Software\"), to deal\n\
301
in the Software without restriction, including without limitation the rights\n\
302
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\
303
copies of the Software, and to permit persons to whom the Software is\n\
304
furnished to do so, subject to the following conditions:\n\n\
305
The above copyright notice and this permission notice shall be included in all\n\
306
copies or substantial portions of the Software.\n\n\
307
THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\
308
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\
309
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\
310
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\
311
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\
312
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\
313
SOFTWARE.\n"
314
        ),
315
        "BSD-2-Clause" => format!(
316
            "BSD 2-Clause License\n\nCopyright (c) {year}, {holder}\n\n\
317
Redistribution and use in source and binary forms, with or without\n\
318
modification, are permitted provided that the following conditions are met:\n\n\
319
1. Redistributions of source code must retain the above copyright notice, this\n   \
320
list of conditions and the following disclaimer.\n\n\
321
2. Redistributions in binary form must reproduce the above copyright notice,\n   \
322
this list of conditions and the following disclaimer in the documentation\n   \
323
and/or other materials provided with the distribution.\n\n\
324
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\
325
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\
326
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\
327
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\
328
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\
329
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\
330
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\
331
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\
332
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\
333
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
334
        ),
335
        "ISC" => format!(
336
            "ISC License\n\nCopyright (c) {year} {holder}\n\n\
337
Permission to use, copy, modify, and/or distribute this software for any\n\
338
purpose with or without fee is hereby granted, provided that the above\n\
339
copyright notice and this permission notice appear in all copies.\n\n\
340
THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\
341
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\
342
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n\
343
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\
344
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\
345
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n\
346
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n"
347
        ),
348
        _ => return None,
349
    })
350
}
351
352
fn ignore(lang: &str) -> Option<&'static str> {
353
    Some(match lang {
354
        "Rust" => "# Build output\ntarget/\n",
355
        "Node" => "# Dependencies and build output\nnode_modules/\ndist/\n*.log\n",
356
        "Python" => "# Caches, environments and build output\n__pycache__/\n*.pyc\n.venv/\nbuild/\ndist/\n*.egg-info/\n",
357
        "Go" => "# Build output\nbin/\n*.test\n",
358
        "Java and Kotlin" => "# Build output and tool state\nbuild/\n.gradle/\nout/\n*.class\n",
359
        _ => return None,
360
    })
361
}
362
363
/// Commit `files` to the new repository's default bookmark as `by`, signed
364
/// as their delegate (as the starter's are); a repository with no files
365
/// yet only.
366
pub async fn commit_start(
367
    app: &Shared,
368
    row: &db::repos::RepoRow,
369
    by: &db::accounts::Account,
370
    files: Vec<(String, String)>,
371
) -> Result<(), String> {
372
    if files.is_empty() {
373
        return Ok(());
374
    }
375
    let name = RepoName::new(&row.owner, &row.name).ok_or("bad repository name")?;
376
    let signer = crate::web::edit::signer_for(app, by.id).await?;
377
    let paths: Vec<String> = files.iter().map(|(p, _)| p.clone()).collect();
378
    let edits: Vec<FileEdit> = files.into_iter().map(|(path, content)| FileEdit { path, content: Some(content.into_bytes()) }).collect();
379
    let b = row.default_bookmark.clone();
380
    crate::repos::edits::commit(&app.repos, &name, b.clone(), b, edits, format!("Start with {}", paths.join(", ")), signer)
381
        .await
382
        .map_err(|e| e.to_string())?;
383
    db::accounts::audit(&app.db, Some(by), "repo.started", &name.to_string(), &paths.join(", ")).await.ok();
384
    Ok(())
385
}
386
387
#[cfg(test)]
388
mod tests {
389
    use super::*;
390
391
    #[test]
392
    fn boards_and_starting_files() {
393
        assert_eq!(Board::parse("", "", "demo").unwrap(), Board::None);
394
        assert_eq!(Board::parse("new", " ", "demo").unwrap(), Board::New("demo".into()));
395
        assert_eq!(Board::parse("new", "Roadmap", "demo").unwrap(), Board::New("Roadmap".into()));
396
        assert_eq!(Board::parse("4", "", "demo").unwrap(), Board::Existing(4));
397
        assert!(Board::parse("four", "", "demo").is_err());
398
        let name = RepoName::new("andy", "demo").unwrap();
399
        let s = Start { readme: true, licence: "MIT".into(), ignore: "Rust".into() };
400
        let files = s.files(&name, "A demo.", "Andy McCall", 2026).unwrap();
401
        let paths: Vec<&str> = files.iter().map(|(p, _)| p.as_str()).collect();
402
        assert_eq!(paths, ["README.md", "LICENSE", ".oxyignore"]);
403
        assert_eq!(files[0].1, "# demo\n\nA demo.\n\n");
404
        assert!(files[1].1.starts_with("MIT License\n\nCopyright (c) 2026 Andy McCall\n"));
405
        assert_eq!(files[2].1, "# Build output\ntarget/\n");
406
        for (id, _) in LICENCES {
407
            assert!(licence(id, "X", 2026).unwrap().contains("2026"), "{id}");
408
        }
409
        for lang in IGNORES {
410
            assert!(ignore(lang).is_some(), "{lang}");
411
        }
412
        assert!(Start { licence: "GPL".into(), ..Default::default() }.files(&name, "", "X", 2026).is_err());
413
        assert!(Start::default().is_empty());
1062a0f8 Andy McCall ↶ 414
    }
415
416
    #[test]
417
    fn flow_choices_and_the_wiki_home() {
418
        assert_eq!(Flow::parse("").unwrap(), Flow::Default);
419
        assert_eq!(Flow::parse("off").unwrap(), Flow::Default);
420
        assert_eq!(Flow::parse("on").unwrap().setting(), "on");
421
        assert_eq!(Flow::parse("own").unwrap().setting(), "own");
422
        assert!(Flow::parse("always").is_err());
423
        let name = RepoName::new("andy", "square").unwrap();
424
        assert_eq!(
425
            wiki_home(&name, " A platform game. "),
426
            "# square\n\nA platform game.\n\nThis is the wiki's home page. Edit it, or add pages beside it.\n"
427
        );
428
        assert!(wiki_home(&name, "").starts_with("# square\n\nThis is"));
429
    }
430
431
    #[test]
432
    fn bookmark_defaults_are_kept_apart() {
433
        assert_eq!(BookmarkScope::Site.key(), "default_bookmark");
434
        assert_eq!(BookmarkScope::Account(7).key(), "default_bookmark.account.7");
435
        assert_eq!(BookmarkScope::Org(7).key(), "default_bookmark.org.7");
436
        assert!(check_bookmark("develop").is_ok());
437
        assert!(check_bookmark("release-1.0").is_ok());
438
        assert!(check_bookmark("feature/x").is_err());
439
        assert!(check_bookmark("-x").is_err());
40a43921 Andy McCall ↶ 440
    }
441
}