import_tracker.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package generator
  2. import (
  3. "strings"
  4. "github.com/golang/glog"
  5. "go-common/app/tool/gengo/namer"
  6. "go-common/app/tool/gengo/types"
  7. )
  8. // NewImportTracker is
  9. func NewImportTracker(typesToAdd ...*types.Type) namer.ImportTracker {
  10. tracker := namer.NewDefaultImportTracker(types.Name{})
  11. tracker.IsInvalidType = func(*types.Type) bool { return false }
  12. tracker.LocalName = func(name types.Name) string { return golangTrackerLocalName(&tracker, name) }
  13. tracker.PrintImport = func(path, name string) string { return name + " \"" + path + "\"" }
  14. tracker.AddTypes(typesToAdd...)
  15. return &tracker
  16. }
  17. func golangTrackerLocalName(tracker namer.ImportTracker, t types.Name) string {
  18. path := t.Package
  19. // Using backslashes in package names causes gengo to produce Go code which
  20. // will not compile with the gc compiler. See the comment on GoSeperator.
  21. if strings.ContainsRune(path, '\\') {
  22. glog.Warningf("Warning: backslash used in import path '%v', this is unsupported.\n", path)
  23. }
  24. dirs := strings.Split(path, namer.GoSeperator)
  25. for n := len(dirs) - 1; n >= 0; n-- {
  26. // follow kube convention of not having anything between directory names
  27. name := strings.Join(dirs[n:], "")
  28. name = strings.Replace(name, "_", "", -1)
  29. // These characters commonly appear in import paths for go
  30. // packages, but aren't legal go names. So we'll sanitize.
  31. name = strings.Replace(name, ".", "", -1)
  32. name = strings.Replace(name, "-", "", -1)
  33. if _, found := tracker.PathOf(name); found {
  34. // This name collides with some other package
  35. continue
  36. }
  37. return name
  38. }
  39. panic("can't find import for " + path)
  40. }