From 42114781ee9d4af802ba02607cd1af4fb839fd24 Mon Sep 17 00:00:00 2001 From: Jan Hensel Date: Thu, 2 Feb 2023 13:27:27 +0100 Subject: [PATCH] feat(timesheet): Allow specification of duration format --- internal/control/cli/timesheet.go | 35 ++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/internal/control/cli/timesheet.go b/internal/control/cli/timesheet.go index e67f8e7a..35944a0a 100644 --- a/internal/control/cli/timesheet.go +++ b/internal/control/cli/timesheet.go @@ -7,6 +7,7 @@ import ( "os" "regexp" "strings" + "time" "github.com/ja-he/dayplan/internal/config" "github.com/ja-he/dayplan/internal/control" @@ -37,6 +38,7 @@ type TimesheetCommand struct { DateFormat string `long:"date-format" value-name:"" description:"specify the date format (see )" default:"2006-01-02"` Enquote bool `long:"enquote" description:"add quotes around field values"` FieldSeparator string `long:"field-separator" value-name:"" default:","` + DurationFormat string `long:"duration-format" option:"golang" option:"colon-delimited" default:"golang"` } // Execute executes the timesheet command. @@ -161,6 +163,27 @@ func (command *TimesheetCommand) Execute(args []string) error { } } + stringifyTimestamp := func(ts model.Timestamp) string { + return ts.ToString() + } + + stringifyDuration := func(dur time.Duration) string { + switch command.DurationFormat { + case "golang": + str := dur.String() + if strings.HasSuffix(str, "m0s") { + str = strings.TrimSuffix(str, "0s") + } + return str + case "colon-delimited": + durHours := dur.Truncate(time.Hour) + durMins := (dur - durHours) + return fmt.Sprintf("%d:%02d", int(durHours.Hours()), int(durMins.Minutes())) + default: + panic("unhandled case '" + command.DurationFormat + "'") + } + } + fmt.Println( strings.Join( []string{ @@ -176,16 +199,12 @@ func (command *TimesheetCommand) Execute(args []string) error { } // asCSVString returns this TimesheetEntry in CSV format. -func asCSVString(e model.TimesheetEntry, processFieldString func(string) string, separator string) string { - dur := e.BreakDuration.String() - if strings.HasSuffix(dur, "m0s") { - dur = strings.TrimSuffix(dur, "0s") - } +func asCSVString(e model.TimesheetEntry, processFieldString func(string) string, stringifyTimestamp func(model.Timestamp) string, stringifyDuration func(time.Duration) string, separator string) string { return strings.Join( []string{ - processFieldString(e.Start.ToString()), - processFieldString(dur), - processFieldString(e.End.ToString()), + processFieldString(stringifyTimestamp(e.Start)), + processFieldString(stringifyDuration(e.BreakDuration)), + processFieldString(stringifyTimestamp(e.End)), }, separator, )