-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcmdutil.go
More file actions
271 lines (236 loc) · 7.19 KB
/
cmdutil.go
File metadata and controls
271 lines (236 loc) · 7.19 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
package cmd
import (
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"os"
"os/exec"
"os/signal"
"path"
"strings"
"syscall"
"github.com/stainless-api/stainless-api-cli/internal/jsonview"
"github.com/stainless-api/stainless-api-go/option"
"github.com/itchyny/json2yaml"
"github.com/logrusorgru/aurora/v4"
"github.com/tidwall/gjson"
"github.com/tidwall/pretty"
"github.com/urfave/cli/v3"
"golang.org/x/term"
)
var OutputFormats = []string{"auto", "explore", "json", "jsonl", "pretty", "raw", "yaml"}
func getDefaultRequestOptions(cmd *cli.Command) []option.RequestOption {
opts := []option.RequestOption{
option.WithHeader("User-Agent", fmt.Sprintf("Stainless/CLI %s", Version)),
option.WithHeader("X-Stainless-Lang", "cli"),
option.WithHeader("X-Stainless-Package-Version", Version),
option.WithHeader("X-Stainless-Runtime", "cli"),
option.WithHeader("X-Stainless-CLI-Command", cmd.FullName()),
}
// Override base URL if the --base-url flag is provided
if baseURL := cmd.String("base-url"); baseURL != "" {
opts = append(opts, option.WithBaseURL(baseURL))
}
// Set environment if the --environment flag is provided
if environment := cmd.String("environment"); environment != "" {
switch environment {
case "production":
opts = append(opts, option.WithEnvironmentProduction())
case "staging":
opts = append(opts, option.WithEnvironmentStaging())
default:
log.Fatalf("Unknown environment: %s. Valid environments are %s", environment, "production, staging")
}
}
if apiKey := os.Getenv("STAINLESS_API_KEY"); apiKey == "" {
config := &AuthConfig{}
if found, err := config.Find(); err == nil && found && config.AccessToken != "" {
opts = append(opts, option.WithAPIKey(config.AccessToken))
}
}
if project := os.Getenv("STAINLESS_PROJECT"); project == "" {
workspaceConfig := WorkspaceConfig{}
found, err := workspaceConfig.Find()
if err == nil && found && workspaceConfig.Project != "" {
cmd.Set("project", workspaceConfig.Project)
}
}
return opts
}
var debugMiddlewareOption = option.WithMiddleware(
func(r *http.Request, mn option.MiddlewareNext) (*http.Response, error) {
logger := log.Default()
if reqBytes, err := httputil.DumpRequest(r, true); err == nil {
logger.Printf("Request Content:\n%s\n", reqBytes)
}
resp, err := mn(r)
if err != nil {
return resp, err
}
if respBytes, err := httputil.DumpResponse(resp, true); err == nil {
logger.Printf("Response Content:\n%s\n", respBytes)
}
return resp, err
},
)
// convertFileFlag reads a file from a flag and mutates the flag's contents to have the file contents rather
// than the file values.
func convertFileFlag(cmd *cli.Command, flagName string) (string, []byte, error) {
filePath := cmd.String(flagName)
if filePath != "" {
content, err := os.ReadFile(filePath)
if err != nil {
return path.Base(filePath), nil, fmt.Errorf("failed to read %s file: %v", flagName, err)
}
return path.Base(filePath), content, nil
}
return "", nil, nil
}
func isInputPiped() bool {
stat, _ := os.Stdin.Stat()
return (stat.Mode() & os.ModeCharDevice) == 0
}
func isTerminal(w io.Writer) bool {
switch v := w.(type) {
case *os.File:
return term.IsTerminal(int(v.Fd()))
default:
return false
}
}
var au *aurora.Aurora
func init() {
au = aurora.New(aurora.WithColors(shouldUseColors(os.Stdout)))
}
func streamOutput(label string, generateOutput func(w *os.File) error) error {
// For non-tty output (probably a pipe), write directly to stdout
if !isTerminal(os.Stdout) {
return streamToStdout(generateOutput)
}
// When streaming output on Unix-like systems, there's a special trick involving creating two socket pairs
// that we prefer because it supports small buffer sizes which results in less pagination per buffer. The
// constructs needed to run it don't exist on Windows builds, so we have this function broken up into
// OS-specific files with conditional build comments. Under Windows (and in case our fancy constructs fail
// on Unix), we fall back to using pipes (`streamToPagerWithPipe`), which are OS agnostic.
//
// Defined in either cmdutil_unix.go or cmdutil_windows.go.
return streamOutputOSSpecific(label, generateOutput)
}
func streamToPagerWithPipe(label string, generateOutput func(w *os.File) error) error {
r, w, err := os.Pipe()
if err != nil {
return err
}
defer r.Close()
defer w.Close()
pagerProgram := os.Getenv("PAGER")
if pagerProgram == "" {
pagerProgram = "less"
}
if _, err := exec.LookPath(pagerProgram); err != nil {
return err
}
cmd := exec.Command(pagerProgram)
cmd.Stdin = r
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = append(os.Environ(),
"LESS=-r -P "+label,
"MORE=-r -P "+label,
)
if err := cmd.Start(); err != nil {
return err
}
if err := r.Close(); err != nil {
return err
}
// If we would be streaming to a terminal and aren't forcing color one way
// or the other, we should configure things to use color so the pager gets
// colorized input.
if isTerminal(os.Stdout) && os.Getenv("FORCE_COLOR") == "" {
os.Setenv("FORCE_COLOR", "1")
}
if err := generateOutput(w); err != nil && !strings.Contains(err.Error(), "broken pipe") {
return err
}
w.Close()
return cmd.Wait()
}
func streamToStdout(generateOutput func(w *os.File) error) error {
signal.Ignore(syscall.SIGPIPE)
err := generateOutput(os.Stdout)
if err != nil && strings.Contains(err.Error(), "broken pipe") {
return nil
}
return err
}
func shouldUseColors(w io.Writer) bool {
// Check if NO_COLOR environment variable is set
if _, noColor := os.LookupEnv("NO_COLOR"); noColor {
return false
}
force, ok := os.LookupEnv("FORCE_COLOR")
if ok {
if force == "1" {
return true
}
if force == "0" {
return false
}
}
return isTerminal(w)
}
func ShowJSON(out *os.File, title string, res gjson.Result, format string, transform string) error {
if format != "raw" && transform != "" {
transformed := res.Get(transform)
if transformed.Exists() {
res = transformed
}
}
switch strings.ToLower(format) {
case "auto":
return ShowJSON(out, title, res, "json", "")
case "explore":
return jsonview.ExploreJSON(title, res)
case "pretty":
_, err := out.WriteString(jsonview.RenderJSON(title, res) + "\n")
return err
case "json":
prettyJSON := pretty.Pretty([]byte(res.Raw))
if shouldUseColors(out) {
_, err := out.Write(pretty.Color(prettyJSON, pretty.TerminalStyle))
return err
} else {
_, err := out.Write(prettyJSON)
return err
}
case "jsonl":
// @ugly is gjson syntax for "no whitespace", so it fits on one line
oneLineJSON := res.Get("@ugly").Raw
if shouldUseColors(out) {
bytes := append(pretty.Color([]byte(oneLineJSON), pretty.TerminalStyle), '\n')
_, err := out.Write(bytes)
return err
} else {
_, err := out.Write([]byte(oneLineJSON + "\n"))
return err
}
case "raw":
if _, err := out.Write([]byte(res.Raw + "\n")); err != nil {
return err
}
return nil
case "yaml":
input := strings.NewReader(res.Raw)
var yaml strings.Builder
if err := json2yaml.Convert(&yaml, input); err != nil {
return err
}
_, err := out.Write([]byte(yaml.String()))
return err
default:
return fmt.Errorf("Invalid format: %s, valid formats are: %s", format, strings.Join(OutputFormats, ", "))
}
}