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
//! Higher-level git operations
//!
//! These are closer to what you expect to see for porcelain commands, rather than just plumbing.
//! They serve as both examples on how to use `git2` but also should be usable in some limited
//! subset of cases.

use itertools::Itertools;

/// Lookup the commit ID for `HEAD`
pub fn head_id(repo: &git2::Repository) -> Option<git2::Oid> {
    repo.head().ok()?.resolve().ok()?.target()
}

/// Lookup the branch that HEAD points to
pub fn head_branch(repo: &git2::Repository) -> Option<String> {
    repo.head()
        .ok()?
        .resolve()
        .ok()?
        .shorthand()
        .map(String::from)
}

/// Report if the working directory is dirty
pub fn is_dirty(repo: &git2::Repository) -> bool {
    if repo.state() != git2::RepositoryState::Clean {
        log::trace!("Repository status is unclean: {:?}", repo.state());
        return true;
    }

    let status = repo
        .statuses(Some(git2::StatusOptions::new().include_ignored(false)))
        .unwrap();
    if status.is_empty() {
        false
    } else {
        log::trace!(
            "Repository is dirty: {}",
            status
                .iter()
                .flat_map(|s| s.path().map(|s| s.to_owned()))
                .join(", ")
        );
        true
    }
}

/// Cherry pick a commit onto another without touching the working directory
pub fn cherry_pick(
    repo: &git2::Repository,
    head_id: git2::Oid,
    cherry_id: git2::Oid,
) -> Result<git2::Oid, git2::Error> {
    let cherry_commit = repo.find_commit(cherry_id)?;
    let base_id = match cherry_commit.parent_count() {
        0 => cherry_id,
        1 => cherry_commit.parent_id(0)?,
        _ => cherry_commit
            .parent_ids()
            .find(|id| *id == head_id)
            .map(Result::Ok)
            .unwrap_or_else(|| cherry_commit.parent_id(0))?,
    };
    if base_id == head_id {
        // Already on top of the intended base
        return Ok(cherry_id);
    }

    let base_ann_commit = repo.find_annotated_commit(base_id)?;
    let head_ann_commit = repo.find_annotated_commit(head_id)?;
    let cherry_ann_commit = repo.find_annotated_commit(cherry_id)?;
    let mut rebase = repo.rebase(
        Some(&cherry_ann_commit),
        Some(&base_ann_commit),
        Some(&head_ann_commit),
        Some(git2::RebaseOptions::new().inmemory(true)),
    )?;

    let mut tip_id = head_id;
    while let Some(op) = rebase.next() {
        op.map_err(|e| {
            let _ = rebase.abort();
            e
        })?;
        let inmemory_index = rebase.inmemory_index().unwrap();
        if inmemory_index.has_conflicts() {
            let conflicts = inmemory_index
                .conflicts()?
                .map(|conflict| {
                    let conflict = conflict.unwrap();
                    let our_path = conflict
                        .our
                        .as_ref()
                        .map(|c| crate::bytes::bytes2path(&c.path))
                        .or_else(|| {
                            conflict
                                .their
                                .as_ref()
                                .map(|c| crate::bytes::bytes2path(&c.path))
                        })
                        .or_else(|| {
                            conflict
                                .ancestor
                                .as_ref()
                                .map(|c| crate::bytes::bytes2path(&c.path))
                        })
                        .unwrap_or_else(|| std::path::Path::new("<unknown>"));
                    format!("{}", our_path.display())
                })
                .join("\n  ");
            return Err(git2::Error::new(
                git2::ErrorCode::Unmerged,
                git2::ErrorClass::Index,
                format!("cherry-pick conflicts:\n  {}\n", conflicts),
            ));
        }

        let mut sig = repo.signature()?;
        if let (Some(name), Some(email)) = (sig.name(), sig.email()) {
            // For simple rebases, preserve the original commit time
            sig = git2::Signature::new(name, email, &cherry_commit.time())?.to_owned();
        }
        let commit_id = match rebase.commit(None, &sig, None).map_err(|e| {
            let _ = rebase.abort();
            e
        }) {
            Ok(commit_id) => Ok(commit_id),
            Err(err) => {
                if err.class() == git2::ErrorClass::Rebase && err.code() == git2::ErrorCode::Applied
                {
                    log::trace!("Skipping {}, already applied to {}", cherry_id, head_id);
                    return Ok(tip_id);
                }
                Err(err)
            }
        }?;
        tip_id = commit_id;
    }
    rebase.finish(None)?;
    Ok(tip_id)
}

/// Squash `head_id` into `into_id` without touching the working directory
///
/// `into_id`'s author, committer, and message are preserved.
pub fn squash(
    repo: &git2::Repository,
    head_id: git2::Oid,
    into_id: git2::Oid,
    sign: Option<&dyn Sign>,
) -> Result<git2::Oid, git2::Error> {
    // Based on https://www.pygit2.org/recipes/git-cherry-pick.html
    let head_commit = repo.find_commit(head_id)?;
    let head_tree = repo.find_tree(head_commit.tree_id())?;

    let base_commit = if 0 < head_commit.parent_count() {
        head_commit.parent(0)?
    } else {
        head_commit.clone()
    };
    let base_tree = repo.find_tree(base_commit.tree_id())?;

    let into_commit = repo.find_commit(into_id)?;
    let into_tree = repo.find_tree(into_commit.tree_id())?;

    let onto_commit;
    let onto_commits;
    let onto_commits: &[&git2::Commit] = if 0 < into_commit.parent_count() {
        onto_commit = into_commit.parent(0)?;
        onto_commits = [&onto_commit];
        &onto_commits
    } else {
        &[]
    };

    let mut result_index = repo.merge_trees(&base_tree, &into_tree, &head_tree, None)?;
    if result_index.has_conflicts() {
        let conflicts = result_index
            .conflicts()?
            .map(|conflict| {
                let conflict = conflict.unwrap();
                let our_path = conflict
                    .our
                    .as_ref()
                    .map(|c| crate::bytes::bytes2path(&c.path))
                    .or_else(|| {
                        conflict
                            .their
                            .as_ref()
                            .map(|c| crate::bytes::bytes2path(&c.path))
                    })
                    .or_else(|| {
                        conflict
                            .ancestor
                            .as_ref()
                            .map(|c| crate::bytes::bytes2path(&c.path))
                    })
                    .unwrap_or_else(|| std::path::Path::new("<unknown>"));
                format!("{}", our_path.display())
            })
            .join("\n  ");
        return Err(git2::Error::new(
            git2::ErrorCode::Unmerged,
            git2::ErrorClass::Index,
            format!("squash conflicts:\n  {}\n", conflicts),
        ));
    }
    let result_id = result_index.write_tree_to(repo)?;
    let result_tree = repo.find_tree(result_id)?;
    let new_id = commit(
        repo,
        &into_commit.author(),
        &into_commit.committer(),
        into_commit.message().unwrap(),
        &result_tree,
        onto_commits,
        sign,
    )?;
    Ok(new_id)
}

/// Reword `head_id`s commit
pub fn reword(
    repo: &git2::Repository,
    head_id: git2::Oid,
    msg: &str,
    sign: Option<&dyn Sign>,
) -> Result<git2::Oid, git2::Error> {
    let old_commit = repo.find_commit(head_id)?;
    let parents = old_commit.parents().collect::<Vec<_>>();
    let parents = parents.iter().collect::<Vec<_>>();
    let tree = repo.find_tree(old_commit.tree_id())?;
    let new_id = commit(
        repo,
        &old_commit.author(),
        &old_commit.committer(),
        msg,
        &tree,
        &parents,
        sign,
    )?;
    Ok(new_id)
}

/// Commit with signing support
pub fn commit(
    repo: &git2::Repository,
    author: &git2::Signature<'_>,
    committer: &git2::Signature<'_>,
    message: &str,
    tree: &git2::Tree<'_>,
    parents: &[&git2::Commit<'_>],
    sign: Option<&dyn Sign>,
) -> Result<git2::Oid, git2::Error> {
    if let Some(sign) = sign {
        let content = repo.commit_create_buffer(author, committer, message, tree, parents)?;
        let content = std::str::from_utf8(&content).unwrap();
        let signed = sign.sign(content);
        repo.commit_signed(content, &signed, None)
    } else {
        repo.commit(None, author, committer, message, tree, parents)
    }
}

/// For signing [commit]s
///
/// See <https://blog.hackeriet.no/signing-git-commits-in-rust/> for an example of what to do.
pub trait Sign {
    fn sign(&self, buffer: &str) -> String;
}