repo_id
stringclasses 927
values | file_path
stringlengths 99
214
| content
stringlengths 2
4.15M
|
|---|---|---|
get
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/get/vcs_test.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package get
import (
"errors"
"internal/testenv"
"io/ioutil"
"os"
"path"
"path/filepath"
"testing"
"cmd/go/internal/web"
)
// Test that RepoRootForImportPath determines the correct RepoRoot for a given importPath.
// TODO(cmang): Add tests for SVN and BZR.
func TestRepoRootForImportPath(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tests := []struct {
path string
want *RepoRoot
}{
{
"github.com/golang/groupcache",
&RepoRoot{
vcs: vcsGit,
Repo: "https://github.com/golang/groupcache",
},
},
// Unicode letters in directories (issue 18660).
{
"github.com/user/unicode/испытание",
&RepoRoot{
vcs: vcsGit,
Repo: "https://github.com/user/unicode",
},
},
// IBM DevOps Services tests
{
"hub.jazz.net/git/user1/pkgname",
&RepoRoot{
vcs: vcsGit,
Repo: "https://hub.jazz.net/git/user1/pkgname",
},
},
{
"hub.jazz.net/git/user1/pkgname/submodule/submodule/submodule",
&RepoRoot{
vcs: vcsGit,
Repo: "https://hub.jazz.net/git/user1/pkgname",
},
},
{
"hub.jazz.net",
nil,
},
{
"hubajazz.net",
nil,
},
{
"hub2.jazz.net",
nil,
},
{
"hub.jazz.net/someotherprefix",
nil,
},
{
"hub.jazz.net/someotherprefix/user1/pkgname",
nil,
},
// Spaces are not valid in user names or package names
{
"hub.jazz.net/git/User 1/pkgname",
nil,
},
{
"hub.jazz.net/git/user1/pkg name",
nil,
},
// Dots are not valid in user names
{
"hub.jazz.net/git/user.1/pkgname",
nil,
},
{
"hub.jazz.net/git/user/pkg.name",
&RepoRoot{
vcs: vcsGit,
Repo: "https://hub.jazz.net/git/user/pkg.name",
},
},
// User names cannot have uppercase letters
{
"hub.jazz.net/git/USER/pkgname",
nil,
},
// OpenStack tests
{
"git.openstack.org/openstack/swift",
&RepoRoot{
vcs: vcsGit,
Repo: "https://git.openstack.org/openstack/swift",
},
},
// Trailing .git is less preferred but included for
// compatibility purposes while the same source needs to
// be compilable on both old and new go
{
"git.openstack.org/openstack/swift.git",
&RepoRoot{
vcs: vcsGit,
Repo: "https://git.openstack.org/openstack/swift.git",
},
},
{
"git.openstack.org/openstack/swift/go/hummingbird",
&RepoRoot{
vcs: vcsGit,
Repo: "https://git.openstack.org/openstack/swift",
},
},
{
"git.openstack.org",
nil,
},
{
"git.openstack.org/openstack",
nil,
},
// Spaces are not valid in package name
{
"git.apache.org/package name/path/to/lib",
nil,
},
// Should have ".git" suffix
{
"git.apache.org/package-name/path/to/lib",
nil,
},
{
"gitbapache.org",
nil,
},
{
"git.apache.org/package-name.git",
&RepoRoot{
vcs: vcsGit,
Repo: "https://git.apache.org/package-name.git",
},
},
{
"git.apache.org/package-name_2.x.git/path/to/lib",
&RepoRoot{
vcs: vcsGit,
Repo: "https://git.apache.org/package-name_2.x.git",
},
},
{
"chiselapp.com/user/kyle/repository/fossilgg",
&RepoRoot{
vcs: vcsFossil,
Repo: "https://chiselapp.com/user/kyle/repository/fossilgg",
},
},
{
// must have a user/$name/repository/$repo path
"chiselapp.com/kyle/repository/fossilgg",
nil,
},
{
"chiselapp.com/user/kyle/fossilgg",
nil,
},
}
for _, test := range tests {
got, err := RepoRootForImportPath(test.path, IgnoreMod, web.Secure)
want := test.want
if want == nil {
if err == nil {
t.Errorf("RepoRootForImportPath(%q): Error expected but not received", test.path)
}
continue
}
if err != nil {
t.Errorf("RepoRootForImportPath(%q): %v", test.path, err)
continue
}
if got.vcs.name != want.vcs.name || got.Repo != want.Repo {
t.Errorf("RepoRootForImportPath(%q) = VCS(%s) Repo(%s), want VCS(%s) Repo(%s)", test.path, got.vcs, got.Repo, want.vcs, want.Repo)
}
}
}
// Test that vcsFromDir correctly inspects a given directory and returns the right VCS and root.
func TestFromDir(t *testing.T) {
tempDir, err := ioutil.TempDir("", "vcstest")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempDir)
for j, vcs := range vcsList {
dir := filepath.Join(tempDir, "example.com", vcs.name, "."+vcs.cmd)
if j&1 == 0 {
err := os.MkdirAll(dir, 0755)
if err != nil {
t.Fatal(err)
}
} else {
err := os.MkdirAll(filepath.Dir(dir), 0755)
if err != nil {
t.Fatal(err)
}
f, err := os.Create(dir)
if err != nil {
t.Fatal(err)
}
f.Close()
}
want := RepoRoot{
vcs: vcs,
Root: path.Join("example.com", vcs.name),
}
var got RepoRoot
got.vcs, got.Root, err = vcsFromDir(dir, tempDir)
if err != nil {
t.Errorf("FromDir(%q, %q): %v", dir, tempDir, err)
continue
}
if got.vcs.name != want.vcs.name || got.Root != want.Root {
t.Errorf("FromDir(%q, %q) = VCS(%s) Root(%s), want VCS(%s) Root(%s)", dir, tempDir, got.vcs, got.Root, want.vcs, want.Root)
}
}
}
func TestIsSecure(t *testing.T) {
tests := []struct {
vcs *vcsCmd
url string
secure bool
}{
{vcsGit, "http://example.com/foo.git", false},
{vcsGit, "https://example.com/foo.git", true},
{vcsBzr, "http://example.com/foo.bzr", false},
{vcsBzr, "https://example.com/foo.bzr", true},
{vcsSvn, "http://example.com/svn", false},
{vcsSvn, "https://example.com/svn", true},
{vcsHg, "http://example.com/foo.hg", false},
{vcsHg, "https://example.com/foo.hg", true},
{vcsGit, "ssh://user@example.com/foo.git", true},
{vcsGit, "user@server:path/to/repo.git", false},
{vcsGit, "user@server:", false},
{vcsGit, "server:repo.git", false},
{vcsGit, "server:path/to/repo.git", false},
{vcsGit, "example.com:path/to/repo.git", false},
{vcsGit, "path/that/contains/a:colon/repo.git", false},
{vcsHg, "ssh://user@example.com/path/to/repo.hg", true},
{vcsFossil, "http://example.com/foo", false},
{vcsFossil, "https://example.com/foo", true},
}
for _, test := range tests {
secure := test.vcs.isSecure(test.url)
if secure != test.secure {
t.Errorf("%s isSecure(%q) = %t; want %t", test.vcs, test.url, secure, test.secure)
}
}
}
func TestIsSecureGitAllowProtocol(t *testing.T) {
tests := []struct {
vcs *vcsCmd
url string
secure bool
}{
// Same as TestIsSecure to verify same behavior.
{vcsGit, "http://example.com/foo.git", false},
{vcsGit, "https://example.com/foo.git", true},
{vcsBzr, "http://example.com/foo.bzr", false},
{vcsBzr, "https://example.com/foo.bzr", true},
{vcsSvn, "http://example.com/svn", false},
{vcsSvn, "https://example.com/svn", true},
{vcsHg, "http://example.com/foo.hg", false},
{vcsHg, "https://example.com/foo.hg", true},
{vcsGit, "user@server:path/to/repo.git", false},
{vcsGit, "user@server:", false},
{vcsGit, "server:repo.git", false},
{vcsGit, "server:path/to/repo.git", false},
{vcsGit, "example.com:path/to/repo.git", false},
{vcsGit, "path/that/contains/a:colon/repo.git", false},
{vcsHg, "ssh://user@example.com/path/to/repo.hg", true},
// New behavior.
{vcsGit, "ssh://user@example.com/foo.git", false},
{vcsGit, "foo://example.com/bar.git", true},
{vcsHg, "foo://example.com/bar.hg", false},
{vcsSvn, "foo://example.com/svn", false},
{vcsBzr, "foo://example.com/bar.bzr", false},
}
defer os.Unsetenv("GIT_ALLOW_PROTOCOL")
os.Setenv("GIT_ALLOW_PROTOCOL", "https:foo")
for _, test := range tests {
secure := test.vcs.isSecure(test.url)
if secure != test.secure {
t.Errorf("%s isSecure(%q) = %t; want %t", test.vcs, test.url, secure, test.secure)
}
}
}
func TestMatchGoImport(t *testing.T) {
tests := []struct {
imports []metaImport
path string
mi metaImport
err error
}{
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/foo",
mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/foo/",
mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
{Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/foo",
mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
{Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/fooa",
mi: metaImport{Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
{Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/foo/bar",
err: errors.New("should not be allowed to create nested repo"),
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
{Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/foo/bar/baz",
err: errors.New("should not be allowed to create nested repo"),
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
{Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/foo/bar/baz/qux",
err: errors.New("should not be allowed to create nested repo"),
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
{Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/foo/bar/baz/",
err: errors.New("should not be allowed to create nested repo"),
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
{Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com",
err: errors.New("pathologically short path"),
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "different.example.com/user/foo",
err: errors.New("meta tags do not match import path"),
},
{
imports: []metaImport{
{Prefix: "myitcv.io/blah2", VCS: "mod", RepoRoot: "https://raw.githubusercontent.com/myitcv/pubx/master"},
{Prefix: "myitcv.io", VCS: "git", RepoRoot: "https://github.com/myitcv/x"},
},
path: "myitcv.io/blah2/foo",
mi: metaImport{Prefix: "myitcv.io/blah2", VCS: "mod", RepoRoot: "https://raw.githubusercontent.com/myitcv/pubx/master"},
},
{
imports: []metaImport{
{Prefix: "myitcv.io/blah2", VCS: "mod", RepoRoot: "https://raw.githubusercontent.com/myitcv/pubx/master"},
{Prefix: "myitcv.io", VCS: "git", RepoRoot: "https://github.com/myitcv/x"},
},
path: "myitcv.io/other",
mi: metaImport{Prefix: "myitcv.io", VCS: "git", RepoRoot: "https://github.com/myitcv/x"},
},
}
for _, test := range tests {
mi, err := matchGoImport(test.imports, test.path)
if mi != test.mi {
t.Errorf("unexpected metaImport; got %v, want %v", mi, test.mi)
}
got := err
want := test.err
if (got == nil) != (want == nil) {
t.Errorf("unexpected error; got %v, want %v", got, want)
}
}
}
func TestValidateRepoRoot(t *testing.T) {
tests := []struct {
root string
ok bool
}{
{
root: "",
ok: false,
},
{
root: "http://",
ok: true,
},
{
root: "git+ssh://",
ok: true,
},
{
root: "http#://",
ok: false,
},
{
root: "-config",
ok: false,
},
{
root: "-config://",
ok: false,
},
}
for _, test := range tests {
err := validateRepoRoot(test.root)
ok := err == nil
if ok != test.ok {
want := "error"
if test.ok {
want = "nil"
}
t.Errorf("validateRepoRoot(%q) = %q, want %s", test.root, err, want)
}
}
}
|
get
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/get/pkg_test.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package get
import (
"cmd/go/internal/str"
"reflect"
"strings"
"testing"
)
var foldDupTests = []struct {
list []string
f1, f2 string
}{
{str.StringList("math/rand", "math/big"), "", ""},
{str.StringList("math", "strings"), "", ""},
{str.StringList("strings"), "", ""},
{str.StringList("strings", "strings"), "strings", "strings"},
{str.StringList("Rand", "rand", "math", "math/rand", "math/Rand"), "Rand", "rand"},
}
func TestFoldDup(t *testing.T) {
for _, tt := range foldDupTests {
f1, f2 := str.FoldDup(tt.list)
if f1 != tt.f1 || f2 != tt.f2 {
t.Errorf("foldDup(%q) = %q, %q, want %q, %q", tt.list, f1, f2, tt.f1, tt.f2)
}
}
}
var parseMetaGoImportsTests = []struct {
in string
mod ModuleMode
out []metaImport
}{
{
`<meta name="go-import" content="foo/bar git https://github.com/rsc/foo/bar">`,
IgnoreMod,
[]metaImport{{"foo/bar", "git", "https://github.com/rsc/foo/bar"}},
},
{
`<meta name="go-import" content="foo/bar git https://github.com/rsc/foo/bar">
<meta name="go-import" content="baz/quux git http://github.com/rsc/baz/quux">`,
IgnoreMod,
[]metaImport{
{"foo/bar", "git", "https://github.com/rsc/foo/bar"},
{"baz/quux", "git", "http://github.com/rsc/baz/quux"},
},
},
{
`<meta name="go-import" content="foo/bar git https://github.com/rsc/foo/bar">
<meta name="go-import" content="foo/bar mod http://github.com/rsc/baz/quux">`,
IgnoreMod,
[]metaImport{
{"foo/bar", "git", "https://github.com/rsc/foo/bar"},
},
},
{
`<meta name="go-import" content="foo/bar mod http://github.com/rsc/baz/quux">
<meta name="go-import" content="foo/bar git https://github.com/rsc/foo/bar">`,
IgnoreMod,
[]metaImport{
{"foo/bar", "git", "https://github.com/rsc/foo/bar"},
},
},
{
`<meta name="go-import" content="foo/bar mod http://github.com/rsc/baz/quux">
<meta name="go-import" content="foo/bar git https://github.com/rsc/foo/bar">`,
PreferMod,
[]metaImport{
{"foo/bar", "mod", "http://github.com/rsc/baz/quux"},
},
},
{
`<head>
<meta name="go-import" content="foo/bar git https://github.com/rsc/foo/bar">
</head>`,
IgnoreMod,
[]metaImport{{"foo/bar", "git", "https://github.com/rsc/foo/bar"}},
},
{
`<meta name="go-import" content="foo/bar git https://github.com/rsc/foo/bar">
<body>`,
IgnoreMod,
[]metaImport{{"foo/bar", "git", "https://github.com/rsc/foo/bar"}},
},
{
`<!doctype html><meta name="go-import" content="foo/bar git https://github.com/rsc/foo/bar">`,
IgnoreMod,
[]metaImport{{"foo/bar", "git", "https://github.com/rsc/foo/bar"}},
},
{
// XML doesn't like <div style=position:relative>.
`<!doctype html><title>Page Not Found</title><meta name=go-import content="chitin.io/chitin git https://github.com/chitin-io/chitin"><div style=position:relative>DRAFT</div>`,
IgnoreMod,
[]metaImport{{"chitin.io/chitin", "git", "https://github.com/chitin-io/chitin"}},
},
{
`<meta name="go-import" content="myitcv.io git https://github.com/myitcv/x">
<meta name="go-import" content="myitcv.io/blah2 mod https://raw.githubusercontent.com/myitcv/pubx/master">
`,
IgnoreMod,
[]metaImport{{"myitcv.io", "git", "https://github.com/myitcv/x"}},
},
{
`<meta name="go-import" content="myitcv.io git https://github.com/myitcv/x">
<meta name="go-import" content="myitcv.io/blah2 mod https://raw.githubusercontent.com/myitcv/pubx/master">
`,
PreferMod,
[]metaImport{
{"myitcv.io/blah2", "mod", "https://raw.githubusercontent.com/myitcv/pubx/master"},
{"myitcv.io", "git", "https://github.com/myitcv/x"},
},
},
}
func TestParseMetaGoImports(t *testing.T) {
for i, tt := range parseMetaGoImportsTests {
out, err := parseMetaGoImports(strings.NewReader(tt.in), tt.mod)
if err != nil {
t.Errorf("test#%d: %v", i, err)
continue
}
if !reflect.DeepEqual(out, tt.out) {
t.Errorf("test#%d:\n\thave %q\n\twant %q", i, out, tt.out)
}
}
}
|
search
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/search/search.go
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package search
import (
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"fmt"
"go/build"
"log"
"os"
"path"
"path/filepath"
"regexp"
"strings"
)
// A Match represents the result of matching a single package pattern.
type Match struct {
Pattern string // the pattern itself
Literal bool // whether it is a literal (no wildcards)
Pkgs []string // matching packages (dirs or import paths)
}
// MatchPackages returns all the packages that can be found
// under the $GOPATH directories and $GOROOT matching pattern.
// The pattern is either "all" (all packages), "std" (standard packages),
// "cmd" (standard commands), or a path including "...".
func MatchPackages(pattern string) *Match {
m := &Match{
Pattern: pattern,
Literal: false,
}
match := func(string) bool { return true }
treeCanMatch := func(string) bool { return true }
if !IsMetaPackage(pattern) {
match = MatchPattern(pattern)
treeCanMatch = TreeCanMatchPattern(pattern)
}
have := map[string]bool{
"builtin": true, // ignore pseudo-package that exists only for documentation
}
if !cfg.BuildContext.CgoEnabled {
have["runtime/cgo"] = true // ignore during walk
}
for _, src := range cfg.BuildContext.SrcDirs() {
if (pattern == "std" || pattern == "cmd") && src != cfg.GOROOTsrc {
continue
}
src = filepath.Clean(src) + string(filepath.Separator)
root := src
if pattern == "cmd" {
root += "cmd" + string(filepath.Separator)
}
filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
if err != nil || path == src {
return nil
}
want := true
// Avoid .foo, _foo, and testdata directory trees.
_, elem := filepath.Split(path)
if strings.HasPrefix(elem, ".") || strings.HasPrefix(elem, "_") || elem == "testdata" {
want = false
}
name := filepath.ToSlash(path[len(src):])
if pattern == "std" && (!IsStandardImportPath(name) || name == "cmd") {
// The name "std" is only the standard library.
// If the name is cmd, it's the root of the command tree.
want = false
}
if !treeCanMatch(name) {
want = false
}
if !fi.IsDir() {
if fi.Mode()&os.ModeSymlink != 0 && want {
if target, err := os.Stat(path); err == nil && target.IsDir() {
fmt.Fprintf(os.Stderr, "warning: ignoring symlink %s\n", path)
}
}
return nil
}
if !want {
return filepath.SkipDir
}
if have[name] {
return nil
}
have[name] = true
if !match(name) {
return nil
}
pkg, err := cfg.BuildContext.ImportDir(path, 0)
if err != nil {
if _, noGo := err.(*build.NoGoError); noGo {
return nil
}
}
// If we are expanding "cmd", skip main
// packages under cmd/vendor. At least as of
// March, 2017, there is one there for the
// vendored pprof tool.
if pattern == "cmd" && strings.HasPrefix(pkg.ImportPath, "cmd/vendor") && pkg.Name == "main" {
return nil
}
m.Pkgs = append(m.Pkgs, name)
return nil
})
}
return m
}
var modRoot string
func SetModRoot(dir string) {
modRoot = dir
}
// MatchPackagesInFS is like allPackages but is passed a pattern
// beginning ./ or ../, meaning it should scan the tree rooted
// at the given directory. There are ... in the pattern too.
// (See go help packages for pattern syntax.)
func MatchPackagesInFS(pattern string) *Match {
m := &Match{
Pattern: pattern,
Literal: false,
}
// Find directory to begin the scan.
// Could be smarter but this one optimization
// is enough for now, since ... is usually at the
// end of a path.
i := strings.Index(pattern, "...")
dir, _ := path.Split(pattern[:i])
// pattern begins with ./ or ../.
// path.Clean will discard the ./ but not the ../.
// We need to preserve the ./ for pattern matching
// and in the returned import paths.
prefix := ""
if strings.HasPrefix(pattern, "./") {
prefix = "./"
}
match := MatchPattern(pattern)
if modRoot != "" {
abs, err := filepath.Abs(dir)
if err != nil {
base.Fatalf("go: %v", err)
}
if !hasFilepathPrefix(abs, modRoot) {
base.Fatalf("go: pattern %s refers to dir %s, outside module root %s", pattern, abs, modRoot)
return nil
}
}
filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error {
if err != nil || !fi.IsDir() {
return nil
}
top := false
if path == dir {
// filepath.Walk starts at dir and recurses. For the recursive case,
// the path is the result of filepath.Join, which calls filepath.Clean.
// The initial case is not Cleaned, though, so we do this explicitly.
//
// This converts a path like "./io/" to "io". Without this step, running
// "cd $GOROOT/src; go list ./io/..." would incorrectly skip the io
// package, because prepending the prefix "./" to the unclean path would
// result in "././io", and match("././io") returns false.
top = true
path = filepath.Clean(path)
}
// Avoid .foo, _foo, and testdata directory trees, but do not avoid "." or "..".
_, elem := filepath.Split(path)
dot := strings.HasPrefix(elem, ".") && elem != "." && elem != ".."
if dot || strings.HasPrefix(elem, "_") || elem == "testdata" {
return filepath.SkipDir
}
if !top && cfg.ModulesEnabled {
// Ignore other modules found in subdirectories.
if _, err := os.Stat(filepath.Join(path, "go.mod")); err == nil {
return filepath.SkipDir
}
}
name := prefix + filepath.ToSlash(path)
if !match(name) {
return nil
}
// We keep the directory if we can import it, or if we can't import it
// due to invalid Go source files. This means that directories containing
// parse errors will be built (and fail) instead of being silently skipped
// as not matching the pattern. Go 1.5 and earlier skipped, but that
// behavior means people miss serious mistakes.
// See golang.org/issue/11407.
if p, err := cfg.BuildContext.ImportDir(path, 0); err != nil && (p == nil || len(p.InvalidGoFiles) == 0) {
if _, noGo := err.(*build.NoGoError); !noGo {
log.Print(err)
}
return nil
}
m.Pkgs = append(m.Pkgs, name)
return nil
})
return m
}
// TreeCanMatchPattern(pattern)(name) reports whether
// name or children of name can possibly match pattern.
// Pattern is the same limited glob accepted by matchPattern.
func TreeCanMatchPattern(pattern string) func(name string) bool {
wildCard := false
if i := strings.Index(pattern, "..."); i >= 0 {
wildCard = true
pattern = pattern[:i]
}
return func(name string) bool {
return len(name) <= len(pattern) && hasPathPrefix(pattern, name) ||
wildCard && strings.HasPrefix(name, pattern)
}
}
// MatchPattern(pattern)(name) reports whether
// name matches pattern. Pattern is a limited glob
// pattern in which '...' means 'any string' and there
// is no other special syntax.
// Unfortunately, there are two special cases. Quoting "go help packages":
//
// First, /... at the end of the pattern can match an empty string,
// so that net/... matches both net and packages in its subdirectories, like net/http.
// Second, any slash-separted pattern element containing a wildcard never
// participates in a match of the "vendor" element in the path of a vendored
// package, so that ./... does not match packages in subdirectories of
// ./vendor or ./mycode/vendor, but ./vendor/... and ./mycode/vendor/... do.
// Note, however, that a directory named vendor that itself contains code
// is not a vendored package: cmd/vendor would be a command named vendor,
// and the pattern cmd/... matches it.
func MatchPattern(pattern string) func(name string) bool {
// Convert pattern to regular expression.
// The strategy for the trailing /... is to nest it in an explicit ? expression.
// The strategy for the vendor exclusion is to change the unmatchable
// vendor strings to a disallowed code point (vendorChar) and to use
// "(anything but that codepoint)*" as the implementation of the ... wildcard.
// This is a bit complicated but the obvious alternative,
// namely a hand-written search like in most shell glob matchers,
// is too easy to make accidentally exponential.
// Using package regexp guarantees linear-time matching.
const vendorChar = "\x00"
if strings.Contains(pattern, vendorChar) {
return func(name string) bool { return false }
}
re := regexp.QuoteMeta(pattern)
re = replaceVendor(re, vendorChar)
switch {
case strings.HasSuffix(re, `/`+vendorChar+`/\.\.\.`):
re = strings.TrimSuffix(re, `/`+vendorChar+`/\.\.\.`) + `(/vendor|/` + vendorChar + `/\.\.\.)`
case re == vendorChar+`/\.\.\.`:
re = `(/vendor|/` + vendorChar + `/\.\.\.)`
case strings.HasSuffix(re, `/\.\.\.`):
re = strings.TrimSuffix(re, `/\.\.\.`) + `(/\.\.\.)?`
}
re = strings.Replace(re, `\.\.\.`, `[^`+vendorChar+`]*`, -1)
reg := regexp.MustCompile(`^` + re + `$`)
return func(name string) bool {
if strings.Contains(name, vendorChar) {
return false
}
return reg.MatchString(replaceVendor(name, vendorChar))
}
}
// replaceVendor returns the result of replacing
// non-trailing vendor path elements in x with repl.
func replaceVendor(x, repl string) string {
if !strings.Contains(x, "vendor") {
return x
}
elem := strings.Split(x, "/")
for i := 0; i < len(elem)-1; i++ {
if elem[i] == "vendor" {
elem[i] = repl
}
}
return strings.Join(elem, "/")
}
// WarnUnmatched warns about patterns that didn't match any packages.
func WarnUnmatched(matches []*Match) {
for _, m := range matches {
if len(m.Pkgs) == 0 {
fmt.Fprintf(os.Stderr, "go: warning: %q matched no packages\n", m.Pattern)
}
}
}
// ImportPaths returns the matching paths to use for the given command line.
// It calls ImportPathsQuiet and then WarnUnmatched.
func ImportPaths(patterns []string) []*Match {
matches := ImportPathsQuiet(patterns)
WarnUnmatched(matches)
return matches
}
// ImportPathsQuiet is like ImportPaths but does not warn about patterns with no matches.
func ImportPathsQuiet(patterns []string) []*Match {
var out []*Match
for _, a := range CleanPatterns(patterns) {
if IsMetaPackage(a) {
out = append(out, MatchPackages(a))
continue
}
if strings.Contains(a, "...") {
if build.IsLocalImport(a) {
out = append(out, MatchPackagesInFS(a))
} else {
out = append(out, MatchPackages(a))
}
continue
}
out = append(out, &Match{Pattern: a, Literal: true, Pkgs: []string{a}})
}
return out
}
// CleanPatterns returns the patterns to use for the given
// command line. It canonicalizes the patterns but does not
// evaluate any matches.
func CleanPatterns(patterns []string) []string {
if len(patterns) == 0 {
return []string{"."}
}
var out []string
for _, a := range patterns {
// Arguments are supposed to be import paths, but
// as a courtesy to Windows developers, rewrite \ to /
// in command-line arguments. Handles .\... and so on.
if filepath.Separator == '\\' {
a = strings.Replace(a, `\`, `/`, -1)
}
// Put argument in canonical form, but preserve leading ./.
if strings.HasPrefix(a, "./") {
a = "./" + path.Clean(a)
if a == "./." {
a = "."
}
} else {
a = path.Clean(a)
}
out = append(out, a)
}
return out
}
// IsMetaPackage checks if name is a reserved package name that expands to multiple packages.
func IsMetaPackage(name string) bool {
return name == "std" || name == "cmd" || name == "all"
}
// hasPathPrefix reports whether the path s begins with the
// elements in prefix.
func hasPathPrefix(s, prefix string) bool {
switch {
default:
return false
case len(s) == len(prefix):
return s == prefix
case len(s) > len(prefix):
if prefix != "" && prefix[len(prefix)-1] == '/' {
return strings.HasPrefix(s, prefix)
}
return s[len(prefix)] == '/' && s[:len(prefix)] == prefix
}
}
// hasFilepathPrefix reports whether the path s begins with the
// elements in prefix.
func hasFilepathPrefix(s, prefix string) bool {
switch {
default:
return false
case len(s) == len(prefix):
return s == prefix
case len(s) > len(prefix):
if prefix != "" && prefix[len(prefix)-1] == filepath.Separator {
return strings.HasPrefix(s, prefix)
}
return s[len(prefix)] == filepath.Separator && s[:len(prefix)] == prefix
}
}
// IsStandardImportPath reports whether $GOROOT/src/path should be considered
// part of the standard distribution. For historical reasons we allow people to add
// their own code to $GOROOT instead of using $GOPATH, but we assume that
// code will start with a domain name (dot in the first element).
//
// Note that this function is meant to evaluate whether a directory found in GOROOT
// should be treated as part of the standard library. It should not be used to decide
// that a directory found in GOPATH should be rejected: directories in GOPATH
// need not have dots in the first element, and they just take their chances
// with future collisions in the standard library.
func IsStandardImportPath(path string) bool {
i := strings.Index(path, "/")
if i < 0 {
i = len(path)
}
elem := path[:i]
return !strings.Contains(elem, ".")
}
// IsRelativePath reports whether pattern should be interpreted as a directory
// path relative to the current directory, as opposed to a pattern matching
// import paths.
func IsRelativePath(pattern string) bool {
return strings.HasPrefix(pattern, "./") || strings.HasPrefix(pattern, "../") || pattern == "." || pattern == ".."
}
// InDir checks whether path is in the file tree rooted at dir.
// If so, InDir returns an equivalent path relative to dir.
// If not, InDir returns an empty string.
// InDir makes some effort to succeed even in the presence of symbolic links.
// TODO(rsc): Replace internal/test.inDir with a call to this function for Go 1.12.
func InDir(path, dir string) string {
if rel := inDirLex(path, dir); rel != "" {
return rel
}
xpath, err := filepath.EvalSymlinks(path)
if err != nil || xpath == path {
xpath = ""
} else {
if rel := inDirLex(xpath, dir); rel != "" {
return rel
}
}
xdir, err := filepath.EvalSymlinks(dir)
if err == nil && xdir != dir {
if rel := inDirLex(path, xdir); rel != "" {
return rel
}
if xpath != "" {
if rel := inDirLex(xpath, xdir); rel != "" {
return rel
}
}
}
return ""
}
// inDirLex is like inDir but only checks the lexical form of the file names.
// It does not consider symbolic links.
// TODO(rsc): This is a copy of str.HasFilePathPrefix, modified to
// return the suffix. Most uses of str.HasFilePathPrefix should probably
// be calling InDir instead.
func inDirLex(path, dir string) string {
pv := strings.ToUpper(filepath.VolumeName(path))
dv := strings.ToUpper(filepath.VolumeName(dir))
path = path[len(pv):]
dir = dir[len(dv):]
switch {
default:
return ""
case pv != dv:
return ""
case len(path) == len(dir):
if path == dir {
return "."
}
return ""
case dir == "":
return path
case len(path) > len(dir):
if dir[len(dir)-1] == filepath.Separator {
if path[:len(dir)] == dir {
return path[len(dir):]
}
return ""
}
if path[len(dir)] == filepath.Separator && path[:len(dir)] == dir {
if len(path) == len(dir)+1 {
return "."
}
return path[len(dir)+1:]
}
return ""
}
}
|
search
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/search/search_test.go
|
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package search
import (
"strings"
"testing"
)
var matchPatternTests = `
pattern ...
match foo
pattern net
match net
not net/http
pattern net/http
match net/http
not net
pattern net...
match net net/http netchan
not not/http not/net/http
# Special cases. Quoting docs:
# First, /... at the end of the pattern can match an empty string,
# so that net/... matches both net and packages in its subdirectories, like net/http.
pattern net/...
match net net/http
not not/http not/net/http netchan
# Second, any slash-separted pattern element containing a wildcard never
# participates in a match of the "vendor" element in the path of a vendored
# package, so that ./... does not match packages in subdirectories of
# ./vendor or ./mycode/vendor, but ./vendor/... and ./mycode/vendor/... do.
# Note, however, that a directory named vendor that itself contains code
# is not a vendored package: cmd/vendor would be a command named vendor,
# and the pattern cmd/... matches it.
pattern ./...
match ./vendor ./mycode/vendor
not ./vendor/foo ./mycode/vendor/foo
pattern ./vendor/...
match ./vendor/foo ./vendor/foo/vendor
not ./vendor/foo/vendor/bar
pattern mycode/vendor/...
match mycode/vendor mycode/vendor/foo mycode/vendor/foo/vendor
not mycode/vendor/foo/vendor/bar
pattern x/vendor/y
match x/vendor/y
not x/vendor
pattern x/vendor/y/...
match x/vendor/y x/vendor/y/z x/vendor/y/vendor x/vendor/y/z/vendor
not x/vendor/y/vendor/z
pattern .../vendor/...
match x/vendor/y x/vendor/y/z x/vendor/y/vendor x/vendor/y/z/vendor
`
func TestMatchPattern(t *testing.T) {
testPatterns(t, "MatchPattern", matchPatternTests, func(pattern, name string) bool {
return MatchPattern(pattern)(name)
})
}
var treeCanMatchPatternTests = `
pattern ...
match foo
pattern net
match net
not net/http
pattern net/http
match net net/http
pattern net...
match net netchan net/http
not not/http not/net/http
pattern net/...
match net net/http
not not/http netchan
pattern abc.../def
match abcxyz
not xyzabc
pattern x/y/z/...
match x x/y x/y/z x/y/z/w
pattern x/y/z
match x x/y x/y/z
not x/y/z/w
pattern x/.../y/z
match x/a/b/c
not y/x/a/b/c
`
func TestTreeCanMatchPattern(t *testing.T) {
testPatterns(t, "TreeCanMatchPattern", treeCanMatchPatternTests, func(pattern, name string) bool {
return TreeCanMatchPattern(pattern)(name)
})
}
var hasPathPrefixTests = []stringPairTest{
{"abc", "a", false},
{"a/bc", "a", true},
{"a", "a", true},
{"a/bc", "a/", true},
}
func TestHasPathPrefix(t *testing.T) {
testStringPairs(t, "hasPathPrefix", hasPathPrefixTests, hasPathPrefix)
}
type stringPairTest struct {
in1 string
in2 string
out bool
}
func testStringPairs(t *testing.T, name string, tests []stringPairTest, f func(string, string) bool) {
for _, tt := range tests {
if out := f(tt.in1, tt.in2); out != tt.out {
t.Errorf("%s(%q, %q) = %v, want %v", name, tt.in1, tt.in2, out, tt.out)
}
}
}
func testPatterns(t *testing.T, name, tests string, fn func(string, string) bool) {
var patterns []string
for _, line := range strings.Split(tests, "\n") {
if i := strings.Index(line, "#"); i >= 0 {
line = line[:i]
}
f := strings.Fields(line)
if len(f) == 0 {
continue
}
switch f[0] {
default:
t.Fatalf("unknown directive %q", f[0])
case "pattern":
patterns = f[1:]
case "match", "not":
want := f[0] == "match"
for _, pattern := range patterns {
for _, in := range f[1:] {
if fn(pattern, in) != want {
t.Errorf("%s(%q, %q) = %v, want %v", name, pattern, in, !want, want)
}
}
}
}
}
}
|
run
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/run/run.go
|
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package run implements the ``go run'' command.
package run
import (
"fmt"
"os"
"strings"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"cmd/go/internal/load"
"cmd/go/internal/str"
"cmd/go/internal/work"
)
var CmdRun = &base.Command{
UsageLine: "go run [build flags] [-exec xprog] package [arguments...]",
Short: "compile and run Go program",
Long: `
Run compiles and runs the named main Go package.
Typically the package is specified as a list of .go source files,
but it may also be an import path, file system path, or pattern
matching a single known package, as in 'go run .' or 'go run my/cmd'.
By default, 'go run' runs the compiled binary directly: 'a.out arguments...'.
If the -exec flag is given, 'go run' invokes the binary using xprog:
'xprog a.out arguments...'.
If the -exec flag is not given, GOOS or GOARCH is different from the system
default, and a program named go_$GOOS_$GOARCH_exec can be found
on the current search path, 'go run' invokes the binary using that program,
for example 'go_nacl_386_exec a.out arguments...'. This allows execution of
cross-compiled programs when a simulator or other execution method is
available.
The exit status of Run is not the exit status of the compiled binary.
For more about build flags, see 'go help build'.
For more about specifying packages, see 'go help packages'.
See also: go build.
`,
}
func init() {
CmdRun.Run = runRun // break init loop
work.AddBuildFlags(CmdRun)
CmdRun.Flag.Var((*base.StringsFlag)(&work.ExecCmd), "exec", "")
}
func printStderr(args ...interface{}) (int, error) {
return fmt.Fprint(os.Stderr, args...)
}
func runRun(cmd *base.Command, args []string) {
work.BuildInit()
var b work.Builder
b.Init()
b.Print = printStderr
i := 0
for i < len(args) && strings.HasSuffix(args[i], ".go") {
i++
}
var p *load.Package
if i > 0 {
files := args[:i]
for _, file := range files {
if strings.HasSuffix(file, "_test.go") {
// GoFilesPackage is going to assign this to TestGoFiles.
// Reject since it won't be part of the build.
base.Fatalf("go run: cannot run *_test.go files (%s)", file)
}
}
p = load.GoFilesPackage(files)
} else if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
pkgs := load.PackagesAndErrors(args[:1])
if len(pkgs) > 1 {
var names []string
for _, p := range pkgs {
names = append(names, p.ImportPath)
}
base.Fatalf("go run: pattern %s matches multiple packages:\n\t%s", args[0], strings.Join(names, "\n\t"))
}
p = pkgs[0]
i++
} else {
base.Fatalf("go run: no go files listed")
}
cmdArgs := args[i:]
if p.Error != nil {
base.Fatalf("%s", p.Error)
}
p.Internal.OmitDebug = true
if len(p.DepsErrors) > 0 {
// Since these are errors in dependencies,
// the same error might show up multiple times,
// once in each package that depends on it.
// Only print each once.
printed := map[*load.PackageError]bool{}
for _, err := range p.DepsErrors {
if !printed[err] {
printed[err] = true
base.Errorf("%s", err)
}
}
}
base.ExitIfErrors()
if p.Name != "main" {
base.Fatalf("go run: cannot run non-main package")
}
p.Target = "" // must build - not up to date
var src string
if len(p.GoFiles) > 0 {
src = p.GoFiles[0]
} else if len(p.CgoFiles) > 0 {
src = p.CgoFiles[0]
} else {
// this case could only happen if the provided source uses cgo
// while cgo is disabled.
hint := ""
if !cfg.BuildContext.CgoEnabled {
hint = " (cgo is disabled)"
}
base.Fatalf("go run: no suitable source files%s", hint)
}
p.Internal.ExeName = src[:len(src)-len(".go")] // name temporary executable for first go file
a1 := b.LinkAction(work.ModeBuild, work.ModeBuild, p)
a := &work.Action{Mode: "go run", Func: buildRunProgram, Args: cmdArgs, Deps: []*work.Action{a1}}
b.Do(a)
}
// buildRunProgram is the action for running a binary that has already
// been compiled. We ignore exit status.
func buildRunProgram(b *work.Builder, a *work.Action) error {
cmdline := str.StringList(work.FindExecCmd(), a.Deps[0].Target, a.Args)
if cfg.BuildN || cfg.BuildX {
b.Showcmd("", "%s", strings.Join(cmdline, " "))
if cfg.BuildN {
return nil
}
}
base.RunStdin(cmdline)
return nil
}
|
webtest
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/webtest/test.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package webtest
import (
"bufio"
"bytes"
"encoding/hex"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"sort"
"strconv"
"strings"
"sync"
"unicode/utf8"
web "cmd/go/internal/web2"
)
var mode = flag.String("webtest", "replay", "set webtest `mode` - record, replay, bypass")
func Hook() {
if *mode == "bypass" {
return
}
web.SetHTTPDoForTesting(Do)
}
func Unhook() {
web.SetHTTPDoForTesting(nil)
}
func Print() {
web.SetHTTPDoForTesting(DoPrint)
}
var responses struct {
mu sync.Mutex
byURL map[string]*respEntry
}
type respEntry struct {
status string
code int
hdr http.Header
body []byte
}
func Serve(url string, status string, hdr http.Header, body []byte) {
if status == "" {
status = "200 OK"
}
code, err := strconv.Atoi(strings.Fields(status)[0])
if err != nil {
panic("bad Serve status - " + status + " - " + err.Error())
}
responses.mu.Lock()
defer responses.mu.Unlock()
if responses.byURL == nil {
responses.byURL = make(map[string]*respEntry)
}
responses.byURL[url] = &respEntry{status: status, code: code, hdr: web.CopyHeader(hdr), body: body}
}
func Do(req *http.Request) (*http.Response, error) {
if req.Method != "GET" {
return nil, fmt.Errorf("bad method - must be GET")
}
responses.mu.Lock()
e := responses.byURL[req.URL.String()]
responses.mu.Unlock()
if e == nil {
if *mode == "record" {
loaded.mu.Lock()
if len(loaded.did) != 1 {
loaded.mu.Unlock()
return nil, fmt.Errorf("cannot use -webtest=record with multiple loaded response files")
}
var file string
for file = range loaded.did {
break
}
loaded.mu.Unlock()
return doSave(file, req)
}
e = &respEntry{code: 599, status: "599 unexpected request (no canned response)"}
}
resp := &http.Response{
Status: e.status,
StatusCode: e.code,
Header: web.CopyHeader(e.hdr),
Body: ioutil.NopCloser(bytes.NewReader(e.body)),
}
return resp, nil
}
func DoPrint(req *http.Request) (*http.Response, error) {
return doSave("", req)
}
func doSave(file string, req *http.Request) (*http.Response, error) {
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, err
}
resp.Body = ioutil.NopCloser(bytes.NewReader(data))
var f *os.File
if file == "" {
f = os.Stderr
} else {
f, err = os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
defer f.Close()
}
fmt.Fprintf(f, "GET %s\n", req.URL.String())
fmt.Fprintf(f, "%s\n", resp.Status)
var keys []string
for k := range resp.Header {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
if k == "Set-Cookie" {
continue
}
for _, v := range resp.Header[k] {
fmt.Fprintf(f, "%s: %s\n", k, v)
}
}
fmt.Fprintf(f, "\n")
if utf8.Valid(data) && !bytes.Contains(data, []byte("\nGET")) && !isHexDump(data) {
fmt.Fprintf(f, "%s\n\n", data)
} else {
fmt.Fprintf(f, "%s\n", hex.Dump(data))
}
return resp, err
}
var loaded struct {
mu sync.Mutex
did map[string]bool
}
func LoadOnce(file string) {
loaded.mu.Lock()
if loaded.did[file] {
loaded.mu.Unlock()
return
}
if loaded.did == nil {
loaded.did = make(map[string]bool)
}
loaded.did[file] = true
loaded.mu.Unlock()
f, err := os.Open(file)
if err != nil {
log.Fatal(err)
}
defer f.Close()
b := bufio.NewReader(f)
var ungetLine string
nextLine := func() string {
if ungetLine != "" {
l := ungetLine
ungetLine = ""
return l
}
line, err := b.ReadString('\n')
if err != nil {
if err == io.EOF {
return ""
}
log.Fatalf("%s: unexpected read error: %v", file, err)
}
return line
}
for {
line := nextLine()
if line == "" { // EOF
break
}
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "#") || line == "" {
continue
}
if !strings.HasPrefix(line, "GET ") {
log.Fatalf("%s: malformed GET line: %s", file, line)
}
url := line[len("GET "):]
status := nextLine()
if _, err := strconv.Atoi(strings.Fields(status)[0]); err != nil {
log.Fatalf("%s: malformed status line (after GET %s): %s", file, url, status)
}
hdr := make(http.Header)
for {
kv := strings.TrimSpace(nextLine())
if kv == "" {
break
}
i := strings.Index(kv, ":")
if i < 0 {
log.Fatalf("%s: malformed header line (after GET %s): %s", file, url, kv)
}
k, v := kv[:i], strings.TrimSpace(kv[i+1:])
hdr[k] = append(hdr[k], v)
}
var body []byte
Body:
for n := 0; ; n++ {
line := nextLine()
if n == 0 && isHexDump([]byte(line)) {
ungetLine = line
b, err := parseHexDump(nextLine)
if err != nil {
log.Fatalf("%s: malformed hex dump (after GET %s): %v", file, url, err)
}
body = b
break
}
if line == "" { // EOF
for i := 0; i < 2; i++ {
if len(body) > 0 && body[len(body)-1] == '\n' {
body = body[:len(body)-1]
}
}
break
}
body = append(body, line...)
for line == "\n" {
line = nextLine()
if strings.HasPrefix(line, "GET ") {
ungetLine = line
body = body[:len(body)-1]
if len(body) > 0 {
body = body[:len(body)-1]
}
break Body
}
body = append(body, line...)
}
}
Serve(url, status, hdr, body)
}
}
func isHexDump(data []byte) bool {
return bytes.HasPrefix(data, []byte("00000000 ")) || bytes.HasPrefix(data, []byte("0000000 "))
}
// parseHexDump parses the hex dump in text, which should be the
// output of "hexdump -C" or Plan 9's "xd -b" or Go's hex.Dump
// and returns the original data used to produce the dump.
// It is meant to enable storing golden binary files as text, so that
// changes to the golden files can be seen during code reviews.
func parseHexDump(nextLine func() string) ([]byte, error) {
var out []byte
for {
line := nextLine()
if line == "" || line == "\n" {
break
}
if i := strings.Index(line, "|"); i >= 0 { // remove text dump
line = line[:i]
}
f := strings.Fields(line)
if len(f) > 1+16 {
return nil, fmt.Errorf("parsing hex dump: too many fields on line %q", line)
}
if len(f) == 0 || len(f) == 1 && f[0] == "*" { // all zeros block omitted
continue
}
addr64, err := strconv.ParseUint(f[0], 16, 0)
if err != nil {
return nil, fmt.Errorf("parsing hex dump: invalid address %q", f[0])
}
addr := int(addr64)
if len(out) < addr {
out = append(out, make([]byte, addr-len(out))...)
}
for _, x := range f[1:] {
val, err := strconv.ParseUint(x, 16, 8)
if err != nil {
return nil, fmt.Errorf("parsing hexdump: invalid hex byte %q", x)
}
out = append(out, byte(val))
}
}
return out, nil
}
|
list
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/list/context.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package list
import (
"go/build"
)
type Context struct {
GOARCH string `json:",omitempty"` // target architecture
GOOS string `json:",omitempty"` // target operating system
GOROOT string `json:",omitempty"` // Go root
GOPATH string `json:",omitempty"` // Go path
CgoEnabled bool `json:",omitempty"` // whether cgo can be used
UseAllFiles bool `json:",omitempty"` // use files regardless of +build lines, file names
Compiler string `json:",omitempty"` // compiler to assume when computing target paths
BuildTags []string `json:",omitempty"` // build constraints to match in +build lines
ReleaseTags []string `json:",omitempty"` // releases the current release is compatible with
InstallSuffix string `json:",omitempty"` // suffix to use in the name of the install dir
}
func newContext(c *build.Context) *Context {
return &Context{
GOARCH: c.GOARCH,
GOOS: c.GOOS,
GOROOT: c.GOROOT,
GOPATH: c.GOPATH,
CgoEnabled: c.CgoEnabled,
UseAllFiles: c.UseAllFiles,
Compiler: c.Compiler,
BuildTags: c.BuildTags,
ReleaseTags: c.ReleaseTags,
InstallSuffix: c.InstallSuffix,
}
}
|
list
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/list/list.go
|
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package list implements the ``go list'' command.
package list
import (
"bufio"
"bytes"
"encoding/json"
"io"
"os"
"sort"
"strings"
"text/template"
"cmd/go/internal/base"
"cmd/go/internal/cache"
"cmd/go/internal/cfg"
"cmd/go/internal/load"
"cmd/go/internal/modload"
"cmd/go/internal/str"
"cmd/go/internal/work"
)
var CmdList = &base.Command{
// Note: -f -json -m are listed explicitly because they are the most common list flags.
// Do not send CLs removing them because they're covered by [list flags].
UsageLine: "go list [-f format] [-json] [-m] [list flags] [build flags] [packages]",
Short: "list packages or modules",
Long: `
List lists the named packages, one per line.
The most commonly-used flags are -f and -json, which control the form
of the output printed for each package. Other list flags, documented below,
control more specific details.
The default output shows the package import path:
bytes
encoding/json
github.com/gorilla/mux
golang.org/x/net/html
The -f flag specifies an alternate format for the list, using the
syntax of package template. The default output is equivalent
to -f '{{.ImportPath}}'. The struct being passed to the template is:
type Package struct {
Dir string // directory containing package sources
ImportPath string // import path of package in dir
ImportComment string // path in import comment on package statement
Name string // package name
Doc string // package documentation string
Target string // install path
Shlib string // the shared library that contains this package (only set when -linkshared)
Goroot bool // is this package in the Go root?
Standard bool // is this package part of the standard Go library?
Stale bool // would 'go install' do anything for this package?
StaleReason string // explanation for Stale==true
Root string // Go root or Go path dir containing this package
ConflictDir string // this directory shadows Dir in $GOPATH
BinaryOnly bool // binary-only package: cannot be recompiled from sources
ForTest string // package is only for use in named test
Export string // file containing export data (when using -export)
Module *Module // info about package's containing module, if any (can be nil)
Match []string // command-line patterns matching this package
DepOnly bool // package is only a dependency, not explicitly listed
// 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
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
// Cgo directives
CgoCFLAGS []string // cgo: flags for C compiler
CgoCPPFLAGS []string // cgo: flags for C preprocessor
CgoCXXFLAGS []string // cgo: flags for C++ compiler
CgoFFLAGS []string // cgo: flags for Fortran compiler
CgoLDFLAGS []string // cgo: flags for linker
CgoPkgConfig []string // cgo: pkg-config names
// Dependency information
Imports []string // import paths used by this package
ImportMap map[string]string // map from source import to ImportPath (identity entries omitted)
Deps []string // all (recursively) imported dependencies
TestImports []string // imports from TestGoFiles
XTestImports []string // imports from XTestGoFiles
// Error information
Incomplete bool // this package or a dependency has an error
Error *PackageError // error loading package
DepsErrors []*PackageError // errors loading dependencies
}
Packages stored in vendor directories report an ImportPath that includes the
path to the vendor directory (for example, "d/vendor/p" instead of "p"),
so that the ImportPath uniquely identifies a given copy of a package.
The Imports, Deps, TestImports, and XTestImports lists also contain these
expanded import paths. See golang.org/s/go15vendor for more about vendoring.
The error information, if any, is
type PackageError struct {
ImportStack []string // shortest path from package named on command line to this one
Pos string // position of error (if present, file:line:col)
Err string // the error itself
}
The module information is a Module struct, defined in the discussion
of list -m below.
The template function "join" calls strings.Join.
The template function "context" returns the build context, defined as:
type Context struct {
GOARCH string // target architecture
GOOS string // target operating system
GOROOT string // Go root
GOPATH string // Go path
CgoEnabled bool // whether cgo can be used
UseAllFiles bool // use files regardless of +build lines, file names
Compiler string // compiler to assume when computing target paths
BuildTags []string // build constraints to match in +build lines
ReleaseTags []string // releases the current release is compatible with
InstallSuffix string // suffix to use in the name of the install dir
}
For more information about the meaning of these fields see the documentation
for the go/build package's Context type.
The -json flag causes the package data to be printed in JSON format
instead of using the template format.
The -compiled flag causes list to set CompiledGoFiles to the Go source
files presented to the compiler. Typically this means that it repeats
the files listed in GoFiles and then also adds the Go code generated
by processing CgoFiles and SwigFiles. The Imports list contains the
union of all imports from both GoFiles and CompiledGoFiles.
The -deps flag causes list to iterate over not just the named packages
but also all their dependencies. It visits them in a depth-first post-order
traversal, so that a package is listed only after all its dependencies.
Packages not explicitly listed on the command line will have the DepOnly
field set to true.
The -e flag changes the handling of erroneous packages, those that
cannot be found or are malformed. By default, the list command
prints an error to standard error for each erroneous package and
omits the packages from consideration during the usual printing.
With the -e flag, the list command never prints errors to standard
error and instead processes the erroneous packages with the usual
printing. Erroneous packages will have a non-empty ImportPath and
a non-nil Error field; other information may or may not be missing
(zeroed).
The -export flag causes list to set the Export field to the name of a
file containing up-to-date export information for the given package.
The -find flag causes list to identify the named packages but not
resolve their dependencies: the Imports and Deps lists will be empty.
The -test flag causes list to report not only the named packages
but also their test binaries (for packages with tests), to convey to
source code analysis tools exactly how test binaries are constructed.
The reported import path for a test binary is the import path of
the package followed by a ".test" suffix, as in "math/rand.test".
When building a test, it is sometimes necessary to rebuild certain
dependencies specially for that test (most commonly the tested
package itself). The reported import path of a package recompiled
for a particular test binary is followed by a space and the name of
the test binary in brackets, as in "math/rand [math/rand.test]"
or "regexp [sort.test]". The ForTest field is also set to the name
of the package being tested ("math/rand" or "sort" in the previous
examples).
The Dir, Target, Shlib, Root, ConflictDir, and Export file paths
are all absolute paths.
By default, the lists GoFiles, CgoFiles, and so on hold names of files in Dir
(that is, paths relative to Dir, not absolute paths).
The generated files added when using the -compiled and -test flags
are absolute paths referring to cached copies of generated Go source files.
Although they are Go source files, the paths may not end in ".go".
The -m flag causes list to list modules instead of packages.
When listing modules, the -f flag still specifies a format template
applied to a Go struct, but now a Module struct:
type Module struct {
Path string // module path
Version string // module version
Versions []string // available module versions (with -versions)
Replace *Module // replaced by this module
Time *time.Time // time version was created
Update *Module // available update, if any (with -u)
Main bool // is this the main module?
Indirect bool // is this module only an indirect dependency of main module?
Dir string // directory holding files for this module, if any
GoMod string // path to go.mod file for this module, if any
Error *ModuleError // error loading module
}
type ModuleError struct {
Err string // the error itself
}
The default output is to print the module path and then
information about the version and replacement if any.
For example, 'go list -m all' might print:
my/main/module
golang.org/x/text v0.3.0 => /tmp/text
rsc.io/pdf v0.1.1
The Module struct has a String method that formats this
line of output, so that the default format is equivalent
to -f '{{.String}}'.
Note that when a module has been replaced, its Replace field
describes the replacement module, and its Dir field is set to
the replacement's source code, if present. (That is, if Replace
is non-nil, then Dir is set to Replace.Dir, with no access to
the replaced source code.)
The -u flag adds information about available upgrades.
When the latest version of a given module is newer than
the current one, list -u sets the Module's Update field
to information about the newer module.
The Module's String method indicates an available upgrade by
formatting the newer version in brackets after the current version.
For example, 'go list -m -u all' might print:
my/main/module
golang.org/x/text v0.3.0 [v0.4.0] => /tmp/text
rsc.io/pdf v0.1.1 [v0.1.2]
(For tools, 'go list -m -u -json all' may be more convenient to parse.)
The -versions flag causes list to set the Module's Versions field
to a list of all known versions of that module, ordered according
to semantic versioning, earliest to latest. The flag also changes
the default output format to display the module path followed by the
space-separated version list.
The arguments to list -m are interpreted as a list of modules, not packages.
The main module is the module containing the current directory.
The active modules are the main module and its dependencies.
With no arguments, list -m shows the main module.
With arguments, list -m shows the modules specified by the arguments.
Any of the active modules can be specified by its module path.
The special pattern "all" specifies all the active modules, first the main
module and then dependencies sorted by module path.
A pattern containing "..." specifies the active modules whose
module paths match the pattern.
A query of the form path@version specifies the result of that query,
which is not limited to active modules.
See 'go help modules' for more about module queries.
The template function "module" takes a single string argument
that must be a module path or query and returns the specified
module as a Module struct. If an error occurs, the result will
be a Module struct with a non-nil Error field.
For more about build flags, see 'go help build'.
For more about specifying packages, see 'go help packages'.
For more about modules, see 'go help modules'.
`,
}
func init() {
CmdList.Run = runList // break init cycle
work.AddBuildFlags(CmdList)
}
var (
listCompiled = CmdList.Flag.Bool("compiled", false, "")
listDeps = CmdList.Flag.Bool("deps", false, "")
listE = CmdList.Flag.Bool("e", false, "")
listExport = CmdList.Flag.Bool("export", false, "")
listFmt = CmdList.Flag.String("f", "", "")
listFind = CmdList.Flag.Bool("find", false, "")
listJson = CmdList.Flag.Bool("json", false, "")
listM = CmdList.Flag.Bool("m", false, "")
listU = CmdList.Flag.Bool("u", false, "")
listTest = CmdList.Flag.Bool("test", false, "")
listVersions = CmdList.Flag.Bool("versions", false, "")
)
var nl = []byte{'\n'}
func runList(cmd *base.Command, args []string) {
modload.LoadTests = *listTest
work.BuildInit()
out := newTrackingWriter(os.Stdout)
defer out.w.Flush()
if *listFmt == "" {
if *listM {
*listFmt = "{{.String}}"
if *listVersions {
*listFmt = `{{.Path}}{{range .Versions}} {{.}}{{end}}`
}
} else {
*listFmt = "{{.ImportPath}}"
}
}
var do func(interface{})
if *listJson {
do = func(x interface{}) {
b, err := json.MarshalIndent(x, "", "\t")
if err != nil {
out.Flush()
base.Fatalf("%s", err)
}
out.Write(b)
out.Write(nl)
}
} else {
var cachedCtxt *Context
context := func() *Context {
if cachedCtxt == nil {
cachedCtxt = newContext(&cfg.BuildContext)
}
return cachedCtxt
}
fm := template.FuncMap{
"join": strings.Join,
"context": context,
"module": modload.ModuleInfo,
}
tmpl, err := template.New("main").Funcs(fm).Parse(*listFmt)
if err != nil {
base.Fatalf("%s", err)
}
do = func(x interface{}) {
if err := tmpl.Execute(out, x); err != nil {
out.Flush()
base.Fatalf("%s", err)
}
if out.NeedNL() {
out.Write(nl)
}
}
}
if *listM {
// Module mode.
if *listCompiled {
base.Fatalf("go list -compiled cannot be used with -m")
}
if *listDeps {
// TODO(rsc): Could make this mean something with -m.
base.Fatalf("go list -deps cannot be used with -m")
}
if *listExport {
base.Fatalf("go list -export cannot be used with -m")
}
if *listFind {
base.Fatalf("go list -find cannot be used with -m")
}
if *listTest {
base.Fatalf("go list -test cannot be used with -m")
}
if modload.Init(); !modload.Enabled() {
base.Fatalf("go list -m: not using modules")
}
modload.LoadBuildList()
mods := modload.ListModules(args, *listU, *listVersions)
if !*listE {
for _, m := range mods {
if m.Error != nil {
base.Errorf("go list -m %s: %v", m.Path, m.Error.Err)
}
}
base.ExitIfErrors()
}
for _, m := range mods {
do(m)
}
return
}
// Package mode (not -m).
if *listU {
base.Fatalf("go list -u can only be used with -m")
}
if *listVersions {
base.Fatalf("go list -versions can only be used with -m")
}
// These pairings make no sense.
if *listFind && *listDeps {
base.Fatalf("go list -deps cannot be used with -find")
}
if *listFind && *listTest {
base.Fatalf("go list -test cannot be used with -find")
}
load.IgnoreImports = *listFind
var pkgs []*load.Package
if *listE {
pkgs = load.PackagesAndErrors(args)
} else {
pkgs = load.Packages(args)
}
if cache.Default() == nil {
// These flags return file names pointing into the build cache,
// so the build cache must exist.
if *listCompiled {
base.Fatalf("go list -compiled requires build cache")
}
if *listExport {
base.Fatalf("go list -export requires build cache")
}
if *listTest {
base.Fatalf("go list -test requires build cache")
}
}
if *listTest {
c := cache.Default()
// Add test binaries to packages to be listed.
for _, p := range pkgs {
if p.Error != nil {
continue
}
if len(p.TestGoFiles)+len(p.XTestGoFiles) > 0 {
pmain, ptest, pxtest, err := load.TestPackagesFor(p, nil)
if err != nil {
if *listE {
pkgs = append(pkgs, &load.Package{
PackagePublic: load.PackagePublic{
ImportPath: p.ImportPath + ".test",
Error: &load.PackageError{Err: err.Error()},
},
})
continue
}
base.Errorf("can't load test package: %s", err)
continue
}
pkgs = append(pkgs, pmain)
if ptest != nil {
pkgs = append(pkgs, ptest)
}
if pxtest != nil {
pkgs = append(pkgs, pxtest)
}
data := *pmain.Internal.TestmainGo
h := cache.NewHash("testmain")
h.Write([]byte("testmain\n"))
h.Write(data)
out, _, err := c.Put(h.Sum(), bytes.NewReader(data))
if err != nil {
base.Fatalf("%s", err)
}
pmain.GoFiles[0] = c.OutputFile(out)
}
}
}
// Remember which packages are named on the command line.
cmdline := make(map[*load.Package]bool)
for _, p := range pkgs {
cmdline[p] = true
}
if *listDeps {
// Note: This changes the order of the listed packages
// from "as written on the command line" to
// "a depth-first post-order traversal".
// (The dependency exploration order for a given node
// is alphabetical, same as listed in .Deps.)
// Note that -deps is applied after -test,
// so that you only get descriptions of tests for the things named
// explicitly on the command line, not for all dependencies.
pkgs = load.PackageList(pkgs)
}
// Do we need to run a build to gather information?
needStale := *listJson || strings.Contains(*listFmt, ".Stale")
if needStale || *listExport || *listCompiled {
var b work.Builder
b.Init()
b.IsCmdList = true
b.NeedExport = *listExport
b.NeedCompiledGoFiles = *listCompiled
a := &work.Action{}
// TODO: Use pkgsFilter?
for _, p := range pkgs {
if len(p.GoFiles)+len(p.CgoFiles) > 0 {
a.Deps = append(a.Deps, b.AutoAction(work.ModeInstall, work.ModeInstall, p))
}
}
b.Do(a)
}
for _, p := range pkgs {
// Show vendor-expanded paths in listing
p.TestImports = p.Resolve(p.TestImports)
p.XTestImports = p.Resolve(p.XTestImports)
p.DepOnly = !cmdline[p]
if *listCompiled {
p.Imports = str.StringList(p.Imports, p.Internal.CompiledImports)
}
}
if *listTest {
all := pkgs
if !*listDeps {
all = load.PackageList(pkgs)
}
// Update import paths to distinguish the real package p
// from p recompiled for q.test.
// This must happen only once the build code is done
// looking at import paths, because it will get very confused
// if it sees these.
old := make(map[string]string)
for _, p := range all {
if p.ForTest != "" {
new := p.ImportPath + " [" + p.ForTest + ".test]"
old[new] = p.ImportPath
p.ImportPath = new
}
p.DepOnly = !cmdline[p]
}
// Update import path lists to use new strings.
m := make(map[string]string)
for _, p := range all {
for _, p1 := range p.Internal.Imports {
if p1.ForTest != "" {
m[old[p1.ImportPath]] = p1.ImportPath
}
}
for i, old := range p.Imports {
if new := m[old]; new != "" {
p.Imports[i] = new
}
}
for old := range m {
delete(m, old)
}
}
// Recompute deps lists using new strings, from the leaves up.
for _, p := range all {
deps := make(map[string]bool)
for _, p1 := range p.Internal.Imports {
deps[p1.ImportPath] = true
for _, d := range p1.Deps {
deps[d] = true
}
}
p.Deps = make([]string, 0, len(deps))
for d := range deps {
p.Deps = append(p.Deps, d)
}
sort.Strings(p.Deps)
}
}
// Record non-identity import mappings in p.ImportMap.
for _, p := range pkgs {
for i, srcPath := range p.Internal.RawImports {
path := p.Imports[i]
if path != srcPath {
if p.ImportMap == nil {
p.ImportMap = make(map[string]string)
}
p.ImportMap[srcPath] = path
}
}
}
for _, p := range pkgs {
do(&p.PackagePublic)
}
}
// TrackingWriter tracks the last byte written on every write so
// we can avoid printing a newline if one was already written or
// if there is no output at all.
type TrackingWriter struct {
w *bufio.Writer
last byte
}
func newTrackingWriter(w io.Writer) *TrackingWriter {
return &TrackingWriter{
w: bufio.NewWriter(w),
last: '\n',
}
}
func (t *TrackingWriter) Write(p []byte) (n int, err error) {
n, err = t.w.Write(p)
if n > 0 {
t.last = p[n-1]
}
return
}
func (t *TrackingWriter) Flush() {
t.w.Flush()
}
func (t *TrackingWriter) NeedNL() bool {
return t.last != '\n'
}
|
bug
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/bug/bug.go
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package bug implements the ``go bug'' command.
package bug
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"cmd/go/internal/envcmd"
"cmd/go/internal/web"
)
var CmdBug = &base.Command{
Run: runBug,
UsageLine: "go bug",
Short: "start a bug report",
Long: `
Bug opens the default browser and starts a new bug report.
The report includes useful system information.
`,
}
func init() {
CmdBug.Flag.BoolVar(&cfg.BuildV, "v", false, "")
}
func runBug(cmd *base.Command, args []string) {
if len(args) > 0 {
base.Fatalf("go bug: bug takes no arguments")
}
var buf bytes.Buffer
buf.WriteString(bugHeader)
inspectGoVersion(&buf)
fmt.Fprint(&buf, "#### System details\n\n")
fmt.Fprintln(&buf, "```")
fmt.Fprintf(&buf, "go version %s %s/%s\n", runtime.Version(), runtime.GOOS, runtime.GOARCH)
env := cfg.CmdEnv
env = append(env, envcmd.ExtraEnvVars()...)
for _, e := range env {
// Hide the TERM environment variable from "go bug".
// See issue #18128
if e.Name != "TERM" {
fmt.Fprintf(&buf, "%s=\"%s\"\n", e.Name, e.Value)
}
}
printGoDetails(&buf)
printOSDetails(&buf)
printCDetails(&buf)
fmt.Fprintln(&buf, "```")
body := buf.String()
url := "https://github.com/golang/go/issues/new?body=" + web.QueryEscape(body)
if !web.OpenBrowser(url) {
fmt.Print("Please file a new issue at golang.org/issue/new using this template:\n\n")
fmt.Print(body)
}
}
const bugHeader = `Please answer these questions before submitting your issue. Thanks!
#### What did you do?
If possible, provide a recipe for reproducing the error.
A complete runnable program is good.
A link on play.golang.org is best.
#### What did you expect to see?
#### What did you see instead?
`
func printGoDetails(w io.Writer) {
printCmdOut(w, "GOROOT/bin/go version: ", filepath.Join(runtime.GOROOT(), "bin/go"), "version")
printCmdOut(w, "GOROOT/bin/go tool compile -V: ", filepath.Join(runtime.GOROOT(), "bin/go"), "tool", "compile", "-V")
}
func printOSDetails(w io.Writer) {
switch runtime.GOOS {
case "darwin":
printCmdOut(w, "uname -v: ", "uname", "-v")
printCmdOut(w, "", "sw_vers")
case "linux":
printCmdOut(w, "uname -sr: ", "uname", "-sr")
printCmdOut(w, "", "lsb_release", "-a")
printGlibcVersion(w)
case "openbsd", "netbsd", "freebsd", "dragonfly":
printCmdOut(w, "uname -v: ", "uname", "-v")
case "solaris":
out, err := ioutil.ReadFile("/etc/release")
if err == nil {
fmt.Fprintf(w, "/etc/release: %s\n", out)
} else {
if cfg.BuildV {
fmt.Printf("failed to read /etc/release: %v\n", err)
}
}
}
}
func printCDetails(w io.Writer) {
printCmdOut(w, "lldb --version: ", "lldb", "--version")
cmd := exec.Command("gdb", "--version")
out, err := cmd.Output()
if err == nil {
// There's apparently no combination of command line flags
// to get gdb to spit out its version without the license and warranty.
// Print up to the first newline.
fmt.Fprintf(w, "gdb --version: %s\n", firstLine(out))
} else {
if cfg.BuildV {
fmt.Printf("failed to run gdb --version: %v\n", err)
}
}
}
func inspectGoVersion(w io.Writer) {
data, err := web.Get("https://golang.org/VERSION?m=text")
if err != nil {
if cfg.BuildV {
fmt.Printf("failed to read from golang.org/VERSION: %v\n", err)
}
return
}
// golang.org/VERSION currently returns a whitespace-free string,
// but just in case, protect against that changing.
// Similarly so for runtime.Version.
release := string(bytes.TrimSpace(data))
vers := strings.TrimSpace(runtime.Version())
if vers == release {
// Up to date
return
}
// Devel version or outdated release. Either way, this request is apropos.
fmt.Fprintf(w, "#### Does this issue reproduce with the latest release (%s)?\n\n\n", release)
}
// printCmdOut prints the output of running the given command.
// It ignores failures; 'go bug' is best effort.
func printCmdOut(w io.Writer, prefix, path string, args ...string) {
cmd := exec.Command(path, args...)
out, err := cmd.Output()
if err != nil {
if cfg.BuildV {
fmt.Printf("%s %s: %v\n", path, strings.Join(args, " "), err)
}
return
}
fmt.Fprintf(w, "%s%s\n", prefix, bytes.TrimSpace(out))
}
// firstLine returns the first line of a given byte slice.
func firstLine(buf []byte) []byte {
idx := bytes.IndexByte(buf, '\n')
if idx > 0 {
buf = buf[:idx]
}
return bytes.TrimSpace(buf)
}
// printGlibcVersion prints information about the glibc version.
// It ignores failures.
func printGlibcVersion(w io.Writer) {
tempdir := os.TempDir()
if tempdir == "" {
return
}
src := []byte(`int main() {}`)
srcfile := filepath.Join(tempdir, "go-bug.c")
outfile := filepath.Join(tempdir, "go-bug")
err := ioutil.WriteFile(srcfile, src, 0644)
if err != nil {
return
}
defer os.Remove(srcfile)
cmd := exec.Command("gcc", "-o", outfile, srcfile)
if _, err = cmd.CombinedOutput(); err != nil {
return
}
defer os.Remove(outfile)
cmd = exec.Command("ldd", outfile)
out, err := cmd.CombinedOutput()
if err != nil {
return
}
re := regexp.MustCompile(`libc\.so[^ ]* => ([^ ]+)`)
m := re.FindStringSubmatch(string(out))
if m == nil {
return
}
cmd = exec.Command(m[1])
out, err = cmd.Output()
if err != nil {
return
}
fmt.Fprintf(w, "%s: %s\n", m[1], firstLine(out))
// print another line (the one containing version string) in case of musl libc
if idx := bytes.IndexByte(out, '\n'); bytes.Index(out, []byte("musl")) != -1 && idx > -1 {
fmt.Fprintf(w, "%s\n", firstLine(out[idx+1:]))
}
}
|
help
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/help/helpdoc.go
|
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package help
import "cmd/go/internal/base"
var HelpC = &base.Command{
UsageLine: "c",
Short: "calling between Go and C",
Long: `
There are two different ways to call between Go and C/C++ code.
The first is the cgo tool, which is part of the Go distribution. For
information on how to use it see the cgo documentation (go doc cmd/cgo).
The second is the SWIG program, which is a general tool for
interfacing between languages. For information on SWIG see
http://swig.org/. When running go build, any file with a .swig
extension will be passed to SWIG. Any file with a .swigcxx extension
will be passed to SWIG with the -c++ option.
When either cgo or SWIG is used, go build will pass any .c, .m, .s,
or .S files to the C compiler, and any .cc, .cpp, .cxx files to the C++
compiler. The CC or CXX environment variables may be set to determine
the C or C++ compiler, respectively, to use.
`,
}
var HelpPackages = &base.Command{
UsageLine: "packages",
Short: "package lists and patterns",
Long: `
Many commands apply to a set of packages:
go action [packages]
Usually, [packages] is a list of import paths.
An import path that is a rooted path or that begins with
a . or .. element is interpreted as a file system path and
denotes the package in that directory.
Otherwise, the import path P denotes the package found in
the directory DIR/src/P for some DIR listed in the GOPATH
environment variable (For more details see: 'go help gopath').
If no import paths are given, the action applies to the
package in the current directory.
There are four reserved names for paths that should not be used
for packages to be built with the go tool:
- "main" denotes the top-level package in a stand-alone executable.
- "all" expands to all packages found in all the GOPATH
trees. For example, 'go list all' lists all the packages on the local
system. When using modules, "all" expands to all packages in
the main module and their dependencies, including dependencies
needed by tests of any of those.
- "std" is like all but expands to just the packages in the standard
Go library.
- "cmd" expands to the Go repository's commands and their
internal libraries.
Import paths beginning with "cmd/" only match source code in
the Go repository.
An import path is a pattern if it includes one or more "..." wildcards,
each of which can match any string, including the empty string and
strings containing slashes. Such a pattern expands to all package
directories found in the GOPATH trees with names matching the
patterns.
To make common patterns more convenient, there are two special cases.
First, /... at the end of the pattern can match an empty string,
so that net/... matches both net and packages in its subdirectories, like net/http.
Second, any slash-separated pattern element containing a wildcard never
participates in a match of the "vendor" element in the path of a vendored
package, so that ./... does not match packages in subdirectories of
./vendor or ./mycode/vendor, but ./vendor/... and ./mycode/vendor/... do.
Note, however, that a directory named vendor that itself contains code
is not a vendored package: cmd/vendor would be a command named vendor,
and the pattern cmd/... matches it.
See golang.org/s/go15vendor for more about vendoring.
An import path can also name a package to be downloaded from
a remote repository. Run 'go help importpath' for details.
Every package in a program must have a unique import path.
By convention, this is arranged by starting each path with a
unique prefix that belongs to you. For example, paths used
internally at Google all begin with 'google', and paths
denoting remote repositories begin with the path to the code,
such as 'github.com/user/repo'.
Packages in a program need not have unique package names,
but there are two reserved package names with special meaning.
The name main indicates a command, not a library.
Commands are built into binaries and cannot be imported.
The name documentation indicates documentation for
a non-Go program in the directory. Files in package documentation
are ignored by the go command.
As a special case, if the package list is a list of .go files from a
single directory, the command is applied to a single synthesized
package made up of exactly those files, ignoring any build constraints
in those files and ignoring any other files in the directory.
Directory and file names that begin with "." or "_" are ignored
by the go tool, as are directories named "testdata".
`,
}
var HelpImportPath = &base.Command{
UsageLine: "importpath",
Short: "import path syntax",
Long: `
An import path (see 'go help packages') denotes a package stored in the local
file system. In general, an import path denotes either a standard package (such
as "unicode/utf8") or a package found in one of the work spaces (For more
details see: 'go help gopath').
Relative import paths
An import path beginning with ./ or ../ is called a relative path.
The toolchain supports relative import paths as a shortcut in two ways.
First, a relative path can be used as a shorthand on the command line.
If you are working in the directory containing the code imported as
"unicode" and want to run the tests for "unicode/utf8", you can type
"go test ./utf8" instead of needing to specify the full path.
Similarly, in the reverse situation, "go test .." will test "unicode" from
the "unicode/utf8" directory. Relative patterns are also allowed, like
"go test ./..." to test all subdirectories. See 'go help packages' for details
on the pattern syntax.
Second, if you are compiling a Go program not in a work space,
you can use a relative path in an import statement in that program
to refer to nearby code also not in a work space.
This makes it easy to experiment with small multipackage programs
outside of the usual work spaces, but such programs cannot be
installed with "go install" (there is no work space in which to install them),
so they are rebuilt from scratch each time they are built.
To avoid ambiguity, Go programs cannot use relative import paths
within a work space.
Remote import paths
Certain import paths also
describe how to obtain the source code for the package using
a revision control system.
A few common code hosting sites have special syntax:
Bitbucket (Git, Mercurial)
import "bitbucket.org/user/project"
import "bitbucket.org/user/project/sub/directory"
GitHub (Git)
import "github.com/user/project"
import "github.com/user/project/sub/directory"
Launchpad (Bazaar)
import "launchpad.net/project"
import "launchpad.net/project/series"
import "launchpad.net/project/series/sub/directory"
import "launchpad.net/~user/project/branch"
import "launchpad.net/~user/project/branch/sub/directory"
IBM DevOps Services (Git)
import "hub.jazz.net/git/user/project"
import "hub.jazz.net/git/user/project/sub/directory"
For code hosted on other servers, import paths may either be qualified
with the version control type, or the go tool can dynamically fetch
the import path over https/http and discover where the code resides
from a <meta> tag in the HTML.
To declare the code location, an import path of the form
repository.vcs/path
specifies the given repository, with or without the .vcs suffix,
using the named version control system, and then the path inside
that repository. The supported version control systems are:
Bazaar .bzr
Fossil .fossil
Git .git
Mercurial .hg
Subversion .svn
For example,
import "example.org/user/foo.hg"
denotes the root directory of the Mercurial repository at
example.org/user/foo or foo.hg, and
import "example.org/repo.git/foo/bar"
denotes the foo/bar directory of the Git repository at
example.org/repo or repo.git.
When a version control system supports multiple protocols,
each is tried in turn when downloading. For example, a Git
download tries https://, then git+ssh://.
By default, downloads are restricted to known secure protocols
(e.g. https, ssh). To override this setting for Git downloads, the
GIT_ALLOW_PROTOCOL environment variable can be set (For more details see:
'go help environment').
If the import path is not a known code hosting site and also lacks a
version control qualifier, the go tool attempts to fetch the import
over https/http and looks for a <meta> tag in the document's HTML
<head>.
The meta tag has the form:
<meta name="go-import" content="import-prefix vcs repo-root">
The import-prefix is the import path corresponding to the repository
root. It must be a prefix or an exact match of the package being
fetched with "go get". If it's not an exact match, another http
request is made at the prefix to verify the <meta> tags match.
The meta tag should appear as early in the file as possible.
In particular, it should appear before any raw JavaScript or CSS,
to avoid confusing the go command's restricted parser.
The vcs is one of "bzr", "fossil", "git", "hg", "svn".
The repo-root is the root of the version control system
containing a scheme and not containing a .vcs qualifier.
For example,
import "example.org/pkg/foo"
will result in the following requests:
https://example.org/pkg/foo?go-get=1 (preferred)
http://example.org/pkg/foo?go-get=1 (fallback, only with -insecure)
If that page contains the meta tag
<meta name="go-import" content="example.org git https://code.org/r/p/exproj">
the go tool will verify that https://example.org/?go-get=1 contains the
same meta tag and then git clone https://code.org/r/p/exproj into
GOPATH/src/example.org.
When using GOPATH, downloaded packages are written to the first directory
listed in the GOPATH environment variable.
(See 'go help gopath-get' and 'go help gopath'.)
When using modules, downloaded packages are stored in the module cache.
(See 'go help modules-get' and 'go help goproxy'.)
When using modules, an additional variant of the go-import meta tag is
recognized and is preferred over those listing version control systems.
That variant uses "mod" as the vcs in the content value, as in:
<meta name="go-import" content="example.org mod https://code.org/moduleproxy">
This tag means to fetch modules with paths beginning with example.org
from the module proxy available at the URL https://code.org/moduleproxy.
See 'go help goproxy' for details about the proxy protocol.
Import path checking
When the custom import path feature described above redirects to a
known code hosting site, each of the resulting packages has two possible
import paths, using the custom domain or the known hosting site.
A package statement is said to have an "import comment" if it is immediately
followed (before the next newline) by a comment of one of these two forms:
package math // import "path"
package math /* import "path" */
The go command will refuse to install a package with an import comment
unless it is being referred to by that import path. In this way, import comments
let package authors make sure the custom import path is used and not a
direct path to the underlying code hosting site.
Import path checking is disabled for code found within vendor trees.
This makes it possible to copy code into alternate locations in vendor trees
without needing to update import comments.
Import path checking is also disabled when using modules.
Import path comments are obsoleted by the go.mod file's module statement.
See https://golang.org/s/go14customimport for details.
`,
}
var HelpGopath = &base.Command{
UsageLine: "gopath",
Short: "GOPATH environment variable",
Long: `
The Go path is used to resolve import statements.
It is implemented by and documented in the go/build package.
The GOPATH environment variable lists places to look for Go code.
On Unix, the value is a colon-separated string.
On Windows, the value is a semicolon-separated string.
On Plan 9, the value is a list.
If the environment variable is unset, GOPATH defaults
to a subdirectory named "go" in the user's home directory
($HOME/go on Unix, %USERPROFILE%\go on Windows),
unless that directory holds a Go distribution.
Run "go env GOPATH" to see the current GOPATH.
See https://golang.org/wiki/SettingGOPATH to set a custom GOPATH.
Each directory listed in GOPATH must have a prescribed structure:
The src directory holds source code. The path below src
determines the import path or executable name.
The pkg directory holds installed package objects.
As in the Go tree, each target operating system and
architecture pair has its own subdirectory of pkg
(pkg/GOOS_GOARCH).
If DIR is a directory listed in the GOPATH, a package with
source in DIR/src/foo/bar can be imported as "foo/bar" and
has its compiled form installed to "DIR/pkg/GOOS_GOARCH/foo/bar.a".
The bin directory holds compiled commands.
Each command is named for its source directory, but only
the final element, not the entire path. That is, the
command with source in DIR/src/foo/quux is installed into
DIR/bin/quux, not DIR/bin/foo/quux. The "foo/" prefix is stripped
so that you can add DIR/bin to your PATH to get at the
installed commands. If the GOBIN environment variable is
set, commands are installed to the directory it names instead
of DIR/bin. GOBIN must be an absolute path.
Here's an example directory layout:
GOPATH=/home/user/go
/home/user/go/
src/
foo/
bar/ (go code in package bar)
x.go
quux/ (go code in package main)
y.go
bin/
quux (installed command)
pkg/
linux_amd64/
foo/
bar.a (installed package object)
Go searches each directory listed in GOPATH to find source code,
but new packages are always downloaded into the first directory
in the list.
See https://golang.org/doc/code.html for an example.
GOPATH and Modules
When using modules, GOPATH is no longer used for resolving imports.
However, it is still used to store downloaded source code (in GOPATH/pkg/mod)
and compiled commands (in GOPATH/bin).
Internal Directories
Code in or below a directory named "internal" is importable only
by code in the directory tree rooted at the parent of "internal".
Here's an extended version of the directory layout above:
/home/user/go/
src/
crash/
bang/ (go code in package bang)
b.go
foo/ (go code in package foo)
f.go
bar/ (go code in package bar)
x.go
internal/
baz/ (go code in package baz)
z.go
quux/ (go code in package main)
y.go
The code in z.go is imported as "foo/internal/baz", but that
import statement can only appear in source files in the subtree
rooted at foo. The source files foo/f.go, foo/bar/x.go, and
foo/quux/y.go can all import "foo/internal/baz", but the source file
crash/bang/b.go cannot.
See https://golang.org/s/go14internal for details.
Vendor Directories
Go 1.6 includes support for using local copies of external dependencies
to satisfy imports of those dependencies, often referred to as vendoring.
Code below a directory named "vendor" is importable only
by code in the directory tree rooted at the parent of "vendor",
and only using an import path that omits the prefix up to and
including the vendor element.
Here's the example from the previous section,
but with the "internal" directory renamed to "vendor"
and a new foo/vendor/crash/bang directory added:
/home/user/go/
src/
crash/
bang/ (go code in package bang)
b.go
foo/ (go code in package foo)
f.go
bar/ (go code in package bar)
x.go
vendor/
crash/
bang/ (go code in package bang)
b.go
baz/ (go code in package baz)
z.go
quux/ (go code in package main)
y.go
The same visibility rules apply as for internal, but the code
in z.go is imported as "baz", not as "foo/vendor/baz".
Code in vendor directories deeper in the source tree shadows
code in higher directories. Within the subtree rooted at foo, an import
of "crash/bang" resolves to "foo/vendor/crash/bang", not the
top-level "crash/bang".
Code in vendor directories is not subject to import path
checking (see 'go help importpath').
When 'go get' checks out or updates a git repository, it now also
updates submodules.
Vendor directories do not affect the placement of new repositories
being checked out for the first time by 'go get': those are always
placed in the main GOPATH, never in a vendor subtree.
See https://golang.org/s/go15vendor for details.
`,
}
var HelpEnvironment = &base.Command{
UsageLine: "environment",
Short: "environment variables",
Long: `
The go command, and the tools it invokes, examine a few different
environment variables. For many of these, you can see the default
value of on your system by running 'go env NAME', where NAME is the
name of the variable.
General-purpose environment variables:
GCCGO
The gccgo command to run for 'go build -compiler=gccgo'.
GOARCH
The architecture, or processor, for which to compile code.
Examples are amd64, 386, arm, ppc64.
GOBIN
The directory where 'go install' will install a command.
GOCACHE
The directory where the go command will store cached
information for reuse in future builds.
GOFLAGS
A space-separated list of -flag=value settings to apply
to go commands by default, when the given flag is known by
the current command. Flags listed on the command-line
are applied after this list and therefore override it.
GOOS
The operating system for which to compile code.
Examples are linux, darwin, windows, netbsd.
GOPATH
For more details see: 'go help gopath'.
GOPROXY
URL of Go module proxy. See 'go help goproxy'.
GORACE
Options for the race detector.
See https://golang.org/doc/articles/race_detector.html.
GOROOT
The root of the go tree.
GOTMPDIR
The directory where the go command will write
temporary source files, packages, and binaries.
Environment variables for use with cgo:
CC
The command to use to compile C code.
CGO_ENABLED
Whether the cgo command is supported. Either 0 or 1.
CGO_CFLAGS
Flags that cgo will pass to the compiler when compiling
C code.
CGO_CFLAGS_ALLOW
A regular expression specifying additional flags to allow
to appear in #cgo CFLAGS source code directives.
Does not apply to the CGO_CFLAGS environment variable.
CGO_CFLAGS_DISALLOW
A regular expression specifying flags that must be disallowed
from appearing in #cgo CFLAGS source code directives.
Does not apply to the CGO_CFLAGS environment variable.
CGO_CPPFLAGS, CGO_CPPFLAGS_ALLOW, CGO_CPPFLAGS_DISALLOW
Like CGO_CFLAGS, CGO_CFLAGS_ALLOW, and CGO_CFLAGS_DISALLOW,
but for the C preprocessor.
CGO_CXXFLAGS, CGO_CXXFLAGS_ALLOW, CGO_CXXFLAGS_DISALLOW
Like CGO_CFLAGS, CGO_CFLAGS_ALLOW, and CGO_CFLAGS_DISALLOW,
but for the C++ compiler.
CGO_FFLAGS, CGO_FFLAGS_ALLOW, CGO_FFLAGS_DISALLOW
Like CGO_CFLAGS, CGO_CFLAGS_ALLOW, and CGO_CFLAGS_DISALLOW,
but for the Fortran compiler.
CGO_LDFLAGS, CGO_LDFLAGS_ALLOW, CGO_LDFLAGS_DISALLOW
Like CGO_CFLAGS, CGO_CFLAGS_ALLOW, and CGO_CFLAGS_DISALLOW,
but for the linker.
CXX
The command to use to compile C++ code.
PKG_CONFIG
Path to pkg-config tool.
Architecture-specific environment variables:
GOARM
For GOARCH=arm, the ARM architecture for which to compile.
Valid values are 5, 6, 7.
GO386
For GOARCH=386, the floating point instruction set.
Valid values are 387, sse2.
GOMIPS
For GOARCH=mips{,le}, whether to use floating point instructions.
Valid values are hardfloat (default), softfloat.
GOMIPS64
For GOARCH=mips64{,le}, whether to use floating point instructions.
Valid values are hardfloat (default), softfloat.
Special-purpose environment variables:
GCCGOTOOLDIR
If set, where to find gccgo tools, such as cgo.
The default is based on how gccgo was configured.
GOROOT_FINAL
The root of the installed Go tree, when it is
installed in a location other than where it is built.
File names in stack traces are rewritten from GOROOT to
GOROOT_FINAL.
GO_EXTLINK_ENABLED
Whether the linker should use external linking mode
when using -linkmode=auto with code that uses cgo.
Set to 0 to disable external linking mode, 1 to enable it.
GIT_ALLOW_PROTOCOL
Defined by Git. A colon-separated list of schemes that are allowed to be used
with git fetch/clone. If set, any scheme not explicitly mentioned will be
considered insecure by 'go get'.
Additional information available from 'go env' but not read from the environment:
GOEXE
The executable file name suffix (".exe" on Windows, "" on other systems).
GOHOSTARCH
The architecture (GOARCH) of the Go toolchain binaries.
GOHOSTOS
The operating system (GOOS) of the Go toolchain binaries.
GOMOD
The absolute path to the go.mod of the main module,
or the empty string if not using modules.
GOTOOLDIR
The directory where the go tools (compile, cover, doc, etc...) are installed.
`,
}
var HelpFileType = &base.Command{
UsageLine: "filetype",
Short: "file types",
Long: `
The go command examines the contents of a restricted set of files
in each directory. It identifies which files to examine based on
the extension of the file name. These extensions are:
.go
Go source files.
.c, .h
C source files.
If the package uses cgo or SWIG, these will be compiled with the
OS-native compiler (typically gcc); otherwise they will
trigger an error.
.cc, .cpp, .cxx, .hh, .hpp, .hxx
C++ source files. Only useful with cgo or SWIG, and always
compiled with the OS-native compiler.
.m
Objective-C source files. Only useful with cgo, and always
compiled with the OS-native compiler.
.s, .S
Assembler source files.
If the package uses cgo or SWIG, these will be assembled with the
OS-native assembler (typically gcc (sic)); otherwise they
will be assembled with the Go assembler.
.swig, .swigcxx
SWIG definition files.
.syso
System object files.
Files of each of these types except .syso may contain build
constraints, but the go command stops scanning for build constraints
at the first item in the file that is not a blank line or //-style
line comment. See the go/build package documentation for
more details.
Non-test Go source files can also include a //go:binary-only-package
comment, indicating that the package sources are included
for documentation only and must not be used to build the
package binary. This enables distribution of Go packages in
their compiled form alone. Even binary-only packages require
accurate import blocks listing required dependencies, so that
those dependencies can be supplied when linking the resulting
command.
`,
}
var HelpBuildmode = &base.Command{
UsageLine: "buildmode",
Short: "build modes",
Long: `
The 'go build' and 'go install' commands take a -buildmode argument which
indicates which kind of object file is to be built. Currently supported values
are:
-buildmode=archive
Build the listed non-main packages into .a files. Packages named
main are ignored.
-buildmode=c-archive
Build the listed main package, plus all packages it imports,
into a C archive file. The only callable symbols will be those
functions exported using a cgo //export comment. Requires
exactly one main package to be listed.
-buildmode=c-shared
Build the listed main package, plus all packages it imports,
into a C shared library. The only callable symbols will
be those functions exported using a cgo //export comment.
Requires exactly one main package to be listed.
-buildmode=default
Listed main packages are built into executables and listed
non-main packages are built into .a files (the default
behavior).
-buildmode=shared
Combine all the listed non-main packages into a single shared
library that will be used when building with the -linkshared
option. Packages named main are ignored.
-buildmode=exe
Build the listed main packages and everything they import into
executables. Packages not named main are ignored.
-buildmode=pie
Build the listed main packages and everything they import into
position independent executables (PIE). Packages not named
main are ignored.
-buildmode=plugin
Build the listed main packages, plus all packages that they
import, into a Go plugin. Packages not named main are ignored.
`,
}
var HelpCache = &base.Command{
UsageLine: "cache",
Short: "build and test caching",
Long: `
The go command caches build outputs for reuse in future builds.
The default location for cache data is a subdirectory named go-build
in the standard user cache directory for the current operating system.
Setting the GOCACHE environment variable overrides this default,
and running 'go env GOCACHE' prints the current cache directory.
You can set the variable to 'off' to disable the cache.
The go command periodically deletes cached data that has not been
used recently. Running 'go clean -cache' deletes all cached data.
The build cache correctly accounts for changes to Go source files,
compilers, compiler options, and so on: cleaning the cache explicitly
should not be necessary in typical use. However, the build cache
does not detect changes to C libraries imported with cgo.
If you have made changes to the C libraries on your system, you
will need to clean the cache explicitly or else use the -a build flag
(see 'go help build') to force rebuilding of packages that
depend on the updated C libraries.
The go command also caches successful package test results.
See 'go help test' for details. Running 'go clean -testcache' removes
all cached test results (but not cached build results).
The GODEBUG environment variable can enable printing of debugging
information about the state of the cache:
GODEBUG=gocacheverify=1 causes the go command to bypass the
use of any cache entries and instead rebuild everything and check
that the results match existing cache entries.
GODEBUG=gocachehash=1 causes the go command to print the inputs
for all of the content hashes it uses to construct cache lookup keys.
The output is voluminous but can be useful for debugging the cache.
GODEBUG=gocachetest=1 causes the go command to print details of its
decisions about whether to reuse a cached test result.
`,
}
|
help
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/help/help.go
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package help implements the ``go help'' command.
package help
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"strings"
"text/template"
"unicode"
"unicode/utf8"
"cmd/go/internal/base"
)
// Help implements the 'help' command.
func Help(args []string) {
// 'go help documentation' generates doc.go.
if len(args) == 1 && args[0] == "documentation" {
fmt.Println("// Copyright 2011 The Go Authors. All rights reserved.")
fmt.Println("// Use of this source code is governed by a BSD-style")
fmt.Println("// license that can be found in the LICENSE file.")
fmt.Println()
fmt.Println("// Code generated by mkalldocs.sh; DO NOT EDIT.")
fmt.Println("// Edit the documentation in other files and rerun mkalldocs.sh to generate this one.")
fmt.Println()
buf := new(bytes.Buffer)
PrintUsage(buf, base.Go)
usage := &base.Command{Long: buf.String()}
cmds := []*base.Command{usage}
for _, cmd := range base.Go.Commands {
if cmd.UsageLine == "gopath-get" {
// Avoid duplication of the "get" documentation.
continue
}
cmds = append(cmds, cmd)
cmds = append(cmds, cmd.Commands...)
}
tmpl(&commentWriter{W: os.Stdout}, documentationTemplate, cmds)
fmt.Println("package main")
return
}
cmd := base.Go
Args:
for i, arg := range args {
for _, sub := range cmd.Commands {
if sub.Name() == arg {
cmd = sub
continue Args
}
}
// helpSuccess is the help command using as many args as possible that would succeed.
helpSuccess := "go help"
if i > 0 {
helpSuccess = " " + strings.Join(args[:i], " ")
}
fmt.Fprintf(os.Stderr, "go help %s: unknown help topic. Run '%s'.\n", strings.Join(args, " "), helpSuccess)
os.Exit(2) // failed at 'go help cmd'
}
if len(cmd.Commands) > 0 {
PrintUsage(os.Stdout, cmd)
} else {
tmpl(os.Stdout, helpTemplate, cmd)
}
// not exit 2: succeeded at 'go help cmd'.
return
}
var usageTemplate = `{{.Long | trim}}
This is vgo, an experimental go command with support for package versioning.
Even though you are invoking it as vgo, most of the messages printed will
still say "go", not "vgo". Sorry.
Usage:
{{.UsageLine}} <command> [arguments]
The commands are:
{{range .Commands}}{{if or (.Runnable) .Commands}}
{{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}}
Use "go help{{with .LongName}} {{.}}{{end}} <command>" for more information about a command.
{{if eq (.UsageLine) "go"}}
Additional help topics:
{{range .Commands}}{{if and (not .Runnable) (not .Commands)}}
{{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}}
Use "go help{{with .LongName}} {{.}}{{end}} <topic>" for more information about that topic.
{{end}}
`
var helpTemplate = `{{if .Runnable}}usage: {{.UsageLine}}
{{end}}{{.Long | trim}}
`
var documentationTemplate = `{{range .}}{{if .Short}}{{.Short | capitalize}}
{{end}}{{if .Commands}}` + usageTemplate + `{{else}}{{if .Runnable}}Usage:
{{.UsageLine}}
{{end}}{{.Long | trim}}
{{end}}{{end}}`
// commentWriter writes a Go comment to the underlying io.Writer,
// using line comment form (//).
type commentWriter struct {
W io.Writer
wroteSlashes bool // Wrote "//" at the beginning of the current line.
}
func (c *commentWriter) Write(p []byte) (int, error) {
var n int
for i, b := range p {
if !c.wroteSlashes {
s := "//"
if b != '\n' {
s = "// "
}
if _, err := io.WriteString(c.W, s); err != nil {
return n, err
}
c.wroteSlashes = true
}
n0, err := c.W.Write(p[i : i+1])
n += n0
if err != nil {
return n, err
}
if b == '\n' {
c.wroteSlashes = false
}
}
return len(p), nil
}
// An errWriter wraps a writer, recording whether a write error occurred.
type errWriter struct {
w io.Writer
err error
}
func (w *errWriter) Write(b []byte) (int, error) {
n, err := w.w.Write(b)
if err != nil {
w.err = err
}
return n, err
}
// tmpl executes the given template text on data, writing the result to w.
func tmpl(w io.Writer, text string, data interface{}) {
t := template.New("top")
t.Funcs(template.FuncMap{"trim": strings.TrimSpace, "capitalize": capitalize})
template.Must(t.Parse(text))
ew := &errWriter{w: w}
err := t.Execute(ew, data)
if ew.err != nil {
// I/O error writing. Ignore write on closed pipe.
if strings.Contains(ew.err.Error(), "pipe") {
os.Exit(1)
}
base.Fatalf("writing output: %v", ew.err)
}
if err != nil {
panic(err)
}
}
func capitalize(s string) string {
if s == "" {
return s
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToTitle(r)) + s[n:]
}
func PrintUsage(w io.Writer, cmd *base.Command) {
bw := bufio.NewWriter(w)
tmpl(bw, usageTemplate, cmd)
bw.Flush()
}
|
mvs
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/mvs/mvs_test.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mvs
import (
"reflect"
"strings"
"testing"
"cmd/go/internal/module"
)
var tests = `
# Scenario from blog.
name: blog
A: B1 C2
B1: D3
C1: D2
C2: D4
C3: D5
C4: G1
D2: E1
D3: E2
D4: E2 F1
D5: E2
G1: C4
A2: B1 C4 D4
build A: A B1 C2 D4 E2 F1
upgrade* A: A B1 C4 D5 E2 G1
upgrade A C4: A B1 C4 D4 E2 F1 G1
downgrade A2 D2: A2 C4 D2
name: trim
A: B1 C2
B1: D3
C2: B2
B2:
build A: A B2 C2
# Cross-dependency between D and E.
# No matter how it arises, should get result of merging all build lists via max,
# which leads to including both D2 and E2.
name: cross1
A: B C
B: D1
C: D2
D1: E2
D2: E1
build A: A B C D2 E2
name: cross1V
A: B2 C D2 E1
B1:
B2: D1
C: D2
D1: E2
D2: E1
build A: A B2 C D2 E2
name: cross1U
A: B1 C
B1:
B2: D1
C: D2
D1: E2
D2: E1
build A: A B1 C D2 E1
upgrade A B2: A B2 C D2 E2
name: cross1R
A: B C
B: D2
C: D1
D1: E2
D2: E1
build A: A B C D2 E2
name: cross1X
A: B C
B: D1 E2
C: D2
D1: E2
D2: E1
build A: A B C D2 E2
name: cross2
A: B D2
B: D1
D1: E2
D2: E1
build A: A B D2 E2
name: cross2X
A: B D2
B: D1 E2
C: D2
D1: E2
D2: E1
build A: A B D2 E2
name: cross3
A: B D2 E1
B: D1
D1: E2
D2: E1
build A: A B D2 E2
name: cross3X
A: B D2 E1
B: D1 E2
D1: E2
D2: E1
build A: A B D2 E2
# Should not get E2 here, because B has been updated
# not to depend on D1 anymore.
name: cross4
A1: B1 D2
A2: B2 D2
B1: D1
B2: D2
D1: E2
D2: E1
build A1: A1 B1 D2 E2
build A2: A2 B2 D2 E1
# But the upgrade from A1 preserves the E2 dep explicitly.
upgrade A1 B2: A1 B2 D2 E2
upgradereq A1 B2: B2 E2
name: cross5
A: D1
D1: E2
D2: E1
build A: A D1 E2
upgrade* A: A D2 E2
upgrade A D2: A D2 E2
upgradereq A D2: D2 E2
name: cross6
A: D2
D1: E2
D2: E1
build A: A D2 E1
upgrade* A: A D2 E2
upgrade A E2: A D2 E2
name: cross7
A: B C
B: D1
C: E1
D1: E2
E1: D2
build A: A B C D2 E2
# Upgrade from B1 to B2 should drop the transitive dep on D.
name: drop
A: B1 C1
B1: D1
B2:
C2:
D2:
build A: A B1 C1 D1
upgrade* A: A B2 C2
name: simplify
A: B1 C1
B1: C2
C1: D1
C2:
build A: A B1 C2
name: up1
A: B1 C1
B1:
B2:
B3:
B4:
B5.hidden:
C2:
C3:
build A: A B1 C1
upgrade* A: A B4 C3
name: up2
A: B5.hidden C1
B1:
B2:
B3:
B4:
B5.hidden:
C2:
C3:
build A: A B5.hidden C1
upgrade* A: A B5.hidden C3
name: down1
A: B2
B1: C1
B2: C2
build A: A B2 C2
downgrade A C1: A B1
name: down2
A: B2 E2
B1:
B2: C2 F2
C1:
D1:
C2: D2 E2
D2: B2
E2: D2
E1:
F1:
downgrade A F1: A B1 E1
name: down3
A:
# golang.org/issue/25542.
name: noprev1
A: B4 C2
B2.hidden:
C2:
downgrade A B2.hidden: A B2.hidden C2
name: noprev2
A: B4 C2
B2.hidden:
B1:
C2:
downgrade A B2.hidden: A B2.hidden C2
name: noprev3
A: B4 C2
B3:
B2.hidden:
C2:
downgrade A B2.hidden: A B2.hidden C2
# Cycles involving the target.
# The target must be the newest version of itself.
name: cycle1
A: B1
B1: A1
B2: A2
B3: A3
build A: A B1
upgrade A B2: A B2
upgrade* A: A B3
# Requirements of older versions of the target
# must not be carried over.
name: cycle2
A: B1
A1: C1
A2: D1
B1: A1
B2: A2
C1: A2
C2:
D2:
build A: A B1
upgrade* A: A B2
# Requirement minimization.
name: req1
A: B1 C1 D1 E1 F1
B1: C1 E1 F1
req A: B1 D1
req A C: B1 C1 D1
name: req2
A: G1 H1
G1: H1
H1: G1
req A: G1
req A G: G1
req A H: H1
`
func Test(t *testing.T) {
var (
name string
reqs reqsMap
fns []func(*testing.T)
)
flush := func() {
if name != "" {
t.Run(name, func(t *testing.T) {
for _, fn := range fns {
fn(t)
}
})
}
}
m := func(s string) module.Version {
return module.Version{Path: s[:1], Version: s[1:]}
}
ms := func(list []string) []module.Version {
var mlist []module.Version
for _, s := range list {
mlist = append(mlist, m(s))
}
return mlist
}
checkList := func(t *testing.T, desc string, list []module.Version, err error, val string) {
if err != nil {
t.Fatalf("%s: %v", desc, err)
}
vs := ms(strings.Fields(val))
if !reflect.DeepEqual(list, vs) {
t.Errorf("%s = %v, want %v", desc, list, vs)
}
}
for _, line := range strings.Split(tests, "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "#") || line == "" {
continue
}
i := strings.Index(line, ":")
if i < 0 {
t.Fatalf("missing colon: %q", line)
}
key := strings.TrimSpace(line[:i])
val := strings.TrimSpace(line[i+1:])
if key == "" {
t.Fatalf("missing key: %q", line)
}
kf := strings.Fields(key)
switch kf[0] {
case "name":
if len(kf) != 1 {
t.Fatalf("name takes no arguments: %q", line)
}
flush()
reqs = make(reqsMap)
fns = nil
name = val
continue
case "build":
if len(kf) != 2 {
t.Fatalf("build takes one argument: %q", line)
}
fns = append(fns, func(t *testing.T) {
list, err := BuildList(m(kf[1]), reqs)
checkList(t, key, list, err, val)
})
continue
case "upgrade*":
if len(kf) != 2 {
t.Fatalf("upgrade* takes one argument: %q", line)
}
fns = append(fns, func(t *testing.T) {
list, err := UpgradeAll(m(kf[1]), reqs)
checkList(t, key, list, err, val)
})
continue
case "upgradereq":
if len(kf) < 2 {
t.Fatalf("upgrade takes at least one argument: %q", line)
}
fns = append(fns, func(t *testing.T) {
list, err := Upgrade(m(kf[1]), reqs, ms(kf[2:])...)
if err == nil {
list, err = Req(m(kf[1]), list, nil, reqs)
}
checkList(t, key, list, err, val)
})
continue
case "upgrade":
if len(kf) < 2 {
t.Fatalf("upgrade takes at least one argument: %q", line)
}
fns = append(fns, func(t *testing.T) {
list, err := Upgrade(m(kf[1]), reqs, ms(kf[2:])...)
checkList(t, key, list, err, val)
})
continue
case "downgrade":
if len(kf) < 2 {
t.Fatalf("downgrade takes at least one argument: %q", line)
}
fns = append(fns, func(t *testing.T) {
list, err := Downgrade(m(kf[1]), reqs, ms(kf[1:])...)
checkList(t, key, list, err, val)
})
continue
case "req":
if len(kf) < 2 {
t.Fatalf("req takes at least one argument: %q", line)
}
fns = append(fns, func(t *testing.T) {
list, err := BuildList(m(kf[1]), reqs)
if err != nil {
t.Fatal(err)
}
list, err = Req(m(kf[1]), list, kf[2:], reqs)
checkList(t, key, list, err, val)
})
continue
}
if len(kf) == 1 && 'A' <= key[0] && key[0] <= 'Z' {
var rs []module.Version
for _, f := range strings.Fields(val) {
r := m(f)
if reqs[r] == nil {
reqs[r] = []module.Version{}
}
rs = append(rs, r)
}
reqs[m(key)] = rs
continue
}
t.Fatalf("bad line: %q", line)
}
flush()
}
type reqsMap map[module.Version][]module.Version
func (r reqsMap) Max(v1, v2 string) string {
if v1 == "none" || v2 == "" {
return v2
}
if v2 == "none" || v1 == "" {
return v1
}
if v1 < v2 {
return v2
}
return v1
}
func (r reqsMap) Upgrade(m module.Version) (module.Version, error) {
var u module.Version
for k := range r {
if k.Path == m.Path && u.Version < k.Version && !strings.HasSuffix(k.Version, ".hidden") {
u = k
}
}
if u.Path == "" {
return module.Version{}, &MissingModuleError{module.Version{Path: m.Path, Version: ""}}
}
return u, nil
}
func (r reqsMap) Previous(m module.Version) (module.Version, error) {
var p module.Version
for k := range r {
if k.Path == m.Path && p.Version < k.Version && k.Version < m.Version && !strings.HasSuffix(k.Version, ".hidden") {
p = k
}
}
if p.Path == "" {
return module.Version{Path: m.Path, Version: "none"}, nil
}
return p, nil
}
func (r reqsMap) Required(m module.Version) ([]module.Version, error) {
rr, ok := r[m]
if !ok {
return nil, &MissingModuleError{m}
}
return rr, nil
}
|
mvs
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/mvs/mvs.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package mvs implements Minimal Version Selection.
// See https://research.swtch.com/vgo-mvs.
package mvs
import (
"fmt"
"sort"
"sync"
"cmd/go/internal/base"
"cmd/go/internal/module"
"cmd/go/internal/par"
)
// A Reqs is the requirement graph on which Minimal Version Selection (MVS) operates.
//
// The version strings are opaque except for the special version "none"
// (see the documentation for module.Version). In particular, MVS does not
// assume that the version strings are semantic versions; instead, the Max method
// gives access to the comparison operation.
//
// It must be safe to call methods on a Reqs from multiple goroutines simultaneously.
// Because a Reqs may read the underlying graph from the network on demand,
// the MVS algorithms parallelize the traversal to overlap network delays.
type Reqs interface {
// Required returns the module versions explicitly required by m itself.
// The caller must not modify the returned list.
Required(m module.Version) ([]module.Version, error)
// Max returns the maximum of v1 and v2 (it returns either v1 or v2).
//
// For all versions v, Max(v, "none") must be v,
// and for the tanget passed as the first argument to MVS functions,
// Max(target, v) must be target.
//
// Note that v1 < v2 can be written Max(v1, v2) != v1
// and similarly v1 <= v2 can be written Max(v1, v2) == v2.
Max(v1, v2 string) string
// Upgrade returns the upgraded version of m,
// for use during an UpgradeAll operation.
// If m should be kept as is, Upgrade returns m.
// If m is not yet used in the build, then m.Version will be "none".
// More typically, m.Version will be the version required
// by some other module in the build.
//
// If no module version is available for the given path,
// Upgrade returns a non-nil error.
// TODO(rsc): Upgrade must be able to return errors,
// but should "no latest version" just return m instead?
Upgrade(m module.Version) (module.Version, error)
// Previous returns the version of m.Path immediately prior to m.Version,
// or "none" if no such version is known.
Previous(m module.Version) (module.Version, error)
}
type MissingModuleError struct {
Module module.Version
}
func (e *MissingModuleError) Error() string {
return fmt.Sprintf("missing module: %v", e.Module)
}
// BuildList returns the build list for the target module.
func BuildList(target module.Version, reqs Reqs) ([]module.Version, error) {
return buildList(target, reqs, nil)
}
func buildList(target module.Version, reqs Reqs, upgrade func(module.Version) module.Version) ([]module.Version, error) {
// Explore work graph in parallel in case reqs.Required
// does high-latency network operations.
var work par.Work
work.Add(target)
var (
mu sync.Mutex
min = map[string]string{target.Path: target.Version}
firstErr error
)
work.Do(10, func(item interface{}) {
m := item.(module.Version)
required, err := reqs.Required(m)
mu.Lock()
if err != nil && firstErr == nil {
firstErr = err
}
if firstErr != nil {
mu.Unlock()
return
}
if v, ok := min[m.Path]; !ok || reqs.Max(v, m.Version) != v {
min[m.Path] = m.Version
}
mu.Unlock()
for _, r := range required {
if r.Path == "" {
base.Errorf("Required(%v) returned zero module in list", m)
continue
}
work.Add(r)
}
if upgrade != nil {
u := upgrade(m)
if u.Path == "" {
base.Errorf("Upgrade(%v) returned zero module", m)
return
}
work.Add(u)
}
})
if firstErr != nil {
return nil, firstErr
}
if v := min[target.Path]; v != target.Version {
panic(fmt.Sprintf("mistake: chose version %q instead of target %+v", v, target)) // TODO: Don't panic.
}
list := []module.Version{target}
listed := map[string]bool{target.Path: true}
for i := 0; i < len(list); i++ {
m := list[i]
required, err := reqs.Required(m)
if err != nil {
return nil, err
}
for _, r := range required {
v := min[r.Path]
if r.Path != target.Path && reqs.Max(v, r.Version) != v {
panic(fmt.Sprintf("mistake: version %q does not satisfy requirement %+v", v, r)) // TODO: Don't panic.
}
if !listed[r.Path] {
list = append(list, module.Version{Path: r.Path, Version: v})
listed[r.Path] = true
}
}
}
tail := list[1:]
sort.Slice(tail, func(i, j int) bool {
return tail[i].Path < tail[j].Path
})
return list, nil
}
// Req returns the minimal requirement list for the target module
// that results in the given build list, with the constraint that all
// module paths listed in base must appear in the returned list.
func Req(target module.Version, list []module.Version, base []string, reqs Reqs) ([]module.Version, error) {
// Note: Not running in parallel because we assume
// that list came from a previous operation that paged
// in all the requirements, so there's no I/O to overlap now.
// Compute postorder, cache requirements.
var postorder []module.Version
reqCache := map[module.Version][]module.Version{}
reqCache[target] = nil
var walk func(module.Version) error
walk = func(m module.Version) error {
_, ok := reqCache[m]
if ok {
return nil
}
required, err := reqs.Required(m)
if err != nil {
return err
}
reqCache[m] = required
for _, m1 := range required {
if err := walk(m1); err != nil {
return err
}
}
postorder = append(postorder, m)
return nil
}
for _, m := range list {
if err := walk(m); err != nil {
return nil, err
}
}
// Walk modules in reverse post-order, only adding those not implied already.
have := map[string]string{}
walk = func(m module.Version) error {
if v, ok := have[m.Path]; ok && reqs.Max(m.Version, v) == v {
return nil
}
have[m.Path] = m.Version
for _, m1 := range reqCache[m] {
walk(m1)
}
return nil
}
max := map[string]string{}
for _, m := range list {
if v, ok := max[m.Path]; ok {
max[m.Path] = reqs.Max(m.Version, v)
} else {
max[m.Path] = m.Version
}
}
// First walk the base modules that must be listed.
var min []module.Version
for _, path := range base {
m := module.Version{Path: path, Version: max[path]}
min = append(min, m)
walk(m)
}
// Now the reverse postorder to bring in anything else.
for i := len(postorder) - 1; i >= 0; i-- {
m := postorder[i]
if max[m.Path] != m.Version {
// Older version.
continue
}
if have[m.Path] != m.Version {
min = append(min, m)
walk(m)
}
}
sort.Slice(min, func(i, j int) bool {
return min[i].Path < min[j].Path
})
return min, nil
}
// UpgradeAll returns a build list for the target module
// in which every module is upgraded to its latest version.
func UpgradeAll(target module.Version, reqs Reqs) ([]module.Version, error) {
return buildList(target, reqs, func(m module.Version) module.Version {
if m.Path == target.Path {
return target
}
latest, err := reqs.Upgrade(m)
if err != nil {
panic(err) // TODO
}
m.Version = latest.Version
return m
})
}
// Upgrade returns a build list for the target module
// in which the given additional modules are upgraded.
func Upgrade(target module.Version, reqs Reqs, upgrade ...module.Version) ([]module.Version, error) {
list, err := reqs.Required(target)
if err != nil {
panic(err) // TODO
}
// TODO: Maybe if an error is given,
// rerun with BuildList(upgrade[0], reqs) etc
// to find which ones are the buggy ones.
list = append([]module.Version(nil), list...)
list = append(list, upgrade...)
return BuildList(target, &override{target, list, reqs})
}
// Downgrade returns a build list for the target module
// in which the given additional modules are downgraded.
//
// The versions to be downgraded may be unreachable from reqs.Latest and
// reqs.Previous, but the methods of reqs must otherwise handle such versions
// correctly.
func Downgrade(target module.Version, reqs Reqs, downgrade ...module.Version) ([]module.Version, error) {
list, err := reqs.Required(target)
if err != nil {
panic(err) // TODO
}
max := make(map[string]string)
for _, r := range list {
max[r.Path] = r.Version
}
for _, d := range downgrade {
if v, ok := max[d.Path]; !ok || reqs.Max(v, d.Version) != d.Version {
max[d.Path] = d.Version
}
}
var (
added = make(map[module.Version]bool)
rdeps = make(map[module.Version][]module.Version)
excluded = make(map[module.Version]bool)
)
var exclude func(module.Version)
exclude = func(m module.Version) {
if excluded[m] {
return
}
excluded[m] = true
for _, p := range rdeps[m] {
exclude(p)
}
}
var add func(module.Version)
add = func(m module.Version) {
if added[m] {
return
}
added[m] = true
if v, ok := max[m.Path]; ok && reqs.Max(m.Version, v) != v {
exclude(m)
return
}
list, err := reqs.Required(m)
if err != nil {
panic(err) // TODO
}
for _, r := range list {
add(r)
if excluded[r] {
exclude(m)
return
}
rdeps[r] = append(rdeps[r], m)
}
}
var out []module.Version
out = append(out, target)
List:
for _, r := range list {
add(r)
for excluded[r] {
p, err := reqs.Previous(r)
if err != nil {
return nil, err // TODO
}
// If the target version is a pseudo-version, it may not be
// included when iterating over prior versions using reqs.Previous.
// Insert it into the right place in the iteration.
// If v is excluded, p should be returned again by reqs.Previous on the next iteration.
if v := max[r.Path]; reqs.Max(v, r.Version) != v && reqs.Max(p.Version, v) != p.Version {
p.Version = v
}
if p.Version == "none" {
continue List
}
add(p)
r = p
}
out = append(out, r)
}
return out, nil
}
type override struct {
target module.Version
list []module.Version
Reqs
}
func (r *override) Required(m module.Version) ([]module.Version, error) {
if m == r.target {
return r.list, nil
}
return r.Reqs.Required(m)
}
|
modinfo
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modinfo/info.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package modinfo
import "time"
// Note that these structs are publicly visible (part of go list's API)
// and the fields are documented in the help text in ../list/list.go
type ModulePublic struct {
Path string `json:",omitempty"` // module path
Version string `json:",omitempty"` // module version
Versions []string `json:",omitempty"` // available module versions
Replace *ModulePublic `json:",omitempty"` // replaced by this module
Time *time.Time `json:",omitempty"` // time version was created
Update *ModulePublic `json:",omitempty"` // available update (with -u)
Main bool `json:",omitempty"` // is this the main module?
Indirect bool `json:",omitempty"` // module is only indirectly needed by main module
Dir string `json:",omitempty"` // directory holding local copy of files, if any
GoMod string `json:",omitempty"` // path to go.mod file describing module, if any
Error *ModuleError `json:",omitempty"` // error loading module
GoVersion string `json:",omitempty"` // go version used in module
}
type ModuleError struct {
Err string // error text
}
func (m *ModulePublic) String() string {
s := m.Path
if m.Version != "" {
s += " " + m.Version
if m.Update != nil {
s += " [" + m.Update.Version + "]"
}
}
if m.Replace != nil {
s += " => " + m.Replace.Path
if m.Replace.Version != "" {
s += " " + m.Replace.Version
if m.Replace.Update != nil {
s += " [" + m.Replace.Update.Version + "]"
}
}
}
return s
}
|
base
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/base/base.go
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package base defines shared basic pieces of the go command,
// in particular logging and the Command structure.
package base
import (
"bytes"
"errors"
"flag"
"fmt"
"go/scanner"
"log"
"os"
"os/exec"
"runtime/debug"
"strings"
"sync"
"cmd/go/internal/cfg"
"cmd/go/internal/str"
)
// A Command is an implementation of a go command
// like go build or go fix.
type Command struct {
// Run runs the command.
// The args are the arguments after the command name.
Run func(cmd *Command, args []string)
// UsageLine is the one-line usage message.
// The first word in the line is taken to be the command name.
UsageLine string
// Short is the short description shown in the 'go help' output.
Short string
// Long is the long message shown in the 'go help <this-command>' output.
Long string
// Flag is a set of flags specific to this command.
Flag flag.FlagSet
// CustomFlags indicates that the command will do its own
// flag parsing.
CustomFlags bool
// Commands lists the available commands and help topics.
// The order here is the order in which they are printed by 'go help'.
// Note that subcommands are in general best avoided.
Commands []*Command
}
var Go = &Command{
UsageLine: "go",
Long: `Go is a tool for managing Go source code.`,
// Commands initialized in package main
}
// LongName returns the command's long name: all the words in the usage line between "go" and a flag or argument,
func (c *Command) LongName() string {
name := c.UsageLine
if i := strings.Index(name, " ["); i >= 0 {
name = name[:i]
}
if name == "go" {
return ""
}
return strings.TrimPrefix(name, "go ")
}
// Name returns the command's short name: the last word in the usage line before a flag or argument.
func (c *Command) Name() string {
name := c.LongName()
if i := strings.LastIndex(name, " "); i >= 0 {
name = name[i+1:]
}
return name
}
func (c *Command) Usage() {
fmt.Fprintf(os.Stderr, "usage: %s\n", c.UsageLine)
fmt.Fprintf(os.Stderr, "Run 'go help %s' for details.\n", c.LongName())
os.Exit(2)
}
// Runnable reports whether the command can be run; otherwise
// it is a documentation pseudo-command such as importpath.
func (c *Command) Runnable() bool {
return c.Run != nil
}
var atExitFuncs []func()
func AtExit(f func()) {
atExitFuncs = append(atExitFuncs, f)
}
func Exit() {
for _, f := range atExitFuncs {
f()
}
os.Exit(exitStatus)
}
var et = flag.Bool("et", false, "print stack traces with errors")
func Fatalf(format string, args ...interface{}) {
Errorf(format, args...)
Exit()
}
func Errorf(format string, args ...interface{}) {
if *et {
stack := debug.Stack()
log.Printf("%s\n%s", fmt.Sprintf(format, args...), stack)
} else {
log.Printf(format, args...)
}
SetExitStatus(1)
}
func ExitIfErrors() {
if exitStatus != 0 {
Exit()
}
}
var exitStatus = 0
var exitMu sync.Mutex
func SetExitStatus(n int) {
exitMu.Lock()
if exitStatus < n {
exitStatus = n
}
exitMu.Unlock()
}
// Run runs the command, with stdout and stderr
// connected to the go command's own stdout and stderr.
// If the command fails, Run reports the error using Errorf.
func Run(cmdargs ...interface{}) {
cmdline := str.StringList(cmdargs...)
if cfg.BuildN || cfg.BuildX {
fmt.Printf("%s\n", strings.Join(cmdline, " "))
if cfg.BuildN {
return
}
}
cmd := exec.Command(cmdline[0], cmdline[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
Errorf("%v", err)
}
}
// RunStdin is like run but connects Stdin.
func RunStdin(cmdline []string) {
cmd := exec.Command(cmdline[0], cmdline[1:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = cfg.OrigEnv
StartSigHandlers()
if err := cmd.Run(); err != nil {
Errorf("%v", err)
}
}
// Usage is the usage-reporting function, filled in by package main
// but here for reference by other packages.
var Usage func()
// ExpandScanner expands a scanner.List error into all the errors in the list.
// The default Error method only shows the first error
// and does not shorten paths.
func ExpandScanner(err error) error {
// Look for parser errors.
if err, ok := err.(scanner.ErrorList); ok {
// Prepare error with \n before each message.
// When printed in something like context: %v
// this will put the leading file positions each on
// its own line. It will also show all the errors
// instead of just the first, as err.Error does.
var buf bytes.Buffer
for _, e := range err {
e.Pos.Filename = ShortPath(e.Pos.Filename)
buf.WriteString("\n")
buf.WriteString(e.Error())
}
return errors.New(buf.String())
}
return err
}
|
base
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/base/path.go
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package base
import (
"os"
"path/filepath"
"strings"
)
func getwd() string {
wd, err := os.Getwd()
if err != nil {
Fatalf("cannot determine current directory: %v", err)
}
return wd
}
var Cwd = getwd()
// ShortPath returns an absolute or relative name for path, whatever is shorter.
func ShortPath(path string) string {
if rel, err := filepath.Rel(Cwd, path); err == nil && len(rel) < len(path) {
return rel
}
return path
}
// RelPaths returns a copy of paths with absolute paths
// made relative to the current directory if they would be shorter.
func RelPaths(paths []string) []string {
var out []string
// TODO(rsc): Can this use Cwd from above?
pwd, _ := os.Getwd()
for _, p := range paths {
rel, err := filepath.Rel(pwd, p)
if err == nil && len(rel) < len(p) {
p = rel
}
out = append(out, p)
}
return out
}
// IsTestFile reports whether the source file is a set of tests and should therefore
// be excluded from coverage analysis.
func IsTestFile(file string) bool {
// We don't cover tests, only the code they test.
return strings.HasSuffix(file, "_test.go")
}
|
base
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/base/tool.go
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package base
import (
"fmt"
"go/build"
"os"
"path/filepath"
"runtime"
"cmd/go/internal/cfg"
)
// Configuration for finding tool binaries.
var (
ToolGOOS = runtime.GOOS
ToolGOARCH = runtime.GOARCH
ToolIsWindows = ToolGOOS == "windows"
ToolDir = build.ToolDir
)
const ToolWindowsExtension = ".exe"
// Tool returns the path to the named tool (for example, "vet").
// If the tool cannot be found, Tool exits the process.
func Tool(toolName string) string {
toolPath := filepath.Join(ToolDir, toolName)
if ToolIsWindows {
toolPath += ToolWindowsExtension
}
if len(cfg.BuildToolexec) > 0 {
return toolPath
}
// Give a nice message if there is no tool with that name.
if _, err := os.Stat(toolPath); err != nil {
fmt.Fprintf(os.Stderr, "go tool: no such tool %q\n", toolName)
SetExitStatus(2)
Exit()
}
return toolPath
}
|
base
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/base/signal_unix.go
|
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd js linux nacl netbsd openbsd solaris
package base
import (
"os"
"syscall"
)
var signalsToIgnore = []os.Signal{os.Interrupt, syscall.SIGQUIT}
// SignalTrace is the signal to send to make a Go program
// crash with a stack trace.
var SignalTrace os.Signal = syscall.SIGQUIT
|
base
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/base/env.go
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package base
import "strings"
// EnvForDir returns a copy of the environment
// suitable for running in the given directory.
// The environment is the current process's environment
// but with an updated $PWD, so that an os.Getwd in the
// child will be faster.
func EnvForDir(dir string, base []string) []string {
// Internally we only use rooted paths, so dir is rooted.
// Even if dir is not rooted, no harm done.
return MergeEnvLists([]string{"PWD=" + dir}, base)
}
// MergeEnvLists merges the two environment lists such that
// variables with the same name in "in" replace those in "out".
// This always returns a newly allocated slice.
func MergeEnvLists(in, out []string) []string {
out = append([]string(nil), out...)
NextVar:
for _, inkv := range in {
k := strings.SplitAfterN(inkv, "=", 2)[0]
for i, outkv := range out {
if strings.HasPrefix(outkv, k) {
out[i] = inkv
continue NextVar
}
}
out = append(out, inkv)
}
return out
}
|
base
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/base/signal.go
|
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package base
import (
"os"
"os/signal"
"sync"
)
// Interrupted is closed when the go command receives an interrupt signal.
var Interrupted = make(chan struct{})
// processSignals setups signal handler.
func processSignals() {
sig := make(chan os.Signal)
signal.Notify(sig, signalsToIgnore...)
go func() {
<-sig
close(Interrupted)
}()
}
var onceProcessSignals sync.Once
// StartSigHandlers starts the signal handlers.
func StartSigHandlers() {
onceProcessSignals.Do(processSignals)
}
|
base
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/base/goflags.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package base
import (
"flag"
"fmt"
"os"
"runtime"
"strings"
"cmd/go/internal/cfg"
)
var (
goflags []string // cached $GOFLAGS list; can be -x or --x form
knownFlag = make(map[string]bool) // flags allowed to appear in $GOFLAGS; no leading dashes
)
// AddKnownFlag adds name to the list of known flags for use in $GOFLAGS.
func AddKnownFlag(name string) {
knownFlag[name] = true
}
// GOFLAGS returns the flags from $GOFLAGS.
// The list can be assumed to contain one string per flag,
// with each string either beginning with -name or --name.
func GOFLAGS() []string {
InitGOFLAGS()
return goflags
}
// InitGOFLAGS initializes the goflags list from $GOFLAGS.
// If goflags is already initialized, it does nothing.
func InitGOFLAGS() {
if goflags != nil { // already initialized
return
}
// Build list of all flags for all commands.
// If no command has that flag, then we report the problem.
// This catches typos while still letting users record flags in GOFLAGS
// that only apply to a subset of go commands.
// Commands using CustomFlags can report their flag names
// by calling AddKnownFlag instead.
var walkFlags func(*Command)
walkFlags = func(cmd *Command) {
for _, sub := range cmd.Commands {
walkFlags(sub)
}
cmd.Flag.VisitAll(func(f *flag.Flag) {
knownFlag[f.Name] = true
})
}
walkFlags(Go)
// Ignore bad flag in go env and go bug, because
// they are what people reach for when debugging
// a problem, and maybe they're debugging GOFLAGS.
// (Both will show the GOFLAGS setting if let succeed.)
hideErrors := cfg.CmdName == "env" || cfg.CmdName == "bug"
goflags = strings.Fields(os.Getenv("GOFLAGS"))
if goflags == nil {
goflags = []string{} // avoid work on later InitGOFLAGS call
}
// Each of the words returned by strings.Fields must be its own flag.
// To set flag arguments use -x=value instead of -x value.
// For boolean flags, -x is fine instead of -x=true.
for _, f := range goflags {
// Check that every flag looks like -x --x -x=value or --x=value.
if !strings.HasPrefix(f, "-") || f == "-" || f == "--" || strings.HasPrefix(f, "---") || strings.HasPrefix(f, "-=") || strings.HasPrefix(f, "--=") {
if hideErrors {
continue
}
Fatalf("go: parsing $GOFLAGS: non-flag %q", f)
}
name := f[1:]
if name[0] == '-' {
name = name[1:]
}
if i := strings.Index(name, "="); i >= 0 {
name = name[:i]
}
if !knownFlag[name] {
if hideErrors {
continue
}
Fatalf("go: parsing $GOFLAGS: unknown flag -%s", name)
}
}
}
// boolFlag is the optional interface for flag.Value known to the flag package.
// (It is not clear why package flag does not export this interface.)
type boolFlag interface {
flag.Value
IsBoolFlag() bool
}
// SetFromGOFLAGS sets the flags in the given flag set using settings in $GOFLAGS.
func SetFromGOFLAGS(flags flag.FlagSet) {
InitGOFLAGS()
// This loop is similar to flag.Parse except that it ignores
// unknown flags found in goflags, so that setting, say, GOFLAGS=-ldflags=-w
// does not break commands that don't have a -ldflags.
// It also adjusts the output to be clear that the reported problem is from $GOFLAGS.
where := "$GOFLAGS"
if runtime.GOOS == "windows" {
where = "%GOFLAGS%"
}
for _, goflag := range goflags {
name, value, hasValue := goflag, "", false
if i := strings.Index(goflag, "="); i >= 0 {
name, value, hasValue = goflag[:i], goflag[i+1:], true
}
if strings.HasPrefix(name, "--") {
name = name[1:]
}
f := flags.Lookup(name[1:])
if f == nil {
continue
}
if fb, ok := f.Value.(boolFlag); ok && fb.IsBoolFlag() {
if hasValue {
if err := fb.Set(value); err != nil {
fmt.Fprintf(flags.Output(), "go: invalid boolean value %q for flag %s (from %s): %v\n", value, name, where, err)
flags.Usage()
}
} else {
if err := fb.Set("true"); err != nil {
fmt.Fprintf(flags.Output(), "go: invalid boolean flag %s (from %s): %v\n", name, where, err)
flags.Usage()
}
}
} else {
if !hasValue {
fmt.Fprintf(flags.Output(), "go: flag needs an argument: %s (from %s)\n", name, where)
flags.Usage()
}
if err := f.Value.Set(value); err != nil {
fmt.Fprintf(flags.Output(), "go: invalid value %q for flag %s (from %s): %v\n", value, name, where, err)
flags.Usage()
}
}
}
}
|
base
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/base/signal_notunix.go
|
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build plan9 windows
package base
import (
"os"
)
var signalsToIgnore = []os.Signal{os.Interrupt}
// SignalTrace is the signal to send to make a Go program
// crash with a stack trace (no such signal in this case).
var SignalTrace os.Signal = nil
|
base
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/base/flag.go
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package base
import (
"flag"
"cmd/go/internal/cfg"
"cmd/go/internal/str"
)
// A StringsFlag is a command-line flag that interprets its argument
// as a space-separated list of possibly-quoted strings.
type StringsFlag []string
func (v *StringsFlag) Set(s string) error {
var err error
*v, err = str.SplitQuotedFields(s)
if *v == nil {
*v = []string{}
}
return err
}
func (v *StringsFlag) String() string {
return "<StringsFlag>"
}
// AddBuildFlagsNX adds the -n and -x build flags to the flag set.
func AddBuildFlagsNX(flags *flag.FlagSet) {
flags.BoolVar(&cfg.BuildN, "n", false, "")
flags.BoolVar(&cfg.BuildX, "x", false, "")
}
|
modcmd
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modcmd/init.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// go mod init
package modcmd
import (
"cmd/go/internal/base"
"cmd/go/internal/modload"
"os"
)
var cmdInit = &base.Command{
UsageLine: "go mod init [module]",
Short: "initialize new module in current directory",
Long: `
Init initializes and writes a new go.mod to the current directory,
in effect creating a new module rooted at the current directory.
The file go.mod must not already exist.
If possible, init will guess the module path from import comments
(see 'go help importpath') or from version control configuration.
To override this guess, supply the module path as an argument.
`,
Run: runInit,
}
func runInit(cmd *base.Command, args []string) {
modload.CmdModInit = true
if len(args) > 1 {
base.Fatalf("go mod init: too many arguments")
}
if len(args) == 1 {
modload.CmdModModule = args[0]
}
if _, err := os.Stat("go.mod"); err == nil {
base.Fatalf("go mod init: go.mod already exists")
}
modload.InitMod() // does all the hard work
}
|
modcmd
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modcmd/graph.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// go mod graph
package modcmd
import (
"bufio"
"os"
"sort"
"cmd/go/internal/base"
"cmd/go/internal/modload"
"cmd/go/internal/module"
"cmd/go/internal/par"
)
var cmdGraph = &base.Command{
UsageLine: "go mod graph",
Short: "print module requirement graph",
Long: `
Graph prints the module requirement graph (with replacements applied)
in text form. Each line in the output has two space-separated fields: a module
and one of its requirements. Each module is identified as a string of the form
path@version, except for the main module, which has no @version suffix.
`,
Run: runGraph,
}
func runGraph(cmd *base.Command, args []string) {
if len(args) > 0 {
base.Fatalf("go mod graph: graph takes no arguments")
}
modload.LoadBuildList()
reqs := modload.MinReqs()
format := func(m module.Version) string {
if m.Version == "" {
return m.Path
}
return m.Path + "@" + m.Version
}
// Note: using par.Work only to manage work queue.
// No parallelism here, so no locking.
var out []string
var deps int // index in out where deps start
var work par.Work
work.Add(modload.Target)
work.Do(1, func(item interface{}) {
m := item.(module.Version)
list, _ := reqs.Required(m)
for _, r := range list {
work.Add(r)
out = append(out, format(m)+" "+format(r)+"\n")
}
if m == modload.Target {
deps = len(out)
}
})
sort.Slice(out[deps:], func(i, j int) bool {
return out[deps+i][0] < out[deps+j][0]
})
w := bufio.NewWriter(os.Stdout)
for _, line := range out {
w.WriteString(line)
}
w.Flush()
}
|
modcmd
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modcmd/vendor.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package modcmd
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"cmd/go/internal/modload"
"cmd/go/internal/module"
)
var cmdVendor = &base.Command{
UsageLine: "go mod vendor [-v]",
Short: "make vendored copy of dependencies",
Long: `
Vendor resets the main module's vendor directory to include all packages
needed to build and test all the main module's packages.
It does not include test code for vendored packages.
The -v flag causes vendor to print the names of vendored
modules and packages to standard error.
`,
Run: runVendor,
}
func init() {
cmdVendor.Flag.BoolVar(&cfg.BuildV, "v", false, "")
}
func runVendor(cmd *base.Command, args []string) {
if len(args) != 0 {
base.Fatalf("go mod vendor: vendor takes no arguments")
}
pkgs := modload.LoadVendor()
vdir := filepath.Join(modload.ModRoot, "vendor")
if err := os.RemoveAll(vdir); err != nil {
base.Fatalf("go vendor: %v", err)
}
modpkgs := make(map[module.Version][]string)
for _, pkg := range pkgs {
m := modload.PackageModule(pkg)
if m == modload.Target {
continue
}
modpkgs[m] = append(modpkgs[m], pkg)
}
var buf bytes.Buffer
for _, m := range modload.BuildList()[1:] {
if pkgs := modpkgs[m]; len(pkgs) > 0 {
repl := ""
if r := modload.Replacement(m); r.Path != "" {
repl = " => " + r.Path
if r.Version != "" {
repl += " " + r.Version
}
}
fmt.Fprintf(&buf, "# %s %s%s\n", m.Path, m.Version, repl)
if cfg.BuildV {
fmt.Fprintf(os.Stderr, "# %s %s%s\n", m.Path, m.Version, repl)
}
for _, pkg := range pkgs {
fmt.Fprintf(&buf, "%s\n", pkg)
if cfg.BuildV {
fmt.Fprintf(os.Stderr, "%s\n", pkg)
}
vendorPkg(vdir, pkg)
}
}
}
if buf.Len() == 0 {
fmt.Fprintf(os.Stderr, "go: no dependencies to vendor\n")
return
}
if err := ioutil.WriteFile(filepath.Join(vdir, "modules.txt"), buf.Bytes(), 0666); err != nil {
base.Fatalf("go vendor: %v", err)
}
}
func vendorPkg(vdir, pkg string) {
realPath := modload.ImportMap(pkg)
if realPath != pkg && modload.ImportMap(realPath) != "" {
fmt.Fprintf(os.Stderr, "warning: %s imported as both %s and %s; making two copies.\n", realPath, realPath, pkg)
}
dst := filepath.Join(vdir, pkg)
src := modload.PackageDir(realPath)
if src == "" {
fmt.Fprintf(os.Stderr, "internal error: no pkg for %s -> %s\n", pkg, realPath)
}
copyDir(dst, src, matchNonTest)
if m := modload.PackageModule(realPath); m.Path != "" {
copyMetadata(m.Path, realPath, dst, src)
}
}
type metakey struct {
modPath string
dst string
}
var copiedMetadata = make(map[metakey]bool)
// copyMetadata copies metadata files from parents of src to parents of dst,
// stopping after processing the src parent for modPath.
func copyMetadata(modPath, pkg, dst, src string) {
for parent := 0; ; parent++ {
if copiedMetadata[metakey{modPath, dst}] {
break
}
copiedMetadata[metakey{modPath, dst}] = true
if parent > 0 {
copyDir(dst, src, matchMetadata)
}
if modPath == pkg {
break
}
pkg = filepath.Dir(pkg)
dst = filepath.Dir(dst)
src = filepath.Dir(src)
}
}
// metaPrefixes is the list of metadata file prefixes.
// Vendoring copies metadata files from parents of copied directories.
// Note that this list could be arbitrarily extended, and it is longer
// in other tools (such as godep or dep). By using this limited set of
// prefixes and also insisting on capitalized file names, we are trying
// to nudge people toward more agreement on the naming
// and also trying to avoid false positives.
var metaPrefixes = []string{
"AUTHORS",
"CONTRIBUTORS",
"COPYLEFT",
"COPYING",
"COPYRIGHT",
"LEGAL",
"LICENSE",
"NOTICE",
"PATENTS",
}
// matchMetadata reports whether info is a metadata file.
func matchMetadata(info os.FileInfo) bool {
name := info.Name()
for _, p := range metaPrefixes {
if strings.HasPrefix(name, p) {
return true
}
}
return false
}
// matchNonTest reports whether info is any non-test file (including non-Go files).
func matchNonTest(info os.FileInfo) bool {
return !strings.HasSuffix(info.Name(), "_test.go")
}
// copyDir copies all regular files satisfying match(info) from src to dst.
func copyDir(dst, src string, match func(os.FileInfo) bool) {
files, err := ioutil.ReadDir(src)
if err != nil {
base.Fatalf("go vendor: %v", err)
}
if err := os.MkdirAll(dst, 0777); err != nil {
base.Fatalf("go vendor: %v", err)
}
for _, file := range files {
if file.IsDir() || !file.Mode().IsRegular() || !match(file) {
continue
}
r, err := os.Open(filepath.Join(src, file.Name()))
if err != nil {
base.Fatalf("go vendor: %v", err)
}
w, err := os.Create(filepath.Join(dst, file.Name()))
if err != nil {
base.Fatalf("go vendor: %v", err)
}
if _, err := io.Copy(w, r); err != nil {
base.Fatalf("go vendor: %v", err)
}
r.Close()
if err := w.Close(); err != nil {
base.Fatalf("go vendor: %v", err)
}
}
}
|
modcmd
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modcmd/why.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package modcmd
import (
"cmd/go/internal/base"
"cmd/go/internal/modload"
"cmd/go/internal/module"
"fmt"
"strings"
)
var cmdWhy = &base.Command{
UsageLine: "go mod why [-m] [-vendor] packages...",
Short: "explain why packages or modules are needed",
Long: `
Why shows a shortest path in the import graph from the main module to
each of the listed packages. If the -m flag is given, why treats the
arguments as a list of modules and finds a path to any package in each
of the modules.
By default, why queries the graph of packages matched by "go list all",
which includes tests for reachable packages. The -vendor flag causes why
to exclude tests of dependencies.
The output is a sequence of stanzas, one for each package or module
name on the command line, separated by blank lines. Each stanza begins
with a comment line "# package" or "# module" giving the target
package or module. Subsequent lines give a path through the import
graph, one package per line. If the package or module is not
referenced from the main module, the stanza will display a single
parenthesized note indicating that fact.
For example:
$ go mod why golang.org/x/text/language golang.org/x/text/encoding
# golang.org/x/text/language
rsc.io/quote
rsc.io/sampler
golang.org/x/text/language
# golang.org/x/text/encoding
(main module does not need package golang.org/x/text/encoding)
$
`,
}
var (
whyM = cmdWhy.Flag.Bool("m", false, "")
whyVendor = cmdWhy.Flag.Bool("vendor", false, "")
)
func init() {
cmdWhy.Run = runWhy // break init cycle
}
func runWhy(cmd *base.Command, args []string) {
loadALL := modload.LoadALL
if *whyVendor {
loadALL = modload.LoadVendor
}
if *whyM {
listU := false
listVersions := false
for _, arg := range args {
if strings.Contains(arg, "@") {
base.Fatalf("go mod why: module query not allowed")
}
}
mods := modload.ListModules(args, listU, listVersions)
byModule := make(map[module.Version][]string)
for _, path := range loadALL() {
m := modload.PackageModule(path)
if m.Path != "" {
byModule[m] = append(byModule[m], path)
}
}
sep := ""
for _, m := range mods {
best := ""
bestDepth := 1000000000
for _, path := range byModule[module.Version{Path: m.Path, Version: m.Version}] {
d := modload.WhyDepth(path)
if d > 0 && d < bestDepth {
best = path
bestDepth = d
}
}
why := modload.Why(best)
if why == "" {
vendoring := ""
if *whyVendor {
vendoring = " to vendor"
}
why = "(main module does not need" + vendoring + " module " + m.Path + ")\n"
}
fmt.Printf("%s# %s\n%s", sep, m.Path, why)
sep = "\n"
}
} else {
matches := modload.ImportPaths(args) // resolve to packages
loadALL() // rebuild graph, from main module (not from named packages)
sep := ""
for _, m := range matches {
for _, path := range m.Pkgs {
why := modload.Why(path)
if why == "" {
vendoring := ""
if *whyVendor {
vendoring = " to vendor"
}
why = "(main module does not need" + vendoring + " package " + path + ")\n"
}
fmt.Printf("%s# %s\n%s", sep, path, why)
sep = "\n"
}
}
}
}
|
modcmd
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modcmd/verify.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package modcmd
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"cmd/go/internal/base"
"cmd/go/internal/dirhash"
"cmd/go/internal/modfetch"
"cmd/go/internal/modload"
"cmd/go/internal/module"
)
var cmdVerify = &base.Command{
UsageLine: "go mod verify",
Short: "verify dependencies have expected content",
Long: `
Verify checks that the dependencies of the current module,
which are stored in a local downloaded source cache, have not been
modified since being downloaded. If all the modules are unmodified,
verify prints "all modules verified." Otherwise it reports which
modules have been changed and causes 'go mod' to exit with a
non-zero status.
`,
Run: runVerify,
}
func runVerify(cmd *base.Command, args []string) {
if len(args) != 0 {
// NOTE(rsc): Could take a module pattern.
base.Fatalf("go mod verify: verify takes no arguments")
}
ok := true
for _, mod := range modload.LoadBuildList()[1:] {
ok = verifyMod(mod) && ok
}
if ok {
fmt.Printf("all modules verified\n")
}
}
func verifyMod(mod module.Version) bool {
ok := true
zip, zipErr := modfetch.CachePath(mod, "zip")
if zipErr == nil {
_, zipErr = os.Stat(zip)
}
dir, dirErr := modfetch.DownloadDir(mod)
if dirErr == nil {
_, dirErr = os.Stat(dir)
}
data, err := ioutil.ReadFile(zip + "hash")
if err != nil {
if zipErr != nil && os.IsNotExist(zipErr) && dirErr != nil && os.IsNotExist(dirErr) {
// Nothing downloaded yet. Nothing to verify.
return true
}
base.Errorf("%s %s: missing ziphash: %v", mod.Path, mod.Version, err)
return false
}
h := string(bytes.TrimSpace(data))
if zipErr != nil && os.IsNotExist(zipErr) {
// ok
} else {
hZ, err := dirhash.HashZip(zip, dirhash.DefaultHash)
if err != nil {
base.Errorf("%s %s: %v", mod.Path, mod.Version, err)
return false
} else if hZ != h {
base.Errorf("%s %s: zip has been modified (%v)", mod.Path, mod.Version, zip)
ok = false
}
}
if dirErr != nil && os.IsNotExist(dirErr) {
// ok
} else {
hD, err := dirhash.HashDir(dir, mod.Path+"@"+mod.Version, dirhash.DefaultHash)
if err != nil {
base.Errorf("%s %s: %v", mod.Path, mod.Version, err)
return false
}
if hD != h {
base.Errorf("%s %s: dir has been modified (%v)", mod.Path, mod.Version, dir)
ok = false
}
}
return ok
}
|
modcmd
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modcmd/edit.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// go mod edit
package modcmd
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"cmd/go/internal/base"
"cmd/go/internal/modfile"
"cmd/go/internal/modload"
"cmd/go/internal/module"
)
var cmdEdit = &base.Command{
UsageLine: "go mod edit [editing flags] [go.mod]",
Short: "edit go.mod from tools or scripts",
Long: `
Edit provides a command-line interface for editing go.mod,
for use primarily by tools or scripts. It reads only go.mod;
it does not look up information about the modules involved.
By default, edit reads and writes the go.mod file of the main module,
but a different target file can be specified after the editing flags.
The editing flags specify a sequence of editing operations.
The -fmt flag reformats the go.mod file without making other changes.
This reformatting is also implied by any other modifications that use or
rewrite the go.mod file. The only time this flag is needed is if no other
flags are specified, as in 'go mod edit -fmt'.
The -module flag changes the module's path (the go.mod file's module line).
The -require=path@version and -droprequire=path flags
add and drop a requirement on the given module path and version.
Note that -require overrides any existing requirements on path.
These flags are mainly for tools that understand the module graph.
Users should prefer 'go get path@version' or 'go get path@none',
which make other go.mod adjustments as needed to satisfy
constraints imposed by other modules.
The -exclude=path@version and -dropexclude=path@version flags
add and drop an exclusion for the given module path and version.
Note that -exclude=path@version is a no-op if that exclusion already exists.
The -replace=old[@v]=new[@v] and -dropreplace=old[@v] flags
add and drop a replacement of the given module path and version pair.
If the @v in old@v is omitted, the replacement applies to all versions
with the old module path. If the @v in new@v is omitted, the new path
should be a local module root directory, not a module path.
Note that -replace overrides any existing replacements for old[@v].
The -require, -droprequire, -exclude, -dropexclude, -replace,
and -dropreplace editing flags may be repeated, and the changes
are applied in the order given.
The -print flag prints the final go.mod in its text format instead of
writing it back to go.mod.
The -json flag prints the final go.mod file in JSON format instead of
writing it back to go.mod. The JSON output corresponds to these Go types:
type Module struct {
Path string
Version string
}
type GoMod struct {
Module Module
Require []Require
Exclude []Module
Replace []Replace
}
type Require struct {
Path string
Version string
Indirect bool
}
type Replace struct {
Old Module
New Module
}
Note that this only describes the go.mod file itself, not other modules
referred to indirectly. For the full set of modules available to a build,
use 'go list -m -json all'.
For example, a tool can obtain the go.mod as a data structure by
parsing the output of 'go mod edit -json' and can then make changes
by invoking 'go mod edit' with -require, -exclude, and so on.
`,
}
var (
editFmt = cmdEdit.Flag.Bool("fmt", false, "")
// editGo = cmdEdit.Flag.String("go", "", "")
editJSON = cmdEdit.Flag.Bool("json", false, "")
editPrint = cmdEdit.Flag.Bool("print", false, "")
editModule = cmdEdit.Flag.String("module", "", "")
edits []func(*modfile.File) // edits specified in flags
)
type flagFunc func(string)
func (f flagFunc) String() string { return "" }
func (f flagFunc) Set(s string) error { f(s); return nil }
func init() {
cmdEdit.Run = runEdit // break init cycle
cmdEdit.Flag.Var(flagFunc(flagRequire), "require", "")
cmdEdit.Flag.Var(flagFunc(flagDropRequire), "droprequire", "")
cmdEdit.Flag.Var(flagFunc(flagExclude), "exclude", "")
cmdEdit.Flag.Var(flagFunc(flagDropReplace), "dropreplace", "")
cmdEdit.Flag.Var(flagFunc(flagReplace), "replace", "")
cmdEdit.Flag.Var(flagFunc(flagDropExclude), "dropexclude", "")
base.AddBuildFlagsNX(&cmdEdit.Flag)
}
func runEdit(cmd *base.Command, args []string) {
anyFlags :=
*editModule != "" ||
*editJSON ||
*editPrint ||
*editFmt ||
len(edits) > 0
if !anyFlags {
base.Fatalf("go mod edit: no flags specified (see 'go help mod edit').")
}
if *editJSON && *editPrint {
base.Fatalf("go mod edit: cannot use both -json and -print")
}
if len(args) > 1 {
base.Fatalf("go mod edit: too many arguments")
}
var gomod string
if len(args) == 1 {
gomod = args[0]
} else {
modload.MustInit()
gomod = filepath.Join(modload.ModRoot, "go.mod")
}
if *editModule != "" {
if err := module.CheckPath(*editModule); err != nil {
base.Fatalf("go mod: invalid -module: %v", err)
}
}
// TODO(rsc): Implement -go= once we start advertising it.
data, err := ioutil.ReadFile(gomod)
if err != nil {
base.Fatalf("go: %v", err)
}
modFile, err := modfile.Parse(gomod, data, nil)
if err != nil {
base.Fatalf("go: errors parsing %s:\n%s", base.ShortPath(gomod), err)
}
if *editModule != "" {
modFile.AddModuleStmt(modload.CmdModModule)
}
if len(edits) > 0 {
for _, edit := range edits {
edit(modFile)
}
}
modFile.SortBlocks()
modFile.Cleanup() // clean file after edits
if *editJSON {
editPrintJSON(modFile)
return
}
data, err = modFile.Format()
if err != nil {
base.Fatalf("go: %v", err)
}
if *editPrint {
os.Stdout.Write(data)
return
}
if err := ioutil.WriteFile(gomod, data, 0666); err != nil {
base.Fatalf("go: %v", err)
}
}
// parsePathVersion parses -flag=arg expecting arg to be path@version.
func parsePathVersion(flag, arg string) (path, version string) {
i := strings.Index(arg, "@")
if i < 0 {
base.Fatalf("go mod: -%s=%s: need path@version", flag, arg)
}
path, version = strings.TrimSpace(arg[:i]), strings.TrimSpace(arg[i+1:])
if err := module.CheckPath(path); err != nil {
base.Fatalf("go mod: -%s=%s: invalid path: %v", flag, arg, err)
}
// We don't call modfile.CheckPathVersion, because that insists
// on versions being in semver form, but here we want to allow
// versions like "master" or "1234abcdef", which the go command will resolve
// the next time it runs (or during -fix).
// Even so, we need to make sure the version is a valid token.
if modfile.MustQuote(version) {
base.Fatalf("go mod: -%s=%s: invalid version %q", flag, arg, version)
}
return path, version
}
// parsePath parses -flag=arg expecting arg to be path (not path@version).
func parsePath(flag, arg string) (path string) {
if strings.Contains(arg, "@") {
base.Fatalf("go mod: -%s=%s: need just path, not path@version", flag, arg)
}
path = arg
if err := module.CheckPath(path); err != nil {
base.Fatalf("go mod: -%s=%s: invalid path: %v", flag, arg, err)
}
return path
}
// parsePathVersionOptional parses path[@version], using adj to
// describe any errors.
func parsePathVersionOptional(adj, arg string, allowDirPath bool) (path, version string, err error) {
if i := strings.Index(arg, "@"); i < 0 {
path = arg
} else {
path, version = strings.TrimSpace(arg[:i]), strings.TrimSpace(arg[i+1:])
}
if err := module.CheckPath(path); err != nil {
if !allowDirPath || !modfile.IsDirectoryPath(path) {
return path, version, fmt.Errorf("invalid %s path: %v", adj, err)
}
}
if path != arg && modfile.MustQuote(version) {
return path, version, fmt.Errorf("invalid %s version: %q", adj, version)
}
return path, version, nil
}
// flagRequire implements the -require flag.
func flagRequire(arg string) {
path, version := parsePathVersion("require", arg)
edits = append(edits, func(f *modfile.File) {
if err := f.AddRequire(path, version); err != nil {
base.Fatalf("go mod: -require=%s: %v", arg, err)
}
})
}
// flagDropRequire implements the -droprequire flag.
func flagDropRequire(arg string) {
path := parsePath("droprequire", arg)
edits = append(edits, func(f *modfile.File) {
if err := f.DropRequire(path); err != nil {
base.Fatalf("go mod: -droprequire=%s: %v", arg, err)
}
})
}
// flagExclude implements the -exclude flag.
func flagExclude(arg string) {
path, version := parsePathVersion("exclude", arg)
edits = append(edits, func(f *modfile.File) {
if err := f.AddExclude(path, version); err != nil {
base.Fatalf("go mod: -exclude=%s: %v", arg, err)
}
})
}
// flagDropExclude implements the -dropexclude flag.
func flagDropExclude(arg string) {
path, version := parsePathVersion("dropexclude", arg)
edits = append(edits, func(f *modfile.File) {
if err := f.DropExclude(path, version); err != nil {
base.Fatalf("go mod: -dropexclude=%s: %v", arg, err)
}
})
}
// flagReplace implements the -replace flag.
func flagReplace(arg string) {
var i int
if i = strings.Index(arg, "="); i < 0 {
base.Fatalf("go mod: -replace=%s: need old[@v]=new[@w] (missing =)", arg)
}
old, new := strings.TrimSpace(arg[:i]), strings.TrimSpace(arg[i+1:])
if strings.HasPrefix(new, ">") {
base.Fatalf("go mod: -replace=%s: separator between old and new is =, not =>", arg)
}
oldPath, oldVersion, err := parsePathVersionOptional("old", old, false)
if err != nil {
base.Fatalf("go mod: -replace=%s: %v", arg, err)
}
newPath, newVersion, err := parsePathVersionOptional("new", new, true)
if err != nil {
base.Fatalf("go mod: -replace=%s: %v", arg, err)
}
if newPath == new && !modfile.IsDirectoryPath(new) {
base.Fatalf("go mod: -replace=%s: unversioned new path must be local directory", arg)
}
edits = append(edits, func(f *modfile.File) {
if err := f.AddReplace(oldPath, oldVersion, newPath, newVersion); err != nil {
base.Fatalf("go mod: -replace=%s: %v", arg, err)
}
})
}
// flagDropReplace implements the -dropreplace flag.
func flagDropReplace(arg string) {
path, version, err := parsePathVersionOptional("old", arg, true)
if err != nil {
base.Fatalf("go mod: -dropreplace=%s: %v", arg, err)
}
edits = append(edits, func(f *modfile.File) {
if err := f.DropReplace(path, version); err != nil {
base.Fatalf("go mod: -dropreplace=%s: %v", arg, err)
}
})
}
// fileJSON is the -json output data structure.
type fileJSON struct {
Module module.Version
Require []requireJSON
Exclude []module.Version
Replace []replaceJSON
}
type requireJSON struct {
Path string
Version string `json:",omitempty"`
Indirect bool `json:",omitempty"`
}
type replaceJSON struct {
Old module.Version
New module.Version
}
// editPrintJSON prints the -json output.
func editPrintJSON(modFile *modfile.File) {
var f fileJSON
f.Module = modFile.Module.Mod
for _, r := range modFile.Require {
f.Require = append(f.Require, requireJSON{Path: r.Mod.Path, Version: r.Mod.Version, Indirect: r.Indirect})
}
for _, x := range modFile.Exclude {
f.Exclude = append(f.Exclude, x.Mod)
}
for _, r := range modFile.Replace {
f.Replace = append(f.Replace, replaceJSON{r.Old, r.New})
}
data, err := json.MarshalIndent(&f, "", "\t")
if err != nil {
base.Fatalf("go: internal error: %v", err)
}
data = append(data, '\n')
os.Stdout.Write(data)
}
|
modcmd
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modcmd/tidy.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// go mod tidy
package modcmd
import (
"fmt"
"os"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"cmd/go/internal/modfetch"
"cmd/go/internal/modload"
"cmd/go/internal/module"
)
var cmdTidy = &base.Command{
UsageLine: "go mod tidy [-v]",
Short: "add missing and remove unused modules",
Long: `
Tidy makes sure go.mod matches the source code in the module.
It adds any missing modules necessary to build the current module's
packages and dependencies, and it removes unused modules that
don't provide any relevant packages. It also adds any missing entries
to go.sum and removes any unnecessary ones.
The -v flag causes tidy to print information about removed modules
to standard error.
`,
}
func init() {
cmdTidy.Run = runTidy // break init cycle
cmdTidy.Flag.BoolVar(&cfg.BuildV, "v", false, "")
}
func runTidy(cmd *base.Command, args []string) {
if len(args) > 0 {
base.Fatalf("go mod tidy: no arguments allowed")
}
// LoadALL adds missing modules.
// Remove unused modules.
used := make(map[module.Version]bool)
for _, pkg := range modload.LoadALL() {
used[modload.PackageModule(pkg)] = true
}
used[modload.Target] = true // note: LoadALL initializes Target
inGoMod := make(map[string]bool)
for _, r := range modload.ModFile().Require {
inGoMod[r.Mod.Path] = true
}
var keep []module.Version
for _, m := range modload.BuildList() {
if used[m] {
keep = append(keep, m)
} else if cfg.BuildV && inGoMod[m.Path] {
fmt.Fprintf(os.Stderr, "unused %s\n", m.Path)
}
}
modload.SetBuildList(keep)
modTidyGoSum() // updates memory copy; WriteGoMod on next line flushes it out
modload.WriteGoMod()
}
// modTidyGoSum resets the go.sum file content
// to be exactly what's needed for the current go.mod.
func modTidyGoSum() {
// Assuming go.sum already has at least enough from the successful load,
// we only have to tell modfetch what needs keeping.
reqs := modload.Reqs()
keep := make(map[module.Version]bool)
var walk func(module.Version)
walk = func(m module.Version) {
keep[m] = true
list, _ := reqs.Required(m)
for _, r := range list {
if !keep[r] {
walk(r)
}
}
}
walk(modload.Target)
modfetch.TrimGoSum(keep)
}
|
modcmd
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modcmd/mod.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package modcmd implements the ``go mod'' command.
package modcmd
import "cmd/go/internal/base"
var CmdMod = &base.Command{
UsageLine: "go mod",
Short: "module maintenance",
Long: `Go mod provides access to operations on modules.
Note that support for modules is built into all the go commands,
not just 'go mod'. For example, day-to-day adding, removing, upgrading,
and downgrading of dependencies should be done using 'go get'.
See 'go help modules' for an overview of module functionality.
`,
Commands: []*base.Command{
cmdDownload,
cmdEdit,
cmdGraph,
cmdInit,
cmdTidy,
cmdVendor,
cmdVerify,
cmdWhy,
},
}
|
modcmd
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modcmd/download.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package modcmd
import (
"cmd/go/internal/base"
"cmd/go/internal/modfetch"
"cmd/go/internal/modload"
"cmd/go/internal/module"
"cmd/go/internal/par"
"encoding/json"
"os"
)
var cmdDownload = &base.Command{
UsageLine: "go mod download [-dir] [-json] [modules]",
Short: "download modules to local cache",
Long: `
Download downloads the named modules, which can be module patterns selecting
dependencies of the main module or module queries of the form path@version.
With no arguments, download applies to all dependencies of the main module.
The go command will automatically download modules as needed during ordinary
execution. The "go mod download" command is useful mainly for pre-filling
the local cache or to compute the answers for a Go module proxy.
By default, download reports errors to standard error but is otherwise silent.
The -json flag causes download to print a sequence of JSON objects
to standard output, describing each downloaded module (or failure),
corresponding to this Go struct:
type Module struct {
Path string // module path
Version string // module version
Error string // error loading module
Info string // absolute path to cached .info file
GoMod string // absolute path to cached .mod file
Zip string // absolute path to cached .zip file
Dir string // absolute path to cached source root directory
Sum string // checksum for path, version (as in go.sum)
GoModSum string // checksum for go.mod (as in go.sum)
}
See 'go help modules' for more about module queries.
`,
}
var downloadJSON = cmdDownload.Flag.Bool("json", false, "")
func init() {
cmdDownload.Run = runDownload // break init cycle
}
type moduleJSON struct {
Path string `json:",omitempty"`
Version string `json:",omitempty"`
Error string `json:",omitempty"`
Info string `json:",omitempty"`
GoMod string `json:",omitempty"`
Zip string `json:",omitempty"`
Dir string `json:",omitempty"`
Sum string `json:",omitempty"`
GoModSum string `json:",omitempty"`
}
func runDownload(cmd *base.Command, args []string) {
if len(args) == 0 {
args = []string{"all"}
}
var mods []*moduleJSON
var work par.Work
listU := false
listVersions := false
for _, info := range modload.ListModules(args, listU, listVersions) {
if info.Replace != nil {
info = info.Replace
}
if info.Version == "" {
continue
}
m := &moduleJSON{
Path: info.Path,
Version: info.Version,
}
mods = append(mods, m)
work.Add(m)
}
work.Do(10, func(item interface{}) {
m := item.(*moduleJSON)
var err error
m.Info, err = modfetch.InfoFile(m.Path, m.Version)
if err != nil {
m.Error = err.Error()
return
}
m.GoMod, err = modfetch.GoModFile(m.Path, m.Version)
if err != nil {
m.Error = err.Error()
return
}
m.GoModSum, err = modfetch.GoModSum(m.Path, m.Version)
if err != nil {
m.Error = err.Error()
return
}
mod := module.Version{Path: m.Path, Version: m.Version}
m.Zip, err = modfetch.DownloadZip(mod)
if err != nil {
m.Error = err.Error()
return
}
m.Sum = modfetch.Sum(mod)
m.Dir, err = modfetch.Download(mod)
if err != nil {
m.Error = err.Error()
return
}
})
if *downloadJSON {
for _, m := range mods {
b, err := json.MarshalIndent(m, "", "\t")
if err != nil {
base.Fatalf("%v", err)
}
os.Stdout.Write(append(b, '\n'))
}
}
}
|
imports
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/imports/scan.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package imports
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
)
func ScanDir(dir string, tags map[string]bool) ([]string, []string, error) {
infos, err := ioutil.ReadDir(dir)
if err != nil {
return nil, nil, err
}
var files []string
for _, info := range infos {
name := info.Name()
if info.Mode().IsRegular() && !strings.HasPrefix(name, "_") && strings.HasSuffix(name, ".go") && MatchFile(name, tags) {
files = append(files, filepath.Join(dir, name))
}
}
return scanFiles(files, tags, false)
}
func ScanFiles(files []string, tags map[string]bool) ([]string, []string, error) {
return scanFiles(files, tags, true)
}
func scanFiles(files []string, tags map[string]bool, explicitFiles bool) ([]string, []string, error) {
imports := make(map[string]bool)
testImports := make(map[string]bool)
numFiles := 0
Files:
for _, name := range files {
r, err := os.Open(name)
if err != nil {
return nil, nil, err
}
var list []string
data, err := ReadImports(r, false, &list)
r.Close()
if err != nil {
return nil, nil, fmt.Errorf("reading %s: %v", name, err)
}
// import "C" is implicit requirement of cgo tag.
// When listing files on the command line (explicitFiles=true)
// we do not apply build tag filtering but we still do apply
// cgo filtering, so no explicitFiles check here.
// Why? Because we always have, and it's not worth breaking
// that behavior now.
for _, path := range list {
if path == `"C"` && !tags["cgo"] && !tags["*"] {
continue Files
}
}
if !explicitFiles && !ShouldBuild(data, tags) {
continue
}
numFiles++
m := imports
if strings.HasSuffix(name, "_test.go") {
m = testImports
}
for _, p := range list {
q, err := strconv.Unquote(p)
if err != nil {
continue
}
m[q] = true
}
}
if numFiles == 0 {
return nil, nil, ErrNoGo
}
return keys(imports), keys(testImports), nil
}
var ErrNoGo = fmt.Errorf("no Go source files")
func keys(m map[string]bool) []string {
var list []string
for k := range m {
list = append(list, k)
}
sort.Strings(list)
return list
}
|
imports
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/imports/build.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copied from Go distribution src/go/build/build.go, syslist.go
package imports
import (
"bytes"
"strings"
"unicode"
)
var slashslash = []byte("//")
// ShouldBuild reports whether it is okay to use this file,
// The rule is that in the file's leading run of // comments
// and blank lines, which must be followed by a blank line
// (to avoid including a Go package clause doc comment),
// lines beginning with '// +build' are taken as build directives.
//
// The file is accepted only if each such line lists something
// matching the file. For example:
//
// // +build windows linux
//
// marks the file as applicable only on Windows and Linux.
//
// If tags["*"] is true, then ShouldBuild will consider every
// build tag except "ignore" to be both true and false for
// the purpose of satisfying build tags, in order to estimate
// (conservatively) whether a file could ever possibly be used
// in any build.
//
func ShouldBuild(content []byte, tags map[string]bool) bool {
// Pass 1. Identify leading run of // comments and blank lines,
// which must be followed by a blank line.
end := 0
p := content
for len(p) > 0 {
line := p
if i := bytes.IndexByte(line, '\n'); i >= 0 {
line, p = line[:i], p[i+1:]
} else {
p = p[len(p):]
}
line = bytes.TrimSpace(line)
if len(line) == 0 { // Blank line
end = len(content) - len(p)
continue
}
if !bytes.HasPrefix(line, slashslash) { // Not comment line
break
}
}
content = content[:end]
// Pass 2. Process each line in the run.
p = content
allok := true
for len(p) > 0 {
line := p
if i := bytes.IndexByte(line, '\n'); i >= 0 {
line, p = line[:i], p[i+1:]
} else {
p = p[len(p):]
}
line = bytes.TrimSpace(line)
if !bytes.HasPrefix(line, slashslash) {
continue
}
line = bytes.TrimSpace(line[len(slashslash):])
if len(line) > 0 && line[0] == '+' {
// Looks like a comment +line.
f := strings.Fields(string(line))
if f[0] == "+build" {
ok := false
for _, tok := range f[1:] {
if matchTags(tok, tags) {
ok = true
}
}
if !ok {
allok = false
}
}
}
}
return allok
}
// matchTags reports whether the name is one of:
//
// tag (if tags[tag] is true)
// !tag (if tags[tag] is false)
// a comma-separated list of any of these
//
func matchTags(name string, tags map[string]bool) bool {
if name == "" {
return false
}
if i := strings.Index(name, ","); i >= 0 {
// comma-separated list
ok1 := matchTags(name[:i], tags)
ok2 := matchTags(name[i+1:], tags)
return ok1 && ok2
}
if strings.HasPrefix(name, "!!") { // bad syntax, reject always
return false
}
if strings.HasPrefix(name, "!") { // negation
return len(name) > 1 && matchTag(name[1:], tags, false)
}
return matchTag(name, tags, true)
}
// matchTag reports whether the tag name is valid and satisfied by tags[name]==want.
func matchTag(name string, tags map[string]bool, want bool) bool {
// Tags must be letters, digits, underscores or dots.
// Unlike in Go identifiers, all digits are fine (e.g., "386").
for _, c := range name {
if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' {
return false
}
}
if tags["*"] && name != "" && name != "ignore" {
// Special case for gathering all possible imports:
// if we put * in the tags map then all tags
// except "ignore" are considered both present and not
// (so we return true no matter how 'want' is set).
return true
}
have := tags[name]
if name == "linux" {
have = have || tags["android"]
}
return have == want
}
// MatchFile returns false if the name contains a $GOOS or $GOARCH
// suffix which does not match the current system.
// The recognized name formats are:
//
// name_$(GOOS).*
// name_$(GOARCH).*
// name_$(GOOS)_$(GOARCH).*
// name_$(GOOS)_test.*
// name_$(GOARCH)_test.*
// name_$(GOOS)_$(GOARCH)_test.*
//
// An exception: if GOOS=android, then files with GOOS=linux are also matched.
//
// If tags["*"] is true, then MatchFile will consider all possible
// GOOS and GOARCH to be available and will consequently
// always return true.
func MatchFile(name string, tags map[string]bool) bool {
if tags["*"] {
return true
}
if dot := strings.Index(name, "."); dot != -1 {
name = name[:dot]
}
// Before Go 1.4, a file called "linux.go" would be equivalent to having a
// build tag "linux" in that file. For Go 1.4 and beyond, we require this
// auto-tagging to apply only to files with a non-empty prefix, so
// "foo_linux.go" is tagged but "linux.go" is not. This allows new operating
// systems, such as android, to arrive without breaking existing code with
// innocuous source code in "android.go". The easiest fix: cut everything
// in the name before the initial _.
i := strings.Index(name, "_")
if i < 0 {
return true
}
name = name[i:] // ignore everything before first _
l := strings.Split(name, "_")
if n := len(l); n > 0 && l[n-1] == "test" {
l = l[:n-1]
}
n := len(l)
if n >= 2 && KnownOS[l[n-2]] && KnownArch[l[n-1]] {
return tags[l[n-2]] && tags[l[n-1]]
}
if n >= 1 && KnownOS[l[n-1]] {
return tags[l[n-1]]
}
if n >= 1 && KnownArch[l[n-1]] {
return tags[l[n-1]]
}
return true
}
var KnownOS = make(map[string]bool)
var KnownArch = make(map[string]bool)
func init() {
for _, v := range strings.Fields(goosList) {
KnownOS[v] = true
}
for _, v := range strings.Fields(goarchList) {
KnownArch[v] = true
}
}
const goosList = "android darwin dragonfly freebsd js linux nacl netbsd openbsd plan9 solaris windows zos "
const goarchList = "386 amd64 amd64p32 arm armbe arm64 arm64be ppc64 ppc64le mips mipsle mips64 mips64le mips64p32 mips64p32le ppc riscv riscv64 s390 s390x sparc sparc64 wasm "
|
imports
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/imports/tags.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package imports
import "cmd/go/internal/cfg"
var tags map[string]bool
func Tags() map[string]bool {
if tags == nil {
tags = loadTags()
}
return tags
}
func loadTags() map[string]bool {
tags := map[string]bool{
cfg.BuildContext.GOOS: true,
cfg.BuildContext.GOARCH: true,
cfg.BuildContext.Compiler: true,
}
if cfg.BuildContext.CgoEnabled {
tags["cgo"] = true
}
for _, tag := range cfg.BuildContext.BuildTags {
tags[tag] = true
}
for _, tag := range cfg.BuildContext.ReleaseTags {
tags[tag] = true
}
return tags
}
|
imports
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/imports/read_test.go
|
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copied from Go distribution src/go/build/read.go.
package imports
import (
"io"
"strings"
"testing"
)
const quote = "`"
type readTest struct {
// Test input contains ℙ where readImports should stop.
in string
err string
}
var readImportsTests = []readTest{
{
`package p`,
"",
},
{
`package p; import "x"`,
"",
},
{
`package p; import . "x"`,
"",
},
{
`package p; import "x";ℙvar x = 1`,
"",
},
{
`package p
// comment
import "x"
import _ "x"
import a "x"
/* comment */
import (
"x" /* comment */
_ "x"
a "x" // comment
` + quote + `x` + quote + `
_ /*comment*/ ` + quote + `x` + quote + `
a ` + quote + `x` + quote + `
)
import (
)
import ()
import()import()import()
import();import();import()
ℙvar x = 1
`,
"",
},
}
var readCommentsTests = []readTest{
{
`ℙpackage p`,
"",
},
{
`ℙpackage p; import "x"`,
"",
},
{
`ℙpackage p; import . "x"`,
"",
},
{
`// foo
/* bar */
/* quux */ // baz
/*/ zot */
// asdf
ℙHello, world`,
"",
},
}
func testRead(t *testing.T, tests []readTest, read func(io.Reader) ([]byte, error)) {
for i, tt := range tests {
var in, testOut string
j := strings.Index(tt.in, "ℙ")
if j < 0 {
in = tt.in
testOut = tt.in
} else {
in = tt.in[:j] + tt.in[j+len("ℙ"):]
testOut = tt.in[:j]
}
r := strings.NewReader(in)
buf, err := read(r)
if err != nil {
if tt.err == "" {
t.Errorf("#%d: err=%q, expected success (%q)", i, err, string(buf))
continue
}
if !strings.Contains(err.Error(), tt.err) {
t.Errorf("#%d: err=%q, expected %q", i, err, tt.err)
continue
}
continue
}
if err == nil && tt.err != "" {
t.Errorf("#%d: success, expected %q", i, tt.err)
continue
}
out := string(buf)
if out != testOut {
t.Errorf("#%d: wrong output:\nhave %q\nwant %q\n", i, out, testOut)
}
}
}
func TestReadImports(t *testing.T) {
testRead(t, readImportsTests, func(r io.Reader) ([]byte, error) { return ReadImports(r, true, nil) })
}
func TestReadComments(t *testing.T) {
testRead(t, readCommentsTests, ReadComments)
}
var readFailuresTests = []readTest{
{
`package`,
"syntax error",
},
{
"package p\n\x00\nimport `math`\n",
"unexpected NUL in input",
},
{
`package p; import`,
"syntax error",
},
{
`package p; import "`,
"syntax error",
},
{
"package p; import ` \n\n",
"syntax error",
},
{
`package p; import "x`,
"syntax error",
},
{
`package p; import _`,
"syntax error",
},
{
`package p; import _ "`,
"syntax error",
},
{
`package p; import _ "x`,
"syntax error",
},
{
`package p; import .`,
"syntax error",
},
{
`package p; import . "`,
"syntax error",
},
{
`package p; import . "x`,
"syntax error",
},
{
`package p; import (`,
"syntax error",
},
{
`package p; import ("`,
"syntax error",
},
{
`package p; import ("x`,
"syntax error",
},
{
`package p; import ("x"`,
"syntax error",
},
}
func TestReadFailures(t *testing.T) {
// Errors should be reported (true arg to readImports).
testRead(t, readFailuresTests, func(r io.Reader) ([]byte, error) { return ReadImports(r, true, nil) })
}
func TestReadFailuresIgnored(t *testing.T) {
// Syntax errors should not be reported (false arg to readImports).
// Instead, entire file should be the output and no error.
// Convert tests not to return syntax errors.
tests := make([]readTest, len(readFailuresTests))
copy(tests, readFailuresTests)
for i := range tests {
tt := &tests[i]
if !strings.Contains(tt.err, "NUL") {
tt.err = ""
}
}
testRead(t, tests, func(r io.Reader) ([]byte, error) { return ReadImports(r, false, nil) })
}
|
imports
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/imports/scan_test.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package imports
import (
"internal/testenv"
"path/filepath"
"reflect"
"runtime"
"testing"
)
func TestScan(t *testing.T) {
testenv.MustHaveGoBuild(t)
imports, testImports, err := ScanDir(filepath.Join(runtime.GOROOT(), "src/encoding/json"), Tags())
if err != nil {
t.Fatal(err)
}
foundBase64 := false
for _, p := range imports {
if p == "encoding/base64" {
foundBase64 = true
}
if p == "encoding/binary" {
// A dependency but not an import
t.Errorf("json reported as importing encoding/binary but does not")
}
if p == "net/http" {
// A test import but not an import
t.Errorf("json reported as importing encoding/binary but does not")
}
}
if !foundBase64 {
t.Errorf("json missing import encoding/base64 (%q)", imports)
}
foundHTTP := false
for _, p := range testImports {
if p == "net/http" {
foundHTTP = true
}
if p == "unicode/utf16" {
// A package import but not a test import
t.Errorf("json reported as test-importing unicode/utf16 but does not")
}
}
if !foundHTTP {
t.Errorf("json missing test import net/http (%q)", testImports)
}
}
func TestScanStar(t *testing.T) {
testenv.MustHaveGoBuild(t)
imports, _, err := ScanDir("testdata/import1", map[string]bool{"*": true})
if err != nil {
t.Fatal(err)
}
want := []string{"import1", "import2", "import3", "import4"}
if !reflect.DeepEqual(imports, want) {
t.Errorf("ScanDir testdata/import1:\nhave %v\nwant %v", imports, want)
}
}
|
imports
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/imports/read.go
|
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copied from Go distribution src/go/build/read.go.
package imports
import (
"bufio"
"errors"
"io"
"unicode/utf8"
)
type importReader struct {
b *bufio.Reader
buf []byte
peek byte
err error
eof bool
nerr int
}
func isIdent(c byte) bool {
return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '_' || c >= utf8.RuneSelf
}
var (
errSyntax = errors.New("syntax error")
errNUL = errors.New("unexpected NUL in input")
)
// syntaxError records a syntax error, but only if an I/O error has not already been recorded.
func (r *importReader) syntaxError() {
if r.err == nil {
r.err = errSyntax
}
}
// readByte reads the next byte from the input, saves it in buf, and returns it.
// If an error occurs, readByte records the error in r.err and returns 0.
func (r *importReader) readByte() byte {
c, err := r.b.ReadByte()
if err == nil {
r.buf = append(r.buf, c)
if c == 0 {
err = errNUL
}
}
if err != nil {
if err == io.EOF {
r.eof = true
} else if r.err == nil {
r.err = err
}
c = 0
}
return c
}
// peekByte returns the next byte from the input reader but does not advance beyond it.
// If skipSpace is set, peekByte skips leading spaces and comments.
func (r *importReader) peekByte(skipSpace bool) byte {
if r.err != nil {
if r.nerr++; r.nerr > 10000 {
panic("go/build: import reader looping")
}
return 0
}
// Use r.peek as first input byte.
// Don't just return r.peek here: it might have been left by peekByte(false)
// and this might be peekByte(true).
c := r.peek
if c == 0 {
c = r.readByte()
}
for r.err == nil && !r.eof {
if skipSpace {
// For the purposes of this reader, semicolons are never necessary to
// understand the input and are treated as spaces.
switch c {
case ' ', '\f', '\t', '\r', '\n', ';':
c = r.readByte()
continue
case '/':
c = r.readByte()
if c == '/' {
for c != '\n' && r.err == nil && !r.eof {
c = r.readByte()
}
} else if c == '*' {
var c1 byte
for (c != '*' || c1 != '/') && r.err == nil {
if r.eof {
r.syntaxError()
}
c, c1 = c1, r.readByte()
}
} else {
r.syntaxError()
}
c = r.readByte()
continue
}
}
break
}
r.peek = c
return r.peek
}
// nextByte is like peekByte but advances beyond the returned byte.
func (r *importReader) nextByte(skipSpace bool) byte {
c := r.peekByte(skipSpace)
r.peek = 0
return c
}
// readKeyword reads the given keyword from the input.
// If the keyword is not present, readKeyword records a syntax error.
func (r *importReader) readKeyword(kw string) {
r.peekByte(true)
for i := 0; i < len(kw); i++ {
if r.nextByte(false) != kw[i] {
r.syntaxError()
return
}
}
if isIdent(r.peekByte(false)) {
r.syntaxError()
}
}
// readIdent reads an identifier from the input.
// If an identifier is not present, readIdent records a syntax error.
func (r *importReader) readIdent() {
c := r.peekByte(true)
if !isIdent(c) {
r.syntaxError()
return
}
for isIdent(r.peekByte(false)) {
r.peek = 0
}
}
// readString reads a quoted string literal from the input.
// If an identifier is not present, readString records a syntax error.
func (r *importReader) readString(save *[]string) {
switch r.nextByte(true) {
case '`':
start := len(r.buf) - 1
for r.err == nil {
if r.nextByte(false) == '`' {
if save != nil {
*save = append(*save, string(r.buf[start:]))
}
break
}
if r.eof {
r.syntaxError()
}
}
case '"':
start := len(r.buf) - 1
for r.err == nil {
c := r.nextByte(false)
if c == '"' {
if save != nil {
*save = append(*save, string(r.buf[start:]))
}
break
}
if r.eof || c == '\n' {
r.syntaxError()
}
if c == '\\' {
r.nextByte(false)
}
}
default:
r.syntaxError()
}
}
// readImport reads an import clause - optional identifier followed by quoted string -
// from the input.
func (r *importReader) readImport(imports *[]string) {
c := r.peekByte(true)
if c == '.' {
r.peek = 0
} else if isIdent(c) {
r.readIdent()
}
r.readString(imports)
}
// ReadComments is like ioutil.ReadAll, except that it only reads the leading
// block of comments in the file.
func ReadComments(f io.Reader) ([]byte, error) {
r := &importReader{b: bufio.NewReader(f)}
r.peekByte(true)
if r.err == nil && !r.eof {
// Didn't reach EOF, so must have found a non-space byte. Remove it.
r.buf = r.buf[:len(r.buf)-1]
}
return r.buf, r.err
}
// ReadImports is like ioutil.ReadAll, except that it expects a Go file as input
// and stops reading the input once the imports have completed.
func ReadImports(f io.Reader, reportSyntaxError bool, imports *[]string) ([]byte, error) {
r := &importReader{b: bufio.NewReader(f)}
r.readKeyword("package")
r.readIdent()
for r.peekByte(true) == 'i' {
r.readKeyword("import")
if r.peekByte(true) == '(' {
r.nextByte(false)
for r.peekByte(true) != ')' && r.err == nil {
r.readImport(imports)
}
r.nextByte(false)
} else {
r.readImport(imports)
}
}
// If we stopped successfully before EOF, we read a byte that told us we were done.
// Return all but that last byte, which would cause a syntax error if we let it through.
if r.err == nil && !r.eof {
return r.buf[:len(r.buf)-1], nil
}
// If we stopped for a syntax error, consume the whole file so that
// we are sure we don't change the errors that go/parser returns.
if r.err == errSyntax && !reportSyntaxError {
r.err = nil
for r.err == nil && !r.eof {
r.readByte()
}
}
return r.buf, r.err
}
|
import1
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/imports/testdata/import1/x_darwin.go
|
package xxxx
import "import3"
|
import1
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/imports/testdata/import1/x.go
|
package x
import "import1"
|
import1
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/imports/testdata/import1/x1.go
|
// +build blahblh
// +build linux
// +build !linux
// +build windows
// +build darwin
package x
import "import4"
|
import1
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/imports/testdata/import1/x_windows.go
|
package x
import "import2"
|
modfetch
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/fetch.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package modfetch
import (
"archive/zip"
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"cmd/go/internal/dirhash"
"cmd/go/internal/module"
"cmd/go/internal/par"
)
var downloadCache par.Cache
// Download downloads the specific module version to the
// local download cache and returns the name of the directory
// corresponding to the root of the module's file tree.
func Download(mod module.Version) (dir string, err error) {
if PkgMod == "" {
// Do not download to current directory.
return "", fmt.Errorf("missing modfetch.PkgMod")
}
// The par.Cache here avoids duplicate work but also
// avoids conflicts from simultaneous calls by multiple goroutines
// for the same version.
type cached struct {
dir string
err error
}
c := downloadCache.Do(mod, func() interface{} {
dir, err := DownloadDir(mod)
if err != nil {
return cached{"", err}
}
if files, _ := ioutil.ReadDir(dir); len(files) == 0 {
zipfile, err := DownloadZip(mod)
if err != nil {
return cached{"", err}
}
modpath := mod.Path + "@" + mod.Version
if err := Unzip(dir, zipfile, modpath, 0); err != nil {
fmt.Fprintf(os.Stderr, "-> %s\n", err)
return cached{"", err}
}
}
checkSum(mod)
return cached{dir, nil}
}).(cached)
return c.dir, c.err
}
var downloadZipCache par.Cache
// DownloadZip downloads the specific module version to the
// local zip cache and returns the name of the zip file.
func DownloadZip(mod module.Version) (zipfile string, err error) {
// The par.Cache here avoids duplicate work but also
// avoids conflicts from simultaneous calls by multiple goroutines
// for the same version.
type cached struct {
zipfile string
err error
}
c := downloadZipCache.Do(mod, func() interface{} {
zipfile, err := CachePath(mod, "zip")
if err != nil {
return cached{"", err}
}
if _, err := os.Stat(zipfile); err == nil {
// Use it.
// This should only happen if the mod/cache directory is preinitialized
// or if pkg/mod/path was removed but not pkg/mod/cache/download.
if cfg.CmdName != "mod download" {
fmt.Fprintf(os.Stderr, "go: extracting %s %s\n", mod.Path, mod.Version)
}
} else {
if err := os.MkdirAll(filepath.Dir(zipfile), 0777); err != nil {
return cached{"", err}
}
if cfg.CmdName != "mod download" {
fmt.Fprintf(os.Stderr, "go: downloading %s %s\n", mod.Path, mod.Version)
}
if err := downloadZip(mod, zipfile); err != nil {
return cached{"", err}
}
}
return cached{zipfile, nil}
}).(cached)
return c.zipfile, c.err
}
func downloadZip(mod module.Version, target string) error {
repo, err := Lookup(mod.Path)
if err != nil {
return err
}
tmpfile, err := repo.Zip(mod.Version, os.TempDir())
if err != nil {
return err
}
defer os.Remove(tmpfile)
// Double-check zip file looks OK.
z, err := zip.OpenReader(tmpfile)
if err != nil {
return err
}
prefix := mod.Path + "@" + mod.Version
for _, f := range z.File {
if !strings.HasPrefix(f.Name, prefix) {
z.Close()
return fmt.Errorf("zip for %s has unexpected file %s", prefix[:len(prefix)-1], f.Name)
}
}
z.Close()
hash, err := dirhash.HashZip(tmpfile, dirhash.DefaultHash)
if err != nil {
return err
}
checkOneSum(mod, hash) // check before installing the zip file
r, err := os.Open(tmpfile)
if err != nil {
return err
}
defer r.Close()
w, err := os.Create(target)
if err != nil {
return err
}
if _, err := io.Copy(w, r); err != nil {
w.Close()
return fmt.Errorf("copying: %v", err)
}
if err := w.Close(); err != nil {
return err
}
return ioutil.WriteFile(target+"hash", []byte(hash), 0666)
}
var GoSumFile string // path to go.sum; set by package modload
var goSum struct {
mu sync.Mutex
m map[module.Version][]string // content of go.sum file (+ go.modverify if present)
enabled bool // whether to use go.sum at all
modverify string // path to go.modverify, to be deleted
}
// initGoSum initializes the go.sum data.
// It reports whether use of go.sum is now enabled.
// The goSum lock must be held.
func initGoSum() bool {
if GoSumFile == "" {
return false
}
if goSum.m != nil {
return true
}
goSum.m = make(map[module.Version][]string)
data, err := ioutil.ReadFile(GoSumFile)
if err != nil && !os.IsNotExist(err) {
base.Fatalf("go: %v", err)
}
goSum.enabled = true
readGoSum(GoSumFile, data)
// Add old go.modverify file.
// We'll delete go.modverify in WriteGoSum.
alt := strings.TrimSuffix(GoSumFile, ".sum") + ".modverify"
if data, err := ioutil.ReadFile(alt); err == nil {
readGoSum(alt, data)
goSum.modverify = alt
}
return true
}
// emptyGoModHash is the hash of a 1-file tree containing a 0-length go.mod.
// A bug caused us to write these into go.sum files for non-modules.
// We detect and remove them.
const emptyGoModHash = "h1:G7mAYYxgmS0lVkHyy2hEOLQCFB0DlQFTMLWggykrydY="
// readGoSum parses data, which is the content of file,
// and adds it to goSum.m. The goSum lock must be held.
func readGoSum(file string, data []byte) {
lineno := 0
for len(data) > 0 {
var line []byte
lineno++
i := bytes.IndexByte(data, '\n')
if i < 0 {
line, data = data, nil
} else {
line, data = data[:i], data[i+1:]
}
f := strings.Fields(string(line))
if len(f) == 0 {
// blank line; skip it
continue
}
if len(f) != 3 {
base.Fatalf("go: malformed go.sum:\n%s:%d: wrong number of fields %v", file, lineno, len(f))
}
if f[2] == emptyGoModHash {
// Old bug; drop it.
continue
}
mod := module.Version{Path: f[0], Version: f[1]}
goSum.m[mod] = append(goSum.m[mod], f[2])
}
}
// checkSum checks the given module's checksum.
func checkSum(mod module.Version) {
if PkgMod == "" {
// Do not use current directory.
return
}
// Do the file I/O before acquiring the go.sum lock.
ziphash, err := CachePath(mod, "ziphash")
if err != nil {
base.Fatalf("go: verifying %s@%s: %v", mod.Path, mod.Version, err)
}
data, err := ioutil.ReadFile(ziphash)
if err != nil {
if os.IsNotExist(err) {
// This can happen if someone does rm -rf GOPATH/src/cache/download. So it goes.
return
}
base.Fatalf("go: verifying %s@%s: %v", mod.Path, mod.Version, err)
}
h := strings.TrimSpace(string(data))
if !strings.HasPrefix(h, "h1:") {
base.Fatalf("go: verifying %s@%s: unexpected ziphash: %q", mod.Path, mod.Version, h)
}
checkOneSum(mod, h)
}
// goModSum returns the checksum for the go.mod contents.
func goModSum(data []byte) (string, error) {
return dirhash.Hash1([]string{"go.mod"}, func(string) (io.ReadCloser, error) {
return ioutil.NopCloser(bytes.NewReader(data)), nil
})
}
// checkGoMod checks the given module's go.mod checksum;
// data is the go.mod content.
func checkGoMod(path, version string, data []byte) {
h, err := goModSum(data)
if err != nil {
base.Fatalf("go: verifying %s %s go.mod: %v", path, version, err)
}
checkOneSum(module.Version{Path: path, Version: version + "/go.mod"}, h)
}
// checkOneSum checks that the recorded hash for mod is h.
func checkOneSum(mod module.Version, h string) {
goSum.mu.Lock()
defer goSum.mu.Unlock()
if !initGoSum() {
return
}
for _, vh := range goSum.m[mod] {
if h == vh {
return
}
if strings.HasPrefix(vh, "h1:") {
base.Fatalf("go: verifying %s@%s: checksum mismatch\n\tdownloaded: %v\n\tgo.sum: %v", mod.Path, mod.Version, h, vh)
}
}
if len(goSum.m[mod]) > 0 {
fmt.Fprintf(os.Stderr, "warning: verifying %s@%s: unknown hashes in go.sum: %v; adding %v", mod.Path, mod.Version, strings.Join(goSum.m[mod], ", "), h)
}
goSum.m[mod] = append(goSum.m[mod], h)
}
// Sum returns the checksum for the downloaded copy of the given module,
// if present in the download cache.
func Sum(mod module.Version) string {
if PkgMod == "" {
// Do not use current directory.
return ""
}
ziphash, err := CachePath(mod, "ziphash")
if err != nil {
return ""
}
data, err := ioutil.ReadFile(ziphash)
if err != nil {
return ""
}
return strings.TrimSpace(string(data))
}
// WriteGoSum writes the go.sum file if it needs to be updated.
func WriteGoSum() {
goSum.mu.Lock()
defer goSum.mu.Unlock()
if !initGoSum() {
return
}
var mods []module.Version
for m := range goSum.m {
mods = append(mods, m)
}
module.Sort(mods)
var buf bytes.Buffer
for _, m := range mods {
list := goSum.m[m]
sort.Strings(list)
for _, h := range list {
fmt.Fprintf(&buf, "%s %s %s\n", m.Path, m.Version, h)
}
}
data, _ := ioutil.ReadFile(GoSumFile)
if !bytes.Equal(data, buf.Bytes()) {
if err := ioutil.WriteFile(GoSumFile, buf.Bytes(), 0666); err != nil {
base.Fatalf("go: writing go.sum: %v", err)
}
}
if goSum.modverify != "" {
os.Remove(goSum.modverify)
}
}
// TrimGoSum trims go.sum to contain only the modules for which keep[m] is true.
func TrimGoSum(keep map[module.Version]bool) {
goSum.mu.Lock()
defer goSum.mu.Unlock()
if !initGoSum() {
return
}
for m := range goSum.m {
// If we're keeping x@v we also keep x@v/go.mod.
// Map x@v/go.mod back to x@v for the keep lookup.
noGoMod := module.Version{Path: m.Path, Version: strings.TrimSuffix(m.Version, "/go.mod")}
if !keep[m] && !keep[noGoMod] {
delete(goSum.m, m)
}
}
}
|
modfetch
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/repo.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package modfetch
import (
"fmt"
"os"
"sort"
"time"
"cmd/go/internal/cfg"
"cmd/go/internal/get"
"cmd/go/internal/modfetch/codehost"
"cmd/go/internal/par"
"cmd/go/internal/semver"
web "cmd/go/internal/web"
)
const traceRepo = false // trace all repo actions, for debugging
// A Repo represents a repository storing all versions of a single module.
// It must be safe for simultaneous use by multiple goroutines.
type Repo interface {
// ModulePath returns the module path.
ModulePath() string
// Versions lists all known versions with the given prefix.
// Pseudo-versions are not included.
// Versions should be returned sorted in semver order
// (implementations can use SortVersions).
Versions(prefix string) (tags []string, err error)
// Stat returns information about the revision rev.
// A revision can be any identifier known to the underlying service:
// commit hash, branch, tag, and so on.
Stat(rev string) (*RevInfo, error)
// Latest returns the latest revision on the default branch,
// whatever that means in the underlying source code repository.
// It is only used when there are no tagged versions.
Latest() (*RevInfo, error)
// GoMod returns the go.mod file for the given version.
GoMod(version string) (data []byte, err error)
// Zip downloads a zip file for the given version
// to a new file in a given temporary directory.
// It returns the name of the new file.
// The caller should remove the file when finished with it.
Zip(version, tmpdir string) (tmpfile string, err error)
}
// A Rev describes a single revision in a module repository.
type RevInfo struct {
Version string // version string
Time time.Time // commit time
// These fields are used for Stat of arbitrary rev,
// but they are not recorded when talking about module versions.
Name string `json:"-"` // complete ID in underlying repository
Short string `json:"-"` // shortened ID, for use in pseudo-version
}
// Re: module paths, import paths, repository roots, and lookups
//
// A module is a collection of Go packages stored in a file tree
// with a go.mod file at the root of the tree.
// The go.mod defines the module path, which is the import path
// corresponding to the root of the file tree.
// The import path of a directory within that file tree is the module path
// joined with the name of the subdirectory relative to the root.
//
// For example, the module with path rsc.io/qr corresponds to the
// file tree in the repository https://github.com/rsc/qr.
// That file tree has a go.mod that says "module rsc.io/qr".
// The package in the root directory has import path "rsc.io/qr".
// The package in the gf256 subdirectory has import path "rsc.io/qr/gf256".
// In this example, "rsc.io/qr" is both a module path and an import path.
// But "rsc.io/qr/gf256" is only an import path, not a module path:
// it names an importable package, but not a module.
//
// As a special case to incorporate code written before modules were
// introduced, if a path p resolves using the pre-module "go get" lookup
// to the root of a source code repository without a go.mod file,
// that repository is treated as if it had a go.mod in its root directory
// declaring module path p. (The go.mod is further considered to
// contain requirements corresponding to any legacy version
// tracking format such as Gopkg.lock, vendor/vendor.conf, and so on.)
//
// The presentation so far ignores the fact that a source code repository
// has many different versions of a file tree, and those versions may
// differ in whether a particular go.mod exists and what it contains.
// In fact there is a well-defined mapping only from a module path, version
// pair - often written path@version - to a particular file tree.
// For example rsc.io/qr@v0.1.0 depends on the "implicit go.mod at root of
// repository" rule, while rsc.io/qr@v0.2.0 has an explicit go.mod.
// Because the "go get" import paths rsc.io/qr and github.com/rsc/qr
// both redirect to the Git repository https://github.com/rsc/qr,
// github.com/rsc/qr@v0.1.0 is the same file tree as rsc.io/qr@v0.1.0
// but a different module (a different name). In contrast, since v0.2.0
// of that repository has an explicit go.mod that declares path rsc.io/qr,
// github.com/rsc/qr@v0.2.0 is an invalid module path, version pair.
// Before modules, import comments would have had the same effect.
//
// The set of import paths associated with a given module path is
// clearly not fixed: at the least, new directories with new import paths
// can always be added. But another potential operation is to split a
// subtree out of a module into its own module. If done carefully,
// this operation can be done while preserving compatibility for clients.
// For example, suppose that we want to split rsc.io/qr/gf256 into its
// own module, so that there would be two modules rsc.io/qr and rsc.io/qr/gf256.
// Then we can simultaneously issue rsc.io/qr v0.3.0 (dropping the gf256 subdirectory)
// and rsc.io/qr/gf256 v0.1.0, including in their respective go.mod
// cyclic requirements pointing at each other: rsc.io/qr v0.3.0 requires
// rsc.io/qr/gf256 v0.1.0 and vice versa. Then a build can be
// using an older rsc.io/qr module that includes the gf256 package, but if
// it adds a requirement on either the newer rsc.io/qr or the newer
// rsc.io/qr/gf256 module, it will automatically add the requirement
// on the complementary half, ensuring both that rsc.io/qr/gf256 is
// available for importing by the build and also that it is only defined
// by a single module. The gf256 package could move back into the
// original by another simultaneous release of rsc.io/qr v0.4.0 including
// the gf256 subdirectory and an rsc.io/qr/gf256 v0.2.0 with no code
// in its root directory, along with a new requirement cycle.
// The ability to shift module boundaries in this way is expected to be
// important in large-scale program refactorings, similar to the ones
// described in https://talks.golang.org/2016/refactor.article.
//
// The possibility of shifting module boundaries reemphasizes
// that you must know both the module path and its version
// to determine the set of packages provided directly by that module.
//
// On top of all this, it is possible for a single code repository
// to contain multiple modules, either in branches or subdirectories,
// as a limited kind of monorepo. For example rsc.io/qr/v2,
// the v2.x.x continuation of rsc.io/qr, is expected to be found
// in v2-tagged commits in https://github.com/rsc/qr, either
// in the root or in a v2 subdirectory, disambiguated by go.mod.
// Again the precise file tree corresponding to a module
// depends on which version we are considering.
//
// It is also possible for the underlying repository to change over time,
// without changing the module path. If I copy the github repo over
// to https://bitbucket.org/rsc/qr and update https://rsc.io/qr?go-get=1,
// then clients of all versions should start fetching from bitbucket
// instead of github. That is, in contrast to the exact file tree,
// the location of the source code repository associated with a module path
// does not depend on the module version. (This is by design, as the whole
// point of these redirects is to allow package authors to establish a stable
// name that can be updated as code moves from one service to another.)
//
// All of this is important background for the lookup APIs defined in this
// file.
//
// The Lookup function takes a module path and returns a Repo representing
// that module path. Lookup can do only a little with the path alone.
// It can check that the path is well-formed (see semver.CheckPath)
// and it can check that the path can be resolved to a target repository.
// To avoid version control access except when absolutely necessary,
// Lookup does not attempt to connect to the repository itself.
//
// The Import function takes an import path found in source code and
// determines which module to add to the requirement list to satisfy
// that import. It checks successive truncations of the import path
// to determine possible modules and stops when it finds a module
// in which the latest version satisfies the import path.
//
// The ImportRepoRev function is a variant of Import which is limited
// to code in a source code repository at a particular revision identifier
// (usually a commit hash or source code repository tag, not necessarily
// a module version).
// ImportRepoRev is used when converting legacy dependency requirements
// from older systems into go.mod files. Those older systems worked
// at either package or repository granularity, and most of the time they
// recorded commit hashes, not tagged versions.
var lookupCache par.Cache
// Lookup returns the module with the given module path.
// A successful return does not guarantee that the module
// has any defined versions.
func Lookup(path string) (Repo, error) {
if traceRepo {
defer logCall("Lookup(%q)", path)()
}
type cached struct {
r Repo
err error
}
c := lookupCache.Do(path, func() interface{} {
r, err := lookup(path)
if err == nil {
if traceRepo {
r = newLoggingRepo(r)
}
r = newCachingRepo(r)
}
return cached{r, err}
}).(cached)
return c.r, c.err
}
// lookup returns the module with the given module path.
func lookup(path string) (r Repo, err error) {
if cfg.BuildMod == "vendor" {
return nil, fmt.Errorf("module lookup disabled by -mod=%s", cfg.BuildMod)
}
if proxyURL == "off" {
return nil, fmt.Errorf("module lookup disabled by GOPROXY=%s", proxyURL)
}
if proxyURL != "" && proxyURL != "direct" {
return lookupProxy(path)
}
security := web.Secure
if get.Insecure {
security = web.Insecure
}
rr, err := get.RepoRootForImportPath(path, get.PreferMod, security)
if err != nil {
// We don't know where to find code for a module with this path.
return nil, err
}
if rr.VCS == "mod" {
// Fetch module from proxy with base URL rr.Repo.
return newProxyRepo(rr.Repo, path)
}
code, err := lookupCodeRepo(rr)
if err != nil {
return nil, err
}
return newCodeRepo(code, rr.Root, path)
}
func lookupCodeRepo(rr *get.RepoRoot) (codehost.Repo, error) {
code, err := codehost.NewRepo(rr.VCS, rr.Repo)
if err != nil {
if _, ok := err.(*codehost.VCSError); ok {
return nil, err
}
return nil, fmt.Errorf("lookup %s: %v", rr.Root, err)
}
return code, nil
}
// ImportRepoRev returns the module and version to use to access
// the given import path loaded from the source code repository that
// the original "go get" would have used, at the specific repository revision
// (typically a commit hash, but possibly also a source control tag).
func ImportRepoRev(path, rev string) (Repo, *RevInfo, error) {
if cfg.BuildMod == "vendor" || cfg.BuildMod == "readonly" {
return nil, nil, fmt.Errorf("repo version lookup disabled by -mod=%s", cfg.BuildMod)
}
// Note: Because we are converting a code reference from a legacy
// version control system, we ignore meta tags about modules
// and use only direct source control entries (get.IgnoreMod).
security := web.Secure
if get.Insecure {
security = web.Insecure
}
rr, err := get.RepoRootForImportPath(path, get.IgnoreMod, security)
if err != nil {
return nil, nil, err
}
code, err := lookupCodeRepo(rr)
if err != nil {
return nil, nil, err
}
revInfo, err := code.Stat(rev)
if err != nil {
return nil, nil, err
}
// TODO: Look in repo to find path, check for go.mod files.
// For now we're just assuming rr.Root is the module path,
// which is true in the absence of go.mod files.
repo, err := newCodeRepo(code, rr.Root, rr.Root)
if err != nil {
return nil, nil, err
}
info, err := repo.(*codeRepo).convert(revInfo, "")
if err != nil {
return nil, nil, err
}
return repo, info, nil
}
func SortVersions(list []string) {
sort.Slice(list, func(i, j int) bool {
cmp := semver.Compare(list[i], list[j])
if cmp != 0 {
return cmp < 0
}
return list[i] < list[j]
})
}
// A loggingRepo is a wrapper around an underlying Repo
// that prints a log message at the start and end of each call.
// It can be inserted when debugging.
type loggingRepo struct {
r Repo
}
func newLoggingRepo(r Repo) *loggingRepo {
return &loggingRepo{r}
}
// logCall prints a log message using format and args and then
// also returns a function that will print the same message again,
// along with the elapsed time.
// Typical usage is:
//
// defer logCall("hello %s", arg)()
//
// Note the final ().
func logCall(format string, args ...interface{}) func() {
start := time.Now()
fmt.Fprintf(os.Stderr, "+++ %s\n", fmt.Sprintf(format, args...))
return func() {
fmt.Fprintf(os.Stderr, "%.3fs %s\n", time.Since(start).Seconds(), fmt.Sprintf(format, args...))
}
}
func (l *loggingRepo) ModulePath() string {
return l.r.ModulePath()
}
func (l *loggingRepo) Versions(prefix string) (tags []string, err error) {
defer logCall("Repo[%s]: Versions(%q)", l.r.ModulePath(), prefix)()
return l.r.Versions(prefix)
}
func (l *loggingRepo) Stat(rev string) (*RevInfo, error) {
defer logCall("Repo[%s]: Stat(%q)", l.r.ModulePath(), rev)()
return l.r.Stat(rev)
}
func (l *loggingRepo) Latest() (*RevInfo, error) {
defer logCall("Repo[%s]: Latest()", l.r.ModulePath())()
return l.r.Latest()
}
func (l *loggingRepo) GoMod(version string) ([]byte, error) {
defer logCall("Repo[%s]: GoMod(%q)", l.r.ModulePath(), version)()
return l.r.GoMod(version)
}
func (l *loggingRepo) Zip(version, tmpdir string) (string, error) {
defer logCall("Repo[%s]: Zip(%q, %q)", l.r.ModulePath(), version, tmpdir)()
return l.r.Zip(version, tmpdir)
}
|
modfetch
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/pseudo_test.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package modfetch
import (
"testing"
"time"
)
var pseudoTests = []struct {
major string
older string
version string
}{
{"", "", "v0.0.0-20060102150405-hash"},
{"v0", "", "v0.0.0-20060102150405-hash"},
{"v1", "", "v1.0.0-20060102150405-hash"},
{"v2", "", "v2.0.0-20060102150405-hash"},
{"unused", "v0.0.0", "v0.0.1-0.20060102150405-hash"},
{"unused", "v1.2.3", "v1.2.4-0.20060102150405-hash"},
{"unused", "v1.2.99999999999999999", "v1.2.100000000000000000-0.20060102150405-hash"},
{"unused", "v1.2.3-pre", "v1.2.3-pre.0.20060102150405-hash"},
{"unused", "v1.3.0-pre", "v1.3.0-pre.0.20060102150405-hash"},
}
var pseudoTime = time.Date(2006, 1, 2, 15, 4, 5, 0, time.UTC)
func TestPseudoVersion(t *testing.T) {
for _, tt := range pseudoTests {
v := PseudoVersion(tt.major, tt.older, pseudoTime, "hash")
if v != tt.version {
t.Errorf("PseudoVersion(%q, %q, ...) = %v, want %v", tt.major, tt.older, v, tt.version)
}
}
}
func TestIsPseudoVersion(t *testing.T) {
for _, tt := range pseudoTests {
if !IsPseudoVersion(tt.version) {
t.Errorf("IsPseudoVersion(%q) = false, want true", tt.version)
}
if IsPseudoVersion(tt.older) {
t.Errorf("IsPseudoVersion(%q) = true, want false", tt.older)
}
}
}
func TestPseudoVersionTime(t *testing.T) {
for _, tt := range pseudoTests {
tm, err := PseudoVersionTime(tt.version)
if tm != pseudoTime || err != nil {
t.Errorf("PseudoVersionTime(%q) = %v, %v, want %v, nil", tt.version, tm.Format(time.RFC3339), err, pseudoTime.Format(time.RFC3339))
}
tm, err = PseudoVersionTime(tt.older)
if tm != (time.Time{}) || err == nil {
t.Errorf("PseudoVersionTime(%q) = %v, %v, want %v, error", tt.older, tm.Format(time.RFC3339), err, time.Time{}.Format(time.RFC3339))
}
}
}
func TestPseudoVersionRev(t *testing.T) {
for _, tt := range pseudoTests {
rev, err := PseudoVersionRev(tt.version)
if rev != "hash" || err != nil {
t.Errorf("PseudoVersionRev(%q) = %q, %v, want %q, nil", tt.older, rev, err, "hash")
}
rev, err = PseudoVersionRev(tt.older)
if rev != "" || err == nil {
t.Errorf("PseudoVersionRev(%q) = %q, %v, want %q, error", tt.older, rev, err, "")
}
}
}
|
modfetch
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/coderepo_test.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package modfetch
import (
"archive/zip"
"internal/testenv"
"io"
"io/ioutil"
"log"
"os"
"reflect"
"strings"
"testing"
"time"
"cmd/go/internal/modfetch/codehost"
)
func TestMain(m *testing.M) {
os.Exit(testMain(m))
}
func testMain(m *testing.M) int {
dir, err := ioutil.TempDir("", "gitrepo-test-")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
codehost.WorkRoot = dir
return m.Run()
}
const (
vgotest1git = "github.com/rsc/vgotest1"
vgotest1hg = "vcs-test.golang.org/hg/vgotest1.hg"
)
var altVgotests = []string{
vgotest1hg,
}
var codeRepoTests = []struct {
path string
lookerr string
mpath string
rev string
err string
version string
name string
short string
time time.Time
gomod string
gomoderr string
zip []string
ziperr string
}{
{
path: "github.com/rsc/vgotest1",
rev: "v0.0.0",
version: "v0.0.0",
name: "80d85c5d4d17598a0e9055e7c175a32b415d6128",
short: "80d85c5d4d17",
time: time.Date(2018, 2, 19, 23, 10, 6, 0, time.UTC),
zip: []string{
"LICENSE",
"README.md",
"pkg/p.go",
},
},
{
path: "github.com/rsc/vgotest1",
rev: "v1.0.0",
version: "v1.0.0",
name: "80d85c5d4d17598a0e9055e7c175a32b415d6128",
short: "80d85c5d4d17",
time: time.Date(2018, 2, 19, 23, 10, 6, 0, time.UTC),
zip: []string{
"LICENSE",
"README.md",
"pkg/p.go",
},
},
{
path: "github.com/rsc/vgotest1/v2",
rev: "v2.0.0",
version: "v2.0.0",
name: "45f53230a74ad275c7127e117ac46914c8126160",
short: "45f53230a74a",
time: time.Date(2018, 7, 19, 1, 21, 27, 0, time.UTC),
ziperr: "missing github.com/rsc/vgotest1/go.mod and .../v2/go.mod at revision v2.0.0",
},
{
path: "github.com/rsc/vgotest1",
rev: "80d85c5",
version: "v1.0.0",
name: "80d85c5d4d17598a0e9055e7c175a32b415d6128",
short: "80d85c5d4d17",
time: time.Date(2018, 2, 19, 23, 10, 6, 0, time.UTC),
zip: []string{
"LICENSE",
"README.md",
"pkg/p.go",
},
},
{
path: "github.com/rsc/vgotest1",
rev: "mytag",
version: "v1.0.0",
name: "80d85c5d4d17598a0e9055e7c175a32b415d6128",
short: "80d85c5d4d17",
time: time.Date(2018, 2, 19, 23, 10, 6, 0, time.UTC),
zip: []string{
"LICENSE",
"README.md",
"pkg/p.go",
},
},
{
path: "github.com/rsc/vgotest1/v2",
rev: "45f53230a",
version: "v2.0.0",
name: "45f53230a74ad275c7127e117ac46914c8126160",
short: "45f53230a74a",
time: time.Date(2018, 7, 19, 1, 21, 27, 0, time.UTC),
gomoderr: "missing github.com/rsc/vgotest1/go.mod and .../v2/go.mod at revision v2.0.0",
ziperr: "missing github.com/rsc/vgotest1/go.mod and .../v2/go.mod at revision v2.0.0",
},
{
path: "github.com/rsc/vgotest1/v54321",
rev: "80d85c5",
version: "v54321.0.0-20180219231006-80d85c5d4d17",
name: "80d85c5d4d17598a0e9055e7c175a32b415d6128",
short: "80d85c5d4d17",
time: time.Date(2018, 2, 19, 23, 10, 6, 0, time.UTC),
ziperr: "missing github.com/rsc/vgotest1/go.mod and .../v54321/go.mod at revision 80d85c5d4d17",
},
{
path: "github.com/rsc/vgotest1/submod",
rev: "v1.0.0",
err: "unknown revision submod/v1.0.0",
},
{
path: "github.com/rsc/vgotest1/submod",
rev: "v1.0.3",
err: "unknown revision submod/v1.0.3",
},
{
path: "github.com/rsc/vgotest1/submod",
rev: "v1.0.4",
version: "v1.0.4",
name: "8afe2b2efed96e0880ecd2a69b98a53b8c2738b6",
short: "8afe2b2efed9",
time: time.Date(2018, 2, 19, 23, 12, 7, 0, time.UTC),
gomod: "module \"github.com/vgotest1/submod\" // submod/go.mod\n",
zip: []string{
"go.mod",
"pkg/p.go",
"LICENSE",
},
},
{
path: "github.com/rsc/vgotest1",
rev: "v1.1.0",
version: "v1.1.0",
name: "b769f2de407a4db81af9c5de0a06016d60d2ea09",
short: "b769f2de407a",
time: time.Date(2018, 2, 19, 23, 13, 36, 0, time.UTC),
gomod: "module \"github.com/rsc/vgotest1\" // root go.mod\nrequire \"github.com/rsc/vgotest1/submod\" v1.0.5\n",
zip: []string{
"LICENSE",
"README.md",
"go.mod",
"pkg/p.go",
},
},
{
path: "github.com/rsc/vgotest1/v2",
rev: "v2.0.1",
version: "v2.0.1",
name: "ea65f87c8f52c15ea68f3bdd9925ef17e20d91e9",
short: "ea65f87c8f52",
time: time.Date(2018, 2, 19, 23, 14, 23, 0, time.UTC),
gomod: "module \"github.com/rsc/vgotest1/v2\" // root go.mod\n",
},
{
path: "github.com/rsc/vgotest1/v2",
rev: "v2.0.3",
version: "v2.0.3",
name: "f18795870fb14388a21ef3ebc1d75911c8694f31",
short: "f18795870fb1",
time: time.Date(2018, 2, 19, 23, 16, 4, 0, time.UTC),
gomoderr: "github.com/rsc/vgotest1/v2/go.mod has non-.../v2 module path \"github.com/rsc/vgotest\" at revision v2.0.3",
},
{
path: "github.com/rsc/vgotest1/v2",
rev: "v2.0.4",
version: "v2.0.4",
name: "1f863feb76bc7029b78b21c5375644838962f88d",
short: "1f863feb76bc",
time: time.Date(2018, 2, 20, 0, 3, 38, 0, time.UTC),
gomoderr: "github.com/rsc/vgotest1/go.mod and .../v2/go.mod both have .../v2 module paths at revision v2.0.4",
},
{
path: "github.com/rsc/vgotest1/v2",
rev: "v2.0.5",
version: "v2.0.5",
name: "2f615117ce481c8efef46e0cc0b4b4dccfac8fea",
short: "2f615117ce48",
time: time.Date(2018, 2, 20, 0, 3, 59, 0, time.UTC),
gomod: "module \"github.com/rsc/vgotest1/v2\" // v2/go.mod\n",
},
{
// redirect to github
path: "rsc.io/quote",
rev: "v1.0.0",
version: "v1.0.0",
name: "f488df80bcdbd3e5bafdc24ad7d1e79e83edd7e6",
short: "f488df80bcdb",
time: time.Date(2018, 2, 14, 0, 45, 20, 0, time.UTC),
gomod: "module \"rsc.io/quote\"\n",
},
{
// redirect to static hosting proxy
path: "swtch.com/testmod",
rev: "v1.0.0",
version: "v1.0.0",
// NO name or short - we intentionally ignore those in the proxy protocol
time: time.Date(1972, 7, 18, 12, 34, 56, 0, time.UTC),
gomod: "module \"swtch.com/testmod\"\n",
},
{
// redirect to googlesource
path: "golang.org/x/text",
rev: "4e4a3210bb",
version: "v0.3.1-0.20180208041248-4e4a3210bb54",
name: "4e4a3210bb54bb31f6ab2cdca2edcc0b50c420c1",
short: "4e4a3210bb54",
time: time.Date(2018, 2, 8, 4, 12, 48, 0, time.UTC),
},
{
path: "github.com/pkg/errors",
rev: "v0.8.0",
version: "v0.8.0",
name: "645ef00459ed84a119197bfb8d8205042c6df63d",
short: "645ef00459ed",
time: time.Date(2016, 9, 29, 1, 48, 1, 0, time.UTC),
},
{
// package in subdirectory - custom domain
// In general we can't reject these definitively in Lookup,
// but gopkg.in is special.
path: "gopkg.in/yaml.v2/abc",
lookerr: "invalid module path \"gopkg.in/yaml.v2/abc\"",
},
{
// package in subdirectory - github
// Because it's a package, Stat should fail entirely.
path: "github.com/rsc/quote/buggy",
rev: "c4d4236f",
err: "missing github.com/rsc/quote/buggy/go.mod at revision c4d4236f9242",
},
{
path: "gopkg.in/yaml.v2",
rev: "d670f940",
version: "v2.0.0",
name: "d670f9405373e636a5a2765eea47fac0c9bc91a4",
short: "d670f9405373",
time: time.Date(2018, 1, 9, 11, 43, 31, 0, time.UTC),
gomod: "module gopkg.in/yaml.v2\n",
},
{
path: "gopkg.in/check.v1",
rev: "20d25e280405",
version: "v1.0.0-20161208181325-20d25e280405",
name: "20d25e2804050c1cd24a7eea1e7a6447dd0e74ec",
short: "20d25e280405",
time: time.Date(2016, 12, 8, 18, 13, 25, 0, time.UTC),
gomod: "module gopkg.in/check.v1\n",
},
{
path: "gopkg.in/yaml.v2",
rev: "v2",
version: "v2.2.1",
name: "5420a8b6744d3b0345ab293f6fcba19c978f1183",
short: "5420a8b6744d",
time: time.Date(2018, 3, 28, 19, 50, 20, 0, time.UTC),
gomod: "module \"gopkg.in/yaml.v2\"\n\nrequire (\n\t\"gopkg.in/check.v1\" v0.0.0-20161208181325-20d25e280405\n)\n",
},
{
path: "vcs-test.golang.org/go/mod/gitrepo1",
rev: "master",
version: "v1.2.4-annotated",
name: "ede458df7cd0fdca520df19a33158086a8a68e81",
short: "ede458df7cd0",
time: time.Date(2018, 4, 17, 19, 43, 22, 0, time.UTC),
gomod: "module vcs-test.golang.org/go/mod/gitrepo1\n",
},
{
path: "gopkg.in/natefinch/lumberjack.v2",
rev: "latest",
version: "v2.0.0-20170531160350-a96e63847dc3",
name: "a96e63847dc3c67d17befa69c303767e2f84e54f",
short: "a96e63847dc3",
time: time.Date(2017, 5, 31, 16, 3, 50, 0, time.UTC),
gomod: "module gopkg.in/natefinch/lumberjack.v2\n",
},
{
path: "gopkg.in/natefinch/lumberjack.v2",
// This repo has a v2.1 tag.
// We only allow semver references to tags that are fully qualified, as in v2.1.0.
// Because we can't record v2.1.0 (the actual tag is v2.1), we record a pseudo-version
// instead, same as if the tag were any other non-version-looking string.
// We use a v2 pseudo-version here because of the .v2 in the path, not because
// of the v2 in the rev.
rev: "v2.1", // non-canonical semantic version turns into pseudo-version
version: "v2.0.0-20170531160350-a96e63847dc3",
name: "a96e63847dc3c67d17befa69c303767e2f84e54f",
short: "a96e63847dc3",
time: time.Date(2017, 5, 31, 16, 3, 50, 0, time.UTC),
gomod: "module gopkg.in/natefinch/lumberjack.v2\n",
},
}
func TestCodeRepo(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tmpdir, err := ioutil.TempDir("", "vgo-modfetch-test-")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpdir)
for _, tt := range codeRepoTests {
f := func(t *testing.T) {
repo, err := Lookup(tt.path)
if tt.lookerr != "" {
if err != nil && err.Error() == tt.lookerr {
return
}
t.Errorf("Lookup(%q): %v, want error %q", tt.path, err, tt.lookerr)
}
if err != nil {
t.Fatalf("Lookup(%q): %v", tt.path, err)
}
if tt.mpath == "" {
tt.mpath = tt.path
}
if mpath := repo.ModulePath(); mpath != tt.mpath {
t.Errorf("repo.ModulePath() = %q, want %q", mpath, tt.mpath)
}
info, err := repo.Stat(tt.rev)
if err != nil {
if tt.err != "" {
if !strings.Contains(err.Error(), tt.err) {
t.Fatalf("repoStat(%q): %v, wanted %q", tt.rev, err, tt.err)
}
return
}
t.Fatalf("repo.Stat(%q): %v", tt.rev, err)
}
if tt.err != "" {
t.Errorf("repo.Stat(%q): success, wanted error", tt.rev)
}
if info.Version != tt.version {
t.Errorf("info.Version = %q, want %q", info.Version, tt.version)
}
if info.Name != tt.name {
t.Errorf("info.Name = %q, want %q", info.Name, tt.name)
}
if info.Short != tt.short {
t.Errorf("info.Short = %q, want %q", info.Short, tt.short)
}
if !info.Time.Equal(tt.time) {
t.Errorf("info.Time = %v, want %v", info.Time, tt.time)
}
if tt.gomod != "" || tt.gomoderr != "" {
data, err := repo.GoMod(tt.version)
if err != nil && tt.gomoderr == "" {
t.Errorf("repo.GoMod(%q): %v", tt.version, err)
} else if err != nil && tt.gomoderr != "" {
if err.Error() != tt.gomoderr {
t.Errorf("repo.GoMod(%q): %v, want %q", tt.version, err, tt.gomoderr)
}
} else if tt.gomoderr != "" {
t.Errorf("repo.GoMod(%q) = %q, want error %q", tt.version, data, tt.gomoderr)
} else if string(data) != tt.gomod {
t.Errorf("repo.GoMod(%q) = %q, want %q", tt.version, data, tt.gomod)
}
}
if tt.zip != nil || tt.ziperr != "" {
zipfile, err := repo.Zip(tt.version, tmpdir)
if err != nil {
if tt.ziperr != "" {
if err.Error() == tt.ziperr {
return
}
t.Fatalf("repo.Zip(%q): %v, want error %q", tt.version, err, tt.ziperr)
}
t.Fatalf("repo.Zip(%q): %v", tt.version, err)
}
if tt.ziperr != "" {
t.Errorf("repo.Zip(%q): success, want error %q", tt.version, tt.ziperr)
}
prefix := tt.path + "@" + tt.version + "/"
z, err := zip.OpenReader(zipfile)
if err != nil {
t.Fatalf("open zip %s: %v", zipfile, err)
}
var names []string
for _, file := range z.File {
if !strings.HasPrefix(file.Name, prefix) {
t.Errorf("zip entry %v does not start with prefix %v", file.Name, prefix)
continue
}
names = append(names, file.Name[len(prefix):])
}
z.Close()
if !reflect.DeepEqual(names, tt.zip) {
t.Fatalf("zip = %v\nwant %v\n", names, tt.zip)
}
}
}
t.Run(strings.Replace(tt.path, "/", "_", -1)+"/"+tt.rev, f)
if strings.HasPrefix(tt.path, vgotest1git) {
for _, alt := range altVgotests {
// Note: Communicating with f through tt; should be cleaned up.
old := tt
tt.path = alt + strings.TrimPrefix(tt.path, vgotest1git)
if strings.HasPrefix(tt.mpath, vgotest1git) {
tt.mpath = alt + strings.TrimPrefix(tt.mpath, vgotest1git)
}
var m map[string]string
if alt == vgotest1hg {
m = hgmap
}
tt.version = remap(tt.version, m)
tt.name = remap(tt.name, m)
tt.short = remap(tt.short, m)
tt.rev = remap(tt.rev, m)
tt.gomoderr = remap(tt.gomoderr, m)
tt.ziperr = remap(tt.ziperr, m)
t.Run(strings.Replace(tt.path, "/", "_", -1)+"/"+tt.rev, f)
tt = old
}
}
}
}
var hgmap = map[string]string{
"github.com/rsc/vgotest1/": "vcs-test.golang.org/hg/vgotest1.hg/",
"f18795870fb14388a21ef3ebc1d75911c8694f31": "a9ad6d1d14eb544f459f446210c7eb3b009807c6",
"ea65f87c8f52c15ea68f3bdd9925ef17e20d91e9": "f1fc0f22021b638d073d31c752847e7bf385def7",
"b769f2de407a4db81af9c5de0a06016d60d2ea09": "92c7eb888b4fac17f1c6bd2e1060a1b881a3b832",
"8afe2b2efed96e0880ecd2a69b98a53b8c2738b6": "4e58084d459ae7e79c8c2264d0e8e9a92eb5cd44",
"2f615117ce481c8efef46e0cc0b4b4dccfac8fea": "879ea98f7743c8eff54f59a918f3a24123d1cf46",
"80d85c5d4d17598a0e9055e7c175a32b415d6128": "e125018e286a4b09061079a81e7b537070b7ff71",
"1f863feb76bc7029b78b21c5375644838962f88d": "bf63880162304a9337477f3858f5b7e255c75459",
"45f53230a74ad275c7127e117ac46914c8126160": "814fce58e83abd5bf2a13892e0b0e1198abefcd4",
}
func remap(name string, m map[string]string) string {
if m[name] != "" {
return m[name]
}
if codehost.AllHex(name) {
for k, v := range m {
if strings.HasPrefix(k, name) {
return v[:len(name)]
}
}
}
for k, v := range m {
name = strings.Replace(name, k, v, -1)
if codehost.AllHex(k) {
name = strings.Replace(name, k[:12], v[:12], -1)
}
}
return name
}
var codeRepoVersionsTests = []struct {
path string
prefix string
versions []string
}{
{
path: "github.com/rsc/vgotest1",
versions: []string{"v0.0.0", "v0.0.1", "v1.0.0", "v1.0.1", "v1.0.2", "v1.0.3", "v1.1.0", "v2.0.0+incompatible"},
},
{
path: "github.com/rsc/vgotest1",
prefix: "v1.0",
versions: []string{"v1.0.0", "v1.0.1", "v1.0.2", "v1.0.3"},
},
{
path: "github.com/rsc/vgotest1/v2",
versions: []string{"v2.0.0", "v2.0.1", "v2.0.2", "v2.0.3", "v2.0.4", "v2.0.5", "v2.0.6"},
},
{
path: "swtch.com/testmod",
versions: []string{"v1.0.0", "v1.1.1"},
},
{
path: "gopkg.in/russross/blackfriday.v2",
versions: []string{"v2.0.0"},
},
{
path: "gopkg.in/natefinch/lumberjack.v2",
versions: nil,
},
}
func TestCodeRepoVersions(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tmpdir, err := ioutil.TempDir("", "vgo-modfetch-test-")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpdir)
for _, tt := range codeRepoVersionsTests {
t.Run(strings.Replace(tt.path, "/", "_", -1), func(t *testing.T) {
repo, err := Lookup(tt.path)
if err != nil {
t.Fatalf("Lookup(%q): %v", tt.path, err)
}
list, err := repo.Versions(tt.prefix)
if err != nil {
t.Fatalf("Versions(%q): %v", tt.prefix, err)
}
if !reflect.DeepEqual(list, tt.versions) {
t.Fatalf("Versions(%q):\nhave %v\nwant %v", tt.prefix, list, tt.versions)
}
})
}
}
var latestTests = []struct {
path string
version string
err string
}{
{
path: "github.com/rsc/empty",
err: "no commits",
},
{
path: "github.com/rsc/vgotest1",
version: "v0.0.0-20180219223237-a08abb797a67",
},
{
path: "github.com/rsc/vgotest1/subdir",
err: "missing github.com/rsc/vgotest1/subdir/go.mod at revision a08abb797a67",
},
{
path: "swtch.com/testmod",
version: "v1.1.1",
},
}
func TestLatest(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tmpdir, err := ioutil.TempDir("", "vgo-modfetch-test-")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpdir)
for _, tt := range latestTests {
name := strings.Replace(tt.path, "/", "_", -1)
t.Run(name, func(t *testing.T) {
repo, err := Lookup(tt.path)
if err != nil {
t.Fatalf("Lookup(%q): %v", tt.path, err)
}
info, err := repo.Latest()
if err != nil {
if tt.err != "" {
if err.Error() == tt.err {
return
}
t.Fatalf("Latest(): %v, want %q", err, tt.err)
}
t.Fatalf("Latest(): %v", err)
}
if tt.err != "" {
t.Fatalf("Latest() = %v, want error %q", info.Version, tt.err)
}
if info.Version != tt.version {
t.Fatalf("Latest() = %v, want %v", info.Version, tt.version)
}
})
}
}
// fixedTagsRepo is a fake codehost.Repo that returns a fixed list of tags
type fixedTagsRepo struct {
tags []string
}
func (ch *fixedTagsRepo) Tags(string) ([]string, error) { return ch.tags, nil }
func (ch *fixedTagsRepo) Latest() (*codehost.RevInfo, error) { panic("not impl") }
func (ch *fixedTagsRepo) ReadFile(string, string, int64) ([]byte, error) { panic("not impl") }
func (ch *fixedTagsRepo) ReadFileRevs([]string, string, int64) (map[string]*codehost.FileRev, error) {
panic("not impl")
}
func (ch *fixedTagsRepo) ReadZip(string, string, int64) (io.ReadCloser, string, error) {
panic("not impl")
}
func (ch *fixedTagsRepo) RecentTag(string, string) (string, error) {
panic("not impl")
}
func (ch *fixedTagsRepo) Stat(string) (*codehost.RevInfo, error) { panic("not impl") }
func TestNonCanonicalSemver(t *testing.T) {
root := "golang.org/x/issue24476"
ch := &fixedTagsRepo{
tags: []string{
"", "huh?", "1.0.1",
// what about "version 1 dot dogcow"?
"v1.🐕.🐄",
"v1", "v0.1",
// and one normal one that should pass through
"v1.0.1",
},
}
cr, err := newCodeRepo(ch, root, root)
if err != nil {
t.Fatal(err)
}
v, err := cr.Versions("")
if err != nil {
t.Fatal(err)
}
if len(v) != 1 || v[0] != "v1.0.1" {
t.Fatal("unexpected versions returned:", v)
}
}
|
modfetch
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/coderepo.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package modfetch
import (
"archive/zip"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"strings"
"cmd/go/internal/modfetch/codehost"
"cmd/go/internal/modfile"
"cmd/go/internal/module"
"cmd/go/internal/semver"
)
// A codeRepo implements modfetch.Repo using an underlying codehost.Repo.
type codeRepo struct {
modPath string
code codehost.Repo
codeRoot string
codeDir string
path string
pathPrefix string
pathMajor string
pseudoMajor string
}
func newCodeRepo(code codehost.Repo, root, path string) (Repo, error) {
if !hasPathPrefix(path, root) {
return nil, fmt.Errorf("mismatched repo: found %s for %s", root, path)
}
pathPrefix, pathMajor, ok := module.SplitPathVersion(path)
if !ok {
return nil, fmt.Errorf("invalid module path %q", path)
}
pseudoMajor := "v0"
if pathMajor != "" {
pseudoMajor = pathMajor[1:]
}
// At this point we might have:
// codeRoot = github.com/rsc/foo
// path = github.com/rsc/foo/bar/v2
// pathPrefix = github.com/rsc/foo/bar
// pathMajor = /v2
// pseudoMajor = v2
//
// Compute codeDir = bar, the subdirectory within the repo
// corresponding to the module root.
codeDir := strings.Trim(strings.TrimPrefix(pathPrefix, root), "/")
if strings.HasPrefix(path, "gopkg.in/") {
// But gopkg.in is a special legacy case, in which pathPrefix does not start with codeRoot.
// For example we might have:
// codeRoot = gopkg.in/yaml.v2
// pathPrefix = gopkg.in/yaml
// pathMajor = .v2
// pseudoMajor = v2
// codeDir = pathPrefix (because codeRoot is not a prefix of pathPrefix)
// Clear codeDir - the module root is the repo root for gopkg.in repos.
codeDir = ""
}
r := &codeRepo{
modPath: path,
code: code,
codeRoot: root,
codeDir: codeDir,
pathPrefix: pathPrefix,
pathMajor: pathMajor,
pseudoMajor: pseudoMajor,
}
return r, nil
}
func (r *codeRepo) ModulePath() string {
return r.modPath
}
func (r *codeRepo) Versions(prefix string) ([]string, error) {
// Special case: gopkg.in/macaroon-bakery.v2-unstable
// does not use the v2 tags (those are for macaroon-bakery.v2).
// It has no possible tags at all.
if strings.HasPrefix(r.modPath, "gopkg.in/") && strings.HasSuffix(r.modPath, "-unstable") {
return nil, nil
}
p := prefix
if r.codeDir != "" {
p = r.codeDir + "/" + p
}
tags, err := r.code.Tags(p)
if err != nil {
return nil, err
}
list := []string{}
var incompatible []string
for _, tag := range tags {
if !strings.HasPrefix(tag, p) {
continue
}
v := tag
if r.codeDir != "" {
v = v[len(r.codeDir)+1:]
}
if v == "" || v != module.CanonicalVersion(v) || IsPseudoVersion(v) {
continue
}
if !module.MatchPathMajor(v, r.pathMajor) {
if r.codeDir == "" && r.pathMajor == "" && semver.Major(v) > "v1" {
incompatible = append(incompatible, v)
}
continue
}
list = append(list, v)
}
if len(incompatible) > 0 {
// Check for later versions that were created not following semantic import versioning,
// as indicated by the absence of a go.mod file. Those versions can be addressed
// by referring to them with a +incompatible suffix, as in v17.0.0+incompatible.
files, err := r.code.ReadFileRevs(incompatible, "go.mod", codehost.MaxGoMod)
if err != nil {
return nil, err
}
for _, rev := range incompatible {
f := files[rev]
if os.IsNotExist(f.Err) {
list = append(list, rev+"+incompatible")
}
}
}
SortVersions(list)
return list, nil
}
func (r *codeRepo) Stat(rev string) (*RevInfo, error) {
if rev == "latest" {
return r.Latest()
}
codeRev := r.revToRev(rev)
if semver.IsValid(codeRev) && r.codeDir != "" {
codeRev = r.codeDir + "/" + codeRev
}
info, err := r.code.Stat(codeRev)
if err != nil {
return nil, err
}
return r.convert(info, rev)
}
func (r *codeRepo) Latest() (*RevInfo, error) {
info, err := r.code.Latest()
if err != nil {
return nil, err
}
return r.convert(info, "")
}
func (r *codeRepo) convert(info *codehost.RevInfo, statVers string) (*RevInfo, error) {
info2 := &RevInfo{
Name: info.Name,
Short: info.Short,
Time: info.Time,
}
// Determine version.
if module.CanonicalVersion(statVers) == statVers && module.MatchPathMajor(statVers, r.pathMajor) {
// The original call was repo.Stat(statVers), and requestedVersion is OK, so use it.
info2.Version = statVers
} else {
// Otherwise derive a version from a code repo tag.
// Tag must have a prefix matching codeDir.
p := ""
if r.codeDir != "" {
p = r.codeDir + "/"
}
// If this is a plain tag (no dir/ prefix)
// and the module path is unversioned,
// and if the underlying file tree has no go.mod,
// then allow using the tag with a +incompatible suffix.
canUseIncompatible := false
if r.codeDir == "" && r.pathMajor == "" {
_, errGoMod := r.code.ReadFile(info.Name, "go.mod", codehost.MaxGoMod)
if errGoMod != nil {
canUseIncompatible = true
}
}
tagToVersion := func(v string) string {
if !strings.HasPrefix(v, p) {
return ""
}
v = v[len(p):]
if module.CanonicalVersion(v) != v || IsPseudoVersion(v) {
return ""
}
if module.MatchPathMajor(v, r.pathMajor) {
return v
}
if canUseIncompatible {
return v + "+incompatible"
}
return ""
}
// If info.Version is OK, use it.
if v := tagToVersion(info.Version); v != "" {
info2.Version = v
} else {
// Otherwise look through all known tags for latest in semver ordering.
for _, tag := range info.Tags {
if v := tagToVersion(tag); v != "" && semver.Compare(info2.Version, v) < 0 {
info2.Version = v
}
}
// Otherwise make a pseudo-version.
if info2.Version == "" {
tag, _ := r.code.RecentTag(statVers, p)
v = tagToVersion(tag)
// TODO: Check that v is OK for r.pseudoMajor or else is OK for incompatible.
info2.Version = PseudoVersion(r.pseudoMajor, v, info.Time, info.Short)
}
}
}
// Do not allow a successful stat of a pseudo-version for a subdirectory
// unless the subdirectory actually does have a go.mod.
if IsPseudoVersion(info2.Version) && r.codeDir != "" {
_, _, _, err := r.findDir(info2.Version)
if err != nil {
// TODO: It would be nice to return an error like "not a module".
// Right now we return "missing go.mod", which is a little confusing.
return nil, err
}
}
return info2, nil
}
func (r *codeRepo) revToRev(rev string) string {
if semver.IsValid(rev) {
if IsPseudoVersion(rev) {
r, _ := PseudoVersionRev(rev)
return r
}
if semver.Build(rev) == "+incompatible" {
rev = rev[:len(rev)-len("+incompatible")]
}
if r.codeDir == "" {
return rev
}
return r.codeDir + "/" + rev
}
return rev
}
func (r *codeRepo) versionToRev(version string) (rev string, err error) {
if !semver.IsValid(version) {
return "", fmt.Errorf("malformed semantic version %q", version)
}
return r.revToRev(version), nil
}
func (r *codeRepo) findDir(version string) (rev, dir string, gomod []byte, err error) {
rev, err = r.versionToRev(version)
if err != nil {
return "", "", nil, err
}
// Load info about go.mod but delay consideration
// (except I/O error) until we rule out v2/go.mod.
file1 := path.Join(r.codeDir, "go.mod")
gomod1, err1 := r.code.ReadFile(rev, file1, codehost.MaxGoMod)
if err1 != nil && !os.IsNotExist(err1) {
return "", "", nil, fmt.Errorf("reading %s/%s at revision %s: %v", r.pathPrefix, file1, rev, err1)
}
mpath1 := modfile.ModulePath(gomod1)
found1 := err1 == nil && isMajor(mpath1, r.pathMajor)
var file2 string
if r.pathMajor != "" && !strings.HasPrefix(r.pathMajor, ".") {
// Suppose pathMajor is "/v2".
// Either go.mod should claim v2 and v2/go.mod should not exist,
// or v2/go.mod should exist and claim v2. Not both.
// Note that we don't check the full path, just the major suffix,
// because of replacement modules. This might be a fork of
// the real module, found at a different path, usable only in
// a replace directive.
dir2 := path.Join(r.codeDir, r.pathMajor[1:])
file2 = path.Join(dir2, "go.mod")
gomod2, err2 := r.code.ReadFile(rev, file2, codehost.MaxGoMod)
if err2 != nil && !os.IsNotExist(err2) {
return "", "", nil, fmt.Errorf("reading %s/%s at revision %s: %v", r.pathPrefix, file2, rev, err2)
}
mpath2 := modfile.ModulePath(gomod2)
found2 := err2 == nil && isMajor(mpath2, r.pathMajor)
if found1 && found2 {
return "", "", nil, fmt.Errorf("%s/%s and ...%s/go.mod both have ...%s module paths at revision %s", r.pathPrefix, file1, r.pathMajor, r.pathMajor, rev)
}
if found2 {
return rev, dir2, gomod2, nil
}
if err2 == nil {
if mpath2 == "" {
return "", "", nil, fmt.Errorf("%s/%s is missing module path at revision %s", r.pathPrefix, file2, rev)
}
return "", "", nil, fmt.Errorf("%s/%s has non-...%s module path %q at revision %s", r.pathPrefix, file2, r.pathMajor, mpath2, rev)
}
}
// Not v2/go.mod, so it's either go.mod or nothing. Which is it?
if found1 {
// Explicit go.mod with matching module path OK.
return rev, r.codeDir, gomod1, nil
}
if err1 == nil {
// Explicit go.mod with non-matching module path disallowed.
suffix := ""
if file2 != "" {
suffix = fmt.Sprintf(" (and ...%s/go.mod does not exist)", r.pathMajor)
}
if mpath1 == "" {
return "", "", nil, fmt.Errorf("%s is missing module path%s at revision %s", file1, suffix, rev)
}
if r.pathMajor != "" { // ".v1", ".v2" for gopkg.in
return "", "", nil, fmt.Errorf("%s has non-...%s module path %q%s at revision %s", file1, r.pathMajor, mpath1, suffix, rev)
}
return "", "", nil, fmt.Errorf("%s has post-%s module path %q%s at revision %s", file1, semver.Major(version), mpath1, suffix, rev)
}
if r.codeDir == "" && (r.pathMajor == "" || strings.HasPrefix(r.pathMajor, ".")) {
// Implicit go.mod at root of repo OK for v0/v1 and for gopkg.in.
return rev, "", nil, nil
}
// Implicit go.mod below root of repo or at v2+ disallowed.
// Be clear about possibility of using either location for v2+.
if file2 != "" {
return "", "", nil, fmt.Errorf("missing %s/go.mod and ...%s/go.mod at revision %s", r.pathPrefix, r.pathMajor, rev)
}
return "", "", nil, fmt.Errorf("missing %s/go.mod at revision %s", r.pathPrefix, rev)
}
func isMajor(mpath, pathMajor string) bool {
if mpath == "" {
return false
}
if pathMajor == "" {
// mpath must NOT have version suffix.
i := len(mpath)
for i > 0 && '0' <= mpath[i-1] && mpath[i-1] <= '9' {
i--
}
if i < len(mpath) && i >= 2 && mpath[i-1] == 'v' && mpath[i-2] == '/' {
// Found valid suffix.
return false
}
return true
}
// Otherwise pathMajor is ".v1", ".v2" (gopkg.in), or "/v2", "/v3" etc.
return strings.HasSuffix(mpath, pathMajor)
}
func (r *codeRepo) GoMod(version string) (data []byte, err error) {
rev, dir, gomod, err := r.findDir(version)
if err != nil {
return nil, err
}
if gomod != nil {
return gomod, nil
}
data, err = r.code.ReadFile(rev, path.Join(dir, "go.mod"), codehost.MaxGoMod)
if err != nil {
if os.IsNotExist(err) {
return r.legacyGoMod(rev, dir), nil
}
return nil, err
}
return data, nil
}
func (r *codeRepo) legacyGoMod(rev, dir string) []byte {
// We used to try to build a go.mod reflecting pre-existing
// package management metadata files, but the conversion
// was inherently imperfect (because those files don't have
// exactly the same semantics as go.mod) and, when done
// for dependencies in the middle of a build, impossible to
// correct. So we stopped.
// Return a fake go.mod that simply declares the module path.
return []byte(fmt.Sprintf("module %s\n", modfile.AutoQuote(r.modPath)))
}
func (r *codeRepo) modPrefix(rev string) string {
return r.modPath + "@" + rev
}
func (r *codeRepo) Zip(version string, tmpdir string) (tmpfile string, err error) {
rev, dir, _, err := r.findDir(version)
if err != nil {
return "", err
}
dl, actualDir, err := r.code.ReadZip(rev, dir, codehost.MaxZipFile)
if err != nil {
return "", err
}
if actualDir != "" && !hasPathPrefix(dir, actualDir) {
return "", fmt.Errorf("internal error: downloading %v %v: dir=%q but actualDir=%q", r.path, rev, dir, actualDir)
}
subdir := strings.Trim(strings.TrimPrefix(dir, actualDir), "/")
// Spool to local file.
f, err := ioutil.TempFile(tmpdir, "go-codehost-")
if err != nil {
dl.Close()
return "", err
}
defer os.Remove(f.Name())
defer f.Close()
maxSize := int64(codehost.MaxZipFile)
lr := &io.LimitedReader{R: dl, N: maxSize + 1}
if _, err := io.Copy(f, lr); err != nil {
dl.Close()
return "", err
}
dl.Close()
if lr.N <= 0 {
return "", fmt.Errorf("downloaded zip file too large")
}
size := (maxSize + 1) - lr.N
if _, err := f.Seek(0, 0); err != nil {
return "", err
}
// Translate from zip file we have to zip file we want.
zr, err := zip.NewReader(f, size)
if err != nil {
return "", err
}
f2, err := ioutil.TempFile(tmpdir, "go-codezip-")
if err != nil {
return "", err
}
zw := zip.NewWriter(f2)
newName := f2.Name()
defer func() {
f2.Close()
if err != nil {
os.Remove(newName)
}
}()
if subdir != "" {
subdir += "/"
}
haveLICENSE := false
topPrefix := ""
haveGoMod := make(map[string]bool)
for _, zf := range zr.File {
if topPrefix == "" {
i := strings.Index(zf.Name, "/")
if i < 0 {
return "", fmt.Errorf("missing top-level directory prefix")
}
topPrefix = zf.Name[:i+1]
}
if !strings.HasPrefix(zf.Name, topPrefix) {
return "", fmt.Errorf("zip file contains more than one top-level directory")
}
dir, file := path.Split(zf.Name)
if file == "go.mod" {
haveGoMod[dir] = true
}
}
root := topPrefix + subdir
inSubmodule := func(name string) bool {
for {
dir, _ := path.Split(name)
if len(dir) <= len(root) {
return false
}
if haveGoMod[dir] {
return true
}
name = dir[:len(dir)-1]
}
}
for _, zf := range zr.File {
if topPrefix == "" {
i := strings.Index(zf.Name, "/")
if i < 0 {
return "", fmt.Errorf("missing top-level directory prefix")
}
topPrefix = zf.Name[:i+1]
}
if strings.HasSuffix(zf.Name, "/") { // drop directory dummy entries
continue
}
if !strings.HasPrefix(zf.Name, topPrefix) {
return "", fmt.Errorf("zip file contains more than one top-level directory")
}
name := strings.TrimPrefix(zf.Name, topPrefix)
if !strings.HasPrefix(name, subdir) {
continue
}
if name == ".hg_archival.txt" {
// Inserted by hg archive.
// Not correct to drop from other version control systems, but too bad.
continue
}
name = strings.TrimPrefix(name, subdir)
if isVendoredPackage(name) {
continue
}
if inSubmodule(zf.Name) {
continue
}
base := path.Base(name)
if strings.ToLower(base) == "go.mod" && base != "go.mod" {
return "", fmt.Errorf("zip file contains %s, want all lower-case go.mod", zf.Name)
}
if name == "LICENSE" {
haveLICENSE = true
}
size := int64(zf.UncompressedSize)
if size < 0 || maxSize < size {
return "", fmt.Errorf("module source tree too big")
}
maxSize -= size
rc, err := zf.Open()
if err != nil {
return "", err
}
w, err := zw.Create(r.modPrefix(version) + "/" + name)
lr := &io.LimitedReader{R: rc, N: size + 1}
if _, err := io.Copy(w, lr); err != nil {
return "", err
}
if lr.N <= 0 {
return "", fmt.Errorf("individual file too large")
}
}
if !haveLICENSE && subdir != "" {
data, err := r.code.ReadFile(rev, "LICENSE", codehost.MaxLICENSE)
if err == nil {
w, err := zw.Create(r.modPrefix(version) + "/LICENSE")
if err != nil {
return "", err
}
if _, err := w.Write(data); err != nil {
return "", err
}
}
}
if err := zw.Close(); err != nil {
return "", err
}
if err := f2.Close(); err != nil {
return "", err
}
return f2.Name(), nil
}
// hasPathPrefix reports whether the path s begins with the
// elements in prefix.
func hasPathPrefix(s, prefix string) bool {
switch {
default:
return false
case len(s) == len(prefix):
return s == prefix
case len(s) > len(prefix):
if prefix != "" && prefix[len(prefix)-1] == '/' {
return strings.HasPrefix(s, prefix)
}
return s[len(prefix)] == '/' && s[:len(prefix)] == prefix
}
}
func isVendoredPackage(name string) bool {
var i int
if strings.HasPrefix(name, "vendor/") {
i += len("vendor/")
} else if j := strings.Index(name, "/vendor/"); j >= 0 {
i += len("/vendor/")
} else {
return false
}
return strings.Contains(name[i:], "/")
}
|
modfetch
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/noweb.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build cmd_go_bootstrap
package modfetch
import (
"fmt"
"io"
)
func webGetGoGet(url string, body *io.ReadCloser) error {
return fmt.Errorf("no network in go_bootstrap")
}
func webGetBytes(url string, body *[]byte) error {
return fmt.Errorf("no network in go_bootstrap")
}
func webGetBody(url string, body *io.ReadCloser) error {
return fmt.Errorf("no network in go_bootstrap")
}
|
modfetch
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/cache.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package modfetch
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"cmd/go/internal/base"
"cmd/go/internal/modfetch/codehost"
"cmd/go/internal/module"
"cmd/go/internal/par"
"cmd/go/internal/semver"
)
var QuietLookup bool // do not print about lookups
var PkgMod string // $GOPATH/pkg/mod; set by package modload
func cacheDir(path string) (string, error) {
if PkgMod == "" {
return "", fmt.Errorf("internal error: modfetch.PkgMod not set")
}
enc, err := module.EncodePath(path)
if err != nil {
return "", err
}
return filepath.Join(PkgMod, "cache/download", enc, "/@v"), nil
}
func CachePath(m module.Version, suffix string) (string, error) {
dir, err := cacheDir(m.Path)
if err != nil {
return "", err
}
if !semver.IsValid(m.Version) {
return "", fmt.Errorf("non-semver module version %q", m.Version)
}
if module.CanonicalVersion(m.Version) != m.Version {
return "", fmt.Errorf("non-canonical module version %q", m.Version)
}
encVer, err := module.EncodeVersion(m.Version)
if err != nil {
return "", err
}
return filepath.Join(dir, encVer+"."+suffix), nil
}
func DownloadDir(m module.Version) (string, error) {
if PkgMod == "" {
return "", fmt.Errorf("internal error: modfetch.PkgMod not set")
}
enc, err := module.EncodePath(m.Path)
if err != nil {
return "", err
}
if !semver.IsValid(m.Version) {
return "", fmt.Errorf("non-semver module version %q", m.Version)
}
if module.CanonicalVersion(m.Version) != m.Version {
return "", fmt.Errorf("non-canonical module version %q", m.Version)
}
encVer, err := module.EncodeVersion(m.Version)
if err != nil {
return "", err
}
return filepath.Join(PkgMod, enc+"@"+encVer), nil
}
// A cachingRepo is a cache around an underlying Repo,
// avoiding redundant calls to ModulePath, Versions, Stat, Latest, and GoMod (but not Zip).
// It is also safe for simultaneous use by multiple goroutines
// (so that it can be returned from Lookup multiple times).
// It serializes calls to the underlying Repo.
type cachingRepo struct {
path string
cache par.Cache // cache for all operations
r Repo
}
func newCachingRepo(r Repo) *cachingRepo {
return &cachingRepo{
r: r,
path: r.ModulePath(),
}
}
func (r *cachingRepo) ModulePath() string {
return r.path
}
func (r *cachingRepo) Versions(prefix string) ([]string, error) {
type cached struct {
list []string
err error
}
c := r.cache.Do("versions:"+prefix, func() interface{} {
list, err := r.r.Versions(prefix)
return cached{list, err}
}).(cached)
if c.err != nil {
return nil, c.err
}
return append([]string(nil), c.list...), nil
}
type cachedInfo struct {
info *RevInfo
err error
}
func (r *cachingRepo) Stat(rev string) (*RevInfo, error) {
c := r.cache.Do("stat:"+rev, func() interface{} {
file, info, err := readDiskStat(r.path, rev)
if err == nil {
return cachedInfo{info, nil}
}
if !QuietLookup {
fmt.Fprintf(os.Stderr, "go: finding %s %s\n", r.path, rev)
}
info, err = r.r.Stat(rev)
if err == nil {
if err := writeDiskStat(file, info); err != nil {
fmt.Fprintf(os.Stderr, "go: writing stat cache: %v\n", err)
}
// If we resolved, say, 1234abcde to v0.0.0-20180604122334-1234abcdef78,
// then save the information under the proper version, for future use.
if info.Version != rev {
r.cache.Do("stat:"+info.Version, func() interface{} {
return cachedInfo{info, err}
})
}
}
return cachedInfo{info, err}
}).(cachedInfo)
if c.err != nil {
return nil, c.err
}
info := *c.info
return &info, nil
}
func (r *cachingRepo) Latest() (*RevInfo, error) {
c := r.cache.Do("latest:", func() interface{} {
if !QuietLookup {
fmt.Fprintf(os.Stderr, "go: finding %s latest\n", r.path)
}
info, err := r.r.Latest()
// Save info for likely future Stat call.
if err == nil {
r.cache.Do("stat:"+info.Version, func() interface{} {
return cachedInfo{info, err}
})
if file, _, err := readDiskStat(r.path, info.Version); err != nil {
writeDiskStat(file, info)
}
}
return cachedInfo{info, err}
}).(cachedInfo)
if c.err != nil {
return nil, c.err
}
info := *c.info
return &info, nil
}
func (r *cachingRepo) GoMod(rev string) ([]byte, error) {
type cached struct {
text []byte
err error
}
c := r.cache.Do("gomod:"+rev, func() interface{} {
file, text, err := readDiskGoMod(r.path, rev)
if err == nil {
// Note: readDiskGoMod already called checkGoMod.
return cached{text, nil}
}
// Convert rev to canonical version
// so that we use the right identifier in the go.sum check.
info, err := r.Stat(rev)
if err != nil {
return cached{nil, err}
}
rev = info.Version
text, err = r.r.GoMod(rev)
if err == nil {
checkGoMod(r.path, rev, text)
if err := writeDiskGoMod(file, text); err != nil {
fmt.Fprintf(os.Stderr, "go: writing go.mod cache: %v\n", err)
}
}
return cached{text, err}
}).(cached)
if c.err != nil {
return nil, c.err
}
return append([]byte(nil), c.text...), nil
}
func (r *cachingRepo) Zip(version, tmpdir string) (string, error) {
return r.r.Zip(version, tmpdir)
}
// Stat is like Lookup(path).Stat(rev) but avoids the
// repository path resolution in Lookup if the result is
// already cached on local disk.
func Stat(path, rev string) (*RevInfo, error) {
_, info, err := readDiskStat(path, rev)
if err == nil {
return info, nil
}
repo, err := Lookup(path)
if err != nil {
return nil, err
}
return repo.Stat(rev)
}
// InfoFile is like Stat but returns the name of the file containing
// the cached information.
func InfoFile(path, version string) (string, error) {
if !semver.IsValid(version) {
return "", fmt.Errorf("invalid version %q", version)
}
if _, err := Stat(path, version); err != nil {
return "", err
}
// Stat should have populated the disk cache for us.
file, _, err := readDiskStat(path, version)
if err != nil {
return "", err
}
return file, nil
}
// GoMod is like Lookup(path).GoMod(rev) but avoids the
// repository path resolution in Lookup if the result is
// already cached on local disk.
func GoMod(path, rev string) ([]byte, error) {
// Convert commit hash to pseudo-version
// to increase cache hit rate.
if !semver.IsValid(rev) {
info, err := Stat(path, rev)
if err != nil {
return nil, err
}
rev = info.Version
}
_, data, err := readDiskGoMod(path, rev)
if err == nil {
return data, nil
}
repo, err := Lookup(path)
if err != nil {
return nil, err
}
return repo.GoMod(rev)
}
// GoModFile is like GoMod but returns the name of the file containing
// the cached information.
func GoModFile(path, version string) (string, error) {
if !semver.IsValid(version) {
return "", fmt.Errorf("invalid version %q", version)
}
if _, err := GoMod(path, version); err != nil {
return "", err
}
// GoMod should have populated the disk cache for us.
file, _, err := readDiskGoMod(path, version)
if err != nil {
return "", err
}
return file, nil
}
// GoModSum returns the go.sum entry for the module version's go.mod file.
// (That is, it returns the entry listed in go.sum as "path version/go.mod".)
func GoModSum(path, version string) (string, error) {
if !semver.IsValid(version) {
return "", fmt.Errorf("invalid version %q", version)
}
data, err := GoMod(path, version)
if err != nil {
return "", err
}
sum, err := goModSum(data)
if err != nil {
return "", err
}
return sum, nil
}
var errNotCached = fmt.Errorf("not in cache")
// readDiskStat reads a cached stat result from disk,
// returning the name of the cache file and the result.
// If the read fails, the caller can use
// writeDiskStat(file, info) to write a new cache entry.
func readDiskStat(path, rev string) (file string, info *RevInfo, err error) {
file, data, err := readDiskCache(path, rev, "info")
if err != nil {
if file, info, err := readDiskStatByHash(path, rev); err == nil {
return file, info, nil
}
return file, nil, err
}
info = new(RevInfo)
if err := json.Unmarshal(data, info); err != nil {
return file, nil, errNotCached
}
// The disk might have stale .info files that have Name and Short fields set.
// We want to canonicalize to .info files with those fields omitted.
// Remarshal and update the cache file if needed.
data2, err := json.Marshal(info)
if err == nil && !bytes.Equal(data2, data) {
writeDiskCache(file, data)
}
return file, info, nil
}
// readDiskStatByHash is a fallback for readDiskStat for the case
// where rev is a commit hash instead of a proper semantic version.
// In that case, we look for a cached pseudo-version that matches
// the commit hash. If we find one, we use it.
// This matters most for converting legacy package management
// configs, when we are often looking up commits by full hash.
// Without this check we'd be doing network I/O to the remote repo
// just to find out about a commit we already know about
// (and have cached under its pseudo-version).
func readDiskStatByHash(path, rev string) (file string, info *RevInfo, err error) {
if PkgMod == "" {
// Do not download to current directory.
return "", nil, errNotCached
}
if !codehost.AllHex(rev) || len(rev) < 12 {
return "", nil, errNotCached
}
rev = rev[:12]
cdir, err := cacheDir(path)
if err != nil {
return "", nil, errNotCached
}
dir, err := os.Open(cdir)
if err != nil {
return "", nil, errNotCached
}
names, err := dir.Readdirnames(-1)
dir.Close()
if err != nil {
return "", nil, errNotCached
}
suffix := "-" + rev + ".info"
for _, name := range names {
if strings.HasSuffix(name, suffix) && IsPseudoVersion(strings.TrimSuffix(name, ".info")) {
return readDiskStat(path, strings.TrimSuffix(name, ".info"))
}
}
return "", nil, errNotCached
}
// oldVgoPrefix is the prefix in the old auto-generated cached go.mod files.
// We stopped trying to auto-generate the go.mod files. Now we use a trivial
// go.mod with only a module line, and we've dropped the version prefix
// entirely. If we see a version prefix, that means we're looking at an old copy
// and should ignore it.
var oldVgoPrefix = []byte("//vgo 0.0.")
// readDiskGoMod reads a cached stat result from disk,
// returning the name of the cache file and the result.
// If the read fails, the caller can use
// writeDiskGoMod(file, data) to write a new cache entry.
func readDiskGoMod(path, rev string) (file string, data []byte, err error) {
file, data, err = readDiskCache(path, rev, "mod")
// If the file has an old auto-conversion prefix, pretend it's not there.
if bytes.HasPrefix(data, oldVgoPrefix) {
err = errNotCached
data = nil
}
if err == nil {
checkGoMod(path, rev, data)
}
return file, data, err
}
// readDiskCache is the generic "read from a cache file" implementation.
// It takes the revision and an identifying suffix for the kind of data being cached.
// It returns the name of the cache file and the content of the file.
// If the read fails, the caller can use
// writeDiskCache(file, data) to write a new cache entry.
func readDiskCache(path, rev, suffix string) (file string, data []byte, err error) {
file, err = CachePath(module.Version{Path: path, Version: rev}, suffix)
if err != nil {
return "", nil, errNotCached
}
data, err = ioutil.ReadFile(file)
if err != nil {
return file, nil, errNotCached
}
return file, data, nil
}
// writeDiskStat writes a stat result cache entry.
// The file name must have been returned by a previous call to readDiskStat.
func writeDiskStat(file string, info *RevInfo) error {
if file == "" {
return nil
}
js, err := json.Marshal(info)
if err != nil {
return err
}
return writeDiskCache(file, js)
}
// writeDiskGoMod writes a go.mod cache entry.
// The file name must have been returned by a previous call to readDiskGoMod.
func writeDiskGoMod(file string, text []byte) error {
return writeDiskCache(file, text)
}
// writeDiskCache is the generic "write to a cache file" implementation.
// The file must have been returned by a previous call to readDiskCache.
func writeDiskCache(file string, data []byte) error {
if file == "" {
return nil
}
// Make sure directory for file exists.
if err := os.MkdirAll(filepath.Dir(file), 0777); err != nil {
return err
}
// Write data to temp file next to target file.
f, err := ioutil.TempFile(filepath.Dir(file), filepath.Base(file)+".tmp-")
if err != nil {
return err
}
defer os.Remove(f.Name())
defer f.Close()
if _, err := f.Write(data); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
// Rename temp file onto cache file,
// so that the cache file is always a complete file.
if err := os.Rename(f.Name(), file); err != nil {
return err
}
if strings.HasSuffix(file, ".mod") {
rewriteVersionList(filepath.Dir(file))
}
return nil
}
// rewriteVersionList rewrites the version list in dir
// after a new *.mod file has been written.
func rewriteVersionList(dir string) {
if filepath.Base(dir) != "@v" {
base.Fatalf("go: internal error: misuse of rewriteVersionList")
}
// TODO(rsc): We should do some kind of directory locking here,
// to avoid lost updates.
infos, err := ioutil.ReadDir(dir)
if err != nil {
return
}
var list []string
for _, info := range infos {
// We look for *.mod files on the theory that if we can't supply
// the .mod file then there's no point in listing that version,
// since it's unusable. (We can have *.info without *.mod.)
// We don't require *.zip files on the theory that for code only
// involved in module graph construction, many *.zip files
// will never be requested.
name := info.Name()
if strings.HasSuffix(name, ".mod") {
v := strings.TrimSuffix(name, ".mod")
if v != "" && module.CanonicalVersion(v) == v {
list = append(list, v)
}
}
}
SortVersions(list)
var buf bytes.Buffer
for _, v := range list {
buf.WriteString(v)
buf.WriteString("\n")
}
listFile := filepath.Join(dir, "list")
old, _ := ioutil.ReadFile(listFile)
if bytes.Equal(buf.Bytes(), old) {
return
}
// TODO: Use rename to install file,
// so that readers never see an incomplete file.
ioutil.WriteFile(listFile, buf.Bytes(), 0666)
}
|
modfetch
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/web.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !cmd_go_bootstrap
package modfetch
import (
"io"
web "cmd/go/internal/web2"
)
// webGetGoGet fetches a go-get=1 URL and returns the body in *body.
// It allows non-200 responses, as usual for these URLs.
func webGetGoGet(url string, body *io.ReadCloser) error {
return web.Get(url, web.Non200OK(), web.Body(body))
}
// webGetBytes returns the body returned by an HTTP GET, as a []byte.
// It insists on a 200 response.
func webGetBytes(url string, body *[]byte) error {
return web.Get(url, web.ReadAllBody(body))
}
// webGetBody returns the body returned by an HTTP GET, as a io.ReadCloser.
// It insists on a 200 response.
func webGetBody(url string, body *io.ReadCloser) error {
return web.Get(url, web.Body(body))
}
|
modfetch
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/unzip.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package modfetch
import (
"archive/zip"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"sort"
"strings"
"cmd/go/internal/modfetch/codehost"
"cmd/go/internal/module"
"cmd/go/internal/str"
)
func Unzip(dir, zipfile, prefix string, maxSize int64) error {
if maxSize == 0 {
maxSize = codehost.MaxZipFile
}
// Directory can exist, but must be empty.
// except maybe
files, _ := ioutil.ReadDir(dir)
if len(files) > 0 {
return fmt.Errorf("target directory %v exists and is not empty", dir)
}
if err := os.MkdirAll(dir, 0777); err != nil {
return err
}
f, err := os.Open(zipfile)
if err != nil {
return err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return err
}
z, err := zip.NewReader(f, info.Size())
if err != nil {
return fmt.Errorf("unzip %v: %s", zipfile, err)
}
foldPath := make(map[string]string)
var checkFold func(string) error
checkFold = func(name string) error {
fold := str.ToFold(name)
if foldPath[fold] == name {
return nil
}
dir := path.Dir(name)
if dir != "." {
if err := checkFold(dir); err != nil {
return err
}
}
if foldPath[fold] == "" {
foldPath[fold] = name
return nil
}
other := foldPath[fold]
return fmt.Errorf("unzip %v: case-insensitive file name collision: %q and %q", zipfile, other, name)
}
// Check total size, valid file names.
var size int64
for _, zf := range z.File {
if !str.HasPathPrefix(zf.Name, prefix) {
return fmt.Errorf("unzip %v: unexpected file name %s", zipfile, zf.Name)
}
if zf.Name == prefix || strings.HasSuffix(zf.Name, "/") {
continue
}
name := zf.Name[len(prefix)+1:]
if err := module.CheckFilePath(name); err != nil {
return fmt.Errorf("unzip %v: %v", zipfile, err)
}
if err := checkFold(name); err != nil {
return err
}
if path.Clean(zf.Name) != zf.Name || strings.HasPrefix(zf.Name[len(prefix)+1:], "/") {
return fmt.Errorf("unzip %v: invalid file name %s", zipfile, zf.Name)
}
s := int64(zf.UncompressedSize64)
if s < 0 || maxSize-size < s {
return fmt.Errorf("unzip %v: content too large", zipfile)
}
size += s
}
// Unzip, enforcing sizes checked earlier.
dirs := map[string]bool{dir: true}
for _, zf := range z.File {
if zf.Name == prefix || strings.HasSuffix(zf.Name, "/") {
continue
}
name := zf.Name[len(prefix):]
dst := filepath.Join(dir, name)
parent := filepath.Dir(dst)
for parent != dir {
dirs[parent] = true
parent = filepath.Dir(parent)
}
if err := os.MkdirAll(filepath.Dir(dst), 0777); err != nil {
return err
}
w, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0444)
if err != nil {
return fmt.Errorf("unzip %v: %v", zipfile, err)
}
r, err := zf.Open()
if err != nil {
w.Close()
return fmt.Errorf("unzip %v: %v", zipfile, err)
}
lr := &io.LimitedReader{R: r, N: int64(zf.UncompressedSize64) + 1}
_, err = io.Copy(w, lr)
r.Close()
if err != nil {
w.Close()
return fmt.Errorf("unzip %v: %v", zipfile, err)
}
if err := w.Close(); err != nil {
return fmt.Errorf("unzip %v: %v", zipfile, err)
}
if lr.N <= 0 {
return fmt.Errorf("unzip %v: content too large", zipfile)
}
}
// Mark directories unwritable, best effort.
var dirlist []string
for dir := range dirs {
dirlist = append(dirlist, dir)
}
sort.Strings(dirlist)
// Run over list backward to chmod children before parents.
for i := len(dirlist) - 1; i >= 0; i-- {
os.Chmod(dirlist[i], 0555)
}
return nil
}
|
modfetch
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/cache_test.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package modfetch
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
)
func TestWriteDiskCache(t *testing.T) {
tmpdir, err := ioutil.TempDir("", "go-writeCache-test-")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpdir)
err = writeDiskCache(filepath.Join(tmpdir, "file"), []byte("data"))
if err != nil {
t.Fatal(err)
}
}
|
modfetch
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/pseudo.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Pseudo-versions
//
// Code authors are expected to tag the revisions they want users to use,
// including prereleases. However, not all authors tag versions at all,
// and not all commits a user might want to try will have tags.
// A pseudo-version is a version with a special form that allows us to
// address an untagged commit and order that version with respect to
// other versions we might encounter.
//
// A pseudo-version takes one of the general forms:
//
// (1) vX.0.0-yyyymmddhhmmss-abcdef123456
// (2) vX.Y.(Z+1)-0.yyyymmddhhmmss-abcdef123456
// (3) vX.Y.(Z+1)-0.yyyymmddhhmmss-abcdef123456+incompatible
// (4) vX.Y.Z-pre.0.yyyymmddhhmmss-abcdef123456
// (5) vX.Y.Z-pre.0.yyyymmddhhmmss-abcdef123456+incompatible
//
// If there is no recently tagged version with the right major version vX,
// then form (1) is used, creating a space of pseudo-versions at the bottom
// of the vX version range, less than any tagged version, including the unlikely v0.0.0.
//
// If the most recent tagged version before the target commit is vX.Y.Z or vX.Y.Z+incompatible,
// then the pseudo-version uses form (2) or (3), making it a prerelease for the next
// possible semantic version after vX.Y.Z. The leading 0 segment in the prerelease string
// ensures that the pseudo-version compares less than possible future explicit prereleases
// like vX.Y.(Z+1)-rc1 or vX.Y.(Z+1)-1.
//
// If the most recent tagged version before the target commit is vX.Y.Z-pre or vX.Y.Z-pre+incompatible,
// then the pseudo-version uses form (4) or (5), making it a slightly later prerelease.
package modfetch
import (
"cmd/go/internal/semver"
"fmt"
"regexp"
"strings"
"time"
)
// PseudoVersion returns a pseudo-version for the given major version ("v1")
// preexisting older tagged version ("" or "v1.2.3" or "v1.2.3-pre"), revision time,
// and revision identifier (usually a 12-byte commit hash prefix).
func PseudoVersion(major, older string, t time.Time, rev string) string {
if major == "" {
major = "v0"
}
major = strings.TrimSuffix(major, "-unstable") // make gopkg.in/macaroon-bakery.v2-unstable use "v2"
segment := fmt.Sprintf("%s-%s", t.UTC().Format("20060102150405"), rev)
build := semver.Build(older)
older = semver.Canonical(older)
if older == "" {
return major + ".0.0-" + segment // form (1)
}
if semver.Prerelease(older) != "" {
return older + ".0." + segment + build // form (4), (5)
}
// Form (2), (3).
// Extract patch from vMAJOR.MINOR.PATCH
v := older[:len(older)]
i := strings.LastIndex(v, ".") + 1
v, patch := v[:i], v[i:]
// Increment PATCH by adding 1 to decimal:
// scan right to left turning 9s to 0s until you find a digit to increment.
// (Number might exceed int64, but math/big is overkill.)
digits := []byte(patch)
for i = len(digits) - 1; i >= 0 && digits[i] == '9'; i-- {
digits[i] = '0'
}
if i >= 0 {
digits[i]++
} else {
// digits is all zeros
digits[0] = '1'
digits = append(digits, '0')
}
patch = string(digits)
// Reassemble.
return v + patch + "-0." + segment + build
}
var pseudoVersionRE = regexp.MustCompile(`^v[0-9]+\.(0\.0-|\d+\.\d+-([^+]*\.)?0\.)\d{14}-[A-Za-z0-9]+(\+incompatible)?$`)
// IsPseudoVersion reports whether v is a pseudo-version.
func IsPseudoVersion(v string) bool {
return strings.Count(v, "-") >= 2 && semver.IsValid(v) && pseudoVersionRE.MatchString(v)
}
// PseudoVersionTime returns the time stamp of the pseudo-version v.
// It returns an error if v is not a pseudo-version or if the time stamp
// embedded in the pseudo-version is not a valid time.
func PseudoVersionTime(v string) (time.Time, error) {
timestamp, _, err := parsePseudoVersion(v)
t, err := time.Parse("20060102150405", timestamp)
if err != nil {
return time.Time{}, fmt.Errorf("pseudo-version with malformed time %s: %q", timestamp, v)
}
return t, nil
}
// PseudoVersionRev returns the revision identifier of the pseudo-version v.
// It returns an error if v is not a pseudo-version.
func PseudoVersionRev(v string) (rev string, err error) {
_, rev, err = parsePseudoVersion(v)
return
}
func parsePseudoVersion(v string) (timestamp, rev string, err error) {
if !IsPseudoVersion(v) {
return "", "", fmt.Errorf("malformed pseudo-version %q", v)
}
v = strings.TrimSuffix(v, "+incompatible")
j := strings.LastIndex(v, "-")
v, rev = v[:j], v[j+1:]
i := strings.LastIndex(v, "-")
if j := strings.LastIndex(v, "."); j > i {
timestamp = v[j+1:]
} else {
timestamp = v[i+1:]
}
return timestamp, rev, nil
}
|
modfetch
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/proxy.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package modfetch
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"strings"
"time"
"cmd/go/internal/base"
"cmd/go/internal/modfetch/codehost"
"cmd/go/internal/module"
"cmd/go/internal/semver"
)
var HelpGoproxy = &base.Command{
UsageLine: "goproxy",
Short: "module proxy protocol",
Long: `
The go command by default downloads modules from version control systems
directly, just as 'go get' always has. The GOPROXY environment variable allows
further control over the download source. If GOPROXY is unset, is the empty string,
or is the string "direct", downloads use the default direct connection to version
control systems. Setting GOPROXY to "off" disallows downloading modules from
any source. Otherwise, GOPROXY is expected to be the URL of a module proxy,
in which case the go command will fetch all modules from that proxy.
No matter the source of the modules, downloaded modules must match existing
entries in go.sum (see 'go help modules' for discussion of verification).
A Go module proxy is any web server that can respond to GET requests for
URLs of a specified form. The requests have no query parameters, so even
a site serving from a fixed file system (including a file:/// URL)
can be a module proxy.
The GET requests sent to a Go module proxy are:
GET $GOPROXY/<module>/@v/list returns a list of all known versions of the
given module, one per line.
GET $GOPROXY/<module>/@v/<version>.info returns JSON-formatted metadata
about that version of the given module.
GET $GOPROXY/<module>/@v/<version>.mod returns the go.mod file
for that version of the given module.
GET $GOPROXY/<module>/@v/<version>.zip returns the zip archive
for that version of the given module.
To avoid problems when serving from case-sensitive file systems,
the <module> and <version> elements are case-encoded, replacing every
uppercase letter with an exclamation mark followed by the corresponding
lower-case letter: github.com/Azure encodes as github.com/!azure.
The JSON-formatted metadata about a given module corresponds to
this Go data structure, which may be expanded in the future:
type Info struct {
Version string // version string
Time time.Time // commit time
}
The zip archive for a specific version of a given module is a
standard zip file that contains the file tree corresponding
to the module's source code and related files. The archive uses
slash-separated paths, and every file path in the archive must
begin with <module>@<version>/, where the module and version are
substituted directly, not case-encoded. The root of the module
file tree corresponds to the <module>@<version>/ prefix in the
archive.
Even when downloading directly from version control systems,
the go command synthesizes explicit info, mod, and zip files
and stores them in its local cache, $GOPATH/pkg/mod/cache/download,
the same as if it had downloaded them directly from a proxy.
The cache layout is the same as the proxy URL space, so
serving $GOPATH/pkg/mod/cache/download at (or copying it to)
https://example.com/proxy would let other users access those
cached module versions with GOPROXY=https://example.com/proxy.
`,
}
var proxyURL = os.Getenv("GOPROXY")
func lookupProxy(path string) (Repo, error) {
if strings.Contains(proxyURL, ",") {
return nil, fmt.Errorf("invalid $GOPROXY setting: cannot have comma")
}
u, err := url.Parse(proxyURL)
if err != nil || u.Scheme != "http" && u.Scheme != "https" && u.Scheme != "file" {
// Don't echo $GOPROXY back in case it has user:password in it (sigh).
return nil, fmt.Errorf("invalid $GOPROXY setting: malformed URL or invalid scheme (must be http, https, file)")
}
return newProxyRepo(u.String(), path)
}
type proxyRepo struct {
url string
path string
}
func newProxyRepo(baseURL, path string) (Repo, error) {
enc, err := module.EncodePath(path)
if err != nil {
return nil, err
}
return &proxyRepo{strings.TrimSuffix(baseURL, "/") + "/" + pathEscape(enc), path}, nil
}
func (p *proxyRepo) ModulePath() string {
return p.path
}
func (p *proxyRepo) Versions(prefix string) ([]string, error) {
var data []byte
err := webGetBytes(p.url+"/@v/list", &data)
if err != nil {
return nil, err
}
var list []string
for _, line := range strings.Split(string(data), "\n") {
f := strings.Fields(line)
if len(f) >= 1 && semver.IsValid(f[0]) && strings.HasPrefix(f[0], prefix) {
list = append(list, f[0])
}
}
SortVersions(list)
return list, nil
}
func (p *proxyRepo) latest() (*RevInfo, error) {
var data []byte
err := webGetBytes(p.url+"/@v/list", &data)
if err != nil {
return nil, err
}
var best time.Time
var bestVersion string
for _, line := range strings.Split(string(data), "\n") {
f := strings.Fields(line)
if len(f) >= 2 && semver.IsValid(f[0]) {
ft, err := time.Parse(time.RFC3339, f[1])
if err == nil && best.Before(ft) {
best = ft
bestVersion = f[0]
}
}
}
if bestVersion == "" {
return nil, fmt.Errorf("no commits")
}
info := &RevInfo{
Version: bestVersion,
Name: bestVersion,
Short: bestVersion,
Time: best,
}
return info, nil
}
func (p *proxyRepo) Stat(rev string) (*RevInfo, error) {
var data []byte
encRev, err := module.EncodeVersion(rev)
if err != nil {
return nil, err
}
err = webGetBytes(p.url+"/@v/"+pathEscape(encRev)+".info", &data)
if err != nil {
return nil, err
}
info := new(RevInfo)
if err := json.Unmarshal(data, info); err != nil {
return nil, err
}
return info, nil
}
func (p *proxyRepo) Latest() (*RevInfo, error) {
var data []byte
u := p.url + "/@latest"
err := webGetBytes(u, &data)
if err != nil {
// TODO return err if not 404
return p.latest()
}
info := new(RevInfo)
if err := json.Unmarshal(data, info); err != nil {
return nil, err
}
return info, nil
}
func (p *proxyRepo) GoMod(version string) ([]byte, error) {
var data []byte
encVer, err := module.EncodeVersion(version)
if err != nil {
return nil, err
}
err = webGetBytes(p.url+"/@v/"+pathEscape(encVer)+".mod", &data)
if err != nil {
return nil, err
}
return data, nil
}
func (p *proxyRepo) Zip(version string, tmpdir string) (tmpfile string, err error) {
var body io.ReadCloser
encVer, err := module.EncodeVersion(version)
if err != nil {
return "", err
}
err = webGetBody(p.url+"/@v/"+pathEscape(encVer)+".zip", &body)
if err != nil {
return "", err
}
defer body.Close()
// Spool to local file.
f, err := ioutil.TempFile(tmpdir, "go-proxy-download-")
if err != nil {
return "", err
}
defer f.Close()
maxSize := int64(codehost.MaxZipFile)
lr := &io.LimitedReader{R: body, N: maxSize + 1}
if _, err := io.Copy(f, lr); err != nil {
os.Remove(f.Name())
return "", err
}
if lr.N <= 0 {
os.Remove(f.Name())
return "", fmt.Errorf("downloaded zip file too large")
}
if err := f.Close(); err != nil {
os.Remove(f.Name())
return "", err
}
return f.Name(), nil
}
// pathEscape escapes s so it can be used in a path.
// That is, it escapes things like ? and # (which really shouldn't appear anyway).
// It does not escape / to %2F: our REST API is designed so that / can be left as is.
func pathEscape(s string) string {
return strings.Replace(url.PathEscape(s), "%2F", "/", -1)
}
|
codehost
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/codehost/vcs.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package codehost
import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"cmd/go/internal/par"
"cmd/go/internal/str"
)
// A VCSError indicates an error using a version control system.
// The implication of a VCSError is that we know definitively where
// to get the code, but we can't access it due to the error.
// The caller should report this error instead of continuing to probe
// other possible module paths.
type VCSError struct {
Err error
}
func (e *VCSError) Error() string { return e.Err.Error() }
func NewRepo(vcs, remote string) (Repo, error) {
type key struct {
vcs string
remote string
}
type cached struct {
repo Repo
err error
}
c := vcsRepoCache.Do(key{vcs, remote}, func() interface{} {
repo, err := newVCSRepo(vcs, remote)
if err != nil {
err = &VCSError{err}
}
return cached{repo, err}
}).(cached)
return c.repo, c.err
}
var vcsRepoCache par.Cache
type vcsRepo struct {
remote string
cmd *vcsCmd
dir string
tagsOnce sync.Once
tags map[string]bool
branchesOnce sync.Once
branches map[string]bool
fetchOnce sync.Once
fetchErr error
}
func newVCSRepo(vcs, remote string) (Repo, error) {
if vcs == "git" {
return newGitRepo(remote, false)
}
cmd := vcsCmds[vcs]
if cmd == nil {
return nil, fmt.Errorf("unknown vcs: %s %s", vcs, remote)
}
if !strings.Contains(remote, "://") {
return nil, fmt.Errorf("invalid vcs remote: %s %s", vcs, remote)
}
r := &vcsRepo{remote: remote, cmd: cmd}
if cmd.init == nil {
return r, nil
}
dir, err := WorkDir(vcsWorkDirType+vcs, r.remote)
if err != nil {
return nil, err
}
r.dir = dir
if _, err := os.Stat(filepath.Join(dir, "."+vcs)); err != nil {
if _, err := Run(dir, cmd.init(r.remote)); err != nil {
os.RemoveAll(dir)
return nil, err
}
}
return r, nil
}
const vcsWorkDirType = "vcs1."
type vcsCmd struct {
vcs string // vcs name "hg"
init func(remote string) []string // cmd to init repo to track remote
tags func(remote string) []string // cmd to list local tags
tagRE *regexp.Regexp // regexp to extract tag names from output of tags cmd
branches func(remote string) []string // cmd to list local branches
branchRE *regexp.Regexp // regexp to extract branch names from output of tags cmd
badLocalRevRE *regexp.Regexp // regexp of names that must not be served out of local cache without doing fetch first
statLocal func(rev, remote string) []string // cmd to stat local rev
parseStat func(rev, out string) (*RevInfo, error) // cmd to parse output of statLocal
fetch []string // cmd to fetch everything from remote
latest string // name of latest commit on remote (tip, HEAD, etc)
readFile func(rev, file, remote string) []string // cmd to read rev's file
readZip func(rev, subdir, remote, target string) []string // cmd to read rev's subdir as zip file
}
var re = regexp.MustCompile
var vcsCmds = map[string]*vcsCmd{
"hg": {
vcs: "hg",
init: func(remote string) []string {
return []string{"hg", "clone", "-U", remote, "."}
},
tags: func(remote string) []string {
return []string{"hg", "tags", "-q"}
},
tagRE: re(`(?m)^[^\n]+$`),
branches: func(remote string) []string {
return []string{"hg", "branches", "-c", "-q"}
},
branchRE: re(`(?m)^[^\n]+$`),
badLocalRevRE: re(`(?m)^(tip)$`),
statLocal: func(rev, remote string) []string {
return []string{"hg", "log", "-l1", "-r", rev, "--template", "{node} {date|hgdate} {tags}"}
},
parseStat: hgParseStat,
fetch: []string{"hg", "pull", "-f"},
latest: "tip",
readFile: func(rev, file, remote string) []string {
return []string{"hg", "cat", "-r", rev, file}
},
readZip: func(rev, subdir, remote, target string) []string {
pattern := []string{}
if subdir != "" {
pattern = []string{"-I", subdir + "/**"}
}
return str.StringList("hg", "archive", "-t", "zip", "--no-decode", "-r", rev, "--prefix=prefix/", pattern, target)
},
},
"svn": {
vcs: "svn",
init: nil, // no local checkout
tags: func(remote string) []string {
return []string{"svn", "list", strings.TrimSuffix(remote, "/trunk") + "/tags"}
},
tagRE: re(`(?m)^(.*?)/?$`),
statLocal: func(rev, remote string) []string {
suffix := "@" + rev
if rev == "latest" {
suffix = ""
}
return []string{"svn", "log", "-l1", "--xml", remote + suffix}
},
parseStat: svnParseStat,
latest: "latest",
readFile: func(rev, file, remote string) []string {
return []string{"svn", "cat", remote + "/" + file + "@" + rev}
},
// TODO: zip
},
"bzr": {
vcs: "bzr",
init: func(remote string) []string {
return []string{"bzr", "branch", "--use-existing-dir", remote, "."}
},
fetch: []string{
"bzr", "pull", "--overwrite-tags",
},
tags: func(remote string) []string {
return []string{"bzr", "tags"}
},
tagRE: re(`(?m)^\S+`),
badLocalRevRE: re(`^revno:-`),
statLocal: func(rev, remote string) []string {
return []string{"bzr", "log", "-l1", "--long", "--show-ids", "-r", rev}
},
parseStat: bzrParseStat,
latest: "revno:-1",
readFile: func(rev, file, remote string) []string {
return []string{"bzr", "cat", "-r", rev, file}
},
readZip: func(rev, subdir, remote, target string) []string {
extra := []string{}
if subdir != "" {
extra = []string{"./" + subdir}
}
return str.StringList("bzr", "export", "--format=zip", "-r", rev, "--root=prefix/", target, extra)
},
},
"fossil": {
vcs: "fossil",
init: func(remote string) []string {
return []string{"fossil", "clone", remote, ".fossil"}
},
fetch: []string{"fossil", "pull", "-R", ".fossil"},
tags: func(remote string) []string {
return []string{"fossil", "tag", "-R", ".fossil", "list"}
},
tagRE: re(`XXXTODO`),
statLocal: func(rev, remote string) []string {
return []string{"fossil", "info", "-R", ".fossil", rev}
},
parseStat: fossilParseStat,
latest: "trunk",
readFile: func(rev, file, remote string) []string {
return []string{"fossil", "cat", "-R", ".fossil", "-r", rev, file}
},
readZip: func(rev, subdir, remote, target string) []string {
extra := []string{}
if subdir != "" && !strings.ContainsAny(subdir, "*?[],") {
extra = []string{"--include", subdir}
}
// Note that vcsRepo.ReadZip below rewrites this command
// to run in a different directory, to work around a fossil bug.
return str.StringList("fossil", "zip", "-R", ".fossil", "--name", "prefix", extra, rev, target)
},
},
}
func (r *vcsRepo) loadTags() {
out, err := Run(r.dir, r.cmd.tags(r.remote))
if err != nil {
return
}
// Run tag-listing command and extract tags.
r.tags = make(map[string]bool)
for _, tag := range r.cmd.tagRE.FindAllString(string(out), -1) {
if r.cmd.badLocalRevRE != nil && r.cmd.badLocalRevRE.MatchString(tag) {
continue
}
r.tags[tag] = true
}
}
func (r *vcsRepo) loadBranches() {
if r.cmd.branches == nil {
return
}
out, err := Run(r.dir, r.cmd.branches(r.remote))
if err != nil {
return
}
r.branches = make(map[string]bool)
for _, branch := range r.cmd.branchRE.FindAllString(string(out), -1) {
if r.cmd.badLocalRevRE != nil && r.cmd.badLocalRevRE.MatchString(branch) {
continue
}
r.branches[branch] = true
}
}
func (r *vcsRepo) Tags(prefix string) ([]string, error) {
r.tagsOnce.Do(r.loadTags)
tags := []string{}
for tag := range r.tags {
if strings.HasPrefix(tag, prefix) {
tags = append(tags, tag)
}
}
sort.Strings(tags)
return tags, nil
}
func (r *vcsRepo) Stat(rev string) (*RevInfo, error) {
if rev == "latest" {
rev = r.cmd.latest
}
r.branchesOnce.Do(r.loadBranches)
revOK := (r.cmd.badLocalRevRE == nil || !r.cmd.badLocalRevRE.MatchString(rev)) && !r.branches[rev]
if revOK {
if info, err := r.statLocal(rev); err == nil {
return info, nil
}
}
r.fetchOnce.Do(r.fetch)
if r.fetchErr != nil {
return nil, r.fetchErr
}
info, err := r.statLocal(rev)
if err != nil {
return nil, err
}
if !revOK {
info.Version = info.Name
}
return info, nil
}
func (r *vcsRepo) fetch() {
_, r.fetchErr = Run(r.dir, r.cmd.fetch)
}
func (r *vcsRepo) statLocal(rev string) (*RevInfo, error) {
out, err := Run(r.dir, r.cmd.statLocal(rev, r.remote))
if err != nil {
return nil, fmt.Errorf("unknown revision %s", rev)
}
return r.cmd.parseStat(rev, string(out))
}
func (r *vcsRepo) Latest() (*RevInfo, error) {
return r.Stat("latest")
}
func (r *vcsRepo) ReadFile(rev, file string, maxSize int64) ([]byte, error) {
if rev == "latest" {
rev = r.cmd.latest
}
_, err := r.Stat(rev) // download rev into local repo
if err != nil {
return nil, err
}
out, err := Run(r.dir, r.cmd.readFile(rev, file, r.remote))
if err != nil {
return nil, os.ErrNotExist
}
return out, nil
}
func (r *vcsRepo) ReadFileRevs(revs []string, file string, maxSize int64) (map[string]*FileRev, error) {
return nil, fmt.Errorf("ReadFileRevs not implemented")
}
func (r *vcsRepo) RecentTag(rev, prefix string) (tag string, err error) {
return "", fmt.Errorf("RecentTags not implemented")
}
func (r *vcsRepo) ReadZip(rev, subdir string, maxSize int64) (zip io.ReadCloser, actualSubdir string, err error) {
if rev == "latest" {
rev = r.cmd.latest
}
f, err := ioutil.TempFile("", "go-readzip-*.zip")
if err != nil {
return nil, "", err
}
if r.cmd.vcs == "fossil" {
// If you run
// fossil zip -R .fossil --name prefix trunk /tmp/x.zip
// fossil fails with "unable to create directory /tmp" [sic].
// Change the command to run in /tmp instead,
// replacing the -R argument with an absolute path.
args := r.cmd.readZip(rev, subdir, r.remote, filepath.Base(f.Name()))
for i := range args {
if args[i] == ".fossil" {
args[i] = filepath.Join(r.dir, ".fossil")
}
}
_, err = Run(filepath.Dir(f.Name()), args)
} else {
_, err = Run(r.dir, r.cmd.readZip(rev, subdir, r.remote, f.Name()))
}
if err != nil {
f.Close()
os.Remove(f.Name())
return nil, "", err
}
return &deleteCloser{f}, "", nil
}
// deleteCloser is a file that gets deleted on Close.
type deleteCloser struct {
*os.File
}
func (d *deleteCloser) Close() error {
defer os.Remove(d.File.Name())
return d.File.Close()
}
func hgParseStat(rev, out string) (*RevInfo, error) {
f := strings.Fields(string(out))
if len(f) < 3 {
return nil, fmt.Errorf("unexpected response from hg log: %q", out)
}
hash := f[0]
version := rev
if strings.HasPrefix(hash, version) {
version = hash // extend to full hash
}
t, err := strconv.ParseInt(f[1], 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid time from hg log: %q", out)
}
var tags []string
for _, tag := range f[3:] {
if tag != "tip" {
tags = append(tags, tag)
}
}
sort.Strings(tags)
info := &RevInfo{
Name: hash,
Short: ShortenSHA1(hash),
Time: time.Unix(t, 0).UTC(),
Version: version,
Tags: tags,
}
return info, nil
}
func svnParseStat(rev, out string) (*RevInfo, error) {
var log struct {
Logentry struct {
Revision int64 `xml:"revision,attr"`
Date string `xml:"date"`
} `xml:"logentry"`
}
if err := xml.Unmarshal([]byte(out), &log); err != nil {
return nil, fmt.Errorf("unexpected response from svn log --xml: %v\n%s", err, out)
}
t, err := time.Parse(time.RFC3339, log.Logentry.Date)
if err != nil {
return nil, fmt.Errorf("unexpected response from svn log --xml: %v\n%s", err, out)
}
info := &RevInfo{
Name: fmt.Sprintf("%d", log.Logentry.Revision),
Short: fmt.Sprintf("%012d", log.Logentry.Revision),
Time: t.UTC(),
Version: rev,
}
return info, nil
}
func bzrParseStat(rev, out string) (*RevInfo, error) {
var revno int64
var tm time.Time
for _, line := range strings.Split(out, "\n") {
if line == "" || line[0] == ' ' || line[0] == '\t' {
// End of header, start of commit message.
break
}
if line[0] == '-' {
continue
}
i := strings.Index(line, ":")
if i < 0 {
// End of header, start of commit message.
break
}
key, val := line[:i], strings.TrimSpace(line[i+1:])
switch key {
case "revno":
if j := strings.Index(val, " "); j >= 0 {
val = val[:j]
}
i, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return nil, fmt.Errorf("unexpected revno from bzr log: %q", line)
}
revno = i
case "timestamp":
j := strings.Index(val, " ")
if j < 0 {
return nil, fmt.Errorf("unexpected timestamp from bzr log: %q", line)
}
t, err := time.Parse("2006-01-02 15:04:05 -0700", val[j+1:])
if err != nil {
return nil, fmt.Errorf("unexpected timestamp from bzr log: %q", line)
}
tm = t.UTC()
}
}
if revno == 0 || tm.IsZero() {
return nil, fmt.Errorf("unexpected response from bzr log: %q", out)
}
info := &RevInfo{
Name: fmt.Sprintf("%d", revno),
Short: fmt.Sprintf("%012d", revno),
Time: tm,
Version: rev,
}
return info, nil
}
func fossilParseStat(rev, out string) (*RevInfo, error) {
for _, line := range strings.Split(out, "\n") {
if strings.HasPrefix(line, "uuid:") {
f := strings.Fields(line)
if len(f) != 5 || len(f[1]) != 40 || f[4] != "UTC" {
return nil, fmt.Errorf("unexpected response from fossil info: %q", line)
}
t, err := time.Parse("2006-01-02 15:04:05", f[2]+" "+f[3])
if err != nil {
return nil, fmt.Errorf("unexpected response from fossil info: %q", line)
}
hash := f[1]
version := rev
if strings.HasPrefix(hash, version) {
version = hash // extend to full hash
}
info := &RevInfo{
Name: hash,
Short: ShortenSHA1(hash),
Time: t,
Version: version,
}
return info, nil
}
}
return nil, fmt.Errorf("unexpected response from fossil info: %q", out)
}
|
codehost
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/codehost/shell.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
// Interactive debugging shell for codehost.Repo implementations.
package main
import (
"archive/zip"
"bufio"
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"time"
"cmd/go/internal/modfetch/codehost"
)
func usage() {
fmt.Fprintf(os.Stderr, "usage: go run shell.go vcs remote\n")
os.Exit(2)
}
func main() {
codehost.WorkRoot = "/tmp/vcswork"
log.SetFlags(0)
log.SetPrefix("shell: ")
flag.Usage = usage
flag.Parse()
if flag.NArg() != 2 {
usage()
}
repo, err := codehost.NewRepo(flag.Arg(0), flag.Arg(1))
if err != nil {
log.Fatal(err)
}
b := bufio.NewReader(os.Stdin)
for {
fmt.Fprintf(os.Stderr, ">>> ")
line, err := b.ReadString('\n')
if err != nil {
log.Fatal(err)
}
f := strings.Fields(line)
if len(f) == 0 {
continue
}
switch f[0] {
default:
fmt.Fprintf(os.Stderr, "?unknown command\n")
continue
case "tags":
prefix := ""
if len(f) == 2 {
prefix = f[1]
}
if len(f) > 2 {
fmt.Fprintf(os.Stderr, "?usage: tags [prefix]\n")
continue
}
tags, err := repo.Tags(prefix)
if err != nil {
fmt.Fprintf(os.Stderr, "?%s\n", err)
continue
}
for _, tag := range tags {
fmt.Printf("%s\n", tag)
}
case "stat":
if len(f) != 2 {
fmt.Fprintf(os.Stderr, "?usage: stat rev\n")
continue
}
info, err := repo.Stat(f[1])
if err != nil {
fmt.Fprintf(os.Stderr, "?%s\n", err)
continue
}
fmt.Printf("name=%s short=%s version=%s time=%s\n", info.Name, info.Short, info.Version, info.Time.UTC().Format(time.RFC3339))
case "read":
if len(f) != 3 {
fmt.Fprintf(os.Stderr, "?usage: read rev file\n")
continue
}
data, err := repo.ReadFile(f[1], f[2], 10<<20)
if err != nil {
fmt.Fprintf(os.Stderr, "?%s\n", err)
continue
}
os.Stdout.Write(data)
case "zip":
if len(f) != 4 {
fmt.Fprintf(os.Stderr, "?usage: zip rev subdir output\n")
continue
}
subdir := f[2]
if subdir == "-" {
subdir = ""
}
rc, _, err := repo.ReadZip(f[1], subdir, 10<<20)
if err != nil {
fmt.Fprintf(os.Stderr, "?%s\n", err)
continue
}
data, err := ioutil.ReadAll(rc)
rc.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "?%s\n", err)
continue
}
if f[3] != "-" {
if err := ioutil.WriteFile(f[3], data, 0666); err != nil {
fmt.Fprintf(os.Stderr, "?%s\n", err)
continue
}
}
z, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
fmt.Fprintf(os.Stderr, "?%s\n", err)
continue
}
for _, f := range z.File {
fmt.Printf("%s %d\n", f.Name, f.UncompressedSize64)
}
}
}
}
|
codehost
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/codehost/codehost.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package codehost defines the interface implemented by a code hosting source,
// along with support code for use by implementations.
package codehost
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"cmd/go/internal/cfg"
"cmd/go/internal/str"
)
// Downloaded size limits.
const (
MaxGoMod = 16 << 20 // maximum size of go.mod file
MaxLICENSE = 16 << 20 // maximum size of LICENSE file
MaxZipFile = 500 << 20 // maximum size of downloaded zip file
)
// A Repo represents a code hosting source.
// Typical implementations include local version control repositories,
// remote version control servers, and code hosting sites.
// A Repo must be safe for simultaneous use by multiple goroutines.
type Repo interface {
// List lists all tags with the given prefix.
Tags(prefix string) (tags []string, err error)
// Stat returns information about the revision rev.
// A revision can be any identifier known to the underlying service:
// commit hash, branch, tag, and so on.
Stat(rev string) (*RevInfo, error)
// Latest returns the latest revision on the default branch,
// whatever that means in the underlying implementation.
Latest() (*RevInfo, error)
// ReadFile reads the given file in the file tree corresponding to revision rev.
// It should refuse to read more than maxSize bytes.
//
// If the requested file does not exist it should return an error for which
// os.IsNotExist(err) returns true.
ReadFile(rev, file string, maxSize int64) (data []byte, err error)
// ReadFileRevs reads a single file at multiple versions.
// It should refuse to read more than maxSize bytes.
// The result is a map from each requested rev strings
// to the associated FileRev. The map must have a non-nil
// entry for every requested rev (unless ReadFileRevs returned an error).
// A file simply being missing or even corrupted in revs[i]
// should be reported only in files[revs[i]].Err, not in the error result
// from ReadFileRevs.
// The overall call should return an error (and no map) only
// in the case of a problem with obtaining the data, such as
// a network failure.
// Implementations may assume that revs only contain tags,
// not direct commit hashes.
ReadFileRevs(revs []string, file string, maxSize int64) (files map[string]*FileRev, err error)
// ReadZip downloads a zip file for the subdir subdirectory
// of the given revision to a new file in a given temporary directory.
// It should refuse to read more than maxSize bytes.
// It returns a ReadCloser for a streamed copy of the zip file,
// along with the actual subdirectory (possibly shorter than subdir)
// contained in the zip file. All files in the zip file are expected to be
// nested in a single top-level directory, whose name is not specified.
ReadZip(rev, subdir string, maxSize int64) (zip io.ReadCloser, actualSubdir string, err error)
// RecentTag returns the most recent tag at or before the given rev
// with the given prefix. It should make a best-effort attempt to
// find a tag that is a valid semantic version (following the prefix),
// or else the result is not useful to the caller, but it need not
// incur great expense in doing so. For example, the git implementation
// of RecentTag limits git's search to tags matching the glob expression
// "v[0-9]*.[0-9]*.[0-9]*" (after the prefix).
RecentTag(rev, prefix string) (tag string, err error)
}
// A Rev describes a single revision in a source code repository.
type RevInfo struct {
Name string // complete ID in underlying repository
Short string // shortened ID, for use in pseudo-version
Version string // version used in lookup
Time time.Time // commit time
Tags []string // known tags for commit
}
// A FileRev describes the result of reading a file at a given revision.
type FileRev struct {
Rev string // requested revision
Data []byte // file data
Err error // error if any; os.IsNotExist(Err)==true if rev exists but file does not exist in that rev
}
// AllHex reports whether the revision rev is entirely lower-case hexadecimal digits.
func AllHex(rev string) bool {
for i := 0; i < len(rev); i++ {
c := rev[i]
if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' {
continue
}
return false
}
return true
}
// ShortenSHA1 shortens a SHA1 hash (40 hex digits) to the canonical length
// used in pseudo-versions (12 hex digits).
func ShortenSHA1(rev string) string {
if AllHex(rev) && len(rev) == 40 {
return rev[:12]
}
return rev
}
// WorkRoot is the root of the cached work directory.
// It is set by cmd/go/internal/modload.InitMod.
var WorkRoot string
// WorkDir returns the name of the cached work directory to use for the
// given repository type and name.
func WorkDir(typ, name string) (string, error) {
if WorkRoot == "" {
return "", fmt.Errorf("codehost.WorkRoot not set")
}
// We name the work directory for the SHA256 hash of the type and name.
// We intentionally avoid the actual name both because of possible
// conflicts with valid file system paths and because we want to ensure
// that one checkout is never nested inside another. That nesting has
// led to security problems in the past.
if strings.Contains(typ, ":") {
return "", fmt.Errorf("codehost.WorkDir: type cannot contain colon")
}
key := typ + ":" + name
dir := filepath.Join(WorkRoot, fmt.Sprintf("%x", sha256.Sum256([]byte(key))))
data, err := ioutil.ReadFile(dir + ".info")
info, err2 := os.Stat(dir)
if err == nil && err2 == nil && info.IsDir() {
// Info file and directory both already exist: reuse.
have := strings.TrimSuffix(string(data), "\n")
if have != key {
return "", fmt.Errorf("%s exists with wrong content (have %q want %q)", dir+".info", have, key)
}
if cfg.BuildX {
fmt.Fprintf(os.Stderr, "# %s for %s %s\n", dir, typ, name)
}
return dir, nil
}
// Info file or directory missing. Start from scratch.
if cfg.BuildX {
fmt.Fprintf(os.Stderr, "mkdir -p %s # %s %s\n", dir, typ, name)
}
os.RemoveAll(dir)
if err := os.MkdirAll(dir, 0777); err != nil {
return "", err
}
if err := ioutil.WriteFile(dir+".info", []byte(key), 0666); err != nil {
os.RemoveAll(dir)
return "", err
}
return dir, nil
}
type RunError struct {
Cmd string
Err error
Stderr []byte
}
func (e *RunError) Error() string {
text := e.Cmd + ": " + e.Err.Error()
stderr := bytes.TrimRight(e.Stderr, "\n")
if len(stderr) > 0 {
text += ":\n\t" + strings.Replace(string(stderr), "\n", "\n\t", -1)
}
return text
}
var dirLock sync.Map
// Run runs the command line in the given directory
// (an empty dir means the current directory).
// It returns the standard output and, for a non-zero exit,
// a *RunError indicating the command, exit status, and standard error.
// Standard error is unavailable for commands that exit successfully.
func Run(dir string, cmdline ...interface{}) ([]byte, error) {
return RunWithStdin(dir, nil, cmdline...)
}
// bashQuoter escapes characters that have special meaning in double-quoted strings in the bash shell.
// See https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html.
var bashQuoter = strings.NewReplacer(`"`, `\"`, `$`, `\$`, "`", "\\`", `\`, `\\`)
func RunWithStdin(dir string, stdin io.Reader, cmdline ...interface{}) ([]byte, error) {
if dir != "" {
muIface, ok := dirLock.Load(dir)
if !ok {
muIface, _ = dirLock.LoadOrStore(dir, new(sync.Mutex))
}
mu := muIface.(*sync.Mutex)
mu.Lock()
defer mu.Unlock()
}
cmd := str.StringList(cmdline...)
if cfg.BuildX {
text := new(strings.Builder)
if dir != "" {
text.WriteString("cd ")
text.WriteString(dir)
text.WriteString("; ")
}
for i, arg := range cmd {
if i > 0 {
text.WriteByte(' ')
}
switch {
case strings.ContainsAny(arg, "'"):
// Quote args that could be mistaken for quoted args.
text.WriteByte('"')
text.WriteString(bashQuoter.Replace(arg))
text.WriteByte('"')
case strings.ContainsAny(arg, "$`\\*?[\"\t\n\v\f\r \u0085\u00a0"):
// Quote args that contain special characters, glob patterns, or spaces.
text.WriteByte('\'')
text.WriteString(arg)
text.WriteByte('\'')
default:
text.WriteString(arg)
}
}
fmt.Fprintf(os.Stderr, "%s\n", text)
start := time.Now()
defer func() {
fmt.Fprintf(os.Stderr, "%.3fs # %s\n", time.Since(start).Seconds(), text)
}()
}
// TODO: Impose limits on command output size.
// TODO: Set environment to get English error messages.
var stderr bytes.Buffer
var stdout bytes.Buffer
c := exec.Command(cmd[0], cmd[1:]...)
c.Dir = dir
c.Stdin = stdin
c.Stderr = &stderr
c.Stdout = &stdout
err := c.Run()
if err != nil {
err = &RunError{Cmd: strings.Join(cmd, " ") + " in " + dir, Stderr: stderr.Bytes(), Err: err}
}
return stdout.Bytes(), err
}
|
codehost
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/codehost/git_test.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package codehost
import (
"archive/zip"
"bytes"
"flag"
"fmt"
"internal/testenv"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
)
func TestMain(m *testing.M) {
// needed for initializing the test environment variables as testing.Short
// and HasExternalNetwork
flag.Parse()
os.Exit(testMain(m))
}
const (
gitrepo1 = "https://vcs-test.golang.org/git/gitrepo1"
hgrepo1 = "https://vcs-test.golang.org/hg/hgrepo1"
)
var altRepos = []string{
"localGitRepo",
hgrepo1,
}
// TODO: Convert gitrepo1 to svn, bzr, fossil and add tests.
// For now, at least the hgrepo1 tests check the general vcs.go logic.
// localGitRepo is like gitrepo1 but allows archive access.
var localGitRepo string
func testMain(m *testing.M) int {
if _, err := exec.LookPath("git"); err != nil {
fmt.Fprintln(os.Stderr, "skipping because git binary not found")
fmt.Println("PASS")
return 0
}
dir, err := ioutil.TempDir("", "gitrepo-test-")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
WorkRoot = dir
if testenv.HasExternalNetwork() && testenv.HasExec() {
// Clone gitrepo1 into a local directory.
// If we use a file:// URL to access the local directory,
// then git starts up all the usual protocol machinery,
// which will let us test remote git archive invocations.
localGitRepo = filepath.Join(dir, "gitrepo2")
if _, err := Run("", "git", "clone", "--mirror", gitrepo1, localGitRepo); err != nil {
log.Fatal(err)
}
if _, err := Run(localGitRepo, "git", "config", "daemon.uploadarch", "true"); err != nil {
log.Fatal(err)
}
}
return m.Run()
}
func testRepo(remote string) (Repo, error) {
if remote == "localGitRepo" {
return LocalGitRepo(filepath.ToSlash(localGitRepo))
}
kind := "git"
for _, k := range []string{"hg"} {
if strings.Contains(remote, "/"+k+"/") {
kind = k
}
}
return NewRepo(kind, remote)
}
var tagsTests = []struct {
repo string
prefix string
tags []string
}{
{gitrepo1, "xxx", []string{}},
{gitrepo1, "", []string{"v1.2.3", "v1.2.4-annotated", "v2.0.1", "v2.0.2", "v2.3"}},
{gitrepo1, "v", []string{"v1.2.3", "v1.2.4-annotated", "v2.0.1", "v2.0.2", "v2.3"}},
{gitrepo1, "v1", []string{"v1.2.3", "v1.2.4-annotated"}},
{gitrepo1, "2", []string{}},
}
func TestTags(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
testenv.MustHaveExec(t)
for _, tt := range tagsTests {
f := func(t *testing.T) {
r, err := testRepo(tt.repo)
if err != nil {
t.Fatal(err)
}
tags, err := r.Tags(tt.prefix)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(tags, tt.tags) {
t.Errorf("Tags: incorrect tags\nhave %v\nwant %v", tags, tt.tags)
}
}
t.Run(path.Base(tt.repo)+"/"+tt.prefix, f)
if tt.repo == gitrepo1 {
for _, tt.repo = range altRepos {
t.Run(path.Base(tt.repo)+"/"+tt.prefix, f)
}
}
}
}
var latestTests = []struct {
repo string
info *RevInfo
}{
{
gitrepo1,
&RevInfo{
Name: "ede458df7cd0fdca520df19a33158086a8a68e81",
Short: "ede458df7cd0",
Version: "ede458df7cd0fdca520df19a33158086a8a68e81",
Time: time.Date(2018, 4, 17, 19, 43, 22, 0, time.UTC),
Tags: []string{"v1.2.3", "v1.2.4-annotated"},
},
},
{
hgrepo1,
&RevInfo{
Name: "18518c07eb8ed5c80221e997e518cccaa8c0c287",
Short: "18518c07eb8e",
Version: "18518c07eb8ed5c80221e997e518cccaa8c0c287",
Time: time.Date(2018, 6, 27, 16, 16, 30, 0, time.UTC),
},
},
}
func TestLatest(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
testenv.MustHaveExec(t)
for _, tt := range latestTests {
f := func(t *testing.T) {
r, err := testRepo(tt.repo)
if err != nil {
t.Fatal(err)
}
info, err := r.Latest()
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(info, tt.info) {
t.Errorf("Latest: incorrect info\nhave %+v\nwant %+v", *info, *tt.info)
}
}
t.Run(path.Base(tt.repo), f)
if tt.repo == gitrepo1 {
tt.repo = "localGitRepo"
t.Run(path.Base(tt.repo), f)
}
}
}
var readFileTests = []struct {
repo string
rev string
file string
err string
data string
}{
{
repo: gitrepo1,
rev: "latest",
file: "README",
data: "",
},
{
repo: gitrepo1,
rev: "v2",
file: "another.txt",
data: "another\n",
},
{
repo: gitrepo1,
rev: "v2.3.4",
file: "another.txt",
err: os.ErrNotExist.Error(),
},
}
func TestReadFile(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
testenv.MustHaveExec(t)
for _, tt := range readFileTests {
f := func(t *testing.T) {
r, err := testRepo(tt.repo)
if err != nil {
t.Fatal(err)
}
data, err := r.ReadFile(tt.rev, tt.file, 100)
if err != nil {
if tt.err == "" {
t.Fatalf("ReadFile: unexpected error %v", err)
}
if !strings.Contains(err.Error(), tt.err) {
t.Fatalf("ReadFile: wrong error %q, want %q", err, tt.err)
}
if len(data) != 0 {
t.Errorf("ReadFile: non-empty data %q with error %v", data, err)
}
return
}
if tt.err != "" {
t.Fatalf("ReadFile: no error, wanted %v", tt.err)
}
if string(data) != tt.data {
t.Errorf("ReadFile: incorrect data\nhave %q\nwant %q", data, tt.data)
}
}
t.Run(path.Base(tt.repo)+"/"+tt.rev+"/"+tt.file, f)
if tt.repo == gitrepo1 {
for _, tt.repo = range altRepos {
t.Run(path.Base(tt.repo)+"/"+tt.rev+"/"+tt.file, f)
}
}
}
}
var readZipTests = []struct {
repo string
rev string
subdir string
actualSubdir string
err string
files map[string]uint64
}{
{
repo: gitrepo1,
rev: "v2.3.4",
subdir: "",
files: map[string]uint64{
"prefix/": 0,
"prefix/README": 0,
"prefix/v2": 3,
},
},
{
repo: hgrepo1,
rev: "v2.3.4",
subdir: "",
files: map[string]uint64{
"prefix/.hg_archival.txt": ^uint64(0),
"prefix/README": 0,
"prefix/v2": 3,
},
},
{
repo: gitrepo1,
rev: "v2",
subdir: "",
files: map[string]uint64{
"prefix/": 0,
"prefix/README": 0,
"prefix/v2": 3,
"prefix/another.txt": 8,
"prefix/foo.txt": 13,
},
},
{
repo: hgrepo1,
rev: "v2",
subdir: "",
files: map[string]uint64{
"prefix/.hg_archival.txt": ^uint64(0),
"prefix/README": 0,
"prefix/v2": 3,
"prefix/another.txt": 8,
"prefix/foo.txt": 13,
},
},
{
repo: gitrepo1,
rev: "v3",
subdir: "",
files: map[string]uint64{
"prefix/": 0,
"prefix/v3/": 0,
"prefix/v3/sub/": 0,
"prefix/v3/sub/dir/": 0,
"prefix/v3/sub/dir/file.txt": 16,
"prefix/README": 0,
},
},
{
repo: hgrepo1,
rev: "v3",
subdir: "",
files: map[string]uint64{
"prefix/.hg_archival.txt": ^uint64(0),
"prefix/.hgtags": 405,
"prefix/v3/sub/dir/file.txt": 16,
"prefix/README": 0,
},
},
{
repo: gitrepo1,
rev: "v3",
subdir: "v3/sub/dir",
files: map[string]uint64{
"prefix/": 0,
"prefix/v3/": 0,
"prefix/v3/sub/": 0,
"prefix/v3/sub/dir/": 0,
"prefix/v3/sub/dir/file.txt": 16,
},
},
{
repo: hgrepo1,
rev: "v3",
subdir: "v3/sub/dir",
files: map[string]uint64{
"prefix/v3/sub/dir/file.txt": 16,
},
},
{
repo: gitrepo1,
rev: "v3",
subdir: "v3/sub",
files: map[string]uint64{
"prefix/": 0,
"prefix/v3/": 0,
"prefix/v3/sub/": 0,
"prefix/v3/sub/dir/": 0,
"prefix/v3/sub/dir/file.txt": 16,
},
},
{
repo: hgrepo1,
rev: "v3",
subdir: "v3/sub",
files: map[string]uint64{
"prefix/v3/sub/dir/file.txt": 16,
},
},
{
repo: gitrepo1,
rev: "aaaaaaaaab",
subdir: "",
err: "unknown revision",
},
{
repo: hgrepo1,
rev: "aaaaaaaaab",
subdir: "",
err: "unknown revision",
},
{
repo: "https://github.com/rsc/vgotest1",
rev: "submod/v1.0.4",
subdir: "submod",
files: map[string]uint64{
"prefix/": 0,
"prefix/submod/": 0,
"prefix/submod/go.mod": 53,
"prefix/submod/pkg/": 0,
"prefix/submod/pkg/p.go": 31,
},
},
}
type zipFile struct {
name string
size int64
}
func TestReadZip(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
testenv.MustHaveExec(t)
for _, tt := range readZipTests {
f := func(t *testing.T) {
r, err := testRepo(tt.repo)
if err != nil {
t.Fatal(err)
}
rc, actualSubdir, err := r.ReadZip(tt.rev, tt.subdir, 100000)
if err != nil {
if tt.err == "" {
t.Fatalf("ReadZip: unexpected error %v", err)
}
if !strings.Contains(err.Error(), tt.err) {
t.Fatalf("ReadZip: wrong error %q, want %q", err, tt.err)
}
if rc != nil {
t.Errorf("ReadZip: non-nil io.ReadCloser with error %v", err)
}
return
}
defer rc.Close()
if tt.err != "" {
t.Fatalf("ReadZip: no error, wanted %v", tt.err)
}
if actualSubdir != tt.actualSubdir {
t.Fatalf("ReadZip: actualSubdir = %q, want %q", actualSubdir, tt.actualSubdir)
}
zipdata, err := ioutil.ReadAll(rc)
if err != nil {
t.Fatal(err)
}
z, err := zip.NewReader(bytes.NewReader(zipdata), int64(len(zipdata)))
if err != nil {
t.Fatalf("ReadZip: cannot read zip file: %v", err)
}
have := make(map[string]bool)
for _, f := range z.File {
size, ok := tt.files[f.Name]
if !ok {
t.Errorf("ReadZip: unexpected file %s", f.Name)
continue
}
have[f.Name] = true
if size != ^uint64(0) && f.UncompressedSize64 != size {
t.Errorf("ReadZip: file %s has unexpected size %d != %d", f.Name, f.UncompressedSize64, size)
}
}
for name := range tt.files {
if !have[name] {
t.Errorf("ReadZip: missing file %s", name)
}
}
}
t.Run(path.Base(tt.repo)+"/"+tt.rev+"/"+tt.subdir, f)
if tt.repo == gitrepo1 {
tt.repo = "localGitRepo"
t.Run(path.Base(tt.repo)+"/"+tt.rev+"/"+tt.subdir, f)
}
}
}
var hgmap = map[string]string{
"HEAD": "41964ddce1180313bdc01d0a39a2813344d6261d", // not tip due to bad hgrepo1 conversion
"9d02800338b8a55be062c838d1f02e0c5780b9eb": "8f49ee7a6ddcdec6f0112d9dca48d4a2e4c3c09e",
"76a00fb249b7f93091bc2c89a789dab1fc1bc26f": "88fde824ec8b41a76baa16b7e84212cee9f3edd0",
"ede458df7cd0fdca520df19a33158086a8a68e81": "41964ddce1180313bdc01d0a39a2813344d6261d",
"97f6aa59c81c623494825b43d39e445566e429a4": "c0cbbfb24c7c3c50c35c7b88e7db777da4ff625d",
}
var statTests = []struct {
repo string
rev string
err string
info *RevInfo
}{
{
repo: gitrepo1,
rev: "HEAD",
info: &RevInfo{
Name: "ede458df7cd0fdca520df19a33158086a8a68e81",
Short: "ede458df7cd0",
Version: "ede458df7cd0fdca520df19a33158086a8a68e81",
Time: time.Date(2018, 4, 17, 19, 43, 22, 0, time.UTC),
Tags: []string{"v1.2.3", "v1.2.4-annotated"},
},
},
{
repo: gitrepo1,
rev: "v2", // branch
info: &RevInfo{
Name: "9d02800338b8a55be062c838d1f02e0c5780b9eb",
Short: "9d02800338b8",
Version: "9d02800338b8a55be062c838d1f02e0c5780b9eb",
Time: time.Date(2018, 4, 17, 20, 00, 32, 0, time.UTC),
Tags: []string{"v2.0.2"},
},
},
{
repo: gitrepo1,
rev: "v2.3.4", // badly-named branch (semver should be a tag)
info: &RevInfo{
Name: "76a00fb249b7f93091bc2c89a789dab1fc1bc26f",
Short: "76a00fb249b7",
Version: "76a00fb249b7f93091bc2c89a789dab1fc1bc26f",
Time: time.Date(2018, 4, 17, 19, 45, 48, 0, time.UTC),
Tags: []string{"v2.0.1", "v2.3"},
},
},
{
repo: gitrepo1,
rev: "v2.3", // badly-named tag (we only respect full semver v2.3.0)
info: &RevInfo{
Name: "76a00fb249b7f93091bc2c89a789dab1fc1bc26f",
Short: "76a00fb249b7",
Version: "v2.3",
Time: time.Date(2018, 4, 17, 19, 45, 48, 0, time.UTC),
Tags: []string{"v2.0.1", "v2.3"},
},
},
{
repo: gitrepo1,
rev: "v1.2.3", // tag
info: &RevInfo{
Name: "ede458df7cd0fdca520df19a33158086a8a68e81",
Short: "ede458df7cd0",
Version: "v1.2.3",
Time: time.Date(2018, 4, 17, 19, 43, 22, 0, time.UTC),
Tags: []string{"v1.2.3", "v1.2.4-annotated"},
},
},
{
repo: gitrepo1,
rev: "ede458df", // hash prefix in refs
info: &RevInfo{
Name: "ede458df7cd0fdca520df19a33158086a8a68e81",
Short: "ede458df7cd0",
Version: "ede458df7cd0fdca520df19a33158086a8a68e81",
Time: time.Date(2018, 4, 17, 19, 43, 22, 0, time.UTC),
Tags: []string{"v1.2.3", "v1.2.4-annotated"},
},
},
{
repo: gitrepo1,
rev: "97f6aa59", // hash prefix not in refs
info: &RevInfo{
Name: "97f6aa59c81c623494825b43d39e445566e429a4",
Short: "97f6aa59c81c",
Version: "97f6aa59c81c623494825b43d39e445566e429a4",
Time: time.Date(2018, 4, 17, 20, 0, 19, 0, time.UTC),
},
},
{
repo: gitrepo1,
rev: "v1.2.4-annotated", // annotated tag uses unwrapped commit hash
info: &RevInfo{
Name: "ede458df7cd0fdca520df19a33158086a8a68e81",
Short: "ede458df7cd0",
Version: "v1.2.4-annotated",
Time: time.Date(2018, 4, 17, 19, 43, 22, 0, time.UTC),
Tags: []string{"v1.2.3", "v1.2.4-annotated"},
},
},
{
repo: gitrepo1,
rev: "aaaaaaaaab",
err: "unknown revision",
},
}
func TestStat(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
testenv.MustHaveExec(t)
for _, tt := range statTests {
f := func(t *testing.T) {
r, err := testRepo(tt.repo)
if err != nil {
t.Fatal(err)
}
info, err := r.Stat(tt.rev)
if err != nil {
if tt.err == "" {
t.Fatalf("Stat: unexpected error %v", err)
}
if !strings.Contains(err.Error(), tt.err) {
t.Fatalf("Stat: wrong error %q, want %q", err, tt.err)
}
if info != nil {
t.Errorf("Stat: non-nil info with error %q", err)
}
return
}
if !reflect.DeepEqual(info, tt.info) {
t.Errorf("Stat: incorrect info\nhave %+v\nwant %+v", *info, *tt.info)
}
}
t.Run(path.Base(tt.repo)+"/"+tt.rev, f)
if tt.repo == gitrepo1 {
for _, tt.repo = range altRepos {
old := tt
var m map[string]string
if tt.repo == hgrepo1 {
m = hgmap
}
if tt.info != nil {
info := *tt.info
tt.info = &info
tt.info.Name = remap(tt.info.Name, m)
tt.info.Version = remap(tt.info.Version, m)
tt.info.Short = remap(tt.info.Short, m)
}
tt.rev = remap(tt.rev, m)
t.Run(path.Base(tt.repo)+"/"+tt.rev, f)
tt = old
}
}
}
}
func remap(name string, m map[string]string) string {
if m[name] != "" {
return m[name]
}
if AllHex(name) {
for k, v := range m {
if strings.HasPrefix(k, name) {
return v[:len(name)]
}
}
}
return name
}
|
codehost
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfetch/codehost/git.go
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package codehost
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"cmd/go/internal/par"
)
// GitRepo returns the code repository at the given Git remote reference.
func GitRepo(remote string) (Repo, error) {
return newGitRepoCached(remote, false)
}
// LocalGitRepo is like Repo but accepts both Git remote references
// and paths to repositories on the local file system.
func LocalGitRepo(remote string) (Repo, error) {
return newGitRepoCached(remote, true)
}
const gitWorkDirType = "git2"
var gitRepoCache par.Cache
func newGitRepoCached(remote string, localOK bool) (Repo, error) {
type key struct {
remote string
localOK bool
}
type cached struct {
repo Repo
err error
}
c := gitRepoCache.Do(key{remote, localOK}, func() interface{} {
repo, err := newGitRepo(remote, localOK)
return cached{repo, err}
}).(cached)
return c.repo, c.err
}
func newGitRepo(remote string, localOK bool) (Repo, error) {
r := &gitRepo{remote: remote}
if strings.Contains(remote, "://") {
// This is a remote path.
dir, err := WorkDir(gitWorkDirType, r.remote)
if err != nil {
return nil, err
}
r.dir = dir
if _, err := os.Stat(filepath.Join(dir, "objects")); err != nil {
if _, err := Run(dir, "git", "init", "--bare"); err != nil {
os.RemoveAll(dir)
return nil, err
}
// We could just say git fetch https://whatever later,
// but this lets us say git fetch origin instead, which
// is a little nicer. More importantly, using a named remote
// avoids a problem with Git LFS. See golang.org/issue/25605.
if _, err := Run(dir, "git", "remote", "add", "origin", r.remote); err != nil {
os.RemoveAll(dir)
return nil, err
}
r.remote = "origin"
}
} else {
// Local path.
// Disallow colon (not in ://) because sometimes
// that's rcp-style host:path syntax and sometimes it's not (c:\work).
// The go command has always insisted on URL syntax for ssh.
if strings.Contains(remote, ":") {
return nil, fmt.Errorf("git remote cannot use host:path syntax")
}
if !localOK {
return nil, fmt.Errorf("git remote must not be local directory")
}
r.local = true
info, err := os.Stat(remote)
if err != nil {
return nil, err
}
if !info.IsDir() {
return nil, fmt.Errorf("%s exists but is not a directory", remote)
}
r.dir = remote
}
return r, nil
}
type gitRepo struct {
remote string
local bool
dir string
mu sync.Mutex // protects fetchLevel, some git repo state
fetchLevel int
statCache par.Cache
refsOnce sync.Once
refs map[string]string
refsErr error
localTagsOnce sync.Once
localTags map[string]bool
}
const (
// How much have we fetched into the git repo (in this process)?
fetchNone = iota // nothing yet
fetchSome // shallow fetches of individual hashes
fetchAll // "fetch -t origin": get all remote branches and tags
)
// loadLocalTags loads tag references from the local git cache
// into the map r.localTags.
// Should only be called as r.localTagsOnce.Do(r.loadLocalTags).
func (r *gitRepo) loadLocalTags() {
// The git protocol sends all known refs and ls-remote filters them on the client side,
// so we might as well record both heads and tags in one shot.
// Most of the time we only care about tags but sometimes we care about heads too.
out, err := Run(r.dir, "git", "tag", "-l")
if err != nil {
return
}
r.localTags = make(map[string]bool)
for _, line := range strings.Split(string(out), "\n") {
if line != "" {
r.localTags[line] = true
}
}
}
// loadRefs loads heads and tags references from the remote into the map r.refs.
// Should only be called as r.refsOnce.Do(r.loadRefs).
func (r *gitRepo) loadRefs() {
// The git protocol sends all known refs and ls-remote filters them on the client side,
// so we might as well record both heads and tags in one shot.
// Most of the time we only care about tags but sometimes we care about heads too.
out, err := Run(r.dir, "git", "ls-remote", "-q", r.remote)
if err != nil {
r.refsErr = err
return
}
r.refs = make(map[string]string)
for _, line := range strings.Split(string(out), "\n") {
f := strings.Fields(line)
if len(f) != 2 {
continue
}
if f[1] == "HEAD" || strings.HasPrefix(f[1], "refs/heads/") || strings.HasPrefix(f[1], "refs/tags/") {
r.refs[f[1]] = f[0]
}
}
for ref, hash := range r.refs {
if strings.HasSuffix(ref, "^{}") { // record unwrapped annotated tag as value of tag
r.refs[strings.TrimSuffix(ref, "^{}")] = hash
delete(r.refs, ref)
}
}
}
func (r *gitRepo) Tags(prefix string) ([]string, error) {
r.refsOnce.Do(r.loadRefs)
if r.refsErr != nil {
return nil, r.refsErr
}
tags := []string{}
for ref := range r.refs {
if !strings.HasPrefix(ref, "refs/tags/") {
continue
}
tag := ref[len("refs/tags/"):]
if !strings.HasPrefix(tag, prefix) {
continue
}
tags = append(tags, tag)
}
sort.Strings(tags)
return tags, nil
}
func (r *gitRepo) Latest() (*RevInfo, error) {
r.refsOnce.Do(r.loadRefs)
if r.refsErr != nil {
return nil, r.refsErr
}
if r.refs["HEAD"] == "" {
return nil, fmt.Errorf("no commits")
}
return r.Stat(r.refs["HEAD"])
}
// findRef finds some ref name for the given hash,
// for use when the server requires giving a ref instead of a hash.
// There may be multiple ref names for a given hash,
// in which case this returns some name - it doesn't matter which.
func (r *gitRepo) findRef(hash string) (ref string, ok bool) {
r.refsOnce.Do(r.loadRefs)
for ref, h := range r.refs {
if h == hash {
return ref, true
}
}
return "", false
}
func unshallow(gitDir string) []string {
if _, err := os.Stat(filepath.Join(gitDir, "shallow")); err == nil {
return []string{"--unshallow"}
}
return []string{}
}
// minHashDigits is the minimum number of digits to require
// before accepting a hex digit sequence as potentially identifying
// a specific commit in a git repo. (Of course, users can always
// specify more digits, and many will paste in all 40 digits,
// but many of git's commands default to printing short hashes
// as 7 digits.)
const minHashDigits = 7
// stat stats the given rev in the local repository,
// or else it fetches more info from the remote repository and tries again.
func (r *gitRepo) stat(rev string) (*RevInfo, error) {
if r.local {
return r.statLocal(rev, rev)
}
// Fast path: maybe rev is a hash we already have locally.
didStatLocal := false
if len(rev) >= minHashDigits && len(rev) <= 40 && AllHex(rev) {
if info, err := r.statLocal(rev, rev); err == nil {
return info, nil
}
didStatLocal = true
}
// Maybe rev is a tag we already have locally.
// (Note that we're excluding branches, which can be stale.)
r.localTagsOnce.Do(r.loadLocalTags)
if r.localTags[rev] {
return r.statLocal(rev, "refs/tags/"+rev)
}
// Maybe rev is the name of a tag or branch on the remote server.
// Or maybe it's the prefix of a hash of a named ref.
// Try to resolve to both a ref (git name) and full (40-hex-digit) commit hash.
r.refsOnce.Do(r.loadRefs)
var ref, hash string
if r.refs["refs/tags/"+rev] != "" {
ref = "refs/tags/" + rev
hash = r.refs[ref]
// Keep rev as is: tags are assumed not to change meaning.
} else if r.refs["refs/heads/"+rev] != "" {
ref = "refs/heads/" + rev
hash = r.refs[ref]
rev = hash // Replace rev, because meaning of refs/heads/foo can change.
} else if rev == "HEAD" && r.refs["HEAD"] != "" {
ref = "HEAD"
hash = r.refs[ref]
rev = hash // Replace rev, because meaning of HEAD can change.
} else if len(rev) >= minHashDigits && len(rev) <= 40 && AllHex(rev) {
// At the least, we have a hash prefix we can look up after the fetch below.
// Maybe we can map it to a full hash using the known refs.
prefix := rev
// Check whether rev is prefix of known ref hash.
for k, h := range r.refs {
if strings.HasPrefix(h, prefix) {
if hash != "" && hash != h {
// Hash is an ambiguous hash prefix.
// More information will not change that.
return nil, fmt.Errorf("ambiguous revision %s", rev)
}
if ref == "" || ref > k { // Break ties deterministically when multiple refs point at same hash.
ref = k
}
rev = h
hash = h
}
}
if hash == "" && len(rev) == 40 { // Didn't find a ref, but rev is a full hash.
hash = rev
}
} else {
return nil, fmt.Errorf("unknown revision %s", rev)
}
// Protect r.fetchLevel and the "fetch more and more" sequence.
// TODO(rsc): Add LockDir and use it for protecting that
// sequence, so that multiple processes don't collide in their
// git commands.
r.mu.Lock()
defer r.mu.Unlock()
// Perhaps r.localTags did not have the ref when we loaded local tags,
// but we've since done fetches that pulled down the hash we need
// (or already have the hash we need, just without its tag).
// Either way, try a local stat before falling back to network I/O.
if !didStatLocal {
if info, err := r.statLocal(rev, hash); err == nil {
if strings.HasPrefix(ref, "refs/tags/") {
// Make sure tag exists, so it will be in localTags next time the go command is run.
Run(r.dir, "git", "tag", strings.TrimPrefix(ref, "refs/tags/"), hash)
}
return info, nil
}
}
// If we know a specific commit we need, fetch it.
if r.fetchLevel <= fetchSome && hash != "" && !r.local {
r.fetchLevel = fetchSome
var refspec string
if ref != "" && ref != "HEAD" {
// If we do know the ref name, save the mapping locally
// so that (if it is a tag) it can show up in localTags
// on a future call. Also, some servers refuse to allow
// full hashes in ref specs, so prefer a ref name if known.
refspec = ref + ":" + ref
} else {
// Fetch the hash but give it a local name (refs/dummy),
// because that triggers the fetch behavior of creating any
// other known remote tags for the hash. We never use
// refs/dummy (it's not refs/tags/dummy) and it will be
// overwritten in the next command, and that's fine.
ref = hash
refspec = hash + ":refs/dummy"
}
_, err := Run(r.dir, "git", "fetch", "-f", "--depth=1", r.remote, refspec)
if err == nil {
return r.statLocal(rev, ref)
}
// Don't try to be smart about parsing the error.
// It's too complex and varies too much by git version.
// No matter what went wrong, fall back to a complete fetch.
}
// Last resort.
// Fetch all heads and tags and hope the hash we want is in the history.
if r.fetchLevel < fetchAll {
// TODO(bcmills): should we wait to upgrade fetchLevel until after we check
// err? If there is a temporary server error, we want subsequent fetches to
// try again instead of proceeding with an incomplete repo.
r.fetchLevel = fetchAll
if err := r.fetchUnshallow("refs/heads/*:refs/heads/*", "refs/tags/*:refs/tags/*"); err != nil {
return nil, err
}
}
return r.statLocal(rev, rev)
}
func (r *gitRepo) fetchUnshallow(refSpecs ...string) error {
// To work around a protocol version 2 bug that breaks --unshallow,
// add -c protocol.version=0.
// TODO(rsc): The bug is believed to be server-side, meaning only
// on Google's Git servers. Once the servers are fixed, drop the
// protocol.version=0. See Google-internal bug b/110495752.
var protoFlag []string
unshallowFlag := unshallow(r.dir)
if len(unshallowFlag) > 0 {
protoFlag = []string{"-c", "protocol.version=0"}
}
_, err := Run(r.dir, "git", protoFlag, "fetch", unshallowFlag, "-f", r.remote, refSpecs)
return err
}
// statLocal returns a RevInfo describing rev in the local git repository.
// It uses version as info.Version.
func (r *gitRepo) statLocal(version, rev string) (*RevInfo, error) {
out, err := Run(r.dir, "git", "-c", "log.showsignature=false", "log", "-n1", "--format=format:%H %ct %D", rev)
if err != nil {
return nil, fmt.Errorf("unknown revision %s", rev)
}
f := strings.Fields(string(out))
if len(f) < 2 {
return nil, fmt.Errorf("unexpected response from git log: %q", out)
}
hash := f[0]
if strings.HasPrefix(hash, version) {
version = hash // extend to full hash
}
t, err := strconv.ParseInt(f[1], 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid time from git log: %q", out)
}
info := &RevInfo{
Name: hash,
Short: ShortenSHA1(hash),
Time: time.Unix(t, 0).UTC(),
Version: hash,
}
// Add tags. Output looks like:
// ede458df7cd0fdca520df19a33158086a8a68e81 1523994202 HEAD -> master, tag: v1.2.4-annotated, tag: v1.2.3, origin/master, origin/HEAD
for i := 2; i < len(f); i++ {
if f[i] == "tag:" {
i++
if i < len(f) {
info.Tags = append(info.Tags, strings.TrimSuffix(f[i], ","))
}
}
}
sort.Strings(info.Tags)
// Used hash as info.Version above.
// Use caller's suggested version if it appears in the tag list
// (filters out branch names, HEAD).
for _, tag := range info.Tags {
if version == tag {
info.Version = version
}
}
return info, nil
}
func (r *gitRepo) Stat(rev string) (*RevInfo, error) {
if rev == "latest" {
return r.Latest()
}
type cached struct {
info *RevInfo
err error
}
c := r.statCache.Do(rev, func() interface{} {
info, err := r.stat(rev)
return cached{info, err}
}).(cached)
return c.info, c.err
}
func (r *gitRepo) ReadFile(rev, file string, maxSize int64) ([]byte, error) {
// TODO: Could use git cat-file --batch.
info, err := r.Stat(rev) // download rev into local git repo
if err != nil {
return nil, err
}
out, err := Run(r.dir, "git", "cat-file", "blob", info.Name+":"+file)
if err != nil {
return nil, os.ErrNotExist
}
return out, nil
}
func (r *gitRepo) ReadFileRevs(revs []string, file string, maxSize int64) (map[string]*FileRev, error) {
// Create space to hold results.
files := make(map[string]*FileRev)
for _, rev := range revs {
f := &FileRev{Rev: rev}
files[rev] = f
}
// Collect locally-known revs.
need, err := r.readFileRevs(revs, file, files)
if err != nil {
return nil, err
}
if len(need) == 0 {
return files, nil
}
// Build list of known remote refs that might help.
var redo []string
r.refsOnce.Do(r.loadRefs)
if r.refsErr != nil {
return nil, r.refsErr
}
for _, tag := range need {
if r.refs["refs/tags/"+tag] != "" {
redo = append(redo, tag)
}
}
if len(redo) == 0 {
return files, nil
}
// Protect r.fetchLevel and the "fetch more and more" sequence.
// See stat method above.
r.mu.Lock()
defer r.mu.Unlock()
var refs []string
var protoFlag []string
var unshallowFlag []string
for _, tag := range redo {
refs = append(refs, "refs/tags/"+tag+":refs/tags/"+tag)
}
if len(refs) > 1 {
unshallowFlag = unshallow(r.dir)
if len(unshallowFlag) > 0 {
// To work around a protocol version 2 bug that breaks --unshallow,
// add -c protocol.version=0.
// TODO(rsc): The bug is believed to be server-side, meaning only
// on Google's Git servers. Once the servers are fixed, drop the
// protocol.version=0. See Google-internal bug b/110495752.
protoFlag = []string{"-c", "protocol.version=0"}
}
}
if _, err := Run(r.dir, "git", protoFlag, "fetch", unshallowFlag, "-f", r.remote, refs); err != nil {
return nil, err
}
// TODO(bcmills): after the 1.11 freeze, replace the block above with:
// if r.fetchLevel <= fetchSome {
// r.fetchLevel = fetchSome
// var refs []string
// for _, tag := range redo {
// refs = append(refs, "refs/tags/"+tag+":refs/tags/"+tag)
// }
// if _, err := Run(r.dir, "git", "fetch", "--update-shallow", "-f", r.remote, refs); err != nil {
// return nil, err
// }
// }
if _, err := r.readFileRevs(redo, file, files); err != nil {
return nil, err
}
return files, nil
}
func (r *gitRepo) readFileRevs(tags []string, file string, fileMap map[string]*FileRev) (missing []string, err error) {
var stdin bytes.Buffer
for _, tag := range tags {
fmt.Fprintf(&stdin, "refs/tags/%s\n", tag)
fmt.Fprintf(&stdin, "refs/tags/%s:%s\n", tag, file)
}
data, err := RunWithStdin(r.dir, &stdin, "git", "cat-file", "--batch")
if err != nil {
return nil, err
}
next := func() (typ string, body []byte, ok bool) {
var line string
i := bytes.IndexByte(data, '\n')
if i < 0 {
return "", nil, false
}
line, data = string(bytes.TrimSpace(data[:i])), data[i+1:]
if strings.HasSuffix(line, " missing") {
return "missing", nil, true
}
f := strings.Fields(line)
if len(f) != 3 {
return "", nil, false
}
n, err := strconv.Atoi(f[2])
if err != nil || n > len(data) {
return "", nil, false
}
body, data = data[:n], data[n:]
if len(data) > 0 && data[0] == '\r' {
data = data[1:]
}
if len(data) > 0 && data[0] == '\n' {
data = data[1:]
}
return f[1], body, true
}
badGit := func() ([]string, error) {
return nil, fmt.Errorf("malformed output from git cat-file --batch")
}
for _, tag := range tags {
commitType, _, ok := next()
if !ok {
return badGit()
}
fileType, fileData, ok := next()
if !ok {
return badGit()
}
f := fileMap[tag]
f.Data = nil
f.Err = nil
switch commitType {
default:
f.Err = fmt.Errorf("unexpected non-commit type %q for rev %s", commitType, tag)
case "missing":
// Note: f.Err must not satisfy os.IsNotExist. That's reserved for the file not existing in a valid commit.
f.Err = fmt.Errorf("no such rev %s", tag)
missing = append(missing, tag)
case "tag", "commit":
switch fileType {
default:
f.Err = &os.PathError{Path: tag + ":" + file, Op: "read", Err: fmt.Errorf("unexpected non-blob type %q", fileType)}
case "missing":
f.Err = &os.PathError{Path: tag + ":" + file, Op: "read", Err: os.ErrNotExist}
case "blob":
f.Data = fileData
}
}
}
if len(bytes.TrimSpace(data)) != 0 {
return badGit()
}
return missing, nil
}
func (r *gitRepo) RecentTag(rev, prefix string) (tag string, err error) {
info, err := r.Stat(rev)
if err != nil {
return "", err
}
rev = info.Name // expand hash prefixes
// describe sets tag and err using 'git describe' and reports whether the
// result is definitive.
describe := func() (definitive bool) {
var out []byte
out, err = Run(r.dir, "git", "describe", "--first-parent", "--always", "--abbrev=0", "--match", prefix+"v[0-9]*.[0-9]*.[0-9]*", "--tags", rev)
if err != nil {
return true // Because we use "--always", describe should never fail.
}
tag = string(bytes.TrimSpace(out))
return tag != "" && !AllHex(tag)
}
if describe() {
return tag, err
}
// Git didn't find a version tag preceding the requested rev.
// See whether any plausible tag exists.
tags, err := r.Tags(prefix + "v")
if err != nil {
return "", err
}
if len(tags) == 0 {
return "", nil
}
// There are plausible tags, but we don't know if rev is a descendent of any of them.
// Fetch the history to find out.
r.mu.Lock()
defer r.mu.Unlock()
if r.fetchLevel < fetchAll {
// Fetch all heads and tags and see if that gives us enough history.
if err := r.fetchUnshallow("refs/heads/*:refs/heads/*", "refs/tags/*:refs/tags/*"); err != nil {
return "", err
}
r.fetchLevel = fetchAll
}
// If we've reached this point, we have all of the commits that are reachable
// from all heads and tags.
//
// The only refs we should be missing are those that are no longer reachable
// (or never were reachable) from any branch or tag, including the master
// branch, and we don't want to resolve them anyway (they're probably
// unreachable for a reason).
//
// Try one last time in case some other goroutine fetched rev while we were
// waiting on r.mu.
describe()
return tag, err
}
func (r *gitRepo) ReadZip(rev, subdir string, maxSize int64) (zip io.ReadCloser, actualSubdir string, err error) {
// TODO: Use maxSize or drop it.
args := []string{}
if subdir != "" {
args = append(args, "--", subdir)
}
info, err := r.Stat(rev) // download rev into local git repo
if err != nil {
return nil, "", err
}
// Incredibly, git produces different archives depending on whether
// it is running on a Windows system or not, in an attempt to normalize
// text file line endings. Setting -c core.autocrlf=input means only
// translate files on the way into the repo, not on the way out (archive).
// The -c core.eol=lf should be unnecessary but set it anyway.
archive, err := Run(r.dir, "git", "-c", "core.autocrlf=input", "-c", "core.eol=lf", "archive", "--format=zip", "--prefix=prefix/", info.Name, args)
if err != nil {
if bytes.Contains(err.(*RunError).Stderr, []byte("did not match any files")) {
return nil, "", os.ErrNotExist
}
return nil, "", err
}
return ioutil.NopCloser(bytes.NewReader(archive)), "", nil
}
|
cmdflag
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/cmdflag/flag.go
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package cmdflag handles flag processing common to several go tools.
package cmdflag
import (
"flag"
"fmt"
"os"
"strconv"
"strings"
"cmd/go/internal/base"
)
// The flag handling part of go commands such as test is large and distracting.
// We can't use the standard flag package because some of the flags from
// our command line are for us, and some are for the binary we're running,
// and some are for both.
// Defn defines a flag we know about.
type Defn struct {
Name string // Name on command line.
BoolVar *bool // If it's a boolean flag, this points to it.
Value flag.Value // The flag.Value represented.
PassToTest bool // Pass to the test binary? Used only by go test.
Present bool // Flag has been seen.
}
// IsBool reports whether v is a bool flag.
func IsBool(v flag.Value) bool {
vv, ok := v.(interface {
IsBoolFlag() bool
})
if ok {
return vv.IsBoolFlag()
}
return false
}
// SetBool sets the addressed boolean to the value.
func SetBool(cmd string, flag *bool, value string) {
x, err := strconv.ParseBool(value)
if err != nil {
SyntaxError(cmd, "illegal bool flag value "+value)
}
*flag = x
}
// SetInt sets the addressed integer to the value.
func SetInt(cmd string, flag *int, value string) {
x, err := strconv.Atoi(value)
if err != nil {
SyntaxError(cmd, "illegal int flag value "+value)
}
*flag = x
}
// SyntaxError reports an argument syntax error and exits the program.
func SyntaxError(cmd, msg string) {
fmt.Fprintf(os.Stderr, "go %s: %s\n", cmd, msg)
if cmd == "test" {
fmt.Fprintf(os.Stderr, `run "go help %s" or "go help testflag" for more information`+"\n", cmd)
} else {
fmt.Fprintf(os.Stderr, `run "go help %s" for more information`+"\n", cmd)
}
os.Exit(2)
}
// AddKnownFlags registers the flags in defns with base.AddKnownFlag.
func AddKnownFlags(cmd string, defns []*Defn) {
for _, f := range defns {
base.AddKnownFlag(f.Name)
base.AddKnownFlag(cmd + "." + f.Name)
}
}
// Parse sees if argument i is present in the definitions and if so,
// returns its definition, value, and whether it consumed an extra word.
// If the flag begins (cmd+".") it is ignored for the purpose of this function.
func Parse(cmd string, defns []*Defn, args []string, i int) (f *Defn, value string, extra bool) {
arg := args[i]
if strings.HasPrefix(arg, "--") { // reduce two minuses to one
arg = arg[1:]
}
switch arg {
case "-?", "-h", "-help":
base.Usage()
}
if arg == "" || arg[0] != '-' {
return
}
name := arg[1:]
// If there's already a prefix such as "test.", drop it for now.
name = strings.TrimPrefix(name, cmd+".")
equals := strings.Index(name, "=")
if equals >= 0 {
value = name[equals+1:]
name = name[:equals]
}
for _, f = range defns {
if name == f.Name {
// Booleans are special because they have modes -x, -x=true, -x=false.
if f.BoolVar != nil || IsBool(f.Value) {
if equals < 0 { // Otherwise, it's been set and will be verified in SetBool.
value = "true"
} else {
// verify it parses
SetBool(cmd, new(bool), value)
}
} else { // Non-booleans must have a value.
extra = equals < 0
if extra {
if i+1 >= len(args) {
SyntaxError(cmd, "missing argument for flag "+f.Name)
}
value = args[i+1]
}
}
if f.Present {
SyntaxError(cmd, f.Name+" flag may be set only once")
}
f.Present = true
return
}
}
f = nil
return
}
// FindGOFLAGS extracts and returns the flags matching defns from GOFLAGS.
// Ideally the caller would mention that the flags were from GOFLAGS
// when reporting errors, but that's too hard for now.
func FindGOFLAGS(defns []*Defn) []string {
var flags []string
for _, flag := range base.GOFLAGS() {
// Flags returned by base.GOFLAGS are well-formed, one of:
// -x
// --x
// -x=value
// --x=value
if strings.HasPrefix(flag, "--") {
flag = flag[1:]
}
name := flag[1:]
if i := strings.Index(name, "="); i >= 0 {
name = name[:i]
}
for _, f := range defns {
if name == f.Name {
flags = append(flags, flag)
break
}
}
}
return flags
}
|
test
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/test/test.go
|
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package test
import (
"bytes"
"crypto/sha256"
"errors"
"fmt"
"go/build"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"cmd/go/internal/base"
"cmd/go/internal/cache"
"cmd/go/internal/cfg"
"cmd/go/internal/load"
"cmd/go/internal/modload"
"cmd/go/internal/str"
"cmd/go/internal/work"
"cmd/internal/test2json"
)
// Break init loop.
func init() {
CmdTest.Run = runTest
}
const testUsage = "go test [build/test flags] [packages] [build/test flags & test binary flags]"
var CmdTest = &base.Command{
CustomFlags: true,
UsageLine: testUsage,
Short: "test packages",
Long: `
'Go test' automates testing the packages named by the import paths.
It prints a summary of the test results in the format:
ok archive/tar 0.011s
FAIL archive/zip 0.022s
ok compress/gzip 0.033s
...
followed by detailed output for each failed package.
'Go test' recompiles each package along with any files with names matching
the file pattern "*_test.go".
These additional files can contain test functions, benchmark functions, and
example functions. See 'go help testfunc' for more.
Each listed package causes the execution of a separate test binary.
Files whose names begin with "_" (including "_test.go") or "." are ignored.
Test files that declare a package with the suffix "_test" will be compiled as a
separate package, and then linked and run with the main test binary.
The go tool will ignore a directory named "testdata", making it available
to hold ancillary data needed by the tests.
As part of building a test binary, go test runs go vet on the package
and its test source files to identify significant problems. If go vet
finds any problems, go test reports those and does not run the test
binary. Only a high-confidence subset of the default go vet checks are
used. That subset is: 'atomic', 'bool', 'buildtags', 'nilfunc', and
'printf'. You can see the documentation for these and other vet tests
via "go doc cmd/vet". To disable the running of go vet, use the
-vet=off flag.
All test output and summary lines are printed to the go command's
standard output, even if the test printed them to its own standard
error. (The go command's standard error is reserved for printing
errors building the tests.)
Go test runs in two different modes:
The first, called local directory mode, occurs when go test is
invoked with no package arguments (for example, 'go test' or 'go
test -v'). In this mode, go test compiles the package sources and
tests found in the current directory and then runs the resulting
test binary. In this mode, caching (discussed below) is disabled.
After the package test finishes, go test prints a summary line
showing the test status ('ok' or 'FAIL'), package name, and elapsed
time.
The second, called package list mode, occurs when go test is invoked
with explicit package arguments (for example 'go test math', 'go
test ./...', and even 'go test .'). In this mode, go test compiles
and tests each of the packages listed on the command line. If a
package test passes, go test prints only the final 'ok' summary
line. If a package test fails, go test prints the full test output.
If invoked with the -bench or -v flag, go test prints the full
output even for passing package tests, in order to display the
requested benchmark results or verbose logging.
In package list mode only, go test caches successful package test
results to avoid unnecessary repeated running of tests. When the
result of a test can be recovered from the cache, go test will
redisplay the previous output instead of running the test binary
again. When this happens, go test prints '(cached)' in place of the
elapsed time in the summary line.
The rule for a match in the cache is that the run involves the same
test binary and the flags on the command line come entirely from a
restricted set of 'cacheable' test flags, defined as -cpu, -list,
-parallel, -run, -short, and -v. If a run of go test has any test
or non-test flags outside this set, the result is not cached. To
disable test caching, use any test flag or argument other than the
cacheable flags. The idiomatic way to disable test caching explicitly
is to use -count=1. Tests that open files within the package's source
root (usually $GOPATH) or that consult environment variables only
match future runs in which the files and environment variables are unchanged.
A cached test result is treated as executing in no time at all,
so a successful package test result will be cached and reused
regardless of -timeout setting.
` + strings.TrimSpace(testFlag1) + ` See 'go help testflag' for details.
For more about build flags, see 'go help build'.
For more about specifying packages, see 'go help packages'.
See also: go build, go vet.
`,
}
const testFlag1 = `
In addition to the build flags, the flags handled by 'go test' itself are:
-args
Pass the remainder of the command line (everything after -args)
to the test binary, uninterpreted and unchanged.
Because this flag consumes the remainder of the command line,
the package list (if present) must appear before this flag.
-c
Compile the test binary to pkg.test but do not run it
(where pkg is the last element of the package's import path).
The file name can be changed with the -o flag.
-exec xprog
Run the test binary using xprog. The behavior is the same as
in 'go run'. See 'go help run' for details.
-i
Install packages that are dependencies of the test.
Do not run the test.
-json
Convert test output to JSON suitable for automated processing.
See 'go doc test2json' for the encoding details.
-o file
Compile the test binary to the named file.
The test still runs (unless -c or -i is specified).
The test binary also accepts flags that control execution of the test; these
flags are also accessible by 'go test'.
`
// Usage prints the usage message for 'go test -h' and exits.
func Usage() {
os.Stderr.WriteString("usage: " + testUsage + "\n\n" +
strings.TrimSpace(testFlag1) + "\n\n\t" +
strings.TrimSpace(testFlag2) + "\n")
os.Exit(2)
}
var HelpTestflag = &base.Command{
UsageLine: "testflag",
Short: "testing flags",
Long: `
The 'go test' command takes both flags that apply to 'go test' itself
and flags that apply to the resulting test binary.
Several of the flags control profiling and write an execution profile
suitable for "go tool pprof"; run "go tool pprof -h" for more
information. The --alloc_space, --alloc_objects, and --show_bytes
options of pprof control how the information is presented.
The following flags are recognized by the 'go test' command and
control the execution of any test:
` + strings.TrimSpace(testFlag2) + `
`,
}
const testFlag2 = `
-bench regexp
Run only those benchmarks matching a regular expression.
By default, no benchmarks are run.
To run all benchmarks, use '-bench .' or '-bench=.'.
The regular expression is split by unbracketed slash (/)
characters into a sequence of regular expressions, and each
part of a benchmark's identifier must match the corresponding
element in the sequence, if any. Possible parents of matches
are run with b.N=1 to identify sub-benchmarks. For example,
given -bench=X/Y, top-level benchmarks matching X are run
with b.N=1 to find any sub-benchmarks matching Y, which are
then run in full.
-benchtime t
Run enough iterations of each benchmark to take t, specified
as a time.Duration (for example, -benchtime 1h30s).
The default is 1 second (1s).
-count n
Run each test and benchmark n times (default 1).
If -cpu is set, run n times for each GOMAXPROCS value.
Examples are always run once.
-cover
Enable coverage analysis.
Note that because coverage works by annotating the source
code before compilation, compilation and test failures with
coverage enabled may report line numbers that don't correspond
to the original sources.
-covermode set,count,atomic
Set the mode for coverage analysis for the package[s]
being tested. The default is "set" unless -race is enabled,
in which case it is "atomic".
The values:
set: bool: does this statement run?
count: int: how many times does this statement run?
atomic: int: count, but correct in multithreaded tests;
significantly more expensive.
Sets -cover.
-coverpkg pattern1,pattern2,pattern3
Apply coverage analysis in each test to packages matching the patterns.
The default is for each test to analyze only the package being tested.
See 'go help packages' for a description of package patterns.
Sets -cover.
-cpu 1,2,4
Specify a list of GOMAXPROCS values for which the tests or
benchmarks should be executed. The default is the current value
of GOMAXPROCS.
-failfast
Do not start new tests after the first test failure.
-list regexp
List tests, benchmarks, or examples matching the regular expression.
No tests, benchmarks or examples will be run. This will only
list top-level tests. No subtest or subbenchmarks will be shown.
-parallel n
Allow parallel execution of test functions that call t.Parallel.
The value of this flag is the maximum number of tests to run
simultaneously; by default, it is set to the value of GOMAXPROCS.
Note that -parallel only applies within a single test binary.
The 'go test' command may run tests for different packages
in parallel as well, according to the setting of the -p flag
(see 'go help build').
-run regexp
Run only those tests and examples matching the regular expression.
For tests, the regular expression is split by unbracketed slash (/)
characters into a sequence of regular expressions, and each part
of a test's identifier must match the corresponding element in
the sequence, if any. Note that possible parents of matches are
run too, so that -run=X/Y matches and runs and reports the result
of all tests matching X, even those without sub-tests matching Y,
because it must run them to look for those sub-tests.
-short
Tell long-running tests to shorten their run time.
It is off by default but set during all.bash so that installing
the Go tree can run a sanity check but not spend time running
exhaustive tests.
-timeout d
If a test binary runs longer than duration d, panic.
If d is 0, the timeout is disabled.
The default is 10 minutes (10m).
-v
Verbose output: log all tests as they are run. Also print all
text from Log and Logf calls even if the test succeeds.
-vet list
Configure the invocation of "go vet" during "go test"
to use the comma-separated list of vet checks.
If list is empty, "go test" runs "go vet" with a curated list of
checks believed to be always worth addressing.
If list is "off", "go test" does not run "go vet" at all.
The following flags are also recognized by 'go test' and can be used to
profile the tests during execution:
-benchmem
Print memory allocation statistics for benchmarks.
-blockprofile block.out
Write a goroutine blocking profile to the specified file
when all tests are complete.
Writes test binary as -c would.
-blockprofilerate n
Control the detail provided in goroutine blocking profiles by
calling runtime.SetBlockProfileRate with n.
See 'go doc runtime.SetBlockProfileRate'.
The profiler aims to sample, on average, one blocking event every
n nanoseconds the program spends blocked. By default,
if -test.blockprofile is set without this flag, all blocking events
are recorded, equivalent to -test.blockprofilerate=1.
-coverprofile cover.out
Write a coverage profile to the file after all tests have passed.
Sets -cover.
-cpuprofile cpu.out
Write a CPU profile to the specified file before exiting.
Writes test binary as -c would.
-memprofile mem.out
Write an allocation profile to the file after all tests have passed.
Writes test binary as -c would.
-memprofilerate n
Enable more precise (and expensive) memory allocation profiles by
setting runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'.
To profile all memory allocations, use -test.memprofilerate=1.
-mutexprofile mutex.out
Write a mutex contention profile to the specified file
when all tests are complete.
Writes test binary as -c would.
-mutexprofilefraction n
Sample 1 in n stack traces of goroutines holding a
contended mutex.
-outputdir directory
Place output files from profiling in the specified directory,
by default the directory in which "go test" is running.
-trace trace.out
Write an execution trace to the specified file before exiting.
Each of these flags is also recognized with an optional 'test.' prefix,
as in -test.v. When invoking the generated test binary (the result of
'go test -c') directly, however, the prefix is mandatory.
The 'go test' command rewrites or removes recognized flags,
as appropriate, both before and after the optional package list,
before invoking the test binary.
For instance, the command
go test -v -myflag testdata -cpuprofile=prof.out -x
will compile the test binary and then run it as
pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out
(The -x flag is removed because it applies only to the go command's
execution, not to the test itself.)
The test flags that generate profiles (other than for coverage) also
leave the test binary in pkg.test for use when analyzing the profiles.
When 'go test' runs a test binary, it does so from within the
corresponding package's source code directory. Depending on the test,
it may be necessary to do the same when invoking a generated test
binary directly.
The command-line package list, if present, must appear before any
flag not known to the go test command. Continuing the example above,
the package list would have to appear before -myflag, but could appear
on either side of -v.
When 'go test' runs in package list mode, 'go test' caches successful
package test results to avoid unnecessary repeated running of tests. To
disable test caching, use any test flag or argument other than the
cacheable flags. The idiomatic way to disable test caching explicitly
is to use -count=1.
To keep an argument for a test binary from being interpreted as a
known flag or a package name, use -args (see 'go help test') which
passes the remainder of the command line through to the test binary
uninterpreted and unaltered.
For instance, the command
go test -v -args -x -v
will compile the test binary and then run it as
pkg.test -test.v -x -v
Similarly,
go test -args math
will compile the test binary and then run it as
pkg.test math
In the first example, the -x and the second -v are passed through to the
test binary unchanged and with no effect on the go command itself.
In the second example, the argument math is passed through to the test
binary, instead of being interpreted as the package list.
`
var HelpTestfunc = &base.Command{
UsageLine: "testfunc",
Short: "testing functions",
Long: `
The 'go test' command expects to find test, benchmark, and example functions
in the "*_test.go" files corresponding to the package under test.
A test function is one named TestXxx (where Xxx does not start with a
lower case letter) and should have the signature,
func TestXxx(t *testing.T) { ... }
A benchmark function is one named BenchmarkXxx and should have the signature,
func BenchmarkXxx(b *testing.B) { ... }
An example function is similar to a test function but, instead of using
*testing.T to report success or failure, prints output to os.Stdout.
If the last comment in the function starts with "Output:" then the output
is compared exactly against the comment (see examples below). If the last
comment begins with "Unordered output:" then the output is compared to the
comment, however the order of the lines is ignored. An example with no such
comment is compiled but not executed. An example with no text after
"Output:" is compiled, executed, and expected to produce no output.
Godoc displays the body of ExampleXxx to demonstrate the use
of the function, constant, or variable Xxx. An example of a method M with
receiver type T or *T is named ExampleT_M. There may be multiple examples
for a given function, constant, or variable, distinguished by a trailing _xxx,
where xxx is a suffix not beginning with an upper case letter.
Here is an example of an example:
func ExamplePrintln() {
Println("The output of\nthis example.")
// Output: The output of
// this example.
}
Here is another example where the ordering of the output is ignored:
func ExamplePerm() {
for _, value := range Perm(4) {
fmt.Println(value)
}
// Unordered output: 4
// 2
// 1
// 3
// 0
}
The entire test file is presented as the example when it contains a single
example function, at least one other function, type, variable, or constant
declaration, and no test or benchmark functions.
See the documentation of the testing package for more information.
`,
}
var (
testC bool // -c flag
testCover bool // -cover flag
testCoverMode string // -covermode flag
testCoverPaths []string // -coverpkg flag
testCoverPkgs []*load.Package // -coverpkg flag
testCoverProfile string // -coverprofile flag
testOutputDir string // -outputdir flag
testO string // -o flag
testProfile string // profiling flag that limits test to one package
testNeedBinary bool // profile needs to keep binary around
testJSON bool // -json flag
testV bool // -v flag
testTimeout string // -timeout flag
testArgs []string
testBench bool
testList bool
testShowPass bool // show passing output
testVetList string // -vet flag
pkgArgs []string
pkgs []*load.Package
testKillTimeout = 10 * time.Minute
testCacheExpire time.Time // ignore cached test results before this time
)
// testVetFlags is the list of flags to pass to vet when invoked automatically during go test.
var testVetFlags = []string{
// TODO(rsc): Decide which tests are enabled by default.
// See golang.org/issue/18085.
// "-asmdecl",
// "-assign",
"-atomic",
"-bool",
"-buildtags",
// "-cgocall",
// "-composites",
// "-copylocks",
// "-httpresponse",
// "-lostcancel",
// "-methods",
"-nilfunc",
"-printf",
// "-rangeloops",
// "-shift",
// "-structtags",
// "-tests",
// "-unreachable",
// "-unsafeptr",
// "-unusedresult",
}
func runTest(cmd *base.Command, args []string) {
modload.LoadTests = true
pkgArgs, testArgs = testFlags(args)
work.FindExecCmd() // initialize cached result
work.BuildInit()
work.VetFlags = testVetFlags
pkgs = load.PackagesForBuild(pkgArgs)
if len(pkgs) == 0 {
base.Fatalf("no packages to test")
}
if testC && len(pkgs) != 1 {
base.Fatalf("cannot use -c flag with multiple packages")
}
if testO != "" && len(pkgs) != 1 {
base.Fatalf("cannot use -o flag with multiple packages")
}
if testProfile != "" && len(pkgs) != 1 {
base.Fatalf("cannot use %s flag with multiple packages", testProfile)
}
initCoverProfile()
defer closeCoverProfile()
// If a test timeout was given and is parseable, set our kill timeout
// to that timeout plus one minute. This is a backup alarm in case
// the test wedges with a goroutine spinning and its background
// timer does not get a chance to fire.
if dt, err := time.ParseDuration(testTimeout); err == nil && dt > 0 {
testKillTimeout = dt + 1*time.Minute
} else if err == nil && dt == 0 {
// An explicit zero disables the test timeout.
// Let it have one century (almost) before we kill it.
testKillTimeout = 100 * 365 * 24 * time.Hour
}
// show passing test output (after buffering) with -v flag.
// must buffer because tests are running in parallel, and
// otherwise the output will get mixed.
testShowPass = testV || testList
// For 'go test -i -o x.test', we want to build x.test. Imply -c to make the logic easier.
if cfg.BuildI && testO != "" {
testC = true
}
// Read testcache expiration time, if present.
// (We implement go clean -testcache by writing an expiration date
// instead of searching out and deleting test result cache entries.)
if dir := cache.DefaultDir(); dir != "off" {
if data, _ := ioutil.ReadFile(filepath.Join(dir, "testexpire.txt")); len(data) > 0 && data[len(data)-1] == '\n' {
if t, err := strconv.ParseInt(string(data[:len(data)-1]), 10, 64); err == nil {
testCacheExpire = time.Unix(0, t)
}
}
}
var b work.Builder
b.Init()
if cfg.BuildI {
cfg.BuildV = testV
deps := make(map[string]bool)
for _, dep := range load.TestMainDeps {
deps[dep] = true
}
for _, p := range pkgs {
// Dependencies for each test.
for _, path := range p.Imports {
deps[path] = true
}
for _, path := range p.Resolve(p.TestImports) {
deps[path] = true
}
for _, path := range p.Resolve(p.XTestImports) {
deps[path] = true
}
}
// translate C to runtime/cgo
if deps["C"] {
delete(deps, "C")
deps["runtime/cgo"] = true
}
// Ignore pseudo-packages.
delete(deps, "unsafe")
all := []string{}
for path := range deps {
if !build.IsLocalImport(path) {
all = append(all, path)
}
}
sort.Strings(all)
a := &work.Action{Mode: "go test -i"}
for _, p := range load.PackagesForBuild(all) {
if cfg.BuildToolchainName == "gccgo" && p.Standard {
// gccgo's standard library packages
// can not be reinstalled.
continue
}
a.Deps = append(a.Deps, b.CompileAction(work.ModeInstall, work.ModeInstall, p))
}
b.Do(a)
if !testC || a.Failed {
return
}
b.Init()
}
var builds, runs, prints []*work.Action
if testCoverPaths != nil {
match := make([]func(*load.Package) bool, len(testCoverPaths))
matched := make([]bool, len(testCoverPaths))
for i := range testCoverPaths {
match[i] = load.MatchPackage(testCoverPaths[i], base.Cwd)
}
// Select for coverage all dependencies matching the testCoverPaths patterns.
for _, p := range load.TestPackageList(pkgs) {
haveMatch := false
for i := range testCoverPaths {
if match[i](p) {
matched[i] = true
haveMatch = true
}
}
// Silently ignore attempts to run coverage on
// sync/atomic when using atomic coverage mode.
// Atomic coverage mode uses sync/atomic, so
// we can't also do coverage on it.
if testCoverMode == "atomic" && p.Standard && p.ImportPath == "sync/atomic" {
continue
}
// If using the race detector, silently ignore
// attempts to run coverage on the runtime
// packages. It will cause the race detector
// to be invoked before it has been initialized.
if cfg.BuildRace && p.Standard && (p.ImportPath == "runtime" || strings.HasPrefix(p.ImportPath, "runtime/internal")) {
continue
}
if haveMatch {
testCoverPkgs = append(testCoverPkgs, p)
}
}
// Warn about -coverpkg arguments that are not actually used.
for i := range testCoverPaths {
if !matched[i] {
fmt.Fprintf(os.Stderr, "warning: no packages being tested depend on matches for pattern %s\n", testCoverPaths[i])
}
}
// Mark all the coverage packages for rebuilding with coverage.
for _, p := range testCoverPkgs {
// There is nothing to cover in package unsafe; it comes from the compiler.
if p.ImportPath == "unsafe" {
continue
}
p.Internal.CoverMode = testCoverMode
var coverFiles []string
coverFiles = append(coverFiles, p.GoFiles...)
coverFiles = append(coverFiles, p.CgoFiles...)
coverFiles = append(coverFiles, p.TestGoFiles...)
p.Internal.CoverVars = declareCoverVars(p, coverFiles...)
if testCover && testCoverMode == "atomic" {
ensureImport(p, "sync/atomic")
}
}
}
// Prepare build + run + print actions for all packages being tested.
for _, p := range pkgs {
// sync/atomic import is inserted by the cover tool. See #18486
if testCover && testCoverMode == "atomic" {
ensureImport(p, "sync/atomic")
}
buildTest, runTest, printTest, err := builderTest(&b, p)
if err != nil {
str := err.Error()
str = strings.TrimPrefix(str, "\n")
if p.ImportPath != "" {
base.Errorf("# %s\n%s", p.ImportPath, str)
} else {
base.Errorf("%s", str)
}
fmt.Printf("FAIL\t%s [setup failed]\n", p.ImportPath)
continue
}
builds = append(builds, buildTest)
runs = append(runs, runTest)
prints = append(prints, printTest)
}
// Ultimately the goal is to print the output.
root := &work.Action{Mode: "go test", Deps: prints}
// Force the printing of results to happen in order,
// one at a time.
for i, a := range prints {
if i > 0 {
a.Deps = append(a.Deps, prints[i-1])
}
}
// Force benchmarks to run in serial.
if !testC && testBench {
// The first run must wait for all builds.
// Later runs must wait for the previous run's print.
for i, run := range runs {
if i == 0 {
run.Deps = append(run.Deps, builds...)
} else {
run.Deps = append(run.Deps, prints[i-1])
}
}
}
b.Do(root)
}
// ensures that package p imports the named package
func ensureImport(p *load.Package, pkg string) {
for _, d := range p.Internal.Imports {
if d.Name == pkg {
return
}
}
p1 := load.LoadPackage(pkg, &load.ImportStack{})
if p1.Error != nil {
base.Fatalf("load %s: %v", pkg, p1.Error)
}
p.Internal.Imports = append(p.Internal.Imports, p1)
}
var windowsBadWords = []string{
"install",
"patch",
"setup",
"update",
}
func builderTest(b *work.Builder, p *load.Package) (buildAction, runAction, printAction *work.Action, err error) {
if len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
build := b.CompileAction(work.ModeBuild, work.ModeBuild, p)
run := &work.Action{Mode: "test run", Package: p, Deps: []*work.Action{build}}
addTestVet(b, p, run, nil)
print := &work.Action{Mode: "test print", Func: builderNoTest, Package: p, Deps: []*work.Action{run}}
return build, run, print, nil
}
// Build Package structs describing:
// pmain - pkg.test binary
// ptest - package + test files
// pxtest - package of external test files
var cover *load.TestCover
if testCover {
cover = &load.TestCover{
Mode: testCoverMode,
Local: testCover && testCoverPaths == nil,
Pkgs: testCoverPkgs,
Paths: testCoverPaths,
DeclVars: declareCoverVars,
}
}
pmain, ptest, pxtest, err := load.TestPackagesFor(p, cover)
if err != nil {
return nil, nil, nil, err
}
// Use last element of import path, not package name.
// They differ when package name is "main".
// But if the import path is "command-line-arguments",
// like it is during 'go run', use the package name.
var elem string
if p.ImportPath == "command-line-arguments" {
elem = p.Name
} else {
_, elem = path.Split(p.ImportPath)
}
testBinary := elem + ".test"
testDir := b.NewObjdir()
if err := b.Mkdir(testDir); err != nil {
return nil, nil, nil, err
}
pmain.Dir = testDir
pmain.Internal.OmitDebug = !testC && !testNeedBinary
if !cfg.BuildN {
// writeTestmain writes _testmain.go,
// using the test description gathered in t.
if err := ioutil.WriteFile(testDir+"_testmain.go", *pmain.Internal.TestmainGo, 0666); err != nil {
return nil, nil, nil, err
}
}
// Set compile objdir to testDir we've already created,
// so that the default file path stripping applies to _testmain.go.
b.CompileAction(work.ModeBuild, work.ModeBuild, pmain).Objdir = testDir
a := b.LinkAction(work.ModeBuild, work.ModeBuild, pmain)
a.Target = testDir + testBinary + cfg.ExeSuffix
if cfg.Goos == "windows" {
// There are many reserved words on Windows that,
// if used in the name of an executable, cause Windows
// to try to ask for extra permissions.
// The word list includes setup, install, update, and patch,
// but it does not appear to be defined anywhere.
// We have run into this trying to run the
// go.codereview/patch tests.
// For package names containing those words, use test.test.exe
// instead of pkgname.test.exe.
// Note that this file name is only used in the Go command's
// temporary directory. If the -c or other flags are
// given, the code below will still use pkgname.test.exe.
// There are two user-visible effects of this change.
// First, you can actually run 'go test' in directories that
// have names that Windows thinks are installer-like,
// without getting a dialog box asking for more permissions.
// Second, in the Windows process listing during go test,
// the test shows up as test.test.exe, not pkgname.test.exe.
// That second one is a drawback, but it seems a small
// price to pay for the test running at all.
// If maintaining the list of bad words is too onerous,
// we could just do this always on Windows.
for _, bad := range windowsBadWords {
if strings.Contains(testBinary, bad) {
a.Target = testDir + "test.test" + cfg.ExeSuffix
break
}
}
}
buildAction = a
var installAction, cleanAction *work.Action
if testC || testNeedBinary {
// -c or profiling flag: create action to copy binary to ./test.out.
target := filepath.Join(base.Cwd, testBinary+cfg.ExeSuffix)
if testO != "" {
target = testO
if !filepath.IsAbs(target) {
target = filepath.Join(base.Cwd, target)
}
}
pmain.Target = target
installAction = &work.Action{
Mode: "test build",
Func: work.BuildInstallFunc,
Deps: []*work.Action{buildAction},
Package: pmain,
Target: target,
}
runAction = installAction // make sure runAction != nil even if not running test
}
var vetRunAction *work.Action
if testC {
printAction = &work.Action{Mode: "test print (nop)", Package: p, Deps: []*work.Action{runAction}} // nop
vetRunAction = printAction
} else {
// run test
c := new(runCache)
runAction = &work.Action{
Mode: "test run",
Func: c.builderRunTest,
Deps: []*work.Action{buildAction},
Package: p,
IgnoreFail: true, // run (prepare output) even if build failed
TryCache: c.tryCache,
Objdir: testDir,
}
vetRunAction = runAction
cleanAction = &work.Action{
Mode: "test clean",
Func: builderCleanTest,
Deps: []*work.Action{runAction},
Package: p,
IgnoreFail: true, // clean even if test failed
Objdir: testDir,
}
printAction = &work.Action{
Mode: "test print",
Func: builderPrintTest,
Deps: []*work.Action{cleanAction},
Package: p,
IgnoreFail: true, // print even if test failed
}
}
if len(ptest.GoFiles)+len(ptest.CgoFiles) > 0 {
addTestVet(b, ptest, vetRunAction, installAction)
}
if pxtest != nil {
addTestVet(b, pxtest, vetRunAction, installAction)
}
if installAction != nil {
if runAction != installAction {
installAction.Deps = append(installAction.Deps, runAction)
}
if cleanAction != nil {
cleanAction.Deps = append(cleanAction.Deps, installAction)
}
}
return buildAction, runAction, printAction, nil
}
func addTestVet(b *work.Builder, p *load.Package, runAction, installAction *work.Action) {
if testVetList == "off" {
return
}
vet := b.VetAction(work.ModeBuild, work.ModeBuild, p)
runAction.Deps = append(runAction.Deps, vet)
// Install will clean the build directory.
// Make sure vet runs first.
// The install ordering in b.VetAction does not apply here
// because we are using a custom installAction (created above).
if installAction != nil {
installAction.Deps = append(installAction.Deps, vet)
}
}
// isTestFile reports whether the source file is a set of tests and should therefore
// be excluded from coverage analysis.
func isTestFile(file string) bool {
// We don't cover tests, only the code they test.
return strings.HasSuffix(file, "_test.go")
}
// declareCoverVars attaches the required cover variables names
// to the files, to be used when annotating the files.
func declareCoverVars(p *load.Package, files ...string) map[string]*load.CoverVar {
coverVars := make(map[string]*load.CoverVar)
coverIndex := 0
// We create the cover counters as new top-level variables in the package.
// We need to avoid collisions with user variables (GoCover_0 is unlikely but still)
// and more importantly with dot imports of other covered packages,
// so we append 12 hex digits from the SHA-256 of the import path.
// The point is only to avoid accidents, not to defeat users determined to
// break things.
sum := sha256.Sum256([]byte(p.ImportPath))
h := fmt.Sprintf("%x", sum[:6])
for _, file := range files {
if isTestFile(file) {
continue
}
// For a package that is "local" (imported via ./ import or command line, outside GOPATH),
// we record the full path to the file name.
// Otherwise we record the import path, then a forward slash, then the file name.
// This makes profiles within GOPATH file system-independent.
// These names appear in the cmd/cover HTML interface.
var longFile string
if p.Internal.Local {
longFile = filepath.Join(p.Dir, file)
} else {
longFile = path.Join(p.ImportPath, file)
}
coverVars[file] = &load.CoverVar{
File: longFile,
Var: fmt.Sprintf("GoCover_%d_%x", coverIndex, h),
}
coverIndex++
}
return coverVars
}
var noTestsToRun = []byte("\ntesting: warning: no tests to run\n")
type runCache struct {
disableCache bool // cache should be disabled for this run
buf *bytes.Buffer
id1 cache.ActionID
id2 cache.ActionID
}
// stdoutMu and lockedStdout provide a locked standard output
// that guarantees never to interlace writes from multiple
// goroutines, so that we can have multiple JSON streams writing
// to a lockedStdout simultaneously and know that events will
// still be intelligible.
var stdoutMu sync.Mutex
type lockedStdout struct{}
func (lockedStdout) Write(b []byte) (int, error) {
stdoutMu.Lock()
defer stdoutMu.Unlock()
return os.Stdout.Write(b)
}
// builderRunTest is the action for running a test binary.
func (c *runCache) builderRunTest(b *work.Builder, a *work.Action) error {
if a.Failed {
// We were unable to build the binary.
a.Failed = false
a.TestOutput = new(bytes.Buffer)
fmt.Fprintf(a.TestOutput, "FAIL\t%s [build failed]\n", a.Package.ImportPath)
base.SetExitStatus(1)
return nil
}
var stdout io.Writer = os.Stdout
if testJSON {
json := test2json.NewConverter(lockedStdout{}, a.Package.ImportPath, test2json.Timestamp)
defer json.Close()
stdout = json
}
var buf bytes.Buffer
if len(pkgArgs) == 0 || testBench {
// Stream test output (no buffering) when no package has
// been given on the command line (implicit current directory)
// or when benchmarking.
// No change to stdout.
} else {
// If we're only running a single package under test or if parallelism is
// set to 1, and if we're displaying all output (testShowPass), we can
// hurry the output along, echoing it as soon as it comes in.
// We still have to copy to &buf for caching the result. This special
// case was introduced in Go 1.5 and is intentionally undocumented:
// the exact details of output buffering are up to the go command and
// subject to change. It would be nice to remove this special case
// entirely, but it is surely very helpful to see progress being made
// when tests are run on slow single-CPU ARM systems.
//
// If we're showing JSON output, then display output as soon as
// possible even when multiple tests are being run: the JSON output
// events are attributed to specific package tests, so interlacing them
// is OK.
if testShowPass && (len(pkgs) == 1 || cfg.BuildP == 1) || testJSON {
// Write both to stdout and buf, for possible saving
// to cache, and for looking for the "no tests to run" message.
stdout = io.MultiWriter(stdout, &buf)
} else {
stdout = &buf
}
}
if c.buf == nil {
// We did not find a cached result using the link step action ID,
// so we ran the link step. Try again now with the link output
// content ID. The attempt using the action ID makes sure that
// if the link inputs don't change, we reuse the cached test
// result without even rerunning the linker. The attempt using
// the link output (test binary) content ID makes sure that if
// we have different link inputs but the same final binary,
// we still reuse the cached test result.
// c.saveOutput will store the result under both IDs.
c.tryCacheWithID(b, a, a.Deps[0].BuildContentID())
}
if c.buf != nil {
if stdout != &buf {
stdout.Write(c.buf.Bytes())
c.buf.Reset()
}
a.TestOutput = c.buf
return nil
}
execCmd := work.FindExecCmd()
testlogArg := []string{}
if !c.disableCache && len(execCmd) == 0 {
testlogArg = []string{"-test.testlogfile=" + a.Objdir + "testlog.txt"}
}
args := str.StringList(execCmd, a.Deps[0].BuiltTarget(), testlogArg, testArgs)
if testCoverProfile != "" {
// Write coverage to temporary profile, for merging later.
for i, arg := range args {
if strings.HasPrefix(arg, "-test.coverprofile=") {
args[i] = "-test.coverprofile=" + a.Objdir + "_cover_.out"
}
}
}
if cfg.BuildN || cfg.BuildX {
b.Showcmd("", "%s", strings.Join(args, " "))
if cfg.BuildN {
return nil
}
}
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = a.Package.Dir
cmd.Env = base.EnvForDir(cmd.Dir, cfg.OrigEnv)
cmd.Stdout = stdout
cmd.Stderr = stdout
// If there are any local SWIG dependencies, we want to load
// the shared library from the build directory.
if a.Package.UsesSwig() {
env := cmd.Env
found := false
prefix := "LD_LIBRARY_PATH="
for i, v := range env {
if strings.HasPrefix(v, prefix) {
env[i] = v + ":."
found = true
break
}
}
if !found {
env = append(env, "LD_LIBRARY_PATH=.")
}
cmd.Env = env
}
t0 := time.Now()
err := cmd.Start()
// This is a last-ditch deadline to detect and
// stop wedged test binaries, to keep the builders
// running.
if err == nil {
tick := time.NewTimer(testKillTimeout)
base.StartSigHandlers()
done := make(chan error)
go func() {
done <- cmd.Wait()
}()
Outer:
select {
case err = <-done:
// ok
case <-tick.C:
if base.SignalTrace != nil {
// Send a quit signal in the hope that the program will print
// a stack trace and exit. Give it five seconds before resorting
// to Kill.
cmd.Process.Signal(base.SignalTrace)
select {
case err = <-done:
fmt.Fprintf(cmd.Stdout, "*** Test killed with %v: ran too long (%v).\n", base.SignalTrace, testKillTimeout)
break Outer
case <-time.After(5 * time.Second):
}
}
cmd.Process.Kill()
err = <-done
fmt.Fprintf(cmd.Stdout, "*** Test killed: ran too long (%v).\n", testKillTimeout)
}
tick.Stop()
}
out := buf.Bytes()
a.TestOutput = &buf
t := fmt.Sprintf("%.3fs", time.Since(t0).Seconds())
mergeCoverProfile(cmd.Stdout, a.Objdir+"_cover_.out")
if err == nil {
norun := ""
if !testShowPass && !testJSON {
buf.Reset()
}
if bytes.HasPrefix(out, noTestsToRun[1:]) || bytes.Contains(out, noTestsToRun) {
norun = " [no tests to run]"
}
fmt.Fprintf(cmd.Stdout, "ok \t%s\t%s%s%s\n", a.Package.ImportPath, t, coveragePercentage(out), norun)
c.saveOutput(a)
} else {
base.SetExitStatus(1)
// If there was test output, assume we don't need to print the exit status.
// Buf there's no test output, do print the exit status.
if len(out) == 0 {
fmt.Fprintf(cmd.Stdout, "%s\n", err)
}
fmt.Fprintf(cmd.Stdout, "FAIL\t%s\t%s\n", a.Package.ImportPath, t)
}
if cmd.Stdout != &buf {
buf.Reset() // cmd.Stdout was going to os.Stdout already
}
return nil
}
// tryCache is called just before the link attempt,
// to see if the test result is cached and therefore the link is unneeded.
// It reports whether the result can be satisfied from cache.
func (c *runCache) tryCache(b *work.Builder, a *work.Action) bool {
return c.tryCacheWithID(b, a, a.Deps[0].BuildActionID())
}
func (c *runCache) tryCacheWithID(b *work.Builder, a *work.Action, id string) bool {
if len(pkgArgs) == 0 {
// Caching does not apply to "go test",
// only to "go test foo" (including "go test .").
if cache.DebugTest {
fmt.Fprintf(os.Stderr, "testcache: caching disabled in local directory mode\n")
}
c.disableCache = true
return false
}
var cacheArgs []string
for _, arg := range testArgs {
i := strings.Index(arg, "=")
if i < 0 || !strings.HasPrefix(arg, "-test.") {
if cache.DebugTest {
fmt.Fprintf(os.Stderr, "testcache: caching disabled for test argument: %s\n", arg)
}
c.disableCache = true
return false
}
switch arg[:i] {
case "-test.cpu",
"-test.list",
"-test.parallel",
"-test.run",
"-test.short",
"-test.v":
// These are cacheable.
// Note that this list is documented above,
// so if you add to this list, update the docs too.
cacheArgs = append(cacheArgs, arg)
case "-test.timeout":
// Special case: this is cacheable but ignored during the hash.
// Do not add to cacheArgs.
default:
// nothing else is cacheable
if cache.DebugTest {
fmt.Fprintf(os.Stderr, "testcache: caching disabled for test argument: %s\n", arg)
}
c.disableCache = true
return false
}
}
if cache.Default() == nil {
if cache.DebugTest {
fmt.Fprintf(os.Stderr, "testcache: GOCACHE=off\n")
}
c.disableCache = true
return false
}
// The test cache result fetch is a two-level lookup.
//
// First, we use the content hash of the test binary
// and its command-line arguments to find the
// list of environment variables and files consulted
// the last time the test was run with those arguments.
// (To avoid unnecessary links, we store this entry
// under two hashes: id1 uses the linker inputs as a
// proxy for the test binary, and id2 uses the actual
// test binary. If the linker inputs are unchanged,
// this way we avoid the link step, even though we
// do not cache link outputs.)
//
// Second, we compute a hash of the values of the
// environment variables and the content of the files
// listed in the log from the previous run.
// Then we look up test output using a combination of
// the hash from the first part (testID) and the hash of the
// test inputs (testInputsID).
//
// In order to store a new test result, we must redo the
// testInputsID computation using the log from the run
// we want to cache, and then we store that new log and
// the new outputs.
h := cache.NewHash("testResult")
fmt.Fprintf(h, "test binary %s args %q execcmd %q", id, cacheArgs, work.ExecCmd)
testID := h.Sum()
if c.id1 == (cache.ActionID{}) {
c.id1 = testID
} else {
c.id2 = testID
}
if cache.DebugTest {
fmt.Fprintf(os.Stderr, "testcache: %s: test ID %x => %x\n", a.Package.ImportPath, id, testID)
}
// Load list of referenced environment variables and files
// from last run of testID, and compute hash of that content.
data, entry, err := cache.Default().GetBytes(testID)
if !bytes.HasPrefix(data, testlogMagic) || data[len(data)-1] != '\n' {
if cache.DebugTest {
if err != nil {
fmt.Fprintf(os.Stderr, "testcache: %s: input list not found: %v\n", a.Package.ImportPath, err)
} else {
fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed\n", a.Package.ImportPath)
}
}
return false
}
testInputsID, err := computeTestInputsID(a, data)
if err != nil {
return false
}
if cache.DebugTest {
fmt.Fprintf(os.Stderr, "testcache: %s: test ID %x => input ID %x => %x\n", a.Package.ImportPath, testID, testInputsID, testAndInputKey(testID, testInputsID))
}
// Parse cached result in preparation for changing run time to "(cached)".
// If we can't parse the cached result, don't use it.
data, entry, err = cache.Default().GetBytes(testAndInputKey(testID, testInputsID))
if len(data) == 0 || data[len(data)-1] != '\n' {
if cache.DebugTest {
if err != nil {
fmt.Fprintf(os.Stderr, "testcache: %s: test output not found: %v\n", a.Package.ImportPath, err)
} else {
fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
}
}
return false
}
if entry.Time.Before(testCacheExpire) {
if cache.DebugTest {
fmt.Fprintf(os.Stderr, "testcache: %s: test output expired due to go clean -testcache\n", a.Package.ImportPath)
}
return false
}
i := bytes.LastIndexByte(data[:len(data)-1], '\n') + 1
if !bytes.HasPrefix(data[i:], []byte("ok \t")) {
if cache.DebugTest {
fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
}
return false
}
j := bytes.IndexByte(data[i+len("ok \t"):], '\t')
if j < 0 {
if cache.DebugTest {
fmt.Fprintf(os.Stderr, "testcache: %s: test output malformed\n", a.Package.ImportPath)
}
return false
}
j += i + len("ok \t") + 1
// Committed to printing.
c.buf = new(bytes.Buffer)
c.buf.Write(data[:j])
c.buf.WriteString("(cached)")
for j < len(data) && ('0' <= data[j] && data[j] <= '9' || data[j] == '.' || data[j] == 's') {
j++
}
c.buf.Write(data[j:])
return true
}
var errBadTestInputs = errors.New("error parsing test inputs")
var testlogMagic = []byte("# test log\n") // known to testing/internal/testdeps/deps.go
// computeTestInputsID computes the "test inputs ID"
// (see comment in tryCacheWithID above) for the
// test log.
func computeTestInputsID(a *work.Action, testlog []byte) (cache.ActionID, error) {
testlog = bytes.TrimPrefix(testlog, testlogMagic)
h := cache.NewHash("testInputs")
pwd := a.Package.Dir
for _, line := range bytes.Split(testlog, []byte("\n")) {
if len(line) == 0 {
continue
}
s := string(line)
i := strings.Index(s, " ")
if i < 0 {
if cache.DebugTest {
fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed (%q)\n", a.Package.ImportPath, line)
}
return cache.ActionID{}, errBadTestInputs
}
op := s[:i]
name := s[i+1:]
switch op {
default:
if cache.DebugTest {
fmt.Fprintf(os.Stderr, "testcache: %s: input list malformed (%q)\n", a.Package.ImportPath, line)
}
return cache.ActionID{}, errBadTestInputs
case "getenv":
fmt.Fprintf(h, "env %s %x\n", name, hashGetenv(name))
case "chdir":
pwd = name // always absolute
fmt.Fprintf(h, "chdir %s %x\n", name, hashStat(name))
case "stat":
if !filepath.IsAbs(name) {
name = filepath.Join(pwd, name)
}
if !inDir(name, a.Package.Root) {
// Do not recheck files outside the GOPATH or GOROOT root.
break
}
fmt.Fprintf(h, "stat %s %x\n", name, hashStat(name))
case "open":
if !filepath.IsAbs(name) {
name = filepath.Join(pwd, name)
}
if !inDir(name, a.Package.Root) {
// Do not recheck files outside the GOPATH or GOROOT root.
break
}
fh, err := hashOpen(name)
if err != nil {
if cache.DebugTest {
fmt.Fprintf(os.Stderr, "testcache: %s: input file %s: %s\n", a.Package.ImportPath, name, err)
}
return cache.ActionID{}, err
}
fmt.Fprintf(h, "open %s %x\n", name, fh)
}
}
sum := h.Sum()
return sum, nil
}
func inDir(path, dir string) bool {
if str.HasFilePathPrefix(path, dir) {
return true
}
xpath, err1 := filepath.EvalSymlinks(path)
xdir, err2 := filepath.EvalSymlinks(dir)
if err1 == nil && err2 == nil && str.HasFilePathPrefix(xpath, xdir) {
return true
}
return false
}
func hashGetenv(name string) cache.ActionID {
h := cache.NewHash("getenv")
v, ok := os.LookupEnv(name)
if !ok {
h.Write([]byte{0})
} else {
h.Write([]byte{1})
h.Write([]byte(v))
}
return h.Sum()
}
const modTimeCutoff = 2 * time.Second
var errFileTooNew = errors.New("file used as input is too new")
func hashOpen(name string) (cache.ActionID, error) {
h := cache.NewHash("open")
info, err := os.Stat(name)
if err != nil {
fmt.Fprintf(h, "err %v\n", err)
return h.Sum(), nil
}
hashWriteStat(h, info)
if info.IsDir() {
names, err := ioutil.ReadDir(name)
if err != nil {
fmt.Fprintf(h, "err %v\n", err)
}
for _, f := range names {
fmt.Fprintf(h, "file %s ", f.Name())
hashWriteStat(h, f)
}
} else if info.Mode().IsRegular() {
// Because files might be very large, do not attempt
// to hash the entirety of their content. Instead assume
// the mtime and size recorded in hashWriteStat above
// are good enough.
//
// To avoid problems for very recent files where a new
// write might not change the mtime due to file system
// mtime precision, reject caching if a file was read that
// is less than modTimeCutoff old.
if time.Since(info.ModTime()) < modTimeCutoff {
return cache.ActionID{}, errFileTooNew
}
}
return h.Sum(), nil
}
func hashStat(name string) cache.ActionID {
h := cache.NewHash("stat")
if info, err := os.Stat(name); err != nil {
fmt.Fprintf(h, "err %v\n", err)
} else {
hashWriteStat(h, info)
}
if info, err := os.Lstat(name); err != nil {
fmt.Fprintf(h, "err %v\n", err)
} else {
hashWriteStat(h, info)
}
return h.Sum()
}
func hashWriteStat(h io.Writer, info os.FileInfo) {
fmt.Fprintf(h, "stat %d %x %v %v\n", info.Size(), uint64(info.Mode()), info.ModTime(), info.IsDir())
}
// testAndInputKey returns the actual cache key for the pair (testID, testInputsID).
func testAndInputKey(testID, testInputsID cache.ActionID) cache.ActionID {
return cache.Subkey(testID, fmt.Sprintf("inputs:%x", testInputsID))
}
func (c *runCache) saveOutput(a *work.Action) {
if c.id1 == (cache.ActionID{}) && c.id2 == (cache.ActionID{}) {
return
}
// See comment about two-level lookup in tryCacheWithID above.
testlog, err := ioutil.ReadFile(a.Objdir + "testlog.txt")
if err != nil || !bytes.HasPrefix(testlog, testlogMagic) || testlog[len(testlog)-1] != '\n' {
if cache.DebugTest {
if err != nil {
fmt.Fprintf(os.Stderr, "testcache: %s: reading testlog: %v\n", a.Package.ImportPath, err)
} else {
fmt.Fprintf(os.Stderr, "testcache: %s: reading testlog: malformed\n", a.Package.ImportPath)
}
}
return
}
testInputsID, err := computeTestInputsID(a, testlog)
if err != nil {
return
}
if c.id1 != (cache.ActionID{}) {
if cache.DebugTest {
fmt.Fprintf(os.Stderr, "testcache: %s: save test ID %x => input ID %x => %x\n", a.Package.ImportPath, c.id1, testInputsID, testAndInputKey(c.id1, testInputsID))
}
cache.Default().PutNoVerify(c.id1, bytes.NewReader(testlog))
cache.Default().PutNoVerify(testAndInputKey(c.id1, testInputsID), bytes.NewReader(a.TestOutput.Bytes()))
}
if c.id2 != (cache.ActionID{}) {
if cache.DebugTest {
fmt.Fprintf(os.Stderr, "testcache: %s: save test ID %x => input ID %x => %x\n", a.Package.ImportPath, c.id2, testInputsID, testAndInputKey(c.id2, testInputsID))
}
cache.Default().PutNoVerify(c.id2, bytes.NewReader(testlog))
cache.Default().PutNoVerify(testAndInputKey(c.id2, testInputsID), bytes.NewReader(a.TestOutput.Bytes()))
}
}
// coveragePercentage returns the coverage results (if enabled) for the
// test. It uncovers the data by scanning the output from the test run.
func coveragePercentage(out []byte) string {
if !testCover {
return ""
}
// The string looks like
// test coverage for encoding/binary: 79.9% of statements
// Extract the piece from the percentage to the end of the line.
re := regexp.MustCompile(`coverage: (.*)\n`)
matches := re.FindSubmatch(out)
if matches == nil {
// Probably running "go test -cover" not "go test -cover fmt".
// The coverage output will appear in the output directly.
return ""
}
return fmt.Sprintf("\tcoverage: %s", matches[1])
}
// builderCleanTest is the action for cleaning up after a test.
func builderCleanTest(b *work.Builder, a *work.Action) error {
if cfg.BuildWork {
return nil
}
if cfg.BuildX {
b.Showcmd("", "rm -r %s", a.Objdir)
}
os.RemoveAll(a.Objdir)
return nil
}
// builderPrintTest is the action for printing a test result.
func builderPrintTest(b *work.Builder, a *work.Action) error {
clean := a.Deps[0]
run := clean.Deps[0]
if run.TestOutput != nil {
os.Stdout.Write(run.TestOutput.Bytes())
run.TestOutput = nil
}
return nil
}
// builderNoTest is the action for testing a package with no test files.
func builderNoTest(b *work.Builder, a *work.Action) error {
var stdout io.Writer = os.Stdout
if testJSON {
json := test2json.NewConverter(lockedStdout{}, a.Package.ImportPath, test2json.Timestamp)
defer json.Close()
stdout = json
}
fmt.Fprintf(stdout, "? \t%s\t[no test files]\n", a.Package.ImportPath)
return nil
}
|
test
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/test/cover.go
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package test
import (
"cmd/go/internal/base"
"fmt"
"io"
"os"
"path/filepath"
"sync"
)
var coverMerge struct {
f *os.File
sync.Mutex // for f.Write
}
// initCoverProfile initializes the test coverage profile.
// It must be run before any calls to mergeCoverProfile or closeCoverProfile.
// Using this function clears the profile in case it existed from a previous run,
// or in case it doesn't exist and the test is going to fail to create it (or not run).
func initCoverProfile() {
if testCoverProfile == "" || testC {
return
}
if !filepath.IsAbs(testCoverProfile) && testOutputDir != "" {
testCoverProfile = filepath.Join(testOutputDir, testCoverProfile)
}
// No mutex - caller's responsibility to call with no racing goroutines.
f, err := os.Create(testCoverProfile)
if err != nil {
base.Fatalf("%v", err)
}
_, err = fmt.Fprintf(f, "mode: %s\n", testCoverMode)
if err != nil {
base.Fatalf("%v", err)
}
coverMerge.f = f
}
// mergeCoverProfile merges file into the profile stored in testCoverProfile.
// It prints any errors it encounters to ew.
func mergeCoverProfile(ew io.Writer, file string) {
if coverMerge.f == nil {
return
}
coverMerge.Lock()
defer coverMerge.Unlock()
expect := fmt.Sprintf("mode: %s\n", testCoverMode)
buf := make([]byte, len(expect))
r, err := os.Open(file)
if err != nil {
// Test did not create profile, which is OK.
return
}
defer r.Close()
n, err := io.ReadFull(r, buf)
if n == 0 {
return
}
if err != nil || string(buf) != expect {
fmt.Fprintf(ew, "error: test wrote malformed coverage profile.\n")
return
}
_, err = io.Copy(coverMerge.f, r)
if err != nil {
fmt.Fprintf(ew, "error: saving coverage profile: %v\n", err)
}
}
func closeCoverProfile() {
if coverMerge.f == nil {
return
}
if err := coverMerge.f.Close(); err != nil {
base.Errorf("closing coverage profile: %v", err)
}
}
|
test
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/test/testflag.go
|
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package test
import (
"flag"
"os"
"strings"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"cmd/go/internal/cmdflag"
"cmd/go/internal/str"
"cmd/go/internal/work"
)
const cmd = "test"
// The flag handling part of go test is large and distracting.
// We can't use the flag package because some of the flags from
// our command line are for us, and some are for 6.out, and
// some are for both.
// testFlagDefn is the set of flags we process.
var testFlagDefn = []*cmdflag.Defn{
// local.
{Name: "c", BoolVar: &testC},
{Name: "i", BoolVar: &cfg.BuildI},
{Name: "o"},
{Name: "cover", BoolVar: &testCover},
{Name: "covermode"},
{Name: "coverpkg"},
{Name: "exec"},
{Name: "json", BoolVar: &testJSON},
{Name: "vet"},
// Passed to 6.out, adding a "test." prefix to the name if necessary: -v becomes -test.v.
{Name: "bench", PassToTest: true},
{Name: "benchmem", BoolVar: new(bool), PassToTest: true},
{Name: "benchtime", PassToTest: true},
{Name: "blockprofile", PassToTest: true},
{Name: "blockprofilerate", PassToTest: true},
{Name: "count", PassToTest: true},
{Name: "coverprofile", PassToTest: true},
{Name: "cpu", PassToTest: true},
{Name: "cpuprofile", PassToTest: true},
{Name: "failfast", BoolVar: new(bool), PassToTest: true},
{Name: "list", PassToTest: true},
{Name: "memprofile", PassToTest: true},
{Name: "memprofilerate", PassToTest: true},
{Name: "mutexprofile", PassToTest: true},
{Name: "mutexprofilefraction", PassToTest: true},
{Name: "outputdir", PassToTest: true},
{Name: "parallel", PassToTest: true},
{Name: "run", PassToTest: true},
{Name: "short", BoolVar: new(bool), PassToTest: true},
{Name: "timeout", PassToTest: true},
{Name: "trace", PassToTest: true},
{Name: "v", BoolVar: &testV, PassToTest: true},
}
// add build flags to testFlagDefn
func init() {
cmdflag.AddKnownFlags("test", testFlagDefn)
var cmd base.Command
work.AddBuildFlags(&cmd)
cmd.Flag.VisitAll(func(f *flag.Flag) {
if f.Name == "v" {
// test overrides the build -v flag
return
}
testFlagDefn = append(testFlagDefn, &cmdflag.Defn{
Name: f.Name,
Value: f.Value,
})
})
}
// testFlags processes the command line, grabbing -x and -c, rewriting known flags
// to have "test" before them, and reading the command line for the 6.out.
// Unfortunately for us, we need to do our own flag processing because go test
// grabs some flags but otherwise its command line is just a holding place for
// pkg.test's arguments.
// We allow known flags both before and after the package name list,
// to allow both
// go test fmt -custom-flag-for-fmt-test
// go test -x math
func testFlags(args []string) (packageNames, passToTest []string) {
args = str.StringList(cmdflag.FindGOFLAGS(testFlagDefn), args)
inPkg := false
var explicitArgs []string
for i := 0; i < len(args); i++ {
if !strings.HasPrefix(args[i], "-") {
if !inPkg && packageNames == nil {
// First package name we've seen.
inPkg = true
}
if inPkg {
packageNames = append(packageNames, args[i])
continue
}
}
if inPkg {
// Found an argument beginning with "-"; end of package list.
inPkg = false
}
f, value, extraWord := cmdflag.Parse(cmd, testFlagDefn, args, i)
if f == nil {
// This is a flag we do not know; we must assume
// that any args we see after this might be flag
// arguments, not package names.
inPkg = false
if packageNames == nil {
// make non-nil: we have seen the empty package list
packageNames = []string{}
}
if args[i] == "-args" || args[i] == "--args" {
// -args or --args signals that everything that follows
// should be passed to the test.
explicitArgs = args[i+1:]
break
}
passToTest = append(passToTest, args[i])
continue
}
if f.Value != nil {
if err := f.Value.Set(value); err != nil {
base.Fatalf("invalid flag argument for -%s: %v", f.Name, err)
}
} else {
// Test-only flags.
// Arguably should be handled by f.Value, but aren't.
switch f.Name {
// bool flags.
case "c", "i", "v", "cover", "json":
cmdflag.SetBool(cmd, f.BoolVar, value)
if f.Name == "json" && testJSON {
passToTest = append(passToTest, "-test.v=true")
}
case "o":
testO = value
testNeedBinary = true
case "exec":
xcmd, err := str.SplitQuotedFields(value)
if err != nil {
base.Fatalf("invalid flag argument for -%s: %v", f.Name, err)
}
work.ExecCmd = xcmd
case "bench":
// record that we saw the flag; don't care about the value
testBench = true
case "list":
testList = true
case "timeout":
testTimeout = value
case "blockprofile", "cpuprofile", "memprofile", "mutexprofile":
testProfile = "-" + f.Name
testNeedBinary = true
case "trace":
testProfile = "-trace"
case "coverpkg":
testCover = true
if value == "" {
testCoverPaths = nil
} else {
testCoverPaths = strings.Split(value, ",")
}
case "coverprofile":
testCover = true
testCoverProfile = value
case "covermode":
switch value {
case "set", "count", "atomic":
testCoverMode = value
default:
base.Fatalf("invalid flag argument for -covermode: %q", value)
}
testCover = true
case "outputdir":
testOutputDir = value
case "vet":
testVetList = value
}
}
if extraWord {
i++
}
if f.PassToTest {
passToTest = append(passToTest, "-test."+f.Name+"="+value)
}
}
if testCoverMode == "" {
testCoverMode = "set"
if cfg.BuildRace {
// Default coverage mode is atomic when -race is set.
testCoverMode = "atomic"
}
}
if testVetList != "" && testVetList != "off" {
if strings.Contains(testVetList, "=") {
base.Fatalf("-vet argument cannot contain equal signs")
}
if strings.Contains(testVetList, " ") {
base.Fatalf("-vet argument is comma-separated list, cannot contain spaces")
}
list := strings.Split(testVetList, ",")
for i, arg := range list {
list[i] = "-" + arg
}
testVetFlags = list
}
if cfg.BuildRace && testCoverMode != "atomic" {
base.Fatalf(`-covermode must be "atomic", not %q, when -race is enabled`, testCoverMode)
}
// Tell the test what directory we're running in, so it can write the profiles there.
if testProfile != "" && testOutputDir == "" {
dir, err := os.Getwd()
if err != nil {
base.Fatalf("error from os.Getwd: %s", err)
}
passToTest = append(passToTest, "-test.outputdir", dir)
}
passToTest = append(passToTest, explicitArgs...)
return
}
|
sublime-config
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/.pep8
|
[flake8]
max-line-length = 120
|
sublime-config
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/CONTRIBUTING.md
|
# Contributing to Go
Go is an open source project.
It is the work of hundreds of contributors. We appreciate your help!
## Filing issues
When filing an issue, make sure to answer these five questions:
1. What version of Go are you using (`go version`)?
2. What operating system and processor architecture are you using?
3. What did you do?
4. What did you expect to see?
5. What did you see instead?
General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker.
The gophers there will answer or ask you to file an issue if you've tripped over a bug.
Sensitive security-related issues should be reported to [security@golang.org](mailto:security@golang.org).
## Contributing code
Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html)
before sending patches.
Unless otherwise noted, the Go source files are distributed under
the BSD-style license found in the LICENSE file.
|
sublime-config
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/PATENTS
|
Additional IP Rights Grant (Patents)
"This implementation" means the copyrightable works distributed by
Google as part of the Go project.
Google hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section)
patent license to make, have made, use, offer to sell, sell, import,
transfer and otherwise run, modify and propagate the contents of this
implementation of Go, where such license applies only to those patent
claims, both currently owned or controlled by Google and acquired in
the future, licensable by Google that are necessarily infringed by this
implementation of Go. This grant does not include claims that would be
infringed only as a consequence of further modification of this
implementation. If you or your agent or exclusive licensee institute or
order or agree to the institution of patent litigation against any
entity (including a cross-claim or counterclaim in a lawsuit) alleging
that this implementation of Go or any code incorporated within this
implementation of Go constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any patent
rights granted to you under this License for this implementation of Go
shall terminate as of the date such litigation is filed.
|
sublime-config
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/Main.sublime-menu
|
[
{
"id": "preferences",
"children":
[
{
"caption": "Package Settings",
"mnemonic": "P",
"id": "package-settings",
"children":
[
{
"caption": "Golang Config",
"children":
[
{
"command": "open_file", "args":
{
"file": "${packages}/User/golang.sublime-settings"
},
"caption": "Settings – User"
}
]
}
]
}
]
}
]
|
sublime-config
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/readme.md
|
# golangconfig
`golangconfig` is a Sublime Text dependency designed to be a common API for
configuration of Go environment variables. It is intended to be used by any and
all Go-related Sublime Text packages in an effort to help reduce duplication
of user configuration.
The documentation for the package is split into two audiences:
- [User documentation](docs/user.md) describing how to configure Sublime Text
to properly work with your Go environment
- [Package developer documentation](docs/package_developer.md) containing API
documentation and instructions on how to require `golangconfig` for your
package
Other documentation:
- [Changelog](docs/changelog.md)
- [License](LICENSE)
- [Design](docs/design.md)
- [Development](docs/development.md)
|
sublime-config
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/.sublime-dependency
|
10
|
sublime-config
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/LICENSE
|
Copyright (c) 2012 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
dev
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/dev/tests.py
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import unittest
import sys
import os
if sys.version_info < (3,):
str_cls = unicode # noqa
else:
str_cls = str
import shellenv
import golangconfig
from .mocks import GolangConfigMock
from .unittest_data import data, data_class
class CustomString():
value = None
def __init__(self, value):
self.value = value
def __str__(self):
return self.value
def __unicode__(self):
return self.__str__()
@data_class
class GolangconfigTests(unittest.TestCase):
@staticmethod
def subprocess_info_data():
return (
(
'basic_shell',
'/bin/bash',
{
'PATH': '{tempdir}bin:{tempdir}usr/bin',
'GOPATH': '{tempdir}gopath',
},
None,
None,
{'debug': True},
['usr/bin/go'],
['gopath/'],
'go',
['GOPATH'],
None,
(
'{tempdir}usr/bin/go',
{
'PATH': '{tempdir}bin:{tempdir}usr/bin',
'GOPATH': '{tempdir}gopath',
}
),
),
(
'view_setting_override',
'/bin/bash',
{
'PATH': '{tempdir}bin:{tempdir}usr/bin',
'GOPATH': '{tempdir}gopath',
},
{'GOPATH': '{tempdir}custom/gopath', 'GOOS': 'windows'},
None,
{'debug': True},
['usr/bin/go'],
['custom/gopath/'],
'go',
['GOPATH'],
None,
(
'{tempdir}usr/bin/go',
{
'PATH': '{tempdir}bin:{tempdir}usr/bin',
'GOPATH': '{tempdir}custom/gopath',
}
),
),
(
'view_setting_override_optional_missing',
'/bin/bash',
{
'PATH': '{tempdir}bin:{tempdir}usr/bin',
'GOPATH': '{tempdir}gopath',
},
{'GOPATH': '{tempdir}custom/gopath'},
None,
{'debug': True},
['usr/bin/go'],
['custom/gopath/'],
'go',
['GOPATH'],
['GOOS'],
(
'{tempdir}usr/bin/go',
{
'PATH': '{tempdir}bin:{tempdir}usr/bin',
'GOPATH': '{tempdir}custom/gopath',
}
),
),
(
'view_setting_override_optional_present',
'/bin/bash',
{
'PATH': '{tempdir}bin:{tempdir}usr/bin',
'GOPATH': '{tempdir}gopath',
},
{'GOPATH': '{tempdir}custom/gopath', 'GOOS': 'windows'},
None,
{'debug': True},
['usr/bin/go'],
['custom/gopath/'],
'go',
['GOPATH'],
['GOOS'],
(
'{tempdir}usr/bin/go',
{
'PATH': '{tempdir}bin:{tempdir}usr/bin',
'GOPATH': '{tempdir}custom/gopath',
'GOOS': 'windows',
}
),
),
(
'view_setting_unset',
'/bin/bash',
{
'PATH': '{tempdir}bin:{tempdir}usr/bin',
'GOPATH': '{tempdir}gopath',
'GOOS': 'windows'
},
{'GOPATH': '{tempdir}custom/gopath', 'GOOS': None},
None,
{'debug': True},
['usr/bin/go'],
['custom/gopath/'],
'go',
['GOPATH'],
['GOOS'],
(
'{tempdir}usr/bin/go',
{
'PATH': '{tempdir}bin:{tempdir}usr/bin',
'GOPATH': '{tempdir}custom/gopath',
}
),
),
(
'no_executable',
'/bin/bash',
{
'PATH': '{tempdir}bin:{tempdir}usr/bin',
'GOPATH': '{tempdir}gopath',
},
{'GOPATH': '{tempdir}custom/gopath'},
None,
{'debug': True, 'PATH': '{tempdir}usr/local/bin'},
[],
['custom/gopath/'],
'go',
['GOPATH'],
None,
golangconfig.ExecutableError
),
(
'env_var_missing',
'/bin/bash',
{
'PATH': '{tempdir}bin:{tempdir}usr/bin',
'GOPATH': '{tempdir}gopath',
},
{'GOPATH': '{tempdir}custom/gopath'},
None,
{'debug': True},
['bin/go'],
['custom/gopath/'],
'go',
['GOPATH', 'GOROOT'],
None,
golangconfig.GoRootNotFoundError
),
)
@data('subprocess_info_data', True)
def subprocess_info(self, shell, env, view_settings, window_settings, sublime_settings,
executable_temp_files, temp_dirs, executable_name, required_vars, optional_vars,
expected_result):
with GolangConfigMock(shell, env, view_settings, window_settings, sublime_settings) as mock_context:
mock_context.replace_tempdir_env()
mock_context.replace_tempdir_view_settings()
mock_context.replace_tempdir_window_settings()
mock_context.replace_tempdir_sublime_settings()
mock_context.make_executable_files(executable_temp_files)
mock_context.make_dirs(temp_dirs)
if isinstance(expected_result, tuple):
tempdir = mock_context.tempdir + os.sep
executable_path = expected_result[0].replace('{tempdir}', tempdir)
executable_path = shellenv.path_encode(executable_path)
env_vars = {}
for name, value in expected_result[1].items():
value = value.replace('{tempdir}', tempdir)
name = shellenv.env_encode(name)
value = shellenv.env_encode(value)
env_vars[name] = value
expected_result = (executable_path, env_vars)
self.assertEquals(
expected_result,
golangconfig.subprocess_info(
executable_name,
required_vars,
optional_vars=optional_vars,
view=mock_context.view,
window=mock_context.window
)
)
self.assertEqual('', sys.stdout.getvalue())
else:
def do_test():
golangconfig.subprocess_info(
executable_name,
required_vars,
optional_vars=optional_vars,
view=mock_context.view,
window=mock_context.window
)
self.assertRaises(expected_result, do_test)
@staticmethod
def executable_path_data():
return (
(
'basic_shell',
'/bin/bash',
{
'PATH': '{tempdir}bin:{tempdir}usr/bin'
},
None,
None,
{'debug': True},
['bin/go'],
[],
None,
('{tempdir}bin/go', '/bin/bash'),
),
(
'basic_view_settings',
'/bin/bash',
{
'PATH': '{tempdir}bin'
},
{'PATH': '{tempdir}usr/bin:{tempdir}usr/local/bin'},
{},
{},
['usr/local/bin/go'],
['usr/bin/go'],
None,
('{tempdir}usr/local/bin/go', 'project file'),
),
(
'basic_view_settings_debug',
'/bin/bash',
{
'PATH': '{tempdir}bin'
},
{'PATH': '{tempdir}usr/bin:{tempdir}usr/local/bin'},
{},
{'debug': True},
['usr/local/bin/go'],
['usr/bin/go'],
'is not executable',
('{tempdir}usr/local/bin/go', 'project file'),
),
(
'basic_view_settings_none_found',
'/bin/bash',
{
'PATH': '{tempdir}bin'
},
{'PATH': '{tempdir}usr/bin:{tempdir}usr/local/bin'},
{},
{'debug': True},
[],
['usr/bin/go'],
'is not executable',
(None, None),
),
)
@data('executable_path_data', True)
def executable_path(self, shell, env, view_settings, window_settings, sublime_settings,
executable_temp_files, non_executable_temp_files, expected_debug, expected_result):
with GolangConfigMock(shell, env, view_settings, window_settings, sublime_settings) as mock_context:
mock_context.replace_tempdir_env()
mock_context.replace_tempdir_view_settings()
mock_context.replace_tempdir_window_settings()
mock_context.make_executable_files(executable_temp_files)
mock_context.make_files(non_executable_temp_files)
if expected_result[0]:
tempdir = mock_context.tempdir + os.sep
expected_result = (expected_result[0].replace('{tempdir}', tempdir), expected_result[1])
self.assertEquals(
expected_result,
golangconfig.executable_path('go', mock_context.view, mock_context.window)
)
if expected_debug is None:
self.assertEqual('', sys.stdout.getvalue())
else:
self.assertTrue(expected_debug in sys.stdout.getvalue())
def test_executable_path_path_not_string(self):
shell = '/bin/bash'
env = {
'PATH': '/bin'
}
view_settings = {
'PATH': 1
}
with GolangConfigMock(shell, env, view_settings, None, {'debug': True}) as mock_context:
self.assertEquals((None, None), golangconfig.executable_path('go', mock_context.view, mock_context.window))
self.assertTrue('is not a string' in sys.stdout.getvalue())
@staticmethod
def setting_value_gopath_data():
return (
(
'basic_shell',
'/bin/bash',
{
'PATH': '/bin',
'GOPATH': os.path.expanduser('~'),
},
None,
None,
{},
'GOPATH',
(os.path.expanduser('~'), '/bin/bash'),
),
(
'basic_shell_2',
'/bin/bash',
{
'PATH': '/bin'
},
None,
None,
{},
'PATH',
('/bin', '/bin/bash'),
),
(
'basic_view_settings',
'/bin/bash',
{
'PATH': '/bin',
'GOPATH': os.path.expanduser('~'),
},
{'GOPATH': '/usr/bin'},
None,
{},
'GOPATH',
('/usr/bin', 'project file'),
),
(
'basic_window_settings',
'/bin/bash',
{
'PATH': '/bin',
'GOPATH': os.path.expanduser('~'),
},
None,
{'GOPATH': '/usr/bin'},
{},
'GOPATH',
('/usr/bin', 'project file'),
),
(
'basic_sublime_settings',
'/bin/bash',
{
'PATH': '/bin',
'GOPATH': os.path.expanduser('~'),
},
{},
{},
{'GOPATH': '/usr/local/bin'},
'GOPATH',
('/usr/local/bin', 'golang.sublime-settings'),
),
(
'os_view_settings',
'/bin/bash',
{
'PATH': '/bin',
'GOPATH': os.path.expanduser('~'),
},
{
'osx': {'GOPATH': '/usr/bin'},
'windows': {'GOPATH': '/usr/bin'},
'linux': {'GOPATH': '/usr/bin'},
},
{},
{},
'GOPATH',
('/usr/bin', 'project file (os-specific)'),
),
(
'os_window_settings',
'/bin/bash',
{
'PATH': '/bin',
'GOPATH': os.path.expanduser('~'),
},
None,
{
'osx': {'GOPATH': '/usr/bin'},
'windows': {'GOPATH': '/usr/bin'},
'linux': {'GOPATH': '/usr/bin'},
},
{},
'GOPATH',
('/usr/bin', 'project file (os-specific)'),
),
(
'os_sublime_settings',
'/bin/bash',
{
'PATH': '/bin',
'GOPATH': os.path.expanduser('~'),
},
{
'GOPATH': '/foo/bar'
},
{},
{
'osx': {'GOPATH': '/usr/local/bin'},
'windows': {'GOPATH': '/usr/local/bin'},
'linux': {'GOPATH': '/usr/local/bin'},
},
'GOPATH',
('/usr/local/bin', 'golang.sublime-settings (os-specific)'),
),
(
'os_sublime_settings_wrong_type',
'/bin/bash',
{
'PATH': '/bin',
'GOPATH': os.path.expanduser('~'),
},
{},
{},
{
'osx': 1,
'windows': 1,
'linux': 1,
},
'GOPATH',
(os.path.expanduser('~'), '/bin/bash'),
),
)
@data('setting_value_gopath_data', True)
def setting_value_gopath(self, shell, env, view_settings, window_settings, sublime_settings, setting, result):
with GolangConfigMock(shell, env, view_settings, window_settings, sublime_settings) as mock_context:
self.assertEquals(result, golangconfig.setting_value(setting, mock_context.view, mock_context.window))
self.assertEqual('', sys.stdout.getvalue())
def test_setting_value_bytes_name(self):
shell = '/bin/bash'
env = {
'GOPATH': os.path.expanduser('~')
}
with GolangConfigMock(shell, env, None, None, {'debug': True}) as mock_context:
def do_test():
golangconfig.setting_value(b'GOPATH', mock_context.view, mock_context.window)
self.assertRaises(TypeError, do_test)
def test_setting_value_custom_type(self):
shell = '/bin/bash'
env = {
'GOPATH': os.path.expanduser('~')
}
with GolangConfigMock(shell, env, None, None, {'debug': True}) as mock_context:
def do_test():
golangconfig.setting_value(CustomString('GOPATH'), mock_context.view, mock_context.window)
self.assertRaises(TypeError, do_test)
def test_setting_value_incorrect_view_type(self):
shell = '/bin/bash'
env = {
'GOPATH': os.path.expanduser('~')
}
with GolangConfigMock(shell, env, None, None, {'debug': True}) as mock_context:
def do_test():
golangconfig.setting_value('GOPATH', True, mock_context.window)
self.assertRaises(TypeError, do_test)
def test_setting_value_incorrect_window_type(self):
shell = '/bin/bash'
env = {
'GOPATH': os.path.expanduser('~')
}
with GolangConfigMock(shell, env, None, None, {'debug': True}) as mock_context:
def do_test():
golangconfig.setting_value('GOPATH', mock_context.view, True)
self.assertRaises(TypeError, do_test)
def test_setting_value_gopath_not_existing(self):
shell = '/bin/bash'
env = {
'GOPATH': os.path.join(os.path.expanduser('~'), 'hdjsahkjzhkjzhiashs7hdsuybyusbguycas')
}
with GolangConfigMock(shell, env, None, None, {'debug': True}) as mock_context:
def do_test():
golangconfig.setting_value('GOPATH', mock_context.view, mock_context.window)
self.assertRaises(golangconfig.GoPathNotFoundError, do_test)
def test_setting_value_multiple_gopath_one_not_existing(self):
shell = '/bin/bash'
env = {
'GOPATH': '{tempdir}bin%s{tempdir}usr/bin' % os.pathsep
}
with GolangConfigMock(shell, env, None, None, {'debug': True}) as mock_context:
mock_context.replace_tempdir_env()
mock_context.make_dirs(['usr/bin'])
def do_test():
golangconfig.setting_value('GOPATH', mock_context.view, mock_context.window)
self.assertRaises(golangconfig.GoPathNotFoundError, do_test)
def test_setting_value_multiple_gopath(self):
shell = '/bin/bash'
env = {
'GOPATH': '{tempdir}bin%s{tempdir}usr/bin' % os.pathsep
}
with GolangConfigMock(shell, env, None, None, {'debug': True}) as mock_context:
mock_context.replace_tempdir_env()
mock_context.make_dirs(['bin', 'usr/bin'])
self.assertEquals(
(env['GOPATH'], shell),
golangconfig.setting_value('GOPATH', mock_context.view, mock_context.window)
)
self.assertEqual('', sys.stdout.getvalue())
def test_setting_value_gopath_not_string(self):
shell = '/bin/bash'
env = {
'GOPATH': 1
}
with GolangConfigMock(shell, env, None, None, {'debug': True}) as mock_context:
def do_test():
golangconfig.setting_value('GOPATH', mock_context.view, mock_context.window)
self.assertRaises(golangconfig.GoPathNotFoundError, do_test)
def test_subprocess_info_goroot_executable_not_inside(self):
shell = '/bin/bash'
env = {
'PATH': '{tempdir}bin:{tempdir}go/bin',
'GOPATH': '{tempdir}workspace',
'GOROOT': '{tempdir}go'
}
with GolangConfigMock(shell, env, None, None, {}) as mock_context:
mock_context.replace_tempdir_env()
mock_context.replace_tempdir_view_settings()
mock_context.replace_tempdir_window_settings()
mock_context.make_executable_files(['bin/go', 'go/bin/go'])
mock_context.make_dirs(['workspace'])
golangconfig.subprocess_info(
'go',
['GOPATH'],
optional_vars=['GOROOT'],
view=mock_context.view,
window=mock_context.window
)
self.assertTrue('which is not inside of the GOROOT' in sys.stdout.getvalue())
|
dev
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/dev/reloader.py
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import sys
if sys.version_info >= (3,):
from imp import reload
if 'golangconfig.dev.mocks' in sys.modules:
reload(sys.modules['golangconfig.dev.mocks'])
if 'golangconfig' in sys.modules:
reload(sys.modules['golangconfig'])
|
dev
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/dev/api_docs.py
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
"""
This script is used to extract markdown API docs from Python docstrings of code
that is part of the golangconfig library.
"""
# This file is Copyright 2015, Will Bond <will@wbond.net>, licensed to Google
# under the terms of the Google Inbound Service Agreement, signed August 15 2015
import re
import os
import ast
import _ast
import textwrap
import CommonMark
from collections import OrderedDict
cur_dir = os.path.dirname(__file__)
project_dir = os.path.abspath(os.path.join(cur_dir, '..'))
docs_dir = os.path.join(project_dir, 'docs')
module_name = 'golangconfig'
# Maps a markdown document to a Python source file to look in for
# class/method/function docstrings
MD_SOURCE_MAP = {
'docs/package_developer.md': ['all/golangconfig.py'],
}
# A search/replace dictionary to modify docstring contents before generating
# markdown from them
definition_replacements = {}
def _get_func_info(docstring, def_lineno, code_lines, prefix):
"""
Extracts the function signature and description of a Python function
:param docstring:
A unicode string of the docstring for the function
:param def_lineno:
An integer line number that function was defined on
:param code_lines:
A list of unicode string lines from the source file the function was
defined in
:param prefix:
A prefix to prepend to all output lines
:return:
A 2-element tuple:
- [0] A unicode string of the function signature with a docstring of
parameter info
- [1] A markdown snippet of the function description
"""
definition = code_lines[def_lineno - 1]
definition = definition.strip().rstrip(':')
description = ''
found_colon = False
params = ''
for line in docstring.splitlines():
if line and line[0] == ':':
found_colon = True
if not found_colon:
if description:
description += '\n'
description += line
else:
if params:
params += '\n'
params += line
description = description.strip()
description_md = ''
if description:
description_md = "%s%s" % (prefix, description.replace("\n", "\n" + prefix))
description_md = re.sub('\n>(\\s+)\n', '\n>\n', description_md)
params = params.strip()
if params:
definition += (':\n%s """\n%s ' % (prefix, prefix))
definition += params.replace('\n', '\n%s ' % prefix)
definition += ('\n%s """' % prefix)
definition = re.sub('\n>(\\s+)\n', '\n>\n', definition)
for search, replace in definition_replacements.items():
definition = definition.replace(search, replace)
return (definition, description_md)
def _find_sections(md_ast, sections, last, last_class, total_lines=None):
"""
Walks through a CommonMark AST to find section headers that delineate
content that should be updated by this script
:param md_ast:
The AST of the markdown document
:param sections:
A dict to store the start and end lines of a section. The key will be
a two-element tuple of the section type ("class", "function",
"method" or "attribute") and identifier. The values are a two-element
tuple of the start and end line number in the markdown document of the
section.
:param last:
A dict containing information about the last section header seen.
Includes the keys "type_name", "identifier", "start_line".
:param last_class:
A unicode string of the name of the last class found - used when
processing methods and attributes.
:param total_lines:
An integer of the total number of lines in the markdown document -
used to work around a bug in the API of the Python port of CommonMark
"""
for child in md_ast.children:
if child.t == 'ATXHeader':
if child.level in set([3, 5]) and len(child.inline_content) == 2:
first = child.inline_content[0]
second = child.inline_content[1]
if first.t != 'Code':
continue
if second.t != 'Str':
continue
type_name = second.c.strip()
identifier = first.c.strip().replace('()', '').lstrip('.')
if last:
sections[(last['type_name'], last['identifier'])] = (last['start_line'], child.start_line - 1)
last.clear()
if type_name == 'function':
if child.level != 3:
continue
if type_name == 'class':
if child.level != 3:
continue
last_class.append(identifier)
if type_name in set(['method', 'attribute']):
if child.level != 5:
continue
identifier = last_class[-1] + '.' + identifier
last.update({
'type_name': type_name,
'identifier': identifier,
'start_line': child.start_line,
})
elif child.t == 'BlockQuote':
find_sections(child, sections, last, last_class)
if last:
sections[(last['type_name'], last['identifier'])] = (last['start_line'], total_lines)
find_sections = _find_sections
def walk_ast(node, code_lines, sections, md_chunks):
"""
A callback used to walk the Python AST looking for classes, functions,
methods and attributes. Generates chunks of markdown markup to replace
the existing content.
:param node:
An _ast module node object
:param code_lines:
A list of unicode strings - the source lines of the Python file
:param sections:
A dict of markdown document sections that need to be updated. The key
will be a two-element tuple of the section type ("class", "function",
"method" or "attribute") and identifier. The values are a two-element
tuple of the start and end line number in the markdown document of the
section.
:param md_chunks:
A dict with keys from the sections param and the values being a unicode
string containing a chunk of markdown markup.
"""
if isinstance(node, _ast.FunctionDef):
key = ('function', node.name)
if key not in sections:
return
docstring = ast.get_docstring(node)
def_lineno = node.lineno + len(node.decorator_list)
definition, description_md = _get_func_info(docstring, def_lineno, code_lines, '> ')
md_chunk = textwrap.dedent("""
### `%s()` function
> ```python
> %s
> ```
>
%s
""").strip() % (
node.name,
definition,
description_md
) + "\n"
md_chunks[key] = md_chunk
elif isinstance(node, _ast.ClassDef):
if ('class', node.name) not in sections:
return
for subnode in node.body:
if isinstance(subnode, _ast.FunctionDef):
node_id = node.name + '.' + subnode.name
method_key = ('method', node_id)
is_method = method_key in sections
attribute_key = ('attribute', node_id)
is_attribute = attribute_key in sections
is_constructor = subnode.name == '__init__'
if not is_constructor and not is_attribute and not is_method:
continue
docstring = ast.get_docstring(subnode)
def_lineno = subnode.lineno + len(subnode.decorator_list)
if not docstring:
continue
if is_method or is_constructor:
definition, description_md = _get_func_info(docstring, def_lineno, code_lines, '> > ')
if is_constructor:
key = ('class', node.name)
class_docstring = ast.get_docstring(node)
class_description = textwrap.dedent(class_docstring).strip()
if class_description:
class_description_md = "> %s\n>" % (class_description.replace("\n", "\n> "))
else:
class_description_md = ''
md_chunk = textwrap.dedent("""
### `%s()` class
%s
> ##### constructor
>
> > ```python
> > %s
> > ```
> >
%s
""").strip() % (
node.name,
class_description_md,
definition,
description_md
)
md_chunk = md_chunk.replace('\n\n\n', '\n\n')
else:
key = method_key
md_chunk = textwrap.dedent("""
>
> ##### `.%s()` method
>
> > ```python
> > %s
> > ```
> >
%s
""").strip() % (
subnode.name,
definition,
description_md
)
if md_chunk[-5:] == '\n> >\n':
md_chunk = md_chunk[0:-5]
else:
key = attribute_key
description = textwrap.dedent(docstring).strip()
description_md = "> > %s" % (description.replace("\n", "\n> > "))
md_chunk = textwrap.dedent("""
>
> ##### `.%s` attribute
>
%s
""").strip() % (
subnode.name,
description_md
)
md_chunks[key] = md_chunk.rstrip()
elif isinstance(node, _ast.If):
for subast in node.body:
walk_ast(subast, code_lines, sections, md_chunks)
for subast in node.orelse:
walk_ast(subast, code_lines, sections, md_chunks)
def run():
"""
Looks through the docs/ dir and parses each markdown document, looking for
sections to update from Python docstrings. Looks for section headers in
the format:
- ### `ClassName()` class
- ##### `.method_name()` method
- ##### `.attribute_name` attribute
- ### `function_name()` function
The markdown content following these section headers up until the next
section header will be replaced by new markdown generated from the Python
docstrings of the associated source files.
By default maps docs/{name}.md to {modulename}/{name}.py. Allows for
custom mapping via the MD_SOURCE_MAP variable.
"""
print('Updating API docs...')
md_files = []
for root, _, filenames in os.walk(docs_dir):
for filename in filenames:
if not filename.endswith('.md'):
continue
md_files.append(os.path.join(root, filename))
parser = CommonMark.DocParser()
for md_file in md_files:
md_file_relative = md_file[len(project_dir) + 1:]
if md_file_relative in MD_SOURCE_MAP:
py_files = MD_SOURCE_MAP[md_file_relative]
py_paths = [os.path.join(project_dir, py_file) for py_file in py_files]
else:
py_files = [os.path.basename(md_file).replace('.md', '.py')]
py_paths = [os.path.join(project_dir, module_name, py_files[0])]
if not os.path.exists(py_paths[0]):
continue
with open(md_file, 'rb') as f:
markdown = f.read().decode('utf-8')
original_markdown = markdown
md_lines = list(markdown.splitlines())
md_ast = parser.parse(markdown)
last_class = []
last = {}
sections = OrderedDict()
find_sections(md_ast, sections, last, last_class, markdown.count("\n") + 1)
md_chunks = {}
for index, py_file in enumerate(py_files):
py_path = py_paths[index]
with open(os.path.join(py_path), 'rb') as f:
code = f.read().decode('utf-8')
module_ast = ast.parse(code, filename=py_file)
code_lines = list(code.splitlines())
for node in ast.iter_child_nodes(module_ast):
walk_ast(node, code_lines, sections, md_chunks)
added_lines = 0
def _replace_md(key, sections, md_chunk, md_lines, added_lines):
start, end = sections[key]
start -= 1
start += added_lines
end += added_lines
new_lines = md_chunk.split('\n')
added_lines += len(new_lines) - (end - start)
# Ensure a newline above each class header
if start > 0 and md_lines[start][0:4] == '### ' and md_lines[start - 1][0:1] == '>':
added_lines += 1
new_lines.insert(0, '')
md_lines[start:end] = new_lines
return added_lines
for key in sections:
if key not in md_chunks:
raise ValueError('No documentation found for %s' % key[1])
added_lines = _replace_md(key, sections, md_chunks[key], md_lines, added_lines)
markdown = '\n'.join(md_lines).strip() + '\n'
if original_markdown != markdown:
with open(md_file, 'wb') as f:
f.write(markdown.encode('utf-8'))
if __name__ == '__main__':
run()
|
dev
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/dev/unittest_data.py
|
# This file is Copyright 2015, Will Bond <will@wbond.net>, licensed to Google
# under the terms of the Google Inbound Service Agreement, signed August 15 2015
def data(provider_method, first_param_name_suffix=False):
"""
A method decorator for unittest.TestCase classes that configured a
static method to be used to provide multiple sets of test data to a single
test
:param provider_method:
The name of the staticmethod of the class to use as the data provider
:param first_param_name_suffix:
If the first parameter for each set should be appended to the method
name to generate the name of the test. Otherwise integers are used.
:return:
The decorated function
"""
def test_func_decorator(test_func):
test_func._provider_method = provider_method
test_func._provider_name_suffix = first_param_name_suffix
return test_func
return test_func_decorator
def data_class(cls):
"""
A class decorator that works with the @provider decorator to generate test
method from a data provider
"""
def generate_test_func(name, original_function, num, params):
if original_function._provider_name_suffix:
data_name = params[0]
params = params[1:]
else:
data_name = num
expanded_name = 'test_%s_%s' % (name, data_name)
# We used expanded variable names here since this line is present in
# backtraces that are generated from test failures.
generated_test_function = lambda self: original_function(self, *params)
setattr(cls, expanded_name, generated_test_function)
for name in dir(cls):
func = getattr(cls, name)
if hasattr(func, '_provider_method'):
num = 1
for params in getattr(cls, func._provider_method)():
generate_test_func(name, func, num, params)
num += 1
return cls
|
dev
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/dev/mocks.py
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import sys
import shutil
import locale
import stat
import golangconfig
if sys.version_info < (3,):
from cStringIO import StringIO
str_cls = unicode # noqa
else:
from io import StringIO
str_cls = str
class SublimeViewMock():
_settings = None
_context = None
def __init__(self, settings, context):
self._settings = settings
self._context = context
def settings(self):
if self.window():
# In Sublime Text, View objects inherit settings from the window/project
# unless they are explicitly set on the view, so we replicate that here
merged_golang_settings = {}
project_data = self.window().project_data()
if project_data:
merged_golang_settings.update(project_data.get('settings', {}).get('golang', {}).copy())
merged_golang_settings.update(self._settings)
elif self._settings:
merged_golang_settings = self._settings.copy()
else:
merged_golang_settings = {}
return {'golang': merged_golang_settings}
def window(self):
return self._context.window
class SublimeWindowMock():
_settings = None
_context = None
def __init__(self, settings, context):
self._settings = settings
self._context = context
def project_data(self):
if self._settings is None:
return None
return {'settings': {'golang': self._settings}}
def active_view(self):
if self._context.view:
return self._context.view
return SublimeViewMock({}, self._context)
class ShellenvMock():
_env_encoding = locale.getpreferredencoding() if sys.platform == 'win32' else 'utf-8'
_fs_encoding = 'mbcs' if sys.platform == 'win32' else 'utf-8'
_shell = None
_data = None
def __init__(self, shell, data):
self._shell = shell
self._data = data
def get_env(self, for_subprocess=False):
if not for_subprocess or sys.version_info >= (3,):
return (self._shell, self._data)
shell = self._shell.encode(self._fs_encoding)
env = {}
for name, value in self._data.items():
env[name.encode(self._env_encoding)] = value.encode(self._env_encoding)
return (shell, env)
def get_path(self):
return (self._shell, self._data.get('PATH', '').split(os.pathsep))
def env_encode(self, value):
if sys.version_info >= (3,):
return value
return value.encode(self._env_encoding)
def path_encode(self, value):
if sys.version_info >= (3,):
return value
return value.encode(self._fs_encoding)
def path_decode(self, value):
if sys.version_info >= (3,):
return value
return value.decode(self._fs_encoding)
class SublimeSettingsMock():
_values = None
def __init__(self, values):
self._values = values
def get(self, name, default=None):
return self._values.get(name, default)
class SublimeMock():
_settings = None
View = SublimeViewMock
Window = SublimeWindowMock
def __init__(self, settings):
self._settings = SublimeSettingsMock(settings)
def load_settings(self, basename):
return self._settings
class GolangConfigMock():
_shellenv = None
_sublime = None
_stdout = None
_tempdir = None
_shell = None
_env = None
_view_settings = None
_window_settings = None
_sublime_settings = None
def __init__(self, shell, env, view_settings, window_settings, sublime_settings):
self._shell = shell
self._env = env
self._view_settings = view_settings
self._window_settings = window_settings
self._sublime_settings = sublime_settings
self._tempdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'mock_fs')
if not os.path.exists(self._tempdir):
os.mkdir(self._tempdir)
def replace_tempdir_env(self):
for key in self._env:
self._env[key] = self._env[key].replace(
'{tempdir}',
self.tempdir + os.sep
)
def replace_tempdir_view_settings(self):
self._replace_tempdir_settings(self._view_settings)
def replace_tempdir_window_settings(self):
self._replace_tempdir_settings(self._window_settings)
def replace_tempdir_sublime_settings(self):
self._replace_tempdir_settings(self._sublime_settings)
def _replace_tempdir_settings(self, settings_dict):
if settings_dict:
for key in settings_dict:
if isinstance(settings_dict[key], str_cls):
settings_dict[key] = settings_dict[key].replace(
'{tempdir}',
self.tempdir + os.sep
)
for platform in ['osx', 'windows', 'linux']:
if platform not in settings_dict:
continue
for key in settings_dict[platform]:
if isinstance(settings_dict[platform][key], str_cls):
settings_dict[platform][key] = settings_dict[platform][key].replace(
'{tempdir}',
self.tempdir + os.sep
)
def make_executable_files(self, executable_temp_files):
self.make_files(executable_temp_files)
for temp_file in executable_temp_files:
temp_file_path = os.path.join(self.tempdir, temp_file)
st = os.stat(temp_file_path)
os.chmod(temp_file_path, st.st_mode | stat.S_IEXEC)
def make_files(self, temp_files):
for temp_file in temp_files:
temp_file_path = os.path.join(self.tempdir, temp_file)
temp_file_dir = os.path.dirname(temp_file_path)
if not os.path.exists(temp_file_dir):
os.makedirs(temp_file_dir)
with open(temp_file_path, 'a'):
pass
def make_dirs(self, temp_dirs):
for temp_dir in temp_dirs:
temp_dir_path = os.path.join(self.tempdir, temp_dir)
if not os.path.exists(temp_dir_path):
os.makedirs(temp_dir_path)
@property
def view(self):
if self._view_settings is None:
return None
return SublimeViewMock(self._view_settings, self)
@property
def window(self):
return SublimeWindowMock(self._window_settings, self)
@property
def tempdir(self):
return self._tempdir
def __enter__(self):
self._shellenv = golangconfig.shellenv
golangconfig.shellenv = ShellenvMock(self._shell, self._env)
self._sublime = golangconfig.sublime
golangconfig.sublime = SublimeMock(self._sublime_settings)
self._stdout = sys.stdout
sys.stdout = StringIO()
return self
def __exit__(self, exc_type, exc_value, traceback):
golangconfig.shellenv = self._shellenv
golangconfig.sublime = self._sublime
temp_stdout = sys.stdout
sys.stdout = self._stdout
print(temp_stdout.getvalue(), end='')
if self._tempdir and os.path.exists(self._tempdir):
shutil.rmtree(self._tempdir)
|
all
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/all/golangconfig.py
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import threading
import sys
import shellenv
import sublime
if sys.version_info < (3,):
str_cls = unicode # noqa
py2 = True
else:
str_cls = str
py2 = False
__version__ = '0.9.0'
__version_info__ = (0, 9, 0)
# The sublime.platform() function will not be available in ST3 upon initial
# import, so we determine the platform via the sys.platform value. We cache
# the value here to prevent extra IPC calls between plugin_host and
# sublime_text in ST3.
_platform = {
'win32': 'windows',
'darwin': 'osx'
}.get(sys.platform, 'linux')
# A special value object to detect if a setting was not found, versus a setting
# explicitly being set to null/None in a settings file. We can't use a Python
# object here because the value is serialized to json via the ST API. Byte
# strings end up turning into an array of integers in ST3.
_NO_VALUE = '\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F'
class EnvVarError(EnvironmentError):
"""
An error occurred finding one or more required environment variables
"""
missing = None
class GoRootNotFoundError(EnvironmentError):
"""
An error occurred finding the $GOROOT on disk
"""
directory = None
class GoPathNotFoundError(EnvironmentError):
"""
An error occurred finding one or more directories from $GOPATH on disk
"""
directories = None
class ExecutableError(EnvironmentError):
"""
An error occurred locating the executable requested
"""
name = None
dirs = None
def debug_enabled():
"""
Checks to see if the "debug" setting is true
:raises:
RuntimeError
When the function is called from any thread but the UI thread
:return:
A boolean - if debug is enabled
"""
# The Sublime Text API is not threadsafe in ST2, so we
# double check here to prevent crashes
if not isinstance(threading.current_thread(), threading._MainThread):
raise RuntimeError('golangconfig.setting_value() must be called from the main thread')
value = sublime.load_settings('golang.sublime-settings').get('debug')
return False if value == '0' else bool(value)
def subprocess_info(executable_name, required_vars, optional_vars=None, view=None, window=None):
"""
Gathers and formats information necessary to use subprocess.Popen() to
run one of the go executables, with details pulled from setting_value() and
executable_path().
Ensures that the executable path and env dictionary are properly encoded for
Sublime Text 2, where byte strings are necessary.
:param executable_name:
A unicode string of the executable to locate, e.g. "go" or "gofmt"
:param required_vars:
A list of unicode strings of the environment variables that are
required, e.g. "GOPATH". Obtains values from setting_value().
:param optional_vars:
A list of unicode strings of the environment variables that are
optional, but should be pulled from setting_value() if available - e.g.
"GOOS", "GOARCH". Obtains values from setting_value().
:param view:
A sublime.View object to use in finding project-specific settings. This
should be passed whenever available.
:param window:
A sublime.Window object to use in finding project-specific settings.
This should be passed whenever available.
:raises:
RuntimeError
When the function is called from any thread but the UI thread
TypeError
When any of the parameters are of the wrong type
golangconfig.ExecutableError
When the executable requested could not be located. The .name
attribute contains the name of the executable that could not be
located. The .dirs attribute contains a list of unicode strings
of the directories searched.
golangconfig.EnvVarError
When one or more required_vars are not available. The .missing
attribute will be a list of the names of missing environment
variables.
golangconfig.GoPathNotFoundError
When one or more directories specified by the GOPATH environment
variable could not be found on disk. The .directories attribute will
be a list of the directories that could not be found.
golangconfig.GoRootNotFoundError
When the directory specified by GOROOT environment variable could
not be found on disk. The .directory attribute will be the path to
the directory that could not be found.
golangconfig.EnvVarError
When one or more required_vars are not available. The .missing
attribute will be a list of the names of missing environment
variables.
:return:
A two-element tuple.
- [0] A unicode string (byte string for ST2) of the path to the executable
- [1] A dict to pass to the env parameter of subprocess.Popen()
"""
path, _ = executable_path(executable_name, view=view, window=window)
if path is None:
name = executable_name
if sys.platform == 'win32':
name += '.exe'
dirs = []
settings_path, _ = _get_most_specific_setting('PATH', view=view, window=window)
if settings_path and settings_path != _NO_VALUE:
dirs.extend(settings_path.split(os.pathsep))
_, shell_dirs = shellenv.get_path()
for shell_dir in shell_dirs:
if shell_dir not in dirs:
dirs.append(shell_dir)
exception = ExecutableError(
'The executable "%s" could not be located in any of the following locations: "%s"' %
(
name,
'", "'.join(dirs)
)
)
exception.name = name
exception.dirs = dirs
raise exception
path = shellenv.path_encode(path)
_, env = shellenv.get_env(for_subprocess=True)
var_groups = [required_vars]
if optional_vars:
var_groups.append(optional_vars)
missing_vars = []
for var_names in var_groups:
for var_name in var_names:
value, _ = setting_value(var_name, view=view, window=window)
var_key = var_name
if value is not None:
value = str_cls(value)
value = shellenv.env_encode(value)
var_key = shellenv.env_encode(var_key)
if value is None:
if var_key in env:
del env[var_key]
continue
env[var_key] = value
for required_var in required_vars:
var_key = shellenv.env_encode(required_var)
if var_key not in env:
missing_vars.append(required_var)
if missing_vars:
missing_vars = sorted(missing_vars, key=lambda s: s.lower())
exception = EnvVarError(
'The following environment variable%s currently unset: %s' %
(
's are' if len(missing_vars) > 1 else ' is',
', '.join(missing_vars)
)
)
exception.missing = missing_vars
raise exception
encoded_goroot = shellenv.env_encode('GOROOT')
if encoded_goroot in env:
unicode_sep = shellenv.path_decode(os.sep)
name = executable_name
if sys.platform == 'win32':
name += '.exe'
relative_executable_path = shellenv.path_encode('bin%s%s' % (unicode_sep, name))
goroot_executable_path = os.path.join(env[encoded_goroot], relative_executable_path)
if goroot_executable_path != path:
print(
'golangconfig: warning - binary %s was found at "%s", which is not inside of the GOROOT "%s"' %
(
executable_name,
path,
shellenv.path_decode(env[encoded_goroot])
)
)
return (path, env)
def setting_value(setting_name, view=None, window=None):
"""
Returns the user's setting for a specific variable, such as GOPATH or
GOROOT. Supports global and per-platform settings. Finds settings by
looking in:
1. If a project is open, the project settings
2. The global golang.sublime-settings file
3. The user's environment variables, as defined by their login shell
If the setting is a known name, e.g. GOPATH or GOROOT, the value will be
checked to ensure the path exists.
:param setting_name:
A unicode string of the setting to retrieve
:param view:
A sublime.View object to use in finding project-specific settings. This
should be passed whenever available.
:param window:
A sublime.Window object to use in finding project-specific settings.
This should be passed whenever available.
:raises:
RuntimeError
When the function is called from any thread but the UI thread
TypeError
When any of the parameters are of the wrong type
golangconfig.GoPathNotFoundError
When one or more directories specified by the GOPATH environment
variable could not be found on disk. The .directories attribute will
be a list of the directories that could not be found.
golangconfig.GoRootNotFoundError
When the directory specified by GOROOT environment variable could
not be found on disk. The .directory attribute will be the path to
the directory that could not be found.
:return:
A two-element tuple.
If no setting was found, the return value will be:
- [0] None
- [1] None
If a setting was found, the return value will be:
- [0] The setting value
- [1] The source of the setting, a unicode string:
- "project file (os-specific)"
- "golang.sublime-settings (os-specific)"
- "project file"
- "golang.sublime-settings"
- A unicode string of the path to the user's login shell
The second element of the tuple is intended to be used in the display
of debugging information to end users.
"""
_require_unicode('setting_name', setting_name)
_check_view_window(view, window)
setting, source = _get_most_specific_setting(setting_name, view, window)
if setting == _NO_VALUE:
setting = None
source = None
shell, env = shellenv.get_env()
if setting_name in env:
source = shell
setting = env[setting_name]
if setting_name not in set(['GOPATH', 'GOROOT']):
return (setting, source)
if setting is None and source is None:
return (setting, source)
# We add some extra processing here for known settings to improve the
# user experience, especially around debugging
_debug_unicode_string(setting_name, setting, source)
if not isinstance(setting, str_cls):
setting = str_cls(setting)
if setting_name == 'GOROOT':
if os.path.exists(setting):
return (setting, source)
has_multiple = False
if setting_name == 'GOPATH':
values = setting.split(os.pathsep)
has_multiple = len(values) > 1
missing = []
for value in values:
if not os.path.exists(value):
missing.append(value)
if not missing:
return (setting, source)
if setting_name == 'GOROOT':
message = 'The GOROOT environment variable value "%s" does not exist on the filesystem'
e = GoRootNotFoundError(message % setting)
e.directory = setting
raise e
if not has_multiple:
suffix = 'value "%s" does not exist on the filesystem' % missing[0]
elif len(missing) == 1:
suffix = 'contains the directory "%s" that does not exist on the filesystem' % missing[0]
else:
paths = ', '.join('"' + path + '"' for path in missing)
suffix = 'contains %s directories that do not exist on the filesystem: %s' % (len(missing), paths)
message = 'The GOPATH environment variable ' + suffix
e = GoPathNotFoundError(message)
e.directories = missing
raise e
def executable_path(executable_name, view=None, window=None):
"""
Uses the user's Sublime Text settings and then PATH environment variable
as set by their login shell to find a go executable
:param name:
The name of the binary to find - a unicode string of "go", "gofmt" or
"godoc"
:param view:
A sublime.View object to use in finding project-specific settings. This
should be passed whenever available.
:param window:
A sublime.Window object to use in finding project-specific settings.
This should be passed whenever available.
:raises:
RuntimeError
When the function is called from any thread but the UI thread
TypeError
When any of the parameters are of the wrong type
:return:
A 2-element tuple.
If the executable was not found, the return value will be:
- [0] None
- [1] None
If the exeutable was found, the return value will be:
- [0] A unicode string of the full path to the executable
- [1] A unicode string of the source of the PATH value
- "project file (os-specific)"
- "golang.sublime-settings (os-specific)"
- "project file"
- "golang.sublime-settings"
- A unicode string of the path to the user's login shell
The second element of the tuple is intended to be used in the display
of debugging information to end users.
"""
_require_unicode('executable_name', executable_name)
_check_view_window(view, window)
executable_suffix = '.exe' if sys.platform == 'win32' else ''
suffixed_name = executable_name + executable_suffix
setting, source = _get_most_specific_setting('PATH', view, window)
if setting is not _NO_VALUE:
is_str = isinstance(setting, str_cls)
if not is_str:
if debug_enabled():
_debug_unicode_string('PATH', setting, source)
else:
for dir_ in setting.split(os.pathsep):
possible_executable_path = os.path.join(dir_, suffixed_name)
if _check_executable(possible_executable_path, source, setting):
return (possible_executable_path, source)
if debug_enabled():
print(
'golangconfig: binary %s not found in PATH from %s - "%s"' %
(
executable_name,
source,
setting
)
)
shell, path_dirs = shellenv.get_path()
for dir_ in path_dirs:
possible_executable_path = os.path.join(dir_, suffixed_name)
if _check_executable(possible_executable_path, shell, os.pathsep.join(path_dirs)):
return (possible_executable_path, shell)
if debug_enabled():
print(
'golangconfig: binary %s not found in PATH from %s - "%s"' %
(
executable_name,
shell,
os.pathsep.join(path_dirs)
)
)
return (None, None)
def _get_most_specific_setting(name, view, window):
"""
Looks up a setting in the following order:
1. View settings, looking inside of the "osx", "windows" or "linux" key
based on the OS that Sublime Text is running on. These settings are from
a project file.
2. Window settings (ST3 only), looking inside of the "osx", "windows" or
"linux" key based on the OS that Sublime Text is running on. These
settings are from a project file.
3. golang.sublime-settings, looking inside of the "osx", "windows" or
"linux" key based on the OS that Sublime Text is running on.
4. The view settings. These settings are from a project file.
5. The window settings (ST3 only). These settings are from a project file.
6. golang.sublime-settings
:param name:
A unicode string of the setting to fetch
:param view:
A sublime.View object to use in finding project-specific settings. This
should be passed whenever available.
:param window:
A sublime.Window object to use in finding project-specific settings.
This should be passed whenever available.
:return:
A two-element tuple.
If no setting was found, the return value will be:
- [0] golangconfig._NO_VALUE
- [1] None
If a setting was found, the return value will be:
- [0] The setting value
- [1] A unicode string of the source:
- "project file (os-specific)"
- "golang.sublime-settings (os-specific)"
- "project file"
- "golang.sublime-settings"
"""
# The Sublime Text API is not threadsafe in ST2, so we
# double check here to prevent crashes
if not isinstance(threading.current_thread(), threading._MainThread):
raise RuntimeError('golangconfig.setting_value() must be called from the main thread')
if view is not None and not isinstance(view, sublime.View):
raise TypeError('view must be an instance of sublime.View, not %s' % _type_name(view))
if window is not None and not isinstance(window, sublime.Window):
raise TypeError('window must be an instance of sublime.Window, not %s' % _type_name(window))
st_settings = sublime.load_settings('golang.sublime-settings')
view_settings = view.settings().get('golang', {}) if view else {}
if view and not window:
window = view.window()
window_settings = {}
if window:
if sys.version_info >= (3,) and window.project_data():
window_settings = window.project_data().get('settings', {}).get('golang', {})
elif not view and window.active_view():
window_settings = window.active_view().settings().get('golang', {})
settings_objects = [
(view_settings, 'project file'),
(window_settings, 'project file'),
(st_settings, 'golang.sublime-settings'),
]
for settings_object, source in settings_objects:
platform_settings = settings_object.get(_platform, _NO_VALUE)
if platform_settings == _NO_VALUE:
continue
if not isinstance(platform_settings, dict):
continue
if platform_settings.get(name, _NO_VALUE) != _NO_VALUE:
return (platform_settings.get(name), source + ' (os-specific)')
for settings_object, source in settings_objects:
result = settings_object.get(name, _NO_VALUE)
if result != _NO_VALUE:
return (settings_object.get(name), source)
return (_NO_VALUE, None)
def _require_unicode(name, value):
"""
Requires that a parameter be a unicode string
:param name:
A unicode string of the parameter name
:param value:
The parameter value
:raises:
TypeError
When the value is not a unicode string
"""
if not isinstance(value, str_cls):
raise TypeError('%s must be a unicode string, not %s' % (name, _type_name(value)))
def _check_view_window(view, window):
"""
Ensures that the view and window parameters to a function are suitable
objects for our purposes. There is not a strict check for type to allow for
mocking during testing.
:param view:
The view parameter to check
:param window:
The window parameter to check
:raises:
TypeError
When the view or window parameters are not of the appropriate type
"""
if view is not None:
if not isinstance(view, sublime.View):
raise TypeError('view must be an instance of sublime.View, not %s' % _type_name(view))
if window is not None:
if not isinstance(window, sublime.Window) and sys.version_info >= (3,):
raise TypeError('window must be an instance of sublime.Window, not %s' % _type_name(window))
def _type_name(value):
"""
:param value:
The value to get the type name of
:return:
A unicode string of the name of the value's type
"""
value_cls = value.__class__
value_module = value_cls.__module__
if value_module in set(['builtins', '__builtin__']):
return value_cls.__name__
return '%s.%s' % (value_module, value_cls.__name__)
def _debug_unicode_string(name, value, source):
"""
Displays a debug message to the console if the value is not a unicode string
:param name:
A unicode string of the name of the setting
:param value:
The setting value to check
:param source:
A unicode string of the source of the setting
"""
if value is not None and not isinstance(value, str_cls):
print(
'golangconfig: the value for %s from %s is not a string, but instead a %s' %
(
name,
source,
_type_name(value)
)
)
def _check_executable(possible_executable_path, source, setting):
"""
Checks to see if a path to an executable exists and that it is, in fact,
executable. Will display debug info if the path exists, but is not
executable.
:param possible_executable_path:
A unicode string of the full file path to the executable
:param source:
A unicode string of the source of the setting
:param setting:
A unicode string of the PATH value that the executable was found in
:return:
A boolean - if the possible_executable_path is a file that is executable
"""
if os.path.exists(possible_executable_path):
is_executable = os.path.isfile(possible_executable_path) and os.access(possible_executable_path, os.X_OK)
if is_executable:
return True
if debug_enabled():
executable_name = os.path.basename(possible_executable_path)
print(
'golangconfig: binary %s found in PATH from %s - "%s" - is not executable' %
(
executable_name,
source,
setting
)
)
return False
|
docs
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/docs/design.md
|
# golangconfig Design
The `golangconfig` Sublime Text dependency was designed based on the following
ideas:
- Settings should be supported coming from the following sources, in order:
- Sublime Text project files under the `golang` key
- Any `golang.sublime-settings` files
- The user's shell environment, as defined by invoking their login shell
- The project and global Sublime Text settings will also allow for placing
settings in a platform-specific sub-dictionary to allow users to easily
work across different operating systems. The keys for these are used by
other ST packages to allow for platform-specific functionality:
- "osx"
- "windows"
- "linux"
- Platform-specific settings are always higher priority than
non-platform-specific, no matter what source they are pulled from
- Setting names that are core to Go configuration preserve the uppercase style
of environment variables. Thus the settings are named `GOPATH`, `GOROOT`,
`PATH`, etc.
- When returning results, the value requested is returned along with a
user-friendly source description that can be used when displaying
configuration details to the user
- The API eschews duck-typing in an attempt to prevent various edge-case bugs.
This is largely due to the weak-typing issues of strings in Python 2 where
byte strings and unicode strings are often mixed, only to cause exceptions
at runtime on user machines where errors are harder to capture.
|
docs
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/docs/readme.md
|
# golangconfig Documentation
The documentation for the package is split into two audiences:
- [User documentation](user.md) describing how to configure Sublime Text
to properly work with your Go environment
- [Package developer documentation](package_developer.md) containing API
documentation and instructions on how to require `golangconfig` for your
package
Other documentation:
- [Design](design.md)
- [Development](development.md)
|
docs
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/docs/user.md
|
# golangconfig User Documentation
The `golangconfig` package is a reusable library that Go-related Sublime Text
packages can use to obtain information about your Go environment.
This documentation details how you can set OS-specific, per-project and global
Sublime Text configuration for all packages that utilize `golangconfig`.
- [Environment Autodetection](#environment-autodetection)
- [Overriding the Environment](#overriding-the-environment)
- [Global Sublime Text Settings](#global-sublime-text-settings)
- [OS-Specific Settings](#os-specific-settings)
- [Project-Specific Settings](#project-specific-settings)
## Environment Autodetection
By default `golangconfig` tries to detect all of your Go configuration by
invoking your login shell. It will pull in your `PATH`, `GOPATH`, and any other
environment variables you have set.
## Overriding the Environment
Generally, autodetecting the shell environment is sufficient for most users
with a homogenous Go environment. If your Go configuration is more complex,
Sublime Text settings may be used to handle it, via:
- [Global Sublime Text Settings](#global-sublime-text-settings)
- [OS-Specific Settings](#os-specific-settings)
- [Project-Specific Settings](#project-specific-settings)
Settings are loading using the following precedence, from most-to-least
specific:
- OS-specific project settings
- OS-specific global Sublime Text settings
- Project settings
- Global Sublime Text settings
- Shell environment
### Global Sublime Text Settings
To set variables for use in Sublime Text windows, you will want to edit your
`golang.sublime-settings` file. This can be accessed via the menu:
1. Preferences
2. Package Settings
3. Golang Config
3. Settings - User
Settings are placed in a json structure. Common settings include:
- `PATH` - a list of directories to search for executables within. On Windows
these are separated by `;`. OS X and Linux use `:` as a directory separator.
- `GOPATH` - a string of the path to the root of your Go environment
Other Go settings may, or may not, be supported by the packages using these
settings. Examples include: `GOOS`, `GOARCH`, `GOROOT`.
```json
{
"PATH": "/Users/jsmith/go/bin",
"GOPATH": "/Users/jsmith/go"
}
```
### OS-Specific Settings
For users that are working on different operating systems, it may be necessary
to segement settings per OS. All settings may be nested under a key of one of
the following strings:
- "osx"
- "windows"
- "linux"
```json
{
"osx": {
"PATH": "/Users/jsmith/go/bin",
"GOPATH": "/Users/jsmith/go"
},
"windows": {
"PATH": "C:\\Users\\jsmith\\go\\bin",
"GOPATH": "C:\\Users\\jsmith\\go"
},
"linux": {
"PATH": "/home/jsmith/go/bin",
"GOPATH": "/home/jsmith/go"
},
}
```
### Project-Specific Settings
When working on Go projects that use different environments, it may be
necessary to define settings in a
[Sublime Text project](http://docs.sublimetext.info/en/latest/file_management/file_management.html#projects)
file. The *Project* menu in Sublime Text provides the interface to create and
edit project files.
Within projects, all Go settings are placed under the `"settings"` key and then
further under a subkey named `"golang"`.
```json
{
"folders": {
"/Users/jsmith/projects/myproj"
},
"settings": {
"golang": {
"PATH": "/Users/jsmith/projects/myproj/env/bin",
"GOPATH": "/Users/jsmith/projects/myproj/env"
}
}
}
```
Project-specific settings may also utilize the OS-specific settings feature.
```json
{
"folders": {
"/Users/jsmith/projects/myproj"
},
"settings": {
"golang": {
"osx": {
"PATH": "/Users/jsmith/projects/myproj/env/bin",
"GOPATH": "/Users/jsmith/projects/myproj/env"
},
"linux": {
"PATH": "/home/jsmith/projects/myproj/env/bin",
"GOPATH": "/home/jsmith/projects/myproj/env"
}
}
}
}
```
|
docs
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/docs/changelog.md
|
# golangconfig Changelog
## 0.9.0
- `subprocess_info()` and `setting_value()` will now raise
`GoRootNotFoundError()` when the `GOROOT` environment variable points to a
directory that could not be found on disk, and `GoPathNotFoundError()` when
one or more of the entries in the `GOPATH` environment variable could not be
found on disk.
## 0.8.1
- Added support for GOPATH with multiple directories
- Fix an error when no project was open when using Sublime Text 3
## 0.8.0
- Initial release
|
docs
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/docs/package_developer.md
|
# golangconfig Package Developer Documentation
`golangconfig` is an API for package developers to obtain configuration
information about a user's Go environment. It is distributed as a Package
Control dependency, and thus automatically installed when a package requiring
it is installed by an end-user.
- [Overview](#overview)
- [Example](#example)
- [API Documentation](#api-documentation)
## Overview
### subprocess_info()
`subprocess_info()` is the primary function that will be used in packages.
It accepts five parameters. The first two are positional:
1. the name of the requested executable, e.g. "go", "gofmt", "godoc"
2. a list of required environment variables
The three remaining parameters are keyword arguments:
- optional_vars: a list of vars that will be pulled from project or Sublime
Text settings and used as environment variables
- view: a `sublime.View` object, if available
- window: a `sublime.Window` object, if available
The function returns a two-element tuple containing the path to the requested
executable and a `dict` to pass via the `env=` arg of `subprocess.Popen()`.
The `sublime.View` and/or `sublime.Window` objects are used to obtain
project-specific settings. These objects are available via attributes of the
`sublime_plugin.WindowCommand` and `sublime_plugin.TextCommand` classes.
The `golangconfig` package interacts with Sublime Text's settings API, which
means that all calls must occur within the UI thread for compatibility with
Sublime Text 2.
### setting_value()
The function `setting_value()` is intended for use when fetching environment
variables for non-subprocess usage, or for getting settings that are not
environment variables. Obtaining the value of an individual environment variable
may be useful when printing debug information, or using the value in an
interactive manner with the user.
The function accepts three parameters. The first is position:
1. a unicode string of the name of the setting or environment variable
The two other parameters are keyword arguments:
- view: a `sublime.View` object, if available
- window: a `sublime.Window` object, if available
The function returns a two-element tuple containing the value of the setting
requested, and a unicode string describing the source of the setting.
If no value was found for the setting, the tuple `(None, None)` will be
returned.
If a value is found for the setting, the second element of the tuple will
contain one of the following unicode strings:
- "project file"
- "project file (os-specific)"
- "golang.sublime-settings"
- "golang.sublime-settings (os-specific)"
- a unicode string of the path to the user's login shell
This value is intended for display to the user for help in debugging.
### Errors
If the executable can not be found, a `golangconfig.ExecutableError()` will be
raised. It has two attributes: `.name` which is the name of the executable that
could not be found, and `.dirs` which is a list of the dirs searched by first
looking at the `PATH` from the Sublime Text settings, and then looking at the
shell `PATH` value.
If one of the required environment variables is not set, an
`golangconfig.EnvVarError()` will be raised. It has one attribute: `.missing`
which is a list of all required environment variables that could not be
found in the Sublime Text settings, or the shell environment.
If the `GOROOT` environment variable points to a directory that does not exist
on disk, the `golangconfig.GoRootNotFoundError()` will be raised. It has one
attribute `.directory` that contains a unicode string of the `GOROOT` value.
If one or more of the directories specified in the `GOPATH` environment variable
can not be found on disk, the `golangconfig.GoPathNotFoundError()` will be
raised. It has one attribute `.directories`, which is a list on unicode strings
of the directories that could not be found.
### Requiring the Dependency
When developing a package to utilize `golangconfig`, Package Control needs to be
told to ensure that `golangconfig` is installed. To accomplish this, a file
named `dependencies.json` needs to be placed in the root of the package. The
file should contain the following specification:
```json
{
"*": {
"*": [
"shellenv",
"golangconfig"
]
}
}
```
This specification indicates that for all operating systems (the outer `*`) and
all versions of Sublime Text (the nested `*`), the dependencies named `shellenv`
and `golangconfig` are required.
## Example
The following snippet of Python show basic usage of `golangconfig` from within
command classes derived from `sublime_plugin.WindowCommand` and
`sublime_plugin.TextCommand`.
```python
# coding: utf-8
from __future__ import unicode_literals
import sys
import sublime
import sublime_plugin
import golangconfig
if sys.version_info < (3,):
str_cls = unicode
else:
str_cls = str
class MyWindowCommand(sublime_plugin.WindowCommand):
def run(self):
try:
go_executable_path, env_dict = golangconfig.subprocess_info(
'go',
['GOPATH'],
[
'GOROOT',
'GOROOT_FINAL',
'GOBIN',
'GOOS',
'GOARCH',
'GORACE',
'GOARM',
'GO386',
'GOHOSTOS',
'GOHOSTARCH',
],
window=self.window
)
# Launch thread to execute subprocess.Popen() ...
except (golangconfig.ExecutableError) as e:
error_message = '''
My Package
The %s executable could not be found. Please ensure it is
installed and available via your PATH.
Would you like to view documentation for setting the PATH?
'''
prompt = error_message % e.name
if sublime.ok_cancel_dialog(prompt, 'Open Documentation'):
self.window.run_command(
'open_url',
{'url': 'http://example.com/documentation'}
)
except (golangconfig.EnvVarError) as e:
error_message = '''
My Package
The setting%s %s could not be found in your Sublime Text
settings or your shell environment.
Would you like to view the configuration documentation?
'''
plural = 's' if len(e.missing) > 1 else ''
setting_names = ', '.join(e.missing)
prompt = error_message % (plural, setting_names)
if sublime.ok_cancel_dialog(prompt, 'Open Documentation'):
self.window.run_command(
'open_url',
{'url': 'http://example.com/documentation'}
)
except (golangconfig.GoRootNotFoundError, golangconfig.GoPathNotFoundError) as e:
error_message = '''
My Package
%s.
Would you like to view the configuration documentation?
'''
prompt = error_message % str_cls(e)
if sublime.ok_cancel_dialog(prompt, 'Open Documentation'):
self.window.run_command(
'open_url',
{'url': 'http://example.com/documentation'}
)
class MyTextCommand(sublime_plugin.TextCommand):
def run(self):
# This example omits exception handling for brevity
gofmt_executable_path, env = golangconfig.subprocess_info(
'gofmt',
['GOPATH'],
# GOOS, GOARCH, GO386 and GOARM are omitted from optional_vars in
# this example with the intent they would be provided through user
# interaction.
[
'GOROOT',
'GOROOT_FINAL',
'GOBIN',
'GORACE',
'GOHOSTOS',
'GOHOSTARCH',
],
view=self.view
)
goos_setting = golangconfig.setting_value('GOOS', view=self.view)
goarch_setting = golangconfig.setting_value('GOARCH', view=self.view)
# Use the sublime API to show the user OS and ARCH options, with their
# values from the settings selected by default
```
Since the `golangconfig` functions must be called in the UI thread, commands
will normally look up any necessary information before firing off a thread to
perform a task in the background.
## API Documentation
The public API consists of the following functions:
- [`subprocess_info()`](#subprocess_info-function)
- [`setting_value()`](#setting_value-function)
- [`executable_path()`](#executable_path-function)
- [`debug_enabled()`](#debug_enabled-function)
### `subprocess_info()` function
> ```python
> def subprocess_info(executable_name, required_vars, optional_vars=None, view=None, window=None):
> """
> :param executable_name:
> A unicode string of the executable to locate, e.g. "go" or "gofmt"
>
> :param required_vars:
> A list of unicode strings of the environment variables that are
> required, e.g. "GOPATH". Obtains values from setting_value().
>
> :param optional_vars:
> A list of unicode strings of the environment variables that are
> optional, but should be pulled from setting_value() if available - e.g.
> "GOOS", "GOARCH". Obtains values from setting_value().
>
> :param view:
> A sublime.View object to use in finding project-specific settings. This
> should be passed whenever available.
>
> :param window:
> A sublime.Window object to use in finding project-specific settings.
> This will only work for Sublime Text 3, and should only be passed if
> no sublime.View object is available to pass via the view parameter.
>
> :raises:
> RuntimeError
> When the function is called from any thread but the UI thread
> TypeError
> When any of the parameters are of the wrong type
> golangconfig.ExecutableError
> When the executable requested could not be located. The .name
> attribute contains the name of the executable that could not be
> located. The .dirs attribute contains a list of unicode strings
> of the directories searched.
> golangconfig.EnvVarError
> When one or more required_vars are not available. The .missing
> attribute will be a list of the names of missing environment
> variables.
>
> :return:
> A two-element tuple.
>
> - [0] A unicode string (byte string for ST2) of the path to the executable
> - [1] A dict to pass to the env parameter of subprocess.Popen()
> """
> ```
>
> Gathers and formats information necessary to use subprocess.Popen() to
> run one of the go executables, with details pulled from setting_value() and
> executable_path().
>
> Ensures that the executable path and env dictionary are properly encoded for
> Sublime Text 2, where byte strings are necessary.
### `setting_value()` function
> ```python
> def setting_value(setting_name, view=None, window=None):
> """
> :param setting_name:
> A unicode string of the setting to retrieve
>
> :param view:
> A sublime.View object to use in finding project-specific settings. This
> should be passed whenever available.
>
> :param window:
> A sublime.Window object to use in finding project-specific settings.
> This will only work for Sublime Text 3, and should only be passed if
> no sublime.View object is available to pass via the view parameter.
>
> :raises:
> RuntimeError
> When the function is called from any thread but the UI thread
> TypeError
> When any of the parameters are of the wrong type
>
> :return:
> A two-element tuple.
>
> If no setting was found, the return value will be:
>
> - [0] None
> - [1] None
>
> If a setting was found, the return value will be:
>
> - [0] The setting value
> - [1] The source of the setting, a unicode string:
> - "project file (os-specific)"
> - "golang.sublime-settings (os-specific)"
> - "project file"
> - "golang.sublime-settings"
> - A unicode string of the path to the user's login shell
>
> The second element of the tuple is intended to be used in the display
> of debugging information to end users.
> """
> ```
>
> Returns the user's setting for a specific variable, such as GOPATH or
> GOROOT. Supports global and per-platform settings. Finds settings by
> looking in:
>
> 1. If a project is open, the project settings
> 2. The global golang.sublime-settings file
> 3. The user's environment variables, as defined by their login shell
>
> If the setting is a known name, e.g. GOPATH or GOROOT, the value will be
> checked to ensure the path exists.
### `executable_path()` function
> ```python
> def executable_path(executable_name, view=None, window=None):
> """
> :param name:
> The name of the binary to find - a unicode string of "go", "gofmt" or
> "godoc"
>
> :param view:
> A sublime.View object to use in finding project-specific settings. This
> should be passed whenever available.
>
> :param window:
> A sublime.Window object to use in finding project-specific settings.
> This will only work for Sublime Text 3, and should only be passed if
> no sublime.View object is available to pass via the view parameter.
>
> :raises:
> RuntimeError
> When the function is called from any thread but the UI thread
> TypeError
> When any of the parameters are of the wrong type
>
> :return:
> A 2-element tuple.
>
> If the executable was not found, the return value will be:
>
> - [0] None
> - [1] None
>
> If the exeutable was found, the return value will be:
>
> - [0] A unicode string of the full path to the executable
> - [1] A unicode string of the source of the PATH value
> - "project file (os-specific)"
> - "golang.sublime-settings (os-specific)"
> - "project file"
> - "golang.sublime-settings"
> - A unicode string of the path to the user's login shell
>
> The second element of the tuple is intended to be used in the display
> of debugging information to end users.
> """
> ```
>
> Uses the user's Sublime Text settings and then PATH environment variable
> as set by their login shell to find a go executable
### `debug_enabled()` function
> ```python
> def debug_enabled():
> """
> :raises:
> RuntimeError
> When the function is called from any thread but the UI thread
>
> :return:
> A boolean - if debug is enabled
> """
> ```
>
> Checks to see if the "debug" setting is true
|
docs
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/sublime-config/docs/development.md
|
# golangconfig Development
## Setup
- Install [Package Coverage](https://packagecontrol.io/packages/Package%20Coverage)
to run tests
- Install the [shellenv](https://github.com/codexns/shellenv) dependency by
executing `git clone --branch 1.4.1 https://github.com/codexns/shellenv`
inside of your `Packages/` folder
- Install this dependency by
executing `git clone https://go.googlesource.com/sublime-config golangconfig`
inside of your `Packages/` folder
- Use the Package Control command "Install Local Dependency" to install
`shellenv` and then `golangconfig` so they are available to the Python plugin
environment
## General Notes
- All code must pass the checks of the Sublime Text package
[Python Flake8 Lint](https://packagecontrol.io/packages/Python%20Flake8%20Lint).
The `python_interpreter` setting should be set to `internal`.
- Tests and coverage measurement must be run in the UI thread since the package
utilizes the `sublime` API, which is not thread safe on ST2
- Sublime Text 2 and 3 must be supported, on Windows, OS X and Linux
- In public-facing functions, types should be strictly checked to help reduce
edge-case bugs
- All functions must include a full docstring with parameter and return types
and a list of exceptions raised
- All code should use a consistent Python header
```python
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
```
- Markdown-based API documentation can be automatically copied from the source
code by executing `dev/api_docs.py` with a Python installation containing
the `CommonMark` package
```bash
pip install CommonMark
python dev/api_docs.py
```
|
protobuf
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/CONTRIBUTING.md
|
# Contributing to Go Protocol Buffers
Go protocol buffers is an open source project and accepts contributions.
This project is the first major version of Go protobufs,
while the next major revision of this project is located at
[protocolbuffers/protobuf-go](https://github.com/protocolbuffers/protobuf-go).
Most new development effort is focused on the latter project,
and changes to this project is primarily reserved for bug fixes.
## Contributor License Agreement
Contributions to this project must be accompanied by a Contributor License
Agreement. You (or your employer) retain the copyright to your contribution,
this simply gives us permission to use and redistribute your contributions as
part of the project. Head over to <https://cla.developers.google.com/> to see
your current agreements on file or to sign a new one.
You generally only need to submit a CLA once, so if you've already submitted one
(even if it was for a different project), you probably don't need to do it
again.
## Code reviews
All submissions, including submissions by project members, require review. We
use GitHub pull requests for this purpose. Consult
[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
information on using pull requests.
|
protobuf
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/AUTHORS
|
# This source code refers to The Go Authors for copyright purposes.
# The master list of authors is in the main Go distribution,
# visible at http://tip.golang.org/AUTHORS.
|
protobuf
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/go.mod
|
// Deprecated: Use the "google.golang.org/protobuf" module instead.
module github.com/golang/protobuf
go 1.17
require (
github.com/google/go-cmp v0.5.5
google.golang.org/protobuf v1.33.0
)
|
protobuf
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/README.md
|
# Go support for Protocol Buffers
[](https://pkg.go.dev/mod/github.com/golang/protobuf)
[](https://travis-ci.org/golang/protobuf)
This module
([`github.com/golang/protobuf`](https://pkg.go.dev/mod/github.com/golang/protobuf))
contains Go bindings for protocol buffers.
It has been superseded by the
[`google.golang.org/protobuf`](https://pkg.go.dev/mod/google.golang.org/protobuf)
module, which contains an updated and simplified API,
support for protobuf reflection, and many other improvements.
We recommend that new code use the `google.golang.org/protobuf` module.
Versions v1.4 and later of `github.com/golang/protobuf` are implemented
in terms of `google.golang.org/protobuf`.
Programs which use both modules must use at least version v1.4 of this one.
See the
[developer guide for protocol buffers in Go](https://developers.google.com/protocol-buffers/docs/gotutorial)
for a general guide for how to get started using protobufs in Go.
See
[release note documentation](https://github.com/golang/protobuf/releases)
for more information about individual releases of this project.
See
[documentation for the next major revision](https://pkg.go.dev/mod/google.golang.org/protobuf)
for more information about the purpose, usage, and history of this project.
## Package index
Summary of the packages provided by this module:
* [`proto`](https://pkg.go.dev/github.com/golang/protobuf/proto): Package
`proto` provides functions operating on protobuf messages such as cloning,
merging, and checking equality, as well as binary serialization and text
serialization.
* [`jsonpb`](https://pkg.go.dev/github.com/golang/protobuf/jsonpb): Package
`jsonpb` serializes protobuf messages as JSON.
* [`ptypes`](https://pkg.go.dev/github.com/golang/protobuf/ptypes): Package
`ptypes` provides helper functionality for protobuf well-known types.
* [`ptypes/any`](https://pkg.go.dev/github.com/golang/protobuf/ptypes/any):
Package `any` is the generated package for `google/protobuf/any.proto`.
* [`ptypes/empty`](https://pkg.go.dev/github.com/golang/protobuf/ptypes/empty):
Package `empty` is the generated package for `google/protobuf/empty.proto`.
* [`ptypes/timestamp`](https://pkg.go.dev/github.com/golang/protobuf/ptypes/timestamp):
Package `timestamp` is the generated package for
`google/protobuf/timestamp.proto`.
* [`ptypes/duration`](https://pkg.go.dev/github.com/golang/protobuf/ptypes/duration):
Package `duration` is the generated package for
`google/protobuf/duration.proto`.
* [`ptypes/wrappers`](https://pkg.go.dev/github.com/golang/protobuf/ptypes/wrappers):
Package `wrappers` is the generated package for
`google/protobuf/wrappers.proto`.
* [`ptypes/struct`](https://pkg.go.dev/github.com/golang/protobuf/ptypes/struct):
Package `structpb` is the generated package for
`google/protobuf/struct.proto`.
* [`protoc-gen-go/descriptor`](https://pkg.go.dev/github.com/golang/protobuf/protoc-gen-go/descriptor):
Package `descriptor` is the generated package for
`google/protobuf/descriptor.proto`.
* [`protoc-gen-go/plugin`](https://pkg.go.dev/github.com/golang/protobuf/protoc-gen-go/plugin):
Package `plugin` is the generated package for
`google/protobuf/compiler/plugin.proto`.
* [`protoc-gen-go`](https://pkg.go.dev/github.com/golang/protobuf/protoc-gen-go):
The `protoc-gen-go` binary is a protoc plugin to generate a Go protocol
buffer package.
## Reporting issues
The issue tracker for this project
[is located here](https://github.com/golang/protobuf/issues).
Please report any issues with a sufficient description of the bug or feature
request. Bug reports should ideally be accompanied by a minimal reproduction of
the issue. Irreproducible bugs are difficult to diagnose and fix (and likely to
be closed after some period of time). Bug reports must specify the version of
the
[Go protocol buffer module](https://github.com/protocolbuffers/protobuf-go/releases)
and also the version of the
[protocol buffer toolchain](https://github.com/protocolbuffers/protobuf/releases)
being used.
## Contributing
This project is open-source and accepts contributions. See the
[contribution guide](https://github.com/golang/protobuf/blob/master/CONTRIBUTING.md)
for more information.
## Compatibility
This module and the generated code are expected to be stable over time. However,
we reserve the right to make breaking changes without notice for the following
reasons:
* **Security:** A security issue in the specification or implementation may
come to light whose resolution requires breaking compatibility. We reserve
the right to address such issues.
* **Unspecified behavior:** There are some aspects of the protocol buffer
specification that are undefined. Programs that depend on unspecified
behavior may break in future releases.
* **Specification changes:** It may become necessary to address an
inconsistency, incompleteness, or change in the protocol buffer
specification, which may affect the behavior of existing programs. We
reserve the right to address such changes.
* **Bugs:** If a package has a bug that violates correctness, a program
depending on the buggy behavior may break if the bug is fixed. We reserve
the right to fix such bugs.
* **Generated additions**: We reserve the right to add new declarations to
generated Go packages of `.proto` files. This includes declared constants,
variables, functions, types, fields in structs, and methods on types. This
may break attempts at injecting additional code on top of what is generated
by `protoc-gen-go`. Such practice is not supported by this project.
* **Internal changes**: We reserve the right to add, modify, and remove
internal code, which includes all unexported declarations, the
[`generator`](https://pkg.go.dev/github.com/golang/protobuf/protoc-gen-go/generator)
package, and all packages under
[`internal`](https://pkg.go.dev/github.com/golang/protobuf/internal).
Any breaking changes outside of these will be announced 6 months in advance to
[protobuf@googlegroups.com](https://groups.google.com/forum/#!forum/protobuf).
|
protobuf
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/test.bash
|
#!/bin/bash
# Copyright 2018 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
cd "$(git rev-parse --show-toplevel)"
BOLD="\x1b[1mRunning: "
PASS="\x1b[32mPASS"
FAIL="\x1b[31mFAIL"
RESET="\x1b[0m"
echo -e "${BOLD}go test ./...${RESET}"
RET_TEST0=$(go test ./... | egrep -v "^(ok|[?])\s+")
if [[ ! -z "$RET_TEST0" ]]; then echo "$RET_TEST0"; echo; fi
echo -e "${BOLD}go test -tags purego ./...${RESET}"
RET_TEST1=$(go test -tags purego ./... | egrep -v "^(ok|[?])\s+")
if [[ ! -z "$RET_TEST1" ]]; then echo "$RET_TEST1"; echo; fi
echo -e "${BOLD}go generate${RESET}"
RET_GEN=$(go run ./internal/cmd/generate-alias 2>&1)
if [[ ! -z "$RET_GEN" ]]; then echo "$RET_GEN"; echo; fi
echo -e "${BOLD}go fmt${RESET}"
RET_FMT=$(gofmt -d $(git ls-files *.go) 2>&1)
if [[ ! -z "$RET_FMT" ]]; then echo "$RET_FMT"; echo; fi
echo -e "${BOLD}git diff${RESET}"
RET_DIFF=$(git diff --no-prefix HEAD 2>&1)
if [[ ! -z "$RET_DIFF" ]]; then echo "$RET_DIFF"; echo; fi
echo -e "${BOLD}git ls-files${RESET}"
RET_FILES=$(git ls-files --others --exclude-standard 2>&1)
if [[ ! -z "$RET_FILES" ]]; then echo "$RET_FILES"; echo; fi
if [[ ! -z "$RET_TEST0" ]] || [[ ! -z "$RET_TEST1" ]] || [[ ! -z "$RET_GEN" ]] || [ ! -z "$RET_FMT" ] || [[ ! -z "$RET_DIFF" ]] || [[ ! -z "$RET_FILES" ]]; then
echo -e "${FAIL}${RESET}"; exit 1
else
echo -e "${PASS}${RESET}"; exit 0
fi
|
protobuf
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/go.sum
|
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
protobuf
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/regenerate.bash
|
#!/bin/bash
# Copyright 2018 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
cd "$(git rev-parse --show-toplevel)"
set -e
go run ./internal/cmd/generate-alias -execute
go test ./protoc-gen-go -regenerate
|
protobuf
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/LICENSE
|
Copyright 2010 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
protobuf
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/CONTRIBUTORS
|
# This source code was written by the Go contributors.
# The master list of contributors is in the main Go distribution,
# visible at http://tip.golang.org/CONTRIBUTORS.
|
ptypes
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/ptypes/duration_test.go
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ptypes
import (
"math"
"testing"
"time"
"github.com/golang/protobuf/proto"
durpb "github.com/golang/protobuf/ptypes/duration"
)
const (
minGoSeconds = math.MinInt64 / int64(1e9)
maxGoSeconds = math.MaxInt64 / int64(1e9)
)
var durationTests = []struct {
proto *durpb.Duration
isValid bool
inRange bool
dur time.Duration
}{
// The zero duration.
{&durpb.Duration{Seconds: 0, Nanos: 0}, true, true, 0},
// Some ordinary non-zero durations.
{&durpb.Duration{Seconds: 100, Nanos: 0}, true, true, 100 * time.Second},
{&durpb.Duration{Seconds: -100, Nanos: 0}, true, true, -100 * time.Second},
{&durpb.Duration{Seconds: 100, Nanos: 987}, true, true, 100*time.Second + 987},
{&durpb.Duration{Seconds: -100, Nanos: -987}, true, true, -(100*time.Second + 987)},
// The largest duration representable in Go.
{&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, true, math.MaxInt64},
// The smallest duration representable in Go.
{&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, true, math.MinInt64},
{nil, false, false, 0},
{&durpb.Duration{Seconds: -100, Nanos: 987}, false, false, 0},
{&durpb.Duration{Seconds: 100, Nanos: -987}, false, false, 0},
{&durpb.Duration{Seconds: math.MinInt64, Nanos: 0}, false, false, 0},
{&durpb.Duration{Seconds: math.MaxInt64, Nanos: 0}, false, false, 0},
// The largest valid duration.
{&durpb.Duration{Seconds: maxSeconds, Nanos: 1e9 - 1}, true, false, 0},
// The smallest valid duration.
{&durpb.Duration{Seconds: minSeconds, Nanos: -(1e9 - 1)}, true, false, 0},
// The smallest invalid duration above the valid range.
{&durpb.Duration{Seconds: maxSeconds + 1, Nanos: 0}, false, false, 0},
// The largest invalid duration below the valid range.
{&durpb.Duration{Seconds: minSeconds - 1, Nanos: -(1e9 - 1)}, false, false, 0},
// One nanosecond past the largest duration representable in Go.
{&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64-1e9*maxGoSeconds) + 1}, true, false, 0},
// One nanosecond past the smallest duration representable in Go.
{&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64-1e9*minGoSeconds) - 1}, true, false, 0},
// One second past the largest duration representable in Go.
{&durpb.Duration{Seconds: maxGoSeconds + 1, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, false, 0},
// One second past the smallest duration representable in Go.
{&durpb.Duration{Seconds: minGoSeconds - 1, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, false, 0},
}
func TestValidateDuration(t *testing.T) {
for _, test := range durationTests {
err := validateDuration(test.proto)
gotValid := (err == nil)
if gotValid != test.isValid {
t.Errorf("validateDuration(%v) = %t, want %t", test.proto, gotValid, test.isValid)
}
}
}
func TestDuration(t *testing.T) {
for _, test := range durationTests {
got, err := Duration(test.proto)
gotOK := (err == nil)
wantOK := test.isValid && test.inRange
if gotOK != wantOK {
t.Errorf("Duration(%v) ok = %t, want %t", test.proto, gotOK, wantOK)
}
if err == nil && got != test.dur {
t.Errorf("Duration(%v) = %v, want %v", test.proto, got, test.dur)
}
}
}
func TestDurationProto(t *testing.T) {
for _, test := range durationTests {
if test.isValid && test.inRange {
got := DurationProto(test.dur)
if !proto.Equal(got, test.proto) {
t.Errorf("DurationProto(%v) = %v, want %v", test.dur, got, test.proto)
}
}
}
}
|
ptypes
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/ptypes/doc.go
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package ptypes provides functionality for interacting with well-known types.
//
// Deprecated: Well-known types have specialized functionality directly
// injected into the generated packages for each message type.
// See the deprecation notice for each function for the suggested alternative.
package ptypes
|
ptypes
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/ptypes/any.go
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ptypes
import (
"fmt"
"strings"
"github.com/golang/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
anypb "github.com/golang/protobuf/ptypes/any"
)
const urlPrefix = "type.googleapis.com/"
// AnyMessageName returns the message name contained in an anypb.Any message.
// Most type assertions should use the Is function instead.
//
// Deprecated: Call the any.MessageName method instead.
func AnyMessageName(any *anypb.Any) (string, error) {
name, err := anyMessageName(any)
return string(name), err
}
func anyMessageName(any *anypb.Any) (protoreflect.FullName, error) {
if any == nil {
return "", fmt.Errorf("message is nil")
}
name := protoreflect.FullName(any.TypeUrl)
if i := strings.LastIndex(any.TypeUrl, "/"); i >= 0 {
name = name[i+len("/"):]
}
if !name.IsValid() {
return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl)
}
return name, nil
}
// MarshalAny marshals the given message m into an anypb.Any message.
//
// Deprecated: Call the anypb.New function instead.
func MarshalAny(m proto.Message) (*anypb.Any, error) {
switch dm := m.(type) {
case DynamicAny:
m = dm.Message
case *DynamicAny:
if dm == nil {
return nil, proto.ErrNil
}
m = dm.Message
}
b, err := proto.Marshal(m)
if err != nil {
return nil, err
}
return &anypb.Any{TypeUrl: urlPrefix + proto.MessageName(m), Value: b}, nil
}
// Empty returns a new message of the type specified in an anypb.Any message.
// It returns protoregistry.NotFound if the corresponding message type could not
// be resolved in the global registry.
//
// Deprecated: Use protoregistry.GlobalTypes.FindMessageByName instead
// to resolve the message name and create a new instance of it.
func Empty(any *anypb.Any) (proto.Message, error) {
name, err := anyMessageName(any)
if err != nil {
return nil, err
}
mt, err := protoregistry.GlobalTypes.FindMessageByName(name)
if err != nil {
return nil, err
}
return proto.MessageV1(mt.New().Interface()), nil
}
// UnmarshalAny unmarshals the encoded value contained in the anypb.Any message
// into the provided message m. It returns an error if the target message
// does not match the type in the Any message or if an unmarshal error occurs.
//
// The target message m may be a *DynamicAny message. If the underlying message
// type could not be resolved, then this returns protoregistry.NotFound.
//
// Deprecated: Call the any.UnmarshalTo method instead.
func UnmarshalAny(any *anypb.Any, m proto.Message) error {
if dm, ok := m.(*DynamicAny); ok {
if dm.Message == nil {
var err error
dm.Message, err = Empty(any)
if err != nil {
return err
}
}
m = dm.Message
}
anyName, err := AnyMessageName(any)
if err != nil {
return err
}
msgName := proto.MessageName(m)
if anyName != msgName {
return fmt.Errorf("mismatched message type: got %q want %q", anyName, msgName)
}
return proto.Unmarshal(any.Value, m)
}
// Is reports whether the Any message contains a message of the specified type.
//
// Deprecated: Call the any.MessageIs method instead.
func Is(any *anypb.Any, m proto.Message) bool {
if any == nil || m == nil {
return false
}
name := proto.MessageName(m)
if !strings.HasSuffix(any.TypeUrl, name) {
return false
}
return len(any.TypeUrl) == len(name) || any.TypeUrl[len(any.TypeUrl)-len(name)-1] == '/'
}
// DynamicAny is a value that can be passed to UnmarshalAny to automatically
// allocate a proto.Message for the type specified in an anypb.Any message.
// The allocated message is stored in the embedded proto.Message.
//
// Example:
//
// var x ptypes.DynamicAny
// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... }
// fmt.Printf("unmarshaled message: %v", x.Message)
//
// Deprecated: Use the any.UnmarshalNew method instead to unmarshal
// the any message contents into a new instance of the underlying message.
type DynamicAny struct{ proto.Message }
func (m DynamicAny) String() string {
if m.Message == nil {
return "<nil>"
}
return m.Message.String()
}
func (m DynamicAny) Reset() {
if m.Message == nil {
return
}
m.Message.Reset()
}
func (m DynamicAny) ProtoMessage() {
return
}
func (m DynamicAny) ProtoReflect() protoreflect.Message {
if m.Message == nil {
return nil
}
return dynamicAny{proto.MessageReflect(m.Message)}
}
type dynamicAny struct{ protoreflect.Message }
func (m dynamicAny) Type() protoreflect.MessageType {
return dynamicAnyType{m.Message.Type()}
}
func (m dynamicAny) New() protoreflect.Message {
return dynamicAnyType{m.Message.Type()}.New()
}
func (m dynamicAny) Interface() protoreflect.ProtoMessage {
return DynamicAny{proto.MessageV1(m.Message.Interface())}
}
type dynamicAnyType struct{ protoreflect.MessageType }
func (t dynamicAnyType) New() protoreflect.Message {
return dynamicAny{t.MessageType.New()}
}
func (t dynamicAnyType) Zero() protoreflect.Message {
return dynamicAny{t.MessageType.Zero()}
}
|
ptypes
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/ptypes/duration.go
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ptypes
import (
"errors"
"fmt"
"time"
durationpb "github.com/golang/protobuf/ptypes/duration"
)
// Range of google.protobuf.Duration as specified in duration.proto.
// This is about 10,000 years in seconds.
const (
maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60)
minSeconds = -maxSeconds
)
// Duration converts a durationpb.Duration to a time.Duration.
// Duration returns an error if dur is invalid or overflows a time.Duration.
//
// Deprecated: Call the dur.AsDuration and dur.CheckValid methods instead.
func Duration(dur *durationpb.Duration) (time.Duration, error) {
if err := validateDuration(dur); err != nil {
return 0, err
}
d := time.Duration(dur.Seconds) * time.Second
if int64(d/time.Second) != dur.Seconds {
return 0, fmt.Errorf("duration: %v is out of range for time.Duration", dur)
}
if dur.Nanos != 0 {
d += time.Duration(dur.Nanos) * time.Nanosecond
if (d < 0) != (dur.Nanos < 0) {
return 0, fmt.Errorf("duration: %v is out of range for time.Duration", dur)
}
}
return d, nil
}
// DurationProto converts a time.Duration to a durationpb.Duration.
//
// Deprecated: Call the durationpb.New function instead.
func DurationProto(d time.Duration) *durationpb.Duration {
nanos := d.Nanoseconds()
secs := nanos / 1e9
nanos -= secs * 1e9
return &durationpb.Duration{
Seconds: int64(secs),
Nanos: int32(nanos),
}
}
// validateDuration determines whether the durationpb.Duration is valid
// according to the definition in google/protobuf/duration.proto.
// A valid durpb.Duration may still be too large to fit into a time.Duration
// Note that the range of durationpb.Duration is about 10,000 years,
// while the range of time.Duration is about 290 years.
func validateDuration(dur *durationpb.Duration) error {
if dur == nil {
return errors.New("duration: nil Duration")
}
if dur.Seconds < minSeconds || dur.Seconds > maxSeconds {
return fmt.Errorf("duration: %v: seconds out of range", dur)
}
if dur.Nanos <= -1e9 || dur.Nanos >= 1e9 {
return fmt.Errorf("duration: %v: nanos out of range", dur)
}
// Seconds and Nanos must have the same sign, unless d.Nanos is zero.
if (dur.Seconds < 0 && dur.Nanos > 0) || (dur.Seconds > 0 && dur.Nanos < 0) {
return fmt.Errorf("duration: %v: seconds and nanos have different signs", dur)
}
return nil
}
|
ptypes
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/ptypes/any_test.go
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ptypes
import (
"reflect"
"testing"
"github.com/golang/protobuf/proto"
descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
anypb "github.com/golang/protobuf/ptypes/any"
)
func TestMarshalUnmarshal(t *testing.T) {
orig := &anypb.Any{Value: []byte("test")}
packed, err := MarshalAny(orig)
if err != nil {
t.Errorf("MarshalAny(%+v): got: _, %v exp: _, nil", orig, err)
}
unpacked := &anypb.Any{}
err = UnmarshalAny(packed, unpacked)
if err != nil || !proto.Equal(unpacked, orig) {
t.Errorf("got: %v, %+v; want nil, %+v", err, unpacked, orig)
}
}
func TestIs(t *testing.T) {
a, err := MarshalAny(&descriptorpb.FileDescriptorProto{})
if err != nil {
t.Fatal(err)
}
if Is(a, &descriptorpb.DescriptorProto{}) {
// No spurious match for message names of different length.
t.Error("FileDescriptorProto is not a DescriptorProto, but Is says it is")
}
if Is(a, &descriptorpb.EnumDescriptorProto{}) {
// No spurious match for message names of equal length.
t.Error("FileDescriptorProto is not an EnumDescriptorProto, but Is says it is")
}
if !Is(a, &descriptorpb.FileDescriptorProto{}) {
t.Error("FileDescriptorProto is indeed a FileDescriptorProto, but Is says it is not")
}
}
func TestIsDifferentUrlPrefixes(t *testing.T) {
m := &descriptorpb.FileDescriptorProto{}
a := &anypb.Any{TypeUrl: "foo/bar/" + proto.MessageName(m)}
if !Is(a, m) {
t.Errorf("message with type url %q didn't satisfy Is for type %q", a.TypeUrl, proto.MessageName(m))
}
}
func TestIsCornerCases(t *testing.T) {
m := &descriptorpb.FileDescriptorProto{}
if Is(nil, m) {
t.Errorf("message with nil type url incorrectly claimed to be %q", proto.MessageName(m))
}
noPrefix := &anypb.Any{TypeUrl: proto.MessageName(m)}
if !Is(noPrefix, m) {
t.Errorf("message with type url %q didn't satisfy Is for type %q", noPrefix.TypeUrl, proto.MessageName(m))
}
shortPrefix := &anypb.Any{TypeUrl: "/" + proto.MessageName(m)}
if !Is(shortPrefix, m) {
t.Errorf("message with type url %q didn't satisfy Is for type %q", shortPrefix.TypeUrl, proto.MessageName(m))
}
}
func TestUnmarshalDynamic(t *testing.T) {
want := &descriptorpb.FileDescriptorProto{Name: proto.String("foo")}
a, err := MarshalAny(want)
if err != nil {
t.Fatal(err)
}
var got DynamicAny
if err := UnmarshalAny(a, &got); err != nil {
t.Fatal(err)
}
if !proto.Equal(got.Message, want) {
t.Errorf("invalid result from UnmarshalAny, got %q want %q", got.Message, want)
}
}
func TestEmpty(t *testing.T) {
want := &descriptorpb.FileDescriptorProto{}
a, err := MarshalAny(want)
if err != nil {
t.Fatal(err)
}
got, err := Empty(a)
if err != nil {
t.Fatal(err)
}
if !proto.Equal(got, want) {
t.Errorf("unequal empty message, got %q, want %q", got, want)
}
// that's a valid type_url for a message which shouldn't be linked into this
// test binary. We want an error.
a.TypeUrl = "type.googleapis.com/google.protobuf.FieldMask"
if _, err := Empty(a); err == nil {
t.Errorf("got no error for an attempt to create a message of type %q, which shouldn't be linked in", a.TypeUrl)
}
}
func TestEmptyCornerCases(t *testing.T) {
_, err := Empty(nil)
if err == nil {
t.Error("expected Empty for nil to fail")
}
want := &descriptorpb.FileDescriptorProto{}
noPrefix := &anypb.Any{TypeUrl: proto.MessageName(want)}
got, err := Empty(noPrefix)
if err != nil {
t.Errorf("Empty for any type %q failed: %s", noPrefix.TypeUrl, err)
}
if !proto.Equal(got, want) {
t.Errorf("Empty for any type %q differs, got %q, want %q", noPrefix.TypeUrl, got, want)
}
shortPrefix := &anypb.Any{TypeUrl: "/" + proto.MessageName(want)}
got, err = Empty(shortPrefix)
if err != nil {
t.Errorf("Empty for any type %q failed: %s", shortPrefix.TypeUrl, err)
}
if !proto.Equal(got, want) {
t.Errorf("Empty for any type %q differs, got %q, want %q", shortPrefix.TypeUrl, got, want)
}
}
func TestAnyReflect(t *testing.T) {
want := &descriptorpb.FileDescriptorProto{Name: proto.String("foo")}
a, err := MarshalAny(want)
if err != nil {
t.Fatal(err)
}
var got DynamicAny
if err := UnmarshalAny(a, &got); err != nil {
t.Fatal(err)
}
wantName := want.ProtoReflect().Descriptor().FullName()
gotName := got.ProtoReflect().Descriptor().FullName()
if gotName != wantName {
t.Errorf("name mismatch: got %v, want %v", gotName, wantName)
}
wantType := reflect.TypeOf(got)
gotType := reflect.TypeOf(got.ProtoReflect().Interface())
if gotType != wantType {
t.Errorf("ProtoReflect().Interface() round-trip type mismatch: got %v, want %v", gotType, wantType)
}
gotType = reflect.TypeOf(got.ProtoReflect().New().Interface())
if gotType != wantType {
t.Errorf("ProtoReflect().New().Interface() type mismatch: got %v, want %v", gotType, wantType)
}
gotType = reflect.TypeOf(got.ProtoReflect().Type().New().Interface())
if gotType != wantType {
t.Errorf("ProtoReflect().Type().New().Interface() type mismatch: got %v, want %v", gotType, wantType)
}
gotType = reflect.TypeOf(got.ProtoReflect().Type().Zero().Interface())
if gotType != wantType {
t.Errorf("ProtoReflect().Type().Zero().Interface() type mismatch: got %v, want %v", gotType, wantType)
}
}
|
ptypes
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/ptypes/timestamp_test.go
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ptypes
import (
"math"
"testing"
"time"
"github.com/golang/protobuf/proto"
tspb "github.com/golang/protobuf/ptypes/timestamp"
)
var tests = []struct {
ts *tspb.Timestamp
valid bool
t time.Time
}{
// The timestamp representing the Unix epoch date.
{&tspb.Timestamp{Seconds: 0, Nanos: 0}, true, utcDate(1970, 1, 1)},
// The smallest representable timestamp.
{&tspb.Timestamp{Seconds: math.MinInt64, Nanos: math.MinInt32}, false,
time.Unix(math.MinInt64, math.MinInt32).UTC()},
// The smallest representable timestamp with non-negative nanos.
{&tspb.Timestamp{Seconds: math.MinInt64, Nanos: 0}, false, time.Unix(math.MinInt64, 0).UTC()},
// The earliest valid timestamp.
{&tspb.Timestamp{Seconds: minValidSeconds, Nanos: 0}, true, utcDate(1, 1, 1)},
//"0001-01-01T00:00:00Z"},
// The largest representable timestamp.
{&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: math.MaxInt32}, false,
time.Unix(math.MaxInt64, math.MaxInt32).UTC()},
// The largest representable timestamp with nanos in range.
{&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: 1e9 - 1}, false,
time.Unix(math.MaxInt64, 1e9-1).UTC()},
// The largest valid timestamp.
{&tspb.Timestamp{Seconds: maxValidSeconds - 1, Nanos: 1e9 - 1}, true,
time.Date(9999, 12, 31, 23, 59, 59, 1e9-1, time.UTC)},
// The smallest invalid timestamp that is larger than the valid range.
{&tspb.Timestamp{Seconds: maxValidSeconds, Nanos: 0}, false, time.Unix(maxValidSeconds, 0).UTC()},
// A date before the epoch.
{&tspb.Timestamp{Seconds: -281836800, Nanos: 0}, true, utcDate(1961, 1, 26)},
// A date after the epoch.
{&tspb.Timestamp{Seconds: 1296000000, Nanos: 0}, true, utcDate(2011, 1, 26)},
// A date after the epoch, in the middle of the day.
{&tspb.Timestamp{Seconds: 1296012345, Nanos: 940483}, true,
time.Date(2011, 1, 26, 3, 25, 45, 940483, time.UTC)},
}
func TestValidateTimestamp(t *testing.T) {
for _, s := range tests {
got := validateTimestamp(s.ts)
if (got == nil) != s.valid {
t.Errorf("validateTimestamp(%v) = %v, want %v", s.ts, got, s.valid)
}
}
}
func TestTimestamp(t *testing.T) {
for _, s := range tests {
got, err := Timestamp(s.ts)
if (err == nil) != s.valid {
t.Errorf("Timestamp(%v) error = %v, but valid = %t", s.ts, err, s.valid)
} else if s.valid && got != s.t {
t.Errorf("Timestamp(%v) = %v, want %v", s.ts, got, s.t)
}
}
// Special case: a nil Timestamp is an error, but returns the 0 Unix time.
got, err := Timestamp(nil)
want := time.Unix(0, 0).UTC()
if got != want {
t.Errorf("Timestamp(nil) = %v, want %v", got, want)
}
if err == nil {
t.Errorf("Timestamp(nil) error = nil, expected error")
}
}
func TestTimestampProto(t *testing.T) {
for _, s := range tests {
got, err := TimestampProto(s.t)
if (err == nil) != s.valid {
t.Errorf("TimestampProto(%v) error = %v, but valid = %t", s.t, err, s.valid)
} else if s.valid && !proto.Equal(got, s.ts) {
t.Errorf("TimestampProto(%v) = %v, want %v", s.t, got, s.ts)
}
}
// No corresponding special case here: no time.Time results in a nil Timestamp.
}
func TestTimestampString(t *testing.T) {
for _, test := range []struct {
ts *tspb.Timestamp
want string
}{
// Not much testing needed because presumably time.Format is
// well-tested.
{&tspb.Timestamp{Seconds: 0, Nanos: 0}, "1970-01-01T00:00:00Z"},
} {
got := TimestampString(test.ts)
if got != test.want {
t.Errorf("TimestampString(%v) = %q, want %q", test.ts, got, test.want)
}
}
}
func utcDate(year, month, day int) time.Time {
return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)
}
func TestTimestampNow(t *testing.T) {
// Bracket the expected time.
before := time.Now()
ts := TimestampNow()
after := time.Now()
tm, err := Timestamp(ts)
if err != nil {
t.Errorf("between %v and %v\nTimestampNow() = %v\nwhich is invalid (%v)", before, after, ts, err)
}
if tm.Before(before) || tm.After(after) {
t.Errorf("between %v and %v\nTimestamp(TimestampNow()) = %v", before, after, tm)
}
}
|
ptypes
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/ptypes/timestamp.go
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ptypes
import (
"errors"
"fmt"
"time"
timestamppb "github.com/golang/protobuf/ptypes/timestamp"
)
// Range of google.protobuf.Duration as specified in timestamp.proto.
const (
// Seconds field of the earliest valid Timestamp.
// This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
minValidSeconds = -62135596800
// Seconds field just after the latest valid Timestamp.
// This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
maxValidSeconds = 253402300800
)
// Timestamp converts a timestamppb.Timestamp to a time.Time.
// It returns an error if the argument is invalid.
//
// Unlike most Go functions, if Timestamp returns an error, the first return
// value is not the zero time.Time. Instead, it is the value obtained from the
// time.Unix function when passed the contents of the Timestamp, in the UTC
// locale. This may or may not be a meaningful time; many invalid Timestamps
// do map to valid time.Times.
//
// A nil Timestamp returns an error. The first return value in that case is
// undefined.
//
// Deprecated: Call the ts.AsTime and ts.CheckValid methods instead.
func Timestamp(ts *timestamppb.Timestamp) (time.Time, error) {
// Don't return the zero value on error, because corresponds to a valid
// timestamp. Instead return whatever time.Unix gives us.
var t time.Time
if ts == nil {
t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp
} else {
t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC()
}
return t, validateTimestamp(ts)
}
// TimestampNow returns a google.protobuf.Timestamp for the current time.
//
// Deprecated: Call the timestamppb.Now function instead.
func TimestampNow() *timestamppb.Timestamp {
ts, err := TimestampProto(time.Now())
if err != nil {
panic("ptypes: time.Now() out of Timestamp range")
}
return ts
}
// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto.
// It returns an error if the resulting Timestamp is invalid.
//
// Deprecated: Call the timestamppb.New function instead.
func TimestampProto(t time.Time) (*timestamppb.Timestamp, error) {
ts := ×tamppb.Timestamp{
Seconds: t.Unix(),
Nanos: int32(t.Nanosecond()),
}
if err := validateTimestamp(ts); err != nil {
return nil, err
}
return ts, nil
}
// TimestampString returns the RFC 3339 string for valid Timestamps.
// For invalid Timestamps, it returns an error message in parentheses.
//
// Deprecated: Call the ts.AsTime method instead,
// followed by a call to the Format method on the time.Time value.
func TimestampString(ts *timestamppb.Timestamp) string {
t, err := Timestamp(ts)
if err != nil {
return fmt.Sprintf("(%v)", err)
}
return t.Format(time.RFC3339Nano)
}
// validateTimestamp determines whether a Timestamp is valid.
// A valid timestamp represents a time in the range [0001-01-01, 10000-01-01)
// and has a Nanos field in the range [0, 1e9).
//
// If the Timestamp is valid, validateTimestamp returns nil.
// Otherwise, it returns an error that describes the problem.
//
// Every valid Timestamp can be represented by a time.Time,
// but the converse is not true.
func validateTimestamp(ts *timestamppb.Timestamp) error {
if ts == nil {
return errors.New("timestamp: nil Timestamp")
}
if ts.Seconds < minValidSeconds {
return fmt.Errorf("timestamp: %v before 0001-01-01", ts)
}
if ts.Seconds >= maxValidSeconds {
return fmt.Errorf("timestamp: %v after 10000-01-01", ts)
}
if ts.Nanos < 0 || ts.Nanos >= 1e9 {
return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts)
}
return nil
}
|
wrappers
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/ptypes/wrappers/wrappers.pb.go
|
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: github.com/golang/protobuf/ptypes/wrappers/wrappers.proto
package wrappers
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
wrapperspb "google.golang.org/protobuf/types/known/wrapperspb"
reflect "reflect"
)
// Symbols defined in public import of google/protobuf/wrappers.proto.
type DoubleValue = wrapperspb.DoubleValue
type FloatValue = wrapperspb.FloatValue
type Int64Value = wrapperspb.Int64Value
type UInt64Value = wrapperspb.UInt64Value
type Int32Value = wrapperspb.Int32Value
type UInt32Value = wrapperspb.UInt32Value
type BoolValue = wrapperspb.BoolValue
type StringValue = wrapperspb.StringValue
type BytesValue = wrapperspb.BytesValue
var File_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto protoreflect.FileDescriptor
var file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_rawDesc = []byte{
0x0a, 0x39, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79,
0x70, 0x65, 0x73, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2f, 0x77, 0x72, 0x61,
0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f,
0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61,
0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x35, 0x5a, 0x33, 0x67,
0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67,
0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73,
0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x3b, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65,
0x72, 0x73, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_goTypes = []interface{}{}
var file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_init() }
func file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_init() {
if File_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_rawDesc,
NumEnums: 0,
NumMessages: 0,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_goTypes,
DependencyIndexes: file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_depIdxs,
}.Build()
File_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto = out.File
file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_rawDesc = nil
file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_goTypes = nil
file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_depIdxs = nil
}
|
struct
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/protobuf/ptypes/struct/struct.pb.go
|
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: github.com/golang/protobuf/ptypes/struct/struct.proto
package structpb
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
structpb "google.golang.org/protobuf/types/known/structpb"
reflect "reflect"
)
// Symbols defined in public import of google/protobuf/struct.proto.
type NullValue = structpb.NullValue
const NullValue_NULL_VALUE = structpb.NullValue_NULL_VALUE
var NullValue_name = structpb.NullValue_name
var NullValue_value = structpb.NullValue_value
type Struct = structpb.Struct
type Value = structpb.Value
type Value_NullValue = structpb.Value_NullValue
type Value_NumberValue = structpb.Value_NumberValue
type Value_StringValue = structpb.Value_StringValue
type Value_BoolValue = structpb.Value_BoolValue
type Value_StructValue = structpb.Value_StructValue
type Value_ListValue = structpb.Value_ListValue
type ListValue = structpb.ListValue
var File_github_com_golang_protobuf_ptypes_struct_struct_proto protoreflect.FileDescriptor
var file_github_com_golang_protobuf_ptypes_struct_struct_proto_rawDesc = []byte{
0x0a, 0x35, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79,
0x70, 0x65, 0x73, 0x2f, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x2f, 0x73, 0x74, 0x72, 0x75, 0x63,
0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x33, 0x5a, 0x31, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e,
0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x73, 0x74, 0x72, 0x75, 0x63,
0x74, 0x3b, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x70, 0x62, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x33,
}
var file_github_com_golang_protobuf_ptypes_struct_struct_proto_goTypes = []interface{}{}
var file_github_com_golang_protobuf_ptypes_struct_struct_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_github_com_golang_protobuf_ptypes_struct_struct_proto_init() }
func file_github_com_golang_protobuf_ptypes_struct_struct_proto_init() {
if File_github_com_golang_protobuf_ptypes_struct_struct_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_github_com_golang_protobuf_ptypes_struct_struct_proto_rawDesc,
NumEnums: 0,
NumMessages: 0,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_github_com_golang_protobuf_ptypes_struct_struct_proto_goTypes,
DependencyIndexes: file_github_com_golang_protobuf_ptypes_struct_struct_proto_depIdxs,
}.Build()
File_github_com_golang_protobuf_ptypes_struct_struct_proto = out.File
file_github_com_golang_protobuf_ptypes_struct_struct_proto_rawDesc = nil
file_github_com_golang_protobuf_ptypes_struct_struct_proto_goTypes = nil
file_github_com_golang_protobuf_ptypes_struct_struct_proto_depIdxs = nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.