github.com/blend/go-sdk@v1.20220411.3/profanity/go_imports.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package profanity 9 10 import ( 11 "fmt" 12 "go/parser" 13 "go/token" 14 "path/filepath" 15 "strings" 16 ) 17 18 var ( 19 _ Rule = (*GoImports)(nil) 20 ) 21 22 // GoImports returns a profanity error if a given file contains 23 // any of a list of imports based on a glob match. 24 type GoImports struct { 25 GlobFilter `yaml:",inline"` 26 } 27 28 // Check implements Rule. 29 func (gi GoImports) Check(filename string, contents []byte) RuleResult { 30 if filepath.Ext(filename) != ".go" { 31 return RuleResult{OK: true} 32 } 33 34 fset := token.NewFileSet() 35 36 ast, err := parser.ParseFile(fset, filename, contents, parser.ImportsOnly) 37 if err != nil { 38 return RuleResult{Err: err} 39 } 40 41 var includeGlob, excludeGlob string 42 var fileImportPath string 43 for _, fileImport := range ast.Imports { 44 fileImportPath = strings.ReplaceAll(fileImport.Path.Value, "\"", "") 45 if includeGlob, excludeGlob = gi.Match(fileImportPath); includeGlob != "" && excludeGlob == "" { 46 return RuleResult{ 47 File: filename, 48 Line: fset.Position(fileImport.Pos()).Line, 49 Message: fmt.Sprintf("go imports glob: \"%s\"", includeGlob), 50 } 51 } 52 } 53 return RuleResult{OK: true} 54 } 55 56 // String implements fmt.Stringer. 57 func (gi GoImports) String() string { 58 return fmt.Sprintf("go imports %s", gi.GlobFilter.String()) 59 }