Id should always represent position in file

This commit is contained in:
Brian Buller 2023-09-07 13:06:22 -05:00
parent 82c2932988
commit 73e7cad897
2 changed files with 32 additions and 7 deletions

View File

@ -37,9 +37,6 @@ func (todolist *TodoList) Sort(sortFlag int) error {
}
func (todolist *TodoList) refresh() {
todolist.Sort(todolist.SortFlag)
for i, t := range todolist.Todos {
t.Id = i
}
}
type todolistSort struct {

View File

@ -121,6 +121,16 @@ func (todolist *TodoList) GetIncompleteTasks() *TodoList {
return &t
}
func (todolist *TodoList) GetNextId() int {
nextId := 0
for _, v := range todolist.Todos {
if v.Id > nextId {
nextId = v.Id
}
}
return nextId + 1
}
// String returns a complete list of tasks in todo.txt format.
func (todolist *TodoList) String() string {
var ret string
@ -132,14 +142,16 @@ func (todolist *TodoList) String() string {
// AddTodo prepends a Todo to the current TodoList and takes care to set the Todo.Id correctly
func (todolist *TodoList) AddTodo(todo *Todo) {
todo.Id = todolist.GetNextId()
todolist.Todos = append(todolist.Todos, todo)
todolist.refresh()
}
// AddTimers adds all passed in timers to the list, sorts the list, then updates the Timer.Id values.
func (todolist *TodoList) AddTodos(todos []*Todo) {
todolist.Todos = append(todolist.Todos, todos...)
todolist.Sort(SortCompletedDateDesc)
for _, v := range todos {
todolist.AddTodo(v)
}
}
func (todolist *TodoList) Combine(other *TodoList) { todolist.AddTodos(other.Todos) }
@ -222,6 +234,14 @@ func (todolist *TodoList) Filter(predicate func(*Todo) bool) *TodoList {
return &newList
}
func (todolist *TodoList) ResetIds() {
todoId := 1
for _, v := range todolist.Todos {
v.Id = todoId
todoId++
}
}
// LoadFromFile loads a TodoList from *os.File.
// Note: This will clear the current TodoList and overwrite it's contents with whatever is in *os.File.
func (todolist *TodoList) LoadFromFile(file *os.File) error {
@ -254,8 +274,12 @@ func (todolist *TodoList) WriteToFile(file *os.File) error {
writer := bufio.NewWriter(file)
_, err := writer.WriteString(todolist.String())
writer.Flush()
if err != nil {
return err
}
todolist.ResetIds()
return nil
}
// LoadFromFilename loads a TodoList from the filename.
func (todolist *TodoList) LoadFromFilename(filename string) error {
@ -269,7 +293,11 @@ func (todolist *TodoList) LoadFromFilename(filename string) error {
// WriteToFilename writes a TodoList to the specified file (most likely called "todo.txt").
func (todolist *TodoList) WriteToFilename(filename string) error {
return ioutil.WriteFile(filename, []byte(todolist.String()), 0640)
if err := ioutil.WriteFile(filename, []byte(todolist.String()), 0640); err != nil {
return err
}
todolist.ResetIds()
return nil
}
// LoadFromFile loads and returns a TodoList from *os.File.