import_tracker.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package generator
  14. import (
  15. "go/token"
  16. "strings"
  17. "k8s.io/klog"
  18. "k8s.io/gengo/namer"
  19. "k8s.io/gengo/types"
  20. )
  21. func NewImportTracker(typesToAdd ...*types.Type) namer.ImportTracker {
  22. tracker := namer.NewDefaultImportTracker(types.Name{})
  23. tracker.IsInvalidType = func(*types.Type) bool { return false }
  24. tracker.LocalName = func(name types.Name) string { return golangTrackerLocalName(&tracker, name) }
  25. tracker.PrintImport = func(path, name string) string { return name + " \"" + path + "\"" }
  26. tracker.AddTypes(typesToAdd...)
  27. return &tracker
  28. }
  29. func golangTrackerLocalName(tracker namer.ImportTracker, t types.Name) string {
  30. path := t.Package
  31. // Using backslashes in package names causes gengo to produce Go code which
  32. // will not compile with the gc compiler. See the comment on GoSeperator.
  33. if strings.ContainsRune(path, '\\') {
  34. klog.Warningf("Warning: backslash used in import path '%v', this is unsupported.\n", path)
  35. }
  36. dirs := strings.Split(path, namer.GoSeperator)
  37. for n := len(dirs) - 1; n >= 0; n-- {
  38. // follow kube convention of not having anything between directory names
  39. name := strings.Join(dirs[n:], "")
  40. name = strings.Replace(name, "_", "", -1)
  41. // These characters commonly appear in import paths for go
  42. // packages, but aren't legal go names. So we'll sanitize.
  43. name = strings.Replace(name, ".", "", -1)
  44. name = strings.Replace(name, "-", "", -1)
  45. if _, found := tracker.PathOf(name); found {
  46. // This name collides with some other package
  47. continue
  48. }
  49. // If the import name is a Go keyword, prefix with an underscore.
  50. if token.Lookup(name).IsKeyword() {
  51. name = "_" + name
  52. }
  53. return name
  54. }
  55. panic("can't find import for " + path)
  56. }