8000 feat(go): allow multiline pragmas by jedevc · Pull Request #10594 · dagger/dagger · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat(go): allow multiline pragmas #10594

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 38 additions & 32 deletions cmd/codegen/generator/go/templates/module_funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"strings"

. "github.com/dave/jennifer/jen" //nolint:stylecheck
"github.com/mitchellh/mapstructure"
)

const errorTypeName = "error"
Expand Down Expand Up @@ -136,16 +137,10 @@ func (spec *funcTypeSpec) TypeDefCode() (*Statement, error) {
if argSpec.sourceMap != nil {
argOptsCode = append(argOptsCode, Id("SourceMap").Op(":").Add(argSpec.sourceMap.TypeDefCode()))
}
if argSpec.defaultValue != "" {
defaultValue := argSpec.defaultValue

var v any
if err := json.Unmarshal([]byte(defaultValue), &v); err != nil {
return nil, fmt.Errorf("default value %q must be valid JSON: %w", defaultValue, err)
}

if argSpec.hasDefaultValue {
var defaultValue string
if enumType, ok := argSpec.typeSpec.(*parsedEnumTypeReference); ok {
v, ok := v.(string)
v, ok := argSpec.defaultValue.(string)
if !ok {
return nil, fmt.Errorf("unknown enum value %q", v)
}
Expand All @@ -154,6 +149,12 @@ func (spec *funcTypeSpec) TypeDefCode() (*Statement, error) {
return nil, fmt.Errorf("unknown enum value %q", defaultValue)
}
defaultValue = strconv.Quote(res.name)
} else {
v, err := json.Marshal(argSpec.defaultValue)
if err != nil {
return nil, fmt.Errorf("could not encode default value %q: %w", argSpec.defaultValue, err)
}
defaultValue = string(v)
}
argOptsCode = append(argOptsCode, Id("DefaultValue").Op(":").Id("dagger").Dot("JSON").Call(Lit(defaultValue)))
}
Expand Down Expand Up @@ -297,35 +298,38 @@ func (ps *parseState) parseParamSpecVar(field *types.Var, astField *ast.Field, d
comment = strings.TrimSpace(lineComment)
}

pragmas := make(map[string]string)
pragmas := make(map[string]any)
maps.Copy(pragmas, docPragmas)
maps.Copy(pragmas, linePragmas)
defaultValue := ""
if v, ok := pragmas["default"]; ok {
defaultValue = v
}

defaultValue, hasDefaultValue := pragmas["default"]

optional := false
if v, ok := pragmas["optional"]; ok {
if v == "" {
if v == nil {
optional = true
} else {
optional, _ = strconv.ParseBool(v)
optional, _ = v.(bool)
}
}
defaultPath := ""
if v, ok := pragmas["defaultPath"]; ok {
defaultPath = v
if strings.HasPrefix(v, `"`) && strings.HasSuffix(v, `"`) {
defaultPath = v[1 : len(v)-1]
defaultPath, ok = v.(string)
if !ok {
return paramSpec{}, fmt.Errorf("defaultPath pragma %q, must be a valid string", v)
}
if strings.HasPrefix(defaultPath, `"`) && strings.HasSuffix(defaultPath, `"`) {
defaultPath = defaultPath[1 : len(defaultPath)-1]
}

optional = true // If defaultPath is set, the argument becomes optional
}

ignore := []string{}
if v, ok := pragmas["ignore"]; ok {
if err := json.Unmarshal([]byte(v), &ignore); err != nil {
return paramSpec{}, fmt.Errorf("ignore pragma '%s', must be a valid JSON array: %w", v, err)
err := mapstructure.Decode(v, &ignore)
if err != nil {
return paramSpec{}, fmt.Errorf("ignore pragma %q, must be a valid JSON array: %w", v, err)
}
}

Expand All @@ -352,16 +356,17 @@ func (ps *parseState) parseParamSpecVar(field *types.Var, astField *ast.Field, d
}

return paramSpec{
name: name,
paramType: paramType,
sourceMap: sourceMap,
typeSpec: typeSpec,
optional: optional,
isContext: isContext,
defaultValue: defaultValue,
description: comment,
defaultPath: defaultPath,
ignore: ignore,
name: name,
paramType: paramType,
sourceMap: sourceMap,
typeSpec: typeSpec,
optional: optional,
isContext: isContext,
defaultValue: defaultValue,
hasDefaultValue: hasDefaultValue,
description: comment,
defaultPath: defaultPath,
ignore: ignore,
}, nil
}

Expand All @@ -376,7 +381,8 @@ type paramSpec struct {
isContext bool

// Set a default value for the argument. Value must be a json-encoded literal value
defaultValue string
defaultValue any
hasDefaultValue bool

// paramType is the full type declared in the function signature, which may
// include pointer types, etc
Expand Down
7 changes: 3 additions & 4 deletions cmd/codegen/generator/go/templates/module_objects.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"maps"
"reflect"
"sort"
"strconv"
"strings"

. "github.com/dave/jennifer/jen" //nolint:stylecheck
Expand Down Expand Up @@ -125,14 +124,14 @@ func (ps *parseState) parseGoStruct(t *types.Struct, named *types.Named) (*parse
if comment == "" {
comment = strings.TrimSpace(lineComment)
}
pragmas := make(map[string]string)
pragmas := make(map[string]any)
maps.Copy(pragmas, docPragmas)
maps.Copy(pragmas, linePragmas)
if v, ok := pragmas["private"]; ok {
if v == "" {
if v == nil {
fieldSpec.isPrivate = true
} else {
fieldSpec.isPrivate, _ = strconv.ParseBool(v)
fieldSpec.isPrivate, _ = v.(bool)
}
}

Expand Down
45 changes: 38 additions & 7 deletions cmd/codegen/generator/go/templates/modules.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package templates

import (
"encoding/json"
"fmt"
"go/ast"
"go/token"
Expand Down Expand Up @@ -1170,24 +1171,54 @@ func (ps *parseState) functionCallArgCode(t types.Type, access *Statement) (type
}
}

var pragmaCommentRegexp = regexp.MustCompile(`[ \t]*\+[ \t]*(\S+?)(?:=(.+?))?(?:\r?\n|$)`)
var pragmaCommentRegexp = regexp.MustCompile(`[ \t]*\+[ \t]*(\S+?)(?:(=[ \t]*)|(?:\r?\n|$))`)

// parsePragmaComment parses a dagger "pragma", that is used to define additional metadata about a parameter.
func parsePragmaComment(comment string) (data map[string]string, rest string) {
data = map[string]string{}
func parsePragmaComment(comment string) (data map[string]any, rest string) {
data = map[string]any{}
lastEnd := 0
for _, v := range pragmaCommentRegexp.FindAllStringSubmatchIndex(comment, -1) {
var key, value string
var key string
if v[2] != -1 {
key = comment[v[2]:v[3]]
}

var value any
end := v[1]
if v[4] != -1 {
value = comment[v[4]:v[5]]
dec := json.NewDecoder(strings.NewReader(comment[v[5]:]))
if err := dec.Decode(&value); err == nil {
// attempt to parse as json (this can span multiple-lines)
end = v[5] + int(dec.InputOffset())
idx := strings.IndexAny(comment[end:], "\n")
if idx == -1 {
end = len(comment)
} else {
end += idx + 1
}
} else {
// otherwise, just read till the end of the line
idx := strings.IndexAny(comment[v[5]:], "\n")
var valueStr string
if idx == -1 {
valueStr = comment[v[5]:]
end = len(comment)
} else {
idx += v[5]
valueStr = strings.TrimSuffix(comment[v[5]:idx], "\r")
end = idx + 1
}
if len(valueStr) == 0 {
value = nil
} else {
value = valueStr
}
}
}
data[key] = value

data[key] = value
rest += comment[lastEnd:v[0]]
lastEnd = v[1]
lastEnd = end
}
rest += comment[lastEnd:]

Expand Down
82 changes: 66 additions & 16 deletions cmd/codegen/generator/go/templates/modules_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,61 +10,102 @@ func TestParsePragmaComment(t *testing.T) {
tests := []struct {
name string
comment string
expected map[string]string
expected map[string]any
rest string
}{
{
name: "single key",
comment: "+foo",
expected: map[string]string{
"foo": "",
expected: map[string]any{
"foo": nil,
},
rest: "",
},
{
name: "single key with trailing lf",
comment: "+foo\n",
expected: map[string]string{
"foo": "",
expected: map[string]any{
"foo": nil,
},
rest: "",
},
{
name: "single key with trailing crlf",
comment: "+foo\r\n",
expected: map[string]string{
"foo": "",
expected: map[string]any{
"foo": nil,
},
rest: "",
},
{
name: "single key with leading whitespace",
comment: " \t +foo",
expected: map[string]string{
"foo": "",
expected: map[string]any{
"foo": nil,
},
rest: "",
},
{
name: "single key empty",
comment: "+foo=",
expected: map[string]any{
"foo": nil,
},
rest: "",
},
{
name: "single key-value",
comment: "+foo=bar",
expected: map[string]string{
expected: map[string]any{
"foo": "bar",
},
rest: "",
},
{
name: "single json key-value",
comment: "+foo=\"bar\"",
expected: map[string]any{
"foo": "bar",
},
rest: "",
},
{
name: "single json key-value multi-line",
comment: "+foo=[\n1,\n2,\n3]",
expected: map[string]any{
"foo": []any{1.0, 2.0, 3.0},
},
rest: "",
},
{
name: "single key-value with trailing",
comment: "+foo=bar\n",
expected: map[string]string{
expected: map[string]any{
"foo": "bar",
},
rest: "",
},
{
name: "single json key-value with trailing",
comment: "+foo=\"bar\"\n",
expected: map[string]any{
"foo": "bar",
},
rest: "",
},
{
name: "multiple key-value",
comment: "+foo=bar\n+baz=qux",
expected: map[string]string{
expected: map[string]any{
"foo": "bar",
"baz": "qux",
},
rest: "",
},
{
name: "multiple json key-value",
comment: "+foo=\"bar\"\n+baz=\"qux\"",
expected: map[string]any{
"foo": "bar",
"baz": "qux",
},
Expand All @@ -73,7 +114,16 @@ func TestParsePragmaComment(t *testing.T) {
{
name: "interpolated key-value",
comment: "line 1\n+foo=bar\nline 2\n+baz=qux\nline 3",
expected: map[string]string{
expected: map[string]any{
"foo": "bar",
"baz": "qux",
},
rest: "line 1\nline 2\nline 3",
},
{
name: "interpolated json key-value",
comment: "line 1\n+foo=\"bar\"\nline 2\n+baz=\"qux\"\nline 3",
expected: map[string]any{
"foo": "bar",
"baz": "qux",
},
Expand All @@ -82,16 +132,16 @@ func TestParsePragmaComment(t *testing.T) {
{
name: "interpolated key-value with trailing",
comment: "line 1\n+foo=bar\nline 2\n+baz=qux\nline 3\n",
expected: map[string]string{
expected: map[string]any{
"foo": "bar",
"baz": "qux",
},
rest: "line 1\nline 2\nline 3\n",
},
{
name: "interpolated key-value with crlf",
comment: "line 1\r\n+foo=bar\r\nline 2\r\n+baz=qux\r\nline 3",
expected: map[string]string{
comment: "line 1\r\n+foo=\"bar\"\r\nline 2\r\n+baz=qux\r\nline 3",
expected: map[string]any{
"foo": "bar",
"baz": "qux",
},
Expand Down
5 changes: 4 additions & 1 deletion core/integration/module_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3842,7 +3842,10 @@ import (
type Test struct {}

func (t *Test) Call(
//+ignore=["foo.txt", "bar"]
// +ignore=[
// "foo.txt",
// "bar"
// ]
dir *dagger.Directory,
) *dagger.Directory {
return dir
Expand Down
Loading
0