Skip to content

feat: Add "coder" CLI #221

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Feb 10, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add CLI test for login
  • Loading branch information
kylecarbs committed Feb 9, 2022
commit 24cc781cd023e9b851f7db98e8d78e57cce88788
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,11 @@
"goleak",
"hashicorp",
"httpmw",
"isatty",
"Jobf",
"kirsle",
"manifoldco",
"mattn",
"moby",
"nhooyr",
"nolint",
Expand Down
38 changes: 38 additions & 0 deletions cli/clitest/clitest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package clitest

import (
"bufio"
"io"
"testing"

"github.com/spf13/cobra"

"github.com/coder/coder/cli"
"github.com/coder/coder/cli/config"
)

func New(t *testing.T, args ...string) (*cobra.Command, config.Root) {
cmd := cli.Root()
dir := t.TempDir()
root := config.Root(dir)
cmd.SetArgs(append([]string{"--global-config", dir}, args...))
return cmd, root
}

func StdoutLogs(t *testing.T) io.Writer {
reader, writer := io.Pipe()
scanner := bufio.NewScanner(reader)
t.Cleanup(func() {
_ = reader.Close()
_ = writer.Close()
})
go func() {
for scanner.Scan() {
if scanner.Err() != nil {
return
}
t.Log(scanner.Text())
}
}()
return writer
}
2 changes: 1 addition & 1 deletion cli/config/file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func TestFile(t *testing.T) {
require.NoError(t, err)
data, err := root.Session().Read()
require.NoError(t, err)
require.Equal(t, "test", string(data))
require.Equal(t, "test", data)
})

t.Run("Delete", func(t *testing.T) {
Expand Down
15 changes: 8 additions & 7 deletions cli/login.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
package cli

import (
"errors"
"fmt"
"net/url"
"os"
"strings"

"github.com/coder/coder/coderd"
"github.com/coder/coder/codersdk"
"github.com/fatih/color"
"github.com/go-playground/validator/v10"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"golang.org/x/xerrors"

"github.com/coder/coder/coderd"
"github.com/coder/coder/codersdk"
)

func login() *cobra.Command {
Expand Down Expand Up @@ -46,7 +47,7 @@ func login() *cobra.Command {
if !isTTY(cmd.InOrStdin()) {
return xerrors.New("the initial user cannot be created in non-interactive mode. use the API")
}
fmt.Fprintf(cmd.OutOrStdout(), "%s Your Coder deployment hasn't been setup!\n", color.HiBlackString(">"))
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s Your Coder deployment hasn't been setup!\n", color.HiBlackString(">"))

_, err := runPrompt(cmd, &promptui.Prompt{
Label: "Would you like to create the first user?",
Expand All @@ -59,7 +60,7 @@ func login() *cobra.Command {

username, err := runPrompt(cmd, &promptui.Prompt{
Label: "What username would you like?",
Default: "kyle",
Default: os.Getenv("USER"),
})
if err != nil {
return err
Expand All @@ -78,7 +79,7 @@ func login() *cobra.Command {
Validate: func(s string) error {
err := validator.New().Var(s, "email")
if err != nil {
return errors.New("That's not a valid email address!")
return xerrors.New("That's not a valid email address!")
}
return err
},
Expand Down Expand Up @@ -121,7 +122,7 @@ func login() *cobra.Command {
return xerrors.Errorf("write server url: %w", err)
}

fmt.Fprintf(cmd.OutOrStdout(), "%s Welcome to Coder, %s! You're logged in.\n", color.HiBlackString(">"), color.HiCyanString(username))
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s Welcome to Coder, %s! You're logged in.\n", color.HiBlackString(">"), color.HiCyanString(username))
return nil
}

Expand Down
54 changes: 54 additions & 0 deletions cli/login_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package cli_test

import (
"testing"

"github.com/coder/coder/cli/clitest"
"github.com/coder/coder/coderd/coderdtest"
"github.com/stretchr/testify/require"

"github.com/Netflix/go-expect"
)

func TestLogin(t *testing.T) {
t.Parallel()
t.Run("InitialUserNoTTY", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t)
root, _ := clitest.New(t, "login", client.URL.String())
err := root.Execute()
require.Error(t, err)
})

t.Run("InitialUserTTY", func(t *testing.T) {
t.Parallel()
console, err := expect.NewConsole(expect.WithStdout(clitest.StdoutLogs(t)))
require.NoError(t, err)
client := coderdtest.New(t)
root, _ := clitest.New(t, "login", client.URL.String())
root.SetIn(console.Tty())
root.SetOut(console.Tty())
go func() {
err = root.Execute()
require.NoError(t, err)
}()

matches := []string{
"first user?", "y",
"username", "testuser",
"organization", "testorg",
"email", "user@coder.com",
"password", "password",
}
for i := 0; i < len(matches); i += 2 {
match := matches[i]
value := matches[i+1]
_, err = console.ExpectString(match)
require.NoError(t, err)
_, err = console.SendLine(value)
require.NoError(t, err)
}
_, err = console.ExpectString("Welcome to Coder")
require.NoError(t, err)
})
}
62 changes: 28 additions & 34 deletions cli/projectcreate.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ import (
"time"

"github.com/briandowns/spinner"
"github.com/coder/coder/coderd"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/database"
"github.com/fatih/color"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"golang.org/x/xerrors"

"github.com/coder/coder/coderd"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/database"
)

func projectCreate() *cobra.Command {
Expand Down Expand Up @@ -48,9 +49,8 @@ func projectCreate() *cobra.Command {
return err
}

name := filepath.Base(workingDir)
name, err = runPrompt(cmd, &promptui.Prompt{
Default: name,
name, err := runPrompt(cmd, &promptui.Prompt{
Default: filepath.Base(workingDir),
Label: "What's your project's name?",
Validate: func(s string) error {
_, err = client.Project(cmd.Context(), organization.Name, s)
Expand All @@ -69,7 +69,7 @@ func projectCreate() *cobra.Command {
spin.Start()
defer spin.Stop()

bytes, err := tarDir(workingDir)
bytes, err := tarDirectory(workingDir)
if err != nil {
return err
}
Expand All @@ -91,8 +91,6 @@ func projectCreate() *cobra.Command {
}
spin.Stop()

time.Sleep(time.Second)

logs, err := client.FollowProvisionerJobLogsAfter(context.Background(), organization.Name, job.ID, time.Time{})
if err != nil {
return err
Expand All @@ -102,54 +100,50 @@ func projectCreate() *cobra.Command {
if !ok {
break
}
fmt.Fprintf(cmd.OutOrStdout(), "%s %s\n", color.HiGreenString("[parse]"), log.Output)
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s %s\n", color.HiGreenString("[parse]"), log.Output)
}

fmt.Printf("Projects %+v %+v\n", projects, organization)
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Create project %q!\n", name)
return nil
},
}
}

func tarDir(directory string) ([]byte, error) {
func tarDirectory(directory string) ([]byte, error) {
var buffer bytes.Buffer
tw := tar.NewWriter(&buffer)
// walk through every file in the folder
err := filepath.Walk(directory, func(file string, fi os.FileInfo, err error) error {
// generate tar header
header, err := tar.FileInfoHeader(fi, file)
tarWriter := tar.NewWriter(&buffer)
err := filepath.Walk(directory, func(file string, fileInfo os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := tar.FileInfoHeader(fileInfo, file)
if err != nil {
return err
}

// must provide real name
// (see https://golang.org/src/archive/tar/common.go?#L626)
rel, err := filepath.Rel(directory, file)
if err != nil {
return err
}
header.Name = rel

// write header
if err := tw.WriteHeader(header); err != nil {
if err := tarWriter.WriteHeader(header); err != nil {
return err
}
// if not a dir, write file content
if !fi.IsDir() {
data, err := os.Open(file)
if err != nil {
return err
}
if _, err := io.Copy(tw, data); err != nil {
return err
}
if fileInfo.IsDir() {
return nil
}
data, err := os.Open(file)
if err != nil {
return err
}
if _, err := io.Copy(tarWriter, data); err != nil {
return err
}
return nil
return data.Close()
})
if err != nil {
return nil, err
}
err = tw.Flush()
err = tarWriter.Flush()
if err != nil {
return nil, err
}
Expand Down
19 changes: 14 additions & 5 deletions cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@ import (
"os"
"strings"

"github.com/coder/coder/cli/config"
"github.com/coder/coder/coderd"
"github.com/coder/coder/codersdk"
"github.com/fatih/color"
"github.com/kirsle/configdir"
"github.com/manifoldco/promptui"
"github.com/mattn/go-isatty"
"github.com/spf13/cobra"
"golang.org/x/xerrors"

"github.com/coder/coder/cli/config"
"github.com/coder/coder/coderd"
"github.com/coder/coder/codersdk"
)

const (
Expand Down Expand Up @@ -115,8 +117,15 @@ func isTTY(reader io.Reader) bool {
}

func runPrompt(cmd *cobra.Command, prompt *promptui.Prompt) (string, error) {
prompt.Stdin = cmd.InOrStdin().(io.ReadCloser)
prompt.Stdout = cmd.OutOrStdout().(io.WriteCloser)
var ok bool
prompt.Stdin, ok = cmd.InOrStdin().(io.ReadCloser)
if !ok {
return "", xerrors.New("stdin must be a readcloser")
}
prompt.Stdout, ok = cmd.OutOrStdout().(io.WriteCloser)
if !ok {
return "", xerrors.New("stdout must be a readcloser")
}

// The prompt library displays defaults in a jarring way for the user
// by attempting to autocomplete it. This sets no default enabling us
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ replace github.com/hashicorp/terraform-config-inspect => github.com/kylecarbs/te

require (
cdr.dev/slog v1.4.1
github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2
github.com/briandowns/spinner v1.18.1
github.com/coder/retry v1.3.0
github.com/fatih/color v1.13.0
Expand Down Expand Up @@ -58,6 +59,7 @@ require (
github.com/cenkalti/backoff/v4 v4.1.2 // indirect
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e // indirect
github.com/containerd/continuity v0.2.2 // indirect
github.com/creack/pty v1.1.17 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dhui/dktest v0.3.9 // indirect
github.com/dlclark/regexp2 v1.4.0 // indirect
Expand Down
5 changes: 4 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ github.com/Microsoft/hcsshim v0.8.23/go.mod h1:4zegtUJth7lAvFyc6cH2gGQ5B3OFQim01
github.com/Microsoft/hcsshim/test v0.0.0-20201218223536-d3e5debf77da/go.mod h1:5hlzMzRKMLyo42nCZ9oml8AdTlq/0cvIaBv6tK1RehU=
github.com/Microsoft/hcsshim/test v0.0.0-20210227013316-43a75bb4edd3/go.mod h1:mw7qgWloBUl75W/gVH3cQszUg1+gUITj7D6NY7ywVnY=
github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ=
github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2 h1:+vx7roKuyA63nhn5WAunQHLTznkw5W8b1Xc0dNjp83s=
github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2/go.mod h1:HBCaDeC1lPdgDeDbhX8XFpy1jqjK0IBG8W5K+xYqA0w=
github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 h1:TngWCqHvy9oXAN6lEVMRuU21PR1EtLVZJmdB18Gu3Rw=
github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5/go.mod h1:lmUJ/7eu/Q8D7ML55dXQrVaamCz2vxCfdQBasLZfHKk=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
Expand Down Expand Up @@ -350,8 +352,9 @@ github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsr
github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw=
github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/creack/pty v1.1.17 h1:QeVUsEDNrLBW4tMgZHvxy18sKtr6VI492kBhUfhDJNI=
github.com/creack/pty v1.1.17/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=
github.com/cyphar/filepath-securejoin v0.2.2/go.mod h1:FpkQEhXnPnOthhzymB7CGsFk2G9VLXONKD9G7QGMM+4=
github.com/cyphar/filepath-securejoin v0.2.3/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxGGx79pTxQpKOJNYHHl4=
github.com/cznic/mathutil v0.0.0-20180504122225-ca4c9f2c1369/go.mod h1:e6NPNENfs9mPDVNRekM7lKScauxd5kXTr1Mfyig6TDM=
Expand Down