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