Repository navigation
Expand file tree
/
Copy pathedit.go
More file actions
267 lines (239 loc) · 8.93 KB
/
Copy pathedit.go
File metadata and controls
267 lines (239 loc) · 8.93 KB
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
package edit
import (
"context"
"errors"
"fmt"
"net/http"
"path/filepath"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/attachments"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/gh/ghtelemetry"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/issue/artifact/client"
"github.com/cli/cli/v2/pkg/cmd/issue/artifact/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
// EditOptions holds the flags and dependencies of gh issue artifact edit.
type EditOptions struct {
IO *iostreams.IOStreams
HttpClient func() (*http.Client, error)
Config func() (gh.Config, error)
BaseRepo func() (ghrepo.Interface, error)
Client func() (client.ArtifactClient, error)
IssueNumber int
ArtifactNumber int
// Name is the new name from --name, or nil to keep the current name.
Name *string
// Body is the new content from --body, or nil when --body wasn't given.
Body *string
// BodyFile is the file --body-file reads the new content from, "-" for
// standard input, or empty when --body-file wasn't given. Result lines
// show it as the source.
BodyFile string
AttachFlag *attachments.Flag
AttachEvent *attachments.TelemetryEvent
Assets []attachments.UserAsset
}
// NewCmdEdit creates the gh issue artifact edit command.
func NewCmdEdit(f *cmdutil.Factory, telemetry ghtelemetry.InvocationRecorder, runF func(*EditOptions) error) *cobra.Command {
opts := &EditOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
Config: f.Config,
}
cmd := &cobra.Command{
Use: "edit {<issue-number> | <issue-url>} <artifact-number>",
Short: "Edit an issue artifact (preview)",
Long: heredoc.Docf(`
Rename an issue artifact or replace its content. The type never changes, so a
link's new content must be an http(s) URL or a %[1]s.url%[1]s Internet Shortcut file.
With only %[1]s--attach%[1]s, the attachments are appended to the current content.
`, "`"),
Example: heredoc.Doc(`
# Rename an artifact
$ gh issue artifact edit 142 2 --name 'OAuth callback plan v2'
# Replace a document's content with a file
$ gh issue artifact edit 142 2 --body-file 2-OAuth-callback-plan.md
# Point a link at a new URL
$ gh issue artifact edit 142 3 --body https://github.com/monalisa/monas-cafe/wiki/OAuth-runbook-v2
# Append a screenshot to a document
$ gh issue artifact edit 142 2 --attach ./signin-flow.png
`),
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
var err error
opts.IssueNumber, opts.BaseRepo, err = shared.ParseIssueArg(args[0], f.BaseRepo)
if err != nil {
return err
}
opts.ArtifactNumber, err = shared.ParseArtifactNumber(args[1])
if err != nil {
return err
}
// An empty --body-file names no file, as in gh issue edit.
if err := cmdutil.MutuallyExclusive("specify only one of `--body` or `--body-file`", opts.Body != nil, opts.BodyFile != ""); err != nil {
return err
}
switch {
case opts.Name == nil && opts.Body == nil && opts.BodyFile == "" && !opts.AttachFlag.Changed():
return cmdutil.FlagErrorf("specify at least one of `--name`, `--body`, `--body-file`, or `--attach`")
case opts.Name != nil && *opts.Name == "":
return cmdutil.FlagErrorf("--name cannot be blank")
case opts.Body != nil && strings.TrimSpace(*opts.Body) == "":
return cmdutil.FlagErrorf("--body cannot be blank")
}
opts.AttachEvent = attachments.BeginTelemetry(telemetry, cmd.CommandPath(), opts.AttachFlag.Count())
opts.Assets, err = opts.AttachFlag.UserAssets()
if err != nil {
return err
}
opts.Client = shared.ClientFunc(f)
if runF != nil {
return runF(opts)
}
return editRun(opts)
},
}
cmdutil.NilStringFlag(cmd, &opts.Body, "body", "b", "New content; for a link, a URL")
cmd.Flags().StringVarP(&opts.BodyFile, "body-file", "F", "", "Read new content from `file` (use \"-\" to read from standard input)")
cmdutil.NilStringFlag(cmd, &opts.Name, "name", "", "New name")
opts.AttachFlag = attachments.AddFlag(cmd)
return cmd
}
func editRun(opts *EditOptions) error {
repo, err := opts.BaseRepo()
if err != nil {
return err
}
if err := shared.CheckHost(repo.RepoHost()); err != nil {
return err
}
// The new content is read and checked before any request, so a file that
// can't be used fails without one.
content, err := readContent(opts)
if err != nil {
return err
}
c, err := opts.Client()
if err != nil {
return err
}
var uploader *attachments.Uploader
if len(opts.Assets) > 0 {
uploader, err = shared.NewUploader(c, repo, opts.IssueNumber, opts.HttpClient, opts.Config)
if err != nil {
return err
}
} else if err := shared.CheckIssue(c, repo, opts.IssueNumber); err != nil {
return err
}
action := fmt.Sprintf("update artifact %d", opts.ArtifactNumber)
result := shared.Result{Number: opts.ArtifactNumber, Source: opts.BodyFile}
current, err := c.Get(repo, opts.IssueNumber, opts.ArtifactNumber)
if err != nil {
shared.PrintFailure(opts.IO, result, action, err)
return cmdutil.SilentError
}
result.Name = text.RemoveExcessiveWhitespace(current.Name)
// The type decides what the new content can be, so every check that
// depends on it runs before anything is uploaded or saved.
if err := shared.CheckType(current.Artifact); err != nil {
return err
}
body, err := newBody(opts, current.Artifact, content)
if err != nil {
return err
}
var uploadErr error
if uploader != nil {
// A --body-file's references resolve against its own directory first.
// Other content has no directory of its own, so its references
// resolve against the working directory.
var dir string
if opts.BodyFile != "" && opts.BodyFile != "-" {
dir = filepath.Dir(opts.BodyFile)
}
md, uploadResult, err := uploader.UploadAndAttach(context.Background(), *body, dir, opts.Assets)
opts.AttachEvent.RecordOperations(uploadResult)
// Uploads can't be undone, so the artifact is saved if any file
// uploaded, even when another failed. It isn't saved when none did.
if err != nil && uploadResult.Uploaded == 0 {
shared.PrintFailure(opts.IO, result, action, err)
return cmdutil.SilentError
}
body, uploadErr = &md, err
}
updated, err := c.Update(repo, opts.IssueNumber, opts.ArtifactNumber, opts.Name, body)
if err != nil {
shared.PrintFailure(opts.IO, result, action, err)
return cmdutil.SilentError
}
result.Name = text.RemoveExcessiveWhitespace(updated.Name)
message := fmt.Sprintf("Updated artifact %d (%s) on %s#%d", opts.ArtifactNumber, result.Name, ghrepo.FullName(repo), opts.IssueNumber)
if uploadErr != nil {
shared.PrintPartialFailure(opts.IO, "updated", result, message, uploadErr)
return cmdutil.SilentError
}
shared.PrintSuccess(opts.IO, "updated", result, opts.IO.ColorScheme().SuccessIcon(), message)
return nil
}
// readContent returns the new content from --body or --body-file, or nil
// when neither was given. Standard input is only read with --body-file -, so
// a stdin that never closes can't hang the command.
func readContent(opts *EditOptions) (*string, error) {
if opts.BodyFile == "" {
return opts.Body, nil
}
content, err := shared.ReadContent(opts.BodyFile, opts.IO.In)
if err != nil {
source := opts.BodyFile
if source == "-" {
source = "standard input"
}
return nil, fmt.Errorf("failed to update artifact %d from %s: %w", opts.ArtifactNumber, source, err)
}
return &content, nil
}
// newBody returns the body to save, checked against the artifact's type, or
// nil to keep the current body. A link's new content must be an http(s) URL:
// a .url file is read as a shortcut, and anything else must be a bare URL,
// with its surrounding whitespace trimmed. A link has no Markdown for
// --attach. Any other artifact is a Markdown document, which never takes a
// .url file, and with only --attach, the files are appended to its current
// body.
func newBody(opts *EditOptions, a client.Artifact, content *string) (*string, error) {
if a.Type != client.TypeLink {
if shared.IsShortcutFile(opts.BodyFile) {
return nil, fmt.Errorf("artifact %d is not a link; .url files can only update link artifacts", a.Number)
}
if content == nil && len(opts.Assets) > 0 {
return &a.Body, nil
}
return content, nil
}
if len(opts.Assets) > 0 {
return nil, fmt.Errorf("artifact %d is a link; --attach can't be used with link artifacts", a.Number)
}
if content == nil {
return nil, nil
}
if shared.IsShortcutFile(opts.BodyFile) {
u, err := shared.ShortcutURL(*content)
if errors.Is(err, shared.ErrNoShortcutSection) {
return nil, fmt.Errorf("%s: %w; pass the URL with `--body` instead", opts.BodyFile, err)
} else if err != nil {
return nil, fmt.Errorf("%s: %w", opts.BodyFile, err)
}
return &u, nil
}
u, ok := shared.HTTPURL(*content)
if !ok {
return nil, fmt.Errorf("artifact %d is a link; its new content must be an http(s) URL or a .url file", a.Number)
}
return &u, nil
}