From bfdeebb7a2c336ffb0f1a19a937af57cc946530c Mon Sep 17 00:00:00 2001 From: Bel LaPointe Date: Mon, 6 Nov 2023 13:06:11 -0700 Subject: [PATCH] use pttodo.Todos.Like...() --- cmd/dump.go | 28 ++-------------------------- pttodo/todos.go | 36 ++++++++++++++++++++++++++++++++++++ pttodo/todos_test.go | 17 +++++++++++++++++ 3 files changed, 55 insertions(+), 26 deletions(-) create mode 100644 pttodo/todos.go create mode 100644 pttodo/todos_test.go diff --git a/cmd/dump.go b/cmd/dump.go index 0394c75..9ab2937 100644 --- a/cmd/dump.go +++ b/cmd/dump.go @@ -4,7 +4,6 @@ import ( "fmt" "io" "os" - "strings" "gogs.inhome.blapointe.com/bel/pttodo/pttodo" "gopkg.in/yaml.v2" @@ -31,31 +30,8 @@ func _dump(writer io.Writer, filepaths []string, tags []string, search, rootDisp v = root.Done } if todos, ok := v.([]pttodo.Todo); ok { - if len(tags) > 0 { - result := make([]pttodo.Todo, 0, len(todos)) - for _, todo := range todos { - skip := false - for _, tag := range tags { - positiveTag := strings.TrimLeft(tag, "-") - hasTag := strings.Contains(todo.Tags, positiveTag) - wantToHaveTag := !strings.HasPrefix(tag, "-") - skip = skip || !(hasTag == wantToHaveTag) - } - if !skip { - result = append(result, todo) - } - } - todos = result - } - if len(search) > 0 { - result := make([]pttodo.Todo, 0, len(todos)) - for _, todo := range todos { - if strings.Contains(strings.ToLower(fmt.Sprint(todo)), strings.ToLower(search)) { - result = append(result, todo) - } - } - todos = result - } + todos = pttodo.Todos(todos).LikeTags(tags) + todos = pttodo.Todos(todos).LikeSearch(search) v = todos } diff --git a/pttodo/todos.go b/pttodo/todos.go new file mode 100644 index 0000000..9a94cd0 --- /dev/null +++ b/pttodo/todos.go @@ -0,0 +1,36 @@ +package pttodo + +import "strings" + +type Todos []Todo + +func (todos Todos) LikeSearch(search string) Todos { + return todos.Like(func(todo Todo) bool { + return strings.Contains( + strings.ToLower(todo.Todo), + strings.ToLower(search), + ) + }) +} + +func (todos Todos) LikeTags(tags []string) Todos { + return todos.Like(func(todo Todo) bool { + matches := true + for _, tag := range tags { + str := strings.TrimLeft(tag, "-") + want := !strings.HasPrefix(tag, "-") + matches = matches && strings.Contains(todo.Tags, str) == want + } + return matches + }) +} + +func (todos Todos) Like(like func(Todo) bool) Todos { + result := make(Todos, 0) + for i := range todos { + if like(todos[i]) { + result = append(result, todos[i]) + } + } + return result +} diff --git a/pttodo/todos_test.go b/pttodo/todos_test.go new file mode 100644 index 0000000..b3ba982 --- /dev/null +++ b/pttodo/todos_test.go @@ -0,0 +1,17 @@ +package pttodo + +import "testing" + +func TestTodosLikeTags(t *testing.T) { + todos := Todos{ + {Todo: "a", Tags: "x"}, + {Todo: "b", Tags: "x,y"}, + } + + result := todos.LikeTags([]string{"x", "-y"}) + if len(result) != 1 { + t.Error(result) + } else if result[0].Todo != "a" { + t.Error(result[0].Todo) + } +}