comment_edit.go

  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		PreRunE:  loadBackendEnsureUser(env),
 27		PostRunE: closeBackend(env),
 28		RunE: func(cmd *cobra.Command, args []string) error {
 29			return runCommentEdit(env, options, args)
 30		},
 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
 42	return cmd
 43}
 44
 45func ResolveComment(repo *cache.RepoCache, args []string) (*cache.BugCache, entity.Id, error) {
 46	fullId := args[0]
 47	bugId, _ := bug.UnpackCommentId(args[0])
 48	args[0] = bugId
 49	b, args, err := _select.ResolveBug(repo, args)
 50	if err != nil {
 51		return nil, entity.UnsetId, err
 52	}
 53
 54	matching := make([]entity.Id, 0, 5)
 55
 56	for _, comment := range b.Snapshot().Comments {
 57		if comment.Id().HasPrefix(fullId) {
 58			matching = append(matching, comment.Id())
 59		}
 60	}
 61
 62	if len(matching) > 1 {
 63		return nil, entity.UnsetId, entity.NewErrMultipleMatch("comment", matching)
 64	} else if len(matching) == 0 {
 65		return nil, entity.UnsetId, errors.New("comment doesn't exist")
 66	}
 67
 68	return b, matching[0], nil
 69}
 70
 71func runCommentEdit(env *Env, opts commentEditOptions, args []string) error {
 72	b, c, err := ResolveComment(env.backend, args)
 73
 74	if err != nil {
 75		return err
 76	}
 77
 78	if opts.messageFile != "" && opts.message == "" {
 79		opts.message, err = input.BugCommentFileInput(opts.messageFile)
 80		if err != nil {
 81			return err
 82		}
 83	}
 84
 85	if opts.messageFile == "" && opts.message == "" {
 86		opts.message, err = input.BugCommentEditorInput(env.backend, "")
 87		if err == input.ErrEmptyMessage {
 88			env.err.Println("Empty message, aborting.")
 89			return nil
 90		}
 91		if err != nil {
 92			return err
 93		}
 94	}
 95
 96	_, err = b.EditComment(c, opts.message)
 97	if err != nil {
 98		return err
 99	}
100
101	return b.Commit()
102}