gopath.go

 1package gopath
 2
 3import (
 4	"fmt"
 5	"go/build"
 6	"path/filepath"
 7	"strings"
 8)
 9
10var NotFound = fmt.Errorf("not on GOPATH")
11
12// Contains returns true if the given directory is in the GOPATH
13func Contains(dir string) bool {
14	_, err := Dir2Import(dir)
15	return err == nil
16}
17
18// Dir2Import takes an *absolute* path and returns a golang import path for the package, and returns an error if it isn't on the gopath
19func Dir2Import(dir string) (string, error) {
20	dir = filepath.ToSlash(dir)
21	for _, gopath := range filepath.SplitList(build.Default.GOPATH) {
22		gopath = filepath.ToSlash(filepath.Join(gopath, "src"))
23		if len(gopath) < len(dir) && strings.EqualFold(gopath, dir[0:len(gopath)]) {
24			return dir[len(gopath)+1:], nil
25		}
26	}
27	return "", NotFound
28}
29
30// MustDir2Import takes an *absolute* path and returns a golang import path for the package, and panics if it isn't on the gopath
31func MustDir2Import(dir string) string {
32	pkg, err := Dir2Import(dir)
33	if err != nil {
34		panic(err)
35	}
36	return pkg
37}