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