diff --git a/cmd/addTask.go b/cmd/addTask.go index 75638ad..1bc0989 100644 --- a/cmd/addTask.go +++ b/cmd/addTask.go @@ -28,33 +28,34 @@ And add a task using the editor. return err } - name := strings.Join(args, " ") - if name != "" { - err = task.AddTask(config.TaskFile, name) + var newTasks []string + + if len(args) > 0 { + newTasks = append(newTasks, strings.Join(args, " ")) + } + + if len(newTasks) == 0 { + lines, err := editor.ContentsByLine(initialText) if err != nil { return err } - fmt.Printf("add %s\n", name) - return nil - } - ts, err := editor.GetSliceText(initialText) - if err != nil { - return err - } + for _, l := range lines { + // ignore empty string and comment + if l == "" || strings.HasPrefix(l, "#") { + continue + } - for _, t := range ts { - if t == "" { - continue - } - if strings.HasPrefix(t, "#") { - continue + newTasks = append(newTasks, l) } - err = task.AddTask(config.TaskFile, t) - if err != nil { + } + + for _, newTask := range newTasks { + if err := task.AddTask(config.TaskFile, newTask); err != nil { return err } - fmt.Printf("add %s\n", t) + + fmt.Printf("added '%s'\n", newTask) } return nil diff --git a/internal/editor/editor.go b/internal/editor/editor.go index a54c5f7..ee96a1c 100644 --- a/internal/editor/editor.go +++ b/internal/editor/editor.go @@ -2,13 +2,13 @@ package editor import ( - "bufio" "os" "os/exec" + "strings" ) -// GetSliceText get slice text edited with editor. -func GetSliceText(initialText string) ([]string, error) { +// ContentsByLine gets contents edited with editor by line. +func ContentsByLine(initialText string) ([]string, error) { tmpfile, err := os.CreateTemp("", "gomodoro") if err != nil { return nil, err @@ -24,32 +24,19 @@ func GetSliceText(initialText string) ([]string, error) { return nil, err } - if err = openEditor(tmpfile.Name()); err != nil { + if err = edit(tmpfile.Name()); err != nil { return nil, err } - f, err := os.Open(tmpfile.Name()) + b, err := os.ReadFile(tmpfile.Name()) if err != nil { return nil, err } - defer func() { - _ = f.Close() - }() - - ts := make([]string, 0) - scanner := bufio.NewScanner(f) - for scanner.Scan() { - ts = append(ts, scanner.Text()) - } - - if err := scanner.Err(); err != nil { - return nil, err - } - return ts, nil + return strings.Split(string(b), "\n"), nil } -func openEditor(filepath string) error { +func edit(filepath string) error { cmdName := "vi" if e := os.Getenv("EDITOR"); e != "" { cmdName = e