Skip to content

Commit

Permalink
Improve editor package and add-task command
Browse files Browse the repository at this point in the history
  • Loading branch information
hatappi committed Jun 11, 2024
1 parent f86ef0b commit 5208427
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 39 deletions.
39 changes: 20 additions & 19 deletions cmd/addTask.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 7 additions & 20 deletions internal/editor/editor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit 5208427

Please sign in to comment.