Created
April 10, 2020 11:10
-
-
Save JohnMertz/39306b25eada1e658338ef5f434ee629 to your computer and use it in GitHub Desktop.
Simple weekly streak counter script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
# Manually trigger with `$0 -a` to log an exercise event for the day. | |
# Automatically run each morning with `$0 -c` to cycle out old data | |
# Simply outputs Bool for event today, count for the last 7 days and the goal | |
# Meant for a simple indicator widget so I know if a streak is at risk | |
use JSON::XS; | |
use Date::Calc; | |
my $out = '/path/to/outfile.json'; | |
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); | |
$year += 1900; | |
my $today = "$year-" . leading_zero($mon+1) . "-" . leading_zero($mday); | |
my $start_day; | |
if ($mday < 6) { | |
if ($mon > 0) { | |
$start_day = "$year-" . leading_zero($mon) . "-" . ($previous_days-$mstart+1); | |
} else { | |
$start_day = ($year-1) . "-12-" . (Date::Calc::Days_in_Month($year,$month+1)+$mday-6); | |
} | |
} else { | |
$start_day = $year . "-" . leading_zero($mon+1) . "-" . ($mday-6); | |
} | |
unless (scalar @ARGV == 1 && ($ARGV[0] eq '-a' || $ARGV[0] eq '-c')) { | |
die "Requires exactly one argument: | |
-a Add event for today | |
-c Cycle day\n"; | |
} | |
open(my $fh, "<", $out) or die "$!"; | |
while (<$fh>) { | |
$json = $json . $_; | |
chomp $json; | |
} | |
close $fh; | |
my %data; | |
if ($json) { | |
%data = %{decode_json($json)}; | |
} else { | |
%data = ( | |
'goal' => 4, | |
'today' => 0, | |
'events'=> [] | |
); | |
} | |
my @events = (); | |
my $today_hit = 0; | |
foreach my $event (@{$data{events}}) { | |
if ($event ge $start_day) { | |
push @events, $event; | |
} | |
if ($event eq $today) { | |
$today_hit = 1; | |
} | |
} | |
if ($ARGV[0] eq '-a') { | |
if ($today_hit) { | |
$data{today} = 1; | |
} else { | |
$data{today} = 1; | |
push @events, $today; | |
} | |
} else { | |
if ($today_hit) { | |
$data{today} = 1; | |
} | |
} | |
$data{events} = \@events; | |
open(my $fh, ">", $out) or die "$!"; | |
print $fh encode_json(\%data); | |
close($fh); | |
sub leading_zero { | |
my $in = shift; | |
if (length($in) == 1) { | |
$in = "0" . $in; | |
} | |
return $in; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment