summaryrefslogtreecommitdiff
path: root/src/git_tools.rs
blob: 878cf7b603c1e055f1de0e79738415765da0ee57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use core::panic;

use git2::{Repository, RepositoryInitOptions};

use crate::{cgit_helper::cgit_add_repo, read_config::Config};

pub enum RepoCreateError {
    Ownership,
    Path,
    RepoNameParse,
    Internal,
}

fn fmt_repo_name_dotgit(raw_name: &str) -> Result<(String, String), RepoCreateError> {
    if raw_name.ends_with(".git") {
        let no_suffix_name = &raw_name.to_string()[..raw_name.chars().count() - 4];
        Ok((no_suffix_name.to_string(), raw_name.to_string()))
    } else {
        Ok((raw_name.to_string(), raw_name.to_string() + ".git"))
    }
}
fn check_owner_against_config(_owner: &str) -> bool {
    true
    /* TODO
     * Check owner against configuration
     * to see if authenticated for managing git repos
     */
}
pub fn make_repo(
    raw_repo_name: &str,
    owner_text: &str,
    section: &str,
    description: &str,
    config: Config,
) -> Result<Repository, RepoCreateError> {
    if !(check_owner_against_config(owner_text)) {
        return Err(RepoCreateError::Ownership);
    }
    let repo_name: Result<(String, String), RepoCreateError> = fmt_repo_name_dotgit(raw_repo_name);
    let (no_suffix, with_suffix) = repo_name.unwrap_or_else(|error| {
        if let RepoCreateError::RepoNameParse = error {
            panic!("RepoNameParseError");
        } else {
            panic!("Unknown error");
        }
    });
    let git_repo_path: String = config.git_host_dir_path + "/" + &with_suffix;

    let mut options = RepositoryInitOptions::new();
    options.no_reinit(true).bare(true);
    let repo = match Repository::init_opts(&git_repo_path, &options) {
        Ok(repo) => {
            println!("Successfully init repository at {}", git_repo_path);
            repo
        }
        Err(_e) => {
            return Err(RepoCreateError::Internal);
        }
    };
    /* TODO
     * We want to change the config file to append http.receivepack = true
     * */
    cgit_add_repo(
        config.cgitrepos_file_path,
        crate::cgit_helper::CGitRepoInfo {
            section: String::from(section),
            url: no_suffix,
            path: git_repo_path,
            owner: owner_text.to_string(),
            description: description.to_string(),
        },
    );
    Ok(repo)
}