summaryrefslogtreecommitdiff
path: root/src/git.rs
blob: ac92908f600ee927f76cbdd8c8c8f9159c4a3554 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
use crate::{
    parser::{GitReceivePackArgs, GitUploadPackArgs},
    ShackleError,
};
use git2::{Repository, RepositoryInitMode, RepositoryInitOptions};
use std::{fs, path::PathBuf, process::Command};
use user_info::{get_user_groups, get_username};

pub struct GitInitResult {
    pub path: PathBuf,
}

fn git_dir_prefix() -> PathBuf {
    PathBuf::from("git")
}

fn personal_git_dir() -> Result<PathBuf, ShackleError> {
    let username = get_username().ok_or(ShackleError::UserReadError)?;
    Ok(git_dir_prefix().join(username))
}

fn group_git_dir(group: &str) -> Result<PathBuf, ShackleError> {
    let groups = get_user_groups();
    if !groups.iter().any(|g| g == group) {
        Err(ShackleError::InvalidGroup)
    } else {
        Ok(git_dir_prefix().join(group))
    }
}

fn is_valid_git_repo_path(path: &PathBuf) -> Result<bool, ShackleError> {
    let prefix = git_dir_prefix();
    let relative_path = match path.strip_prefix(&prefix) {
        Ok(relative_path) => relative_path,
        Err(_) => {
            return Ok(false);
        }
    };

    let mut it = relative_path.iter();
    let group = it.next();
    let repo_name = it.next();
    let end = it.next();

    match (group, repo_name, end) {
        (_, _, Some(_)) | (None, _, _) | (_, None, _) => Ok(false),
        (Some(group_name), Some(_repo_name), _) => {
            if relative_path.extension().map(|ext| ext == "git") != Some(true) {
                Ok(false)
            } else {
                let group_name = group_name.to_string_lossy();

                let user_name = get_username();
                let is_valid_personal_repo_path = user_name
                    .map(|user_name| user_name == group_name)
                    .unwrap_or(false);

                let user_groups = get_user_groups();
                let is_valid_shared_repo_path =
                    user_groups.iter().any(|group| group.as_ref() == group_name);

                Ok(is_valid_personal_repo_path || is_valid_shared_repo_path)
            }
        }
    }
}

pub fn init(repo_name: &str, group: &Option<String>) -> Result<GitInitResult, ShackleError> {
    fn init_group(repo_name: &str, group: &str) -> Result<GitInitResult, ShackleError> {
        let path = group_git_dir(group)?.join(repo_name).with_extension("git");

        Repository::init_opts(
            &path,
            &RepositoryInitOptions::new()
                .bare(true)
                .mode(RepositoryInitMode::SHARED_GROUP)
                .mkdir(true)
                .no_reinit(true),
        )?;
        Ok(GitInitResult { path })
    }

    fn init_personal(repo_name: &str) -> Result<GitInitResult, ShackleError> {
        let path = personal_git_dir()?.join(repo_name).with_extension("git");

        Repository::init_opts(
            &path,
            &RepositoryInitOptions::new()
                .bare(true)
                .mkdir(true)
                .no_reinit(true),
        )?;
        Ok(GitInitResult { path })
    }

    match group {
        Some(group) => init_group(repo_name, group),
        None => init_personal(repo_name),
    }
}

pub struct RepoMetadata {
    pub path: PathBuf,
    pub description: String,
}

pub fn list() -> Result<Vec<RepoMetadata>, ShackleError> {
    fn add_from_dir(
        collection_dir: &PathBuf,
        is_checking_group: bool,
    ) -> Result<Vec<RepoMetadata>, ShackleError> {
        let mut results = Vec::new();
        if !collection_dir.is_dir() {
            return Ok(results);
        }

        for dir in collection_dir.read_dir()? {
            let path = dir?.path();
            let description_path = path.join("description");
            let has_git_ext = path.extension().map_or(false, |ext| ext == "git");

            if has_git_ext {
                if let Ok(repo) = Repository::open_bare(&path) {
                    let config = repo.config()?.snapshot()?;
                    let shared_config = config.get_str("core.sharedRepository").ok(); // TODO: Could shis fail for other reasons?
                    let is_group_shared =
                        [Some("group"), Some("1"), Some("true")].contains(&shared_config);

                    if is_group_shared == is_checking_group {
                        let description = if description_path.is_file() {
                            fs::read_to_string(description_path)?
                        } else {
                            String::new()
                        };

                        results.push(RepoMetadata { path, description });
                    }
                }
            }
        }
        Ok(results)
    }

    let mut results = Vec::new();

    results.append(&mut add_from_dir(&personal_git_dir()?, false)?);

    // TODO: Do the same (more or less) for group repos

    Ok(results)
}

pub fn upload_pack(upload_pack_args: &GitUploadPackArgs) -> Result<(), ShackleError> {
    if !is_valid_git_repo_path(&upload_pack_args.directory)? {
        return Err(ShackleError::InvalidDirectory);
    }

    let mut command = Command::new("git-upload-pack");
    if upload_pack_args.strict {
        command.arg("strict");
    }
    if upload_pack_args.no_strict {
        command.arg("no-strict");
    }
    if let Some(timeout) = upload_pack_args.timeout {
        command.args(["timeout", &timeout.to_string()]);
    }
    if upload_pack_args.stateless_rpc {
        command.arg("stateless-rpc");
    }
    if upload_pack_args.advertise_refs {
        command.arg("advertise-refs");
    }
    command.arg(&upload_pack_args.directory);

    command.spawn()?.wait()?;
    Ok(())
}

pub fn receive_pack(receive_pack_args: &GitReceivePackArgs) -> Result<(), ShackleError> {
    if !is_valid_git_repo_path(&receive_pack_args.directory)? {
        return Err(ShackleError::InvalidDirectory);
    }

    let mut command = Command::new("git-receive-pack");
    if receive_pack_args.http_backend_info_refs {
        command.arg("--http-backend-info-refs");
    }
    command.arg(&receive_pack_args.directory);

    command.spawn()?.wait()?;
    Ok(())
}