GoPackagePath returns the path to the provided Go package's source directory. pkg may be a path prefix without any *.go files. The error is os.ErrNotExist if GOPATH is unset.
(pkg string)
| 371 | // pkg may be a path prefix without any *.go files. |
| 372 | // The error is os.ErrNotExist if GOPATH is unset. |
| 373 | func GoPackagePath(pkg string) (path string, err error) { |
| 374 | gp := os.Getenv("GOPATH") |
| 375 | if gp == "" { |
| 376 | cmd := exec.Command("go", "env", "GOPATH") |
| 377 | out, err := cmd.Output() |
| 378 | if err != nil { |
| 379 | return "", fmt.Errorf("could not run 'go env GOPATH': %v, %s", err, out) |
| 380 | } |
| 381 | gp = strings.TrimSpace(string(out)) |
| 382 | if gp == "" { |
| 383 | return "", os.ErrNotExist |
| 384 | } |
| 385 | } |
| 386 | for _, p := range filepath.SplitList(gp) { |
| 387 | dir := filepath.Join(p, "src", filepath.FromSlash(pkg)) |
| 388 | fi, err := os.Stat(dir) |
| 389 | if os.IsNotExist(err) { |
| 390 | continue |
| 391 | } |
| 392 | if err != nil { |
| 393 | return "", err |
| 394 | } |
| 395 | if !fi.IsDir() { |
| 396 | continue |
| 397 | } |
| 398 | return dir, nil |
| 399 | } |
| 400 | return path, os.ErrNotExist |
| 401 | } |
| 402 | |
| 403 | // GoModPackagePath return the absolute path for the go.mod file without "go.mod" suffix. |
| 404 | func GoModPackagePath() (string, error) { |
no test coverage detected