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
// License: see LICENSE file at root directory of main branch

//! # Git

use core::{
    str::FromStr,
};

use std::{
    collections::HashSet,
    env,
    ffi::OsStr,
    io::{Error, ErrorKind},
    path::{Path, PathBuf},
    process::{Command, Stdio},
};

use {
    crate::Result,
    dia_semver::Semver,
};

mod remote;

pub use self::remote::*;

const APP: &str = "git";

const CMD_ADD: &str = "add";
const CMD_BRANCH: &str = "branch";
const CMD_COMMIT: &str = "commit";
const CMD_PUSH: &str = "push";
const CMD_REMOTE: &str = "remote";
const CMD_TAG: &str = "tag";

const OPTION_2_HYPHENS: &str = "--";
const OPTION_ALL: &str = "--all";
const OPTION_ANNOTATE: &str = "--annotate";
const OPTION_MESSAGE: &str = "--message";
const OPTION_SHOW_CURRENT: &str = "--show-current";
const OPTION_TAGS: &str = "--tags";
const OPTION_VERBOSE: &str = "--verbose";

/// # Git
///
/// This struct holds a path to some repository. The path does not need to be root directory of that repository.
#[derive(Debug)]
pub struct Git {

    path: PathBuf,

}

impl Git {

    /// # Makes new instance
    ///
    /// If you don't provide a path, current directory will be used.
    pub fn make<P>(path: Option<P>) -> Result<Self> where P: AsRef<Path> {
        Ok(Self {
            path: match path {
                Some(path) => path.as_ref().to_path_buf(),
                None => env::current_dir()?,
            },
        })
    }

    /// # Makes new command
    fn new_cmd<S, S2>(&self, cmd: S, args: Option<&[S2]>) -> Command where S: AsRef<OsStr>, S2: AsRef<OsStr> {
        let mut result = Command::new(APP);
        result.current_dir(&self.path);

        // Command
        result.arg(cmd);

        // Arguments
        if let Some(args) = args {
            for a in args {
                result.arg(a);
            }
        }

        result
    }

    /// # Makes new command for adding all files
    pub fn new_cmd_for_adding_all_files<F, P>(&self, files: Option<F>) -> Command where F: Iterator<Item=P>, P: AsRef<Path> {
        let mut result = self.new_cmd(CMD_ADD, Some(&[OPTION_ALL]));

        if let Some(files) = files {
            result.arg(OPTION_2_HYPHENS);
            for f in files {
                result.arg(f.as_ref());
            }
        }

        result
    }

    /// # Makes new command for committing all files with a message
    pub fn new_cmd_for_committing_all_files_with_a_message<S>(&self, msg: S) -> Command where S: AsRef<str> {
        self.new_cmd(CMD_COMMIT, Some(&[OPTION_ALL, OPTION_MESSAGE, msg.as_ref()]))
    }

    /// # Makes new command for adding an annotated tag with a message
    pub fn new_cmd_for_adding_an_annotated_tag_with_a_message<S>(&self, tag: &Semver, msg: S) -> Command where S: AsRef<str> {
        let tag = tag.to_string();
        self.new_cmd(CMD_TAG, Some(&[tag.as_str(), OPTION_ANNOTATE, OPTION_MESSAGE, msg.as_ref()]))
    }

    /// # Makes new command for pushing to a remote
    pub fn new_cmd_for_pushing_to_a_remote(&self, remote: &Remote) -> Command {
        self.new_cmd(CMD_PUSH, Some(&[remote.name()]))
    }

    /// # Makes new command for pushing tags to a remote
    pub fn new_cmd_for_pushing_tags_to_a_remote(&self, remote: &Remote) -> Command {
        self.new_cmd(CMD_PUSH, Some(&[remote.name(), OPTION_TAGS]))
    }

    /// # Makes new command, runs it and returns its output (stdout)
    fn run_cmd<S, S2>(&self, cmd: S, args: Option<&[S2]>) -> Result<String> where S: AsRef<OsStr>, S2: AsRef<OsStr> {
        let mut cmd = self.new_cmd(cmd, args);
        cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null());

        let output = cmd.output()?;
        if output.status.success() {
            Ok(String::from_utf8(output.stdout).map_err(|e| Error::new(ErrorKind::Other, e))?)
        } else {
            Err(Error::new(ErrorKind::Other, format!("{app} returned: {status}", app=APP, status=output.status)))
        }
    }

    /// # Loads current branch
    pub fn current_branch(&self) -> Result<String> {
        let output = self.run_cmd(CMD_BRANCH, Some(&[OPTION_SHOW_CURRENT]))?;
        let output = output.trim();
        if output.lines().count() == 1 {
            Ok(output.to_string())
        } else {
            Err(Error::new(ErrorKind::Other, format!("{app} returned: {output}", app=APP, output=output)))
        }
    }

    /// # Finds last version having same build metadata
    pub fn find_last_version_with_build_metadata(&self, build_metadata: Option<&str>) -> Result<Option<Semver>> {
        let output = self.run_cmd::<_, &str>(CMD_TAG, None)?;

        let mut result = None;
        for line in output.lines() {
            if let Ok(version) = Semver::from_str(line.trim()) {
                if version.build_metadata() == build_metadata {
                    result = match result {
                        None => Some(version),
                        Some(other) => Some(version.max(other)),
                    };
                }
            }
        }

        Ok(result)
    }

    /// # Loads remotes and sort them
    pub fn remotes(&self) -> Result<Vec<Remote>> {
        let output = self.run_cmd(CMD_REMOTE, Some(&[OPTION_VERBOSE]))?;

        let mut set = HashSet::with_capacity(9);
        for line in output.lines() {
            let mut parts = line.split_whitespace();
            match (parts.next(), parts.next(), parts.next(), parts.next()) {
                (Some(name), Some(url), Some("(fetch)" | "(push)"), None) => set.insert(Remote::new(name.to_string(), url.to_string())),
                _ => continue,
            };
        }

        let mut result: Vec<_> = set.into_iter().collect();
        result.sort();
        Ok(result)
    }

}