Generate the imports
()
| 1266 | |
| 1267 | // Generate the imports |
| 1268 | func (g *Generator) generateImports() { |
| 1269 | imports := make(map[GoImportPath]GoPackageName) |
| 1270 | for i, s := range g.file.Dependency { |
| 1271 | fd := g.fileByName(s) |
| 1272 | importPath := fd.importPath |
| 1273 | // Do not import our own package. |
| 1274 | if importPath == g.file.importPath { |
| 1275 | continue |
| 1276 | } |
| 1277 | // Do not import weak imports. |
| 1278 | if g.weak(int32(i)) { |
| 1279 | continue |
| 1280 | } |
| 1281 | // Do not import a package twice. |
| 1282 | if _, ok := imports[importPath]; ok { |
| 1283 | continue |
| 1284 | } |
| 1285 | // We need to import all the dependencies, even if we don't reference them, |
| 1286 | // because other code and tools depend on having the full transitive closure |
| 1287 | // of protocol buffer types in the binary. |
| 1288 | packageName := g.GoPackageName(importPath) |
| 1289 | if _, ok := g.usedPackages[importPath]; !ok { |
| 1290 | packageName = "_" |
| 1291 | } |
| 1292 | imports[importPath] = packageName |
| 1293 | } |
| 1294 | for importPath := range g.addedImports { |
| 1295 | imports[importPath] = g.GoPackageName(importPath) |
| 1296 | } |
| 1297 | // We almost always need a proto import. Rather than computing when we |
| 1298 | // do, which is tricky when there's a plugin, just import it and |
| 1299 | // reference it later. The same argument applies to the fmt and math packages. |
| 1300 | g.P("import (") |
| 1301 | g.P(g.Pkg["fmt"] + ` "fmt"`) |
| 1302 | g.P(g.Pkg["math"] + ` "math"`) |
| 1303 | g.P(g.Pkg["proto"]+" ", GoImportPath(g.ImportPrefix)+"github.com/golang/protobuf/proto") |
| 1304 | for importPath, packageName := range imports { |
| 1305 | g.P(packageName, " ", GoImportPath(g.ImportPrefix)+importPath) |
| 1306 | } |
| 1307 | g.P(")") |
| 1308 | g.P() |
| 1309 | // TODO: may need to worry about uniqueness across plugins |
| 1310 | for _, p := range plugins { |
| 1311 | p.GenerateImports(g.file) |
| 1312 | g.P() |
| 1313 | } |
| 1314 | g.P("// Reference imports to suppress errors if they are not otherwise used.") |
| 1315 | g.P("var _ = ", g.Pkg["proto"], ".Marshal") |
| 1316 | g.P("var _ = ", g.Pkg["fmt"], ".Errorf") |
| 1317 | g.P("var _ = ", g.Pkg["math"], ".Inf") |
| 1318 | g.P() |
| 1319 | } |
| 1320 | |
| 1321 | func (g *Generator) generateImported(id *ImportedDescriptor) { |
| 1322 | df := id.o.File() |
no test coverage detected