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
use std::path::{Path, PathBuf};

use eyre::Context;
use tracing::instrument;

use crate::core::eventlog::EventTransactionId;

use super::{FileMode, GitRunInfo, GitRunOpts, GitRunResult, MaybeZeroOid, NonZeroOid, Repo};

/// The possible stages for items in the index.
#[derive(Copy, Clone, Debug)]
pub enum Stage {
    /// Normal staged change.
    Stage0,

    /// For a merge conflict, the contents of the file at the common ancestor of the merged commits.
    Stage1,

    /// "Our" changes.
    Stage2,

    /// "Their" changes (from the commit being merged in).
    Stage3,
}

impl Stage {
    pub(super) fn get_trailer(&self) -> &'static str {
        match self {
            Stage::Stage0 => "Branchless-stage-0",
            Stage::Stage1 => "Branchless-stage-1",
            Stage::Stage2 => "Branchless-stage-2",
            Stage::Stage3 => "Branchless-stage-3",
        }
    }
}

impl From<Stage> for i32 {
    fn from(stage: Stage) -> Self {
        match stage {
            Stage::Stage0 => 0,
            Stage::Stage1 => 1,
            Stage::Stage2 => 2,
            Stage::Stage3 => 3,
        }
    }
}

/// An entry in the Git index.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct IndexEntry {
    pub(super) oid: MaybeZeroOid,
    pub(super) file_mode: FileMode,
}

/// The Git index.
pub struct Index {
    pub(super) inner: git2::Index,
}

impl std::fmt::Debug for Index {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "<Index>")
    }
}

impl Index {
    /// Whether or not there are unresolved merge conflicts in the index.
    pub fn has_conflicts(&self) -> bool {
        self.inner.has_conflicts()
    }

    /// Get the (stage 0) entry for the given path.
    pub fn get_entry(&self, path: &Path) -> Option<IndexEntry> {
        self.get_entry_in_stage(path, Stage::Stage0)
    }

    /// Get the entry for the given path in the given stage.
    pub fn get_entry_in_stage(&self, path: &Path, stage: Stage) -> Option<IndexEntry> {
        self.inner
            .get_path(path, i32::from(stage))
            .map(|entry| IndexEntry {
                oid: entry.id.into(),
                file_mode: {
                    // `libgit2` uses u32 for file modes in index entries, but
                    // i32 for file modes in tree entries for some reason.
                    let mode = i32::try_from(entry.mode).unwrap();
                    FileMode::try_from(mode).unwrap()
                },
            })
    }
}

/// The command to update the index, as defined by `git update-index`.
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub enum UpdateIndexCommand {
    Delete {
        path: PathBuf,
    },
    Update {
        path: PathBuf,
        stage: Stage,
        mode: FileMode,
        oid: NonZeroOid,
    },
}

/// Update the index. This handles updates to stages other than 0.
///
/// libgit2 doesn't offer a good way of updating the index for higher stages, so
/// internally we use `git update-index` directly.
#[instrument]
pub fn update_index(
    git_run_info: &GitRunInfo,
    repo: &Repo,
    index: &Index,
    event_tx_id: EventTransactionId,
    commands: &[UpdateIndexCommand],
) -> eyre::Result<()> {
    let stdin = {
        let mut buf = Vec::new();
        for command in commands {
            use std::io::Write;

            match command {
                UpdateIndexCommand::Delete { path } => {
                    write!(
                        &mut buf,
                        "0 {zero} 0\t{path}\0",
                        zero = MaybeZeroOid::Zero,
                        path = path.display(),
                    )?;
                }

                UpdateIndexCommand::Update {
                    path,
                    stage,
                    mode,
                    oid,
                } => {
                    write!(
                        &mut buf,
                        "{mode} {sha1} {stage}\t{path}\0",
                        mode = mode.to_string(),
                        sha1 = oid,
                        stage = i32::from(*stage),
                        path = path.display(),
                    )?;
                }
            }
        }
        buf
    };

    let GitRunResult { .. } = git_run_info
        .run_silent(
            repo,
            Some(event_tx_id),
            &["update-index", "-z", "--index-info"],
            GitRunOpts {
                treat_git_failure_as_error: true,
                stdin: Some(stdin),
            },
        )
        .wrap_err("Updating index")?;
    Ok(())
}