//! 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. 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)) } /// 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()); } }