Skip to content

Commit 4c6396b

Browse files
committed
Derive the package from given files
Move some utility functions into the helper
1 parent 3f2b814 commit 4c6396b

File tree

3 files changed

+71
-45
lines changed

3 files changed

+71
-45
lines changed

analyzer.go

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,6 @@ import (
2828
"regexp"
2929
"strings"
3030

31-
"path/filepath"
32-
3331
"golang.org/x/tools/go/loader"
3432
)
3533

@@ -106,11 +104,8 @@ func (gosec *Analyzer) Process(buildTags []string, packagePaths ...string) error
106104
AllowErrors: true,
107105
}
108106
for _, packagePath := range packagePaths {
109-
abspath, err := filepath.Abs(packagePath)
107+
abspath, err := GetPkgAbsPath(packagePath)
110108
if err != nil {
111-
return err
112-
}
113-
if _, err := os.Stat(abspath); os.IsNotExist(err) {
114109
gosec.logger.Printf("Skipping: %s. Path doesn't exist.", abspath)
115110
continue
116111
}

cmd/gosec/main.go

Lines changed: 7 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,8 @@ import (
2020
"io/ioutil"
2121
"log"
2222
"os"
23-
"os/user"
2423
"path/filepath"
2524
"regexp"
26-
"runtime"
2725
"sort"
2826
"strings"
2927

@@ -178,36 +176,13 @@ func saveOutput(filename, format string, issues []*gosec.Issue, metrics *gosec.M
178176
return nil
179177
}
180178

181-
func getenv(key, userDefault string) string {
182-
if val := os.Getenv(key); val != "" {
183-
return val
184-
}
185-
return userDefault
186-
}
187-
188-
func gopath() []string {
189-
defaultGoPath := runtime.GOROOT()
190-
if u, err := user.Current(); err == nil {
191-
defaultGoPath = filepath.Join(u.HomeDir, "go")
192-
}
193-
path := getenv("GOPATH", defaultGoPath)
194-
paths := strings.Split(path, string(os.PathListSeparator))
195-
for idx, path := range paths {
196-
if abs, err := filepath.Abs(path); err == nil {
197-
paths[idx] = abs
198-
}
199-
}
200-
return paths
201-
}
202-
203-
func cleanPath(path string, gopaths []string) (string, error) {
204-
179+
func cleanPath(path string) (string, error) {
205180
cleanFailed := fmt.Errorf("%s is not within the $GOPATH and cannot be processed", path)
206181
nonRecursivePath := strings.TrimSuffix(path, "/...")
207182
// do not attempt to clean directs that are resolvable on gopath
208183
if _, err := os.Stat(nonRecursivePath); err != nil && os.IsNotExist(err) {
209184
log.Printf("directory %s doesn't exist, checking if is a package on $GOPATH", path)
210-
for _, basedir := range gopaths {
185+
for _, basedir := range gosec.Gopath() {
211186
dir := filepath.Join(basedir, "src", nonRecursivePath)
212187
if st, err := os.Stat(dir); err == nil && st.IsDir() {
213188
log.Printf("located %s in %s", path, dir)
@@ -218,24 +193,17 @@ func cleanPath(path string, gopaths []string) (string, error) {
218193
}
219194

220195
// ensure we resolve package directory correctly based on $GOPATH
221-
abspath, err := filepath.Abs(path)
196+
pkgPath, err := gosec.GetPkgRelativePath(path)
222197
if err != nil {
223-
abspath = path
224-
}
225-
for _, base := range gopaths {
226-
projectRoot := filepath.FromSlash(fmt.Sprintf("%s/src/", base))
227-
if strings.HasPrefix(abspath, projectRoot) {
228-
return strings.TrimPrefix(abspath, projectRoot), nil
229-
}
198+
return "", cleanFailed
230199
}
231-
return "", cleanFailed
200+
return pkgPath, nil
232201
}
233202

234203
func cleanPaths(paths []string) []string {
235-
gopaths := gopath()
236204
var clean []string
237205
for _, path := range paths {
238-
cleaned, err := cleanPath(path, gopaths)
206+
cleaned, err := cleanPath(path)
239207
if err != nil {
240208
log.Fatal(err)
241209
}
@@ -306,7 +274,7 @@ func main() {
306274

307275
var packages []string
308276
// Iterate over packages on the import paths
309-
gopaths := gopath()
277+
gopaths := gosec.Gopath()
310278
for _, pkg := range gotool.ImportPaths(cleanPaths(flag.Args())) {
311279

312280
// Skip vendor directory

helpers.go

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,17 @@
1515
package gosec
1616

1717
import (
18+
"errors"
1819
"fmt"
1920
"go/ast"
2021
"go/token"
2122
"go/types"
23+
"os"
24+
"os/user"
25+
"path/filepath"
26+
"runtime"
2227
"strconv"
28+
"strings"
2329
)
2430

2531
// MatchCallByPackage ensures that the specified package is imported,
@@ -193,3 +199,60 @@ func GetLocation(n ast.Node, ctx *Context) (string, int) {
193199
fobj := ctx.FileSet.File(n.Pos())
194200
return fobj.Name(), fobj.Line(n.Pos())
195201
}
202+
203+
// Gopath returns all GOPATHs
204+
func Gopath() []string {
205+
defaultGoPath := runtime.GOROOT()
206+
if u, err := user.Current(); err == nil {
207+
defaultGoPath = filepath.Join(u.HomeDir, "go")
208+
}
209+
path := Getenv("GOPATH", defaultGoPath)
210+
paths := strings.Split(path, string(os.PathListSeparator))
211+
for idx, path := range paths {
212+
if abs, err := filepath.Abs(path); err == nil {
213+
paths[idx] = abs
214+
}
215+
}
216+
return paths
217+
}
218+
219+
// Getenv returns the values of the environment variable, otherwise
220+
//returns the default if variable is not set
221+
func Getenv(key, userDefault string) string {
222+
if val := os.Getenv(key); val != "" {
223+
return val
224+
}
225+
return userDefault
226+
}
227+
228+
// GetPkgRelativePath returns the Go relative relative path derived
229+
// form the given path
230+
func GetPkgRelativePath(path string) (string, error) {
231+
abspath, err := filepath.Abs(path)
232+
if err != nil {
233+
abspath = path
234+
}
235+
if strings.HasSuffix(abspath, ".go") {
236+
abspath = filepath.Dir(abspath)
237+
}
238+
for _, base := range Gopath() {
239+
projectRoot := filepath.FromSlash(fmt.Sprintf("%s/src/", base))
240+
if strings.HasPrefix(abspath, projectRoot) {
241+
return strings.TrimPrefix(abspath, projectRoot), nil
242+
}
243+
}
244+
return "", errors.New("no project relative path found")
245+
}
246+
247+
// GetPkgAbsPath returns the Go package absolute path derived from
248+
// the given path
249+
func GetPkgAbsPath(pkgPath string) (string, error) {
250+
absPath, err := filepath.Abs(pkgPath)
251+
if err != nil {
252+
return "", err
253+
}
254+
if _, err := os.Stat(absPath); os.IsNotExist(err) {
255+
return "", errors.New("no project absolute path found")
256+
}
257+
return absPath, nil
258+
}

0 commit comments

Comments
 (0)