2022-02-10 08:33:27 -06:00
package cli
import (
2022-05-19 15:35:59 -07:00
"fmt"
2022-02-10 08:33:27 -06:00
"net/url"
"os"
2022-06-29 17:49:40 -05:00
"strconv"
2022-05-23 12:19:33 -05:00
"strings"
2022-04-04 20:35:03 -05:00
"time"
2022-02-10 08:33:27 -06:00
2022-05-23 14:51:49 -04:00
"golang.org/x/xerrors"
2022-06-29 17:49:40 -05:00
"github.com/charmbracelet/lipgloss"
2022-02-10 08:33:27 -06:00
"github.com/kirsle/configdir"
"github.com/mattn/go-isatty"
"github.com/spf13/cobra"
2022-04-07 12:18:58 -05:00
"github.com/coder/coder/buildinfo"
2022-04-30 11:40:30 -05:00
"github.com/coder/coder/cli/cliflag"
2022-03-22 13:17:50 -06:00
"github.com/coder/coder/cli/cliui"
2022-02-10 08:33:27 -06:00
"github.com/coder/coder/cli/config"
"github.com/coder/coder/codersdk"
)
2022-02-21 12:47:08 -06:00
var (
2022-03-22 13:17:50 -06:00
caret = cliui . Styles . Prompt . String ()
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 {
"workspaces" : " " ,
}
2022-02-21 12:47:08 -06:00
)
2022-02-10 08:33:27 -06:00
const (
2022-05-24 13:11:01 -04:00
varURL = "url"
varToken = "token"
varAgentToken = "agent-token"
varAgentURL = "agent-url"
varGlobalConfig = "global-config"
varNoOpen = "no-open"
varForceTty = "force-tty"
notLoggedInMessage = "You are not logged in. Try logging in using 'coder login <url>'."
2022-06-24 18:50:35 -05:00
2022-06-29 17:49:40 -05:00
noVersionCheckFlag = "no-version-warning"
envNoVersionCheck = "CODER_NO_VERSION_WARNING"
)
var (
errUnauthenticated = xerrors . New ( notLoggedInMessage )
envSessionToken = "CODER_SESSION_TOKEN"
2022-02-10 08:33:27 -06:00
)
2022-05-19 00:10:40 +10:00
func init () {
// Customizes the color of headings to make subcommands more visually
// appealing.
header := cliui . Styles . Placeholder
cobra . AddTemplateFunc ( "usageHeader" , func ( s string ) string {
return header . Render ( s )
})
}
2022-02-10 08:33:27 -06:00
func Root () * cobra . Command {
2022-06-29 17:49:40 -05:00
var varSuppressVersion bool
2022-02-10 08:33:27 -06:00
cmd := & cobra . Command {
2022-04-11 18:54:30 -05:00
Use : "coder" ,
SilenceErrors : true ,
SilenceUsage : true ,
2022-05-09 17:42:02 -05:00
Long : `Coder — A tool for provisioning self-hosted development environments.
2022-02-10 08:33:27 -06:00
` ,
2022-06-29 17:49:40 -05:00
PersistentPreRun : func ( cmd * cobra . Command , args [] string ) {
err := func () error {
if varSuppressVersion {
return nil
}
// Login handles checking the versions itself since it
// has a handle to an unauthenticated client.
// Server is skipped for obvious reasons.
2022-06-30 12:03:41 -05:00
if cmd . Name () == "login" || cmd . Name () == "server" || cmd . Name () == "gitssh" {
2022-06-29 17:49:40 -05:00
return nil
}
client , err := createClient ( cmd )
// If the client is unauthenticated we can ignore the check.
// The child commands should handle an unauthenticated client.
if xerrors . Is ( err , errUnauthenticated ) {
return nil
}
if err != nil {
return xerrors . Errorf ( "create client: %w" , err )
}
return checkVersions ( cmd , client )
}()
if err != nil {
// Just log the error here. We never want to fail a command
// due to a pre-run.
_ , _ = fmt . Fprintf ( cmd . ErrOrStderr (),
cliui . Styles . Warn . Render ( "check versions error: %s" ), err )
_ , _ = fmt . Fprintln ( cmd . ErrOrStderr ())
}
},
2022-07-11 19:08:09 +03:00
Example : formatExamples (
example {
Description : "Start a Coder server" ,
Command : "coder server" ,
},
example {
Description : "Get started by creating a template from an example" ,
Command : "coder templates init" ,
},
),
2022-02-10 08:33:27 -06:00
}
2022-03-22 13:17:50 -06:00
cmd . AddCommand (
configSSH (),
2022-05-02 11:08:52 -05:00
create (),
2022-06-27 11:19:10 -05:00
deleteWorkspace (),
2022-05-25 16:43:20 -05:00
dotfiles (),
2022-05-02 11:08:52 -05:00
gitssh (),
list (),
2022-03-22 13:17:50 -06:00
login (),
2022-05-19 17:42:32 -05:00
logout (),
2022-06-24 10:25:01 -05:00
parameters (),
portForward (),
2022-04-07 17:40:27 -05:00
publickey (),
2022-05-12 12:32:56 -05:00
resetPassword (),
2022-06-16 18:24:10 +01:00
schedules (),
2022-05-02 11:08:52 -05:00
server (),
show (),
2022-06-24 10:25:01 -05:00
ssh (),
2022-05-02 11:08:52 -05:00
start (),
2022-05-02 17:51:58 -05:00
state (),
2022-05-02 11:08:52 -05:00
stop (),
templates (),
update (),
users (),
2022-06-06 17:38:51 -05:00
versionCmd (),
2022-06-24 10:25:01 -05:00
wireguardPortForward (),
workspaceAgent (),
2022-03-22 13:17:50 -06:00
)
2022-02-10 08:33:27 -06:00
2022-05-09 17:42:02 -05:00
cmd . SetUsageTemplate ( usageTemplate ())
2022-05-06 13:46:21 -05:00
cmd . PersistentFlags (). String ( varURL , "" , "Specify the URL to your deployment." )
2022-06-29 17:49:40 -05:00
cliflag . BoolVarP ( cmd . PersistentFlags (), & varSuppressVersion , noVersionCheckFlag , "" , envNoVersionCheck , false , "Suppress warning when client and server versions do not match." )
2022-06-24 18:50:35 -05:00
cliflag . String ( cmd . PersistentFlags (), varToken , "" , envSessionToken , "" , fmt . Sprintf ( "Specify an authentication token. For security reasons setting %s is preferred." , envSessionToken ))
2022-04-30 11:40:30 -05:00
cliflag . String ( cmd . PersistentFlags (), varAgentToken , "" , "CODER_AGENT_TOKEN" , "" , "Specify an agent authentication token." )
2022-05-10 15:57:07 -05:00
_ = cmd . PersistentFlags (). MarkHidden ( varAgentToken )
2022-04-30 11:40:30 -05:00
cliflag . String ( cmd . PersistentFlags (), varAgentURL , "" , "CODER_AGENT_URL" , "" , "Specify the URL for an agent to access your deployment." )
2022-05-10 15:57:07 -05:00
_ = cmd . PersistentFlags (). MarkHidden ( varAgentURL )
2022-04-30 11:40:30 -05:00
cliflag . String ( cmd . PersistentFlags (), varGlobalConfig , "" , "CODER_CONFIG_DIR" , configdir . LocalConfig ( "coderv2" ), "Specify the path to the global `coder` config directory." )
cmd . PersistentFlags (). Bool ( varForceTty , false , "Force the `coder` command to run as if connected to a TTY." )
_ = cmd . PersistentFlags (). MarkHidden ( varForceTty )
2022-02-21 11:10:05 -06:00
cmd . PersistentFlags (). Bool ( varNoOpen , false , "Block automatically opening URLs in the browser." )
2022-04-30 11:40:30 -05:00
_ = cmd . PersistentFlags (). MarkHidden ( varNoOpen )
2022-02-10 08:33:27 -06:00
return cmd
}
2022-06-06 17:38:51 -05:00
// versionCmd prints the coder version
func versionCmd () * cobra . Command {
return & cobra . Command {
2022-07-11 19:08:09 +03:00
Use : "version" ,
Short : "Show coder version" ,
2022-06-06 17:38:51 -05:00
RunE : func ( cmd * cobra . Command , args [] string ) error {
var str strings . Builder
_ , _ = str . WriteString ( fmt . Sprintf ( "Coder %s" , buildinfo . Version ()))
buildTime , valid := buildinfo . Time ()
if valid {
_ , _ = str . WriteString ( " " + buildTime . Format ( time . UnixDate ))
}
_ , _ = str . WriteString ( "\r\n" + buildinfo . ExternalURL () + "\r\n" )
_ , _ = fmt . Fprint ( cmd . OutOrStdout (), str . String ())
return nil
},
}
}
2022-02-12 13:34:04 -06:00
// createClient returns a new client from the command context.
2022-04-30 11:40:30 -05:00
// It reads from global configuration files if flags are not set.
2022-02-10 08:33:27 -06:00
func createClient ( cmd * cobra . Command ) ( * codersdk . Client , error ) {
root := createConfig ( cmd )
2022-04-30 11:40:30 -05:00
rawURL , err := cmd . Flags (). GetString ( varURL )
if err != nil || rawURL == "" {
rawURL , err = root . URL (). Read ()
if err != nil {
2022-05-23 14:51:49 -04:00
// If the configuration files are absent, the user is logged out
if os . IsNotExist ( err ) {
2022-06-29 17:49:40 -05:00
return nil , errUnauthenticated
2022-05-23 14:51:49 -04:00
}
2022-04-30 11:40:30 -05:00
return nil , err
}
}
2022-05-23 12:19:33 -05:00
serverURL , err := url . Parse ( strings . TrimSpace ( rawURL ))
2022-04-30 11:40:30 -05:00
if err != nil {
return nil , err
}
token , err := cmd . Flags (). GetString ( varToken )
if err != nil || token == "" {
token , err = root . Session (). Read ()
if err != nil {
2022-05-23 14:51:49 -04:00
// If the configuration files are absent, the user is logged out
if os . IsNotExist ( err ) {
2022-06-29 17:49:40 -05:00
return nil , errUnauthenticated
2022-05-23 14:51:49 -04:00
}
2022-04-30 11:40:30 -05:00
return nil , err
}
}
client := codersdk . New ( serverURL )
2022-05-23 12:19:33 -05:00
client . SessionToken = strings . TrimSpace ( token )
2022-04-30 11:40:30 -05:00
return client , nil
}
// createAgentClient returns a new client from the command context.
// It works just like createClient, but uses the agent token and URL instead.
func createAgentClient ( cmd * cobra . Command ) ( * codersdk . Client , error ) {
rawURL , err := cmd . Flags (). GetString ( varAgentURL )
2022-02-10 08:33:27 -06:00
if err != nil {
return nil , err
}
serverURL , err := url . Parse ( rawURL )
if err != nil {
return nil , err
}
2022-04-30 11:40:30 -05:00
token , err := cmd . Flags (). GetString ( varAgentToken )
2022-02-10 08:33:27 -06:00
if err != nil {
return nil , err
}
client := codersdk . New ( serverURL )
2022-02-12 13:34:04 -06:00
client . SessionToken = token
return client , nil
2022-02-10 08:33:27 -06:00
}
2022-02-12 13:34:04 -06:00
// currentOrganization returns the currently active organization for the authenticated user.
2022-03-22 13:17:50 -06:00
func currentOrganization ( cmd * cobra . Command , client * codersdk . Client ) ( codersdk . Organization , error ) {
2022-04-01 14:42:36 -05:00
orgs , err := client . OrganizationsByUser ( cmd . 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
}
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.
2022-06-03 14:36:08 -05:00
func namedWorkspace ( cmd * cobra . Command , client * codersdk . Client , identifier string ) ( codersdk . Workspace , error ) {
2022-06-03 12:47:56 -05:00
parts := strings . Split ( identifier , "/" )
var owner , name string
switch len ( parts ) {
case 1 :
owner = codersdk . Me
name = parts [ 0 ]
case 2 :
owner = parts [ 0 ]
name = parts [ 1 ]
default :
return codersdk . Workspace {}, xerrors . Errorf ( "invalid workspace name: %q" , identifier )
}
2022-06-10 09:58:42 -05:00
return client . WorkspaceByOwnerAndName ( cmd . Context (), 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.
2022-02-10 08:33:27 -06:00
func createConfig ( cmd * cobra . Command ) config . Root {
globalRoot , err := cmd . Flags (). GetString ( varGlobalConfig )
if err != nil {
panic ( err )
}
return config . Root ( globalRoot )
}
// isTTY returns whether the passed reader is a TTY or not.
// This accepts a reader to work with Cobra's "InOrStdin"
// function for simple testing.
2022-02-14 17:05:40 -08:00
func isTTY ( cmd * cobra . Command ) bool {
// 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)
forceTty , err := cmd . Flags (). GetBool ( varForceTty )
if forceTty && err == nil {
return true
}
2022-03-22 13:17:50 -06:00
file , ok := cmd . InOrStdin ().( * 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.
// This accepts a reader to work with Cobra's "OutOrStdout"
// function for simple testing.
func isTTYOut ( cmd * cobra . Command ) bool {
// 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)
forceTty , err := cmd . Flags (). GetBool ( varForceTty )
if forceTty && err == nil {
return true
}
file , ok := cmd . OutOrStdout ().( * os . File )
if ! ok {
return false
}
return isatty . IsTerminal ( file . Fd ())
}
2022-05-09 17:42:02 -05:00
func usageTemplate () string {
2022-05-19 00:10:40 +10:00
// usageHeader is defined in init().
2022-05-16 20:01:42 +03:00
return ` {{ usageHeader "Usage:" }}
{{- if .Runnable }}
{{ .UseLine }}
{{ end }}
{{- if .HasAvailableSubCommands }}
{{ .CommandPath }} [command]
{{ end }}
{{- if gt ( len .Aliases ) 0 }}
{{ usageHeader "Aliases:" }}
{{ .NameAndAliases }}
{{ end }}
{{- if .HasExample }}
{{ usageHeader "Get Started:" }}
2022-05-09 17:42:02 -05:00
{{ .Example }}
2022-05-16 20:01:42 +03:00
{{ end }}
2022-05-09 17:42:02 -05:00
2022-05-16 20:01:42 +03:00
{{- if .HasAvailableSubCommands }}
{{ usageHeader "Commands:" }}
{{- range .Commands }}
{{- if ( or ( and .IsAvailableCommand ( eq ( len .Annotations ) 0 )) ( eq .Name "help" )) }}
{{ rpad .Name .NamePadding }} {{ .Short }}
{{- end }}
{{- end }}
{{ end }}
2022-05-09 17:42:02 -05:00
2022-05-16 20:01:42 +03:00
{{- if and ( not .HasParent ) .HasAvailableSubCommands }}
{{ usageHeader "Workspace Commands:" }}
{{- range .Commands }}
{{- if ( and .IsAvailableCommand ( ne ( index .Annotations "workspaces" ) "" )) }}
{{ rpad .Name .NamePadding }} {{ .Short }}
{{- end }}
{{- end }}
{{ end }}
2022-05-09 17:42:02 -05:00
2022-05-16 20:01:42 +03:00
{{- if .HasAvailableLocalFlags }}
{{ usageHeader "Flags:" }}
2022-07-11 17:07:25 +03:00
{{ .LocalFlags.FlagUsagesWrapped 100 }}
2022-05-16 20:01:42 +03:00
{{ end }}
2022-05-09 17:42:02 -05:00
2022-05-16 20:01:42 +03:00
{{- if .HasAvailableInheritedFlags }}
{{ usageHeader "Global Flags:" }}
2022-07-11 17:07:25 +03:00
{{ .InheritedFlags.FlagUsagesWrapped 100 }}
2022-05-16 20:01:42 +03:00
{{ end }}
{{- if .HasHelpSubCommands }}
{{ usageHeader "Additional help topics:" }}
{{- range .Commands }}
{{- if .IsAdditionalHelpTopicCommand }}
{{ rpad .CommandPath .CommandPathPadding }} {{ .Short }}
{{- end }}
{{- end }}
{{ end }}
{{- if .HasAvailableSubCommands }}
2022-05-09 17:42:02 -05:00
Use " {{ .CommandPath }} [command] --help" for more information about a command.
2022-05-16 20:01:42 +03:00
{{ end }} `
2022-05-09 17:42:02 -05:00
}
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
}
// formatExamples formats the exampels as width wrapped bulletpoint
// descriptions with the command underneath.
func formatExamples ( examples ... example ) string {
wrap := cliui . Styles . Wrap . Copy ()
wrap . PaddingLeft ( 4 )
var sb strings . Builder
for i , e := range examples {
if len ( e . Description ) > 0 {
_ , _ = sb . WriteString ( " - " + wrap . Render ( e . Description + ":" )[ 4 :] + "\n\n " )
}
// We add 1 space here because `cliui.Styles.Code` adds an extra
// space. This makes the code block align at an even 2 or 6
// spaces for symmetry.
_ , _ = sb . WriteString ( " " + cliui . Styles . Code . Render ( fmt . Sprintf ( "$ %s" , e . Command )))
if i < len ( examples ) - 1 {
_ , _ = sb . WriteString ( "\n\n" )
}
}
return sb . String ()
}
2022-05-19 15:35:59 -07:00
// FormatCobraError colorizes and adds "--help" docs to cobra commands.
func FormatCobraError ( err error , cmd * cobra . Command ) string {
2022-05-20 12:42:56 +03:00
helpErrMsg := fmt . Sprintf ( "Run '%s --help' for usage." , cmd . CommandPath ())
2022-05-19 15:35:59 -07:00
return cliui . Styles . Error . Render ( err . Error () + "\n" + helpErrMsg )
}
2022-06-29 17:49:40 -05:00
func checkVersions ( cmd * cobra . Command , client * codersdk . Client ) error {
flag := cmd . Flag ( "no-version-warning" )
if suppress , _ := strconv . ParseBool ( flag . Value . String ()); suppress {
return nil
}
clientVersion := buildinfo . Version ()
info , err := client . BuildInfo ( cmd . Context ())
if err != nil {
return xerrors . Errorf ( "build info: %w" , err )
}
fmtWarningText := `version mismatch: client %s, server %s
download the server version with: 'curl -L https://coder.com/install.sh | sh -s -- --version %s'
`
if ! buildinfo . VersionsMatch ( clientVersion , info . Version ) {
warn := cliui . Styles . Warn . Copy (). Align ( lipgloss . Left )
// Trim the leading 'v', our install.sh script does not handle this case well.
_ , _ = fmt . Fprintf ( cmd . OutOrStdout (), warn . Render ( fmtWarningText ), clientVersion , info . Version , strings . TrimPrefix ( info . CanonicalVersion (), "v" ))
_ , _ = fmt . Fprintln ( cmd . OutOrStdout ())
}
return nil
}