Skip to content

Instantly share code, notes, and snippets.

@kstep
Last active July 27, 2016 11:05
Show Gist options
  • Save kstep/0fd0ccaf24887aa333ae1d518ea12aeb to your computer and use it in GitHub Desktop.
Save kstep/0fd0ccaf24887aa333ae1d518ea12aeb to your computer and use it in GitHub Desktop.
//! # git-recent
//!
//! Prints recently checked out git branches, most recently checked out branch first.
//!
//! Usage: git recent [lines]
//!
//! Options:
//! lines - number of lines to output [default=10]
use std::io::prelude::*;
use std::io::BufReader;
use std::process::{Command, Stdio};
use std::collections::HashSet;
use std::path::PathBuf;
use std::env;
fn main() {
let max_lines = env::args().nth(1)
.and_then(|arg| arg.parse::<usize>().ok())
.unwrap_or(10);
let revparse = Command::new("git")
.arg("rev-parse")
.arg("--git-dir")
.stdout(Stdio::piped())
.output()
.expect("git-rev-parse command failed")
.stdout;
let heads_dir = {
let mut git_dir = PathBuf::from(String::from_utf8_lossy(&revparse).trim_right().to_owned());
git_dir.push("refs");
git_dir.push("heads");
git_dir
};
let reflog = BufReader::new(
Command::new("git")
.arg("reflog")
.stdout(Stdio::piped())
.spawn()
.expect("git-reflog command failed")
.stdout.unwrap());
let mut seen = HashSet::new();
let branches = reflog.lines()
.filter_map(Result::ok)
.filter(|line| line.contains("checkout: "))
.filter_map(|line| line.rsplitn(2, ' ').next().map(str::to_owned))
.filter(|branch| heads_dir.join(branch).exists())
.filter(|branch| seen.insert(branch.clone()))
.take(max_lines);
for branch in branches {
println!("{}", branch);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment