1package commands
 2
 3import (
 4	"github.com/spf13/cobra"
 5
 6	_select "github.com/MichaelMure/git-bug/commands/select"
 7	"github.com/MichaelMure/git-bug/input"
 8	"github.com/MichaelMure/git-bug/util/text"
 9)
10
11type commentAddOptions struct {
12	messageFile    string
13	message        string
14	nonInteractive bool
15}
16
17func newCommentAddCommand() *cobra.Command {
18	env := newEnv()
19	options := commentAddOptions{}
20
21	cmd := &cobra.Command{
22		Use:     "add [ID]",
23		Short:   "Add a new comment to a bug.",
24		PreRunE: loadBackendEnsureUser(env),
25		RunE: closeBackend(env, func(cmd *cobra.Command, args []string) error {
26			return runCommentAdd(env, options, args)
27		}),
28		ValidArgsFunction: completeBug(env),
29	}
30
31	flags := cmd.Flags()
32	flags.SortFlags = false
33
34	flags.StringVarP(&options.messageFile, "file", "F", "",
35		"Take the message from the given file. Use - to read the message from the standard input")
36
37	flags.StringVarP(&options.message, "message", "m", "",
38		"Provide the new message from the command line")
39	flags.BoolVar(&options.nonInteractive, "non-interactive", false, "Do not ask for user input")
40
41	return cmd
42}
43
44func runCommentAdd(env *Env, opts commentAddOptions, args []string) error {
45	b, args, err := _select.ResolveBug(env.backend, args)
46	if err != nil {
47		return err
48	}
49
50	if opts.messageFile != "" && opts.message == "" {
51		opts.message, err = input.BugCommentFileInput(opts.messageFile)
52		if err != nil {
53			return err
54		}
55	}
56
57	if opts.messageFile == "" && opts.message == "" {
58		if opts.nonInteractive {
59			env.err.Println("No message given. Use -m or -F option to specify a message. Aborting.")
60			return nil
61		}
62		opts.message, err = input.BugCommentEditorInput(env.backend, "")
63		if err == input.ErrEmptyMessage {
64			env.err.Println("Empty message, aborting.")
65			return nil
66		}
67		if err != nil {
68			return err
69		}
70	}
71
72	_, err = b.AddComment(text.Cleanup(opts.message))
73	if err != nil {
74		return err
75	}
76
77	return b.Commit()
78}