comment_add.go

 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}
15
16func newCommentAddCommand() *cobra.Command {
17	env := newEnv()
18	options := commentAddOptions{}
19
20	cmd := &cobra.Command{
21		Use:      "add [ID]",
22		Short:    "Add a new comment to a bug.",
23		PreRunE:  loadBackendEnsureUser(env),
24		PostRunE: closeBackend(env),
25		RunE: func(cmd *cobra.Command, args []string) error {
26			return runCommentAdd(env, options, args)
27		},
28	}
29
30	flags := cmd.Flags()
31	flags.SortFlags = false
32
33	flags.StringVarP(&options.messageFile, "file", "F", "",
34		"Take the message from the given file. Use - to read the message from the standard input")
35
36	flags.StringVarP(&options.message, "message", "m", "",
37		"Provide the new message from the command line")
38
39	return cmd
40}
41
42func runCommentAdd(env *Env, opts commentAddOptions, args []string) error {
43	b, args, err := _select.ResolveBug(env.backend, args)
44	if err != nil {
45		return err
46	}
47
48	if opts.messageFile != "" && opts.message == "" {
49		opts.message, err = input.BugCommentFileInput(opts.messageFile)
50		if err != nil {
51			return err
52		}
53	}
54
55	if opts.messageFile == "" && opts.message == "" {
56		opts.message, err = input.BugCommentEditorInput(env.backend, "")
57		if err == input.ErrEmptyMessage {
58			env.err.Println("Empty message, aborting.")
59			return nil
60		}
61		if err != nil {
62			return err
63		}
64	}
65
66	_, err = b.AddComment(text.Cleanup(opts.message))
67	if err != nil {
68		return err
69	}
70
71	return b.Commit()
72}