add.go

  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, completed")
 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	area, err := applyAreaAndGoal(cmd, builder)
 77	if err != nil {
 78		return err
 79	}
 80
 81	if err := applyOptionalFlags(cmd, builder, area); err != nil {
 82		return err
 83	}
 84
 85	task, err := ui.Spin("Creating task…", func() (*lunatask.Task, error) {
 86		return builder.Create(cmd.Context())
 87	})
 88	if err != nil {
 89		return err
 90	}
 91
 92	fmt.Fprintln(cmd.OutOrStdout(), ui.Success.Render("Created task: "+task.ID))
 93
 94	return nil
 95}
 96
 97func resolveName(arg string) (string, error) {
 98	if arg != "-" {
 99		return arg, nil
100	}
101
102	scanner := bufio.NewScanner(os.Stdin)
103	if scanner.Scan() {
104		return strings.TrimSpace(scanner.Text()), nil
105	}
106
107	if err := scanner.Err(); err != nil {
108		return "", fmt.Errorf("reading stdin: %w", err)
109	}
110
111	return "", ErrNoInput
112}
113
114//nolint:nilnil // nil area with no error is valid when area flag not provided
115func applyAreaAndGoal(cmd *cobra.Command, builder *lunatask.TaskBuilder) (*config.Area, error) {
116	areaKey, _ := cmd.Flags().GetString("area")
117	goalKey, _ := cmd.Flags().GetString("goal")
118
119	if areaKey == "" && goalKey == "" {
120		return nil, nil
121	}
122
123	if areaKey == "" && goalKey != "" {
124		fmt.Fprintln(cmd.ErrOrStderr(), ui.Warning.Render("Goal specified without area; ignoring"))
125
126		return nil, nil
127	}
128
129	cfg, err := config.Load()
130	if err != nil {
131		return nil, err
132	}
133
134	area := cfg.AreaByKey(areaKey)
135	if area == nil {
136		return nil, fmt.Errorf("%w: %s", ErrUnknownArea, areaKey)
137	}
138
139	builder.InArea(area.ID)
140
141	if goalKey == "" {
142		return area, nil
143	}
144
145	goal := area.GoalByKey(goalKey)
146	if goal == nil {
147		return nil, fmt.Errorf("%w: %s", ErrUnknownGoal, goalKey)
148	}
149
150	builder.InGoal(goal.ID)
151
152	return area, nil
153}
154
155//nolint:cyclop // flag handling inherently has many branches
156func applyOptionalFlags(cmd *cobra.Command, builder *lunatask.TaskBuilder, area *config.Area) error {
157	if status, _ := cmd.Flags().GetString("status"); status != "" {
158		var (
159			parsedStatus lunatask.TaskStatus
160			err          error
161		)
162
163		if area != nil {
164			parsedStatus, err = validate.TaskStatusForWorkflow(status, area.Workflow)
165		} else {
166			parsedStatus, err = validate.TaskStatus(status)
167		}
168
169		if err != nil {
170			return err
171		}
172
173		builder.WithStatus(parsedStatus)
174	}
175
176	if note, _ := cmd.Flags().GetString("note"); note != "" {
177		resolved, err := resolveNote(note)
178		if err != nil {
179			return err
180		}
181
182		builder.WithNote(resolved)
183	}
184
185	if priority, _ := cmd.Flags().GetString("priority"); priority != "" {
186		p, err := lunatask.ParsePriority(priority)
187		if err != nil {
188			return err
189		}
190
191		builder.Priority(p)
192	}
193
194	if estimate, _ := cmd.Flags().GetInt("estimate"); estimate != 0 {
195		builder.WithEstimate(estimate)
196	}
197
198	if motivation, _ := cmd.Flags().GetString("motivation"); motivation != "" {
199		m, err := validate.Motivation(motivation)
200		if err != nil {
201			return err
202		}
203
204		builder.WithMotivation(m)
205	}
206
207	applyEisenhower(cmd, builder)
208
209	return applySchedule(cmd, builder)
210}
211
212func applyEisenhower(cmd *cobra.Command, builder *lunatask.TaskBuilder) {
213	if important, _ := cmd.Flags().GetBool("important"); important {
214		builder.Important()
215	} else if notImportant, _ := cmd.Flags().GetBool("not-important"); notImportant {
216		builder.NotImportant()
217	}
218
219	if urgent, _ := cmd.Flags().GetBool("urgent"); urgent {
220		builder.Urgent()
221	} else if notUrgent, _ := cmd.Flags().GetBool("not-urgent"); notUrgent {
222		builder.NotUrgent()
223	}
224}
225
226func applySchedule(cmd *cobra.Command, builder *lunatask.TaskBuilder) error {
227	schedule, _ := cmd.Flags().GetString("schedule")
228	if schedule == "" {
229		return nil
230	}
231
232	date, err := dateutil.Parse(schedule)
233	if err != nil {
234		return err
235	}
236
237	builder.ScheduledOn(date)
238
239	return nil
240}
241
242func resolveNote(note string) (string, error) {
243	if note != "-" {
244		return note, nil
245	}
246
247	data, err := os.ReadFile("/dev/stdin")
248	if err != nil {
249		return "", fmt.Errorf("reading stdin: %w", err)
250	}
251
252	return strings.TrimSpace(string(data)), nil
253}