MCPcopy
hub / github.com/vektra/mockery / AddVar

Method AddVar

template/method_scope.go:118–206  ·  view source on GitHub ↗

AddVar allocates a variable instance and adds it to the method scope. Variables names are generated if required and are ensured to be without conflict with other variables and imported packages. It also adds the relevant imports to the registry for each added variable. This method is not meant to

(ctx context.Context, vr *types.Var, prefix string, replacement *config.ReplaceType)

Source from the content-addressed store, hash-verified

116//
117// This method is not meant to be used directly by templates.
118func (m *MethodScope) AddVar(ctx context.Context, vr *types.Var, prefix string, replacement *config.ReplaceType) (*Var, error) {
119 var (
120 imports map[string]*Package = map[string]*Package{}
121 v Var
122 )
123
124 log := zerolog.Ctx(ctx)
125
126 if replacement != nil {
127 newLogger := log.With().
128 Str("replace-pkg-path", replacement.PkgPath).
129 Str("replace-type-name", replacement.TypeName).Logger()
130 log = &newLogger
131 ctx = log.WithContext(ctx)
132 log.Debug().Msg("working with replacement")
133
134 // Type replacements are really tricky. Mockery needs to correctly
135 // gather type information from the package specified in the replacement.
136 // This basically means that we need to call packages.Load to satisfy this requirement,
137 // then find the type name in the replacement.
138 //
139 // NOTE: This section WILL be slow, because `packages.Load` is slow. Future
140 // enhancement will be to find a way to either cache these calls, batch
141 // them together for all replace-type instances, or find a way to avoid
142 // this altogether.
143 var conf packages.Config
144 conf.Mode = packages.NeedTypes |
145 packages.NeedTypesSizes |
146 packages.NeedSyntax |
147 packages.NeedTypesInfo |
148 packages.NeedImports |
149 packages.NeedName |
150 packages.NeedFiles |
151 packages.NeedCompiledGoFiles
152 pkgs, err := packages.Load(&conf, replacement.PkgPath)
153 if err != nil {
154 log.Err(err).Msg("couldn't load package")
155 return nil, stackerr.NewStackErr(err)
156 }
157 var object types.Object
158 var objectPkg *packages.Package
159 for _, pkg := range pkgs {
160 object = pkg.Types.Scope().Lookup(replacement.TypeName)
161 if object != nil {
162 objectPkg = pkg
163 break
164 }
165 }
166 if object == nil {
167 log.Error().Msg("type-name was not found in the referenced package")
168 return nil, stackerr.NewStackErr(fmt.Errorf("type does not exist in referenced package"))
169 }
170
171 m.addImport(
172 ctx,
173 objectPkg.Types,
174 imports,
175 )

Callers 2

methodDataMethod · 0.80
typeParamsMethod · 0.80

Calls 9

addImportMethod · 0.95
populateImportsMethod · 0.95
AddNameMethod · 0.95
SuggestNameMethod · 0.95
NewStackErrFunction · 0.92
varNameFunction · 0.85
TypeMethod · 0.80
ErrorMethod · 0.45
TypeStringMethod · 0.45

Tested by

no test coverage detected