From 217ff5b19ac438fe9a44f5ba4cdb997fb507b2f8 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Thu, 22 Oct 2026 16:31:13 +0000 Subject: [PATCH 1/9] helpers: format schema names with engine/naming The Python code generator needs a schema's names in snake_case as the engine formats them, but generation reads schemas from introspection JSON and python-sdk itself is served before v1.0.0-beta.21, where Query.formatIdentifiers lives, so it can't ask the engine. helpers/names writes the names file (SNAKE:UPPERCASE map) with a verbatim copy of dagger/dagger's engine/naming at a pinned commit (naming/pin.go), keyed by the schema's __schemaVersion like formatIdentifiers(version:). A schema without Query.formatIdentifiers gets an empty file: that's the gate. It warns when a schema is newer than the release line the copy covers, and tests the copy against the engine's own vectors. Signed-off-by: Alex Suraci --- helpers/names/go.mod | 5 + helpers/names/go.sum | 2 + helpers/names/main.go | 242 ++ helpers/names/main_test.go | 165 ++ helpers/names/naming/dictionary.go | 192 ++ helpers/names/naming/format.go | 153 + helpers/names/naming/naming.go | 513 ++++ helpers/names/naming/pin.go | 16 + helpers/names/naming/testdata/vectors.json | 3119 ++++++++++++++++++++ helpers/names/naming/vectors_test.go | 57 + helpers/names/naming/version.go | 58 + 11 files changed, 4522 insertions(+) create mode 100644 helpers/names/go.mod create mode 100644 helpers/names/go.sum create mode 100644 helpers/names/main.go create mode 100644 helpers/names/main_test.go create mode 100644 helpers/names/naming/dictionary.go create mode 100644 helpers/names/naming/format.go create mode 100644 helpers/names/naming/naming.go create mode 100644 helpers/names/naming/pin.go create mode 100644 helpers/names/naming/testdata/vectors.json create mode 100644 helpers/names/naming/vectors_test.go create mode 100644 helpers/names/naming/version.go diff --git a/helpers/names/go.mod b/helpers/names/go.mod new file mode 100644 index 00000000..6d617fa0 --- /dev/null +++ b/helpers/names/go.mod @@ -0,0 +1,5 @@ +module names + +go 1.25.0 + +require golang.org/x/mod v0.37.0 diff --git a/helpers/names/go.sum b/helpers/names/go.sum new file mode 100644 index 00000000..9e6a024a --- /dev/null +++ b/helpers/names/go.sum @@ -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= diff --git a/helpers/names/main.go b/helpers/names/main.go new file mode 100644 index 00000000..42834c93 --- /dev/null +++ b/helpers/names/main.go @@ -0,0 +1,242 @@ +// 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: a schema without it gets an empty +// names file, and the generator keeps its legacy conversion. +// +// usage: names -o ... +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" + +// 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") + if err := flags.Parse(args); err != nil { + return err + } + if *output == "" || flags.NArg() == 0 { + return fmt.Errorf("usage: names -o ...") + } + + 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, 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 +} + +// 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 +} diff --git a/helpers/names/main_test.go b/helpers/names/main_test.go new file mode 100644 index 00000000..e53aa8b1 --- /dev/null +++ b/helpers/names/main_test.go @@ -0,0 +1,165 @@ +package main + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +func introspection(version string, queryFields ...string) string { + fields := make([]string, 0, len(queryFields)) + for _, f := range queryFields { + fields = append(fields, `{"name": "`+f+`", "args": []}`) + } + return `{ + "__schemaVersion": "` + version + `", + "__schema": { + "queryType": {"name": "Query"}, + "types": [ + {"name": "Query", "fields": [` + strings.Join(fields, ",") + `]}, + {"name": "GitCommit", "fields": [ + {"name": "shortSHA", "args": []}, + {"name": "parentSHAs", "args": []} + ]}, + {"name": "GitRepository", "fields": [ + {"name": "withRemote", "args": [{"name": "pushURL"}, {"name": "café"}]} + ]}, + {"name": "LLMContentBlockInput", "inputFields": [{"name": "callID"}]}, + {"name": "ImageMediaTypes", "enumValues": [{"name": "OCI"}, {"name": "OCIMediaTypes"}]}, + {"name": "__Type", "fields": [{"name": "__internal", "args": []}]} + ] + } + }` +} + +func generate(t *testing.T, schemas ...string) (File, string) { + t.Helper() + dir := t.TempDir() + args := []string{"-o", filepath.Join(dir, "names.json")} + for i, s := range schemas { + path := filepath.Join(dir, "schema"+string(rune('a'+i))+".json") + if err := os.WriteFile(path, []byte(s), 0o644); err != nil { + t.Fatal(err) + } + args = append(args, path) + } + var stdout, stderr bytes.Buffer + if err := run(args, &stdout, &stderr); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(filepath.Join(dir, "names.json")) + if err != nil { + t.Fatal(err) + } + var file File + if err := json.Unmarshal(data, &file); err != nil { + t.Fatal(err) + } + return file, stderr.String() +} + +func TestNamesWithFormatIdentifiers(t *testing.T) { + file, warnings := generate(t, introspection("v1.0.0-beta.21", "formatIdentifiers", "gitRepository")) + if warnings != "" { + t.Errorf("unexpected warnings: %s", warnings) + } + want := map[string]string{ + "Query": "query", + "formatIdentifiers": "format_identifiers", + "gitRepository": "git_repository", + "GitCommit": "git_commit", + "shortSHA": "short_sha", + "parentSHAs": "parent_shas", + "GitRepository": "git_repository", + "withRemote": "with_remote", + "pushURL": "push_url", + "LLMContentBlockInput": "llm_content_block_input", + "callID": "call_id", + "ImageMediaTypes": "image_media_types", + "OCI": "oci", + "OCIMediaTypes": "oci_media_types", + } + snake := file[SnakeFormat] + for name, formatted := range want { + if got := snake[name]; got != formatted { + t.Errorf("%s: got %q, want %q", name, got, formatted) + } + } + // Non-ASCII names don't parse: left to the generator's own conversion. + if _, ok := snake["café"]; ok { + t.Error("café should be left out") + } + // Introspection's own names aren't the schema's. + if _, ok := snake["__internal"]; ok { + t.Error("__internal should be left out") + } + if len(snake) != len(want) { + t.Errorf("got %d names, want %d: %v", len(snake), len(want), snake) + } +} + +// A schema without Query.formatIdentifiers is named by the legacy rules: the +// file has no format, and the generator keeps its own conversion. +func TestNamesWithoutFormatIdentifiers(t *testing.T) { + file, _ := generate(t, introspection("v1.0.0-beta.20", "gitRepository")) + if len(file) != 0 { + t.Errorf("got %v, want an empty file", file) + } +} + +// The names of every schema of a scope, for the global client. +func TestNamesOfSeveralSchemas(t *testing.T) { + other := strings.Replace(introspection("v1.0.0-beta.21", "formatIdentifiers"), "withRemote", "withHTTPClient", 1) + file, _ := generate(t, introspection("v1.0.0-beta.21", "formatIdentifiers"), other) + snake := file[SnakeFormat] + if snake["withRemote"] != "with_remote" || snake["withHTTPClient"] != "with_http_client" { + t.Errorf("got %v", snake) + } +} + +// The generator writes an enum value's member as its snake_case name, +// uppercased: the names file has no SCREAMING_SNAKE map. That is the +// engine's SCREAMING_SNAKE for every name of its test vectors. +func TestScreamingSnakeIsUppercasedSnake(t *testing.T) { + data, err := os.ReadFile("naming/testdata/vectors.json") + if err != nil { + t.Fatal(err) + } + var vectors []struct { + Input string `json:"input"` + Formats map[string]string `json:"formats"` + } + if err := json.Unmarshal(data, &vectors); err != nil { + t.Fatal(err) + } + for _, v := range vectors { + if got, want := strings.ToUpper(v.Formats["SNAKE"]), v.Formats["SCREAMING_SNAKE"]; got != want { + t.Errorf("%q: uppercased snake_case %q, SCREAMING_SNAKE %q", v.Input, got, want) + } + } +} + +func TestCoverageWarning(t *testing.T) { + for version, warns := range map[string]bool{ + "v1.0.0-beta.21": false, + "v1.0.0": false, + "v1.0.0-dev-123": false, + "v1.0.0-beta.21+abcde": false, + "": false, + "garbage": false, + "v1.0.1": true, + "v1.1.0-beta.1": true, + "2.0.0": true, + } { + if got := coverageWarning(version) != ""; got != warns { + t.Errorf("%q: warns %v, want %v", version, got, warns) + } + } + _, warnings := generate(t, introspection("v1.1.0", "formatIdentifiers")) + if !strings.Contains(warnings, "WARNING:") || !strings.Contains(warnings, "v1.1.0") { + t.Errorf("got warnings %q", warnings) + } +} diff --git a/helpers/names/naming/dictionary.go b/helpers/names/naming/dictionary.go new file mode 100644 index 00000000..5e7891f9 --- /dev/null +++ b/helpers/names/naming/dictionary.go @@ -0,0 +1,192 @@ +package naming + +import ( + "fmt" + "strings" +) + +// Term is a dictionary entry: an acronym (HTTP) or a term with a fixed +// mixed-case spelling (GitHub, IPv6). +type Term struct { + // Spelling is the standard spelling: HTTP, IPv6, GitHub, iOS, 3D. + Spelling string + // Capitalized is the spelling in the CAPITALIZED acronym style: Http, + // Ipv6, GitHub, Ios, 3D. It can't be derived from Spelling (a brand like + // GitHub never changes), so terms with lowercase letters or leading + // digits must set it; plain acronyms default to the first letter + // capitalized and the rest lowercase. + Capitalized string +} + +// Kind is the kind of word a match against this term produces. +func (t Term) Kind() WordKind { + if hasLower(t.Spelling) { + return KindTerm + } + return KindAcronym +} + +// Dictionary is a set of acronyms and terms used to parse identifiers. +// +// Adding a term renames every identifier that contains it, so a released +// dictionary must never change: additions go into a new Dictionary that is +// selected by engine version, leaving older modules on the one they had. +type Dictionary struct { + terms []Term + // byFold maps a lowercased spelling to its index in terms. + byFold map[string]int + // maxLen and maxLetters are the longest entry's length and letter count, + // which bound how far parsing looks for a match. + maxLen, maxLetters int +} + +// NewDictionary builds a dictionary from terms. It returns an error for an +// entry that is empty, not alphanumeric ASCII, duplicated (ignoring case), or +// missing a Capitalized form that can't be defaulted. +func NewDictionary(terms []Term) (*Dictionary, error) { + d := &Dictionary{ + terms: make([]Term, 0, len(terms)), + byFold: make(map[string]int, len(terms)), + } + for _, t := range terms { + if t.Spelling == "" { + return nil, fmt.Errorf("naming: empty dictionary entry") + } + for i := 0; i < len(t.Spelling); i++ { + if !isAlnum(t.Spelling[i]) { + return nil, fmt.Errorf("naming: dictionary entry %q is not alphanumeric ASCII", t.Spelling) + } + } + if !hasLetter(t.Spelling) { + return nil, fmt.Errorf("naming: dictionary entry %q has no letters", t.Spelling) + } + if t.Capitalized == "" { + if hasLower(t.Spelling) || isDigit(t.Spelling[0]) { + return nil, fmt.Errorf("naming: dictionary entry %q needs an explicit capitalized form", t.Spelling) + } + t.Capitalized = upperFirst(strings.ToLower(t.Spelling)) + } + if !strings.EqualFold(t.Capitalized, t.Spelling) { + return nil, fmt.Errorf("naming: dictionary entry %q has mismatched capitalized form %q", t.Spelling, t.Capitalized) + } + fold := strings.ToLower(t.Spelling) + if _, dup := d.byFold[fold]; dup { + return nil, fmt.Errorf("naming: duplicate dictionary entry %q", t.Spelling) + } + d.byFold[fold] = len(d.terms) + d.terms = append(d.terms, t) + d.maxLen = max(d.maxLen, len(t.Spelling)) + d.maxLetters = max(d.maxLetters, countLetters(t.Spelling)) + } + return d, nil +} + +// MustDictionary is NewDictionary, panicking on error. +func MustDictionary(terms []Term) *Dictionary { + d, err := NewDictionary(terms) + if err != nil { + panic(err) + } + return d +} + +// Terms returns the dictionary's entries in definition order. +func (d *Dictionary) Terms() []Term { + return append([]Term(nil), d.terms...) +} + +// lookup finds the entry spelled like fold, which must be lowercase. +func (d *Dictionary) lookup(fold string) (*Term, bool) { + i, ok := d.byFold[fold] + if !ok { + return nil, false + } + return &d.terms[i], true +} + +// Initial is the dictionary the engine first shipped identifier parsing +// with. Don't edit it; see Dictionary. TestInitialDictionaryFrozen pins it. +var Initial = MustDictionary(initialTerms) + +// Latest is the newest dictionary, used by the package-level Parse. +var Latest = Initial + +var initialTerms = []Term{ + // golint's commonInitialisms, which the Go SDK uses today. + {Spelling: "ACL"}, + {Spelling: "API"}, + {Spelling: "ASCII"}, + {Spelling: "CPU"}, + {Spelling: "CSS"}, + {Spelling: "DNS"}, + {Spelling: "EOF"}, + {Spelling: "GUID"}, + {Spelling: "HTML"}, + {Spelling: "HTTP"}, + {Spelling: "HTTPS"}, + {Spelling: "ID"}, + {Spelling: "IP"}, + {Spelling: "JSON"}, + {Spelling: "LHS"}, + {Spelling: "QPS"}, + {Spelling: "RAM"}, + {Spelling: "RHS"}, + {Spelling: "RPC"}, + {Spelling: "SLA"}, + {Spelling: "SMTP"}, + {Spelling: "SQL"}, + {Spelling: "SSH"}, + {Spelling: "TCP"}, + {Spelling: "TLS"}, + {Spelling: "TTL"}, + {Spelling: "UDP"}, + {Spelling: "UI"}, + {Spelling: "UID"}, + {Spelling: "UUID"}, + {Spelling: "URI"}, + {Spelling: "URL"}, + {Spelling: "UTF8"}, + {Spelling: "VM"}, + {Spelling: "XML"}, + {Spelling: "XMPP"}, + {Spelling: "XSRF"}, + {Spelling: "XSS"}, + + // The Go SDK's Dagger additions. + {Spelling: "FS"}, + {Spelling: "SDK"}, + {Spelling: "LLM"}, + + // Acronyms found in the core schema. + {Spelling: "GPU"}, + {Spelling: "VCS"}, + {Spelling: "SHA"}, + {Spelling: "MCP"}, + {Spelling: "OCI"}, + // A lowercase word is never split, but all-caps input is: without this + // entry, sshfsVolume would be sshfs · volume, and its SCREAMING_SNAKE + // form SSHFS_VOLUME would parse as SSH · FS · volume. + {Spelling: "SSHFS"}, + + // Common in modules. + {Spelling: "E2E"}, + {Spelling: "CLI"}, + {Spelling: "TUI"}, + {Spelling: "IO"}, + {Spelling: "PR"}, + {Spelling: "EC2"}, + {Spelling: "MD5"}, + + // Terms the case heuristic or the digit rule would split. + {Spelling: "GitHub", Capitalized: "GitHub"}, + {Spelling: "GitLab", Capitalized: "GitLab"}, + {Spelling: "OAuth", Capitalized: "Oauth"}, + {Spelling: "IPv4", Capitalized: "Ipv4"}, + {Spelling: "IPv6", Capitalized: "Ipv6"}, + {Spelling: "iOS", Capitalized: "Ios"}, + {Spelling: "macOS", Capitalized: "MacOS"}, + {Spelling: "gRPC", Capitalized: "Grpc"}, + {Spelling: "GraphQL", Capitalized: "GraphQL"}, + {Spelling: "3D", Capitalized: "3D"}, + {Spelling: "2D", Capitalized: "2D"}, +} diff --git a/helpers/names/naming/format.go b/helpers/names/naming/format.go new file mode 100644 index 00000000..a08d2e6c --- /dev/null +++ b/helpers/names/naming/format.go @@ -0,0 +1,153 @@ +package naming + +import ( + "fmt" + "strings" +) + +// Casing is a convention for joining words into an identifier. +type Casing int + +const ( + // Pascal capitalizes every word: HTTPClient. + Pascal Casing = iota + // Camel lowercases the first word and capitalizes the rest: httpClient. + Camel + // Snake lowercases every word and joins them with "_": http_client. + Snake + // ScreamingSnake uppercases every word and joins them with "_": + // HTTP_CLIENT. + ScreamingSnake + // Kebab lowercases every word and joins them with "-": http-client. + Kebab + // Flat lowercases every word and drops the boundaries: httpclient. It is + // for Go package and Python module names, and doesn't round-trip. + Flat +) + +// Casings lists every Casing. +var Casings = []Casing{Pascal, Camel, Snake, ScreamingSnake, Kebab, Flat} + +func (c Casing) String() string { + switch c { + case Pascal: + return "PASCAL" + case Camel: + return "CAMEL" + case Snake: + return "SNAKE" + case ScreamingSnake: + return "SCREAMING_SNAKE" + case Kebab: + return "KEBAB" + case Flat: + return "FLAT" + default: + return fmt.Sprintf("Casing(%d)", int(c)) + } +} + +// AcronymStyle is how acronyms and terms are written where a word starts +// with a capital. It only affects Pascal and Camel. +type AcronymStyle int + +const ( + // Uppercase writes HTTPClient, IPv6Address, GitHubRepo. + Uppercase AcronymStyle = iota + // Capitalized writes HttpClient, Ipv6Address, GitHubRepo. + Capitalized +) + +// AcronymStyles lists every AcronymStyle. +var AcronymStyles = []AcronymStyle{Uppercase, Capitalized} + +func (s AcronymStyle) String() string { + switch s { + case Uppercase: + return "UPPERCASE" + case Capitalized: + return "CAPITALIZED" + default: + return fmt.Sprintf("AcronymStyle(%d)", int(s)) + } +} + +// Format formats id's words in a casing. +func Format(id Identifier, casing Casing, style AcronymStyle) string { + return id.Format(casing, style) +} + +// Format formats the identifier's words in a casing. +func (id Identifier) Format(casing Casing, style AcronymStyle) string { + var b strings.Builder + for i, w := range id.Words { + switch casing { + case Pascal: + b.WriteString(w.capitalized(style)) + case Camel: + if i == 0 { + b.WriteString(w.lower()) + } else { + b.WriteString(w.capitalized(style)) + } + case Snake: + if i > 0 { + b.WriteByte('_') + } + b.WriteString(w.lower()) + case ScreamingSnake: + if i > 0 { + b.WriteByte('_') + } + b.WriteString(strings.ToUpper(w.Text + w.Suffix)) + case Kebab: + if i > 0 { + b.WriteByte('-') + } + b.WriteString(w.lower()) + case Flat: + b.WriteString(w.lower()) + default: + panic(fmt.Sprintf("naming: unknown casing %d", int(casing))) + } + } + return b.String() +} + +// Convert parses name with the Latest dictionary and formats it in a casing. +func Convert(name string, casing Casing, style AcronymStyle) (string, error) { + id, err := Parse(name) + if err != nil { + return "", err + } + return id.Format(casing, style), nil +} + +func (w Word) lower() string { + return strings.ToLower(w.Text + w.Suffix) +} + +// capitalized is the word's form where it starts with a capital. +func (w Word) capitalized(style AcronymStyle) string { + var text string + switch { + case w.Kind == KindWord: + text = upperFirst(strings.ToLower(w.Text)) + case style == Capitalized && w.Term != nil: + text = w.Term.Capitalized + case style == Capitalized: + text = upperFirst(strings.ToLower(w.Text)) + case w.Kind == KindTerm: + text = upperFirst(w.Text) + default: + text = w.Text + } + return text + w.Suffix +} + +func upperFirst(s string) string { + if s == "" || !isLower(s[0]) { + return s + } + return string(s[0]-'a'+'A') + s[1:] +} diff --git a/helpers/names/naming/naming.go b/helpers/names/naming/naming.go new file mode 100644 index 00000000..316f0322 --- /dev/null +++ b/helpers/names/naming/naming.go @@ -0,0 +1,513 @@ +// Package naming parses identifiers written in any casing into words, and +// formats those words in any other casing. +// +// Case conventions lose information: HTTPAPIClient doesn't say where HTTP +// ends, httpClient doesn't say http is an acronym, and IPv6Address looks like +// I + Pv6 + Address. Parsing recovers it from a dictionary of acronyms and +// terms first, and falls back to a case heuristic for everything else, so +// every casing of a name the dictionary covers parses to the same words. +// +// The algorithm and the initial dictionary are specified in +// hack/designs/identifier-casing.md. +package naming + +import ( + "errors" + "fmt" + "slices" + "strings" +) + +// WordKind classifies a word of an identifier. +type WordKind int + +const ( + // KindWord is an ordinary word, stored lowercase: client. + KindWord WordKind = iota + // KindAcronym is a word written in capitals, from the dictionary or a + // run of capitals in the input: HTTP, E2E, 3D. + KindAcronym + // KindTerm is a dictionary entry with a fixed mixed-case spelling: + // GitHub, IPv6, iOS. + KindTerm +) + +func (k WordKind) String() string { + switch k { + case KindWord: + return "WORD" + case KindAcronym: + return "ACRONYM" + case KindTerm: + return "TERM" + default: + return fmt.Sprintf("WordKind(%d)", int(k)) + } +} + +// Word is one unit of an identifier. +type Word struct { + Kind WordKind + // Text is the standard spelling: client (WORD), HTTP (ACRONYM), GitHub + // (TERM). A WORD's digits are part of its text: base64, v1. + Text string + // Suffix is trailing digits and/or a plural "s", in that order, on an + // acronym or term: SHA+"s", OAuth+"2", HTTP+"2s". + Suffix string + // Term is the dictionary entry the word matched, or nil for a word + // found by the case heuristic. It is shared with the dictionary and must + // not be modified. + Term *Term +} + +// Identifier is a name parsed into words. +type Identifier struct { + // Name is the name as given to Parse. + Name string + // Words are the words of the name, in order. + Words []Word +} + +// ErrNonASCII is returned when parsing a name with non-ASCII characters. +var ErrNonASCII = errors.New("identifier must be ASCII") + +// ErrNoWords is returned when parsing a name with no letters or digits. +var ErrNoWords = errors.New("identifier must contain a letter or digit") + +// MaxLength is the longest name, in bytes, that Parse accepts. +const MaxLength = 256 + +// ErrTooLong is returned when parsing a name longer than MaxLength. +var ErrTooLong = fmt.Errorf("identifier must be at most %d bytes", MaxLength) + +// Parse parses name with the Latest dictionary. +func Parse(name string) (Identifier, error) { + return Latest.Parse(name) +} + +// Parse parses a name in any casing into words. +func (d *Dictionary) Parse(name string) (Identifier, error) { + if len(name) > MaxLength { + return Identifier{}, fmt.Errorf("parse %q...: %w", name[:32], ErrTooLong) + } + var hasUpperLetter, hasLowerLetter, hasAlnumChar bool + for i := 0; i < len(name); i++ { + c := name[i] + switch { + case c >= 0x80: + return Identifier{}, fmt.Errorf("parse %q: %w", name, ErrNonASCII) + case isUpper(c): + hasUpperLetter = true + case isLower(c): + hasLowerLetter = true + } + if isAlnum(c) { + hasAlnumChar = true + } + } + if !hasAlnumChar { + return Identifier{}, fmt.Errorf("parse %q: %w", name, ErrNoWords) + } + + // With only one case of letters (HTTP_CLIENT, http_client), case carries + // no information; treating capitals as acronyms would make CLIENT one. + cased := hasUpperLetter && hasLowerLetter + // All-caps input still has no boundaries between adjacent acronyms + // (JSONAPI), so its chunks may split where dictionary entries cover them + // completely, as runs of capitals do in cased input. Lowercase input never + // splits: too many words happen to be spelled as runs of entries. + allCaps := hasUpperLetter && !hasLowerLetter + + var words []Word + for _, chunk := range strings.FieldsFunc(name, func(r rune) bool { + return r >= 0x80 || !isAlnum(byte(r)) + }) { + var pieces []string + if cased { + pieces = splitPieces(chunk) + } else { + pieces = []string{strings.ToLower(chunk)} + } + words = append(words, d.segment(pieces, allCaps)...) + } + return Identifier{Name: name, Words: glueDigits(words)}, nil +} + +// splitPieces splits a chunk of a cased name at its case boundaries. +func splitPieces(chunk string) []string { + var pieces []string + start := 0 + for k := 1; k < len(chunk); k++ { + if caseBoundary(chunk, k) { + pieces = append(pieces, chunk[start:k]) + start = k + } + } + return append(pieces, chunk[start:]) +} + +// caseBoundary reports whether a new piece starts at s[k]. +func caseBoundary(s string, k int) bool { + // (c) A lone lowercase letter with digits after a run of capitals is a + // word of its own: APIv1, UUIDv7. + if letterDigitsAfterCaps(s, k) { + return true + } + if !isUpper(s[k]) { + return false + } + // (a) A capital after lowercase, looking past digits: httpClient, + // Get3DModel, Base64URLEncode. + for j := k - 1; j >= 0; j-- { + if isDigit(s[j]) { + continue + } + if isLower(s[j]) { + return true + } + break + } + // (b) The last capital of a run starts the next word: HTTPClient, + // E2ETest. A lone "s" after the run is a plural instead: SHAs, IDsFoo. + if k+1 < len(s) && isLower(s[k+1]) && (isUpper(s[k-1]) || isDigit(s[k-1])) { + if s[k+1] == 's' && (k+2 == len(s) || isUpper(s[k+2]) || isDigit(s[k+2])) { + return false + } + if letterDigitsAfterCaps(s, k+1) { + return false + } + return true + } + return false +} + +// letterDigitsAfterCaps reports whether s[k] is a lowercase letter followed +// by a digit, after at least two capitals: the v of APIv1. +func letterDigitsAfterCaps(s string, k int) bool { + return k >= 2 && k+1 < len(s) && + isLower(s[k]) && isDigit(s[k+1]) && + isUpper(s[k-1]) && isUpper(s[k-2]) +} + +// isCapsPiece reports whether a piece has no lowercase letters, ignoring a +// trailing plural "s" on a piece of three or more characters. +func isCapsPiece(p string) bool { + if len(p) >= 3 && p[len(p)-1] == 's' { + p = p[:len(p)-1] + } + return !hasLower(p) +} + +// cut is a run of only letters or only digits within one piece. Dictionary +// matching compares whole cuts, never substrings of one, which keeps +// Capital from containing API. +type cut struct { + text string + piece int + // offset is where the cut starts in its piece. + offset int +} + +type pieceInfo struct { + text string + start, end int // cut range + // caps marks a caps piece, whose heuristic words are acronyms. + caps bool + // cover marks a piece the dictionary may look inside, if its entries + // cover the whole piece: a caps piece, or a chunk of all-caps input. + cover bool +} + +// score ranks a division of a chunk into words; lower is better. +type score struct { + uncovered int // letters not covered by a dictionary entry + words int // words, not counting digit-only words + plurals int // plural dictionary matches + total int // all words, so heuristic words keep their digits +} + +func (s score) add(o score) score { + return score{s.uncovered + o.uncovered, s.words + o.words, s.plurals + o.plurals, s.total + o.total} +} + +func (s score) less(o score) bool { + switch { + case s.uncovered != o.uncovered: + return s.uncovered < o.uncovered + case s.words != o.words: + return s.words < o.words + case s.plurals != o.plurals: + return s.plurals < o.plurals + default: + return s.total < o.total + } +} + +// segment chooses the best division of one chunk's pieces into words. +// allCaps reports that the chunk came from all-caps input, lowercased. +func (d *Dictionary) segment(pieces []string, allCaps bool) []Word { + var cuts []cut + infos := make([]pieceInfo, len(pieces)) + for i, p := range pieces { + caps := isCapsPiece(p) + infos[i] = pieceInfo{text: p, start: len(cuts), caps: caps, cover: caps || allCaps} + start := 0 + for k := 1; k <= len(p); k++ { + if k == len(p) || isDigit(p[k]) != isDigit(p[k-1]) { + cuts = append(cuts, cut{text: p[start:k], piece: i, offset: start}) + start = k + } + } + infos[i].end = len(cuts) + } + + type state struct { + ok bool + score score + from int + words []Word + } + n := len(cuts) + best := make([]state, n+1) + best[0].ok = true + relax := func(i, j int, sc score, words []Word) { + sc = best[i].score.add(sc) + if !best[j].ok || sc.less(best[j].score) { + best[j] = state{ok: true, score: sc, from: i, words: words} + } + } + improves := func(i, j int, sc score) bool { + sc = best[i].score.add(sc) + return !best[j].ok || sc.less(best[j].score) + } + + for i := 0; i < n; i++ { + if !best[i].ok { + continue + } + + // Dictionary matches over whole cuts, possibly crossing pieces. A + // match has at most one letter (a plural s) beyond its entry's, so + // stop extending past that. + var fold strings.Builder + letters := 0 + for j := i + 1; j <= n; j++ { + c := cuts[j-1].text + if !isDigit(c[0]) { + letters += len(c) + } + if letters > d.maxLetters+1 { + break + } + fold.WriteString(strings.ToLower(c)) + f := fold.String() + if t, ok := d.lookup(f); ok { + relax(i, j, score{words: 1, total: 1}, []Word{termWord(t, "")}) + } + // A suffix is digits, then a plural "s", which ends the word: SHAs, + // HTTP2s, EC2s, but APIs3 is API · s3. + if base, ok := strings.CutSuffix(f, "s"); ok && (j == n || !isDigits(cuts[j].text)) { + if t, ok := d.lookup(base); ok { + relax(i, j, score{words: 1, plurals: 1, total: 1}, []Word{termWord(t, "s")}) + } else if stem := strings.TrimRight(base, "0123456789"); stem != base { + if t, ok := d.lookup(stem); ok { + relax(i, j, score{words: 1, plurals: 1, total: 1}, []Word{termWord(t, base[len(stem):]+"s")}) + } + } + } + } + + p := cuts[i].piece + info := infos[p] + + // A run of capitals has no internal boundaries, so it is the one + // place the dictionary looks inside a cut: HTTPAPI is HTTP + API. + if info.cover && i == info.start { + if words, sc, ok := d.coverCaps(info.text); ok { + relax(i, info.end, sc, words) + } + } + + // Heuristic words stay within one piece. Their score only depends on + // their letter count, so build the word only when it would win. + letters = 0 + for j := i + 1; j <= info.end; j++ { + c := cuts[j-1] + if !isDigit(c.text[0]) { + letters += len(c.text) + } + sc := heuristicScore(letters) + if !improves(i, j, sc) { + continue + } + text := info.text[cuts[i].offset : c.offset+len(c.text)] + relax(i, j, sc, []Word{heuristicWord(text, info.caps, j == info.end)}) + } + } + + var steps [][]Word + for j := n; j > 0; j = best[j].from { + steps = append(steps, best[j].words) + } + var out []Word + for i := len(steps) - 1; i >= 0; i-- { + out = append(out, steps[i]...) + } + return out +} + +// coverCaps writes a whole run of capitals (a caps piece, or a lowercased +// chunk of all-caps input) as a sequence of dictionary entries, digit runs +// and letter-digit words (V1), with the fewest uncovered letters, then the +// fewest entries, then the fewest plurals. It fails if any other letter is +// left over (HTTPX). +func (d *Dictionary) coverCaps(p string) ([]Word, score, bool) { + type state struct { + ok bool + score score + from int + word Word + } + n := len(p) + best := make([]state, n+1) + best[0].ok = true + relax := func(i, j int, sc score, w Word) { + sc = best[i].score.add(sc) + if !best[j].ok || sc.less(best[j].score) { + best[j] = state{ok: true, score: sc, from: i, word: w} + } + } + for i := 0; i < n; i++ { + if !best[i].ok { + continue + } + for j := i + 1; j <= n && isDigit(p[j-1]); j++ { + relax(i, j, score{total: 1}, Word{Kind: KindWord, Text: p[i:j]}) + } + // A letter and its digits (the V1 of APIV1) is an ordinary word. It + // counts as uncovered, so it only splits a run that entries + // otherwise cover: M3U8 stays whole. + if !isDigit(p[i]) { + j := i + 1 + for j < n && isDigit(p[j]) { + j++ + } + if j > i+1 { + relax(i, j, score{uncovered: 1, words: 1, total: 1}, Word{Kind: KindWord, Text: strings.ToLower(p[i:j])}) + } + } + for j := i + 1; j <= n && j-i <= d.maxLen; j++ { + t, ok := d.lookup(strings.ToLower(p[i:j])) + if !ok { + continue + } + relax(i, j, score{words: 1, total: 1}, termWord(t, "")) + // The plural may follow the entry's digits: APIHTTP2s. + k := j + for k < n && isDigit(p[k]) { + k++ + } + if k == n-1 && p[k] == 's' { + relax(i, n, score{words: 1, plurals: 1, total: 1}, termWord(t, p[j:k]+"s")) + } + } + } + if !best[n].ok { + return nil, score{}, false + } + var words []Word + for j := n; j > 0; j = best[j].from { + words = append(words, best[j].word) + } + slices.Reverse(words) + return words, best[n].score, true +} + +func termWord(t *Term, suffix string) Word { + return Word{Kind: t.Kind(), Text: t.Spelling, Suffix: suffix, Term: t} +} + +// heuristicScore scores a word found by the case heuristic, from its number +// of letters. +func heuristicScore(letters int) score { + if letters == 0 { + return score{total: 1} + } + return score{uncovered: letters, words: 1, total: 1} +} + +// heuristicWord makes a word from text found by the case heuristic. +// atPieceEnd reports whether text ends its piece, where a caps piece may +// carry a plural "s". +func heuristicWord(text string, caps, atPieceEnd bool) Word { + if !hasLetter(text) { + return Word{Kind: KindWord, Text: text} + } + if caps { + body, suffix := text, "" + if atPieceEnd && len(text) >= 2 && text[len(text)-1] == 's' { + body, suffix = text[:len(text)-1], "s" + } + if !hasLower(body) && countLetters(body) >= 2 { + return Word{Kind: KindAcronym, Text: body, Suffix: suffix} + } + } + return Word{Kind: KindWord, Text: strings.ToLower(text)} +} + +// glueDigits attaches each digit-only word to the word before it: OAuth·2 +// becomes OAuth+2, and v·1 becomes v1. Digits that start the name stay a word +// of their own. +func glueDigits(words []Word) []Word { + out := words[:0] + for _, w := range words { + if len(out) > 0 && w.Kind == KindWord && w.Term == nil && isDigits(w.Text) { + prev := &out[len(out)-1] + if prev.Kind == KindWord { + prev.Text += w.Text + } else { + prev.Suffix += w.Text + } + continue + } + out = append(out, w) + } + return out +} + +func isUpper(c byte) bool { return 'A' <= c && c <= 'Z' } +func isLower(c byte) bool { return 'a' <= c && c <= 'z' } +func isDigit(c byte) bool { return '0' <= c && c <= '9' } +func isAlnum(c byte) bool { return isUpper(c) || isLower(c) || isDigit(c) } + +func hasLower(s string) bool { + for i := 0; i < len(s); i++ { + if isLower(s[i]) { + return true + } + } + return false +} + +func hasLetter(s string) bool { + return countLetters(s) > 0 +} + +func countLetters(s string) int { + n := 0 + for i := 0; i < len(s); i++ { + if isUpper(s[i]) || isLower(s[i]) { + n++ + } + } + return n +} + +func isDigits(s string) bool { + for i := 0; i < len(s); i++ { + if !isDigit(s[i]) { + return false + } + } + return s != "" +} diff --git a/helpers/names/naming/pin.go b/helpers/names/naming/pin.go new file mode 100644 index 00000000..ec90baa3 --- /dev/null +++ b/helpers/names/naming/pin.go @@ -0,0 +1,16 @@ +package naming + +// This package is a verbatim copy of github.com/dagger/dagger's engine/naming +// (dictionary.go, format.go, naming.go, version.go and testdata/vectors.json), +// at the commit below. Only this file and vectors_test.go are this +// repository's own. +// +// To bump it, copy those files again from a newer commit, set Commit, run +// `go mod tidy` and `go test ./...` in helpers/names, and raise +// CoveredVersion in main.go to the engine release line that commit belongs +// to. TestVectors fails when the copy no longer formats the engine's own test +// vectors as the engine does. +const ( + Source = "https://github.com/dagger/dagger/tree/" + Commit + "/engine/naming" + Commit = "198d001192d3179a8215980e97c766026f2dd0c2" +) diff --git a/helpers/names/naming/testdata/vectors.json b/helpers/names/naming/testdata/vectors.json new file mode 100644 index 00000000..c0026717 --- /dev/null +++ b/helpers/names/naming/testdata/vectors.json @@ -0,0 +1,3119 @@ +[ + { + "input": "HTTPClient", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTP", + "suffix": "", + "capitalized": "Http" + }, + { + "kind": "WORD", + "text": "client", + "suffix": "", + "capitalized": "Client" + } + ], + "formats": { + "CAMEL": "httpClient", + "CAMEL_CAPITALIZED": "httpClient", + "FLAT": "httpclient", + "KEBAB": "http-client", + "PASCAL": "HTTPClient", + "PASCAL_CAPITALIZED": "HttpClient", + "SCREAMING_SNAKE": "HTTP_CLIENT", + "SNAKE": "http_client" + } + }, + { + "input": "httpClient", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTP", + "suffix": "", + "capitalized": "Http" + }, + { + "kind": "WORD", + "text": "client", + "suffix": "", + "capitalized": "Client" + } + ], + "formats": { + "CAMEL": "httpClient", + "CAMEL_CAPITALIZED": "httpClient", + "FLAT": "httpclient", + "KEBAB": "http-client", + "PASCAL": "HTTPClient", + "PASCAL_CAPITALIZED": "HttpClient", + "SCREAMING_SNAKE": "HTTP_CLIENT", + "SNAKE": "http_client" + } + }, + { + "input": "HttpClient", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTP", + "suffix": "", + "capitalized": "Http" + }, + { + "kind": "WORD", + "text": "client", + "suffix": "", + "capitalized": "Client" + } + ], + "formats": { + "CAMEL": "httpClient", + "CAMEL_CAPITALIZED": "httpClient", + "FLAT": "httpclient", + "KEBAB": "http-client", + "PASCAL": "HTTPClient", + "PASCAL_CAPITALIZED": "HttpClient", + "SCREAMING_SNAKE": "HTTP_CLIENT", + "SNAKE": "http_client" + } + }, + { + "input": "http_client", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTP", + "suffix": "", + "capitalized": "Http" + }, + { + "kind": "WORD", + "text": "client", + "suffix": "", + "capitalized": "Client" + } + ], + "formats": { + "CAMEL": "httpClient", + "CAMEL_CAPITALIZED": "httpClient", + "FLAT": "httpclient", + "KEBAB": "http-client", + "PASCAL": "HTTPClient", + "PASCAL_CAPITALIZED": "HttpClient", + "SCREAMING_SNAKE": "HTTP_CLIENT", + "SNAKE": "http_client" + } + }, + { + "input": "HTTP_CLIENT", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTP", + "suffix": "", + "capitalized": "Http" + }, + { + "kind": "WORD", + "text": "client", + "suffix": "", + "capitalized": "Client" + } + ], + "formats": { + "CAMEL": "httpClient", + "CAMEL_CAPITALIZED": "httpClient", + "FLAT": "httpclient", + "KEBAB": "http-client", + "PASCAL": "HTTPClient", + "PASCAL_CAPITALIZED": "HttpClient", + "SCREAMING_SNAKE": "HTTP_CLIENT", + "SNAKE": "http_client" + } + }, + { + "input": "HTTPAPIClient", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTP", + "suffix": "", + "capitalized": "Http" + }, + { + "kind": "ACRONYM", + "text": "API", + "suffix": "", + "capitalized": "Api" + }, + { + "kind": "WORD", + "text": "client", + "suffix": "", + "capitalized": "Client" + } + ], + "formats": { + "CAMEL": "httpAPIClient", + "CAMEL_CAPITALIZED": "httpApiClient", + "FLAT": "httpapiclient", + "KEBAB": "http-api-client", + "PASCAL": "HTTPAPIClient", + "PASCAL_CAPITALIZED": "HttpApiClient", + "SCREAMING_SNAKE": "HTTP_API_CLIENT", + "SNAKE": "http_api_client" + } + }, + { + "input": "LLMContentBlock", + "words": [ + { + "kind": "ACRONYM", + "text": "LLM", + "suffix": "", + "capitalized": "Llm" + }, + { + "kind": "WORD", + "text": "content", + "suffix": "", + "capitalized": "Content" + }, + { + "kind": "WORD", + "text": "block", + "suffix": "", + "capitalized": "Block" + } + ], + "formats": { + "CAMEL": "llmContentBlock", + "CAMEL_CAPITALIZED": "llmContentBlock", + "FLAT": "llmcontentblock", + "KEBAB": "llm-content-block", + "PASCAL": "LLMContentBlock", + "PASCAL_CAPITALIZED": "LlmContentBlock", + "SCREAMING_SNAKE": "LLM_CONTENT_BLOCK", + "SNAKE": "llm_content_block" + } + }, + { + "input": "E2ETest", + "words": [ + { + "kind": "ACRONYM", + "text": "E2E", + "suffix": "", + "capitalized": "E2e" + }, + { + "kind": "WORD", + "text": "test", + "suffix": "", + "capitalized": "Test" + } + ], + "formats": { + "CAMEL": "e2eTest", + "CAMEL_CAPITALIZED": "e2eTest", + "FLAT": "e2etest", + "KEBAB": "e2e-test", + "PASCAL": "E2ETest", + "PASCAL_CAPITALIZED": "E2eTest", + "SCREAMING_SNAKE": "E2E_TEST", + "SNAKE": "e2e_test" + } + }, + { + "input": "e2e_test", + "words": [ + { + "kind": "ACRONYM", + "text": "E2E", + "suffix": "", + "capitalized": "E2e" + }, + { + "kind": "WORD", + "text": "test", + "suffix": "", + "capitalized": "Test" + } + ], + "formats": { + "CAMEL": "e2eTest", + "CAMEL_CAPITALIZED": "e2eTest", + "FLAT": "e2etest", + "KEBAB": "e2e-test", + "PASCAL": "E2ETest", + "PASCAL_CAPITALIZED": "E2eTest", + "SCREAMING_SNAKE": "E2E_TEST", + "SNAKE": "e2e_test" + } + }, + { + "input": "prerequisiteSHAs", + "words": [ + { + "kind": "WORD", + "text": "prerequisite", + "suffix": "", + "capitalized": "Prerequisite" + }, + { + "kind": "ACRONYM", + "text": "SHA", + "suffix": "s", + "capitalized": "Sha" + } + ], + "formats": { + "CAMEL": "prerequisiteSHAs", + "CAMEL_CAPITALIZED": "prerequisiteShas", + "FLAT": "prerequisiteshas", + "KEBAB": "prerequisite-shas", + "PASCAL": "PrerequisiteSHAs", + "PASCAL_CAPITALIZED": "PrerequisiteShas", + "SCREAMING_SNAKE": "PREREQUISITE_SHAS", + "SNAKE": "prerequisite_shas" + } + }, + { + "input": "experimentalWithAllGPUs", + "words": [ + { + "kind": "WORD", + "text": "experimental", + "suffix": "", + "capitalized": "Experimental" + }, + { + "kind": "WORD", + "text": "with", + "suffix": "", + "capitalized": "With" + }, + { + "kind": "WORD", + "text": "all", + "suffix": "", + "capitalized": "All" + }, + { + "kind": "ACRONYM", + "text": "GPU", + "suffix": "s", + "capitalized": "Gpu" + } + ], + "formats": { + "CAMEL": "experimentalWithAllGPUs", + "CAMEL_CAPITALIZED": "experimentalWithAllGpus", + "FLAT": "experimentalwithallgpus", + "KEBAB": "experimental-with-all-gpus", + "PASCAL": "ExperimentalWithAllGPUs", + "PASCAL_CAPITALIZED": "ExperimentalWithAllGpus", + "SCREAMING_SNAKE": "EXPERIMENTAL_WITH_ALL_GPUS", + "SNAKE": "experimental_with_all_gpus" + } + }, + { + "input": "userIds", + "words": [ + { + "kind": "WORD", + "text": "user", + "suffix": "", + "capitalized": "User" + }, + { + "kind": "ACRONYM", + "text": "ID", + "suffix": "s", + "capitalized": "Id" + } + ], + "formats": { + "CAMEL": "userIDs", + "CAMEL_CAPITALIZED": "userIds", + "FLAT": "userids", + "KEBAB": "user-ids", + "PASCAL": "UserIDs", + "PASCAL_CAPITALIZED": "UserIds", + "SCREAMING_SNAKE": "USER_IDS", + "SNAKE": "user_ids" + } + }, + { + "input": "listPRs", + "words": [ + { + "kind": "WORD", + "text": "list", + "suffix": "", + "capitalized": "List" + }, + { + "kind": "ACRONYM", + "text": "PR", + "suffix": "s", + "capitalized": "Pr" + } + ], + "formats": { + "CAMEL": "listPRs", + "CAMEL_CAPITALIZED": "listPrs", + "FLAT": "listprs", + "KEBAB": "list-prs", + "PASCAL": "ListPRs", + "PASCAL_CAPITALIZED": "ListPrs", + "SCREAMING_SNAKE": "LIST_PRS", + "SNAKE": "list_prs" + } + }, + { + "input": "IPv6Address", + "words": [ + { + "kind": "TERM", + "text": "IPv6", + "suffix": "", + "capitalized": "Ipv6" + }, + { + "kind": "WORD", + "text": "address", + "suffix": "", + "capitalized": "Address" + } + ], + "formats": { + "CAMEL": "ipv6Address", + "CAMEL_CAPITALIZED": "ipv6Address", + "FLAT": "ipv6address", + "KEBAB": "ipv6-address", + "PASCAL": "IPv6Address", + "PASCAL_CAPITALIZED": "Ipv6Address", + "SCREAMING_SNAKE": "IPV6_ADDRESS", + "SNAKE": "ipv6_address" + } + }, + { + "input": "ipv6_address", + "words": [ + { + "kind": "TERM", + "text": "IPv6", + "suffix": "", + "capitalized": "Ipv6" + }, + { + "kind": "WORD", + "text": "address", + "suffix": "", + "capitalized": "Address" + } + ], + "formats": { + "CAMEL": "ipv6Address", + "CAMEL_CAPITALIZED": "ipv6Address", + "FLAT": "ipv6address", + "KEBAB": "ipv6-address", + "PASCAL": "IPv6Address", + "PASCAL_CAPITALIZED": "Ipv6Address", + "SCREAMING_SNAKE": "IPV6_ADDRESS", + "SNAKE": "ipv6_address" + } + }, + { + "input": "OAuth2Token", + "words": [ + { + "kind": "TERM", + "text": "OAuth", + "suffix": "2", + "capitalized": "Oauth" + }, + { + "kind": "WORD", + "text": "token", + "suffix": "", + "capitalized": "Token" + } + ], + "formats": { + "CAMEL": "oauth2Token", + "CAMEL_CAPITALIZED": "oauth2Token", + "FLAT": "oauth2token", + "KEBAB": "oauth2-token", + "PASCAL": "OAuth2Token", + "PASCAL_CAPITALIZED": "Oauth2Token", + "SCREAMING_SNAKE": "OAUTH2_TOKEN", + "SNAKE": "oauth2_token" + } + }, + { + "input": "oauth2_token", + "words": [ + { + "kind": "TERM", + "text": "OAuth", + "suffix": "2", + "capitalized": "Oauth" + }, + { + "kind": "WORD", + "text": "token", + "suffix": "", + "capitalized": "Token" + } + ], + "formats": { + "CAMEL": "oauth2Token", + "CAMEL_CAPITALIZED": "oauth2Token", + "FLAT": "oauth2token", + "KEBAB": "oauth2-token", + "PASCAL": "OAuth2Token", + "PASCAL_CAPITALIZED": "Oauth2Token", + "SCREAMING_SNAKE": "OAUTH2_TOKEN", + "SNAKE": "oauth2_token" + } + }, + { + "input": "GitHubRepo", + "words": [ + { + "kind": "TERM", + "text": "GitHub", + "suffix": "", + "capitalized": "GitHub" + }, + { + "kind": "WORD", + "text": "repo", + "suffix": "", + "capitalized": "Repo" + } + ], + "formats": { + "CAMEL": "githubRepo", + "CAMEL_CAPITALIZED": "githubRepo", + "FLAT": "githubrepo", + "KEBAB": "github-repo", + "PASCAL": "GitHubRepo", + "PASCAL_CAPITALIZED": "GitHubRepo", + "SCREAMING_SNAKE": "GITHUB_REPO", + "SNAKE": "github_repo" + } + }, + { + "input": "github_repo", + "words": [ + { + "kind": "TERM", + "text": "GitHub", + "suffix": "", + "capitalized": "GitHub" + }, + { + "kind": "WORD", + "text": "repo", + "suffix": "", + "capitalized": "Repo" + } + ], + "formats": { + "CAMEL": "githubRepo", + "CAMEL_CAPITALIZED": "githubRepo", + "FLAT": "githubrepo", + "KEBAB": "github-repo", + "PASCAL": "GitHubRepo", + "PASCAL_CAPITALIZED": "GitHubRepo", + "SCREAMING_SNAKE": "GITHUB_REPO", + "SNAKE": "github_repo" + } + }, + { + "input": "iOSApp", + "words": [ + { + "kind": "TERM", + "text": "iOS", + "suffix": "", + "capitalized": "Ios" + }, + { + "kind": "WORD", + "text": "app", + "suffix": "", + "capitalized": "App" + } + ], + "formats": { + "CAMEL": "iosApp", + "CAMEL_CAPITALIZED": "iosApp", + "FLAT": "iosapp", + "KEBAB": "ios-app", + "PASCAL": "IOSApp", + "PASCAL_CAPITALIZED": "IosApp", + "SCREAMING_SNAKE": "IOS_APP", + "SNAKE": "ios_app" + } + }, + { + "input": "macOSBuild", + "words": [ + { + "kind": "TERM", + "text": "macOS", + "suffix": "", + "capitalized": "MacOS" + }, + { + "kind": "WORD", + "text": "build", + "suffix": "", + "capitalized": "Build" + } + ], + "formats": { + "CAMEL": "macosBuild", + "CAMEL_CAPITALIZED": "macosBuild", + "FLAT": "macosbuild", + "KEBAB": "macos-build", + "PASCAL": "MacOSBuild", + "PASCAL_CAPITALIZED": "MacOSBuild", + "SCREAMING_SNAKE": "MACOS_BUILD", + "SNAKE": "macos_build" + } + }, + { + "input": "gRPCServer", + "words": [ + { + "kind": "TERM", + "text": "gRPC", + "suffix": "", + "capitalized": "Grpc" + }, + { + "kind": "WORD", + "text": "server", + "suffix": "", + "capitalized": "Server" + } + ], + "formats": { + "CAMEL": "grpcServer", + "CAMEL_CAPITALIZED": "grpcServer", + "FLAT": "grpcserver", + "KEBAB": "grpc-server", + "PASCAL": "GRPCServer", + "PASCAL_CAPITALIZED": "GrpcServer", + "SCREAMING_SNAKE": "GRPC_SERVER", + "SNAKE": "grpc_server" + } + }, + { + "input": "Get3DModel", + "words": [ + { + "kind": "WORD", + "text": "get", + "suffix": "", + "capitalized": "Get" + }, + { + "kind": "ACRONYM", + "text": "3D", + "suffix": "", + "capitalized": "3D" + }, + { + "kind": "WORD", + "text": "model", + "suffix": "", + "capitalized": "Model" + } + ], + "formats": { + "CAMEL": "get3DModel", + "CAMEL_CAPITALIZED": "get3DModel", + "FLAT": "get3dmodel", + "KEBAB": "get-3d-model", + "PASCAL": "Get3DModel", + "PASCAL_CAPITALIZED": "Get3DModel", + "SCREAMING_SNAKE": "GET_3D_MODEL", + "SNAKE": "get_3d_model" + } + }, + { + "input": "get3d_model", + "words": [ + { + "kind": "WORD", + "text": "get", + "suffix": "", + "capitalized": "Get" + }, + { + "kind": "ACRONYM", + "text": "3D", + "suffix": "", + "capitalized": "3D" + }, + { + "kind": "WORD", + "text": "model", + "suffix": "", + "capitalized": "Model" + } + ], + "formats": { + "CAMEL": "get3DModel", + "CAMEL_CAPITALIZED": "get3DModel", + "FLAT": "get3dmodel", + "KEBAB": "get-3d-model", + "PASCAL": "Get3DModel", + "PASCAL_CAPITALIZED": "Get3DModel", + "SCREAMING_SNAKE": "GET_3D_MODEL", + "SNAKE": "get_3d_model" + } + }, + { + "input": "Base64URLEncode", + "words": [ + { + "kind": "WORD", + "text": "base64", + "suffix": "", + "capitalized": "Base64" + }, + { + "kind": "ACRONYM", + "text": "URL", + "suffix": "", + "capitalized": "Url" + }, + { + "kind": "WORD", + "text": "encode", + "suffix": "", + "capitalized": "Encode" + } + ], + "formats": { + "CAMEL": "base64URLEncode", + "CAMEL_CAPITALIZED": "base64UrlEncode", + "FLAT": "base64urlencode", + "KEBAB": "base64-url-encode", + "PASCAL": "Base64URLEncode", + "PASCAL_CAPITALIZED": "Base64UrlEncode", + "SCREAMING_SNAKE": "BASE64_URL_ENCODE", + "SNAKE": "base64_url_encode" + } + }, + { + "input": "Win32API", + "words": [ + { + "kind": "WORD", + "text": "win32", + "suffix": "", + "capitalized": "Win32" + }, + { + "kind": "ACRONYM", + "text": "API", + "suffix": "", + "capitalized": "Api" + } + ], + "formats": { + "CAMEL": "win32API", + "CAMEL_CAPITALIZED": "win32Api", + "FLAT": "win32api", + "KEBAB": "win32-api", + "PASCAL": "Win32API", + "PASCAL_CAPITALIZED": "Win32Api", + "SCREAMING_SNAKE": "WIN32_API", + "SNAKE": "win32_api" + } + }, + { + "input": "HTTP2Server", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTP", + "suffix": "2", + "capitalized": "Http" + }, + { + "kind": "WORD", + "text": "server", + "suffix": "", + "capitalized": "Server" + } + ], + "formats": { + "CAMEL": "http2Server", + "CAMEL_CAPITALIZED": "http2Server", + "FLAT": "http2server", + "KEBAB": "http2-server", + "PASCAL": "HTTP2Server", + "PASCAL_CAPITALIZED": "Http2Server", + "SCREAMING_SNAKE": "HTTP2_SERVER", + "SNAKE": "http2_server" + } + }, + { + "input": "Sha256Sum", + "words": [ + { + "kind": "ACRONYM", + "text": "SHA", + "suffix": "256", + "capitalized": "Sha" + }, + { + "kind": "WORD", + "text": "sum", + "suffix": "", + "capitalized": "Sum" + } + ], + "formats": { + "CAMEL": "sha256Sum", + "CAMEL_CAPITALIZED": "sha256Sum", + "FLAT": "sha256sum", + "KEBAB": "sha256-sum", + "PASCAL": "SHA256Sum", + "PASCAL_CAPITALIZED": "Sha256Sum", + "SCREAMING_SNAKE": "SHA256_SUM", + "SNAKE": "sha256_sum" + } + }, + { + "input": "md5sum", + "words": [ + { + "kind": "ACRONYM", + "text": "MD5", + "suffix": "", + "capitalized": "Md5" + }, + { + "kind": "WORD", + "text": "sum", + "suffix": "", + "capitalized": "Sum" + } + ], + "formats": { + "CAMEL": "md5Sum", + "CAMEL_CAPITALIZED": "md5Sum", + "FLAT": "md5sum", + "KEBAB": "md5-sum", + "PASCAL": "MD5Sum", + "PASCAL_CAPITALIZED": "Md5Sum", + "SCREAMING_SNAKE": "MD5_SUM", + "SNAKE": "md5_sum" + } + }, + { + "input": "S3Bucket", + "words": [ + { + "kind": "WORD", + "text": "s3", + "suffix": "", + "capitalized": "S3" + }, + { + "kind": "WORD", + "text": "bucket", + "suffix": "", + "capitalized": "Bucket" + } + ], + "formats": { + "CAMEL": "s3Bucket", + "CAMEL_CAPITALIZED": "s3Bucket", + "FLAT": "s3bucket", + "KEBAB": "s3-bucket", + "PASCAL": "S3Bucket", + "PASCAL_CAPITALIZED": "S3Bucket", + "SCREAMING_SNAKE": "S3_BUCKET", + "SNAKE": "s3_bucket" + } + }, + { + "input": "V1Beta1Foo", + "words": [ + { + "kind": "WORD", + "text": "v1", + "suffix": "", + "capitalized": "V1" + }, + { + "kind": "WORD", + "text": "beta1", + "suffix": "", + "capitalized": "Beta1" + }, + { + "kind": "WORD", + "text": "foo", + "suffix": "", + "capitalized": "Foo" + } + ], + "formats": { + "CAMEL": "v1Beta1Foo", + "CAMEL_CAPITALIZED": "v1Beta1Foo", + "FLAT": "v1beta1foo", + "KEBAB": "v1-beta1-foo", + "PASCAL": "V1Beta1Foo", + "PASCAL_CAPITALIZED": "V1Beta1Foo", + "SCREAMING_SNAKE": "V1_BETA1_FOO", + "SNAKE": "v1_beta1_foo" + } + }, + { + "input": "ModuleAOverlay", + "words": [ + { + "kind": "WORD", + "text": "module", + "suffix": "", + "capitalized": "Module" + }, + { + "kind": "WORD", + "text": "a", + "suffix": "", + "capitalized": "A" + }, + { + "kind": "WORD", + "text": "overlay", + "suffix": "", + "capitalized": "Overlay" + } + ], + "formats": { + "CAMEL": "moduleAOverlay", + "CAMEL_CAPITALIZED": "moduleAOverlay", + "FLAT": "moduleaoverlay", + "KEBAB": "module-a-overlay", + "PASCAL": "ModuleAOverlay", + "PASCAL_CAPITALIZED": "ModuleAOverlay", + "SCREAMING_SNAKE": "MODULE_A_OVERLAY", + "SNAKE": "module_a_overlay" + } + }, + { + "input": "IOStream", + "words": [ + { + "kind": "ACRONYM", + "text": "IO", + "suffix": "", + "capitalized": "Io" + }, + { + "kind": "WORD", + "text": "stream", + "suffix": "", + "capitalized": "Stream" + } + ], + "formats": { + "CAMEL": "ioStream", + "CAMEL_CAPITALIZED": "ioStream", + "FLAT": "iostream", + "KEBAB": "io-stream", + "PASCAL": "IOStream", + "PASCAL_CAPITALIZED": "IoStream", + "SCREAMING_SNAKE": "IO_STREAM", + "SNAKE": "io_stream" + } + }, + { + "input": "Capital", + "words": [ + { + "kind": "WORD", + "text": "capital", + "suffix": "", + "capitalized": "Capital" + } + ], + "formats": { + "CAMEL": "capital", + "CAMEL_CAPITALIZED": "capital", + "FLAT": "capital", + "KEBAB": "capital", + "PASCAL": "Capital", + "PASCAL_CAPITALIZED": "Capital", + "SCREAMING_SNAKE": "CAPITAL", + "SNAKE": "capital" + } + }, + { + "input": "Identity", + "words": [ + { + "kind": "WORD", + "text": "identity", + "suffix": "", + "capitalized": "Identity" + } + ], + "formats": { + "CAMEL": "identity", + "CAMEL_CAPITALIZED": "identity", + "FLAT": "identity", + "KEBAB": "identity", + "PASCAL": "Identity", + "PASCAL_CAPITALIZED": "Identity", + "SCREAMING_SNAKE": "IDENTITY", + "SNAKE": "identity" + } + }, + { + "input": "HTTPXClient", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTPX", + "suffix": "", + "capitalized": "Httpx" + }, + { + "kind": "WORD", + "text": "client", + "suffix": "", + "capitalized": "Client" + } + ], + "formats": { + "CAMEL": "httpxClient", + "CAMEL_CAPITALIZED": "httpxClient", + "FLAT": "httpxclient", + "KEBAB": "httpx-client", + "PASCAL": "HTTPXClient", + "PASCAL_CAPITALIZED": "HttpxClient", + "SCREAMING_SNAKE": "HTTPX_CLIENT", + "SNAKE": "httpx_client" + } + }, + { + "input": "httpx_client", + "words": [ + { + "kind": "WORD", + "text": "httpx", + "suffix": "", + "capitalized": "Httpx" + }, + { + "kind": "WORD", + "text": "client", + "suffix": "", + "capitalized": "Client" + } + ], + "formats": { + "CAMEL": "httpxClient", + "CAMEL_CAPITALIZED": "httpxClient", + "FLAT": "httpxclient", + "KEBAB": "httpx-client", + "PASCAL": "HttpxClient", + "PASCAL_CAPITALIZED": "HttpxClient", + "SCREAMING_SNAKE": "HTTPX_CLIENT", + "SNAKE": "httpx_client" + } + }, + { + "input": "E2EAPI", + "words": [ + { + "kind": "ACRONYM", + "text": "E2E", + "suffix": "", + "capitalized": "E2e" + }, + { + "kind": "ACRONYM", + "text": "API", + "suffix": "", + "capitalized": "Api" + } + ], + "formats": { + "CAMEL": "e2eAPI", + "CAMEL_CAPITALIZED": "e2eApi", + "FLAT": "e2eapi", + "KEBAB": "e2e-api", + "PASCAL": "E2EAPI", + "PASCAL_CAPITALIZED": "E2eApi", + "SCREAMING_SNAKE": "E2E_API", + "SNAKE": "e2e_api" + } + }, + { + "input": "JSONAPI", + "words": [ + { + "kind": "ACRONYM", + "text": "JSON", + "suffix": "", + "capitalized": "Json" + }, + { + "kind": "ACRONYM", + "text": "API", + "suffix": "", + "capitalized": "Api" + } + ], + "formats": { + "CAMEL": "jsonAPI", + "CAMEL_CAPITALIZED": "jsonApi", + "FLAT": "jsonapi", + "KEBAB": "json-api", + "PASCAL": "JSONAPI", + "PASCAL_CAPITALIZED": "JsonApi", + "SCREAMING_SNAKE": "JSON_API", + "SNAKE": "json_api" + } + }, + { + "input": "HTMLURL", + "words": [ + { + "kind": "ACRONYM", + "text": "HTML", + "suffix": "", + "capitalized": "Html" + }, + { + "kind": "ACRONYM", + "text": "URL", + "suffix": "", + "capitalized": "Url" + } + ], + "formats": { + "CAMEL": "htmlURL", + "CAMEL_CAPITALIZED": "htmlUrl", + "FLAT": "htmlurl", + "KEBAB": "html-url", + "PASCAL": "HTMLURL", + "PASCAL_CAPITALIZED": "HtmlUrl", + "SCREAMING_SNAKE": "HTML_URL", + "SNAKE": "html_url" + } + }, + { + "input": "HTTPX_CLIENT", + "words": [ + { + "kind": "WORD", + "text": "httpx", + "suffix": "", + "capitalized": "Httpx" + }, + { + "kind": "WORD", + "text": "client", + "suffix": "", + "capitalized": "Client" + } + ], + "formats": { + "CAMEL": "httpxClient", + "CAMEL_CAPITALIZED": "httpxClient", + "FLAT": "httpxclient", + "KEBAB": "httpx-client", + "PASCAL": "HttpxClient", + "PASCAL_CAPITALIZED": "HttpxClient", + "SCREAMING_SNAKE": "HTTPX_CLIENT", + "SNAKE": "httpx_client" + } + }, + { + "input": "APIv1", + "words": [ + { + "kind": "ACRONYM", + "text": "API", + "suffix": "", + "capitalized": "Api" + }, + { + "kind": "WORD", + "text": "v1", + "suffix": "", + "capitalized": "V1" + } + ], + "formats": { + "CAMEL": "apiV1", + "CAMEL_CAPITALIZED": "apiV1", + "FLAT": "apiv1", + "KEBAB": "api-v1", + "PASCAL": "APIV1", + "PASCAL_CAPITALIZED": "ApiV1", + "SCREAMING_SNAKE": "API_V1", + "SNAKE": "api_v1" + } + }, + { + "input": "UUIDV7", + "words": [ + { + "kind": "ACRONYM", + "text": "UUID", + "suffix": "", + "capitalized": "Uuid" + }, + { + "kind": "WORD", + "text": "v7", + "suffix": "", + "capitalized": "V7" + } + ], + "formats": { + "CAMEL": "uuidV7", + "CAMEL_CAPITALIZED": "uuidV7", + "FLAT": "uuidv7", + "KEBAB": "uuid-v7", + "PASCAL": "UUIDV7", + "PASCAL_CAPITALIZED": "UuidV7", + "SCREAMING_SNAKE": "UUID_V7", + "SNAKE": "uuid_v7" + } + }, + { + "input": "JSONV2Schema", + "words": [ + { + "kind": "ACRONYM", + "text": "JSON", + "suffix": "", + "capitalized": "Json" + }, + { + "kind": "WORD", + "text": "v2", + "suffix": "", + "capitalized": "V2" + }, + { + "kind": "WORD", + "text": "schema", + "suffix": "", + "capitalized": "Schema" + } + ], + "formats": { + "CAMEL": "jsonV2Schema", + "CAMEL_CAPITALIZED": "jsonV2Schema", + "FLAT": "jsonv2schema", + "KEBAB": "json-v2-schema", + "PASCAL": "JSONV2Schema", + "PASCAL_CAPITALIZED": "JsonV2Schema", + "SCREAMING_SNAKE": "JSON_V2_SCHEMA", + "SNAKE": "json_v2_schema" + } + }, + { + "input": "json_v2_schema", + "words": [ + { + "kind": "ACRONYM", + "text": "JSON", + "suffix": "", + "capitalized": "Json" + }, + { + "kind": "WORD", + "text": "v2", + "suffix": "", + "capitalized": "V2" + }, + { + "kind": "WORD", + "text": "schema", + "suffix": "", + "capitalized": "Schema" + } + ], + "formats": { + "CAMEL": "jsonV2Schema", + "CAMEL_CAPITALIZED": "jsonV2Schema", + "FLAT": "jsonv2schema", + "KEBAB": "json-v2-schema", + "PASCAL": "JSONV2Schema", + "PASCAL_CAPITALIZED": "JsonV2Schema", + "SCREAMING_SNAKE": "JSON_V2_SCHEMA", + "SNAKE": "json_v2_schema" + } + }, + { + "input": "apiS3Bucket", + "words": [ + { + "kind": "ACRONYM", + "text": "API", + "suffix": "", + "capitalized": "Api" + }, + { + "kind": "WORD", + "text": "s3", + "suffix": "", + "capitalized": "S3" + }, + { + "kind": "WORD", + "text": "bucket", + "suffix": "", + "capitalized": "Bucket" + } + ], + "formats": { + "CAMEL": "apiS3Bucket", + "CAMEL_CAPITALIZED": "apiS3Bucket", + "FLAT": "apis3bucket", + "KEBAB": "api-s3-bucket", + "PASCAL": "APIS3Bucket", + "PASCAL_CAPITALIZED": "ApiS3Bucket", + "SCREAMING_SNAKE": "API_S3_BUCKET", + "SNAKE": "api_s3_bucket" + } + }, + { + "input": "HTTP2s", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTP", + "suffix": "2s", + "capitalized": "Http" + } + ], + "formats": { + "CAMEL": "http2s", + "CAMEL_CAPITALIZED": "http2s", + "FLAT": "http2s", + "KEBAB": "http2s", + "PASCAL": "HTTP2s", + "PASCAL_CAPITALIZED": "Http2s", + "SCREAMING_SNAKE": "HTTP2S", + "SNAKE": "http2s" + } + }, + { + "input": "SHA256s", + "words": [ + { + "kind": "ACRONYM", + "text": "SHA", + "suffix": "256s", + "capitalized": "Sha" + } + ], + "formats": { + "CAMEL": "sha256s", + "CAMEL_CAPITALIZED": "sha256s", + "FLAT": "sha256s", + "KEBAB": "sha256s", + "PASCAL": "SHA256s", + "PASCAL_CAPITALIZED": "Sha256s", + "SCREAMING_SNAKE": "SHA256S", + "SNAKE": "sha256s" + } + }, + { + "input": "IDsFoo", + "words": [ + { + "kind": "ACRONYM", + "text": "ID", + "suffix": "s", + "capitalized": "Id" + }, + { + "kind": "WORD", + "text": "foo", + "suffix": "", + "capitalized": "Foo" + } + ], + "formats": { + "CAMEL": "idsFoo", + "CAMEL_CAPITALIZED": "idsFoo", + "FLAT": "idsfoo", + "KEBAB": "ids-foo", + "PASCAL": "IDsFoo", + "PASCAL_CAPITALIZED": "IdsFoo", + "SCREAMING_SNAKE": "IDS_FOO", + "SNAKE": "ids_foo" + } + }, + { + "input": "HTTPSettings", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTP", + "suffix": "", + "capitalized": "Http" + }, + { + "kind": "WORD", + "text": "settings", + "suffix": "", + "capitalized": "Settings" + } + ], + "formats": { + "CAMEL": "httpSettings", + "CAMEL_CAPITALIZED": "httpSettings", + "FLAT": "httpsettings", + "KEBAB": "http-settings", + "PASCAL": "HTTPSettings", + "PASCAL_CAPITALIZED": "HttpSettings", + "SCREAMING_SNAKE": "HTTP_SETTINGS", + "SNAKE": "http_settings" + } + }, + { + "input": "HTTPSServer", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTPS", + "suffix": "", + "capitalized": "Https" + }, + { + "kind": "WORD", + "text": "server", + "suffix": "", + "capitalized": "Server" + } + ], + "formats": { + "CAMEL": "httpsServer", + "CAMEL_CAPITALIZED": "httpsServer", + "FLAT": "httpsserver", + "KEBAB": "https-server", + "PASCAL": "HTTPSServer", + "PASCAL_CAPITALIZED": "HttpsServer", + "SCREAMING_SNAKE": "HTTPS_SERVER", + "SNAKE": "https_server" + } + }, + { + "input": "GetAs", + "words": [ + { + "kind": "WORD", + "text": "get", + "suffix": "", + "capitalized": "Get" + }, + { + "kind": "WORD", + "text": "as", + "suffix": "", + "capitalized": "As" + } + ], + "formats": { + "CAMEL": "getAs", + "CAMEL_CAPITALIZED": "getAs", + "FLAT": "getas", + "KEBAB": "get-as", + "PASCAL": "GetAs", + "PASCAL_CAPITALIZED": "GetAs", + "SCREAMING_SNAKE": "GET_AS", + "SNAKE": "get_as" + } + }, + { + "input": "MyAPIsList", + "words": [ + { + "kind": "WORD", + "text": "my", + "suffix": "", + "capitalized": "My" + }, + { + "kind": "ACRONYM", + "text": "API", + "suffix": "s", + "capitalized": "Api" + }, + { + "kind": "WORD", + "text": "list", + "suffix": "", + "capitalized": "List" + } + ], + "formats": { + "CAMEL": "myAPIsList", + "CAMEL_CAPITALIZED": "myApisList", + "FLAT": "myapislist", + "KEBAB": "my-apis-list", + "PASCAL": "MyAPIsList", + "PASCAL_CAPITALIZED": "MyApisList", + "SCREAMING_SNAKE": "MY_APIS_LIST", + "SNAKE": "my_apis_list" + } + }, + { + "input": "ios", + "words": [ + { + "kind": "TERM", + "text": "iOS", + "suffix": "", + "capitalized": "Ios" + } + ], + "formats": { + "CAMEL": "ios", + "CAMEL_CAPITALIZED": "ios", + "FLAT": "ios", + "KEBAB": "ios", + "PASCAL": "IOS", + "PASCAL_CAPITALIZED": "Ios", + "SCREAMING_SNAKE": "IOS", + "SNAKE": "ios" + } + }, + { + "input": "https", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTPS", + "suffix": "", + "capitalized": "Https" + } + ], + "formats": { + "CAMEL": "https", + "CAMEL_CAPITALIZED": "https", + "FLAT": "https", + "KEBAB": "https", + "PASCAL": "HTTPS", + "PASCAL_CAPITALIZED": "Https", + "SCREAMING_SNAKE": "HTTPS", + "SNAKE": "https" + } + }, + { + "input": "3D", + "words": [ + { + "kind": "ACRONYM", + "text": "3D", + "suffix": "", + "capitalized": "3D" + } + ], + "formats": { + "CAMEL": "3d", + "CAMEL_CAPITALIZED": "3d", + "FLAT": "3d", + "KEBAB": "3d", + "PASCAL": "3D", + "PASCAL_CAPITALIZED": "3D", + "SCREAMING_SNAKE": "3D", + "SNAKE": "3d" + } + }, + { + "input": "123Foo", + "words": [ + { + "kind": "WORD", + "text": "123", + "suffix": "", + "capitalized": "123" + }, + { + "kind": "WORD", + "text": "foo", + "suffix": "", + "capitalized": "Foo" + } + ], + "formats": { + "CAMEL": "123Foo", + "CAMEL_CAPITALIZED": "123Foo", + "FLAT": "123foo", + "KEBAB": "123-foo", + "PASCAL": "123Foo", + "PASCAL_CAPITALIZED": "123Foo", + "SCREAMING_SNAKE": "123_FOO", + "SNAKE": "123_foo" + } + }, + { + "input": "foo_2_bar", + "words": [ + { + "kind": "WORD", + "text": "foo2", + "suffix": "", + "capitalized": "Foo2" + }, + { + "kind": "WORD", + "text": "bar", + "suffix": "", + "capitalized": "Bar" + } + ], + "formats": { + "CAMEL": "foo2Bar", + "CAMEL_CAPITALIZED": "foo2Bar", + "FLAT": "foo2bar", + "KEBAB": "foo2-bar", + "PASCAL": "Foo2Bar", + "PASCAL_CAPITALIZED": "Foo2Bar", + "SCREAMING_SNAKE": "FOO2_BAR", + "SNAKE": "foo2_bar" + } + }, + { + "input": "utf8_string", + "words": [ + { + "kind": "ACRONYM", + "text": "UTF8", + "suffix": "", + "capitalized": "Utf8" + }, + { + "kind": "WORD", + "text": "string", + "suffix": "", + "capitalized": "String" + } + ], + "formats": { + "CAMEL": "utf8String", + "CAMEL_CAPITALIZED": "utf8String", + "FLAT": "utf8string", + "KEBAB": "utf8-string", + "PASCAL": "UTF8String", + "PASCAL_CAPITALIZED": "Utf8String", + "SCREAMING_SNAKE": "UTF8_STRING", + "SNAKE": "utf8_string" + } + }, + { + "input": "runE2EAPITest", + "words": [ + { + "kind": "WORD", + "text": "run", + "suffix": "", + "capitalized": "Run" + }, + { + "kind": "ACRONYM", + "text": "E2E", + "suffix": "", + "capitalized": "E2e" + }, + { + "kind": "ACRONYM", + "text": "API", + "suffix": "", + "capitalized": "Api" + }, + { + "kind": "WORD", + "text": "test", + "suffix": "", + "capitalized": "Test" + } + ], + "formats": { + "CAMEL": "runE2EAPITest", + "CAMEL_CAPITALIZED": "runE2eApiTest", + "FLAT": "rune2eapitest", + "KEBAB": "run-e2e-api-test", + "PASCAL": "RunE2EAPITest", + "PASCAL_CAPITALIZED": "RunE2eApiTest", + "SCREAMING_SNAKE": "RUN_E2E_API_TEST", + "SNAKE": "run_e2e_api_test" + } + }, + { + "input": "Get4KStream", + "words": [ + { + "kind": "WORD", + "text": "get4", + "suffix": "", + "capitalized": "Get4" + }, + { + "kind": "WORD", + "text": "k", + "suffix": "", + "capitalized": "K" + }, + { + "kind": "WORD", + "text": "stream", + "suffix": "", + "capitalized": "Stream" + } + ], + "formats": { + "CAMEL": "get4KStream", + "CAMEL_CAPITALIZED": "get4KStream", + "FLAT": "get4kstream", + "KEBAB": "get4-k-stream", + "PASCAL": "Get4KStream", + "PASCAL_CAPITALIZED": "Get4KStream", + "SCREAMING_SNAKE": "GET4_K_STREAM", + "SNAKE": "get4_k_stream" + } + }, + { + "input": "IOx86", + "words": [ + { + "kind": "ACRONYM", + "text": "IO", + "suffix": "", + "capitalized": "Io" + }, + { + "kind": "WORD", + "text": "x86", + "suffix": "", + "capitalized": "X86" + } + ], + "formats": { + "CAMEL": "ioX86", + "CAMEL_CAPITALIZED": "ioX86", + "FLAT": "iox86", + "KEBAB": "io-x86", + "PASCAL": "IOX86", + "PASCAL_CAPITALIZED": "IoX86", + "SCREAMING_SNAKE": "IO_X86", + "SNAKE": "io_x86" + } + }, + { + "input": "APIR2", + "words": [ + { + "kind": "ACRONYM", + "text": "API", + "suffix": "", + "capitalized": "Api" + }, + { + "kind": "WORD", + "text": "r2", + "suffix": "", + "capitalized": "R2" + } + ], + "formats": { + "CAMEL": "apiR2", + "CAMEL_CAPITALIZED": "apiR2", + "FLAT": "apir2", + "KEBAB": "api-r2", + "PASCAL": "APIR2", + "PASCAL_CAPITALIZED": "ApiR2", + "SCREAMING_SNAKE": "API_R2", + "SNAKE": "api_r2" + } + }, + { + "input": "Vp9Codec", + "words": [ + { + "kind": "WORD", + "text": "vp9", + "suffix": "", + "capitalized": "Vp9" + }, + { + "kind": "WORD", + "text": "codec", + "suffix": "", + "capitalized": "Codec" + } + ], + "formats": { + "CAMEL": "vp9Codec", + "CAMEL_CAPITALIZED": "vp9Codec", + "FLAT": "vp9codec", + "KEBAB": "vp9-codec", + "PASCAL": "Vp9Codec", + "PASCAL_CAPITALIZED": "Vp9Codec", + "SCREAMING_SNAKE": "VP9_CODEC", + "SNAKE": "vp9_codec" + } + }, + { + "input": "M3U8", + "words": [ + { + "kind": "WORD", + "text": "m3u8", + "suffix": "", + "capitalized": "M3u8" + } + ], + "formats": { + "CAMEL": "m3u8", + "CAMEL_CAPITALIZED": "m3u8", + "FLAT": "m3u8", + "KEBAB": "m3u8", + "PASCAL": "M3u8", + "PASCAL_CAPITALIZED": "M3u8", + "SCREAMING_SNAKE": "M3U8", + "SNAKE": "m3u8" + } + }, + { + "input": "EC2s", + "words": [ + { + "kind": "ACRONYM", + "text": "EC2", + "suffix": "s", + "capitalized": "Ec2" + } + ], + "formats": { + "CAMEL": "ec2s", + "CAMEL_CAPITALIZED": "ec2s", + "FLAT": "ec2s", + "KEBAB": "ec2s", + "PASCAL": "EC2s", + "PASCAL_CAPITALIZED": "Ec2s", + "SCREAMING_SNAKE": "EC2S", + "SNAKE": "ec2s" + } + }, + { + "input": "APIHTTP2s", + "words": [ + { + "kind": "ACRONYM", + "text": "API", + "suffix": "", + "capitalized": "Api" + }, + { + "kind": "ACRONYM", + "text": "HTTP", + "suffix": "2s", + "capitalized": "Http" + } + ], + "formats": { + "CAMEL": "apiHTTP2s", + "CAMEL_CAPITALIZED": "apiHttp2s", + "FLAT": "apihttp2s", + "KEBAB": "api-http2s", + "PASCAL": "APIHTTP2s", + "PASCAL_CAPITALIZED": "ApiHttp2s", + "SCREAMING_SNAKE": "API_HTTP2S", + "SNAKE": "api_http2s" + } + }, + { + "input": "IDs2", + "words": [ + { + "kind": "ACRONYM", + "text": "ID", + "suffix": "", + "capitalized": "Id" + }, + { + "kind": "WORD", + "text": "s2", + "suffix": "", + "capitalized": "S2" + } + ], + "formats": { + "CAMEL": "idS2", + "CAMEL_CAPITALIZED": "idS2", + "FLAT": "ids2", + "KEBAB": "id-s2", + "PASCAL": "IDS2", + "PASCAL_CAPITALIZED": "IdS2", + "SCREAMING_SNAKE": "ID_S2", + "SNAKE": "id_s2" + } + }, + { + "input": "HTTPAPIS", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTP", + "suffix": "", + "capitalized": "Http" + }, + { + "kind": "ACRONYM", + "text": "API", + "suffix": "s", + "capitalized": "Api" + } + ], + "formats": { + "CAMEL": "httpAPIs", + "CAMEL_CAPITALIZED": "httpApis", + "FLAT": "httpapis", + "KEBAB": "http-apis", + "PASCAL": "HTTPAPIs", + "PASCAL_CAPITALIZED": "HttpApis", + "SCREAMING_SNAKE": "HTTP_APIS", + "SNAKE": "http_apis" + } + }, + { + "input": "MY_HTTPAPI_CLIENT", + "words": [ + { + "kind": "WORD", + "text": "my", + "suffix": "", + "capitalized": "My" + }, + { + "kind": "ACRONYM", + "text": "HTTP", + "suffix": "", + "capitalized": "Http" + }, + { + "kind": "ACRONYM", + "text": "API", + "suffix": "", + "capitalized": "Api" + }, + { + "kind": "WORD", + "text": "client", + "suffix": "", + "capitalized": "Client" + } + ], + "formats": { + "CAMEL": "myHTTPAPIClient", + "CAMEL_CAPITALIZED": "myHttpApiClient", + "FLAT": "myhttpapiclient", + "KEBAB": "my-http-api-client", + "PASCAL": "MyHTTPAPIClient", + "PASCAL_CAPITALIZED": "MyHttpApiClient", + "SCREAMING_SNAKE": "MY_HTTP_API_CLIENT", + "SNAKE": "my_http_api_client" + } + }, + { + "input": "UTF8JSON", + "words": [ + { + "kind": "ACRONYM", + "text": "UTF8", + "suffix": "", + "capitalized": "Utf8" + }, + { + "kind": "ACRONYM", + "text": "JSON", + "suffix": "", + "capitalized": "Json" + } + ], + "formats": { + "CAMEL": "utf8JSON", + "CAMEL_CAPITALIZED": "utf8Json", + "FLAT": "utf8json", + "KEBAB": "utf8-json", + "PASCAL": "UTF8JSON", + "PASCAL_CAPITALIZED": "Utf8Json", + "SCREAMING_SNAKE": "UTF8_JSON", + "SNAKE": "utf8_json" + } + }, + { + "input": "HTTPXAPI", + "words": [ + { + "kind": "WORD", + "text": "httpxapi", + "suffix": "", + "capitalized": "Httpxapi" + } + ], + "formats": { + "CAMEL": "httpxapi", + "CAMEL_CAPITALIZED": "httpxapi", + "FLAT": "httpxapi", + "KEBAB": "httpxapi", + "PASCAL": "Httpxapi", + "PASCAL_CAPITALIZED": "Httpxapi", + "SCREAMING_SNAKE": "HTTPXAPI", + "SNAKE": "httpxapi" + } + }, + { + "input": "httpapi", + "words": [ + { + "kind": "WORD", + "text": "httpapi", + "suffix": "", + "capitalized": "Httpapi" + } + ], + "formats": { + "CAMEL": "httpapi", + "CAMEL_CAPITALIZED": "httpapi", + "FLAT": "httpapi", + "KEBAB": "httpapi", + "PASCAL": "Httpapi", + "PASCAL_CAPITALIZED": "Httpapi", + "SCREAMING_SNAKE": "HTTPAPI", + "SNAKE": "httpapi" + } + }, + { + "input": "HTTPXAPIClient", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTPXAPI", + "suffix": "", + "capitalized": "Httpxapi" + }, + { + "kind": "WORD", + "text": "client", + "suffix": "", + "capitalized": "Client" + } + ], + "formats": { + "CAMEL": "httpxapiClient", + "CAMEL_CAPITALIZED": "httpxapiClient", + "FLAT": "httpxapiclient", + "KEBAB": "httpxapi-client", + "PASCAL": "HTTPXAPIClient", + "PASCAL_CAPITALIZED": "HttpxapiClient", + "SCREAMING_SNAKE": "HTTPXAPI_CLIENT", + "SNAKE": "httpxapi_client" + } + }, + { + "input": "PostgreSQL", + "words": [ + { + "kind": "WORD", + "text": "postgre", + "suffix": "", + "capitalized": "Postgre" + }, + { + "kind": "ACRONYM", + "text": "SQL", + "suffix": "", + "capitalized": "Sql" + } + ], + "formats": { + "CAMEL": "postgreSQL", + "CAMEL_CAPITALIZED": "postgreSql", + "FLAT": "postgresql", + "KEBAB": "postgre-sql", + "PASCAL": "PostgreSQL", + "PASCAL_CAPITALIZED": "PostgreSql", + "SCREAMING_SNAKE": "POSTGRE_SQL", + "SNAKE": "postgre_sql" + } + }, + { + "input": "gRPCAPI", + "words": [ + { + "kind": "WORD", + "text": "g", + "suffix": "", + "capitalized": "G" + }, + { + "kind": "ACRONYM", + "text": "RPC", + "suffix": "", + "capitalized": "Rpc" + }, + { + "kind": "ACRONYM", + "text": "API", + "suffix": "", + "capitalized": "Api" + } + ], + "formats": { + "CAMEL": "gRPCAPI", + "CAMEL_CAPITALIZED": "gRpcApi", + "FLAT": "grpcapi", + "KEBAB": "g-rpc-api", + "PASCAL": "GRPCAPI", + "PASCAL_CAPITALIZED": "GRpcApi", + "SCREAMING_SNAKE": "G_RPC_API", + "SNAKE": "g_rpc_api" + } + }, + { + "input": "iOSSDK", + "words": [ + { + "kind": "WORD", + "text": "i", + "suffix": "", + "capitalized": "I" + }, + { + "kind": "ACRONYM", + "text": "OSSDK", + "suffix": "", + "capitalized": "Ossdk" + } + ], + "formats": { + "CAMEL": "iOSSDK", + "CAMEL_CAPITALIZED": "iOssdk", + "FLAT": "iossdk", + "KEBAB": "i-ossdk", + "PASCAL": "IOSSDK", + "PASCAL_CAPITALIZED": "IOssdk", + "SCREAMING_SNAKE": "I_OSSDK", + "SNAKE": "i_ossdk" + } + }, + { + "input": "foo.bar-baz qux", + "words": [ + { + "kind": "WORD", + "text": "foo", + "suffix": "", + "capitalized": "Foo" + }, + { + "kind": "WORD", + "text": "bar", + "suffix": "", + "capitalized": "Bar" + }, + { + "kind": "WORD", + "text": "baz", + "suffix": "", + "capitalized": "Baz" + }, + { + "kind": "WORD", + "text": "qux", + "suffix": "", + "capitalized": "Qux" + } + ], + "formats": { + "CAMEL": "fooBarBazQux", + "CAMEL_CAPITALIZED": "fooBarBazQux", + "FLAT": "foobarbazqux", + "KEBAB": "foo-bar-baz-qux", + "PASCAL": "FooBarBazQux", + "PASCAL_CAPITALIZED": "FooBarBazQux", + "SCREAMING_SNAKE": "FOO_BAR_BAZ_QUX", + "SNAKE": "foo_bar_baz_qux" + } + }, + { + "input": "__init__", + "words": [ + { + "kind": "WORD", + "text": "init", + "suffix": "", + "capitalized": "Init" + } + ], + "formats": { + "CAMEL": "init", + "CAMEL_CAPITALIZED": "init", + "FLAT": "init", + "KEBAB": "init", + "PASCAL": "Init", + "PASCAL_CAPITALIZED": "Init", + "SCREAMING_SNAKE": "INIT", + "SNAKE": "init" + } + }, + { + "input": "base64", + "words": [ + { + "kind": "WORD", + "text": "base64", + "suffix": "", + "capitalized": "Base64" + } + ], + "formats": { + "CAMEL": "base64", + "CAMEL_CAPITALIZED": "base64", + "FLAT": "base64", + "KEBAB": "base64", + "PASCAL": "Base64", + "PASCAL_CAPITALIZED": "Base64", + "SCREAMING_SNAKE": "BASE64", + "SNAKE": "base64" + } + }, + { + "input": "int32", + "words": [ + { + "kind": "WORD", + "text": "int32", + "suffix": "", + "capitalized": "Int32" + } + ], + "formats": { + "CAMEL": "int32", + "CAMEL_CAPITALIZED": "int32", + "FLAT": "int32", + "KEBAB": "int32", + "PASCAL": "Int32", + "PASCAL_CAPITALIZED": "Int32", + "SCREAMING_SNAKE": "INT32", + "SNAKE": "int32" + } + }, + { + "input": "e2eapi", + "words": [ + { + "kind": "WORD", + "text": "e2eapi", + "suffix": "", + "capitalized": "E2eapi" + } + ], + "formats": { + "CAMEL": "e2eapi", + "CAMEL_CAPITALIZED": "e2eapi", + "FLAT": "e2eapi", + "KEBAB": "e2eapi", + "PASCAL": "E2eapi", + "PASCAL_CAPITALIZED": "E2eapi", + "SCREAMING_SNAKE": "E2EAPI", + "SNAKE": "e2eapi" + } + }, + { + "input": "httpS3", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTPS", + "suffix": "3", + "capitalized": "Https" + } + ], + "formats": { + "CAMEL": "https3", + "CAMEL_CAPITALIZED": "https3", + "FLAT": "https3", + "KEBAB": "https3", + "PASCAL": "HTTPS3", + "PASCAL_CAPITALIZED": "Https3", + "SCREAMING_SNAKE": "HTTPS3", + "SNAKE": "https3" + } + }, + { + "input": "htmlURL", + "words": [ + { + "kind": "ACRONYM", + "text": "HTML", + "suffix": "", + "capitalized": "Html" + }, + { + "kind": "ACRONYM", + "text": "URL", + "suffix": "", + "capitalized": "Url" + } + ], + "formats": { + "CAMEL": "htmlURL", + "CAMEL_CAPITALIZED": "htmlUrl", + "FLAT": "htmlurl", + "KEBAB": "html-url", + "PASCAL": "HTMLURL", + "PASCAL_CAPITALIZED": "HtmlUrl", + "SCREAMING_SNAKE": "HTML_URL", + "SNAKE": "html_url" + } + }, + { + "input": "HTTPAPI", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTP", + "suffix": "", + "capitalized": "Http" + }, + { + "kind": "ACRONYM", + "text": "API", + "suffix": "", + "capitalized": "Api" + } + ], + "formats": { + "CAMEL": "httpAPI", + "CAMEL_CAPITALIZED": "httpApi", + "FLAT": "httpapi", + "KEBAB": "http-api", + "PASCAL": "HTTPAPI", + "PASCAL_CAPITALIZED": "HttpApi", + "SCREAMING_SNAKE": "HTTP_API", + "SNAKE": "http_api" + } + }, + { + "input": "GitHubAPI", + "words": [ + { + "kind": "TERM", + "text": "GitHub", + "suffix": "", + "capitalized": "GitHub" + }, + { + "kind": "ACRONYM", + "text": "API", + "suffix": "", + "capitalized": "Api" + } + ], + "formats": { + "CAMEL": "githubAPI", + "CAMEL_CAPITALIZED": "githubApi", + "FLAT": "githubapi", + "KEBAB": "github-api", + "PASCAL": "GitHubAPI", + "PASCAL_CAPITALIZED": "GitHubApi", + "SCREAMING_SNAKE": "GITHUB_API", + "SNAKE": "github_api" + } + }, + { + "input": "IPv6URL", + "words": [ + { + "kind": "TERM", + "text": "IPv6", + "suffix": "", + "capitalized": "Ipv6" + }, + { + "kind": "ACRONYM", + "text": "URL", + "suffix": "", + "capitalized": "Url" + } + ], + "formats": { + "CAMEL": "ipv6URL", + "CAMEL_CAPITALIZED": "ipv6Url", + "FLAT": "ipv6url", + "KEBAB": "ipv6-url", + "PASCAL": "IPv6URL", + "PASCAL_CAPITALIZED": "Ipv6Url", + "SCREAMING_SNAKE": "IPV6_URL", + "SNAKE": "ipv6_url" + } + }, + { + "input": "sha256URL", + "words": [ + { + "kind": "ACRONYM", + "text": "SHA", + "suffix": "256", + "capitalized": "Sha" + }, + { + "kind": "ACRONYM", + "text": "URL", + "suffix": "", + "capitalized": "Url" + } + ], + "formats": { + "CAMEL": "sha256URL", + "CAMEL_CAPITALIZED": "sha256Url", + "FLAT": "sha256url", + "KEBAB": "sha256-url", + "PASCAL": "SHA256URL", + "PASCAL_CAPITALIZED": "Sha256Url", + "SCREAMING_SNAKE": "SHA256_URL", + "SNAKE": "sha256_url" + } + }, + { + "input": "IDs", + "words": [ + { + "kind": "ACRONYM", + "text": "ID", + "suffix": "s", + "capitalized": "Id" + } + ], + "formats": { + "CAMEL": "ids", + "CAMEL_CAPITALIZED": "ids", + "FLAT": "ids", + "KEBAB": "ids", + "PASCAL": "IDs", + "PASCAL_CAPITALIZED": "Ids", + "SCREAMING_SNAKE": "IDS", + "SNAKE": "ids" + } + }, + { + "input": "GPUsAPI", + "words": [ + { + "kind": "ACRONYM", + "text": "GPU", + "suffix": "s", + "capitalized": "Gpu" + }, + { + "kind": "ACRONYM", + "text": "API", + "suffix": "", + "capitalized": "Api" + } + ], + "formats": { + "CAMEL": "gpusAPI", + "CAMEL_CAPITALIZED": "gpusApi", + "FLAT": "gpusapi", + "KEBAB": "gpus-api", + "PASCAL": "GPUsAPI", + "PASCAL_CAPITALIZED": "GpusApi", + "SCREAMING_SNAKE": "GPUS_API", + "SNAKE": "gpus_api" + } + }, + { + "input": "JSONValue", + "words": [ + { + "kind": "ACRONYM", + "text": "JSON", + "suffix": "", + "capitalized": "Json" + }, + { + "kind": "WORD", + "text": "value", + "suffix": "", + "capitalized": "Value" + } + ], + "formats": { + "CAMEL": "jsonValue", + "CAMEL_CAPITALIZED": "jsonValue", + "FLAT": "jsonvalue", + "KEBAB": "json-value", + "PASCAL": "JSONValue", + "PASCAL_CAPITALIZED": "JsonValue", + "SCREAMING_SNAKE": "JSON_VALUE", + "SNAKE": "json_value" + } + }, + { + "input": "LLMTokenUsage", + "words": [ + { + "kind": "ACRONYM", + "text": "LLM", + "suffix": "", + "capitalized": "Llm" + }, + { + "kind": "WORD", + "text": "token", + "suffix": "", + "capitalized": "Token" + }, + { + "kind": "WORD", + "text": "usage", + "suffix": "", + "capitalized": "Usage" + } + ], + "formats": { + "CAMEL": "llmTokenUsage", + "CAMEL_CAPITALIZED": "llmTokenUsage", + "FLAT": "llmtokenusage", + "KEBAB": "llm-token-usage", + "PASCAL": "LLMTokenUsage", + "PASCAL_CAPITALIZED": "LlmTokenUsage", + "SCREAMING_SNAKE": "LLM_TOKEN_USAGE", + "SNAKE": "llm_token_usage" + } + }, + { + "input": "LLMMessageRole", + "words": [ + { + "kind": "ACRONYM", + "text": "LLM", + "suffix": "", + "capitalized": "Llm" + }, + { + "kind": "WORD", + "text": "message", + "suffix": "", + "capitalized": "Message" + }, + { + "kind": "WORD", + "text": "role", + "suffix": "", + "capitalized": "Role" + } + ], + "formats": { + "CAMEL": "llmMessageRole", + "CAMEL_CAPITALIZED": "llmMessageRole", + "FLAT": "llmmessagerole", + "KEBAB": "llm-message-role", + "PASCAL": "LLMMessageRole", + "PASCAL_CAPITALIZED": "LlmMessageRole", + "SCREAMING_SNAKE": "LLM_MESSAGE_ROLE", + "SNAKE": "llm_message_role" + } + }, + { + "input": "SDKConfig", + "words": [ + { + "kind": "ACRONYM", + "text": "SDK", + "suffix": "", + "capitalized": "Sdk" + }, + { + "kind": "WORD", + "text": "config", + "suffix": "", + "capitalized": "Config" + } + ], + "formats": { + "CAMEL": "sdkConfig", + "CAMEL_CAPITALIZED": "sdkConfig", + "FLAT": "sdkconfig", + "KEBAB": "sdk-config", + "PASCAL": "SDKConfig", + "PASCAL_CAPITALIZED": "SdkConfig", + "SCREAMING_SNAKE": "SDK_CONFIG", + "SNAKE": "sdk_config" + } + }, + { + "input": "HTTPState", + "words": [ + { + "kind": "ACRONYM", + "text": "HTTP", + "suffix": "", + "capitalized": "Http" + }, + { + "kind": "WORD", + "text": "state", + "suffix": "", + "capitalized": "State" + } + ], + "formats": { + "CAMEL": "httpState", + "CAMEL_CAPITALIZED": "httpState", + "FLAT": "httpstate", + "KEBAB": "http-state", + "PASCAL": "HTTPState", + "PASCAL_CAPITALIZED": "HttpState", + "SCREAMING_SNAKE": "HTTP_STATE", + "SNAKE": "http_state" + } + }, + { + "input": "GitRepository", + "words": [ + { + "kind": "WORD", + "text": "git", + "suffix": "", + "capitalized": "Git" + }, + { + "kind": "WORD", + "text": "repository", + "suffix": "", + "capitalized": "Repository" + } + ], + "formats": { + "CAMEL": "gitRepository", + "CAMEL_CAPITALIZED": "gitRepository", + "FLAT": "gitrepository", + "KEBAB": "git-repository", + "PASCAL": "GitRepository", + "PASCAL_CAPITALIZED": "GitRepository", + "SCREAMING_SNAKE": "GIT_REPOSITORY", + "SNAKE": "git_repository" + } + }, + { + "input": "CacheSharingMode", + "words": [ + { + "kind": "WORD", + "text": "cache", + "suffix": "", + "capitalized": "Cache" + }, + { + "kind": "WORD", + "text": "sharing", + "suffix": "", + "capitalized": "Sharing" + }, + { + "kind": "WORD", + "text": "mode", + "suffix": "", + "capitalized": "Mode" + } + ], + "formats": { + "CAMEL": "cacheSharingMode", + "CAMEL_CAPITALIZED": "cacheSharingMode", + "FLAT": "cachesharingmode", + "KEBAB": "cache-sharing-mode", + "PASCAL": "CacheSharingMode", + "PASCAL_CAPITALIZED": "CacheSharingMode", + "SCREAMING_SNAKE": "CACHE_SHARING_MODE", + "SNAKE": "cache_sharing_mode" + } + }, + { + "input": "SHARED", + "words": [ + { + "kind": "WORD", + "text": "shared", + "suffix": "", + "capitalized": "Shared" + } + ], + "formats": { + "CAMEL": "shared", + "CAMEL_CAPITALIZED": "shared", + "FLAT": "shared", + "KEBAB": "shared", + "PASCAL": "Shared", + "PASCAL_CAPITALIZED": "Shared", + "SCREAMING_SNAKE": "SHARED", + "SNAKE": "shared" + } + }, + { + "input": "ImageMediaTypes", + "words": [ + { + "kind": "WORD", + "text": "image", + "suffix": "", + "capitalized": "Image" + }, + { + "kind": "WORD", + "text": "media", + "suffix": "", + "capitalized": "Media" + }, + { + "kind": "WORD", + "text": "types", + "suffix": "", + "capitalized": "Types" + } + ], + "formats": { + "CAMEL": "imageMediaTypes", + "CAMEL_CAPITALIZED": "imageMediaTypes", + "FLAT": "imagemediatypes", + "KEBAB": "image-media-types", + "PASCAL": "ImageMediaTypes", + "PASCAL_CAPITALIZED": "ImageMediaTypes", + "SCREAMING_SNAKE": "IMAGE_MEDIA_TYPES", + "SNAKE": "image_media_types" + } + }, + { + "input": "OCI", + "words": [ + { + "kind": "ACRONYM", + "text": "OCI", + "suffix": "", + "capitalized": "Oci" + } + ], + "formats": { + "CAMEL": "oci", + "CAMEL_CAPITALIZED": "oci", + "FLAT": "oci", + "KEBAB": "oci", + "PASCAL": "OCI", + "PASCAL_CAPITALIZED": "Oci", + "SCREAMING_SNAKE": "OCI", + "SNAKE": "oci" + } + }, + { + "input": "withGPU", + "words": [ + { + "kind": "WORD", + "text": "with", + "suffix": "", + "capitalized": "With" + }, + { + "kind": "ACRONYM", + "text": "GPU", + "suffix": "", + "capitalized": "Gpu" + } + ], + "formats": { + "CAMEL": "withGPU", + "CAMEL_CAPITALIZED": "withGpu", + "FLAT": "withgpu", + "KEBAB": "with-gpu", + "PASCAL": "WithGPU", + "PASCAL_CAPITALIZED": "WithGpu", + "SCREAMING_SNAKE": "WITH_GPU", + "SNAKE": "with_gpu" + } + }, + { + "input": "withMCPServer", + "words": [ + { + "kind": "WORD", + "text": "with", + "suffix": "", + "capitalized": "With" + }, + { + "kind": "ACRONYM", + "text": "MCP", + "suffix": "", + "capitalized": "Mcp" + }, + { + "kind": "WORD", + "text": "server", + "suffix": "", + "capitalized": "Server" + } + ], + "formats": { + "CAMEL": "withMCPServer", + "CAMEL_CAPITALIZED": "withMcpServer", + "FLAT": "withmcpserver", + "KEBAB": "with-mcp-server", + "PASCAL": "WithMCPServer", + "PASCAL_CAPITALIZED": "WithMcpServer", + "SCREAMING_SNAKE": "WITH_MCP_SERVER", + "SNAKE": "with_mcp_server" + } + }, + { + "input": "asJSON", + "words": [ + { + "kind": "WORD", + "text": "as", + "suffix": "", + "capitalized": "As" + }, + { + "kind": "ACRONYM", + "text": "JSON", + "suffix": "", + "capitalized": "Json" + } + ], + "formats": { + "CAMEL": "asJSON", + "CAMEL_CAPITALIZED": "asJson", + "FLAT": "asjson", + "KEBAB": "as-json", + "PASCAL": "AsJSON", + "PASCAL_CAPITALIZED": "AsJson", + "SCREAMING_SNAKE": "AS_JSON", + "SNAKE": "as_json" + } + }, + { + "input": "traceURL", + "words": [ + { + "kind": "WORD", + "text": "trace", + "suffix": "", + "capitalized": "Trace" + }, + { + "kind": "ACRONYM", + "text": "URL", + "suffix": "", + "capitalized": "Url" + } + ], + "formats": { + "CAMEL": "traceURL", + "CAMEL_CAPITALIZED": "traceUrl", + "FLAT": "traceurl", + "KEBAB": "trace-url", + "PASCAL": "TraceURL", + "PASCAL_CAPITALIZED": "TraceUrl", + "SCREAMING_SNAKE": "TRACE_URL", + "SNAKE": "trace_url" + } + }, + { + "input": "commitSHA", + "words": [ + { + "kind": "WORD", + "text": "commit", + "suffix": "", + "capitalized": "Commit" + }, + { + "kind": "ACRONYM", + "text": "SHA", + "suffix": "", + "capitalized": "Sha" + } + ], + "formats": { + "CAMEL": "commitSHA", + "CAMEL_CAPITALIZED": "commitSha", + "FLAT": "commitsha", + "KEBAB": "commit-sha", + "PASCAL": "CommitSHA", + "PASCAL_CAPITALIZED": "CommitSha", + "SCREAMING_SNAKE": "COMMIT_SHA", + "SNAKE": "commit_sha" + } + }, + { + "input": "shortSha", + "words": [ + { + "kind": "WORD", + "text": "short", + "suffix": "", + "capitalized": "Short" + }, + { + "kind": "ACRONYM", + "text": "SHA", + "suffix": "", + "capitalized": "Sha" + } + ], + "formats": { + "CAMEL": "shortSHA", + "CAMEL_CAPITALIZED": "shortSha", + "FLAT": "shortsha", + "KEBAB": "short-sha", + "PASCAL": "ShortSHA", + "PASCAL_CAPITALIZED": "ShortSha", + "SCREAMING_SNAKE": "SHORT_SHA", + "SNAKE": "short_sha" + } + }, + { + "input": "parentShas", + "words": [ + { + "kind": "WORD", + "text": "parent", + "suffix": "", + "capitalized": "Parent" + }, + { + "kind": "ACRONYM", + "text": "SHA", + "suffix": "s", + "capitalized": "Sha" + } + ], + "formats": { + "CAMEL": "parentSHAs", + "CAMEL_CAPITALIZED": "parentShas", + "FLAT": "parentshas", + "KEBAB": "parent-shas", + "PASCAL": "ParentSHAs", + "PASCAL_CAPITALIZED": "ParentShas", + "SCREAMING_SNAKE": "PARENT_SHAS", + "SNAKE": "parent_shas" + } + }, + { + "input": "pushUrl", + "words": [ + { + "kind": "WORD", + "text": "push", + "suffix": "", + "capitalized": "Push" + }, + { + "kind": "ACRONYM", + "text": "URL", + "suffix": "", + "capitalized": "Url" + } + ], + "formats": { + "CAMEL": "pushURL", + "CAMEL_CAPITALIZED": "pushUrl", + "FLAT": "pushurl", + "KEBAB": "push-url", + "PASCAL": "PushURL", + "PASCAL_CAPITALIZED": "PushUrl", + "SCREAMING_SNAKE": "PUSH_URL", + "SNAKE": "push_url" + } + }, + { + "input": "asSdkName", + "words": [ + { + "kind": "WORD", + "text": "as", + "suffix": "", + "capitalized": "As" + }, + { + "kind": "ACRONYM", + "text": "SDK", + "suffix": "", + "capitalized": "Sdk" + }, + { + "kind": "WORD", + "text": "name", + "suffix": "", + "capitalized": "Name" + } + ], + "formats": { + "CAMEL": "asSDKName", + "CAMEL_CAPITALIZED": "asSdkName", + "FLAT": "assdkname", + "KEBAB": "as-sdk-name", + "PASCAL": "AsSDKName", + "PASCAL_CAPITALIZED": "AsSdkName", + "SCREAMING_SNAKE": "AS_SDK_NAME", + "SNAKE": "as_sdk_name" + } + }, + { + "input": "withoutUri", + "words": [ + { + "kind": "WORD", + "text": "without", + "suffix": "", + "capitalized": "Without" + }, + { + "kind": "ACRONYM", + "text": "URI", + "suffix": "", + "capitalized": "Uri" + } + ], + "formats": { + "CAMEL": "withoutURI", + "CAMEL_CAPITALIZED": "withoutUri", + "FLAT": "withouturi", + "KEBAB": "without-uri", + "PASCAL": "WithoutURI", + "PASCAL_CAPITALIZED": "WithoutUri", + "SCREAMING_SNAKE": "WITHOUT_URI", + "SNAKE": "without_uri" + } + }, + { + "input": "vcsGeneratedPaths", + "words": [ + { + "kind": "ACRONYM", + "text": "VCS", + "suffix": "", + "capitalized": "Vcs" + }, + { + "kind": "WORD", + "text": "generated", + "suffix": "", + "capitalized": "Generated" + }, + { + "kind": "WORD", + "text": "paths", + "suffix": "", + "capitalized": "Paths" + } + ], + "formats": { + "CAMEL": "vcsGeneratedPaths", + "CAMEL_CAPITALIZED": "vcsGeneratedPaths", + "FLAT": "vcsgeneratedpaths", + "KEBAB": "vcs-generated-paths", + "PASCAL": "VCSGeneratedPaths", + "PASCAL_CAPITALIZED": "VcsGeneratedPaths", + "SCREAMING_SNAKE": "VCS_GENERATED_PATHS", + "SNAKE": "vcs_generated_paths" + } + }, + { + "input": "insecureSkipTLSVerify", + "words": [ + { + "kind": "WORD", + "text": "insecure", + "suffix": "", + "capitalized": "Insecure" + }, + { + "kind": "WORD", + "text": "skip", + "suffix": "", + "capitalized": "Skip" + }, + { + "kind": "ACRONYM", + "text": "TLS", + "suffix": "", + "capitalized": "Tls" + }, + { + "kind": "WORD", + "text": "verify", + "suffix": "", + "capitalized": "Verify" + } + ], + "formats": { + "CAMEL": "insecureSkipTLSVerify", + "CAMEL_CAPITALIZED": "insecureSkipTlsVerify", + "FLAT": "insecureskiptlsverify", + "KEBAB": "insecure-skip-tls-verify", + "PASCAL": "InsecureSkipTLSVerify", + "PASCAL_CAPITALIZED": "InsecureSkipTlsVerify", + "SCREAMING_SNAKE": "INSECURE_SKIP_TLS_VERIFY", + "SNAKE": "insecure_skip_tls_verify" + } + }, + { + "input": "sshfsVolume", + "words": [ + { + "kind": "ACRONYM", + "text": "SSHFS", + "suffix": "", + "capitalized": "Sshfs" + }, + { + "kind": "WORD", + "text": "volume", + "suffix": "", + "capitalized": "Volume" + } + ], + "formats": { + "CAMEL": "sshfsVolume", + "CAMEL_CAPITALIZED": "sshfsVolume", + "FLAT": "sshfsvolume", + "KEBAB": "sshfs-volume", + "PASCAL": "SSHFSVolume", + "PASCAL_CAPITALIZED": "SshfsVolume", + "SCREAMING_SNAKE": "SSHFS_VOLUME", + "SNAKE": "sshfs_volume" + } + } +] diff --git a/helpers/names/naming/vectors_test.go b/helpers/names/naming/vectors_test.go new file mode 100644 index 00000000..b189a284 --- /dev/null +++ b/helpers/names/naming/vectors_test.go @@ -0,0 +1,57 @@ +package naming + +import ( + "encoding/json" + "os" + "testing" +) + +// TestVectors checks the copy against the engine's shared test vectors, which +// were copied with it: every input formats, in every casing, as the engine +// formats it. +func TestVectors(t *testing.T) { + data, err := os.ReadFile("testdata/vectors.json") + if err != nil { + t.Fatal(err) + } + var vectors []struct { + Input string `json:"input"` + Formats map[string]string `json:"formats"` + } + if err := json.Unmarshal(data, &vectors); err != nil { + t.Fatal(err) + } + if len(vectors) == 0 { + t.Fatal("no vectors") + } + formats := map[string]struct { + casing Casing + style AcronymStyle + }{ + "PASCAL": {Pascal, Uppercase}, + "PASCAL_CAPITALIZED": {Pascal, Capitalized}, + "CAMEL": {Camel, Uppercase}, + "CAMEL_CAPITALIZED": {Camel, Capitalized}, + "SNAKE": {Snake, Uppercase}, + "SCREAMING_SNAKE": {ScreamingSnake, Uppercase}, + "KEBAB": {Kebab, Uppercase}, + "FLAT": {Flat, Uppercase}, + } + for _, v := range vectors { + id, err := DictionaryFor(FirstVersion).Parse(v.Input) + if err != nil { + t.Errorf("%q: %v", v.Input, err) + continue + } + for name, want := range v.Formats { + f, ok := formats[name] + if !ok { + t.Errorf("%q: unknown format %s", v.Input, name) + continue + } + if got := id.Format(f.casing, f.style); got != want { + t.Errorf("%q in %s: got %q, want %q", v.Input, name, got, want) + } + } + } +} diff --git a/helpers/names/naming/version.go b/helpers/names/naming/version.go new file mode 100644 index 00000000..535f11f0 --- /dev/null +++ b/helpers/names/naming/version.go @@ -0,0 +1,58 @@ +package naming + +import ( + "strings" + + "golang.org/x/mod/semver" +) + +// FirstVersion is the engine version that introduced identifier parsing, +// with the Initial dictionary. The engine names modules that declare an older +// engineVersion with its previous (strcase) rules instead; see +// hack/designs/identifier-casing.md. +const FirstVersion = "v1.0.0" + +// releases lists every released dictionary with the engine version that +// introduced it, oldest first. A dictionary addition is a new entry here, +// never an edit to an existing dictionary: modules and clients keep the +// dictionary of the engine version they declare. +var releases = []struct { + version string + dict *Dictionary +}{ + {FirstVersion, Initial}, +} + +// DictionaryFor returns the dictionary for a module or client that declares +// engineVersion: the newest dictionary introduced at or before it. +// +// Versions compare by their base version, like engine API views: every +// prerelease of vX.Y.Z (v1.0.0-beta.15, v1.0.0-dev-123) selects vX.Y.Z's +// dictionary. An empty version means the latest, as an empty view does. +// Versions older than FirstVersion, and invalid versions, get Initial; callers +// that need the pre-naming behavior for those check FirstVersion themselves. +func DictionaryFor(engineVersion string) *Dictionary { + if engineVersion == "" { + return Latest + } + if !strings.HasPrefix(engineVersion, "v") { + engineVersion = "v" + engineVersion + } + if !semver.IsValid(engineVersion) { + return Initial + } + base := baseVersion(engineVersion) + dict := Initial + for _, r := range releases { + if semver.Compare(base, r.version) >= 0 { + dict = r.dict + } + } + return dict +} + +// baseVersion strips a version's prerelease and build metadata. +func baseVersion(v string) string { + v = strings.TrimSuffix(v, semver.Build(v)) + return strings.TrimSuffix(v, semver.Prerelease(v)) +} From 1308002ef6a0b827622ad090857ff9e43686e8e2 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Thu, 22 Oct 2026 16:31:33 +0000 Subject: [PATCH 2/9] sdk: name codegen output like the engine Every generate command takes a names file (-n, as helpers/names writes it). For a schema with Query.formatIdentifiers (v1.0.0-beta.21 views), names come from it; schemas without it, and names missing from it, keep the legacy converter and generate byte-identical code. With the engine's names: - A method whose legacy-converted name differs (prerequisite_sh_as) keeps it as a deprecated alias. - Core enums extend the new ValueEnum: SCREAMING_SNAKE members holding the schema value they stand for, sent by value; the schema's other spellings (OCIMediaTypes) are deprecated aliases, and defaults use the canonical member. - A dependency module's enum whose @enumValue holds its own values stays a plain Enum, as before. Signed-off-by: Alex Suraci --- sdk/codegen/src/codegen/cli.py | 68 +++- sdk/codegen/src/codegen/generator.py | 387 ++++++++++++++++++++--- sdk/codegen/src/codegen/packages.py | 80 +++-- sdk/src/dagger/client/_core.py | 19 +- sdk/src/dagger/client/base.py | 13 + sdk/tests/codegen/test_names.py | 448 +++++++++++++++++++++++++++ 6 files changed, 935 insertions(+), 80 deletions(-) create mode 100644 sdk/tests/codegen/test_names.py diff --git a/sdk/codegen/src/codegen/cli.py b/sdk/codegen/src/codegen/cli.py index 42b53f04..4d7b672e 100644 --- a/sdk/codegen/src/codegen/cli.py +++ b/sdk/codegen/src/codegen/cli.py @@ -2,6 +2,7 @@ import json import pathlib import sys +from collections.abc import Mapping import graphql @@ -21,6 +22,7 @@ def main(argv: list[str] | None = None): help="generate a Python client for the API", ) add_introspection_argument(gen_parser) + add_names_argument(gen_parser) gen_parser.add_argument( "-o", "--output", @@ -30,21 +32,27 @@ def main(argv: list[str] | None = None): "(defaults to printing it to stdout)" ), ) - gen_parser.set_defaults(run=lambda args: codegen(args.introspection, args.output)) + gen_parser.set_defaults( + run=lambda args: codegen(args.introspection, args.output, args.names) + ) core_parser = subparsers.add_parser( "generate-core", help=f"generate the {packages.NAMESPACE}.core package", ) add_introspection_argument(core_parser) + add_names_argument(core_parser) add_package_output_argument(core_parser) - core_parser.set_defaults(run=lambda args: core(args.introspection, args.output)) + core_parser.set_defaults( + run=lambda args: core(args.introspection, args.output, args.names) + ) client_parser = subparsers.add_parser( "generate-client", help=f"generate the {packages.NAMESPACE} package of one client", ) add_introspection_argument(client_parser) + add_names_argument(client_parser) add_package_output_argument(client_parser) client_parser.add_argument( "--name", @@ -83,6 +91,7 @@ def main(argv: list[str] | None = None): "repeat it for the schema of each client" ), ) + add_names_argument(global_parser) global_parser.add_argument( "-o", "--output", @@ -91,7 +100,7 @@ def main(argv: list[str] | None = None): help=f"directory to write the {packages.GLOBAL} package into", ) global_parser.set_defaults( - run=lambda args: global_client(args.introspection, args.output) + run=lambda args: global_client(args.introspection, args.output, args.names) ) args = parser.parse_args(argv) @@ -120,6 +129,20 @@ def add_introspection_argument(subparser: argparse.ArgumentParser): ) +def add_names_argument(subparser: argparse.ArgumentParser): + subparser.add_argument( + "-n", + "--names", + type=pathlib.Path, + help=( + "path to a .json file holding the schema's names as the engine " + f"formats them, with a {generator.NAMES_FORMAT} map, as " + "helpers/names writes it (defaults to converting names locally, " + "which is how schemas without Query.formatIdentifiers are named)" + ), + ) + + def add_package_output_argument(subparser: argparse.ArgumentParser): subparser.add_argument( "-o", @@ -137,9 +160,27 @@ def read_schema(introspection: pathlib.Path) -> tuple[graphql.GraphQLSchema, str return schema, result.get("__schemaVersion", "") -def codegen(introspection: pathlib.Path, output: pathlib.Path | None): +def load_names(path: pathlib.Path | None) -> Mapping[str, str] | None: + """Read the snake_case names from a names file. + + A names file maps each ``CASING:ACRONYMS`` format to the schema's names + formatted in it. It has no format for schemas without + ``Query.formatIdentifiers``, which then keep the legacy conversion. + """ + if path is None: + return None + return json.loads(path.read_text()).get(generator.NAMES_FORMAT) + + +def codegen( + introspection: pathlib.Path, + output: pathlib.Path | None, + names: pathlib.Path | None = None, +): schema, schema_version = read_schema(introspection) - code = generator.generate(schema, schema_version=schema_version) + code = generator.generate( + schema, schema_version=schema_version, names=load_names(names) + ) if output: output.write_text(code) @@ -148,9 +189,13 @@ def codegen(introspection: pathlib.Path, output: pathlib.Path | None): sys.stdout.write(f"{code}\n") -def core(introspection: pathlib.Path, output: pathlib.Path): +def core( + introspection: pathlib.Path, + output: pathlib.Path, + names: pathlib.Path | None = None, +): schema, schema_version = read_schema(introspection) - files = packages.core_package(schema, schema_version) + files = packages.core_package(schema, schema_version, load_names(names)) root = packages.write_package(output, partition.CORE, files) sys.stdout.write(f"Core generated successfully to {root}\n") @@ -164,18 +209,23 @@ def client(args: argparse.Namespace): args.pin, core_digest=args.core_digest, schema_version=schema_version, + names=load_names(args.names), ) root = packages.write_package(args.output, package, files) sys.stdout.write(f"Client generated successfully to {root}\n") -def global_client(introspections: list[pathlib.Path], output: pathlib.Path): +def global_client( + introspections: list[pathlib.Path], + output: pathlib.Path, + names: pathlib.Path | None = None, +): schemas, versions = zip( *(read_schema(path) for path in introspections), strict=True ) if len(set(versions)) > 1: msg = f"the schemas have different versions: {', '.join(sorted(set(versions)))}" raise partition.ClientError(msg) - files = packages.global_package(schemas, versions[0]) + files = packages.global_package(schemas, versions[0], load_names(names)) root = packages.write_global(output, files) sys.stdout.write(f"Global client generated successfully to {root}\n") diff --git a/sdk/codegen/src/codegen/generator.py b/sdk/codegen/src/codegen/generator.py index abb0ee4f..9ddf0722 100644 --- a/sdk/codegen/src/codegen/generator.py +++ b/sdk/codegen/src/codegen/generator.py @@ -6,7 +6,7 @@ import textwrap from abc import ABC, abstractmethod from collections import defaultdict -from collections.abc import Callable, Iterable, Iterator +from collections.abc import Callable, Iterable, Iterator, Mapping from dataclasses import dataclass, field from datetime import date, datetime, time from decimal import Decimal @@ -29,6 +29,7 @@ from graphql import ( GraphQLArgument, GraphQLEnumType, + GraphQLEnumValue, GraphQLField, GraphQLInputField, GraphQLInputFieldMap, @@ -54,6 +55,14 @@ from codegen.partition import own_fields +NAMES_FORMAT = "SNAKE:UPPERCASE" +"""The format of the names the generator reads from a names file. + +A ``CASING:ACRONYMS`` key of the names file helpers/names writes, as +``Query.formatIdentifiers`` would be called. The acronym style doesn't change +snake_case names. +""" + ACRONYM_RE = re.compile(r"([A-Z\d]+)(?=[A-Z\d]|$)") """Pattern for grouping initialisms.""" @@ -130,6 +139,23 @@ class Context: partitioned: bool = False """Render one package of a partition, rather than the whole schema.""" + names: Mapping[str, str] | None = None + """Schema names in snake_case, as the engine formats them. + + Absent for schemas without ``Query.formatIdentifiers`` (before + v1.0.0-beta.21), whose names are converted with :func:`format_name`. + """ + + def format_name(self, name: str) -> PythonName: + """Format a schema name into Python (snake_case).""" + if self.names is None or not (formatted := self.names.get(name)): + return format_name(name) + return escape_name(formatted) + + def rewrite_notice(self, reason: str | None, prefix='"', suffix='"') -> str | None: + """Rewrite references in a deprecation or experimental notice.""" + return rewrite_notice(reason, prefix, suffix, self.format_name) + @property def legacy_sdk_compat(self) -> bool: """Generate the pre-v0.21 ID/load helper source facade.""" @@ -209,10 +235,22 @@ def render_body(self, t: _H) -> Iterator[str]: @joiner -def generate(schema: GraphQLSchema, schema_version: str = "") -> Iterator[str]: - """Code generation main function.""" +def generate( + schema: GraphQLSchema, + schema_version: str = "", + names: Mapping[str, str] | None = None, +) -> Iterator[str]: + """Code generation main function. + + ``names`` maps schema names to their snake_case form, as the engine + formats them (the :data:`NAMES_FORMAT` map of a names file). It's ignored + for schemas without ``Query.formatIdentifiers``, which keep the legacy + conversion, like names missing from it. + """ + ctx = new_context(schema, schema_version, names=names) + bases = ", ".join(sorted(["Input", "Root", "Scalar", "Type", *enum_bases(ctx)])) yield textwrap.dedent( - """\ + f"""\ # Code generated by dagger. DO NOT EDIT. import warnings # noqa: F401 @@ -222,11 +260,10 @@ def generate(schema: GraphQLSchema, schema_version: str = "") -> Iterator[str]: from dagger.client._core import Arg from dagger.client._guards import type_error as _type_error - from dagger.client.base import Enum, Input, Root, Scalar, Type + from dagger.client.base import {bases} """, ) - ctx = new_context(schema, schema_version) yield from render_types(ctx, schema.type_map) yield "" @@ -252,9 +289,16 @@ def generate(schema: GraphQLSchema, schema_version: str = "") -> Iterator[str]: def new_context( - schema: GraphQLSchema, schema_version: str = "", partitioned: bool = False + schema: GraphQLSchema, + schema_version: str = "", + partitioned: bool = False, + names: Mapping[str, str] | None = None, ) -> Context: - """Shared state between all handler instances.""" + """Shared state between all handler instances. + + The names are only used for a schema with ``Query.formatIdentifiers``, + the gate for the engine's naming rules. + """ # Pre-create handy maps to make handler code simpler. ids = frozenset(n for n, t in schema.type_map.items() if is_id_type(t)) return Context( @@ -262,9 +306,32 @@ def new_context( schema=schema, schema_version=schema_version, partitioned=partitioned, + names=names if has_format_identifiers(schema) else None, ) +def enum_bases(ctx: Context) -> list[str]: + """The enum base classes the rendered types extend. + + Without engine-formatted names every enum is an ``Enum``. With them, a + core enum is a ``ValueEnum``, and a module's enum whose members hold the + module's values stays an ``Enum`` (see :func:`has_module_values`). + """ + if ctx.names is None: + return ["Enum"] + enums = [ + t + for t in ctx.schema.type_map.values() + if is_enum_type(t) and not t.name.startswith("_") + ] + bases = [] + if any(has_module_values(ctx.schema, t) for t in enums): + bases.append("Enum") + if not all(has_module_values(ctx.schema, t) for t in enums): + bases.append("ValueEnum") + return bases + + def render_types(ctx: Context, type_map: TypeMap) -> Iterator[str]: """Render the given types, which may be a part of the schema only.""" handlers: tuple[Handler, ...] = ( @@ -368,6 +435,29 @@ def is_enum_type(t: GraphQLNamedType) -> TypeGuard[GraphQLEnumType]: return isinstance(t, GraphQLEnumType) +_CONVENTIONAL_ENUM_NAME = re.compile(r"[A-Z][A-Z0-9_]*") + + +def is_conventional_enum_name(name: str) -> bool: + """Whether an enum value name is in SCREAMING_SNAKE convention. + + E.g. ``PER_SESSION`` or ``HTTP2``, like the engine's check. + """ + return _CONVENTIONAL_ENUM_NAME.fullmatch(name) is not None + + +def has_format_identifiers(schema: GraphQLSchema) -> bool: + """Whether the schema has ``Query.formatIdentifiers``. + + It's the gate for the engine's naming rules: the engine serves it in the + views it names schemas by those rules (v1.0.0-beta.21 and later), and only + in those. Schemas without it keep the legacy conversion, and generate the + code they always did. + """ + query = schema.query_type + return query is not None and "formatIdentifiers" in query.fields + + def is_self_chainable(t: GraphQLObjectType, fields: Iterable[GraphQLField]) -> bool: """Checks if an object type has any fields that return that same type.""" return any( @@ -486,25 +576,39 @@ def expected_type_name( ) -def rewrite_notice(reason: str | None, prefix='"', suffix='"') -> str | None: +def rewrite_notice( + reason: str | None, + prefix='"', + suffix='"', + formatter: Callable[[str], str] | None = None, +) -> str | None: """Normalize deprecation/experimental messages and rewrite references.""" if reason is None: return None reason = reason.strip() + formatter = formatter or format_name def _format_name(match: re.Match[str]) -> str: - name = format_name(match.group(1)) + name = formatter(match.group(1)) return f"{prefix}{name}{suffix}" return DEPRECATION_RE.sub(_format_name, reason) def format_name(s: str) -> str: - """Format a GraphQL field or argument name into Python.""" + """Format a GraphQL field or argument name into Python. + + Guesses at word boundaries. Only used for schemas without the engine's + names (see :meth:`Context.format_name`). + """ # rewrite acronyms, initialisms and abbreviations s = ACRONYM_RE.sub(lambda m: m.group(0).title(), s) - s = camel_to_snake(s) + return escape_name(camel_to_snake(s)) + + +def escape_name(s: str) -> str: + """Avoid clashing with Python keywords and type builtins.""" if iskeyword(s) or s in _reserved_builtins: s += "_" return s @@ -594,7 +698,7 @@ def __init__( self.graphql_name = name self.graphql = graphql - self.name = format_name(name) + self.name = ctx.format_name(name) self.named_type = get_named_type(graphql.type) self.parent_return_type: TypeName | None = ( get_named_type(parent.graphql.type).name if parent else None @@ -635,7 +739,7 @@ def __init__( self.description = graphql.description self.has_default = graphql.default_value is not Undefined reason = getattr(graphql, "deprecation_reason", None) - self.deprecated = rewrite_notice(reason, prefix="", suffix="") + self.deprecated = ctx.rewrite_notice(reason, prefix="", suffix="") default_value = graphql.default_value self.default_is_mutable = isinstance(default_value, list) @@ -653,7 +757,8 @@ def _enum_default(self, value) -> str: """Render an enum default: the named type unwraps lists, the value doesn't.""" if isinstance(value, list): return f"[{', '.join(self._enum_default(v) for v in value)}]" - return f"{self.named_type.name}.{value}" + enum_t = cast(GraphQLEnumType, self.named_type) + return f"{enum_t.name}.{Enum(self.ctx).python_member(enum_t, value)}" @joiner def __str__(self) -> Iterator[str]: @@ -774,10 +879,20 @@ def __init__( self.graphql_name = name self.graphql = field - self.name = format_name(name) + self.name = ctx.format_name(name) self.named_type = get_named_type(field.type) self.parent_name = get_named_type(parent).name + # The name schemas before the engine's names made us guess. When it + # differs, the method keeps it as a deprecated alias. + self.legacy_name: PythonName | None = None + if ctx.names is not None: + legacy_name = format_name(name) + if legacy_name != self.name and legacy_name not in { + ctx.format_name(n) for n in parent.fields + }: + self.legacy_name = legacy_name + self.required_args = [] self.default_args = [] for args in field.args.items(): @@ -846,6 +961,36 @@ def __str__(self) -> Iterator[str]: indent("return self.sync().__await__()"), ) + if self.legacy_name: + yield from ( + "", + self.legacy_alias(), + ) + + @joiner + def legacy_alias(self) -> Iterator[str]: + """A deprecated method under the name older SDK versions generated.""" + msg = f'Method "{self.legacy_name}" is deprecated: use "{self.name}" instead.' + yield f"def {self.legacy_name}(self, *args, **kwargs):" + yield indent( + doc( + f"Deprecated alias for :py:meth:`{self.name}`.\n\n" + f".. deprecated::\n Use :py:meth:`{self.name}` instead." + ) + ) + yield indent( + textwrap.dedent( + f"""\ + {self.ctx.helper("warnings")}.warn( + {msg!r}, + DeprecationWarning, + stacklevel=2, + ) + return self.{self.name}(*args, **kwargs)\ + """ + ) + ) + @property def label(self) -> str: """The name a rejected argument is reported against.""" @@ -1003,7 +1148,7 @@ def _out(): return "\n\n".join("\n".join(section) for section in _out()) def deprecated(self, prefix='"', suffix='"') -> str | None: - return rewrite_notice(self.graphql.deprecation_reason, prefix, suffix) + return self.ctx.rewrite_notice(self.graphql.deprecation_reason, prefix, suffix) def experimental(self, prefix='"', suffix='"') -> str: reason = "" @@ -1013,7 +1158,7 @@ def experimental(self, prefix='"', suffix='"') -> str: args = graphql.get_directive_values(directive, self.graphql.ast_node) if args: reason = args["reason"] - return rewrite_notice(reason, prefix, suffix) + return self.ctx.rewrite_notice(reason, prefix, suffix) @dataclass @@ -1024,47 +1169,203 @@ def render_body(self, t: GraphQLScalarType) -> str: return super().render_body(t) or "..." +@dataclass(frozen=True, slots=True) +class _EnumMember: + """A member of an enum named by Python's convention.""" + + name: str + """The Python name.""" + wire: str + """The value: the schema value it stands for, sent over the wire.""" + schema_name: str + """The schema value name it was named after.""" + alias_of: str | None + """The member it's a deprecated alias of, if any.""" + + @dataclass class Enum(Handler[GraphQLEnumType]): predicate: ClassVar[Predicate] = staticmethod(is_enum_type) + def supertype_name(self, t: GraphQLEnumType) -> str: + # Enums named by convention are sent by value (see `ValueEnum`). + return self.ctx.helper("ValueEnum" if self.is_conventional(t) else "Enum") + + def is_conventional(self, t: GraphQLEnumType) -> bool: + """Whether members are named by convention and sent by value. + + Only with the engine's names (see `_render_conventional`), and not + for a module's enum whose members hold the module's own values (see + `has_module_values`). + """ + return self.ctx.names is not None and not has_module_values(self.ctx.schema, t) + @joiner def render_body(self, t: GraphQLEnumType) -> Iterable[str]: if body := super().render_body(t): yield body - by_value = defaultdict(list) - for name, value in t.values.items(): - by_value[self._get_value(value)].append(name) + by_value = self._by_value(t) + + if self.is_conventional(t): + yield from self._render_conventional(t, by_value) + return for val, names in sorted(by_value.items()): yield "" for name in names: + # Member names are the GraphQL enum value names, as is: the + # runtime sends a member by its name (see + # `configure_converter_enum`). yield f"{name} = {val!r}" + yield from self._member_doc(t, name) - member = t.values[name] - desc = member.description - reason = rewrite_notice(member.deprecation_reason) - - doc_parts: list[str] = [] - if desc: - doc_parts.append(desc) - if reason is not None: - directive = ".. deprecated::" - if reason: - directive = f"{directive} {reason}" - doc_parts.append(directive) - - if doc_parts: - yield doc("\n\n".join(doc_parts)) - - def _get_value(self, value) -> str: - if value.ast_node and (directive := self.ctx.schema.get_directive("enumValue")): - args = graphql.get_directive_values(directive, value.ast_node) - if args: - return args["value"] - return value.value + def _render_conventional( + self, + t: GraphQLEnumType, + by_value: Mapping[str, list[str]], + ) -> Iterator[str]: + """Members named by Python's convention. + + For schemas the engine names. Members are SCREAMING_SNAKE, and a + member's value is the schema value it stands for, which is what goes + over the wire (see `ValueEnum`). Schema values written another way + (the legacy ``OCIMediaTypes``, ``Gzip``) stay as deprecated aliases, + which keep old code working and let a value the API returns be looked + up by name. + """ + for group in self._conventional_members(by_value, t): + yield "" + for member in group: + yield f"{member.name} = {member.wire!r}" + if member.alias_of is None: + yield from self._member_doc(t, member.schema_name) + else: + yield doc(f".. deprecated:: Use {member.alias_of} instead.") + + def python_member(self, t: GraphQLEnumType, schema_name: str) -> str: + """The Python member to write for a schema value, as a default value. + + That's its group's canonical member, not a deprecated alias. + """ + if not self.is_conventional(t): + return schema_name + for group in self._conventional_members(self._by_value(t), t): + for member in group: + if member.schema_name == schema_name: + return member.alias_of or member.name + return schema_name + + def _by_value(self, t: GraphQLEnumType) -> dict[str, list[str]]: + by_value = defaultdict(list) + for name, value in t.values.items(): + by_value[enum_member_value(self.ctx.schema, value)].append(name) + return by_value + + def _conventional_members( + self, + by_value: Mapping[str, list[str]], + t: GraphQLEnumType, + ) -> Iterator[list[_EnumMember]]: + """The members of each group of schema values that share a value.""" + emitted: set[str] = set() + for val, names in sorted(by_value.items()): + # The schema's own SCREAMING_SNAKE names, else the first name, + # formatted. + canonical = [n for n in names if is_conventional_enum_name(n)] + if not canonical: + canonical = names[:1] + wire = val if val in t.values else canonical[0] + + group: list[_EnumMember] = [] + first: str | None = None + # The member another group already defines under the canonical + # name: this group's own spellings are deprecated in its favor. + taken: str | None = None + for name in canonical: + member = self.member_name(name) + if member in emitted: + taken = taken or member + continue + emitted.add(member) + first = first or member + group.append(_EnumMember(member, wire, name, None)) + + for name in names: + if name in emitted: + continue + emitted.add(name) + target = first or taken + alias_of = target if target != name else None + group.append(_EnumMember(name, wire, name, alias_of)) + + yield group + + def member_name(self, name: str) -> str: + """The Python name of a schema enum value: SCREAMING_SNAKE. + + Names already in that form are kept, as the engine does (``HTTP2``); + the others are the engine's snake_case, uppercased, which is its + SCREAMING_SNAKE form. + """ + if is_conventional_enum_name(name) or self.ctx.names is None: + return name + if formatted := self.ctx.names.get(name): + return formatted.upper() + return name + + def _member_doc(self, t: GraphQLEnumType, name: str) -> Iterator[str]: + member = t.values[name] + desc = member.description + reason = self.ctx.rewrite_notice(member.deprecation_reason) + + doc_parts: list[str] = [] + if desc: + doc_parts.append(desc) + if reason is not None: + directive = ".. deprecated::" + if reason: + directive = f"{directive} {reason}" + doc_parts.append(directive) + + if doc_parts: + yield doc("\n\n".join(doc_parts)) + + +def enum_member_value(schema: GraphQLSchema, value: GraphQLEnumValue) -> str: + """The value an enum member stands for: its ``@enumValue``, else its own.""" + if (directed := enum_value_directive(schema, value)) is not None: + return directed + return value.value + + +def enum_value_directive( + schema: GraphQLSchema, + value: GraphQLEnumValue, +) -> str | None: + """An enum member's ``@enumValue``, if it has one.""" + if value.ast_node and (directive := schema.get_directive("enumValue")): + args = graphql.get_directive_values(directive, value.ast_node) + if args: + return args["value"] + return None + + +def has_module_values(schema: GraphQLSchema, t: GraphQLEnumType) -> bool: + """Whether an enum's members hold values that aren't schema values. + + That's a module's enum, whose ``@enumValue`` is the module's own value for + a member (``"ACTIVE value"`` for ``ACTIVE``). Such an enum keeps the + members it always had: named by schema value, holding the module's value, + and sent by name, since only schema values can go over the wire. Core + enums' ``@enumValue`` only ever names another schema value. + """ + return any( + (directed := enum_value_directive(schema, v)) is not None + and directed not in t.values + for v in t.values.values() + ) class Field(Protocol): diff --git a/sdk/codegen/src/codegen/packages.py b/sdk/codegen/src/codegen/packages.py index d160168f..c960a5dc 100644 --- a/sdk/codegen/src/codegen/packages.py +++ b/sdk/codegen/src/codegen/packages.py @@ -6,7 +6,7 @@ import json import pathlib import textwrap -from collections.abc import Iterator, Sequence +from collections.abc import Iterator, Mapping, Sequence from itertools import groupby from graphql import ( @@ -24,8 +24,8 @@ from codegen.generator import ( Context, _ObjectField, + enum_bases, expected_type_name, - format_name, indent, is_builtin_scalar_type, is_input_object_type, @@ -87,6 +87,17 @@ from dagger.client.base import Type as _Type """ +_VALUE_ENUM_IMPORT = "from dagger.client.base import ValueEnum as _ValueEnum\n" +"""What the header imports too for a schema the engine names, whose core enums +are value enums.""" + + +def _header(ctx: Context, modules: str) -> str: + header = _HEADER % modules + if "ValueEnum" in enum_bases(ctx): + header += _VALUE_ENUM_IMPORT + return header + def _aliased(*names: str) -> str: return "\n".join(f"from dagger.client import {name} as _{name}" for name in names) @@ -144,7 +155,7 @@ def __init__( parent: GraphQLObjectType | GraphQLInterfaceType, ) -> None: super().__init__(ctx, name, field, parent) - self.receiver = format_name(parent.name) + self.receiver = ctx.format_name(parent.name) self.receiver_is_interface = is_interface_type(parent) self.receiver_class = ( f"_{parent.name}Client" if self.receiver_is_interface else parent.name @@ -247,11 +258,15 @@ def _all(names: list[str]) -> str: @joiner -def _core_init(schema: GraphQLSchema, schema_version: str) -> Iterator[str]: - ctx = new_context(schema, schema_version, partitioned=True) +def _core_init( + schema: GraphQLSchema, + schema_version: str, + names: Mapping[str, str] | None = None, +) -> Iterator[str]: + ctx = new_context(schema, schema_version, partitioned=True, names=names) digest = partition.core_digest(schema, legacy_sdk_compat=ctx.legacy_sdk_compat) - yield _HEADER % _aliased("Session", "client_root") + yield _header(ctx, _aliased("Session", "client_root")) yield from render_types(ctx, _owned(schema, None)) yield _block( "def core(*, session: _Session | None = None) -> Query:", @@ -347,9 +362,13 @@ def _core_imports(ctx: Context, module: str, references: dict[str, str]) -> list @joiner def _client_init( - schema: GraphQLSchema, module: str, package: str, schema_version: str + schema: GraphQLSchema, + module: str, + package: str, + schema_version: str, + names: Mapping[str, str] | None = None, ) -> Iterator[str]: - ctx = new_context(schema, schema_version, partitioned=True) + ctx = new_context(schema, schema_version, partitioned=True, names=names) owned = _owned(schema, module) entry: _EntryField | None = None @@ -370,9 +389,9 @@ def _client_init( references = _references(schema, module, owned) references |= {f.parent_name: f.label for f in contributed} - yield _HEADER.rstrip() % _aliased( - "Session", "Target", "check_core", "client_root", "client_select" - ) + yield _header( + ctx, _aliased("Session", "Target", "check_core", "client_root", "client_select") + ).rstrip() yield f"from {NAMESPACE}.{partition.CORE} import CORE_DIGEST as _installed_core" yield "" yield "from ._target import CORE_DIGEST, NAME, PIN, REF" @@ -433,11 +452,15 @@ def _target(name: str, ref: str, pin: str | None, core_digest: str) -> str: ) -def core_package(schema: GraphQLSchema, schema_version: str = "") -> Files: +def core_package( + schema: GraphQLSchema, + schema_version: str = "", + names: Mapping[str, str] | None = None, +) -> Files: """Files of `dagger_clients.core`, whatever clients the schema holds.""" partition.check_attribution(schema) return { - "__init__.py": _core_init(schema, schema_version), + "__init__.py": _core_init(schema, schema_version, names), "py.typed": "", } @@ -450,6 +473,7 @@ def client_package( # noqa: PLR0913 *, core_digest: str | None = None, schema_version: str = "", + names: Mapping[str, str] | None = None, ) -> tuple[str, Files]: """Package name and files of one client, whatever the other clients are.""" partition.check_attribution(schema) @@ -472,7 +496,7 @@ def client_package( # noqa: PLR0913 ) raise partition.ClientError(msg) return package, { - "__init__.py": _client_init(schema, module, package, schema_version), + "__init__.py": _client_init(schema, module, package, schema_version, names), "_target.py": _target(name, ref, pin, core_digest), "py.typed": "", } @@ -577,10 +601,12 @@ def _global_clients( @joiner def _global_init( - schemas: Sequence[GraphQLSchema], schema_version: str + schemas: Sequence[GraphQLSchema], + schema_version: str, + names: Mapping[str, str] | None = None, ) -> Iterator[str]: core_schema = schemas[0] - ctx = new_context(core_schema, schema_version, partitioned=True) + ctx = new_context(core_schema, schema_version, partitioned=True, names=names) legacy = ctx.legacy_sdk_compat clients = _global_clients(schemas) @@ -599,7 +625,7 @@ def _global_init( name, f, query, - f"{core_root}.{format_name(name)}", + f"{core_root}.{ctx.format_name(name)}", owner=partition.CORE, ) for name, f in partition.own_fields(query).items() @@ -607,14 +633,14 @@ def _global_init( for package, (module, schema) in sorted(clients.items()): alias = f"_{package}" - names = sorted(_type_names(schema, module, legacy=legacy)) - exported |= set(names) - if names: - imports.append(f"from {NAMESPACE}.{package} import ({_lines(names)})") - client_ctx = new_context(schema, schema_version, partitioned=True) + type_names = sorted(_type_names(schema, module, legacy=legacy)) + exported |= set(type_names) + if type_names: + imports.append(f"from {NAMESPACE}.{package} import ({_lines(type_names)})") + client_ctx = new_context(schema, schema_version, partitioned=True, names=names) owner = f'the client "{module}"' for parent, name, f in partition.contributed_fields(schema, module): - function = format_name(name) + function = client_ctx.format_name(name) if parent.name == "Query" and name.lower() == package.replace("_", ""): methods.append( _GlobalField( @@ -683,7 +709,11 @@ def _lines(names: Sequence[str]) -> str: return "\n" + "".join(indent(f"{name},") + "\n" for name in names) -def global_package(schemas: Sequence[GraphQLSchema], schema_version: str = "") -> Files: +def global_package( + schemas: Sequence[GraphQLSchema], + schema_version: str = "", + names: Mapping[str, str] | None = None, +) -> Files: """Files of `dagger_global`, for core and every client the schemas hold. Each client is generated from a schema of core and that module, so the @@ -708,7 +738,7 @@ def global_package(schemas: Sequence[GraphQLSchema], schema_version: str = "") - ) raise partition.ClientError(msg) return { - "__init__.py": _global_init(schemas, schema_version), + "__init__.py": _global_init(schemas, schema_version, names), "py.typed": "", } diff --git a/sdk/src/dagger/client/_core.py b/sdk/src/dagger/client/_core.py index c5d3987b..2f9edc5b 100644 --- a/sdk/src/dagger/client/_core.py +++ b/sdk/src/dagger/client/_core.py @@ -28,7 +28,7 @@ as_session, default_session, ) -from dagger.client.base import Input, Scalar, Type +from dagger.client.base import Input, Scalar, Type, ValueEnum from ._guards import ( IDType, @@ -141,7 +141,10 @@ def _scalar_literal(value: Any) -> str: def _enum_literal(value: enum.Enum | EnumName) -> str: - if isinstance(value, enum.Enum): + if isinstance(value, ValueEnum): + # Named by Python's convention: the value is the API's name. + value = EnumName(value.value) + elif isinstance(value, enum.Enum): return value.name # Rendered bare, so anything but a name would inject query syntax. if not _ENUM_NAME_RE.fullmatch(value): @@ -395,12 +398,22 @@ def _struct(d: dict[str, Any], cls: type) -> Any: def configure_converter_enum(conv: cattrs.Converter, cl: typing.Any = enum.Enum): - """Register hooks for structuring and destructuring enums using member names.""" + """Register hooks for structuring and destructuring enums using member names. + + Members of a :py:class:`~dagger.client.base.ValueEnum` are named by + Python's convention and go over the wire by value instead. They're still + structured by name, since such an enum keeps the API's spellings as + aliases, and by value for a name it doesn't have. + """ def to_enum_name(val: enum.Enum) -> str: + if isinstance(val, ValueEnum): + return val.value return val.name def from_enum_name(name: str, cls: type[enum.Enum]) -> enum.Enum: + if issubclass(cls, ValueEnum) and name not in cls.__members__: + return cls(name) return cls[name] conv.register_unstructure_hook(cl, to_enum_name) diff --git a/sdk/src/dagger/client/base.py b/sdk/src/dagger/client/base.py index 3b618d21..49667faa 100644 --- a/sdk/src/dagger/client/base.py +++ b/sdk/src/dagger/client/base.py @@ -24,6 +24,19 @@ def __str__(self) -> str: return str(self.value) +class ValueEnum(Enum): + """Enumeration whose values are the API's enum values. + + Generated for schemas the engine names by its naming rules (from + v1.0.0-beta.21): members follow Python's convention (``PER_SESSION``), so + unlike :py:class:`Enum`, a member is sent over the wire by its value + rather than its name. Values the API writes another way are kept as + aliases, so a value the API returns is found by name too. + """ + + __slots__ = () + + class Object: """Base for object types.""" diff --git a/sdk/tests/codegen/test_names.py b/sdk/tests/codegen/test_names.py new file mode 100644 index 00000000..edee90bb --- /dev/null +++ b/sdk/tests/codegen/test_names.py @@ -0,0 +1,448 @@ +"""Code generation from the names the engine formats (v1.0.0-beta.21 views). + +The gate is the schema having ``Query.formatIdentifiers``: a schema without it +generates the code it always did, names file or not. +""" + +import json +import sys +import types +import warnings + +import pytest +from graphql import GraphQLEnumType, GraphQLEnumValue, build_schema +from graphql import GraphQLField as Field +from graphql import GraphQLList as List +from graphql import GraphQLNonNull as NonNull +from graphql import GraphQLObjectType as Object +from graphql import GraphQLString as String + +from codegen import cli +from codegen.cli import load_names +from codegen.generator import ( + NAMES_FORMAT, + Context, + _ObjectField, + generate, + has_format_identifiers, +) +from codegen.generator import Enum as EnumHandler +from codegen.packages import client_package, core_package, global_package +from dagger.client._core import Context as QueryContext +from dagger.client._core import make_converter + +# Names as helpers/names writes them in snake_case. Made up where they differ +# from the legacy conversion, to tell which one was used. +_NAMES = { + "prerequisiteSHAs": "prerequisite_shas", + "experimentalWithAllGPUs": "experimental_with_all_gpus", + "withFS": "with_fs", + "from": "from", + "str": "str", + "gitRef": "git_ref", + "withRepoURL": "with_repo_url_engine", + "repoURL": "repo_url_engine", +} + +_FORMAT_IDENTIFIERS = "formatIdentifiers(names: [String!]!): [String!]!" + + +@pytest.mark.parametrize( + ("graphql", "expected"), + [ + ("prerequisiteSHAs", "prerequisite_shas"), + ("experimentalWithAllGPUs", "experimental_with_all_gpus"), + ("withFS", "with_fs"), + ("withRepoURL", "with_repo_url_engine"), + ("from", "from_"), # reserved keyword, escaped after formatting + ("str", "str_"), # builtin, escaped after formatting + ("envVariable", "env_variable"), # not in the names: fallback + ], +) +def test_context_format_name(graphql, expected): + assert Context(names=_NAMES).format_name(graphql) == expected + + +def test_context_format_name_without_names(): + # Older schemas have no engine names: keep guessing, as before. + assert Context().format_name("prerequisiteSHAs") == "prerequisite_sh_as" + + +def test_has_format_identifiers(): + sdl = "type Query { %s }" + assert has_format_identifiers(build_schema(sdl % _FORMAT_IDENTIFIERS)) + assert not has_format_identifiers(build_schema(sdl % "version: String!")) + + +def _git_ref() -> Object: + return Object( + "GitRef", + lambda: {"prerequisiteSHAs": Field(NonNull(List(NonNull(String))))}, + ) + + +def test_legacy_alias(): + parent = _git_ref() + handler = _ObjectField( + Context(names=_NAMES), + "prerequisiteSHAs", + parent.fields["prerequisiteSHAs"], + parent, + ) + assert handler.func_signature() == "async def prerequisite_shas(self) -> list[str]:" + code = str(handler) + assert "def prerequisite_sh_as(self, *args, **kwargs):" in code + assert "return self.prerequisite_shas(*args, **kwargs)" in code + assert "DeprecationWarning" in code + + +def test_no_legacy_alias_without_names(): + parent = _git_ref() + handler = _ObjectField( + Context(), + "prerequisiteSHAs", + parent.fields["prerequisiteSHAs"], + parent, + ) + assert handler.legacy_name is None + assert "**kwargs" not in str(handler) + + +def test_deprecation_reference(): + ctx = Context(names=_NAMES) + assert ( + ctx.rewrite_notice("Use `prerequisiteSHAs` instead.", "", "") + == "Use prerequisite_shas instead." + ) + + +_NAMES_SCHEMA = """ + type GitRef { + prerequisiteSHAs: [String!]! + withRepoURL(repoURL: String!): GitRef! + } + type Query { + gitRef: GitRef! + %s + } +""" + + +def test_generate_with_names(): + code = generate(build_schema(_NAMES_SCHEMA % _FORMAT_IDENTIFIERS), names=_NAMES) + + assert "async def prerequisite_shas(self) -> list[str]:" in code + assert "def prerequisite_sh_as(self, *args, **kwargs):" in code + assert "def with_repo_url_engine(self, repo_url_engine: str) -> Self:" in code + assert 'Arg("repoURL", repo_url_engine),' in code + assert "def git_ref(self) -> GitRef:" in code + assert "class GitRef(Type):" in code + + +def test_generate_without_names(): + code = generate(build_schema(_NAMES_SCHEMA % _FORMAT_IDENTIFIERS)) + + assert "async def prerequisite_sh_as(self) -> list[str]:" in code + assert "def with_repo_url(self, repo_url: str) -> Self:" in code + assert "**kwargs" not in code + + +def test_generate_names_gate(): + # A schema without Query.formatIdentifiers keeps the legacy conversion, + # even with names, and generates exactly what it did without them. + schema = build_schema(_NAMES_SCHEMA % "") + + code = generate(schema, names=_NAMES) + + assert code == generate(schema) + assert "async def prerequisite_sh_as(self) -> list[str]:" in code + assert "def with_repo_url(self, repo_url: str) -> Self:" in code + + +def test_load_names(tmp_path): + assert load_names(None) is None + + path = tmp_path / "names.json" + path.write_text("{}") # a schema without Query.formatIdentifiers + assert load_names(path) is None + + path.write_text( + json.dumps( + { + NAMES_FORMAT: {"withGPU": "with_gpu"}, + "PASCAL:CAPITALIZED": {"withGPU": "WithGpu"}, + } + ) + ) + assert load_names(path) == {"withGPU": "with_gpu"} + + +def test_enum_render_conventional(): + # With the engine's names, members are SCREAMING_SNAKE and their values + # the API's values, which go over the wire; the API's other spellings + # stay as deprecated aliases. + ctx = Context(names={"Default": "default", "PerSession": "per_session"}) + type_ = GraphQLEnumType( + "Compression", + { + "Gzip": GraphQLEnumValue("Gzip", description="Legacy."), + "GZIP": GraphQLEnumValue("Gzip", description="Gzip."), + "PerSession": GraphQLEnumValue("PerSession"), + "Default": GraphQLEnumValue("Default"), + "HTTP2": GraphQLEnumValue("HTTP2"), + }, + ) + assert EnumHandler(ctx).render(type_) == ( + "\n" + "class Compression(ValueEnum):\n" + "\n" + " DEFAULT = 'Default'\n" + " Default = 'Default'\n" + ' """.. deprecated:: Use DEFAULT instead."""\n' + "\n" + " GZIP = 'Gzip'\n" + ' """Gzip."""\n' + " Gzip = 'Gzip'\n" + ' """.. deprecated:: Use GZIP instead."""\n' + "\n" + " HTTP2 = 'HTTP2'\n" + "\n" + " PER_SESSION = 'PerSession'\n" + " PerSession = 'PerSession'\n" + ' """.. deprecated:: Use PER_SESSION instead."""\n' + ) + + +_ENUM_SCHEMA = """ + enum Policy { DEFAULT PER_SESSION Default PerSession } + type Query { + policy: Policy! + run(policy: Policy = PerSession): String! + %s + } +""" + +_ENUM_NAMES = { + "DEFAULT": "default", + "PER_SESSION": "per_session", + "Default": "default", + "PerSession": "per_session", + "run": "run", +} + + +def test_generate_enum_names(): + code = generate(build_schema(_ENUM_SCHEMA % _FORMAT_IDENTIFIERS), names=_ENUM_NAMES) + + assert "from dagger.client.base import Input, Root, Scalar, Type, ValueEnum" in code + assert "class Policy(ValueEnum):" in code + assert "PER_SESSION = 'PER_SESSION'" in code + assert "PerSession = 'PerSession'" in code + # A default names the canonical member, not a deprecated alias. + assert "policy: Policy | None = Policy.PER_SESSION" in code + + +def test_generate_enum_without_names(): + # Older schemas generate the code they always did. + code = generate(build_schema(_ENUM_SCHEMA % ""), names=_ENUM_NAMES) + + assert "from dagger.client.base import Enum, Input, Root, Scalar, Type" in code + assert "class Policy(Enum):" in code + assert "PerSession = 'PerSession'" in code + assert "policy: Policy | None = Policy.PerSession" in code + + +def test_generate_module_enum_values(): + # A dependency module's enum keeps its members as they always were: named + # by schema value, holding the module's value, and sent by name, since its + # values aren't schema values. + sdl = """ + directive @enumValue(value: String!) on ENUM_VALUE + enum Policy { DEFAULT PER_SESSION } + enum DepStatus { + ACTIVE @enumValue(value: "ACTIVE value") + INACTIVE @enumValue(value: "INACTIVE value") + } + type Query { + policy: Policy! + status(status: DepStatus = ACTIVE): DepStatus! + %s + } + """ + names = { + "DEFAULT": "default", + "PER_SESSION": "per_session", + "ACTIVE": "active", + "INACTIVE": "inactive", + "status": "status", + } + + code = generate(build_schema(sdl % _FORMAT_IDENTIFIERS), names=names) + + assert ( + "from dagger.client.base import Enum, Input, Root, Scalar, Type, ValueEnum" + in code + ) + assert "class Policy(ValueEnum):" in code + assert "class DepStatus(Enum):" in code + assert "ACTIVE = 'ACTIVE value'" in code + assert "status: DepStatus | None = DepStatus.ACTIVE" in code + + +# A partitioned schema, as a scope generates it: core and one client. +_PARTITIONED = """ + directive @sourceMap(module: String, filename: String) + on OBJECT | FIELD_DEFINITION | ENUM | ENUM_VALUE | INPUT_OBJECT + directive @expectedType(name: String!) on FIELD_DEFINITION | ARGUMENT_DEFINITION + directive @enumValue(value: String!) on ENUM_VALUE + + # As the engine serves it: the legacy values, and the conventional ones + # standing for them. + enum ImageMediaTypes { + OCIMediaTypes + DockerMediaTypes + OCI @enumValue(value: "OCIMediaTypes") + DOCKER @enumValue(value: "DockerMediaTypes") + } + type GitCommit { + id: ID! @expectedType(name: "GitCommit") + shortSHA: String! + parentSHAs: [String!]! + export(mediaTypes: ImageMediaTypes = OCI): String! + } + type Linter @sourceMap(module: "linter") { + id: ID! @expectedType(name: "Linter") + lintURL(baseURL: String!): String! + } + type Query { + gitCommit: GitCommit! + linter: Linter! @sourceMap(module: "linter") + %s + } +""" + +_PARTITIONED_NAMES = { + "Query": "query", + "GitCommit": "git_commit", + "gitCommit": "git_commit", + "shortSHA": "short_sha", + "parentSHAs": "parent_shas", + "export": "export", + "mediaTypes": "media_types", + "ImageMediaTypes": "image_media_types", + "OCI": "oci", + "DOCKER": "docker", + "OCIMediaTypes": "oci_media_types", + "DockerMediaTypes": "docker_media_types", + "Linter": "linter", + "linter": "linter", + "lintURL": "lint_url", + "baseURL": "base_url", + "formatIdentifiers": "format_identifiers", + "names": "names", +} + + +@pytest.fixture +def load_core(monkeypatch: pytest.MonkeyPatch): + namespace = types.ModuleType("dagger_clients") + namespace.__path__ = [] + monkeypatch.setitem(sys.modules, "dagger_clients", namespace) + + def load(code: str) -> types.ModuleType: + name = "dagger_clients.core" + module = types.ModuleType(name) + monkeypatch.setitem(sys.modules, name, module) + exec(compile(code, name, "exec"), module.__dict__) + return module + + return load + + +def test_core_package_with_names(load_core): + schema = build_schema(_PARTITIONED % _FORMAT_IDENTIFIERS) + code = core_package(schema, "v1.0.0-beta.21", _PARTITIONED_NAMES)["__init__.py"] + + assert "from dagger.client.base import ValueEnum as _ValueEnum" in code + assert "class ImageMediaTypes(_ValueEnum):" in code + assert "media_types: ImageMediaTypes | None = ImageMediaTypes.OCI" in code + + core = load_core(code) + media = core.ImageMediaTypes + assert [m.name for m in media] == ["DOCKER", "OCI"] + assert media.OCIMediaTypes is media.OCI + # Sent as the value it stands for, which every view has. + assert media.OCI.value == "OCIMediaTypes" + + commit = core.GitCommit(QueryContext()) + assert commit.short_sha + assert commit.parent_shas + # The legacy conversion's name keeps working, deprecated. + with pytest.warns(DeprecationWarning, match="parent_sh_as"): + commit.parent_sh_as().close() + + +def test_core_package_names_gate(load_core): + # The same schema without formatIdentifiers: the names don't apply. + schema = build_schema(_PARTITIONED % "") + code = core_package(schema, "v1.0.0-beta.20", _PARTITIONED_NAMES)["__init__.py"] + + assert code == core_package(schema, "v1.0.0-beta.20")["__init__.py"] + assert "_ValueEnum" not in code + assert "class ImageMediaTypes(_Enum):" in code + assert "def parent_sh_as(self)" in code + + with warnings.catch_warnings(): + warnings.simplefilter("error") + load_core(code) + + +def test_client_package_with_names(): + schema = build_schema(_PARTITIONED % _FORMAT_IDENTIFIERS) + _, files = client_package(schema, "linter", "./linter", names=_PARTITIONED_NAMES) + code = files["__init__.py"] + + assert "def lint_url(self, base_url: str) -> str:" in code + assert '_Arg("baseURL", base_url),' in code + + +def test_global_package_with_names(): + schema = build_schema(_PARTITIONED % _FORMAT_IDENTIFIERS) + code = global_package([schema], "v1.0.0-beta.21", _PARTITIONED_NAMES)["__init__.py"] + + assert "def git_commit(self) -> GitCommit:" in code + assert ".git_commit()" in code + + +def test_cli_reads_names(tmp_path, monkeypatch: pytest.MonkeyPatch): + schema = build_schema(_ENUM_SCHEMA % _FORMAT_IDENTIFIERS) + monkeypatch.setattr(cli, "read_schema", lambda _: (schema, "v1.0.0-beta.21")) + names = tmp_path / "names.json" + names.write_text(json.dumps({NAMES_FORMAT: _ENUM_NAMES})) + output = tmp_path / "gen.py" + + cli.main(["generate", "-i", "schema.json", "-n", str(names), "-o", str(output)]) + assert "class Policy(ValueEnum):" in output.read_text() + + cli.main(["generate", "-i", "schema.json", "-o", str(output)]) + assert "class Policy(Enum):" in output.read_text() + + +@pytest.mark.parametrize("member", ["PER_SESSION", "PerSession"]) +def test_value_enum_on_the_wire(member): + from dagger.client import base + from dagger.client._core import _scalar_literal + + class Policy(base.ValueEnum): + DEFAULT = "DEFAULT" + PER_SESSION = "PER_SESSION" + Default = "Default" + PerSession = "PerSession" + + value = Policy[member] + # Sent by value, so a deprecated alias sends the spelling it stands for. + assert _scalar_literal(value) == value.value + conv = make_converter(QueryContext()) + assert conv.unstructure(value) == value.value + # Read back by name, aliases included. + assert conv.structure(member, Policy) is value From eb07d514c9f82c3cd73c744860c21757e4ea5130 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Thu, 22 Oct 2026 16:32:56 +0000 Subject: [PATCH 3/9] sdk: call own interfaces by the engine's names From v1.0.0-beta.21 the engine names a module's declarations by its naming rules (get_url is getURL, Ready is READY), so the calls the runtime builds through the module's own interfaces must use those names. Before invoking a function of a module that declares interfaces, the runtime asks Query.formatIdentifiers, in batches, by raw query since the SDK files can't import bindings. The API being in the session's schema is the gate: the session is served in the module's view, so older modules keep the plain conversion. Interface arguments are now bound by their Python name. Signed-off-by: Alex Suraci --- sdk/src/dagger/mod/_converter.py | 25 ++- sdk/src/dagger/mod/_module.py | 32 ++- sdk/src/dagger/mod/_naming.py | 234 ++++++++++++++++++++ sdk/tests/mod/test_naming.py | 367 +++++++++++++++++++++++++++++++ 4 files changed, 650 insertions(+), 8 deletions(-) create mode 100644 sdk/src/dagger/mod/_naming.py create mode 100644 sdk/tests/mod/test_naming.py diff --git a/sdk/src/dagger/mod/_converter.py b/sdk/src/dagger/mod/_converter.py index 470fa539..15530af5 100644 --- a/sdk/src/dagger/mod/_converter.py +++ b/sdk/src/dagger/mod/_converter.py @@ -9,6 +9,7 @@ from dagger.client.base import Interface, Scalar, Type from dagger.mod import _api from dagger.mod._describe import TypeRef, describe_type +from dagger.mod._naming import SchemaNames from dagger.mod._resolver import Function from dagger.mod._utils import ( get_module, @@ -18,7 +19,6 @@ list_of, strip_annotations, syncify, - to_camel_case, ) logger = logging.getLogger(__name__) @@ -80,19 +80,27 @@ def to_interface_impl(proto: type) -> type[Interface]: msg = f"Unexpected interface type '{proto}'" raise TypeError(msg) + names = mod.schema_names methods = { - func.original_name: make_method(name, func, proto) + func.original_name: make_method(name, func, proto, names) for name, func in typ.functions.items() } + # The class name is the interface's schema name: it's what the client + # selects the type by (see `Type._graphql_name`). return type( - mod.main_cls.__name__ + proto.__name__, + names.interface_name(mod.main_cls.__name__, proto), (Interface,), {"_declaration": proto, **methods}, ) -def make_method(name: str, func: Function, proto: type) -> typing.Callable: # noqa: C901 +def make_method( # noqa: C901 + name: str, + func: Function, + proto: type, + names: SchemaNames | None = None, +) -> typing.Callable: """Generate method for interface client binding.""" ret_type = func.return_type _is_self = ret_type is proto @@ -101,16 +109,19 @@ def make_method(name: str, func: Function, proto: type) -> typing.Callable: # n ret_type = to_interface_impl(ret_type) # Need to convert names to GraphQL convention for query builder - gql_name = to_camel_case(name) + if names is None: + names = SchemaNames() + gql_name = names.field_name(name) gql_arg_names = { - param.name: to_camel_case(param.name) for param in func.parameters.values() + py_name: names.field_name(param.name) + for py_name, param in func.parameters.items() } # Generate query builder selection based on inputs def select(obj: Interface, *args, **kwargs): bound = func.signature.bind(obj, *args, **kwargs) args = [ - Arg(name=gql_arg_names[arg_name], value=arg_value) + Arg(name=gql_arg_names[arg_name], value=names.enum_value(arg_value)) for arg_name, arg_value in bound.arguments.items() if arg_name != "self" ] diff --git a/sdk/src/dagger/mod/_module.py b/sdk/src/dagger/mod/_module.py index e9b6c0d0..f7bf8c50 100644 --- a/sdk/src/dagger/mod/_module.py +++ b/sdk/src/dagger/mod/_module.py @@ -19,7 +19,7 @@ from dagger._exceptions import QueryError from dagger.client._core import configure_converter_enum from dagger.mod import _api -from dagger.mod._converter import make_converter, typedef_from +from dagger.mod._converter import make_converter, to_interface_impl, typedef_from from dagger.mod._describe import ( ArgumentDescription, EnumDescription, @@ -40,6 +40,7 @@ log_exception_only, transform_error, ) +from dagger.mod._naming import SchemaNames, resolve_schema_names from dagger.mod._resolver import ( Constructor, Field, @@ -92,6 +93,7 @@ def __init__(self, main_name: str = MAIN_OBJECT): self._objects: dict[str, ObjectType] = {} self._enums: dict[str, type[enum.Enum]] = {} self._main: ObjectType | None = None + self._schema_names = SchemaNames() # Escape hatch if there's too much noise from showing stack traces # from exceptions raised in functions by default. Not documented # intentionally for now. @@ -102,6 +104,31 @@ def main_cls(self) -> type[ObjectType]: assert self._main is not None return self._main.cls + @property + def schema_names(self) -> SchemaNames: + """Schema names of the module's interfaces, for calls through them.""" + return self._schema_names + + async def load_schema_names(self): + """Ask the engine how it names the module's interfaces. + + From engine version v1.0.0-beta.21 the engine names a module's + declarations by its naming rules. Calls through the module's + interfaces need those names, so get them before invoking anything. + """ + interfaces = [obj for obj in self._objects.values() if obj.interface] + if not interfaces: + return + names = await resolve_schema_names( + self.main_cls.__name__, + interfaces, + enums=self._enums.values(), + ) + if names is not None: + self._schema_names = names + # Bindings built before now used the older conversion. + to_interface_impl.cache_clear() + def is_main(self, other: ObjectType) -> bool: """Check if the given object is the main object of the module.""" return self.main_cls is other.cls @@ -234,6 +261,8 @@ async def invoke(self) -> str: }, ) + await self.load_schema_names() + result = await self.get_result( parent_name, parent_state, @@ -261,6 +290,7 @@ async def dispatch(self, request: Mapping[str, Any]) -> Any: except ValueError as e: msg = "Unable to decode the call request" raise InvalidInputError(msg, extra={"request": request}) from e + await self.load_schema_names() return await self.get_result( request["receiverType"], parent_state or {}, diff --git a/sdk/src/dagger/mod/_naming.py b/sdk/src/dagger/mod/_naming.py new file mode 100644 index 00000000..2c2e4160 --- /dev/null +++ b/sdk/src/dagger/mod/_naming.py @@ -0,0 +1,234 @@ +"""Schema names the engine gives a module's own declarations. + +The runtime registers Python names (``get_url``) and the engine turns them +into schema names (``getURL``). Calls the runtime builds itself, against its +own module's interfaces, have to use those schema names. + +From engine version v1.0.0-beta.21 the engine names a module's declarations +by its naming rules, which know acronyms (``URL``, ``HTTP``) a plain case +conversion can't. Rather than duplicate those rules here, the runtime asks the +engine to format its names (``Query.formatIdentifiers``). That API is only in +the views the engine names modules by those rules, and the runtime's session +is served in its module's view, so the API being there is the gate: older +modules keep the conversion they always had. +""" + +import dataclasses +import enum +import logging +import re +import typing +from collections.abc import Awaitable, Callable, Iterable + +from dagger._exceptions import QueryError +from dagger.client._core import Arg, Context, EnumName +from dagger.client._descriptor import missing_field +from dagger.mod._utils import to_camel_case + +if typing.TYPE_CHECKING: + from dagger.mod._resolver import ObjectType + +logger = logging.getLogger(__package__) + +CAMEL = "CAMEL" +PASCAL = "PASCAL" +SNAKE = "SNAKE" +SCREAMING_SNAKE = "SCREAMING_SNAKE" + +Formatter: typing.TypeAlias = Callable[[list[str], str], Awaitable[list[str]]] +"""Format names in a casing (``CAMEL``, ``PASCAL``, ``SNAKE`` or +``SCREAMING_SNAKE``).""" + +_CONVENTIONAL_ENUM_MEMBER = re.compile(r"[A-Z][A-Z0-9_]*") + + +@dataclasses.dataclass(slots=True) +class SchemaNames: + """The schema names of a module's interfaces and their members. + + Names not found here fall back to the conversion modules get before + v1.0.0-beta.21, which is also what an empty instance gives. + """ + + fields: dict[str, str] = dataclasses.field(default_factory=dict) + """Function and argument names, from the name the runtime registers.""" + + types: dict[type, str] = dataclasses.field(default_factory=dict) + """Interface type names, from the interface's class.""" + + enum_members: dict[type, dict[str, str]] = dataclasses.field(default_factory=dict) + """Member names of the module's own enums, by enum class, from the + member's Python name.""" + + def field_name(self, name: str) -> str: + """The schema name of a function or argument.""" + return self.fields.get(name) or to_camel_case(name) + + def interface_name(self, main_name: str, proto: type) -> str: + """The schema name of an interface declared in the module.""" + return self.types.get(proto) or main_name + proto.__name__ + + def enum_value(self, value: typing.Any) -> typing.Any: + """A value as it goes over the wire in a call through an interface. + + A member of one of the module's own enums is sent by its schema name, + which the engine formats (``Ready`` is ``READY``); anything else, and + any member not found here, is left for the client to convert, which + sends a member by its Python name. + """ + if isinstance(value, list | tuple): + return [self.enum_value(v) for v in value] + if isinstance(value, enum.Enum) and ( + name := self.enum_members.get(type(value), {}).get(value.name) + ): + return EnumName(name) + return value + + +async def resolve_schema_names( + main_name: str, + interfaces: Iterable["ObjectType"], + formatter: Formatter | None = None, + enums: Iterable[type[enum.Enum]] = (), +) -> SchemaNames | None: + """Ask the engine for the schema names of the module's interfaces. + + The member names of the module's own ``enums`` are resolved too, since + calls through an interface can pass them. + + Returns None if the engine doesn't name the module by its naming rules + (modules before v1.0.0-beta.21). + """ + interfaces = list(interfaces) + if not interfaces: + return None + + if formatter is None: + if not await supports_identifiers(): + return None + formatter = format_names + + names = sorted( + { + name + for iface in interfaces + for fn in iface.functions.values() + for name in (fn.name, *(p.name for p in fn.parameters.values())) + if name + } + ) + protos = [iface.cls for iface in interfaces] + proto_names = [proto.__name__ for proto in protos] + + camel = await formatter(names, CAMEL) if names else [] + snake = await formatter([main_name, *proto_names], SNAKE) + pascal = await formatter( + [*proto_names, *(f"{main_name}_{name}" for name in proto_names)], + PASCAL, + ) + + # Like the engine, namespace an interface with the module's name unless + # its name already starts with the module's name, comparing words. + main_snake, proto_snakes = snake[0], snake[1:] + types = {} + for i, proto in enumerate(protos): + proto_snake = proto_snakes[i] + if proto_snake == main_snake or proto_snake.startswith(f"{main_snake}_"): + types[proto] = pascal[i] + else: + types[proto] = pascal[len(protos) + i] + + return SchemaNames( + fields=dict(zip(names, camel, strict=True)), + types=types, + enum_members=await _enum_member_names(enums, formatter), + ) + + +async def _enum_member_names( + enums: Iterable[type[enum.Enum]], + formatter: Formatter, +) -> dict[type, dict[str, str]]: + """The schema names of the members of the module's enums, by enum class. + + Like the engine, members already named in GraphQL's convention (``READY``, + ``HTTP2``) keep their name; the others are formatted SCREAMING_SNAKE. + """ + enums = list(enums) + todo = sorted( + { + member.name + for cls in enums + for member in cls + if not _CONVENTIONAL_ENUM_MEMBER.fullmatch(member.name) + } + ) + formatted = ( + dict(zip(todo, await formatter(todo, SCREAMING_SNAKE), strict=True)) + if todo + else {} + ) + return { + cls: {member.name: formatted.get(member.name, member.name) for member in cls} + for cls in enums + } + + +_supported: bool | None = None + + +async def supports_identifiers() -> bool: + """Whether the session's schema has ``Query.formatIdentifiers``. + + The engine serves it in the views it names schemas by its naming rules + (v1.0.0-beta.21 and later), and only in those. The runtime's session is + served in its module's view, so it tells how the engine names the module. + Asked once per process. + """ + global _supported # noqa: PLW0603 + if _supported is None: + try: + await _format_identifiers([], CAMEL) + except QueryError as e: + if missing_field(e) is None: + raise + _supported = False + else: + _supported = True + return _supported + + +async def format_names(names: list[str], casing: str) -> list[str]: + """Format names with the engine's naming rules. + + A name the engine can't parse (non-ASCII, say) fails the whole batch. + The engine leaves such a name unchanged when it names a module, so do + the same, formatting the rest one by one. + """ + try: + return await _format_identifiers(names, casing) + except QueryError: + logger.debug("Failed to format names in a batch", exc_info=True) + + return [await _format_name(name, casing) for name in names] + + +async def _format_identifiers(names: list[str], casing: str) -> list[str]: + # The SDK files can't import the generated bindings: select by name. + ctx = Context().root_select( + "formatIdentifiers", + [Arg("names", names), Arg("casing", EnumName(casing))], + ) + return await ctx.execute(list[str]) + + +async def _format_name(name: str, casing: str) -> str: + ctx = ( + Context() + .root_select("identifier", [Arg("name", name)]) + .select("Identifier", "format", [Arg("casing", EnumName(casing))]) + ) + try: + return await ctx.execute(str) + except QueryError: + return name diff --git a/sdk/tests/mod/test_naming.py b/sdk/tests/mod/test_naming.py new file mode 100644 index 00000000..37c49744 --- /dev/null +++ b/sdk/tests/mod/test_naming.py @@ -0,0 +1,367 @@ +"""Calls through a module's own interfaces, named as the engine names them. + +The gate is the module session's schema having ``Query.formatIdentifiers``. +""" + +import enum +import typing +from typing import Self + +import pytest + +import dagger +from dagger._exceptions import QueryError, QueryErrorValue +from dagger.client._core import Context, EnumName +from dagger.mod import Module, _naming +from dagger.mod._converter import to_interface_impl +from dagger.mod._naming import ( + SchemaNames, + format_names, + resolve_schema_names, + supports_identifiers, +) + +pytestmark = [ + pytest.mark.anyio, +] + +# How an engine from v1.0.0-beta.21 formats the names below: acronyms are +# words of their own, which a plain case conversion can't tell. +ENGINE_NAMES = { + "CAMEL": { + "get_url": "getURL", + "com_url": "comURL", + "with_http_client": "withHTTPClient", + "speak": "speak", + "name": "name", + "fetch": "fetch", + "from": "from", + "wait": "wait", + "status": "status", + "statuses": "statuses", + }, + "SNAKE": { + "Pond": "pond", + "HttpFetcher": "http_fetcher", + "PondSpeaker": "pond_speaker", + "Waiter": "waiter", + }, + "PASCAL": { + "HttpFetcher": "HTTPFetcher", + "PondSpeaker": "PondSpeaker", + "Pond_HttpFetcher": "PondHTTPFetcher", + "Pond_PondSpeaker": "PondPondSpeaker", + "Waiter": "Waiter", + "Pond_Waiter": "PondWaiter", + }, + "SCREAMING_SNAKE": { + "Ready": "READY", + "HttpOk": "HTTP_OK", + }, +} + + +async def engine_formatter(names: list[str], casing: str) -> list[str]: + return [ENGINE_NAMES[casing][name] for name in names] + + +@pytest.fixture(autouse=True) +def fresh_bindings(): + to_interface_impl.cache_clear() + yield + to_interface_impl.cache_clear() + + +@pytest.fixture +def mod() -> Module: + m = Module("Pond") + + @m.interface + class HttpFetcher(typing.Protocol): + @m.function + def get_url(self, com_url: str) -> Self: ... + + @m.function + def with_http_client(self, name: str) -> Self: ... + + @m.function + def fetch(self, from_: str) -> Self: ... + + # Already starts with the module's name: not namespaced again. + @m.interface + class PondSpeaker(typing.Protocol): + @m.function + def speak(self) -> Self: ... + + @m.object_type + class Pond: + fetcher: HttpFetcher = dagger.field() + + return m + + +def interface(mod: Module, name: str) -> type: + return mod.get_object(name).cls + + +def interfaces(mod: Module): + return [obj for obj in mod._objects.values() if obj.interface] + + +def selection(obj) -> tuple[str, str, dict]: + field = obj._ctx.selections[-1] + return field.type_name, field.name, field.args + + +async def test_resolve_schema_names(mod: Module): + names = await resolve_schema_names("Pond", interfaces(mod), engine_formatter) + + assert names is not None + assert names.fields == { + "com_url": "comURL", + "fetch": "fetch", + "from": "from", + "get_url": "getURL", + "name": "name", + "speak": "speak", + "with_http_client": "withHTTPClient", + } + assert names.types == { + interface(mod, "HttpFetcher"): "PondHTTPFetcher", + interface(mod, "PondSpeaker"): "PondSpeaker", + } + + +async def test_resolve_schema_names_without_interfaces(): + async def fail(*_): + pytest.fail("unexpected call to the engine") + + assert await resolve_schema_names("Pond", [], fail) is None + + +async def test_resolve_schema_names_before_the_cut( + mod: Module, monkeypatch: pytest.MonkeyPatch +): + async def unsupported(): + return False + + monkeypatch.setattr(_naming, "supports_identifiers", unsupported) + + assert await resolve_schema_names("Pond", interfaces(mod)) is None + + +def test_legacy_schema_names(): + # Modules before v1.0.0-beta.21 keep the conversion they always had. + names = SchemaNames() + + class HttpFetcher: ... + + assert names.field_name("get_url") == "getUrl" + assert names.field_name("com_url") == "comUrl" + assert names.interface_name("Pond", HttpFetcher) == "PondHttpFetcher" + + +@pytest.mark.parametrize( + ("schema_names", "expected"), + [ + # before the cut + (False, ("PondHttpFetcher", "getUrl", {"comUrl": "x"})), + # from v1.0.0-beta.21 + (True, ("PondHTTPFetcher", "getURL", {"comURL": "x"})), + ], +) +async def test_interface_call_names(mod: Module, schema_names: bool, expected): + if schema_names: + names = await resolve_schema_names("Pond", interfaces(mod), engine_formatter) + assert names is not None + mod._schema_names = names + + impl = to_interface_impl(interface(mod, "HttpFetcher")) + assert impl.__name__ == expected[0] + assert impl._graphql_name() == expected[0] + + obj = impl(Context()) + assert selection(obj.get_url(com_url="x")) == expected + + +async def test_interface_call_renamed_arg(mod: Module): + # `from_` is registered as `from`: bind by the Python name, send the other. + impl = to_interface_impl(interface(mod, "HttpFetcher")) + + obj = impl(Context()) + assert selection(obj.fetch(from_="x")) == ( + "PondHttpFetcher", + "fetch", + {"from": "x"}, + ) + + +async def test_load_schema_names(mod: Module, monkeypatch: pytest.MonkeyPatch): + async def resolve(main_name, ifaces, **kwargs): + return await resolve_schema_names(main_name, ifaces, engine_formatter, **kwargs) + + monkeypatch.setattr("dagger.mod._module.resolve_schema_names", resolve) + stale = to_interface_impl(interface(mod, "HttpFetcher")) + + await mod.load_schema_names() + + impl = to_interface_impl(interface(mod, "HttpFetcher")) + assert impl is not stale + assert impl.__name__ == "PondHTTPFetcher" + + +async def test_load_schema_names_without_interfaces(monkeypatch: pytest.MonkeyPatch): + async def fail(*_, **__): + pytest.fail("unexpected call to the engine") + + monkeypatch.setattr("dagger.mod._module.resolve_schema_names", fail) + m = Module("Pond") + + @m.object_type + class Pond: + name: str = dagger.field() + + await m.load_schema_names() + + +async def test_interface_call_enum_members(): + # The engine names a module's enum members SCREAMING_SNAKE (Ready is + # READY), so a call through an interface sends that, not the Python name. + m = Module("Pond") + + @m.enum_type + class Status(enum.Enum): + Ready = "ready" + HttpOk = "ok" + DONE = "done" + + @m.interface + class Waiter(typing.Protocol): + @m.function + def wait(self, status: Status, statuses: list[Status]) -> Self: ... + + @m.object_type + class Pond: + waiter: Waiter = dagger.field() + + names = await resolve_schema_names( + "Pond", interfaces(m), engine_formatter, enums=[Status] + ) + assert names is not None + assert names.enum_members == { + Status: {"Ready": "READY", "HttpOk": "HTTP_OK", "DONE": "DONE"}, + } + + # Before the cut, the client sends a member by its Python name. + obj = to_interface_impl(interface(m, "Waiter"))(Context()) + _, _, args = selection(obj.wait(status=Status.Ready, statuses=[Status.HttpOk])) + assert args == {"status": Status.Ready, "statuses": [Status.HttpOk]} + + m._schema_names = names + to_interface_impl.cache_clear() + obj = to_interface_impl(interface(m, "Waiter"))(Context()) + _, _, args = selection( + obj.wait(status=Status.Ready, statuses=[Status.HttpOk, Status.DONE]) + ) + assert args == {"status": "READY", "statuses": ["HTTP_OK", "DONE"]} + assert isinstance(args["status"], EnumName) + # Bare in the query, as enum values. + query = obj.wait(status=Status.Ready, statuses=[Status.HttpOk])._ctx.build() + assert "wait(status: READY, statuses: [HTTP_OK])" in query + + +def validation_error() -> QueryError: + return QueryError( + [ + QueryErrorValue( + 'Cannot query field "formatIdentifiers" on type "Query".', + extensions={"code": "GRAPHQL_VALIDATION_FAILED"}, + ) + ], + "query", + ) + + +@pytest.fixture +def unknown_support(monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(_naming, "_supported", None) + + +@pytest.mark.usefixtures("unknown_support") +async def test_supports_identifiers(monkeypatch: pytest.MonkeyPatch): + calls = [] + + async def format_identifiers(names, casing): + calls.append((names, casing)) + return [] + + monkeypatch.setattr(_naming, "_format_identifiers", format_identifiers) + + assert await supports_identifiers() + assert await supports_identifiers() + assert calls == [([], "CAMEL")] # asked once + + +@pytest.mark.usefixtures("unknown_support") +async def test_supports_identifiers_before_the_cut(monkeypatch: pytest.MonkeyPatch): + # A view without the API refuses the query: the module keeps the old + # conversion. + async def format_identifiers(*_): + raise validation_error() + + monkeypatch.setattr(_naming, "_format_identifiers", format_identifiers) + + assert not await supports_identifiers() + + +@pytest.mark.usefixtures("unknown_support") +async def test_supports_identifiers_other_errors(monkeypatch: pytest.MonkeyPatch): + async def format_identifiers(*_): + raise QueryError([QueryErrorValue("boom")], "query") + + monkeypatch.setattr(_naming, "_format_identifiers", format_identifiers) + + with pytest.raises(QueryError, match="boom"): + await supports_identifiers() + + +def test_format_identifiers_query(): + ctx = Context().root_select( + "formatIdentifiers", + [ + _naming.Arg("names", ["get_url"]), + _naming.Arg("casing", EnumName("CAMEL")), + ], + ) + assert ctx.build() == ( + 'query {\n formatIdentifiers(names: ["get_url"], casing: CAMEL)\n}' + ) + + +async def test_format_names(monkeypatch: pytest.MonkeyPatch): + async def format_identifiers(names, casing): + return [ENGINE_NAMES[casing][n] for n in names] + + monkeypatch.setattr(_naming, "_format_identifiers", format_identifiers) + + assert await format_names(["get_url", "com_url"], "CAMEL") == [ + "getURL", + "comURL", + ] + + +async def test_format_names_unparseable(monkeypatch: pytest.MonkeyPatch): + # The engine keeps a name it can't parse as it is; one of those fails a + # whole batch, so the rest are formatted one by one. + async def format_identifiers(*_): + raise QueryError([QueryErrorValue("can't parse name")], "query") + + async def format_name(name, casing): + if not name.isascii(): + return name + return ENGINE_NAMES[casing][name] + + monkeypatch.setattr(_naming, "_format_identifiers", format_identifiers) + monkeypatch.setattr(_naming, "_format_name", format_name) + + assert await format_names(["get_url", "café"], "CAMEL") == ["getURL", "café"] From 6e8f66e142efaec74415cfa8e75d6882c9ed3840 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Thu, 22 Oct 2026 16:33:15 +0000 Subject: [PATCH 4/9] python-sdk: version generated entrypoints The engine reads `[imports.Dagger] dagger` from a dang.toml beside an entrypoint (dagger/dagger#14812) and serves it at v1.0.0-beta.20 without one. The entrypoint generated into a module now ships one, and the scope is generated in that version's view, so bindings and calls agree. A new module declares the engine it is created on, without build metadata, and so gets the engine's naming from beta.21. A module that already had an entrypoint but no dang.toml gets beta.20, what the engine already serves it, so regenerating never moves it silently. An existing dang.toml is kept. FunctionCachePolicy keeps its old spellings: they stay valid in every view. Signed-off-by: Alex Suraci --- mod.dang | 26 +++++++++++++++++++++--- python-sdk.dang | 54 ++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 74 insertions(+), 6 deletions(-) diff --git a/mod.dang b/mod.dang index 48556d77..2d7f77d2 100644 --- a/mod.dang +++ b/mod.dang @@ -27,9 +27,10 @@ type Mod { """ The engine version the scope's code is generated against, empty for the - engine's own view. Only a module that keeps a runtime of its own runs on a - version of its own, and only the caller knows which runtime the manifest - names. + view core-schema declares. A module that keeps a runtime of its own runs on + the version its manifest declares, and one on the entrypoint generated into + it on the version the entrypoint's dang.toml declares; only the caller + knows which the manifest names. """ let engineVersion: String! @@ -234,6 +235,25 @@ type Mod { .directory(entrypointOutput) .withNewFile("build.dang", buildDang) .withNewFile("workspace_reader.py", currentModule.source.file("runtime/workspace_reader.py").contents) + .withNewFile("dang.toml", dangToml) + } + + """ + The dang.toml beside the entrypoint, which declares the Dang and the engine + version the engine serves it at: the one the module's scope is generated + against. A dang.toml the module already has is its own and stays as it is. + """ + let dangToml: String! { + let path = rootPathed(vendorDirName + "/" + entrypointDirName + "/dang.toml") + if (ws.directory("/", include: [path]).exists(path)) { + ws.file("/" + path).contents + } else { + "dang = \"2.1\"\n\n[imports.Dagger]\ndagger = \"" + engineVersion + "\"\n" + } + } + + let rootPathed(rel: String!): String! { + if (rootPath == ".") { rel } else { rootPath + "/" + rel } } """ diff --git a/python-sdk.dang b/python-sdk.dang index 9a465c2f..f4784a60 100644 --- a/python-sdk.dang +++ b/python-sdk.dang @@ -195,7 +195,11 @@ type PythonSdk { ws: configured, entrypointMode: mode, migrating: migrating, - engineVersion: scopeEngineVersion(initialized, scope), + engineVersion: if (mode == generatedMode) { + entrypointVersion(initialized, scope, hadConfig == false) + } else { + scopeEngineVersion(initialized, scope) + }, clients: clients, ).generated.withWorkdir(scope) } @@ -364,6 +368,45 @@ type PythonSdk { } } + """ + The engine version a module on the entrypoint generated into it runs on: + the `[imports.Dagger] dagger` of the dang.toml beside that entrypoint, which + the engine reads for it (dagger/dagger#14812). A dang.toml that is there is + the module's, and is kept as it is. A new module declares the engine it is + created on, so it gets that engine's API and naming. A module that already + has an entrypoint but no such version gets the one the engine serves it + without, the last before the engine's naming rules, so generating it again + never moves it to them behind the user's back. + """ + let entrypointVersion(ws: Workspace!, scope: String!, fresh: Boolean!): String! { + let path = staticEntrypointPath + "/dang.toml" + if (scopeHasFile(ws, scope, path)) { + let config = tomlConfig(ws.file("/" + scopePath(scope, path)).contents) + let declares = config.fields.contains("imports") and + config.field(["imports"]).fields.contains("Dagger") and + config.field(["imports", "Dagger"]).fields.contains("dagger") + # `dagger = true` declares no version either. + let declared = if (declares) { + config.field(["imports", "Dagger", "dagger"]).asString rescue { + err: Error => "" + } + } else { + "" + } + if (declared == "") { unversionedEntrypointVersion } else { declared } + } else if (fresh) { + version.split("+")[0] ?? version + } else { + unversionedEntrypointVersion + } + } + + """ + The version the engine serves an entrypoint that declares none, the last + before the engine's naming rules (v1.0.0-beta.21). + """ + let unversionedEntrypointVersion: String! = "v1.0.0-beta.20" + """ Refuse a manifest that names both a runtime of the user's own and an entrypoint. The engine runs the entrypoint and never calls the runtime, @@ -729,12 +772,17 @@ type PythonSdk { normalizePath(path) } + let mode = entrypointModeOf(ws, modPath) Mod( rootPath: modPath, ws: ws, - entrypointMode: entrypointModeOf(ws, modPath), + entrypointMode: mode, migrating: migratingModule(ws, modPath), - engineVersion: scopeEngineVersion(ws, modPath), + engineVersion: if (mode == generatedMode) { + entrypointVersion(ws, modPath, false) + } else { + scopeEngineVersion(ws, modPath) + }, clients: null, ) } From bdd2b36eaf1b3f1375ff3a158f622f8e6ac98825 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Thu, 22 Oct 2026 16:33:42 +0000 Subject: [PATCH 5/9] e2e: check the names helper and dang.toml namesHelperTestCheck refuses a copy of engine/naming that differs from the pinned commit and runs the helper's tests. entrypointVersionCheck covers the version a generated entrypoint declares: new, existing without a dang.toml, and the module's own dang.toml. Signed-off-by: Alex Suraci --- .dagger/modules/e2e/main.dang | 70 +++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index 129b8e86..d415d74d 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -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. @@ -2089,6 +2123,42 @@ 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) + null + } + """ 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 From 8b8bd68e07d419bf294af2e380fbe558eb0e278e Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Thu, 22 Oct 2026 16:35:35 +0000 Subject: [PATCH 6/9] python-sdk: generate scopes with engine names Core, each client and the global client are generated with the names file helpers/names writes from their schemas, so a scope read in a v1.0.0-beta.21 view gets the engine's names; any other gets an empty file and the code it always had. Signed-off-by: Alex Suraci --- scope.dang | 63 +++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 55 insertions(+), 8 deletions(-) diff --git a/scope.dang b/scope.dang index f24c4aa9..82c0399e 100644 --- a/scope.dang +++ b/scope.dang @@ -445,17 +445,19 @@ type Scope { cores differ, as it refuses a client generated against another core. """ let globalSource(members: [ClientMember!]!): Directory! { - let mounted = if (members.length == 0) { - codegenEnv.withMountedFile(schemasPath + "/" + coreDirName + ".json", coreSchema) + let schemas = if (members.length == 0) { + directory.withFile(coreDirName + ".json", coreSchema) } else { - members.reduce(codegenEnv) { ctr, member => - ctr.withMountedFile(schemasPath + "/" + member.dir + ".json", clientSchema(member)) + members.reduce(directory) { dir, member => + dir.withFile(member.dir + ".json", clientSchema(member)) } } let names = if (members.length == 0) { [coreDirName] } else { members.map { member => member.dir } } let inputs = names.reduce([] :: [String!]!) { args, name => args + ["-i", schemasPath + "/" + name + ".json"] } - mounted - .withExec([codegenPython, "-m", "codegen", "generate-global"] + inputs + ["-o", outputPath]) + codegenEnv + .withMountedDirectory(schemasPath, schemas) + .withMountedFile(namesPath, NamesHelper().namesFile(schemas)) + .withExec([codegenPython, "-m", "codegen", "generate-global"] + inputs + ["-n", namesPath, "-o", outputPath]) .directory(outputPath + "/" + globalPackage) } @@ -473,7 +475,8 @@ type Scope { let coreSource: Directory! { codegenEnv .withMountedFile(schemaPath, coreSchema) - .withExec([codegenPython, "-m", "codegen", "generate-core", "-i", schemaPath, "-o", outputPath]) + .withMountedFile(namesPath, NamesHelper().namesOf(coreSchema)) + .withExec([codegenPython, "-m", "codegen", "generate-core", "-i", schemaPath, "-n", namesPath, "-o", outputPath]) .directory(outputPath) } @@ -584,9 +587,10 @@ type Scope { let pin = if (member.pin == null) { [] :: [String!]! } else { ["--pin", member.pin ?? ""] } codegenEnv .withMountedFile(schemaPath, clientSchema(member)) + .withMountedFile(namesPath, NamesHelper().namesOf(clientSchema(member))) .withExec([ codegenPython, "-m", "codegen", "generate-client", - "-i", schemaPath, "-o", outputPath, + "-i", schemaPath, "-n", namesPath, "-o", outputPath, "--name", member.name, "--ref", member.ref, "--core-digest", coreDigest, ] + pin) .directory(outputPath) @@ -693,6 +697,7 @@ type Scope { let stripScriptPath: String! = "/strip-dev-sections.py" let schemaPath: String! = "/schema.json" let schemasPath: String! = "/schemas" + let namesPath: String! = "/names.json" let coreOnlyScriptPath: String! = "/core-only.py" let coreOnlyPath: String! = "/core-only.json" let outputPath: String! = "/generated" @@ -837,3 +842,45 @@ type OutsidePath { self } } + +""" +The names helper, helpers/names, which writes the names file the code +generator reads: a schema's names in snake_case, as the engine formats them. + +A schema served at v1.0.0-beta.21 or later is named by the engine's naming +rules, and has Query.formatIdentifiers to tell how to write its names. This +module is served before that version, so it can't call it; the helper formats +the names with a copy of the engine's naming package instead. For a schema +without Query.formatIdentifiers it writes a file with no names, and the +generator keeps its own conversion. +""" +type NamesHelper { + pub tool: Container! { + container + .from("golang:1.25-alpine") + .withoutEntrypoint + .withMountedCache("/go/pkg/mod", cacheVolume("go-mod")) + .withMountedCache("/root/.cache/go-build", cacheVolume("go-build")) + .withDirectory("/helper", currentModule.source.directory("helpers/names")) + .withWorkdir("/helper") + .withExec(["go", "build", "-o", "/usr/local/bin/names", "."]) + } + + """ + The names file of one introspection result. + """ + pub namesOf(schema: File!): File! { + namesFile(directory.withFile("schema.json", schema)) + } + + """ + The names file of every introspection result in a directory, the schemas + of one scope, which share a version. + """ + pub namesFile(schemas: Directory!): File! { + tool + .withMountedDirectory("/schemas", schemas) + .withExec(["sh", "-c", "names -o /names.json /schemas/*.json"]) + .file("/names.json") + } +} From d947a273a3875d40f023b4f879027547b64277cd Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Thu, 22 Oct 2026 17:18:32 +0000 Subject: [PATCH 7/9] helpers: re-pin engine/naming, gate on release Re-pin the copy of engine/naming to dagger/dagger 3bae26f, where K8s and K3s are terms of their own. Released engines before v1.0.0-beta.21 (beta.19, beta.20) serve Query.formatIdentifiers in every v1 view but still name modules by their legacy rules, so the schema alone is not a sufficient gate there. The helper now takes the engine's version (-engine) and writes no names for a release before the cut; scope.dang passes it. Signed-off-by: Alex Suraci --- helpers/names/main.go | 38 +++- helpers/names/main_test.go | 37 ++++ helpers/names/naming/dictionary.go | 6 + helpers/names/naming/pin.go | 2 +- helpers/names/naming/testdata/vectors.json | 195 +++++++++++++++++++++ helpers/names/naming/version.go | 6 +- scope.dang | 6 +- 7 files changed, 280 insertions(+), 10 deletions(-) diff --git a/helpers/names/main.go b/helpers/names/main.go index 42834c93..2cf649b5 100644 --- a/helpers/names/main.go +++ b/helpers/names/main.go @@ -10,10 +10,14 @@ // package instead (see naming/pin.go), keyed by the schema's __schemaVersion like // formatIdentifiers(version:). // -// The gate is the one formatIdentifiers has: a schema without it gets an empty -// names file, and the generator keeps its legacy conversion. +// 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 -o ... +// usage: names [-engine ] -o ... package main import ( @@ -35,6 +39,10 @@ import ( // 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 @@ -53,11 +61,12 @@ 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 -o ...") + return fmt.Errorf("usage: names [-engine ] -o ...") } schemas := make([]schema, 0, flags.NArg()) @@ -73,7 +82,11 @@ func run(args []string, stdout, stderr io.Writer) error { schemas = append(schemas, s) } - file, warnings := namesFile(schemas) + file := File{} + var warnings []string + if namesSchemas(*engine) { + file, warnings = namesFile(schemas) + } for _, w := range warnings { fmt.Fprintln(stderr, "WARNING:", w) } @@ -88,6 +101,21 @@ func run(args []string, stdout, stderr io.Writer) error { 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. diff --git a/helpers/names/main_test.go b/helpers/names/main_test.go index e53aa8b1..0ad5a9b2 100644 --- a/helpers/names/main_test.go +++ b/helpers/names/main_test.go @@ -36,9 +36,17 @@ func introspection(version string, queryFields ...string) string { } func generate(t *testing.T, schemas ...string) (File, string) { + t.Helper() + return generateOn(t, "", schemas...) +} + +func generateOn(t *testing.T, engine string, schemas ...string) (File, string) { t.Helper() dir := t.TempDir() args := []string{"-o", filepath.Join(dir, "names.json")} + if engine != "" { + args = append(args, "-engine", engine) + } for i, s := range schemas { path := filepath.Join(dir, "schema"+string(rune('a'+i))+".json") if err := os.WriteFile(path, []byte(s), 0o644); err != nil { @@ -101,6 +109,35 @@ func TestNamesWithFormatIdentifiers(t *testing.T) { } } +// Released engines before v1.0.0-beta.21 serve formatIdentifiers in every v1 +// view, but name modules by their legacy rules. +func TestNamesEngineGate(t *testing.T) { + schema := introspection("v1.0.0", "formatIdentifiers", "gitRepository") + for engine, names := range map[string]bool{ + "v1.0.0-beta.19": false, + "v1.0.0-beta.20+0da36c8d": false, + "v1.0.0-beta.21": true, + "v1.0.0-beta.22": true, + "v1.0.0-dev-0123456789ab": true, + "v1.0.0": true, + "devel": true, + } { + file, _ := generateOn(t, engine, schema) + if got := len(file) > 0; got != names { + t.Errorf("engine %s: names %v, want %v", engine, got, names) + } + } +} + +// The pinned dictionary: K8s is a term of its own, however it's written. +func TestNamesDictionary(t *testing.T) { + schema := strings.Replace(introspection("v1.0.0-beta.21", "formatIdentifiers"), "withRemote", "withK8SCluster", 1) + file, _ := generate(t, schema) + if got := file[SnakeFormat]["withK8SCluster"]; got != "with_k8s_cluster" { + t.Errorf("withK8SCluster: got %q", got) + } +} + // A schema without Query.formatIdentifiers is named by the legacy rules: the // file has no format, and the generator keeps its own conversion. func TestNamesWithoutFormatIdentifiers(t *testing.T) { diff --git a/helpers/names/naming/dictionary.go b/helpers/names/naming/dictionary.go index 5e7891f9..c13f6d53 100644 --- a/helpers/names/naming/dictionary.go +++ b/helpers/names/naming/dictionary.go @@ -189,4 +189,10 @@ var initialTerms = []Term{ {Spelling: "GraphQL", Capitalized: "GraphQL"}, {Spelling: "3D", Capitalized: "3D"}, {Spelling: "2D", Capitalized: "2D"}, + + // Numeronym product names spelled with a fixed lowercase "s", not + // acronyms: without these, K8STools would keep its author's K8S (and + // K8sTools, k8s-tools their K8s), so the spellings wouldn't agree. + {Spelling: "K8s", Capitalized: "K8s"}, + {Spelling: "K3s", Capitalized: "K3s"}, } diff --git a/helpers/names/naming/pin.go b/helpers/names/naming/pin.go index ec90baa3..4ef06fa8 100644 --- a/helpers/names/naming/pin.go +++ b/helpers/names/naming/pin.go @@ -12,5 +12,5 @@ package naming // vectors as the engine does. const ( Source = "https://github.com/dagger/dagger/tree/" + Commit + "/engine/naming" - Commit = "198d001192d3179a8215980e97c766026f2dd0c2" + Commit = "3bae26f41fbfd1ceb7f65ea515da3f72939e76a2" ) diff --git a/helpers/names/naming/testdata/vectors.json b/helpers/names/naming/testdata/vectors.json index c0026717..9b7570ab 100644 --- a/helpers/names/naming/testdata/vectors.json +++ b/helpers/names/naming/testdata/vectors.json @@ -1343,6 +1343,201 @@ "SNAKE": "sha256s" } }, + { + "input": "K8STools", + "words": [ + { + "kind": "TERM", + "text": "K8s", + "suffix": "", + "capitalized": "K8s" + }, + { + "kind": "WORD", + "text": "tools", + "suffix": "", + "capitalized": "Tools" + } + ], + "formats": { + "CAMEL": "k8sTools", + "CAMEL_CAPITALIZED": "k8sTools", + "FLAT": "k8stools", + "KEBAB": "k8s-tools", + "PASCAL": "K8sTools", + "PASCAL_CAPITALIZED": "K8sTools", + "SCREAMING_SNAKE": "K8S_TOOLS", + "SNAKE": "k8s_tools" + } + }, + { + "input": "K8sTools", + "words": [ + { + "kind": "TERM", + "text": "K8s", + "suffix": "", + "capitalized": "K8s" + }, + { + "kind": "WORD", + "text": "tools", + "suffix": "", + "capitalized": "Tools" + } + ], + "formats": { + "CAMEL": "k8sTools", + "CAMEL_CAPITALIZED": "k8sTools", + "FLAT": "k8stools", + "KEBAB": "k8s-tools", + "PASCAL": "K8sTools", + "PASCAL_CAPITALIZED": "K8sTools", + "SCREAMING_SNAKE": "K8S_TOOLS", + "SNAKE": "k8s_tools" + } + }, + { + "input": "k8s-tools", + "words": [ + { + "kind": "TERM", + "text": "K8s", + "suffix": "", + "capitalized": "K8s" + }, + { + "kind": "WORD", + "text": "tools", + "suffix": "", + "capitalized": "Tools" + } + ], + "formats": { + "CAMEL": "k8sTools", + "CAMEL_CAPITALIZED": "k8sTools", + "FLAT": "k8stools", + "KEBAB": "k8s-tools", + "PASCAL": "K8sTools", + "PASCAL_CAPITALIZED": "K8sTools", + "SCREAMING_SNAKE": "K8S_TOOLS", + "SNAKE": "k8s_tools" + } + }, + { + "input": "K8S_TOOLS", + "words": [ + { + "kind": "TERM", + "text": "K8s", + "suffix": "", + "capitalized": "K8s" + }, + { + "kind": "WORD", + "text": "tools", + "suffix": "", + "capitalized": "Tools" + } + ], + "formats": { + "CAMEL": "k8sTools", + "CAMEL_CAPITALIZED": "k8sTools", + "FLAT": "k8stools", + "KEBAB": "k8s-tools", + "PASCAL": "K8sTools", + "PASCAL_CAPITALIZED": "K8sTools", + "SCREAMING_SNAKE": "K8S_TOOLS", + "SNAKE": "k8s_tools" + } + }, + { + "input": "MyK8SCluster", + "words": [ + { + "kind": "WORD", + "text": "my", + "suffix": "", + "capitalized": "My" + }, + { + "kind": "TERM", + "text": "K8s", + "suffix": "", + "capitalized": "K8s" + }, + { + "kind": "WORD", + "text": "cluster", + "suffix": "", + "capitalized": "Cluster" + } + ], + "formats": { + "CAMEL": "myK8sCluster", + "CAMEL_CAPITALIZED": "myK8sCluster", + "FLAT": "myk8scluster", + "KEBAB": "my-k8s-cluster", + "PASCAL": "MyK8sCluster", + "PASCAL_CAPITALIZED": "MyK8sCluster", + "SCREAMING_SNAKE": "MY_K8S_CLUSTER", + "SNAKE": "my_k8s_cluster" + } + }, + { + "input": "K3SServer", + "words": [ + { + "kind": "TERM", + "text": "K3s", + "suffix": "", + "capitalized": "K3s" + }, + { + "kind": "WORD", + "text": "server", + "suffix": "", + "capitalized": "Server" + } + ], + "formats": { + "CAMEL": "k3sServer", + "CAMEL_CAPITALIZED": "k3sServer", + "FLAT": "k3sserver", + "KEBAB": "k3s-server", + "PASCAL": "K3sServer", + "PASCAL_CAPITALIZED": "K3sServer", + "SCREAMING_SNAKE": "K3S_SERVER", + "SNAKE": "k3s_server" + } + }, + { + "input": "k3s_server", + "words": [ + { + "kind": "TERM", + "text": "K3s", + "suffix": "", + "capitalized": "K3s" + }, + { + "kind": "WORD", + "text": "server", + "suffix": "", + "capitalized": "Server" + } + ], + "formats": { + "CAMEL": "k3sServer", + "CAMEL_CAPITALIZED": "k3sServer", + "FLAT": "k3sserver", + "KEBAB": "k3s-server", + "PASCAL": "K3sServer", + "PASCAL_CAPITALIZED": "K3sServer", + "SCREAMING_SNAKE": "K3S_SERVER", + "SNAKE": "k3s_server" + } + }, { "input": "IDsFoo", "words": [ diff --git a/helpers/names/naming/version.go b/helpers/names/naming/version.go index 535f11f0..acc02d6d 100644 --- a/helpers/names/naming/version.go +++ b/helpers/names/naming/version.go @@ -7,8 +7,10 @@ import ( ) // FirstVersion is the engine version that introduced identifier parsing, -// with the Initial dictionary. The engine names modules that declare an older -// engineVersion with its previous (strcase) rules instead; see +// with the Initial dictionary. Dictionaries compare by base version, so every +// v1.0.0 prerelease selects it too; which modules the engine names with it at +// all is decided by its own gate (core.IdentifierNamingVersion, +// v1.0.0-beta.21), and older modules keep the previous (strcase) rules. See // hack/designs/identifier-casing.md. const FirstVersion = "v1.0.0" diff --git a/scope.dang b/scope.dang index 82c0399e..48eec0f5 100644 --- a/scope.dang +++ b/scope.dang @@ -875,12 +875,14 @@ type NamesHelper { """ The names file of every introspection result in a directory, the schemas - of one scope, which share a version. + of one scope, which share a version. The engine's version goes along: + released engines before v1.0.0-beta.21 serve Query.formatIdentifiers but + don't name schemas by its rules. """ pub namesFile(schemas: Directory!): File! { tool .withMountedDirectory("/schemas", schemas) - .withExec(["sh", "-c", "names -o /names.json /schemas/*.json"]) + .withExec(["sh", "-c", "names -engine \"$1\" -o /names.json /schemas/*.json", "names", version]) .file("/names.json") } } From b5cc4218a92dcc9326e3616bb541a6a19daaefd3 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Thu, 22 Oct 2026 17:18:37 +0000 Subject: [PATCH 8/9] sdk: gate runtime names on release, read enums The runtime's gate also checks Query.version: released engines before v1.0.0-beta.21 serve formatIdentifiers but name modules by their legacy rules. Calls through a module's own interfaces that return its enums (or lists of them) now read the members by the names the engine gave them (READY for Ready), the reverse of how they're sent. Signed-off-by: Alex Suraci --- sdk/src/dagger/mod/_converter.py | 5 ++ sdk/src/dagger/mod/_naming.py | 76 ++++++++++++++++++++++++--- sdk/tests/mod/test_naming.py | 89 ++++++++++++++++++++++++++++++++ 3 files changed, 164 insertions(+), 6 deletions(-) diff --git a/sdk/src/dagger/mod/_converter.py b/sdk/src/dagger/mod/_converter.py index 15530af5..5146945a 100644 --- a/sdk/src/dagger/mod/_converter.py +++ b/sdk/src/dagger/mod/_converter.py @@ -147,7 +147,12 @@ def chain_method(self, *args, **kwargs): # Anything else triggers execution (async) async def exec_method(self, *args, **kwargs): _ctx = select(self, *args, **kwargs) + # The module's own enums come back by the names the engine gave them. + if read := names.enum_reader(ret_type): + return read(await _ctx.execute(str)) if cls := list_of(ret_type): + if read := names.enum_reader(cls): + return [read(v) for v in await _ctx.execute(list[str])] if cls is proto: cls = type(self) elif is_dagger_interface_type(cls): diff --git a/sdk/src/dagger/mod/_naming.py b/sdk/src/dagger/mod/_naming.py index 2c2e4160..60dce5d7 100644 --- a/sdk/src/dagger/mod/_naming.py +++ b/sdk/src/dagger/mod/_naming.py @@ -84,6 +84,18 @@ def enum_value(self, value: typing.Any) -> typing.Any: return EnumName(name) return value + def enum_reader(self, cls: typing.Any) -> Callable[[str], enum.Enum] | None: + """Read a member of one of the module's own enums by its schema name. + + The engine returns a member by the name it gave it (``READY``), not + by its Python name (``Ready``). None for any other type. + """ + members = self.enum_members.get(cls) if isinstance(cls, type) else None + if not members: + return None + python = {schema: member for member, schema in members.items()} + return lambda name: cls[python.get(name, name)] + async def resolve_schema_names( main_name: str, @@ -176,17 +188,25 @@ async def _enum_member_names( _supported: bool | None = None +IDENTIFIER_CASING_VERSION = "v1.0.0-beta.21" +"""The first engine release that names modules by its naming rules.""" -async def supports_identifiers() -> bool: - """Whether the session's schema has ``Query.formatIdentifiers``. - The engine serves it in the views it names schemas by its naming rules - (v1.0.0-beta.21 and later), and only in those. The runtime's session is - served in its module's view, so it tells how the engine names the module. - Asked once per process. +async def supports_identifiers() -> bool: + """Whether the engine names the module by its naming rules. + + From v1.0.0-beta.21 the engine serves ``Query.formatIdentifiers`` in the + views it names schemas by those rules, and only in those. The runtime's + session is served in its module's view, so the API being there tells how + the engine names the module. Released engines before that serve the API + in every v1 view but name modules by their legacy rules, so the engine's + version is checked first. Asked once per process. """ global _supported # noqa: PLW0603 if _supported is None: + if not names_schemas(await _engine_version()): + _supported = False + return _supported try: await _format_identifiers([], CAMEL) except QueryError as e: @@ -198,6 +218,50 @@ async def supports_identifiers() -> bool: return _supported +_SEMVER = re.compile( + r"^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$" +) + + +def names_schemas(engine: str) -> bool: + """Whether an engine release names schemas by its naming rules. + + A release from v1.0.0-beta.21 on. An unreadable version leaves the + decision to the schema. + """ + version, cut = _SEMVER.match(engine), _SEMVER.match(IDENTIFIER_CASING_VERSION) + assert cut is not None + if version is None: + return True + return not _precedes(version, cut) + + +def _precedes(a: re.Match[str], b: re.Match[str]) -> bool: + """Semver precedence of two versions matched by ``_SEMVER``.""" + core_a, core_b = tuple(map(int, a.groups()[:3])), tuple(map(int, b.groups()[:3])) + if core_a != core_b: + return core_a < core_b + pre_a, pre_b = a.group(4), b.group(4) + if not pre_a or not pre_b: + # A release follows its prereleases. + return bool(pre_a) and not pre_b + ids_a, ids_b = pre_a.split("."), pre_b.split(".") + for x, y in zip(ids_a, ids_b, strict=False): + if x == y: + continue + if x.isdigit() and y.isdigit(): + return int(x) < int(y) + if x.isdigit() or y.isdigit(): + # Numbers come before words. + return x.isdigit() + return x < y + return len(ids_a) < len(ids_b) + + +async def _engine_version() -> str: + return await Context().root_select("version", []).execute(str) + + async def format_names(names: list[str], casing: str) -> list[str]: """Format names with the engine's naming rules. diff --git a/sdk/tests/mod/test_naming.py b/sdk/tests/mod/test_naming.py index 37c49744..0d2fc8f4 100644 --- a/sdk/tests/mod/test_naming.py +++ b/sdk/tests/mod/test_naming.py @@ -17,6 +17,7 @@ from dagger.mod._naming import ( SchemaNames, format_names, + names_schemas, resolve_schema_names, supports_identifiers, ) @@ -270,6 +271,52 @@ class Pond: assert "wait(status: READY, statuses: [HTTP_OK])" in query +@pytest.mark.parametrize("schema_names", [False, True]) +async def test_interface_call_enum_results( + monkeypatch: pytest.MonkeyPatch, schema_names: bool +): + # The engine returns a module's enum members by the names it gave them. + m = Module("Pond") + + @m.enum_type + class Status(enum.Enum): + Ready = "ready" + HttpOk = "ok" + + @m.interface + class Waiter(typing.Protocol): + @m.function + async def status(self) -> Status: ... + + @m.function + async def statuses(self) -> list[Status]: ... + + @m.object_type + class Pond: + waiter: Waiter = dagger.field() + + if schema_names: + names = await resolve_schema_names( + "Pond", interfaces(m), engine_formatter, enums=[Status] + ) + assert names is not None + m._schema_names = names + status, statuses = "READY", ["HTTP_OK", "READY"] + else: + # Before the cut, they're the Python names. + status, statuses = "Ready", ["HttpOk", "Ready"] + + async def execute(ctx, return_type=None): + value = statuses if ctx.selections[-1].name == "statuses" else status + return ctx.converter.structure(value, return_type) + + monkeypatch.setattr(Context, "execute", execute) + obj = to_interface_impl(interface(m, "Waiter"))(Context()) + + assert await obj.status() is Status.Ready + assert await obj.statuses() == [Status.HttpOk, Status.Ready] + + def validation_error() -> QueryError: return QueryError( [ @@ -286,6 +333,48 @@ def validation_error() -> QueryError: def unknown_support(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(_naming, "_supported", None) + async def engine_version(): + return "v1.0.0-beta.21" + + monkeypatch.setattr(_naming, "_engine_version", engine_version) + + +@pytest.mark.usefixtures("unknown_support") +async def test_supports_identifiers_released_before_the_cut( + monkeypatch: pytest.MonkeyPatch, +): + # Released engines before v1.0.0-beta.21 serve the API in every v1 view, + # but name modules by their legacy rules. + async def engine_version(): + return "v1.0.0-beta.20+0da36c8d" + + async def format_identifiers(*_): + pytest.fail("unexpected call to formatIdentifiers") + + monkeypatch.setattr(_naming, "_engine_version", engine_version) + monkeypatch.setattr(_naming, "_format_identifiers", format_identifiers) + + assert not await supports_identifiers() + + +@pytest.mark.parametrize( + ("engine", "expected"), + [ + ("v1.0.0-beta.19", False), + ("v1.0.0-beta.20+0da36c8d", False), + ("v0.21.9", False), + ("v1.0.0-beta.21", True), + ("v1.0.0-beta.100", True), + ("v1.0.0-dev-0123456789ab", True), + ("v1.0.0-rc.1", True), + ("v1.0.0", True), + ("v1.1.0", True), + ("devel", True), + ], +) +def test_names_schemas(engine: str, expected: bool): + assert names_schemas(engine) is expected + @pytest.mark.usefixtures("unknown_support") async def test_supports_identifiers(monkeypatch: pytest.MonkeyPatch): From bc3561996182f5ca46b8fdf0ee31d8531e6fdf73 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Thu, 22 Oct 2026 17:19:33 +0000 Subject: [PATCH 9/9] python-sdk: keep a migrated module's naming A module moving onto the generated entrypoint from a runtime whose manifest declares v1.0.0-beta.21 or later was already named by the engine's rules: its dang.toml declares that version rather than beta.20, so its code keeps working. Signed-off-by: Alex Suraci --- .dagger/modules/e2e/main.dang | 14 +++++++++++ python-sdk.dang | 44 +++++++++++++++++++++++++++++++---- 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index d415d74d..027b2a42 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -2156,9 +2156,23 @@ type E2e { 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 diff --git a/python-sdk.dang b/python-sdk.dang index f4784a60..4c8d8e43 100644 --- a/python-sdk.dang +++ b/python-sdk.dang @@ -349,8 +349,10 @@ type PythonSdk { """ The engine version a module's scope generates against: the one its manifest declares, and only while the module keeps a runtime of its own, which runs - it on that version. A module on an entrypoint runs on the engine's own - version, and so does one this SDK takes over from the builtin runtime. A + it on that version. A module on the shared entrypoint runs on the version + the engine serves an entrypoint that declares none, which core-schema's + view matches, and so does one this SDK takes over from the builtin runtime; + one on the entrypoint generated into it runs on entrypointVersion. A pre-1.0 manifest's version outlives `dagger module migrate`, and generating against that view writes bindings around a core the session does not serve, which the generator then refuses beside a client read in the engine's view. @@ -373,8 +375,10 @@ type PythonSdk { the `[imports.Dagger] dagger` of the dang.toml beside that entrypoint, which the engine reads for it (dagger/dagger#14812). A dang.toml that is there is the module's, and is kept as it is. A new module declares the engine it is - created on, so it gets that engine's API and naming. A module that already - has an entrypoint but no such version gets the one the engine serves it + created on, so it gets that engine's API and naming. A module moving onto + the entrypoint from a runtime keeps the version its manifest declares when + that already named it by the engine's rules. Any other module that already + has a config but no such version gets the one the engine serves it without, the last before the engine's naming rules, so generating it again never moves it to them behind the user's back. """ @@ -397,10 +401,40 @@ type PythonSdk { } else if (fresh) { version.split("+")[0] ?? version } else { - unversionedEntrypointVersion + # A module moving onto the entrypoint from a runtime that already + # named it by the engine's rules keeps that version. + let declared = declaredEngineVersion(ws, scope) + if (declared.containsMatch("^v[0-9]+\\.[0-9]+\\.[0-9]+") and releasePrecedes(declared, identifierCasingVersion) == false) { + declared.split("+")[0] ?? declared + } else { + unversionedEntrypointVersion + } } } + """ + The engineVersion a scope's module config declares, or empty. + """ + let declaredEngineVersion(ws: Workspace!, scope: String!): String! { + if (hasModuleConfig(ws, scope)) { + let config = manifestSettings(ws, scope) + if (config.fields.contains("engineVersion")) { + config.field(["engineVersion"]).asString rescue { + err: Error => "" + } + } else { + "" + } + } else { + "" + } + } + + """ + The first engine release that names modules by its naming rules. + """ + let identifierCasingVersion: String! = "v1.0.0-beta.21" + """ The version the engine serves an entrypoint that declares none, the last before the engine's naming rules (v1.0.0-beta.21).