Skip to content

Commit

Permalink
Add optional type to config
Browse files Browse the repository at this point in the history
  • Loading branch information
VolkerLieber committed Jun 10, 2024
1 parent 0287f98 commit 997d656
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
23 changes: 23 additions & 0 deletions tygo/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ type PackageConfig struct {
// In "types" mode, only type comments are preserved.
// If "none" is supplied, no comments are preserved.
PreserveComments string `yaml:"preserve_comments"`

// Set the optional type (null or undefined).
// Supported values: "default", "undefined" (same as "default"), "" (same as "default"), "null".
// Default is "undefined".
// Useful for usage with JSON marshalers that output null for optional fields (e.g. gofiber JSON).
OptionalType string `yaml:"optional_type"`
}

type Config struct {
Expand Down Expand Up @@ -82,6 +88,12 @@ func (c Config) PackageConfig(packagePath string) *PackageConfig {
if err != nil {
log.Fatalf("Invalid config for package %s: %s", packagePath, err)
}

pc.OptionalType, err = normalizeOptionalType(pc.OptionalType)
if err != nil {
log.Fatalf("Invalid config for package %s: %s", packagePath, err)
}

return pc
}
}
Expand Down Expand Up @@ -113,6 +125,17 @@ func normalizePreserveComments(preserveComments string) (string, error) {
}
}

func normalizeOptionalType(optional string) (string, error) {
switch optional {
case "", "default", "undefined":
return "undefined", nil
case "null":
return "null", nil
default:
return "", fmt.Errorf("unsupported optional: %s", optional)
}
}

func (c PackageConfig) IsFileIgnored(pathToFile string) bool {
basename := filepath.Base(pathToFile)
for _, ef := range c.ExcludeFiles {
Expand Down
5 changes: 4 additions & 1 deletion tygo/write.go
Original file line number Diff line number Diff line change
Expand Up @@ -373,14 +373,17 @@ func (g *PackageGenerator) writeStructFields(s *strings.Builder, fields []*ast.F
f.Type = t.X
}

if optional {
if optional && g.conf.OptionalType == "undefined" {
s.WriteByte('?')
}

s.WriteString(": ")

if tstype == "" {
g.writeType(s, f.Type, nil, depth, false)
if optional && g.conf.OptionalType == "null" {
s.WriteString(" | null")
}
} else {
s.WriteString(tstype)
}
Expand Down

0 comments on commit 997d656

Please sign in to comment.