bug_comment_edit.go

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