16 // FakeContext returns a build.Context for the fake file tree specified
17 // by pkgs, which maps package import paths to a mapping from file base
20 // The fake Context has a GOROOT of "/go" and no GOPATH, and overrides
21 // the necessary file access methods to read from memory instead of the
24 // Unlike a real file tree, the fake one has only two levels---packages
25 // and files---so ReadDir("/go/src/") returns all packages under
26 // /go/src/ including, for instance, "math" and "math/big".
27 // ReadDir("/go/src/math/big") would return all the files in the
28 // "math/big" package.
30 func FakeContext(pkgs map[string]map[string]string) *build.Context {
31 clean := func(filename string) string {
32 f := path.Clean(filepath.ToSlash(filename))
33 // Removing "/go/src" while respecting segment
34 // boundaries has this unfortunate corner case:
38 return strings.TrimPrefix(f, "/go/src/")
41 ctxt := build.Default // copy
45 ctxt.IsDir = func(dir string) bool {
48 return true // needed by (*build.Context).SrcDirs
50 return pkgs[dir] != nil
52 ctxt.ReadDir = func(dir string) ([]os.FileInfo, error) {
57 for importPath := range pkgs {
58 fis = append(fis, fakeDirInfo(importPath))
61 // enumerate files of package
62 for basename := range pkgs[dir] {
63 fis = append(fis, fakeFileInfo(basename))
66 sort.Sort(byName(fis))
69 ctxt.OpenFile = func(filename string) (io.ReadCloser, error) {
70 filename = clean(filename)
71 dir, base := path.Split(filename)
72 content, ok := pkgs[path.Clean(dir)][base]
74 return nil, fmt.Errorf("file not found: %s", filename)
76 return ioutil.NopCloser(strings.NewReader(content)), nil
78 ctxt.IsAbsPath = func(path string) bool {
79 path = filepath.ToSlash(path)
80 // Don't rely on the default (filepath.Path) since on
81 // Windows, it reports virtual paths as non-absolute.
82 return strings.HasPrefix(path, "/")
87 type byName []os.FileInfo
89 func (s byName) Len() int { return len(s) }
90 func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
91 func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }
93 type fakeFileInfo string
95 func (fi fakeFileInfo) Name() string { return string(fi) }
96 func (fakeFileInfo) Sys() interface{} { return nil }
97 func (fakeFileInfo) ModTime() time.Time { return time.Time{} }
98 func (fakeFileInfo) IsDir() bool { return false }
99 func (fakeFileInfo) Size() int64 { return 0 }
100 func (fakeFileInfo) Mode() os.FileMode { return 0644 }
102 type fakeDirInfo string
104 func (fd fakeDirInfo) Name() string { return string(fd) }
105 func (fakeDirInfo) Sys() interface{} { return nil }
106 func (fakeDirInfo) ModTime() time.Time { return time.Time{} }
107 func (fakeDirInfo) IsDir() bool { return true }
108 func (fakeDirInfo) Size() int64 { return 0 }
109 func (fakeDirInfo) Mode() os.FileMode { return 0755 }