Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
feat(go extractor): relative paths against KYTHE_ROOT_DIRECTORY (#4380)
By default, the go extractor makes source files relative to GOPATH or
the module root if using modules. This change extends the extractor to
use the KYTHE_ROOT_DIRECTORY environment variable instead if it is
provided.
  • Loading branch information
justbuchanan committed Feb 19, 2020
1 parent 5986688 commit 18c0563
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
1 change: 1 addition & 0 deletions kythe/go/extractors/cmd/gotool/gotool.go
Expand Up @@ -120,6 +120,7 @@ func main() {
DefaultCorpus: *corpus,
Rules: rules,
CanonicalizePackageCorpus: *canonicalizePackageCorpus,
RootDirectory: os.Getenv("KYTHE_ROOT_DIRECTORY"),
},
}
if *extraFiles != "" {
Expand Down
11 changes: 10 additions & 1 deletion kythe/go/extractors/golang/golang.go
Expand Up @@ -377,12 +377,21 @@ func (p *Package) EachUnit(ctx context.Context, f func(cu *apb.CompilationUnit,
// The digest will be the complete path as written -- this will be replaced
// with the content digest in the fetcher.
func (p *Package) addFiles(cu *apb.CompilationUnit, root, base string, names []string) {
// If a root directory is specified, use it instead of the the root from the
// go package loader.
if p.ext.RootDirectory != "" {
root = p.ext.RootDirectory
}
if !strings.HasSuffix(root, "/") {
root += "/"
}

for _, name := range names {
path := name
if base != "" {
path = filepath.Join(base, name)
}
trimmed := strings.TrimPrefix(path, root+"/")
trimmed := strings.TrimPrefix(path, root)
vn := &spb.VName{
Corpus: p.ext.DefaultCorpus,
Path: trimmed,
Expand Down
14 changes: 12 additions & 2 deletions kythe/go/extractors/govname/govname.go
Expand Up @@ -54,6 +54,11 @@ type PackageVNameOptions struct {
// Rules optionally provides a list of rules to apply to go package and file
// paths to customize output vnames. See the vnameutil package for details.
Rules vnameutil.Rules

// If set, file and package paths are made relative to this directory before
// applying vname rules (if any). If unset, the module root (if using
// modules) or the gopath directory is used instead.
RootDirectory string
}

// ForPackage returns a VName for a Go package.
Expand Down Expand Up @@ -97,9 +102,14 @@ type PackageVNameOptions struct {
// }
func ForPackage(pkg *build.Package, opts *PackageVNameOptions) *spb.VName {
if !pkg.Goroot && opts != nil && opts.Rules != nil {
relpath, err := filepath.Rel(pkg.Root, pkg.Dir)
root := pkg.Root
if opts.RootDirectory != "" {
root = opts.RootDirectory
}

relpath, err := filepath.Rel(root, pkg.Dir)
if err != nil {
log.Fatalf("relativizing path %q against dir %q: %v", pkg.Dir, pkg.Root, err)
log.Fatalf("relativizing path %q against dir %q: %v", pkg.Dir, root, err)
}
if relpath == "." {
relpath = ""
Expand Down

0 comments on commit 18c0563

Please sign in to comment.