Skip to content

Commit

Permalink
fix: catch bun install error when package is in dependencies and dev …
Browse files Browse the repository at this point in the history
…dependencies
  • Loading branch information
shyim committed Dec 19, 2023
1 parent 65092ed commit 7f08f7e
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 1 deletion.
2 changes: 1 addition & 1 deletion extension/asset_platform.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ func getInstallCommand(path string) *exec.Cmd {
}

// Bun can migrate on the fly the package-lock.json to a bun.lockdb and is much faster than NPM
if _, err := exec.LookPath("bun"); err == nil {
if _, err := exec.LookPath("bun"); err == nil && canRunBunOnPackage(path) {
return exec.Command("bun", "install", "--no-save")
}

Expand Down
35 changes: 35 additions & 0 deletions extension/bun_helper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package extension

import (
"encoding/json"
"os"
"path"
)

type npmPackage struct {
Dependencies map[string]string `json:"dependencies"`
DevDependencies map[string]string `json:"devDependencies"`
}

// When a package is defined in both dependencies and devDependencies, bun will crash
func canRunBunOnPackage(packagePath string) bool {
packageJson, err := os.ReadFile(path.Join(packagePath, "package.json"))

if err != nil {
return false
}

var npmPackage npmPackage

if json.Unmarshal(packageJson, &npmPackage) != nil {
return false
}

for name, _ := range npmPackage.Dependencies {
if _, ok := npmPackage.DevDependencies[name]; ok {
return false
}
}

return true
}
62 changes: 62 additions & 0 deletions extension/bun_helper_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package extension

import (
"github.com/stretchr/testify/assert"
"os"
"path"
"testing"
)

func TestValidPackageJsonBun(t *testing.T) {
tmpDir := t.TempDir()

packageJson := `{
"dependencies": {
"foo": "1.0.0"
}
}`

if err := os.WriteFile(path.Join(tmpDir, "package.json"), []byte(packageJson), 0644); err != nil {
t.Fatal(err)
}

assert.True(t, canRunBunOnPackage(tmpDir))
}

func TestValidPackageJsonWithDevBun(t *testing.T) {
tmpDir := t.TempDir()

packageJson := `{
"dependencies": {
"foo": "1.0.0"
},
"devDependencies": {
"bar": "1.0.0"
}
}`

if err := os.WriteFile(path.Join(tmpDir, "package.json"), []byte(packageJson), 0644); err != nil {
t.Fatal(err)
}

assert.True(t, canRunBunOnPackage(tmpDir))
}

func TestInvalidPackageJsonBun(t *testing.T) {
tmpDir := t.TempDir()

packageJson := `{
"dependencies": {
"foo": "1.0.0"
},
"devDependencies": {
"foo": "1.0.0"
}
}`

if err := os.WriteFile(path.Join(tmpDir, "package.json"), []byte(packageJson), 0644); err != nil {
t.Fatal(err)
}

assert.False(t, canRunBunOnPackage(tmpDir))
}

0 comments on commit 7f08f7e

Please sign in to comment.