gopkg.in/alecthomas/gometalinter.v3@v3.0.0/_linters/src/github.com/securego/gosec/import_tracker.go (about)

     1  // Licensed under the Apache License, Version 2.0 (the "License");
     2  // you may not use this file except in compliance with the License.
     3  // You may obtain a copy of the License at
     4  //
     5  //     http://www.apache.org/licenses/LICENSE-2.0
     6  //
     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 gosec
    14  
    15  import (
    16  	"go/ast"
    17  	"go/types"
    18  	"strings"
    19  )
    20  
    21  // ImportTracker is used to normalize the packages that have been imported
    22  // by a source file. It is able to differentiate between plain imports, aliased
    23  // imports and init only imports.
    24  type ImportTracker struct {
    25  	Imported map[string]string
    26  	Aliased  map[string]string
    27  	InitOnly map[string]bool
    28  }
    29  
    30  // NewImportTracker creates an empty Import tracker instance
    31  func NewImportTracker() *ImportTracker {
    32  	return &ImportTracker{
    33  		make(map[string]string),
    34  		make(map[string]string),
    35  		make(map[string]bool),
    36  	}
    37  }
    38  
    39  // TrackPackages tracks all the imports used by the supplied packages
    40  func (t *ImportTracker) TrackPackages(pkgs ...*types.Package) {
    41  	for _, pkg := range pkgs {
    42  		t.Imported[pkg.Path()] = pkg.Name()
    43  		// Transient imports
    44  		//for _, imp := range pkg.Imports() {
    45  		//	t.Imported[imp.Path()] = imp.Name()
    46  		//}
    47  	}
    48  }
    49  
    50  // TrackImport tracks imports and handles the 'unsafe' import
    51  func (t *ImportTracker) TrackImport(n ast.Node) {
    52  	if imported, ok := n.(*ast.ImportSpec); ok {
    53  		path := strings.Trim(imported.Path.Value, `"`)
    54  		if imported.Name != nil {
    55  			if imported.Name.Name == "_" {
    56  				// Initialization only import
    57  				t.InitOnly[path] = true
    58  			} else {
    59  				// Aliased import
    60  				t.Aliased[path] = imported.Name.Name
    61  			}
    62  		}
    63  		if path == "unsafe" {
    64  			t.Imported[path] = path
    65  		}
    66  	}
    67  }