Skip to content

Commit 1dd5ccb

Browse files
committed
fix: Prefer attached HEADs
1 parent 7938f1d commit 1dd5ccb

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

src/lib.rs

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -212,15 +212,22 @@ impl TodoList {
212212
repo.tag(tag.as_str(), commit.as_object(), &sig, &message, true)?;
213213
}
214214
Command::Head => {
215-
let current_oid = last_oid.ok_or_else(|| eyre::eyre!("no commits yet"))?;
216-
log::trace!("exec git checkout {}", current_oid);
217-
head = Some(AnnotatedOid::Commit(current_oid));
215+
let new_head = if let Some(branch) = self.last_branch(i) {
216+
AnnotatedOid::Branch(branch)
217+
} else {
218+
let current_oid = last_oid.ok_or_else(|| eyre::eyre!("no commits yet"))?;
219+
AnnotatedOid::Commit(current_oid)
220+
};
221+
log::trace!("exec git checkout {}", new_head);
222+
head = Some(new_head);
218223
}
219224
}
220225
}
221226

222227
let head = if let Some(head) = head {
223228
head
229+
} else if let Some(branch) = self.last_branch(self.commands.len()) {
230+
AnnotatedOid::Branch(branch)
224231
} else {
225232
let current_oid = last_oid.ok_or_else(|| eyre::eyre!("no commits yet"))?;
226233
AnnotatedOid::Commit(current_oid)
@@ -230,20 +237,38 @@ impl TodoList {
230237
repo.set_head_detached(head)?;
231238
}
232239
AnnotatedOid::Branch(head) => {
233-
repo.set_head(&head)?;
240+
let branch = repo.find_branch(&head, git2::BranchType::Local)?;
241+
repo.set_head(branch.get().name().unwrap())?;
234242
}
235243
}
236244
repo.checkout_head(None)?;
237245

238246
Ok(())
239247
}
248+
249+
fn last_branch(&self, current_index: usize) -> Option<String> {
250+
if let Some(Command::Branch(prev)) = self.commands.get(current_index.saturating_sub(1)) {
251+
Some(prev.as_str().to_owned())
252+
} else {
253+
None
254+
}
255+
}
240256
}
241257

242-
pub enum AnnotatedOid {
258+
enum AnnotatedOid {
243259
Commit(git2::Oid),
244260
Branch(String),
245261
}
246262

263+
impl std::fmt::Display for AnnotatedOid {
264+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265+
match self {
266+
Self::Commit(ann) => ann.fmt(f),
267+
Self::Branch(ann) => ann.fmt(f),
268+
}
269+
}
270+
}
271+
247272
#[cfg(unix)]
248273
fn path2bytes(p: &std::path::Path) -> Vec<u8> {
249274
use std::os::unix::prelude::*;

0 commit comments

Comments
 (0)