From 5b138fbddafde827b15696b275e26107220ccaf6 Mon Sep 17 00:00:00 2001 From: Vishal Raut Date: Mon, 6 Dec 2021 12:33:37 +0530 Subject: [PATCH] Bugfix: Skip reading same file multiple times Also merge types from schemas read from multiple files --- xsd/parse.go | 9 ++++++++- xsdgen/cli.go | 9 ++++++++- xsdgen/config.go | 11 +++++++---- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/xsd/parse.go b/xsd/parse.go index 0e1ac4f..938c1de 100644 --- a/xsd/parse.go +++ b/xsd/parse.go @@ -150,7 +150,14 @@ func Parse(docs ...[]byte) ([]Schema, error) { if err := s.parse(root); err != nil { return nil, err } - parsed[tns] = s + // schema already exists, so merge types with new ones + if ps, ok := parsed[tns]; ok { + for name, newType := range s.Types { + ps.Types[name] = newType + } + } else { + parsed[tns] = s + } } for _, s := range parsed { diff --git a/xsdgen/cli.go b/xsdgen/cli.go index 0274086..6474b0f 100644 --- a/xsdgen/cli.go +++ b/xsdgen/cli.go @@ -54,6 +54,7 @@ func (cfg *Config) GenCode(data ...[]byte) (*Code, error) { // GenAST creates an *ast.File containing type declarations and // associated methods based on a set of XML schema. func (cfg *Config) GenAST(files ...string) (*ast.File, error) { + cfg.filesRead = make(map[string]bool) data, err := cfg.readFiles(files...) code, err := cfg.GenCode(data...) if err != nil { @@ -62,14 +63,20 @@ func (cfg *Config) GenAST(files ...string) (*ast.File, error) { return code.GenAST() } -func (cfg *Config) readFiles(files ...string) ([][]byte,error) { +func (cfg *Config) readFiles(files ...string) ([][]byte, error) { data := make([][]byte, 0, len(files)) for _, filename := range files { + if _, ok := cfg.filesRead[filename]; ok { + // skip reading the file again + continue + } + b, err := ioutil.ReadFile(filename) if err != nil { return nil, err } cfg.debugf("read %s", filename) + cfg.filesRead[filename] = true if cfg.followImports { importedRefs, err := xsd.Imports(b) if err != nil { diff --git a/xsdgen/config.go b/xsdgen/config.go index 5a1903f..984b89f 100644 --- a/xsdgen/config.go +++ b/xsdgen/config.go @@ -16,10 +16,10 @@ import ( // A Config holds user-defined overrides and filters that are used when // generating Go source code from an xsd document. type Config struct { - logger Logger - loglevel int - namespaces []string - pkgname string + logger Logger + loglevel int + namespaces []string + pkgname string // load xsd imports recursively into memory before parsing followImports bool preprocessType typeTransform @@ -42,6 +42,9 @@ type Config struct { // if populated, only types that are true in this map // will be selected. allowTypes map[xml.Name]bool + + // keep track of files that are read already to avoid reading it again + filesRead map[string]bool } type typeTransform func(xsd.Schema, xsd.Type) xsd.Type