|
1 | 1 | package command |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "errors" |
4 | 5 | "fmt" |
5 | 6 | "io" |
6 | 7 | "os" |
@@ -184,6 +185,49 @@ var apiClientForContext = func(ctx context.Context) (*api.Client, error) { |
184 | 185 | return api.NewClient(opts...), nil |
185 | 186 | } |
186 | 187 |
|
| 188 | +func ensureScopes(ctx context.Context, client *api.Client, wantedScopes ...string) (*api.Client, error) { |
| 189 | + hasScopes, appID, err := client.HasScopes(wantedScopes...) |
| 190 | + if err != nil { |
| 191 | + return client, err |
| 192 | + } |
| 193 | + |
| 194 | + if hasScopes { |
| 195 | + return client, nil |
| 196 | + } |
| 197 | + |
| 198 | + if config.IsGitHubApp(appID) && utils.IsTerminal(os.Stdin) && utils.IsTerminal(os.Stderr) { |
| 199 | + newToken, loginHandle, err := config.AuthFlow("Notice: additional authorization required") |
| 200 | + if err != nil { |
| 201 | + return client, err |
| 202 | + } |
| 203 | + cfg, err := ctx.Config() |
| 204 | + if err != nil { |
| 205 | + return client, err |
| 206 | + } |
| 207 | + _ = cfg.Set(defaultHostname, "oauth_token", newToken) |
| 208 | + _ = cfg.Set(defaultHostname, "user", loginHandle) |
| 209 | + // update config file on disk |
| 210 | + err = cfg.Write() |
| 211 | + if err != nil { |
| 212 | + return client, err |
| 213 | + } |
| 214 | + // update configuration in memory |
| 215 | + config.AuthFlowComplete() |
| 216 | + reloadedClient, err := apiClientForContext(ctx) |
| 217 | + if err != nil { |
| 218 | + return client, err |
| 219 | + } |
| 220 | + |
| 221 | + return reloadedClient, nil |
| 222 | + } else { |
| 223 | + fmt.Fprintln(os.Stderr, fmt.Sprintf("Warning: gh now requires the `%s` OAuth scope(s).", wantedScopes)) |
| 224 | + fmt.Fprintln(os.Stderr, fmt.Sprintf("Visit https://github.com/settings/tokens and edit your token to enable %s", wantedScopes)) |
| 225 | + fmt.Fprintln(os.Stderr, "or generate a new token and paste it via `gh config set -h github.com oauth_token MYTOKEN`") |
| 226 | + return client, errors.New("Unable to reauthenticate") |
| 227 | + } |
| 228 | + |
| 229 | +} |
| 230 | + |
187 | 231 | func apiVerboseLog() api.ClientOption { |
188 | 232 | logTraffic := strings.Contains(os.Getenv("DEBUG"), "api") |
189 | 233 | colorize := utils.IsTerminal(os.Stderr) |
|
0 commit comments