Skip to content

Commit 024620b

Browse files
authored
Merge pull request #106 from 3vilhamster/avoid-double-read
fix: avoid double loading of source package
2 parents 732ab5f + 252d8f1 commit 024620b

File tree

2 files changed

+18
-8
lines changed

2 files changed

+18
-8
lines changed

cmd_generate.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,10 @@ import (
1313
"unicode"
1414

1515
"github.com/Masterminds/sprig/v3"
16+
"github.com/pkg/errors"
17+
1618
"github.com/hexdigest/gowrap/generator"
1719
"github.com/hexdigest/gowrap/pkg"
18-
"github.com/pkg/errors"
1920
)
2021

2122
// GenerateCommand implements Command interface
@@ -151,6 +152,7 @@ func (gc *GenerateCommand) getOptions() (*generator.Options, error) {
151152
}
152153

153154
options.SourcePackage = sourcePackage.PkgPath
155+
options.SourcePackageInstance = sourcePackage // Pass the loaded package
154156
options.BodyTemplate, options.HeaderVars["Template"], err = gc.loadTemplate(outputFileDir)
155157

156158
return &options, err

generator/generator.go

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,12 @@ package generator
33
import (
44
"bytes"
55
"fmt"
6-
"path/filepath"
7-
"sort"
8-
"strings"
9-
106
"go/ast"
117
"go/token"
128
"io"
9+
"path/filepath"
10+
"sort"
11+
"strings"
1312
"text/template"
1413

1514
"github.com/pkg/errors"
@@ -106,6 +105,9 @@ type Options struct {
106105
//SourcePackage is an import path or a relative path of the package that contains the source interface
107106
SourcePackage string
108107

108+
//SourcePackageInstance is the already loaded package (optional)
109+
SourcePackageInstance *packages.Package
110+
109111
//SourcePackageAlias is an import selector defauls is source package name
110112
SourcePackageAlias string
111113

@@ -181,9 +183,15 @@ func NewGenerator(options Options) (*Generator, error) {
181183

182184
fs := token.NewFileSet()
183185

184-
srcPackage, err := pkg.Load(options.SourcePackage)
185-
if err != nil {
186-
return nil, errors.Wrap(err, "failed to load source package")
186+
var srcPackage *packages.Package
187+
// Use the preloaded package if available, only load if not
188+
if options.SourcePackageInstance != nil {
189+
srcPackage = options.SourcePackageInstance
190+
} else {
191+
srcPackage, err = pkg.Load(options.SourcePackage)
192+
if err != nil {
193+
return nil, errors.Wrap(err, "failed to load source package")
194+
}
187195
}
188196

189197
dstPackagePath := filepath.Dir(options.OutputFile)

0 commit comments

Comments
 (0)