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
pub mod store;
use crate::command;
use crate::os;
use anyhow::Result;
pub use git2::BranchType;
use git2::{Commit, Config, Error, Oid, Repository, Signature};
use std::env;
use std::path::PathBuf;
pub use store::Store;

pub trait Git {
    fn run(&self, args: &[&str]) -> Result<()>;
    fn tree_is_clean(&self) -> Result<bool>;
    fn has_branch(&self, branch: &str) -> Result<bool>;
    fn current_branch(&self) -> Result<Option<String>>;
    fn dirty_files(&self) -> Result<String>;
}

#[derive(Debug)]
pub struct CommitFile<'a> {
    pub filename: &'a str,
    pub data: &'a [u8],
    pub message: &'a str,
    pub reference: &'a str,
}

pub struct GitCommand<'repo> {
    command: command::Command<'repo>,
    repo: Repository,
    pub remote: String,
}

impl<'repo> GitCommand<'repo> {
    pub fn new(path: Option<PathBuf>, remote: String) -> Result<GitCommand<'repo>> {
        let path = path.unwrap_or(env::current_dir()?);
        let repo = Repository::open(&path)?;
        let command = command::Command::new(os::command("git")).working_directory(path.as_path());
        Ok(Self {
            command,
            repo,
            remote,
        })
    }

    pub fn from_repo(repo: Repository) -> Self {
        let workdir = repo.workdir().expect("Repo does not have a workdir");
        let command = command::Command::new(os::command("git")).working_directory(workdir);
        Self {
            command,
            repo,
            remote: "origin".into(),
        }
    }

    fn last_commit(&self, reference: &str) -> Option<Commit> {
        let absolute_ref = format!("refs/heads/{}", reference);

        self.repo
            .find_reference(absolute_ref.as_str())
            .and_then(|reference| reference.resolve())
            .and_then(|reference| {
                self.repo
                    .find_commit(reference.target().unwrap_or_else(Oid::zero))
            })
            .ok()
    }

    fn get_signature() -> Result<Signature<'static>, Error> {
        let config = Config::open_default()?;
        let name = config.get_string("user.name")?;
        let email = config.get_string("user.email")?;
        Signature::now(name.as_str(), email.as_str())
    }

    pub fn create_commit(&self, commit: &CommitFile) -> Result<git2::Oid, Error> {
        let oid = self.repo.blob(commit.data)?;

        let mut tree = self.repo.treebuilder(None)?;
        tree.insert(commit.filename, oid, 0o100_644)?;
        let tree = tree.write()?;
        let tree = self.repo.find_tree(tree)?;

        let parent = self.last_commit(commit.reference);
        let parent = match parent {
            Some(ref commit) => vec![commit],
            None => vec![],
        };

        let signature = GitCommand::get_signature()?;

        let absolute_ref = format!("refs/heads/{}", commit.reference);
        self.repo.commit(
            Some(absolute_ref.as_str()),
            &signature,
            &signature,
            commit.message,
            &tree,
            parent.as_slice(),
        )
    }

    fn find_branch(&self, name: &str) -> Result<Option<git2::Branch>> {
        let branches = self.repo.branches(None)?;

        for branch_result in branches {
            let branch = branch_result?.0;

            if let Ok(Some(branch_name)) = branch.name() {
                if branch_name == name {
                    return Ok(Some(branch));
                }
            }
        }
        Ok(None)
    }

    fn run_quietly(&self, args: &[&str]) -> Result<()> {
        log::trace!("running git {}", args.join(" "));
        self.command.run_checked(args)
    }
}

impl<'repo> Git for GitCommand<'repo> {
    fn run(&self, args: &[&str]) -> Result<()> {
        log::debug!("git {}", args.join(" "));
        self.command.run_checked(args)
    }

    fn tree_is_clean(&self) -> Result<bool> {
        self.dirty_files().map(|output| output.trim().is_empty())
    }

    fn has_branch(&self, branch: &str) -> Result<bool> {
        match self.find_branch(branch)? {
            Some(_) => Ok(true),
            None => Ok(false),
        }
    }

    fn current_branch(&self) -> Result<Option<String>> {
        return Ok(self.repo.head()?.shorthand().map(String::from));
    }

    fn dirty_files(&self) -> Result<String> {
        self.command.run_stdout(&["status", "--short"])
    }
}