Skip to content

Commit ce2e254

Browse files
DO-rraocursoragentSSharma-10claude
authored
Add a shared terminal capability layer (ui.Env) (#1939)
* Upgrade lipgloss to v1.1.1 and termenv to v0.16.0 The terminal capability layer needs lipgloss's per-writer renderer API (NewRenderer, SetColorProfile, Style.Renderer), which does not exist in v0.5.0. Styling that resolves against a process-wide renderer makes output depend on the machine running the code rather than on the stream it is written to. Co-authored-by: Cursor <cursoragent@cursor.com> * Add a shared terminal capability layer and thread it through CmdConfig Presentation decisions across doctl are currently re-derived at each call site from process-wide state: whether stdout is a terminal, whether NO_COLOR is set, and little else. That answers the question about the wrong stream when output is redirected, and it misses CI detection, terminal width, and any ASCII fallback. ui.Env resolves those facts once per invocation and carries them as a value, with colour tracked separately per stream so that piping data into another program still leaves progress on stderr styled. Animation is never inferred from colour, since CI is routinely colour-capable but must not receive animation frames. CmdConfig now carries an Env. Rendering surfaces are migrated separately. Co-authored-by: Cursor <cursoragent@cursor.com> * Pre-run flag validation and terminal error styling (#1941) * pre-run flag validation and terminal error styling * Fix pre-run validation edge cases for backup policy and error output * Fix pre-run validation to honor defaults and reuse internal/ui styling * Restore exit 1 and type-aware required flags; share UI env and palette * Standardize wait and progress handling behind one shared waiter (#1946) * Standardize wait and progress handling behind one shared waiter * Greet the user on a bare doctl instead of printing the command listing Running `doctl` with no arguments printed cobra's full grouped help, which buries the two things a newcomer needs: whether their credentials work, and where to start. Report version, account, team, and context instead, followed by a short list of next steps and an upgrade notice when one is due. The account line is resolved against /v2/account rather than inferred from whether a token is configured, because "configured" and "working" are different claims. Four outcomes are distinguished, since a user would act on each differently: no token, accepted, rejected, and unverified. Only an HTTP 401 produces "rejected" -- a 403 from a scoped token, a 5xx, a connection failure, or a timeout all leave validity genuinely unknown, and reporting those as a bad token would send someone off to rotate a working credential. Account and team are separate rows because the same login belongs to several teams, so the email alone does not say which one a command is about to act on. Both network lookups are bounded and run concurrently, so a user waits for the slower rather than their sum: three seconds for the account lookup and two for the release check, which is additionally cached for a day, skipped in CI, and disabled outright by DOCTL_NO_UPDATE_CHECK. Retries are turned off so a greeting cannot sit through a backoff sequence on a rate-limited API. With no token configured, nothing is contacted at all. There is no account to resolve, and a binary the user has not configured yet should not make unsolicited outbound requests to report that a newer one exists; the answer the greeting owes them is `auth init`, which needs no network to give. The cost is that an unauthenticated user with an outdated binary is not told so. Whether the process is in CI is passed into the release-check rule, and whether that check may run is passed into the step that gathers the greeting, rather than either being read from the environment where it is used. doctl's own tests run under a CI provider, so a rule that consulted the environment directly could not be tested without the ambient environment deciding the answer -- clearing CI is not enough when GITHUB_ACTIONS is also set. Args is left unset on the root command so cobra keeps rejecting unknown subcommands through legacyArgs; only a genuinely empty invocation reaches Run. SilenceErrors and SilenceUsage are deliberately not set, as cobra consults them on the root as well as the executed command and would suppress every subcommand's error output. The semver comparison behind the notice moves out of Complete and CompleteJSON into Version.NewerThan so the greeting can reuse it, preserving the "-release" suffix that keeps a current release build from being reported as stale; a "-dev" or "-beta" build of the same version is still flagged, as before. GithubLatestVersioner gains an optional Client so the incidental check can be time-bounded; `doctl version` behaviour is unchanged. Co-authored-by: Cursor <cursoragent@cursor.com> * rebased changes * Correct the auth command descriptions that contradict the code Co-authored-by: Cursor <cursoragent@cursor.com> * Say when the active token came from outside the config file Co-authored-by: Cursor <cursoragent@cursor.com> * Fix RunAuthSwitch build break left by the rebase writeConfig referenced a bare context identifier that was never passed in or declared, and RunAuthSwitch still carried the old viper-based existence check and the auth-contexts workaround for #996 that this branch's file-based config rewrite was meant to replace. Fold the file-based load/check/write into RunAuthSwitch directly, matching the pattern RunAuthInit and RunAuthRemove already use, and drop the orphaned writeConfig helper. * Fix ASCII glyph assertions in welcome test The ASCII fallback glyph for a valid auth state is "OK" and the unicode one is "✓" (internal/ui/glyphs.go), not "+" and "✔" as the test asserted. Those never appeared in the rendered output, so the Contains check failed and the NotContains check never exercised anything real. * Color the welcome screen's section headers "Welcome to DigitalOcean" is now bold blue (ui.ColorInfo) and "Get started" is bold green (ui.ColorSuccess), reusing the palette already defined in internal/ui/style.go instead of introducing new colors. * Distinguish record field labels from their values labelStyle stacked Faint on top of ColorMuted, and unclassified values fell back to the same ColorMuted tone as their label, so on a dark terminal a field's label and value rendered in the same washed-out grey. Drop the Faint stacking on labels, and leave an unclassified value in the default foreground so it reads apart from the label introducing it. * Structure errors as Title/Reason/Status/Next step, name exit codes checkErr now resolves every error to a StructuredError (an explicit implementation, or a genericStructuredError synthesized from the status-code table) and renders Title, Reason, Status and Next step as separate lines, mirroring the same four fields into the JSON error envelope additively (detail is unchanged). FlagValidationError implements the interface for its JSON output while keeping its own richer text block. Adds an error-code table (error_codes.go) for common API status codes (400/401/403/404/409/422/429/5xx), each with a canned reason and a "run <command>" next step so Style.Hint bolds the whole suggestion. Names the two exit codes doctl has always used (exitGeneralError=1, exitUsageError=255) instead of magic numbers, and routes the config-read failure through checkErr instead of a raw log.Fatalln so it gets the same formatting and a controlled exit code. Also fixes a pre-existing bug in auth.go's writeConfig(), which referenced an out-of-scope `context` identifier and could not compile; it's now a parameter from its one call site. * Surface the API's message, request ID, and a saner 404 next step Reason() preferred the canned status-code table text over the API's own message, so the specific detail a request failed with (e.g. "the requested resource does not exist") never reached text output, only JSON's detail field. It now prefers godo.ErrorResponse.Message, falling back to the table only when the API had nothing more to say. A 404's canned next step was "run doctl auth list", which fits a wrong-context request no better than a plain typo'd ID, and the latter is by far the more common case. Dropped it in favor of StructuredError.NextStep() falling through to the command's own --help when the table entry has nothing to suggest. Added RequestID() to StructuredError so the identifier the API assigned a request is available for support to look up, in text output and the JSON envelope, instead of being buried in Error()'s full text. Status and request-id values are painted in a light grey distinct from both their label and the bold default-colored command path in the hint line beneath them. * Update integration fixtures for the structured error format These fixtures still asserted the plain, pre-structured error text (or, for the retry tests, a hardcoded string with reversed testify arguments that masked which side was real). None of this was a regression: the structured-error commit that introduced Title/ Reason/Status/NextStep never updated the golden output these tests compare against. Update each to the new format, appending the command-specific --help hint where the shared confirmation-abort or timestamp-format constants can't since it differs per command. The two retry-flag tests now expect identical output for the retried-and-exhausted and retries-disabled cases: Reason() reads godo.ErrorResponse.Message, not Error()'s full text, so the "giving up after N attempts" annotation that used to distinguish them is no longer part of what's shown. * Add shared colorful --help layout for all doctl commands * Highlight doctl invocations embedded in Example prose * Fix Example highlighting across services * Greet the user on a bare `doctl`, and stop auth commands rewriting the config file (#1954) * Greet the user on a bare doctl instead of printing the command listing Running `doctl` with no arguments printed cobra's full grouped help, which buries the two things a newcomer needs: whether their credentials work, and where to start. Report version, account, team, and context instead, followed by a short list of next steps and an upgrade notice when one is due. The account line is resolved against /v2/account rather than inferred from whether a token is configured, because "configured" and "working" are different claims. Four outcomes are distinguished, since a user would act on each differently: no token, accepted, rejected, and unverified. Only an HTTP 401 produces "rejected" -- a 403 from a scoped token, a 5xx, a connection failure, or a timeout all leave validity genuinely unknown, and reporting those as a bad token would send someone off to rotate a working credential. Account and team are separate rows because the same login belongs to several teams, so the email alone does not say which one a command is about to act on. Both network lookups are bounded and run concurrently, so a user waits for the slower rather than their sum: three seconds for the account lookup and two for the release check, which is additionally cached for a day, skipped in CI, and disabled outright by DOCTL_NO_UPDATE_CHECK. Retries are turned off so a greeting cannot sit through a backoff sequence on a rate-limited API. With no token configured, nothing is contacted at all. There is no account to resolve, and a binary the user has not configured yet should not make unsolicited outbound requests to report that a newer one exists; the answer the greeting owes them is `auth init`, which needs no network to give. The cost is that an unauthenticated user with an outdated binary is not told so. Whether the process is in CI is passed into the release-check rule, and whether that check may run is passed into the step that gathers the greeting, rather than either being read from the environment where it is used. doctl's own tests run under a CI provider, so a rule that consulted the environment directly could not be tested without the ambient environment deciding the answer -- clearing CI is not enough when GITHUB_ACTIONS is also set. Args is left unset on the root command so cobra keeps rejecting unknown subcommands through legacyArgs; only a genuinely empty invocation reaches Run. SilenceErrors and SilenceUsage are deliberately not set, as cobra consults them on the root as well as the executed command and would suppress every subcommand's error output. The semver comparison behind the notice moves out of Complete and CompleteJSON into Version.NewerThan so the greeting can reuse it, preserving the "-release" suffix that keeps a current release build from being reported as stale; a "-dev" or "-beta" build of the same version is still flagged, as before. GithubLatestVersioner gains an optional Client so the incidental check can be time-bounded; `doctl version` behaviour is unchanged. Co-authored-by: Cursor <cursoragent@cursor.com> * rebased changes * Correct the auth command descriptions that contradict the code Co-authored-by: Cursor <cursoragent@cursor.com> * Say when the active token came from outside the config file Co-authored-by: Cursor <cursoragent@cursor.com> * Fix RunAuthSwitch build break left by the rebase writeConfig referenced a bare context identifier that was never passed in or declared, and RunAuthSwitch still carried the old viper-based existence check and the auth-contexts workaround for #996 that this branch's file-based config rewrite was meant to replace. Fold the file-based load/check/write into RunAuthSwitch directly, matching the pattern RunAuthInit and RunAuthRemove already use, and drop the orphaned writeConfig helper. * Fix ASCII glyph assertions in welcome test The ASCII fallback glyph for a valid auth state is "OK" and the unicode one is "✓" (internal/ui/glyphs.go), not "+" and "✔" as the test asserted. Those never appeared in the rendered output, so the Contains check failed and the NotContains check never exercised anything real. * Color the welcome screen's section headers "Welcome to DigitalOcean" is now bold blue (ui.ColorInfo) and "Get started" is bold green (ui.ColorSuccess), reusing the palette already defined in internal/ui/style.go instead of introducing new colors. * Distinguish record field labels from their values labelStyle stacked Faint on top of ColorMuted, and unclassified values fell back to the same ColorMuted tone as their label, so on a dark terminal a field's label and value rendered in the same washed-out grey. Drop the Faint stacking on labels, and leave an unclassified value in the default foreground so it reads apart from the label introducing it. --------- Co-authored-by: Cursor <cursoragent@cursor.com> * Narrow the next-step hint to failures it can answer Review feedback on the structured error format raised three problems, each about a hint or a detail being wrong rather than missing. `--help` was the fallback for every unannotated error, so it followed both errors that already said what to do ("access token is required. (hint: run 'doctl auth init')") and errors it cannot explain at all - a 404, a refused connection, an exhausted retry. It is now offered only for failures doctl raised itself, such as a bad argument or a rejected flag combination, and withheld once a request carries a status code or a transport error. A status-code entry with no NextStep now means what its comment always claimed - nothing useful to suggest - instead of falling through to --help. 409 and 5xx no longer suggest re-running the command that just failed. 409 drops the hint outright; the 5xx entries keep it only while retries have not been spent, since the retry client giving up is evidence that trying again immediately will not help. godo records the retry count in ErrorResponse.Error() but not in .Message, and the structured block reads .Message, so an exhausted retry and a disabled one printed identically. The Reason line now carries the count. Two defects surfaced while testing the above: - A confirmation declined outside a terminal printed a warning and returned ErrExitSilently, so `--output json` produced a bare warning on stderr and nothing on stdout. It is a real error now, rendered once in whichever format was asked for. - commands/auth.go wrapped a rejected token with %s, hiding the godo error from errors.As. A 401 from `doctl auth init` lost its title, status, request ID and its `doctl auth init` hint, degrading to raw text followed by a generic --help. About fifty confirm-abort call sites discarded whatever AskForConfirm returned and substituted a generic "Operation aborted.", which is how the non-interactive warning came to be followed by a contradicting --help. They now return the error they were handed, via confirmAction and confirmDelete. `auth switch` and `auth remove` also disagreed about what to call a missing context; both now report it the same way and point at `doctl auth list`. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Keep the error block readable when the failure is not well behaved Three gaps found while testing the previous commit, all cases where the structured block either fell apart or said nothing useful. godo fills ErrorResponse.Message with the raw response body when that body is not the JSON it expected, so a proxy or load balancer between doctl and the API can put an HTML error page there. Reason printed it verbatim: a realistic nginx 502 rendered fifty-two lines of markup where one sentence belongs. A message is now quoted only if it reads like one - single line, no leading tag, and short enough to be a sentence - and the status code's canned reason is used otherwise. The raw body is still in the JSON detail. The attempt count moved so that it survives this fallback; previously a 502 with an unparseable body lost it. Fourteen call sites wrapped an API error with %v or %s, which hides it from errors.As. The same 409 rendered as a clean block from one command and as a raw line with the method and URL in it from another. They wrap with %w now. That alone would have cost something: with the godo error recovered, Title returns the status name, so "Unable to delete Droplet 111" became "Conflict" and `droplet delete 111 222` no longer said which one failed. Title now prefers the sentence the call site wrote, falling back to the status name when there is none. The status keeps its own line either way. Cobra rejects an unknown subcommand only at the root, so `doctl bogus` exited 255 while `doctl compute bogus` printed the compute help and exited 0 - a typo indistinguishable from success to anything reading the exit code. Commands that exist only to dispatch to children now reject an argument naming no child. The check lives in RunE because cobra returns flag.ErrHelp for a non-runnable command before it validates arguments; being runnable also means a bare `doctl compute` still prints its help. One visible consequence: a group's usage block gains the "[flags]" line that the root command has always shown. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Mask secrets and database credentials unless --show or CI is set (#1966) * Mask secrets and database credentials unless --show or CI is set Secret values and database passwords/connection strings were shown in plain text by default, and secrets get had its own local --show flag. Promote --show to a global flag, and gate masking on it and on CI through the shared ui.Env capability layer so scripted/CI usage still gets the real value without passing --show explicitly. Also fold IsCI() into the same layer that decides color and TTY-gated layout (cards, boxed tables, the records fallback), so CI gets the same plain, uncolored output it always did even on a runner whose streams would otherwise pass every terminal capability check. * Mention masking in database user create/group help text The list/get help text already noted the password is masked by default and how to reveal it, but the user group description and create command's help did not, leaving the tradeoff undocumented where a user would first encounter the generated password. * pin to godo-v1.210.0 * test fix * test fix * Skip welcome-screen API calls when stdout is not a TTY (#2017) * Skip welcome-screen API calls when stdout is not a TTY. Bare `doctl` used to be instant and offline; the greeting's account lookup made health checks and pipes hit the API. Leave Version and Context, and omit Account/Team instead of reporting a failed check. Co-authored-by: Cursor <cursoragent@cursor.com> * Gate welcome-screen lookups on env.DataTTY. That is the same interactive-stdout check cards and boxed tables already use, so a pipe, CI, or machine output skips the API without a second isTerminal helper. Co-authored-by: Cursor <cursoragent@cursor.com> * Omit JSON auth fields when the welcome lookup is skipped. Machine output stays offline with DataTTY, so reporting unverified would look like a failed check rather than a lookup that never ran. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> * Next gen: neutral table borders, readable list colors, lookup commands in help (#2039) * Next gen: neutral table borders, readable list colors, lookup commands in help Address phase 1 review feedback: - Draw boxed table and card borders in a neutral gray (ColorFrame) instead of the success green, so a frame no longer implies a state. - List (records) layout: labels in a slate gray (ColorLabel) that stays legible on dark backgrounds, separators in the frame gray, and only the resource name accented so it stands apart from the ID. - Help: EXAMPLES now opens with the commands that list valid values for the command's flags (e.g. size, image, region for droplet create), derived from flag hints. Required flags lead, then flags the examples use. - Add a shared fallback hint for --project-id, --vpc-uuid, --private-network-uuid and --ssh-keys, and explicit hints on the main create commands (databases, load balancer, volume, VPC, reserved IP, droplet autoscale). Point droplet create --image at image list-distribution. Co-authored-by: Cursor <cursoragent@cursor.com> * Document installing a previous version of doctl Add per-platform instructions for going back to an earlier release (for example v2 to v1): the release binary as the default on any OS, Homebrew pin and replacement on macOS, snap revert and hold on Linux, the zip and community package managers on Windows, plus Docker tags and go install. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> * test fix * Update signals deletion integration expectations for next-gen errors Confirmation refusal and missing --type now render through checkErr / flag validation as Error: / Missing required flag, not the old Warning and missing-arguments wording brought in with main. Co-authored-by: Cursor <cursoragent@cursor.com> * Use shared error formatting for hosted-agent failures --------- Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: SSharma-10 <shivanisharma@digitalocean.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1 parent 89a2557 commit ce2e254

150 files changed

Lines changed: 12232 additions & 2054 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎README.md‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,8 @@ To set a new default context, run `doctl auth switch --context <new-context-name
388388

389389
The `--access-token` flag or `DIGITALOCEAN_ACCESS_TOKEN` [environment variable](#environment-variables) are acknowledged only if the `default` context is used. Otherwise, they will have no effect on what API access token is used. To temporarily override the access token if a different context is set as default, use `doctl --context default --access-token your_DO_token ...`.
390390

391+
When the `default` context is used, the flag and the environment variable take precedence over the token saved in your configuration file, and they apply only to the command you run: `doctl` does not write them to the file. The exception is `doctl auth init`, which saves the token it validates whatever its source, because saving a token is what that command is for. Run `doctl` with no arguments to see which account is active and whether its token came from your configuration file or from the environment.
392+
391393
## Configuring Default Values
392394

393395
The `doctl` configuration file is used to store your API Access Token as well as the defaults for command flags. If you find yourself using certain flags frequently, you can change their default values to avoid typing them every time. This can be useful when, for example, you want to change the username or port used for SSH.
@@ -396,9 +398,11 @@ On OS X, `doctl` saves its configuration as `${HOME}/Library/Application Support
396398

397399
On Linux, `doctl` saves its configuration as `${XDG_CONFIG_HOME}/doctl/config.yaml` if the `${XDG_CONFIG_HOME}` environmental variable is set, or `~/.config/doctl/config.yaml` if it is not. On Windows, the config file location is `%APPDATA%\doctl\config.yaml`.
398400

399-
The configuration file is automatically created and populated with default properties when you authenticate with `doctl` for the first time. The typical format for a property is `category.command.sub-command.flag: value`. For example, the property for the `force` flag with tag deletion is `tag.delete.force`.
401+
The configuration file is created when you authenticate with `doctl` for the first time. It holds your credentials plus any flag defaults you choose to set. `doctl` only writes the settings you ask it to save, so you set a default by adding the property yourself. The format for a property is `category.command.sub-command.flag: value`. For example, the property for the `force` flag with tag deletion is `tag.delete.force`.
402+
403+
Configuration files written by older versions of `doctl` contain a large block of pre-populated properties. Those are still honored, and `doctl` leaves them alone; you can delete any you have not deliberately changed.
400404

401-
To change the default SSH user used when connecting to a Droplet with `doctl`, look for the `compute.ssh.ssh-user` property and change the value after the colon. In this example, we changed it to the username **sammy**.
405+
To change the default SSH user used when connecting to a Droplet with `doctl`, add the `compute.ssh.ssh-user` property with the username you want. In this example, we set it to **sammy**.
402406

403407
```
404408
. . .
@@ -422,6 +426,35 @@ DIGITALOCEAN_CONTEXT=my-context doctl auth list
422426
DIGITALOCEAN_ACCESS_TOKEN=my-do-token doctl
423427
```
424428

429+
These affect only the session, and `doctl` never writes them to `config.yaml`. `doctl auth init` is the exception: it saves the token it validates, so running it with `DIGITALOCEAN_ACCESS_TOKEN` set replaces the token stored for the `default` context with the one from your environment.
430+
431+
Running `doctl` with no arguments prints a short summary of your version and
432+
authentication state, and tells you when a newer release is available:
433+
434+
```
435+
Welcome to DigitalOcean
436+
doctl is the command line interface for the DigitalOcean API.
437+
438+
Version 1.146.0
439+
Account ✔ sammy@example.com
440+
Team Sharks
441+
Context default
442+
```
443+
444+
The account line reflects what the API says about the token for your current
445+
context, so it distinguishes a working token from one that has been revoked. If
446+
the API cannot be reached, the token is reported as unverified rather than
447+
rejected. `Team` is shown when the token is scoped to a team, since the same
448+
login can belong to several.
449+
450+
The release check contacts GitHub at most once a day and is skipped
451+
automatically in CI. Until you have authenticated, `doctl` makes no network
452+
requests at all. To turn the check off entirely:
453+
454+
```
455+
DOCTL_NO_UPDATE_CHECK=1 doctl
456+
```
457+
425458
## Enabling Shell Auto-Completion
426459

427460
`doctl` also has auto-completion support. It can be set up so that if you partially type a command and then press `TAB`, the rest of the command is automatically filled in. For example, if you type `doctl comp<TAB><TAB> drop<TAB><TAB>` with auto-completion enabled, you'll see `doctl compute droplet` appear on your command prompt.

‎args.go‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,8 @@ const (
203203
ArgCommandUpdateSources = "update-sources"
204204
// ArgCommandWait is a wait for a resource to be created argument.
205205
ArgCommandWait = "wait"
206+
// ArgWaitTimeout bounds how long --wait polls before giving up.
207+
ArgWaitTimeout = "wait-timeout"
206208
// ArgSetCurrentContext is a flag to set the new kubeconfig context as current.
207209
ArgSetCurrentContext = "set-current-context"
208210
// ArgDropletID is a droplet id argument.
@@ -231,6 +233,8 @@ const (
231233
ArgImageSlug = "image-slug"
232234
// ArgInteractive is the argument to enable an interactive CLI.
233235
ArgInteractive = "interactive"
236+
// ArgShow reveals masked values, such as secrets, instead of hiding them.
237+
ArgShow = "show"
234238
// ArgIPAddress is an IP address argument.
235239
ArgIPAddress = "ip-address"
236240
// ArgDropletName is a droplet name argument.
@@ -734,12 +738,7 @@ const (
734738
ArgSecretFromEnvFile = "from-env-file"
735739
// ArgSecretVersion is the current version of a secret for update operations.
736740
ArgSecretVersion = "version"
737-
// ArgSecretShow reveals secret values instead of masking them on get.
738-
ArgSecretShow = "show"
739-
// ArgSecretShowKV reveals secret values instead of masking them on get,
740-
// formatted as:
741-
//
742-
// KEY=VALUE
741+
// ArgSecretShowKV prints secret values as KEY=VALUE pairs on get.
743742
ArgSecretShowKV = "kvs"
744743
// ArgSecretRaw writes a single secret value to stdout with no formatting.
745744
ArgSecretRaw = "raw"

‎commands/account.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ func RunAccountRateLimit(c *CmdConfig) error {
7878
accessToken := c.getContextAccessToken()
7979
godoClient, err := c.Doit.GetGodoClient(Trace, false, accessToken)
8080
if err != nil {
81-
return fmt.Errorf("Unable to initialize DigitalOcean API client: %s", err)
81+
return fmt.Errorf("Unable to initialize DigitalOcean API client: %w", err)
8282
}
8383

8484
c.Account = func() do.AccountService { return do.NewAccountService(godoClient) }

‎commands/actions.go‎

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ limitations under the License.
1414
package commands
1515

1616
import (
17+
"fmt"
1718
"sort"
1819
"strconv"
1920
"time"
@@ -67,6 +68,7 @@ For example, if you find an action when calling `+"`"+`doctl compute action list
6768
aliasOpt("w"), displayerType(&displayers.Action{}))
6869
cmdActionWait.Example = `The following example waits for the action ` + "`" + `123456` + "`" + ` to complete before allowing further commands to execute: doctl compute action wait 123456`
6970
AddIntFlag(cmdActionWait, doctl.ArgPollTime, "", 5, "Re-poll time in seconds")
71+
AddDurationFlag(cmdActionWait, doctl.ArgWaitTimeout, "", defaultActionWaitTimeout, waitTimeoutDesc)
7072

7173
return cmd
7274
}
@@ -237,23 +239,52 @@ func RunCmdActionWait(c *CmdConfig) error {
237239
}
238240

239241
func actionWait(c *CmdConfig, actionID, pollTime int) (*do.Action, error) {
240-
as := c.Actions()
242+
w, err := newWaiter(c)
243+
if err != nil {
244+
return nil, err
245+
}
241246

242-
var a *do.Action
243-
var err error
247+
return waitForAction(w, c.Actions(), actionID, time.Duration(pollTime)*time.Second)
248+
}
244249

245-
for {
246-
a, err = as.Get(actionID)
250+
// waitForAction polls an action until it leaves the in-progress state. An
251+
// action that ends in `errored` is reported as a failure: it used to be
252+
// returned as a successful wait, which left `--wait` claiming a resource was
253+
// ready when the API had already given up on it.
254+
func waitForAction(w waiter, as do.ActionsService, actionID int, interval time.Duration) (*do.Action, error) {
255+
var action *do.Action
256+
257+
err := w.wait(waitOp{
258+
Activity: fmt.Sprintf("Running action (%d)", actionID),
259+
Subject: fmt.Sprintf("action (%d) to complete", actionID),
260+
Success: fmt.Sprintf("Action (%d) completed", actionID),
261+
Interval: interval,
262+
}, func() (bool, string, error) {
263+
a, err := as.Get(actionID)
247264
if err != nil {
248-
return nil, err
265+
return false, "", err
249266
}
250267

251-
if a.Status != "in-progress" {
252-
break
268+
action = a
269+
270+
switch a.Status {
271+
case "in-progress":
272+
// The only status an action in flight reports, so naming it says
273+
// nothing the spinner has not already said.
274+
return false, "", nil
275+
case "errored":
276+
return false, "", fmt.Errorf("action (%d) failed", actionID)
277+
default:
278+
return true, a.Status, nil
253279
}
254-
255-
time.Sleep(time.Duration(pollTime) * time.Second)
280+
})
281+
if err != nil {
282+
// The action goes back with the error when one was fetched, so a
283+
// caller can show what the API last said about it rather than only
284+
// the error string. It stays nil when the poll itself never
285+
// succeeded.
286+
return action, err
256287
}
257288

258-
return a, nil
289+
return action, nil
259290
}

‎commands/agent_port_forward_test.go‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ import (
2828

2929
"github.com/digitalocean/doctl/do"
3030
"github.com/digitalocean/doctl/internal/deviceid"
31+
"github.com/digitalocean/doctl/internal/ui"
3132
"github.com/digitalocean/godo"
32-
"github.com/fatih/color"
3333
"github.com/gorilla/websocket"
3434
"github.com/spf13/viper"
3535
"github.com/stretchr/testify/assert"
@@ -442,9 +442,8 @@ func TestExplainTunnelClose(t *testing.T) {
442442
// rewrite: one browser page load opens several connections, and an unstarted
443443
// server made each of them print the same line.
444444
func TestTunnelWarnerSuppressesRepeats(t *testing.T) {
445-
defer func(a io.Writer) { color.Output = a }(color.Output)
446445
var buf bytes.Buffer
447-
color.Output = &buf
446+
withUIEnv(t, ui.Plain(&buf, &buf))
448447

449448
w := newTunnelWarner(8080)
450449
unreachable := &websocket.CloseError{Code: 4002, Text: "guest port unreachable"}

‎commands/agents.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4664,7 +4664,7 @@ func classifyStreamError(err error) (string, bool) {
46644664
if reason := strings.TrimSpace(msg); reason != "" {
46654665
ape.reason = reason
46664666
}
4667-
return "\n" + ape.DisplayError(), true
4667+
return "\n" + strings.TrimRight(formatStructuredError(uiEnv(), ape), "\n"), true
46684668
}
46694669
return "\n" + strings.TrimSpace(err.Error()), true
46704670
}

‎commands/agents_billing.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ func (s *attachState) clearPrepayBlocked() {
136136
s.mu.Unlock()
137137
}
138138

139-
// printPrepayBlocked renders the add-funds card inline and leaves the session
139+
// printPrepayBlocked renders the add-funds error inline and leaves the session
140140
// attached. The work is intact and the next prompt succeeds once funds land —
141141
// harness-api resumes implicitly on the next send — so tearing the attach down
142142
// would discard a recoverable state for a condition the user can fix from
@@ -145,7 +145,8 @@ func printPrepayBlocked(c *CmdConfig, state *attachState, cause error) {
145145
if !state.notePrepayBlocked() {
146146
return
147147
}
148-
fmt.Fprintf(c.Out, "\n%s\n", newPrepayBlockedError(c, cause).DisplayError())
148+
env := resolveUIEnv(c.Out)
149+
fmt.Fprintf(c.Out, "\n%s", formatStructuredError(env, newPrepayBlockedError(c, cause)))
149150
}
150151

151152
// reportHITLResolveErr renders a failed approval resolution. Resolving an

‎commands/agents_billing_test.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ func TestNewPrepayBlockedError_Enrichment(t *testing.T) {
181181

182182
assert.Equal(t, []string{"Ask your Team Owner or Biller to add funds"}, pretty.tips)
183183
// The caller cannot open the billing page, so it must not be offered.
184-
assert.NotContains(t, pretty.DisplayError(), prepayTopUpURL)
184+
assert.NotContains(t, pretty.NextStep(), prepayTopUpURL)
185185
})
186186

187187
t.Run("a billing failure falls back to the plain card", func(t *testing.T) {
@@ -191,7 +191,8 @@ func TestNewPrepayBlockedError_Enrichment(t *testing.T) {
191191
assert.Equal(t, prepayBlockedTitle, pretty.title)
192192
assert.Contains(t, pretty.tips, fmt.Sprintf("Add funds at %s", prepayTopUpURL))
193193
// A billing lookup must never turn a clean 402 into a double error.
194-
assert.NotContains(t, pretty.DisplayError(), "billing is down")
194+
assert.NotContains(t, pretty.Reason(), "billing is down")
195+
assert.NotContains(t, pretty.NextStep(), "billing is down")
195196
})
196197

197198
t.Run("an uninitialized config still renders", func(t *testing.T) {

‎commands/agents_errors.go‎

Lines changed: 39 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,10 @@ import (
1717
"errors"
1818
"fmt"
1919
"net/http"
20-
"os"
2120
"regexp"
2221
"strconv"
2322
"strings"
2423
"unicode"
25-
26-
"golang.org/x/term"
2724
)
2825

2926
// godoErrorLine matches godo.ErrorResponse.Error() output:
@@ -45,7 +42,9 @@ var unknownFieldQuotedRE = regexp.MustCompile(`unknown field "([^"]*)"`)
4542
var contractsPathHintRE = regexp.MustCompile(`;?\s*see contracts/[A-Za-z0-9._/-]+`)
4643

4744
// agentPrettyError is a user-facing agent CLI error: human title + reason,
48-
// without METHOD/URL/status noise from raw godo ErrorResponse strings.
45+
// without METHOD/URL/status noise from raw godo ErrorResponse strings. It
46+
// implements StructuredError so checkErr and inline stream failures share the
47+
// same Title/Reason/status/next-step layout as every other doctl command.
4948
type agentPrettyError struct {
5049
title string
5150
reason string
@@ -74,68 +73,63 @@ func (e *agentPrettyError) Unwrap() error {
7473
return e.cause
7574
}
7675

77-
// DisplayError returns the styled multi-line form printed by checkErr for
78-
// agent commands (instead of "Error: METHOD URL: 400 …").
79-
func (e *agentPrettyError) DisplayError() string {
76+
func (e *agentPrettyError) Title() string {
8077
if e == nil {
8178
return ""
8279
}
83-
prev := stylingEnabled
84-
stylingEnabled = agentErrorStyling()
85-
defer func() { stylingEnabled = prev }()
86-
87-
var b strings.Builder
88-
title := strings.TrimSpace(e.title)
89-
if title == "" {
90-
title = "Something went wrong"
80+
if title := strings.TrimSpace(e.title); title != "" {
81+
return title
9182
}
92-
fmt.Fprintf(&b, "%s %s\n", colorize("✗", colError), boldColor(title, colError))
83+
return "Something went wrong"
84+
}
9385

86+
func (e *agentPrettyError) Reason() string {
87+
if e == nil {
88+
return ""
89+
}
9490
reason := strings.TrimSpace(e.reason)
9591
if reason == "" && e.cause != nil {
9692
reason = strings.TrimSpace(e.cause.Error())
9793
}
98-
if reason != "" && !strings.EqualFold(reason, title) {
99-
fmt.Fprintf(&b, " %s\n", reason)
100-
}
101-
if e.status > 0 {
102-
b.WriteString(cardRow("Status", colorize(httpStatusLabel(e.status), colMuted)))
94+
if reason == "" || strings.EqualFold(reason, e.Title()) {
95+
return ""
10396
}
104-
if len(e.tips) > 0 {
105-
fmt.Fprintln(&b)
106-
fmt.Fprintln(&b, colorize("Next step", colMuted))
107-
for _, tip := range e.tips {
108-
tip = strings.TrimSpace(tip)
109-
if tip == "" {
110-
continue
111-
}
112-
fmt.Fprintf(&b, " %s\n", tip)
113-
}
97+
return reason
98+
}
99+
100+
func (e *agentPrettyError) Status() int {
101+
if e == nil {
102+
return 0
114103
}
115-
return strings.TrimRight(b.String(), "\n")
104+
return e.status
116105
}
117106

118-
func agentErrorStyling() bool {
119-
if os.Getenv("NO_COLOR") != "" {
120-
return false
107+
func (e *agentPrettyError) RequestID() string {
108+
if e == nil {
109+
return ""
121110
}
122-
return term.IsTerminal(int(os.Stderr.Fd()))
111+
return genericStructuredError{err: e.cause}.RequestID()
123112
}
124113

125-
func httpStatusLabel(code int) string {
126-
text := http.StatusText(code)
127-
if text == "" {
128-
return fmt.Sprintf("%d", code)
114+
func (e *agentPrettyError) NextStep() string {
115+
if e == nil {
116+
return ""
117+
}
118+
parts := make([]string, 0, len(e.tips))
119+
for _, tip := range e.tips {
120+
if tip = strings.TrimSpace(tip); tip != "" {
121+
parts = append(parts, tip)
122+
}
129123
}
130-
return fmt.Sprintf("%d %s", code, text)
124+
return strings.Join(parts, "; ")
131125
}
132126

133127
// beautifyAgentErrorFor is beautifyAgentError plus billing enrichment: a
134128
// prepayment-gate 402 gets the team's live balance and auto top-off state
135-
// folded into its card. Every spend path returns through here, so no call site
136-
// has to opt in.
129+
// folded into the StructuredError. Every spend path returns through here, so
130+
// no call site has to opt in.
137131
//
138-
// It re-derives the prepay card even from an already-beautified error, because
132+
// It re-derives the prepay error even from an already-beautified error, because
139133
// several commands beautify early and would otherwise keep the plain variant.
140134
func beautifyAgentErrorFor(c *CmdConfig, err error) error {
141135
if err == nil {
@@ -148,7 +142,7 @@ func beautifyAgentErrorFor(c *CmdConfig, err error) error {
148142
}
149143

150144
// beautifyAgentError rewrites bare API/local errors into agentPrettyError so
151-
// checkErr can render a card instead of a raw REST dump.
145+
// checkErr can render the shared structured layout instead of a raw REST dump.
152146
func beautifyAgentError(err error) error {
153147
if err == nil {
154148
return nil
@@ -357,8 +351,3 @@ func isCopyPasteSpace(r rune) bool {
357351
}
358352
return unicode.IsSpace(r) && r != ' ' && r != '\t' && r != '\n' && r != '\r'
359353
}
360-
361-
// displayableError is implemented by agentPrettyError for checkErr.
362-
type displayableError interface {
363-
DisplayError() string
364-
}

0 commit comments

Comments
 (0)
⌂ 换网址