Skip to content

Instantly share code, notes, and snippets.

@Michael-F-Bryan
Last active May 18, 2017 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Michael-F-Bryan/4c475ce82eaa7e058a1d586e5d415186 to your computer and use it in GitHub Desktop.
Save Michael-F-Bryan/4c475ce82eaa7e058a1d586e5d415186 to your computer and use it in GitHub Desktop.
An quick program for parsing `git log` output and capturing each commit's hash and commit message.
#[macro_use]
extern crate error_chain;
extern crate regex;
use std::process::Command;
use regex::Regex;
error_chain!{
foreign_links {
Io(std::io::Error);
Regex(regex::Error);
Utf8(std::string::FromUtf8Error);
}
}
#[derive(PartialEq, Default, Clone, Debug)]
struct Commit {
hash: String,
message: String,
}
fn run() -> Result<()> {
let output = Command::new("git").arg("log").arg("--oneline").output()?;
if !output.status.success() {
bail!("Command executed with failing error code");
}
let pattern = Regex::new(r"(?x)
([0-9a-fA-F]+) # commit hash
(.*) # The commit message")?;
let stdout = String::from_utf8(output.stdout)?;
let commits = stdout
.lines()
.filter_map(|line| pattern.captures(line))
.map(|cap| {
Commit {
hash: cap[1].to_string(),
message: cap[2].trim().to_string(),
}
});
for commit in commits {
println!("{:?}", commit);
}
Ok(())
}
quick_main!(run);
@Michael-F-Bryan
Copy link
Author

Running this on my fork of rust-cookbook gives the following output:

$ cd ~/Documents/forks/rust-cookbook && /tmp/parsing-subprocess-output | head
Commit { hash: "fd0e0b4", message: "Merge pull request #120 from gsquire/head-example" }
Commit { hash: "bbfdc8a", message: "remove dead link" }
Commit { hash: "3cd5ab1", message: "update some of the wording to be clearer" }
Commit { hash: "761054f", message: "add an example for making a HEAD request with a timeout" }
Commit { hash: "4a5c675", message: "Add CI badge to readme" }
Commit { hash: "2dcc48b", message: "Merge pull request #118 from budziq/label_sync" }
Commit { hash: "ed3a42d", message: "Travis \"cron\" builds run tests with \"*\" dependencies" }
Commit { hash: "62fd9dc", message: "Link to example of a commit" }
Commit { hash: "e698443", message: "Add percent-encode example" }
Commit { hash: "cbad25c", message: "Sort badge links" }

And the original command's output:

$ git log --oneline | head
fd0e0b4 Merge pull request #120 from gsquire/head-example
bbfdc8a remove dead link
3cd5ab1 update some of the wording to be clearer
761054f add an example for making a HEAD request with a timeout
4a5c675 Add CI badge to readme
2dcc48b Merge pull request #118 from budziq/label_sync
ed3a42d Travis "cron" builds run tests with "*" dependencies
62fd9dc Link to example of a commit
e698443 Add percent-encode example
cbad25c Sort badge links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment