diff --git a/README.md b/README.md index 8af9711..e1ef4e8 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,10 @@ err := gen.Generate() ## Config ```yaml +# You can specify default mappings that will apply to all packages. +type_mappings: + time.Time: "string /* RFC3339 */" + # You can specify more than one package packages: # The package path just like you would import it in Go @@ -149,7 +153,8 @@ packages: indent: " " # Specify your own custom type translations, useful for custom types, `time.Time` and `null.String`. - # Be default unrecognized types will be `any`. + # By default unrecognized types will be `any`. + # A mapping specified here will override one specified globally. type_mappings: time.Time: "string" my.Type: "SomeType" diff --git a/examples/globalconfig/globalconfig.go b/examples/globalconfig/globalconfig.go new file mode 100644 index 0000000..ac79b02 --- /dev/null +++ b/examples/globalconfig/globalconfig.go @@ -0,0 +1,7 @@ +package globalconfig + +import "time" + +type Config struct { + Duration time.Duration +} diff --git a/tygo.yaml b/tygo.yaml index 32c5f5b..396bb09 100644 --- a/tygo.yaml +++ b/tygo.yaml @@ -1,5 +1,7 @@ # This is a config file that typescriptifies the packages under the example folder. # and some other packages. +type_mappings: + time.Duration: "number /* int, ns */" packages: - path: "github.com/gzuidhof/tygo/examples/bookstore" @@ -56,4 +58,6 @@ packages: - "excluded.go" - path: "github.com/gzuidhof/tygo/examples/rune" + - path: "github.com/gzuidhof/tygo/examples/globalconfig" + diff --git a/tygo/config.go b/tygo/config.go index 105b86a..bcb28aa 100644 --- a/tygo/config.go +++ b/tygo/config.go @@ -64,7 +64,8 @@ type PackageConfig struct { } type Config struct { - Packages []*PackageConfig `yaml:"packages"` + TypeMappings map[string]string `yaml:"type_mappings"` + Packages []*PackageConfig `yaml:"packages"` } func (c Config) PackageNames() []string { @@ -79,6 +80,7 @@ func (c Config) PackageNames() []string { func (c Config) PackageConfig(packagePath string) *PackageConfig { for _, pc := range c.Packages { if pc.Path == packagePath { + pc.TypeMappings = c.mergeMappings(pc.TypeMappings) pcNormalized, err := pc.Normalize() if err != nil { log.Fatalf("Error in config for package %s: %s", packagePath, err) @@ -188,3 +190,14 @@ func (pc PackageConfig) Normalize() (PackageConfig, error) { return pc, nil } + +func (c Config) mergeMappings(pkg map[string]string) map[string]string { + mappings := make(map[string]string) + for k, v := range c.TypeMappings { + mappings[k] = v + } + for k, v := range pkg { + mappings[k] = v + } + return mappings +}