Added support for multiple repos each with their own number of branches

master
Wynd 2024-08-17 01:48:06 +03:00
parent 893947b6ec
commit cbbe8c44b0
3 changed files with 84 additions and 61 deletions

View File

@ -8,9 +8,6 @@ use crate::heatmap::HeatmapColors;
#[derive(Clone, Debug, Parser, PartialEq, Eq)] #[derive(Clone, Debug, Parser, PartialEq, Eq)]
#[command(version, about, long_about = None)] #[command(version, about, long_about = None)]
pub struct CliArgs { pub struct CliArgs {
#[arg(default_value=".", value_hint = ValueHint::DirPath)]
pub input: PathBuf,
#[arg(short, long)] #[arg(short, long)]
pub author: String, pub author: String,
@ -20,6 +17,9 @@ pub struct CliArgs {
#[arg(long("color"), value_enum, default_value_t = HeatmapColors::Green)] #[arg(long("color"), value_enum, default_value_t = HeatmapColors::Green)]
pub color_scheme: HeatmapColors, pub color_scheme: HeatmapColors,
#[arg(short, long, num_args(0..), value_hint = ValueHint::DirPath)]
pub repos: Option<Vec<PathBuf>>,
#[arg(short, long, num_args(0..))] #[arg(short, long, num_args(0..))]
pub branches: Option<Vec<String>>, pub branches: Option<Vec<String>>,

View File

@ -12,10 +12,11 @@ pub struct Heatmap {
commits: Vec<Commit>, commits: Vec<Commit>,
months: Vec<(usize, String)>, months: Vec<(usize, String)>,
highest_count: i32, highest_count: i32,
repos: usize,
} }
impl Heatmap { impl Heatmap {
pub fn new(since: NaiveDate, until: NaiveDate, commits: Vec<Commit>) -> Self { pub fn new(since: NaiveDate, until: NaiveDate, repos: usize, commits: Vec<Commit>) -> Self {
let mut heatmap = Self { let mut heatmap = Self {
data: [vec![], vec![], vec![], vec![], vec![], vec![], vec![]], data: [vec![], vec![], vec![], vec![], vec![], vec![], vec![]],
since, since,
@ -23,6 +24,7 @@ impl Heatmap {
commits, commits,
months: vec![], months: vec![],
highest_count: 0, highest_count: 0,
repos,
}; };
let mut grouped_commits = BTreeMap::new(); let mut grouped_commits = BTreeMap::new();
@ -97,6 +99,7 @@ impl Display for Heatmap {
let commits = self.commits.len().to_string(); let commits = self.commits.len().to_string();
write!(f, "{} - {}\n", start_date, end_date).unwrap(); write!(f, "{} - {}\n", start_date, end_date).unwrap();
write!(f, "{} repos\n", self.repos).unwrap();
write!(f, "{} commits\n\n", commits).unwrap(); write!(f, "{} commits\n\n", commits).unwrap();
write!(f, "{}\n", self.months_row()).unwrap(); write!(f, "{}\n", self.months_row()).unwrap();

View File

@ -2,14 +2,14 @@
#![feature(let_chains)] #![feature(let_chains)]
#![allow(dead_code)] #![allow(dead_code)]
use std::{cmp::Reverse, collections::HashSet, sync::OnceLock}; use std::{cmp::Reverse, collections::HashSet, path::PathBuf, sync::OnceLock};
use anyhow::{Context, Result}; use anyhow::{anyhow, Context, Result};
use chrono::{DateTime, Duration, Local, NaiveDate, TimeZone}; use chrono::{DateTime, Duration, Local, NaiveDate, TimeZone};
use clap::Parser; use clap::Parser;
use gix::{bstr::ByteSlice, ObjectId, Repository}; use gix::{bstr::ByteSlice, ObjectId, Repository};
use heatmap::HeatmapColors; use heatmap::HeatmapColors;
use itertools::Itertools; use itertools::{enumerate, Itertools};
use rgb::Rgb; use rgb::Rgb;
use crate::{cli::CliArgs, heatmap::Heatmap}; use crate::{cli::CliArgs, heatmap::Heatmap};
@ -53,6 +53,8 @@ fn main() -> Result<()> {
let args = CliArgs::parse(); let args = CliArgs::parse();
// dbg!(&args);
CHAR.set(args.char).unwrap(); CHAR.set(args.char).unwrap();
let color_map = match args.color_scheme { let color_map = match args.color_scheme {
HeatmapColors::Green => GREEN_COLOR_MAP, HeatmapColors::Green => GREEN_COLOR_MAP,
@ -64,8 +66,6 @@ fn main() -> Result<()> {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
COLOR_MAP.set(color_map).unwrap(); COLOR_MAP.set(color_map).unwrap();
let repo = gix::open(&args.input).unwrap();
let since = NaiveDate::parse_from_str(&args.since, "%Y-%m-%d").unwrap(); let since = NaiveDate::parse_from_str(&args.since, "%Y-%m-%d").unwrap();
let until = args let until = args
@ -74,9 +74,9 @@ fn main() -> Result<()> {
.unwrap_or_else(|| get_default_until(since)); .unwrap_or_else(|| get_default_until(since));
let until = NaiveDate::parse_from_str(&until, "%Y-%m-%d").unwrap(); let until = NaiveDate::parse_from_str(&until, "%Y-%m-%d").unwrap();
let commits = get_commits(repo, args, since).with_context(|| "Could not fetch commit list")?; let commits = get_commits(args, since).with_context(|| "Could not fetch commit list")?;
let heatmap = Heatmap::new(since, until, commits); let heatmap = Heatmap::new(since, until, commits.0, commits.1);
println!("{heatmap}"); println!("{heatmap}");
@ -122,65 +122,85 @@ fn get_color_map() -> Vec<String> {
.to_vec() .to_vec()
} }
fn get_commits(repo: Repository, args: CliArgs, start_date: NaiveDate) -> Result<Vec<Commit>> { fn get_commits(args: CliArgs, start_date: NaiveDate) -> Result<(usize, Vec<Commit>)> {
let mut commits: HashSet<Commit> = HashSet::new(); let mut commits: HashSet<Commit> = HashSet::new();
let branches = match args.branches { let repos = match args.repos {
Some(b) => b, Some(r) => r,
None => repo None => vec![PathBuf::from(".")],
.branch_names()
.into_iter()
.map(|b| b.to_string())
.collect_vec(),
}; };
for branch in branches { let branches = args.branches.unwrap_or_else(|| vec!["@".to_string()]);
let branch_commits = repo
.rev_parse(&*branch)?
.single()
.unwrap()
.ancestors()
.all()?;
branch_commits if repos.len() > 1 && repos.len() != branches.len() {
.filter_map(|c| c.ok()) return Err(anyhow!(
.filter_map(|c| c.object().ok()) "Number of repos ({}) needs to match the number of branch lists ({})!",
.filter_map(|c| { repos.len(),
let title = c branches.len()
.message() ));
.ok()? }
.title
.trim_ascii()
.to_str()
.ok()?
.to_string();
let author = c.author().ok()?.name.to_string(); for (i, repo) in repos.iter().enumerate() {
if author != args.author { let repo = gix::open(repo).unwrap();
return None;
}
let current_time = Local::now().time(); let branch_names = &*branches[i];
let start_date = start_date.and_time(current_time); let mut branches = vec![];
let start_date = Local.from_local_datetime(&start_date).unwrap(); if branch_names.is_empty() {
branches.extend(repo.branch_names().iter());
}
else {
let branch_names = branch_names.split(' ');
branches.extend(branch_names);
}
let time = c.time().ok()?; for branch in branches {
let time = let branch_commits = repo
DateTime::from_timestamp_millis(time.seconds * 1000)?.with_timezone(&Local); .rev_parse(branch)?
if time <= start_date + Duration::days(1) { .single()
return None; .unwrap()
} .ancestors()
.all()?;
Some(Commit { branch_commits
id: c.id, .filter_map(|c| c.ok())
title, .filter_map(|c| c.object().ok())
author, .filter_map(|c| {
time, let title = c
.message()
.ok()?
.title
.trim_ascii()
.to_str()
.ok()?
.to_string();
let author = c.author().ok()?.name.to_string();
if author != args.author {
return None;
}
let current_time = Local::now().time();
let start_date = start_date.and_time(current_time);
let start_date = Local.from_local_datetime(&start_date).unwrap();
let time = c.time().ok()?;
let time =
DateTime::from_timestamp_millis(time.seconds * 1000)?.with_timezone(&Local);
if time <= start_date + Duration::days(1) {
return None;
}
Some(Commit {
id: c.id,
title,
author,
time,
})
}) })
}) .for_each(|c| {
.for_each(|c| { commits.insert(c);
commits.insert(c); });
}); }
} }
let commits = commits let commits = commits
@ -188,5 +208,5 @@ fn get_commits(repo: Repository, args: CliArgs, start_date: NaiveDate) -> Result
.sorted_by_cached_key(|a| Reverse(a.time)) .sorted_by_cached_key(|a| Reverse(a.time))
.collect_vec(); .collect_vec();
Ok(commits) Ok((repos.len(), commits))
} }