From 96a75b058d8ca8727b4a34abd1f06881b124cad9 Mon Sep 17 00:00:00 2001 From: Brian Buller Date: Mon, 25 Feb 2019 16:04:10 -0600 Subject: [PATCH] Add some more functions for helping out --- timer.go | 18 ++++++++++++++++++ timerlist.go | 42 ++++++++++++++++++++++++++++++++++++++---- 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/timer.go b/timer.go index c7c059b..cb4e4c1 100644 --- a/timer.go +++ b/timer.go @@ -173,3 +173,21 @@ func (timer *Timer) ActiveOnDay(t time.Time) bool { // Otherwise, if StartDate is before t and FinishDate is after t return timer.StartDate.Before(t) && timer.FinishDate.After(t) } + +func (timer *Timer) HasContext(context string) bool { + for _, v := range timer.Contexts { + if v == context { + return true + } + } + return false +} + +func (timer *Timer) HasProject(project string) bool { + for _, v := range timer.Projects { + if v == project { + return true + } + } + return false +} diff --git a/timerlist.go b/timerlist.go index 0bde275..4268cc3 100644 --- a/timerlist.go +++ b/timerlist.go @@ -7,6 +7,7 @@ import ( "io/ioutil" "os" "strings" + "time" ) // TimerList represents a list of timer.txt timer entries. @@ -19,11 +20,28 @@ func NewTimerList() *TimerList { } func (timerlist *TimerList) GetTimersInRange(start, end time.Time) *TimerList { - t := *NewTimerList() - for _, v := range *timerlist { - if v.FinishDate.Before(end) && + fltr := func(t Timer) bool { + if t.StartDate.Before(end) && t.StartDate.After(start) { + return true + } + if t.FinishDate.Before(end) && t.FinishDate.After(start) { + return true + } + return false } - return &t + return timerlist.Filter(fltr) +} + +func (timerlist *TimerList) GetTimersWithContext(context string) *TimerList { + return timerlist.Filter(func(t Timer) bool { + return t.HasContext(context) + }) +} + +func (timerlist *TimerList) GetTimersWithProject(project string) *TimerList { + return timerlist.Filter(func(t Timer) bool { + return t.HasProject(project) + }) } func (timerlist *TimerList) GetActiveTimers() *TimerList { @@ -106,6 +124,22 @@ func (timerlist *TimerList) RemoveTimer(timer Timer) error { return nil } +// ArchiveTimerToFile removes the timer from the active list and concatenates it to +// the passed in filename +// Return an err if any part of that fails +func (timerlist *TimerList) ArchiveTimerToFile(timer Timer, filename string) error { + if err := timerlist.RemoveTimer(timer); err != nil { + return err + } + f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + return err + } + defer f.Close() + _, err = f.WriteString(timer.String() + "\n") + return err +} + // Filter filters the current TimerList for the given predicate (a function that takes a timer as input and returns a // bool), and returns a new TimerList. The original TimerList is not modified. func (timerlist *TimerList) Filter(predicate func(Timer) bool) *TimerList {