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
//! Convenience commands to help the user move through a stack of commits.

use std::collections::HashMap;
use std::io::Write;

use log::warn;

use crate::commands::smartlog::smartlog;
use crate::core::eventlog::{EventLogDb, EventReplayer};
use crate::core::formatting::Glyphs;
use crate::core::graph::{
    find_path_to_merge_base, make_graph, BranchOids, 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, run_git,
    GitExecutable,
};

/// Go back a certain number of commits.
pub fn prev(
    out: &mut impl Write,
    err: &mut impl Write,
    git_executable: &GitExecutable,
    num_commits: Option<isize>,
) -> anyhow::Result<isize> {
    let exit_code = match num_commits {
        None => run_git(out, err, git_executable, None, &["checkout", "HEAD^"])?,
        Some(num_commits) => run_git(
            out,
            err,
            git_executable,
            None,
            &["checkout", &format!("HEAD~{}", num_commits)],
        )?,
    };
    if exit_code != 0 {
        return Ok(exit_code);
    }
    smartlog(out)?;
    Ok(0)
}

/// Some commits have multiple children, which makes `next` ambiguous. These
/// values disambiguate which child commit to go to, according to the committed
/// date.
#[derive(Clone, Copy, Debug)]
pub enum Towards {
    /// When encountering multiple children, select the newest one.
    Newest,

    /// When encountering multiple children, select the oldest one.
    Oldest,
}

fn advance_towards_main_branch(
    repo: &git2::Repository,
    merge_base_db: &MergeBaseDb,
    graph: &HashMap<git2::Oid, Node>,
    current_oid: git2::Oid,
    main_branch_oid: &MainBranchOid,
) -> anyhow::Result<(isize, git2::Oid)> {
    let MainBranchOid(main_branch_oid) = main_branch_oid;
    let path = find_path_to_merge_base(repo, merge_base_db, *main_branch_oid, current_oid)?;
    let path = match path {
        None => return Ok((0, current_oid)),
        Some(path) if path.len() == 1 => {
            // Must be the case that `current_oid == main_branch_oid`.
            return Ok((0, current_oid));
        }
        Some(path) => path,
    };

    for (i, commit) in (1..).zip(path.iter().rev().skip(1)) {
        if graph.contains_key(&commit.id()) {
            return Ok((i, commit.id()));
        }
    }

    warn!("Failed to find graph commit when advancing towards main branch");
    Ok((0, current_oid))
}

fn advance_towards_own_commit(
    out: &mut impl Write,
    glyphs: &Glyphs,
    repo: &git2::Repository,
    graph: &HashMap<git2::Oid, Node>,
    current_oid: git2::Oid,
    num_commits: isize,
    towards: Option<Towards>,
) -> anyhow::Result<Option<git2::Oid>> {
    let mut current_oid = current_oid;
    for i in 0..num_commits {
        let mut children: Vec<git2::Oid> = graph[&current_oid].children.iter().copied().collect();
        children.sort_by_key(|child_oid| graph[child_oid].commit.time());
        current_oid = match (towards, &children.as_slice()) {
            (_, []) => {
                // It would also make sense to issue an error here, rather than
                // silently stop going forward commits.
                break;
            }
            (_, [only_child_oid]) => *only_child_oid,
            (Some(Towards::Newest), [.., newest_child_oid]) => *newest_child_oid,
            (Some(Towards::Oldest), [oldest_child_oid, ..]) => *oldest_child_oid,
            (None, [_, _, ..]) => {
                writeln!(
                    out,
                    "Found multiple possible next commits to go to after traversing {} children:",
                    i
                )?;

                for (j, child_oid) in (0..).zip(children.iter()) {
                    let descriptor = if j == 0 {
                        " (oldest)"
                    } else if j + 1 == children.len() {
                        " (newest)"
                    } else {
                        ""
                    };

                    let commit_text = render_commit_metadata(
                        &repo.find_commit(*child_oid)?,
                        &[
                            &CommitOidProvider::new(true)?,
                            &CommitMessageProvider::new()?,
                        ],
                    )?;
                    writeln!(
                        out,
                        "  {} {}{}",
                        glyphs.bullet_point, commit_text, descriptor
                    )?;
                }
                writeln!(out, "(Pass --oldest (-o) or --newest (-n) to select between ambiguous next commits)")?;
                return Ok(None);
            }
        };
    }
    Ok(Some(current_oid))
}

/// Go forward a certain number of commits.
pub fn next(
    out: &mut impl Write,
    err: &mut impl Write,
    git_executable: &GitExecutable,
    num_commits: Option<isize>,
    towards: Option<Towards>,
) -> anyhow::Result<isize> {
    let glyphs = Glyphs::detect();
    let repo = get_repo()?;
    let conn = get_db_conn(&repo)?;
    let merge_base_db = MergeBaseDb::new(&conn)?;
    let event_log_db = EventLogDb::new(&conn)?;
    let event_replayer = EventReplayer::from_event_log_db(&event_log_db)?;

    let head_oid = match get_head_oid(&repo)? {
        Some(head_oid) => head_oid,
        None => anyhow::bail!("No HEAD present; cannot calculate next commit"),
    };
    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(Some(head_oid)),
        &MainBranchOid(main_branch_oid),
        &BranchOids(branch_oid_to_names.keys().copied().collect()),
        true,
    )?;

    let num_commits = num_commits.unwrap_or(1);
    let (num_commits_traversed_towards_main_branch, current_oid) = advance_towards_main_branch(
        &repo,
        &merge_base_db,
        &graph,
        head_oid,
        &MainBranchOid(main_branch_oid),
    )?;
    let num_commits = num_commits - num_commits_traversed_towards_main_branch;
    let current_oid = advance_towards_own_commit(
        out,
        &glyphs,
        &repo,
        &graph,
        current_oid,
        num_commits,
        towards,
    )?;
    let current_oid = match current_oid {
        None => return Ok(1),
        Some(current_oid) => current_oid,
    };

    let result = run_git(
        out,
        err,
        git_executable,
        None,
        &["checkout", &current_oid.to_string()],
    )?;
    if result != 0 {
        return Ok(result);
    }

    smartlog(out)?;
    Ok(0)
}