Compare commits

..

No commits in common. "893947b6ec05b60d046bd03fd0bd6eb60bb6d469" and "de4143ed812fb24b5ce966f7ba37593a1a52a036" have entirely different histories.

3 changed files with 153 additions and 160 deletions

View File

@ -1,6 +1,5 @@
use std::path::PathBuf; use std::path::PathBuf;
use chrono::{Duration, Local};
use clap::{arg, Parser, ValueHint}; use clap::{arg, Parser, ValueHint};
use crate::heatmap::HeatmapColors; use crate::heatmap::HeatmapColors;
@ -19,18 +18,6 @@ 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, default_value = "24")]
#[arg(short, long, num_args(0..))] // pub split: u32,
pub branches: Option<Vec<String>>,
#[arg(long("since"), default_value_t = get_since_date())]
pub since: String,
#[arg(long("until"))]
pub until: Option<String>,
}
fn get_since_date() -> String {
let date = Local::now() - Duration::days(365);
date.format("%Y-%m-%d").to_string()
} }

View File

@ -1,28 +1,30 @@
use std::{collections::BTreeMap, fmt::Display}; use std::collections::BTreeMap;
use chrono::{Datelike, Duration, NaiveDate}; use chrono::{DateTime, Datelike, Duration, Local, Utc};
use clap::ValueEnum; use clap::ValueEnum;
use crate::{get_char, get_color, get_color_map, Commit, DAYS, RESET}; use crate::{get_char, get_color, get_color_map, Commit, DAYS, RESET};
pub struct Heatmap { pub struct Heatmap {
data: [Vec<i32>; 7], data: [Vec<u32>; 7],
since: NaiveDate, start_date: DateTime<Local>,
until: NaiveDate, end_date: DateTime<Local>,
commits: Vec<Commit>, commits: Vec<Commit>,
months: Vec<(usize, String)>, months: Vec<(usize, String)>,
highest_count: i32,
} }
impl Heatmap { impl Heatmap {
pub fn new(since: NaiveDate, until: NaiveDate, commits: Vec<Commit>) -> Self { pub fn new(
start_date: DateTime<Local>,
end_date: DateTime<Local>,
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, start_date,
until, end_date,
commits, commits,
months: vec![], months: vec![],
highest_count: 0,
}; };
let mut grouped_commits = BTreeMap::new(); let mut grouped_commits = BTreeMap::new();
@ -33,19 +35,19 @@ impl Heatmap {
*record += 1; *record += 1;
} }
let mut current_day = since; let mut current_day = start_date;
let mut day_of_week = current_day.weekday().num_days_from_monday() % 7; let mut day_of_week = (current_day.weekday().num_days_from_monday()) % 7;
if day_of_week != 0 { if day_of_week != 0 {
for i in 0..day_of_week { for i in 0..day_of_week {
heatmap.data[i as usize].push(-1); heatmap.data[i as usize].push(0);
} }
} }
while current_day <= until { while current_day <= end_date {
let month_name = current_day.format("%b").to_string(); let month_name = current_day.format("%b").to_string();
if current_day == since { if current_day == start_date {
heatmap.months.push((0, month_name)); heatmap.months.push((0, month_name));
} }
else if current_day.day0() == 0 { else if current_day.day0() == 0 {
@ -54,17 +56,12 @@ impl Heatmap {
.push((heatmap.data[day_of_week as usize].len(), month_name)); .push((heatmap.data[day_of_week as usize].len(), month_name));
} }
let value = grouped_commits.get(&current_day); let value = grouped_commits.get(&current_day.date_naive());
match value { match value {
Some(val) => { Some(val) => heatmap.data[day_of_week as usize].push(*val),
heatmap.data[day_of_week as usize].push(*val);
if *val > heatmap.highest_count {
heatmap.highest_count = *val;
}
}
None => heatmap.data[day_of_week as usize].push(0), None => heatmap.data[day_of_week as usize].push(0),
} }
// println!("{} {value:?}", current_day); // println!("{} {value:?}", current_day.date_naive());
current_day += Duration::days(1); current_day += Duration::days(1);
day_of_week = current_day.weekday().num_days_from_monday() % 7; day_of_week = current_day.weekday().num_days_from_monday() % 7;
} }
@ -88,42 +85,28 @@ impl Heatmap {
row row
} }
}
impl Display for Heatmap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let start_date = self.since.format("%Y-%b-%d").to_string();
let end_date = self.until.format("%Y-%b-%d").to_string();
let commits = self.commits.len().to_string();
write!(f, "{} - {}\n", start_date, end_date).unwrap();
write!(f, "{} commits\n\n", commits).unwrap();
write!(f, "{}\n", self.months_row()).unwrap();
pub fn print(&self) {
println!(
"{} - {}",
self.start_date.format("%Y-%b-%d"),
self.end_date.format("%Y-%b-%d")
);
println!("{} commits\n", &self.commits.len());
println!("{}", self.months_row());
for (day, row) in DAYS.iter().zip(&self.data) { for (day, row) in DAYS.iter().zip(&self.data) {
write!(f, "{day} ").unwrap(); print!("{day} ");
for val in row { for val in row {
match val { let color = &get_color_map()[get_color(*val)];
x if *x >= 0 => { print!("{color}{}{RESET} ", get_char());
let color = &get_color_map()[get_color(*val, self.highest_count)];
write!(f, "{color}{}{RESET} ", get_char()).unwrap();
} }
x if *x < 0 => { print!("\n");
write!(f, "{RESET} ").unwrap();
} }
_ => {} print!("\nLess ");
}
}
write!(f, "\n").unwrap();
}
write!(f, "\nLess ").unwrap();
for color in get_color_map() { for color in get_color_map() {
write!(f, "{color}{}{RESET} ", get_char()).unwrap(); print!("{color}{}{RESET} ", get_char())
} }
write!(f, " More\n").unwrap(); print!(" More\n");
Ok(())
} }
} }

View File

@ -2,14 +2,13 @@
#![feature(let_chains)] #![feature(let_chains)]
#![allow(dead_code)] #![allow(dead_code)]
use std::{cmp::Reverse, collections::HashSet, sync::OnceLock}; use std::{cmp::Reverse, sync::OnceLock};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use chrono::{DateTime, Duration, Local, NaiveDate, TimeZone}; use chrono::{Date, DateTime, Datelike, Duration, Local, NaiveDate, Offset, TimeZone, Utc};
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 rgb::Rgb; use rgb::Rgb;
use crate::{cli::CliArgs, heatmap::Heatmap}; use crate::{cli::CliArgs, heatmap::Heatmap};
@ -29,7 +28,7 @@ const GREEN_COLOR_MAP: [Rgb; 5] = [
Rgb(14, 68, 41), Rgb(14, 68, 41),
Rgb(0, 109, 50), Rgb(0, 109, 50),
Rgb(38, 166, 65), Rgb(38, 166, 65),
Rgb(25, 255, 64), Rgb(57, 211, 83),
]; ];
const RED_COLOR_MAP: [Rgb; 5] = [ const RED_COLOR_MAP: [Rgb; 5] = [
@ -37,10 +36,9 @@ const RED_COLOR_MAP: [Rgb; 5] = [
Rgb(208, 169, 35), Rgb(208, 169, 35),
Rgb(208, 128, 35), Rgb(208, 128, 35),
Rgb(208, 78, 35), Rgb(208, 78, 35),
Rgb(255, 0, 0), Rgb(208, 35, 64),
]; ];
#[derive(PartialEq, Eq, Hash)]
struct Commit { struct Commit {
id: ObjectId, id: ObjectId,
title: String, title: String,
@ -66,39 +64,25 @@ fn main() -> Result<()> {
let repo = gix::open(&args.input).unwrap(); let repo = gix::open(&args.input).unwrap();
let since = NaiveDate::parse_from_str(&args.since, "%Y-%m-%d").unwrap(); let end_date = Local::now();
let start_date = end_date - Duration::days(365);
let until = args let commits =
.until get_commits(repo, args, start_date).with_context(|| "Could not fetch commit list")?;
.clone()
.unwrap_or_else(|| get_default_until(since));
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 heatmap = Heatmap::new(start_date, end_date, commits);
heatmap.print();
let heatmap = Heatmap::new(since, until, commits);
println!("{heatmap}");
Ok(()) Ok(())
} }
fn get_default_until(since: NaiveDate) -> String { fn get_color(val: u32) -> usize {
let mut until = Local::now().date_naive(); match val {
if since + Duration::days(365) < until { 0 => 0,
until = since + Duration::days(365); x if x < 2 => 1,
} x if x < 4 => 2,
until.format("%Y-%m-%d").to_string() x if x < 6 => 3,
} x if x > 8 => 4,
fn get_color(val: i32, high: i32) -> usize {
let color = val as f32 / high as f32;
match color {
0.0 => 0,
x if x <= 0.2 => 1,
x if x <= 0.4 => 2,
x if x <= 0.8 => 3,
x if x > 0.8 => 4,
_ => 0, _ => 0,
} }
} }
@ -122,27 +106,16 @@ 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(
let mut commits: HashSet<Commit> = HashSet::new(); repo: Repository,
args: CliArgs,
let branches = match args.branches { start_date: DateTime<Local>,
Some(b) => b, ) -> Result<Vec<Commit>> {
None => repo let mut commits: Vec<Commit> = repo
.branch_names() .head()?
.into_iter() .into_peeled_id()?
.map(|b| b.to_string())
.collect_vec(),
};
for branch in branches {
let branch_commits = repo
.rev_parse(&*branch)?
.single()
.unwrap()
.ancestors() .ancestors()
.all()?; .all()?
branch_commits
.filter_map(|c| c.ok()) .filter_map(|c| c.ok())
.filter_map(|c| c.object().ok()) .filter_map(|c| c.object().ok())
.filter_map(|c| { .filter_map(|c| {
@ -160,13 +133,10 @@ fn get_commits(repo: Repository, args: CliArgs, start_date: NaiveDate) -> Result
return None; 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 = c.time().ok()?;
let time = // let offset = Local.timestamp_opt(0, 0).unwrap().offset().fix();
DateTime::from_timestamp_millis(time.seconds * 1000)?.with_timezone(&Local); // let time = Local::now() - Duration::seconds(time.seconds);
let time = DateTime::from_timestamp_millis(time.seconds * 1000)?.with_timezone(&Local);
if time <= start_date + Duration::days(1) { if time <= start_date + Duration::days(1) {
return None; return None;
} }
@ -178,15 +148,68 @@ fn get_commits(repo: Repository, args: CliArgs, start_date: NaiveDate) -> Result
time, time,
}) })
}) })
.for_each(|c| { .collect();
commits.insert(c);
});
}
let commits = commits commits.sort_by_cached_key(|a| Reverse(a.time));
.into_iter()
.sorted_by_cached_key(|a| Reverse(a.time))
.collect_vec();
Ok(commits) Ok(commits)
} }
// fn print_streak(commits: Vec<Commit>) {
// let mut commits_pushed = 0;
// let mut days_streak = 0;
// let mut last_date: Option<DateTime<Utc>> = None;
// let mut start_date: Option<DateTime<Utc>> = None;
// let mut end_date: Option<DateTime<Utc>> = None;
//
// for commit in commits {
// match last_date {
// Some(date) => {
// let day = date.ordinal0();
// let commit_day = commit.time.ordinal0();
// let time_diff = date - commit.time;
//
// if commit_day != day {
// days_streak += 1;
// }
//
// if time_diff.num_hours() >= 24 {
// // println!(
// // "Failing Commit\n{} - {} {} hours difference",
// // commit.id,
// // commit.time.to_rfc3339(),
// // time_diff.num_hours()
// // );
// break;
// }
//
// commits_pushed += 1;
// last_date = Some(commit.time);
// end_date = Some(commit.time);
//
// // println!(
// // "{} - {} {} hours difference",
// // commit.id,
// // commit.time.to_rfc3339(),
// // time_diff.num_hours()
// // );
// }
// None => {
// last_date = Some(commit.time);
// start_date = Some(commit.time);
// // println!("First Commit\n{} - {}", commit.id, commit.time.to_rfc3339());
// continue;
// }
// }
// }
//
// println!("{commits_pushed} commits pushed during a {days_streak} days streak");
// if let Some(start_date) = start_date
// && let Some(end_date) = end_date
// {
// let start_date = start_date.format("%d-%b-%Y").to_string();
// let end_date = end_date.format("%d-%b-%Y").to_string();
//
// println!("Between: {start_date} {end_date}");
// }
// }