board_adddraft.go

 1package boardcmd
 2
 3import (
 4	"strconv"
 5
 6	"github.com/spf13/cobra"
 7
 8	buginput "github.com/git-bug/git-bug/commands/bug/input"
 9	"github.com/git-bug/git-bug/commands/execenv"
10	"github.com/git-bug/git-bug/entity"
11)
12
13type boardAddDraftOptions struct {
14	title          string
15	messageFile    string
16	message        string
17	column         string
18	nonInteractive bool
19}
20
21func newBoardAddDraftCommand() *cobra.Command {
22	env := execenv.NewEnv()
23	options := boardAddDraftOptions{}
24
25	cmd := &cobra.Command{
26		Use:     "add-draft [BOARD_ID]",
27		Short:   "Add a draft item to a board",
28		PreRunE: execenv.LoadBackend(env),
29		RunE: execenv.CloseBackend(env, func(cmd *cobra.Command, args []string) error {
30			return runBoardAddDraft(env, options, args)
31		}),
32		ValidArgsFunction: BoardCompletion(env),
33	}
34
35	flags := cmd.Flags()
36	flags.SortFlags = false
37
38	flags.StringVarP(&options.title, "title", "t", "",
39		"Provide the title to describe the draft item")
40	flags.StringVarP(&options.message, "message", "m", "",
41		"Provide the message of the draft item")
42	flags.StringVarP(&options.messageFile, "file", "F", "",
43		"Take the message from the given file. Use - to read the message from the standard input")
44	flags.StringVarP(&options.column, "column", "c", "1",
45		"The column to add to. Either a column Id or prefix, or the column number starting from 1.")
46	// _ = cmd.MarkFlagRequired("column")
47	_ = cmd.RegisterFlagCompletionFunc("column", ColumnCompletion(env))
48	flags.BoolVar(&options.nonInteractive, "non-interactive", false, "Do not ask for user input")
49
50	return cmd
51}
52
53func runBoardAddDraft(env *execenv.Env, opts boardAddDraftOptions, args []string) error {
54	b, args, err := ResolveSelected(env.Backend, args)
55	if err != nil {
56		return err
57	}
58
59	var columnId entity.Id
60
61	index, err := strconv.Atoi(opts.column)
62	if err == nil && index-1 >= 0 && index-1 < len(b.Snapshot().Columns) {
63		columnId = b.Snapshot().Columns[index-1].Id
64	} else {
65		// TODO: ID or combined ID?
66		// TODO: resolve
67	}
68
69	if opts.messageFile != "" && opts.message == "" {
70		// Note: reuse the bug inputs
71		opts.title, opts.message, err = buginput.BugCreateFileInput(opts.messageFile)
72		if err != nil {
73			return err
74		}
75	}
76
77	if !opts.nonInteractive && opts.messageFile == "" && (opts.message == "" || opts.title == "") {
78		opts.title, opts.message, err = buginput.BugCreateEditorInput(env.Backend, opts.title, opts.message)
79		if err == buginput.ErrEmptyTitle {
80			env.Out.Println("Empty title, aborting.")
81			return nil
82		}
83		if err != nil {
84			return err
85		}
86	}
87
88	id, _, err := b.AddItemDraft(columnId, opts.title, opts.message, nil)
89	if err != nil {
90		return err
91	}
92
93	env.Out.Printf("%s created\n", id.Human())
94
95	return b.Commit()
96}