-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathpkg.go
More file actions
30 lines (27 loc) · 688 Bytes
/
pkg.go
File metadata and controls
30 lines (27 loc) · 688 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main
import (
"errors"
"go/parser"
"go/token"
"os"
)
// errMissingPackage is returned by pkg if it cannot find
// the package for the specified package.
var errMissingPackage = errors.New("cannot discover package name")
// pkg gets the go package name from the specified directory.
func pkg(p string) (string, error) {
fset := token.NewFileSet()
first := true
pkgs, err := parser.ParseDir(fset, p, func(os.FileInfo) bool {
// process only a single file
defer func() { first = false }()
return first
}, parser.PackageClauseOnly)
if err != nil {
return "", err
}
for k := range pkgs {
return k, nil // return first package
}
return "", errMissingPackage
}