Skip to content

Commit

Permalink
Add a Corpus type representing a place where packages live.
Browse files Browse the repository at this point in the history
  • Loading branch information
korfuri committed Jul 12, 2017
1 parent ecbe2e3 commit 2d5d1d5
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
53 changes: 53 additions & 0 deletions corpus.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package goref

import (
"fmt"
"go/build"
"path/filepath"
"strings"
)

// A Corpus represents a prefix from which Go packages may be loaded.
// Default corpora are $GOROOT/src and each of $GOPATH/src
type Corpus string

// NewCorpus creates a new Corpus.
func NewCorpus(basepath string) (Corpus, error) {
if !filepath.IsAbs(basepath) {
return Corpus(""), fmt.Errorf("Corpus %s has a relative basepath", basepath)
}
return Corpus(basepath), nil
}

// Contains returns whether the provided filepath exists under this
// Corpus.
func (c Corpus) Contains(fpath string) bool {
rel, err := filepath.Rel(string(c), fpath)
if err != nil {
return false
}
return !strings.HasPrefix(rel, "../") && rel != ".."
}

// Rel returns the relative path of a file within a Corpus.
// If the string does not belong to the corpus, it returns fpath.
func (c Corpus) Rel(fpath string) string {
if !c.Contains(fpath) {
return fpath
}
rel, err := filepath.Rel(string(c), fpath)
if err != nil {
return fpath
}
return rel
}

// Returns the set of default corpora based on GOROOT and GOPATH.
func DefaultCorpora() []Corpus {
srcdirs := build.Default.SrcDirs()
corpora := make([]Corpus, len(srcdirs))
for n, s := range srcdirs {
corpora[n] = Corpus(s)
}
return corpora
}
32 changes: 32 additions & 0 deletions corpus_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package goref_test

import (
"testing"

"github.com/korfuri/goref"
"github.com/stretchr/testify/assert"
)

func TestContains(t *testing.T) {
assert.True(t, goref.Corpus("/a/b/c").Contains("/a/b/c/d"))
assert.True(t, goref.Corpus("/a/b/c/d").Contains("/a/b/c/d"))
assert.True(t, goref.Corpus("/").Contains("/a/b/c/d"))
assert.False(t, goref.Corpus("/a/b/c").Contains("/a/b/d"))
assert.False(t, goref.Corpus("/a/b/c").Contains("/"))
assert.False(t, goref.Corpus("/a/b/c").Contains("/a/b/"))
}

func TestRel(t *testing.T) {
assert.Equal(t, "d",
goref.Corpus("/a/b/c").Rel("/a/b/c/d"))
assert.Equal(t, ".",
goref.Corpus("/a/b/c/d").Rel("/a/b/c/d"))
assert.Equal(t, "a/b/c/d",
goref.Corpus("/").Rel("/a/b/c/d"))
assert.Equal(t, "/a/b/d",
goref.Corpus("/a/b/c").Rel("/a/b/d"))
assert.Equal(t, "/",
goref.Corpus("/a/b/c").Rel("/"))
assert.Equal(t, "/a/b/",
goref.Corpus("/a/b/c").Rel("/a/b/"))
}

0 comments on commit 2d5d1d5

Please sign in to comment.