1package commands
2
3import (
4 "github.com/pkg/errors"
5 "github.com/spf13/cobra"
6
7 "github.com/MichaelMure/git-bug/bug"
8 "github.com/MichaelMure/git-bug/cache"
9 _select "github.com/MichaelMure/git-bug/commands/select"
10 "github.com/MichaelMure/git-bug/entity"
11 "github.com/MichaelMure/git-bug/input"
12)
13
14type commentEditOptions struct {
15 messageFile string
16 message string
17}
18
19func newCommentEditCommand() *cobra.Command {
20 env := newEnv()
21 options := commentEditOptions{}
22
23 cmd := &cobra.Command{
24 Use: "edit <id>",
25 Short: "Edit an existing comment on a bug.",
26 Args: cobra.ExactArgs(1),
27 PreRunE: loadBackendEnsureUser(env),
28 PostRunE: closeBackend(env),
29 RunE: func(cmd *cobra.Command, args []string) error {
30 return runCommentEdit(env, options, args)
31 },
32 }
33
34 flags := cmd.Flags()
35 flags.SortFlags = false
36
37 flags.StringVarP(&options.messageFile, "file", "F", "",
38 "Take the message from the given file. Use - to read the message from the standard input")
39
40 flags.StringVarP(&options.message, "message", "m", "",
41 "Provide the new message from the command line")
42
43 return cmd
44}
45
46func ResolveComment(repo *cache.RepoCache, fullId string) (*cache.BugCache, entity.Id, error) {
47 bugId, _ := bug.SplitCommentId(fullId)
48 b, _, err := _select.ResolveBug(repo, []string{bugId})
49 if err != nil {
50 return nil, entity.UnsetId, err
51 }
52
53 matching := make([]entity.Id, 0, 5)
54
55 for _, comment := range b.Snapshot().Comments {
56 if comment.Id().HasPrefix(fullId) {
57 matching = append(matching, comment.Id())
58 }
59 }
60
61 if len(matching) > 1 {
62 return nil, entity.UnsetId, entity.NewErrMultipleMatch("comment", matching)
63 } else if len(matching) == 0 {
64 return nil, entity.UnsetId, errors.New("comment doesn't exist")
65 }
66
67 return b, matching[0], nil
68}
69
70func runCommentEdit(env *Env, opts commentEditOptions, args []string) error {
71 b, c, err := ResolveComment(env.backend, args[0])
72
73 if err != nil {
74 return err
75 }
76
77 if opts.messageFile != "" && opts.message == "" {
78 opts.message, err = input.BugCommentFileInput(opts.messageFile)
79 if err != nil {
80 return err
81 }
82 }
83
84 if opts.messageFile == "" && opts.message == "" {
85 opts.message, err = input.BugCommentEditorInput(env.backend, "")
86 if err == input.ErrEmptyMessage {
87 env.err.Println("Empty message, aborting.")
88 return nil
89 }
90 if err != nil {
91 return err
92 }
93 }
94
95 _, err = b.EditComment(c, opts.message)
96 if err != nil {
97 return err
98 }
99
100 return b.Commit()
101}