aboutsummaryrefslogtreecommitdiffstats
path: root/src/git.rs
blob: 728b247c57d34195f6f316845133d88d8a9a68db (plain) (blame)
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
use std::num::ParseIntError;
use std::fmt;
use std::process::Command;
use std::io::Write;
use std::process::Stdio;

#[derive(Debug)]
pub enum GitError {
    GitLog(String),
    Parse(ParseIntError),
    UnknownRef,
}
impl fmt::Display for GitError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GitError::GitLog(s) => write!(f, "{}", s),
            GitError::Parse(s) => write!(f, "{}", s),
            GitError::UnknownRef => write!(f, "Unknown reference"),
        }
    }
}
impl From<ParseIntError> for GitError {
    fn from(err: ParseIntError) -> GitError {
        GitError::Parse(err)
    }
}
impl std::error::Error for GitError {}

////// TODO
pub fn get_files_to_unstage() -> String {
    let cmd = Command::new("git")
        .arg("update-index")
        .arg("--refresh")
        .output()
        .expect("Error with update-index");
    match cmd.status.code() {
        Some(1) => (),
        Some(0) => (),
        Some(s) => panic!("Fixme status code: {}",s),
        None => panic!("Fixme git update-index"),
    }
    let lines = String::from_utf8_lossy(&cmd.stdout).to_string();
    let mut files = String::default();
    for line in lines.lines() {
        files = files + " " +line.split(":").next().unwrap();
    }
    files[1..].to_string()
}

pub fn unstage_object(path: &str) {
    let cmd = Command::new("git")
        .arg("update-index")
        .arg("--remove")
        .arg(path)
        .output()
        .expect("Error with update-index");
    if !cmd.status.success() {
        panic!("FIXME unstage_object failed");
    }
}

pub fn update_ref(object: &str) {
    let cmd = Command::new("git")
        .arg("update-ref")
        .arg("refs/notes/devtools/future-me")
        .arg(object)
        .output()
        .expect("Error with update-index");
    if !cmd.status.success() {
        panic!("FIXME: update ref failed");
    }
}

pub fn stage_object(hash: &str, path: &str) {
    // with git update-index --add --cacheinfo 100644 hash dd/fffff
    let cmd = Command::new("git")
        .arg("update-index")
        .arg("--add")
        .arg("--cacheinfo")
        .arg("100644")
        .arg(hash)
        .arg(path)
        .output()
        .expect("Error with update-index");
    if !cmd.status.success() {
        panic!("FIXME");
    }
}

pub fn create_object(object: String) -> Result<String, GitError> {

    // create an git object with git hash-object -w --stdin
    let mut files = Command::new("git")
        .arg("hash-object")
        .arg("-w")
        .arg("--stdin")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("Error with git hash-ojbect");

    let mut stdin = files.stdin.take().expect("Failed to open stdin");
    std::thread::spawn(move || {
        stdin.write_all(object.as_bytes()).expect("Failed to write to stdin");
    });

    let output = files.wait_with_output().expect("Failed to write to stdout");
    let lines = String::from_utf8_lossy(&output.stdout).to_string();
    Ok(lines.split_whitespace().next().unwrap().to_string())
}

pub fn commit(object: String, parent: Option<String>) -> Result<String, GitError> {
    // commit_id=$(echo 'future-me: created a new bug for you' | git commit-tree $tree_id)
    let mut files = match parent {
        Some(parent) => 
            Command::new("git")
            .arg("commit-tree")
            .arg(object)
            .arg("-p")
            .arg(parent)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .expect("Error with git commit-tree"),
        None =>
            Command::new("git")
            .arg("commit-tree")
            .arg(object)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .expect("Error with git commit-tree"),
    };

    let mut stdin = files.stdin.take().expect("Failed to open stdin");
    std::thread::spawn(move || {
        stdin.write_all("future-me: created a new bug for you".as_bytes()).expect("Failed to write to stdin");
    });

    let output = files.wait_with_output().expect("Failed to write to stdout");
    let lines = String::from_utf8_lossy(&output.stdout).to_string();
    Ok(lines.split_whitespace().next().unwrap().to_string())
}

pub fn get_last_ref() -> Result<String, GitError> {
    let cmd = Command::new("git")
        .arg("show-ref")
        .arg("refs/notes/devtools/future-me")
        .output()
        .expect("Error with git show-ref");
    if !cmd.status.success() {
        //return GitError::GitLog(String::from_utf8_lossy(&cmd.stderr).to_string());
        GitError::GitLog(String::from_utf8_lossy(&cmd.stderr).to_string());
    }
    let lines = String::from_utf8_lossy(&cmd.stdout);

    match lines.split_whitespace().next() {
        Some(line) => Ok(line.to_string()),
        None => Err(GitError::UnknownRef),
    }
}

pub fn get_current_tree() -> Result<String, GitError>{
    let cmd = Command::new("git")
        .arg("log")
        .arg("-1")
        .arg("--format=%H")
        .output()
        .expect("Error with git log");
    if !cmd.status.success() {
        GitError::GitLog(String::from_utf8_lossy(&cmd.stderr).to_string());
    }
    let lines = String::from_utf8_lossy(&cmd.stdout);
    Ok(lines.trim().to_string())
}

pub fn write_tree() -> String {
    let cmd = Command::new("git")
        .arg("write-tree")
        .output()
        .expect("Error with git write-tree");
    if !cmd.status.success() {
        panic!("{}", String::from_utf8_lossy(&cmd.stderr));
    }
    let lines = String::from_utf8_lossy(&cmd.stdout);
    lines.trim().to_string()
}

pub fn create_new_tree() {
    let cmd = Command::new("git")
        .arg("read-tree")
        .arg("--empty")
        .output()
        .expect("Error with git read-tree");
    if !cmd.status.success() {
        panic!("{}", String::from_utf8_lossy(&cmd.stderr));
    }
}

pub fn read_tree(tree: &str) {
    let cmd = Command::new("git")
        .arg("read-tree")
        .arg(tree)
        .output()
        .expect("Error with git read-tree");
    if !cmd.status.success() {
        panic!("{}", String::from_utf8_lossy(&cmd.stderr));
    }
}

pub fn check_status() {
    let logs = Command::new("git")
        .arg("status")
        .arg("--porcelain")
        .output()
        .expect("Error with git status");
    if !logs.status.success() {
        GitError::GitLog(String::from_utf8_lossy(&logs.stderr).to_string());
    }
    let lines = String::from_utf8_lossy(&logs.stdout);
    for line in lines.lines() {
        println!("{}", line);
        if line.starts_with(['M', 'A']) {
            panic!("You first need to clean you git staging status to use future-me");
        }
    }
}

pub fn hello() {
    println!("hello from git");
}