Skip to content

Commit dc106d7

Browse files
committed
merge conflict
2 parents a4f84e3 + 7a52a9c commit dc106d7

File tree

101 files changed

+2650
-2213
lines changed

Some content is hidden

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

101 files changed

+2650
-2213
lines changed

Makefile

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -501,9 +501,10 @@ docs/admin/prometheus.md: scripts/metricsdocgen/main.go scripts/metricsdocgen/me
501501
yarn run format:write:only ../docs/admin/prometheus.md
502502

503503
docs/cli/coder.md: scripts/clidocgen/main.go $(GO_SRC_FILES) docs/manifest.json
504-
BASE_PATH="." go run scripts/clidocgen/main.go
504+
rm -rf ./docs/cli/*.md
505+
BASE_PATH="." go run ./scripts/clidocgen
505506
cd site
506-
yarn run format:write:only ../docs/cli/*.md ../docs/manifest.json
507+
yarn run format:write:only ../docs/cli.md ../docs/cli/*.md ../docs/manifest.json
507508

508509
docs/admin/audit-logs.md: scripts/auditdocgen/main.go enterprise/audit/table.go
509510
go run scripts/auditdocgen/main.go

cli/speedtest.go

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ import (
1919

2020
func speedtest() *cobra.Command {
2121
var (
22-
direct bool
23-
duration time.Duration
24-
reverse bool
22+
direct bool
23+
duration time.Duration
24+
direction string
2525
)
2626
cmd := &cobra.Command{
2727
Annotations: workspaceCommand,
@@ -48,7 +48,7 @@ func speedtest() *cobra.Command {
4848
return client.WorkspaceAgent(ctx, workspaceAgent.ID)
4949
},
5050
})
51-
if err != nil {
51+
if err != nil && !xerrors.Is(err, cliui.AgentStartError) {
5252
return xerrors.Errorf("await agent: %w", err)
5353
}
5454
logger := slog.Make(sloghuman.Sink(cmd.ErrOrStderr()))
@@ -94,25 +94,29 @@ func speedtest() *cobra.Command {
9494
} else {
9595
conn.AwaitReachable(ctx)
9696
}
97-
dir := tsspeedtest.Download
98-
if reverse {
99-
dir = tsspeedtest.Upload
97+
var tsDir tsspeedtest.Direction
98+
switch direction {
99+
case "up":
100+
tsDir = tsspeedtest.Upload
101+
case "down":
102+
tsDir = tsspeedtest.Download
103+
default:
104+
return xerrors.Errorf("invalid direction: %q", direction)
100105
}
101-
cmd.Printf("Starting a %ds %s test...\n", int(duration.Seconds()), dir)
102-
results, err := conn.Speedtest(ctx, dir, duration)
106+
cmd.Printf("Starting a %ds %s test...\n", int(duration.Seconds()), tsDir)
107+
results, err := conn.Speedtest(ctx, tsDir, duration)
103108
if err != nil {
104109
return err
105110
}
106111
tableWriter := cliui.Table()
107-
tableWriter.AppendHeader(table.Row{"Interval", "Transfer", "Bandwidth"})
112+
tableWriter.AppendHeader(table.Row{"Interval", "Throughput"})
108113
startTime := results[0].IntervalStart
109114
for _, r := range results {
110115
if r.Total {
111116
tableWriter.AppendSeparator()
112117
}
113118
tableWriter.AppendRow(table.Row{
114119
fmt.Sprintf("%.2f-%.2f sec", r.IntervalStart.Sub(startTime).Seconds(), r.IntervalEnd.Sub(startTime).Seconds()),
115-
fmt.Sprintf("%.4f MBits", r.MegaBits()),
116120
fmt.Sprintf("%.4f Mbits/sec", r.MBitsPerSecond()),
117121
})
118122
}
@@ -122,8 +126,9 @@ func speedtest() *cobra.Command {
122126
}
123127
cliflag.BoolVarP(cmd.Flags(), &direct, "direct", "d", "", false,
124128
"Specifies whether to wait for a direct connection before testing speed.")
125-
cliflag.BoolVarP(cmd.Flags(), &reverse, "reverse", "r", "", false,
126-
"Specifies whether to run in reverse mode where the client receives and the server sends.")
129+
cliflag.StringVarP(cmd.Flags(), &direction, "direction", "", "", "down",
130+
"Specifies whether to run in reverse mode where the client receives and the server sends. (up|down)",
131+
)
127132
cmd.Flags().DurationVarP(&duration, "time", "t", tsspeedtest.DefaultDuration,
128133
"Specifies the duration to monitor traffic.")
129134
return cmd

cli/state.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,9 @@ func state() *cobra.Command {
2727
func statePull() *cobra.Command {
2828
var buildNumber int
2929
cmd := &cobra.Command{
30-
Use: "pull <workspace> [file]",
31-
Args: cobra.MinimumNArgs(1),
30+
Use: "pull <workspace> [file]",
31+
Short: "Pull a Terraform state file from a workspace.",
32+
Args: cobra.MinimumNArgs(1),
3233
RunE: func(cmd *cobra.Command, args []string) error {
3334
client, err := CreateClient(cmd)
3435
if err != nil {
@@ -68,8 +69,9 @@ func statePull() *cobra.Command {
6869
func statePush() *cobra.Command {
6970
var buildNumber int
7071
cmd := &cobra.Command{
71-
Use: "push <workspace> <file>",
72-
Args: cobra.ExactArgs(2),
72+
Use: "push <workspace> <file>",
73+
Args: cobra.ExactArgs(2),
74+
Short: "Push a Terraform state file to a workspace.",
7375
RunE: func(cmd *cobra.Command, args []string) error {
7476
client, err := CreateClient(cmd)
7577
if err != nil {

cli/templatepull.go

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
package cli
22

33
import (
4+
"bytes"
45
"fmt"
5-
"io/fs"
66
"os"
77
"sort"
88

9+
"github.com/codeclysm/extract"
910
"github.com/spf13/cobra"
1011
"golang.org/x/xerrors"
1112

@@ -14,6 +15,7 @@ import (
1415
)
1516

1617
func templatePull() *cobra.Command {
18+
var tarMode bool
1719
cmd := &cobra.Command{
1820
Use: "pull <name> [destination]",
1921
Short: "Download the latest version of a template to a path.",
@@ -75,48 +77,44 @@ func templatePull() *cobra.Command {
7577
return xerrors.Errorf("unexpected Content-Type %q, expecting %q", ctype, codersdk.ContentTypeTar)
7678
}
7779

78-
// If the destination is empty then we write to stdout
79-
// and bail early.
80-
if dest == "" {
80+
if tarMode {
8181
_, err = cmd.OutOrStdout().Write(raw)
82-
if err != nil {
83-
return xerrors.Errorf("write stdout: %w", err)
84-
}
85-
return nil
82+
return err
8683
}
8784

88-
// Stat the destination to ensure nothing exists already.
89-
fi, err := os.Stat(dest)
90-
if err != nil && !xerrors.Is(err, fs.ErrNotExist) {
91-
return xerrors.Errorf("stat destination: %w", err)
85+
if dest == "" {
86+
dest = templateName + "/"
9287
}
9388

94-
if fi != nil && fi.IsDir() {
95-
// If the destination is a directory we just bail.
96-
return xerrors.Errorf("%q already exists.", dest)
89+
err = os.MkdirAll(dest, 0o750)
90+
if err != nil {
91+
return xerrors.Errorf("mkdirall %q: %w", dest, err)
9792
}
9893

99-
// If a file exists at the destination prompt the user
100-
// to ensure we don't overwrite something valuable.
101-
if fi != nil {
94+
ents, err := os.ReadDir(dest)
95+
if err != nil {
96+
return xerrors.Errorf("read dir %q: %w", dest, err)
97+
}
98+
99+
if len(ents) > 0 {
102100
_, err = cliui.Prompt(cmd, cliui.PromptOptions{
103-
Text: fmt.Sprintf("%q already exists, do you want to overwrite it?", dest),
101+
Text: fmt.Sprintf("Directory %q is not empty, existing files may be overwritten.\nContinue extracting?", dest),
102+
Default: "No",
103+
Secret: false,
104104
IsConfirm: true,
105105
})
106106
if err != nil {
107-
return xerrors.Errorf("parse prompt: %w", err)
107+
return err
108108
}
109109
}
110110

111-
err = os.WriteFile(dest, raw, 0o600)
112-
if err != nil {
113-
return xerrors.Errorf("write to path: %w", err)
114-
}
115-
116-
return nil
111+
_, _ = fmt.Fprintf(cmd.OutOrStderr(), "Extracting template to %q\n", dest)
112+
err = extract.Tar(ctx, bytes.NewReader(raw), dest, nil)
113+
return err
117114
},
118115
}
119116

117+
cmd.Flags().BoolVar(&tarMode, "tar", false, "output the template as a tar archive to stdout")
120118
cliui.AllowSkipPrompt(cmd)
121119

122120
return cmd

cli/templatepull_test.go

Lines changed: 103 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,14 @@ package cli_test
22

33
import (
44
"bytes"
5+
"context"
6+
"crypto/sha256"
7+
"encoding/hex"
58
"os"
69
"path/filepath"
710
"testing"
811

12+
"github.com/codeclysm/extract"
913
"github.com/google/uuid"
1014
"github.com/stretchr/testify/require"
1115

@@ -16,6 +20,26 @@ import (
1620
"github.com/coder/coder/pty/ptytest"
1721
)
1822

23+
// dirSum calculates a checksum of the files in a directory.
24+
func dirSum(t *testing.T, dir string) string {
25+
ents, err := os.ReadDir(dir)
26+
require.NoError(t, err)
27+
sum := sha256.New()
28+
for _, e := range ents {
29+
path := filepath.Join(dir, e.Name())
30+
31+
stat, err := os.Stat(path)
32+
require.NoError(t, err)
33+
34+
byt, err := os.ReadFile(
35+
path,
36+
)
37+
require.NoError(t, err, "mode: %+v", stat.Mode())
38+
_, _ = sum.Write(byt)
39+
}
40+
return hex.EncodeToString(sum.Sum(nil))
41+
}
42+
1943
func TestTemplatePull(t *testing.T) {
2044
t.Parallel()
2145

@@ -53,7 +77,7 @@ func TestTemplatePull(t *testing.T) {
5377
// are being sorted correctly.
5478
_ = coderdtest.UpdateTemplateVersion(t, client, user.OrganizationID, source2, template.ID)
5579

56-
cmd, root := clitest.New(t, "templates", "pull", template.Name)
80+
cmd, root := clitest.New(t, "templates", "pull", "--tar", template.Name)
5781
clitest.SetupConfig(t, client, root)
5882

5983
var buf bytes.Buffer
@@ -65,9 +89,9 @@ func TestTemplatePull(t *testing.T) {
6589
require.True(t, bytes.Equal(expected, buf.Bytes()), "tar files differ")
6690
})
6791

68-
// ToFile tests that 'templates pull' pulls down the latest template
92+
// ToDir tests that 'templates pull' pulls down the latest template
6993
// and writes it to the correct directory.
70-
t.Run("ToFile", func(t *testing.T) {
94+
t.Run("ToDir", func(t *testing.T) {
7195
t.Parallel()
7296

7397
client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true})
@@ -93,15 +117,14 @@ func TestTemplatePull(t *testing.T) {
93117

94118
dir := t.TempDir()
95119

96-
dest := filepath.Join(dir, "actual.tar")
120+
expectedDest := filepath.Join(dir, "expected")
121+
actualDest := filepath.Join(dir, "actual")
122+
ctx := context.Background()
97123

98-
// Create the file so that we can test that the command
99-
// warns the user before overwriting a preexisting file.
100-
fi, err := os.OpenFile(dest, os.O_CREATE|os.O_RDONLY, 0o600)
124+
err = extract.Tar(ctx, bytes.NewReader(expected), expectedDest, nil)
101125
require.NoError(t, err)
102-
_ = fi.Close()
103126

104-
cmd, root := clitest.New(t, "templates", "pull", template.Name, dest)
127+
cmd, root := clitest.New(t, "templates", "pull", template.Name, actualDest)
105128
clitest.SetupConfig(t, client, root)
106129

107130
pty := ptytest.New(t)
@@ -114,16 +137,81 @@ func TestTemplatePull(t *testing.T) {
114137
errChan <- cmd.Execute()
115138
}()
116139

117-
// We expect to be prompted that a file already exists.
118-
pty.ExpectMatch("already exists")
119-
pty.WriteLine("yes")
120-
121140
require.NoError(t, <-errChan)
122141

123-
actual, err := os.ReadFile(dest)
142+
require.Equal(t,
143+
dirSum(t, expectedDest),
144+
dirSum(t, actualDest),
145+
)
146+
})
147+
148+
// FolderConflict tests that 'templates pull' fails when a folder with has
149+
// existing
150+
t.Run("FolderConflict", func(t *testing.T) {
151+
t.Parallel()
152+
153+
client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true})
154+
user := coderdtest.CreateFirstUser(t, client)
155+
156+
// Create an initial template bundle.
157+
source1 := genTemplateVersionSource()
158+
// Create an updated template bundle. This will be used to ensure
159+
// that templates are correctly returned in order from latest to oldest.
160+
source2 := genTemplateVersionSource()
161+
162+
expected, err := echo.Tar(source2)
163+
require.NoError(t, err)
164+
165+
version1 := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, source1)
166+
_ = coderdtest.AwaitTemplateVersionJob(t, client, version1.ID)
167+
168+
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version1.ID)
169+
170+
// Update the template version so that we can assert that templates
171+
// are being sorted correctly.
172+
_ = coderdtest.UpdateTemplateVersion(t, client, user.OrganizationID, source2, template.ID)
173+
174+
dir := t.TempDir()
175+
176+
expectedDest := filepath.Join(dir, "expected")
177+
conflictDest := filepath.Join(dir, "conflict")
178+
179+
err = os.MkdirAll(conflictDest, 0o700)
180+
require.NoError(t, err)
181+
182+
err = os.WriteFile(
183+
filepath.Join(conflictDest, "conflict-file"),
184+
[]byte("conflict"), 0o600,
185+
)
186+
require.NoError(t, err)
187+
188+
ctx := context.Background()
189+
190+
err = extract.Tar(ctx, bytes.NewReader(expected), expectedDest, nil)
191+
require.NoError(t, err)
192+
193+
cmd, root := clitest.New(t, "templates", "pull", template.Name, conflictDest)
194+
clitest.SetupConfig(t, client, root)
195+
196+
pty := ptytest.New(t)
197+
cmd.SetIn(pty.Input())
198+
cmd.SetOut(pty.Output())
199+
200+
errChan := make(chan error)
201+
go func() {
202+
defer close(errChan)
203+
errChan <- cmd.Execute()
204+
}()
205+
206+
pty.ExpectMatch("not empty")
207+
pty.WriteLine("no")
208+
209+
require.Error(t, <-errChan)
210+
211+
ents, err := os.ReadDir(conflictDest)
124212
require.NoError(t, err)
125213

126-
require.True(t, bytes.Equal(actual, expected), "tar files differ")
214+
require.Len(t, ents, 1, "conflict folder should have single conflict file")
127215
})
128216
}
129217

cli/testdata/coder_speedtest_--help.golden

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@ Usage:
44
coder speedtest <workspace> [flags]
55

66
Flags:
7-
-d, --direct Specifies whether to wait for a direct connection before testing speed.
8-
-h, --help help for speedtest
9-
-r, --reverse Specifies whether to run in reverse mode where the client receives and
10-
the server sends.
11-
-t, --time duration Specifies the duration to monitor traffic. (default 5s)
7+
-d, --direct Specifies whether to wait for a direct connection before testing speed.
8+
--direction string Specifies whether to run in reverse mode where the client receives
9+
and the server sends. (up|down) (default "down")
10+
-h, --help help for speedtest
11+
-t, --time duration Specifies the duration to monitor traffic. (default 5s)
1212

1313
Global Flags:
1414
--global-config coder Path to the global coder config directory.

cli/testdata/coder_state_--help.golden

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ Usage:
66
coder state [command]
77

88
Commands:
9-
pull
10-
push
9+
pull Pull a Terraform state file from a workspace.
10+
push Push a Terraform state file to a workspace.
1111

1212
Flags:
1313
-h, --help help for state

0 commit comments

Comments
 (0)