-
-
Notifications
You must be signed in to change notification settings - Fork 676
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
go/tools: add gopackagesdriver #2858
Merged
Merged
Changes from all commits
Commits
Show all changes
41 commits
Select commit
Hold shift + click to select a range
a67afe0
go/tools: add gopackagesdriver
steeve bdd0556
go/tools/gopackagesdriver: Go <= 1.16 compatibility
steeve 76e6753
go/tools/gopackagesdriver: don't use compiled Go files
steeve 5a53ae2
go/tools/gopackagesdriver: explicitely ignore the C package
steeve d2b527a
go/tools/packagesdriver: fetch package name from the sources
steeve ce61882
go/tools/gopackagesdriver: ensure bazel doesn't print out output files
steeve b08da87
go/tools/gopackagesdriver: don't index by package ID or files
steeve 5dd1e0e
go/tools/builders/stdliblist: ensure CC is absolute
steeve 168e90d
go/tools/gopackagedriver: fetch stdlib info from inner most target
steeve 331470a
go/tools/gopackagesdriver: move bazel UI related flags to the bazel type
steeve 29d0b78
go/tools/gopackagesdriver: add keep_going when building
steeve 529b5ab
go/tools/gopackagesdriver: remove dependecy on x/tools/packages
steeve a0eeeec
Buildifier pass
steeve 79f0cb8
go/tools/gopackagesdriver: use BUILD_WORKSPACE_DIRECTORY for workspace
steeve 8f76121
go/tools/gopackagesdriver: simplify bazel bin lookup
steeve 1203bea
go/tools/gopackagesdriver: simplify BEP JSON file handling
steeve 2657063
go/tools/gopackagesdriver: explicit errors
steeve 859a3b1
go/tools/gopackagesdriver: check for stdlibjson before returning it
steeve 2190ab6
go/tools/gopackagesdriver: fix wrong error format
steeve d69fad2
go/tools/gopackagesdriver: try to speed up bazel queries
steeve 4719e91
go/tools/gopackagesdriver: add missing error check
steeve 07ad711
go/tools/gopackagesdriver: fix typos in comments
steeve b3af1b1
go/tools/gopackagesdriver: unquote imports with strconv.Unquote
steeve 079bb2a
go/tools/gopackagesdriver: pass show_result only to a build command
steeve 070b4c3
go/tools/gopackagesdriver: remove unrelated comment
steeve 69fef40
go/tools/packagesdriver: split targets with fields
steeve fb2df68
go/tools/gopackagesdriver: rename x as export_file
steeve 0d01dc3
go/tools/gopackagesdriver: make GoStdLib._list_json private
steeve c36a5eb
go/tools/gopackagesdriver: don't reallocate absolute paths slice
steeve 2773277
go/tools/gopackagesdriver: packageToPackage -> flatPackageForStd
steeve 5923382
go/tools/builders: fix stdliblist comment
steeve b962df0
go/tools/builder: add GOMODCACHE to stdliblist builder
steeve 98338cc
go/tools/builder: stdlib and stdliblist tags should be comma separated
steeve bcd9713
go/tools/gopackagesdriver: rename to new gazelle convention
steeve b81ac13
go/tools/gopackagesdriver: add file headers
steeve ae8788f
go/tools/gopackagesdriver: cleaner iteration on optional fields
steeve 5b80ccd
go/tools/gopackagesdriver: ensure BEP file paths work on windows too
steeve 34ee2be
go/tools/gopackagesdriver: remove == false expressions
steeve dfe668a
go/tools/gopackagesdriver: don't panic when an error is returned
steeve 81166a8
go/tools/gopackagesdriver: properly compute roots using a pattern mat…
steeve 32aba61
go/tools/gopackagesdriver: walk packages from root
steeve File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,210 @@ | ||
// Copyright 2021 The Bazel Authors. All rights reserved. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package main | ||
|
||
import ( | ||
"bytes" | ||
"encoding/json" | ||
"flag" | ||
"go/build" | ||
"os" | ||
"path/filepath" | ||
"strings" | ||
) | ||
|
||
// Copy and pasted from golang.org/x/tools/go/packages | ||
type flatPackagesError struct { | ||
Pos string // "file:line:col" or "file:line" or "" or "-" | ||
Msg string | ||
Kind flatPackagesErrorKind | ||
} | ||
|
||
type flatPackagesErrorKind int | ||
|
||
const ( | ||
UnknownError flatPackagesErrorKind = iota | ||
ListError | ||
ParseError | ||
TypeError | ||
) | ||
|
||
func (err flatPackagesError) Error() string { | ||
pos := err.Pos | ||
if pos == "" { | ||
pos = "-" // like token.Position{}.String() | ||
} | ||
return pos + ": " + err.Msg | ||
} | ||
|
||
// flatPackage is the JSON form of Package | ||
// It drops all the type and syntax fields, and transforms the Imports | ||
type flatPackage struct { | ||
ID string | ||
Name string `json:",omitempty"` | ||
PkgPath string `json:",omitempty"` | ||
Standard bool `json:",omitempty"` | ||
Errors []flatPackagesError `json:",omitempty"` | ||
GoFiles []string `json:",omitempty"` | ||
CompiledGoFiles []string `json:",omitempty"` | ||
OtherFiles []string `json:",omitempty"` | ||
ExportFile string `json:",omitempty"` | ||
Imports map[string]string `json:",omitempty"` | ||
} | ||
|
||
type goListPackage struct { | ||
Dir string // directory containing package sources | ||
ImportPath string // import path of package in dir | ||
Name string // package name | ||
Target string // install path | ||
Goroot bool // is this package in the Go root? | ||
Standard bool // is this package part of the standard Go library? | ||
Root string // Go root or Go path dir containing this package | ||
Export string // file containing export data (when using -export) | ||
// Source files | ||
GoFiles []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles) | ||
CgoFiles []string // .go source files that import "C" | ||
CompiledGoFiles []string // .go files presented to compiler (when using -compiled) | ||
IgnoredGoFiles []string // .go source files ignored due to build constraints | ||
IgnoredOtherFiles []string // non-.go source files ignored due to build constraints | ||
CFiles []string // .c source files | ||
CXXFiles []string // .cc, .cxx and .cpp source files | ||
MFiles []string // .m source files | ||
HFiles []string // .h, .hh, .hpp and .hxx source files | ||
FFiles []string // .f, .F, .for and .f90 Fortran source files | ||
SFiles []string // .s source files | ||
SwigFiles []string // .swig files | ||
SwigCXXFiles []string // .swigcxx files | ||
SysoFiles []string // .syso object files to add to archive | ||
TestGoFiles []string // _test.go files in package | ||
XTestGoFiles []string // _test.go files outside package | ||
// Embedded files | ||
EmbedPatterns []string // //go:embed patterns | ||
EmbedFiles []string // files matched by EmbedPatterns | ||
TestEmbedPatterns []string // //go:embed patterns in TestGoFiles | ||
TestEmbedFiles []string // files matched by TestEmbedPatterns | ||
XTestEmbedPatterns []string // //go:embed patterns in XTestGoFiles | ||
XTestEmbedFiles []string // files matched by XTestEmbedPatterns | ||
// Dependency information | ||
Imports []string // import paths used by this package | ||
ImportMap map[string]string // map from source import to ImportPath (identity entries omitted) | ||
// Error information | ||
Incomplete bool // this package or a dependency has an error | ||
Error *flatPackagesError // error loading package | ||
DepsErrors []*flatPackagesError // errors loading dependencies | ||
} | ||
|
||
func stdlibPackageID(importPath string) string { | ||
return "@io_bazel_rules_go//stdlib:" + importPath | ||
} | ||
|
||
func execRootPath(execRoot, p string) string { | ||
dir, _ := filepath.Rel(execRoot, p) | ||
return filepath.Join("__BAZEL_EXECROOT__", dir) | ||
} | ||
|
||
func absoluteSourcesPaths(execRoot, pkgDir string, srcs []string) []string { | ||
ret := make([]string, 0, len(srcs)) | ||
pkgDir = execRootPath(execRoot, pkgDir) | ||
for _, src := range srcs { | ||
ret = append(ret, filepath.Join(pkgDir, src)) | ||
} | ||
return ret | ||
} | ||
|
||
func flatPackageForStd(execRoot string, pkg *goListPackage) *flatPackage { | ||
// Don't use generated files from the stdlib | ||
goFiles := absoluteSourcesPaths(execRoot, pkg.Dir, pkg.GoFiles) | ||
|
||
newPkg := &flatPackage{ | ||
ID: stdlibPackageID(pkg.ImportPath), | ||
Name: pkg.Name, | ||
PkgPath: pkg.ImportPath, | ||
ExportFile: execRootPath(execRoot, pkg.Target), | ||
Imports: map[string]string{}, | ||
Standard: pkg.Standard, | ||
GoFiles: goFiles, | ||
CompiledGoFiles: goFiles, | ||
} | ||
for _, imp := range pkg.Imports { | ||
newPkg.Imports[imp] = stdlibPackageID(imp) | ||
} | ||
// We don't support CGo for now | ||
delete(newPkg.Imports, "C") | ||
return newPkg | ||
} | ||
|
||
// stdliblist runs `go list -json` on the standard library and saves it to a file. | ||
func stdliblist(args []string) error { | ||
// process the args | ||
flags := flag.NewFlagSet("stdliblist", flag.ExitOnError) | ||
goenv := envFlags(flags) | ||
out := flags.String("out", "", "Path to output go list json") | ||
if err := flags.Parse(args); err != nil { | ||
return err | ||
} | ||
if err := goenv.checkFlags(); err != nil { | ||
return err | ||
} | ||
|
||
// Ensure paths are absolute. | ||
absPaths := []string{} | ||
for _, path := range filepath.SplitList(os.Getenv("PATH")) { | ||
absPaths = append(absPaths, abs(path)) | ||
} | ||
os.Setenv("PATH", strings.Join(absPaths, string(os.PathListSeparator))) | ||
os.Setenv("GOROOT", abs(os.Getenv("GOROOT"))) | ||
// Make sure we have an absolute path to the C compiler. | ||
// TODO(#1357): also take absolute paths of includes and other paths in flags. | ||
os.Setenv("CC", abs(os.Getenv("CC"))) | ||
|
||
execRoot := abs(".") | ||
|
||
cachePath := abs(*out + ".gocache") | ||
defer os.RemoveAll(cachePath) | ||
os.Setenv("GOCACHE", cachePath) | ||
os.Setenv("GOMODCACHE", cachePath) | ||
os.Setenv("GOPATH", cachePath) | ||
steeve marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
listArgs := goenv.goCmd("list") | ||
if len(build.Default.BuildTags) > 0 { | ||
listArgs = append(listArgs, "-tags", strings.Join(build.Default.BuildTags, ",")) | ||
} | ||
listArgs = append(listArgs, "-json", "builtin", "std", "runtime/cgo") | ||
|
||
jsonFile, err := os.Create(*out) | ||
if err != nil { | ||
return err | ||
} | ||
defer jsonFile.Close() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Check for an error when closing writable files:
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I mean, yes, but is there a cleaner way to do this ? |
||
|
||
jsonData := &bytes.Buffer{} | ||
if err := goenv.runCommandToFile(jsonData, listArgs); err != nil { | ||
return err | ||
} | ||
|
||
encoder := json.NewEncoder(jsonFile) | ||
decoder := json.NewDecoder(jsonData) | ||
for decoder.More() { | ||
var pkg *goListPackage | ||
if err := decoder.Decode(&pkg); err != nil { | ||
return err | ||
} | ||
if err := encoder.Encode(flatPackageForStd(execRoot, pkg)); err != nil { | ||
return err | ||
} | ||
} | ||
|
||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") | ||
|
||
go_library( | ||
name = "gopackagesdriver_lib", | ||
srcs = [ | ||
"bazel.go", | ||
"bazel_json_builder.go", | ||
"driver_request.go", | ||
"flatpackage.go", | ||
"json_packages_driver.go", | ||
"main.go", | ||
"packageregistry.go", | ||
], | ||
importpath = "github.com/bazelbuild/rules_go/go/tools/gopackagesdriver", | ||
visibility = ["//visibility:private"], | ||
) | ||
|
||
go_binary( | ||
name = "gopackagesdriver", | ||
embed = [":gopackagesdriver_lib"], | ||
visibility = ["//visibility:public"], | ||
) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Are there paths in particular that must be relative coming in? If so, let's document that here. If not, let's drop relative paths from
PATH
.We had a security issue in cmd/go with
PATH
on Windows, which implicitly checks the current directory, which could have some maliciousgcc.exe
in it. Russ described that in https://blog.golang.org/path-security.That may not really be relevant for this action, and it may not be possible since analysis might only have relative paths, but it's taught me to handle relative paths in
PATH
carefully.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I actually copied it from the stdlib builder