Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug and style report from Shreq on Reddit #1

Open
linden2015 opened this issue Mar 29, 2020 · 0 comments
Open

Bug and style report from Shreq on Reddit #1

linden2015 opened this issue Mar 29, 2020 · 0 comments

Comments

@linden2015
Copy link
Owner

Feedback at:
https://www.reddit.com/r/commandline/comments/fqrxg7/clockout_a_bash_script_to_calculate_totals_of_a/flsgqqt/

awk refactor at:
https://termbin.com/vjki
(copied because termbin expires)

#!/usr/bin/awk -f

function error(text)
{
	printf "%s: Error: %s\n", ARGV[0], text >"/dev/stderr"
	has_error=1
	exit(1)
}

function to_mins(time,    arr, hours, minutes)
{
	split(time, arr, ":")
	hours=arr[1]; minutes=arr[2]

	return hours * 60 + minutes
}

function time_diff(a, b,    diff)
{
	diff=to_mins(b) - to_mins(a)

	if (diff < 0)
		diff+=1440

	return diff
}

function pluralize(num, str)
{
	return (num " " str) (num != 1 ? "s" : "")
}

function pretty_time(mins,    hours, minutes, str)
{
	if ((hours=int(mins / 60)) > 0)
		str=" " pluralize(hours, "hr")
	if ((minutes=int(mins % 60)) > 0)
		str=str " " pluralize(minutes, "min")

	return str
}

function valid_time(time)
{
	return (time ~ /^([01]?[0-9]|2[0-4]):[0-5][0-9]$/)
}

{
	if (NF != 3 || !valid_time($2) || !valid_time($3))
		error("input file has incorrect format on line: " NR)

	categories[$1]=categories[$1] " " $2 "-" $3
}

END {
	if (has_error)
		exit(1)

	for (category in categories) {
		category_total=0

		split(categories[category], times)
		for (time in times) {
			split(times[time], arr, "-")
			from=arr[1]; to=arr[2]
			duration=time_diff(from, to)
			category_total+=duration

			printf "%-50s%5s\t%5s\t%d\n", \
				category, from, to, duration
		}
		total+=category_total
		if (category_total > duration)
			printf "└ Total: %d\n", category_total

		print ""
	}
	printf "Total:%s\n", pretty_time(total)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant