diff --git a/sort.go b/sort.go index acd074f..1dcf7ab 100644 --- a/sort.go +++ b/sort.go @@ -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 { diff --git a/todolist.go b/todolist.go index 58aa5e3..17dcd79 100644 --- a/todolist.go +++ b/todolist.go @@ -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,7 +274,11 @@ func (todolist *TodoList) WriteToFile(file *os.File) error { writer := bufio.NewWriter(file) _, err := writer.WriteString(todolist.String()) writer.Flush() - return err + if err != nil { + return err + } + todolist.ResetIds() + return nil } // LoadFromFilename loads a TodoList from the filename. @@ -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.