Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[zeroconfig] Default nodejs to corepack enabled #2396

Merged
merged 2 commits into from
Nov 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
29 changes: 29 additions & 0 deletions internal/devconfig/configfile/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,3 +425,32 @@ func (c *configAST) beforeComment(path ...any) []byte {
}),
)
}

func (c *configAST) createMemberIfMissing(key string) *hujson.ObjectMember {
i := c.memberIndex(c.root.Value.(*hujson.Object), key)
if i == -1 {
c.root.Value.(*hujson.Object).Members = append(c.root.Value.(*hujson.Object).Members, hujson.ObjectMember{
Name: hujson.Value{Value: hujson.String(key)},
})
i = len(c.root.Value.(*hujson.Object).Members) - 1
}
return &c.root.Value.(*hujson.Object).Members[i]
}

func mapToObjectMembers(env map[string]string) []hujson.ObjectMember {
members := make([]hujson.ObjectMember, 0, len(env))
for k, v := range env {
members = append(members, hujson.ObjectMember{
Name: hujson.Value{Value: hujson.String(k)},
Value: hujson.Value{Value: hujson.String(v)},
})
}
return members
}

func (c *configAST) setEnv(env map[string]string) {
c.createMemberIfMissing("env").Value.Value = &hujson.Object{
Members: mapToObjectMembers(env),
}
c.root.Format()
Copy link
Collaborator

@LucilleH LucilleH Oct 31, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The above logic seems so convoluted - what's hujson.ObjectMember?

Is there a simpler representation? Something like

env := [key, val, key, val]
members := make(map[string]string)

for i := 0; i < len(env); i += 2 {
    members[env[i]] = env[i+1]
}

I'm not sure about this part of the logic as I don't understand it. Maybe @gcurtis knows better.

Approving for the rest of the NodeJS logic 👍

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if we can get rid of any of the code because hujson api is pretty generic so everything needs to be explicit. Maybe I can refactor some portions out:

func (c *configAST) createMemberIfMissing(key string) *hujson.ObjectMember {
	i := c.memberIndex(c.root.Value.(*hujson.Object), key)
	if i == -1 {
		c.root.Value.(*hujson.Object).Members = append(c.root.Value.(*hujson.Object).Members, hujson.ObjectMember{
			Name: hujson.Value{Value: hujson.String(key)},
		})
		i = len(c.root.Value.(*hujson.Object).Members) - 1
	}
	return &c.root.Value.(*hujson.Object).Members[i]
}

func mapToObjectMembers(env map[string]string) []hujson.ObjectMember {
	members := make([]hujson.ObjectMember, 0, len(env))
	for k, v := range env {
		members = append(members, hujson.ObjectMember{
			Name:  hujson.Value{Value: hujson.String(k)},
			Value: hujson.Value{Value: hujson.String(v)},
		})
	}
	return members
}

func (c *configAST) setEnv(env map[string]string) {
	c.createMemberIfMissing("env").Value.Value = &hujson.Object{
		Members: mapToObjectMembers(env),
	}
	c.root.Format()
}

}
69 changes: 69 additions & 0 deletions internal/devconfig/configfile/ast_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package configfile

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/tailscale/hujson"
)

func TestSetEnv(t *testing.T) {
tests := []struct {
name string
initial string
env map[string]string
expected string
}{
{
name: "add env to empty config",
initial: "{}",
env: map[string]string{
"FOO": "bar",
"BAZ": "qux",
},
expected: `{"env": {"FOO": "bar", "BAZ": "qux"}}
`,
},
{
name: "update existing env",
initial: `{
"env": {
"EXISTING": "value"
}
}`,
env: map[string]string{
"FOO": "bar",
},
expected: `{
"env": {"FOO": "bar"}
}
`,
},
{
name: "clear env with empty map",
initial: `{
"env": {
"EXISTING": "value"
}
}`,
env: map[string]string{},
expected: `{
"env": {}
}
`,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
val, err := hujson.Parse([]byte(tt.initial))
assert.NoError(t, err)

ast := &configAST{root: val}
ast.setEnv(tt.env)

actual := string(ast.root.Pack())
assert.Equal(t, tt.expected, actual)
})
}
}
5 changes: 5 additions & 0 deletions internal/devconfig/configfile/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,8 @@ func (c *ConfigFile) ParseEnvsFromDotEnv() (map[string]string, error) {

return envMap, nil
}

func (c *ConfigFile) SetEnv(env map[string]string) {
c.Env = env
c.ast.setEnv(env)
}
13 changes: 13 additions & 0 deletions pkg/autodetect/autodetect.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ func populateConfig(ctx context.Context, path string, config *devconfig.Config)
for _, pkg := range pkgs {
config.PackageMutator().Add(pkg)
}
env, err := env(ctx, path)
if err != nil {
return err
}
config.Root.SetEnv(env)
return nil
}

Expand All @@ -57,6 +62,14 @@ func packages(ctx context.Context, path string) ([]string, error) {
return mostRelevantDetector.Packages(ctx)
}

func env(ctx context.Context, path string) (map[string]string, error) {
mostRelevantDetector, err := relevantDetector(path)
if err != nil || mostRelevantDetector == nil {
return nil, err
}
return mostRelevantDetector.Env(ctx)
}

// relevantDetector returns the most relevant detector for the given path.
// We could modify this to return a list of detectors and their scores or
// possibly grouped detectors by category (e.g. python, server, etc.)
Expand Down
1 change: 1 addition & 0 deletions pkg/autodetect/detector/detector.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ import "context"
type Detector interface {
Relevance(path string) (float64, error)
Packages(ctx context.Context) ([]string, error)
Env(ctx context.Context) (map[string]string, error)
}
4 changes: 4 additions & 0 deletions pkg/autodetect/detector/go.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ func (d *GoDetector) Packages(ctx context.Context) ([]string, error) {
return []string{"go@" + goVersion}, nil
}

func (d *GoDetector) Env(ctx context.Context) (map[string]string, error) {
return map[string]string{}, nil
}

func parseGoVersion(goModContent string) string {
// Use a regular expression to find the Go version directive
re := regexp.MustCompile(`(?m)^go\s+(\d+\.\d+(\.\d+)?)`)
Expand Down
4 changes: 4 additions & 0 deletions pkg/autodetect/detector/nodejs.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ func (d *NodeJSDetector) Packages(ctx context.Context) ([]string, error) {
return []string{"nodejs@" + d.nodeVersion(ctx)}, nil
}

func (d *NodeJSDetector) Env(ctx context.Context) (map[string]string, error) {
return map[string]string{"DEVBOX_COREPACK_ENABLED": "1"}, nil
}

func (d *NodeJSDetector) nodeVersion(ctx context.Context) string {
if d.packageJSON == nil || d.packageJSON.Engines.Node == "" {
return "latest" // Default to latest if not specified
Expand Down
24 changes: 20 additions & 4 deletions pkg/autodetect/detector/nodejs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ func TestNodeJSDetector_Relevance(t *testing.T) {
fs fstest.MapFS
expected float64
expectedPackages []string
expectedEnv map[string]string
}{
{
name: "package.json in root",
Expand All @@ -27,6 +28,7 @@ func TestNodeJSDetector_Relevance(t *testing.T) {
},
expected: 1,
expectedPackages: []string{"nodejs@latest"},
expectedEnv: map[string]string{"DEVBOX_COREPACK_ENABLED": "1"},
},
{
name: "package.json with node version",
Expand All @@ -41,6 +43,7 @@ func TestNodeJSDetector_Relevance(t *testing.T) {
},
expected: 1,
expectedPackages: []string{"nodejs@18.0.0"},
expectedEnv: map[string]string{"DEVBOX_COREPACK_ENABLED": "1"},
},
{
name: "no nodejs files",
Expand All @@ -54,12 +57,14 @@ func TestNodeJSDetector_Relevance(t *testing.T) {
},
expected: 0,
expectedPackages: []string{},
expectedEnv: map[string]string{},
},
{
name: "empty directory",
fs: fstest.MapFS{},
expected: 0,
expectedPackages: []string{},
expectedEnv: map[string]string{},
},
}

Expand All @@ -74,17 +79,21 @@ func TestNodeJSDetector_Relevance(t *testing.T) {
require.NoError(t, err)
}

d := &NodeJSDetector{Root: dir}
err := d.Init()
detector := &NodeJSDetector{Root: dir}
err := detector.Init()
require.NoError(t, err)

score, err := d.Relevance(dir)
score, err := detector.Relevance(dir)
require.NoError(t, err)
assert.Equal(t, curTest.expected, score)
if score > 0 {
packages, err := d.Packages(context.Background())
packages, err := detector.Packages(context.Background())
require.NoError(t, err)
assert.Equal(t, curTest.expectedPackages, packages)

env, err := detector.Env(context.Background())
require.NoError(t, err)
assert.Equal(t, curTest.expectedEnv, env)
}
})
}
Expand All @@ -96,3 +105,10 @@ func TestNodeJSDetector_Packages(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, []string{"nodejs@latest"}, packages)
}

func TestNodeJSDetector_Env(t *testing.T) {
d := &NodeJSDetector{}
env, err := d.Env(context.Background())
require.NoError(t, err)
assert.Equal(t, map[string]string{"DEVBOX_COREPACK_ENABLED": "1"}, env)
}
4 changes: 4 additions & 0 deletions pkg/autodetect/detector/php.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ func (d *PHPDetector) Packages(ctx context.Context) ([]string, error) {
return packages, nil
}

func (d *PHPDetector) Env(ctx context.Context) (map[string]string, error) {
return map[string]string{}, nil
}

func (d *PHPDetector) phpVersion(ctx context.Context) string {
require := d.composerJSON.Require

Expand Down
4 changes: 4 additions & 0 deletions pkg/autodetect/detector/poetry.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ func (d *PoetryDetector) Packages(ctx context.Context) ([]string, error) {
return []string{"python@" + pythonVersion, "poetry@" + poetryVersion}, nil
}

func (d *PoetryDetector) Env(ctx context.Context) (map[string]string, error) {
return d.PythonDetector.Env(ctx)
}

func determineBestVersion(ctx context.Context, pkg, version string) string {
if version == "" {
return "latest"
Expand Down
4 changes: 4 additions & 0 deletions pkg/autodetect/detector/python.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ func (d *PythonDetector) Packages(ctx context.Context) ([]string, error) {
return []string{"python@latest"}, nil
}

func (d *PythonDetector) Env(ctx context.Context) (map[string]string, error) {
return map[string]string{}, nil
}

func (d *PythonDetector) maxRelevance() float64 {
return 1.0
}
Loading