Skip to content

Commit

Permalink
feat(lk): use tmp directory while preparing files
Browse files Browse the repository at this point in the history
  • Loading branch information
rektdeckard committed Oct 9, 2024
1 parent 9db8c14 commit 06923f7
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
16 changes: 12 additions & 4 deletions cmd/lk/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,21 +268,29 @@ func setupTemplate(ctx context.Context, cmd *cli.Command) error {

func cloneTemplate(_ context.Context, cmd *cli.Command, url, appName string) error {
var cmdErr error

tempName, relocate := useTempPath(appName)

if err := spinner.New().
Title("Cloning template from " + url).
Action(func() {
c := exec.Command("git", "clone", "--depth=1", url, appName)
c := exec.Command("git", "clone", "--depth=1", url, tempName)
var out []byte
if out, cmdErr = c.CombinedOutput(); len(out) > 0 && cmd.Bool("verbose") {
fmt.Println(string(out))
if out, cmdErr = c.CombinedOutput(); len(out) > 0 {
if cmdErr != nil || cmd.Bool("verbose") {
fmt.Println(string(out))
}
}
os.RemoveAll(path.Join(appName, ".git"))
}).
Style(theme.Focused.Title).
Run(); err != nil {
return err
}
return cmdErr
if cmdErr != nil {
return cmdErr
}
return relocate()
}

func instantiateEnv(ctx context.Context, cmd *cli.Command, rootPath string, addlEnv *map[string]string) error {
Expand Down
29 changes: 29 additions & 0 deletions cmd/lk/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,13 @@ import (
"encoding/json"
"errors"
"fmt"
"math/rand"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"time"

"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/lipgloss/table"
Expand Down Expand Up @@ -153,6 +156,32 @@ func wrapWith(wrap string) func(string) string {
}
}

func randomID() string {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
seed := rand.NewSource(time.Now().UnixNano())
r := rand.New(seed)

result := make([]byte, 16)
for i := range result {
result[i] = charset[r.Intn(len(charset))]
}
return string(result)
}

func useTempPath(permanentPath string) (string, func() error) {
tempPath := path.Join(os.TempDir(), randomID())
relocate := func() error {
if err := os.Rename(tempPath, permanentPath); err != nil {
// NOTE: on macOS, `os.TempDir()` points to `/var/folders/...`.
// Because this directory is not automatically cleaned up, we need
// to remove it explicitly on a failure to relocate.
return os.RemoveAll(tempPath)
}
return nil
}
return tempPath, relocate
}

func hashString(str string) (string, error) {
hash := sha256.New()
if _, err := hash.Write([]byte(str)); err != nil {
Expand Down

0 comments on commit 06923f7

Please sign in to comment.