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
//! Handle hiding commits when explicitly requested by the user (as opposed to
//! automatically as the result of a rewrite operation).

use std::collections::HashSet;
use std::io::Write;
use std::time::SystemTime;

use fn_error_context::context;
use git2::ErrorCode;

use crate::core::eventlog::{CommitVisibility, Event};
use crate::core::eventlog::{EventLogDb, EventReplayer};
use crate::core::graph::{make_graph, BranchOids, CommitGraph, HeadOid, MainBranchOid, Node};
use crate::core::mergebase::MergeBaseDb;
use crate::core::metadata::{render_commit_metadata, CommitMessageProvider, CommitOidProvider};
use crate::util::{
    get_branch_oid_to_names, get_db_conn, get_head_oid, get_main_branch_oid, get_repo,
};

enum ProcessHashesResult<'repo> {
    Ok { commits: Vec<git2::Commit<'repo>> },
    CommitNotFound { hash: String },
}

#[context("Processing hashes")]
fn process_hashes(
    repo: &git2::Repository,
    hashes: Vec<String>,
) -> anyhow::Result<ProcessHashesResult> {
    let mut commits = Vec::new();
    for hash in hashes {
        let commit = match repo.revparse_single(&hash) {
            Ok(commit) => match commit.into_commit() {
                Ok(commit) => commit,
                Err(_) => return Ok(ProcessHashesResult::CommitNotFound { hash }),
            },
            Err(err) if err.code() == ErrorCode::NotFound => {
                return Ok(ProcessHashesResult::CommitNotFound { hash })
            }
            Err(err) => return Err(err.into()),
        };
        commits.push(commit)
    }
    Ok(ProcessHashesResult::Ok { commits })
}

fn recurse_on_commits_helper<
    'repo,
    'graph,
    Condition: Fn(&'graph Node<'repo>) -> bool,
    Callback: FnMut(&'graph Node<'repo>),
>(
    graph: &'graph CommitGraph<'repo>,
    condition: &Condition,
    commit: &git2::Commit<'repo>,
    callback: &mut Callback,
) {
    let node = &graph[&commit.id()];
    if condition(node) {
        callback(node);
    };

    for child_oid in node.children.iter() {
        let child_commit = &graph[&child_oid].commit;
        recurse_on_commits_helper(graph, condition, child_commit, callback)
    }
}

fn recurse_on_commits<'repo, F: Fn(&Node) -> bool>(
    repo: &'repo git2::Repository,
    merge_base_db: &MergeBaseDb,
    event_replayer: &EventReplayer,
    commits: Vec<git2::Commit<'repo>>,
    condition: F,
) -> anyhow::Result<Vec<git2::Commit<'repo>>> {
    let head_oid = get_head_oid(repo)?;
    let main_branch_oid = get_main_branch_oid(repo)?;
    let branch_oid_to_names = get_branch_oid_to_names(repo)?;
    let graph = make_graph(
        repo,
        merge_base_db,
        event_replayer,
        event_replayer.make_default_cursor(),
        &HeadOid(head_oid),
        &MainBranchOid(main_branch_oid),
        &BranchOids(branch_oid_to_names.keys().copied().collect()),
        false,
    )?;

    // Maintain ordering, since it's likely to be meaningful.
    let mut result: Vec<git2::Commit<'repo>> = Vec::new();
    let mut seen_oids = HashSet::new();
    for commit in commits {
        recurse_on_commits_helper(&graph, &condition, &commit, &mut |child_node| {
            let child_commit = &child_node.commit;
            if !seen_oids.contains(&child_commit.id()) {
                seen_oids.insert(child_commit.id());
                result.push(child_commit.clone());
            }
        });
    }
    Ok(result)
}

/// Hide the hashes provided on the command-line.
///
/// Args:
/// * `out`: The output stream to write to.
/// * `hashes`: A list of commit hashes to hide. Revs will be resolved (you can
///   provide an abbreviated commit hash or ref name).
/// * `recursive: If `true`, will recursively hide all children of the provided
///   commits as well.
///
/// Returns: exit code (0 denotes successful exit).
pub fn hide(out: &mut impl Write, hashes: Vec<String>, recursive: bool) -> anyhow::Result<isize> {
    let now = SystemTime::now();
    let repo = get_repo()?;
    let conn = get_db_conn(&repo)?;
    let mut event_log_db = EventLogDb::new(&conn)?;
    let event_replayer = EventReplayer::from_event_log_db(&event_log_db)?;
    let merge_base_db = MergeBaseDb::new(&conn)?;

    let commits = process_hashes(&repo, hashes)?;
    let commits = match commits {
        ProcessHashesResult::Ok { commits } => commits,
        ProcessHashesResult::CommitNotFound { hash } => {
            writeln!(out, "Commit not found: {}", hash)?;
            return Ok(1);
        }
    };
    let commits = if recursive {
        recurse_on_commits(&repo, &merge_base_db, &event_replayer, commits, |node| {
            node.is_visible
        })?
    } else {
        commits
    };

    let timestamp = now.duration_since(SystemTime::UNIX_EPOCH)?.as_secs_f64();
    let event_tx_id = event_log_db.make_transaction_id(now, "hide")?;
    let events = commits
        .iter()
        .map(|commit| Event::HideEvent {
            timestamp,
            event_tx_id,
            commit_oid: commit.id(),
        })
        .collect();
    event_log_db.add_events(events)?;

    let cursor = event_replayer.make_default_cursor();
    for commit in commits {
        let hidden_commit_text = {
            render_commit_metadata(
                &commit,
                &[
                    &CommitOidProvider::new(true)?,
                    &CommitMessageProvider::new()?,
                ],
            )?
        };
        writeln!(out, "Hid commit: {}", hidden_commit_text)?;
        if let Some(CommitVisibility::Hidden) =
            event_replayer.get_cursor_commit_visibility(cursor, commit.id())
        {
            writeln!(
                out,
                "(It was already hidden, so this operation had no effect.)"
            )?;
        }

        let commit_target_oid =
            render_commit_metadata(&commit, &[&CommitOidProvider::new(false)?])?;
        writeln!(
            out,
            "To unhide this commit, run: git unhide {}",
            commit_target_oid
        )?;
    }

    Ok(0)
}

/// Unhide the hashes provided on the command-line.
///
/// Args:
/// * `out`: The output stream to write to.
/// * `hashes`: A list of commit hashes to unhide. Revs will be resolved (you can
/// provide an abbreviated commit hash or ref name).
/// * `recursive: If `true`, will recursively unhide all children of the provided
///   commits as well.
///
/// Returns: exit code (0 denotes successful exit).
pub fn unhide(out: &mut impl Write, hashes: Vec<String>, recursive: bool) -> anyhow::Result<isize> {
    let now = SystemTime::now();
    let repo = get_repo()?;
    let conn = get_db_conn(&repo)?;
    let mut event_log_db = EventLogDb::new(&conn)?;
    let event_replayer = EventReplayer::from_event_log_db(&event_log_db)?;
    let merge_base_db = MergeBaseDb::new(&conn)?;

    let commits = process_hashes(&repo, hashes)?;
    let commits = match commits {
        ProcessHashesResult::Ok { commits } => commits,
        ProcessHashesResult::CommitNotFound { hash } => {
            writeln!(out, "Commit not found: {}", hash)?;
            return Ok(1);
        }
    };
    let commits = if recursive {
        recurse_on_commits(&repo, &merge_base_db, &event_replayer, commits, |node| {
            !node.is_visible
        })?
    } else {
        commits
    };

    let timestamp = now.duration_since(SystemTime::UNIX_EPOCH)?.as_secs_f64();
    let event_tx_id = event_log_db.make_transaction_id(now, "unhide")?;
    let events = commits
        .iter()
        .map(|commit| Event::UnhideEvent {
            timestamp,
            event_tx_id,
            commit_oid: commit.id(),
        })
        .collect();
    event_log_db.add_events(events)?;

    let cursor = event_replayer.make_default_cursor();
    for commit in commits {
        let unhidden_commit_text = {
            render_commit_metadata(
                &commit,
                &[
                    &CommitOidProvider::new(true)?,
                    &CommitMessageProvider::new()?,
                ],
            )?
        };
        writeln!(out, "Unhid commit: {}", unhidden_commit_text)?;
        if let Some(CommitVisibility::Visible) =
            event_replayer.get_cursor_commit_visibility(cursor, commit.id())
        {
            writeln!(out, "(It was not hidden, so this operation had no effect.)")?;
        }

        let commit_target_oid =
            render_commit_metadata(&commit, &[&CommitOidProvider::new(false)?])?;
        writeln!(
            out,
            "To hide this commit, run: git hide {}",
            commit_target_oid
        )?;
    }

    Ok(0)
}