Skip to content
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
46 changes: 15 additions & 31 deletions cli/templatepull.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package cli

import (
"bytes"
"fmt"
"io/fs"
"os"
"sort"

"github.com/codeclysm/extract"
"github.com/spf13/cobra"
"golang.org/x/xerrors"

Expand All @@ -14,6 +16,7 @@ import (
)

func templatePull() *cobra.Command {
var tarMode bool
cmd := &cobra.Command{
Use: "pull <name> [destination]",
Short: "Download the latest version of a template to a path.",
Expand Down Expand Up @@ -75,48 +78,29 @@ func templatePull() *cobra.Command {
return xerrors.Errorf("unexpected Content-Type %q, expecting %q", ctype, codersdk.ContentTypeTar)
}

// If the destination is empty then we write to stdout
// and bail early.
if dest == "" {
if tarMode {
_, err = cmd.OutOrStdout().Write(raw)
if err != nil {
return xerrors.Errorf("write stdout: %w", err)
}
return nil
}

// Stat the destination to ensure nothing exists already.
fi, err := os.Stat(dest)
if err != nil && !xerrors.Is(err, fs.ErrNotExist) {
return xerrors.Errorf("stat destination: %w", err)
return err
}

if fi != nil && fi.IsDir() {
// If the destination is a directory we just bail.
return xerrors.Errorf("%q already exists.", dest)
if dest == "" {
dest = templateName + "/"
}

// If a file exists at the destination prompt the user
// to ensure we don't overwrite something valuable.
if fi != nil {
_, err = cliui.Prompt(cmd, cliui.PromptOptions{
Text: fmt.Sprintf("%q already exists, do you want to overwrite it?", dest),
IsConfirm: true,
})
if err != nil {
return xerrors.Errorf("parse prompt: %w", err)
}
}
_, _ = fmt.Fprintf(cmd.OutOrStderr(), "Extracting template to %q\n", dest)

err = os.WriteFile(dest, raw, 0o600)
if err != nil {
return xerrors.Errorf("write to path: %w", err)
// Stat the destination to ensure nothing exists already.
_, err = os.Stat(dest)
if err != nil && !xerrors.Is(err, fs.ErrNotExist) {
return xerrors.Errorf("stat destination: %w", err)
}

return nil
err = extract.Tar(ctx, bytes.NewReader(raw), dest, nil)
return err
},
}

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

return cmd
Expand Down
34 changes: 20 additions & 14 deletions cli/templatepull_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ package cli_test

import (
"bytes"
"os"
"context"
"io"
"path/filepath"
"testing"

"github.com/codeclysm/extract"
"github.com/google/uuid"
"github.com/ory/dockertest/v3/docker/pkg/archive"
"github.com/stretchr/testify/require"

"github.com/coder/coder/cli/clitest"
Expand Down Expand Up @@ -53,7 +56,7 @@ func TestTemplatePull(t *testing.T) {
// are being sorted correctly.
_ = coderdtest.UpdateTemplateVersion(t, client, user.OrganizationID, source2, template.ID)

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

var buf bytes.Buffer
Expand Down Expand Up @@ -93,15 +96,14 @@ func TestTemplatePull(t *testing.T) {

dir := t.TempDir()

dest := filepath.Join(dir, "actual.tar")
expectedDest := filepath.Join(dir, "expected")
actualDest := filepath.Join(dir, "actual")
ctx := context.Background()

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

cmd, root := clitest.New(t, "templates", "pull", template.Name, dest)
cmd, root := clitest.New(t, "templates", "pull", template.Name, actualDest)
clitest.SetupConfig(t, client, root)

pty := ptytest.New(t)
Expand All @@ -114,16 +116,20 @@ func TestTemplatePull(t *testing.T) {
errChan <- cmd.Execute()
}()

// We expect to be prompted that a file already exists.
pty.ExpectMatch("already exists")
pty.WriteLine("yes")

require.NoError(t, <-errChan)

actual, err := os.ReadFile(dest)
expectedTarRd, err := archive.Tar(expectedDest, archive.Uncompressed)
require.NoError(t, err)
expectedTar, err := io.ReadAll(expectedTarRd)
require.NoError(t, err)

actualTarRd, err := archive.Tar(actualDest, archive.Uncompressed)
require.NoError(t, err)

actualTar, err := io.ReadAll(actualTarRd)
require.NoError(t, err)

require.True(t, bytes.Equal(actual, expected), "tar files differ")
require.True(t, bytes.Equal(expectedTar, actualTar), "tar files differ")
})
}

Expand Down
6 changes: 6 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,12 @@ require (
tailscale.com v1.32.2
)

require (
github.com/codeclysm/extract v2.2.0+incompatible // indirect
github.com/h2non/filetype v1.1.3 // indirect
github.com/juju/errors v1.0.0 // indirect
)

require (
cloud.google.com/go/compute v1.12.1 // indirect
cloud.google.com/go/longrunning v0.3.0 // indirect
Expand Down
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,8 @@ github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:z
github.com/cockroachdb/datadriven v0.0.0-20200714090401-bf6692d28da5/go.mod h1:h6jFvWxBdQXxjopDMZyH2UVceIRfR84bdzbkoKrsWNo=
github.com/cockroachdb/errors v1.2.4/go.mod h1:rQD95gz6FARkaKkQXUksEje/d9a6wBJoCr5oaCLELYA=
github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f/go.mod h1:i/u985jwjWRlyHXQbwatDASoW0RMlZ/3i9yJHE2xLkI=
github.com/codeclysm/extract v2.2.0+incompatible h1:q3wyckoA30bhUSiwdQezMqVhwd8+WGE64/GL//LtUhI=
github.com/codeclysm/extract v2.2.0+incompatible/go.mod h1:2nhFMPHiU9At61hz+12bfrlpXSUrOnK+wR+KlGO4Uks=
github.com/coder/glog v1.0.1-0.20220322161911-7365fe7f2cd1 h1:UqBrPWSYvRI2s5RtOul20JukUEpu4ip9u7biBL+ntgk=
github.com/coder/glog v1.0.1-0.20220322161911-7365fe7f2cd1/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4=
github.com/coder/retry v1.3.1-0.20230210155434-e90a2e1e091d h1:09JG37IgTB6n3ouX9BXdUiibGzkGGbslFuDZO9Ru9aw=
Expand Down Expand Up @@ -984,6 +986,8 @@ github.com/grpc-ecosystem/grpc-gateway v1.12.1/go.mod h1:8XEsbTttt/W+VvjtQhLACqC
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0 h1:BZHcxBETFHIdVyhyEfOvn/RdU/QGdLI4y34qQGjGWO0=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0/go.mod h1:hgWBS7lorOAVIJEQMi4ZsPv9hVvWI6+ch50m39Pf2Ks=
github.com/h2non/filetype v1.1.3 h1:FKkx9QbD7HR/zjK1Ia5XiBsq9zdLi5Kf3zGyFTAFkGg=
github.com/h2non/filetype v1.1.3/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY=
github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed/go.mod h1:tMWxXQ9wFIaZeTI9F+hmhFiGpFmhOHzyShyFUhRm0H4=
github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q=
github.com/hashicorp/consul/api v1.10.1/go.mod h1:XjsvQN+RJGWI2TWy1/kqaE16HrR2J/FWgkYjdZQsX9M=
Expand Down Expand Up @@ -1188,6 +1192,8 @@ github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHm
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/juju/errors v1.0.0 h1:yiq7kjCLll1BiaRuNY53MGI0+EQ3rF6GB+wvboZDefM=
github.com/juju/errors v1.0.0/go.mod h1:B5x9thDqx0wIMH3+aLIMP9HjItInYWObRovoCFM5Qe8=
github.com/juju/ratelimit v1.0.1/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
Expand Down
1 change: 1 addition & 0 deletions provisioner/echo/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ func Tar(responses *Responses) ([]byte, error) {
err = writer.WriteHeader(&tar.Header{
Name: fmt.Sprintf("%d.parse.protobuf", index),
Size: int64(len(data)),
Mode: 0o777,
})
if err != nil {
return nil, err
Expand Down