2022-02-10 08:33:27 -06:00
package cli
import (
2023-08-14 12:12:17 -08:00
"bufio"
"bytes"
2022-09-08 23:59:28 +10:00
"context"
2023-05-24 11:08:03 -05:00
"encoding/base64"
"encoding/json"
2023-03-23 17:42:20 -05:00
"errors"
2022-05-19 15:35:59 -07:00
"fmt"
2022-10-17 08:43:30 -05:00
"io"
2023-03-23 17:42:20 -05:00
"math/rand"
2023-01-29 15:47:24 -06:00
"net"
2022-09-12 16:22:05 -05:00
"net/http"
2022-02-10 08:33:27 -06:00
"net/url"
"os"
2023-08-14 12:12:17 -08:00
"os/exec"
2023-01-11 10:22:20 -06:00
"os/signal"
"path/filepath"
2022-12-14 10:36:28 -06:00
"runtime"
2022-05-23 12:19:33 -05:00
"strings"
2023-01-11 10:22:20 -06:00
"syscall"
2023-04-07 17:58:21 -05:00
"text/tabwriter"
2022-04-04 20:35:03 -05:00
"time"
2022-02-10 08:33:27 -06:00
2023-06-14 21:52:01 +10:00
"github.com/mattn/go-isatty"
"github.com/mitchellh/go-wordwrap"
2023-03-23 17:42:20 -05:00
"golang.org/x/exp/slices"
2022-05-23 14:51:49 -04:00
"golang.org/x/xerrors"
2023-09-07 17:28:22 -04:00
"github.com/coder/pretty"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/buildinfo"
"github.com/coder/coder/v2/cli/clibase"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/cli/config"
2023-09-01 18:41:22 +03:00
"github.com/coder/coder/v2/cli/gitauth"
2023-09-04 21:42:45 +03:00
"github.com/coder/coder/v2/cli/telemetry"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
2022-02-10 08:33:27 -06:00
)
2022-02-21 12:47:08 -06:00
var (
2023-09-07 17:28:22 -04:00
Caret = pretty . Sprint ( cliui . DefaultStyles . Prompt , "" )
2022-05-09 17:42:02 -05:00
// Applied as annotations to workspace commands
// so they display in a separated "help" section.
workspaceCommand = map [ string ] string {
2022-07-12 23:24:53 +03:00
"workspaces" : "" ,
2022-05-09 17:42:02 -05:00
}
2022-02-21 12:47:08 -06:00
)
2022-02-10 08:33:27 -06:00
const (
2022-08-29 11:30:06 -07:00
varURL = "url"
varToken = "token"
varAgentToken = "agent-token"
2023-10-05 15:41:05 -05:00
varAgentTokenFile = "agent-token-file"
2022-08-29 11:30:06 -07:00
varAgentURL = "agent-url"
2022-09-12 16:22:05 -05:00
varHeader = "header"
2023-08-14 12:12:17 -08:00
varHeaderCommand = "header-command"
2022-08-29 11:30:06 -07:00
varNoOpen = "no-open"
varNoVersionCheck = "no-version-warning"
varNoFeatureWarning = "no-feature-warning"
varForceTty = "force-tty"
varVerbose = "verbose"
2023-06-22 06:22:43 +10:00
varDisableDirect = "disable-direct-connections"
2022-08-29 11:30:06 -07:00
notLoggedInMessage = "You are not logged in. Try logging in using 'coder login <url>'."
2022-06-24 18:50:35 -05:00
2022-08-29 11:30:06 -07:00
envNoVersionCheck = "CODER_NO_VERSION_WARNING"
envNoFeatureWarning = "CODER_NO_FEATURE_WARNING"
2022-10-11 11:58:28 -04:00
envSessionToken = "CODER_SESSION_TOKEN"
2023-03-23 18:38:15 -05:00
//nolint:gosec
envAgentToken = "CODER_AGENT_TOKEN"
2023-10-05 15:41:05 -05:00
//nolint:gosec
envAgentTokenFile = "CODER_AGENT_TOKEN_FILE"
envURL = "CODER_URL"
2022-06-29 17:49:40 -05:00
)
2023-02-18 18:32:09 -06:00
var errUnauthenticated = xerrors . New ( notLoggedInMessage )
2022-02-10 08:33:27 -06:00
2023-03-23 17:42:20 -05:00
func ( r * RootCmd ) Core () [] * clibase . Cmd {
2022-11-03 04:30:00 +10:00
// Please re-sort this list alphabetically if you change it!
2023-03-23 17:42:20 -05:00
return [] * clibase . Cmd {
r . dotfiles (),
2023-10-09 18:04:35 -05:00
r . externalAuth (),
2023-03-23 17:42:20 -05:00
r . login (),
r . logout (),
2023-07-10 21:38:02 -05:00
r . netcheck (),
2023-03-23 17:42:20 -05:00
r . portForward (),
r . publickey (),
r . resetPassword (),
r . state (),
r . templates (),
r . tokens (),
2023-07-10 21:38:02 -05:00
r . users (),
2023-04-05 13:16:05 +01:00
r . version ( defaultVersionInfo ),
2023-03-23 17:42:20 -05:00
// Workspace Commands
2023-11-02 14:41:34 -05:00
r . autoupdate (),
2023-03-23 17:42:20 -05:00
r . configSSH (),
r . create (),
r . deleteWorkspace (),
2024-01-24 14:05:39 +00:00
r . favorite (),
2023-03-23 17:42:20 -05:00
r . list (),
2024-01-02 20:46:18 +02:00
r . open (),
2023-05-05 10:34:58 +01:00
r . ping (),
r . rename (),
2024-01-02 20:46:18 +02:00
r . restart (),
2023-03-23 17:42:20 -05:00
r . schedules (),
r . show (),
r . speedtest (),
r . ssh (),
r . start (),
2024-01-02 20:46:18 +02:00
r . stat (),
2023-03-23 17:42:20 -05:00
r . stop (),
2024-01-24 14:05:39 +00:00
r . unfavorite (),
2023-03-23 17:42:20 -05:00
r . update (),
// Hidden
r . gitssh (),
r . vscodeSSH (),
2023-05-05 10:34:58 +01:00
r . workspaceAgent (),
2023-07-07 09:10:14 +01:00
r . expCmd (),
2022-08-22 15:02:50 -07:00
}
}
2023-03-23 17:42:20 -05:00
func ( r * RootCmd ) AGPL () [] * clibase . Cmd {
2023-09-01 16:32:21 +03:00
all := append ( r . Core (), r . Server ( /* Do not import coderd here. */ nil ))
2022-08-22 15:02:50 -07:00
return all
}
2023-03-23 17:42:20 -05:00
// Main is the entrypoint for the Coder CLI.
func ( r * RootCmd ) RunMain ( subcommands [] * clibase . Cmd ) {
rand . Seed ( time . Now (). UnixMicro ())
2022-10-24 19:46:24 -05:00
2023-03-23 17:42:20 -05:00
cmd , err := r . Command ( subcommands )
if err != nil {
panic ( err )
}
err = cmd . Invoke (). WithOS (). Run ()
if err != nil {
2023-11-24 14:35:56 +02:00
code := 1
var exitErr * exitError
if errors . As ( err , & exitErr ) {
code = exitErr . code
err = exitErr . err
}
2023-03-23 17:42:20 -05:00
if errors . Is ( err , cliui . Canceled ) {
//nolint:revive
2023-11-24 14:35:56 +02:00
os . Exit ( code )
2023-03-23 17:42:20 -05:00
}
2023-09-29 16:50:23 -05:00
f := prettyErrorFormatter { w : os . Stderr , verbose : r . verbose }
2023-11-24 14:35:56 +02:00
if err != nil {
f . format ( err )
}
2023-03-23 17:42:20 -05:00
//nolint:revive
2023-11-24 14:35:56 +02:00
os . Exit ( code )
2023-03-23 17:42:20 -05:00
}
}
func ( r * RootCmd ) Command ( subcommands [] * clibase . Cmd ) ( * clibase . Cmd , error ) {
2022-10-25 00:17:48 +08:00
fmtLong := `Coder %s — A tool for provisioning self-hosted development environments with Terraform.
`
2023-03-23 17:42:20 -05:00
cmd := & clibase . Cmd {
Use : "coder [global-flags] <subcommand>" ,
Long : fmt . Sprintf ( fmtLong , buildinfo . Version ()) + formatExamples (
2022-07-11 19:08:09 +03:00
example {
Description : "Start a Coder server" ,
Command : "coder server" ,
},
example {
Description : "Get started by creating a template from an example" ,
Command : "coder templates init" ,
},
),
2023-03-23 17:42:20 -05:00
Handler : func ( i * clibase . Invocation ) error {
2023-10-04 15:37:15 -05:00
if r . versionFlag {
return r . version ( defaultVersionInfo ). Handler ( i )
}
2023-03-23 17:42:20 -05:00
// The GIT_ASKPASS environment variable must point at
// a binary with no arguments. To prevent writing
// cross-platform scripts to invoke the Coder binary
// with a `gitaskpass` subcommand, we override the entrypoint
// to check if the command was invoked.
if gitauth . CheckCommand ( i . Args , i . Environ . ToOS ()) {
return r . gitAskpass (). Handler ( i )
}
return i . Command . HelpHandler ( i )
},
2022-02-10 08:33:27 -06:00
}
2023-03-23 17:42:20 -05:00
cmd . AddSubcommands ( subcommands ... )
2022-02-10 08:33:27 -06:00
2023-03-23 17:42:20 -05:00
// Set default help handler for all commands.
cmd . Walk ( func ( c * clibase . Cmd ) {
if c . HelpHandler == nil {
c . HelpHandler = helpFn ()
}
})
2022-05-09 17:42:02 -05:00
2023-03-23 17:42:20 -05:00
var merr error
// Add [flags] to usage when appropriate.
cmd . Walk ( func ( cmd * clibase . Cmd ) {
const flags = "[flags]"
if strings . Contains ( cmd . Use , flags ) {
merr = errors . Join (
merr ,
xerrors . Errorf (
"command %q shouldn't have %q in usage since it's automatically populated" ,
cmd . FullUsage (),
flags ,
),
)
return
}
2022-02-10 08:33:27 -06:00
2023-03-23 17:42:20 -05:00
var hasFlag bool
for _ , opt := range cmd . Options {
if opt . Flag != "" {
hasFlag = true
break
}
}
if ! hasFlag {
return
}
// We insert [flags] between the command's name and its arguments.
tokens := strings . SplitN ( cmd . Use , " " , 2 )
if len ( tokens ) == 1 {
cmd . Use = fmt . Sprintf ( "%s %s" , tokens [ 0 ], flags )
return
}
cmd . Use = fmt . Sprintf ( "%s %s %s" , tokens [ 0 ], flags , tokens [ 1 ])
})
// Add alises when appropriate.
cmd . Walk ( func ( cmd * clibase . Cmd ) {
// TODO: we should really be consistent about naming.
if cmd . Name () == "delete" || cmd . Name () == "remove" {
if slices . Contains ( cmd . Aliases , "rm" ) {
merr = errors . Join (
merr ,
xerrors . Errorf ( "command %q shouldn't have alias %q since it's added automatically" , cmd . FullName (), "rm" ),
)
return
}
cmd . Aliases = append ( cmd . Aliases , "rm" )
}
})
// Sanity-check command options.
cmd . Walk ( func ( cmd * clibase . Cmd ) {
for _ , opt := range cmd . Options {
// Verify that every option is configurable.
if opt . Flag == "" && opt . Env == "" {
if cmd . Name () == "server" {
// The server command is funky and has YAML-only options, e.g.
// support links.
return
}
merr = errors . Join (
merr ,
xerrors . Errorf ( "option %q in %q should have a flag or env" , opt . Name , cmd . FullName ()),
)
}
}
})
if merr != nil {
return nil , merr
}
2023-04-07 17:58:21 -05:00
var debugOptions bool
// Add a wrapper to every command to enable debugging options.
cmd . Walk ( func ( cmd * clibase . Cmd ) {
h := cmd . Handler
2023-07-05 13:20:12 -04:00
if h == nil {
// We should never have a nil handler, but if we do, do not
// wrap it. Wrapping it just hides a nil pointer dereference.
// If a nil handler exists, this is a developer bug. If no handler
// is required for a command such as command grouping (e.g. `users'
// and 'groups'), then the handler should be set to the helper
// function.
// func(inv *clibase.Invocation) error {
// return inv.Command.HelpHandler(inv)
// }
return
}
2023-04-07 17:58:21 -05:00
cmd . Handler = func ( i * clibase . Invocation ) error {
if ! debugOptions {
return h ( i )
}
tw := tabwriter . NewWriter ( i . Stdout , 0 , 0 , 4 , ' ' , 0 )
_ , _ = fmt . Fprintf ( tw , "Option\tValue Source\n" )
for _ , opt := range cmd . Options {
_ , _ = fmt . Fprintf ( tw , "%q\t%v\n" , opt . Name , opt . ValueSource )
}
tw . Flush ()
return nil
}
})
2023-03-23 17:42:20 -05:00
if r . agentURL == nil {
r . agentURL = new ( url . URL )
}
if r . clientURL == nil {
r . clientURL = new ( url . URL )
}
globalGroup := & clibase . Group {
Name : "Global" ,
Description : `Global options are applied to all commands. They can be set using environment variables or flags.` ,
}
cmd . Options = clibase . OptionSet {
{
Flag : varURL ,
Env : envURL ,
Description : "URL to a deployment." ,
Value : clibase . URLOf ( r . clientURL ),
Group : globalGroup ,
},
2023-04-07 17:58:21 -05:00
{
Flag : "debug-options" ,
Description : "Print all options, how they're set, then exit." ,
Value : clibase . BoolOf ( & debugOptions ),
Group : globalGroup ,
},
2023-03-23 17:42:20 -05:00
{
Flag : varToken ,
Env : envSessionToken ,
Description : fmt . Sprintf ( "Specify an authentication token. For security reasons setting %s is preferred." , envSessionToken ),
Value : clibase . StringOf ( & r . token ),
Group : globalGroup ,
},
{
Flag : varAgentToken ,
2023-03-23 18:38:15 -05:00
Env : envAgentToken ,
2023-03-23 17:42:20 -05:00
Description : "An agent authentication token." ,
Value : clibase . StringOf ( & r . agentToken ),
Hidden : true ,
Group : globalGroup ,
},
2023-10-05 15:41:05 -05:00
{
Flag : varAgentTokenFile ,
Env : envAgentTokenFile ,
Description : "A file containing an agent authentication token." ,
Value : clibase . StringOf ( & r . agentTokenFile ),
Hidden : true ,
Group : globalGroup ,
},
2023-03-23 17:42:20 -05:00
{
Flag : varAgentURL ,
Env : "CODER_AGENT_URL" ,
Description : "URL for an agent to access your deployment." ,
Value : clibase . URLOf ( r . agentURL ),
Hidden : true ,
Group : globalGroup ,
},
{
Flag : varNoVersionCheck ,
Env : envNoVersionCheck ,
Description : "Suppress warning when client and server versions do not match." ,
Value : clibase . BoolOf ( & r . noVersionCheck ),
Group : globalGroup ,
},
{
Flag : varNoFeatureWarning ,
Env : envNoFeatureWarning ,
Description : "Suppress warnings about unlicensed features." ,
Value : clibase . BoolOf ( & r . noFeatureWarning ),
Group : globalGroup ,
},
{
Flag : varHeader ,
Env : "CODER_HEADER" ,
Description : "Additional HTTP headers added to all requests. Provide as " + `key=value` + ". Can be specified multiple times." ,
Value : clibase . StringArrayOf ( & r . header ),
Group : globalGroup ,
},
2023-08-14 12:12:17 -08:00
{
Flag : varHeaderCommand ,
Env : "CODER_HEADER_COMMAND" ,
Description : "An external command that outputs additional HTTP headers added to all requests. The command must output each header as `key=value` on its own line." ,
Value : clibase . StringOf ( & r . headerCommand ),
Group : globalGroup ,
},
2023-03-23 17:42:20 -05:00
{
Flag : varNoOpen ,
Env : "CODER_NO_OPEN" ,
Description : "Suppress opening the browser after logging in." ,
Value : clibase . BoolOf ( & r . noOpen ),
Hidden : true ,
Group : globalGroup ,
},
{
Flag : varForceTty ,
Env : "CODER_FORCE_TTY" ,
Hidden : true ,
Description : "Force the use of a TTY." ,
Value : clibase . BoolOf ( & r . forceTTY ),
Group : globalGroup ,
},
{
Flag : varVerbose ,
FlagShorthand : "v" ,
Env : "CODER_VERBOSE" ,
Description : "Enable verbose output." ,
Value : clibase . BoolOf ( & r . verbose ),
Group : globalGroup ,
},
2023-06-22 06:22:43 +10:00
{
Flag : varDisableDirect ,
Env : "CODER_DISABLE_DIRECT_CONNECTIONS" ,
Description : "Disable direct (P2P) connections to workspaces." ,
Value : clibase . BoolOf ( & r . disableDirect ),
Group : globalGroup ,
},
2023-04-19 11:07:53 -05:00
{
Flag : "debug-http" ,
Description : "Debug codersdk HTTP requests." ,
Value : clibase . BoolOf ( & r . debugHTTP ),
Group : globalGroup ,
Hidden : true ,
},
2023-03-23 17:42:20 -05:00
{
Flag : config . FlagName ,
Env : "CODER_CONFIG_DIR" ,
Description : "Path to the global `coder` config directory." ,
Default : config . DefaultDir (),
Value : clibase . StringOf ( & r . globalConfig ),
Group : globalGroup ,
},
2023-10-04 15:37:15 -05:00
{
Flag : "version" ,
// This was requested by a customer to assist with their migration.
// They have two Coder CLIs, and want to tell the difference by running
// the same base command.
Description : "Run the version command. Useful for v1 customers migrating to v2." ,
Value : clibase . BoolOf ( & r . versionFlag ),
Hidden : true ,
},
2023-03-23 17:42:20 -05:00
}
err := cmd . PrepareAll ()
if err != nil {
return nil , err
}
return cmd , nil
2022-02-10 08:33:27 -06:00
}
2023-03-23 17:42:20 -05:00
// RootCmd contains parameters and helpers useful to all commands.
type RootCmd struct {
2023-10-05 15:41:05 -05:00
clientURL * url . URL
token string
globalConfig string
header [] string
headerCommand string
agentToken string
agentTokenFile string
agentURL * url . URL
forceTTY bool
noOpen bool
verbose bool
versionFlag bool
disableDirect bool
debugHTTP bool
2022-12-02 15:40:23 -06:00
2023-03-23 17:42:20 -05:00
noVersionCheck bool
noFeatureWarning bool
2022-09-12 16:22:05 -05:00
}
2023-05-30 19:11:56 -05:00
func addTelemetryHeader ( client * codersdk . Client , inv * clibase . Invocation ) {
2023-12-05 02:13:42 -08:00
transport , ok := client . HTTPClient . Transport .( * codersdk . HeaderTransport )
2023-06-14 21:52:01 +10:00
if ! ok {
2023-12-05 02:13:42 -08:00
transport = & codersdk . HeaderTransport {
Transport : client . HTTPClient . Transport ,
Header : http . Header {},
2023-06-14 21:52:01 +10:00
}
client . HTTPClient . Transport = transport
}
2023-09-04 21:42:45 +03:00
var topts [] telemetry . Option
2023-05-30 19:11:56 -05:00
for _ , opt := range inv . Command . FullOptions () {
2023-05-24 11:08:03 -05:00
if opt . ValueSource == clibase . ValueSourceNone || opt . ValueSource == clibase . ValueSourceDefault {
continue
}
2023-09-04 21:42:45 +03:00
topts = append ( topts , telemetry . Option {
2023-05-24 11:08:03 -05:00
Name : opt . Name ,
ValueSource : string ( opt . ValueSource ),
})
}
2023-09-04 21:42:45 +03:00
ti := telemetry . Invocation {
2023-05-30 19:11:56 -05:00
Command : inv . Command . FullName (),
2023-05-24 11:08:03 -05:00
Options : topts ,
InvokedAt : time . Now (),
}
2023-05-30 19:11:56 -05:00
byt , err := json . Marshal ( ti )
if err != nil {
// Should be impossible
panic ( err )
}
// Per https://stackoverflow.com/questions/686217/maximum-on-http-header-values,
// we don't want to send headers that are too long.
s := base64 . StdEncoding . EncodeToString ( byt )
if len ( s ) > 4096 {
return
}
2023-12-05 02:13:42 -08:00
transport . Header . Add ( codersdk . CLITelemetryHeader , s )
2023-05-24 11:08:03 -05:00
}
2023-03-23 17:42:20 -05:00
// InitClient sets client to a new client.
// It reads from global configuration files if flags are not set.
func ( r * RootCmd ) InitClient ( client * codersdk . Client ) clibase . MiddlewareFunc {
2023-12-21 16:55:34 +04:00
return clibase . Chain (
r . initClientInternal ( client , false ),
// By default, we should print warnings in addition to initializing the client
r . PrintWarnings ( client ),
)
2023-08-04 12:32:28 +04:00
}
func ( r * RootCmd ) InitClientMissingTokenOK ( client * codersdk . Client ) clibase . MiddlewareFunc {
return r . initClientInternal ( client , true )
}
// nolint: revive
func ( r * RootCmd ) initClientInternal ( client * codersdk . Client , allowTokenMissing bool ) clibase . MiddlewareFunc {
2023-03-23 17:42:20 -05:00
if client == nil {
panic ( "client is nil" )
2022-09-12 16:22:05 -05:00
}
2023-03-23 17:42:20 -05:00
if r == nil {
panic ( "root is nil" )
}
return func ( next clibase . HandlerFunc ) clibase . HandlerFunc {
2023-05-30 19:11:56 -05:00
return func ( inv * clibase . Invocation ) error {
2023-03-23 17:42:20 -05:00
conf := r . createConfig ()
var err error
if r . clientURL == nil || r . clientURL . String () == "" {
rawURL , err := conf . URL (). Read ()
// If the configuration files are absent, the user is logged out
if os . IsNotExist ( err ) {
2023-08-04 12:32:28 +04:00
return errUnauthenticated
2023-03-23 17:42:20 -05:00
}
if err != nil {
return err
}
r . clientURL , err = url . Parse ( strings . TrimSpace ( rawURL ))
if err != nil {
return err
}
}
if r . token == "" {
r . token , err = conf . Session (). Read ()
// If the configuration files are absent, the user is logged out
if os . IsNotExist ( err ) {
2023-08-04 12:32:28 +04:00
if ! allowTokenMissing {
return errUnauthenticated
}
} else if err != nil {
2023-03-23 17:42:20 -05:00
return err
}
}
2023-08-14 12:12:17 -08:00
err = r . setClient ( inv . Context (), client , r . clientURL )
2023-03-23 17:42:20 -05:00
if err != nil {
return err
}
2023-05-30 19:11:56 -05:00
addTelemetryHeader ( client , inv )
2023-03-23 17:42:20 -05:00
client . SetSessionToken ( r . token )
2023-04-19 11:07:53 -05:00
if r . debugHTTP {
client . PlainLogger = os . Stderr
2023-07-06 09:43:39 +01:00
client . SetLogBodies ( true )
2023-04-19 11:07:53 -05:00
}
2023-06-22 06:22:43 +10:00
client . DisableDirectConnections = r . disableDirect
2023-12-21 16:55:34 +04:00
return next ( inv )
}
}
}
2023-04-19 11:07:53 -05:00
2023-12-21 16:55:34 +04:00
func ( r * RootCmd ) PrintWarnings ( client * codersdk . Client ) clibase . MiddlewareFunc {
if client == nil {
panic ( "client is nil" )
}
if r == nil {
panic ( "root is nil" )
}
return func ( next clibase . HandlerFunc ) clibase . HandlerFunc {
return func ( inv * clibase . Invocation ) error {
2023-03-23 17:42:20 -05:00
// We send these requests in parallel to minimize latency.
var (
versionErr = make ( chan error )
warningErr = make ( chan error )
)
go func () {
2024-01-30 17:11:37 -06:00
versionErr <- r . checkVersions ( inv , client , buildinfo . Version ())
2023-03-23 17:42:20 -05:00
close ( versionErr )
}()
go func () {
2023-05-30 19:11:56 -05:00
warningErr <- r . checkWarnings ( inv , client )
2023-03-23 17:42:20 -05:00
close ( warningErr )
}()
2023-12-21 16:55:34 +04:00
if err := <- versionErr ; err != nil {
2023-03-23 17:42:20 -05:00
// Just log the error here. We never want to fail a command
// due to a pre-run.
2023-09-07 17:28:22 -04:00
pretty . Fprintf ( inv . Stderr , cliui . DefaultStyles . Warn , "check versions error: %s" , err )
2023-05-30 19:11:56 -05:00
_ , _ = fmt . Fprintln ( inv . Stderr )
2023-03-23 17:42:20 -05:00
}
2023-12-21 16:55:34 +04:00
if err := <- warningErr ; err != nil {
2023-03-23 17:42:20 -05:00
// Same as above
2023-09-07 17:28:22 -04:00
pretty . Fprintf ( inv . Stderr , cliui . DefaultStyles . Warn , "check entitlement warnings error: %s" , err )
2023-05-30 19:11:56 -05:00
_ , _ = fmt . Fprintln ( inv . Stderr )
2023-03-23 17:42:20 -05:00
}
2023-05-30 19:11:56 -05:00
return next ( inv )
2023-03-23 17:42:20 -05:00
}
}
}
2023-12-05 02:13:42 -08:00
func ( r * RootCmd ) HeaderTransport ( ctx context . Context , serverURL * url . URL ) ( * codersdk . HeaderTransport , error ) {
transport := & codersdk . HeaderTransport {
Transport : http . DefaultTransport ,
Header : http . Header {},
2022-09-12 16:22:05 -05:00
}
2023-08-14 12:12:17 -08:00
headers := r . header
if r . headerCommand != "" {
shell := "sh"
caller := "-c"
if runtime . GOOS == "windows" {
shell = "cmd.exe"
caller = "/c"
}
var outBuf bytes . Buffer
// #nosec
cmd := exec . CommandContext ( ctx , shell , caller , r . headerCommand )
cmd . Env = append ( os . Environ (), "CODER_URL=" + serverURL . String ())
cmd . Stdout = & outBuf
cmd . Stderr = io . Discard
err := cmd . Run ()
if err != nil {
2023-12-05 02:13:42 -08:00
return nil , xerrors . Errorf ( "failed to run %v: %w" , cmd . Args , err )
2023-08-14 12:12:17 -08:00
}
scanner := bufio . NewScanner ( & outBuf )
for scanner . Scan () {
headers = append ( headers , scanner . Text ())
}
if err := scanner . Err (); err != nil {
2023-12-05 02:13:42 -08:00
return nil , xerrors . Errorf ( "scan %v: %w" , cmd . Args , err )
2023-08-14 12:12:17 -08:00
}
}
for _ , header := range headers {
2023-06-14 21:52:01 +10:00
parts := strings . SplitN ( header , "=" , 2 )
if len ( parts ) < 2 {
2023-12-05 02:13:42 -08:00
return nil , xerrors . Errorf ( "split header %q had less than two parts" , header )
2023-06-14 21:52:01 +10:00
}
2023-12-05 02:13:42 -08:00
transport . Header . Add ( parts [ 0 ], parts [ 1 ])
2023-06-14 21:52:01 +10:00
}
2023-12-05 02:13:42 -08:00
return transport , nil
}
func ( r * RootCmd ) setClient ( ctx context . Context , client * codersdk . Client , serverURL * url . URL ) error {
transport , err := r . HeaderTransport ( ctx , serverURL )
if err != nil {
return xerrors . Errorf ( "create header transport: %w" , err )
}
2023-03-23 17:42:20 -05:00
client . URL = serverURL
client . HTTPClient = & http . Client {
Transport : transport ,
}
return nil
}
2023-08-14 12:12:17 -08:00
func ( r * RootCmd ) createUnauthenticatedClient ( ctx context . Context , serverURL * url . URL ) ( * codersdk . Client , error ) {
2023-03-23 17:42:20 -05:00
var client codersdk . Client
2023-08-14 12:12:17 -08:00
err := r . setClient ( ctx , & client , serverURL )
2023-03-23 17:42:20 -05:00
return & client , err
2022-04-30 11:40:30 -05:00
}
// createAgentClient returns a new client from the command context.
2022-08-23 13:55:39 -07:00
// It works just like CreateClient, but uses the agent token and URL instead.
2023-03-23 17:42:20 -05:00
func ( r * RootCmd ) createAgentClient () ( * agentsdk . Client , error ) {
client := agentsdk . New ( r . agentURL )
client . SetSessionToken ( r . agentToken )
2022-02-12 13:34:04 -06:00
return client , nil
2022-02-10 08:33:27 -06:00
}
2022-10-27 16:49:35 -05:00
// CurrentOrganization returns the currently active organization for the authenticated user.
2023-03-23 17:42:20 -05:00
func CurrentOrganization ( inv * clibase . Invocation , client * codersdk . Client ) ( codersdk . Organization , error ) {
orgs , err := client . OrganizationsByUser ( inv . Context (), codersdk . Me )
2022-02-10 08:33:27 -06:00
if err != nil {
2022-03-22 13:17:50 -06:00
return codersdk . Organization {}, nil
2022-02-10 08:33:27 -06:00
}
// For now, we won't use the config to set this.
// Eventually, we will support changing using "coder switch <org>"
return orgs [ 0 ], nil
}
2023-07-14 09:48:02 -04:00
func splitNamedWorkspace ( identifier string ) ( owner string , workspaceName string , err error ) {
parts := strings . Split ( identifier , "/" )
switch len ( parts ) {
case 1 :
owner = codersdk . Me
workspaceName = parts [ 0 ]
case 2 :
owner = parts [ 0 ]
workspaceName = parts [ 1 ]
default :
return "" , "" , xerrors . Errorf ( "invalid workspace name: %q" , identifier )
}
return owner , workspaceName , nil
}
2022-06-03 12:47:56 -05:00
// namedWorkspace fetches and returns a workspace by an identifier, which may be either
// a bare name (for a workspace owned by the current user) or a "user/workspace" combination,
// where user is either a username or UUID.
2023-03-23 17:42:20 -05:00
func namedWorkspace ( ctx context . Context , client * codersdk . Client , identifier string ) ( codersdk . Workspace , error ) {
2023-07-14 09:48:02 -04:00
owner , name , err := splitNamedWorkspace ( identifier )
if err != nil {
return codersdk . Workspace {}, err
2022-06-03 12:47:56 -05:00
}
2023-03-23 17:42:20 -05:00
return client . WorkspaceByOwnerAndName ( ctx , owner , name , codersdk . WorkspaceOptions {})
2022-06-03 12:47:56 -05:00
}
2022-02-12 13:34:04 -06:00
// createConfig consumes the global configuration flag to produce a config root.
2023-03-23 17:42:20 -05:00
func ( r * RootCmd ) createConfig () config . Root {
return config . Root ( r . globalConfig )
2022-02-10 08:33:27 -06:00
}
// isTTY returns whether the passed reader is a TTY or not.
2023-03-23 17:42:20 -05:00
func isTTY ( inv * clibase . Invocation ) bool {
2022-02-14 17:05:40 -08:00
// If the `--force-tty` command is available, and set,
// assume we're in a tty. This is primarily for cases on Windows
// where we may not be able to reliably detect this automatically (ie, tests)
2023-03-23 17:42:20 -05:00
forceTty , err := inv . ParsedFlags (). GetBool ( varForceTty )
2022-02-14 17:05:40 -08:00
if forceTty && err == nil {
return true
}
2023-03-23 17:42:20 -05:00
file , ok := inv . Stdin .( * os . File )
2022-02-10 08:33:27 -06:00
if ! ok {
return false
}
return isatty . IsTerminal ( file . Fd ())
}
2022-04-04 20:35:03 -05:00
2022-06-08 11:45:29 +03:00
// isTTYOut returns whether the passed reader is a TTY or not.
2023-03-23 17:42:20 -05:00
func isTTYOut ( inv * clibase . Invocation ) bool {
return isTTYWriter ( inv , inv . Stdout )
2022-11-07 19:12:39 +01:00
}
// isTTYErr returns whether the passed reader is a TTY or not.
2023-03-23 17:42:20 -05:00
func isTTYErr ( inv * clibase . Invocation ) bool {
return isTTYWriter ( inv , inv . Stderr )
2022-11-07 19:12:39 +01:00
}
2023-03-23 17:42:20 -05:00
func isTTYWriter ( inv * clibase . Invocation , writer io . Writer ) bool {
2022-06-08 11:45:29 +03:00
// If the `--force-tty` command is available, and set,
// assume we're in a tty. This is primarily for cases on Windows
// where we may not be able to reliably detect this automatically (ie, tests)
2023-03-23 17:42:20 -05:00
forceTty , err := inv . ParsedFlags (). GetBool ( varForceTty )
2022-06-08 11:45:29 +03:00
if forceTty && err == nil {
return true
}
2023-03-23 17:42:20 -05:00
file , ok := writer .( * os . File )
2022-06-08 11:45:29 +03:00
if ! ok {
return false
}
return isatty . IsTerminal ( file . Fd ())
}
2022-07-11 19:08:09 +03:00
// example represents a standard example for command usage, to be used
// with formatExamples.
type example struct {
Description string
Command string
}
2022-08-01 09:29:52 -04:00
// formatExamples formats the examples as width wrapped bulletpoint
2022-07-11 19:08:09 +03:00
// descriptions with the command underneath.
func formatExamples ( examples ... example ) string {
var sb strings . Builder
2023-06-07 00:22:58 -05:00
2023-09-07 17:28:22 -04:00
padStyle := cliui . DefaultStyles . Wrap . With ( pretty . XPad ( 4 , 0 ))
2022-07-11 19:08:09 +03:00
for i , e := range examples {
if len ( e . Description ) > 0 {
2023-06-07 00:22:58 -05:00
wordwrap . WrapString ( e . Description , 80 )
_ , _ = sb . WriteString (
2023-09-07 17:28:22 -04:00
" - " + pretty . Sprint ( padStyle , e . Description + ":" )[ 4 :] + "\n\n " ,
2023-06-07 00:22:58 -05:00
)
2022-07-11 19:08:09 +03:00
}
2023-06-07 02:13:22 -07:00
// We add 1 space here because `cliui.DefaultStyles.Code` adds an extra
2022-07-11 19:08:09 +03:00
// space. This makes the code block align at an even 2 or 6
// spaces for symmetry.
2023-09-07 17:28:22 -04:00
_ , _ = sb . WriteString ( " " + pretty . Sprint ( cliui . DefaultStyles . Code , fmt . Sprintf ( "$ %s" , e . Command )))
2022-07-11 19:08:09 +03:00
if i < len ( examples ) - 1 {
_ , _ = sb . WriteString ( "\n\n" )
}
}
return sb . String ()
}
2024-01-30 17:11:37 -06:00
// checkVersions checks to see if there's a version mismatch between the client
// and server and prints a message nudging the user to upgrade if a mismatch
// is detected. forceCheck is a test flag and should always be false in production.
//
//nolint:revive
func ( r * RootCmd ) checkVersions ( i * clibase . Invocation , client * codersdk . Client , clientVersion string ) error {
2023-03-23 17:42:20 -05:00
if r . noVersionCheck {
2022-06-29 17:49:40 -05:00
return nil
}
2023-03-23 17:42:20 -05:00
ctx , cancel := context . WithTimeout ( i . Context (), 10 * time . Second )
2022-09-08 23:59:28 +10:00
defer cancel ()
2022-06-29 17:49:40 -05:00
2024-01-30 17:11:37 -06:00
serverInfo , err := client . BuildInfo ( ctx )
2022-07-21 14:28:24 -05:00
// Avoid printing errors that are connection-related.
2023-01-29 15:47:24 -06:00
if isConnectionError ( err ) {
2022-07-21 14:28:24 -05:00
return nil
}
2022-06-29 17:49:40 -05:00
if err != nil {
return xerrors . Errorf ( "build info: %w" , err )
}
2024-01-30 17:11:37 -06:00
if ! buildinfo . VersionsMatch ( clientVersion , serverInfo . Version ) {
upgradeMessage := defaultUpgradeMessage ( serverInfo . CanonicalVersion ())
if serverInfo . UpgradeMessage != "" {
upgradeMessage = serverInfo . UpgradeMessage
}
2022-06-29 17:49:40 -05:00
2024-01-30 17:11:37 -06:00
fmtWarningText := "version mismatch: client %s, server %s\n%s"
fmtWarn := pretty . Sprint ( cliui . DefaultStyles . Warn , fmtWarningText )
warning := fmt . Sprintf ( fmtWarn , clientVersion , serverInfo . Version , upgradeMessage )
_ , _ = fmt . Fprint ( i . Stderr , warning )
2023-03-23 17:42:20 -05:00
_ , _ = fmt . Fprintln ( i . Stderr )
2022-06-29 17:49:40 -05:00
}
return nil
}
2022-08-29 11:30:06 -07:00
2023-03-23 17:42:20 -05:00
func ( r * RootCmd ) checkWarnings ( i * clibase . Invocation , client * codersdk . Client ) error {
if r . noFeatureWarning {
2022-09-08 23:59:28 +10:00
return nil
2022-08-29 11:30:06 -07:00
}
2022-09-08 23:59:28 +10:00
2023-03-23 17:42:20 -05:00
ctx , cancel := context . WithTimeout ( i . Context (), 10 * time . Second )
2022-09-08 23:59:28 +10:00
defer cancel ()
2023-10-10 12:48:51 -05:00
user , err := client . User ( ctx , codersdk . Me )
if err != nil {
return xerrors . Errorf ( "get user me: %w" , err )
}
2022-09-08 23:59:28 +10:00
entitlements , err := client . Entitlements ( ctx )
2022-09-19 23:11:01 -05:00
if err == nil {
2023-10-10 12:48:51 -05:00
// Don't show warning to regular users.
if len ( user . Roles ) > 0 {
for _ , w := range entitlements . Warnings {
_ , _ = fmt . Fprintln ( i . Stderr , pretty . Sprint ( cliui . DefaultStyles . Warn , w ))
}
2022-09-19 23:11:01 -05:00
}
2022-08-29 11:30:06 -07:00
}
2022-09-08 23:59:28 +10:00
return nil
2022-08-29 11:30:06 -07:00
}
2022-09-12 16:22:05 -05:00
2023-08-27 14:46:44 -05:00
// Verbosef logs a message if verbose mode is enabled.
func ( r * RootCmd ) Verbosef ( inv * clibase . Invocation , fmtStr string , args ... interface {}) {
if r . verbose {
cliui . Infof ( inv . Stdout , fmtStr , args ... )
}
}
2023-04-13 09:07:19 -05:00
// DumpHandler provides a custom SIGQUIT and SIGTRAP handler that dumps the
2023-01-11 10:22:20 -06:00
// stacktrace of all goroutines to stderr and a well-known file in the home
// directory. This is useful for debugging deadlock issues that may occur in
// production in workspaces, since the default Go runtime will only dump to
// stderr (which is often difficult/impossible to read in a workspace).
//
// SIGQUITs will still cause the program to exit (similarly to the default Go
// runtime behavior).
//
// A SIGQUIT handler will not be registered if GOTRACEBACK=crash.
//
// On Windows this immediately returns.
2023-04-13 09:07:19 -05:00
func DumpHandler ( ctx context . Context ) {
2023-01-11 10:22:20 -06:00
if runtime . GOOS == "windows" {
// free up the goroutine since it'll be permanently blocked anyways
return
}
listenSignals := [] os . Signal { syscall . SIGTRAP }
if os . Getenv ( "GOTRACEBACK" ) != "crash" {
listenSignals = append ( listenSignals , syscall . SIGQUIT )
}
sigs := make ( chan os . Signal , 1 )
signal . Notify ( sigs , listenSignals ... )
defer signal . Stop ( sigs )
for {
sigStr := ""
select {
case <- ctx . Done ():
return
case sig := <- sigs :
switch sig {
case syscall . SIGQUIT :
sigStr = "SIGQUIT"
case syscall . SIGTRAP :
sigStr = "SIGTRAP"
}
}
// Start with a 1MB buffer and keep doubling it until we can fit the
// entire stacktrace, stopping early once we reach 64MB.
buf := make ([] byte , 1_000_000 )
stacklen := 0
for {
stacklen = runtime . Stack ( buf , true )
if stacklen < len ( buf ) {
break
}
if 2 * len ( buf ) > 64_000_000 {
// Write a message to the end of the buffer saying that it was
// truncated.
const truncatedMsg = "\n\n\nstack trace truncated due to size\n"
copy ( buf [ len ( buf ) - len ( truncatedMsg ):], truncatedMsg )
break
}
buf = make ([] byte , 2 * len ( buf ))
}
_ , _ = fmt . Fprintf ( os . Stderr , "%s:\n%s\n" , sigStr , buf [: stacklen ])
// Write to a well-known file.
dir , err := os . UserHomeDir ()
if err != nil {
dir = os . TempDir ()
}
fpath := filepath . Join ( dir , fmt . Sprintf ( "coder-agent-%s.dump" , time . Now (). Format ( "2006-01-02T15:04:05.000Z" )))
_ , _ = fmt . Fprintf ( os . Stderr , "writing dump to %q\n" , fpath )
f , err := os . Create ( fpath )
if err != nil {
_ , _ = fmt . Fprintf ( os . Stderr , "failed to open dump file: %v\n" , err . Error ())
goto done
}
_ , err = f . Write ( buf [: stacklen ])
_ = f . Close ()
if err != nil {
_ , _ = fmt . Fprintf ( os . Stderr , "failed to write dump file: %v\n" , err . Error ())
goto done
}
done :
if sigStr == "SIGQUIT" {
//nolint:revive
os . Exit ( 1 )
}
}
}
2023-01-29 15:47:24 -06:00
2023-11-24 14:35:56 +02:00
type exitError struct {
code int
err error
}
var _ error = ( * exitError )( nil )
func ( e * exitError ) Error () string {
if e . err != nil {
return fmt . Sprintf ( "exit code %d: %v" , e . code , e . err )
}
return fmt . Sprintf ( "exit code %d" , e . code )
}
func ( e * exitError ) Unwrap () error {
return e . err
}
// ExitError returns an error that will cause the CLI to exit with the given
// exit code. If err is non-nil, it will be wrapped by the returned error.
func ExitError ( code int , err error ) error {
return & exitError { code : code , err : err }
}
2023-01-29 15:47:24 -06:00
// IiConnectionErr is a convenience function for checking if the source of an
// error is due to a 'connection refused', 'no such host', etc.
func isConnectionError ( err error ) bool {
var (
// E.g. no such host
dnsErr * net . DNSError
// Eg. connection refused
opErr * net . OpError
)
return xerrors . As ( err , & dnsErr ) || xerrors . As ( err , & opErr )
}
2023-03-23 17:42:20 -05:00
type prettyErrorFormatter struct {
2023-03-28 11:03:34 -05:00
w io . Writer
2023-09-29 16:50:23 -05:00
// verbose turns on more detailed error logs, such as stack traces.
verbose bool
2023-03-23 17:42:20 -05:00
}
2023-09-29 16:50:23 -05:00
// format formats the error to the console. This error should be human
// readable.
2023-03-23 17:42:20 -05:00
func ( p * prettyErrorFormatter ) format ( err error ) {
2024-01-11 16:55:34 -06:00
output , _ := cliHumanFormatError ( "" , err , & formatOpts {
2023-09-29 16:50:23 -05:00
Verbose : p . verbose ,
})
// always trail with a newline
_ , _ = p . w . Write ([] byte ( output + "\n" ))
}
type formatOpts struct {
Verbose bool
}
const indent = " "
// cliHumanFormatError formats an error for the CLI. Newlines and styling are
2024-01-11 16:55:34 -06:00
// included. The second return value is true if the error is special and the error
// chain has custom formatting applied.
//
// If you change this code, you can use the cli "example-errors" tool to
// verify all errors still look ok.
//
// go run main.go exp example-error <type>
// go run main.go exp example-error api
// go run main.go exp example-error cmd
// go run main.go exp example-error multi-error
// go run main.go exp example-error validation
//
//nolint:errorlint
func cliHumanFormatError ( from string , err error , opts * formatOpts ) ( string , bool ) {
2023-09-29 16:50:23 -05:00
if opts == nil {
opts = & formatOpts {}
}
2024-01-11 16:55:34 -06:00
if err == nil {
return "<nil>" , true
}
2023-03-23 17:42:20 -05:00
2023-09-29 16:50:23 -05:00
if multi , ok := err .( interface { Unwrap () [] error }); ok {
multiErrors := multi . Unwrap ()
if len ( multiErrors ) == 1 {
// Format as a single error
2024-01-11 16:55:34 -06:00
return cliHumanFormatError ( from , multiErrors [ 0 ], opts )
2023-09-29 16:50:23 -05:00
}
2024-01-11 16:55:34 -06:00
return formatMultiError ( from , multiErrors , opts ), true
2023-03-23 17:42:20 -05:00
}
2023-09-29 16:50:23 -05:00
// First check for sentinel errors that we want to handle specially.
// Order does matter! We want to check for the most specific errors first.
2024-01-11 16:55:34 -06:00
if sdkError , ok := err .( * codersdk . Error ); ok {
return formatCoderSDKError ( from , sdkError , opts ), true
2023-03-28 11:03:34 -05:00
}
2024-01-11 16:55:34 -06:00
if cmdErr , ok := err .( * clibase . RunCommandError ); ok {
// no need to pass the "from" context to this since it is always
// top level. We care about what is below this.
return formatRunCommandError ( cmdErr , opts ), true
2023-03-23 17:42:20 -05:00
}
2023-09-29 16:50:23 -05:00
2024-01-11 16:55:34 -06:00
uw , ok := err .( interface { Unwrap () error })
if ok {
msg , special := cliHumanFormatError ( from + traceError ( err ), uw . Unwrap (), opts )
if special {
return msg , special
}
}
// If we got here, that means that the wrapped error chain does not have
// any special formatting below it. So we want to return the topmost non-special
// error (which is 'err')
2023-09-29 16:50:23 -05:00
// Default just printing the error. Use +v for verbose to handle stack
// traces of xerrors.
if opts . Verbose {
2024-01-11 16:55:34 -06:00
return pretty . Sprint ( headLineStyle (), fmt . Sprintf ( "%+v" , err )), false
2023-09-29 16:50:23 -05:00
}
2024-01-11 16:55:34 -06:00
return pretty . Sprint ( headLineStyle (), fmt . Sprintf ( "%v" , err )), false
2023-03-23 17:42:20 -05:00
}
2023-09-29 16:50:23 -05:00
// formatMultiError formats a multi-error. It formats it as a list of errors.
//
// Multiple Errors:
// <# errors encountered>:
// 1. <heading error message>
// <verbose error message>
// 2. <heading error message>
// <verbose error message>
2024-01-11 16:55:34 -06:00
func formatMultiError ( from string , multi [] error , opts * formatOpts ) string {
2023-09-29 16:50:23 -05:00
var errorStrings [] string
for _ , err := range multi {
2024-01-11 16:55:34 -06:00
msg , _ := cliHumanFormatError ( "" , err , opts )
errorStrings = append ( errorStrings , msg )
2023-09-29 16:50:23 -05:00
}
// Write errors out
var str strings . Builder
2024-01-11 16:55:34 -06:00
var traceMsg string
if from != "" {
traceMsg = fmt . Sprintf ( "Trace=[%s])" , from )
}
_ , _ = str . WriteString ( pretty . Sprint ( headLineStyle (), fmt . Sprintf ( "%d errors encountered: %s" , len ( multi ), traceMsg )))
2023-09-29 16:50:23 -05:00
for i , errStr := range errorStrings {
// Indent each error
errStr = strings . ReplaceAll ( errStr , "\n" , "\n" + indent )
// Error now looks like
// | <line>
// | <line>
prefix := fmt . Sprintf ( "%d. " , i + 1 )
if len ( prefix ) < len ( indent ) {
// Indent the prefix to match the indent
prefix = prefix + strings . Repeat ( " " , len ( indent ) - len ( prefix ))
}
errStr = prefix + errStr
// Now looks like
// |1.<line>
// | <line>
_ , _ = str . WriteString ( "\n" + errStr )
}
return str . String ()
}
// formatRunCommandError are cli command errors. This kind of error is very
// broad, as it contains all errors that occur when running a command.
// If you know the error is something else, like a codersdk.Error, make a new
// formatter and add it to cliHumanFormatError function.
func formatRunCommandError ( err * clibase . RunCommandError , opts * formatOpts ) string {
var str strings . Builder
_ , _ = str . WriteString ( pretty . Sprint ( headLineStyle (), fmt . Sprintf ( "Encountered an error running %q" , err . Cmd . FullName ())))
2024-01-11 16:55:34 -06:00
msgString , special := cliHumanFormatError ( "" , err . Err , opts )
2023-09-29 16:50:23 -05:00
_ , _ = str . WriteString ( "\n" )
2024-01-11 16:55:34 -06:00
if special {
_ , _ = str . WriteString ( msgString )
} else {
_ , _ = str . WriteString ( pretty . Sprint ( tailLineStyle (), msgString ))
}
2023-09-29 16:50:23 -05:00
return str . String ()
}
// formatCoderSDKError come from API requests. In verbose mode, add the
// request debug information.
2024-01-11 16:55:34 -06:00
func formatCoderSDKError ( from string , err * codersdk . Error , opts * formatOpts ) string {
2023-09-29 16:50:23 -05:00
var str strings . Builder
if opts . Verbose {
_ , _ = str . WriteString ( pretty . Sprint ( headLineStyle (), fmt . Sprintf ( "API request error to \"%s:%s\". Status code %d" , err . Method (), err . URL (), err . StatusCode ())))
_ , _ = str . WriteString ( "\n" )
}
2024-01-11 16:55:34 -06:00
// Always include this trace. Users can ignore this.
if from != "" {
_ , _ = str . WriteString ( pretty . Sprint ( headLineStyle (), fmt . Sprintf ( "Trace=[%s]" , from )))
_ , _ = str . WriteString ( "\n" )
}
2023-09-29 16:50:23 -05:00
_ , _ = str . WriteString ( pretty . Sprint ( headLineStyle (), err . Message ))
if err . Helper != "" {
_ , _ = str . WriteString ( "\n" )
_ , _ = str . WriteString ( pretty . Sprint ( tailLineStyle (), err . Helper ))
}
// By default we do not show the Detail with the helper.
if opts . Verbose || ( err . Helper == "" && err . Detail != "" ) {
_ , _ = str . WriteString ( "\n" )
_ , _ = str . WriteString ( pretty . Sprint ( tailLineStyle (), err . Detail ))
}
return str . String ()
}
2024-01-11 16:55:34 -06:00
// traceError is a helper function that aides developers debugging failed cli
// commands. When we pretty print errors, we lose the context in which they came.
// This function adds the context back. Unfortunately there is no easy way to get
// the prefix to: "error string: %w", so we do a bit of string manipulation.
//
//nolint:errorlint
func traceError ( err error ) string {
if uw , ok := err .( interface { Unwrap () error }); ok {
a , b := err . Error (), uw . Unwrap (). Error ()
c := strings . TrimSuffix ( a , b )
return c
}
return err . Error ()
}
2023-09-29 16:50:23 -05:00
// These styles are arbitrary.
func headLineStyle () pretty . Style {
return cliui . DefaultStyles . Error
}
func tailLineStyle () pretty . Style {
return pretty . Style { pretty . Nop }
2023-03-23 17:42:20 -05:00
}
2023-09-04 19:38:53 +03:00
//nolint:unused
func SlimUnsupported ( w io . Writer , cmd string ) {
2023-09-07 17:28:22 -04:00
_ , _ = fmt . Fprintf ( w , "You are using a 'slim' build of Coder, which does not support the %s subcommand.\n" , pretty . Sprint ( cliui . DefaultStyles . Code , cmd ))
2023-09-04 19:38:53 +03:00
_ , _ = fmt . Fprintln ( w , "" )
_ , _ = fmt . Fprintln ( w , "Please use a build of Coder from GitHub releases:" )
_ , _ = fmt . Fprintln ( w , " https://github.com/coder/coder/releases" )
//nolint:revive
os . Exit ( 1 )
}
2024-01-30 17:11:37 -06:00
func defaultUpgradeMessage ( version string ) string {
// Our installation script doesn't work on Windows, so instead we direct the user
// to the GitHub release page to download the latest installer.
version = strings . TrimPrefix ( version , "v" )
if runtime . GOOS == "windows" {
return fmt . Sprintf ( "download the server version from: https://github.com/coder/coder/releases/v%s" , version )
}
return fmt . Sprintf ( "download the server version with: 'curl -L https://coder.com/install.sh | sh -s -- --version %s'" , version )
}