Add some more functions for helping out

This commit is contained in:
Brian Buller 2019-02-25 16:04:10 -06:00
parent 43d7a5806b
commit 96a75b058d
2 changed files with 56 additions and 4 deletions

View File

@ -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
}

View File

@ -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
}
return &t
if t.FinishDate.Before(end) && t.FinishDate.After(start) {
return true
}
return false
}
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 {