feat(cli): extract tar in template pull (#6289)

This commit is contained in:
Ammar Bandukwala
2023-02-22 13:29:51 -06:00
committed by GitHub
parent 8231de94ca
commit f7c10adb04
7 changed files with 127 additions and 41 deletions

View File

@ -1,11 +1,12 @@
package cli
import (
"bytes"
"fmt"
"io/fs"
"os"
"sort"
"github.com/codeclysm/extract"
"github.com/spf13/cobra"
"golang.org/x/xerrors"
@ -14,6 +15,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.",
@ -75,48 +77,44 @@ 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
return err
}
// 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)
if dest == "" {
dest = templateName + "/"
}
if fi != nil && fi.IsDir() {
// If the destination is a directory we just bail.
return xerrors.Errorf("%q already exists.", dest)
err = os.MkdirAll(dest, 0o750)
if err != nil {
return xerrors.Errorf("mkdirall %q: %w", dest, err)
}
// If a file exists at the destination prompt the user
// to ensure we don't overwrite something valuable.
if fi != nil {
ents, err := os.ReadDir(dest)
if err != nil {
return xerrors.Errorf("read dir %q: %w", dest, err)
}
if len(ents) > 0 {
_, err = cliui.Prompt(cmd, cliui.PromptOptions{
Text: fmt.Sprintf("%q already exists, do you want to overwrite it?", dest),
Text: fmt.Sprintf("Directory %q is not empty, existing files may be overwritten.\nContinue extracting?", dest),
Default: "No",
Secret: false,
IsConfirm: true,
})
if err != nil {
return xerrors.Errorf("parse prompt: %w", err)
return err
}
}
err = os.WriteFile(dest, raw, 0o600)
if err != nil {
return xerrors.Errorf("write to path: %w", err)
}
return nil
_, _ = fmt.Fprintf(cmd.OutOrStderr(), "Extracting template to %q\n", dest)
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