1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
|
package edit
import (
"fmt"
"net/http"
"sort"
"sync"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/text"
shared "github.com/cli/cli/v2/pkg/cmd/issue/shared"
prShared "github.com/cli/cli/v2/pkg/cmd/pr/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type EditOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
Prompter prShared.EditPrompter
DetermineEditor func() (string, error)
FieldsToEditSurvey func(prShared.EditPrompter, *prShared.Editable) error
EditFieldsSurvey func(prShared.EditPrompter, *prShared.Editable, string) error
FetchOptions func(*api.Client, ghrepo.Interface, *prShared.Editable) error
SelectorArgs []string
Interactive bool
prShared.Editable
}
func NewCmdEdit(f *cmdutil.Factory, runF func(*EditOptions) error) *cobra.Command {
opts := &EditOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
DetermineEditor: func() (string, error) { return cmdutil.DetermineEditor(f.Config) },
FieldsToEditSurvey: prShared.FieldsToEditSurvey,
EditFieldsSurvey: prShared.EditFieldsSurvey,
FetchOptions: prShared.FetchOptions,
Prompter: f.Prompter,
}
var bodyFile string
cmd := &cobra.Command{
Use: "edit {<numbers> | <urls>}",
Short: "Edit issues",
Long: heredoc.Docf(`
Edit one or more issues within the same repository.
Editing issues' projects requires authorization with the %[1]sproject%[1]s scope.
To authorize, run %[1]sgh auth refresh -s project%[1]s.
`, "`"),
Example: heredoc.Doc(`
$ gh issue edit 23 --title "I found a bug" --body "Nothing works"
$ gh issue edit 23 --add-label "bug,help wanted" --remove-label "core"
$ gh issue edit 23 --add-assignee "@me" --remove-assignee monalisa,hubot
$ gh issue edit 23 --add-project "Roadmap" --remove-project v1,v2
$ gh issue edit 23 --milestone "Version 1"
$ gh issue edit 23 --body-file body.txt
$ gh issue edit 23 34 --add-label "help wanted"
`),
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
opts.SelectorArgs = args
flags := cmd.Flags()
bodyProvided := flags.Changed("body")
bodyFileProvided := bodyFile != ""
if err := cmdutil.MutuallyExclusive(
"specify only one of `--body` or `--body-file`",
bodyProvided,
bodyFileProvided,
); err != nil {
return err
}
if bodyProvided || bodyFileProvided {
opts.Editable.Body.Edited = true
if bodyFileProvided {
b, err := cmdutil.ReadFile(bodyFile, opts.IO.In)
if err != nil {
return err
}
opts.Editable.Body.Value = string(b)
}
}
if flags.Changed("title") {
opts.Editable.Title.Edited = true
}
if flags.Changed("add-assignee") || flags.Changed("remove-assignee") {
opts.Editable.Assignees.Edited = true
}
if flags.Changed("add-label") || flags.Changed("remove-label") {
opts.Editable.Labels.Edited = true
}
if flags.Changed("add-project") || flags.Changed("remove-project") {
opts.Editable.Projects.Edited = true
}
if flags.Changed("milestone") {
opts.Editable.Milestone.Edited = true
}
if !opts.Editable.Dirty() {
opts.Interactive = true
}
if opts.Interactive && !opts.IO.CanPrompt() {
return cmdutil.FlagErrorf("field to edit flag required when not running interactively")
}
if opts.Interactive && len(opts.SelectorArgs) > 1 {
return cmdutil.FlagErrorf("multiple issues cannot be edited interactively")
}
if runF != nil {
return runF(opts)
}
return editRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Editable.Title.Value, "title", "t", "", "Set the new title.")
cmd.Flags().StringVarP(&opts.Editable.Body.Value, "body", "b", "", "Set the new body.")
cmd.Flags().StringVarP(&bodyFile, "body-file", "F", "", "Read body text from `file` (use \"-\" to read from standard input)")
cmd.Flags().StringSliceVar(&opts.Editable.Assignees.Add, "add-assignee", nil, "Add assigned users by their `login`. Use \"@me\" to assign yourself.")
cmd.Flags().StringSliceVar(&opts.Editable.Assignees.Remove, "remove-assignee", nil, "Remove assigned users by their `login`. Use \"@me\" to unassign yourself.")
cmd.Flags().StringSliceVar(&opts.Editable.Labels.Add, "add-label", nil, "Add labels by `name`")
cmd.Flags().StringSliceVar(&opts.Editable.Labels.Remove, "remove-label", nil, "Remove labels by `name`")
cmd.Flags().StringSliceVar(&opts.Editable.Projects.Add, "add-project", nil, "Add the issue to projects by `name`")
cmd.Flags().StringSliceVar(&opts.Editable.Projects.Remove, "remove-project", nil, "Remove the issue from projects by `name`")
cmd.Flags().StringVarP(&opts.Editable.Milestone.Value, "milestone", "m", "", "Edit the milestone the issue belongs to by `name`")
return cmd
}
func editRun(opts *EditOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
// Prompt the user which fields they'd like to edit.
editable := opts.Editable
if opts.Interactive {
err = opts.FieldsToEditSurvey(opts.Prompter, &editable)
if err != nil {
return err
}
}
lookupFields := []string{"id", "number", "title", "body", "url"}
if editable.Assignees.Edited {
lookupFields = append(lookupFields, "assignees")
}
if editable.Labels.Edited {
lookupFields = append(lookupFields, "labels")
}
if editable.Projects.Edited {
lookupFields = append(lookupFields, "projectCards")
lookupFields = append(lookupFields, "projectItems")
}
if editable.Milestone.Edited {
lookupFields = append(lookupFields, "milestone")
}
// Get all specified issues and make sure they are within the same repo.
issues, repo, err := shared.IssuesFromArgsWithFields(httpClient, opts.BaseRepo, opts.SelectorArgs, lookupFields)
if err != nil {
return err
}
// Fetch editable shared fields once for all issues.
apiClient := api.NewClientFromHTTP(httpClient)
opts.IO.StartProgressIndicatorWithLabel("Fetching repository information")
err = opts.FetchOptions(apiClient, repo, &editable)
opts.IO.StopProgressIndicator()
if err != nil {
return err
}
// Update all issues in parallel.
editedIssueChan := make(chan string, len(issues))
failedIssueChan := make(chan string, len(issues))
g := sync.WaitGroup{}
// Only show progress if we will not prompt below or the survey will break up the progress indicator.
if !opts.Interactive {
opts.IO.StartProgressIndicatorWithLabel(fmt.Sprintf("Updating %d issues", len(issues)))
}
for _, issue := range issues {
// Copy variables to capture in the go routine below.
editable := editable.Clone()
editable.Title.Default = issue.Title
editable.Body.Default = issue.Body
editable.Assignees.Default = issue.Assignees.Logins()
editable.Labels.Default = issue.Labels.Names()
editable.Projects.Default = append(issue.ProjectCards.ProjectNames(), issue.ProjectItems.ProjectTitles()...)
projectItems := map[string]string{}
for _, n := range issue.ProjectItems.Nodes {
projectItems[n.Project.ID] = n.ID
}
editable.Projects.ProjectItems = projectItems
if issue.Milestone != nil {
editable.Milestone.Default = issue.Milestone.Title
}
// Allow interactive prompts for one issue; failed earlier if multiple issues specified.
if opts.Interactive {
editorCommand, err := opts.DetermineEditor()
if err != nil {
return err
}
err = opts.EditFieldsSurvey(opts.Prompter, &editable, editorCommand)
if err != nil {
return err
}
}
g.Add(1)
go func(issue *api.Issue) {
defer g.Done()
err := prShared.UpdateIssue(httpClient, repo, issue.ID, issue.IsPullRequest(), editable)
if err != nil {
failedIssueChan <- fmt.Sprintf("failed to update %s: %s", issue.URL, err)
return
}
editedIssueChan <- issue.URL
}(issue)
}
g.Wait()
close(editedIssueChan)
close(failedIssueChan)
// Does nothing if progress was not started above.
opts.IO.StopProgressIndicator()
// Print a sorted list of successfully edited issue URLs to stdout.
editedIssueURLs := make([]string, 0, len(issues))
for editedIssueURL := range editedIssueChan {
editedIssueURLs = append(editedIssueURLs, editedIssueURL)
}
sort.Strings(editedIssueURLs)
for _, editedIssueURL := range editedIssueURLs {
fmt.Fprintln(opts.IO.Out, editedIssueURL)
}
// Print a sorted list of failures to stderr.
failedIssueErrors := make([]string, 0, len(issues))
for failedIssueError := range failedIssueChan {
failedIssueErrors = append(failedIssueErrors, failedIssueError)
}
sort.Strings(failedIssueErrors)
for _, failedIssueError := range failedIssueErrors {
fmt.Fprintln(opts.IO.ErrOut, failedIssueError)
}
if len(failedIssueErrors) > 0 {
return fmt.Errorf("failed to update %s", text.Pluralize(len(failedIssueErrors), "issue"))
}
return nil
}
|