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
6 changes: 6 additions & 0 deletions .changes/unreleased/Added-20240612-145159.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
kind: Added
body: allow other CIs than GitHub
time: 2024-06-12T14:51:59.394243036Z
custom:
Author: grouville
PR: "7511"
44 changes: 44 additions & 0 deletions core/integration/ref_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package core

import (
"strings"
"testing"

"dagger.io/dagger"
"github.com/stretchr/testify/require"
)

func TestRefIntegration(t *testing.T) {

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.

We should also have some more complete integration tests - see

const (
gitTestRepoURL = "github.com/dagger/dagger-test-modules"
gitTestRepoCommit = "2cb6cb4b0dba52c1e65b3ff46dd1a4a8f9a02f94"
)
func testGitModuleRef(subpath string) string {
url := gitTestRepoURL
if subpath != "" {
if !strings.HasPrefix(subpath, "/") {
subpath = "/" + subpath
}
url += subpath
}
return fmt.Sprintf("%s@%s", url, gitTestRepoCommit)
}
func TestModuleDaggerGitRefs(t *testing.T) {

We can mirror https://github.com/dagger/dagger-test-modules to some places in gitlab, and parameterize the tests to run against that repo hosted in different places (like a subgroup in gitlab). That way, we're testing against these other VCSs in the same way that we're testing against github, so they're both first-class citizens.

@grouville grouville Jun 10, 2024 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I discussed it with @marcosnils and I am not sure that integration tests are necessary here. Most of the logic here is to basically split the ref into root of repo and subdir. With the tests on vcs.repoRootForImportPath and the new vcs.ExtractRootAndSubdirFromRef: https://github.com/dagger/dagger/pull/7511/files#diff-8432d1812b1f1b774598e92639e78ab8a25fcb6804617f7587d692149d155e21, we cover a lot

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.

Will re-review in a bit - but. I don't necessarily think we need to test this for an initial merge, but we absolutely need some sanity integration tests at some point soon.

Previously, changes to some logic in git resolution/etc changes this in incredibly subtle and unexpected ways. If we aren't testing this, this becomes much more likely. This has happened before, multiple times - the module source logic gets touched a lot, and from experience it seems to be very fragile.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok, this makes sense 👌. I was planning on adding integration tests for the private git support, it seems a great complementary add at this time, wdyt?

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.

SGTM 🚀

t.Parallel()
c, ctx := connect(t)

// This test handles a very edgy case:
// goGitBase inits a /work directory with a git context
// we then create a local dir with the same structure as a git remote: `/work/github.com/dagger/dagger`
// It should be resolved as a local ref, not a remote one
t.Run("local module with same format as remote: github.com/dagger/dagger", func(t *testing.T) {
t.Parallel()
out, err := goGitBase(t, c).
WithMountedFile(testCLIBinPath, daggerCliFile(t, c)).
WithWorkdir("/work/github.com/dagger/dagger").
WithExec([]string{"pwd"}).
With(daggerExec("init", "--source=.", "--name=dep", "--sdk=go")).
WithNewFile("/work/github.com/dagger/dagger/main.go", dagger.ContainerWithNewFileOpts{
Contents: `package main

import "context"

type Dep struct {}

func (m *Dep) GetSource(ctx context.Context) string {
return "hello"
}
`,
}).
WithWorkdir("/work").
With(daggerCallAt("github.com/dagger/dagger", "get-source")).
Stdout(ctx)
require.NoError(t, err)
require.Equal(t, "hello", strings.TrimSpace(out))
})
}
2 changes: 1 addition & 1 deletion core/modfunc.go
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ func moduleAnalyticsProps(mod *Module, prefix string, props map[string]string) {
git := source.AsGitSource.Value
props[prefix+"source_kind"] = "git"
props[prefix+"git_symbolic"] = git.Symbolic()
props[prefix+"git_clone_url"] = git.CloneURL()
props[prefix+"git_clone_url"] = git.CloneURL
props[prefix+"git_subpath"] = git.RootSubpath
props[prefix+"git_version"] = git.Version
props[prefix+"git_commit"] = git.Commit
Expand Down
20 changes: 8 additions & 12 deletions core/modulesource.go
Original file line number Diff line number Diff line change
Expand Up @@ -397,13 +397,13 @@ func (src *LocalModuleSource) Symbolic() string {
}

type GitModuleSource struct {
Version string `field:"true" doc:"The specified version of the git repo this source points to."`
Root string `field:"true" doc:"The clean module name of the root of the module"`
RootSubpath string `field:"true" doc:"The path to the root of the module source under the context directory. This directory contains its configuration file. It also contains its source code (possibly as a subdirectory)."`

Commit string `field:"true" doc:"The resolved commit of the git repo this source points to."`
Version string `field:"true" doc:"The specified version of the git repo this source points to."`
Commit string `field:"true" doc:"The resolved commit of the git repo this source points to."`

URLParent string

RootSubpath string `field:"true" doc:"The path to the root of the module source under the context directory. This directory contains its configuration file. It also contains its source code (possibly as a subdirectory)."`
CloneURL string `field:"true" name:"cloneURL" doc:"The URL to clone the root of the git repo from"`

ContextDirectory dagql.Instance[*Directory] `field:"true" doc:"The directory containing everything needed to load load and use the module."`
}
Expand Down Expand Up @@ -432,7 +432,7 @@ func (src *GitModuleSource) PBDefinitions(ctx context.Context) ([]*pb.Definition
}

func (src *GitModuleSource) RefString() string {
refPath := src.URLParent
refPath := src.Root
subPath := filepath.Join("/", src.RootSubpath)
if subPath != "/" {
refPath += subPath
Expand All @@ -442,16 +442,12 @@ func (src *GitModuleSource) RefString() string {

func (src *GitModuleSource) Symbolic() string {
// ignore error since ref is validated upon module initialization
p, _ := url.JoinPath(src.CloneURL(), src.RootSubpath)
p, _ := url.JoinPath(src.CloneURL, src.RootSubpath)
return p
}

func (src *GitModuleSource) CloneURL() string {
return "https://" + src.URLParent
}

func (src *GitModuleSource) HTMLURL() string {
u := "https://" + src.URLParent + "/tree/" + src.Commit
u := "https://" + src.Root + "/tree/" + src.Commit
if subPath := src.RootSubpath; subPath != "" {
u += "/" + subPath
}
Expand Down
3 changes: 0 additions & 3 deletions core/schema/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,6 @@ func (s *moduleSchema) Install() {
dagql.Fields[*core.LocalModuleSource]{}.Install(s.dag)

dagql.Fields[*core.GitModuleSource]{
dagql.Func("cloneURL", s.gitModuleSourceCloneURL).
Doc(`The URL from which the source's git repo can be cloned.`),

dagql.Func("htmlURL", s.gitModuleSourceHTMLURL).
Doc(`The URL to the source's git repo in a web browser`),
}.Install(s.dag)
Expand Down
112 changes: 63 additions & 49 deletions core/schema/modulesource.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import (
"github.com/dagger/dagger/core/modules"
"github.com/dagger/dagger/dagql"
"github.com/dagger/dagger/engine/buildkit"
"github.com/dagger/dagger/engine/vcs"
"github.com/tonistiigi/fsutil/types"
)

type moduleSourceArgs struct {
Expand All @@ -27,10 +29,8 @@ type moduleSourceArgs struct {
}

func (s *moduleSchema) moduleSource(ctx context.Context, query *core.Query, args moduleSourceArgs) (*core.ModuleSource, error) {
parsed := parseRefString(args.RefString)
modPath, modVersion, hasVersion, isGitHub := parsed.modPath, parsed.modVersion, parsed.hasVersion, parsed.isGitHub

if !hasVersion && isGitHub && args.Stable {
parsed := parseRefString(ctx, query.Buildkit, args.RefString)
if args.Stable && !parsed.hasVersion && parsed.kind == core.ModuleSourceKindGit {
return nil, fmt.Errorf("no version provided for stable remote ref: %s", args.RefString)
}

Expand All @@ -41,51 +41,43 @@ func (s *moduleSchema) moduleSource(ctx context.Context, query *core.Query, args

switch src.Kind {
case core.ModuleSourceKindLocal:
if filepath.IsAbs(modPath) {
return nil, fmt.Errorf("local module source root path is absolute: %s", modPath)
if filepath.IsAbs(parsed.modPath) {
return nil, fmt.Errorf("local module source root path is absolute: %s", parsed.modPath)
}

src.AsLocalSource = dagql.NonNull(&core.LocalModuleSource{
RootSubpath: modPath,
RootSubpath: parsed.modPath,
})

case core.ModuleSourceKindGit:
if !isGitHub {
return nil, fmt.Errorf("for now, only github.com/ paths are supported: %q", args.RefString)
}

src.AsGitSource = dagql.NonNull(&core.GitModuleSource{})

segments := strings.SplitN(modPath, "/", 4)
if len(segments) < 3 {
return nil, fmt.Errorf("invalid github.com path: %s", modPath)
}

src.AsGitSource.Value.URLParent = segments[0] + "/" + segments[1] + "/" + segments[2]
src.AsGitSource.Value.Root = parsed.repoRoot.Root
src.AsGitSource.Value.CloneURL = parsed.repoRoot.Repo

cloneURL := src.AsGitSource.Value.CloneURL()

if !hasVersion {
var modVersion string
if parsed.hasVersion {
modVersion = parsed.modVersion
} else {
if args.Stable {
return nil, fmt.Errorf("no version provided for stable remote ref: %s", args.RefString)
}
var err error
modVersion, err = defaultBranch(ctx, cloneURL)
modVersion, err = defaultBranch(ctx, parsed.repoRoot.Repo)
if err != nil {
return nil, fmt.Errorf("determine default branch: %w", err)
}
}
src.AsGitSource.Value.Version = modVersion

var subPath string
if len(segments) == 4 {
subPath = segments[3]
} else {
subPath = "/"
subPath := "/"
if parsed.repoRootSubdir != "" {
subPath = parsed.repoRootSubdir
}

commitRef := modVersion
if hasVersion && isSemver(modVersion) {
allTags, err := gitTags(ctx, cloneURL)
if parsed.hasVersion && isSemver(modVersion) {
allTags, err := gitTags(ctx, parsed.repoRoot.Repo)
if err != nil {
return nil, fmt.Errorf("get git tags: %w", err)
}
Expand All @@ -102,7 +94,7 @@ func (s *moduleSchema) moduleSource(ctx context.Context, query *core.Query, args
dagql.Selector{
Field: "git",
Args: []dagql.NamedInput{
{Name: "url", Value: dagql.String(cloneURL)},
{Name: "url", Value: dagql.String(parsed.repoRoot.Repo)},
},
},
dagql.Selector{
Expand Down Expand Up @@ -146,23 +138,49 @@ func (s *moduleSchema) moduleSource(ctx context.Context, query *core.Query, args
}

type parsedRefString struct {
modPath string
modVersion string
hasVersion bool
isGitHub bool
kind core.ModuleSourceKind
modPath string
modVersion string
hasVersion bool
kind core.ModuleSourceKind
repoRoot *vcs.RepoRoot
repoRootSubdir string
}

// interface used for host interaction mocking
type buildkitClient interface {
StatCallerHostPath(ctx context.Context, path string, followLinks bool) (*types.Stat, error)
}

func parseRefString(refString string) parsedRefString {
// parseRefString parses a ref string into its components
// New heuristic:
// - stat folder to see if dir is present
// - if not, try to isolate root of git repo from the ref
// - if nothing worked, fallback as local ref, as before
func parseRefString(ctx context.Context, bk buildkitClient, refString string) parsedRefString {
var parsed parsedRefString
parsed.modPath, parsed.modVersion, parsed.hasVersion = strings.Cut(refString, "@")
parsed.isGitHub = strings.HasPrefix(parsed.modPath, "github.com/")

if !parsed.hasVersion && !parsed.isGitHub {
parsed.kind = core.ModuleSourceKindLocal
// We do a stat in case the mod path github.com/username is a local directory
stat, err := bk.StatCallerHostPath(ctx, parsed.modPath, false)

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.

we're not checking for this err != nil anywhere?

@grouville grouville Jun 6, 2024 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

We are, it is being returned in https://github.com/dagger/dagger/blob/a257857d89659ee6f1fd86c6252021d4361f19ab/core/schema/modulesource.go#L52, in the edge case where we fallback to a local source kind.

This is currently not being exploited to its fullest potential I agree, but it is being checked here: https://github.com/dagger/dagger/blob/a257857d89659ee6f1fd86c6252021d4361f19ab/core/schema/modulesource.go#L52-L57, currently only as a log to specify the user that a fallback just happened. It could be refined a bit more afterwards to not log every case ?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I changed the logic to log directly inside parseRefString, to be able to debug when wrongful fallback happen

if err == nil {
if !parsed.hasVersion && stat.IsDir() {
parsed.kind = core.ModuleSourceKindLocal
return parsed
}
}

// we try to isolate the root of the git repo
repoRoot, err := vcs.RepoRootForImportPath(parsed.modPath, false)
if err == nil && repoRoot != nil && repoRoot.VCS != nil && repoRoot.VCS.Name == "Git" {
parsed.kind = core.ModuleSourceKindGit
parsed.repoRoot = repoRoot
parsed.repoRootSubdir = strings.TrimPrefix(parsed.modPath, repoRoot.Root)
// the extra "/" is important as subpath traversal such as /../ are being cleaned by filePath.Clean
parsed.repoRootSubdir = strings.TrimPrefix(parsed.repoRootSubdir, "/")
return parsed
}
parsed.kind = core.ModuleSourceKindGit

parsed.kind = core.ModuleSourceKindLocal
return parsed
}

Expand Down Expand Up @@ -192,14 +210,6 @@ func (s *moduleSchema) moduleSourceAsString(ctx context.Context, src *core.Modul
return src.RefString()
}

func (s *moduleSchema) gitModuleSourceCloneURL(
ctx context.Context,
ref *core.GitModuleSource,
args struct{},
) (string, error) {
return ref.CloneURL(), nil
}

func (s *moduleSchema) gitModuleSourceHTMLURL(
ctx context.Context,
ref *core.GitModuleSource,
Expand Down Expand Up @@ -642,6 +652,10 @@ func (s *moduleSchema) moduleSourceResolveFromCaller(
if err != nil {
return inst, fmt.Errorf("failed to get source root relative path: %w", err)
}
// ensure sourceRootRelPath has a local path structure
// even when subdir relative to git source has ref structure
// (cf. test TestRefFormat)
sourceRootRelPath = "./" + sourceRootRelPath

collectedDeps := dagql.NewCacheMap[string, *callerLocalDep]()
if err := s.collectCallerLocalDeps(ctx, src.Query, contextAbsPath, sourceRootAbsPath, true, src, collectedDeps); err != nil {
Expand Down Expand Up @@ -970,7 +984,7 @@ func (s *moduleSchema) collectCallerLocalDeps(
}

for _, depCfg := range modCfg.Dependencies {
parsed := parseRefString(depCfg.Source)
parsed := parseRefString(ctx, query.Buildkit, depCfg.Source)
if parsed.kind != core.ModuleSourceKindLocal {
continue
}
Expand All @@ -991,7 +1005,7 @@ func (s *moduleSchema) collectCallerLocalDeps(
switch {
case err == nil:
case errors.Is(err, errUnknownBuiltinSDK):
parsed := parseRefString(modCfg.SDK)
parsed := parseRefString(ctx, query.Buildkit, modCfg.SDK)
switch parsed.kind {
case core.ModuleSourceKindLocal:
// SDK is a local custom one, it needs to be included
Expand Down
Loading