OXYGENHUB

Coverage / crates/hub/src/repo_setup.rs 80.3%

110 of 137 lines run, 18 of 46 functions · run #543 on main · run missed

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
6
//! and proposals as they open.
7
8
use crate::auth::roles;
9
use crate::db::{self, projects as pdb};
10
use crate::repos::RepoName;
11
use crate::Shared;
12
use oxy_core::repo::FileEdit;
13
14
/// Whether `owner/name` may be made by `account`: `Ok` with its address,
15
/// or why not, said as the page and the API say it.
1629×
pub async fn check_name(app: &Shared, account: &db::accounts::Account, owner: &str, name: &str) -> Result<RepoName, String> {
1729×
    let Some(n) = RepoName::new(owner.trim(), name.trim()) else {
182×
        return Err("A repository name is letters, digits, dots, dashes and underscores, up to 64.".into());
19
    };
2027×
    if n.name.ends_with(crate::wiki::SUFFIX) {
211×
        return Err("A name cannot end in .wiki: that is the address of a repository's wiki.".into());
2226×
    }
2326×
    if !roles::may_create_under(&app.db, account, &n.owner).await.map_err(|e| e.to_string())? {
240×
        return Err(format!("You cannot create repositories under {}.", n.owner));
2526×
    }
2626×
    if db::repos::get(&app.db, &n.owner, &n.name).await.map_err(|e| e.to_string())?.is_some() || app.repos.exists(&n) {
271×
        return Err(format!("{n} exists."));
2825×
    }
2925×
    Ok(n)
3029×
}
31
32
/// A board for a new repository: none, a new one under its owner with this
33
/// title, or the owner's board of this number.
34
#[derive(Clone, Debug, PartialEq, Eq)]
35
pub enum Board {
36
    None,
37
    New(String),
38
    Existing(i64),
39
}
40
41
impl Board {
42
    /// The form's or the API's choice: `new` with a title (the
43
    /// repository's name when empty), a board number, or nothing.
4429×
    pub fn parse(choice: &str, title: &str, repo: &str) -> Result<Board, String> {
4529×
        match choice.trim() {
4629×
            "" | "none" => Ok(Board::None),
475×
            "new" => {
483×
                let t: String = title.trim().chars().take(100).collect();
493×
                Ok(Board::New(if t.is_empty() { repo.to_string() } else { t }))
50
            }
512×
            n => n.parse().map(Board::Existing).map_err(|_| format!("No board {n}.")),
52
        }
5329×
    }
54
}
55
56
/// Checked before the repository is made: a chosen board must be the
57
/// owner's, open, and one `account` may change.
5838×
pub async fn check_board(app: &Shared, account: &db::accounts::Account, owner: &str, board: &Board) -> Result<(), String> {
5938×
    match board {
6034×
        Board::None => Ok(()),
612×
        Board::New(_) => match crate::web::projects::rights_of(app, Some(account), owner).await.map_err(|e| e.to_string())? {
622×
            Some(r) if r.edit => Ok(()),
630×
            _ => Err(format!("You cannot make boards under {owner}.")),
64
        },
652×
        Board::Existing(n) => {
662×
            let p = pdb::get(&app.db, owner, *n).await.map_err(|e| e.to_string())?.ok_or(format!("{owner} has no board {n}."))?;
671×
            if p.closed {
680×
                return Err(format!("Board {n} is closed."));
691×
            }
701×
            match crate::web::projects::rights_of(app, Some(account), owner).await.map_err(|e| e.to_string())? {
711×
                Some(r) if r.edit => Ok(()),
720×
                _ => Err(format!("You cannot change {owner}'s boards.")),
73
            }
74
        }
75
    }
7638×
}
77
78
/// Make or find the board and link it to the repository; its number.
7927×
pub async fn link_board(app: &Shared, row: &db::repos::RepoRow, board: &Board, public: bool) -> sqlx::Result<Option<i64>> {
8027×
    let p = match board {
8124×
        Board::None => return Ok(None),
822×
        Board::New(title) => pdb::create(&app.db, &row.owner, title, &format!("Work on {}/{}", row.owner, row.name), public).await?,
831×
        Board::Existing(n) => match pdb::get(&app.db, &row.owner, *n).await? {
841×
            Some(p) => p,
850×
            None => return Ok(None),
86
        },
87
    };
883×
    pdb::link_repo(&app.db, p.id, row.id).await?;
893×
    Ok(Some(p.number))
9027×
}
91
92
/// The licences offered, with what each allows, for the page.
93
pub const LICENCES: &[(&str, &str)] = &[
94
    ("MIT", "use, change and share it freely, keeping the notice"),
95
    ("BSD-2-Clause", "as MIT, in the BSD's words"),
96
    ("ISC", "as MIT, in fewer words"),
97
];
98
99
/// The languages an `.oxyignore` is offered for.
100
pub const IGNORES: &[&str] = &["Rust", "Node", "Python", "Go", "Java and Kotlin"];
101
102
/// What a new repository starts with: the files, by path.
103
#[derive(Clone, Debug, Default, PartialEq, Eq)]
104
pub struct Start {
105
    pub readme: bool,
106
    /// One of [`LICENCES`], or empty.
107
    pub licence: String,
108
    /// One of [`IGNORES`], or empty.
109
    pub ignore: String,
110
}
111
112
impl Start {
1131×
    pub fn is_empty(&self) -> bool {
1141×
        !self.readme && self.licence.is_empty() && self.ignore.is_empty()
1151×
    }
116
117
    /// The files, for a repository `name` described as `description`,
118
    /// whose copyright `holder` keeps in `year`.
11939×
    pub fn files(&self, name: &RepoName, description: &str, holder: &str, year: i32) -> Result<Vec<(String, String)>, String> {
12039×
        let mut out = Vec::new();
12139×
        if self.readme {
1223×
            let about = if description.trim().is_empty() { String::new() } else { format!("{}\n\n", description.trim()) };
1233×
            out.push(("README.md".to_string(), format!("# {}\n\n{about}", name.name)));
12436×
        }
12539×
        if !self.licence.is_empty() {
1262×
            let text = licence(&self.licence, holder, year).ok_or(format!("No licence {}.", self.licence))?;
1271×
            out.push(("LICENSE".to_string(), text));
12837×
        }
12938×
        if !self.ignore.is_empty() {
1301×
            let text = ignore(&self.ignore).ok_or(format!("No .oxyignore for {}.", self.ignore))?;
1311×
            out.push((".oxyignore".to_string(), text.to_string()));
13237×
        }
13338×
        Ok(out)
13439×
    }
135
}
136
1375×
fn licence(id: &str, holder: &str, year: i32) -> Option<String> {
1385×
    Some(match id {
1395×
        "MIT" => format!(
140
            "MIT License\n\nCopyright (c) {year} {holder}\n\n\
141
Permission is hereby granted, free of charge, to any person obtaining a copy\n\
142
of this software and associated documentation files (the \"Software\"), to deal\n\
143
in the Software without restriction, including without limitation the rights\n\
144
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\
145
copies of the Software, and to permit persons to whom the Software is\n\
146
furnished to do so, subject to the following conditions:\n\n\
147
The above copyright notice and this permission notice shall be included in all\n\
148
copies or substantial portions of the Software.\n\n\
149
THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\
150
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\
151
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\
152
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\
153
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\
154
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\
155
SOFTWARE.\n"
156
        ),
1573×
        "BSD-2-Clause" => format!(
158
            "BSD 2-Clause License\n\nCopyright (c) {year}, {holder}\n\n\
159
Redistribution and use in source and binary forms, with or without\n\
160
modification, are permitted provided that the following conditions are met:\n\n\
161
1. Redistributions of source code must retain the above copyright notice, this\n   \
162
list of conditions and the following disclaimer.\n\n\
163
2. Redistributions in binary form must reproduce the above copyright notice,\n   \
164
this list of conditions and the following disclaimer in the documentation\n   \
165
and/or other materials provided with the distribution.\n\n\
166
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\
167
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\
168
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\
169
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\
170
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\
171
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\
172
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\
173
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\
174
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\
175
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
176
        ),
1772×
        "ISC" => format!(
178
            "ISC License\n\nCopyright (c) {year} {holder}\n\n\
179
Permission to use, copy, modify, and/or distribute this software for any\n\
180
purpose with or without fee is hereby granted, provided that the above\n\
181
copyright notice and this permission notice appear in all copies.\n\n\
182
THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\
183
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\
184
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n\
185
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\
186
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\
187
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n\
188
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n"
189
        ),
1901×
        _ => return None,
191
    })
1925×
}
193
1946×
fn ignore(lang: &str) -> Option<&'static str> {
1956×
    Some(match lang {
1966×
        "Rust" => "# Build output\ntarget/\n",
1974×
        "Node" => "# Dependencies and build output\nnode_modules/\ndist/\n*.log\n",
1983×
        "Python" => "# Caches, environments and build output\n__pycache__/\n*.pyc\n.venv/\nbuild/\ndist/\n*.egg-info/\n",
1992×
        "Go" => "# Build output\nbin/\n*.test\n",
2001×
        "Java and Kotlin" => "# Build output and tool state\nbuild/\n.gradle/\nout/\n*.class\n",
2010×
        _ => return None,
202
    })
2036×
}
204
205
/// Commit `files` to the new repository's default bookmark as `by`, signed
206
/// as their delegate (as the starter's are); a repository with no files
207
/// yet only.
20827×
pub async fn commit_start(
20927×
    app: &Shared,
21027×
    row: &db::repos::RepoRow,
21127×
    by: &db::accounts::Account,
21227×
    files: Vec<(String, String)>,
21327×
) -> Result<(), String> {
21427×
    if files.is_empty() {
21527×
        return Ok(());
2160×
    }
2170×
    let name = RepoName::new(&row.owner, &row.name).ok_or("bad repository name")?;
2180×
    let signer = crate::web::edit::signer_for(app, by.id).await?;
2190×
    let paths: Vec<String> = files.iter().map(|(p, _)| p.clone()).collect();
2200×
    let edits: Vec<FileEdit> = files.into_iter().map(|(path, content)| FileEdit { path, content: Some(content.into_bytes()) }).collect();
2210×
    let b = row.default_bookmark.clone();
2220×
    crate::repos::edits::commit(&app.repos, &name, b.clone(), b, edits, format!("Start with {}", paths.join(", ")), signer)
2230×
        .await
2240×
        .map_err(|e| e.to_string())?;
2250×
    db::accounts::audit(&app.db, Some(by), "repo.started", &name.to_string(), &paths.join(", ")).await.ok();
2260×
    Ok(())
22727×
}
228
229
#[cfg(test)]
230
mod tests {
231
    use super::*;
232
233
    #[test]
2341×
    fn boards_and_starting_files() {
2351×
        assert_eq!(Board::parse("", "", "demo").unwrap(), Board::None);
2361×
        assert_eq!(Board::parse("new", " ", "demo").unwrap(), Board::New("demo".into()));
2371×
        assert_eq!(Board::parse("new", "Roadmap", "demo").unwrap(), Board::New("Roadmap".into()));
2381×
        assert_eq!(Board::parse("4", "", "demo").unwrap(), Board::Existing(4));
2391×
        assert!(Board::parse("four", "", "demo").is_err());
2401×
        let name = RepoName::new("andy", "demo").unwrap();
2411×
        let s = Start { readme: true, licence: "MIT".into(), ignore: "Rust".into() };
2421×
        let files = s.files(&name, "A demo.", "Andy McCall", 2026).unwrap();
2433×
        let paths: Vec<&str> = files.iter().map(|(p, _)| p.as_str()).collect();
2441×
        assert_eq!(paths, ["README.md", "LICENSE", ".oxyignore"]);
2451×
        assert_eq!(files[0].1, "# demo\n\nA demo.\n\n");
2461×
        assert!(files[1].1.starts_with("MIT License\n\nCopyright (c) 2026 Andy McCall\n"));
2471×
        assert_eq!(files[2].1, "# Build output\ntarget/\n");
2483×
        for (id, _) in LICENCES {
2493×
            assert!(licence(id, "X", 2026).unwrap().contains("2026"), "{id}");
250
        }
2515×
        for lang in IGNORES {
2525×
            assert!(ignore(lang).is_some(), "{lang}");
253
        }
2541×
        assert!(Start { licence: "GPL".into(), ..Default::default() }.files(&name, "", "X", 2026).is_err());
2551×
        assert!(Start::default().is_empty());
2561×
    }
257
}