1// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
2//
3// SPDX-License-Identifier: AGPL-3.0-or-later
4
5package task
6
7import (
8 "bufio"
9 "errors"
10 "fmt"
11 "os"
12 "strings"
13
14 "git.secluded.site/go-lunatask"
15 "git.secluded.site/lune/internal/client"
16 "git.secluded.site/lune/internal/completion"
17 "git.secluded.site/lune/internal/config"
18 "git.secluded.site/lune/internal/dateutil"
19 "git.secluded.site/lune/internal/ui"
20 "git.secluded.site/lune/internal/validate"
21 "github.com/spf13/cobra"
22)
23
24// ErrUnknownGoal indicates the specified goal key was not found in config.
25var ErrUnknownGoal = errors.New("unknown goal key")
26
27// ErrNoInput indicates no input was provided on stdin.
28var ErrNoInput = errors.New("no input provided on stdin")
29
30// AddCmd creates a new task. Exported for use by the add shortcut.
31var AddCmd = &cobra.Command{
32 Use: "add NAME",
33 Short: "Create a new task",
34 Long: `Create a new task in Lunatask.
35
36The task name is required. Use flags to set additional properties.
37Use "-" as NAME to read the task name from stdin.`,
38 Args: cobra.MinimumNArgs(1),
39 RunE: runAdd,
40}
41
42func init() {
43 AddCmd.Flags().StringP("area", "a", "", "Area key (from config)")
44 AddCmd.Flags().StringP("goal", "g", "", "Goal key (from config)")
45 AddCmd.Flags().StringP("status", "s", "", "Status: later, next, in-progress, waiting")
46 AddCmd.Flags().StringP("note", "n", "", "Task note (use - for stdin)")
47 AddCmd.Flags().StringP("priority", "p", "", "Priority: lowest, low, normal, high, highest")
48 AddCmd.Flags().IntP("estimate", "e", 0, "Estimate in minutes (0-720)")
49 AddCmd.Flags().StringP("motivation", "m", "", "Motivation: must, should, want")
50 AddCmd.Flags().Bool("important", false, "Mark as important (Eisenhower matrix)")
51 AddCmd.Flags().Bool("not-important", false, "Mark as not important")
52 AddCmd.Flags().Bool("urgent", false, "Mark as urgent (Eisenhower matrix)")
53 AddCmd.Flags().Bool("not-urgent", false, "Mark as not urgent")
54 AddCmd.Flags().String("schedule", "", "Schedule date (YYYY-MM-DD)")
55
56 _ = AddCmd.RegisterFlagCompletionFunc("area", completion.Areas)
57 _ = AddCmd.RegisterFlagCompletionFunc("goal", completion.Goals)
58 _ = AddCmd.RegisterFlagCompletionFunc("status", completion.TaskStatuses)
59 _ = AddCmd.RegisterFlagCompletionFunc("priority", completion.Priorities)
60 _ = AddCmd.RegisterFlagCompletionFunc("motivation", completion.Motivations)
61}
62
63func runAdd(cmd *cobra.Command, args []string) error {
64 name, err := resolveName(args[0])
65 if err != nil {
66 return err
67 }
68
69 apiClient, err := client.New()
70 if err != nil {
71 return err
72 }
73
74 builder := apiClient.NewTask(name)
75
76 if err := applyAreaAndGoal(cmd, builder); err != nil {
77 return err
78 }
79
80 if err := applyOptionalFlags(cmd, builder); err != nil {
81 return err
82 }
83
84 task, err := ui.Spin("Creating task…", func() (*lunatask.Task, error) {
85 return builder.Create(cmd.Context())
86 })
87 if err != nil {
88 return err
89 }
90
91 fmt.Fprintln(cmd.OutOrStdout(), ui.Success.Render("Created task: "+task.ID))
92
93 return nil
94}
95
96func resolveName(arg string) (string, error) {
97 if arg != "-" {
98 return arg, nil
99 }
100
101 scanner := bufio.NewScanner(os.Stdin)
102 if scanner.Scan() {
103 return strings.TrimSpace(scanner.Text()), nil
104 }
105
106 if err := scanner.Err(); err != nil {
107 return "", fmt.Errorf("reading stdin: %w", err)
108 }
109
110 return "", ErrNoInput
111}
112
113func applyAreaAndGoal(cmd *cobra.Command, builder *lunatask.TaskBuilder) error {
114 areaKey, _ := cmd.Flags().GetString("area")
115 goalKey, _ := cmd.Flags().GetString("goal")
116
117 if areaKey == "" && goalKey == "" {
118 return nil
119 }
120
121 if areaKey == "" && goalKey != "" {
122 fmt.Fprintln(cmd.ErrOrStderr(), ui.Warning.Render("Goal specified without area; ignoring"))
123
124 return nil
125 }
126
127 cfg, err := config.Load()
128 if err != nil {
129 return err
130 }
131
132 area := cfg.AreaByKey(areaKey)
133 if area == nil {
134 return fmt.Errorf("%w: %s", ErrUnknownArea, areaKey)
135 }
136
137 builder.InArea(area.ID)
138
139 if goalKey == "" {
140 return nil
141 }
142
143 goal := area.GoalByKey(goalKey)
144 if goal == nil {
145 return fmt.Errorf("%w: %s", ErrUnknownGoal, goalKey)
146 }
147
148 builder.InGoal(goal.ID)
149
150 return nil
151}
152
153func applyOptionalFlags(cmd *cobra.Command, builder *lunatask.TaskBuilder) error {
154 if status, _ := cmd.Flags().GetString("status"); status != "" {
155 s, err := validate.TaskStatus(status)
156 if err != nil {
157 return err
158 }
159
160 builder.WithStatus(s)
161 }
162
163 if note, _ := cmd.Flags().GetString("note"); note != "" {
164 resolved, err := resolveNote(note)
165 if err != nil {
166 return err
167 }
168
169 builder.WithNote(resolved)
170 }
171
172 if priority, _ := cmd.Flags().GetString("priority"); priority != "" {
173 p, err := lunatask.ParsePriority(priority)
174 if err != nil {
175 return err
176 }
177
178 builder.Priority(p)
179 }
180
181 if estimate, _ := cmd.Flags().GetInt("estimate"); estimate != 0 {
182 builder.WithEstimate(estimate)
183 }
184
185 if motivation, _ := cmd.Flags().GetString("motivation"); motivation != "" {
186 m, err := validate.Motivation(motivation)
187 if err != nil {
188 return err
189 }
190
191 builder.WithMotivation(m)
192 }
193
194 applyEisenhower(cmd, builder)
195
196 return applySchedule(cmd, builder)
197}
198
199func applyEisenhower(cmd *cobra.Command, builder *lunatask.TaskBuilder) {
200 if important, _ := cmd.Flags().GetBool("important"); important {
201 builder.Important()
202 } else if notImportant, _ := cmd.Flags().GetBool("not-important"); notImportant {
203 builder.NotImportant()
204 }
205
206 if urgent, _ := cmd.Flags().GetBool("urgent"); urgent {
207 builder.Urgent()
208 } else if notUrgent, _ := cmd.Flags().GetBool("not-urgent"); notUrgent {
209 builder.NotUrgent()
210 }
211}
212
213func applySchedule(cmd *cobra.Command, builder *lunatask.TaskBuilder) error {
214 schedule, _ := cmd.Flags().GetString("schedule")
215 if schedule == "" {
216 return nil
217 }
218
219 date, err := dateutil.Parse(schedule)
220 if err != nil {
221 return err
222 }
223
224 builder.ScheduledOn(date)
225
226 return nil
227}
228
229func resolveNote(note string) (string, error) {
230 if note != "-" {
231 return note, nil
232 }
233
234 data, err := os.ReadFile("/dev/stdin")
235 if err != nil {
236 return "", fmt.Errorf("reading stdin: %w", err)
237 }
238
239 return strings.TrimSpace(string(data)), nil
240}