Skip to content

Commit

Permalink
feat(timesheet): Allow specification of duration format
Browse files Browse the repository at this point in the history
  • Loading branch information
ja-he committed Nov 26, 2023
1 parent 32daa5d commit 4211478
Showing 1 changed file with 27 additions and 8 deletions.
35 changes: 27 additions & 8 deletions internal/control/cli/timesheet.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"regexp"
"strings"
"time"

"github.com/ja-he/dayplan/internal/config"
"github.com/ja-he/dayplan/internal/control"
Expand Down Expand Up @@ -37,6 +38,7 @@ type TimesheetCommand struct {
DateFormat string `long:"date-format" value-name:"<format>" description:"specify the date format (see <https://pkg.go.dev/time#pkg-constants>)" default:"2006-01-02"`
Enquote bool `long:"enquote" description:"add quotes around field values"`
FieldSeparator string `long:"field-separator" value-name:"<CSV separator (default ',')>" default:","`
DurationFormat string `long:"duration-format" option:"golang" option:"colon-delimited" default:"golang"`
}

// Execute executes the timesheet command.
Expand Down Expand Up @@ -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{
Expand All @@ -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,
)
Expand Down

0 comments on commit 4211478

Please sign in to comment.