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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
//! MHgit is a simple git library for interracting with git repositories.
//! 
//! Interraction with git repositories are done through [`Repository`] objects.
//! 
//! Simple git commands can be run with the repository methods. For more 
//! complex commands, or to set command options before running, several 
//! _Options_ types are provided.
//! 
//! ```rust,no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use mhgit::{Repository, CommandOptions};
//! use mhgit::commands::AddOptions;
//! 
//! let repo = Repository::new();
//! AddOptions::new()
//!            .all(true)
//!            .run(&repo)?;
//! # Ok(())
//! # }
//! ```
//! 
//! Creating repository
//! -------------------
//! 
//! ```rust,no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use mhgit::Repository;
//! Repository::at("/home/mh/awesomeness")?
//!            .init()?
//!            .add()?
//!            .commit("Initial commit")?;
//! # Ok(())
//! # }
//! ```
//! 
//! [`Repository`]: struct.Repository.html

// Copyright 2020 Magnus Aa. Hirth. All rights reserved.

#![allow(unused_imports, unused_variables, dead_code)]

#[macro_use]
extern crate failure;

use failure::{Fail, ResultExt};
use std::convert::TryFrom;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{self, Command, Stdio, Output};

mod status;
pub mod commands;

pub use status::Status;

type Result<T> = std::result::Result<T, failure::Error>;

/// Git errors are returned when a git command fails.
#[derive(Fail, Debug)]
pub struct GitError {
    cmd: String,
    code: Option<i32>,
    #[cause] stderr: failure::Error,
}

impl fmt::Display for GitError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(code) = self.code {
            write!(f, "{} returned error code {}", self.cmd, code)
        } else {
            write!(f, "{} was stopped...", self.cmd)
        }
    }
}

/// GitOut indicates if git output should be piped or printed.
#[derive(Debug, PartialEq, Eq, Hash)]
pub enum GitOut {
    Print,
    Pipe,
}

impl Default for GitOut {
    fn default() -> Self {
        GitOut::Pipe
    }
}

/// A handle to a git repository.
/// 
/// By creating with [`at`] the repository may be somewhere other than in
/// current working directory. 
/// 
/// ```rust,no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use mhgit::Repository;
/// Repository::at("/home/mh/awesomeness")?
///            .init()?
///            .add()?
///            .commit("Initial commit")?;
/// # Ok(())
/// # }
/// ```
/// 
/// [`at`]: struct.Repository.html#method.at
#[derive(Debug, Default, PartialEq, Eq, Hash)]
pub struct Repository {
    // Location of repository.
    location: Option<PathBuf>,
    stdout: GitOut,
}

/// Trait implemented by all command option struct ([`CommitOptions`], [`PushOptions`], etc.)
/// 
/// [`CommitOptions`]: commands/struct.CommitOptions.html
/// [`PushOptions`]: commands/struct.PushOptions.html
pub trait CommandOptions {
    type Output;

    /// Return a vector of the arguments passed to git. 
    /// 
    /// The vector contains at least one element, which is the name of the subcommand.
    fn git_args(&self) -> Vec<&str>;

    /// Parse the captured stdout into an appropriate rust type.
    fn parse_output(&self, out: &str) -> Result<Self::Output>;

    /// Run the command in the given git repository. Calling git and parsing
    /// and return the output of the command, if any.
    /// 
    /// If the git command returns error a GitError is returned.
    /// 
    /// ```rust,no_run
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use mhgit::{Repository, CommandOptions};
    /// use mhgit::commands::AddOptions;
    /// let repo = Repository::new();
    /// let _ = AddOptions::new()
    ///                    .all(true)
    ///                    .run(&repo)?;
    /// # Ok(())
    /// # }
    /// ```
    /// 
    fn run(&self, repo: &Repository) -> Result<Self::Output> {
        let args = self.git_args();
        let out = repo.run(args)?;
        self.parse_output(&out)
    }
}

impl Repository {

    /// Get a repository in the current directory.
    /// 
    /// ```rust,no_run
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use mhgit::Repository;
    /// let status = Repository::new()
    ///                         .status()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new() -> Repository {
        // TODO: check if git is installed on the system
        Repository {
            ..Default::default()
        }
    }

    /// Get a repository at the given location.
    /// 
    /// ```rust,no_run
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use mhgit::Repository;
    /// Repository::at("/home/mh/awesomeness")?
    ///            .init()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn at<P: AsRef<Path>>(path: P) -> Result<Repository> {
        Ok(Repository {
            location: Some(
                fs::canonicalize(path).context("failed to canonicalize repository path")?,
            ),
            ..Default::default()
        })
    }

    /// Return true if the repository is initialized.
    pub fn is_init(&self) -> bool {
        let git_dir = match &self.location {
            Some(loc) => loc.join(".git"),
            None      => PathBuf::from("./.git"),
        };
        git_dir.exists() && git_dir.is_dir()
    }

    /// Configure if the output of git commands run in this repo should be
    /// piped or printed to screen. 
    /// 
    /// Piping is default. 
    /// 
    /// ```rust,no_run
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use mhgit::Repository;
    /// use mhgit::GitOut::Print;
    /// Repository::new()
    ///     .gitout(Print)
    ///     .status()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn gitout(&mut self, val: GitOut) -> &mut Repository {
        self.stdout = val;
        self
    }

    /// Run `git add` in the repository.
    /// 
    /// The command is called with the --all option. To call `git add` with
    /// different options use [`AddOptions`].
    /// 
    /// [`AddOptions`]: commands/struct.AddOptions.html
    pub fn add(&mut self) -> Result<&mut Self> {
        let args = vec!["add", "--all"];
        self.run(args)?;
        Ok(self)
    }

    /// Run `git commit` in the repository, with the given commit message.
    /// 
    /// The command is called with --allow-empty, avoiding errors if no changes
    /// were added since last commit. To call `git commit` with different
    /// options use [`CommitOptions`].
    /// 
    /// [`CommitOptions`]: commands/struct.CommitOptions.html
    pub fn commit(&mut self, msg: &str) -> Result<&mut Self> {
        let args = vec!["commit", "-m", msg, "-q", "--allow-empty"];
        self.run(args)?;
        Ok(self)
    }

    /// Run `git fetch` in the repository.
    /// 
    /// The command is called with --all
    pub fn fetch(&mut self) -> Result<&mut Self> {
        let args = vec!["fetch", "--all", "-q"];
        self.run(args)?;
        Ok(self)
    }

    /// Run `git init`, initializing the repository.
    pub fn init(&mut self) -> Result<&mut Self> {
        // Create the directory if it doesn't already exist
        if let Some(loc) = &self.location {
            if !loc.exists() {
                fs::create_dir_all(loc)?;
            }
        }
        let args = vec!["init", "-q"];
        self.run(args)?;
        Ok(self)
    }

    /// Run `git notes add`, adding a note to HEAD.
    /// 
    /// To call `git notes` with different optinos use [`NotesOptions`].
    /// 
    /// [`NotesOptions`]: commands/struct.NotesOptions.html
    pub fn notes(&mut self, msg: &str) -> Result<&mut Self> {
        let args = vec!["notes", "add", "-m", msg];
        self.run(args)?;
        Ok(self)
    }

    /// Run `git pull` without specifying remote or refs.
    /// 
    /// To call `git pull` with different options use [`PullOptions`].
    /// 
    /// [`PullOptions`]: commands/struct.PullOptions.html
    pub fn pull(&mut self) -> Result<&mut Self> {
        let args = vec!["pull", "-q"];
        self.run(args)?;
        Ok(self)
    }

    /// Run `git push` without specifying remote or refs.
    /// 
    /// To call `git push` with different options use [`PushOptions`].
    /// 
    /// [`PushOptions`]: commands/struct.PushOptions.html
    pub fn push(&mut self) -> Result<&mut Self> {
        let args = vec!["push", "-q"];
        self.run(args)?;
        Ok(self)
    }

    /// Run `git remote add` in the repository.
    /// 
    /// This adds a single remote to the repository. To call `git remote`
    /// with different options use [`RemoteOptions`].
    /// 
    /// [`RemoteOptions`]: commands/struct.RemoteOptions.html
    pub fn remote(&mut self, name: &str, url: &str) -> Result<&mut Self> {
        let args = vec!["remote", "add", name, url];
        self.run(args)?;
        Ok(self)
    }

    /// Run `git status` parsing the status into idiomatic Rust type.
    /// 
    /// The status information is returned in a [`Status`].
    /// 
    /// [`Status`]: struct.Status.html
    pub fn status(&self) -> Result<Status> {
        let args = vec!["status", "--porcelain=v2", "--branch", "--ignored"];
        let out = self.run(args)?;
        Status::try_from(out.as_str())
    }

    /// Run `git stash` in the repository.
    /// 
    /// The command is run without ony options.
    pub fn stash(&mut self) -> Result<&mut Self> {
        let args = vec!["stash", "-q"];
        self.run(args)?;
        Ok(self)
    }

    /// Run `git tag`, creating a new tag object.
    /// 
    /// To call `git tag` with different options use [`TagOptions`].
    /// 
    /// [`TagOptions`]: commands/struct.TagOptions.html
    pub fn tag(&mut self, tagname: &str) -> Result<&mut Self> {
        let args = vec!["tag", tagname];
        self.run(args)?;
        Ok(self)
    }

    fn run(&self, args: Vec<&str>) -> Result<String> {
        // Setup command
        let mut cmd = Command::new("git");
        cmd.stdin(Stdio::inherit());
        if matches!(self.stdout, GitOut::Print) {
            cmd.stdout(Stdio::inherit())
               .stderr(Stdio::inherit());
        }
        if let Some(path) = &self.location {
            (&mut cmd).current_dir(path);
        }
        (&mut cmd).args(&args);

        if matches!(self.stdout, GitOut::Print) {
            // Run with inherited stdin/out
            let status = cmd.status().context("git execution failed")?;
            if status.success() {
                return Ok(String::new())
            } else {
                Err(GitError {
                    cmd: format!("git {}", args[0]),
                    code: status.code(),
                    stderr: format_err!("check stderr output"),
                }.into())
            }
        } else {
            // Run with piped stdin/out
            let out = cmd.output().context("git execution failed")?;
            if out.status.success() {
                Ok(String::from_utf8(out.stdout)?)
            } else {
                Err(GitError {
                    cmd: format!("git {}", args[0]),
                    code: out.status.code(),
                    stderr: format_err!("{}", std::str::from_utf8(&out.stderr)?),
                }.into())
            }
        }
    }
}

// -----------------------------------------------------------------------------
// Tests

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_mhgit_unit() {
        assert_eq!(2 + 2, 4);
    }
}