//! What a new repository starts with (oxygenhub#360), shared by the New //! repository page and the API: a name check before anything is made, the //! files it starts with (a README, a licence, an `.oxyignore` for a //! language), committed as its creator the way the starter's are (#347), //! and a project board made or chosen with it, which then takes its issues //! and proposals as they open. OxygenFlow switched on and the wiki //! started with a Home page come with it too (#371). use crate::auth::roles; use crate::db::{self, projects as pdb}; use crate::repos::RepoName; use crate::Shared; use oxy_core::repo::FileEdit; /// Whether `owner/name` may be made by `account`: `Ok` with its address, /// or why not, said as the page and the API say it. pub async fn check_name(app: &Shared, account: &db::accounts::Account, owner: &str, name: &str) -> Result { let Some(n) = RepoName::new(owner.trim(), name.trim()) else { return Err("A repository name is letters, digits, dots, dashes and underscores, up to 64.".into()); }; if n.name.ends_with(crate::wiki::SUFFIX) { return Err("A name cannot end in .wiki: that is the address of a repository's wiki.".into()); } if !roles::may_create_under(&app.db, account, &n.owner).await.map_err(|e| e.to_string())? { return Err(format!("You cannot create repositories under {}.", n.owner)); } if db::repos::get(&app.db, &n.owner, &n.name).await.map_err(|e| e.to_string())?.is_some() || app.repos.exists(&n) { return Err(format!("{n} exists.")); } Ok(n) } /// A board for a new repository: none, a new one under its owner with this /// title, or the owner's board of this number. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Board { None, New(String), Existing(i64), } impl Board { /// The form's or the API's choice: `new` with a title (the /// repository's name when empty), a board number, or nothing. pub fn parse(choice: &str, title: &str, repo: &str) -> Result { match choice.trim() { "" | "none" => Ok(Board::None), "new" => { let t: String = title.trim().chars().take(100).collect(); Ok(Board::New(if t.is_empty() { repo.to_string() } else { t })) } n => n.parse().map(Board::Existing).map_err(|_| format!("No board {n}.")), } } } /// Checked before the repository is made: a chosen board must be the /// owner's, open, and one `account` may change. pub async fn check_board(app: &Shared, account: &db::accounts::Account, owner: &str, board: &Board) -> Result<(), String> { match board { Board::None => Ok(()), Board::New(_) => match crate::web::projects::rights_of(app, Some(account), owner).await.map_err(|e| e.to_string())? { Some(r) if r.edit => Ok(()), _ => Err(format!("You cannot make boards under {owner}.")), }, Board::Existing(n) => { let p = pdb::get(&app.db, owner, *n).await.map_err(|e| e.to_string())?.ok_or(format!("{owner} has no board {n}."))?; if p.closed { return Err(format!("Board {n} is closed.")); } match crate::web::projects::rights_of(app, Some(account), owner).await.map_err(|e| e.to_string())? { Some(r) if r.edit => Ok(()), _ => Err(format!("You cannot change {owner}'s boards.")), } } } } /// Make or find the board and link it to the repository; its number. pub async fn link_board(app: &Shared, row: &db::repos::RepoRow, board: &Board, public: bool) -> sqlx::Result> { let p = match board { Board::None => return Ok(None), Board::New(title) => pdb::create(&app.db, &row.owner, title, &format!("Work on {}/{}", row.owner, row.name), public).await?, Board::Existing(n) => match pdb::get(&app.db, &row.owner, *n).await? { Some(p) => p, None => return Ok(None), }, }; pdb::link_repo(&app.db, p.id, row.id).await?; Ok(Some(p.number)) } /// Where a new repository's default bookmark comes from (#371): the /// owner's own choice (a user's or an organisation's), else the site's, /// else `main`. Kept in the settings table, so nothing else changes. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BookmarkScope { Site, Account(i64), Org(i64), } /// The bookmark a repository has when nothing else is chosen. pub const MAIN: &str = "main"; impl BookmarkScope { fn key(self) -> String { match self { BookmarkScope::Site => "default_bookmark".into(), BookmarkScope::Account(id) => format!("default_bookmark.account.{id}"), BookmarkScope::Org(id) => format!("default_bookmark.org.{id}"), } } } /// The default bookmark set at `scope`, if one is. pub async fn bookmark_setting(pool: &db::Pool, scope: BookmarkScope) -> sqlx::Result> { Ok(db::accounts::setting(pool, &scope.key()).await?.filter(|v| !v.is_empty())) } /// Set (or, empty, clear) the default bookmark at `scope`. pub async fn set_bookmark_setting(pool: &db::Pool, scope: BookmarkScope, value: &str) -> Result<(), String> { let v = value.trim(); if !v.is_empty() { check_bookmark(v)?; } db::accounts::set_setting(pool, &scope.key(), v).await.map_err(|e| e.to_string()) } /// A bookmark name a repository may default to. pub fn check_bookmark(name: &str) -> Result<(), String> { if crate::repos::names::valid_segment(name) { Ok(()) } else { Err(format!( "{name:?} is not a bookmark name: letters, digits, dots, dashes and underscores, up to 64, starting with a letter or digit." )) } } /// The default bookmark a new repository under `owner` takes, and where /// it comes from (for the page: "develop, from doomsdayone's settings"). pub async fn default_bookmark_for(app: &Shared, owner: &str) -> (String, String) { let own = match db::accounts::org_by_name(&app.db, owner).await.ok().flatten() { Some(org) => Some(BookmarkScope::Org(org.id)), None => db::accounts::account_by_name(&app.db, owner).await.ok().flatten().map(|a| BookmarkScope::Account(a.id)), }; if let Some(scope) = own { if let Ok(Some(b)) = bookmark_setting(&app.db, scope).await { return (b, format!("{owner}'s default")); } } match bookmark_setting(&app.db, BookmarkScope::Site).await { Ok(Some(b)) => (b, "this site's default".into()), _ => (MAIN.into(), "the usual default".into()), } } /// The new repository's default bookmark: the one asked for, or its /// owner's, the site's or `main`; set on its row when it is not `main`. pub async fn set_default_bookmark(app: &Shared, row: db::repos::RepoRow, asked: &str) -> sqlx::Result { let asked = asked.trim(); let b = if asked.is_empty() { default_bookmark_for(app, &row.owner).await.0 } else { asked.to_string() }; if b == row.default_bookmark { return Ok(row); } db::repos::set_default_bookmark(&app.db, row.id, &b).await?; Ok(db::repos::get_by_id(&app.db, row.id).await?.unwrap_or(row)) } /// OxygenFlow for a new repository (#371): left to the site's default, /// on the site's runners (a site administrator's choice), or on the /// owner's own runners. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Flow { Default, On, Own, } impl Flow { pub fn parse(choice: &str) -> Result { match choice.trim() { "" | "default" | "off" => Ok(Flow::Default), "on" => Ok(Flow::On), "own" => Ok(Flow::Own), other => Err(format!("OxygenFlow is on, own or left to the default, not {other}.")), } } /// The repository's `flow` setting, as Settings › Pipelines writes it. pub fn setting(self) -> &'static str { match self { Flow::Default => "", Flow::On => "on", Flow::Own => "own", } } } /// Whether `owner` has runners of its own (not the site's), which /// [`Flow::Own`] needs before its repository exists. pub async fn owner_has_runner(app: &Shared, owner: &str) -> sqlx::Result { Ok(db::runners::serving_owner(&app.db, owner).await?.iter().any(|r| !r.scope().is_site())) } /// Checked before the repository is made, as Settings › Pipelines checks. pub async fn check_flow(app: &Shared, account: &db::accounts::Account, owner: &str, flow: Flow) -> Result<(), String> { match flow { Flow::Default => Ok(()), Flow::On if account.is_admin => Ok(()), Flow::On => Err("Only site administrators let the site's runners take a repository's jobs.".into()), Flow::Own => match owner_has_runner(app, owner).await.map_err(|e| e.to_string())? { true => Ok(()), false => { Err(format!("{owner} has no runners of its own yet: register one, then switch OxygenFlow on in Settings › Pipelines.")) } }, } } /// Switch OxygenFlow on for the new repository, as chosen. pub async fn set_flow(app: &Shared, row: &db::repos::RepoRow, by: &db::accounts::Account, flow: Flow) -> sqlx::Result<()> { if flow == Flow::Default { return Ok(()); } db::repos::set_flow(&app.db, row.id, flow.setting()).await?; db::accounts::audit(&app.db, Some(by), "repo.flow", &format!("{}/{}", row.owner, row.name), flow.setting()).await.ok(); Ok(()) } /// A new wiki's Home page: the repository's name and description. pub fn wiki_home(name: &RepoName, description: &str) -> String { let about = description.trim(); let about = if about.is_empty() { String::new() } else { format!("{about}\n\n") }; format!("# {}\n\n{about}This is the wiki's home page. Edit it, or add pages beside it.\n", name.name) } /// Start the repository's wiki with its Home page, written as `by` and /// signed as their delegate, as a wiki edit on the site is. pub async fn start_wiki(app: &Shared, row: &db::repos::RepoRow, by: &db::accounts::Account, description: &str) -> Result<(), String> { let name = RepoName::new(&row.owner, &row.name).ok_or("bad repository name")?; let signer = crate::web::edit::signer_for(app, by.id).await?; let edit = FileEdit { path: crate::wiki::path_of(crate::wiki::HOME), content: Some(wiki_home(&name, description).into_bytes()) }; crate::wiki::commit(app, &name, vec![edit], "Start the wiki".into(), signer).await.map_err(|e| e.to_string())?; db::accounts::audit(&app.db, Some(by), "wiki.started", &name.to_string(), "Home").await.ok(); Ok(()) } /// The licences offered, with what each allows, for the page. pub const LICENCES: &[(&str, &str)] = &[ ("MIT", "use, change and share it freely, keeping the notice"), ("BSD-2-Clause", "as MIT, in the BSD's words"), ("ISC", "as MIT, in fewer words"), ]; /// The languages an `.oxyignore` is offered for. pub const IGNORES: &[&str] = &["Rust", "Node", "Python", "Go", "Java and Kotlin"]; /// What a new repository starts with: the files, by path. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Start { pub readme: bool, /// One of [`LICENCES`], or empty. pub licence: String, /// One of [`IGNORES`], or empty. pub ignore: String, } impl Start { pub fn is_empty(&self) -> bool { !self.readme && self.licence.is_empty() && self.ignore.is_empty() } /// The files, for a repository `name` described as `description`, /// whose copyright `holder` keeps in `year`. pub fn files(&self, name: &RepoName, description: &str, holder: &str, year: i32) -> Result, String> { let mut out = Vec::new(); if self.readme { let about = if description.trim().is_empty() { String::new() } else { format!("{}\n\n", description.trim()) }; out.push(("README.md".to_string(), format!("# {}\n\n{about}", name.name))); } if !self.licence.is_empty() { let text = licence(&self.licence, holder, year).ok_or(format!("No licence {}.", self.licence))?; out.push(("LICENSE".to_string(), text)); } if !self.ignore.is_empty() { let text = ignore(&self.ignore).ok_or(format!("No .oxyignore for {}.", self.ignore))?; out.push((".oxyignore".to_string(), text.to_string())); } Ok(out) } } fn licence(id: &str, holder: &str, year: i32) -> Option { Some(match id { "MIT" => format!( "MIT License\n\nCopyright (c) {year} {holder}\n\n\ Permission is hereby granted, free of charge, to any person obtaining a copy\n\ of this software and associated documentation files (the \"Software\"), to deal\n\ in the Software without restriction, including without limitation the rights\n\ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ copies of the Software, and to permit persons to whom the Software is\n\ furnished to do so, subject to the following conditions:\n\n\ The above copyright notice and this permission notice shall be included in all\n\ copies or substantial portions of the Software.\n\n\ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\ SOFTWARE.\n" ), "BSD-2-Clause" => format!( "BSD 2-Clause License\n\nCopyright (c) {year}, {holder}\n\n\ Redistribution and use in source and binary forms, with or without\n\ modification, are permitted provided that the following conditions are met:\n\n\ 1. Redistributions of source code must retain the above copyright notice, this\n \ list of conditions and the following disclaimer.\n\n\ 2. Redistributions in binary form must reproduce the above copyright notice,\n \ this list of conditions and the following disclaimer in the documentation\n \ and/or other materials provided with the distribution.\n\n\ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" ), "ISC" => format!( "ISC License\n\nCopyright (c) {year} {holder}\n\n\ Permission to use, copy, modify, and/or distribute this software for any\n\ purpose with or without fee is hereby granted, provided that the above\n\ copyright notice and this permission notice appear in all copies.\n\n\ THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n\ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n\ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n" ), _ => return None, }) } fn ignore(lang: &str) -> Option<&'static str> { Some(match lang { "Rust" => "# Build output\ntarget/\n", "Node" => "# Dependencies and build output\nnode_modules/\ndist/\n*.log\n", "Python" => "# Caches, environments and build output\n__pycache__/\n*.pyc\n.venv/\nbuild/\ndist/\n*.egg-info/\n", "Go" => "# Build output\nbin/\n*.test\n", "Java and Kotlin" => "# Build output and tool state\nbuild/\n.gradle/\nout/\n*.class\n", _ => return None, }) } /// Commit `files` to the new repository's default bookmark as `by`, signed /// as their delegate (as the starter's are); a repository with no files /// yet only. pub async fn commit_start( app: &Shared, row: &db::repos::RepoRow, by: &db::accounts::Account, files: Vec<(String, String)>, ) -> Result<(), String> { if files.is_empty() { return Ok(()); } let name = RepoName::new(&row.owner, &row.name).ok_or("bad repository name")?; let signer = crate::web::edit::signer_for(app, by.id).await?; let paths: Vec = files.iter().map(|(p, _)| p.clone()).collect(); let edits: Vec = files.into_iter().map(|(path, content)| FileEdit { path, content: Some(content.into_bytes()) }).collect(); let b = row.default_bookmark.clone(); crate::repos::edits::commit(&app.repos, &name, b.clone(), b, edits, format!("Start with {}", paths.join(", ")), signer) .await .map_err(|e| e.to_string())?; db::accounts::audit(&app.db, Some(by), "repo.started", &name.to_string(), &paths.join(", ")).await.ok(); Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn boards_and_starting_files() { assert_eq!(Board::parse("", "", "demo").unwrap(), Board::None); assert_eq!(Board::parse("new", " ", "demo").unwrap(), Board::New("demo".into())); assert_eq!(Board::parse("new", "Roadmap", "demo").unwrap(), Board::New("Roadmap".into())); assert_eq!(Board::parse("4", "", "demo").unwrap(), Board::Existing(4)); assert!(Board::parse("four", "", "demo").is_err()); let name = RepoName::new("andy", "demo").unwrap(); let s = Start { readme: true, licence: "MIT".into(), ignore: "Rust".into() }; let files = s.files(&name, "A demo.", "Andy McCall", 2026).unwrap(); let paths: Vec<&str> = files.iter().map(|(p, _)| p.as_str()).collect(); assert_eq!(paths, ["README.md", "LICENSE", ".oxyignore"]); assert_eq!(files[0].1, "# demo\n\nA demo.\n\n"); assert!(files[1].1.starts_with("MIT License\n\nCopyright (c) 2026 Andy McCall\n")); assert_eq!(files[2].1, "# Build output\ntarget/\n"); for (id, _) in LICENCES { assert!(licence(id, "X", 2026).unwrap().contains("2026"), "{id}"); } for lang in IGNORES { assert!(ignore(lang).is_some(), "{lang}"); } assert!(Start { licence: "GPL".into(), ..Default::default() }.files(&name, "", "X", 2026).is_err()); assert!(Start::default().is_empty()); } #[test] fn flow_choices_and_the_wiki_home() { assert_eq!(Flow::parse("").unwrap(), Flow::Default); assert_eq!(Flow::parse("off").unwrap(), Flow::Default); assert_eq!(Flow::parse("on").unwrap().setting(), "on"); assert_eq!(Flow::parse("own").unwrap().setting(), "own"); assert!(Flow::parse("always").is_err()); let name = RepoName::new("andy", "square").unwrap(); assert_eq!( wiki_home(&name, " A platform game. "), "# square\n\nA platform game.\n\nThis is the wiki's home page. Edit it, or add pages beside it.\n" ); assert!(wiki_home(&name, "").starts_with("# square\n\nThis is")); } #[test] fn bookmark_defaults_are_kept_apart() { assert_eq!(BookmarkScope::Site.key(), "default_bookmark"); assert_eq!(BookmarkScope::Account(7).key(), "default_bookmark.account.7"); assert_eq!(BookmarkScope::Org(7).key(), "default_bookmark.org.7"); assert!(check_bookmark("develop").is_ok()); assert!(check_bookmark("release-1.0").is_ok()); assert!(check_bookmark("feature/x").is_err()); assert!(check_bookmark("-x").is_err()); } }