Skip to content
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
46 changes: 37 additions & 9 deletions .dagger/sdk_elixir.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"regexp"
"strings"

"go.opentelemetry.io/otel/codes"
"golang.org/x/sync/errgroup"

"github.com/dagger/dagger/.dagger/internal/dagger"
Expand All @@ -31,16 +32,43 @@ type ElixirSDK struct {

// Lint the Elixir SDK
func (t ElixirSDK) Lint(ctx context.Context) error {
installer, err := t.Dagger.installer(ctx, "sdk-elixir-lint")
if err != nil {
return err
}
eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() (rerr error) {
ctx, span := Tracer().Start(ctx, "lint the elixir source")
defer func() {
if rerr != nil {
span.SetStatus(codes.Error, rerr.Error())
}
span.End()
}()

installer, err := t.Dagger.installer(ctx, "sdk-elixir-lint")
if err != nil {
return err
}

_, err = t.elixirBase(elixirVersions[elixirLatestVersion]).
With(installer).
WithExec([]string{"mix", "lint"}).
Sync(ctx)
return err
_, err = t.elixirBase(elixirVersions[elixirLatestVersion]).
With(installer).
WithExec([]string{"mix", "lint"}).
Sync(ctx)
return err
})
eg.Go(func() (rerr error) {
ctx, span := Tracer().Start(ctx, "check that the generated client library is up-to-date")
defer func() {
if rerr != nil {
span.SetStatus(codes.Error, rerr.Error())
}
span.End()
}()
before := t.Dagger.Source()
after, err := t.Generate(ctx)
if err != nil {
return err
}
return dag.Dirdiff().AssertEqual(ctx, before, after, []string{"sdk/elixir/lib/dagger/gen"})
})
return eg.Wait()
}

// Test the Elixir SDK
Expand Down
20 changes: 17 additions & 3 deletions .dagger/sdk_php.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"path/filepath"
"strings"

"go.opentelemetry.io/otel/codes"
"golang.org/x/sync/errgroup"

"github.com/dagger/dagger/.dagger/internal/dagger"
Expand All @@ -29,19 +30,32 @@ type PHPSDK struct {
func (t PHPSDK) Lint(ctx context.Context) error {
eg, ctx := errgroup.WithContext(ctx)

eg.Go(func() error {
eg.Go(func() (rerr error) {
ctx, span := Tracer().Start(ctx, "lint the php source")
defer func() {
if rerr != nil {
span.SetStatus(codes.Error, rerr.Error())
}
span.End()
}()
src := t.Dagger.Source().Directory(phpSDKPath)
_, err := dag.PhpSDKDev().Lint(src).Sync(ctx)
return err
})

eg.Go(func() error {
eg.Go(func() (rerr error) {
ctx, span := Tracer().Start(ctx, "check that the generated client library is up-to-date")
defer func() {
if rerr != nil {
span.SetStatus(codes.Error, rerr.Error())
}
span.End()
}()
before := t.Dagger.Source()
after, err := t.Generate(ctx)
if err != nil {
return err
}

return dag.Dirdiff().AssertEqual(ctx, before, after, []string{
filepath.Join(phpSDKPath, phpSDKGeneratedDir),
})
Expand Down
5 changes: 4 additions & 1 deletion cmd/codegen/generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,11 @@ type Config struct {
// ModuleContextPath is the subpath where a module can be found.
ModuleContextPath string

// IntrospectionJSON is an optional pre-computed introspection json string
// IntrospectionJSON is an optional pre-computed introspection json string.
IntrospectionJSON string

// Merge indicates whether to merge the module deps with the existing project.
Merge *bool
}

type Generator interface {
Expand Down
11 changes: 8 additions & 3 deletions cmd/codegen/generator/go/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ func (g *GoGenerator) bootstrapMod(ctx context.Context, mfs *memfs.FS) (*Package
var modPath string
var mod *modfile.File

modname := fmt.Sprintf("dagger/%s", strcase.ToKebab(g.Config.ModuleName))
// check for a go.mod already for the dagger module
if content, err := os.ReadFile(filepath.Join(g.Config.OutputDir, g.Config.ModuleContextPath, "go.mod")); err == nil {
modPath = g.Config.ModuleContextPath
Expand All @@ -172,13 +173,19 @@ func (g *GoGenerator) bootstrapMod(ctx context.Context, mfs *memfs.FS) (*Package
if err != nil {
return nil, false, fmt.Errorf("parse go.mod: %w", err)
}

if g.Config.Merge != nil && !*g.Config.Merge && mod.Module.Mod.Path != modname {
return nil, false, fmt.Errorf("existing go.mod does not match the module's path")
}
}

// if no go.mod is available, check the root output directory instead
// and if no merge is set
//
// this is a necessary part of bootstrapping: SDKs such as the Go SDK
// will want to have a runtime module that lives in the same Go module as
// the generated client, which typically lives in the parent directory.
if mod == nil {
if mod == nil && (g.Config.Merge == nil || *g.Config.Merge) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should this not be (g.Config.Merge && *g.Config.Merge)? If g.Config is nil, we should assume merge is false right?

@marcosnils marcosnils Aug 14, 2024 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

g.Config can't be nil since it's not a pointer.

Should this not be (g.Config.Merge && *g.Config.Merge)

this doesn't evaluate as g.Config.Merge is *bool

the reason behind this condition is to only perform the block below if mod ==nil AND merge is not set (which dagger init should always set), or it's set to true

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Sorry, I mean - g.Config.Merge == nil shouldn't be assumed to be true? If it's nil, shouldn't it be false? That keeps zero-ish values roughly equivalent.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

If it's nil, shouldn't it be false?

Not really since "not set" (g.Config.Merge == nil) doesn't have the same meaning as set to false. That's the main reason for making it a *bool and not passing the flag directly here https://github.com/dagger/dagger/pull/8095/files#diff-fc3b73c833f27945a9663b13ce2651daa11e86389d062a3468e2e038d14d2d6aR66-R68.

I'll add a comment in that line.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we handle this and remove the pointer at that point then? I don't understand why we need to have it be a trinary setting.

The conditions where we use it, g.Config.Merge != nil && !*g.Config.Merge and g.Config.Merge == nil || *g.Config.Merge, are just the inverse of each other (by De Morgan's).

if content, err := os.ReadFile(filepath.Join(g.Config.OutputDir, "go.mod")); err == nil {
modPath = "."
mod, err = modfile.ParseLax("go.mod", content, nil)
Expand All @@ -192,8 +199,6 @@ func (g *GoGenerator) bootstrapMod(ctx context.Context, mfs *memfs.FS) (*Package
modPath = g.Config.ModuleContextPath
mod = new(modfile.File)

modname := fmt.Sprintf("dagger/%s", strcase.ToKebab(g.Config.ModuleName))

mod.AddModuleStmt(modname)
mod.AddGoStmt(goVersion)

Expand Down
11 changes: 11 additions & 0 deletions cmd/codegen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ var (
moduleName string

outputSchema string
merge bool
)

var rootCmd = &cobra.Command{
Expand All @@ -47,6 +48,7 @@ func init() {

rootCmd.Flags().StringVar(&modulePath, "module-context-path", "", "path to context directory of the module")
rootCmd.Flags().StringVar(&moduleName, "module-name", "", "name of module to generate code for")
rootCmd.Flags().BoolVar(&merge, "merge", false, "merge module deps with project's")

introspectCmd.Flags().StringVarP(&outputSchema, "output", "o", "", "save introspection result to file")
rootCmd.AddCommand(introspectCmd)
Expand All @@ -59,10 +61,19 @@ func ClientGen(cmd *cobra.Command, args []string) error {
return err
}

// we're checking for the flag existence here as not setting the flag and
// setting it to false doesn't produce the same behavior.
var mergePtr *bool
if cmd.Flags().Changed("merge") {
mergePtr = &merge
}

cfg := generator.Config{
Lang: generator.SDKLang(lang),

OutputDir: outputDir,

Merge: mergePtr,
}

if moduleName != "" {
Expand Down
5 changes: 5 additions & 0 deletions cmd/dagger/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ var (
developSourcePath string

force bool

mergeDeps bool
)

const (
Expand All @@ -75,6 +77,8 @@ func init() {
moduleInitCmd.Flags().StringVar(&moduleName, "name", "", "Name of the new module (defaults to parent directory name)")
moduleInitCmd.Flags().StringVar(&moduleSourcePath, "source", "", "Source directory used by the installed SDK. Defaults to module root")
moduleInitCmd.Flags().StringVar(&licenseID, "license", defaultLicense, "License identifier to generate. See https://spdx.org/licenses/")
moduleInitCmd.Flags().BoolVar(&mergeDeps, "merge", false, "Merge module dependencies with existing project ones")
moduleInitCmd.Flags().MarkHidden("merge")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

marking this as hidden as a fallback in case users need to override this behavior. Not entirely sure if we should un-hide it. Thoughts?

@jedevc jedevc Aug 9, 2024 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hm, I'm actually not sure about this option at all. (It's also a bit weird to have a go sdk specific flag right here, if we do want to have it, we probably want to make it a bit more generic or hide it if --sdk=go isn't set).

I think we should probably default to always generating go.mod/go.sum. If the user doesn't want them, they can delete them after, right? As long as we have a test for that, and check it works as expected and gets merged into the root, I think that's fine.

That way, go is like all the other sdks, which manage their own dependencies.

I might be wrong, maybe we do need to keep this option - WDYT @sipsma?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The feedback about allowing backwards compatibility with a flag came from @shykes https://discord.com/channels/707636530424053791/1003718839739105300/1266140398112346203.

I'd have preferred to avoid it since it makes the implementation cleaner but on the other hand I understand the reason to add it also.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

if we do want to have it, we probably want to make it a bit more generic or hide it if --sdk=go isn't set).

The flag is hidden by default, so users won't know it's there. It's mostly a "safeguard" in case someone is trying to get the current "merge by default" behavior. IMO it's very unlikely to happen, but if it does, we can tell them to use this hidden flag.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Yeah okay, I guess a flag isn't too bad 🤷‍♀️ But, we should have a way of explicitly erroring in python/typescript/etc if --merge is set - maybe one day they could be set with merged dependencies, but I don't think that's the behavior today, and I don't think it's configurable (cc @helderco @TomChv).

(Ideally this check should be in the SDK! Not the CLI).

After merging, we should consider either:

  • Update Remove deprecated APIs in v0.13.0 #8065 to discuss removing the flag (if we wanna go that route)
  • Opening a follow-up issue to implement something similar in python/typescript if we wanna keep this flag around indefinitely

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

As long as the flag is hidden, we can wait for someone to ask for it, and if nobody does, we'll just remove it.


modulePublishCmd.Flags().BoolVarP(&force, "force", "f", false, "Force publish even if the git repository is not clean")
modFlag := *moduleFlags.Lookup("mod")
Expand Down Expand Up @@ -162,6 +166,7 @@ If --sdk is specified, the given SDK is installed in the module. You can do this
_, err = modConf.Source.
WithName(moduleName).
WithSDK(sdk).
WithInit(dagger.ModuleSourceWithInitOpts{Merge: mergeDeps}).
WithSourceSubpath(moduleSourcePath).
ResolveFromCaller().
AsModule(dagger.ModuleSourceAsModuleOpts{EngineVersion: modules.EngineVersionLatest}).
Expand Down
22 changes: 22 additions & 0 deletions core/integration/module_python_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,28 @@ version = "0.0.0"
require.NoError(t, err)
require.JSONEq(t, `{"helloWorld":{"message":"Hello, Monde!"}}`, out)
})

t.Run("fail if --merge is specified", func(ctx context.Context, t *testctx.T) {
c := connect(ctx, t)

_, err := daggerCliBase(t, c).
With(daggerInitPython("--name=hello-world", "--merge")).
With(pythonSource(`
from dagger import field, function, object_type

@object_type
class HelloWorld:
my_name: str = field(default="World")

@function
def message(self) -> str:
return f"Hello, {self.my_name}!"
`)).
With(daggerQuery(`{helloWorld(myName: "Monde"){message}}`)).
Stdout(ctx)

require.ErrorContains(t, err, "merge is only supported")
})
}

func (ModuleSuite) TestPythonProjectLayout(ctx context.Context, t *testctx.T) {
Expand Down
37 changes: 33 additions & 4 deletions core/integration/module_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ func (ModuleSuite) TestGoInit(ctx context.Context, t *testctx.T) {
WithMountedFile(testCLIBinPath, daggerCliFile(t, c)).
WithWorkdir("/work").
WithExec([]string{"go", "mod", "init", "example.com/test"}).
With(daggerExec("init", "--name=hasGoMod", "--sdk=go"))
With(daggerExec("init", "--name=hasGoMod", "--merge", "--sdk=go"))

out, err := modGen.
With(daggerQuery(`{hasGoMod{containerEcho(stringArg:"hello"){stdout}}}`)).
Expand Down Expand Up @@ -174,7 +174,7 @@ func (ModuleSuite) TestGoInit(ctx context.Context, t *testctx.T) {
WithExec([]string{"go", "mod", "init", "example.com/test"}).
WithExec([]string{"go", "work", "init"}).
WithExec([]string{"go", "work", "use", "."}).
With(daggerExec("init", "--name=hasGoMod", "--sdk=go"))
With(daggerExec("init", "--name=hasGoMod", "--sdk=go", "--merge"))

out, err := modGen.
With(daggerQuery(`{hasGoMod{containerEcho(stringArg:"hello"){stdout}}}`)).
Expand Down Expand Up @@ -247,7 +247,7 @@ func (ModuleSuite) TestGoInit(ctx context.Context, t *testctx.T) {
WithWorkdir("/work").
WithExec([]string{"go", "mod", "init", "example.com/test"}).
WithNewFile("/work/foo.go", "package foo\n").
With(daggerExec("init", "--name=child", "--sdk=go", "./child")).
With(daggerExec("init", "--name=child", "--merge", "--sdk=go", "./child")).
WithWorkdir("/work/child").
// explicitly develop to see whether it makes a go.mod
With(daggerExec("develop")).
Expand Down Expand Up @@ -280,7 +280,7 @@ func (ModuleSuite) TestGoInit(ctx context.Context, t *testctx.T) {
WithWorkdir("/work/child").
WithExec([]string{"go", "mod", "init", "my-mod"}).
WithWorkdir("/work").
With(daggerExec("init", "--source=./child", "--name=child", "--sdk=go", "./child")).
With(daggerExec("init", "--source=./child", "--merge", "--name=child", "--sdk=go", "./child")).
WithWorkdir("/work/child").
// explicitly develop to see whether it makes a go.mod
With(daggerExec("develop")).
Expand Down Expand Up @@ -424,6 +424,35 @@ func (m *HasNotMainGo) Hello() string { return "Hello, world!" }
require.NoError(t, err)
require.JSONEq(t, `{"bar":{"containerEcho":{"stdout":"hello\n"}}}`, out)
})

t.Run("fails if go.mod exists without merge flag", func(ctx context.Context, t *testctx.T) {
c := connect(ctx, t)

modGen := c.Container().From(golangImage).
WithMountedFile(testCLIBinPath, daggerCliFile(t, c)).
WithWorkdir("/work").
WithExec([]string{"go", "mod", "init", "example.com/test"}).
With(daggerExec("init", "--name=hasGoMod", "--sdk=go"))

_, err := modGen.
With(daggerQuery(`{hasGoMod{containerEcho(stringArg:"hello"){stdout}}}`)).
Stdout(ctx)
require.ErrorContains(t, err, "existing go.mod does not")
})

t.Run("do not merge go.mod with parent", func(ctx context.Context, t *testctx.T) {
c := connect(ctx, t)

modGen := c.Container().From(golangImage).
WithMountedFile(testCLIBinPath, daggerCliFile(t, c)).
WithWorkdir("/work").
WithExec([]string{"go", "mod", "init", "example.com/test"}).
With(daggerExec("init", "--name=bare", "--sdk=go", "--source=some/subdir"))

sourceSubdirEnts, err := modGen.Directory("/work/some/subdir").Entries(ctx)
require.NoError(t, err)
require.Contains(t, sourceSubdirEnts, "go.mod", "go.sum")
})
}

func (ModuleSuite) TestElixirInit(ctx context.Context, t *testctx.T) {
Expand Down
26 changes: 26 additions & 0 deletions core/integration/module_typescript_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,32 @@ func (ModuleSuite) TestTypescriptInit(ctx context.Context, t *testctx.T) {
require.NoError(t, err)
require.Contains(t, sourcePackageJSON, `"packageManager": "yarn@`) // We don't check the exact version because it's a SHA
})

t.Run("fail if --merge is specified", func(ctx context.Context, t *testctx.T) {
c := connect(ctx, t)

modGen := c.Container().From(golangImage).
WithMountedFile(testCLIBinPath, daggerCliFile(t, c)).
WithWorkdir("/work").
WithNewFile("/work/package.json", `{
"name": "my-module",
"version": "1.0.0",
"description": "My module",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "John doe",
"license": "MIT"
}`,
).
With(daggerExec("init", "--source=.", "--merge", "--name=hasPkgJson", "--sdk=typescript"))

_, err := modGen.
With(daggerQuery(`{hasPkgJson{containerEcho(stringArg:"hello"){stdout}}}`)).
Stdout(ctx)
require.ErrorContains(t, err, "merge is only supported")
})
}

//go:embed testdata/modules/typescript/syntax/index.ts
Expand Down
10 changes: 10 additions & 0 deletions core/modulesource.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ func (proto ModuleSourceKind) ToLiteral() call.Literal {
return ModuleSourceKindEnum.Literal(proto)
}

type ModuleInitConfig struct {
Merge bool
}

type ModuleSource struct {
Query *Query

Expand All @@ -59,6 +63,7 @@ type ModuleSource struct {
WithName string
WithDependencies []dagql.Instance[*ModuleDependency]
WithSDK string
WithInitConfig *ModuleInitConfig
WithSourceSubpath string
WithViews []*ModuleSourceView
}
Expand Down Expand Up @@ -99,6 +104,11 @@ func (src ModuleSource) Clone() *ModuleSource {
copy(cp.WithViews, src.WithViews)
}

if src.WithInitConfig != nil {
cp.WithInitConfig = new(ModuleInitConfig)
*cp.WithInitConfig = *src.WithInitConfig
}

return &cp
}

Expand Down
Loading