Skip to content
Draft
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
84 changes: 84 additions & 0 deletions .dagger/modules/e2e/main.dang
Original file line number Diff line number Diff line change
Expand Up @@ -1872,6 +1872,40 @@ type E2e {
.withWorkdir("/sdk")
}

"""
The names helper formats a schema's names as the engine does. Its copy of
the engine's naming package is byte for byte the package at the dagger/dagger
commit naming/pin.go names, and formats the engine's own test vectors,
copied with it, as the engine does.
"""
pub namesHelperTestCheck(ws: Workspace!): Void @check {
let helper = ws.directory("/helpers/names")
let pin = helper.file("naming/pin.go").contents.match("Commit = \"([0-9a-f]{40})\"")
let commit = if (pin == null) {
raise "helpers/names/naming/pin.go names no commit"
} else {
pin.captures[0] ?? ""
}
let upstream = git("https://github.com/dagger/dagger").commit(commit).tree.directory("engine/naming")
["dictionary.go", "format.go", "naming.go", "version.go", "testdata/vectors.json"].each { file =>
assert(
helper.file("naming/" + file).contents == upstream.file(file).contents,
"helpers/names/naming/" + file + " is not engine/naming/" + file + " at the pinned commit: copy it again",
)
}
container
.from("golang:1.25-alpine")
.withoutEntrypoint
.withMountedCache("/go/pkg/mod", cacheVolume("go-mod"))
.withMountedCache("/root/.cache/go-build", cacheVolume("go-build"))
.withDirectory("/helper", helper)
.withWorkdir("/helper")
.withExec(["go", "vet", "./..."])
.withExec(["go", "test", "./..."])
.sync
null
}

"""
The client library and code generator pass their own suites: the query
builder, generator output and module registration.
Expand Down Expand Up @@ -2089,6 +2123,56 @@ type E2e {
null
}

"""
The entrypoint generated into a module declares the engine version it runs
on in a dang.toml beside it, which the engine reads for it: a new module
the engine it is created on, a module that already had an entrypoint but no
dang.toml the last version before the engine's naming rules, which is what
the engine serves it without one. A dang.toml the module has is kept byte
for byte, and its version is the view the scope is generated in.
"""
pub entrypointVersionCheck(ws: Workspace!): Void @check {
let scope = outputRoot + "/entrypoint-version"
let scoped = ws.withNewDirectory("/" + scope, directory).withWorkdir(scope)
let fresh = pythonSdk.generateScope(scoped, isModule: true, name: "entrypoint-version", clients: [])
let tomlPath = "/" + scope + "/sdk/entrypoint/dang.toml"
let engine = version.split("+")[0] ?? version
assert(
fresh.file(tomlPath).contents == "dang = \"2.1\"\n\n[imports.Dagger]\ndagger = \"" + engine + "\"\n",
"a new module does not declare the engine it was created on: " + fresh.file(tomlPath).contents,
)
let again = pythonSdk.generateScope(fresh, isModule: true, name: "entrypoint-version", clients: [])
assert(again.changes(fresh).isEmpty, "generating a new module again changed it")

# An entrypoint from before the dang.toml keeps the version the engine
# served it without one.
let unversioned = fresh.withoutFile(tomlPath)
let regenerated = pythonSdk.generateScope(unversioned, isModule: true, name: "entrypoint-version", clients: [])
assertContains(regenerated.file(tomlPath).contents, "dagger = \"v1.0.0-beta.20\"", "an existing entrypoint moved to another version")
let direct = unversioned.withChanges(pythonSdk.mod(unversioned, path: scope, findUp: false).generate)
assertContains(direct.file(tomlPath).contents, "dagger = \"v1.0.0-beta.20\"", "generating the module on its own moved it to another version")

# The module's own dang.toml stays as it is.
let own = "# mine\ndang = \"2.1\"\n\n[imports.Dagger]\ndagger = \"v1.0.0-beta.19\"\n"
let kept = pythonSdk.generateScope(fresh.withNewFile(tomlPath, own), isModule: true, name: "entrypoint-version", clients: [])
assert(kept.file(tomlPath).contents == own, "generation rewrote the module's dang.toml: " + kept.file(tomlPath).contents)

# A module the builtin runtime ran keeps a version that already named it
# by the engine's rules, and only such a version.
let bare = unversioned.withoutDirectory("/" + scope + "/sdk/entrypoint")
assertContains(migratedDangToml(bare, scope, "v1.0.0-beta.21"), "dagger = \"v1.0.0-beta.21\"", "a migrated module lost the version that named it")
assertContains(migratedDangToml(bare, scope, "v0.21.9"), "dagger = \"v1.0.0-beta.20\"", "a migrated module kept a version older than the entrypoint")
null
}

let migratedDangToml(ws: Workspace!, scope: String!, declared: String!): String! {
let runtime = "name = \"entrypoint-version\"\nengineVersion = \"" + declared + "\"\n\n[runtime]\nsource = \"python\"\n"
pythonSdk
.generateScope(ws.withNewFile("/" + scope + "/dagger-module.toml", runtime), isModule: true, name: "entrypoint-version", clients: [])
.file("/" + scope + "/sdk/entrypoint/dang.toml")
.contents
}

"""
The SDK refuses an engine release older than its floor before it generates
anything, and names the version it found and what to do: pin the SDK's last
Expand Down
5 changes: 5 additions & 0 deletions helpers/names/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module names

go 1.25.0

require golang.org/x/mod v0.37.0
2 changes: 2 additions & 0 deletions helpers/names/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
270 changes: 270 additions & 0 deletions helpers/names/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
// Command names writes the names file the Python code generator reads: the
// schema's names in snake_case, as the engine formats them.
//
// The engine names everything in a schema served at v1.0.0-beta.21 or later
// by its naming rules, and from then on its Query.formatIdentifiers tells how
// to write a schema name in any casing. Generation reads schemas from
// introspection JSON, without a session in the view of the schema it
// generates (python-sdk itself is served before that version), so it can't
// call it. This formats the names with a copy of the engine's own naming
// package instead (see naming/pin.go), keyed by the schema's __schemaVersion like
// formatIdentifiers(version:).
//
// The gate is the one formatIdentifiers has on engines from v1.0.0-beta.21: a
// schema without it gets an empty names file, and the generator keeps its
// legacy conversion. Released engines before that (v1.0.0-beta.19 and
// beta.20) serve formatIdentifiers in every v1 view but still name modules by
// their legacy rules, so given the engine's version (-engine), a release
// before v1.0.0-beta.21 gets an empty file too.
//
// usage: names [-engine <version>] -o <names.json> <introspection.json>...
package main

import (
"encoding/json"
"flag"
"fmt"
"io"
"os"
"sort"
"strings"

"golang.org/x/mod/semver"

"names/naming"
)

// SnakeFormat is the key of the names file's snake_case names: the CASING and
// ACRONYMS that formatIdentifiers would be called with. The acronym style
// doesn't change snake_case.
const SnakeFormat = "SNAKE:UPPERCASE"

// IdentifierCasingVersion is the first engine release that names schemas by
// its naming rules, in the views from that version on.
const IdentifierCasingVersion = "v1.0.0-beta.21"

// CoveredVersion is the newest engine release line whose dictionaries the copy
// of engine/naming in naming/ is known to hold. A dictionary addition is keyed
// by the engine version that introduced it, so a schema newer than this may be
// named by a dictionary the copy doesn't have. Bump it with the copy (see
// naming/pin.go).
const CoveredVersion = "v1.0.0"

func main() {
if err := run(os.Args[1:], os.Stdout, os.Stderr); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

func run(args []string, stdout, stderr io.Writer) error {
flags := flag.NewFlagSet("names", flag.ContinueOnError)
flags.SetOutput(stderr)
output := flags.String("o", "", "path to write the names file to")
engine := flags.String("engine", "", "version of the engine that served the schemas")
if err := flags.Parse(args); err != nil {
return err
}
if *output == "" || flags.NArg() == 0 {
return fmt.Errorf("usage: names [-engine <version>] -o <names.json> <introspection.json>...")
}

schemas := make([]schema, 0, flags.NArg())
for _, path := range flags.Args() {
data, err := os.ReadFile(path)
if err != nil {
return err
}
s, err := parseSchema(data)
if err != nil {
return fmt.Errorf("%s: %w", path, err)
}
schemas = append(schemas, s)
}

file := File{}
var warnings []string
if namesSchemas(*engine) {
file, warnings = namesFile(schemas)
}
for _, w := range warnings {
fmt.Fprintln(stderr, "WARNING:", w)
}
data, err := json.MarshalIndent(file, "", " ")
if err != nil {
return err
}
if err := os.WriteFile(*output, append(data, '\n'), 0o644); err != nil {
return err
}
fmt.Fprintf(stdout, "Names written to %s\n", *output)
return nil
}

// namesSchemas reports whether an engine of the given version names schemas
// by its naming rules where it serves Query.formatIdentifiers: a release from
// IdentifierCasingVersion on. An unknown or unreadable version leaves the
// decision to the schemas.
func namesSchemas(engine string) bool {
v := engine
if v != "" && !strings.HasPrefix(v, "v") {
v = "v" + v
}
if !semver.IsValid(v) {
return true
}
return semver.Compare(v, IdentifierCasingVersion) >= 0
}

// File is the names file: each CASING:ACRONYMS format to the names in it, by
// schema name. It has no format at all for schemas without
// Query.formatIdentifiers.
type File map[string]map[string]string

// namesFile formats the names of the schemas that have Query.formatIdentifiers.
// A name the engine can't parse (non-ASCII, say) is left out, and the
// generator converts it the old way, like a name the engine leaves as it is.
func namesFile(schemas []schema) (File, []string) {
file := File{}
var warnings []string
for _, s := range schemas {
if !s.hasFormatIdentifiers() {
continue
}
if w := coverageWarning(s.Version); w != "" {
warnings = append(warnings, w)
}
dict := naming.DictionaryFor(s.Version)
snake := file[SnakeFormat]
if snake == nil {
snake = map[string]string{}
file[SnakeFormat] = snake
}
for _, name := range s.names() {
id, err := dict.Parse(name)
if err != nil {
continue
}
snake[name] = id.Format(naming.Snake, naming.Uppercase)
}
}
return file, warnings
}

// coverageWarning says when a schema may be named by a dictionary newer than
// the copy's. It doesn't fail generation: dictionary additions are rare,
// engine releases are not, and the names only differ where an added term
// occurs.
func coverageWarning(version string) string {
v := version
if v != "" && !strings.HasPrefix(v, "v") {
v = "v" + v
}
if !semver.IsValid(v) {
return ""
}
base := strings.TrimSuffix(strings.TrimSuffix(v, semver.Build(v)), semver.Prerelease(v))
if semver.Compare(base, CoveredVersion) <= 0 {
return ""
}
return fmt.Sprintf(
"the schema's version %s is newer than %s, the newest engine this "+
"Python SDK's copy of the engine's naming rules covers: names the "+
"engine added acronyms or terms for since may be written "+
"differently than the engine writes them. Upgrade the Python SDK.",
version, CoveredVersion)
}

// schema is what the names file needs of an introspection result.
type schema struct {
Version string `json:"__schemaVersion"`
Schema struct {
QueryType *struct {
Name string `json:"name"`
} `json:"queryType"`
Types []schemaType `json:"types"`
} `json:"__schema"`
}

type schemaType struct {
Name string `json:"name"`
Fields []struct {
Name string `json:"name"`
Args []struct {
Name string `json:"name"`
} `json:"args"`
} `json:"fields"`
InputFields []struct {
Name string `json:"name"`
} `json:"inputFields"`
EnumValues []struct {
Name string `json:"name"`
} `json:"enumValues"`
}

func parseSchema(data []byte) (schema, error) {
var s schema
if err := json.Unmarshal(data, &s); err != nil {
return s, err
}
if len(s.Schema.Types) == 0 {
return s, fmt.Errorf("not an introspection result: no __schema types")
}
return s, nil
}

// hasFormatIdentifiers reports whether the schema has Query.formatIdentifiers,
// which is in the schemas the engine names by its naming rules, and only in
// those.
func (s schema) hasFormatIdentifiers() bool {
query := "Query"
if s.Schema.QueryType != nil && s.Schema.QueryType.Name != "" {
query = s.Schema.QueryType.Name
}
for _, t := range s.Schema.Types {
if t.Name != query {
continue
}
for _, f := range t.Fields {
if f.Name == "formatIdentifiers" {
return true
}
}
}
return false
}

// names lists the schema's own names, sorted: its types, fields, arguments,
// input fields and enum values. Introspection's own (__Type) are left out.
func (s schema) names() []string {
seen := map[string]bool{}
add := func(name string) {
if name != "" && !strings.HasPrefix(name, "__") {
seen[name] = true
}
}
for _, t := range s.Schema.Types {
if strings.HasPrefix(t.Name, "__") {
continue
}
add(t.Name)
for _, f := range t.Fields {
add(f.Name)
for _, a := range f.Args {
add(a.Name)
}
}
for _, f := range t.InputFields {
add(f.Name)
}
for _, v := range t.EnumValues {
add(v.Name)
}
}
names := make([]string, 0, len(seen))
for name := range seen {
names = append(names, name)
}
sort.Strings(names)
return names
}
Loading