forked from cli/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate.go
More file actions
294 lines (242 loc) · 6.98 KB
/
create.go
File metadata and controls
294 lines (242 loc) · 6.98 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package create
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"path"
"regexp"
"sort"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/pkg/cmd/gist/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/utils"
"github.com/spf13/cobra"
)
type browser interface {
Browse(string) error
}
type CreateOptions struct {
IO *iostreams.IOStreams
Description string
Public bool
Filenames []string
FilenameOverride string
WebMode bool
Config func() (config.Config, error)
HttpClient func() (*http.Client, error)
Browser browser
}
func NewCmdCreate(f *cmdutil.Factory, runF func(*CreateOptions) error) *cobra.Command {
opts := CreateOptions{
IO: f.IOStreams,
Config: f.Config,
HttpClient: f.HttpClient,
Browser: f.Browser,
}
cmd := &cobra.Command{
Use: "create [<filename>... | -]",
Short: "Create a new gist",
Long: heredoc.Doc(`
Create a new GitHub gist with given contents.
Gists can be created from one or multiple files. Alternatively, pass "-" as
file name to read from standard input.
By default, gists are secret; use '--public' to make publicly listed ones.
`),
Example: heredoc.Doc(`
# publish file 'hello.py' as a public gist
$ gh gist create --public hello.py
# create a gist with a description
$ gh gist create hello.py -d "my Hello-World program in Python"
# create a gist containing several files
$ gh gist create hello.py world.py cool.txt
# read from standard input to create a gist
$ gh gist create -
# create a gist from output piped from another command
$ cat cool.txt | gh gist create
`),
Args: func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
return nil
}
if opts.IO.IsStdinTTY() {
return cmdutil.FlagErrorf("no filenames passed and nothing on STDIN")
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
opts.Filenames = args
if runF != nil {
return runF(&opts)
}
return createRun(&opts)
},
}
cmd.Flags().StringVarP(&opts.Description, "desc", "d", "", "A description for this gist")
cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "Open the web browser with created gist")
cmd.Flags().BoolVarP(&opts.Public, "public", "p", false, "List the gist publicly (default: secret)")
cmd.Flags().StringVarP(&opts.FilenameOverride, "filename", "f", "", "Provide a filename to be used when reading from standard input")
return cmd
}
func createRun(opts *CreateOptions) error {
fileArgs := opts.Filenames
if len(fileArgs) == 0 {
fileArgs = []string{"-"}
}
files, err := processFiles(opts.IO.In, opts.FilenameOverride, fileArgs)
if err != nil {
return fmt.Errorf("failed to collect files for posting: %w", err)
}
gistName := guessGistName(files)
processMessage := "Creating gist..."
completionMessage := "Created gist"
if gistName != "" {
if len(files) > 1 {
processMessage = "Creating gist with multiple files"
} else {
processMessage = fmt.Sprintf("Creating gist %s", gistName)
}
completionMessage = fmt.Sprintf("Created gist %s", gistName)
}
cs := opts.IO.ColorScheme()
errOut := opts.IO.ErrOut
fmt.Fprintf(errOut, "%s %s\n", cs.Gray("-"), processMessage)
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
cfg, err := opts.Config()
if err != nil {
return err
}
host, err := cfg.DefaultHost()
if err != nil {
return err
}
gist, err := createGist(httpClient, host, opts.Description, opts.Public, files)
if err != nil {
var httpError api.HTTPError
if errors.As(err, &httpError) {
if httpError.StatusCode == http.StatusUnprocessableEntity {
if detectEmptyFiles(files) {
fmt.Fprintf(errOut, "%s Failed to create gist: %s\n", cs.FailureIcon(), "a gist file cannot be blank")
return cmdutil.SilentError
}
}
}
return fmt.Errorf("%s Failed to create gist: %w", cs.Red("X"), err)
}
fmt.Fprintf(errOut, "%s %s\n", cs.SuccessIconWithColor(cs.Green), completionMessage)
if opts.WebMode {
fmt.Fprintf(opts.IO.Out, "Opening %s in your browser.\n", utils.DisplayURL(gist.HTMLURL))
return opts.Browser.Browse(gist.HTMLURL)
}
fmt.Fprintln(opts.IO.Out, gist.HTMLURL)
return nil
}
func processFiles(stdin io.ReadCloser, filenameOverride string, filenames []string) (map[string]*shared.GistFile, error) {
fs := map[string]*shared.GistFile{}
if len(filenames) == 0 {
return nil, errors.New("no files passed")
}
for i, f := range filenames {
var filename string
var content []byte
var err error
if f == "-" {
if filenameOverride != "" {
filename = filenameOverride
} else {
filename = fmt.Sprintf("gistfile%d.txt", i)
}
content, err = ioutil.ReadAll(stdin)
if err != nil {
return fs, fmt.Errorf("failed to read from stdin: %w", err)
}
stdin.Close()
if shared.IsBinaryContents(content) {
return nil, fmt.Errorf("binary file contents not supported")
}
} else {
isBinary, err := shared.IsBinaryFile(f)
if err != nil {
return fs, fmt.Errorf("failed to read file %s: %w", f, err)
}
if isBinary {
return nil, fmt.Errorf("failed to upload %s: binary file not supported", f)
}
content, err = ioutil.ReadFile(f)
if err != nil {
return fs, fmt.Errorf("failed to read file %s: %w", f, err)
}
filename = path.Base(f)
}
fs[filename] = &shared.GistFile{
Content: string(content),
}
}
return fs, nil
}
func guessGistName(files map[string]*shared.GistFile) string {
filenames := make([]string, 0, len(files))
gistName := ""
re := regexp.MustCompile(`^gistfile\d+\.txt$`)
for k := range files {
if !re.MatchString(k) {
filenames = append(filenames, k)
}
}
if len(filenames) > 0 {
sort.Strings(filenames)
gistName = filenames[0]
}
return gistName
}
func createGist(client *http.Client, hostname, description string, public bool, files map[string]*shared.GistFile) (*shared.Gist, error) {
body := &shared.Gist{
Description: description,
Public: public,
Files: files,
}
requestBody := &bytes.Buffer{}
enc := json.NewEncoder(requestBody)
if err := enc.Encode(body); err != nil {
return nil, err
}
u := ghinstance.RESTPrefix(hostname) + "gists"
req, err := http.NewRequest(http.MethodPost, u, requestBody)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return nil, api.HandleHTTPError(api.EndpointNeedsScopes(resp, "gist"))
}
result := &shared.Gist{}
dec := json.NewDecoder(resp.Body)
if err := dec.Decode(result); err != nil {
return nil, err
}
return result, nil
}
func detectEmptyFiles(files map[string]*shared.GistFile) bool {
for _, file := range files {
if strings.TrimSpace(file.Content) == "" {
return true
}
}
return false
}