Id should always represent position in file

This commit is contained in:
Brian Buller 2023-09-07 13:06:40 -05:00
parent 8a9e6c2bec
commit 6ea3390313
2 changed files with 32 additions and 7 deletions

View File

@ -34,9 +34,6 @@ func (timerlist *TimerList) Sort(sortFlag int) error {
}
func (timerlist *TimerList) refresh() {
timerlist.Sort(timerlist.SortFlag)
for i, t := range timerlist.Timers {
t.Id = i
}
}
type timerlistSort struct {

View File

@ -184,6 +184,16 @@ func (timerlist *TimerList) GetActiveTimers() *TimerList {
return &t
}
func (timerlist *TimerList) GetNextId() int {
nextId := 0
for _, v := range timerlist.Timers {
if v.Id > nextId {
nextId = v.Id
}
}
return nextId + 1
}
// String returns a complete list of timers in timer.txt format.
func (timerlist *TimerList) String() string {
var ret string
@ -195,14 +205,16 @@ func (timerlist *TimerList) String() string {
// AddTimer prepends a Timer to the current TimerList and takes care to set the Timer.Id correctly
func (timerlist *TimerList) AddTimer(timer *Timer) {
timer.Id = timerlist.GetNextId()
timerlist.Timers = append(timerlist.Timers, timer)
timerlist.refresh()
}
// AddTimers adds all passed in timers to the list, sorts the list, then updates the Timer.Id values.
func (timerlist *TimerList) AddTimers(timers []*Timer) {
timerlist.Timers = append(timerlist.Timers, timers...)
timerlist.Sort(SortStartDateAsc)
for _, v := range timers {
timerlist.AddTimer(v)
}
}
func (timerlist *TimerList) Combine(other *TimerList) { timerlist.AddTimers(other.Timers) }
@ -285,6 +297,14 @@ func (timerlist *TimerList) Filter(predicate func(*Timer) bool) *TimerList {
return &newList
}
func (timerlist *TimerList) ResetIds() {
timerId := 1
for _, v := range timerlist.Timers {
v.Id = timerId
timerId++
}
}
// LoadFromFile loads a TimerList from *os.File.
// Note: This will clear the current TimerList and overwrite it's contents with whatever is in *os.File.
func (timerlist *TimerList) LoadFromFile(file *os.File) error {
@ -317,8 +337,12 @@ func (timerlist *TimerList) WriteToFile(file *os.File) error {
writer := bufio.NewWriter(file)
_, err := writer.WriteString(timerlist.String())
writer.Flush()
if err != nil {
return err
}
timerlist.ResetIds()
return nil
}
// LoadFromFilename loads a TimerList from the filename.
func (timerlist *TimerList) LoadFromFilename(filename string) error {
@ -332,7 +356,11 @@ func (timerlist *TimerList) LoadFromFilename(filename string) error {
// WriteToFilename writes a TimerList to the specified file (most likely called "timer.txt").
func (timerlist *TimerList) WriteToFilename(filename string) error {
return ioutil.WriteFile(filename, []byte(timerlist.String()), 0640)
if err := ioutil.WriteFile(filename, []byte(timerlist.String()), 0640); err != nil {
return err
}
timerlist.ResetIds()
return nil
}
// LoadFromFile loads and returns a TimerList from *os.File.