forked from cookieo9/resources-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
package.go
85 lines (77 loc) · 2.03 KB
/
package.go
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package resources
import (
"go/build"
"os"
"path/filepath"
"runtime"
"strings"
)
// Check a package to see if it's a valid place to look for resources
// Anywhere in GOROOT, and in the resources package are not valid
// locations
func checkPackage(pkg *build.Package) bool {
if strings.Index(pkg.Dir, runtime.GOROOT()) != -1 {
return false
}
var thispkg *build.Package
_, sfile, _, _ := runtime.Caller(0)
if p, err := build.ImportDir(filepath.Dir(sfile), build.FindOnly); err != nil {
panic(err)
} else {
thispkg = p
}
if pkg.Dir == thispkg.Dir {
return false
}
return true
}
// Opens the source directory of the current package as a Bundle.
// The current package is the package of the code calling
// OpenCurrentPackage() (as determined by runtime.Caller())
func OpenCurrentPackage() (Bundle, error) {
// Keep calling runtime.Caller with increasing values until we are no longer in
// this package
for i := 1; ; i++ {
_, sfile, _, _ := runtime.Caller(i)
if p, err := build.ImportDir(filepath.Dir(sfile), build.FindOnly); err == nil {
if checkPackage(p) {
return &packageBundle{OpenFS(p.Dir).(*fsBundle)}, nil
}
} else {
return nil, err
}
}
panic("Shouldn't Get Here!")
}
// OpenPackagePath returns a Bundle which accesses files
// in the source directory of the package named by the given
// import path.
//
// Bundles accessing packages support the Searcher and Lister
// interfaces.
func OpenPackage(import_path string) (Bundle, error) {
pkg, err := build.Import(import_path, "", build.FindOnly)
if err != nil {
return nil, err
}
return &packageBundle{OpenFS(pkg.Dir).(*fsBundle)}, nil
}
type packageBundle struct {
*fsBundle
}
func (pb *packageBundle) List() ([]Resource, error) {
var list []Resource
err := filepath.Walk(pb.base, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
rel, err := filepath.Rel(pb.base, path)
if err == nil {
list = append(list, pb.file(filepath.ToSlash(rel)))
}
}
return nil
})
return list, err
}