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-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-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-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 {
cmd := & cobra . Command {
2022-04-11 18:54:30 -05:00
Use : "coder" ,
Version : buildinfo . Version (),
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-05-09 17:42:02 -05:00
Example : ` Start Coder in "dev" mode. This dev-mode requires no further setup, and your local ` + cliui . Styles . Code . Render ( "coder" ) + ` CLI will be authenticated to talk to it. This makes it easy to experiment with Coder.
` + cliui . Styles . Code . Render ( "$ coder server --dev" ) + `
2022-02-10 08:33:27 -06:00
2022-05-09 17:42:02 -05:00
Get started by creating a template from an example.
` + cliui . Styles . Code . Render ( "$ coder templates init" ),
2022-02-10 08:33:27 -06:00
}
2022-03-22 13:17:50 -06:00
cmd . AddCommand (
2022-05-02 11:08:52 -05:00
autostart (),
2022-05-27 20:04:33 +01:00
bump (),
2022-03-22 13:17:50 -06:00
configSSH (),
2022-05-02 11:08:52 -05:00
create (),
delete (),
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-04-07 17:40:27 -05:00
publickey (),
2022-05-12 12:32:56 -05:00
resetPassword (),
2022-05-02 11:08:52 -05:00
server (),
show (),
start (),
2022-05-02 17:51:58 -05:00
state (),
2022-05-02 11:08:52 -05:00
stop (),
ssh (),
templates (),
2022-05-19 20:09:27 +01:00
ttl (),
2022-05-02 11:08:52 -05:00
update (),
users (),
2022-05-19 00:10:40 +10:00
portForward (),
2022-04-13 15:55:55 -05:00
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 ())
cmd . SetVersionTemplate ( versionTemplate ())
2022-05-06 13:46:21 -05:00
cmd . PersistentFlags (). String ( varURL , "" , "Specify the URL to your deployment." )
cmd . PersistentFlags (). String ( varToken , "" , "Specify an authentication token." )
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-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-05-24 13:11:01 -04:00
return nil , xerrors . New ( notLoggedInMessage )
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-05-24 13:11:01 -04:00
return nil , xerrors . New ( notLoggedInMessage )
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-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-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:" }}
{{ .LocalFlags.FlagUsages | trimTrailingWhitespaces }}
{{ end }}
2022-05-09 17:42:02 -05:00
2022-05-16 20:01:42 +03:00
{{- if .HasAvailableInheritedFlags }}
{{ usageHeader "Global Flags:" }}
{{ .InheritedFlags.FlagUsages | trimTrailingWhitespaces }}
{{ 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-04-04 20:35:03 -05:00
func versionTemplate () string {
template := `Coder {{ printf "%s" .Version }} `
buildTime , valid := buildinfo . Time ()
if valid {
template += " " + buildTime . Format ( time . UnixDate )
}
template += "\r\n" + buildinfo . ExternalURL ()
template += "\r\n"
return template
}
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 )
}