diff --git a/src/base.rs b/src/base.rs index 1e44efb..9b1849c 100644 --- a/src/base.rs +++ b/src/base.rs @@ -5,6 +5,12 @@ use std::path::Path; #[path = "data.rs"] mod data; +pub struct Commit { + pub tree: String, + pub parent: String, + pub message: String, +} + pub fn write_tree(directory: String) -> String { let mut entries: Vec<(String, String, String)> = vec![]; let mut name; @@ -77,6 +83,32 @@ pub fn commit(message: &str) -> String { return oid; } +pub fn get_commit(oid: String) -> Commit { + let commit = data::get_object(oid, "commit".to_owned()); + let tree: String; + let mut parent: String = "".to_owned(); + let message: String; + let mut message_start = 2; + + let lines: Vec<&str> = commit.lines().collect(); + let mut line_items: Vec<&str> = lines[0].splitn(2, " ").collect(); + tree = line_items[1].to_owned(); + + line_items = lines[1].splitn(2, " ").collect(); + if line_items[0] == "parent" { + parent = line_items[1].to_owned(); + message_start = 3; + } + + message = lines[message_start..].join("\n"); + + return Commit { + tree, + parent, + message, + }; +} + fn is_ignored(path: &String) -> bool { if path.contains(".rgit") { true diff --git a/src/main.rs b/src/main.rs index 402001e..a61b13f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -38,6 +38,7 @@ fn main() { .takes_value(true), ), ) + .subcommand(SubCommand::with_name("log").about("List all commits")) .get_matches(); match matches.subcommand_name() { @@ -47,6 +48,7 @@ fn main() { Some("write-tree") => write_tree(), Some("read-tree") => read_tree(matches), Some("commit") => commit(matches), + Some("log") => log_commits(), _ => println!("unknown sub command"), } } @@ -94,3 +96,20 @@ fn commit(matches: ArgMatches) { println!("{}", base::commit(message)); } } + +fn log_commits() { + let mut oid = data::get_head().expect("Cannot read HEAD file"); + loop { + let commit = base::get_commit(oid.clone()); + + println!("commit {}", oid); + println!("{}", commit.message); + println!(""); + + if commit.parent == "" { + break; + } + + oid = commit.parent; + } +}