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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
use std::env::current_dir;
use std::ffi::OsStr;
use std::fmt;
use std::io::{self, BufRead, BufReader};
use std::path::PathBuf;
use std::process::{Command, Stdio};

#[derive(Debug, Clone)]
pub struct Git {
    cwd: PathBuf,
    repo_root: PathBuf,
}

#[derive(Debug, Clone)]
pub struct GitStatus(pub Vec<GitStatusItem>);

#[derive(Debug, Clone)]
pub struct GitStatusItem {
    file: String,
    staged: Option<GitStatusType>,
    unstaged: Option<GitStatusType>,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum GitStatusType {
    Added,
    Modified,
    Untracked,
    Deleted,
}

#[derive(Debug)]
pub enum GitError {
    NotGitRepo,
    Io(io::Error),
}

impl Git {
    pub fn from_cwd() -> Result<Self, GitError> {
        let cwd = current_dir().map_err(GitError::Io)?;

        let mut repo_root = None;

        for dir in cwd.ancestors() {
            if dir.join(".git").is_dir() {
                repo_root = Some(dir.into());

                break;
            }
        }

        match repo_root {
            Some(repo_root) => Ok(Git { cwd, repo_root }),
            None => Err(GitError::NotGitRepo),
        }
    }

    pub fn commit<I>(&self, message: &str, other_args: impl IntoIterator<Item = I>) -> Command
    where
        I: AsRef<OsStr>,
    {
        let mut command = Command::new("git");

        // Setup
        command.current_dir(&self.cwd);
        command.stdin(Stdio::null());

        // Args
        command.arg("commit");
        command.arg("-m");
        command.arg(message);
        for arg in other_args {
            command.arg(arg);
        }

        command
    }

    /// Stages files using `git add`. Run from the repo root.gs
    pub fn add<I>(&self, files: impl IntoIterator<Item = I>) -> Command
    where
        I: AsRef<OsStr>,
    {
        let mut command = Command::new("git");

        // Setup
        command.current_dir(&self.repo_root);
        command.stdin(Stdio::null());

        // Args
        command.arg("add");
        command.arg("--");

        for file in files {
            command.arg(file.as_ref());
        }

        command
    }

    pub fn diff_less<I>(&self, files: impl IntoIterator<Item = I>) -> io::Result<()>
    where
        I: AsRef<OsStr>,
    {
        let diff = Command::new("git")
            .current_dir(&self.repo_root)
            .arg("diff")
            .arg("--color=always")
            .arg("--")
            .args(files.into_iter())
            .stdout(Stdio::piped())
            .spawn()?;

        Command::new("less")
            .arg("-R")
            .current_dir(&self.repo_root)
            .stdin(diff.stdout.ok_or_else(|| {
                io::Error::new(io::ErrorKind::Other, "failed to get stdout of git diff")
            })?)
            .status()?;

        Ok(())
    }

    pub fn status(&self) -> io::Result<GitStatus> {
        let mut command = Command::new("git");

        // Setup
        command.current_dir(&self.cwd);
        command.stdout(Stdio::piped());

        // Args
        command.arg("status");
        command.arg("--porcelain");

        let stdout = command.spawn()?.stdout.ok_or_else(|| {
            io::Error::new(io::ErrorKind::Other, "Could not capture standard output.")
        })?;

        let items = BufReader::new(stdout)
            .lines()
            .filter_map(|line| line.ok())
            .filter_map(|line| {
                let mut chars = line.chars();
                let staged = chars
                    .next()
                    .and_then(GitStatusType::from_char)
                    .filter(|item| match item {
                        GitStatusType::Untracked => false,
                        _ => true,
                    });
                let unstaged = chars.next().and_then(GitStatusType::from_char);

                chars.next();
                let file: String = chars.collect();

                if file.is_empty() {
                    None
                } else {
                    Some(GitStatusItem {
                        file,
                        staged,
                        unstaged,
                    })
                }
            })
            .collect();

        Ok(GitStatus(items))
    }
}
impl GitStatus {
    pub fn iter(&self) -> impl Iterator<Item = &GitStatusItem> {
        self.0.iter()
    }

    pub fn any_staged(&self) -> bool {
        self.iter().any(|item| item.staged.is_some())
    }

    pub fn any_unstaged(&self) -> bool {
        self.iter().any(|item| item.unstaged.is_some())
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }
}

impl GitStatusItem {
    pub fn file(&self) -> &str {
        &self.file
    }
}

impl Into<String> for GitStatusItem {
    fn into(self) -> String {
        (&self).into()
    }
}

impl Into<String> for &'_ GitStatusItem {
    fn into(self) -> String {
        self.file().into()
    }
}

impl GitStatusType {
    pub fn from_char(ch: char) -> Option<Self> {
        match ch {
            'A' => Some(GitStatusType::Added),
            'M' => Some(GitStatusType::Modified),
            'D' => Some(GitStatusType::Deleted),
            '?' => Some(GitStatusType::Untracked),
            _ => None,
        }
    }
}

impl fmt::Display for GitError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GitError::NotGitRepo => write!(f, "This directory is not a git repository."),
            GitError::Io(err) => write!(f, "Internal I/O error: {}", err),
        }
    }
}