From b54604ac72ee90fe917b4733f93576030bbb3e0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gon=C3=A7alo=20Val=C3=A9rio?= Date: Fri, 13 Nov 2020 20:17:20 +0000 Subject: [PATCH] step thirty six: switch branches --- src/base.rs | 28 ++++++++++++++++++++-------- src/main.rs | 6 +++--- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/base.rs b/src/base.rs index 901a3ff..b23b9f5 100644 --- a/src/base.rs +++ b/src/base.rs @@ -137,17 +137,25 @@ pub fn iter_commits_and_parents(mut oids: VecDeque) -> Vec { return oid_sequence; } -pub fn checkout(oid: String) { +pub fn checkout(name: String) { + let oid = get_oid(name.clone()); let commit = get_commit(oid.clone()); + let head; read_tree(commit.tree); - data::update_ref( - "HEAD".to_owned(), - data::RefValue { - value: oid, + + if is_branch(name.clone()) { + head = data::RefValue { + symbolic: true, + value: format!("refs/heads/{}", name), + }; + } else { + head = data::RefValue { symbolic: false, - }, - true, - ); + value: oid, + }; + } + + data::update_ref("HEAD".to_owned(), head, false); } pub fn create_tag(name: String, oid: String) { @@ -269,3 +277,7 @@ fn empty_current_directory(dir: &str) -> io::Result<()> { } Ok(()) } + +fn is_branch(name: String) -> bool { + return data::get_ref(name, true).value != ""; +} diff --git a/src/main.rs b/src/main.rs index 9dd46e0..5c00368 100644 --- a/src/main.rs +++ b/src/main.rs @@ -49,7 +49,7 @@ fn main() { .subcommand( SubCommand::with_name("checkout") .about("Move the current content and HEAD to given commit") - .arg(Arg::with_name("oid").index(1).required(true)), + .arg(Arg::with_name("commit").index(1).required(true)), ) .subcommand( SubCommand::with_name("tag") @@ -147,8 +147,8 @@ fn log_commits(matches: ArgMatches) { fn checkout(matches: ArgMatches) { if let Some(cmd_matches) = matches.subcommand_matches("checkout") { - let oid = base::get_oid(cmd_matches.value_of("oid").unwrap().to_owned()); - base::checkout(oid); + let name = cmd_matches.value_of("commit").unwrap().to_owned(); + base::checkout(name); } }