import_tracker.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. "strings"
  16. "k8s.io/klog"
  17. "k8s.io/gengo/namer"
  18. "k8s.io/gengo/types"
  19. )
  20. func NewImportTracker(typesToAdd ...*types.Type) namer.ImportTracker {
  21. tracker := namer.NewDefaultImportTracker(types.Name{})
  22. tracker.IsInvalidType = func(*types.Type) bool { return false }
  23. tracker.LocalName = func(name types.Name) string { return golangTrackerLocalName(&tracker, name) }
  24. tracker.PrintImport = func(path, name string) string { return name + " \"" + path + "\"" }
  25. tracker.AddTypes(typesToAdd...)
  26. return &tracker
  27. }
  28. func golangTrackerLocalName(tracker namer.ImportTracker, t types.Name) string {
  29. path := t.Package
  30. // Using backslashes in package names causes gengo to produce Go code which
  31. // will not compile with the gc compiler. See the comment on GoSeperator.
  32. if strings.ContainsRune(path, '\\') {
  33. klog.Warningf("Warning: backslash used in import path '%v', this is unsupported.\n", path)
  34. }
  35. dirs := strings.Split(path, namer.GoSeperator)
  36. for n := len(dirs) - 1; n >= 0; n-- {
  37. // follow kube convention of not having anything between directory names
  38. name := strings.Join(dirs[n:], "")
  39. name = strings.Replace(name, "_", "", -1)
  40. // These characters commonly appear in import paths for go
  41. // packages, but aren't legal go names. So we'll sanitize.
  42. name = strings.Replace(name, ".", "", -1)
  43. name = strings.Replace(name, "-", "", -1)
  44. if _, found := tracker.PathOf(name); found {
  45. // This name collides with some other package
  46. continue
  47. }
  48. return name
  49. }
  50. panic("can't find import for " + path)
  51. }