repo_id
stringclasses
927 values
file_path
stringlengths
99
214
content
stringlengths
2
4.15M
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfile/testdata/module.golden
module abc
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfile/testdata/comment.golden
// comment module "x" // eol // mid comment // comment 2 // comment 2 line 2 module "y" // eoy // comment 3
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modfile/testdata/block.in
// comment x "y" z // block block ( // block-eol // x-before-line "x" ( y // x-eol "x1" "x2" // line "x3" "x4" "x5" // y-line "y" // y-eol "z" // z-eol ) // block-eol2 block2 (x y z ) // eof
module
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/module/module_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 module import "testing" var checkTests = []struct { path string version string ok bool }{ {"rsc.io/quote", "0.1.0", false}, {"rsc io/quote", "v1.0.0", false}, {"github.com/go-yaml/yaml", "v0.8.0", true}, {"github.com/go-yaml/yaml", "v1.0.0", true}, {"github.com/go-yaml/yaml", "v2.0.0", false}, {"github.com/go-yaml/yaml", "v2.1.5", false}, {"github.com/go-yaml/yaml", "v3.0.0", false}, {"github.com/go-yaml/yaml/v2", "v1.0.0", false}, {"github.com/go-yaml/yaml/v2", "v2.0.0", true}, {"github.com/go-yaml/yaml/v2", "v2.1.5", true}, {"github.com/go-yaml/yaml/v2", "v3.0.0", false}, {"gopkg.in/yaml.v0", "v0.8.0", true}, {"gopkg.in/yaml.v0", "v1.0.0", false}, {"gopkg.in/yaml.v0", "v2.0.0", false}, {"gopkg.in/yaml.v0", "v2.1.5", false}, {"gopkg.in/yaml.v0", "v3.0.0", false}, {"gopkg.in/yaml.v1", "v0.8.0", false}, {"gopkg.in/yaml.v1", "v1.0.0", true}, {"gopkg.in/yaml.v1", "v2.0.0", false}, {"gopkg.in/yaml.v1", "v2.1.5", false}, {"gopkg.in/yaml.v1", "v3.0.0", false}, // For gopkg.in, .v1 means v1 only (not v0). // But early versions of vgo still generated v0 pseudo-versions for it. // Even though now we'd generate those as v1 pseudo-versions, // we accept the old pseudo-versions to avoid breaking existing go.mod files. // For example gopkg.in/yaml.v2@v2.2.1's go.mod requires check.v1 at a v0 pseudo-version. {"gopkg.in/check.v1", "v0.0.0", false}, {"gopkg.in/check.v1", "v0.0.0-20160102150405-abcdef123456", true}, {"gopkg.in/yaml.v2", "v1.0.0", false}, {"gopkg.in/yaml.v2", "v2.0.0", true}, {"gopkg.in/yaml.v2", "v2.1.5", true}, {"gopkg.in/yaml.v2", "v3.0.0", false}, {"rsc.io/quote", "v17.0.0", false}, {"rsc.io/quote", "v17.0.0+incompatible", true}, } func TestCheck(t *testing.T) { for _, tt := range checkTests { err := Check(tt.path, tt.version) if tt.ok && err != nil { t.Errorf("Check(%q, %q) = %v, wanted nil error", tt.path, tt.version, err) } else if !tt.ok && err == nil { t.Errorf("Check(%q, %q) succeeded, wanted error", tt.path, tt.version) } } } var checkPathTests = []struct { path string ok bool importOK bool fileOK bool }{ {"x.y/z", true, true, true}, {"x.y", true, true, true}, {"", false, false, false}, {"x.y/\xFFz", false, false, false}, {"/x.y/z", false, false, false}, {"x./z", false, false, false}, {".x/z", false, false, true}, {"-x/z", false, true, true}, {"x..y/z", false, false, false}, {"x.y/z/../../w", false, false, false}, {"x.y//z", false, false, false}, {"x.y/z//w", false, false, false}, {"x.y/z/", false, false, false}, {"x.y/z/v0", false, true, true}, {"x.y/z/v1", false, true, true}, {"x.y/z/v2", true, true, true}, {"x.y/z/v2.0", false, true, true}, {"X.y/z", false, true, true}, {"!x.y/z", false, false, true}, {"_x.y/z", false, true, true}, {"x.y!/z", false, false, true}, {"x.y\"/z", false, false, false}, {"x.y#/z", false, false, true}, {"x.y$/z", false, false, true}, {"x.y%/z", false, false, true}, {"x.y&/z", false, false, true}, {"x.y'/z", false, false, false}, {"x.y(/z", false, false, true}, {"x.y)/z", false, false, true}, {"x.y*/z", false, false, false}, {"x.y+/z", false, true, true}, {"x.y,/z", false, false, true}, {"x.y-/z", true, true, true}, {"x.y./zt", false, false, false}, {"x.y:/z", false, false, false}, {"x.y;/z", false, false, false}, {"x.y</z", false, false, false}, {"x.y=/z", false, false, true}, {"x.y>/z", false, false, false}, {"x.y?/z", false, false, false}, {"x.y@/z", false, false, true}, {"x.y[/z", false, false, true}, {"x.y\\/z", false, false, false}, {"x.y]/z", false, false, true}, {"x.y^/z", false, false, true}, {"x.y_/z", false, true, true}, {"x.y`/z", false, false, false}, {"x.y{/z", false, false, true}, {"x.y}/z", false, false, true}, {"x.y~/z", false, true, true}, {"x.y/z!", false, false, true}, {"x.y/z\"", false, false, false}, {"x.y/z#", false, false, true}, {"x.y/z$", false, false, true}, {"x.y/z%", false, false, true}, {"x.y/z&", false, false, true}, {"x.y/z'", false, false, false}, {"x.y/z(", false, false, true}, {"x.y/z)", false, false, true}, {"x.y/z*", false, false, false}, {"x.y/z+", true, true, true}, {"x.y/z,", false, false, true}, {"x.y/z-", true, true, true}, {"x.y/z.t", true, true, true}, {"x.y/z/t", true, true, true}, {"x.y/z:", false, false, false}, {"x.y/z;", false, false, false}, {"x.y/z<", false, false, false}, {"x.y/z=", false, false, true}, {"x.y/z>", false, false, false}, {"x.y/z?", false, false, false}, {"x.y/z@", false, false, true}, {"x.y/z[", false, false, true}, {"x.y/z\\", false, false, false}, {"x.y/z]", false, false, true}, {"x.y/z^", false, false, true}, {"x.y/z_", true, true, true}, {"x.y/z`", false, false, false}, {"x.y/z{", false, false, true}, {"x.y/z}", false, false, true}, {"x.y/z~", true, true, true}, {"x.y/x.foo", true, true, true}, {"x.y/aux.foo", false, false, false}, {"x.y/prn", false, false, false}, {"x.y/prn2", true, true, true}, {"x.y/com", true, true, true}, {"x.y/com1", false, false, false}, {"x.y/com1.txt", false, false, false}, {"x.y/calm1", true, true, true}, {"github.com/!123/logrus", false, false, true}, // TODO: CL 41822 allowed Unicode letters in old "go get" // without due consideration of the implications, and only on github.com (!). // For now, we disallow non-ASCII characters in module mode, // in both module paths and general import paths, // until we can get the implications right. // When we do, we'll enable them everywhere, not just for GitHub. {"github.com/user/unicode/испытание", false, false, true}, {"../x", false, false, false}, {"./y", false, false, false}, {"x:y", false, false, false}, {`\temp\foo`, false, false, false}, {".gitignore", false, false, true}, {".github/ISSUE_TEMPLATE", false, false, true}, {"x☺y", false, false, false}, } func TestCheckPath(t *testing.T) { for _, tt := range checkPathTests { err := CheckPath(tt.path) if tt.ok && err != nil { t.Errorf("CheckPath(%q) = %v, wanted nil error", tt.path, err) } else if !tt.ok && err == nil { t.Errorf("CheckPath(%q) succeeded, wanted error", tt.path) } err = CheckImportPath(tt.path) if tt.importOK && err != nil { t.Errorf("CheckImportPath(%q) = %v, wanted nil error", tt.path, err) } else if !tt.importOK && err == nil { t.Errorf("CheckImportPath(%q) succeeded, wanted error", tt.path) } err = CheckFilePath(tt.path) if tt.fileOK && err != nil { t.Errorf("CheckFilePath(%q) = %v, wanted nil error", tt.path, err) } else if !tt.fileOK && err == nil { t.Errorf("CheckFilePath(%q) succeeded, wanted error", tt.path) } } } var splitPathVersionTests = []struct { pathPrefix string version string }{ {"x.y/z", ""}, {"x.y/z", "/v2"}, {"x.y/z", "/v3"}, {"gopkg.in/yaml", ".v0"}, {"gopkg.in/yaml", ".v1"}, {"gopkg.in/yaml", ".v2"}, {"gopkg.in/yaml", ".v3"}, } func TestSplitPathVersion(t *testing.T) { for _, tt := range splitPathVersionTests { pathPrefix, version, ok := SplitPathVersion(tt.pathPrefix + tt.version) if pathPrefix != tt.pathPrefix || version != tt.version || !ok { t.Errorf("SplitPathVersion(%q) = %q, %q, %v, want %q, %q, true", tt.pathPrefix+tt.version, pathPrefix, version, ok, tt.pathPrefix, tt.version) } } for _, tt := range checkPathTests { pathPrefix, version, ok := SplitPathVersion(tt.path) if pathPrefix+version != tt.path { t.Errorf("SplitPathVersion(%q) = %q, %q, %v, doesn't add to input", tt.path, pathPrefix, version, ok) } } } var encodeTests = []struct { path string enc string // empty means same as path }{ {path: "ascii.com/abcdefghijklmnopqrstuvwxyz.-+/~_0123456789"}, {path: "github.com/GoogleCloudPlatform/omega", enc: "github.com/!google!cloud!platform/omega"}, } func TestEncodePath(t *testing.T) { // Check invalid paths. for _, tt := range checkPathTests { if !tt.ok { _, err := EncodePath(tt.path) if err == nil { t.Errorf("EncodePath(%q): succeeded, want error (invalid path)", tt.path) } } } // Check encodings. for _, tt := range encodeTests { enc, err := EncodePath(tt.path) if err != nil { t.Errorf("EncodePath(%q): unexpected error: %v", tt.path, err) continue } want := tt.enc if want == "" { want = tt.path } if enc != want { t.Errorf("EncodePath(%q) = %q, want %q", tt.path, enc, want) } } } var badDecode = []string{ "github.com/GoogleCloudPlatform/omega", "github.com/!google!cloud!platform!/omega", "github.com/!0google!cloud!platform/omega", "github.com/!_google!cloud!platform/omega", "github.com/!!google!cloud!platform/omega", "", } func TestDecodePath(t *testing.T) { // Check invalid decodings. for _, bad := range badDecode { _, err := DecodePath(bad) if err == nil { t.Errorf("DecodePath(%q): succeeded, want error (invalid decoding)", bad) } } // Check invalid paths (or maybe decodings). for _, tt := range checkPathTests { if !tt.ok { path, err := DecodePath(tt.path) if err == nil { t.Errorf("DecodePath(%q) = %q, want error (invalid path)", tt.path, path) } } } // Check encodings. for _, tt := range encodeTests { enc := tt.enc if enc == "" { enc = tt.path } path, err := DecodePath(enc) if err != nil { t.Errorf("DecodePath(%q): unexpected error: %v", enc, err) continue } if path != tt.path { t.Errorf("DecodePath(%q) = %q, want %q", enc, path, tt.path) } } }
module
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/module/module.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 module defines the module.Version type // along with support code. package module // IMPORTANT NOTE // // This file essentially defines the set of valid import paths for the go command. // There are many subtle considerations, including Unicode ambiguity, // security, network, and file system representations. // // This file also defines the set of valid module path and version combinations, // another topic with many subtle considerations. // // Changes to the semantics in this file require approval from rsc. import ( "fmt" "sort" "strings" "unicode" "unicode/utf8" "cmd/go/internal/semver" ) // A Version is defined by a module path and version pair. type Version struct { Path string // Version is usually a semantic version in canonical form. // There are two exceptions to this general rule. // First, the top-level target of a build has no specific version // and uses Version = "". // Second, during MVS calculations the version "none" is used // to represent the decision to take no version of a given module. Version string `json:",omitempty"` } // Check checks that a given module path, version pair is valid. // In addition to the path being a valid module path // and the version being a valid semantic version, // the two must correspond. // For example, the path "yaml/v2" only corresponds to // semantic versions beginning with "v2.". func Check(path, version string) error { if err := CheckPath(path); err != nil { return err } if !semver.IsValid(version) { return fmt.Errorf("malformed semantic version %v", version) } _, pathMajor, _ := SplitPathVersion(path) if !MatchPathMajor(version, pathMajor) { if pathMajor == "" { pathMajor = "v0 or v1" } if pathMajor[0] == '.' { // .v1 pathMajor = pathMajor[1:] } return fmt.Errorf("mismatched module path %v and version %v (want %v)", path, version, pathMajor) } return nil } // firstPathOK reports whether r can appear in the first element of a module path. // The first element of the path must be an LDH domain name, at least for now. // To avoid case ambiguity, the domain name must be entirely lower case. func firstPathOK(r rune) bool { return r == '-' || r == '.' || '0' <= r && r <= '9' || 'a' <= r && r <= 'z' } // pathOK reports whether r can appear in an import path element. // Paths can be ASCII letters, ASCII digits, and limited ASCII punctuation: + - . _ and ~. // This matches what "go get" has historically recognized in import paths. // TODO(rsc): We would like to allow Unicode letters, but that requires additional // care in the safe encoding (see note below). func pathOK(r rune) bool { if r < utf8.RuneSelf { return r == '+' || r == '-' || r == '.' || r == '_' || r == '~' || '0' <= r && r <= '9' || 'A' <= r && r <= 'Z' || 'a' <= r && r <= 'z' } return false } // fileNameOK reports whether r can appear in a file name. // For now we allow all Unicode letters but otherwise limit to pathOK plus a few more punctuation characters. // If we expand the set of allowed characters here, we have to // work harder at detecting potential case-folding and normalization collisions. // See note about "safe encoding" below. func fileNameOK(r rune) bool { if r < utf8.RuneSelf { // Entire set of ASCII punctuation, from which we remove characters: // ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~ // We disallow some shell special characters: " ' * < > ? ` | // (Note that some of those are disallowed by the Windows file system as well.) // We also disallow path separators / : and \ (fileNameOK is only called on path element characters). // We allow spaces (U+0020) in file names. const allowed = "!#$%&()+,-.=@[]^_{}~ " if '0' <= r && r <= '9' || 'A' <= r && r <= 'Z' || 'a' <= r && r <= 'z' { return true } for i := 0; i < len(allowed); i++ { if rune(allowed[i]) == r { return true } } return false } // It may be OK to add more ASCII punctuation here, but only carefully. // For example Windows disallows < > \, and macOS disallows :, so we must not allow those. return unicode.IsLetter(r) } // CheckPath checks that a module path is valid. func CheckPath(path string) error { if err := checkPath(path, false); err != nil { return fmt.Errorf("malformed module path %q: %v", path, err) } i := strings.Index(path, "/") if i < 0 { i = len(path) } if i == 0 { return fmt.Errorf("malformed module path %q: leading slash", path) } if !strings.Contains(path[:i], ".") { return fmt.Errorf("malformed module path %q: missing dot in first path element", path) } if path[0] == '-' { return fmt.Errorf("malformed module path %q: leading dash in first path element", path) } for _, r := range path[:i] { if !firstPathOK(r) { return fmt.Errorf("malformed module path %q: invalid char %q in first path element", path, r) } } if _, _, ok := SplitPathVersion(path); !ok { return fmt.Errorf("malformed module path %q: invalid version", path) } return nil } // CheckImportPath checks that an import path is valid. func CheckImportPath(path string) error { if err := checkPath(path, false); err != nil { return fmt.Errorf("malformed import path %q: %v", path, err) } return nil } // checkPath checks that a general path is valid. // It returns an error describing why but not mentioning path. // Because these checks apply to both module paths and import paths, // the caller is expected to add the "malformed ___ path %q: " prefix. // fileName indicates whether the final element of the path is a file name // (as opposed to a directory name). func checkPath(path string, fileName bool) error { if !utf8.ValidString(path) { return fmt.Errorf("invalid UTF-8") } if path == "" { return fmt.Errorf("empty string") } if strings.Contains(path, "..") { return fmt.Errorf("double dot") } if strings.Contains(path, "//") { return fmt.Errorf("double slash") } if path[len(path)-1] == '/' { return fmt.Errorf("trailing slash") } elemStart := 0 for i, r := range path { if r == '/' { if err := checkElem(path[elemStart:i], fileName); err != nil { return err } elemStart = i + 1 } } if err := checkElem(path[elemStart:], fileName); err != nil { return err } return nil } // checkElem checks whether an individual path element is valid. // fileName indicates whether the element is a file name (not a directory name). func checkElem(elem string, fileName bool) error { if elem == "" { return fmt.Errorf("empty path element") } if strings.Count(elem, ".") == len(elem) { return fmt.Errorf("invalid path element %q", elem) } if elem[0] == '.' && !fileName { return fmt.Errorf("leading dot in path element") } if elem[len(elem)-1] == '.' { return fmt.Errorf("trailing dot in path element") } charOK := pathOK if fileName { charOK = fileNameOK } for _, r := range elem { if !charOK(r) { return fmt.Errorf("invalid char %q", r) } } // Windows disallows a bunch of path elements, sadly. // See https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file short := elem if i := strings.Index(short, "."); i >= 0 { short = short[:i] } for _, bad := range badWindowsNames { if strings.EqualFold(bad, short) { return fmt.Errorf("disallowed path element %q", elem) } } return nil } // CheckFilePath checks whether a slash-separated file path is valid. func CheckFilePath(path string) error { if err := checkPath(path, true); err != nil { return fmt.Errorf("malformed file path %q: %v", path, err) } return nil } // badWindowsNames are the reserved file path elements on Windows. // See https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file var badWindowsNames = []string{ "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", } // SplitPathVersion returns prefix and major version such that prefix+pathMajor == path // and version is either empty or "/vN" for N >= 2. // As a special case, gopkg.in paths are recognized directly; // they require ".vN" instead of "/vN", and for all N, not just N >= 2. func SplitPathVersion(path string) (prefix, pathMajor string, ok bool) { if strings.HasPrefix(path, "gopkg.in/") { return splitGopkgIn(path) } i := len(path) dot := false for i > 0 && ('0' <= path[i-1] && path[i-1] <= '9' || path[i-1] == '.') { if path[i-1] == '.' { dot = true } i-- } if i <= 1 || path[i-1] != 'v' || path[i-2] != '/' { return path, "", true } prefix, pathMajor = path[:i-2], path[i-2:] if dot || len(pathMajor) <= 2 || pathMajor[2] == '0' || pathMajor == "/v1" { return path, "", false } return prefix, pathMajor, true } // splitGopkgIn is like SplitPathVersion but only for gopkg.in paths. func splitGopkgIn(path string) (prefix, pathMajor string, ok bool) { if !strings.HasPrefix(path, "gopkg.in/") { return path, "", false } i := len(path) if strings.HasSuffix(path, "-unstable") { i -= len("-unstable") } for i > 0 && ('0' <= path[i-1] && path[i-1] <= '9') { i-- } if i <= 1 || path[i-1] != 'v' || path[i-2] != '.' { // All gopkg.in paths must end in vN for some N. return path, "", false } prefix, pathMajor = path[:i-2], path[i-2:] if len(pathMajor) <= 2 || pathMajor[2] == '0' && pathMajor != ".v0" { return path, "", false } return prefix, pathMajor, true } // MatchPathMajor reports whether the semantic version v // matches the path major version pathMajor. func MatchPathMajor(v, pathMajor string) bool { if strings.HasPrefix(pathMajor, ".v") && strings.HasSuffix(pathMajor, "-unstable") { pathMajor = strings.TrimSuffix(pathMajor, "-unstable") } if strings.HasPrefix(v, "v0.0.0-") && pathMajor == ".v1" { // Allow old bug in pseudo-versions that generated v0.0.0- pseudoversion for gopkg .v1. // For example, gopkg.in/yaml.v2@v2.2.1's go.mod requires gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405. return true } m := semver.Major(v) if pathMajor == "" { return m == "v0" || m == "v1" || semver.Build(v) == "+incompatible" } return (pathMajor[0] == '/' || pathMajor[0] == '.') && m == pathMajor[1:] } // CanonicalVersion returns the canonical form of the version string v. // It is the same as semver.Canonical(v) except that it preserves the special build suffix "+incompatible". func CanonicalVersion(v string) string { cv := semver.Canonical(v) if semver.Build(v) == "+incompatible" { cv += "+incompatible" } return cv } // Sort sorts the list by Path, breaking ties by comparing Versions. func Sort(list []Version) { sort.Slice(list, func(i, j int) bool { mi := list[i] mj := list[j] if mi.Path != mj.Path { return mi.Path < mj.Path } // To help go.sum formatting, allow version/file. // Compare semver prefix by semver rules, // file by string order. vi := mi.Version vj := mj.Version var fi, fj string if k := strings.Index(vi, "/"); k >= 0 { vi, fi = vi[:k], vi[k:] } if k := strings.Index(vj, "/"); k >= 0 { vj, fj = vj[:k], vj[k:] } if vi != vj { return semver.Compare(vi, vj) < 0 } return fi < fj }) } // Safe encodings // // Module paths appear as substrings of file system paths // (in the download cache) and of web server URLs in the proxy protocol. // In general we cannot rely on file systems to be case-sensitive, // nor can we rely on web servers, since they read from file systems. // That is, we cannot rely on the file system to keep rsc.io/QUOTE // and rsc.io/quote separate. Windows and macOS don't. // Instead, we must never require two different casings of a file path. // Because we want the download cache to match the proxy protocol, // and because we want the proxy protocol to be possible to serve // from a tree of static files (which might be stored on a case-insensitive // file system), the proxy protocol must never require two different casings // of a URL path either. // // One possibility would be to make the safe encoding be the lowercase // hexadecimal encoding of the actual path bytes. This would avoid ever // needing different casings of a file path, but it would be fairly illegible // to most programmers when those paths appeared in the file system // (including in file paths in compiler errors and stack traces) // in web server logs, and so on. Instead, we want a safe encoding that // leaves most paths unaltered. // // The safe encoding is this: // replace every uppercase letter with an exclamation mark // followed by the letter's lowercase equivalent. // // For example, // github.com/Azure/azure-sdk-for-go -> github.com/!azure/azure-sdk-for-go. // github.com/GoogleCloudPlatform/cloudsql-proxy -> github.com/!google!cloud!platform/cloudsql-proxy // github.com/Sirupsen/logrus -> github.com/!sirupsen/logrus. // // Import paths that avoid upper-case letters are left unchanged. // Note that because import paths are ASCII-only and avoid various // problematic punctuation (like : < and >), the safe encoding is also ASCII-only // and avoids the same problematic punctuation. // // Import paths have never allowed exclamation marks, so there is no // need to define how to encode a literal !. // // Although paths are disallowed from using Unicode (see pathOK above), // the eventual plan is to allow Unicode letters as well, to assume that // file systems and URLs are Unicode-safe (storing UTF-8), and apply // the !-for-uppercase convention. Note however that not all runes that // are different but case-fold equivalent are an upper/lower pair. // For example, U+004B ('K'), U+006B ('k'), and U+212A ('K' for Kelvin) // are considered to case-fold to each other. When we do add Unicode // letters, we must not assume that upper/lower are the only case-equivalent pairs. // Perhaps the Kelvin symbol would be disallowed entirely, for example. // Or perhaps it would encode as "!!k", or perhaps as "(212A)". // // Also, it would be nice to allow Unicode marks as well as letters, // but marks include combining marks, and then we must deal not // only with case folding but also normalization: both U+00E9 ('é') // and U+0065 U+0301 ('e' followed by combining acute accent) // look the same on the page and are treated by some file systems // as the same path. If we do allow Unicode marks in paths, there // must be some kind of normalization to allow only one canonical // encoding of any character used in an import path. // EncodePath returns the safe encoding of the given module path. // It fails if the module path is invalid. func EncodePath(path string) (encoding string, err error) { if err := CheckPath(path); err != nil { return "", err } return encodeString(path) } // EncodeVersion returns the safe encoding of the given module version. // Versions are allowed to be in non-semver form but must be valid file names // and not contain exclamation marks. func EncodeVersion(v string) (encoding string, err error) { if err := checkElem(v, true); err != nil || strings.Contains(v, "!") { return "", fmt.Errorf("disallowed version string %q", v) } return encodeString(v) } func encodeString(s string) (encoding string, err error) { haveUpper := false for _, r := range s { if r == '!' || r >= utf8.RuneSelf { // This should be disallowed by CheckPath, but diagnose anyway. // The correctness of the encoding loop below depends on it. return "", fmt.Errorf("internal error: inconsistency in EncodePath") } if 'A' <= r && r <= 'Z' { haveUpper = true } } if !haveUpper { return s, nil } var buf []byte for _, r := range s { if 'A' <= r && r <= 'Z' { buf = append(buf, '!', byte(r+'a'-'A')) } else { buf = append(buf, byte(r)) } } return string(buf), nil } // DecodePath returns the module path of the given safe encoding. // It fails if the encoding is invalid or encodes an invalid path. func DecodePath(encoding string) (path string, err error) { path, ok := decodeString(encoding) if !ok { return "", fmt.Errorf("invalid module path encoding %q", encoding) } if err := CheckPath(path); err != nil { return "", fmt.Errorf("invalid module path encoding %q: %v", encoding, err) } return path, nil } // DecodeVersion returns the version string for the given safe encoding. // It fails if the encoding is invalid or encodes an invalid version. // Versions are allowed to be in non-semver form but must be valid file names // and not contain exclamation marks. func DecodeVersion(encoding string) (v string, err error) { v, ok := decodeString(encoding) if !ok { return "", fmt.Errorf("invalid version encoding %q", encoding) } if err := checkElem(v, true); err != nil { return "", fmt.Errorf("disallowed version string %q", v) } return v, nil } func decodeString(encoding string) (string, bool) { var buf []byte bang := false for _, r := range encoding { if r >= utf8.RuneSelf { return "", false } if bang { bang = false if r < 'a' || 'z' < r { return "", false } buf = append(buf, byte(r+'A'-'a')) continue } if r == '!' { bang = true continue } if 'A' <= r && r <= 'Z' { return "", false } buf = append(buf, byte(r)) } if bang { return "", false } return string(buf), true }
txtar
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/txtar/archive_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 txtar import ( "bytes" "fmt" "reflect" "testing" ) var tests = []struct { name string text string parsed *Archive }{ { name: "basic", text: `comment1 comment2 -- file1 -- File 1 text. -- foo --- More file 1 text. -- file 2 -- File 2 text. -- empty -- -- noNL -- hello world`, parsed: &Archive{ Comment: []byte("comment1\ncomment2\n"), Files: []File{ {"file1", []byte("File 1 text.\n-- foo ---\nMore file 1 text.\n")}, {"file 2", []byte("File 2 text.\n")}, {"empty", []byte{}}, {"noNL", []byte("hello world\n")}, }, }, }, } func Test(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { a := Parse([]byte(tt.text)) if !reflect.DeepEqual(a, tt.parsed) { t.Fatalf("Parse: wrong output:\nhave:\n%s\nwant:\n%s", shortArchive(a), shortArchive(tt.parsed)) } text := Format(a) a = Parse(text) if !reflect.DeepEqual(a, tt.parsed) { t.Fatalf("Parse after Format: wrong output:\nhave:\n%s\nwant:\n%s", shortArchive(a), shortArchive(tt.parsed)) } }) } } func shortArchive(a *Archive) string { var buf bytes.Buffer fmt.Fprintf(&buf, "comment: %q\n", a.Comment) for _, f := range a.Files { fmt.Fprintf(&buf, "file %q: %q\n", f.Name, f.Data) } return buf.String() }
txtar
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/txtar/archive.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 txtar implements a trivial text-based file archive format. // // The goals for the format are: // // - be trivial enough to create and edit by hand. // - be able to store trees of text files describing go command test cases. // - diff nicely in git history and code reviews. // // Non-goals include being a completely general archive format, // storing binary data, storing file modes, storing special files like // symbolic links, and so on. // // Txtar format // // A txtar archive is zero or more comment lines and then a sequence of file entries. // Each file entry begins with a file marker line of the form "-- FILENAME --" // and is followed by zero or more file content lines making up the file data. // The comment or file content ends at the next file marker line. // The file marker line must begin with the three-byte sequence "-- " // and end with the three-byte sequence " --", but the enclosed // file name can be surrounding by additional white space, // all of which is stripped. // // If the txtar file is missing a trailing newline on the final line, // parsers should consider a final newline to be present anyway. // // There are no possible syntax errors in a txtar archive. package txtar import ( "bytes" "fmt" "io/ioutil" "strings" ) // An Archive is a collection of files. type Archive struct { Comment []byte Files []File } // A File is a single file in an archive. type File struct { Name string // name of file ("foo/bar.txt") Data []byte // text content of file } // Format returns the serialized form of an Archive. // It is assumed that the Archive data structure is well-formed: // a.Comment and all a.File[i].Data contain no file marker lines, // and all a.File[i].Name is non-empty. func Format(a *Archive) []byte { var buf bytes.Buffer buf.Write(fixNL(a.Comment)) for _, f := range a.Files { fmt.Fprintf(&buf, "-- %s --\n", f.Name) buf.Write(fixNL(f.Data)) } return buf.Bytes() } // ParseFile parses the named file as an archive. func ParseFile(file string) (*Archive, error) { data, err := ioutil.ReadFile(file) if err != nil { return nil, err } return Parse(data), nil } // Parse parses the serialized form of an Archive. // The returned Archive holds slices of data. func Parse(data []byte) *Archive { a := new(Archive) var name string a.Comment, name, data = findFileMarker(data) for name != "" { f := File{name, nil} f.Data, name, data = findFileMarker(data) a.Files = append(a.Files, f) } return a } var ( newlineMarker = []byte("\n-- ") marker = []byte("-- ") markerEnd = []byte(" --") ) // findFileMarker finds the next file marker in data, // extracts the file name, and returns the data before the marker, // the file name, and the data after the marker. // If there is no next marker, findFileMarker returns before = fixNL(data), name = "", after = nil. func findFileMarker(data []byte) (before []byte, name string, after []byte) { var i int for { if name, after = isMarker(data[i:]); name != "" { return data[:i], name, after } j := bytes.Index(data[i:], newlineMarker) if j < 0 { return fixNL(data), "", nil } i += j + 1 // positioned at start of new possible marker } } // isMarker checks whether data begins with a file marker line. // If so, it returns the name from the line and the data after the line. // Otherwise it returns name == "" with an unspecified after. func isMarker(data []byte) (name string, after []byte) { if !bytes.HasPrefix(data, marker) { return "", nil } if i := bytes.IndexByte(data, '\n'); i >= 0 { data, after = data[:i], data[i+1:] } if !bytes.HasSuffix(data, markerEnd) { return "", nil } return strings.TrimSpace(string(data[len(marker) : len(data)-len(markerEnd)])), after } // If data is empty or ends in \n, fixNL returns data. // Otherwise fixNL returns a new slice consisting of data with a final \n added. func fixNL(data []byte) []byte { if len(data) == 0 || data[len(data)-1] == '\n' { return data } d := make([]byte, len(data)+1) copy(d, data) d[len(data)] = '\n' return d }
web2
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/web2/web_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 web2 import ( "reflect" "testing" ) var testNetrc = ` machine api.github.com login user password pwd machine incomlete.host login justlogin machine test.host login user2 password pwd2 ` func TestReadNetrc(t *testing.T) { lines := parseNetrc(testNetrc) want := []netrcLine{ {"api.github.com", "user", "pwd"}, {"test.host", "user2", "pwd2"}, } if !reflect.DeepEqual(lines, want) { t.Errorf("parseNetrc:\nhave %q\nwant %q", lines, want) } }
web2
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/web2/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. package web2 import ( "bytes" "cmd/go/internal/base" "encoding/json" "flag" "fmt" "io" "io/ioutil" "net/http" "os" "path/filepath" "runtime" "runtime/debug" "strings" "sync" ) var TraceGET = false var webstack = false func init() { flag.BoolVar(&TraceGET, "webtrace", TraceGET, "trace GET requests") flag.BoolVar(&webstack, "webstack", webstack, "print stack for GET requests") } type netrcLine struct { machine string login string password string } var netrcOnce sync.Once var netrc []netrcLine func parseNetrc(data string) []netrcLine { var nrc []netrcLine var l netrcLine for _, line := range strings.Split(data, "\n") { f := strings.Fields(line) for i := 0; i < len(f)-1; i += 2 { switch f[i] { case "machine": l.machine = f[i+1] case "login": l.login = f[i+1] case "password": l.password = f[i+1] } } if l.machine != "" && l.login != "" && l.password != "" { nrc = append(nrc, l) l = netrcLine{} } } return nrc } func havePassword(machine string) bool { netrcOnce.Do(readNetrc) for _, line := range netrc { if line.machine == machine { return true } } return false } func netrcPath() string { switch runtime.GOOS { case "windows": return filepath.Join(os.Getenv("USERPROFILE"), "_netrc") case "plan9": return filepath.Join(os.Getenv("home"), ".netrc") default: return filepath.Join(os.Getenv("HOME"), ".netrc") } } func readNetrc() { data, err := ioutil.ReadFile(netrcPath()) if err != nil { return } netrc = parseNetrc(string(data)) } type getState struct { req *http.Request resp *http.Response body io.ReadCloser non200ok bool } type Option interface { option(*getState) error } func Non200OK() Option { return optionFunc(func(g *getState) error { g.non200ok = true return nil }) } type optionFunc func(*getState) error func (f optionFunc) option(g *getState) error { return f(g) } func DecodeJSON(dst interface{}) Option { return optionFunc(func(g *getState) error { if g.resp != nil { return json.NewDecoder(g.body).Decode(dst) } return nil }) } func ReadAllBody(body *[]byte) Option { return optionFunc(func(g *getState) error { if g.resp != nil { var err error *body, err = ioutil.ReadAll(g.body) return err } return nil }) } func Body(body *io.ReadCloser) Option { return optionFunc(func(g *getState) error { if g.resp != nil { *body = g.body g.body = nil } return nil }) } func Header(hdr *http.Header) Option { return optionFunc(func(g *getState) error { if g.resp != nil { *hdr = CopyHeader(g.resp.Header) } return nil }) } func CopyHeader(hdr http.Header) http.Header { if hdr == nil { return nil } h2 := make(http.Header) for k, v := range hdr { v2 := make([]string, len(v)) copy(v2, v) h2[k] = v2 } return h2 } var cache struct { mu sync.Mutex byURL map[string]*cacheEntry } type cacheEntry struct { mu sync.Mutex resp *http.Response body []byte } var httpDo = http.DefaultClient.Do func SetHTTPDoForTesting(do func(*http.Request) (*http.Response, error)) { if do == nil { do = http.DefaultClient.Do } httpDo = do } func Get(url string, options ...Option) error { if TraceGET || webstack { println("GET", url) if webstack { println(string(debug.Stack())) } } req, err := http.NewRequest("GET", url, nil) if err != nil { return err } netrcOnce.Do(readNetrc) for _, l := range netrc { if l.machine == req.URL.Host { req.SetBasicAuth(l.login, l.password) break } } g := &getState{req: req} for _, o := range options { if err := o.option(g); err != nil { return err } } cache.mu.Lock() e := cache.byURL[url] if e == nil { e = new(cacheEntry) if !strings.HasPrefix(url, "file:") { if cache.byURL == nil { cache.byURL = make(map[string]*cacheEntry) } cache.byURL[url] = e } } cache.mu.Unlock() e.mu.Lock() if strings.HasPrefix(url, "file:") { body, err := ioutil.ReadFile(req.URL.Path) if err != nil { e.mu.Unlock() return err } e.body = body e.resp = &http.Response{ StatusCode: 200, } } else if e.resp == nil { resp, err := httpDo(req) if err != nil { e.mu.Unlock() return err } e.resp = resp // TODO: Spool to temp file. body, err := ioutil.ReadAll(resp.Body) resp.Body.Close() resp.Body = nil if err != nil { e.mu.Unlock() return err } e.body = body } g.resp = e.resp g.body = ioutil.NopCloser(bytes.NewReader(e.body)) e.mu.Unlock() defer func() { if g.body != nil { g.body.Close() } }() if g.resp.StatusCode == 403 && req.URL.Host == "api.github.com" && !havePassword("api.github.com") { base.Errorf("%s", githubMessage) } if !g.non200ok && g.resp.StatusCode != 200 { return fmt.Errorf("unexpected status (%s): %v", url, g.resp.Status) } for _, o := range options { if err := o.option(g); err != nil { return err } } return err } var githubMessage = `go: 403 response from api.github.com GitHub applies fairly small rate limits to unauthenticated users, and you appear to be hitting them. To authenticate, please visit https://github.com/settings/tokens and click "Generate New Token" to create a Personal Access Token. The token only needs "public_repo" scope, but you can add "repo" if you want to access private repositories too. Add the token to your $HOME/.netrc (%USERPROFILE%\_netrc on Windows): machine api.github.com login YOU password TOKEN Sorry for the interruption. `
fmtcmd
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/fmtcmd/fmt.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 fmtcmd implements the ``go fmt'' command. package fmtcmd import ( "fmt" "os" "path/filepath" "runtime" "strings" "sync" "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/load" "cmd/go/internal/modload" "cmd/go/internal/str" ) func init() { base.AddBuildFlagsNX(&CmdFmt.Flag) } var CmdFmt = &base.Command{ Run: runFmt, UsageLine: "go fmt [-n] [-x] [packages]", Short: "gofmt (reformat) package sources", Long: ` Fmt runs the command 'gofmt -l -w' on the packages named by the import paths. It prints the names of the files that are modified. For more about gofmt, see 'go doc cmd/gofmt'. For more about specifying packages, see 'go help packages'. The -n flag prints commands that would be executed. The -x flag prints commands as they are executed. To run gofmt with specific options, run gofmt itself. See also: go fix, go vet. `, } func runFmt(cmd *base.Command, args []string) { printed := false gofmt := gofmtPath() procs := runtime.GOMAXPROCS(0) var wg sync.WaitGroup wg.Add(procs) fileC := make(chan string, 2*procs) for i := 0; i < procs; i++ { go func() { defer wg.Done() for file := range fileC { base.Run(str.StringList(gofmt, "-l", "-w", file)) } }() } for _, pkg := range load.PackagesAndErrors(args) { if modload.Enabled() && pkg.Module != nil && !pkg.Module.Main { if !printed { fmt.Fprintf(os.Stderr, "go: not formatting packages in dependency modules\n") printed = true } continue } if pkg.Error != nil { if strings.HasPrefix(pkg.Error.Err, "build constraints exclude all Go files") { // Skip this error, as we will format // all files regardless. } else { base.Errorf("can't load package: %s", pkg.Error) continue } } // Use pkg.gofiles instead of pkg.Dir so that // the command only applies to this package, // not to packages in subdirectories. files := base.RelPaths(pkg.InternalAllGoFiles()) for _, file := range files { fileC <- file } } close(fileC) wg.Wait() } func gofmtPath() string { gofmt := "gofmt" if base.ToolIsWindows { gofmt += base.ToolWindowsExtension } gofmtPath := filepath.Join(cfg.GOBIN, gofmt) if _, err := os.Stat(gofmtPath); err == nil { return gofmtPath } gofmtPath = filepath.Join(cfg.GOROOT, "bin", gofmt) if _, err := os.Stat(gofmtPath); err == nil { return gofmtPath } // fallback to looking for gofmt in $PATH return "gofmt" }
str
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/str/path.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 str import ( "path/filepath" "strings" ) // HasPath reports whether the slash-separated path s // begins with the elements in prefix. func HasPathPrefix(s, prefix string) bool { if len(s) == len(prefix) { return s == prefix } if prefix == "" { return true } if len(s) > len(prefix) { if prefix[len(prefix)-1] == '/' || s[len(prefix)] == '/' { return s[:len(prefix)] == prefix } } return false } // HasFilePathPrefix reports whether the filesystem path s // begins with the elements in prefix. func HasFilePathPrefix(s, prefix string) bool { sv := strings.ToUpper(filepath.VolumeName(s)) pv := strings.ToUpper(filepath.VolumeName(prefix)) s = s[len(sv):] prefix = prefix[len(pv):] switch { default: return false case sv != pv: return false case len(s) == len(prefix): return s == prefix case prefix == "": return true case len(s) > len(prefix): if prefix[len(prefix)-1] == filepath.Separator { return strings.HasPrefix(s, prefix) } return s[len(prefix)] == filepath.Separator && s[:len(prefix)] == prefix } }
str
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/str/str.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 str provides string manipulation utilities. package str import ( "bytes" "fmt" "unicode" "unicode/utf8" ) // StringList flattens its arguments into a single []string. // Each argument in args must have type string or []string. func StringList(args ...interface{}) []string { var x []string for _, arg := range args { switch arg := arg.(type) { case []string: x = append(x, arg...) case string: x = append(x, arg) default: panic("stringList: invalid argument of type " + fmt.Sprintf("%T", arg)) } } return x } // ToFold returns a string with the property that // strings.EqualFold(s, t) iff ToFold(s) == ToFold(t) // This lets us test a large set of strings for fold-equivalent // duplicates without making a quadratic number of calls // to EqualFold. Note that strings.ToUpper and strings.ToLower // do not have the desired property in some corner cases. func ToFold(s string) string { // Fast path: all ASCII, no upper case. // Most paths look like this already. for i := 0; i < len(s); i++ { c := s[i] if c >= utf8.RuneSelf || 'A' <= c && c <= 'Z' { goto Slow } } return s Slow: var buf bytes.Buffer for _, r := range s { // SimpleFold(x) cycles to the next equivalent rune > x // or wraps around to smaller values. Iterate until it wraps, // and we've found the minimum value. for { r0 := r r = unicode.SimpleFold(r0) if r <= r0 { break } } // Exception to allow fast path above: A-Z => a-z if 'A' <= r && r <= 'Z' { r += 'a' - 'A' } buf.WriteRune(r) } return buf.String() } // FoldDup reports a pair of strings from the list that are // equal according to strings.EqualFold. // It returns "", "" if there are no such strings. func FoldDup(list []string) (string, string) { clash := map[string]string{} for _, s := range list { fold := ToFold(s) if t := clash[fold]; t != "" { if s > t { s, t = t, s } return s, t } clash[fold] = s } return "", "" } // Contains reports whether x contains s. func Contains(x []string, s string) bool { for _, t := range x { if t == s { return true } } return false } func isSpaceByte(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' } // SplitQuotedFields splits s into a list of fields, // allowing single or double quotes around elements. // There is no unescaping or other processing within // quoted fields. func SplitQuotedFields(s string) ([]string, error) { // Split fields allowing '' or "" around elements. // Quotes further inside the string do not count. var f []string for len(s) > 0 { for len(s) > 0 && isSpaceByte(s[0]) { s = s[1:] } if len(s) == 0 { break } // Accepted quoted string. No unescaping inside. if s[0] == '"' || s[0] == '\'' { quote := s[0] s = s[1:] i := 0 for i < len(s) && s[i] != quote { i++ } if i >= len(s) { return nil, fmt.Errorf("unterminated %c string", quote) } f = append(f, s[:i]) s = s[i+1:] continue } i := 0 for i < len(s) && !isSpaceByte(s[i]) { i++ } f = append(f, s[:i]) s = s[i:] } return f, nil }
generate
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/generate/generate.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 generate implements the ``go generate'' command. package generate import ( "bufio" "bytes" "fmt" "io" "log" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/load" "cmd/go/internal/modload" "cmd/go/internal/work" ) var CmdGenerate = &base.Command{ Run: runGenerate, UsageLine: "go generate [-run regexp] [-n] [-v] [-x] [build flags] [file.go... | packages]", Short: "generate Go files by processing source", Long: ` Generate runs commands described by directives within existing files. Those commands can run any process but the intent is to create or update Go source files. Go generate is never run automatically by go build, go get, go test, and so on. It must be run explicitly. Go generate scans the file for directives, which are lines of the form, //go:generate command argument... (note: no leading spaces and no space in "//go") where command is the generator to be run, corresponding to an executable file that can be run locally. It must either be in the shell path (gofmt), a fully qualified path (/usr/you/bin/mytool), or a command alias, described below. To convey to humans and machine tools that code is generated, generated source should have a line early in the file that matches the following regular expression (in Go syntax): ^// Code generated .* DO NOT EDIT\.$ Note that go generate does not parse the file, so lines that look like directives in comments or multiline strings will be treated as directives. The arguments to the directive are space-separated tokens or double-quoted strings passed to the generator as individual arguments when it is run. Quoted strings use Go syntax and are evaluated before execution; a quoted string appears as a single argument to the generator. Go generate sets several variables when it runs the generator: $GOARCH The execution architecture (arm, amd64, etc.) $GOOS The execution operating system (linux, windows, etc.) $GOFILE The base name of the file. $GOLINE The line number of the directive in the source file. $GOPACKAGE The name of the package of the file containing the directive. $DOLLAR A dollar sign. Other than variable substitution and quoted-string evaluation, no special processing such as "globbing" is performed on the command line. As a last step before running the command, any invocations of any environment variables with alphanumeric names, such as $GOFILE or $HOME, are expanded throughout the command line. The syntax for variable expansion is $NAME on all operating systems. Due to the order of evaluation, variables are expanded even inside quoted strings. If the variable NAME is not set, $NAME expands to the empty string. A directive of the form, //go:generate -command xxx args... specifies, for the remainder of this source file only, that the string xxx represents the command identified by the arguments. This can be used to create aliases or to handle multiword generators. For example, //go:generate -command foo go tool foo specifies that the command "foo" represents the generator "go tool foo". Generate processes packages in the order given on the command line, one at a time. If the command line lists .go files, they are treated as a single package. Within a package, generate processes the source files in a package in file name order, one at a time. Within a source file, generate runs generators in the order they appear in the file, one at a time. If any generator returns an error exit status, "go generate" skips all further processing for that package. The generator is run in the package's source directory. Go generate accepts one specific flag: -run="" if non-empty, specifies a regular expression to select directives whose full original source text (excluding any trailing spaces and final newline) matches the expression. It also accepts the standard build flags including -v, -n, and -x. The -v flag prints the names of packages and files as they are processed. The -n flag prints commands that would be executed. The -x flag prints commands as they are executed. For more about build flags, see 'go help build'. For more about specifying packages, see 'go help packages'. `, } var ( generateRunFlag string // generate -run flag generateRunRE *regexp.Regexp // compiled expression for -run ) func init() { work.AddBuildFlags(CmdGenerate) CmdGenerate.Flag.StringVar(&generateRunFlag, "run", "", "") } func runGenerate(cmd *base.Command, args []string) { load.IgnoreImports = true if generateRunFlag != "" { var err error generateRunRE, err = regexp.Compile(generateRunFlag) if err != nil { log.Fatalf("generate: %s", err) } } // Even if the arguments are .go files, this loop suffices. printed := false for _, pkg := range load.Packages(args) { if modload.Enabled() && !pkg.Module.Main { if !printed { fmt.Fprintf(os.Stderr, "go: not generating in packages in dependency modules\n") printed = true } continue } pkgName := pkg.Name for _, file := range pkg.InternalGoFiles() { if !generate(pkgName, file) { break } } pkgName += "_test" for _, file := range pkg.InternalXGoFiles() { if !generate(pkgName, file) { break } } } } // generate runs the generation directives for a single file. func generate(pkg, absFile string) bool { fd, err := os.Open(absFile) if err != nil { log.Fatalf("generate: %s", err) } defer fd.Close() g := &Generator{ r: fd, path: absFile, pkg: pkg, commands: make(map[string][]string), } return g.run() } // A Generator represents the state of a single Go source file // being scanned for generator commands. type Generator struct { r io.Reader path string // full rooted path name. dir string // full rooted directory of file. file string // base name of file. pkg string commands map[string][]string lineNum int // current line number. env []string } // run runs the generators in the current file. func (g *Generator) run() (ok bool) { // Processing below here calls g.errorf on failure, which does panic(stop). // If we encounter an error, we abort the package. defer func() { e := recover() if e != nil { ok = false if e != stop { panic(e) } base.SetExitStatus(1) } }() g.dir, g.file = filepath.Split(g.path) g.dir = filepath.Clean(g.dir) // No final separator please. if cfg.BuildV { fmt.Fprintf(os.Stderr, "%s\n", base.ShortPath(g.path)) } // Scan for lines that start "//go:generate". // Can't use bufio.Scanner because it can't handle long lines, // which are likely to appear when using generate. input := bufio.NewReader(g.r) var err error // One line per loop. for { g.lineNum++ // 1-indexed. var buf []byte buf, err = input.ReadSlice('\n') if err == bufio.ErrBufferFull { // Line too long - consume and ignore. if isGoGenerate(buf) { g.errorf("directive too long") } for err == bufio.ErrBufferFull { _, err = input.ReadSlice('\n') } if err != nil { break } continue } if err != nil { // Check for marker at EOF without final \n. if err == io.EOF && isGoGenerate(buf) { err = io.ErrUnexpectedEOF } break } if !isGoGenerate(buf) { continue } if generateRunFlag != "" { if !generateRunRE.Match(bytes.TrimSpace(buf)) { continue } } g.setEnv() words := g.split(string(buf)) if len(words) == 0 { g.errorf("no arguments to directive") } if words[0] == "-command" { g.setShorthand(words) continue } // Run the command line. if cfg.BuildN || cfg.BuildX { fmt.Fprintf(os.Stderr, "%s\n", strings.Join(words, " ")) } if cfg.BuildN { continue } g.exec(words) } if err != nil && err != io.EOF { g.errorf("error reading %s: %s", base.ShortPath(g.path), err) } return true } func isGoGenerate(buf []byte) bool { return bytes.HasPrefix(buf, []byte("//go:generate ")) || bytes.HasPrefix(buf, []byte("//go:generate\t")) } // setEnv sets the extra environment variables used when executing a // single go:generate command. func (g *Generator) setEnv() { g.env = []string{ "GOARCH=" + cfg.BuildContext.GOARCH, "GOOS=" + cfg.BuildContext.GOOS, "GOFILE=" + g.file, "GOLINE=" + strconv.Itoa(g.lineNum), "GOPACKAGE=" + g.pkg, "DOLLAR=" + "$", } } // split breaks the line into words, evaluating quoted // strings and evaluating environment variables. // The initial //go:generate element is present in line. func (g *Generator) split(line string) []string { // Parse line, obeying quoted strings. var words []string line = line[len("//go:generate ") : len(line)-1] // Drop preamble and final newline. // There may still be a carriage return. if len(line) > 0 && line[len(line)-1] == '\r' { line = line[:len(line)-1] } // One (possibly quoted) word per iteration. Words: for { line = strings.TrimLeft(line, " \t") if len(line) == 0 { break } if line[0] == '"' { for i := 1; i < len(line); i++ { c := line[i] // Only looking for ASCII so this is OK. switch c { case '\\': if i+1 == len(line) { g.errorf("bad backslash") } i++ // Absorb next byte (If it's a multibyte we'll get an error in Unquote). case '"': word, err := strconv.Unquote(line[0 : i+1]) if err != nil { g.errorf("bad quoted string") } words = append(words, word) line = line[i+1:] // Check the next character is space or end of line. if len(line) > 0 && line[0] != ' ' && line[0] != '\t' { g.errorf("expect space after quoted argument") } continue Words } } g.errorf("mismatched quoted string") } i := strings.IndexAny(line, " \t") if i < 0 { i = len(line) } words = append(words, line[0:i]) line = line[i:] } // Substitute command if required. if len(words) > 0 && g.commands[words[0]] != nil { // Replace 0th word by command substitution. words = append(g.commands[words[0]], words[1:]...) } // Substitute environment variables. for i, word := range words { words[i] = os.Expand(word, g.expandVar) } return words } var stop = fmt.Errorf("error in generation") // errorf logs an error message prefixed with the file and line number. // It then exits the program (with exit status 1) because generation stops // at the first error. func (g *Generator) errorf(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, "%s:%d: %s\n", base.ShortPath(g.path), g.lineNum, fmt.Sprintf(format, args...)) panic(stop) } // expandVar expands the $XXX invocation in word. It is called // by os.Expand. func (g *Generator) expandVar(word string) string { w := word + "=" for _, e := range g.env { if strings.HasPrefix(e, w) { return e[len(w):] } } return os.Getenv(word) } // setShorthand installs a new shorthand as defined by a -command directive. func (g *Generator) setShorthand(words []string) { // Create command shorthand. if len(words) == 1 { g.errorf("no command specified for -command") } command := words[1] if g.commands[command] != nil { g.errorf("command %q multiply defined", command) } g.commands[command] = words[2:len(words):len(words)] // force later append to make copy } // exec runs the command specified by the argument. The first word is // the command name itself. func (g *Generator) exec(words []string) { cmd := exec.Command(words[0], words[1:]...) // Standard in and out of generator should be the usual. cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr // Run the command in the package directory. cmd.Dir = g.dir cmd.Env = base.MergeEnvLists(g.env, cfg.OrigEnv) err := cmd.Run() if err != nil { g.errorf("running %q: %s", words[0], err) } }
generate
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/generate/generate_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 generate import ( "reflect" "runtime" "testing" ) type splitTest struct { in string out []string } var splitTests = []splitTest{ {"", nil}, {"x", []string{"x"}}, {" a b\tc ", []string{"a", "b", "c"}}, {` " a " `, []string{" a "}}, {"$GOARCH", []string{runtime.GOARCH}}, {"$GOOS", []string{runtime.GOOS}}, {"$GOFILE", []string{"proc.go"}}, {"$GOPACKAGE", []string{"sys"}}, {"a $XXNOTDEFINEDXX b", []string{"a", "", "b"}}, {"/$XXNOTDEFINED/", []string{"//"}}, {"/$DOLLAR/", []string{"/$/"}}, {"yacc -o $GOARCH/yacc_$GOFILE", []string{"go", "tool", "yacc", "-o", runtime.GOARCH + "/yacc_proc.go"}}, } func TestGenerateCommandParse(t *testing.T) { g := &Generator{ r: nil, // Unused here. path: "/usr/ken/sys/proc.go", dir: "/usr/ken/sys", file: "proc.go", pkg: "sys", commands: make(map[string][]string), } g.setEnv() g.setShorthand([]string{"-command", "yacc", "go", "tool", "yacc"}) for _, test := range splitTests { // First with newlines. got := g.split("//go:generate " + test.in + "\n") if !reflect.DeepEqual(got, test.out) { t.Errorf("split(%q): got %q expected %q", test.in, got, test.out) } // Then with CRLFs, thank you Windows. got = g.split("//go:generate " + test.in + "\r\n") if !reflect.DeepEqual(got, test.out) { t.Errorf("split(%q): got %q expected %q", test.in, got, test.out) } } }
modconv
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/dep.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 modconv import ( "fmt" "strconv" "strings" "cmd/go/internal/modfile" "cmd/go/internal/module" "cmd/go/internal/semver" ) func ParseGopkgLock(file string, data []byte) (*modfile.File, error) { mf := new(modfile.File) var list []module.Version var r *module.Version for lineno, line := range strings.Split(string(data), "\n") { lineno++ if i := strings.Index(line, "#"); i >= 0 { line = line[:i] } line = strings.TrimSpace(line) if line == "[[projects]]" { list = append(list, module.Version{}) r = &list[len(list)-1] continue } if strings.HasPrefix(line, "[") { r = nil continue } if r == nil { continue } i := strings.Index(line, "=") if i < 0 { continue } key := strings.TrimSpace(line[:i]) val := strings.TrimSpace(line[i+1:]) if len(val) >= 2 && val[0] == '"' && val[len(val)-1] == '"' { q, err := strconv.Unquote(val) // Go unquoting, but close enough for now if err != nil { return nil, fmt.Errorf("%s:%d: invalid quoted string: %v", file, lineno, err) } val = q } switch key { case "name": r.Path = val case "revision", "version": // Note: key "version" should take priority over "revision", // and it does, because dep writes toml keys in alphabetical order, // so we see version (if present) second. if key == "version" { if !semver.IsValid(val) || semver.Canonical(val) != val { break } } r.Version = val } } for _, r := range list { if r.Path == "" || r.Version == "" { return nil, fmt.Errorf("%s: empty [[projects]] stanza (%s)", file, r.Path) } mf.Require = append(mf.Require, &modfile.Require{Mod: r}) } return mf, nil }
modconv
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/glock.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 modconv import ( "strings" "cmd/go/internal/modfile" "cmd/go/internal/module" ) func ParseGLOCKFILE(file string, data []byte) (*modfile.File, error) { mf := new(modfile.File) for lineno, line := range strings.Split(string(data), "\n") { lineno++ f := strings.Fields(line) if len(f) >= 2 && f[0] != "cmd" { mf.Require = append(mf.Require, &modfile.Require{Mod: module.Version{Path: f[0], Version: f[1]}}) } } return mf, nil }
modconv
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/modconv.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 modconv import "cmd/go/internal/modfile" var Converters = map[string]func(string, []byte) (*modfile.File, error){ "GLOCKFILE": ParseGLOCKFILE, "Godeps/Godeps.json": ParseGodepsJSON, "Gopkg.lock": ParseGopkgLock, "dependencies.tsv": ParseDependenciesTSV, "glide.lock": ParseGlideLock, "vendor.conf": ParseVendorConf, "vendor.yml": ParseVendorYML, "vendor/manifest": ParseVendorManifest, "vendor/vendor.json": ParseVendorJSON, }
modconv
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/vjson.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 modconv import ( "encoding/json" "cmd/go/internal/modfile" "cmd/go/internal/module" ) func ParseVendorJSON(file string, data []byte) (*modfile.File, error) { var cfg struct { Package []struct { Path string Revision string } } if err := json.Unmarshal(data, &cfg); err != nil { return nil, err } mf := new(modfile.File) for _, d := range cfg.Package { mf.Require = append(mf.Require, &modfile.Require{Mod: module.Version{Path: d.Path, Version: d.Revision}}) } return mf, nil }
modconv
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/convert_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 modconv import ( "bytes" "fmt" "internal/testenv" "io/ioutil" "log" "os" "os/exec" "path/filepath" "strings" "testing" "cmd/go/internal/cfg" "cmd/go/internal/modfetch" "cmd/go/internal/modfetch/codehost" "cmd/go/internal/modfile" "cmd/go/internal/module" ) func TestMain(m *testing.M) { os.Exit(testMain(m)) } 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("", "modconv-test-") if err != nil { log.Fatal(err) } defer os.RemoveAll(dir) modfetch.PkgMod = filepath.Join(dir, "pkg/mod") codehost.WorkRoot = filepath.Join(dir, "codework") return m.Run() } func TestConvertLegacyConfig(t *testing.T) { testenv.MustHaveExternalNetwork(t) if testing.Verbose() { old := cfg.BuildX defer func() { cfg.BuildX = old }() cfg.BuildX = true } var tests = []struct { path string vers string gomod string }{ /* Different versions of git seem to find or not find github.com/Masterminds/semver's a93e51b5a57e, which is an unmerged pull request. We'd rather not provide access to unmerged pull requests, so the line is removed from the golden file here, but some git commands still find it somehow. { // Gopkg.lock parsing. "github.com/golang/dep", "v0.4.0", `module github.com/golang/dep require ( github.com/Masterminds/vcs v1.11.1 github.com/armon/go-radix v0.0.0-20160115234725-4239b77079c7 github.com/boltdb/bolt v1.3.1 github.com/go-yaml/yaml v0.0.0-20170407172122-cd8b52f8269e github.com/golang/protobuf v0.0.0-20170901042739-5afd06f9d81a github.com/jmank88/nuts v0.3.0 github.com/nightlyone/lockfile v0.0.0-20170707060451-e83dc5e7bba0 github.com/pelletier/go-toml v0.0.0-20171218135716-b8b5e7696574 github.com/pkg/errors v0.8.0 github.com/sdboyer/constext v0.0.0-20170321163424-836a14457353 golang.org/x/net v0.0.0-20170828231752-66aacef3dd8a golang.org/x/sync v0.0.0-20170517211232-f52d1811a629 golang.org/x/sys v0.0.0-20170830134202-bb24a47a89ea )`, }, */ // TODO: https://github.com/docker/distribution uses vendor.conf { // Godeps.json parsing. // TODO: Should v2.0.0 work here too? "github.com/docker/distribution", "v0.0.0-20150410205453-85de3967aa93", `module github.com/docker/distribution require ( github.com/AdRoll/goamz v0.0.0-20150130162828-d3664b76d905 github.com/MSOpenTech/azure-sdk-for-go v0.0.0-20150323223030-d90753bcad2e github.com/Sirupsen/logrus v0.7.3 github.com/bugsnag/bugsnag-go v0.0.0-20141110184014-b1d153021fcd github.com/bugsnag/osext v0.0.0-20130617224835-0dd3f918b21b github.com/bugsnag/panicwrap v0.0.0-20141110184334-e5f9854865b9 github.com/codegangsta/cli v0.0.0-20150131031259-6086d7927ec3 github.com/docker/docker v0.0.0-20150204013315-165ea5c158cf github.com/docker/libtrust v0.0.0-20150114040149-fa567046d9b1 github.com/garyburd/redigo v0.0.0-20150301180006-535138d7bcd7 github.com/gorilla/context v0.0.0-20140604161150-14f550f51af5 github.com/gorilla/handlers v0.0.0-20140825150757-0e84b7d810c1 github.com/gorilla/mux v0.0.0-20140926153814-e444e69cbd2e github.com/jlhawn/go-crypto v0.0.0-20150401213827-cd738dde20f0 github.com/yvasiyarov/go-metrics v0.0.0-20140926110328-57bccd1ccd43 github.com/yvasiyarov/gorelic v0.0.0-20141212073537-a9bba5b9ab50 github.com/yvasiyarov/newrelic_platform_go v0.0.0-20140908184405-b21fdbd4370f golang.org/x/net v0.0.0-20150202051010-1dfe7915deaf gopkg.in/check.v1 v1.0.0-20141024133853-64131543e789 gopkg.in/yaml.v2 v2.0.0-20150116202057-bef53efd0c76 )`, }, { // golang.org/issue/24585 - confusion about v2.0.0 tag in legacy non-v2 module "github.com/fishy/gcsbucket", "v0.0.0-20150410205453-618d60fe84e0", `module github.com/fishy/gcsbucket require ( cloud.google.com/go v0.18.0 github.com/fishy/fsdb v0.0.0-20180217030800-5527ded01371 github.com/golang/protobuf v1.0.0 github.com/googleapis/gax-go v2.0.0+incompatible golang.org/x/net v0.0.0-20180216171745-136a25c244d3 golang.org/x/oauth2 v0.0.0-20180207181906-543e37812f10 golang.org/x/text v0.0.0-20180208041248-4e4a3210bb54 google.golang.org/api v0.0.0-20180217000815-c7a403bb5fe1 google.golang.org/appengine v1.0.0 google.golang.org/genproto v0.0.0-20180206005123-2b5a72b8730b google.golang.org/grpc v1.10.0 )`, }, } for _, tt := range tests { t.Run(strings.Replace(tt.path, "/", "_", -1)+"_"+tt.vers, func(t *testing.T) { f, err := modfile.Parse("golden", []byte(tt.gomod), nil) if err != nil { t.Fatal(err) } want, err := f.Format() if err != nil { t.Fatal(err) } dir, err := modfetch.Download(module.Version{Path: tt.path, Version: tt.vers}) if err != nil { t.Fatal(err) } for name := range Converters { file := filepath.Join(dir, name) data, err := ioutil.ReadFile(file) if err == nil { f := new(modfile.File) f.AddModuleStmt(tt.path) if err := ConvertLegacyConfig(f, filepath.ToSlash(file), data); err != nil { t.Fatal(err) } out, err := f.Format() if err != nil { t.Fatalf("format after conversion: %v", err) } if !bytes.Equal(out, want) { t.Fatalf("final go.mod:\n%s\n\nwant:\n%s", out, want) } return } } t.Fatalf("no converter found for %s@%s", tt.path, tt.vers) }) } }
modconv
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/tsv.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 modconv import ( "strings" "cmd/go/internal/modfile" "cmd/go/internal/module" ) func ParseDependenciesTSV(file string, data []byte) (*modfile.File, error) { mf := new(modfile.File) for lineno, line := range strings.Split(string(data), "\n") { lineno++ f := strings.Split(line, "\t") if len(f) >= 3 { mf.Require = append(mf.Require, &modfile.Require{Mod: module.Version{Path: f[0], Version: f[2]}}) } } return mf, nil }
modconv
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/convert.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 modconv import ( "fmt" "os" "sort" "strings" "sync" "cmd/go/internal/base" "cmd/go/internal/modfetch" "cmd/go/internal/modfile" "cmd/go/internal/module" "cmd/go/internal/par" "cmd/go/internal/semver" ) // ConvertLegacyConfig converts legacy config to modfile. // The file argument is slash-delimited. func ConvertLegacyConfig(f *modfile.File, file string, data []byte) error { i := strings.LastIndex(file, "/") j := -2 if i >= 0 { j = strings.LastIndex(file[:i], "/") } convert := Converters[file[i+1:]] if convert == nil && j != -2 { convert = Converters[file[j+1:]] } if convert == nil { return fmt.Errorf("unknown legacy config file %s", file) } mf, err := convert(file, data) if err != nil { return fmt.Errorf("parsing %s: %v", file, err) } // Convert requirements block, which may use raw SHA1 hashes as versions, // to valid semver requirement list, respecting major versions. var work par.Work for _, r := range mf.Require { m := r.Mod if m.Path == "" { continue } work.Add(r.Mod) } var ( mu sync.Mutex need = make(map[string]string) ) work.Do(10, func(item interface{}) { r := item.(module.Version) repo, info, err := modfetch.ImportRepoRev(r.Path, r.Version) if err != nil { fmt.Fprintf(os.Stderr, "go: converting %s: stat %s@%s: %v\n", base.ShortPath(file), r.Path, r.Version, err) return } mu.Lock() path := repo.ModulePath() // Don't use semver.Max here; need to preserve +incompatible suffix. if v, ok := need[path]; !ok || semver.Compare(v, info.Version) < 0 { need[path] = info.Version } mu.Unlock() }) var paths []string for path := range need { paths = append(paths, path) } sort.Strings(paths) for _, path := range paths { f.AddNewRequire(path, need[path], false) } for _, r := range mf.Replace { err := f.AddReplace(r.Old.Path, r.Old.Version, r.New.Path, r.New.Version) if err != nil { return fmt.Errorf("add replace: %v", err) } } f.Cleanup() return nil }
modconv
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/vconf.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 modconv import ( "strings" "cmd/go/internal/modfile" "cmd/go/internal/module" ) func ParseVendorConf(file string, data []byte) (*modfile.File, error) { mf := new(modfile.File) for lineno, line := range strings.Split(string(data), "\n") { lineno++ if i := strings.Index(line, "#"); i >= 0 { line = line[:i] } f := strings.Fields(line) if len(f) >= 2 { mf.Require = append(mf.Require, &modfile.Require{Mod: module.Version{Path: f[0], Version: f[1]}}) } } return mf, nil }
modconv
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/vyml.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 modconv import ( "strings" "cmd/go/internal/modfile" "cmd/go/internal/module" ) func ParseVendorYML(file string, data []byte) (*modfile.File, error) { mf := new(modfile.File) vendors := false path := "" for lineno, line := range strings.Split(string(data), "\n") { lineno++ if line == "" { continue } if strings.HasPrefix(line, "vendors:") { vendors = true } else if line[0] != '-' && line[0] != ' ' && line[0] != '\t' { vendors = false } if !vendors { continue } if strings.HasPrefix(line, "- path:") { path = strings.TrimSpace(line[len("- path:"):]) } if strings.HasPrefix(line, " rev:") { rev := strings.TrimSpace(line[len(" rev:"):]) if path != "" && rev != "" { mf.Require = append(mf.Require, &modfile.Require{Mod: module.Version{Path: path, Version: rev}}) } } } return mf, nil }
modconv
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/modconv_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 modconv import ( "bytes" "fmt" "io/ioutil" "path/filepath" "testing" ) var extMap = map[string]string{ ".dep": "Gopkg.lock", ".glide": "glide.lock", ".glock": "GLOCKFILE", ".godeps": "Godeps/Godeps.json", ".tsv": "dependencies.tsv", ".vconf": "vendor.conf", ".vjson": "vendor/vendor.json", ".vyml": "vendor.yml", ".vmanifest": "vendor/manifest", } func Test(t *testing.T) { tests, _ := filepath.Glob("testdata/*") if len(tests) == 0 { t.Fatalf("no tests found") } for _, test := range tests { file := filepath.Base(test) ext := filepath.Ext(file) if ext == ".out" { continue } t.Run(file, func(t *testing.T) { if extMap[ext] == "" { t.Fatal("unknown extension") } if Converters[extMap[ext]] == nil { t.Fatalf("Converters[%q] == nil", extMap[ext]) } data, err := ioutil.ReadFile(test) if err != nil { t.Fatal(err) } out, err := Converters[extMap[ext]](test, data) if err != nil { t.Fatal(err) } want, err := ioutil.ReadFile(test[:len(test)-len(ext)] + ".out") if err != nil { t.Error(err) } var buf bytes.Buffer for _, r := range out.Require { fmt.Fprintf(&buf, "%s %s\n", r.Mod.Path, r.Mod.Version) } if !bytes.Equal(buf.Bytes(), want) { t.Errorf("have:\n%s\nwant:\n%s", buf.Bytes(), want) } }) } }
modconv
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/vmanifest.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 modconv import ( "encoding/json" "cmd/go/internal/modfile" "cmd/go/internal/module" ) func ParseVendorManifest(file string, data []byte) (*modfile.File, error) { var cfg struct { Dependencies []struct { ImportPath string Revision string } } if err := json.Unmarshal(data, &cfg); err != nil { return nil, err } mf := new(modfile.File) for _, d := range cfg.Dependencies { mf.Require = append(mf.Require, &modfile.Require{Mod: module.Version{Path: d.ImportPath, Version: d.Revision}}) } return mf, nil }
modconv
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/glide.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 modconv import ( "strings" "cmd/go/internal/modfile" "cmd/go/internal/module" ) func ParseGlideLock(file string, data []byte) (*modfile.File, error) { mf := new(modfile.File) imports := false name := "" for lineno, line := range strings.Split(string(data), "\n") { lineno++ if line == "" { continue } if strings.HasPrefix(line, "imports:") { imports = true } else if line[0] != '-' && line[0] != ' ' && line[0] != '\t' { imports = false } if !imports { continue } if strings.HasPrefix(line, "- name:") { name = strings.TrimSpace(line[len("- name:"):]) } if strings.HasPrefix(line, " version:") { version := strings.TrimSpace(line[len(" version:"):]) if name != "" && version != "" { mf.Require = append(mf.Require, &modfile.Require{Mod: module.Version{Path: name, Version: version}}) } } } return mf, nil }
modconv
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/godeps.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 modconv import ( "encoding/json" "cmd/go/internal/modfile" "cmd/go/internal/module" ) func ParseGodepsJSON(file string, data []byte) (*modfile.File, error) { var cfg struct { ImportPath string Deps []struct { ImportPath string Rev string } } if err := json.Unmarshal(data, &cfg); err != nil { return nil, err } mf := new(modfile.File) for _, d := range cfg.Deps { mf.Require = append(mf.Require, &modfile.Require{Mod: module.Version{Path: d.ImportPath, Version: d.Rev}}) } return mf, nil }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/dockermachine.godeps
{ "ImportPath": "github.com/docker/machine", "GoVersion": "go1.4.2", "Deps": [ { "ImportPath": "code.google.com/p/goauth2/oauth", "Comment": "weekly-56", "Rev": "afe77d958c701557ec5dc56f6936fcc194d15520" }, { "ImportPath": "github.com/MSOpenTech/azure-sdk-for-go", "Comment": "v1.1-17-g515f3ec", "Rev": "515f3ec74ce6a5b31e934cefae997c97bd0a1b1e" }, { "ImportPath": "github.com/cenkalti/backoff", "Rev": "9831e1e25c874e0a0601b6dc43641071414eec7a" }, { "ImportPath": "github.com/codegangsta/cli", "Comment": "1.2.0-64-ge1712f3", "Rev": "e1712f381785e32046927f64a7c86fe569203196" }, { "ImportPath": "github.com/digitalocean/godo", "Comment": "v0.5.0", "Rev": "5478aae80694de1d2d0e02c386bbedd201266234" }, { "ImportPath": "github.com/docker/docker/dockerversion", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/docker/engine", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/docker/pkg/archive", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/docker/pkg/fileutils", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/docker/pkg/ioutils", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/docker/pkg/mflag", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/docker/pkg/parsers", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/docker/pkg/pools", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/docker/pkg/promise", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/docker/pkg/system", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/docker/pkg/term", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/docker/pkg/timeutils", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/docker/pkg/units", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/docker/pkg/version", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar", "Comment": "v1.5.0", "Rev": "a8a31eff10544860d2188dddabdee4d727545796" }, { "ImportPath": "github.com/docker/libtrust", "Rev": "c54fbb67c1f1e68d7d6f8d2ad7c9360404616a41" }, { "ImportPath": "github.com/google/go-querystring/query", "Rev": "30f7a39f4a218feb5325f3aebc60c32a572a8274" }, { "ImportPath": "github.com/mitchellh/mapstructure", "Rev": "740c764bc6149d3f1806231418adb9f52c11bcbf" }, { "ImportPath": "github.com/rackspace/gophercloud", "Comment": "v1.0.0-558-ce0f487", "Rev": "ce0f487f6747ab43c4e4404722df25349385bebd" }, { "ImportPath": "github.com/skarademir/naturalsort", "Rev": "983d4d86054d80f91fd04dd62ec52c1d078ce403" }, { "ImportPath": "github.com/smartystreets/go-aws-auth", "Rev": "1f0db8c0ee6362470abe06a94e3385927ed72a4b" }, { "ImportPath": "github.com/stretchr/testify/assert", "Rev": "e4ec8152c15fc46bd5056ce65997a07c7d415325" }, { "ImportPath": "github.com/pyr/egoscale/src/egoscale", "Rev": "bbaa67324aeeacc90430c1fe0a9c620d3929512e" }, { "ImportPath": "github.com/tent/http-link-go", "Rev": "ac974c61c2f990f4115b119354b5e0b47550e888" }, { "ImportPath": "github.com/vmware/govcloudair", "Comment": "v0.0.2", "Rev": "66a23eaabc61518f91769939ff541886fe1dceef" }, { "ImportPath": "golang.org/x/crypto/ssh", "Rev": "1fbbd62cfec66bd39d91e97749579579d4d3037e" }, { "ImportPath": "google.golang.org/api/compute/v1", "Rev": "aa91ac681e18e52b1a0dfe29b9d8354e88c0dcf5" }, { "ImportPath": "google.golang.org/api/googleapi", "Rev": "aa91ac681e18e52b1a0dfe29b9d8354e88c0dcf5" } ] }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/dockerman.glide
hash: ead3ea293a6143fe41069ebec814bf197d8c43a92cc7666b1f7e21a419b46feb updated: 2016-06-20T21:53:35.420817456Z imports: - name: github.com/BurntSushi/toml version: f0aeabca5a127c4078abb8c8d64298b147264b55 - name: github.com/cpuguy83/go-md2man version: a65d4d2de4d5f7c74868dfa9b202a3c8be315aaa subpackages: - md2man - name: github.com/fsnotify/fsnotify version: 30411dbcefb7a1da7e84f75530ad3abe4011b4f8 - name: github.com/hashicorp/hcl version: da486364306ed66c218be9b7953e19173447c18b subpackages: - hcl/ast - hcl/parser - hcl/token - json/parser - hcl/scanner - hcl/strconv - json/scanner - json/token - name: github.com/inconshreveable/mousetrap version: 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 - name: github.com/magiconair/properties version: c265cfa48dda6474e208715ca93e987829f572f8 - name: github.com/mitchellh/mapstructure version: d2dd0262208475919e1a362f675cfc0e7c10e905 - name: github.com/russross/blackfriday version: 1d6b8e9301e720b08a8938b8c25c018285885438 - name: github.com/shurcooL/sanitized_anchor_name version: 10ef21a441db47d8b13ebcc5fd2310f636973c77 - name: github.com/spf13/cast version: 27b586b42e29bec072fe7379259cc719e1289da6 - name: github.com/spf13/jwalterweatherman version: 33c24e77fb80341fe7130ee7c594256ff08ccc46 - name: github.com/spf13/pflag version: dabebe21bf790f782ea4c7bbd2efc430de182afd - name: github.com/spf13/viper version: c1ccc378a054ea8d4e38d8c67f6938d4760b53dd - name: golang.org/x/sys version: 62bee037599929a6e9146f29d10dd5208c43507d subpackages: - unix - name: gopkg.in/yaml.v2 version: a83829b6f1293c91addabc89d0571c246397bbf4 - name: github.com/spf13/cobra repo: https://github.com/dnephin/cobra subpackages: - doc version: v1.3 devImports: []
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/govmomi.out
github.com/davecgh/go-xdr/xdr2 4930550ba2e22f87187498acfd78348b15f4e7a8 github.com/google/uuid 6a5e28554805e78ea6141142aba763936c4761c0 github.com/kr/pretty 2ee9d7453c02ef7fa518a83ae23644eb8872186a github.com/kr/pty 95d05c1eef33a45bd58676b6ce28d105839b8d0b github.com/vmware/vmw-guestinfo 25eff159a728be87e103a0b8045e08273f4dbec4
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/cockroach.glock
cmd github.com/cockroachdb/c-protobuf/cmd/protoc cmd github.com/cockroachdb/yacc cmd github.com/gogo/protobuf/protoc-gen-gogo cmd github.com/golang/lint/golint cmd github.com/jteeuwen/go-bindata/go-bindata cmd github.com/kisielk/errcheck cmd github.com/robfig/glock cmd github.com/tebeka/go2xunit cmd golang.org/x/tools/cmd/goimports cmd golang.org/x/tools/cmd/stringer github.com/agtorre/gocolorize f42b554bf7f006936130c9bb4f971afd2d87f671 github.com/biogo/store e1f74b3c58befe661feed7fa4cf52436de753128 github.com/cockroachdb/c-lz4 6e71f140a365017bbe0904710007f8725fd3f809 github.com/cockroachdb/c-protobuf 0f9ab7b988ca7474cf76b9a961ab03c0552abcb3 github.com/cockroachdb/c-rocksdb 7fc876fe79b96de0e25069c9ae27e6444637bd54 github.com/cockroachdb/c-snappy 618733f9e5bab8463b9049117a335a7a1bfc9fd5 github.com/cockroachdb/yacc 572e006f8e6b0061ebda949d13744f5108389514 github.com/coreos/etcd 18ecc297bc913bed6fc093d66b1fa22020dba7dc github.com/docker/docker 7374852be9def787921aea2ca831771982badecf github.com/elazarl/go-bindata-assetfs 3dcc96556217539f50599357fb481ac0dc7439b9 github.com/gogo/protobuf 98e73e511a62a9c232152f94999112c80142a813 github.com/golang/lint 7b7f4364ff76043e6c3610281525fabc0d90f0e4 github.com/google/btree cc6329d4279e3f025a53a83c397d2339b5705c45 github.com/inconshreveable/mousetrap 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 github.com/jteeuwen/go-bindata dce55d09e24ac40a6e725c8420902b86554f8046 github.com/julienschmidt/httprouter 6aacfd5ab513e34f7e64ea9627ab9670371b34e7 github.com/kisielk/errcheck 50b84cf7fa18ee2985b8c63ba3de5edd604b9259 github.com/kisielk/gotool d678387370a2eb9b5b0a33218bc8c9d8de15b6be github.com/lib/pq a8d8d01c4f91602f876bf5aa210274e8203a6b45 github.com/montanaflynn/stats 44fb56da2a2a67d394dec0e18a82dd316f192529 github.com/peterh/liner 1bb0d1c1a25ed393d8feb09bab039b2b1b1fbced github.com/robfig/glock cb3c3ec56de988289cab7bbd284eddc04dfee6c9 github.com/samalba/dockerclient 12570e600d71374233e5056ba315f657ced496c7 github.com/spf13/cobra 66816bcd0378e248c613e3c443c020f544c28804 github.com/spf13/pflag 67cbc198fd11dab704b214c1e629a97af392c085 github.com/tebeka/go2xunit d45000af2242dd0e7b8c7b07d82a1068adc5fd40 golang.org/x/crypto cc04154d65fb9296747569b107cfd05380b1ea3e golang.org/x/net 8bfde94a845cb31000de3266ac83edbda58dab09 golang.org/x/text d4cc1b1e16b49d6dafc4982403b40fe89c512cd5 golang.org/x/tools d02228d1857b9f49cd0252788516ff5584266eb6 gopkg.in/yaml.v1 9f9df34309c04878acc86042b16630b0f696e1de
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/juju.out
github.com/Azure/azure-sdk-for-go 902d95d9f311ae585ee98cfd18f418b467d60d5a github.com/Azure/go-autorest 6f40a8acfe03270d792cb8155e2942c09d7cff95 github.com/ajstarks/svgo 89e3ac64b5b3e403a5e7c35ea4f98d45db7b4518 github.com/altoros/gosigma 31228935eec685587914528585da4eb9b073c76d github.com/beorn7/perks 3ac7bf7a47d159a033b107610db8a1b6575507a4 github.com/bmizerany/pat c068ca2f0aacee5ac3681d68e4d0a003b7d1fd2c github.com/coreos/go-systemd 7b2428fec40033549c68f54e26e89e7ca9a9ce31 github.com/dgrijalva/jwt-go 01aeca54ebda6e0fbfafd0a524d234159c05ec20 github.com/dustin/go-humanize 145fabdb1ab757076a70a886d092a3af27f66f4c github.com/godbus/dbus 32c6cc29c14570de4cf6d7e7737d68fb2d01ad15 github.com/golang/protobuf 4bd1920723d7b7c925de087aa32e2187708897f7 github.com/google/go-querystring 9235644dd9e52eeae6fa48efd539fdc351a0af53 github.com/gorilla/schema 08023a0215e7fc27a9aecd8b8c50913c40019478 github.com/gorilla/websocket 804cb600d06b10672f2fbc0a336a7bee507a428e github.com/gosuri/uitable 36ee7e946282a3fb1cfecd476ddc9b35d8847e42 github.com/joyent/gocommon ade826b8b54e81a779ccb29d358a45ba24b7809c github.com/joyent/gosdc 2f11feadd2d9891e92296a1077c3e2e56939547d github.com/joyent/gosign 0da0d5f1342065321c97812b1f4ac0c2b0bab56c github.com/juju/ansiterm b99631de12cf04a906c1d4e4ec54fb86eae5863d github.com/juju/blobstore 06056004b3d7b54bbb7984d830c537bad00fec21 github.com/juju/bundlechanges 7725027b95e0d54635e0fb11efc2debdcdf19f75 github.com/juju/cmd 9425a576247f348b9b40afe3b60085de63470de5 github.com/juju/description d3742c23561884cd7d759ef7142340af1d22cab0 github.com/juju/errors 1b5e39b83d1835fa480e0c2ddefb040ee82d58b3 github.com/juju/gnuflag 4e76c56581859c14d9d87e1ddbe29e1c0f10195f github.com/juju/go4 40d72ab9641a2a8c36a9c46a51e28367115c8e59 github.com/juju/gojsonpointer afe8b77aa08f272b49e01b82de78510c11f61500 github.com/juju/gojsonreference f0d24ac5ee330baa21721cdff56d45e4ee42628e github.com/juju/gojsonschema e1ad140384f254c82f89450d9a7c8dd38a632838 github.com/juju/gomaasapi cfbc096bd45f276c17a391efc4db710b60ae3ad7 github.com/juju/httpprof 14bf14c307672fd2456bdbf35d19cf0ccd3cf565 github.com/juju/httprequest 266fd1e9debf09c037a63f074d099a2da4559ece github.com/juju/idmclient 4dc25171f675da4206b71695d3fd80e519ad05c1 github.com/juju/jsonschema a0ef8b74ebcffeeff9fc374854deb4af388f037e github.com/juju/loggo 21bc4c63e8b435779a080e39e592969b7b90b889 github.com/juju/mempool 24974d6c264fe5a29716e7d56ea24c4bd904b7cc github.com/juju/mutex 59c26ee163447c5c57f63ff71610d433862013de github.com/juju/persistent-cookiejar 5243747bf8f2d0897f6c7a52799327dc97d585e8 github.com/juju/pubsub 9dcaca7eb4340dbf685aa7b3ad4cc4f8691a33d4 github.com/juju/replicaset 6b5becf2232ce76656ea765d8d915d41755a1513 github.com/juju/retry 62c62032529169c7ec02fa48f93349604c345e1f github.com/juju/rfc ebdbbdb950cd039a531d15cdc2ac2cbd94f068ee github.com/juju/romulus 98d6700423d63971f10ca14afea9ecf2b9b99f0f github.com/juju/schema 075de04f9b7d7580d60a1e12a0b3f50bb18e6998 github.com/juju/terms-client 9b925afd677234e4146dde3cb1a11e187cbed64e github.com/juju/testing fce9bc4ebf7a77310c262ac4884e03b778eae06a github.com/juju/txn 28898197906200d603394d8e4ce537436529f1c5 github.com/juju/usso 68a59c96c178fbbad65926e7f93db50a2cd14f33 github.com/juju/utils 9f8aeb9b09e2d8c769be8317ccfa23f7eec62c26 github.com/juju/version 1f41e27e54f21acccf9b2dddae063a782a8a7ceb github.com/juju/webbrowser 54b8c57083b4afb7dc75da7f13e2967b2606a507 github.com/juju/xml eb759a627588d35166bc505fceb51b88500e291e github.com/juju/zip f6b1e93fa2e29a1d7d49b566b2b51efb060c982a github.com/julienschmidt/httprouter 77a895ad01ebc98a4dc95d8355bc825ce80a56f6 github.com/lestrrat/go-jspointer f4881e611bdbe9fb413a7780721ef8400a1f2341 github.com/lestrrat/go-jsref e452c7b5801d1c6494c9e7e0cbc7498c0f88dfd1 github.com/lestrrat/go-jsschema b09d7650b822d2ea3dc83d5091a5e2acd8330051 github.com/lestrrat/go-jsval b1258a10419fe0693f7b35ad65cd5074bc0ba1e5 github.com/lestrrat/go-pdebug 2e6eaaa5717f81bda41d27070d3c966f40a1e75f github.com/lestrrat/go-structinfo f74c056fe41f860aa6264478c664a6fff8a64298 github.com/lunixbochs/vtclean 4fbf7632a2c6d3fbdb9931439bdbbeded02cbe36 github.com/lxc/lxd 23da0234979fa6299565b91b529a6dbeb42ee36d github.com/masterzen/azure-sdk-for-go ee4f0065d00cd12b542f18f5bc45799e88163b12 github.com/masterzen/simplexml 4572e39b1ab9fe03ee513ce6fc7e289e98482190 github.com/masterzen/winrm 7a535cd943fccaeed196718896beec3fb51aff41 github.com/masterzen/xmlpath 13f4951698adc0fa9c1dda3e275d489a24201161 github.com/mattn/go-colorable ed8eb9e318d7a84ce5915b495b7d35e0cfe7b5a8 github.com/mattn/go-isatty 66b8e73f3f5cda9f96b69efd03dd3d7fc4a5cdb8 github.com/mattn/go-runewidth d96d1bd051f2bd9e7e43d602782b37b93b1b5666 github.com/matttproud/golang_protobuf_extensions c12348ce28de40eed0136aa2b644d0ee0650e56c github.com/nu7hatch/gouuid 179d4d0c4d8d407a32af483c2354df1d2c91e6c3 github.com/pkg/errors 839d9e913e063e28dfd0e6c7b7512793e0a48be9 github.com/prometheus/client_golang 575f371f7862609249a1be4c9145f429fe065e32 github.com/prometheus/client_model fa8ad6fec33561be4280a8f0514318c79d7f6cb6 github.com/prometheus/common dd586c1c5abb0be59e60f942c22af711a2008cb4 github.com/prometheus/procfs abf152e5f3e97f2fafac028d2cc06c1feb87ffa5 github.com/rogpeppe/fastuuid 6724a57986aff9bff1a1770e9347036def7c89f6 github.com/vmware/govmomi c0c7ce63df7edd78e713257b924c89d9a2dac119 golang.org/x/crypto 8e06e8ddd9629eb88639aba897641bff8031f1d3 golang.org/x/net ea47fc708ee3e20177f3ca3716217c4ab75942cb golang.org/x/oauth2 11c60b6f71a6ad48ed6f93c65fa4c6f9b1b5b46a golang.org/x/sys 7a6e5648d140666db5d920909e082ca00a87ba2c golang.org/x/text 2910a502d2bf9e43193af9d68ca516529614eed3 google.golang.org/api 0d3983fb069cb6651353fc44c5cb604e263f2a93 google.golang.org/cloud f20d6dcccb44ed49de45ae3703312cb46e627db1 gopkg.in/amz.v3 8c3190dff075bf5442c9eedbf8f8ed6144a099e7 gopkg.in/check.v1 4f90aeace3a26ad7021961c297b22c42160c7b25 gopkg.in/errgo.v1 442357a80af5c6bf9b6d51ae791a39c3421004f3 gopkg.in/goose.v1 ac43167b647feacdd9a1e34ee81e574551bc748d gopkg.in/ini.v1 776aa739ce9373377cd16f526cdf06cb4c89b40f gopkg.in/juju/blobstore.v2 51fa6e26128d74e445c72d3a91af555151cc3654 gopkg.in/juju/charm.v6-unstable 83771c4919d6810bce5b7e63f46bea5fbfed0b93 gopkg.in/juju/charmrepo.v2-unstable e79aa298df89ea887c9bffec46063c24bfb730f7 gopkg.in/juju/charmstore.v5-unstable fd1eef3002fc6b6daff5e97efab6f5056d22dcc7 gopkg.in/juju/environschema.v1 7359fc7857abe2b11b5b3e23811a9c64cb6b01e0 gopkg.in/juju/jujusvg.v2 d82160011935ef79fc7aca84aba2c6f74700fe75 gopkg.in/juju/names.v2 0847c26d322a121e52614f969fb82eae2820c715 gopkg.in/juju/worker.v1 6965b9d826717287bb002e02d1fd4d079978083e gopkg.in/macaroon-bakery.v1 469b44e6f1f9479e115c8ae879ef80695be624d5 gopkg.in/macaroon.v1 ab3940c6c16510a850e1c2dd628b919f0f3f1464 gopkg.in/mgo.v2 f2b6f6c918c452ad107eec89615f074e3bd80e33 gopkg.in/natefinch/lumberjack.v2 514cbda263a734ae8caac038dadf05f8f3f9f738 gopkg.in/natefinch/npipe.v2 c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6 gopkg.in/retry.v1 c09f6b86ba4d5d2cf5bdf0665364aec9fd4815db gopkg.in/tomb.v1 dd632973f1e7218eb1089048e0798ec9ae7dceb8 gopkg.in/yaml.v2 a3f3340b5840cee44f372bddb5880fcbc419b46a
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/prometheus.vjson
{ "comment": "", "ignore": "test appengine", "package": [ { "checksumSHA1": "Cslv4/ITyQmgjSUhNXFu8q5bqOU=", "origin": "k8s.io/client-go/1.5/vendor/cloud.google.com/go/compute/metadata", "path": "cloud.google.com/go/compute/metadata", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "hiJXjkFEGy+sDFf6O58Ocdy9Rnk=", "origin": "k8s.io/client-go/1.5/vendor/cloud.google.com/go/internal", "path": "cloud.google.com/go/internal", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "oIt4tXgFYnZJBsCac1BQLnTWALM=", "path": "github.com/Azure/azure-sdk-for-go/arm/compute", "revision": "bd73d950fa4440dae889bd9917bff7cef539f86e", "revisionTime": "2016-10-28T18:31:11Z" }, { "checksumSHA1": "QKi6LiSyD5GnRK8ExpMgZl4XiMI=", "path": "github.com/Azure/azure-sdk-for-go/arm/network", "revision": "bd73d950fa4440dae889bd9917bff7cef539f86e", "revisionTime": "2016-10-28T18:31:11Z" }, { "checksumSHA1": "eVSHe6GIHj9/ziFrQLZ1SC7Nn6k=", "path": "github.com/Azure/go-autorest/autorest", "revision": "8a25372bbfec739b8719a9e3987400d15ef9e179", "revisionTime": "2016-10-25T18:07:34Z" }, { "checksumSHA1": "0sYi0JprevG/PZjtMbOh8h0pt0g=", "path": "github.com/Azure/go-autorest/autorest/azure", "revision": "8a25372bbfec739b8719a9e3987400d15ef9e179", "revisionTime": "2016-10-25T18:07:34Z" }, { "checksumSHA1": "q9Qz8PAxK5FTOZwgYKe5Lj38u4c=", "path": "github.com/Azure/go-autorest/autorest/date", "revision": "8a25372bbfec739b8719a9e3987400d15ef9e179", "revisionTime": "2016-10-25T18:07:34Z" }, { "checksumSHA1": "Ev8qCsbFjDlMlX0N2tYAhYQFpUc=", "path": "github.com/Azure/go-autorest/autorest/to", "revision": "8a25372bbfec739b8719a9e3987400d15ef9e179", "revisionTime": "2016-10-25T18:07:34Z" }, { "checksumSHA1": "oBixceM+55gdk47iff8DSEIh3po=", "path": "github.com/Azure/go-autorest/autorest/validation", "revision": "8a25372bbfec739b8719a9e3987400d15ef9e179", "revisionTime": "2016-10-25T18:07:34Z" }, { "checksumSHA1": "IatnluZB5jTVUncMN134e4VOV34=", "origin": "k8s.io/client-go/1.5/vendor/github.com/PuerkitoBio/purell", "path": "github.com/PuerkitoBio/purell", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "E/Tz8z0B/gaR551g+XqPKAhcteM=", "origin": "k8s.io/client-go/1.5/vendor/github.com/PuerkitoBio/urlesc", "path": "github.com/PuerkitoBio/urlesc", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "BdLdZP/C2uOO3lqk9X3NCKFpXa4=", "path": "github.com/asaskevich/govalidator", "revision": "7b3beb6df3c42abd3509abfc3bcacc0fbfb7c877", "revisionTime": "2016-10-01T16:31:30Z" }, { "checksumSHA1": "WNfR3yhLjRC5/uccgju/bwrdsxQ=", "path": "github.com/aws/aws-sdk-go/aws", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "Y9W+4GimK4Fuxq+vyIskVYFRnX4=", "path": "github.com/aws/aws-sdk-go/aws/awserr", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "+q4vdl3l1Wom8K1wfIpJ4jlFsbY=", "path": "github.com/aws/aws-sdk-go/aws/awsutil", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "/232RBWA3KnT7U+wciPS2+wmvR0=", "path": "github.com/aws/aws-sdk-go/aws/client", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "ieAJ+Cvp/PKv1LpUEnUXpc3OI6E=", "path": "github.com/aws/aws-sdk-go/aws/client/metadata", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "c1N3Loy3AS9zD+m5CzpPNAED39U=", "path": "github.com/aws/aws-sdk-go/aws/corehandlers", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "zu5C95rmCZff6NYZb62lEaT5ibE=", "path": "github.com/aws/aws-sdk-go/aws/credentials", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "KQiUK/zr3mqnAXD7x/X55/iNme0=", "path": "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "NUJUTWlc1sV8b7WjfiYc4JZbXl0=", "path": "github.com/aws/aws-sdk-go/aws/credentials/endpointcreds", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "4Ipx+5xN0gso+cENC2MHMWmQlR4=", "path": "github.com/aws/aws-sdk-go/aws/credentials/stscreds", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "DwhFsNluCFEwqzyp3hbJR3q2Wqs=", "path": "github.com/aws/aws-sdk-go/aws/defaults", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "8E0fEBUJY/1lJOyVxzTxMGQGInk=", "path": "github.com/aws/aws-sdk-go/aws/ec2metadata", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "5Ac22YMTBmrX/CXaEIXzWljr8UY=", "path": "github.com/aws/aws-sdk-go/aws/request", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "eOo6evLMAxQfo7Qkc5/h5euN1Sw=", "path": "github.com/aws/aws-sdk-go/aws/session", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "diXvBs1LRC0RJ9WK6sllWKdzC04=", "path": "github.com/aws/aws-sdk-go/aws/signer/v4", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "Esab5F8KswqkTdB4TtjSvZgs56k=", "path": "github.com/aws/aws-sdk-go/private/endpoints", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "wk7EyvDaHwb5qqoOP/4d3cV0708=", "path": "github.com/aws/aws-sdk-go/private/protocol", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "1QmQ3FqV37w0Zi44qv8pA1GeR0A=", "path": "github.com/aws/aws-sdk-go/private/protocol/ec2query", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "ZqY5RWavBLWTo6j9xqdyBEaNFRk=", "path": "github.com/aws/aws-sdk-go/private/protocol/query", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "5xzix1R8prUyWxgLnzUQoxTsfik=", "path": "github.com/aws/aws-sdk-go/private/protocol/query/queryutil", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "TW/7U+/8ormL7acf6z2rv2hDD+s=", "path": "github.com/aws/aws-sdk-go/private/protocol/rest", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "eUEkjyMPAuekKBE4ou+nM9tXEas=", "path": "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "Eo9yODN5U99BK0pMzoqnBm7PCrY=", "path": "github.com/aws/aws-sdk-go/private/waiter", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "6h4tJ9wVtbYb9wG4srtUxyPoAYM=", "path": "github.com/aws/aws-sdk-go/service/ec2", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "ouwhxcAsIYQ6oJbMRdLW/Ys/iyg=", "path": "github.com/aws/aws-sdk-go/service/sts", "revision": "707203bc55114ed114446bf57949c5c211d8b7c0", "revisionTime": "2016-11-02T21:59:28Z" }, { "checksumSHA1": "4QnLdmB1kG3N+KlDd1N+G9TWAGQ=", "path": "github.com/beorn7/perks/quantile", "revision": "3ac7bf7a47d159a033b107610db8a1b6575507a4", "revisionTime": "2016-02-29T21:34:45Z" }, { "checksumSHA1": "n+s4YwtzpMWW5Rt0dEaQa7NHDGQ=", "origin": "k8s.io/client-go/1.5/vendor/github.com/blang/semver", "path": "github.com/blang/semver", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "Z2AOGSmDKKvI6nuxa+UPjQWpIeM=", "origin": "k8s.io/client-go/1.5/vendor/github.com/coreos/go-oidc/http", "path": "github.com/coreos/go-oidc/http", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "8yvt1xKCgNwuuavJdxRnvaIjrIc=", "origin": "k8s.io/client-go/1.5/vendor/github.com/coreos/go-oidc/jose", "path": "github.com/coreos/go-oidc/jose", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "zhXKrWBSSJLqZxVE/Xsw0M9ynFQ=", "origin": "k8s.io/client-go/1.5/vendor/github.com/coreos/go-oidc/key", "path": "github.com/coreos/go-oidc/key", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "bkW0mnXvmHQwHprW/6wrbpP7lAk=", "origin": "k8s.io/client-go/1.5/vendor/github.com/coreos/go-oidc/oauth2", "path": "github.com/coreos/go-oidc/oauth2", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "E1x2k5FdhJ+dzFrh3kCmC6aJfVw=", "origin": "k8s.io/client-go/1.5/vendor/github.com/coreos/go-oidc/oidc", "path": "github.com/coreos/go-oidc/oidc", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "O0UMBRCOD9ItMayDqLQ2MJEjkVE=", "origin": "k8s.io/client-go/1.5/vendor/github.com/coreos/pkg/health", "path": "github.com/coreos/pkg/health", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "74vyZz/d49FZXMbFaHOfCGvSLj0=", "origin": "k8s.io/client-go/1.5/vendor/github.com/coreos/pkg/httputil", "path": "github.com/coreos/pkg/httputil", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "etBdQ0LN6ojGunfvUt6B5C3FNrQ=", "origin": "k8s.io/client-go/1.5/vendor/github.com/coreos/pkg/timeutil", "path": "github.com/coreos/pkg/timeutil", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "SdSd7pyjONWWTHc5XE3AhglLo34=", "origin": "k8s.io/client-go/1.5/vendor/github.com/davecgh/go-spew/spew", "path": "github.com/davecgh/go-spew/spew", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "2Fy1Y6Z3lRRX1891WF/+HT4XS2I=", "path": "github.com/dgrijalva/jwt-go", "revision": "9ed569b5d1ac936e6494082958d63a6aa4fff99a", "revisionTime": "2016-11-01T19:39:35Z" }, { "checksumSHA1": "f1wARLDzsF/JoyN01yoxXEwFIp8=", "origin": "k8s.io/client-go/1.5/vendor/github.com/docker/distribution/digest", "path": "github.com/docker/distribution/digest", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "PzXRTLmmqWXxmDqdIXLcRYBma18=", "origin": "k8s.io/client-go/1.5/vendor/github.com/docker/distribution/reference", "path": "github.com/docker/distribution/reference", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "1vQR+ZyudsjKio6RNKmWhwzGTb0=", "origin": "k8s.io/client-go/1.5/vendor/github.com/emicklei/go-restful", "path": "github.com/emicklei/go-restful", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "3xWz4fZ9xW+CfADpYoPFcZCYJ4E=", "origin": "k8s.io/client-go/1.5/vendor/github.com/emicklei/go-restful/log", "path": "github.com/emicklei/go-restful/log", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "J7CtF9gIs2yH9A7lPQDDrhYxiRk=", "origin": "k8s.io/client-go/1.5/vendor/github.com/emicklei/go-restful/swagger", "path": "github.com/emicklei/go-restful/swagger", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "ww7LVo7jNJ1o6sfRcromEHKyY+o=", "origin": "k8s.io/client-go/1.5/vendor/github.com/ghodss/yaml", "path": "github.com/ghodss/yaml", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "cVyhKIRI2gQrgpn5qrBeAqErmWM=", "path": "github.com/go-ini/ini", "revision": "6e4869b434bd001f6983749881c7ead3545887d8", "revisionTime": "2016-08-27T06:11:18Z" }, { "checksumSHA1": "NaZnW0tKj/b0k5WzcMD0twrLbrE=", "origin": "k8s.io/client-go/1.5/vendor/github.com/go-openapi/jsonpointer", "path": "github.com/go-openapi/jsonpointer", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "3LJXjMDxPY+veIqzQtiAvK3hXnY=", "origin": "k8s.io/client-go/1.5/vendor/github.com/go-openapi/jsonreference", "path": "github.com/go-openapi/jsonreference", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "faeB3fny260hQ/gEfEXa1ZQTGtk=", "origin": "k8s.io/client-go/1.5/vendor/github.com/go-openapi/spec", "path": "github.com/go-openapi/spec", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "wGpZwJ5HZtReou8A3WEV1Gdxs6k=", "origin": "k8s.io/client-go/1.5/vendor/github.com/go-openapi/swag", "path": "github.com/go-openapi/swag", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "BIyZQL97iG7mzZ2UMR3XpiXbZdc=", "origin": "k8s.io/client-go/1.5/vendor/github.com/gogo/protobuf/proto", "path": "github.com/gogo/protobuf/proto", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "e6cMbpJj41MpihS5eP4SIliRBK4=", "origin": "k8s.io/client-go/1.5/vendor/github.com/gogo/protobuf/sortkeys", "path": "github.com/gogo/protobuf/sortkeys", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "URsJa4y/sUUw/STmbeYx9EKqaYE=", "origin": "k8s.io/client-go/1.5/vendor/github.com/golang/glog", "path": "github.com/golang/glog", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "yDh5kmmr0zEF1r+rvYqbZcR7iLs=", "path": "github.com/golang/protobuf/proto", "revision": "98fa357170587e470c5f27d3c3ea0947b71eb455", "revisionTime": "2016-10-12T20:53:35Z" }, { "checksumSHA1": "2a/SsTUBMKtcM6VtpbdPGO+c6c8=", "path": "github.com/golang/snappy", "revision": "d9eb7a3d35ec988b8585d4a0068e462c27d28380", "revisionTime": "2016-05-29T05:00:41Z" }, { "checksumSHA1": "/yFfUp3tGt6cK22UVzbq8SjPDCU=", "origin": "k8s.io/client-go/1.5/vendor/github.com/google/gofuzz", "path": "github.com/google/gofuzz", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "LclVLJYrBi03PBjsVPpgoMbUDQ8=", "path": "github.com/hashicorp/consul/api", "revision": "daacc4be8bee214e3fc4b32a6dd385f5ef1b4c36", "revisionTime": "2016-10-28T04:06:46Z" }, { "checksumSHA1": "Uzyon2091lmwacNsl1hCytjhHtg=", "path": "github.com/hashicorp/go-cleanhttp", "revision": "ad28ea4487f05916463e2423a55166280e8254b5", "revisionTime": "2016-04-07T17:41:26Z" }, { "checksumSHA1": "E3Xcanc9ouQwL+CZGOUyA/+giLg=", "path": "github.com/hashicorp/serf/coordinate", "revision": "1d4fa605f6ff3ed628d7ae5eda7c0e56803e72a5", "revisionTime": "2016-10-07T00:41:22Z" }, { "path": "github.com/influxdb/influxdb/client", "revision": "291aaeb9485b43b16875c238482b2f7d0a22a13b", "revisionTime": "2015-09-16T14:41:53+02:00" }, { "path": "github.com/influxdb/influxdb/tsdb", "revision": "291aaeb9485b43b16875c238482b2f7d0a22a13b", "revisionTime": "2015-09-16T14:41:53+02:00" }, { "checksumSHA1": "0ZrwvB6KoGPj2PoDNSEJwxQ6Mog=", "path": "github.com/jmespath/go-jmespath", "revision": "bd40a432e4c76585ef6b72d3fd96fb9b6dc7b68d", "revisionTime": "2016-08-03T19:07:31Z" }, { "checksumSHA1": "9ZVOEbIXnTuYpVqce4en8rwlkPE=", "origin": "k8s.io/client-go/1.5/vendor/github.com/jonboulle/clockwork", "path": "github.com/jonboulle/clockwork", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "gA95N2LM2hEJLoqrTPaFsSWDJ2Y=", "origin": "k8s.io/client-go/1.5/vendor/github.com/juju/ratelimit", "path": "github.com/juju/ratelimit", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "Farach1xcmsQYrhiUfkwF2rbIaE=", "path": "github.com/julienschmidt/httprouter", "revision": "109e267447e95ad1bb48b758e40dd7453eb7b039", "revisionTime": "2015-09-05T19:25:33+02:00" }, { "checksumSHA1": "urY45++NYCue4nh4k8OjUFnIGfU=", "origin": "k8s.io/client-go/1.5/vendor/github.com/mailru/easyjson/buffer", "path": "github.com/mailru/easyjson/buffer", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "yTDKAM4KBgOvXRsZC50zg0OChvM=", "origin": "k8s.io/client-go/1.5/vendor/github.com/mailru/easyjson/jlexer", "path": "github.com/mailru/easyjson/jlexer", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "4+d+6rhM1pei6lBguhqSEW7LaXs=", "origin": "k8s.io/client-go/1.5/vendor/github.com/mailru/easyjson/jwriter", "path": "github.com/mailru/easyjson/jwriter", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "Q2vw4HZBbnU8BLFt8VrzStwqSJg=", "path": "github.com/matttproud/golang_protobuf_extensions/pbutil", "revision": "fc2b8d3a73c4867e51861bbdd5ae3c1f0869dd6a", "revisionTime": "2015-04-06T19:39:34+02:00" }, { "checksumSHA1": "Wahi4g/9XiHhSLAJ+8jskg71PCU=", "path": "github.com/miekg/dns", "revision": "58f52c57ce9df13460ac68200cef30a008b9c468", "revisionTime": "2016-10-18T06:08:08Z" }, { "checksumSHA1": "3YJklSuzSE1Rt8A+2dhiWSmf/fw=", "origin": "k8s.io/client-go/1.5/vendor/github.com/pborman/uuid", "path": "github.com/pborman/uuid", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "zKKp5SZ3d3ycKe4EKMNT0BqAWBw=", "origin": "github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/difflib", "path": "github.com/pmezard/go-difflib/difflib", "revision": "d77da356e56a7428ad25149ca77381849a6a5232", "revisionTime": "2016-06-15T09:26:46Z" }, { "checksumSHA1": "KkB+77Ziom7N6RzSbyUwYGrmDeU=", "path": "github.com/prometheus/client_golang/prometheus", "revision": "c5b7fccd204277076155f10851dad72b76a49317", "revisionTime": "2016-08-17T15:48:24Z" }, { "checksumSHA1": "DvwvOlPNAgRntBzt3b3OSRMS2N4=", "path": "github.com/prometheus/client_model/go", "revision": "fa8ad6fec33561be4280a8f0514318c79d7f6cb6", "revisionTime": "2015-02-12T10:17:44Z" }, { "checksumSHA1": "mHyjbJ3BWOfUV6q9f5PBt0gaY1k=", "path": "github.com/prometheus/common/expfmt", "revision": "85637ea67b04b5c3bb25e671dacded2977f8f9f6", "revisionTime": "2016-10-02T21:02:34Z" }, { "checksumSHA1": "GWlM3d2vPYyNATtTFgftS10/A9w=", "path": "github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg", "revision": "85637ea67b04b5c3bb25e671dacded2977f8f9f6", "revisionTime": "2016-10-02T21:02:34Z" }, { "checksumSHA1": "UU6hIfhVjnAYDADQEfE/3T7Ddm8=", "path": "github.com/prometheus/common/log", "revision": "85637ea67b04b5c3bb25e671dacded2977f8f9f6", "revisionTime": "2016-10-02T21:02:34Z" }, { "checksumSHA1": "nFie+rxcX5WdIv1diZ+fu3aj6lE=", "path": "github.com/prometheus/common/model", "revision": "85637ea67b04b5c3bb25e671dacded2977f8f9f6", "revisionTime": "2016-10-02T21:02:34Z" }, { "checksumSHA1": "QQKJYoGcY10nIHxhBEHwjwUZQzk=", "path": "github.com/prometheus/common/route", "revision": "85637ea67b04b5c3bb25e671dacded2977f8f9f6", "revisionTime": "2016-10-02T21:02:34Z" }, { "checksumSHA1": "91KYK0SpvkaMJJA2+BcxbVnyRO0=", "path": "github.com/prometheus/common/version", "revision": "85637ea67b04b5c3bb25e671dacded2977f8f9f6", "revisionTime": "2016-10-02T21:02:34Z" }, { "checksumSHA1": "W218eJZPXJG783fUr/z6IaAZyes=", "path": "github.com/prometheus/procfs", "revision": "abf152e5f3e97f2fafac028d2cc06c1feb87ffa5", "revisionTime": "2016-04-11T19:08:41Z" }, { "checksumSHA1": "+49Vr4Me28p3cR+gxX5SUQHbbas=", "path": "github.com/samuel/go-zookeeper/zk", "revision": "177002e16a0061912f02377e2dd8951a8b3551bc", "revisionTime": "2015-08-17T10:50:50-07:00" }, { "checksumSHA1": "YuPBOVkkE3uuBh4RcRUTF0n+frs=", "origin": "k8s.io/client-go/1.5/vendor/github.com/spf13/pflag", "path": "github.com/spf13/pflag", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "iydUphwYqZRq3WhstEdGsbvBAKs=", "path": "github.com/stretchr/testify/assert", "revision": "d77da356e56a7428ad25149ca77381849a6a5232", "revisionTime": "2016-06-15T09:26:46Z" }, { "checksumSHA1": "P9FJpir2c4G5PA46qEkaWy3l60U=", "path": "github.com/stretchr/testify/require", "revision": "d77da356e56a7428ad25149ca77381849a6a5232", "revisionTime": "2016-06-15T09:26:46Z" }, { "checksumSHA1": "VhcnDY37sYAnL8WjfYQN9YYl+W4=", "path": "github.com/syndtr/goleveldb/leveldb", "revision": "6b4daa5362b502898ddf367c5c11deb9e7a5c727", "revisionTime": "2016-10-11T05:00:08Z" }, { "checksumSHA1": "EKIow7XkgNdWvR/982ffIZxKG8Y=", "path": "github.com/syndtr/goleveldb/leveldb/cache", "revision": "6b4daa5362b502898ddf367c5c11deb9e7a5c727", "revisionTime": "2016-10-11T05:00:08Z" }, { "checksumSHA1": "5KPgnvCPlR0ysDAqo6jApzRQ3tw=", "path": "github.com/syndtr/goleveldb/leveldb/comparer", "revision": "6b4daa5362b502898ddf367c5c11deb9e7a5c727", "revisionTime": "2016-10-11T05:00:08Z" }, { "checksumSHA1": "1DRAxdlWzS4U0xKN/yQ/fdNN7f0=", "path": "github.com/syndtr/goleveldb/leveldb/errors", "revision": "6b4daa5362b502898ddf367c5c11deb9e7a5c727", "revisionTime": "2016-10-11T05:00:08Z" }, { "checksumSHA1": "eqKeD6DS7eNCtxVYZEHHRKkyZrw=", "path": "github.com/syndtr/goleveldb/leveldb/filter", "revision": "6b4daa5362b502898ddf367c5c11deb9e7a5c727", "revisionTime": "2016-10-11T05:00:08Z" }, { "checksumSHA1": "8dXuAVIsbtaMiGGuHjzGR6Ny/5c=", "path": "github.com/syndtr/goleveldb/leveldb/iterator", "revision": "6b4daa5362b502898ddf367c5c11deb9e7a5c727", "revisionTime": "2016-10-11T05:00:08Z" }, { "checksumSHA1": "gJY7bRpELtO0PJpZXgPQ2BYFJ88=", "path": "github.com/syndtr/goleveldb/leveldb/journal", "revision": "6b4daa5362b502898ddf367c5c11deb9e7a5c727", "revisionTime": "2016-10-11T05:00:08Z" }, { "checksumSHA1": "j+uaQ6DwJ50dkIdfMQu1TXdlQcY=", "path": "github.com/syndtr/goleveldb/leveldb/memdb", "revision": "6b4daa5362b502898ddf367c5c11deb9e7a5c727", "revisionTime": "2016-10-11T05:00:08Z" }, { "checksumSHA1": "UmQeotV+m8/FduKEfLOhjdp18rs=", "path": "github.com/syndtr/goleveldb/leveldb/opt", "revision": "6b4daa5362b502898ddf367c5c11deb9e7a5c727", "revisionTime": "2016-10-11T05:00:08Z" }, { "checksumSHA1": "/Wvv9HeJTN9UUjdjwUlz7X4ioIo=", "path": "github.com/syndtr/goleveldb/leveldb/storage", "revision": "6b4daa5362b502898ddf367c5c11deb9e7a5c727", "revisionTime": "2016-10-11T05:00:08Z" }, { "checksumSHA1": "JTJA+u8zk7EXy1UUmpFPNGvtO2A=", "path": "github.com/syndtr/goleveldb/leveldb/table", "revision": "6b4daa5362b502898ddf367c5c11deb9e7a5c727", "revisionTime": "2016-10-11T05:00:08Z" }, { "checksumSHA1": "4zil8Gwg8VPkDn1YzlgCvtukJFU=", "path": "github.com/syndtr/goleveldb/leveldb/util", "revision": "6b4daa5362b502898ddf367c5c11deb9e7a5c727", "revisionTime": "2016-10-11T05:00:08Z" }, { "checksumSHA1": "f6Aew+ZA+HBAXCw6/xTST3mB0Lw=", "origin": "k8s.io/client-go/1.5/vendor/github.com/ugorji/go/codec", "path": "github.com/ugorji/go/codec", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "sFD8LpJPQtWLwGda3edjf5mNUbs=", "path": "github.com/vaughan0/go-ini", "revision": "a98ad7ee00ec53921f08832bc06ecf7fd600e6a1", "revisionTime": "2013-09-23T16:52:12+02:00" }, { "checksumSHA1": "9jjO5GjLa0XF/nfWihF02RoH4qc=", "path": "golang.org/x/net/context", "revision": "b336a971b799939dd16ae9b1df8334cb8b977c4d", "revisionTime": "2016-10-27T19:58:04Z" }, { "checksumSHA1": "WHc3uByvGaMcnSoI21fhzYgbOgg=", "path": "golang.org/x/net/context/ctxhttp", "revision": "b336a971b799939dd16ae9b1df8334cb8b977c4d", "revisionTime": "2016-10-27T19:58:04Z" }, { "checksumSHA1": "SPYGC6DQrH9jICccUsOfbvvhB4g=", "origin": "k8s.io/client-go/1.5/vendor/golang.org/x/net/http2", "path": "golang.org/x/net/http2", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "EYNaHp7XdLWRydUCE0amEkKAtgk=", "origin": "k8s.io/client-go/1.5/vendor/golang.org/x/net/http2/hpack", "path": "golang.org/x/net/http2/hpack", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "gXiSniT8fevWOVPVKopYgrdzi60=", "origin": "k8s.io/client-go/1.5/vendor/golang.org/x/net/idna", "path": "golang.org/x/net/idna", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "/k7k6eJDkxXx6K9Zpo/OwNm58XM=", "path": "golang.org/x/net/internal/timeseries", "revision": "6250b412798208e6c90b03b7c4f226de5aa299e2", "revisionTime": "2016-08-24T22:20:41Z" }, { "checksumSHA1": "yhndhWXMs/VSEDLks4dNyFMQStA=", "origin": "k8s.io/client-go/1.5/vendor/golang.org/x/net/lex/httplex", "path": "golang.org/x/net/lex/httplex", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "7WASrg0PEueWDDRHkFhEEN6Qrms=", "path": "golang.org/x/net/netutil", "revision": "bc3663df0ac92f928d419e31e0d2af22e683a5a2", "revisionTime": "2016-06-21T20:48:10Z" }, { "checksumSHA1": "mktBVED98G2vv+OKcSgtnFVZC1Y=", "path": "golang.org/x/oauth2", "revision": "65a8d08c6292395d47053be10b3c5e91960def76", "revisionTime": "2016-06-07T03:33:14Z" }, { "checksumSHA1": "2rk6lthfQa5Rfydj8j7+dilKGbo=", "path": "golang.org/x/oauth2/google", "revision": "65a8d08c6292395d47053be10b3c5e91960def76", "revisionTime": "2016-06-07T03:33:14Z" }, { "checksumSHA1": "W/GiDqzsagBnR7/yEvxatMhUDBs=", "path": "golang.org/x/oauth2/internal", "revision": "65a8d08c6292395d47053be10b3c5e91960def76", "revisionTime": "2016-06-07T03:33:14Z" }, { "checksumSHA1": "CPTYHWrVL4jA0B1IuC0hvgcE2AQ=", "path": "golang.org/x/oauth2/jws", "revision": "65a8d08c6292395d47053be10b3c5e91960def76", "revisionTime": "2016-06-07T03:33:14Z" }, { "checksumSHA1": "xifBSq0Pn6pIoPA/o3tyzq8X4Ds=", "path": "golang.org/x/oauth2/jwt", "revision": "65a8d08c6292395d47053be10b3c5e91960def76", "revisionTime": "2016-06-07T03:33:14Z" }, { "checksumSHA1": "aVgPDgwY3/t4J/JOw9H3FVMHqh0=", "path": "golang.org/x/sys/unix", "revision": "c200b10b5d5e122be351b67af224adc6128af5bf", "revisionTime": "2016-10-22T18:22:21Z" }, { "checksumSHA1": "fpW2dhGFC6SrVzipJx7fjg2DIH8=", "path": "golang.org/x/sys/windows", "revision": "c200b10b5d5e122be351b67af224adc6128af5bf", "revisionTime": "2016-10-22T18:22:21Z" }, { "checksumSHA1": "PjYlbMS0ttyZYlaevvjA/gV3g1c=", "path": "golang.org/x/sys/windows/registry", "revision": "c200b10b5d5e122be351b67af224adc6128af5bf", "revisionTime": "2016-10-22T18:22:21Z" }, { "checksumSHA1": "uVlUSSKplihZG7N+QJ6fzDZ4Kh8=", "path": "golang.org/x/sys/windows/svc/eventlog", "revision": "c200b10b5d5e122be351b67af224adc6128af5bf", "revisionTime": "2016-10-22T18:22:21Z" }, { "checksumSHA1": "QQpKbWuqvhmxVr/hfEYdWzzcXRM=", "origin": "k8s.io/client-go/1.5/vendor/golang.org/x/text/cases", "path": "golang.org/x/text/cases", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "iAsGo/kxvnwILbJVUCd0ZcqZO/Q=", "origin": "k8s.io/client-go/1.5/vendor/golang.org/x/text/internal/tag", "path": "golang.org/x/text/internal/tag", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "mQ6PCGHY7K0oPjKbYD8wsTjm/P8=", "origin": "k8s.io/client-go/1.5/vendor/golang.org/x/text/language", "path": "golang.org/x/text/language", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "WpeH2TweiuiZAQVTJNO5vyZAQQA=", "origin": "k8s.io/client-go/1.5/vendor/golang.org/x/text/runes", "path": "golang.org/x/text/runes", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "1VjEPyjdi0xOiIN/Alkqiad/B/c=", "origin": "k8s.io/client-go/1.5/vendor/golang.org/x/text/secure/bidirule", "path": "golang.org/x/text/secure/bidirule", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "FcK7VslktIAWj5jnWVnU2SesBq0=", "origin": "k8s.io/client-go/1.5/vendor/golang.org/x/text/secure/precis", "path": "golang.org/x/text/secure/precis", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "nwlu7UTwYbCj9l5f3a7t2ROwNzM=", "origin": "k8s.io/client-go/1.5/vendor/golang.org/x/text/transform", "path": "golang.org/x/text/transform", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "nWJ9R1+Xw41f/mM3b7BYtv77CfI=", "origin": "k8s.io/client-go/1.5/vendor/golang.org/x/text/unicode/bidi", "path": "golang.org/x/text/unicode/bidi", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "BAZ96wCGUj6HdY9sG60Yw09KWA4=", "origin": "k8s.io/client-go/1.5/vendor/golang.org/x/text/unicode/norm", "path": "golang.org/x/text/unicode/norm", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "AZMILKWqLP99UilLgbGZ+uzIVrM=", "origin": "k8s.io/client-go/1.5/vendor/golang.org/x/text/width", "path": "golang.org/x/text/width", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "AjdmRXf0fiy6Bec9mNlsGsmZi1k=", "path": "google.golang.org/api/compute/v1", "revision": "63ade871fd3aec1225809d496e81ec91ab76ea29", "revisionTime": "2016-05-31T06:42:46Z" }, { "checksumSHA1": "OtsMVXY89Hc/bBXdDp84atFQawM=", "path": "google.golang.org/api/gensupport", "revision": "63ade871fd3aec1225809d496e81ec91ab76ea29", "revisionTime": "2016-05-31T06:42:46Z" }, { "checksumSHA1": "yQREK/OWrz9PLljbr127+xFk6J0=", "path": "google.golang.org/api/googleapi", "revision": "63ade871fd3aec1225809d496e81ec91ab76ea29", "revisionTime": "2016-05-31T06:42:46Z" }, { "checksumSHA1": "ii4ET3JHk3vkMUEcg+9t/1RZSUU=", "path": "google.golang.org/api/googleapi/internal/uritemplates", "revision": "63ade871fd3aec1225809d496e81ec91ab76ea29", "revisionTime": "2016-05-31T06:42:46Z" }, { "checksumSHA1": "N3KZEuQ9O1QwJXcCJbe7Czwroo4=", "path": "google.golang.org/appengine", "revision": "267c27e7492265b84fc6719503b14a1e17975d79", "revisionTime": "2016-06-21T05:59:22Z" }, { "checksumSHA1": "G9Xp1ScdsfcKsw+PcWunivRRP3o=", "path": "google.golang.org/appengine/internal", "revision": "267c27e7492265b84fc6719503b14a1e17975d79", "revisionTime": "2016-06-21T05:59:22Z" }, { "checksumSHA1": "x6Thdfyasqd68dWZWqzWWeIfAfI=", "path": "google.golang.org/appengine/internal/app_identity", "revision": "267c27e7492265b84fc6719503b14a1e17975d79", "revisionTime": "2016-06-21T05:59:22Z" }, { "checksumSHA1": "TsNO8P0xUlLNyh3Ic/tzSp/fDWM=", "path": "google.golang.org/appengine/internal/base", "revision": "267c27e7492265b84fc6719503b14a1e17975d79", "revisionTime": "2016-06-21T05:59:22Z" }, { "checksumSHA1": "5QsV5oLGSfKZqTCVXP6NRz5T4Tw=", "path": "google.golang.org/appengine/internal/datastore", "revision": "267c27e7492265b84fc6719503b14a1e17975d79", "revisionTime": "2016-06-21T05:59:22Z" }, { "checksumSHA1": "Gep2T9zmVYV8qZfK2gu3zrmG6QE=", "path": "google.golang.org/appengine/internal/log", "revision": "267c27e7492265b84fc6719503b14a1e17975d79", "revisionTime": "2016-06-21T05:59:22Z" }, { "checksumSHA1": "eLZVX1EHLclFtQnjDIszsdyWRHo=", "path": "google.golang.org/appengine/internal/modules", "revision": "267c27e7492265b84fc6719503b14a1e17975d79", "revisionTime": "2016-06-21T05:59:22Z" }, { "checksumSHA1": "a1XY7rz3BieOVqVI2Et6rKiwQCk=", "path": "google.golang.org/appengine/internal/remote_api", "revision": "4f7eeb5305a4ba1966344836ba4af9996b7b4e05", "revisionTime": "2016-08-19T23:33:10Z" }, { "checksumSHA1": "QtAbHtHmDzcf6vOV9eqlCpKgjiw=", "path": "google.golang.org/appengine/internal/urlfetch", "revision": "267c27e7492265b84fc6719503b14a1e17975d79", "revisionTime": "2016-06-21T05:59:22Z" }, { "checksumSHA1": "akOV9pYnCbcPA8wJUutSQVibdyg=", "path": "google.golang.org/appengine/urlfetch", "revision": "267c27e7492265b84fc6719503b14a1e17975d79", "revisionTime": "2016-06-21T05:59:22Z" }, { "checksumSHA1": "Wp8g9MHRmK8SwcyGVCoGtPx+5Lo=", "path": "google.golang.org/cloud/compute/metadata", "revision": "0a83eba2cadb60eb22123673c8fb6fca02b03c94", "revisionTime": "2016-06-21T15:59:29Z" }, { "checksumSHA1": "U7dGDNwEHORvJFMoNSXErKE7ITg=", "path": "google.golang.org/cloud/internal", "revision": "0a83eba2cadb60eb22123673c8fb6fca02b03c94", "revisionTime": "2016-06-21T15:59:29Z" }, { "checksumSHA1": "JfVmsMwyeeepbdw4q4wpN07BuFg=", "path": "gopkg.in/fsnotify.v1", "revision": "30411dbcefb7a1da7e84f75530ad3abe4011b4f8", "revisionTime": "2016-04-12T13:37:56Z" }, { "checksumSHA1": "pfQwQtWlFezJq0Viroa/L+v+yDM=", "origin": "k8s.io/client-go/1.5/vendor/gopkg.in/inf.v0", "path": "gopkg.in/inf.v0", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "KgT+peLCcuh0/m2mpoOZXuxXmwc=", "path": "gopkg.in/yaml.v2", "revision": "7ad95dd0798a40da1ccdff6dff35fd177b5edf40", "revisionTime": "2015-06-24T11:29:02+01:00" }, { "checksumSHA1": "st0Nbu4zwLcP3mz03lDOJVZtn8Y=", "path": "k8s.io/client-go/1.5/discovery", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "S+OzpkipMb46LGZoWuveqSLAcoM=", "path": "k8s.io/client-go/1.5/kubernetes", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "yCBn8ig1TUMrk+ljtK0nDr7E5Vo=", "path": "k8s.io/client-go/1.5/kubernetes/typed/apps/v1alpha1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "ZRnUz5NrpvJsXAjtnRdEv5UYhSI=", "path": "k8s.io/client-go/1.5/kubernetes/typed/authentication/v1beta1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "TY55Np20olmPMzXgfVlIUIyqv04=", "path": "k8s.io/client-go/1.5/kubernetes/typed/authorization/v1beta1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "FRByJsFff/6lPH20FtJPaK1NPWI=", "path": "k8s.io/client-go/1.5/kubernetes/typed/autoscaling/v1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "3Cy2as7HnQ2FDcvpNbatpFWx0P4=", "path": "k8s.io/client-go/1.5/kubernetes/typed/batch/v1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "RUKywApIbSLLsfkYxXzifh7HIvs=", "path": "k8s.io/client-go/1.5/kubernetes/typed/certificates/v1alpha1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "4+Lsxu+sYgzsS2JOHP7CdrZLSKc=", "path": "k8s.io/client-go/1.5/kubernetes/typed/core/v1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "H8jzevN03YUfmf2krJt0qj2P9sU=", "path": "k8s.io/client-go/1.5/kubernetes/typed/extensions/v1beta1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "hrpA6xxtwj3oMcQbFxI2cDhO2ZA=", "path": "k8s.io/client-go/1.5/kubernetes/typed/policy/v1alpha1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "B2+F12NeMwrOHvHK2ALyEcr3UGA=", "path": "k8s.io/client-go/1.5/kubernetes/typed/rbac/v1alpha1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "h2eSNUym87RWPlez7UKujShwrUQ=", "path": "k8s.io/client-go/1.5/kubernetes/typed/storage/v1beta1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "+oIykJ3A0wYjAWbbrGo0jNnMLXw=", "path": "k8s.io/client-go/1.5/pkg/api", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "UsUsIdhuy5Ej2vI0hbmSsrimoaQ=", "path": "k8s.io/client-go/1.5/pkg/api/errors", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "Eo6LLHFqG6YznIAKr2mVjuqUj6k=", "path": "k8s.io/client-go/1.5/pkg/api/install", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "dYznkLcCEai21z1dX8kZY7uDsck=", "path": "k8s.io/client-go/1.5/pkg/api/meta", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "b06esG4xMj/YNFD85Lqq00cx+Yo=", "path": "k8s.io/client-go/1.5/pkg/api/meta/metatypes", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "L9svak1yut0Mx8r9VLDOwpqZzBk=", "path": "k8s.io/client-go/1.5/pkg/api/resource", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "m7jGshKDLH9kdokfa6MwAqzxRQk=", "path": "k8s.io/client-go/1.5/pkg/api/unversioned", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "iI6s5WAexr1PEfqrbvuscB+oVik=", "path": "k8s.io/client-go/1.5/pkg/api/v1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "ikac34qI/IkTWHnfi8pPl9irPyo=", "path": "k8s.io/client-go/1.5/pkg/api/validation/path", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "MJyygSPp8N6z+7SPtcROz4PEwas=", "path": "k8s.io/client-go/1.5/pkg/apimachinery", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "EGb4IcSTQ1VXCmX0xcyG5GpWId8=", "path": "k8s.io/client-go/1.5/pkg/apimachinery/announced", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "vhSyuINHQhCsDKTyBmvJT1HzDHI=", "path": "k8s.io/client-go/1.5/pkg/apimachinery/registered", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "rXeBnwLg8ZFe6m5/Ki7tELVBYDk=", "path": "k8s.io/client-go/1.5/pkg/apis/apps", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "KzHaG858KV1tBh5cuLInNcm+G5s=", "path": "k8s.io/client-go/1.5/pkg/apis/apps/install", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "fynWdchlRbPaxuST2oGDKiKLTqE=", "path": "k8s.io/client-go/1.5/pkg/apis/apps/v1alpha1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "hreIYssoH4Ef/+Aglpitn3GNLR4=", "path": "k8s.io/client-go/1.5/pkg/apis/authentication", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "EgUqJH4CqB9vXVg6T8II2OEt5LE=", "path": "k8s.io/client-go/1.5/pkg/apis/authentication/install", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "Z3DKgomzRPGcBv/8hlL6pfnIpXI=", "path": "k8s.io/client-go/1.5/pkg/apis/authentication/v1beta1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "GpuScB2Z+NOT4WIQg1mVvVSDUts=", "path": "k8s.io/client-go/1.5/pkg/apis/authorization", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "+u3UD+HY9lBH+PFi/2B4W564JEw=", "path": "k8s.io/client-go/1.5/pkg/apis/authorization/install", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "zIFzgWjmlWNLHGHMpCpDCvoLtKY=", "path": "k8s.io/client-go/1.5/pkg/apis/authorization/v1beta1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "tdpzQFQyVkt5kCLTvtKTVqT+maE=", "path": "k8s.io/client-go/1.5/pkg/apis/autoscaling", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "nb6LbYGS5tv8H8Ovptg6M7XuDZ4=", "path": "k8s.io/client-go/1.5/pkg/apis/autoscaling/install", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "DNb1/nl/5RDdckRrJoXBRagzJXs=", "path": "k8s.io/client-go/1.5/pkg/apis/autoscaling/v1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "4bLhH2vNl5l4Qp6MjLhWyWVAPE0=", "path": "k8s.io/client-go/1.5/pkg/apis/batch", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "RpAAEynmxlvOlLLZK1KEUQRnYzk=", "path": "k8s.io/client-go/1.5/pkg/apis/batch/install", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "uWJ2BHmjL/Gq4FFlNkqiN6vvPyM=", "path": "k8s.io/client-go/1.5/pkg/apis/batch/v1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "mHWt/p724dKeP1vqLtWQCye7zaE=", "path": "k8s.io/client-go/1.5/pkg/apis/batch/v2alpha1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "6dJ1dGfXkB3A42TOtMaY/rvv4N8=", "path": "k8s.io/client-go/1.5/pkg/apis/certificates", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "Bkrhm6HbFYANwtzUE8eza9SWBk0=", "path": "k8s.io/client-go/1.5/pkg/apis/certificates/install", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "nRRPIBQ5O3Ad24kscNtK+gPC+fk=", "path": "k8s.io/client-go/1.5/pkg/apis/certificates/v1alpha1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "KUMhoaOg9GXHN/aAVvSLO18SgqU=", "path": "k8s.io/client-go/1.5/pkg/apis/extensions", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "eSo2VhNAYtesvmpEPqn05goW4LY=", "path": "k8s.io/client-go/1.5/pkg/apis/extensions/install", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "DunWIPrCC5iGMWzkaaugMOxD+hg=", "path": "k8s.io/client-go/1.5/pkg/apis/extensions/v1beta1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "rVGYi2ko0E7vL5OZSMYX+NAGPYw=", "path": "k8s.io/client-go/1.5/pkg/apis/policy", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "llJHd2H0LzABGB6BcletzIHnexo=", "path": "k8s.io/client-go/1.5/pkg/apis/policy/install", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "j44bqyY13ldnuCtysYE8nRkMD7o=", "path": "k8s.io/client-go/1.5/pkg/apis/policy/v1alpha1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "vT7rFxowcKMTYc55mddePqUFRgE=", "path": "k8s.io/client-go/1.5/pkg/apis/rbac", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "r1MzUXsG+Zyn30aU8I5R5dgrJPA=", "path": "k8s.io/client-go/1.5/pkg/apis/rbac/install", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "aNfO8xn8VDO3fM9CpVCe6EIB+GA=", "path": "k8s.io/client-go/1.5/pkg/apis/rbac/v1alpha1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "rQCxrbisCXmj2wymlYG63kcTL9I=", "path": "k8s.io/client-go/1.5/pkg/apis/storage", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "wZyxh5nt5Eh6kF7YNAIYukKWWy0=", "path": "k8s.io/client-go/1.5/pkg/apis/storage/install", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "P8ANOt/I4Cs3QtjVXWmDA/gpQdg=", "path": "k8s.io/client-go/1.5/pkg/apis/storage/v1beta1", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "qnVPwzvNLz2mmr3BXdU9qIhQXXU=", "path": "k8s.io/client-go/1.5/pkg/auth/user", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "KrIchxhapSs242yAy8yrTS1XlZo=", "path": "k8s.io/client-go/1.5/pkg/conversion", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "weZqKFcOhcnF47eDDHXzluCKSF0=", "path": "k8s.io/client-go/1.5/pkg/conversion/queryparams", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "T3EMfyXZX5939/OOQ1JU+Nmbk4k=", "path": "k8s.io/client-go/1.5/pkg/fields", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "2v11s3EBH8UBl2qfImT29tQN2kM=", "path": "k8s.io/client-go/1.5/pkg/genericapiserver/openapi/common", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "GvBlph6PywK3zguou/T9kKNNdoQ=", "path": "k8s.io/client-go/1.5/pkg/labels", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "Vtrgy827r0rWzIAgvIWY4flu740=", "path": "k8s.io/client-go/1.5/pkg/runtime", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "SEcZqRATexhgHvDn+eHvMc07UJs=", "path": "k8s.io/client-go/1.5/pkg/runtime/serializer", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "qzYKG9YZSj8l/W1QVTOrGAry/BM=", "path": "k8s.io/client-go/1.5/pkg/runtime/serializer/json", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "F7h+8zZ0JPLYkac4KgSVljguBE4=", "path": "k8s.io/client-go/1.5/pkg/runtime/serializer/protobuf", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "CvySOL8C85e3y7EWQ+Au4cwUZJM=", "path": "k8s.io/client-go/1.5/pkg/runtime/serializer/recognizer", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "eCitoKeIun+lJzYFhAfdSIIicSM=", "path": "k8s.io/client-go/1.5/pkg/runtime/serializer/streaming", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "kVWvZuLGltJ4YqQsiaCLRRLDDK0=", "path": "k8s.io/client-go/1.5/pkg/runtime/serializer/versioning", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "m51+LAeQ9RK1KHX+l2iGcwbVCKs=", "path": "k8s.io/client-go/1.5/pkg/selection", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "dp4IWcC3U6a0HeOdVCDQWODWCbw=", "path": "k8s.io/client-go/1.5/pkg/third_party/forked/golang/reflect", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "ER898XJD1ox4d71gKZD8TLtTSpM=", "path": "k8s.io/client-go/1.5/pkg/types", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "BVdXtnLDlmBQksRPfHOIG+qdeVg=", "path": "k8s.io/client-go/1.5/pkg/util", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "nnh8Sa4dCupxRI4bbKaozGp1d/A=", "path": "k8s.io/client-go/1.5/pkg/util/cert", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "S32d5uduNlwouM8+mIz+ALpliUQ=", "path": "k8s.io/client-go/1.5/pkg/util/clock", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "Y6rWC0TUw2/uUeUjJ7kazyEUzBQ=", "path": "k8s.io/client-go/1.5/pkg/util/errors", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "C7IfEAdCOePw3/IraaZCNXuYXLw=", "path": "k8s.io/client-go/1.5/pkg/util/flowcontrol", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "EuslQHnhBSRXaWimYqLEqhMPV48=", "path": "k8s.io/client-go/1.5/pkg/util/framer", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "ByO18NbZwiifFr8qtLyfJAHXguA=", "path": "k8s.io/client-go/1.5/pkg/util/integer", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "ww+RfsoIlUBDwThg2oqC5QVz33Y=", "path": "k8s.io/client-go/1.5/pkg/util/intstr", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "7E8f8dLlXW7u6r9sggMjvB4HEiw=", "path": "k8s.io/client-go/1.5/pkg/util/json", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "d0pFZxMJG9j95acNmaIM1l+X+QU=", "path": "k8s.io/client-go/1.5/pkg/util/labels", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "wCN7u1lE+25neM9jXeI7aE8EAfk=", "path": "k8s.io/client-go/1.5/pkg/util/net", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "g+kBkxcb+tYmFtRRly+VE+JAIfw=", "path": "k8s.io/client-go/1.5/pkg/util/parsers", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "S4wUnE5VkaWWrkLbgPL/1oNLJ4g=", "path": "k8s.io/client-go/1.5/pkg/util/rand", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "8j9c2PqTKybtnymXbStNYRexRj8=", "path": "k8s.io/client-go/1.5/pkg/util/runtime", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "aAz4e8hLGs0+ZAz1TdA5tY/9e1A=", "path": "k8s.io/client-go/1.5/pkg/util/sets", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "P/fwh6QZ5tsjVyHTaASDWL3WaGs=", "path": "k8s.io/client-go/1.5/pkg/util/uuid", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "P9Bq/1qbF4SvnN9HyCTRpbUz7sQ=", "path": "k8s.io/client-go/1.5/pkg/util/validation", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "D0JIEjlP69cuPOZEdsSKeFgsnI8=", "path": "k8s.io/client-go/1.5/pkg/util/validation/field", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "T7ba8t8i+BtgClMgL+aMZM94fcI=", "path": "k8s.io/client-go/1.5/pkg/util/wait", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "6RCTv/KDiw7as4KeyrgU3XrUSQI=", "path": "k8s.io/client-go/1.5/pkg/util/yaml", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "OwKlsSeKtz1FBVC9cQ5gWRL5pKc=", "path": "k8s.io/client-go/1.5/pkg/version", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "Oil9WGw/dODbpBopn6LWQGS3DYg=", "path": "k8s.io/client-go/1.5/pkg/watch", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "r5alnRCbLaPsbTeJjjTVn/bt6uw=", "path": "k8s.io/client-go/1.5/pkg/watch/versioned", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "X1+ltyfHui/XCwDupXIf39+9gWQ=", "path": "k8s.io/client-go/1.5/plugin/pkg/client/auth", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "KYy+js37AS0ZT08g5uBr1ZoMPmE=", "path": "k8s.io/client-go/1.5/plugin/pkg/client/auth/gcp", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "wQ9G5++lbQpejqCzGHo037N3YcY=", "path": "k8s.io/client-go/1.5/plugin/pkg/client/auth/oidc", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "ABe8YfZVEDoRpAUqp2BKP8o1VIA=", "path": "k8s.io/client-go/1.5/rest", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "Gbe0Vs9hkI7X5hhbXUuWdRFffSI=", "path": "k8s.io/client-go/1.5/tools/cache", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "K/oOznXABjqSS1c2Fs407c5F8KA=", "path": "k8s.io/client-go/1.5/tools/clientcmd/api", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "c1PQ4WJRfpA9BYcFHW2+46hu5IE=", "path": "k8s.io/client-go/1.5/tools/metrics", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" }, { "checksumSHA1": "e4W2q+6wvjejv3V0UCI1mewTTro=", "path": "k8s.io/client-go/1.5/transport", "revision": "c589d0c9f0d81640c518354c7bcae77d99820aa3", "revisionTime": "2016-09-30T00:14:02Z" } ], "rootPath": "github.com/prometheus/prometheus" }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/dockerman.out
github.com/BurntSushi/toml f0aeabca5a127c4078abb8c8d64298b147264b55 github.com/cpuguy83/go-md2man a65d4d2de4d5f7c74868dfa9b202a3c8be315aaa github.com/fsnotify/fsnotify 30411dbcefb7a1da7e84f75530ad3abe4011b4f8 github.com/hashicorp/hcl da486364306ed66c218be9b7953e19173447c18b github.com/inconshreveable/mousetrap 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 github.com/magiconair/properties c265cfa48dda6474e208715ca93e987829f572f8 github.com/mitchellh/mapstructure d2dd0262208475919e1a362f675cfc0e7c10e905 github.com/russross/blackfriday 1d6b8e9301e720b08a8938b8c25c018285885438 github.com/shurcooL/sanitized_anchor_name 10ef21a441db47d8b13ebcc5fd2310f636973c77 github.com/spf13/cast 27b586b42e29bec072fe7379259cc719e1289da6 github.com/spf13/jwalterweatherman 33c24e77fb80341fe7130ee7c594256ff08ccc46 github.com/spf13/pflag dabebe21bf790f782ea4c7bbd2efc430de182afd github.com/spf13/viper c1ccc378a054ea8d4e38d8c67f6938d4760b53dd golang.org/x/sys 62bee037599929a6e9146f29d10dd5208c43507d gopkg.in/yaml.v2 a83829b6f1293c91addabc89d0571c246397bbf4 github.com/spf13/cobra v1.3
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/moby.out
github.com/Azure/go-ansiterm d6e3b3328b783f23731bc4d058875b0371ff8109 github.com/Microsoft/hcsshim v0.6.5 github.com/Microsoft/go-winio v0.4.5 github.com/davecgh/go-spew 346938d642f2ec3594ed81d874461961cd0faa76 github.com/docker/libtrust 9cbd2a1374f46905c68a4eb3694a130610adc62a github.com/go-check/check 4ed411733c5785b40214c70bce814c3a3a689609 github.com/gorilla/context v1.1 github.com/gorilla/mux v1.1 github.com/Microsoft/opengcs v0.3.4 github.com/kr/pty 5cf931ef8f github.com/mattn/go-shellwords v1.0.3 github.com/sirupsen/logrus v1.0.3 github.com/tchap/go-patricia v2.2.6 github.com/vdemeester/shakers 24d7f1d6a71aa5d9cbe7390e4afb66b7eef9e1b3 golang.org/x/net 7dcfb8076726a3fdd9353b6b8a1f1b6be6811bd6 golang.org/x/sys 07c182904dbd53199946ba614a412c61d3c548f5 github.com/docker/go-units 9e638d38cf6977a37a8ea0078f3ee75a7cdb2dd1 github.com/docker/go-connections 3ede32e2033de7505e6500d6c868c2b9ed9f169d golang.org/x/text f72d8390a633d5dfb0cc84043294db9f6c935756 github.com/stretchr/testify 4d4bfba8f1d1027c4fdbe371823030df51419987 github.com/pmezard/go-difflib v1.0.0 github.com/gotestyourself/gotestyourself v1.1.0 github.com/RackSec/srslog 456df3a81436d29ba874f3590eeeee25d666f8a5 github.com/imdario/mergo 0.2.1 golang.org/x/sync de49d9dcd27d4f764488181bea099dfe6179bcf0 github.com/containerd/continuity 22694c680ee48fb8f50015b44618517e2bde77e8 github.com/moby/buildkit aaff9d591ef128560018433fe61beb802e149de8 github.com/tonistiigi/fsutil dea3a0da73aee887fc02142d995be764106ac5e2 github.com/docker/libnetwork 68f1039f172434709a4550fe92e3e058406c74ce github.com/docker/go-events 9461782956ad83b30282bf90e31fa6a70c255ba9 github.com/armon/go-radix e39d623f12e8e41c7b5529e9a9dd67a1e2261f80 github.com/armon/go-metrics eb0af217e5e9747e41dd5303755356b62d28e3ec github.com/hashicorp/go-msgpack 71c2886f5a673a35f909803f38ece5810165097b github.com/hashicorp/memberlist v0.1.0 github.com/sean-/seed e2103e2c35297fb7e17febb81e49b312087a2372 github.com/hashicorp/go-sockaddr acd314c5781ea706c710d9ea70069fd2e110d61d github.com/hashicorp/go-multierror fcdddc395df1ddf4247c69bd436e84cfa0733f7e github.com/hashicorp/serf 598c54895cc5a7b1a24a398d635e8c0ea0959870 github.com/docker/libkv 1d8431073ae03cdaedb198a89722f3aab6d418ef github.com/vishvananda/netns 604eaf189ee867d8c147fafc28def2394e878d25 github.com/vishvananda/netlink bd6d5de5ccef2d66b0a26177928d0d8895d7f969 github.com/BurntSushi/toml f706d00e3de6abe700c994cdd545a1a4915af060 github.com/samuel/go-zookeeper d0e0d8e11f318e000a8cc434616d69e329edc374 github.com/deckarep/golang-set ef32fa3046d9f249d399f98ebaf9be944430fd1d github.com/coreos/etcd v3.2.1 github.com/coreos/go-semver v0.2.0 github.com/ugorji/go f1f1a805ed361a0e078bb537e4ea78cd37dcf065 github.com/hashicorp/consul v0.5.2 github.com/boltdb/bolt fff57c100f4dea1905678da7e90d92429dff2904 github.com/miekg/dns 75e6e86cc601825c5dbcd4e0c209eab180997cd7 github.com/docker/distribution edc3ab29cdff8694dd6feb85cfeb4b5f1b38ed9c github.com/vbatts/tar-split v0.10.1 github.com/opencontainers/go-digest a6d0ee40d4207ea02364bd3b9e8e77b9159ba1eb github.com/mistifyio/go-zfs 22c9b32c84eb0d0c6f4043b6e90fc94073de92fa github.com/pborman/uuid v1.0 google.golang.org/grpc v1.3.0 github.com/opencontainers/runc 0351df1c5a66838d0c392b4ac4cf9450de844e2d github.com/opencontainers/image-spec 372ad780f63454fbbbbcc7cf80e5b90245c13e13 github.com/opencontainers/runtime-spec v1.0.0 github.com/seccomp/libseccomp-golang 32f571b70023028bd57d9288c20efbcb237f3ce0 github.com/coreos/go-systemd v4 github.com/godbus/dbus v4.0.0 github.com/syndtr/gocapability 2c00daeb6c3b45114c80ac44119e7b8801fdd852 github.com/golang/protobuf 7a211bcf3bce0e3f1d74f9894916e6f116ae83b4 github.com/Graylog2/go-gelf v2 github.com/fluent/fluent-logger-golang v1.2.1 github.com/philhofer/fwd 98c11a7a6ec829d672b03833c3d69a7fae1ca972 github.com/tinylib/msgp 75ee40d2601edf122ef667e2a07d600d4c44490c github.com/fsnotify/fsnotify v1.4.2 github.com/aws/aws-sdk-go v1.4.22 github.com/go-ini/ini 060d7da055ba6ec5ea7a31f116332fe5efa04ce0 github.com/jmespath/go-jmespath 0b12d6b521d83fc7f755e7cfc1b1fbdd35a01a74 github.com/bsphere/le_go 7a984a84b5492ae539b79b62fb4a10afc63c7bcf golang.org/x/oauth2 96382aa079b72d8c014eb0c50f6c223d1e6a2de0 google.golang.org/api 3cc2e591b550923a2c5f0ab5a803feda924d5823 cloud.google.com/go 9d965e63e8cceb1b5d7977a202f0fcb8866d6525 github.com/googleapis/gax-go da06d194a00e19ce00d9011a13931c3f6f6887c7 google.golang.org/genproto d80a6e20e776b0b17a324d0ba1ab50a39c8e8944 github.com/containerd/containerd 06b9cb35161009dcb7123345749fef02f7cea8e0 github.com/tonistiigi/fifo 1405643975692217d6720f8b54aeee1bf2cd5cf4 github.com/docker/swarmkit 872861d2ae46958af7ead1d5fffb092c73afbaf0 github.com/gogo/protobuf v0.4 github.com/cloudflare/cfssl 7fb22c8cba7ecaf98e4082d22d65800cf45e042a github.com/google/certificate-transparency d90e65c3a07988180c5b1ece71791c0b6506826e golang.org/x/crypto 558b6879de74bc843225cde5686419267ff707ca golang.org/x/time a4bde12657593d5e90d0533a3e4fd95e635124cb github.com/hashicorp/go-memdb cb9a474f84cc5e41b273b20c6927680b2a8776ad github.com/hashicorp/go-immutable-radix 8e8ed81f8f0bf1bdd829593fdd5c29922c1ea990 github.com/hashicorp/golang-lru a0d98a5f288019575c6d1f4bb1573fef2d1fcdc4 github.com/coreos/pkg fa29b1d70f0beaddd4c7021607cc3c3be8ce94b8 github.com/pivotal-golang/clock 3fd3c1944c59d9742e1cd333672181cd1a6f9fa0 github.com/prometheus/client_golang 52437c81da6b127a9925d17eb3a382a2e5fd395e github.com/beorn7/perks 4c0e84591b9aa9e6dcfdf3e020114cd81f89d5f9 github.com/prometheus/client_model fa8ad6fec33561be4280a8f0514318c79d7f6cb6 github.com/prometheus/common ebdfc6da46522d58825777cf1f90490a5b1ef1d8 github.com/prometheus/procfs abf152e5f3e97f2fafac028d2cc06c1feb87ffa5 github.com/matttproud/golang_protobuf_extensions v1.0.0 github.com/pkg/errors 839d9e913e063e28dfd0e6c7b7512793e0a48be9 github.com/grpc-ecosystem/go-grpc-prometheus 6b7015e65d366bf3f19b2b2a000a831940f0f7e0 github.com/spf13/cobra v1.5.1 github.com/spf13/pflag 9ff6c6923cfffbcd502984b8e0c80539a94968b7 github.com/inconshreveable/mousetrap 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 github.com/Nvveen/Gotty a8b993ba6abdb0e0c12b0125c603323a71c7790c github.com/docker/go-metrics d466d4f6fd960e01820085bd7e1a24426ee7ef18 github.com/opencontainers/selinux v1.0.0-rc1
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/govmomi.vmanifest
{ "version": 0, "dependencies": [ { "importpath": "github.com/davecgh/go-xdr/xdr2", "repository": "https://github.com/rasky/go-xdr", "vcs": "git", "revision": "4930550ba2e22f87187498acfd78348b15f4e7a8", "branch": "improvements", "path": "/xdr2", "notests": true }, { "importpath": "github.com/google/uuid", "repository": "https://github.com/google/uuid", "vcs": "git", "revision": "6a5e28554805e78ea6141142aba763936c4761c0", "branch": "master", "notests": true }, { "importpath": "github.com/kr/pretty", "repository": "https://github.com/dougm/pretty", "vcs": "git", "revision": "2ee9d7453c02ef7fa518a83ae23644eb8872186a", "branch": "govmomi", "notests": true }, { "importpath": "github.com/kr/pty", "repository": "https://github.com/kr/pty", "vcs": "git", "revision": "95d05c1eef33a45bd58676b6ce28d105839b8d0b", "branch": "master", "notests": true }, { "importpath": "github.com/vmware/vmw-guestinfo", "repository": "https://github.com/vmware/vmw-guestinfo", "vcs": "git", "revision": "25eff159a728be87e103a0b8045e08273f4dbec4", "branch": "master", "notests": true } ] }
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/cockroach.out
github.com/agtorre/gocolorize f42b554bf7f006936130c9bb4f971afd2d87f671 github.com/biogo/store e1f74b3c58befe661feed7fa4cf52436de753128 github.com/cockroachdb/c-lz4 6e71f140a365017bbe0904710007f8725fd3f809 github.com/cockroachdb/c-protobuf 0f9ab7b988ca7474cf76b9a961ab03c0552abcb3 github.com/cockroachdb/c-rocksdb 7fc876fe79b96de0e25069c9ae27e6444637bd54 github.com/cockroachdb/c-snappy 618733f9e5bab8463b9049117a335a7a1bfc9fd5 github.com/cockroachdb/yacc 572e006f8e6b0061ebda949d13744f5108389514 github.com/coreos/etcd 18ecc297bc913bed6fc093d66b1fa22020dba7dc github.com/docker/docker 7374852be9def787921aea2ca831771982badecf github.com/elazarl/go-bindata-assetfs 3dcc96556217539f50599357fb481ac0dc7439b9 github.com/gogo/protobuf 98e73e511a62a9c232152f94999112c80142a813 github.com/golang/lint 7b7f4364ff76043e6c3610281525fabc0d90f0e4 github.com/google/btree cc6329d4279e3f025a53a83c397d2339b5705c45 github.com/inconshreveable/mousetrap 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 github.com/jteeuwen/go-bindata dce55d09e24ac40a6e725c8420902b86554f8046 github.com/julienschmidt/httprouter 6aacfd5ab513e34f7e64ea9627ab9670371b34e7 github.com/kisielk/errcheck 50b84cf7fa18ee2985b8c63ba3de5edd604b9259 github.com/kisielk/gotool d678387370a2eb9b5b0a33218bc8c9d8de15b6be github.com/lib/pq a8d8d01c4f91602f876bf5aa210274e8203a6b45 github.com/montanaflynn/stats 44fb56da2a2a67d394dec0e18a82dd316f192529 github.com/peterh/liner 1bb0d1c1a25ed393d8feb09bab039b2b1b1fbced github.com/robfig/glock cb3c3ec56de988289cab7bbd284eddc04dfee6c9 github.com/samalba/dockerclient 12570e600d71374233e5056ba315f657ced496c7 github.com/spf13/cobra 66816bcd0378e248c613e3c443c020f544c28804 github.com/spf13/pflag 67cbc198fd11dab704b214c1e629a97af392c085 github.com/tebeka/go2xunit d45000af2242dd0e7b8c7b07d82a1068adc5fd40 golang.org/x/crypto cc04154d65fb9296747569b107cfd05380b1ea3e golang.org/x/net 8bfde94a845cb31000de3266ac83edbda58dab09 golang.org/x/text d4cc1b1e16b49d6dafc4982403b40fe89c512cd5 golang.org/x/tools d02228d1857b9f49cd0252788516ff5584266eb6 gopkg.in/yaml.v1 9f9df34309c04878acc86042b16630b0f696e1de
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/upspin.dep
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. [[projects]] branch = "master" name = "bazil.org/fuse" packages = [".","fs","fuseutil"] revision = "371fbbdaa8987b715bdd21d6adc4c9b20155f748" [[projects]] branch = "master" name = "github.com/NYTimes/gziphandler" packages = ["."] revision = "97ae7fbaf81620fe97840685304a78a306a39c64" [[projects]] branch = "master" name = "github.com/golang/protobuf" packages = ["proto"] revision = "1643683e1b54a9e88ad26d98f81400c8c9d9f4f9" [[projects]] branch = "master" name = "github.com/russross/blackfriday" packages = ["."] revision = "6d1ef893fcb01b4f50cb6e57ed7df3e2e627b6b2" [[projects]] branch = "master" name = "golang.org/x/crypto" packages = ["acme","acme/autocert","hkdf"] revision = "13931e22f9e72ea58bb73048bc752b48c6d4d4ac" [[projects]] branch = "master" name = "golang.org/x/net" packages = ["context"] revision = "4b14673ba32bee7f5ac0f990a48f033919fd418b" [[projects]] branch = "master" name = "golang.org/x/text" packages = ["cases","internal","internal/gen","internal/tag","internal/triegen","internal/ucd","language","runes","secure/bidirule","secure/precis","transform","unicode/bidi","unicode/cldr","unicode/norm","unicode/rangetable","width"] revision = "6eab0e8f74e86c598ec3b6fad4888e0c11482d48" [[projects]] branch = "v2" name = "gopkg.in/yaml.v2" packages = ["."] revision = "eb3733d160e74a9c7e442f435eb3bea458e1d19f" [solve-meta] analyzer-name = "dep" analyzer-version = 1 inputs-digest = "2246e647ba1c78b0b9f948f9fb072fff1467284fb138709c063e99736f646b90" solver-name = "gps-cdcl" solver-version = 1
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/dockermachine.out
code.google.com/p/goauth2/oauth afe77d958c701557ec5dc56f6936fcc194d15520 github.com/MSOpenTech/azure-sdk-for-go 515f3ec74ce6a5b31e934cefae997c97bd0a1b1e github.com/cenkalti/backoff 9831e1e25c874e0a0601b6dc43641071414eec7a github.com/codegangsta/cli e1712f381785e32046927f64a7c86fe569203196 github.com/digitalocean/godo 5478aae80694de1d2d0e02c386bbedd201266234 github.com/docker/docker/dockerversion a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/docker/engine a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/docker/pkg/archive a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/docker/pkg/fileutils a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/docker/pkg/ioutils a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/docker/pkg/mflag a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/docker/pkg/parsers a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/docker/pkg/pools a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/docker/pkg/promise a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/docker/pkg/system a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/docker/pkg/term a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/docker/pkg/timeutils a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/docker/pkg/units a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/docker/pkg/version a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar a8a31eff10544860d2188dddabdee4d727545796 github.com/docker/libtrust c54fbb67c1f1e68d7d6f8d2ad7c9360404616a41 github.com/google/go-querystring/query 30f7a39f4a218feb5325f3aebc60c32a572a8274 github.com/mitchellh/mapstructure 740c764bc6149d3f1806231418adb9f52c11bcbf github.com/rackspace/gophercloud ce0f487f6747ab43c4e4404722df25349385bebd github.com/skarademir/naturalsort 983d4d86054d80f91fd04dd62ec52c1d078ce403 github.com/smartystreets/go-aws-auth 1f0db8c0ee6362470abe06a94e3385927ed72a4b github.com/stretchr/testify/assert e4ec8152c15fc46bd5056ce65997a07c7d415325 github.com/pyr/egoscale/src/egoscale bbaa67324aeeacc90430c1fe0a9c620d3929512e github.com/tent/http-link-go ac974c61c2f990f4115b119354b5e0b47550e888 github.com/vmware/govcloudair 66a23eaabc61518f91769939ff541886fe1dceef golang.org/x/crypto/ssh 1fbbd62cfec66bd39d91e97749579579d4d3037e google.golang.org/api/compute/v1 aa91ac681e18e52b1a0dfe29b9d8354e88c0dcf5 google.golang.org/api/googleapi aa91ac681e18e52b1a0dfe29b9d8354e88c0dcf5
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/moby.vconf
# the following lines are in sorted order, FYI github.com/Azure/go-ansiterm d6e3b3328b783f23731bc4d058875b0371ff8109 github.com/Microsoft/hcsshim v0.6.5 github.com/Microsoft/go-winio v0.4.5 github.com/davecgh/go-spew 346938d642f2ec3594ed81d874461961cd0faa76 github.com/docker/libtrust 9cbd2a1374f46905c68a4eb3694a130610adc62a github.com/go-check/check 4ed411733c5785b40214c70bce814c3a3a689609 https://github.com/cpuguy83/check.git github.com/gorilla/context v1.1 github.com/gorilla/mux v1.1 github.com/Microsoft/opengcs v0.3.4 github.com/kr/pty 5cf931ef8f github.com/mattn/go-shellwords v1.0.3 github.com/sirupsen/logrus v1.0.3 github.com/tchap/go-patricia v2.2.6 github.com/vdemeester/shakers 24d7f1d6a71aa5d9cbe7390e4afb66b7eef9e1b3 golang.org/x/net 7dcfb8076726a3fdd9353b6b8a1f1b6be6811bd6 golang.org/x/sys 07c182904dbd53199946ba614a412c61d3c548f5 github.com/docker/go-units 9e638d38cf6977a37a8ea0078f3ee75a7cdb2dd1 github.com/docker/go-connections 3ede32e2033de7505e6500d6c868c2b9ed9f169d golang.org/x/text f72d8390a633d5dfb0cc84043294db9f6c935756 github.com/stretchr/testify 4d4bfba8f1d1027c4fdbe371823030df51419987 github.com/pmezard/go-difflib v1.0.0 github.com/gotestyourself/gotestyourself v1.1.0 github.com/RackSec/srslog 456df3a81436d29ba874f3590eeeee25d666f8a5 github.com/imdario/mergo 0.2.1 golang.org/x/sync de49d9dcd27d4f764488181bea099dfe6179bcf0 github.com/containerd/continuity 22694c680ee48fb8f50015b44618517e2bde77e8 github.com/moby/buildkit aaff9d591ef128560018433fe61beb802e149de8 github.com/tonistiigi/fsutil dea3a0da73aee887fc02142d995be764106ac5e2 #get libnetwork packages github.com/docker/libnetwork 68f1039f172434709a4550fe92e3e058406c74ce github.com/docker/go-events 9461782956ad83b30282bf90e31fa6a70c255ba9 github.com/armon/go-radix e39d623f12e8e41c7b5529e9a9dd67a1e2261f80 github.com/armon/go-metrics eb0af217e5e9747e41dd5303755356b62d28e3ec github.com/hashicorp/go-msgpack 71c2886f5a673a35f909803f38ece5810165097b github.com/hashicorp/memberlist v0.1.0 github.com/sean-/seed e2103e2c35297fb7e17febb81e49b312087a2372 github.com/hashicorp/go-sockaddr acd314c5781ea706c710d9ea70069fd2e110d61d github.com/hashicorp/go-multierror fcdddc395df1ddf4247c69bd436e84cfa0733f7e github.com/hashicorp/serf 598c54895cc5a7b1a24a398d635e8c0ea0959870 github.com/docker/libkv 1d8431073ae03cdaedb198a89722f3aab6d418ef github.com/vishvananda/netns 604eaf189ee867d8c147fafc28def2394e878d25 github.com/vishvananda/netlink bd6d5de5ccef2d66b0a26177928d0d8895d7f969 github.com/BurntSushi/toml f706d00e3de6abe700c994cdd545a1a4915af060 github.com/samuel/go-zookeeper d0e0d8e11f318e000a8cc434616d69e329edc374 github.com/deckarep/golang-set ef32fa3046d9f249d399f98ebaf9be944430fd1d github.com/coreos/etcd v3.2.1 github.com/coreos/go-semver v0.2.0 github.com/ugorji/go f1f1a805ed361a0e078bb537e4ea78cd37dcf065 github.com/hashicorp/consul v0.5.2 github.com/boltdb/bolt fff57c100f4dea1905678da7e90d92429dff2904 github.com/miekg/dns 75e6e86cc601825c5dbcd4e0c209eab180997cd7 # get graph and distribution packages github.com/docker/distribution edc3ab29cdff8694dd6feb85cfeb4b5f1b38ed9c github.com/vbatts/tar-split v0.10.1 github.com/opencontainers/go-digest a6d0ee40d4207ea02364bd3b9e8e77b9159ba1eb # get go-zfs packages github.com/mistifyio/go-zfs 22c9b32c84eb0d0c6f4043b6e90fc94073de92fa github.com/pborman/uuid v1.0 google.golang.org/grpc v1.3.0 # When updating, also update RUNC_COMMIT in hack/dockerfile/binaries-commits accordingly github.com/opencontainers/runc 0351df1c5a66838d0c392b4ac4cf9450de844e2d github.com/opencontainers/image-spec 372ad780f63454fbbbbcc7cf80e5b90245c13e13 github.com/opencontainers/runtime-spec v1.0.0 github.com/seccomp/libseccomp-golang 32f571b70023028bd57d9288c20efbcb237f3ce0 # libcontainer deps (see src/github.com/opencontainers/runc/Godeps/Godeps.json) github.com/coreos/go-systemd v4 github.com/godbus/dbus v4.0.0 github.com/syndtr/gocapability 2c00daeb6c3b45114c80ac44119e7b8801fdd852 github.com/golang/protobuf 7a211bcf3bce0e3f1d74f9894916e6f116ae83b4 # gelf logging driver deps github.com/Graylog2/go-gelf v2 github.com/fluent/fluent-logger-golang v1.2.1 # fluent-logger-golang deps github.com/philhofer/fwd 98c11a7a6ec829d672b03833c3d69a7fae1ca972 github.com/tinylib/msgp 75ee40d2601edf122ef667e2a07d600d4c44490c # fsnotify github.com/fsnotify/fsnotify v1.4.2 # awslogs deps github.com/aws/aws-sdk-go v1.4.22 github.com/go-ini/ini 060d7da055ba6ec5ea7a31f116332fe5efa04ce0 github.com/jmespath/go-jmespath 0b12d6b521d83fc7f755e7cfc1b1fbdd35a01a74 # logentries github.com/bsphere/le_go 7a984a84b5492ae539b79b62fb4a10afc63c7bcf # gcplogs deps golang.org/x/oauth2 96382aa079b72d8c014eb0c50f6c223d1e6a2de0 google.golang.org/api 3cc2e591b550923a2c5f0ab5a803feda924d5823 cloud.google.com/go 9d965e63e8cceb1b5d7977a202f0fcb8866d6525 github.com/googleapis/gax-go da06d194a00e19ce00d9011a13931c3f6f6887c7 google.golang.org/genproto d80a6e20e776b0b17a324d0ba1ab50a39c8e8944 # containerd github.com/containerd/containerd 06b9cb35161009dcb7123345749fef02f7cea8e0 github.com/tonistiigi/fifo 1405643975692217d6720f8b54aeee1bf2cd5cf4 # cluster github.com/docker/swarmkit 872861d2ae46958af7ead1d5fffb092c73afbaf0 github.com/gogo/protobuf v0.4 github.com/cloudflare/cfssl 7fb22c8cba7ecaf98e4082d22d65800cf45e042a github.com/google/certificate-transparency d90e65c3a07988180c5b1ece71791c0b6506826e golang.org/x/crypto 558b6879de74bc843225cde5686419267ff707ca golang.org/x/time a4bde12657593d5e90d0533a3e4fd95e635124cb github.com/hashicorp/go-memdb cb9a474f84cc5e41b273b20c6927680b2a8776ad github.com/hashicorp/go-immutable-radix 8e8ed81f8f0bf1bdd829593fdd5c29922c1ea990 github.com/hashicorp/golang-lru a0d98a5f288019575c6d1f4bb1573fef2d1fcdc4 github.com/coreos/pkg fa29b1d70f0beaddd4c7021607cc3c3be8ce94b8 github.com/pivotal-golang/clock 3fd3c1944c59d9742e1cd333672181cd1a6f9fa0 github.com/prometheus/client_golang 52437c81da6b127a9925d17eb3a382a2e5fd395e github.com/beorn7/perks 4c0e84591b9aa9e6dcfdf3e020114cd81f89d5f9 github.com/prometheus/client_model fa8ad6fec33561be4280a8f0514318c79d7f6cb6 github.com/prometheus/common ebdfc6da46522d58825777cf1f90490a5b1ef1d8 github.com/prometheus/procfs abf152e5f3e97f2fafac028d2cc06c1feb87ffa5 github.com/matttproud/golang_protobuf_extensions v1.0.0 github.com/pkg/errors 839d9e913e063e28dfd0e6c7b7512793e0a48be9 github.com/grpc-ecosystem/go-grpc-prometheus 6b7015e65d366bf3f19b2b2a000a831940f0f7e0 # cli github.com/spf13/cobra v1.5.1 https://github.com/dnephin/cobra.git github.com/spf13/pflag 9ff6c6923cfffbcd502984b8e0c80539a94968b7 github.com/inconshreveable/mousetrap 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 github.com/Nvveen/Gotty a8b993ba6abdb0e0c12b0125c603323a71c7790c https://github.com/ijc25/Gotty # metrics github.com/docker/go-metrics d466d4f6fd960e01820085bd7e1a24426ee7ef18 github.com/opencontainers/selinux v1.0.0-rc1 # archive/tar # mkdir -p ./vendor/archive # git clone git://github.com/tonistiigi/go-1.git ./go # git --git-dir ./go/.git --work-tree ./go checkout revert-prefix-ignore # cp -a go/src/archive/tar ./vendor/archive/tar # rm -rf ./go # vndr
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/prometheus.out
cloud.google.com/go/compute/metadata c589d0c9f0d81640c518354c7bcae77d99820aa3 cloud.google.com/go/internal c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/Azure/azure-sdk-for-go/arm/compute bd73d950fa4440dae889bd9917bff7cef539f86e github.com/Azure/azure-sdk-for-go/arm/network bd73d950fa4440dae889bd9917bff7cef539f86e github.com/Azure/go-autorest/autorest 8a25372bbfec739b8719a9e3987400d15ef9e179 github.com/Azure/go-autorest/autorest/azure 8a25372bbfec739b8719a9e3987400d15ef9e179 github.com/Azure/go-autorest/autorest/date 8a25372bbfec739b8719a9e3987400d15ef9e179 github.com/Azure/go-autorest/autorest/to 8a25372bbfec739b8719a9e3987400d15ef9e179 github.com/Azure/go-autorest/autorest/validation 8a25372bbfec739b8719a9e3987400d15ef9e179 github.com/PuerkitoBio/purell c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/PuerkitoBio/urlesc c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/asaskevich/govalidator 7b3beb6df3c42abd3509abfc3bcacc0fbfb7c877 github.com/aws/aws-sdk-go/aws 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/aws/awserr 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/aws/awsutil 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/aws/client 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/aws/client/metadata 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/aws/corehandlers 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/aws/credentials 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/aws/credentials/endpointcreds 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/aws/credentials/stscreds 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/aws/defaults 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/aws/ec2metadata 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/aws/request 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/aws/session 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/aws/signer/v4 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/private/endpoints 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/private/protocol 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/private/protocol/ec2query 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/private/protocol/query 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/private/protocol/query/queryutil 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/private/protocol/rest 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/private/waiter 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/service/ec2 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/aws/aws-sdk-go/service/sts 707203bc55114ed114446bf57949c5c211d8b7c0 github.com/beorn7/perks/quantile 3ac7bf7a47d159a033b107610db8a1b6575507a4 github.com/blang/semver c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/coreos/go-oidc/http c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/coreos/go-oidc/jose c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/coreos/go-oidc/key c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/coreos/go-oidc/oauth2 c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/coreos/go-oidc/oidc c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/coreos/pkg/health c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/coreos/pkg/httputil c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/coreos/pkg/timeutil c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/davecgh/go-spew/spew c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/dgrijalva/jwt-go 9ed569b5d1ac936e6494082958d63a6aa4fff99a github.com/docker/distribution/digest c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/docker/distribution/reference c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/emicklei/go-restful c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/emicklei/go-restful/log c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/emicklei/go-restful/swagger c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/ghodss/yaml c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/go-ini/ini 6e4869b434bd001f6983749881c7ead3545887d8 github.com/go-openapi/jsonpointer c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/go-openapi/jsonreference c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/go-openapi/spec c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/go-openapi/swag c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/gogo/protobuf/proto c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/gogo/protobuf/sortkeys c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/golang/glog c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/golang/protobuf/proto 98fa357170587e470c5f27d3c3ea0947b71eb455 github.com/golang/snappy d9eb7a3d35ec988b8585d4a0068e462c27d28380 github.com/google/gofuzz c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/hashicorp/consul/api daacc4be8bee214e3fc4b32a6dd385f5ef1b4c36 github.com/hashicorp/go-cleanhttp ad28ea4487f05916463e2423a55166280e8254b5 github.com/hashicorp/serf/coordinate 1d4fa605f6ff3ed628d7ae5eda7c0e56803e72a5 github.com/influxdb/influxdb/client 291aaeb9485b43b16875c238482b2f7d0a22a13b github.com/influxdb/influxdb/tsdb 291aaeb9485b43b16875c238482b2f7d0a22a13b github.com/jmespath/go-jmespath bd40a432e4c76585ef6b72d3fd96fb9b6dc7b68d github.com/jonboulle/clockwork c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/juju/ratelimit c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/julienschmidt/httprouter 109e267447e95ad1bb48b758e40dd7453eb7b039 github.com/mailru/easyjson/buffer c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/mailru/easyjson/jlexer c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/mailru/easyjson/jwriter c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/matttproud/golang_protobuf_extensions/pbutil fc2b8d3a73c4867e51861bbdd5ae3c1f0869dd6a github.com/miekg/dns 58f52c57ce9df13460ac68200cef30a008b9c468 github.com/pborman/uuid c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/pmezard/go-difflib/difflib d77da356e56a7428ad25149ca77381849a6a5232 github.com/prometheus/client_golang/prometheus c5b7fccd204277076155f10851dad72b76a49317 github.com/prometheus/client_model/go fa8ad6fec33561be4280a8f0514318c79d7f6cb6 github.com/prometheus/common/expfmt 85637ea67b04b5c3bb25e671dacded2977f8f9f6 github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg 85637ea67b04b5c3bb25e671dacded2977f8f9f6 github.com/prometheus/common/log 85637ea67b04b5c3bb25e671dacded2977f8f9f6 github.com/prometheus/common/model 85637ea67b04b5c3bb25e671dacded2977f8f9f6 github.com/prometheus/common/route 85637ea67b04b5c3bb25e671dacded2977f8f9f6 github.com/prometheus/common/version 85637ea67b04b5c3bb25e671dacded2977f8f9f6 github.com/prometheus/procfs abf152e5f3e97f2fafac028d2cc06c1feb87ffa5 github.com/samuel/go-zookeeper/zk 177002e16a0061912f02377e2dd8951a8b3551bc github.com/spf13/pflag c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/stretchr/testify/assert d77da356e56a7428ad25149ca77381849a6a5232 github.com/stretchr/testify/require d77da356e56a7428ad25149ca77381849a6a5232 github.com/syndtr/goleveldb/leveldb 6b4daa5362b502898ddf367c5c11deb9e7a5c727 github.com/syndtr/goleveldb/leveldb/cache 6b4daa5362b502898ddf367c5c11deb9e7a5c727 github.com/syndtr/goleveldb/leveldb/comparer 6b4daa5362b502898ddf367c5c11deb9e7a5c727 github.com/syndtr/goleveldb/leveldb/errors 6b4daa5362b502898ddf367c5c11deb9e7a5c727 github.com/syndtr/goleveldb/leveldb/filter 6b4daa5362b502898ddf367c5c11deb9e7a5c727 github.com/syndtr/goleveldb/leveldb/iterator 6b4daa5362b502898ddf367c5c11deb9e7a5c727 github.com/syndtr/goleveldb/leveldb/journal 6b4daa5362b502898ddf367c5c11deb9e7a5c727 github.com/syndtr/goleveldb/leveldb/memdb 6b4daa5362b502898ddf367c5c11deb9e7a5c727 github.com/syndtr/goleveldb/leveldb/opt 6b4daa5362b502898ddf367c5c11deb9e7a5c727 github.com/syndtr/goleveldb/leveldb/storage 6b4daa5362b502898ddf367c5c11deb9e7a5c727 github.com/syndtr/goleveldb/leveldb/table 6b4daa5362b502898ddf367c5c11deb9e7a5c727 github.com/syndtr/goleveldb/leveldb/util 6b4daa5362b502898ddf367c5c11deb9e7a5c727 github.com/ugorji/go/codec c589d0c9f0d81640c518354c7bcae77d99820aa3 github.com/vaughan0/go-ini a98ad7ee00ec53921f08832bc06ecf7fd600e6a1 golang.org/x/net/context b336a971b799939dd16ae9b1df8334cb8b977c4d golang.org/x/net/context/ctxhttp b336a971b799939dd16ae9b1df8334cb8b977c4d golang.org/x/net/http2 c589d0c9f0d81640c518354c7bcae77d99820aa3 golang.org/x/net/http2/hpack c589d0c9f0d81640c518354c7bcae77d99820aa3 golang.org/x/net/idna c589d0c9f0d81640c518354c7bcae77d99820aa3 golang.org/x/net/internal/timeseries 6250b412798208e6c90b03b7c4f226de5aa299e2 golang.org/x/net/lex/httplex c589d0c9f0d81640c518354c7bcae77d99820aa3 golang.org/x/net/netutil bc3663df0ac92f928d419e31e0d2af22e683a5a2 golang.org/x/oauth2 65a8d08c6292395d47053be10b3c5e91960def76 golang.org/x/oauth2/google 65a8d08c6292395d47053be10b3c5e91960def76 golang.org/x/oauth2/internal 65a8d08c6292395d47053be10b3c5e91960def76 golang.org/x/oauth2/jws 65a8d08c6292395d47053be10b3c5e91960def76 golang.org/x/oauth2/jwt 65a8d08c6292395d47053be10b3c5e91960def76 golang.org/x/sys/unix c200b10b5d5e122be351b67af224adc6128af5bf golang.org/x/sys/windows c200b10b5d5e122be351b67af224adc6128af5bf golang.org/x/sys/windows/registry c200b10b5d5e122be351b67af224adc6128af5bf golang.org/x/sys/windows/svc/eventlog c200b10b5d5e122be351b67af224adc6128af5bf golang.org/x/text/cases c589d0c9f0d81640c518354c7bcae77d99820aa3 golang.org/x/text/internal/tag c589d0c9f0d81640c518354c7bcae77d99820aa3 golang.org/x/text/language c589d0c9f0d81640c518354c7bcae77d99820aa3 golang.org/x/text/runes c589d0c9f0d81640c518354c7bcae77d99820aa3 golang.org/x/text/secure/bidirule c589d0c9f0d81640c518354c7bcae77d99820aa3 golang.org/x/text/secure/precis c589d0c9f0d81640c518354c7bcae77d99820aa3 golang.org/x/text/transform c589d0c9f0d81640c518354c7bcae77d99820aa3 golang.org/x/text/unicode/bidi c589d0c9f0d81640c518354c7bcae77d99820aa3 golang.org/x/text/unicode/norm c589d0c9f0d81640c518354c7bcae77d99820aa3 golang.org/x/text/width c589d0c9f0d81640c518354c7bcae77d99820aa3 google.golang.org/api/compute/v1 63ade871fd3aec1225809d496e81ec91ab76ea29 google.golang.org/api/gensupport 63ade871fd3aec1225809d496e81ec91ab76ea29 google.golang.org/api/googleapi 63ade871fd3aec1225809d496e81ec91ab76ea29 google.golang.org/api/googleapi/internal/uritemplates 63ade871fd3aec1225809d496e81ec91ab76ea29 google.golang.org/appengine 267c27e7492265b84fc6719503b14a1e17975d79 google.golang.org/appengine/internal 267c27e7492265b84fc6719503b14a1e17975d79 google.golang.org/appengine/internal/app_identity 267c27e7492265b84fc6719503b14a1e17975d79 google.golang.org/appengine/internal/base 267c27e7492265b84fc6719503b14a1e17975d79 google.golang.org/appengine/internal/datastore 267c27e7492265b84fc6719503b14a1e17975d79 google.golang.org/appengine/internal/log 267c27e7492265b84fc6719503b14a1e17975d79 google.golang.org/appengine/internal/modules 267c27e7492265b84fc6719503b14a1e17975d79 google.golang.org/appengine/internal/remote_api 4f7eeb5305a4ba1966344836ba4af9996b7b4e05 google.golang.org/appengine/internal/urlfetch 267c27e7492265b84fc6719503b14a1e17975d79 google.golang.org/appengine/urlfetch 267c27e7492265b84fc6719503b14a1e17975d79 google.golang.org/cloud/compute/metadata 0a83eba2cadb60eb22123673c8fb6fca02b03c94 google.golang.org/cloud/internal 0a83eba2cadb60eb22123673c8fb6fca02b03c94 gopkg.in/fsnotify.v1 30411dbcefb7a1da7e84f75530ad3abe4011b4f8 gopkg.in/inf.v0 c589d0c9f0d81640c518354c7bcae77d99820aa3 gopkg.in/yaml.v2 7ad95dd0798a40da1ccdff6dff35fd177b5edf40 k8s.io/client-go/1.5/discovery c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/kubernetes c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/kubernetes/typed/apps/v1alpha1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/kubernetes/typed/authentication/v1beta1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/kubernetes/typed/authorization/v1beta1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/kubernetes/typed/autoscaling/v1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/kubernetes/typed/batch/v1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/kubernetes/typed/certificates/v1alpha1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/kubernetes/typed/core/v1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/kubernetes/typed/extensions/v1beta1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/kubernetes/typed/policy/v1alpha1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/kubernetes/typed/rbac/v1alpha1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/kubernetes/typed/storage/v1beta1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/api c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/api/errors c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/api/install c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/api/meta c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/api/meta/metatypes c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/api/resource c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/api/unversioned c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/api/v1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/api/validation/path c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apimachinery c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apimachinery/announced c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apimachinery/registered c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/apps c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/apps/install c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/apps/v1alpha1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/authentication c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/authentication/install c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/authentication/v1beta1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/authorization c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/authorization/install c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/authorization/v1beta1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/autoscaling c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/autoscaling/install c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/autoscaling/v1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/batch c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/batch/install c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/batch/v1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/batch/v2alpha1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/certificates c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/certificates/install c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/certificates/v1alpha1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/extensions c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/extensions/install c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/extensions/v1beta1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/policy c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/policy/install c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/policy/v1alpha1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/rbac c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/rbac/install c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/rbac/v1alpha1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/storage c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/storage/install c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/apis/storage/v1beta1 c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/auth/user c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/conversion c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/conversion/queryparams c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/fields c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/genericapiserver/openapi/common c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/labels c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/runtime c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/runtime/serializer c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/runtime/serializer/json c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/runtime/serializer/protobuf c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/runtime/serializer/recognizer c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/runtime/serializer/streaming c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/runtime/serializer/versioning c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/selection c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/third_party/forked/golang/reflect c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/types c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/cert c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/clock c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/errors c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/flowcontrol c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/framer c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/integer c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/intstr c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/json c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/labels c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/net c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/parsers c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/rand c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/runtime c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/sets c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/uuid c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/validation c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/validation/field c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/wait c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/util/yaml c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/version c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/watch c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/pkg/watch/versioned c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/plugin/pkg/client/auth c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/plugin/pkg/client/auth/gcp c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/plugin/pkg/client/auth/oidc c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/rest c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/tools/cache c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/tools/clientcmd/api c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/tools/metrics c589d0c9f0d81640c518354c7bcae77d99820aa3 k8s.io/client-go/1.5/transport c589d0c9f0d81640c518354c7bcae77d99820aa3
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/juju.tsv
github.com/Azure/azure-sdk-for-go git 902d95d9f311ae585ee98cfd18f418b467d60d5a 2016-07-20T05:16:58Z github.com/Azure/go-autorest git 6f40a8acfe03270d792cb8155e2942c09d7cff95 2016-07-19T23:14:56Z github.com/ajstarks/svgo git 89e3ac64b5b3e403a5e7c35ea4f98d45db7b4518 2014-10-04T21:11:59Z github.com/altoros/gosigma git 31228935eec685587914528585da4eb9b073c76d 2015-04-08T14:52:32Z github.com/beorn7/perks git 3ac7bf7a47d159a033b107610db8a1b6575507a4 2016-02-29T21:34:45Z github.com/bmizerany/pat git c068ca2f0aacee5ac3681d68e4d0a003b7d1fd2c 2016-02-17T10:32:42Z github.com/coreos/go-systemd git 7b2428fec40033549c68f54e26e89e7ca9a9ce31 2016-02-02T21:14:25Z github.com/dgrijalva/jwt-go git 01aeca54ebda6e0fbfafd0a524d234159c05ec20 2016-07-05T20:30:06Z github.com/dustin/go-humanize git 145fabdb1ab757076a70a886d092a3af27f66f4c 2014-12-28T07:11:48Z github.com/godbus/dbus git 32c6cc29c14570de4cf6d7e7737d68fb2d01ad15 2016-05-06T22:25:50Z github.com/golang/protobuf git 4bd1920723d7b7c925de087aa32e2187708897f7 2016-11-09T07:27:36Z github.com/google/go-querystring git 9235644dd9e52eeae6fa48efd539fdc351a0af53 2016-04-01T23:30:42Z github.com/gorilla/schema git 08023a0215e7fc27a9aecd8b8c50913c40019478 2016-04-26T23:15:12Z github.com/gorilla/websocket git 804cb600d06b10672f2fbc0a336a7bee507a428e 2017-02-14T17:41:18Z github.com/gosuri/uitable git 36ee7e946282a3fb1cfecd476ddc9b35d8847e42 2016-04-04T20:39:58Z github.com/joyent/gocommon git ade826b8b54e81a779ccb29d358a45ba24b7809c 2016-03-20T19:31:33Z github.com/joyent/gosdc git 2f11feadd2d9891e92296a1077c3e2e56939547d 2014-05-24T00:08:15Z github.com/joyent/gosign git 0da0d5f1342065321c97812b1f4ac0c2b0bab56c 2014-05-24T00:07:34Z github.com/juju/ansiterm git b99631de12cf04a906c1d4e4ec54fb86eae5863d 2016-09-07T23:45:32Z github.com/juju/blobstore git 06056004b3d7b54bbb7984d830c537bad00fec21 2015-07-29T11:18:58Z github.com/juju/bundlechanges git 7725027b95e0d54635e0fb11efc2debdcdf19f75 2016-12-15T16:06:52Z github.com/juju/cmd git 9425a576247f348b9b40afe3b60085de63470de5 2017-03-20T01:37:09Z github.com/juju/description git d3742c23561884cd7d759ef7142340af1d22cab0 2017-03-20T07:46:40Z github.com/juju/errors git 1b5e39b83d1835fa480e0c2ddefb040ee82d58b3 2015-09-16T12:56:42Z github.com/juju/gnuflag git 4e76c56581859c14d9d87e1ddbe29e1c0f10195f 2016-08-09T16:52:14Z github.com/juju/go4 git 40d72ab9641a2a8c36a9c46a51e28367115c8e59 2016-02-22T16:32:58Z github.com/juju/gojsonpointer git afe8b77aa08f272b49e01b82de78510c11f61500 2015-02-04T19:46:29Z github.com/juju/gojsonreference git f0d24ac5ee330baa21721cdff56d45e4ee42628e 2015-02-04T19:46:33Z github.com/juju/gojsonschema git e1ad140384f254c82f89450d9a7c8dd38a632838 2015-03-12T17:00:16Z github.com/juju/gomaasapi git cfbc096bd45f276c17a391efc4db710b60ae3ad7 2017-02-27T07:51:07Z github.com/juju/httpprof git 14bf14c307672fd2456bdbf35d19cf0ccd3cf565 2014-12-17T16:00:36Z github.com/juju/httprequest git 266fd1e9debf09c037a63f074d099a2da4559ece 2016-10-06T15:09:09Z github.com/juju/idmclient git 4dc25171f675da4206b71695d3fd80e519ad05c1 2017-02-09T16:27:49Z github.com/juju/jsonschema git a0ef8b74ebcffeeff9fc374854deb4af388f037e 2016-11-02T18:19:19Z github.com/juju/loggo git 21bc4c63e8b435779a080e39e592969b7b90b889 2017-02-22T12:20:47Z github.com/juju/mempool git 24974d6c264fe5a29716e7d56ea24c4bd904b7cc 2016-02-05T10:49:27Z github.com/juju/mutex git 59c26ee163447c5c57f63ff71610d433862013de 2016-06-17T01:09:07Z github.com/juju/persistent-cookiejar git 5243747bf8f2d0897f6c7a52799327dc97d585e8 2016-11-15T13:33:28Z github.com/juju/pubsub git 9dcaca7eb4340dbf685aa7b3ad4cc4f8691a33d4 2016-07-28T03:00:34Z github.com/juju/replicaset git 6b5becf2232ce76656ea765d8d915d41755a1513 2016-11-25T16:08:49Z github.com/juju/retry git 62c62032529169c7ec02fa48f93349604c345e1f 2015-10-29T02:48:21Z github.com/juju/rfc git ebdbbdb950cd039a531d15cdc2ac2cbd94f068ee 2016-07-11T02:42:13Z github.com/juju/romulus git 98d6700423d63971f10ca14afea9ecf2b9b99f0f 2017-01-23T14:29:29Z github.com/juju/schema git 075de04f9b7d7580d60a1e12a0b3f50bb18e6998 2016-04-20T04:42:03Z github.com/juju/terms-client git 9b925afd677234e4146dde3cb1a11e187cbed64e 2016-08-09T13:19:00Z github.com/juju/testing git fce9bc4ebf7a77310c262ac4884e03b778eae06a 2017-02-22T09:01:19Z github.com/juju/txn git 28898197906200d603394d8e4ce537436529f1c5 2016-11-16T04:07:55Z github.com/juju/usso git 68a59c96c178fbbad65926e7f93db50a2cd14f33 2016-04-01T10:44:24Z github.com/juju/utils git 9f8aeb9b09e2d8c769be8317ccfa23f7eec62c26 2017-02-15T08:19:00Z github.com/juju/version git 1f41e27e54f21acccf9b2dddae063a782a8a7ceb 2016-10-31T05:19:06Z github.com/juju/webbrowser git 54b8c57083b4afb7dc75da7f13e2967b2606a507 2016-03-09T14:36:29Z github.com/juju/xml git eb759a627588d35166bc505fceb51b88500e291e 2015-04-13T13:11:21Z github.com/juju/zip git f6b1e93fa2e29a1d7d49b566b2b51efb060c982a 2016-02-05T10:52:21Z github.com/julienschmidt/httprouter git 77a895ad01ebc98a4dc95d8355bc825ce80a56f6 2015-10-13T22:55:20Z github.com/lestrrat/go-jspointer git f4881e611bdbe9fb413a7780721ef8400a1f2341 2016-02-29T02:13:54Z github.com/lestrrat/go-jsref git e452c7b5801d1c6494c9e7e0cbc7498c0f88dfd1 2016-06-01T01:32:40Z github.com/lestrrat/go-jsschema git b09d7650b822d2ea3dc83d5091a5e2acd8330051 2016-09-03T13:19:57Z github.com/lestrrat/go-jsval git b1258a10419fe0693f7b35ad65cd5074bc0ba1e5 2016-10-12T04:57:17Z github.com/lestrrat/go-pdebug git 2e6eaaa5717f81bda41d27070d3c966f40a1e75f 2016-08-17T06:33:33Z github.com/lestrrat/go-structinfo git f74c056fe41f860aa6264478c664a6fff8a64298 2016-03-08T13:11:05Z github.com/lunixbochs/vtclean git 4fbf7632a2c6d3fbdb9931439bdbbeded02cbe36 2016-01-25T03:51:06Z github.com/lxc/lxd git 23da0234979fa6299565b91b529a6dbeb42ee36d 2017-02-16T05:29:42Z github.com/masterzen/azure-sdk-for-go git ee4f0065d00cd12b542f18f5bc45799e88163b12 2016-10-14T13:56:28Z github.com/masterzen/simplexml git 4572e39b1ab9fe03ee513ce6fc7e289e98482190 2016-06-08T18:30:07Z github.com/masterzen/winrm git 7a535cd943fccaeed196718896beec3fb51aff41 2016-10-14T15:10:40Z github.com/masterzen/xmlpath git 13f4951698adc0fa9c1dda3e275d489a24201161 2014-02-18T18:59:01Z github.com/mattn/go-colorable git ed8eb9e318d7a84ce5915b495b7d35e0cfe7b5a8 2016-07-31T23:54:17Z github.com/mattn/go-isatty git 66b8e73f3f5cda9f96b69efd03dd3d7fc4a5cdb8 2016-08-06T12:27:52Z github.com/mattn/go-runewidth git d96d1bd051f2bd9e7e43d602782b37b93b1b5666 2015-11-18T07:21:59Z github.com/matttproud/golang_protobuf_extensions git c12348ce28de40eed0136aa2b644d0ee0650e56c 2016-04-24T11:30:07Z github.com/nu7hatch/gouuid git 179d4d0c4d8d407a32af483c2354df1d2c91e6c3 2013-12-21T20:05:32Z github.com/pkg/errors git 839d9e913e063e28dfd0e6c7b7512793e0a48be9 2016-10-02T05:25:12Z github.com/prometheus/client_golang git 575f371f7862609249a1be4c9145f429fe065e32 2016-11-24T15:57:32Z github.com/prometheus/client_model git fa8ad6fec33561be4280a8f0514318c79d7f6cb6 2015-02-12T10:17:44Z github.com/prometheus/common git dd586c1c5abb0be59e60f942c22af711a2008cb4 2016-05-03T22:05:32Z github.com/prometheus/procfs git abf152e5f3e97f2fafac028d2cc06c1feb87ffa5 2016-04-11T19:08:41Z github.com/rogpeppe/fastuuid git 6724a57986aff9bff1a1770e9347036def7c89f6 2015-01-06T09:32:20Z github.com/vmware/govmomi git c0c7ce63df7edd78e713257b924c89d9a2dac119 2016-06-30T15:37:42Z golang.org/x/crypto git 8e06e8ddd9629eb88639aba897641bff8031f1d3 2016-09-22T17:06:29Z golang.org/x/net git ea47fc708ee3e20177f3ca3716217c4ab75942cb 2015-08-29T23:03:18Z golang.org/x/oauth2 git 11c60b6f71a6ad48ed6f93c65fa4c6f9b1b5b46a 2015-03-25T02:00:22Z golang.org/x/sys git 7a6e5648d140666db5d920909e082ca00a87ba2c 2017-02-01T05:12:45Z golang.org/x/text git 2910a502d2bf9e43193af9d68ca516529614eed3 2016-07-26T16:48:57Z google.golang.org/api git 0d3983fb069cb6651353fc44c5cb604e263f2a93 2014-12-10T23:51:26Z google.golang.org/cloud git f20d6dcccb44ed49de45ae3703312cb46e627db1 2015-03-19T22:36:35Z gopkg.in/amz.v3 git 8c3190dff075bf5442c9eedbf8f8ed6144a099e7 2016-12-15T13:08:49Z gopkg.in/check.v1 git 4f90aeace3a26ad7021961c297b22c42160c7b25 2016-01-05T16:49:36Z gopkg.in/errgo.v1 git 442357a80af5c6bf9b6d51ae791a39c3421004f3 2016-12-22T12:58:16Z gopkg.in/goose.v1 git ac43167b647feacdd9a1e34ee81e574551bc748d 2017-02-15T01:56:23Z gopkg.in/ini.v1 git 776aa739ce9373377cd16f526cdf06cb4c89b40f 2016-02-22T23:24:41Z gopkg.in/juju/blobstore.v2 git 51fa6e26128d74e445c72d3a91af555151cc3654 2016-01-25T02:37:03Z gopkg.in/juju/charm.v6-unstable git 83771c4919d6810bce5b7e63f46bea5fbfed0b93 2016-10-03T20:31:18Z gopkg.in/juju/charmrepo.v2-unstable git e79aa298df89ea887c9bffec46063c24bfb730f7 2016-11-17T15:25:28Z gopkg.in/juju/charmstore.v5-unstable git fd1eef3002fc6b6daff5e97efab6f5056d22dcc7 2016-09-16T10:09:07Z gopkg.in/juju/environschema.v1 git 7359fc7857abe2b11b5b3e23811a9c64cb6b01e0 2015-11-04T11:58:10Z gopkg.in/juju/jujusvg.v2 git d82160011935ef79fc7aca84aba2c6f74700fe75 2016-06-09T10:52:15Z gopkg.in/juju/names.v2 git 0847c26d322a121e52614f969fb82eae2820c715 2016-11-02T13:43:03Z gopkg.in/juju/worker.v1 git 6965b9d826717287bb002e02d1fd4d079978083e 2017-03-08T00:24:58Z gopkg.in/macaroon-bakery.v1 git 469b44e6f1f9479e115c8ae879ef80695be624d5 2016-06-22T12:14:21Z gopkg.in/macaroon.v1 git ab3940c6c16510a850e1c2dd628b919f0f3f1464 2015-01-21T11:42:31Z gopkg.in/mgo.v2 git f2b6f6c918c452ad107eec89615f074e3bd80e33 2016-08-18T01:52:18Z gopkg.in/natefinch/lumberjack.v2 git 514cbda263a734ae8caac038dadf05f8f3f9f738 2016-01-25T11:17:49Z gopkg.in/natefinch/npipe.v2 git c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6 2016-06-21T03:49:01Z gopkg.in/retry.v1 git c09f6b86ba4d5d2cf5bdf0665364aec9fd4815db 2016-10-25T18:14:30Z gopkg.in/tomb.v1 git dd632973f1e7218eb1089048e0798ec9ae7dceb8 2014-10-24T13:56:13Z gopkg.in/yaml.v2 git a3f3340b5840cee44f372bddb5880fcbc419b46a 2017-02-08T14:18:51Z
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/upspin.out
bazil.org/fuse 371fbbdaa8987b715bdd21d6adc4c9b20155f748 github.com/NYTimes/gziphandler 97ae7fbaf81620fe97840685304a78a306a39c64 github.com/golang/protobuf 1643683e1b54a9e88ad26d98f81400c8c9d9f4f9 github.com/russross/blackfriday 6d1ef893fcb01b4f50cb6e57ed7df3e2e627b6b2 golang.org/x/crypto 13931e22f9e72ea58bb73048bc752b48c6d4d4ac golang.org/x/net 4b14673ba32bee7f5ac0f990a48f033919fd418b golang.org/x/text 6eab0e8f74e86c598ec3b6fad4888e0c11482d48 gopkg.in/yaml.v2 eb3733d160e74a9c7e442f435eb3bea458e1d19f
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/panicparse.out
github.com/kr/pretty 737b74a46c4bf788349f72cb256fed10aea4d0ac github.com/kr/text 7cafcd837844e784b526369c9bce262804aebc60 github.com/maruel/ut a9c9f15ccfa6f8b90182a53df32f4745586fbae3 github.com/mattn/go-colorable 9056b7a9f2d1f2d96498d6d146acd1f9d5ed3d59 github.com/mattn/go-isatty 56b76bdf51f7708750eac80fa38b952bb9f32639 github.com/mgutz/ansi c286dcecd19ff979eeb73ea444e479b903f2cfcb github.com/pmezard/go-difflib 792786c7400a136282c1664665ae0a8db921c6c2 golang.org/x/sys a646d33e2ee3172a661fc09bca23bb4889a41bc8
testdata
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modconv/testdata/panicparse.vyml
vendors: - path: github.com/kr/pretty rev: 737b74a46c4bf788349f72cb256fed10aea4d0ac - path: github.com/kr/text rev: 7cafcd837844e784b526369c9bce262804aebc60 - path: github.com/maruel/ut rev: a9c9f15ccfa6f8b90182a53df32f4745586fbae3 - path: github.com/mattn/go-colorable rev: 9056b7a9f2d1f2d96498d6d146acd1f9d5ed3d59 - path: github.com/mattn/go-isatty rev: 56b76bdf51f7708750eac80fa38b952bb9f32639 - path: github.com/mgutz/ansi rev: c286dcecd19ff979eeb73ea444e479b903f2cfcb - path: github.com/pmezard/go-difflib rev: 792786c7400a136282c1664665ae0a8db921c6c2 - path: golang.org/x/sys rev: a646d33e2ee3172a661fc09bca23bb4889a41bc8
web
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/web/http.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 !cmd_go_bootstrap // This code is compiled into the real 'go' binary, but it is not // compiled into the binary that is built during all.bash, so as // to avoid needing to build net (and thus use cgo) during the // bootstrap process. package web import ( "crypto/tls" "fmt" "io" "io/ioutil" "log" "net/http" "net/url" "time" "cmd/go/internal/cfg" "cmd/internal/browser" ) // httpClient is the default HTTP client, but a variable so it can be // changed by tests, without modifying http.DefaultClient. var httpClient = http.DefaultClient // impatientInsecureHTTPClient is used in -insecure mode, // when we're connecting to https servers that might not be there // or might be using self-signed certificates. var impatientInsecureHTTPClient = &http.Client{ Timeout: 5 * time.Second, Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, }, } type HTTPError struct { status string StatusCode int url string } func (e *HTTPError) Error() string { return fmt.Sprintf("%s: %s", e.url, e.status) } // Get returns the data from an HTTP GET request for the given URL. func Get(url string) ([]byte, error) { resp, err := httpClient.Get(url) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != 200 { err := &HTTPError{status: resp.Status, StatusCode: resp.StatusCode, url: url} return nil, err } b, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("%s: %v", url, err) } return b, nil } // GetMaybeInsecure returns the body of either the importPath's // https resource or, if unavailable and permitted by the security mode, the http resource. func GetMaybeInsecure(importPath string, security SecurityMode) (urlStr string, body io.ReadCloser, err error) { fetch := func(scheme string) (urlStr string, res *http.Response, err error) { u, err := url.Parse(scheme + "://" + importPath) if err != nil { return "", nil, err } u.RawQuery = "go-get=1" urlStr = u.String() if cfg.BuildV { log.Printf("Fetching %s", urlStr) } if security == Insecure && scheme == "https" { // fail earlier res, err = impatientInsecureHTTPClient.Get(urlStr) } else { res, err = httpClient.Get(urlStr) } return } closeBody := func(res *http.Response) { if res != nil { res.Body.Close() } } urlStr, res, err := fetch("https") if err != nil { if cfg.BuildV { log.Printf("https fetch failed: %v", err) } if security == Insecure { closeBody(res) urlStr, res, err = fetch("http") } } if err != nil { closeBody(res) return "", nil, err } // Note: accepting a non-200 OK here, so people can serve a // meta import in their http 404 page. if cfg.BuildV { log.Printf("Parsing meta tags from %s (status code %d)", urlStr, res.StatusCode) } return urlStr, res.Body, nil } func QueryEscape(s string) string { return url.QueryEscape(s) } func OpenBrowser(url string) bool { return browser.Open(url) }
web
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/web/security.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 web defines helper routines for accessing HTTP/HTTPS resources. package web // SecurityMode specifies whether a function should make network // calls using insecure transports (eg, plain text HTTP). // The zero value is "secure". type SecurityMode int const ( Secure SecurityMode = iota Insecure )
web
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/web/bootstrap.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 cmd_go_bootstrap // This code is compiled only into the bootstrap 'go' binary. // These stubs avoid importing packages with large dependency // trees, like the use of "net/http" in vcs.go. package web import ( "errors" "io" ) var errHTTP = errors.New("no http in bootstrap go command") type HTTPError struct { StatusCode int } func (e *HTTPError) Error() string { panic("unreachable") } func Get(url string) ([]byte, error) { return nil, errHTTP } func GetMaybeInsecure(importPath string, security SecurityMode) (string, io.ReadCloser, error) { return "", nil, errHTTP } func QueryEscape(s string) string { panic("unreachable") } func OpenBrowser(url string) bool { panic("unreachable") }
cfg
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/cfg/zdefaultcc.go
// Code generated by go tool dist; DO NOT EDIT. package cfg const DefaultPkgConfig = `pkg-config` func DefaultCC(goos, goarch string) string { switch goos + `/` + goarch { } return "gcc" } func DefaultCXX(goos, goarch string) string { switch goos + `/` + goarch { } return "c++" }
cfg
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/cfg/cfg.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 cfg holds configuration shared by multiple parts // of the go command. package cfg import ( "bytes" "fmt" "go/build" "io/ioutil" "log" "os" "path/filepath" "runtime" ) // These are general "build flags" used by build and other commands. var ( BuildA bool // -a flag BuildBuildmode string // -buildmode flag BuildContext = defaultContext() BuildMod string // -mod flag BuildI bool // -i flag BuildLinkshared bool // -linkshared flag BuildMSan bool // -msan flag BuildN bool // -n flag BuildO string // -o flag BuildP = runtime.NumCPU() // -p flag BuildPkgdir string // -pkgdir flag BuildRace bool // -race flag BuildToolexec []string // -toolexec flag BuildToolchainName string BuildToolchainCompiler func() string BuildToolchainLinker func() string BuildV bool // -v flag BuildWork bool // -work flag BuildX bool // -x flag CmdName string // "build", "install", "list", etc. DebugActiongraph string // -debug-actiongraph flag (undocumented, unstable) ) func defaultContext() build.Context { ctxt := build.Default ctxt.JoinPath = filepath.Join // back door to say "do not use go command" return ctxt } func init() { BuildToolchainCompiler = func() string { return "missing-compiler" } BuildToolchainLinker = func() string { return "missing-linker" } } // An EnvVar is an environment variable Name=Value. type EnvVar struct { Name string Value string } // OrigEnv is the original environment of the program at startup. var OrigEnv []string // CmdEnv is the new environment for running go tool commands. // User binaries (during go test or go run) are run with OrigEnv, // not CmdEnv. var CmdEnv []EnvVar // Global build parameters (used during package load) var ( Goarch = BuildContext.GOARCH Goos = BuildContext.GOOS ExeSuffix string Gopath = filepath.SplitList(BuildContext.GOPATH) // ModulesEnabled specifies whether the go command is running // in module-aware mode (as opposed to GOPATH mode). // It is equal to modload.Enabled, but not all packages can import modload. ModulesEnabled bool // GoModInGOPATH records whether we've found a go.mod in GOPATH/src // in GO111MODULE=auto mode. In that case, we don't use modules // but people might expect us to, so 'go get' warns. GoModInGOPATH string ) func init() { if Goos == "windows" { ExeSuffix = ".exe" } } var ( GOROOT = findGOROOT() GOBIN = os.Getenv("GOBIN") GOROOTbin = filepath.Join(GOROOT, "bin") GOROOTpkg = filepath.Join(GOROOT, "pkg") GOROOTsrc = filepath.Join(GOROOT, "src") GOROOT_FINAL = findGOROOT_FINAL() // Used in envcmd.MkEnv and build ID computations. GOARM, GO386, GOMIPS, GOMIPS64 = objabi() // C and C++ compilers CC, CXX = compilers() ) // Update build context to use our computed GOROOT. func init() { BuildContext.GOROOT = GOROOT if runtime.Compiler != "gccgo" { // Note that we must use runtime.GOOS and runtime.GOARCH here, // as the tool directory does not move based on environment // variables. This matches the initialization of ToolDir in // go/build, except for using GOROOT rather than // runtime.GOROOT. build.ToolDir = filepath.Join(GOROOT, "pkg/tool/"+runtime.GOOS+"_"+runtime.GOARCH) } } func objabi() (GOARM, GO386, GOMIPS, GOMIPS64 string) { data, err := ioutil.ReadFile(filepath.Join(GOROOT, "src/cmd/internal/objabi/zbootstrap.go")) if err != nil { fmt.Fprintf(os.Stderr, "go objabi: %v\n", err) } find := func(key string) string { if env := os.Getenv(key); env != "" { return env } i := bytes.Index(data, []byte("default"+key+" = `")) if i < 0 { if key == "GOMIPS64" { // new in Go 1.11 return "" } fmt.Fprintf(os.Stderr, "go objabi: cannot find %s\n", key) os.Exit(2) } line := data[i:] line = line[bytes.IndexByte(line, '`')+1:] return string(line[:bytes.IndexByte(line, '`')]) } return find("GOARM"), find("GO386"), find("GOMIPS"), find("GOMIPS64") } func compilers() (CC, CXX string) { data, err := ioutil.ReadFile(filepath.Join(GOROOT, "src/cmd/go/internal/cfg/zdefaultcc.go")) if err != nil { fmt.Fprintf(os.Stderr, "go compilers: %v\n", err) } find := func(key string) string { if env := os.Getenv(key); env != "" { return env } fi := bytes.Index(data, []byte("Default"+key+"(goos, goarch string)")) if fi < 0 { fmt.Fprintf(os.Stderr, "go compilers: cannot find %s\n", key) os.Exit(2) } i := bytes.Index(data[fi:], []byte("\treturn ")) if i < 0 { fmt.Fprintf(os.Stderr, "go compilers: cannot find %s\n", key) os.Exit(2) } line := data[fi+i:] line = line[bytes.IndexByte(line, '"')+1:] return string(line[:bytes.IndexByte(line, '"')]) } return find("CC"), find("CXX") } func findGOROOT() string { goroot := findGOROOT1() _, err := os.Stat(filepath.Join(goroot, "api/go1.10.txt")) if err != nil { log.SetFlags(0) log.Fatalf("go requires Go 1.10 but VGOROOT=%s is not a Go 1.10 source tree", goroot) } return goroot } func findGOROOT1() string { if env := os.Getenv("VGOROOT"); env != "" { return filepath.Clean(env) } if env := os.Getenv("GOROOT"); env != "" { return filepath.Clean(env) } def := filepath.Clean(runtime.GOROOT()) if runtime.Compiler == "gccgo" { // gccgo has no real GOROOT, and it certainly doesn't // depend on the executable's location. return def } exe, err := os.Executable() if err == nil { exe, err = filepath.Abs(exe) if err == nil { if dir := filepath.Join(exe, "../.."); isGOROOT(dir) { // If def (runtime.GOROOT()) and dir are the same // directory, prefer the spelling used in def. if isSameDir(def, dir) { return def } return dir } exe, err = filepath.EvalSymlinks(exe) if err == nil { if dir := filepath.Join(exe, "../.."); isGOROOT(dir) { if isSameDir(def, dir) { return def } return dir } } } } return def } func findGOROOT_FINAL() string { def := GOROOT if env := os.Getenv("GOROOT_FINAL"); env != "" { def = filepath.Clean(env) } return def } // isSameDir reports whether dir1 and dir2 are the same directory. func isSameDir(dir1, dir2 string) bool { if dir1 == dir2 { return true } info1, err1 := os.Stat(dir1) info2, err2 := os.Stat(dir2) return err1 == nil && err2 == nil && os.SameFile(info1, info2) } // isGOROOT reports whether path looks like a GOROOT. // // It does this by looking for the path/pkg/tool directory, // which is necessary for useful operation of the cmd/go tool, // and is not typically present in a GOPATH. // // There is a copy of this code in x/tools/cmd/godoc/goroot.go. func isGOROOT(path string) bool { stat, err := os.Stat(filepath.Join(path, "pkg", "tool")) if err != nil { return false } return stat.IsDir() }
cfg
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/cfg/zosarch.go
// Code generated by go tool dist; DO NOT EDIT. package cfg var OSArchSupportsCgo = map[string]bool{ "android/386": true, "android/amd64": true, "android/arm": true, "android/arm64": true, "darwin/386": true, "darwin/amd64": true, "darwin/arm": true, "darwin/arm64": true, "dragonfly/amd64": true, "freebsd/386": true, "freebsd/amd64": true, "freebsd/arm": false, "js/wasm": false, "linux/386": true, "linux/amd64": true, "linux/arm": true, "linux/arm64": true, "linux/mips": true, "linux/mips64": true, "linux/mips64le": true, "linux/mipsle": true, "linux/ppc64": false, "linux/ppc64le": true, "linux/riscv64": true, "linux/s390x": true, "nacl/386": false, "nacl/amd64p32": false, "nacl/arm": false, "netbsd/386": true, "netbsd/amd64": true, "netbsd/arm": true, "openbsd/386": true, "openbsd/amd64": true, "openbsd/arm": false, "plan9/386": false, "plan9/amd64": false, "plan9/arm": false, "solaris/amd64": true, "windows/386": true, "windows/amd64": true, }
load
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/load/flag_test.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 load import ( "fmt" "path/filepath" "reflect" "testing" ) type ppfTestPackage struct { path string dir string cmdline bool flags []string } type ppfTest struct { args []string pkgs []ppfTestPackage } var ppfTests = []ppfTest{ // -gcflags=-S applies only to packages on command line. { args: []string{"-S"}, pkgs: []ppfTestPackage{ {cmdline: true, flags: []string{"-S"}}, {cmdline: false, flags: []string{}}, }, }, // -gcflags=-S -gcflags= overrides the earlier -S. { args: []string{"-S", ""}, pkgs: []ppfTestPackage{ {cmdline: true, flags: []string{}}, }, }, // -gcflags=net=-S applies only to package net { args: []string{"net=-S"}, pkgs: []ppfTestPackage{ {path: "math", cmdline: true, flags: []string{}}, {path: "net", flags: []string{"-S"}}, }, }, // -gcflags=net=-S -gcflags=net= also overrides the earlier -S { args: []string{"net=-S", "net="}, pkgs: []ppfTestPackage{ {path: "net", flags: []string{}}, }, }, // -gcflags=net/...=-S net math // applies -S to net and net/http but not math { args: []string{"net/...=-S"}, pkgs: []ppfTestPackage{ {path: "net", flags: []string{"-S"}}, {path: "net/http", flags: []string{"-S"}}, {path: "math", flags: []string{}}, }, }, // -gcflags=net/...=-S -gcflags=-m net math // applies -m to net and math and -S to other packages matching net/... // (net matches too, but it was grabbed by the later -gcflags). { args: []string{"net/...=-S", "-m"}, pkgs: []ppfTestPackage{ {path: "net", cmdline: true, flags: []string{"-m"}}, {path: "math", cmdline: true, flags: []string{"-m"}}, {path: "net", cmdline: false, flags: []string{"-S"}}, {path: "net/http", flags: []string{"-S"}}, {path: "math", flags: []string{}}, }, }, // relative path patterns // ppfDirTest(pattern, n, dirs...) says the first n dirs should match and the others should not. ppfDirTest(".", 1, "/my/test/dir", "/my/test", "/my/test/other", "/my/test/dir/sub"), ppfDirTest("..", 1, "/my/test", "/my/test/dir", "/my/test/other", "/my/test/dir/sub"), ppfDirTest("./sub", 1, "/my/test/dir/sub", "/my/test", "/my/test/dir", "/my/test/other", "/my/test/dir/sub/sub"), ppfDirTest("../other", 1, "/my/test/other", "/my/test", "/my/test/dir", "/my/test/other/sub", "/my/test/dir/other", "/my/test/dir/sub"), ppfDirTest("./...", 3, "/my/test/dir", "/my/test/dir/sub", "/my/test/dir/sub/sub", "/my/test/other", "/my/test/other/sub"), ppfDirTest("../...", 4, "/my/test/dir", "/my/test/other", "/my/test/dir/sub", "/my/test/other/sub", "/my/other/test"), ppfDirTest("../...sub...", 3, "/my/test/dir/sub", "/my/test/othersub", "/my/test/yellowsubmarine", "/my/other/test"), } func ppfDirTest(pattern string, nmatch int, dirs ...string) ppfTest { var pkgs []ppfTestPackage for i, d := range dirs { flags := []string{} if i < nmatch { flags = []string{"-S"} } pkgs = append(pkgs, ppfTestPackage{path: "p", dir: d, flags: flags}) } return ppfTest{args: []string{pattern + "=-S"}, pkgs: pkgs} } func TestPerPackageFlag(t *testing.T) { nativeDir := func(d string) string { if filepath.Separator == '\\' { return `C:` + filepath.FromSlash(d) } return d } for i, tt := range ppfTests { t.Run(fmt.Sprintf("#%d", i), func(t *testing.T) { ppFlags := new(PerPackageFlag) for _, arg := range tt.args { t.Logf("set(%s)", arg) if err := ppFlags.set(arg, nativeDir("/my/test/dir")); err != nil { t.Fatal(err) } } for _, p := range tt.pkgs { dir := nativeDir(p.dir) flags := ppFlags.For(&Package{PackagePublic: PackagePublic{ImportPath: p.path, Dir: dir}, Internal: PackageInternal{CmdlinePkg: p.cmdline}}) if !reflect.DeepEqual(flags, p.flags) { t.Errorf("For(%v, %v, %v) = %v, want %v", p.path, dir, p.cmdline, flags, p.flags) } } }) } }
load
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/load/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 load import ( "path/filepath" "strings" ) // hasSubdir reports whether dir is a subdirectory of // (possibly multiple levels below) root. // If so, it sets rel to the path fragment that must be // appended to root to reach dir. func hasSubdir(root, dir string) (rel string, ok bool) { if p, err := filepath.EvalSymlinks(root); err == nil { root = p } if p, err := filepath.EvalSymlinks(dir); err == nil { dir = p } const sep = string(filepath.Separator) root = filepath.Clean(root) if !strings.HasSuffix(root, sep) { root += sep } dir = filepath.Clean(dir) if !strings.HasPrefix(dir, root) { return "", false } return filepath.ToSlash(dir[len(root):]), true } // expandPath returns the symlink-expanded form of path. func expandPath(p string) string { x, err := filepath.EvalSymlinks(p) if err == nil { return x } return p }
load
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/load/pkg.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 load loads packages. package load import ( "bytes" "fmt" "go/build" "go/token" "io/ioutil" "os" pathpkg "path" "path/filepath" "sort" "strconv" "strings" "unicode" "unicode/utf8" "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/modinfo" "cmd/go/internal/search" "cmd/go/internal/str" ) var ( // module initialization hook; never nil, no-op if module use is disabled ModInit func() // module hooks; nil if module use is disabled ModBinDir func() string // return effective bin directory ModLookup func(path string) (dir, realPath string, err error) // lookup effective meaning of import ModPackageModuleInfo func(path string) *modinfo.ModulePublic // return module info for Package struct ModImportPaths func(args []string) []*search.Match // expand import paths ModPackageBuildInfo func(main string, deps []string) string // return module info to embed in binary ModInfoProg func(info string) []byte // wrap module info in .go code for binary ModImportFromFiles func([]string) // update go.mod to add modules for imports in these files ModDirImportPath func(string) string // return effective import path for directory ) var IgnoreImports bool // control whether we ignore imports in packages // A Package describes a single package found in a directory. type Package struct { PackagePublic // visible in 'go list' Internal PackageInternal // for use inside go command only } type PackagePublic struct { // Note: These fields are part of the go command's public API. // See list.go. It is okay to add fields, but not to change or // remove existing ones. Keep in sync with list.go Dir string `json:",omitempty"` // directory containing package sources ImportPath string `json:",omitempty"` // import path of package in dir ImportComment string `json:",omitempty"` // path in import comment on package statement Name string `json:",omitempty"` // package name Doc string `json:",omitempty"` // package documentation string Target string `json:",omitempty"` // installed target for this package (may be executable) Shlib string `json:",omitempty"` // the shared library that contains this package (only set when -linkshared) Root string `json:",omitempty"` // Go root or Go path dir containing this package ConflictDir string `json:",omitempty"` // Dir is hidden by this other directory ForTest string `json:",omitempty"` // package is only for use in named test Export string `json:",omitempty"` // file containing export data (set by go list -export) Module *modinfo.ModulePublic `json:",omitempty"` // info about package's module, if any Match []string `json:",omitempty"` // command-line patterns matching this package Goroot bool `json:",omitempty"` // is this package found in the Go root? Standard bool `json:",omitempty"` // is this package part of the standard Go library? DepOnly bool `json:",omitempty"` // package is only as a dependency, not explicitly listed BinaryOnly bool `json:",omitempty"` // package cannot be recompiled Incomplete bool `json:",omitempty"` // was there an error loading this package or dependencies? // Stale and StaleReason remain here *only* for the list command. // They are only initialized in preparation for list execution. // The regular build determines staleness on the fly during action execution. Stale bool `json:",omitempty"` // would 'go install' do anything for this package? StaleReason string `json:",omitempty"` // why is Stale true? // Source files // If you add to this list you MUST add to p.AllFiles (below) too. // Otherwise file name security lists will not apply to any new additions. GoFiles []string `json:",omitempty"` // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles) CgoFiles []string `json:",omitempty"` // .go source files that import "C" CompiledGoFiles []string `json:",omitempty"` // .go output from running cgo on CgoFiles IgnoredGoFiles []string `json:",omitempty"` // .go source files ignored due to build constraints CFiles []string `json:",omitempty"` // .c source files CXXFiles []string `json:",omitempty"` // .cc, .cpp and .cxx source files MFiles []string `json:",omitempty"` // .m source files HFiles []string `json:",omitempty"` // .h, .hh, .hpp and .hxx source files FFiles []string `json:",omitempty"` // .f, .F, .for and .f90 Fortran source files SFiles []string `json:",omitempty"` // .s source files SwigFiles []string `json:",omitempty"` // .swig files SwigCXXFiles []string `json:",omitempty"` // .swigcxx files SysoFiles []string `json:",omitempty"` // .syso system object files added to package // Cgo directives CgoCFLAGS []string `json:",omitempty"` // cgo: flags for C compiler CgoCPPFLAGS []string `json:",omitempty"` // cgo: flags for C preprocessor CgoCXXFLAGS []string `json:",omitempty"` // cgo: flags for C++ compiler CgoFFLAGS []string `json:",omitempty"` // cgo: flags for Fortran compiler CgoLDFLAGS []string `json:",omitempty"` // cgo: flags for linker CgoPkgConfig []string `json:",omitempty"` // cgo: pkg-config names // Dependency information Imports []string `json:",omitempty"` // import paths used by this package ImportMap map[string]string `json:",omitempty"` // map from source import to ImportPath (identity entries omitted) Deps []string `json:",omitempty"` // all (recursively) imported dependencies // Error information // Incomplete is above, packed into the other bools Error *PackageError `json:",omitempty"` // error loading this package (not dependencies) DepsErrors []*PackageError `json:",omitempty"` // errors loading dependencies // Test information // If you add to this list you MUST add to p.AllFiles (below) too. // Otherwise file name security lists will not apply to any new additions. TestGoFiles []string `json:",omitempty"` // _test.go files in package TestImports []string `json:",omitempty"` // imports from TestGoFiles XTestGoFiles []string `json:",omitempty"` // _test.go files outside package XTestImports []string `json:",omitempty"` // imports from XTestGoFiles } // AllFiles returns the names of all the files considered for the package. // This is used for sanity and security checks, so we include all files, // even IgnoredGoFiles, because some subcommands consider them. // The go/build package filtered others out (like foo_wrongGOARCH.s) // and that's OK. func (p *Package) AllFiles() []string { return str.StringList( p.GoFiles, p.CgoFiles, // no p.CompiledGoFiles, because they are from GoFiles or generated by us p.IgnoredGoFiles, p.CFiles, p.CXXFiles, p.MFiles, p.HFiles, p.FFiles, p.SFiles, p.SwigFiles, p.SwigCXXFiles, p.SysoFiles, p.TestGoFiles, p.XTestGoFiles, ) } // Desc returns the package "description", for use in b.showOutput. func (p *Package) Desc() string { if p.ForTest != "" { return p.ImportPath + " [" + p.ForTest + ".test]" } return p.ImportPath } type PackageInternal struct { // Unexported fields are not part of the public API. Build *build.Package Imports []*Package // this package's direct imports CompiledImports []string // additional Imports necessary when using CompiledGoFiles (all from standard library) RawImports []string // this package's original imports as they appear in the text of the program ForceLibrary bool // this package is a library (even if named "main") CmdlineFiles bool // package built from files listed on command line CmdlinePkg bool // package listed on command line CmdlinePkgLiteral bool // package listed as literal on command line (not via wildcard) Local bool // imported via local path (./ or ../) LocalPrefix string // interpret ./ and ../ imports relative to this prefix ExeName string // desired name for temporary executable CoverMode string // preprocess Go source files with the coverage tool in this mode CoverVars map[string]*CoverVar // variables created by coverage analysis OmitDebug bool // tell linker not to write debug information GobinSubdir bool // install target would be subdir of GOBIN BuildInfo string // add this info to package main TestmainGo *[]byte // content for _testmain.go Asmflags []string // -asmflags for this package Gcflags []string // -gcflags for this package Ldflags []string // -ldflags for this package Gccgoflags []string // -gccgoflags for this package } type NoGoError struct { Package *Package } func (e *NoGoError) Error() string { // Count files beginning with _ and ., which we will pretend don't exist at all. dummy := 0 for _, name := range e.Package.IgnoredGoFiles { if strings.HasPrefix(name, "_") || strings.HasPrefix(name, ".") { dummy++ } } if len(e.Package.IgnoredGoFiles) > dummy { // Go files exist, but they were ignored due to build constraints. return "build constraints exclude all Go files in " + e.Package.Dir } if len(e.Package.TestGoFiles)+len(e.Package.XTestGoFiles) > 0 { // Test Go files exist, but we're not interested in them. // The double-negative is unfortunate but we want e.Package.Dir // to appear at the end of error message. return "no non-test Go files in " + e.Package.Dir } return "no Go files in " + e.Package.Dir } // Resolve returns the resolved version of imports, // which should be p.TestImports or p.XTestImports, NOT p.Imports. // The imports in p.TestImports and p.XTestImports are not recursively // loaded during the initial load of p, so they list the imports found in // the source file, but most processing should be over the vendor-resolved // import paths. We do this resolution lazily both to avoid file system work // and because the eventual real load of the test imports (during 'go test') // can produce better error messages if it starts with the original paths. // The initial load of p loads all the non-test imports and rewrites // the vendored paths, so nothing should ever call p.vendored(p.Imports). func (p *Package) Resolve(imports []string) []string { if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] { panic("internal error: p.Resolve(p.Imports) called") } seen := make(map[string]bool) var all []string for _, path := range imports { path = ResolveImportPath(p, path) if !seen[path] { seen[path] = true all = append(all, path) } } sort.Strings(all) return all } // CoverVar holds the name of the generated coverage variables targeting the named file. type CoverVar struct { File string // local file name Var string // name of count struct } func (p *Package) copyBuild(pp *build.Package) { p.Internal.Build = pp if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" { old := pp.PkgTargetRoot pp.PkgRoot = cfg.BuildPkgdir pp.PkgTargetRoot = cfg.BuildPkgdir pp.PkgObj = filepath.Join(cfg.BuildPkgdir, strings.TrimPrefix(pp.PkgObj, old)) } p.Dir = pp.Dir p.ImportPath = pp.ImportPath p.ImportComment = pp.ImportComment p.Name = pp.Name p.Doc = pp.Doc p.Root = pp.Root p.ConflictDir = pp.ConflictDir p.BinaryOnly = pp.BinaryOnly // TODO? Target p.Goroot = pp.Goroot p.Standard = p.Goroot && p.ImportPath != "" && search.IsStandardImportPath(p.ImportPath) p.GoFiles = pp.GoFiles p.CgoFiles = pp.CgoFiles p.IgnoredGoFiles = pp.IgnoredGoFiles p.CFiles = pp.CFiles p.CXXFiles = pp.CXXFiles p.MFiles = pp.MFiles p.HFiles = pp.HFiles p.FFiles = pp.FFiles p.SFiles = pp.SFiles p.SwigFiles = pp.SwigFiles p.SwigCXXFiles = pp.SwigCXXFiles p.SysoFiles = pp.SysoFiles p.CgoCFLAGS = pp.CgoCFLAGS p.CgoCPPFLAGS = pp.CgoCPPFLAGS p.CgoCXXFLAGS = pp.CgoCXXFLAGS p.CgoFFLAGS = pp.CgoFFLAGS p.CgoLDFLAGS = pp.CgoLDFLAGS p.CgoPkgConfig = pp.CgoPkgConfig // We modify p.Imports in place, so make copy now. p.Imports = make([]string, len(pp.Imports)) copy(p.Imports, pp.Imports) p.Internal.RawImports = pp.Imports p.TestGoFiles = pp.TestGoFiles p.TestImports = pp.TestImports p.XTestGoFiles = pp.XTestGoFiles p.XTestImports = pp.XTestImports if IgnoreImports { p.Imports = nil p.Internal.RawImports = nil p.TestImports = nil p.XTestImports = nil } } // A PackageError describes an error loading information about a package. type PackageError struct { ImportStack []string // shortest path from package named on command line to this one Pos string // position of error Err string // the error itself IsImportCycle bool `json:"-"` // the error is an import cycle Hard bool `json:"-"` // whether the error is soft or hard; soft errors are ignored in some places } func (p *PackageError) Error() string { // Import cycles deserve special treatment. if p.IsImportCycle { return fmt.Sprintf("%s\npackage %s\n", p.Err, strings.Join(p.ImportStack, "\n\timports ")) } if p.Pos != "" { // Omit import stack. The full path to the file where the error // is the most important thing. return p.Pos + ": " + p.Err } if len(p.ImportStack) == 0 { return p.Err } return "package " + strings.Join(p.ImportStack, "\n\timports ") + ": " + p.Err } // An ImportStack is a stack of import paths, possibly with the suffix " (test)" appended. // The import path of a test package is the import path of the corresponding // non-test package with the suffix "_test" added. type ImportStack []string func (s *ImportStack) Push(p string) { *s = append(*s, p) } func (s *ImportStack) Pop() { *s = (*s)[0 : len(*s)-1] } func (s *ImportStack) Copy() []string { return append([]string{}, *s...) } // shorterThan reports whether sp is shorter than t. // We use this to record the shortest import sequence // that leads to a particular package. func (sp *ImportStack) shorterThan(t []string) bool { s := *sp if len(s) != len(t) { return len(s) < len(t) } // If they are the same length, settle ties using string ordering. for i := range s { if s[i] != t[i] { return s[i] < t[i] } } return false // they are equal } // packageCache is a lookup cache for loadPackage, // so that if we look up a package multiple times // we return the same pointer each time. var packageCache = map[string]*Package{} func ClearPackageCache() { for name := range packageCache { delete(packageCache, name) } } func ClearPackageCachePartial(args []string) { for _, arg := range args { p := packageCache[arg] if p != nil { delete(packageCache, p.Dir) delete(packageCache, p.ImportPath) } } } // ReloadPackageNoFlags is like LoadPackageNoFlags but makes sure // not to use the package cache. // It is only for use by GOPATH-based "go get". // TODO(rsc): When GOPATH-based "go get" is removed, delete this function. func ReloadPackageNoFlags(arg string, stk *ImportStack) *Package { p := packageCache[arg] if p != nil { delete(packageCache, p.Dir) delete(packageCache, p.ImportPath) } return LoadPackageNoFlags(arg, stk) } // dirToImportPath returns the pseudo-import path we use for a package // outside the Go path. It begins with _/ and then contains the full path // to the directory. If the package lives in c:\home\gopher\my\pkg then // the pseudo-import path is _/c_/home/gopher/my/pkg. // Using a pseudo-import path like this makes the ./ imports no longer // a special case, so that all the code to deal with ordinary imports works // automatically. func dirToImportPath(dir string) string { return pathpkg.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir))) } func makeImportValid(r rune) rune { // Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport. const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD" if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) { return '_' } return r } // Mode flags for loadImport and download (in get.go). const ( // ResolveImport means that loadImport should do import path expansion. // That is, ResolveImport means that the import path came from // a source file and has not been expanded yet to account for // vendoring or possible module adjustment. // Every import path should be loaded initially with ResolveImport, // and then the expanded version (for example with the /vendor/ in it) // gets recorded as the canonical import path. At that point, future loads // of that package must not pass ResolveImport, because // disallowVendor will reject direct use of paths containing /vendor/. ResolveImport = 1 << iota // ResolveModule is for download (part of "go get") and indicates // that the module adjustment should be done, but not vendor adjustment. ResolveModule // GetTestDeps is for download (part of "go get") and indicates // that test dependencies should be fetched too. GetTestDeps ) // LoadImport scans the directory named by path, which must be an import path, // but possibly a local import path (an absolute file system path or one beginning // with ./ or ../). A local relative path is interpreted relative to srcDir. // It returns a *Package describing the package found in that directory. // LoadImport does not set tool flags and should only be used by // this package, as part of a bigger load operation, and by GOPATH-based "go get". // TODO(rsc): When GOPATH-based "go get" is removed, unexport this function. func LoadImport(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package { stk.Push(path) defer stk.Pop() if strings.HasPrefix(path, "mod/") { // Paths beginning with "mod/" might accidentally // look in the module cache directory tree in $GOPATH/pkg/mod/. // This prefix is owned by the Go core for possible use in the // standard library (since it does not begin with a domain name), // so it's OK to disallow entirely. return &Package{ PackagePublic: PackagePublic{ ImportPath: path, Error: &PackageError{ ImportStack: stk.Copy(), Err: fmt.Sprintf("disallowed import path %q", path), }, }, } } if strings.Contains(path, "@") { var text string if cfg.ModulesEnabled { text = "can only use path@version syntax with 'go get'" } else { text = "cannot use path@version syntax in GOPATH mode" } return &Package{ PackagePublic: PackagePublic{ ImportPath: path, Error: &PackageError{ ImportStack: stk.Copy(), Err: text, }, }, } } parentPath := "" if parent != nil { parentPath = parent.ImportPath } // Determine canonical identifier for this package. // For a local import the identifier is the pseudo-import path // we create from the full directory to the package. // Otherwise it is the usual import path. // For vendored imports, it is the expanded form. importPath := path origPath := path isLocal := build.IsLocalImport(path) var modDir string var modErr error if isLocal { importPath = dirToImportPath(filepath.Join(srcDir, path)) } else if cfg.ModulesEnabled { var p string modDir, p, modErr = ModLookup(path) if modErr == nil { importPath = p } } else if mode&ResolveImport != 0 { // We do our own path resolution, because we want to // find out the key to use in packageCache without the // overhead of repeated calls to buildContext.Import. // The code is also needed in a few other places anyway. path = ResolveImportPath(parent, path) importPath = path } else if mode&ResolveModule != 0 { path = ModuleImportPath(parent, path) importPath = path } p := packageCache[importPath] if p != nil { p = reusePackage(p, stk) } else { p = new(Package) p.Internal.Local = isLocal p.ImportPath = importPath packageCache[importPath] = p // Load package. // Import always returns bp != nil, even if an error occurs, // in order to return partial information. var bp *build.Package var err error if modDir != "" { bp, err = cfg.BuildContext.ImportDir(modDir, 0) } else if modErr != nil { bp = new(build.Package) err = fmt.Errorf("unknown import path %q: %v", importPath, modErr) } else if cfg.ModulesEnabled && path != "unsafe" { bp = new(build.Package) err = fmt.Errorf("unknown import path %q: internal error: module loader did not resolve import", importPath) } else { buildMode := build.ImportComment if mode&ResolveImport == 0 || path != origPath { // Not vendoring, or we already found the vendored path. buildMode |= build.IgnoreVendor } bp, err = cfg.BuildContext.Import(path, srcDir, buildMode) } bp.ImportPath = importPath if cfg.GOBIN != "" { bp.BinDir = cfg.GOBIN } else if cfg.ModulesEnabled { bp.BinDir = ModBinDir() } if modDir == "" && err == nil && !isLocal && bp.ImportComment != "" && bp.ImportComment != path && !strings.Contains(path, "/vendor/") && !strings.HasPrefix(path, "vendor/") { err = fmt.Errorf("code in directory %s expects import %q", bp.Dir, bp.ImportComment) } p.load(stk, bp, err) if p.Error != nil && p.Error.Pos == "" { p = setErrorPos(p, importPos) } if modDir == "" && origPath != cleanImport(origPath) { p.Error = &PackageError{ ImportStack: stk.Copy(), Err: fmt.Sprintf("non-canonical import path: %q should be %q", origPath, pathpkg.Clean(origPath)), } p.Incomplete = true } } // Checked on every import because the rules depend on the code doing the importing. if perr := disallowInternal(srcDir, parent, parentPath, p, stk); perr != p { return setErrorPos(perr, importPos) } if mode&ResolveImport != 0 { if perr := disallowVendor(srcDir, parent, parentPath, origPath, p, stk); perr != p { return setErrorPos(perr, importPos) } } if p.Name == "main" && parent != nil && parent.Dir != p.Dir { perr := *p perr.Error = &PackageError{ ImportStack: stk.Copy(), Err: fmt.Sprintf("import %q is a program, not an importable package", path), } return setErrorPos(&perr, importPos) } if p.Internal.Local && parent != nil && !parent.Internal.Local { perr := *p perr.Error = &PackageError{ ImportStack: stk.Copy(), Err: fmt.Sprintf("local import %q in non-local package", path), } return setErrorPos(&perr, importPos) } return p } func setErrorPos(p *Package, importPos []token.Position) *Package { if len(importPos) > 0 { pos := importPos[0] pos.Filename = base.ShortPath(pos.Filename) p.Error.Pos = pos.String() } return p } func cleanImport(path string) string { orig := path path = pathpkg.Clean(path) if strings.HasPrefix(orig, "./") && path != ".." && !strings.HasPrefix(path, "../") { path = "./" + path } return path } var isDirCache = map[string]bool{} func isDir(path string) bool { result, ok := isDirCache[path] if ok { return result } fi, err := os.Stat(path) result = err == nil && fi.IsDir() isDirCache[path] = result return result } // ResolveImportPath returns the true meaning of path when it appears in parent. // There are two different resolutions applied. // First, there is Go 1.5 vendoring (golang.org/s/go15vendor). // If vendor expansion doesn't trigger, then the path is also subject to // Go 1.11 module legacy conversion (golang.org/issue/25069). func ResolveImportPath(parent *Package, path string) (found string) { if cfg.ModulesEnabled { if _, p, e := ModLookup(path); e == nil { return p } return path } found = VendoredImportPath(parent, path) if found != path { return found } return ModuleImportPath(parent, path) } // dirAndRoot returns the source directory and workspace root // for the package p, guaranteeing that root is a path prefix of dir. func dirAndRoot(p *Package) (dir, root string) { dir = filepath.Clean(p.Dir) root = filepath.Join(p.Root, "src") if !str.HasFilePathPrefix(dir, root) || p.ImportPath != "command-line-arguments" && filepath.Join(root, p.ImportPath) != dir { // Look for symlinks before reporting error. dir = expandPath(dir) root = expandPath(root) } if !str.HasFilePathPrefix(dir, root) || len(dir) <= len(root) || dir[len(root)] != filepath.Separator || p.ImportPath != "command-line-arguments" && !p.Internal.Local && filepath.Join(root, p.ImportPath) != dir { base.Fatalf("unexpected directory layout:\n"+ " import path: %s\n"+ " root: %s\n"+ " dir: %s\n"+ " expand root: %s\n"+ " expand dir: %s\n"+ " separator: %s", p.ImportPath, filepath.Join(p.Root, "src"), filepath.Clean(p.Dir), root, dir, string(filepath.Separator)) } return dir, root } // VendoredImportPath returns the vendor-expansion of path when it appears in parent. // If parent is x/y/z, then path might expand to x/y/z/vendor/path, x/y/vendor/path, // x/vendor/path, vendor/path, or else stay path if none of those exist. // VendoredImportPath returns the expanded path or, if no expansion is found, the original. func VendoredImportPath(parent *Package, path string) (found string) { if parent == nil || parent.Root == "" { return path } dir, root := dirAndRoot(parent) vpath := "vendor/" + path for i := len(dir); i >= len(root); i-- { if i < len(dir) && dir[i] != filepath.Separator { continue } // Note: checking for the vendor directory before checking // for the vendor/path directory helps us hit the // isDir cache more often. It also helps us prepare a more useful // list of places we looked, to report when an import is not found. if !isDir(filepath.Join(dir[:i], "vendor")) { continue } targ := filepath.Join(dir[:i], vpath) if isDir(targ) && hasGoFiles(targ) { importPath := parent.ImportPath if importPath == "command-line-arguments" { // If parent.ImportPath is 'command-line-arguments'. // set to relative directory to root (also chopped root directory) importPath = dir[len(root)+1:] } // We started with parent's dir c:\gopath\src\foo\bar\baz\quux\xyzzy. // We know the import path for parent's dir. // We chopped off some number of path elements and // added vendor\path to produce c:\gopath\src\foo\bar\baz\vendor\path. // Now we want to know the import path for that directory. // Construct it by chopping the same number of path elements // (actually the same number of bytes) from parent's import path // and then append /vendor/path. chopped := len(dir) - i if chopped == len(importPath)+1 { // We walked up from c:\gopath\src\foo\bar // and found c:\gopath\src\vendor\path. // We chopped \foo\bar (length 8) but the import path is "foo/bar" (length 7). // Use "vendor/path" without any prefix. return vpath } return importPath[:len(importPath)-chopped] + "/" + vpath } } return path } var ( modulePrefix = []byte("\nmodule ") goModPathCache = make(map[string]string) ) // goModPath returns the module path in the go.mod in dir, if any. func goModPath(dir string) (path string) { path, ok := goModPathCache[dir] if ok { return path } defer func() { goModPathCache[dir] = path }() data, err := ioutil.ReadFile(filepath.Join(dir, "go.mod")) if err != nil { return "" } var i int if bytes.HasPrefix(data, modulePrefix[1:]) { i = 0 } else { i = bytes.Index(data, modulePrefix) if i < 0 { return "" } i++ } line := data[i:] // Cut line at \n, drop trailing \r if present. if j := bytes.IndexByte(line, '\n'); j >= 0 { line = line[:j] } if line[len(line)-1] == '\r' { line = line[:len(line)-1] } line = line[len("module "):] // If quoted, unquote. path = strings.TrimSpace(string(line)) if path != "" && path[0] == '"' { s, err := strconv.Unquote(path) if err != nil { return "" } path = s } return path } // findVersionElement returns the slice indices of the final version element /vN in path. // If there is no such element, it returns -1, -1. func findVersionElement(path string) (i, j int) { j = len(path) for i = len(path) - 1; i >= 0; i-- { if path[i] == '/' { if isVersionElement(path[i:j]) { return i, j } j = i } } return -1, -1 } // isVersionElement reports whether s is a well-formed path version element: // v2, v3, v10, etc, but not v0, v05, v1. func isVersionElement(s string) bool { if len(s) < 3 || s[0] != '/' || s[1] != 'v' || s[2] == '0' || s[2] == '1' && len(s) == 3 { return false } for i := 2; i < len(s); i++ { if s[i] < '0' || '9' < s[i] { return false } } return true } // ModuleImportPath translates import paths found in go modules // back down to paths that can be resolved in ordinary builds. // // Define “new” code as code with a go.mod file in the same directory // or a parent directory. If an import in new code says x/y/v2/z but // x/y/v2/z does not exist and x/y/go.mod says “module x/y/v2”, // then go build will read the import as x/y/z instead. // See golang.org/issue/25069. func ModuleImportPath(parent *Package, path string) (found string) { if parent == nil || parent.Root == "" { return path } // If there are no vN elements in path, leave it alone. // (The code below would do the same, but only after // some other file system accesses that we can avoid // here by returning early.) if i, _ := findVersionElement(path); i < 0 { return path } dir, root := dirAndRoot(parent) // Consider dir and parents, up to and including root. for i := len(dir); i >= len(root); i-- { if i < len(dir) && dir[i] != filepath.Separator { continue } if goModPath(dir[:i]) != "" { goto HaveGoMod } } // This code is not in a tree with a go.mod, // so apply no changes to the path. return path HaveGoMod: // This import is in a tree with a go.mod. // Allow it to refer to code in GOPATH/src/x/y/z as x/y/v2/z // if GOPATH/src/x/y/go.mod says module "x/y/v2", // If x/y/v2/z exists, use it unmodified. if bp, _ := cfg.BuildContext.Import(path, "", build.IgnoreVendor); bp.Dir != "" { return path } // Otherwise look for a go.mod supplying a version element. // Some version-like elements may appear in paths but not // be module versions; we skip over those to look for module // versions. For example the module m/v2 might have a // package m/v2/api/v1/foo. limit := len(path) for limit > 0 { i, j := findVersionElement(path[:limit]) if i < 0 { return path } if bp, _ := cfg.BuildContext.Import(path[:i], "", build.IgnoreVendor); bp.Dir != "" { if mpath := goModPath(bp.Dir); mpath != "" { // Found a valid go.mod file, so we're stopping the search. // If the path is m/v2/p and we found m/go.mod that says // "module m/v2", then we return "m/p". if mpath == path[:j] { return path[:i] + path[j:] } // Otherwise just return the original path. // We didn't find anything worth rewriting, // and the go.mod indicates that we should // not consider parent directories. return path } } limit = i } return path } // hasGoFiles reports whether dir contains any files with names ending in .go. // For a vendor check we must exclude directories that contain no .go files. // Otherwise it is not possible to vendor just a/b/c and still import the // non-vendored a/b. See golang.org/issue/13832. func hasGoFiles(dir string) bool { fis, _ := ioutil.ReadDir(dir) for _, fi := range fis { if !fi.IsDir() && strings.HasSuffix(fi.Name(), ".go") { return true } } return false } // reusePackage reuses package p to satisfy the import at the top // of the import stack stk. If this use causes an import loop, // reusePackage updates p's error information to record the loop. func reusePackage(p *Package, stk *ImportStack) *Package { // We use p.Internal.Imports==nil to detect a package that // is in the midst of its own loadPackage call // (all the recursion below happens before p.Internal.Imports gets set). if p.Internal.Imports == nil { if p.Error == nil { p.Error = &PackageError{ ImportStack: stk.Copy(), Err: "import cycle not allowed", IsImportCycle: true, } } p.Incomplete = true } // Don't rewrite the import stack in the error if we have an import cycle. // If we do, we'll lose the path that describes the cycle. if p.Error != nil && !p.Error.IsImportCycle && stk.shorterThan(p.Error.ImportStack) { p.Error.ImportStack = stk.Copy() } return p } // disallowInternal checks that srcDir (containing package importerPath, if non-empty) // is allowed to import p. // If the import is allowed, disallowInternal returns the original package p. // If not, it returns a new package containing just an appropriate error. func disallowInternal(srcDir string, importer *Package, importerPath string, p *Package, stk *ImportStack) *Package { // golang.org/s/go14internal: // An import of a path containing the element “internal” // is disallowed if the importing code is outside the tree // rooted at the parent of the “internal” directory. // There was an error loading the package; stop here. if p.Error != nil { return p } // The generated 'testmain' package is allowed to access testing/internal/..., // as if it were generated into the testing directory tree // (it's actually in a temporary directory outside any Go tree). // This cleans up a former kludge in passing functionality to the testing package. if strings.HasPrefix(p.ImportPath, "testing/internal") && len(*stk) >= 2 && (*stk)[len(*stk)-2] == "testmain" { return p } // We can't check standard packages with gccgo. if cfg.BuildContext.Compiler == "gccgo" && p.Standard { return p } // The stack includes p.ImportPath. // If that's the only thing on the stack, we started // with a name given on the command line, not an // import. Anything listed on the command line is fine. if len(*stk) == 1 { return p } // Check for "internal" element: three cases depending on begin of string and/or end of string. i, ok := findInternal(p.ImportPath) if !ok { return p } // Internal is present. // Map import path back to directory corresponding to parent of internal. if i > 0 { i-- // rewind over slash in ".../internal" } if p.Module == nil { parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)] if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) { return p } // Look for symlinks before reporting error. srcDir = expandPath(srcDir) parent = expandPath(parent) if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) { return p } } else { // p is in a module, so make it available based on the importer's import path instead // of the file path (https://golang.org/issue/23970). if importerPath == "." { // The importer is a list of command-line files. // Pretend that the import path is the import path of the // directory containing them. importerPath = ModDirImportPath(importer.Dir) } parentOfInternal := p.ImportPath[:i] if str.HasPathPrefix(importerPath, parentOfInternal) { return p } } // Internal is present, and srcDir is outside parent's tree. Not allowed. perr := *p perr.Error = &PackageError{ ImportStack: stk.Copy(), Err: "use of internal package " + p.ImportPath + " not allowed", } perr.Incomplete = true return &perr } // findInternal looks for the final "internal" path element in the given import path. // If there isn't one, findInternal returns ok=false. // Otherwise, findInternal returns ok=true and the index of the "internal". func findInternal(path string) (index int, ok bool) { // Three cases, depending on internal at start/end of string or not. // The order matters: we must return the index of the final element, // because the final one produces the most restrictive requirement // on the importer. switch { case strings.HasSuffix(path, "/internal"): return len(path) - len("internal"), true case strings.Contains(path, "/internal/"): return strings.LastIndex(path, "/internal/") + 1, true case path == "internal", strings.HasPrefix(path, "internal/"): return 0, true } return 0, false } // disallowVendor checks that srcDir (containing package importerPath, if non-empty) // is allowed to import p as path. // If the import is allowed, disallowVendor returns the original package p. // If not, it returns a new package containing just an appropriate error. func disallowVendor(srcDir string, importer *Package, importerPath, path string, p *Package, stk *ImportStack) *Package { // The stack includes p.ImportPath. // If that's the only thing on the stack, we started // with a name given on the command line, not an // import. Anything listed on the command line is fine. if len(*stk) == 1 { return p } // Modules must not import vendor packages in the standard library, // but the usual vendor visibility check will not catch them // because the module loader presents them with an ImportPath starting // with "golang_org/" instead of "vendor/". if p.Standard && !importer.Standard && strings.HasPrefix(p.ImportPath, "golang_org") { perr := *p perr.Error = &PackageError{ ImportStack: stk.Copy(), Err: "use of vendored package " + path + " not allowed", } perr.Incomplete = true return &perr } if perr := disallowVendorVisibility(srcDir, p, stk); perr != p { return perr } // Paths like x/vendor/y must be imported as y, never as x/vendor/y. if i, ok := FindVendor(path); ok { perr := *p perr.Error = &PackageError{ ImportStack: stk.Copy(), Err: "must be imported as " + path[i+len("vendor/"):], } perr.Incomplete = true return &perr } return p } // disallowVendorVisibility checks that srcDir is allowed to import p. // The rules are the same as for /internal/ except that a path ending in /vendor // is not subject to the rules, only subdirectories of vendor. // This allows people to have packages and commands named vendor, // for maximal compatibility with existing source trees. func disallowVendorVisibility(srcDir string, p *Package, stk *ImportStack) *Package { // The stack includes p.ImportPath. // If that's the only thing on the stack, we started // with a name given on the command line, not an // import. Anything listed on the command line is fine. if len(*stk) == 1 { return p } // Check for "vendor" element. i, ok := FindVendor(p.ImportPath) if !ok { return p } // Vendor is present. // Map import path back to directory corresponding to parent of vendor. if i > 0 { i-- // rewind over slash in ".../vendor" } truncateTo := i + len(p.Dir) - len(p.ImportPath) if truncateTo < 0 || len(p.Dir) < truncateTo { return p } parent := p.Dir[:truncateTo] if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) { return p } // Look for symlinks before reporting error. srcDir = expandPath(srcDir) parent = expandPath(parent) if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) { return p } // Vendor is present, and srcDir is outside parent's tree. Not allowed. perr := *p perr.Error = &PackageError{ ImportStack: stk.Copy(), Err: "use of vendored package not allowed", } perr.Incomplete = true return &perr } // FindVendor looks for the last non-terminating "vendor" path element in the given import path. // If there isn't one, FindVendor returns ok=false. // Otherwise, FindVendor returns ok=true and the index of the "vendor". // // Note that terminating "vendor" elements don't count: "x/vendor" is its own package, // not the vendored copy of an import "" (the empty import path). // This will allow people to have packages or commands named vendor. // This may help reduce breakage, or it may just be confusing. We'll see. func FindVendor(path string) (index int, ok bool) { // Two cases, depending on internal at start of string or not. // The order matters: we must return the index of the final element, // because the final one is where the effective import path starts. switch { case strings.Contains(path, "/vendor/"): return strings.LastIndex(path, "/vendor/") + 1, true case strings.HasPrefix(path, "vendor/"): return 0, true } return 0, false } type TargetDir int const ( ToTool TargetDir = iota // to GOROOT/pkg/tool (default for cmd/*) ToBin // to bin dir inside package root (default for non-cmd/*) StalePath // an old import path; fail to build ) // InstallTargetDir reports the target directory for installing the command p. func InstallTargetDir(p *Package) TargetDir { if strings.HasPrefix(p.ImportPath, "code.google.com/p/go.tools/cmd/") { return StalePath } if p.Goroot && strings.HasPrefix(p.ImportPath, "cmd/") && p.Name == "main" { switch p.ImportPath { case "cmd/go", "cmd/gofmt": return ToBin } return ToTool } return ToBin } var cgoExclude = map[string]bool{ "runtime/cgo": true, } var cgoSyscallExclude = map[string]bool{ "runtime/cgo": true, "runtime/race": true, "runtime/msan": true, } var foldPath = make(map[string]string) // load populates p using information from bp, err, which should // be the result of calling build.Context.Import. func (p *Package) load(stk *ImportStack, bp *build.Package, err error) { p.copyBuild(bp) // The localPrefix is the path we interpret ./ imports relative to. // Synthesized main packages sometimes override this. if p.Internal.Local { p.Internal.LocalPrefix = dirToImportPath(p.Dir) } if err != nil { if _, ok := err.(*build.NoGoError); ok { err = &NoGoError{Package: p} } p.Incomplete = true err = base.ExpandScanner(err) p.Error = &PackageError{ ImportStack: stk.Copy(), Err: err.Error(), } return } useBindir := p.Name == "main" if !p.Standard { switch cfg.BuildBuildmode { case "c-archive", "c-shared", "plugin": useBindir = false } } if useBindir { // Report an error when the old code.google.com/p/go.tools paths are used. if InstallTargetDir(p) == StalePath { newPath := strings.Replace(p.ImportPath, "code.google.com/p/go.", "golang.org/x/", 1) e := fmt.Sprintf("the %v command has moved; use %v instead.", p.ImportPath, newPath) p.Error = &PackageError{Err: e} return } _, elem := filepath.Split(p.Dir) if cfg.ModulesEnabled { // NOTE(rsc): Using p.ImportPath instead of p.Dir // makes sure we install a package in the root of a // cached module directory as that package name // not name@v1.2.3. // Using p.ImportPath instead of p.Dir // is probably correct all the time, // even for non-module-enabled code, // but I'm not brave enough to change the // non-module behavior this late in the // release cycle. Maybe for Go 1.12. // See golang.org/issue/26869. _, elem = pathpkg.Split(p.ImportPath) // If this is example.com/mycmd/v2, it's more useful to install it as mycmd than as v2. // See golang.org/issue/24667. isVersion := func(v string) bool { if len(v) < 2 || v[0] != 'v' || v[1] < '1' || '9' < v[1] { return false } for i := 2; i < len(v); i++ { if c := v[i]; c < '0' || '9' < c { return false } } return true } if isVersion(elem) { _, elem = pathpkg.Split(pathpkg.Dir(p.ImportPath)) } } full := cfg.BuildContext.GOOS + "_" + cfg.BuildContext.GOARCH + "/" + elem if cfg.BuildContext.GOOS != base.ToolGOOS || cfg.BuildContext.GOARCH != base.ToolGOARCH { // Install cross-compiled binaries to subdirectories of bin. elem = full } if p.Internal.Build.BinDir == "" && cfg.ModulesEnabled { p.Internal.Build.BinDir = ModBinDir() } if p.Internal.Build.BinDir != "" { // Install to GOBIN or bin of GOPATH entry. p.Target = filepath.Join(p.Internal.Build.BinDir, elem) if !p.Goroot && strings.Contains(elem, "/") && cfg.GOBIN != "" { // Do not create $GOBIN/goos_goarch/elem. p.Target = "" p.Internal.GobinSubdir = true } } if InstallTargetDir(p) == ToTool { // This is for 'go tool'. // Override all the usual logic and force it into the tool directory. if cfg.BuildToolchainName == "gccgo" { p.Target = filepath.Join(base.ToolDir, elem) } else { p.Target = filepath.Join(cfg.GOROOTpkg, "tool", full) } } if p.Target != "" && cfg.BuildContext.GOOS == "windows" { p.Target += ".exe" } } else if p.Internal.Local { // Local import turned into absolute path. // No permanent install target. p.Target = "" } else { p.Target = p.Internal.Build.PkgObj if cfg.BuildLinkshared { shlibnamefile := p.Target[:len(p.Target)-2] + ".shlibname" shlib, err := ioutil.ReadFile(shlibnamefile) if err != nil && !os.IsNotExist(err) { base.Fatalf("reading shlibname: %v", err) } if err == nil { libname := strings.TrimSpace(string(shlib)) if cfg.BuildContext.Compiler == "gccgo" { p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, "shlibs", libname) } else { p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, libname) } } } } // Build augmented import list to add implicit dependencies. // Be careful not to add imports twice, just to avoid confusion. importPaths := p.Imports addImport := func(path string, forCompiler bool) { for _, p := range importPaths { if path == p { return } } importPaths = append(importPaths, path) if forCompiler { p.Internal.CompiledImports = append(p.Internal.CompiledImports, path) } } // Cgo translation adds imports of "unsafe", "runtime/cgo" and "syscall", // except for certain packages, to avoid circular dependencies. if p.UsesCgo() { addImport("unsafe", true) } if p.UsesCgo() && (!p.Standard || !cgoExclude[p.ImportPath]) && cfg.BuildContext.Compiler != "gccgo" { addImport("runtime/cgo", true) } if p.UsesCgo() && (!p.Standard || !cgoSyscallExclude[p.ImportPath]) { addImport("syscall", true) } // SWIG adds imports of some standard packages. if p.UsesSwig() { if cfg.BuildContext.Compiler != "gccgo" { addImport("runtime/cgo", true) } addImport("syscall", true) addImport("sync", true) // TODO: The .swig and .swigcxx files can use // %go_import directives to import other packages. } // The linker loads implicit dependencies. if p.Name == "main" && !p.Internal.ForceLibrary { for _, dep := range LinkerDeps(p) { addImport(dep, false) } } // Check for case-insensitive collision of input files. // To avoid problems on case-insensitive files, we reject any package // where two different input files have equal names under a case-insensitive // comparison. inputs := p.AllFiles() f1, f2 := str.FoldDup(inputs) if f1 != "" { p.Error = &PackageError{ ImportStack: stk.Copy(), Err: fmt.Sprintf("case-insensitive file name collision: %q and %q", f1, f2), } return } // If first letter of input file is ASCII, it must be alphanumeric. // This avoids files turning into flags when invoking commands, // and other problems we haven't thought of yet. // Also, _cgo_ files must be generated by us, not supplied. // They are allowed to have //go:cgo_ldflag directives. // The directory scan ignores files beginning with _, // so we shouldn't see any _cgo_ files anyway, but just be safe. for _, file := range inputs { if !SafeArg(file) || strings.HasPrefix(file, "_cgo_") { p.Error = &PackageError{ ImportStack: stk.Copy(), Err: fmt.Sprintf("invalid input file name %q", file), } return } } if name := pathpkg.Base(p.ImportPath); !SafeArg(name) { p.Error = &PackageError{ ImportStack: stk.Copy(), Err: fmt.Sprintf("invalid input directory name %q", name), } return } if !SafeArg(p.ImportPath) { p.Error = &PackageError{ ImportStack: stk.Copy(), Err: fmt.Sprintf("invalid import path %q", p.ImportPath), } return } // Build list of imported packages and full dependency list. imports := make([]*Package, 0, len(p.Imports)) for i, path := range importPaths { if path == "C" { continue } p1 := LoadImport(path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], ResolveImport) if p.Standard && p.Error == nil && !p1.Standard && p1.Error == nil { p.Error = &PackageError{ ImportStack: stk.Copy(), Err: fmt.Sprintf("non-standard import %q in standard package %q", path, p.ImportPath), } pos := p.Internal.Build.ImportPos[path] if len(pos) > 0 { p.Error.Pos = pos[0].String() } } path = p1.ImportPath importPaths[i] = path if i < len(p.Imports) { p.Imports[i] = path } imports = append(imports, p1) if p1.Incomplete { p.Incomplete = true } } p.Internal.Imports = imports deps := make(map[string]*Package) var q []*Package q = append(q, imports...) for i := 0; i < len(q); i++ { p1 := q[i] path := p1.ImportPath // The same import path could produce an error or not, // depending on what tries to import it. // Prefer to record entries with errors, so we can report them. p0 := deps[path] if p0 == nil || p1.Error != nil && (p0.Error == nil || len(p0.Error.ImportStack) > len(p1.Error.ImportStack)) { deps[path] = p1 for _, p2 := range p1.Internal.Imports { if deps[p2.ImportPath] != p2 { q = append(q, p2) } } } } p.Deps = make([]string, 0, len(deps)) for dep := range deps { p.Deps = append(p.Deps, dep) } sort.Strings(p.Deps) for _, dep := range p.Deps { p1 := deps[dep] if p1 == nil { panic("impossible: missing entry in package cache for " + dep + " imported by " + p.ImportPath) } if p1.Error != nil { p.DepsErrors = append(p.DepsErrors, p1.Error) } } // unsafe is a fake package. if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") { p.Target = "" } // If cgo is not enabled, ignore cgo supporting sources // just as we ignore go files containing import "C". if !cfg.BuildContext.CgoEnabled { p.CFiles = nil p.CXXFiles = nil p.MFiles = nil p.SwigFiles = nil p.SwigCXXFiles = nil // Note that SFiles are okay (they go to the Go assembler) // and HFiles are okay (they might be used by the SFiles). // Also Sysofiles are okay (they might not contain object // code; see issue #16050). } setError := func(msg string) { p.Error = &PackageError{ ImportStack: stk.Copy(), Err: msg, } } // The gc toolchain only permits C source files with cgo or SWIG. if len(p.CFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() && cfg.BuildContext.Compiler == "gc" { setError(fmt.Sprintf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " "))) return } // C++, Objective-C, and Fortran source files are permitted only with cgo or SWIG, // regardless of toolchain. if len(p.CXXFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() { setError(fmt.Sprintf("C++ source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CXXFiles, " "))) return } if len(p.MFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() { setError(fmt.Sprintf("Objective-C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.MFiles, " "))) return } if len(p.FFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() { setError(fmt.Sprintf("Fortran source files not allowed when not using cgo or SWIG: %s", strings.Join(p.FFiles, " "))) return } // Check for case-insensitive collisions of import paths. fold := str.ToFold(p.ImportPath) if other := foldPath[fold]; other == "" { foldPath[fold] = p.ImportPath } else if other != p.ImportPath { setError(fmt.Sprintf("case-insensitive import collision: %q and %q", p.ImportPath, other)) return } if cfg.ModulesEnabled { p.Module = ModPackageModuleInfo(p.ImportPath) if p.Name == "main" { p.Internal.BuildInfo = ModPackageBuildInfo(p.ImportPath, p.Deps) } } } // SafeArg reports whether arg is a "safe" command-line argument, // meaning that when it appears in a command-line, it probably // doesn't have some special meaning other than its own name. // Obviously args beginning with - are not safe (they look like flags). // Less obviously, args beginning with @ are not safe (they look like // GNU binutils flagfile specifiers, sometimes called "response files"). // To be conservative, we reject almost any arg beginning with non-alphanumeric ASCII. // We accept leading . _ and / as likely in file system paths. // There is a copy of this function in cmd/compile/internal/gc/noder.go. func SafeArg(name string) bool { if name == "" { return false } c := name[0] return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf } // LinkerDeps returns the list of linker-induced dependencies for main package p. func LinkerDeps(p *Package) []string { // Everything links runtime. deps := []string{"runtime"} // External linking mode forces an import of runtime/cgo. if externalLinkingForced(p) && cfg.BuildContext.Compiler != "gccgo" { deps = append(deps, "runtime/cgo") } // On ARM with GOARM=5, it forces an import of math, for soft floating point. if cfg.Goarch == "arm" { deps = append(deps, "math") } // Using the race detector forces an import of runtime/race. if cfg.BuildRace { deps = append(deps, "runtime/race") } // Using memory sanitizer forces an import of runtime/msan. if cfg.BuildMSan { deps = append(deps, "runtime/msan") } return deps } // externalLinkingForced reports whether external linking is being // forced even for programs that do not use cgo. func externalLinkingForced(p *Package) bool { // Some targets must use external linking even inside GOROOT. switch cfg.BuildContext.GOOS { case "android": return true case "darwin": switch cfg.BuildContext.GOARCH { case "arm", "arm64": return true } } if !cfg.BuildContext.CgoEnabled { return false } // Currently build modes c-shared, pie (on systems that do not // support PIE with internal linking mode (currently all // systems: issue #18968)), plugin, and -linkshared force // external linking mode, as of course does // -ldflags=-linkmode=external. External linking mode forces // an import of runtime/cgo. pieCgo := cfg.BuildBuildmode == "pie" linkmodeExternal := false if p != nil { ldflags := BuildLdflags.For(p) for i, a := range ldflags { if a == "-linkmode=external" { linkmodeExternal = true } if a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "external" { linkmodeExternal = true } } } return cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" || pieCgo || cfg.BuildLinkshared || linkmodeExternal } // mkAbs rewrites list, which must be paths relative to p.Dir, // into a sorted list of absolute paths. It edits list in place but for // convenience also returns list back to its caller. func (p *Package) mkAbs(list []string) []string { for i, f := range list { list[i] = filepath.Join(p.Dir, f) } sort.Strings(list) return list } // InternalGoFiles returns the list of Go files being built for the package, // using absolute paths. func (p *Package) InternalGoFiles() []string { return p.mkAbs(str.StringList(p.GoFiles, p.CgoFiles, p.TestGoFiles)) } // InternalXGoFiles returns the list of Go files being built for the XTest package, // using absolute paths. func (p *Package) InternalXGoFiles() []string { return p.mkAbs(p.XTestGoFiles) } // InternalGoFiles returns the list of all Go files possibly relevant for the package, // using absolute paths. "Possibly relevant" means that files are not excluded // due to build tags, but files with names beginning with . or _ are still excluded. func (p *Package) InternalAllGoFiles() []string { var extra []string for _, f := range p.IgnoredGoFiles { if f != "" && f[0] != '.' || f[0] != '_' { extra = append(extra, f) } } return p.mkAbs(str.StringList(extra, p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles)) } // usesSwig reports whether the package needs to run SWIG. func (p *Package) UsesSwig() bool { return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0 } // usesCgo reports whether the package needs to run cgo func (p *Package) UsesCgo() bool { return len(p.CgoFiles) > 0 } // PackageList returns the list of packages in the dag rooted at roots // as visited in a depth-first post-order traversal. func PackageList(roots []*Package) []*Package { seen := map[*Package]bool{} all := []*Package{} var walk func(*Package) walk = func(p *Package) { if seen[p] { return } seen[p] = true for _, p1 := range p.Internal.Imports { walk(p1) } all = append(all, p) } for _, root := range roots { walk(root) } return all } // TestPackageList returns the list of packages in the dag rooted at roots // as visited in a depth-first post-order traversal, including the test // imports of the roots. This ignores errors in test packages. func TestPackageList(roots []*Package) []*Package { seen := map[*Package]bool{} all := []*Package{} var walk func(*Package) walk = func(p *Package) { if seen[p] { return } seen[p] = true for _, p1 := range p.Internal.Imports { walk(p1) } all = append(all, p) } walkTest := func(root *Package, path string) { var stk ImportStack p1 := LoadImport(path, root.Dir, root, &stk, root.Internal.Build.TestImportPos[path], ResolveImport) if p1.Error == nil { walk(p1) } } for _, root := range roots { walk(root) for _, path := range root.TestImports { walkTest(root, path) } for _, path := range root.XTestImports { walkTest(root, path) } } return all } var cmdCache = map[string]*Package{} func ClearCmdCache() { for name := range cmdCache { delete(cmdCache, name) } } // LoadPackage loads the package named by arg. func LoadPackage(arg string, stk *ImportStack) *Package { p := loadPackage(arg, stk) setToolFlags(p) return p } // LoadPackageNoFlags is like LoadPackage // but does not guarantee that the build tool flags are set in the result. // It is only for use by GOPATH-based "go get" // and is only appropriate for preliminary loading of packages. // A real load using LoadPackage or (more likely) // Packages, PackageAndErrors, or PackagesForBuild // must be done before passing the package to any build // steps, so that the tool flags can be set properly. // TODO(rsc): When GOPATH-based "go get" is removed, delete this function. func LoadPackageNoFlags(arg string, stk *ImportStack) *Package { return loadPackage(arg, stk) } // loadPackage is like loadImport but is used for command-line arguments, // not for paths found in import statements. In addition to ordinary import paths, // loadPackage accepts pseudo-paths beginning with cmd/ to denote commands // in the Go command directory, as well as paths to those directories. func loadPackage(arg string, stk *ImportStack) *Package { if build.IsLocalImport(arg) { dir := arg if !filepath.IsAbs(dir) { if abs, err := filepath.Abs(dir); err == nil { // interpret relative to current directory dir = abs } } if sub, ok := hasSubdir(cfg.GOROOTsrc, dir); ok && strings.HasPrefix(sub, "cmd/") && !strings.Contains(sub[4:], "/") { arg = sub } } if strings.HasPrefix(arg, "cmd/") && !strings.Contains(arg[4:], "/") { if p := cmdCache[arg]; p != nil { return p } stk.Push(arg) defer stk.Pop() bp, err := cfg.BuildContext.ImportDir(filepath.Join(cfg.GOROOTsrc, arg), 0) bp.ImportPath = arg bp.Goroot = true bp.BinDir = cfg.GOROOTbin if cfg.GOROOTbin != "" { bp.BinDir = cfg.GOROOTbin } bp.Root = cfg.GOROOT bp.SrcRoot = cfg.GOROOTsrc p := new(Package) cmdCache[arg] = p p.load(stk, bp, err) if p.Error == nil && p.Name != "main" { p.Error = &PackageError{ ImportStack: stk.Copy(), Err: fmt.Sprintf("expected package main but found package %s in %s", p.Name, p.Dir), } } return p } // Wasn't a command; must be a package. // If it is a local import path but names a standard package, // we treat it as if the user specified the standard package. // This lets you run go test ./ioutil in package io and be // referring to io/ioutil rather than a hypothetical import of // "./ioutil". if build.IsLocalImport(arg) || filepath.IsAbs(arg) { dir := arg if !filepath.IsAbs(arg) { dir = filepath.Join(base.Cwd, arg) } bp, _ := cfg.BuildContext.ImportDir(dir, build.FindOnly) if bp.ImportPath != "" && bp.ImportPath != "." { arg = bp.ImportPath } } return LoadImport(arg, base.Cwd, nil, stk, nil, 0) } // Packages returns the packages named by the // command line arguments 'args'. If a named package // cannot be loaded at all (for example, if the directory does not exist), // then packages prints an error and does not include that // package in the results. However, if errors occur trying // to load dependencies of a named package, the named // package is still returned, with p.Incomplete = true // and details in p.DepsErrors. func Packages(args []string) []*Package { var pkgs []*Package for _, pkg := range PackagesAndErrors(args) { if pkg.Error != nil { base.Errorf("can't load package: %s", pkg.Error) continue } pkgs = append(pkgs, pkg) } return pkgs } // PackagesAndErrors is like 'packages' but returns a // *Package for every argument, even the ones that // cannot be loaded at all. // The packages that fail to load will have p.Error != nil. func PackagesAndErrors(patterns []string) []*Package { if len(patterns) > 0 && strings.HasSuffix(patterns[0], ".go") { return []*Package{GoFilesPackage(patterns)} } matches := ImportPaths(patterns) var ( pkgs []*Package stk ImportStack seenPkg = make(map[*Package]bool) ) for _, m := range matches { for _, pkg := range m.Pkgs { p := loadPackage(pkg, &stk) p.Match = append(p.Match, m.Pattern) p.Internal.CmdlinePkg = true if m.Literal { // Note: do not set = m.Literal unconditionally // because maybe we'll see p matching both // a literal and also a non-literal pattern. p.Internal.CmdlinePkgLiteral = true } if seenPkg[p] { continue } seenPkg[p] = true pkgs = append(pkgs, p) } } // Now that CmdlinePkg is set correctly, // compute the effective flags for all loaded packages // (not just the ones matching the patterns but also // their dependencies). setToolFlags(pkgs...) return pkgs } func setToolFlags(pkgs ...*Package) { for _, p := range PackageList(pkgs) { p.Internal.Asmflags = BuildAsmflags.For(p) p.Internal.Gcflags = BuildGcflags.For(p) p.Internal.Ldflags = BuildLdflags.For(p) p.Internal.Gccgoflags = BuildGccgoflags.For(p) } } func ImportPaths(args []string) []*search.Match { if ModInit(); cfg.ModulesEnabled { return ModImportPaths(args) } return search.ImportPaths(args) } // PackagesForBuild is like Packages but exits // if any of the packages or their dependencies have errors // (cannot be built). func PackagesForBuild(args []string) []*Package { pkgs := PackagesAndErrors(args) printed := map[*PackageError]bool{} for _, pkg := range pkgs { if pkg.Error != nil { base.Errorf("can't load package: %s", pkg.Error) printed[pkg.Error] = true } for _, err := range pkg.DepsErrors { // 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. if !printed[err] { printed[err] = true base.Errorf("%s", err) } } } base.ExitIfErrors() // Check for duplicate loads of the same package. // That should be impossible, but if it does happen then // we end up trying to build the same package twice, // usually in parallel overwriting the same files, // which doesn't work very well. seen := map[string]bool{} reported := map[string]bool{} for _, pkg := range PackageList(pkgs) { if seen[pkg.ImportPath] && !reported[pkg.ImportPath] { reported[pkg.ImportPath] = true base.Errorf("internal error: duplicate loads of %s", pkg.ImportPath) } seen[pkg.ImportPath] = true } base.ExitIfErrors() return pkgs } // GoFilesPackage creates a package for building a collection of Go files // (typically named on the command line). The target is named p.a for // package p or named after the first Go file for package main. func GoFilesPackage(gofiles []string) *Package { ModInit() for _, f := range gofiles { if !strings.HasSuffix(f, ".go") { base.Fatalf("named files must be .go files") } } var stk ImportStack ctxt := cfg.BuildContext ctxt.UseAllFiles = true // Synthesize fake "directory" that only shows the named files, // to make it look like this is a standard package or // command directory. So that local imports resolve // consistently, the files must all be in the same directory. var dirent []os.FileInfo var dir string for _, file := range gofiles { fi, err := os.Stat(file) if err != nil { base.Fatalf("%s", err) } if fi.IsDir() { base.Fatalf("%s is a directory, should be a Go file", file) } dir1, _ := filepath.Split(file) if dir1 == "" { dir1 = "./" } if dir == "" { dir = dir1 } else if dir != dir1 { base.Fatalf("named files must all be in one directory; have %s and %s", dir, dir1) } dirent = append(dirent, fi) } ctxt.ReadDir = func(string) ([]os.FileInfo, error) { return dirent, nil } if cfg.ModulesEnabled { ModImportFromFiles(gofiles) } var err error if dir == "" { dir = base.Cwd } dir, err = filepath.Abs(dir) if err != nil { base.Fatalf("%s", err) } bp, err := ctxt.ImportDir(dir, 0) if ModDirImportPath != nil { // Use the effective import path of the directory // for deciding visibility during pkg.load. bp.ImportPath = ModDirImportPath(dir) } pkg := new(Package) pkg.Internal.Local = true pkg.Internal.CmdlineFiles = true stk.Push("main") pkg.load(&stk, bp, err) stk.Pop() pkg.Internal.LocalPrefix = dirToImportPath(dir) pkg.ImportPath = "command-line-arguments" pkg.Target = "" pkg.Match = gofiles if pkg.Name == "main" { _, elem := filepath.Split(gofiles[0]) exe := elem[:len(elem)-len(".go")] + cfg.ExeSuffix if cfg.BuildO == "" { cfg.BuildO = exe } if cfg.GOBIN != "" { pkg.Target = filepath.Join(cfg.GOBIN, exe) } else if cfg.ModulesEnabled { pkg.Target = filepath.Join(ModBinDir(), exe) } } setToolFlags(pkg) return pkg }
load
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/load/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 load import ( "bytes" "cmd/go/internal/base" "cmd/go/internal/str" "errors" "fmt" "go/ast" "go/build" "go/doc" "go/parser" "go/token" "path/filepath" "sort" "strings" "text/template" "unicode" "unicode/utf8" ) var TestMainDeps = []string{ // Dependencies for testmain. "os", "testing", "testing/internal/testdeps", } type TestCover struct { Mode string Local bool Pkgs []*Package Paths []string Vars []coverInfo DeclVars func(*Package, ...string) map[string]*CoverVar } // TestPackagesFor returns three packages: // - ptest, the package p compiled with added "package p" test files. // - pxtest, the result of compiling any "package p_test" (external) test files. // - pmain, the package main corresponding to the test binary (running tests in ptest and pxtest). // // If the package has no "package p_test" test files, pxtest will be nil. // If the non-test compilation of package p can be reused // (for example, if there are no "package p" test files and // package p need not be instrumented for coverage or any other reason), // then the returned ptest == p. // // The caller is expected to have checked that len(p.TestGoFiles)+len(p.XTestGoFiles) > 0, // or else there's no point in any of this. func TestPackagesFor(p *Package, cover *TestCover) (pmain, ptest, pxtest *Package, err error) { var imports, ximports []*Package var stk ImportStack stk.Push(p.ImportPath + " (test)") rawTestImports := str.StringList(p.TestImports) for i, path := range p.TestImports { p1 := LoadImport(path, p.Dir, p, &stk, p.Internal.Build.TestImportPos[path], ResolveImport) if p1.Error != nil { return nil, nil, nil, p1.Error } if len(p1.DepsErrors) > 0 { err := p1.DepsErrors[0] err.Pos = "" // show full import stack return nil, nil, nil, err } if str.Contains(p1.Deps, p.ImportPath) || p1.ImportPath == p.ImportPath { // Same error that loadPackage returns (via reusePackage) in pkg.go. // Can't change that code, because that code is only for loading the // non-test copy of a package. err := &PackageError{ ImportStack: testImportStack(stk[0], p1, p.ImportPath), Err: "import cycle not allowed in test", IsImportCycle: true, } return nil, nil, nil, err } p.TestImports[i] = p1.ImportPath imports = append(imports, p1) } stk.Pop() stk.Push(p.ImportPath + "_test") pxtestNeedsPtest := false rawXTestImports := str.StringList(p.XTestImports) for i, path := range p.XTestImports { p1 := LoadImport(path, p.Dir, p, &stk, p.Internal.Build.XTestImportPos[path], ResolveImport) if p1.Error != nil { return nil, nil, nil, p1.Error } if len(p1.DepsErrors) > 0 { err := p1.DepsErrors[0] err.Pos = "" // show full import stack return nil, nil, nil, err } if p1.ImportPath == p.ImportPath { pxtestNeedsPtest = true } else { ximports = append(ximports, p1) } p.XTestImports[i] = p1.ImportPath } stk.Pop() // Test package. if len(p.TestGoFiles) > 0 || p.Name == "main" || cover != nil && cover.Local { ptest = new(Package) *ptest = *p ptest.ForTest = p.ImportPath ptest.GoFiles = nil ptest.GoFiles = append(ptest.GoFiles, p.GoFiles...) ptest.GoFiles = append(ptest.GoFiles, p.TestGoFiles...) ptest.Target = "" // Note: The preparation of the vet config requires that common // indexes in ptest.Imports and ptest.Internal.RawImports // all line up (but RawImports can be shorter than the others). // That is, for 0 ≤ i < len(RawImports), // RawImports[i] is the import string in the program text, and // Imports[i] is the expanded import string (vendoring applied or relative path expanded away). // Any implicitly added imports appear in Imports and Internal.Imports // but not RawImports (because they were not in the source code). // We insert TestImports, imports, and rawTestImports at the start of // these lists to preserve the alignment. // Note that p.Internal.Imports may not be aligned with p.Imports/p.Internal.RawImports, // but we insert at the beginning there too just for consistency. ptest.Imports = str.StringList(p.TestImports, p.Imports) ptest.Internal.Imports = append(imports, p.Internal.Imports...) ptest.Internal.RawImports = str.StringList(rawTestImports, p.Internal.RawImports) ptest.Internal.ForceLibrary = true ptest.Internal.Build = new(build.Package) *ptest.Internal.Build = *p.Internal.Build m := map[string][]token.Position{} for k, v := range p.Internal.Build.ImportPos { m[k] = append(m[k], v...) } for k, v := range p.Internal.Build.TestImportPos { m[k] = append(m[k], v...) } ptest.Internal.Build.ImportPos = m } else { ptest = p } // External test package. if len(p.XTestGoFiles) > 0 { pxtest = &Package{ PackagePublic: PackagePublic{ Name: p.Name + "_test", ImportPath: p.ImportPath + "_test", Root: p.Root, Dir: p.Dir, GoFiles: p.XTestGoFiles, Imports: p.XTestImports, ForTest: p.ImportPath, }, Internal: PackageInternal{ LocalPrefix: p.Internal.LocalPrefix, Build: &build.Package{ ImportPos: p.Internal.Build.XTestImportPos, }, Imports: ximports, RawImports: rawXTestImports, Asmflags: p.Internal.Asmflags, Gcflags: p.Internal.Gcflags, Ldflags: p.Internal.Ldflags, Gccgoflags: p.Internal.Gccgoflags, }, } if pxtestNeedsPtest { pxtest.Internal.Imports = append(pxtest.Internal.Imports, ptest) } } // Build main package. pmain = &Package{ PackagePublic: PackagePublic{ Name: "main", Dir: p.Dir, GoFiles: []string{"_testmain.go"}, ImportPath: p.ImportPath + ".test", Root: p.Root, Imports: str.StringList(TestMainDeps), }, Internal: PackageInternal{ Build: &build.Package{Name: "main"}, Asmflags: p.Internal.Asmflags, Gcflags: p.Internal.Gcflags, Ldflags: p.Internal.Ldflags, Gccgoflags: p.Internal.Gccgoflags, }, } // The generated main also imports testing, regexp, and os. // Also the linker introduces implicit dependencies reported by LinkerDeps. stk.Push("testmain") deps := TestMainDeps // cap==len, so safe for append for _, d := range LinkerDeps(p) { deps = append(deps, d) } for _, dep := range deps { if dep == ptest.ImportPath { pmain.Internal.Imports = append(pmain.Internal.Imports, ptest) } else { p1 := LoadImport(dep, "", nil, &stk, nil, 0) if p1.Error != nil { return nil, nil, nil, p1.Error } pmain.Internal.Imports = append(pmain.Internal.Imports, p1) } } stk.Pop() if cover != nil && cover.Pkgs != nil { // Add imports, but avoid duplicates. seen := map[*Package]bool{p: true, ptest: true} for _, p1 := range pmain.Internal.Imports { seen[p1] = true } for _, p1 := range cover.Pkgs { if !seen[p1] { seen[p1] = true pmain.Internal.Imports = append(pmain.Internal.Imports, p1) } } } // Do initial scan for metadata needed for writing _testmain.go // Use that metadata to update the list of imports for package main. // The list of imports is used by recompileForTest and by the loop // afterward that gathers t.Cover information. t, err := loadTestFuncs(ptest) if err != nil { return nil, nil, nil, err } t.Cover = cover if len(ptest.GoFiles)+len(ptest.CgoFiles) > 0 { pmain.Internal.Imports = append(pmain.Internal.Imports, ptest) pmain.Imports = append(pmain.Imports, ptest.ImportPath) t.ImportTest = true } if pxtest != nil { pmain.Internal.Imports = append(pmain.Internal.Imports, pxtest) pmain.Imports = append(pmain.Imports, pxtest.ImportPath) t.ImportXtest = true } // Sort and dedup pmain.Imports. // Only matters for go list -test output. sort.Strings(pmain.Imports) w := 0 for _, path := range pmain.Imports { if w == 0 || path != pmain.Imports[w-1] { pmain.Imports[w] = path w++ } } pmain.Imports = pmain.Imports[:w] pmain.Internal.RawImports = str.StringList(pmain.Imports) if ptest != p { // We have made modifications to the package p being tested // and are rebuilding p (as ptest). // Arrange to rebuild all packages q such that // the test depends on q and q depends on p. // This makes sure that q sees the modifications to p. // Strictly speaking, the rebuild is only necessary if the // modifications to p change its export metadata, but // determining that is a bit tricky, so we rebuild always. recompileForTest(pmain, p, ptest, pxtest) } // Should we apply coverage analysis locally, // only for this package and only for this test? // Yes, if -cover is on but -coverpkg has not specified // a list of packages for global coverage. if cover != nil && cover.Local { ptest.Internal.CoverMode = cover.Mode var coverFiles []string coverFiles = append(coverFiles, ptest.GoFiles...) coverFiles = append(coverFiles, ptest.CgoFiles...) ptest.Internal.CoverVars = cover.DeclVars(ptest, coverFiles...) } for _, cp := range pmain.Internal.Imports { if len(cp.Internal.CoverVars) > 0 { t.Cover.Vars = append(t.Cover.Vars, coverInfo{cp, cp.Internal.CoverVars}) } } data, err := formatTestmain(t) if err != nil { return nil, nil, nil, err } pmain.Internal.TestmainGo = &data return pmain, ptest, pxtest, nil } func testImportStack(top string, p *Package, target string) []string { stk := []string{top, p.ImportPath} Search: for p.ImportPath != target { for _, p1 := range p.Internal.Imports { if p1.ImportPath == target || str.Contains(p1.Deps, target) { stk = append(stk, p1.ImportPath) p = p1 continue Search } } // Can't happen, but in case it does... stk = append(stk, "<lost path to cycle>") break } return stk } func recompileForTest(pmain, preal, ptest, pxtest *Package) { // The "test copy" of preal is ptest. // For each package that depends on preal, make a "test copy" // that depends on ptest. And so on, up the dependency tree. testCopy := map[*Package]*Package{preal: ptest} for _, p := range PackageList([]*Package{pmain}) { if p == preal { continue } // Copy on write. didSplit := p == pmain || p == pxtest split := func() { if didSplit { return } didSplit = true if testCopy[p] != nil { panic("recompileForTest loop") } p1 := new(Package) testCopy[p] = p1 *p1 = *p p1.ForTest = preal.ImportPath p1.Internal.Imports = make([]*Package, len(p.Internal.Imports)) copy(p1.Internal.Imports, p.Internal.Imports) p1.Imports = make([]string, len(p.Imports)) copy(p1.Imports, p.Imports) p = p1 p.Target = "" } // Update p.Internal.Imports to use test copies. for i, imp := range p.Internal.Imports { if p1 := testCopy[imp]; p1 != nil && p1 != imp { split() p.Internal.Imports[i] = p1 } } } } // isTestFunc tells whether fn has the type of a testing function. arg // specifies the parameter type we look for: B, M or T. func isTestFunc(fn *ast.FuncDecl, arg string) bool { if fn.Type.Results != nil && len(fn.Type.Results.List) > 0 || fn.Type.Params.List == nil || len(fn.Type.Params.List) != 1 || len(fn.Type.Params.List[0].Names) > 1 { return false } ptr, ok := fn.Type.Params.List[0].Type.(*ast.StarExpr) if !ok { return false } // We can't easily check that the type is *testing.M // because we don't know how testing has been imported, // but at least check that it's *M or *something.M. // Same applies for B and T. if name, ok := ptr.X.(*ast.Ident); ok && name.Name == arg { return true } if sel, ok := ptr.X.(*ast.SelectorExpr); ok && sel.Sel.Name == arg { return true } return false } // isTest tells whether name looks like a test (or benchmark, according to prefix). // It is a Test (say) if there is a character after Test that is not a lower-case letter. // We don't want TesticularCancer. func isTest(name, prefix string) bool { if !strings.HasPrefix(name, prefix) { return false } if len(name) == len(prefix) { // "Test" is ok return true } rune, _ := utf8.DecodeRuneInString(name[len(prefix):]) return !unicode.IsLower(rune) } type coverInfo struct { Package *Package Vars map[string]*CoverVar } // loadTestFuncs returns the testFuncs describing the tests that will be run. func loadTestFuncs(ptest *Package) (*testFuncs, error) { t := &testFuncs{ Package: ptest, } for _, file := range ptest.TestGoFiles { if err := t.load(filepath.Join(ptest.Dir, file), "_test", &t.ImportTest, &t.NeedTest); err != nil { return nil, err } } for _, file := range ptest.XTestGoFiles { if err := t.load(filepath.Join(ptest.Dir, file), "_xtest", &t.ImportXtest, &t.NeedXtest); err != nil { return nil, err } } return t, nil } // formatTestmain returns the content of the _testmain.go file for t. func formatTestmain(t *testFuncs) ([]byte, error) { var buf bytes.Buffer if err := testmainTmpl.Execute(&buf, t); err != nil { return nil, err } return buf.Bytes(), nil } type testFuncs struct { Tests []testFunc Benchmarks []testFunc Examples []testFunc TestMain *testFunc Package *Package ImportTest bool NeedTest bool ImportXtest bool NeedXtest bool Cover *TestCover } // ImportPath returns the import path of the package being tested, if it is within GOPATH. // This is printed by the testing package when running benchmarks. func (t *testFuncs) ImportPath() string { pkg := t.Package.ImportPath if strings.HasPrefix(pkg, "_/") { return "" } if pkg == "command-line-arguments" { return "" } return pkg } // Covered returns a string describing which packages are being tested for coverage. // If the covered package is the same as the tested package, it returns the empty string. // Otherwise it is a comma-separated human-readable list of packages beginning with // " in", ready for use in the coverage message. func (t *testFuncs) Covered() string { if t.Cover == nil || t.Cover.Paths == nil { return "" } return " in " + strings.Join(t.Cover.Paths, ", ") } // Tested returns the name of the package being tested. func (t *testFuncs) Tested() string { return t.Package.Name } type testFunc struct { Package string // imported package name (_test or _xtest) Name string // function name Output string // output, for examples Unordered bool // output is allowed to be unordered. } var testFileSet = token.NewFileSet() func (t *testFuncs) load(filename, pkg string, doImport, seen *bool) error { f, err := parser.ParseFile(testFileSet, filename, nil, parser.ParseComments) if err != nil { return base.ExpandScanner(err) } for _, d := range f.Decls { n, ok := d.(*ast.FuncDecl) if !ok { continue } if n.Recv != nil { continue } name := n.Name.String() switch { case name == "TestMain": if isTestFunc(n, "T") { t.Tests = append(t.Tests, testFunc{pkg, name, "", false}) *doImport, *seen = true, true continue } err := checkTestFunc(n, "M") if err != nil { return err } if t.TestMain != nil { return errors.New("multiple definitions of TestMain") } t.TestMain = &testFunc{pkg, name, "", false} *doImport, *seen = true, true case isTest(name, "Test"): err := checkTestFunc(n, "T") if err != nil { return err } t.Tests = append(t.Tests, testFunc{pkg, name, "", false}) *doImport, *seen = true, true case isTest(name, "Benchmark"): err := checkTestFunc(n, "B") if err != nil { return err } t.Benchmarks = append(t.Benchmarks, testFunc{pkg, name, "", false}) *doImport, *seen = true, true } } ex := doc.Examples(f) sort.Slice(ex, func(i, j int) bool { return ex[i].Order < ex[j].Order }) for _, e := range ex { *doImport = true // import test file whether executed or not if e.Output == "" && !e.EmptyOutput { // Don't run examples with no output. continue } t.Examples = append(t.Examples, testFunc{pkg, "Example" + e.Name, e.Output, e.Unordered}) *seen = true } return nil } func checkTestFunc(fn *ast.FuncDecl, arg string) error { if !isTestFunc(fn, arg) { name := fn.Name.String() pos := testFileSet.Position(fn.Pos()) return fmt.Errorf("%s: wrong signature for %s, must be: func %s(%s *testing.%s)", pos, name, name, strings.ToLower(arg), arg) } return nil } var testmainTmpl = template.Must(template.New("main").Parse(` package main import ( {{if not .TestMain}} "os" {{end}} "testing" "testing/internal/testdeps" {{if .ImportTest}} {{if .NeedTest}}_test{{else}}_{{end}} {{.Package.ImportPath | printf "%q"}} {{end}} {{if .ImportXtest}} {{if .NeedXtest}}_xtest{{else}}_{{end}} {{.Package.ImportPath | printf "%s_test" | printf "%q"}} {{end}} {{if .Cover}} {{range $i, $p := .Cover.Vars}} _cover{{$i}} {{$p.Package.ImportPath | printf "%q"}} {{end}} {{end}} ) var tests = []testing.InternalTest{ {{range .Tests}} {"{{.Name}}", {{.Package}}.{{.Name}}}, {{end}} } var benchmarks = []testing.InternalBenchmark{ {{range .Benchmarks}} {"{{.Name}}", {{.Package}}.{{.Name}}}, {{end}} } var examples = []testing.InternalExample{ {{range .Examples}} {"{{.Name}}", {{.Package}}.{{.Name}}, {{.Output | printf "%q"}}, {{.Unordered}}}, {{end}} } func init() { testdeps.ImportPath = {{.ImportPath | printf "%q"}} } {{if .Cover}} // Only updated by init functions, so no need for atomicity. var ( coverCounters = make(map[string][]uint32) coverBlocks = make(map[string][]testing.CoverBlock) ) func init() { {{range $i, $p := .Cover.Vars}} {{range $file, $cover := $p.Vars}} coverRegisterFile({{printf "%q" $cover.File}}, _cover{{$i}}.{{$cover.Var}}.Count[:], _cover{{$i}}.{{$cover.Var}}.Pos[:], _cover{{$i}}.{{$cover.Var}}.NumStmt[:]) {{end}} {{end}} } func coverRegisterFile(fileName string, counter []uint32, pos []uint32, numStmts []uint16) { if 3*len(counter) != len(pos) || len(counter) != len(numStmts) { panic("coverage: mismatched sizes") } if coverCounters[fileName] != nil { // Already registered. return } coverCounters[fileName] = counter block := make([]testing.CoverBlock, len(counter)) for i := range counter { block[i] = testing.CoverBlock{ Line0: pos[3*i+0], Col0: uint16(pos[3*i+2]), Line1: pos[3*i+1], Col1: uint16(pos[3*i+2]>>16), Stmts: numStmts[i], } } coverBlocks[fileName] = block } {{end}} func main() { {{if .Cover}} testing.RegisterCover(testing.Cover{ Mode: {{printf "%q" .Cover.Mode}}, Counters: coverCounters, Blocks: coverBlocks, CoveredPackages: {{printf "%q" .Covered}}, }) {{end}} m := testing.MainStart(testdeps.TestDeps{}, tests, benchmarks, examples) {{with .TestMain}} {{.Package}}.{{.Name}}(m) {{else}} os.Exit(m.Run()) {{end}} } `))
load
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/load/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 load import ( "path/filepath" "strings" "cmd/go/internal/search" ) // MatchPackage(pattern, cwd)(p) reports whether package p matches pattern in the working directory cwd. func MatchPackage(pattern, cwd string) func(*Package) bool { switch { case search.IsRelativePath(pattern): // Split pattern into leading pattern-free directory path // (including all . and .. elements) and the final pattern. var dir string i := strings.Index(pattern, "...") if i < 0 { dir, pattern = pattern, "" } else { j := strings.LastIndex(pattern[:i], "/") dir, pattern = pattern[:j], pattern[j+1:] } dir = filepath.Join(cwd, dir) if pattern == "" { return func(p *Package) bool { return p.Dir == dir } } matchPath := search.MatchPattern(pattern) return func(p *Package) bool { // Compute relative path to dir and see if it matches the pattern. rel, err := filepath.Rel(dir, p.Dir) if err != nil { // Cannot make relative - e.g. different drive letters on Windows. return false } rel = filepath.ToSlash(rel) if rel == ".." || strings.HasPrefix(rel, "../") { return false } return matchPath(rel) } case pattern == "all": return func(p *Package) bool { return true } case pattern == "std": return func(p *Package) bool { return p.Standard } case pattern == "cmd": return func(p *Package) bool { return p.Standard && strings.HasPrefix(p.ImportPath, "cmd/") } default: matchPath := search.MatchPattern(pattern) return func(p *Package) bool { return matchPath(p.ImportPath) } } }
load
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/load/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 load import ( "cmd/go/internal/base" "cmd/go/internal/str" "fmt" "strings" ) var ( BuildAsmflags PerPackageFlag // -asmflags BuildGcflags PerPackageFlag // -gcflags BuildLdflags PerPackageFlag // -ldflags BuildGccgoflags PerPackageFlag // -gccgoflags ) // A PerPackageFlag is a command-line flag implementation (a flag.Value) // that allows specifying different effective flags for different packages. // See 'go help build' for more details about per-package flags. type PerPackageFlag struct { present bool values []ppfValue } // A ppfValue is a single <pattern>=<flags> per-package flag value. type ppfValue struct { match func(*Package) bool // compiled pattern flags []string } // Set is called each time the flag is encountered on the command line. func (f *PerPackageFlag) Set(v string) error { return f.set(v, base.Cwd) } // set is the implementation of Set, taking a cwd (current working directory) for easier testing. func (f *PerPackageFlag) set(v, cwd string) error { f.present = true match := func(p *Package) bool { return p.Internal.CmdlinePkg || p.Internal.CmdlineFiles } // default predicate with no pattern // For backwards compatibility with earlier flag splitting, ignore spaces around flags. v = strings.TrimSpace(v) if v == "" { // Special case: -gcflags="" means no flags for command-line arguments // (overrides previous -gcflags="-whatever"). f.values = append(f.values, ppfValue{match, []string{}}) return nil } if !strings.HasPrefix(v, "-") { i := strings.Index(v, "=") if i < 0 { return fmt.Errorf("missing =<value> in <pattern>=<value>") } if i == 0 { return fmt.Errorf("missing <pattern> in <pattern>=<value>") } pattern := strings.TrimSpace(v[:i]) match = MatchPackage(pattern, cwd) v = v[i+1:] } flags, err := str.SplitQuotedFields(v) if err != nil { return err } if flags == nil { flags = []string{} } f.values = append(f.values, ppfValue{match, flags}) return nil } // String is required to implement flag.Value. // It is not used, because cmd/go never calls flag.PrintDefaults. func (f *PerPackageFlag) String() string { return "<PerPackageFlag>" } // Present reports whether the flag appeared on the command line. func (f *PerPackageFlag) Present() bool { return f.present } // For returns the flags to use for the given package. func (f *PerPackageFlag) For(p *Package) []string { flags := []string{} for _, v := range f.values { if v.match(p) { flags = v.flags } } return flags }
clean
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/clean/clean.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 clean implements the ``go clean'' command. package clean import ( "fmt" "io/ioutil" "os" "path/filepath" "strings" "time" "cmd/go/internal/base" "cmd/go/internal/cache" "cmd/go/internal/cfg" "cmd/go/internal/load" "cmd/go/internal/modfetch" "cmd/go/internal/modload" "cmd/go/internal/work" ) var CmdClean = &base.Command{ UsageLine: "go clean [clean flags] [build flags] [packages]", Short: "remove object files and cached files", Long: ` Clean removes object files from package source directories. The go command builds most objects in a temporary directory, so go clean is mainly concerned with object files left by other tools or by manual invocations of go build. Specifically, clean removes the following files from each of the source directories corresponding to the import paths: _obj/ old object directory, left from Makefiles _test/ old test directory, left from Makefiles _testmain.go old gotest file, left from Makefiles test.out old test log, left from Makefiles build.out old test log, left from Makefiles *.[568ao] object files, left from Makefiles DIR(.exe) from go build DIR.test(.exe) from go test -c MAINFILE(.exe) from go build MAINFILE.go *.so from SWIG In the list, DIR represents the final path element of the directory, and MAINFILE is the base name of any Go source file in the directory that is not included when building the package. The -i flag causes clean to remove the corresponding installed archive or binary (what 'go install' would create). The -n flag causes clean to print the remove commands it would execute, but not run them. The -r flag causes clean to be applied recursively to all the dependencies of the packages named by the import paths. The -x flag causes clean to print remove commands as it executes them. The -cache flag causes clean to remove the entire go build cache. The -testcache flag causes clean to expire all test results in the go build cache. The -modcache flag causes clean to remove the entire module download cache, including unpacked source code of versioned dependencies. For more about build flags, see 'go help build'. For more about specifying packages, see 'go help packages'. `, } var ( cleanI bool // clean -i flag cleanR bool // clean -r flag cleanCache bool // clean -cache flag cleanModcache bool // clean -modcache flag cleanTestcache bool // clean -testcache flag ) func init() { // break init cycle CmdClean.Run = runClean CmdClean.Flag.BoolVar(&cleanI, "i", false, "") CmdClean.Flag.BoolVar(&cleanR, "r", false, "") CmdClean.Flag.BoolVar(&cleanCache, "cache", false, "") CmdClean.Flag.BoolVar(&cleanModcache, "modcache", false, "") CmdClean.Flag.BoolVar(&cleanTestcache, "testcache", false, "") // -n and -x are important enough to be // mentioned explicitly in the docs but they // are part of the build flags. work.AddBuildFlags(CmdClean) } func runClean(cmd *base.Command, args []string) { if len(args) == 0 && modload.Failed() { // Don't try to clean current directory, // which will cause modload to base.Fatalf. } else { for _, pkg := range load.PackagesAndErrors(args) { clean(pkg) } } if cleanCache { var b work.Builder b.Print = fmt.Print dir := cache.DefaultDir() if dir != "off" { // Remove the cache subdirectories but not the top cache directory. // The top cache directory may have been created with special permissions // and not something that we want to remove. Also, we'd like to preserve // the access log for future analysis, even if the cache is cleared. subdirs, _ := filepath.Glob(filepath.Join(dir, "[0-9a-f][0-9a-f]")) if len(subdirs) > 0 { if cfg.BuildN || cfg.BuildX { b.Showcmd("", "rm -r %s", strings.Join(subdirs, " ")) } printedErrors := false for _, d := range subdirs { // Only print the first error - there may be many. // This also mimics what os.RemoveAll(dir) would do. if err := os.RemoveAll(d); err != nil && !printedErrors { printedErrors = true base.Errorf("go clean -cache: %v", err) } } } } } if cleanTestcache && !cleanCache { // Instead of walking through the entire cache looking for test results, // we write a file to the cache indicating that all test results from before // right now are to be ignored. dir := cache.DefaultDir() if dir != "off" { err := ioutil.WriteFile(filepath.Join(dir, "testexpire.txt"), []byte(fmt.Sprintf("%d\n", time.Now().UnixNano())), 0666) if err != nil { base.Errorf("go clean -testcache: %v", err) } } } if cleanModcache { if modfetch.PkgMod == "" { base.Fatalf("go clean -modcache: no module cache") } if err := removeAll(modfetch.PkgMod); err != nil { base.Errorf("go clean -modcache: %v", err) } } } func removeAll(dir string) error { // Module cache has 0555 directories; make them writable in order to remove content. filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { return nil // ignore errors walking in file system } if info.IsDir() { os.Chmod(path, 0777) } return nil }) return os.RemoveAll(dir) } var cleaned = map[*load.Package]bool{} // TODO: These are dregs left by Makefile-based builds. // Eventually, can stop deleting these. var cleanDir = map[string]bool{ "_test": true, "_obj": true, } var cleanFile = map[string]bool{ "_testmain.go": true, "test.out": true, "build.out": true, "a.out": true, } var cleanExt = map[string]bool{ ".5": true, ".6": true, ".8": true, ".a": true, ".o": true, ".so": true, } func clean(p *load.Package) { if cleaned[p] { return } cleaned[p] = true if p.Dir == "" { base.Errorf("can't load package: %v", p.Error) return } dirs, err := ioutil.ReadDir(p.Dir) if err != nil { base.Errorf("go clean %s: %v", p.Dir, err) return } var b work.Builder b.Print = fmt.Print packageFile := map[string]bool{} if p.Name != "main" { // Record which files are not in package main. // The others are. keep := func(list []string) { for _, f := range list { packageFile[f] = true } } keep(p.GoFiles) keep(p.CgoFiles) keep(p.TestGoFiles) keep(p.XTestGoFiles) } _, elem := filepath.Split(p.Dir) var allRemove []string // Remove dir-named executable only if this is package main. if p.Name == "main" { allRemove = append(allRemove, elem, elem+".exe", ) } // Remove package test executables. allRemove = append(allRemove, elem+".test", elem+".test.exe", ) // Remove a potential executable for each .go file in the directory that // is not part of the directory's package. for _, dir := range dirs { name := dir.Name() if packageFile[name] { continue } if !dir.IsDir() && strings.HasSuffix(name, ".go") { // TODO(adg,rsc): check that this .go file is actually // in "package main", and therefore capable of building // to an executable file. base := name[:len(name)-len(".go")] allRemove = append(allRemove, base, base+".exe") } } if cfg.BuildN || cfg.BuildX { b.Showcmd(p.Dir, "rm -f %s", strings.Join(allRemove, " ")) } toRemove := map[string]bool{} for _, name := range allRemove { toRemove[name] = true } for _, dir := range dirs { name := dir.Name() if dir.IsDir() { // TODO: Remove once Makefiles are forgotten. if cleanDir[name] { if cfg.BuildN || cfg.BuildX { b.Showcmd(p.Dir, "rm -r %s", name) if cfg.BuildN { continue } } if err := os.RemoveAll(filepath.Join(p.Dir, name)); err != nil { base.Errorf("go clean: %v", err) } } continue } if cfg.BuildN { continue } if cleanFile[name] || cleanExt[filepath.Ext(name)] || toRemove[name] { removeFile(filepath.Join(p.Dir, name)) } } if cleanI && p.Target != "" { if cfg.BuildN || cfg.BuildX { b.Showcmd("", "rm -f %s", p.Target) } if !cfg.BuildN { removeFile(p.Target) } } if cleanR { for _, p1 := range p.Internal.Imports { clean(p1) } } } // removeFile tries to remove file f, if error other than file doesn't exist // occurs, it will report the error. func removeFile(f string) { err := os.Remove(f) if err == nil || os.IsNotExist(err) { return } // Windows does not allow deletion of a binary file while it is executing. if base.ToolIsWindows { // Remove lingering ~ file from last attempt. if _, err2 := os.Stat(f + "~"); err2 == nil { os.Remove(f + "~") } // Try to move it out of the way. If the move fails, // which is likely, we'll try again the // next time we do an install of this binary. if err2 := os.Rename(f, f+"~"); err2 == nil { os.Remove(f + "~") return } } base.Errorf("go clean: %v", err) }
semver
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/semver/semver_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 semver import ( "strings" "testing" ) var tests = []struct { in string out string }{ {"bad", ""}, {"v1-alpha.beta.gamma", ""}, {"v1-pre", ""}, {"v1+meta", ""}, {"v1-pre+meta", ""}, {"v1.2-pre", ""}, {"v1.2+meta", ""}, {"v1.2-pre+meta", ""}, {"v1.0.0-alpha", "v1.0.0-alpha"}, {"v1.0.0-alpha.1", "v1.0.0-alpha.1"}, {"v1.0.0-alpha.beta", "v1.0.0-alpha.beta"}, {"v1.0.0-beta", "v1.0.0-beta"}, {"v1.0.0-beta.2", "v1.0.0-beta.2"}, {"v1.0.0-beta.11", "v1.0.0-beta.11"}, {"v1.0.0-rc.1", "v1.0.0-rc.1"}, {"v1", "v1.0.0"}, {"v1.0", "v1.0.0"}, {"v1.0.0", "v1.0.0"}, {"v1.2", "v1.2.0"}, {"v1.2.0", "v1.2.0"}, {"v1.2.3-456", "v1.2.3-456"}, {"v1.2.3-456.789", "v1.2.3-456.789"}, {"v1.2.3-456-789", "v1.2.3-456-789"}, {"v1.2.3-456a", "v1.2.3-456a"}, {"v1.2.3-pre", "v1.2.3-pre"}, {"v1.2.3-pre+meta", "v1.2.3-pre"}, {"v1.2.3-pre.1", "v1.2.3-pre.1"}, {"v1.2.3-zzz", "v1.2.3-zzz"}, {"v1.2.3", "v1.2.3"}, {"v1.2.3+meta", "v1.2.3"}, {"v1.2.3+meta-pre", "v1.2.3"}, } func TestIsValid(t *testing.T) { for _, tt := range tests { ok := IsValid(tt.in) if ok != (tt.out != "") { t.Errorf("IsValid(%q) = %v, want %v", tt.in, ok, !ok) } } } func TestCanonical(t *testing.T) { for _, tt := range tests { out := Canonical(tt.in) if out != tt.out { t.Errorf("Canonical(%q) = %q, want %q", tt.in, out, tt.out) } } } func TestMajor(t *testing.T) { for _, tt := range tests { out := Major(tt.in) want := "" if i := strings.Index(tt.out, "."); i >= 0 { want = tt.out[:i] } if out != want { t.Errorf("Major(%q) = %q, want %q", tt.in, out, want) } } } func TestMajorMinor(t *testing.T) { for _, tt := range tests { out := MajorMinor(tt.in) var want string if tt.out != "" { want = tt.in if i := strings.Index(want, "+"); i >= 0 { want = want[:i] } if i := strings.Index(want, "-"); i >= 0 { want = want[:i] } switch strings.Count(want, ".") { case 0: want += ".0" case 1: // ok case 2: want = want[:strings.LastIndex(want, ".")] } } if out != want { t.Errorf("MajorMinor(%q) = %q, want %q", tt.in, out, want) } } } func TestPrerelease(t *testing.T) { for _, tt := range tests { pre := Prerelease(tt.in) var want string if tt.out != "" { if i := strings.Index(tt.out, "-"); i >= 0 { want = tt.out[i:] } } if pre != want { t.Errorf("Prerelease(%q) = %q, want %q", tt.in, pre, want) } } } func TestBuild(t *testing.T) { for _, tt := range tests { build := Build(tt.in) var want string if tt.out != "" { if i := strings.Index(tt.in, "+"); i >= 0 { want = tt.in[i:] } } if build != want { t.Errorf("Build(%q) = %q, want %q", tt.in, build, want) } } } func TestCompare(t *testing.T) { for i, ti := range tests { for j, tj := range tests { cmp := Compare(ti.in, tj.in) var want int if ti.out == tj.out { want = 0 } else if i < j { want = -1 } else { want = +1 } if cmp != want { t.Errorf("Compare(%q, %q) = %d, want %d", ti.in, tj.in, cmp, want) } } } } func TestMax(t *testing.T) { for i, ti := range tests { for j, tj := range tests { max := Max(ti.in, tj.in) want := Canonical(ti.in) if i < j { want = Canonical(tj.in) } if max != want { t.Errorf("Max(%q, %q) = %q, want %q", ti.in, tj.in, max, want) } } } } var ( v1 = "v1.0.0+metadata-dash" v2 = "v1.0.0+metadata-dash1" ) func BenchmarkCompare(b *testing.B) { for i := 0; i < b.N; i++ { if Compare(v1, v2) != 0 { b.Fatalf("bad compare") } } }
semver
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/semver/semver.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 semver implements comparison of semantic version strings. // In this package, semantic version strings must begin with a leading "v", // as in "v1.0.0". // // The general form of a semantic version string accepted by this package is // // vMAJOR[.MINOR[.PATCH[-PRERELEASE][+BUILD]]] // // where square brackets indicate optional parts of the syntax; // MAJOR, MINOR, and PATCH are decimal integers without extra leading zeros; // PRERELEASE and BUILD are each a series of non-empty dot-separated identifiers // using only alphanumeric characters and hyphens; and // all-numeric PRERELEASE identifiers must not have leading zeros. // // This package follows Semantic Versioning 2.0.0 (see semver.org) // with two exceptions. First, it requires the "v" prefix. Second, it recognizes // vMAJOR and vMAJOR.MINOR (with no prerelease or build suffixes) // as shorthands for vMAJOR.0.0 and vMAJOR.MINOR.0. package semver // parsed returns the parsed form of a semantic version string. type parsed struct { major string minor string patch string short string prerelease string build string err string } // IsValid reports whether v is a valid semantic version string. func IsValid(v string) bool { _, ok := parse(v) return ok } // Canonical returns the canonical formatting of the semantic version v. // It fills in any missing .MINOR or .PATCH and discards build metadata. // Two semantic versions compare equal only if their canonical formattings // are identical strings. // The canonical invalid semantic version is the empty string. func Canonical(v string) string { p, ok := parse(v) if !ok { return "" } if p.build != "" { return v[:len(v)-len(p.build)] } if p.short != "" { return v + p.short } return v } // Major returns the major version prefix of the semantic version v. // For example, Major("v2.1.0") == "v2". // If v is an invalid semantic version string, Major returns the empty string. func Major(v string) string { pv, ok := parse(v) if !ok { return "" } return v[:1+len(pv.major)] } // MajorMinor returns the major.minor version prefix of the semantic version v. // For example, MajorMinor("v2.1.0") == "v2.1". // If v is an invalid semantic version string, MajorMinor returns the empty string. func MajorMinor(v string) string { pv, ok := parse(v) if !ok { return "" } i := 1 + len(pv.major) if j := i + 1 + len(pv.minor); j <= len(v) && v[i] == '.' && v[i+1:j] == pv.minor { return v[:j] } return v[:i] + "." + pv.minor } // Prerelease returns the prerelease suffix of the semantic version v. // For example, Prerelease("v2.1.0-pre+meta") == "-pre". // If v is an invalid semantic version string, Prerelease returns the empty string. func Prerelease(v string) string { pv, ok := parse(v) if !ok { return "" } return pv.prerelease } // Build returns the build suffix of the semantic version v. // For example, Build("v2.1.0+meta") == "+meta". // If v is an invalid semantic version string, Build returns the empty string. func Build(v string) string { pv, ok := parse(v) if !ok { return "" } return pv.build } // Compare returns an integer comparing two versions according to // according to semantic version precedence. // The result will be 0 if v == w, -1 if v < w, or +1 if v > w. // // An invalid semantic version string is considered less than a valid one. // All invalid semantic version strings compare equal to each other. func Compare(v, w string) int { pv, ok1 := parse(v) pw, ok2 := parse(w) if !ok1 && !ok2 { return 0 } if !ok1 { return -1 } if !ok2 { return +1 } if c := compareInt(pv.major, pw.major); c != 0 { return c } if c := compareInt(pv.minor, pw.minor); c != 0 { return c } if c := compareInt(pv.patch, pw.patch); c != 0 { return c } return comparePrerelease(pv.prerelease, pw.prerelease) } // Max canonicalizes its arguments and then returns the version string // that compares greater. func Max(v, w string) string { v = Canonical(v) w = Canonical(w) if Compare(v, w) > 0 { return v } return w } func parse(v string) (p parsed, ok bool) { if v == "" || v[0] != 'v' { p.err = "missing v prefix" return } p.major, v, ok = parseInt(v[1:]) if !ok { p.err = "bad major version" return } if v == "" { p.minor = "0" p.patch = "0" p.short = ".0.0" return } if v[0] != '.' { p.err = "bad minor prefix" ok = false return } p.minor, v, ok = parseInt(v[1:]) if !ok { p.err = "bad minor version" return } if v == "" { p.patch = "0" p.short = ".0" return } if v[0] != '.' { p.err = "bad patch prefix" ok = false return } p.patch, v, ok = parseInt(v[1:]) if !ok { p.err = "bad patch version" return } if len(v) > 0 && v[0] == '-' { p.prerelease, v, ok = parsePrerelease(v) if !ok { p.err = "bad prerelease" return } } if len(v) > 0 && v[0] == '+' { p.build, v, ok = parseBuild(v) if !ok { p.err = "bad build" return } } if v != "" { p.err = "junk on end" ok = false return } ok = true return } func parseInt(v string) (t, rest string, ok bool) { if v == "" { return } if v[0] < '0' || '9' < v[0] { return } i := 1 for i < len(v) && '0' <= v[i] && v[i] <= '9' { i++ } if v[0] == '0' && i != 1 { return } return v[:i], v[i:], true } func parsePrerelease(v string) (t, rest string, ok bool) { // "A pre-release version MAY be denoted by appending a hyphen and // a series of dot separated identifiers immediately following the patch version. // Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. // Identifiers MUST NOT be empty. Numeric identifiers MUST NOT include leading zeroes." if v == "" || v[0] != '-' { return } i := 1 start := 1 for i < len(v) && v[i] != '+' { if !isIdentChar(v[i]) && v[i] != '.' { return } if v[i] == '.' { if start == i || isBadNum(v[start:i]) { return } start = i + 1 } i++ } if start == i || isBadNum(v[start:i]) { return } return v[:i], v[i:], true } func parseBuild(v string) (t, rest string, ok bool) { if v == "" || v[0] != '+' { return } i := 1 start := 1 for i < len(v) { if !isIdentChar(v[i]) { return } if v[i] == '.' { if start == i { return } start = i + 1 } i++ } if start == i { return } return v[:i], v[i:], true } func isIdentChar(c byte) bool { return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '-' } func isBadNum(v string) bool { i := 0 for i < len(v) && '0' <= v[i] && v[i] <= '9' { i++ } return i == len(v) && i > 1 && v[0] == '0' } func isNum(v string) bool { i := 0 for i < len(v) && '0' <= v[i] && v[i] <= '9' { i++ } return i == len(v) } func compareInt(x, y string) int { if x == y { return 0 } if len(x) < len(y) { return -1 } if len(x) > len(y) { return +1 } if x < y { return -1 } else { return +1 } } func comparePrerelease(x, y string) int { // "When major, minor, and patch are equal, a pre-release version has // lower precedence than a normal version. // Example: 1.0.0-alpha < 1.0.0. // Precedence for two pre-release versions with the same major, minor, // and patch version MUST be determined by comparing each dot separated // identifier from left to right until a difference is found as follows: // identifiers consisting of only digits are compared numerically and // identifiers with letters or hyphens are compared lexically in ASCII // sort order. Numeric identifiers always have lower precedence than // non-numeric identifiers. A larger set of pre-release fields has a // higher precedence than a smaller set, if all of the preceding // identifiers are equal. // Example: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < // 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0." if x == y { return 0 } if x == "" { return +1 } if y == "" { return -1 } for x != "" && y != "" { x = x[1:] // skip - or . y = y[1:] // skip - or . var dx, dy string dx, x = nextIdent(x) dy, y = nextIdent(y) if dx != dy { ix := isNum(dx) iy := isNum(dy) if ix != iy { if ix { return -1 } else { return +1 } } if ix { if len(dx) < len(dy) { return -1 } if len(dx) > len(dy) { return +1 } } if dx < dy { return -1 } else { return +1 } } } if x == "" { return -1 } else { return +1 } } func nextIdent(x string) (dx, rest string) { i := 0 for i < len(x) && x[i] != '.' { i++ } return x[:i], x[i:] }
dirhash
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/dirhash/hash.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 dirhash defines hashes over directory trees. package dirhash import ( "archive/zip" "crypto/sha256" "encoding/base64" "errors" "fmt" "io" "os" "path/filepath" "sort" "strings" ) var DefaultHash = Hash1 type Hash func(files []string, open func(string) (io.ReadCloser, error)) (string, error) func Hash1(files []string, open func(string) (io.ReadCloser, error)) (string, error) { h := sha256.New() files = append([]string(nil), files...) sort.Strings(files) for _, file := range files { if strings.Contains(file, "\n") { return "", errors.New("filenames with newlines are not supported") } r, err := open(file) if err != nil { return "", err } hf := sha256.New() _, err = io.Copy(hf, r) r.Close() if err != nil { return "", err } fmt.Fprintf(h, "%x %s\n", hf.Sum(nil), file) } return "h1:" + base64.StdEncoding.EncodeToString(h.Sum(nil)), nil } func HashDir(dir, prefix string, hash Hash) (string, error) { files, err := DirFiles(dir, prefix) if err != nil { return "", err } osOpen := func(name string) (io.ReadCloser, error) { return os.Open(filepath.Join(dir, strings.TrimPrefix(name, prefix))) } return hash(files, osOpen) } func DirFiles(dir, prefix string) ([]string, error) { var files []string dir = filepath.Clean(dir) err := filepath.Walk(dir, func(file string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { return nil } rel := file if dir != "." { rel = file[len(dir)+1:] } f := filepath.Join(prefix, rel) files = append(files, filepath.ToSlash(f)) return nil }) if err != nil { return nil, err } return files, nil } func HashZip(zipfile string, hash Hash) (string, error) { z, err := zip.OpenReader(zipfile) if err != nil { return "", err } defer z.Close() var files []string zfiles := make(map[string]*zip.File) for _, file := range z.File { files = append(files, file.Name) zfiles[file.Name] = file } zipOpen := func(name string) (io.ReadCloser, error) { f := zfiles[name] if f == nil { return nil, fmt.Errorf("file %q not found in zip", name) // should never happen } return f.Open() } return hash(files, zipOpen) }
dirhash
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/dirhash/hash_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 dirhash import ( "archive/zip" "crypto/sha256" "encoding/base64" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "testing" ) func h(s string) string { return fmt.Sprintf("%x", sha256.Sum256([]byte(s))) } func htop(k string, s string) string { sum := sha256.Sum256([]byte(s)) return k + ":" + base64.StdEncoding.EncodeToString(sum[:]) } func TestHash1(t *testing.T) { files := []string{"xyz", "abc"} open := func(name string) (io.ReadCloser, error) { return ioutil.NopCloser(strings.NewReader("data for " + name)), nil } want := htop("h1", fmt.Sprintf("%s %s\n%s %s\n", h("data for abc"), "abc", h("data for xyz"), "xyz")) out, err := Hash1(files, open) if err != nil { t.Fatal(err) } if out != want { t.Errorf("Hash1(...) = %s, want %s", out, want) } _, err = Hash1([]string{"xyz", "a\nbc"}, open) if err == nil { t.Error("Hash1: expected error on newline in filenames") } } func TestHashDir(t *testing.T) { dir, err := ioutil.TempDir("", "dirhash-test-") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) if err := ioutil.WriteFile(filepath.Join(dir, "xyz"), []byte("data for xyz"), 0666); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(filepath.Join(dir, "abc"), []byte("data for abc"), 0666); err != nil { t.Fatal(err) } want := htop("h1", fmt.Sprintf("%s %s\n%s %s\n", h("data for abc"), "prefix/abc", h("data for xyz"), "prefix/xyz")) out, err := HashDir(dir, "prefix", Hash1) if err != nil { t.Fatalf("HashDir: %v", err) } if out != want { t.Errorf("HashDir(...) = %s, want %s", out, want) } } func TestHashZip(t *testing.T) { f, err := ioutil.TempFile("", "dirhash-test-") if err != nil { t.Fatal(err) } defer os.Remove(f.Name()) defer f.Close() z := zip.NewWriter(f) w, err := z.Create("prefix/xyz") if err != nil { t.Fatal(err) } w.Write([]byte("data for xyz")) w, err = z.Create("prefix/abc") if err != nil { t.Fatal(err) } w.Write([]byte("data for abc")) if err := z.Close(); err != nil { t.Fatal(err) } if err := f.Close(); err != nil { t.Fatal(err) } want := htop("h1", fmt.Sprintf("%s %s\n%s %s\n", h("data for abc"), "prefix/abc", h("data for xyz"), "prefix/xyz")) out, err := HashZip(f.Name(), Hash1) if err != nil { t.Fatalf("HashDir: %v", err) } if out != want { t.Errorf("HashDir(...) = %s, want %s", out, want) } } func TestDirFiles(t *testing.T) { dir, err := ioutil.TempDir("", "dirfiles-test-") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) if err := ioutil.WriteFile(filepath.Join(dir, "xyz"), []byte("data for xyz"), 0666); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(filepath.Join(dir, "abc"), []byte("data for abc"), 0666); err != nil { t.Fatal(err) } if err := os.Mkdir(filepath.Join(dir, "subdir"), 0777); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(filepath.Join(dir, "subdir", "xyz"), []byte("data for subdir xyz"), 0666); err != nil { t.Fatal(err) } prefix := "foo/bar@v2.3.4" out, err := DirFiles(dir, prefix) if err != nil { t.Fatalf("DirFiles: %v", err) } for _, file := range out { if !strings.HasPrefix(file, prefix) { t.Errorf("Dir file = %s, want prefix %s", file, prefix) } } }
version
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/version/vgo.go
package version const version = "devel +b0a1c5df98"
version
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/version/version.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 version implements the ``go version'' command. package version import ( "fmt" "runtime" "cmd/go/internal/base" "cmd/go/internal/work" ) var CmdVersion = &base.Command{ Run: runVersion, UsageLine: "go version", Short: "print Go version", Long: `Version prints the Go version, as reported by runtime.Version.`, } func runVersion(cmd *base.Command, args []string) { if len(args) != 0 { cmd.Usage() } fmt.Printf("go version %s %s/%s vgo:%s\n", work.RuntimeVersion, runtime.GOOS, runtime.GOARCH, version) }
tool
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/tool/tool.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 tool implements the ``go tool'' command. package tool import ( "fmt" "os" "os/exec" "sort" "strings" "cmd/go/internal/base" "cmd/go/internal/cfg" ) var CmdTool = &base.Command{ Run: runTool, UsageLine: "go tool [-n] command [args...]", Short: "run specified go tool", Long: ` Tool runs the go tool command identified by the arguments. With no arguments it prints the list of known tools. The -n flag causes tool to print the command that would be executed but not execute it. For more about each tool command, see 'go doc cmd/<command>'. `, } var toolN bool // Return whether tool can be expected in the gccgo tool directory. // Other binaries could be in the same directory so don't // show those with the 'go tool' command. func isGccgoTool(tool string) bool { switch tool { case "cgo", "fix", "cover", "godoc", "vet": return true } return false } func init() { CmdTool.Flag.BoolVar(&toolN, "n", false, "") } func runTool(cmd *base.Command, args []string) { if len(args) == 0 { listTools() return } toolName := args[0] // The tool name must be lower-case letters, numbers or underscores. for _, c := range toolName { switch { case 'a' <= c && c <= 'z', '0' <= c && c <= '9', c == '_': default: fmt.Fprintf(os.Stderr, "go tool: bad tool name %q\n", toolName) base.SetExitStatus(2) return } } toolPath := base.Tool(toolName) if toolPath == "" { return } if toolN { cmd := toolPath if len(args) > 1 { cmd += " " + strings.Join(args[1:], " ") } fmt.Printf("%s\n", cmd) return } args[0] = toolPath // in case the tool wants to re-exec itself, e.g. cmd/dist toolCmd := &exec.Cmd{ Path: toolPath, Args: args, Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr, // Set $GOROOT, mainly for go tool dist. Env: base.MergeEnvLists([]string{"GOROOT=" + cfg.GOROOT}, os.Environ()), } err := toolCmd.Run() if err != nil { // Only print about the exit status if the command // didn't even run (not an ExitError) or it didn't exit cleanly // or we're printing command lines too (-x mode). // Assume if command exited cleanly (even with non-zero status) // it printed any messages it wanted to print. if e, ok := err.(*exec.ExitError); !ok || !e.Exited() || cfg.BuildX { fmt.Fprintf(os.Stderr, "go tool %s: %s\n", toolName, err) } base.SetExitStatus(1) return } } // listTools prints a list of the available tools in the tools directory. func listTools() { f, err := os.Open(base.ToolDir) if err != nil { fmt.Fprintf(os.Stderr, "go tool: no tool directory: %s\n", err) base.SetExitStatus(2) return } defer f.Close() names, err := f.Readdirnames(-1) if err != nil { fmt.Fprintf(os.Stderr, "go tool: can't read directory: %s\n", err) base.SetExitStatus(2) return } sort.Strings(names) for _, name := range names { // Unify presentation by going to lower case. name = strings.ToLower(name) // If it's windows, don't show the .exe suffix. if base.ToolIsWindows && strings.HasSuffix(name, base.ToolWindowsExtension) { name = name[:len(name)-len(base.ToolWindowsExtension)] } // The tool directory used by gccgo will have other binaries // in addition to go tools. Only display go tools here. if cfg.BuildToolchainName == "gccgo" && !isGccgoTool(name) { continue } fmt.Println(name) } }
doc
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/doc/doc.go
// Copyright 2015 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 doc implements the ``go doc'' command. package doc import ( "cmd/go/internal/base" "cmd/go/internal/cfg" ) var CmdDoc = &base.Command{ Run: runDoc, UsageLine: "go doc [-u] [-c] [package|[package.]symbol[.methodOrField]]", CustomFlags: true, Short: "show documentation for package or symbol", Long: ` Doc prints the documentation comments associated with the item identified by its arguments (a package, const, func, type, var, method, or struct field) followed by a one-line summary of each of the first-level items "under" that item (package-level declarations for a package, methods for a type, etc.). Doc accepts zero, one, or two arguments. Given no arguments, that is, when run as go doc it prints the package documentation for the package in the current directory. If the package is a command (package main), the exported symbols of the package are elided from the presentation unless the -cmd flag is provided. When run with one argument, the argument is treated as a Go-syntax-like representation of the item to be documented. What the argument selects depends on what is installed in GOROOT and GOPATH, as well as the form of the argument, which is schematically one of these: go doc <pkg> go doc <sym>[.<methodOrField>] go doc [<pkg>.]<sym>[.<methodOrField>] go doc [<pkg>.][<sym>.]<methodOrField> The first item in this list matched by the argument is the one whose documentation is printed. (See the examples below.) However, if the argument starts with a capital letter it is assumed to identify a symbol or method in the current directory. For packages, the order of scanning is determined lexically in breadth-first order. That is, the package presented is the one that matches the search and is nearest the root and lexically first at its level of the hierarchy. The GOROOT tree is always scanned in its entirety before GOPATH. If there is no package specified or matched, the package in the current directory is selected, so "go doc Foo" shows the documentation for symbol Foo in the current package. The package path must be either a qualified path or a proper suffix of a path. The go tool's usual package mechanism does not apply: package path elements like . and ... are not implemented by go doc. When run with two arguments, the first must be a full package path (not just a suffix), and the second is a symbol, or symbol with method or struct field. This is similar to the syntax accepted by godoc: go doc <pkg> <sym>[.<methodOrField>] In all forms, when matching symbols, lower-case letters in the argument match either case but upper-case letters match exactly. This means that there may be multiple matches of a lower-case argument in a package if different symbols have different cases. If this occurs, documentation for all matches is printed. Examples: go doc Show documentation for current package. go doc Foo Show documentation for Foo in the current package. (Foo starts with a capital letter so it cannot match a package path.) go doc encoding/json Show documentation for the encoding/json package. go doc json Shorthand for encoding/json. go doc json.Number (or go doc json.number) Show documentation and method summary for json.Number. go doc json.Number.Int64 (or go doc json.number.int64) Show documentation for json.Number's Int64 method. go doc cmd/doc Show package docs for the doc command. go doc -cmd cmd/doc Show package docs and exported symbols within the doc command. go doc template.new Show documentation for html/template's New function. (html/template is lexically before text/template) go doc text/template.new # One argument Show documentation for text/template's New function. go doc text/template new # Two arguments Show documentation for text/template's New function. At least in the current tree, these invocations all print the documentation for json.Decoder's Decode method: go doc json.Decoder.Decode go doc json.decoder.decode go doc json.decode cd go/src/encoding/json; go doc decode Flags: -c Respect case when matching symbols. -cmd Treat a command (package main) like a regular package. Otherwise package main's exported symbols are hidden when showing the package's top-level documentation. -u Show documentation for unexported as well as exported symbols, methods, and fields. `, } func runDoc(cmd *base.Command, args []string) { base.Run(cfg.BuildToolexec, base.Tool("doc"), args) }
work
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/work/security_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 work import ( "os" "testing" ) var goodCompilerFlags = [][]string{ {"-DFOO"}, {"-Dfoo=bar"}, {"-F/Qt"}, {"-I/"}, {"-I/etc/passwd"}, {"-I."}, {"-O"}, {"-O2"}, {"-Osmall"}, {"-W"}, {"-Wall"}, {"-fobjc-arc"}, {"-fno-objc-arc"}, {"-fomit-frame-pointer"}, {"-fno-omit-frame-pointer"}, {"-fpic"}, {"-fno-pic"}, {"-fPIC"}, {"-fno-PIC"}, {"-fpie"}, {"-fno-pie"}, {"-fPIE"}, {"-fno-PIE"}, {"-fsplit-stack"}, {"-fno-split-stack"}, {"-fstack-xxx"}, {"-fno-stack-xxx"}, {"-fsanitize=hands"}, {"-g"}, {"-ggdb"}, {"-march=souza"}, {"-mcpu=123"}, {"-mfpu=123"}, {"-mtune=happybirthday"}, {"-mstack-overflow"}, {"-mno-stack-overflow"}, {"-mmacosx-version"}, {"-mnop-fun-dllimport"}, {"-pthread"}, {"-std=c99"}, {"-xc"}, {"-D", "FOO"}, {"-D", "foo=bar"}, {"-I", "."}, {"-I", "/etc/passwd"}, {"-I", "世界"}, {"-framework", "Chocolate"}, {"-x", "c"}, {"-v"}, } var badCompilerFlags = [][]string{ {"-D@X"}, {"-D-X"}, {"-F@dir"}, {"-F-dir"}, {"-I@dir"}, {"-I-dir"}, {"-O@1"}, {"-Wa,-foo"}, {"-W@foo"}, {"-g@gdb"}, {"-g-gdb"}, {"-march=@dawn"}, {"-march=-dawn"}, {"-std=@c99"}, {"-std=-c99"}, {"-x@c"}, {"-x-c"}, {"-D", "@foo"}, {"-D", "-foo"}, {"-I", "@foo"}, {"-I", "-foo"}, {"-framework", "-Caffeine"}, {"-framework", "@Home"}, {"-x", "--c"}, {"-x", "@obj"}, } func TestCheckCompilerFlags(t *testing.T) { for _, f := range goodCompilerFlags { if err := checkCompilerFlags("test", "test", f); err != nil { t.Errorf("unexpected error for %q: %v", f, err) } } for _, f := range badCompilerFlags { if err := checkCompilerFlags("test", "test", f); err == nil { t.Errorf("missing error for %q", f) } } } var goodLinkerFlags = [][]string{ {"-Fbar"}, {"-lbar"}, {"-Lbar"}, {"-fpic"}, {"-fno-pic"}, {"-fPIC"}, {"-fno-PIC"}, {"-fpie"}, {"-fno-pie"}, {"-fPIE"}, {"-fno-PIE"}, {"-fsanitize=hands"}, {"-g"}, {"-ggdb"}, {"-march=souza"}, {"-mcpu=123"}, {"-mfpu=123"}, {"-mtune=happybirthday"}, {"-pic"}, {"-pthread"}, {"-Wl,-rpath,foo"}, {"-Wl,-rpath,$ORIGIN/foo"}, {"-Wl,--warn-error"}, {"-Wl,--no-warn-error"}, {"foo.so"}, {"_世界.dll"}, {"./x.o"}, {"libcgosotest.dylib"}, {"-F", "framework"}, {"-l", "."}, {"-l", "/etc/passwd"}, {"-l", "世界"}, {"-L", "framework"}, {"-framework", "Chocolate"}, {"-v"}, {"-Wl,-framework", "-Wl,Chocolate"}, {"-Wl,-framework,Chocolate"}, {"-Wl,-unresolved-symbols=ignore-all"}, } var badLinkerFlags = [][]string{ {"-DFOO"}, {"-Dfoo=bar"}, {"-W"}, {"-Wall"}, {"-fobjc-arc"}, {"-fno-objc-arc"}, {"-fomit-frame-pointer"}, {"-fno-omit-frame-pointer"}, {"-fsplit-stack"}, {"-fno-split-stack"}, {"-fstack-xxx"}, {"-fno-stack-xxx"}, {"-mstack-overflow"}, {"-mno-stack-overflow"}, {"-mnop-fun-dllimport"}, {"-std=c99"}, {"-xc"}, {"-D", "FOO"}, {"-D", "foo=bar"}, {"-I", "FOO"}, {"-L", "@foo"}, {"-L", "-foo"}, {"-x", "c"}, {"-D@X"}, {"-D-X"}, {"-I@dir"}, {"-I-dir"}, {"-O@1"}, {"-Wa,-foo"}, {"-W@foo"}, {"-g@gdb"}, {"-g-gdb"}, {"-march=@dawn"}, {"-march=-dawn"}, {"-std=@c99"}, {"-std=-c99"}, {"-x@c"}, {"-x-c"}, {"-D", "@foo"}, {"-D", "-foo"}, {"-I", "@foo"}, {"-I", "-foo"}, {"-l", "@foo"}, {"-l", "-foo"}, {"-framework", "-Caffeine"}, {"-framework", "@Home"}, {"-Wl,-framework,-Caffeine"}, {"-Wl,-framework", "-Wl,@Home"}, {"-Wl,-framework", "@Home"}, {"-Wl,-framework,Chocolate,@Home"}, {"-x", "--c"}, {"-x", "@obj"}, {"-Wl,-rpath,@foo"}, {"../x.o"}, } func TestCheckLinkerFlags(t *testing.T) { for _, f := range goodLinkerFlags { if err := checkLinkerFlags("test", "test", f); err != nil { t.Errorf("unexpected error for %q: %v", f, err) } } for _, f := range badLinkerFlags { if err := checkLinkerFlags("test", "test", f); err == nil { t.Errorf("missing error for %q", f) } } } func TestCheckFlagAllowDisallow(t *testing.T) { if err := checkCompilerFlags("TEST", "test", []string{"-disallow"}); err == nil { t.Fatalf("missing error for -disallow") } os.Setenv("CGO_TEST_ALLOW", "-disallo") if err := checkCompilerFlags("TEST", "test", []string{"-disallow"}); err == nil { t.Fatalf("missing error for -disallow with CGO_TEST_ALLOW=-disallo") } os.Setenv("CGO_TEST_ALLOW", "-disallow") if err := checkCompilerFlags("TEST", "test", []string{"-disallow"}); err != nil { t.Fatalf("unexpected error for -disallow with CGO_TEST_ALLOW=-disallow: %v", err) } os.Unsetenv("CGO_TEST_ALLOW") if err := checkCompilerFlags("TEST", "test", []string{"-Wall"}); err != nil { t.Fatalf("unexpected error for -Wall: %v", err) } os.Setenv("CGO_TEST_DISALLOW", "-Wall") if err := checkCompilerFlags("TEST", "test", []string{"-Wall"}); err == nil { t.Fatalf("missing error for -Wall with CGO_TEST_DISALLOW=-Wall") } os.Setenv("CGO_TEST_ALLOW", "-Wall") // disallow wins if err := checkCompilerFlags("TEST", "test", []string{"-Wall"}); err == nil { t.Fatalf("missing error for -Wall with CGO_TEST_DISALLOW=-Wall and CGO_TEST_ALLOW=-Wall") } os.Setenv("CGO_TEST_ALLOW", "-fplugin.*") os.Setenv("CGO_TEST_DISALLOW", "-fplugin=lint.so") if err := checkCompilerFlags("TEST", "test", []string{"-fplugin=faster.so"}); err != nil { t.Fatalf("unexpected error for -fplugin=faster.so: %v", err) } if err := checkCompilerFlags("TEST", "test", []string{"-fplugin=lint.so"}); err == nil { t.Fatalf("missing error for -fplugin=lint.so: %v", err) } }
work
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/work/init.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. // Build initialization (after flag parsing). package work import ( "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/load" "flag" "fmt" "os" "path/filepath" "strings" ) func BuildInit() { load.ModInit() instrumentInit() buildModeInit() // Make sure -pkgdir is absolute, because we run commands // in different directories. if cfg.BuildPkgdir != "" && !filepath.IsAbs(cfg.BuildPkgdir) { p, err := filepath.Abs(cfg.BuildPkgdir) if err != nil { fmt.Fprintf(os.Stderr, "go %s: evaluating -pkgdir: %v\n", flag.Args()[0], err) os.Exit(2) } cfg.BuildPkgdir = p } } func instrumentInit() { if !cfg.BuildRace && !cfg.BuildMSan { return } if cfg.BuildRace && cfg.BuildMSan { fmt.Fprintf(os.Stderr, "go %s: may not use -race and -msan simultaneously\n", flag.Args()[0]) os.Exit(2) } if cfg.BuildMSan && (cfg.Goos != "linux" || cfg.Goarch != "amd64" && cfg.Goarch != "arm64") { fmt.Fprintf(os.Stderr, "-msan is not supported on %s/%s\n", cfg.Goos, cfg.Goarch) os.Exit(2) } if cfg.BuildRace { platform := cfg.Goos + "/" + cfg.Goarch switch platform { default: fmt.Fprintf(os.Stderr, "go %s: -race is only supported on linux/amd64, linux/ppc64le, freebsd/amd64, netbsd/amd64, darwin/amd64 and windows/amd64\n", flag.Args()[0]) os.Exit(2) case "linux/amd64", "linux/ppc64le", "freebsd/amd64", "netbsd/amd64", "darwin/amd64", "windows/amd64": // race supported on these platforms } } mode := "race" if cfg.BuildMSan { mode = "msan" } modeFlag := "-" + mode if !cfg.BuildContext.CgoEnabled { fmt.Fprintf(os.Stderr, "go %s: %s requires cgo; enable cgo by setting CGO_ENABLED=1\n", flag.Args()[0], modeFlag) os.Exit(2) } forcedGcflags = append(forcedGcflags, modeFlag) forcedLdflags = append(forcedLdflags, modeFlag) if cfg.BuildContext.InstallSuffix != "" { cfg.BuildContext.InstallSuffix += "_" } cfg.BuildContext.InstallSuffix += mode cfg.BuildContext.BuildTags = append(cfg.BuildContext.BuildTags, mode) } func buildModeInit() { gccgo := cfg.BuildToolchainName == "gccgo" var codegenArg string platform := cfg.Goos + "/" + cfg.Goarch switch cfg.BuildBuildmode { case "archive": pkgsFilter = pkgsNotMain case "c-archive": pkgsFilter = oneMainPkg switch platform { case "darwin/arm", "darwin/arm64": codegenArg = "-shared" default: switch cfg.Goos { case "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "solaris": if platform == "linux/ppc64" { base.Fatalf("-buildmode=c-archive not supported on %s\n", platform) } // Use -shared so that the result is // suitable for inclusion in a PIE or // shared library. codegenArg = "-shared" } } cfg.ExeSuffix = ".a" ldBuildmode = "c-archive" case "c-shared": pkgsFilter = oneMainPkg if gccgo { codegenArg = "-fPIC" } else { switch platform { case "linux/amd64", "linux/arm", "linux/arm64", "linux/386", "linux/ppc64le", "linux/s390x", "android/amd64", "android/arm", "android/arm64", "android/386", "freebsd/amd64": codegenArg = "-shared" case "darwin/amd64", "darwin/386": case "windows/amd64", "windows/386": // Do not add usual .exe suffix to the .dll file. cfg.ExeSuffix = "" default: base.Fatalf("-buildmode=c-shared not supported on %s\n", platform) } } ldBuildmode = "c-shared" case "default": switch platform { case "android/arm", "android/arm64", "android/amd64", "android/386": codegenArg = "-shared" ldBuildmode = "pie" case "darwin/arm", "darwin/arm64": codegenArg = "-shared" fallthrough default: ldBuildmode = "exe" } case "exe": pkgsFilter = pkgsMain ldBuildmode = "exe" // Set the pkgsFilter to oneMainPkg if the user passed a specific binary output // and is using buildmode=exe for a better error message. // See issue #20017. if cfg.BuildO != "" { pkgsFilter = oneMainPkg } case "pie": if cfg.BuildRace { base.Fatalf("-buildmode=pie not supported when -race is enabled") } if gccgo { base.Fatalf("-buildmode=pie not supported by gccgo") } else { switch platform { case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x", "android/amd64", "android/arm", "android/arm64", "android/386", "freebsd/amd64": codegenArg = "-shared" case "darwin/amd64": codegenArg = "-shared" default: base.Fatalf("-buildmode=pie not supported on %s\n", platform) } } ldBuildmode = "pie" case "shared": pkgsFilter = pkgsNotMain if gccgo { codegenArg = "-fPIC" } else { switch platform { case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x": default: base.Fatalf("-buildmode=shared not supported on %s\n", platform) } codegenArg = "-dynlink" } if cfg.BuildO != "" { base.Fatalf("-buildmode=shared and -o not supported together") } ldBuildmode = "shared" case "plugin": pkgsFilter = oneMainPkg if gccgo { codegenArg = "-fPIC" } else { switch platform { case "linux/amd64", "linux/arm", "linux/arm64", "linux/386", "linux/s390x", "linux/ppc64le", "android/amd64", "android/arm", "android/arm64", "android/386": case "darwin/amd64": // Skip DWARF generation due to #21647 forcedLdflags = append(forcedLdflags, "-w") default: base.Fatalf("-buildmode=plugin not supported on %s\n", platform) } codegenArg = "-dynlink" } cfg.ExeSuffix = ".so" ldBuildmode = "plugin" default: base.Fatalf("buildmode=%s not supported", cfg.BuildBuildmode) } if cfg.BuildLinkshared { if gccgo { codegenArg = "-fPIC" } else { switch platform { case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x": forcedAsmflags = append(forcedAsmflags, "-D=GOBUILDMODE_shared=1") default: base.Fatalf("-linkshared not supported on %s\n", platform) } codegenArg = "-dynlink" // TODO(mwhudson): remove -w when that gets fixed in linker. forcedLdflags = append(forcedLdflags, "-linkshared", "-w") } } if codegenArg != "" { if gccgo { forcedGccgoflags = append([]string{codegenArg}, forcedGccgoflags...) } else { forcedAsmflags = append([]string{codegenArg}, forcedAsmflags...) forcedGcflags = append([]string{codegenArg}, forcedGcflags...) } // Don't alter InstallSuffix when modifying default codegen args. if cfg.BuildBuildmode != "default" || cfg.BuildLinkshared { if cfg.BuildContext.InstallSuffix != "" { cfg.BuildContext.InstallSuffix += "_" } cfg.BuildContext.InstallSuffix += codegenArg[1:] } } switch cfg.BuildMod { case "": // ok case "readonly", "vendor": if load.ModLookup == nil && !inGOFLAGS("-mod") { base.Fatalf("build flag -mod=%s only valid when using modules", cfg.BuildMod) } default: base.Fatalf("-mod=%s not supported (can be '', 'readonly', or 'vendor')", cfg.BuildMod) } } func inGOFLAGS(flag string) bool { for _, goflag := range base.GOFLAGS() { name := goflag if strings.HasPrefix(name, "--") { name = name[1:] } if i := strings.Index(name, "="); i >= 0 { name = name[:i] } if name == flag { return true } } return false }
work
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/work/security.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. // Checking of compiler and linker flags. // We must avoid flags like -fplugin=, which can allow // arbitrary code execution during the build. // Do not make changes here without carefully // considering the implications. // (That's why the code is isolated in a file named security.go.) // // Note that -Wl,foo means split foo on commas and pass to // the linker, so that -Wl,-foo,bar means pass -foo bar to // the linker. Similarly -Wa,foo for the assembler and so on. // If any of these are permitted, the wildcard portion must // disallow commas. // // Note also that GNU binutils accept any argument @foo // as meaning "read more flags from the file foo", so we must // guard against any command-line argument beginning with @, // even things like "-I @foo". // We use load.SafeArg (which is even more conservative) // to reject these. // // Even worse, gcc -I@foo (one arg) turns into cc1 -I @foo (two args), // so although gcc doesn't expand the @foo, cc1 will. // So out of paranoia, we reject @ at the beginning of every // flag argument that might be split into its own argument. package work import ( "cmd/go/internal/load" "fmt" "os" "regexp" "strings" ) var re = regexp.MustCompile var validCompilerFlags = []*regexp.Regexp{ re(`-D([A-Za-z_].*)`), re(`-F([^@\-].*)`), re(`-I([^@\-].*)`), re(`-O`), re(`-O([^@\-].*)`), re(`-W`), re(`-W([^@,]+)`), // -Wall but not -Wa,-foo. re(`-Wa,-mbig-obj`), re(`-Wp,-D([A-Za-z_].*)`), re(`-ansi`), re(`-f(no-)?asynchronous-unwind-tables`), re(`-f(no-)?blocks`), re(`-f(no-)builtin-[a-zA-Z0-9_]*`), re(`-f(no-)?common`), re(`-f(no-)?constant-cfstrings`), re(`-fdiagnostics-show-note-include-stack`), re(`-f(no-)?eliminate-unused-debug-types`), re(`-f(no-)?exceptions`), re(`-f(no-)?fast-math`), re(`-f(no-)?inline-functions`), re(`-finput-charset=([^@\-].*)`), re(`-f(no-)?fat-lto-objects`), re(`-f(no-)?keep-inline-dllexport`), re(`-f(no-)?lto`), re(`-fmacro-backtrace-limit=(.+)`), re(`-fmessage-length=(.+)`), re(`-f(no-)?modules`), re(`-f(no-)?objc-arc`), re(`-f(no-)?objc-nonfragile-abi`), re(`-f(no-)?objc-legacy-dispatch`), re(`-f(no-)?omit-frame-pointer`), re(`-f(no-)?openmp(-simd)?`), re(`-f(no-)?permissive`), re(`-f(no-)?(pic|PIC|pie|PIE)`), re(`-f(no-)?plt`), re(`-f(no-)?rtti`), re(`-f(no-)?split-stack`), re(`-f(no-)?stack-(.+)`), re(`-f(no-)?strict-aliasing`), re(`-f(un)signed-char`), re(`-f(no-)?use-linker-plugin`), // safe if -B is not used; we don't permit -B re(`-f(no-)?visibility-inlines-hidden`), re(`-fsanitize=(.+)`), re(`-ftemplate-depth-(.+)`), re(`-fvisibility=(.+)`), re(`-g([^@\-].*)?`), re(`-m32`), re(`-m64`), re(`-m(abi|arch|cpu|fpu|tune)=([^@\-].*)`), re(`-marm`), re(`-mfloat-abi=([^@\-].*)`), re(`-mfpmath=[0-9a-z,+]*`), re(`-m(no-)?avx[0-9a-z.]*`), re(`-m(no-)?ms-bitfields`), re(`-m(no-)?stack-(.+)`), re(`-mmacosx-(.+)`), re(`-mios-simulator-version-min=(.+)`), re(`-miphoneos-version-min=(.+)`), re(`-mnop-fun-dllimport`), re(`-m(no-)?sse[0-9.]*`), re(`-mthumb(-interwork)?`), re(`-mthreads`), re(`-mwindows`), re(`--param=ssp-buffer-size=[0-9]*`), re(`-pedantic(-errors)?`), re(`-pipe`), re(`-pthread`), re(`-?-std=([^@\-].*)`), re(`-?-stdlib=([^@\-].*)`), re(`--sysroot=([^@\-].*)`), re(`-w`), re(`-x([^@\-].*)`), re(`-v`), } var validCompilerFlagsWithNextArg = []string{ "-arch", "-D", "-I", "-framework", "-isysroot", "-isystem", "--sysroot", "-target", "-x", } var validLinkerFlags = []*regexp.Regexp{ re(`-F([^@\-].*)`), re(`-l([^@\-].*)`), re(`-L([^@\-].*)`), re(`-O`), re(`-O([^@\-].*)`), re(`-f(no-)?(pic|PIC|pie|PIE)`), re(`-f(no-)?openmp(-simd)?`), re(`-fsanitize=([^@\-].*)`), re(`-flat_namespace`), re(`-g([^@\-].*)?`), re(`-headerpad_max_install_names`), re(`-m(abi|arch|cpu|fpu|tune)=([^@\-].*)`), re(`-mfloat-abi=([^@\-].*)`), re(`-mmacosx-(.+)`), re(`-mios-simulator-version-min=(.+)`), re(`-miphoneos-version-min=(.+)`), re(`-mthreads`), re(`-mwindows`), re(`-(pic|PIC|pie|PIE)`), re(`-pthread`), re(`-rdynamic`), re(`-shared`), re(`-?-static([-a-z0-9+]*)`), re(`-?-stdlib=([^@\-].*)`), re(`-v`), // Note that any wildcards in -Wl need to exclude comma, // since -Wl splits its argument at commas and passes // them all to the linker uninterpreted. Allowing comma // in a wildcard would allow tunnelling arbitrary additional // linker arguments through one of these. re(`-Wl,--(no-)?allow-multiple-definition`), re(`-Wl,--(no-)?allow-shlib-undefined`), re(`-Wl,--(no-)?as-needed`), re(`-Wl,-Bdynamic`), re(`-Wl,-Bstatic`), re(`-WL,-O([^@,\-][^,]*)?`), re(`-Wl,-d[ny]`), re(`-Wl,--disable-new-dtags`), re(`-Wl,-e[=,][a-zA-Z0-9]*`), re(`-Wl,--enable-new-dtags`), re(`-Wl,--end-group`), re(`-Wl,-framework,[^,@\-][^,]+`), re(`-Wl,-headerpad_max_install_names`), re(`-Wl,--no-undefined`), re(`-Wl,-rpath(-link)?[=,]([^,@\-][^,]+)`), re(`-Wl,-s`), re(`-Wl,-search_paths_first`), re(`-Wl,-sectcreate,([^,@\-][^,]+),([^,@\-][^,]+),([^,@\-][^,]+)`), re(`-Wl,--start-group`), re(`-Wl,-?-static`), re(`-Wl,-?-subsystem,(native|windows|console|posix|xbox)`), re(`-Wl,-syslibroot[=,]([^,@\-][^,]+)`), re(`-Wl,-undefined[=,]([^,@\-][^,]+)`), re(`-Wl,-?-unresolved-symbols=[^,]+`), re(`-Wl,--(no-)?warn-([^,]+)`), re(`-Wl,-z,(no)?execstack`), re(`-Wl,-z,relro`), re(`[a-zA-Z0-9_/].*\.(a|o|obj|dll|dylib|so)`), // direct linker inputs: x.o or libfoo.so (but not -foo.o or @foo.o) re(`\./.*\.(a|o|obj|dll|dylib|so)`), } var validLinkerFlagsWithNextArg = []string{ "-arch", "-F", "-l", "-L", "-framework", "-isysroot", "--sysroot", "-target", "-Wl,-framework", "-Wl,-rpath", "-Wl,-undefined", } func checkCompilerFlags(name, source string, list []string) error { return checkFlags(name, source, list, validCompilerFlags, validCompilerFlagsWithNextArg) } func checkLinkerFlags(name, source string, list []string) error { return checkFlags(name, source, list, validLinkerFlags, validLinkerFlagsWithNextArg) } func checkFlags(name, source string, list []string, valid []*regexp.Regexp, validNext []string) error { // Let users override rules with $CGO_CFLAGS_ALLOW, $CGO_CFLAGS_DISALLOW, etc. var ( allow *regexp.Regexp disallow *regexp.Regexp ) if env := os.Getenv("CGO_" + name + "_ALLOW"); env != "" { r, err := regexp.Compile(env) if err != nil { return fmt.Errorf("parsing $CGO_%s_ALLOW: %v", name, err) } allow = r } if env := os.Getenv("CGO_" + name + "_DISALLOW"); env != "" { r, err := regexp.Compile(env) if err != nil { return fmt.Errorf("parsing $CGO_%s_DISALLOW: %v", name, err) } disallow = r } Args: for i := 0; i < len(list); i++ { arg := list[i] if disallow != nil && disallow.FindString(arg) == arg { goto Bad } if allow != nil && allow.FindString(arg) == arg { continue Args } for _, re := range valid { if re.FindString(arg) == arg { // must be complete match continue Args } } for _, x := range validNext { if arg == x { if i+1 < len(list) && load.SafeArg(list[i+1]) { i++ continue Args } // Permit -Wl,-framework -Wl,name. if i+1 < len(list) && strings.HasPrefix(arg, "-Wl,") && strings.HasPrefix(list[i+1], "-Wl,") && load.SafeArg(list[i+1][4:]) && !strings.Contains(list[i+1][4:], ",") { i++ continue Args } if i+1 < len(list) { return fmt.Errorf("invalid flag in %s: %s %s (see https://golang.org/s/invalidflag)", source, arg, list[i+1]) } return fmt.Errorf("invalid flag in %s: %s without argument (see https://golang.org/s/invalidflag)", source, arg) } } Bad: return fmt.Errorf("invalid flag in %s: %s", source, arg) } return nil }
work
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/work/gc.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 work import ( "bufio" "bytes" "fmt" "io" "io/ioutil" "log" "os" "path/filepath" "runtime" "strings" "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/load" "cmd/go/internal/str" "crypto/sha1" ) // The Go toolchain. type gcToolchain struct{} func (gcToolchain) compiler() string { return base.Tool("compile") } func (gcToolchain) linker() string { return base.Tool("link") } func (gcToolchain) gc(b *Builder, a *Action, archive string, importcfg []byte, asmhdr bool, gofiles []string) (ofile string, output []byte, err error) { p := a.Package objdir := a.Objdir if archive != "" { ofile = archive } else { out := "_go_.o" ofile = objdir + out } pkgpath := p.ImportPath if cfg.BuildBuildmode == "plugin" { pkgpath = pluginPath(a) } else if p.Name == "main" && !p.Internal.ForceLibrary { pkgpath = "main" } gcargs := []string{"-p", pkgpath} if p.Standard { gcargs = append(gcargs, "-std") } compilingRuntime := p.Standard && (p.ImportPath == "runtime" || strings.HasPrefix(p.ImportPath, "runtime/internal")) // The runtime package imports a couple of general internal packages. if p.Standard && (p.ImportPath == "internal/cpu" || p.ImportPath == "internal/bytealg") { compilingRuntime = true } if compilingRuntime { // runtime compiles with a special gc flag to check for // memory allocations that are invalid in the runtime package, // and to implement some special compiler pragmas. gcargs = append(gcargs, "-+") } // If we're giving the compiler the entire package (no C etc files), tell it that, // so that it can give good error messages about forward declarations. // Exceptions: a few standard packages have forward declarations for // pieces supplied behind-the-scenes by package runtime. extFiles := len(p.CgoFiles) + len(p.CFiles) + len(p.CXXFiles) + len(p.MFiles) + len(p.FFiles) + len(p.SFiles) + len(p.SysoFiles) + len(p.SwigFiles) + len(p.SwigCXXFiles) if p.Standard { switch p.ImportPath { case "bytes", "internal/poll", "net", "os", "runtime/pprof", "runtime/trace", "sync", "syscall", "time": extFiles++ } } if extFiles == 0 { gcargs = append(gcargs, "-complete") } if cfg.BuildContext.InstallSuffix != "" { gcargs = append(gcargs, "-installsuffix", cfg.BuildContext.InstallSuffix) } if a.buildID != "" { gcargs = append(gcargs, "-buildid", a.buildID) } platform := cfg.Goos + "/" + cfg.Goarch if p.Internal.OmitDebug || platform == "nacl/amd64p32" || cfg.Goos == "plan9" || cfg.Goarch == "wasm" { gcargs = append(gcargs, "-dwarf=false") } if strings.HasPrefix(runtimeVersion, "go1") && !strings.Contains(os.Args[0], "go_bootstrap") { gcargs = append(gcargs, "-goversion", runtimeVersion) } gcflags := str.StringList(forcedGcflags, p.Internal.Gcflags) if compilingRuntime { // Remove -N, if present. // It is not possible to build the runtime with no optimizations, // because the compiler cannot eliminate enough write barriers. for i := 0; i < len(gcflags); i++ { if gcflags[i] == "-N" { copy(gcflags[i:], gcflags[i+1:]) gcflags = gcflags[:len(gcflags)-1] i-- } } } args := []interface{}{cfg.BuildToolexec, base.Tool("compile"), "-o", ofile, "-trimpath", trimDir(a.Objdir), gcflags, gcargs, "-D", p.Internal.LocalPrefix} if importcfg != nil { if err := b.writeFile(objdir+"importcfg", importcfg); err != nil { return "", nil, err } args = append(args, "-importcfg", objdir+"importcfg") } if ofile == archive { args = append(args, "-pack") } if asmhdr { args = append(args, "-asmhdr", objdir+"go_asm.h") } // Add -c=N to use concurrent backend compilation, if possible. if c := gcBackendConcurrency(gcflags); c > 1 { args = append(args, fmt.Sprintf("-c=%d", c)) } for _, f := range gofiles { args = append(args, mkAbs(p.Dir, f)) } output, err = b.runOut(p.Dir, nil, args...) return ofile, output, err } // gcBackendConcurrency returns the backend compiler concurrency level for a package compilation. func gcBackendConcurrency(gcflags []string) int { // First, check whether we can use -c at all for this compilation. canDashC := concurrentGCBackendCompilationEnabledByDefault switch e := os.Getenv("GO19CONCURRENTCOMPILATION"); e { case "0": canDashC = false case "1": canDashC = true case "": // Not set. Use default. default: log.Fatalf("GO19CONCURRENTCOMPILATION must be 0, 1, or unset, got %q", e) } CheckFlags: for _, flag := range gcflags { // Concurrent compilation is presumed incompatible with any gcflags, // except for a small whitelist of commonly used flags. // If the user knows better, they can manually add their own -c to the gcflags. switch flag { case "-N", "-l", "-S", "-B", "-C", "-I": // OK default: canDashC = false break CheckFlags } } if !canDashC { return 1 } // Decide how many concurrent backend compilations to allow. // // If we allow too many, in theory we might end up with p concurrent processes, // each with c concurrent backend compiles, all fighting over the same resources. // However, in practice, that seems not to happen too much. // Most build graphs are surprisingly serial, so p==1 for much of the build. // Furthermore, concurrent backend compilation is only enabled for a part // of the overall compiler execution, so c==1 for much of the build. // So don't worry too much about that interaction for now. // // However, in practice, setting c above 4 tends not to help very much. // See the analysis in CL 41192. // // TODO(josharian): attempt to detect whether this particular compilation // is likely to be a bottleneck, e.g. when: // - it has no successor packages to compile (usually package main) // - all paths through the build graph pass through it // - critical path scheduling says it is high priority // and in such a case, set c to runtime.NumCPU. // We do this now when p==1. if cfg.BuildP == 1 { // No process parallelism. Max out c. return runtime.NumCPU() } // Some process parallelism. Set c to min(4, numcpu). c := 4 if ncpu := runtime.NumCPU(); ncpu < c { c = ncpu } return c } func trimDir(dir string) string { if len(dir) > 1 && dir[len(dir)-1] == filepath.Separator { dir = dir[:len(dir)-1] } return dir } func (gcToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error) { p := a.Package // Add -I pkg/GOOS_GOARCH so #include "textflag.h" works in .s files. inc := filepath.Join(cfg.GOROOT, "pkg", "include") args := []interface{}{cfg.BuildToolexec, base.Tool("asm"), "-trimpath", trimDir(a.Objdir), "-I", a.Objdir, "-I", inc, "-D", "GOOS_" + cfg.Goos, "-D", "GOARCH_" + cfg.Goarch, forcedAsmflags, p.Internal.Asmflags} if p.ImportPath == "runtime" && cfg.Goarch == "386" { for _, arg := range forcedAsmflags { if arg == "-dynlink" { args = append(args, "-D=GOBUILDMODE_shared=1") } } } if cfg.Goarch == "mips" || cfg.Goarch == "mipsle" { // Define GOMIPS_value from cfg.GOMIPS. args = append(args, "-D", "GOMIPS_"+cfg.GOMIPS) } if cfg.Goarch == "mips64" || cfg.Goarch == "mips64le" { // Define GOMIPS64_value from cfg.GOMIPS64. args = append(args, "-D", "GOMIPS64_"+cfg.GOMIPS64) } var ofiles []string for _, sfile := range sfiles { ofile := a.Objdir + sfile[:len(sfile)-len(".s")] + ".o" ofiles = append(ofiles, ofile) args1 := append(args, "-o", ofile, mkAbs(p.Dir, sfile)) if err := b.run(a, p.Dir, p.ImportPath, nil, args1...); err != nil { return nil, err } } return ofiles, nil } // toolVerify checks that the command line args writes the same output file // if run using newTool instead. // Unused now but kept around for future use. func toolVerify(a *Action, b *Builder, p *load.Package, newTool string, ofile string, args []interface{}) error { newArgs := make([]interface{}, len(args)) copy(newArgs, args) newArgs[1] = base.Tool(newTool) newArgs[3] = ofile + ".new" // x.6 becomes x.6.new if err := b.run(a, p.Dir, p.ImportPath, nil, newArgs...); err != nil { return err } data1, err := ioutil.ReadFile(ofile) if err != nil { return err } data2, err := ioutil.ReadFile(ofile + ".new") if err != nil { return err } if !bytes.Equal(data1, data2) { return fmt.Errorf("%s and %s produced different output files:\n%s\n%s", filepath.Base(args[1].(string)), newTool, strings.Join(str.StringList(args...), " "), strings.Join(str.StringList(newArgs...), " ")) } os.Remove(ofile + ".new") return nil } func (gcToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error { var absOfiles []string for _, f := range ofiles { absOfiles = append(absOfiles, mkAbs(a.Objdir, f)) } absAfile := mkAbs(a.Objdir, afile) // The archive file should have been created by the compiler. // Since it used to not work that way, verify. if !cfg.BuildN { if _, err := os.Stat(absAfile); err != nil { base.Fatalf("os.Stat of archive file failed: %v", err) } } p := a.Package if cfg.BuildN || cfg.BuildX { cmdline := str.StringList(base.Tool("pack"), "r", absAfile, absOfiles) b.Showcmd(p.Dir, "%s # internal", joinUnambiguously(cmdline)) } if cfg.BuildN { return nil } if err := packInternal(absAfile, absOfiles); err != nil { b.showOutput(a, p.Dir, p.Desc(), err.Error()+"\n") return errPrintedOutput } return nil } func packInternal(afile string, ofiles []string) error { dst, err := os.OpenFile(afile, os.O_WRONLY|os.O_APPEND, 0) if err != nil { return err } defer dst.Close() // only for error returns or panics w := bufio.NewWriter(dst) for _, ofile := range ofiles { src, err := os.Open(ofile) if err != nil { return err } fi, err := src.Stat() if err != nil { src.Close() return err } // Note: Not using %-16.16s format because we care // about bytes, not runes. name := fi.Name() if len(name) > 16 { name = name[:16] } else { name += strings.Repeat(" ", 16-len(name)) } size := fi.Size() fmt.Fprintf(w, "%s%-12d%-6d%-6d%-8o%-10d`\n", name, 0, 0, 0, 0644, size) n, err := io.Copy(w, src) src.Close() if err == nil && n < size { err = io.ErrUnexpectedEOF } else if err == nil && n > size { err = fmt.Errorf("file larger than size reported by stat") } if err != nil { return fmt.Errorf("copying %s to %s: %v", ofile, afile, err) } if size&1 != 0 { w.WriteByte(0) } } if err := w.Flush(); err != nil { return err } return dst.Close() } // setextld sets the appropriate linker flags for the specified compiler. func setextld(ldflags []string, compiler []string) []string { for _, f := range ldflags { if f == "-extld" || strings.HasPrefix(f, "-extld=") { // don't override -extld if supplied return ldflags } } ldflags = append(ldflags, "-extld="+compiler[0]) if len(compiler) > 1 { extldflags := false add := strings.Join(compiler[1:], " ") for i, f := range ldflags { if f == "-extldflags" && i+1 < len(ldflags) { ldflags[i+1] = add + " " + ldflags[i+1] extldflags = true break } else if strings.HasPrefix(f, "-extldflags=") { ldflags[i] = "-extldflags=" + add + " " + ldflags[i][len("-extldflags="):] extldflags = true break } } if !extldflags { ldflags = append(ldflags, "-extldflags="+add) } } return ldflags } // pluginPath computes the package path for a plugin main package. // // This is typically the import path of the main package p, unless the // plugin is being built directly from source files. In that case we // combine the package build ID with the contents of the main package // source files. This allows us to identify two different plugins // built from two source files with the same name. func pluginPath(a *Action) string { p := a.Package if p.ImportPath != "command-line-arguments" { return p.ImportPath } h := sha1.New() fmt.Fprintf(h, "build ID: %s\n", a.buildID) for _, file := range str.StringList(p.GoFiles, p.CgoFiles, p.SFiles) { data, err := ioutil.ReadFile(filepath.Join(p.Dir, file)) if err != nil { base.Fatalf("go: %s", err) } h.Write(data) } return fmt.Sprintf("plugin/unnamed-%x", h.Sum(nil)) } func (gcToolchain) ld(b *Builder, root *Action, out, importcfg, mainpkg string) error { cxx := len(root.Package.CXXFiles) > 0 || len(root.Package.SwigCXXFiles) > 0 for _, a := range root.Deps { if a.Package != nil && (len(a.Package.CXXFiles) > 0 || len(a.Package.SwigCXXFiles) > 0) { cxx = true } } var ldflags []string if cfg.BuildContext.InstallSuffix != "" { ldflags = append(ldflags, "-installsuffix", cfg.BuildContext.InstallSuffix) } if root.Package.Internal.OmitDebug { ldflags = append(ldflags, "-s", "-w") } if cfg.BuildBuildmode == "plugin" { ldflags = append(ldflags, "-pluginpath", pluginPath(root)) } // Store BuildID inside toolchain binaries as a unique identifier of the // tool being run, for use by content-based staleness determination. if root.Package.Goroot && strings.HasPrefix(root.Package.ImportPath, "cmd/") { ldflags = append(ldflags, "-X=cmd/internal/objabi.buildID="+root.buildID) } // If the user has not specified the -extld option, then specify the // appropriate linker. In case of C++ code, use the compiler named // by the CXX environment variable or defaultCXX if CXX is not set. // Else, use the CC environment variable and defaultCC as fallback. var compiler []string if cxx { compiler = envList("CXX", cfg.DefaultCXX(cfg.Goos, cfg.Goarch)) } else { compiler = envList("CC", cfg.DefaultCC(cfg.Goos, cfg.Goarch)) } ldflags = append(ldflags, "-buildmode="+ldBuildmode) if root.buildID != "" { ldflags = append(ldflags, "-buildid="+root.buildID) } ldflags = append(ldflags, forcedLdflags...) ldflags = append(ldflags, root.Package.Internal.Ldflags...) ldflags = setextld(ldflags, compiler) // On OS X when using external linking to build a shared library, // the argument passed here to -o ends up recorded in the final // shared library in the LC_ID_DYLIB load command. // To avoid putting the temporary output directory name there // (and making the resulting shared library useless), // run the link in the output directory so that -o can name // just the final path element. // On Windows, DLL file name is recorded in PE file // export section, so do like on OS X. dir := "." if (cfg.Goos == "darwin" || cfg.Goos == "windows") && cfg.BuildBuildmode == "c-shared" { dir, out = filepath.Split(out) } return b.run(root, dir, root.Package.ImportPath, nil, cfg.BuildToolexec, base.Tool("link"), "-o", out, "-importcfg", importcfg, ldflags, mainpkg) } func (gcToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, out, importcfg string, allactions []*Action) error { ldflags := []string{"-installsuffix", cfg.BuildContext.InstallSuffix} ldflags = append(ldflags, "-buildmode=shared") ldflags = append(ldflags, forcedLdflags...) ldflags = append(ldflags, root.Package.Internal.Ldflags...) cxx := false for _, a := range allactions { if a.Package != nil && (len(a.Package.CXXFiles) > 0 || len(a.Package.SwigCXXFiles) > 0) { cxx = true } } // If the user has not specified the -extld option, then specify the // appropriate linker. In case of C++ code, use the compiler named // by the CXX environment variable or defaultCXX if CXX is not set. // Else, use the CC environment variable and defaultCC as fallback. var compiler []string if cxx { compiler = envList("CXX", cfg.DefaultCXX(cfg.Goos, cfg.Goarch)) } else { compiler = envList("CC", cfg.DefaultCC(cfg.Goos, cfg.Goarch)) } ldflags = setextld(ldflags, compiler) for _, d := range toplevelactions { if !strings.HasSuffix(d.Target, ".a") { // omit unsafe etc and actions for other shared libraries continue } ldflags = append(ldflags, d.Package.ImportPath+"="+d.Target) } return b.run(root, ".", out, nil, cfg.BuildToolexec, base.Tool("link"), "-o", out, "-importcfg", importcfg, ldflags) } func (gcToolchain) cc(b *Builder, a *Action, ofile, cfile string) error { return fmt.Errorf("%s: C source files not supported without cgo", mkAbs(a.Package.Dir, cfile)) }
work
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/work/gccgo.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 work import ( "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "strings" "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/load" "cmd/go/internal/str" ) // The Gccgo toolchain. type gccgoToolchain struct{} var GccgoName, GccgoBin string var gccgoErr error func init() { GccgoName = os.Getenv("GCCGO") if GccgoName == "" { GccgoName = "gccgo" } GccgoBin, gccgoErr = exec.LookPath(GccgoName) } func (gccgoToolchain) compiler() string { checkGccgoBin() return GccgoBin } func (gccgoToolchain) linker() string { checkGccgoBin() return GccgoBin } func checkGccgoBin() { if gccgoErr == nil { return } fmt.Fprintf(os.Stderr, "cmd/go: gccgo: %s\n", gccgoErr) os.Exit(2) } func (tools gccgoToolchain) gc(b *Builder, a *Action, archive string, importcfg []byte, asmhdr bool, gofiles []string) (ofile string, output []byte, err error) { p := a.Package objdir := a.Objdir out := "_go_.o" ofile = objdir + out gcargs := []string{"-g"} gcargs = append(gcargs, b.gccArchArgs()...) if pkgpath := gccgoPkgpath(p); pkgpath != "" { gcargs = append(gcargs, "-fgo-pkgpath="+pkgpath) } if p.Internal.LocalPrefix != "" { gcargs = append(gcargs, "-fgo-relative-import-path="+p.Internal.LocalPrefix) } args := str.StringList(tools.compiler(), "-c", gcargs, "-o", ofile, forcedGccgoflags) if importcfg != nil { if b.gccSupportsFlag(args[:1], "-fgo-importcfg=/dev/null") { if err := b.writeFile(objdir+"importcfg", importcfg); err != nil { return "", nil, err } args = append(args, "-fgo-importcfg="+objdir+"importcfg") } else { root := objdir + "_importcfgroot_" if err := buildImportcfgSymlinks(b, root, importcfg); err != nil { return "", nil, err } args = append(args, "-I", root) } } args = append(args, a.Package.Internal.Gccgoflags...) for _, f := range gofiles { args = append(args, mkAbs(p.Dir, f)) } output, err = b.runOut(p.Dir, nil, args) return ofile, output, err } // buildImportcfgSymlinks builds in root a tree of symlinks // implementing the directives from importcfg. // This serves as a temporary transition mechanism until // we can depend on gccgo reading an importcfg directly. // (The Go 1.9 and later gc compilers already do.) func buildImportcfgSymlinks(b *Builder, root string, importcfg []byte) error { for lineNum, line := range strings.Split(string(importcfg), "\n") { lineNum++ // 1-based line = strings.TrimSpace(line) if line == "" { continue } if line == "" || strings.HasPrefix(line, "#") { continue } var verb, args string if i := strings.Index(line, " "); i < 0 { verb = line } else { verb, args = line[:i], strings.TrimSpace(line[i+1:]) } var before, after string if i := strings.Index(args, "="); i >= 0 { before, after = args[:i], args[i+1:] } switch verb { default: base.Fatalf("importcfg:%d: unknown directive %q", lineNum, verb) case "packagefile": if before == "" || after == "" { return fmt.Errorf(`importcfg:%d: invalid packagefile: syntax is "packagefile path=filename": %s`, lineNum, line) } archive := gccgoArchive(root, before) if err := b.Mkdir(filepath.Dir(archive)); err != nil { return err } if err := b.Symlink(after, archive); err != nil { return err } case "importmap": if before == "" || after == "" { return fmt.Errorf(`importcfg:%d: invalid importmap: syntax is "importmap old=new": %s`, lineNum, line) } beforeA := gccgoArchive(root, before) afterA := gccgoArchive(root, after) if err := b.Mkdir(filepath.Dir(beforeA)); err != nil { return err } if err := b.Mkdir(filepath.Dir(afterA)); err != nil { return err } if err := b.Symlink(afterA, beforeA); err != nil { return err } case "packageshlib": return fmt.Errorf("gccgo -importcfg does not support shared libraries") } } return nil } func (tools gccgoToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error) { p := a.Package var ofiles []string for _, sfile := range sfiles { base := filepath.Base(sfile) ofile := a.Objdir + base[:len(base)-len(".s")] + ".o" ofiles = append(ofiles, ofile) sfile = mkAbs(p.Dir, sfile) defs := []string{"-D", "GOOS_" + cfg.Goos, "-D", "GOARCH_" + cfg.Goarch} if pkgpath := gccgoCleanPkgpath(p); pkgpath != "" { defs = append(defs, `-D`, `GOPKGPATH=`+pkgpath) } defs = tools.maybePIC(defs) defs = append(defs, b.gccArchArgs()...) err := b.run(a, p.Dir, p.ImportPath, nil, tools.compiler(), "-xassembler-with-cpp", "-I", a.Objdir, "-c", "-o", ofile, defs, sfile) if err != nil { return nil, err } } return ofiles, nil } func gccgoArchive(basedir, imp string) string { end := filepath.FromSlash(imp + ".a") afile := filepath.Join(basedir, end) // add "lib" to the final element return filepath.Join(filepath.Dir(afile), "lib"+filepath.Base(afile)) } func (gccgoToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error { p := a.Package objdir := a.Objdir var absOfiles []string for _, f := range ofiles { absOfiles = append(absOfiles, mkAbs(objdir, f)) } return b.run(a, p.Dir, p.ImportPath, nil, "ar", "rc", mkAbs(objdir, afile), absOfiles) } func (tools gccgoToolchain) link(b *Builder, root *Action, out, importcfg string, allactions []*Action, buildmode, desc string) error { // gccgo needs explicit linking with all package dependencies, // and all LDFLAGS from cgo dependencies. afiles := []string{} shlibs := []string{} ldflags := b.gccArchArgs() cgoldflags := []string{} usesCgo := false cxx := false objc := false fortran := false if root.Package != nil { cxx = len(root.Package.CXXFiles) > 0 || len(root.Package.SwigCXXFiles) > 0 objc = len(root.Package.MFiles) > 0 fortran = len(root.Package.FFiles) > 0 } readCgoFlags := func(flagsFile string) error { flags, err := ioutil.ReadFile(flagsFile) if err != nil { return err } const ldflagsPrefix = "_CGO_LDFLAGS=" for _, line := range strings.Split(string(flags), "\n") { if strings.HasPrefix(line, ldflagsPrefix) { newFlags := strings.Fields(line[len(ldflagsPrefix):]) for _, flag := range newFlags { // Every _cgo_flags file has -g and -O2 in _CGO_LDFLAGS // but they don't mean anything to the linker so filter // them out. if flag != "-g" && !strings.HasPrefix(flag, "-O") { cgoldflags = append(cgoldflags, flag) } } } } return nil } newID := 0 readAndRemoveCgoFlags := func(archive string) (string, error) { newID++ newArchive := root.Objdir + fmt.Sprintf("_pkg%d_.a", newID) if err := b.copyFile(newArchive, archive, 0666, false); err != nil { return "", err } if cfg.BuildN || cfg.BuildX { b.Showcmd("", "ar d %s _cgo_flags", newArchive) if cfg.BuildN { // TODO(rsc): We could do better about showing the right _cgo_flags even in -n mode. // Either the archive is already built and we can read them out, // or we're printing commands to build the archive and can // forward the _cgo_flags directly to this step. return "", nil } } err := b.run(root, root.Objdir, desc, nil, "ar", "x", newArchive, "_cgo_flags") if err != nil { return "", err } err = b.run(root, ".", desc, nil, "ar", "d", newArchive, "_cgo_flags") if err != nil { return "", err } err = readCgoFlags(filepath.Join(root.Objdir, "_cgo_flags")) if err != nil { return "", err } return newArchive, nil } // If using -linkshared, find the shared library deps. haveShlib := make(map[string]bool) targetBase := filepath.Base(root.Target) if cfg.BuildLinkshared { for _, a := range root.Deps { p := a.Package if p == nil || p.Shlib == "" { continue } // The .a we are linking into this .so // will have its Shlib set to this .so. // Don't start thinking we want to link // this .so into itself. base := filepath.Base(p.Shlib) if base != targetBase { haveShlib[base] = true } } } // Arrange the deps into afiles and shlibs. addedShlib := make(map[string]bool) for _, a := range root.Deps { p := a.Package if p != nil && p.Shlib != "" && haveShlib[filepath.Base(p.Shlib)] { // This is a package linked into a shared // library that we will put into shlibs. continue } if haveShlib[filepath.Base(a.Target)] { // This is a shared library we want to link againt. if !addedShlib[a.Target] { shlibs = append(shlibs, a.Target) addedShlib[a.Target] = true } continue } if p != nil { target := a.built if p.UsesCgo() || p.UsesSwig() { var err error target, err = readAndRemoveCgoFlags(target) if err != nil { continue } } afiles = append(afiles, target) } } for _, a := range allactions { // Gather CgoLDFLAGS, but not from standard packages. // The go tool can dig up runtime/cgo from GOROOT and // think that it should use its CgoLDFLAGS, but gccgo // doesn't use runtime/cgo. if a.Package == nil { continue } if !a.Package.Standard { cgoldflags = append(cgoldflags, a.Package.CgoLDFLAGS...) } if len(a.Package.CgoFiles) > 0 { usesCgo = true } if a.Package.UsesSwig() { usesCgo = true } if len(a.Package.CXXFiles) > 0 || len(a.Package.SwigCXXFiles) > 0 { cxx = true } if len(a.Package.MFiles) > 0 { objc = true } if len(a.Package.FFiles) > 0 { fortran = true } } ldflags = append(ldflags, "-Wl,--whole-archive") ldflags = append(ldflags, afiles...) ldflags = append(ldflags, "-Wl,--no-whole-archive") ldflags = append(ldflags, cgoldflags...) ldflags = append(ldflags, envList("CGO_LDFLAGS", "")...) if root.Package != nil { ldflags = append(ldflags, root.Package.CgoLDFLAGS...) } ldflags = str.StringList("-Wl,-(", ldflags, "-Wl,-)") if root.buildID != "" { // On systems that normally use gold or the GNU linker, // use the --build-id option to write a GNU build ID note. switch cfg.Goos { case "android", "dragonfly", "linux", "netbsd": ldflags = append(ldflags, fmt.Sprintf("-Wl,--build-id=0x%x", root.buildID)) } } for _, shlib := range shlibs { ldflags = append( ldflags, "-L"+filepath.Dir(shlib), "-Wl,-rpath="+filepath.Dir(shlib), "-l"+strings.TrimSuffix( strings.TrimPrefix(filepath.Base(shlib), "lib"), ".so")) } var realOut string switch buildmode { case "exe": if usesCgo && cfg.Goos == "linux" { ldflags = append(ldflags, "-Wl,-E") } case "c-archive": // Link the Go files into a single .o, and also link // in -lgolibbegin. // // We need to use --whole-archive with -lgolibbegin // because it doesn't define any symbols that will // cause the contents to be pulled in; it's just // initialization code. // // The user remains responsible for linking against // -lgo -lpthread -lm in the final link. We can't use // -r to pick them up because we can't combine // split-stack and non-split-stack code in a single -r // link, and libgo picks up non-split-stack code from // libffi. ldflags = append(ldflags, "-Wl,-r", "-nostdlib", "-Wl,--whole-archive", "-lgolibbegin", "-Wl,--no-whole-archive") if nopie := b.gccNoPie([]string{tools.linker()}); nopie != "" { ldflags = append(ldflags, nopie) } // We are creating an object file, so we don't want a build ID. if root.buildID == "" { ldflags = b.disableBuildID(ldflags) } realOut = out out = out + ".o" case "c-shared": ldflags = append(ldflags, "-shared", "-nostdlib", "-Wl,--whole-archive", "-lgolibbegin", "-Wl,--no-whole-archive", "-lgo", "-lgcc_s", "-lgcc", "-lc", "-lgcc") case "shared": ldflags = append(ldflags, "-zdefs", "-shared", "-nostdlib", "-lgo", "-lgcc_s", "-lgcc", "-lc") default: base.Fatalf("-buildmode=%s not supported for gccgo", buildmode) } switch buildmode { case "exe", "c-shared": if cxx { ldflags = append(ldflags, "-lstdc++") } if objc { ldflags = append(ldflags, "-lobjc") } if fortran { fc := os.Getenv("FC") if fc == "" { fc = "gfortran" } // support gfortran out of the box and let others pass the correct link options // via CGO_LDFLAGS if strings.Contains(fc, "gfortran") { ldflags = append(ldflags, "-lgfortran") } } } if err := b.run(root, ".", desc, nil, tools.linker(), "-o", out, ldflags, forcedGccgoflags, root.Package.Internal.Gccgoflags); err != nil { return err } switch buildmode { case "c-archive": if err := b.run(root, ".", desc, nil, "ar", "rc", realOut, out); err != nil { return err } } return nil } func (tools gccgoToolchain) ld(b *Builder, root *Action, out, importcfg, mainpkg string) error { return tools.link(b, root, out, importcfg, root.Deps, ldBuildmode, root.Package.ImportPath) } func (tools gccgoToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, out, importcfg string, allactions []*Action) error { return tools.link(b, root, out, importcfg, allactions, "shared", out) } func (tools gccgoToolchain) cc(b *Builder, a *Action, ofile, cfile string) error { p := a.Package inc := filepath.Join(cfg.GOROOT, "pkg", "include") cfile = mkAbs(p.Dir, cfile) defs := []string{"-D", "GOOS_" + cfg.Goos, "-D", "GOARCH_" + cfg.Goarch} defs = append(defs, b.gccArchArgs()...) if pkgpath := gccgoCleanPkgpath(p); pkgpath != "" { defs = append(defs, `-D`, `GOPKGPATH="`+pkgpath+`"`) } switch cfg.Goarch { case "386", "amd64": defs = append(defs, "-fsplit-stack") } defs = tools.maybePIC(defs) return b.run(a, p.Dir, p.ImportPath, nil, envList("CC", cfg.DefaultCC(cfg.Goos, cfg.Goarch)), "-Wall", "-g", "-I", a.Objdir, "-I", inc, "-o", ofile, defs, "-c", cfile) } // maybePIC adds -fPIC to the list of arguments if needed. func (tools gccgoToolchain) maybePIC(args []string) []string { switch cfg.BuildBuildmode { case "c-shared", "shared", "plugin": args = append(args, "-fPIC") } return args } func gccgoPkgpath(p *load.Package) string { if p.Internal.Build.IsCommand() && !p.Internal.ForceLibrary { return "" } return p.ImportPath } func gccgoCleanPkgpath(p *load.Package) string { clean := func(r rune) rune { switch { case 'A' <= r && r <= 'Z', 'a' <= r && r <= 'z', '0' <= r && r <= '9': return r } return '_' } return strings.Map(clean, gccgoPkgpath(p)) }
work
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/work/build.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 work import ( "bytes" "errors" "fmt" "go/build" "io/ioutil" "os" "os/exec" "path" "path/filepath" "runtime" "strings" "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/load" "cmd/go/internal/search" ) var CmdBuild = &base.Command{ UsageLine: "go build [-o output] [-i] [build flags] [packages]", Short: "compile packages and dependencies", Long: ` Build compiles the packages named by the import paths, along with their dependencies, but it does not install the results. If the arguments to build are a list of .go files, build treats them as a list of source files specifying a single package. When compiling a single main package, build writes the resulting executable to an output file named after the first source file ('go build ed.go rx.go' writes 'ed' or 'ed.exe') or the source code directory ('go build unix/sam' writes 'sam' or 'sam.exe'). The '.exe' suffix is added when writing a Windows executable. When compiling multiple packages or a single non-main package, build compiles the packages but discards the resulting object, serving only as a check that the packages can be built. When compiling packages, build ignores files that end in '_test.go'. The -o flag, only allowed when compiling a single package, forces build to write the resulting executable or object to the named output file, instead of the default behavior described in the last two paragraphs. The -i flag installs the packages that are dependencies of the target. The build flags are shared by the build, clean, get, install, list, run, and test commands: -a force rebuilding of packages that are already up-to-date. -n print the commands but do not run them. -p n the number of programs, such as build commands or test binaries, that can be run in parallel. The default is the number of CPUs available. -race enable data race detection. Supported only on linux/amd64, freebsd/amd64, darwin/amd64 and windows/amd64. -msan enable interoperation with memory sanitizer. Supported only on linux/amd64, linux/arm64 and only with Clang/LLVM as the host C compiler. -v print the names of packages as they are compiled. -work print the name of the temporary work directory and do not delete it when exiting. -x print the commands. -asmflags '[pattern=]arg list' arguments to pass on each go tool asm invocation. -buildmode mode build mode to use. See 'go help buildmode' for more. -compiler name name of compiler to use, as in runtime.Compiler (gccgo or gc). -gccgoflags '[pattern=]arg list' arguments to pass on each gccgo compiler/linker invocation. -gcflags '[pattern=]arg list' arguments to pass on each go tool compile invocation. -installsuffix suffix a suffix to use in the name of the package installation directory, in order to keep output separate from default builds. If using the -race flag, the install suffix is automatically set to race or, if set explicitly, has _race appended to it. Likewise for the -msan flag. Using a -buildmode option that requires non-default compile flags has a similar effect. -ldflags '[pattern=]arg list' arguments to pass on each go tool link invocation. -linkshared link against shared libraries previously created with -buildmode=shared. -mod mode module download mode to use: readonly, release, or vendor. See 'go help modules' for more. -pkgdir dir install and load all packages from dir instead of the usual locations. For example, when building with a non-standard configuration, use -pkgdir to keep generated packages in a separate location. -tags 'tag list' a space-separated list of build tags to consider satisfied during the build. For more information about build tags, see the description of build constraints in the documentation for the go/build package. -toolexec 'cmd args' a program to use to invoke toolchain programs like vet and asm. For example, instead of running asm, the go command will run 'cmd args /path/to/asm <arguments for asm>'. The -asmflags, -gccgoflags, -gcflags, and -ldflags flags accept a space-separated list of arguments to pass to an underlying tool during the build. To embed spaces in an element in the list, surround it with either single or double quotes. The argument list may be preceded by a package pattern and an equal sign, which restricts the use of that argument list to the building of packages matching that pattern (see 'go help packages' for a description of package patterns). Without a pattern, the argument list applies only to the packages named on the command line. The flags may be repeated with different patterns in order to specify different arguments for different sets of packages. If a package matches patterns given in multiple flags, the latest match on the command line wins. For example, 'go build -gcflags=-S fmt' prints the disassembly only for package fmt, while 'go build -gcflags=all=-S fmt' prints the disassembly for fmt and all its dependencies. For more about specifying packages, see 'go help packages'. For more about where packages and binaries are installed, run 'go help gopath'. For more about calling between Go and C/C++, run 'go help c'. Note: Build adheres to certain conventions such as those described by 'go help gopath'. Not all projects can follow these conventions, however. Installations that have their own conventions or that use a separate software build system may choose to use lower-level invocations such as 'go tool compile' and 'go tool link' to avoid some of the overheads and design decisions of the build tool. See also: go install, go get, go clean. `, } const concurrentGCBackendCompilationEnabledByDefault = true func init() { // break init cycle CmdBuild.Run = runBuild CmdInstall.Run = runInstall CmdBuild.Flag.BoolVar(&cfg.BuildI, "i", false, "") CmdBuild.Flag.StringVar(&cfg.BuildO, "o", "", "output file") CmdInstall.Flag.BoolVar(&cfg.BuildI, "i", false, "") AddBuildFlags(CmdBuild) AddBuildFlags(CmdInstall) } // Note that flags consulted by other parts of the code // (for example, buildV) are in cmd/go/internal/cfg. var ( forcedAsmflags []string // internally-forced flags for cmd/asm forcedGcflags []string // internally-forced flags for cmd/compile forcedLdflags []string // internally-forced flags for cmd/link forcedGccgoflags []string // internally-forced flags for gccgo ) var BuildToolchain toolchain = noToolchain{} var ldBuildmode string // buildCompiler implements flag.Var. // It implements Set by updating both // BuildToolchain and buildContext.Compiler. type buildCompiler struct{} func (c buildCompiler) Set(value string) error { switch value { case "gc": BuildToolchain = gcToolchain{} case "gccgo": BuildToolchain = gccgoToolchain{} default: return fmt.Errorf("unknown compiler %q", value) } cfg.BuildToolchainName = value cfg.BuildToolchainCompiler = BuildToolchain.compiler cfg.BuildToolchainLinker = BuildToolchain.linker cfg.BuildContext.Compiler = value return nil } func (c buildCompiler) String() string { return cfg.BuildContext.Compiler } func init() { switch build.Default.Compiler { case "gc", "gccgo": buildCompiler{}.Set(build.Default.Compiler) } } // addBuildFlags adds the flags common to the build, clean, get, // install, list, run, and test commands. func AddBuildFlags(cmd *base.Command) { cmd.Flag.BoolVar(&cfg.BuildA, "a", false, "") cmd.Flag.BoolVar(&cfg.BuildN, "n", false, "") cmd.Flag.IntVar(&cfg.BuildP, "p", cfg.BuildP, "") cmd.Flag.BoolVar(&cfg.BuildV, "v", false, "") cmd.Flag.BoolVar(&cfg.BuildX, "x", false, "") cmd.Flag.Var(&load.BuildAsmflags, "asmflags", "") cmd.Flag.Var(buildCompiler{}, "compiler", "") cmd.Flag.StringVar(&cfg.BuildBuildmode, "buildmode", "default", "") cmd.Flag.Var(&load.BuildGcflags, "gcflags", "") cmd.Flag.Var(&load.BuildGccgoflags, "gccgoflags", "") cmd.Flag.StringVar(&cfg.BuildMod, "mod", "", "") cmd.Flag.StringVar(&cfg.BuildContext.InstallSuffix, "installsuffix", "", "") cmd.Flag.Var(&load.BuildLdflags, "ldflags", "") cmd.Flag.BoolVar(&cfg.BuildLinkshared, "linkshared", false, "") cmd.Flag.StringVar(&cfg.BuildPkgdir, "pkgdir", "", "") cmd.Flag.BoolVar(&cfg.BuildRace, "race", false, "") cmd.Flag.BoolVar(&cfg.BuildMSan, "msan", false, "") cmd.Flag.Var((*base.StringsFlag)(&cfg.BuildContext.BuildTags), "tags", "") cmd.Flag.Var((*base.StringsFlag)(&cfg.BuildToolexec), "toolexec", "") cmd.Flag.BoolVar(&cfg.BuildWork, "work", false, "") // Undocumented, unstable debugging flags. cmd.Flag.StringVar(&cfg.DebugActiongraph, "debug-actiongraph", "", "") } // fileExtSplit expects a filename and returns the name // and ext (without the dot). If the file has no // extension, ext will be empty. func fileExtSplit(file string) (name, ext string) { dotExt := filepath.Ext(file) name = file[:len(file)-len(dotExt)] if dotExt != "" { ext = dotExt[1:] } return } func pkgsMain(pkgs []*load.Package) (res []*load.Package) { for _, p := range pkgs { if p.Name == "main" { res = append(res, p) } } return res } func pkgsNotMain(pkgs []*load.Package) (res []*load.Package) { for _, p := range pkgs { if p.Name != "main" { res = append(res, p) } } return res } func oneMainPkg(pkgs []*load.Package) []*load.Package { if len(pkgs) != 1 || pkgs[0].Name != "main" { base.Fatalf("-buildmode=%s requires exactly one main package", cfg.BuildBuildmode) } return pkgs } var pkgsFilter = func(pkgs []*load.Package) []*load.Package { return pkgs } var runtimeVersion = getRuntimeVersion() var RuntimeVersion = runtimeVersion func getRuntimeVersion() string { data, err := ioutil.ReadFile(filepath.Join(cfg.GOROOT, "src/runtime/internal/sys/zversion.go")) if err != nil { base.Fatalf("go: %v", err) } i := bytes.Index(data, []byte("TheVersion = `")) if i < 0 { base.Fatalf("go: cannot find TheVersion") } data = data[i+len("TheVersion = `"):] j := bytes.IndexByte(data, '`') if j < 0 { base.Fatalf("go: cannot find TheVersion") } return string(data[:j]) } func runBuild(cmd *base.Command, args []string) { BuildInit() var b Builder b.Init() pkgs := load.PackagesForBuild(args) if len(pkgs) == 1 && pkgs[0].Name == "main" && cfg.BuildO == "" { _, cfg.BuildO = path.Split(pkgs[0].ImportPath) cfg.BuildO += cfg.ExeSuffix } // sanity check some often mis-used options switch cfg.BuildContext.Compiler { case "gccgo": if load.BuildGcflags.Present() { fmt.Println("go build: when using gccgo toolchain, please pass compiler flags using -gccgoflags, not -gcflags") } if load.BuildLdflags.Present() { fmt.Println("go build: when using gccgo toolchain, please pass linker flags using -gccgoflags, not -ldflags") } case "gc": if load.BuildGccgoflags.Present() { fmt.Println("go build: when using gc toolchain, please pass compile flags using -gcflags, and linker flags using -ldflags") } } depMode := ModeBuild if cfg.BuildI { depMode = ModeInstall } pkgs = omitTestOnly(pkgsFilter(load.Packages(args))) // Special case -o /dev/null by not writing at all. if cfg.BuildO == os.DevNull { cfg.BuildO = "" } if cfg.BuildO != "" { if len(pkgs) > 1 { base.Fatalf("go build: cannot use -o with multiple packages") } else if len(pkgs) == 0 { base.Fatalf("no packages to build") } p := pkgs[0] p.Target = cfg.BuildO p.Stale = true // must build - not up to date p.StaleReason = "build -o flag in use" a := b.AutoAction(ModeInstall, depMode, p) b.Do(a) return } a := &Action{Mode: "go build"} for _, p := range pkgs { a.Deps = append(a.Deps, b.AutoAction(ModeBuild, depMode, p)) } if cfg.BuildBuildmode == "shared" { a = b.buildmodeShared(ModeBuild, depMode, args, pkgs, a) } b.Do(a) } var CmdInstall = &base.Command{ UsageLine: "go install [-i] [build flags] [packages]", Short: "compile and install packages and dependencies", Long: ` Install compiles and installs the packages named by the import paths. The -i flag installs the dependencies of the named packages as well. For more about the build flags, see 'go help build'. For more about specifying packages, see 'go help packages'. See also: go build, go get, go clean. `, } // libname returns the filename to use for the shared library when using // -buildmode=shared. The rules we use are: // Use arguments for special 'meta' packages: // std --> libstd.so // std cmd --> libstd,cmd.so // A single non-meta argument with trailing "/..." is special cased: // foo/... --> libfoo.so // (A relative path like "./..." expands the "." first) // Use import paths for other cases, changing '/' to '-': // somelib --> libsubdir-somelib.so // ./ or ../ --> libsubdir-somelib.so // gopkg.in/tomb.v2 -> libgopkg.in-tomb.v2.so // a/... b/... ---> liba/c,b/d.so - all matching import paths // Name parts are joined with ','. func libname(args []string, pkgs []*load.Package) (string, error) { var libname string appendName := func(arg string) { if libname == "" { libname = arg } else { libname += "," + arg } } var haveNonMeta bool for _, arg := range args { if search.IsMetaPackage(arg) { appendName(arg) } else { haveNonMeta = true } } if len(libname) == 0 { // non-meta packages only. use import paths if len(args) == 1 && strings.HasSuffix(args[0], "/...") { // Special case of "foo/..." as mentioned above. arg := strings.TrimSuffix(args[0], "/...") if build.IsLocalImport(arg) { cwd, _ := os.Getwd() bp, _ := cfg.BuildContext.ImportDir(filepath.Join(cwd, arg), build.FindOnly) if bp.ImportPath != "" && bp.ImportPath != "." { arg = bp.ImportPath } } appendName(strings.Replace(arg, "/", "-", -1)) } else { for _, pkg := range pkgs { appendName(strings.Replace(pkg.ImportPath, "/", "-", -1)) } } } else if haveNonMeta { // have both meta package and a non-meta one return "", errors.New("mixing of meta and non-meta packages is not allowed") } // TODO(mwhudson): Needs to change for platforms that use different naming // conventions... return "lib" + libname + ".so", nil } func runInstall(cmd *base.Command, args []string) { BuildInit() InstallPackages(args, load.PackagesForBuild(args)) } // omitTestOnly returns pkgs with test-only packages removed. func omitTestOnly(pkgs []*load.Package) []*load.Package { var list []*load.Package for _, p := range pkgs { if len(p.GoFiles)+len(p.CgoFiles) == 0 && !p.Internal.CmdlinePkgLiteral { // Package has no source files, // perhaps due to build tags or perhaps due to only having *_test.go files. // Also, it is only being processed as the result of a wildcard match // like ./..., not because it was listed as a literal path on the command line. // Ignore it. continue } list = append(list, p) } return list } func InstallPackages(patterns []string, pkgs []*load.Package) { if cfg.GOBIN != "" && !filepath.IsAbs(cfg.GOBIN) { base.Fatalf("cannot install, GOBIN must be an absolute path") } pkgs = omitTestOnly(pkgsFilter(pkgs)) for _, p := range pkgs { if p.Target == "" { switch { case p.Standard && p.ImportPath == "unsafe": // unsafe is a built-in package, has no target case p.Name != "main" && p.Internal.Local && p.ConflictDir == "": // Non-executables outside GOPATH need not have a target: // we can use the cache to hold the built package archive for use in future builds. // The ones inside GOPATH should have a target (in GOPATH/pkg) // or else something is wrong and worth reporting (like a ConflictDir). case p.Name != "main" && p.Module != nil: // Non-executables have no target (except the cache) when building with modules. case p.Internal.GobinSubdir: base.Errorf("go %s: cannot install cross-compiled binaries when GOBIN is set", cfg.CmdName) case p.Internal.CmdlineFiles: base.Errorf("go %s: no install location for .go files listed on command line (GOBIN not set)", cfg.CmdName) case p.ConflictDir != "": base.Errorf("go %s: no install location for %s: hidden by %s", cfg.CmdName, p.Dir, p.ConflictDir) default: base.Errorf("go %s: no install location for directory %s outside GOPATH\n"+ "\tFor more details see: 'go help gopath'", cfg.CmdName, p.Dir) } } } base.ExitIfErrors() var b Builder b.Init() depMode := ModeBuild if cfg.BuildI { depMode = ModeInstall } a := &Action{Mode: "go install"} var tools []*Action for _, p := range pkgs { // If p is a tool, delay the installation until the end of the build. // This avoids installing assemblers/compilers that are being executed // by other steps in the build. a1 := b.AutoAction(ModeInstall, depMode, p) if load.InstallTargetDir(p) == load.ToTool { a.Deps = append(a.Deps, a1.Deps...) a1.Deps = append(a1.Deps, a) tools = append(tools, a1) continue } a.Deps = append(a.Deps, a1) } if len(tools) > 0 { a = &Action{ Mode: "go install (tools)", Deps: tools, } } if cfg.BuildBuildmode == "shared" { // Note: If buildmode=shared then only non-main packages // are present in the pkgs list, so all the special case code about // tools above did not apply, and a is just a simple Action // with a list of Deps, one per package named in pkgs, // the same as in runBuild. a = b.buildmodeShared(ModeInstall, ModeInstall, patterns, pkgs, a) } b.Do(a) base.ExitIfErrors() // Success. If this command is 'go install' with no arguments // and the current directory (the implicit argument) is a command, // remove any leftover command binary from a previous 'go build'. // The binary is installed; it's not needed here anymore. // And worse it might be a stale copy, which you don't want to find // instead of the installed one if $PATH contains dot. // One way to view this behavior is that it is as if 'go install' first // runs 'go build' and the moves the generated file to the install dir. // See issue 9645. if len(patterns) == 0 && len(pkgs) == 1 && pkgs[0].Name == "main" { // Compute file 'go build' would have created. // If it exists and is an executable file, remove it. _, targ := filepath.Split(pkgs[0].ImportPath) targ += cfg.ExeSuffix if filepath.Join(pkgs[0].Dir, targ) != pkgs[0].Target { // maybe $GOBIN is the current directory fi, err := os.Stat(targ) if err == nil { m := fi.Mode() if m.IsRegular() { if m&0111 != 0 || cfg.Goos == "windows" { // windows never sets executable bit os.Remove(targ) } } } } } } // ExecCmd is the command to use to run user binaries. // Normally it is empty, meaning run the binaries directly. // If cross-compiling and running on a remote system or // simulator, it is typically go_GOOS_GOARCH_exec, with // the target GOOS and GOARCH substituted. // The -exec flag overrides these defaults. var ExecCmd []string // FindExecCmd derives the value of ExecCmd to use. // It returns that value and leaves ExecCmd set for direct use. func FindExecCmd() []string { if ExecCmd != nil { return ExecCmd } ExecCmd = []string{} // avoid work the second time if cfg.Goos == runtime.GOOS && cfg.Goarch == runtime.GOARCH { return ExecCmd } path, err := exec.LookPath(fmt.Sprintf("go_%s_%s_exec", cfg.Goos, cfg.Goarch)) if err == nil { ExecCmd = []string{path} } return ExecCmd }
work
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/work/action.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. // Action graph creation (planning). package work import ( "bufio" "bytes" "container/heap" "debug/elf" "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" "strings" "sync" "cmd/go/internal/base" "cmd/go/internal/cache" "cmd/go/internal/cfg" "cmd/go/internal/load" "cmd/internal/buildid" ) // A Builder holds global state about a build. // It does not hold per-package state, because we // build packages in parallel, and the builder is shared. type Builder struct { WorkDir string // the temporary work directory (ends in filepath.Separator) actionCache map[cacheKey]*Action // a cache of already-constructed actions mkdirCache map[string]bool // a cache of created directories flagCache map[[2]string]bool // a cache of supported compiler flags Print func(args ...interface{}) (int, error) IsCmdList bool // running as part of go list; set p.Stale and additional fields below NeedError bool // list needs p.Error NeedExport bool // list needs p.Export NeedCompiledGoFiles bool // list needs p.CompiledGoFIles objdirSeq int // counter for NewObjdir pkgSeq int output sync.Mutex scriptDir string // current directory in printed script exec sync.Mutex readySema chan bool ready actionQueue id sync.Mutex toolIDCache map[string]string // tool name -> tool ID buildIDCache map[string]string // file name -> build ID } // NOTE: Much of Action would not need to be exported if not for test. // Maybe test functionality should move into this package too? // An Action represents a single action in the action graph. type Action struct { Mode string // description of action operation Package *load.Package // the package this action works on Deps []*Action // actions that must happen before this one Func func(*Builder, *Action) error // the action itself (nil = no-op) IgnoreFail bool // whether to run f even if dependencies fail TestOutput *bytes.Buffer // test output buffer Args []string // additional args for runProgram triggers []*Action // inverse of deps buggyInstall bool // is this a buggy install (see -linkshared)? TryCache func(*Builder, *Action) bool // callback for cache bypass // Generated files, directories. Objdir string // directory for intermediate objects Target string // goal of the action: the created package or executable built string // the actual created package or executable actionID cache.ActionID // cache ID of action input buildID string // build ID of action output VetxOnly bool // Mode=="vet": only being called to supply info about dependencies needVet bool // Mode=="build": need to fill in vet config vetCfg *vetConfig // vet config output []byte // output redirect buffer (nil means use b.Print) // Execution state. pending int // number of deps yet to complete priority int // relative execution priority Failed bool // whether the action failed } // BuildActionID returns the action ID section of a's build ID. func (a *Action) BuildActionID() string { return actionID(a.buildID) } // BuildContentID returns the content ID section of a's build ID. func (a *Action) BuildContentID() string { return contentID(a.buildID) } // BuildID returns a's build ID. func (a *Action) BuildID() string { return a.buildID } // BuiltTarget returns the actual file that was built. This differs // from Target when the result was cached. func (a *Action) BuiltTarget() string { return a.built } // An actionQueue is a priority queue of actions. type actionQueue []*Action // Implement heap.Interface func (q *actionQueue) Len() int { return len(*q) } func (q *actionQueue) Swap(i, j int) { (*q)[i], (*q)[j] = (*q)[j], (*q)[i] } func (q *actionQueue) Less(i, j int) bool { return (*q)[i].priority < (*q)[j].priority } func (q *actionQueue) Push(x interface{}) { *q = append(*q, x.(*Action)) } func (q *actionQueue) Pop() interface{} { n := len(*q) - 1 x := (*q)[n] *q = (*q)[:n] return x } func (q *actionQueue) push(a *Action) { heap.Push(q, a) } func (q *actionQueue) pop() *Action { return heap.Pop(q).(*Action) } type actionJSON struct { ID int Mode string Package string Deps []int `json:",omitempty"` IgnoreFail bool `json:",omitempty"` Args []string `json:",omitempty"` Link bool `json:",omitempty"` Objdir string `json:",omitempty"` Target string `json:",omitempty"` Priority int `json:",omitempty"` Failed bool `json:",omitempty"` Built string `json:",omitempty"` VetxOnly bool `json:",omitempty"` } // cacheKey is the key for the action cache. type cacheKey struct { mode string p *load.Package } func actionGraphJSON(a *Action) string { var workq []*Action var inWorkq = make(map[*Action]int) add := func(a *Action) { if _, ok := inWorkq[a]; ok { return } inWorkq[a] = len(workq) workq = append(workq, a) } add(a) for i := 0; i < len(workq); i++ { for _, dep := range workq[i].Deps { add(dep) } } var list []*actionJSON for id, a := range workq { aj := &actionJSON{ Mode: a.Mode, ID: id, IgnoreFail: a.IgnoreFail, Args: a.Args, Objdir: a.Objdir, Target: a.Target, Failed: a.Failed, Priority: a.priority, Built: a.built, VetxOnly: a.VetxOnly, } if a.Package != nil { // TODO(rsc): Make this a unique key for a.Package somehow. aj.Package = a.Package.ImportPath } for _, a1 := range a.Deps { aj.Deps = append(aj.Deps, inWorkq[a1]) } list = append(list, aj) } js, err := json.MarshalIndent(list, "", "\t") if err != nil { fmt.Fprintf(os.Stderr, "go: writing debug action graph: %v\n", err) return "" } return string(js) } // BuildMode specifies the build mode: // are we just building things or also installing the results? type BuildMode int const ( ModeBuild BuildMode = iota ModeInstall ModeBuggyInstall ) func (b *Builder) Init() { b.Print = func(a ...interface{}) (int, error) { return fmt.Fprint(os.Stderr, a...) } b.actionCache = make(map[cacheKey]*Action) b.mkdirCache = make(map[string]bool) b.toolIDCache = make(map[string]string) b.buildIDCache = make(map[string]string) if cfg.BuildN { b.WorkDir = "$WORK" } else { tmp, err := ioutil.TempDir(os.Getenv("GOTMPDIR"), "go-build") if err != nil { base.Fatalf("go: creating work dir: %v", err) } if !filepath.IsAbs(tmp) { abs, err := filepath.Abs(tmp) if err != nil { os.RemoveAll(tmp) base.Fatalf("go: creating work dir: %v", err) } tmp = abs } b.WorkDir = tmp if cfg.BuildX || cfg.BuildWork { fmt.Fprintf(os.Stderr, "WORK=%s\n", b.WorkDir) } if !cfg.BuildWork { workdir := b.WorkDir base.AtExit(func() { os.RemoveAll(workdir) }) } } if _, ok := cfg.OSArchSupportsCgo[cfg.Goos+"/"+cfg.Goarch]; !ok && cfg.BuildContext.Compiler == "gc" { fmt.Fprintf(os.Stderr, "cmd/go: unsupported GOOS/GOARCH pair %s/%s\n", cfg.Goos, cfg.Goarch) os.Exit(2) } for _, tag := range cfg.BuildContext.BuildTags { if strings.Contains(tag, ",") { fmt.Fprintf(os.Stderr, "cmd/go: -tags space-separated list contains comma\n") os.Exit(2) } } } // NewObjdir returns the name of a fresh object directory under b.WorkDir. // It is up to the caller to call b.Mkdir on the result at an appropriate time. // The result ends in a slash, so that file names in that directory // can be constructed with direct string addition. // // NewObjdir must be called only from a single goroutine at a time, // so it is safe to call during action graph construction, but it must not // be called during action graph execution. func (b *Builder) NewObjdir() string { b.objdirSeq++ return filepath.Join(b.WorkDir, fmt.Sprintf("b%03d", b.objdirSeq)) + string(filepath.Separator) } // readpkglist returns the list of packages that were built into the shared library // at shlibpath. For the native toolchain this list is stored, newline separated, in // an ELF note with name "Go\x00\x00" and type 1. For GCCGO it is extracted from the // .go_export section. func readpkglist(shlibpath string) (pkgs []*load.Package) { var stk load.ImportStack if cfg.BuildToolchainName == "gccgo" { f, _ := elf.Open(shlibpath) sect := f.Section(".go_export") data, _ := sect.Data() scanner := bufio.NewScanner(bytes.NewBuffer(data)) for scanner.Scan() { t := scanner.Text() if strings.HasPrefix(t, "pkgpath ") { t = strings.TrimPrefix(t, "pkgpath ") t = strings.TrimSuffix(t, ";") pkgs = append(pkgs, load.LoadPackage(t, &stk)) } } } else { pkglistbytes, err := buildid.ReadELFNote(shlibpath, "Go\x00\x00", 1) if err != nil { base.Fatalf("readELFNote failed: %v", err) } scanner := bufio.NewScanner(bytes.NewBuffer(pkglistbytes)) for scanner.Scan() { t := scanner.Text() pkgs = append(pkgs, load.LoadPackage(t, &stk)) } } return } // cacheAction looks up {mode, p} in the cache and returns the resulting action. // If the cache has no such action, f() is recorded and returned. // TODO(rsc): Change the second key from *load.Package to interface{}, // to make the caching in linkShared less awkward? func (b *Builder) cacheAction(mode string, p *load.Package, f func() *Action) *Action { a := b.actionCache[cacheKey{mode, p}] if a == nil { a = f() b.actionCache[cacheKey{mode, p}] = a } return a } // AutoAction returns the "right" action for go build or go install of p. func (b *Builder) AutoAction(mode, depMode BuildMode, p *load.Package) *Action { if p.Name == "main" { return b.LinkAction(mode, depMode, p) } return b.CompileAction(mode, depMode, p) } // CompileAction returns the action for compiling and possibly installing // (according to mode) the given package. The resulting action is only // for building packages (archives), never for linking executables. // depMode is the action (build or install) to use when building dependencies. // To turn package main into an executable, call b.Link instead. func (b *Builder) CompileAction(mode, depMode BuildMode, p *load.Package) *Action { if mode != ModeBuild && (p.Internal.Local || p.Module != nil) && p.Target == "" { // Imported via local path or using modules. No permanent target. mode = ModeBuild } if mode != ModeBuild && p.Name == "main" { // We never install the .a file for a main package. mode = ModeBuild } // Construct package build action. a := b.cacheAction("build", p, func() *Action { a := &Action{ Mode: "build", Package: p, Func: (*Builder).build, Objdir: b.NewObjdir(), } if p.Error == nil || !p.Error.IsImportCycle { for _, p1 := range p.Internal.Imports { a.Deps = append(a.Deps, b.CompileAction(depMode, depMode, p1)) } } if p.Standard { switch p.ImportPath { case "builtin", "unsafe": // Fake packages - nothing to build. a.Mode = "built-in package" a.Func = nil return a } // gccgo standard library is "fake" too. if cfg.BuildToolchainName == "gccgo" { // the target name is needed for cgo. a.Mode = "gccgo stdlib" a.Target = p.Target a.Func = nil return a } } return a }) // Construct install action. if mode == ModeInstall || mode == ModeBuggyInstall { a = b.installAction(a, mode) } return a } // VetAction returns the action for running go vet on package p. // It depends on the action for compiling p. // If the caller may be causing p to be installed, it is up to the caller // to make sure that the install depends on (runs after) vet. func (b *Builder) VetAction(mode, depMode BuildMode, p *load.Package) *Action { a := b.vetAction(mode, depMode, p) a.VetxOnly = false return a } func (b *Builder) vetAction(mode, depMode BuildMode, p *load.Package) *Action { // Construct vet action. a := b.cacheAction("vet", p, func() *Action { a1 := b.CompileAction(mode, depMode, p) // vet expects to be able to import "fmt". var stk load.ImportStack stk.Push("vet") p1 := load.LoadPackage("fmt", &stk) stk.Pop() aFmt := b.CompileAction(ModeBuild, depMode, p1) var deps []*Action if a1.buggyInstall { // (*Builder).vet expects deps[0] to be the package // and deps[1] to be "fmt". If we see buggyInstall // here then a1 is an install of a shared library, // and the real package is a1.Deps[0]. deps = []*Action{a1.Deps[0], aFmt, a1} } else { deps = []*Action{a1, aFmt} } for _, p1 := range load.PackageList(p.Internal.Imports) { deps = append(deps, b.vetAction(mode, depMode, p1)) } a := &Action{ Mode: "vet", Package: p, Deps: deps, Objdir: a1.Objdir, VetxOnly: true, IgnoreFail: true, // it's OK if vet of dependencies "fails" (reports problems) } if a1.Func == nil { // Built-in packages like unsafe. return a } deps[0].needVet = true a.Func = (*Builder).vet return a }) return a } // LinkAction returns the action for linking p into an executable // and possibly installing the result (according to mode). // depMode is the action (build or install) to use when compiling dependencies. func (b *Builder) LinkAction(mode, depMode BuildMode, p *load.Package) *Action { // Construct link action. a := b.cacheAction("link", p, func() *Action { a := &Action{ Mode: "link", Package: p, } a1 := b.CompileAction(ModeBuild, depMode, p) a.Func = (*Builder).link a.Deps = []*Action{a1} a.Objdir = a1.Objdir // An executable file. (This is the name of a temporary file.) // Because we run the temporary file in 'go run' and 'go test', // the name will show up in ps listings. If the caller has specified // a name, use that instead of a.out. The binary is generated // in an otherwise empty subdirectory named exe to avoid // naming conflicts. The only possible conflict is if we were // to create a top-level package named exe. name := "a.out" if p.Internal.ExeName != "" { name = p.Internal.ExeName } else if (cfg.Goos == "darwin" || cfg.Goos == "windows") && cfg.BuildBuildmode == "c-shared" && p.Target != "" { // On OS X, the linker output name gets recorded in the // shared library's LC_ID_DYLIB load command. // The code invoking the linker knows to pass only the final // path element. Arrange that the path element matches what // we'll install it as; otherwise the library is only loadable as "a.out". // On Windows, DLL file name is recorded in PE file // export section, so do like on OS X. _, name = filepath.Split(p.Target) } a.Target = a.Objdir + filepath.Join("exe", name) + cfg.ExeSuffix a.built = a.Target b.addTransitiveLinkDeps(a, a1, "") // Sequence the build of the main package (a1) strictly after the build // of all other dependencies that go into the link. It is likely to be after // them anyway, but just make sure. This is required by the build ID-based // shortcut in (*Builder).useCache(a1), which will call b.linkActionID(a). // In order for that linkActionID call to compute the right action ID, all the // dependencies of a (except a1) must have completed building and have // recorded their build IDs. a1.Deps = append(a1.Deps, &Action{Mode: "nop", Deps: a.Deps[1:]}) return a }) if mode == ModeInstall || mode == ModeBuggyInstall { a = b.installAction(a, mode) } return a } // installAction returns the action for installing the result of a1. func (b *Builder) installAction(a1 *Action, mode BuildMode) *Action { // Because we overwrite the build action with the install action below, // a1 may already be an install action fetched from the "build" cache key, // and the caller just doesn't realize. if strings.HasSuffix(a1.Mode, "-install") { if a1.buggyInstall && mode == ModeInstall { // Congratulations! The buggy install is now a proper install. a1.buggyInstall = false } return a1 } // If there's no actual action to build a1, // there's nothing to install either. // This happens if a1 corresponds to reusing an already-built object. if a1.Func == nil { return a1 } p := a1.Package return b.cacheAction(a1.Mode+"-install", p, func() *Action { // The install deletes the temporary build result, // so we need all other actions, both past and future, // that attempt to depend on the build to depend instead // on the install. // Make a private copy of a1 (the build action), // no longer accessible to any other rules. buildAction := new(Action) *buildAction = *a1 // Overwrite a1 with the install action. // This takes care of updating past actions that // point at a1 for the build action; now they will // point at a1 and get the install action. // We also leave a1 in the action cache as the result // for "build", so that actions not yet created that // try to depend on the build will instead depend // on the install. *a1 = Action{ Mode: buildAction.Mode + "-install", Func: BuildInstallFunc, Package: p, Objdir: buildAction.Objdir, Deps: []*Action{buildAction}, Target: p.Target, built: p.Target, buggyInstall: mode == ModeBuggyInstall, } b.addInstallHeaderAction(a1) return a1 }) } // addTransitiveLinkDeps adds to the link action a all packages // that are transitive dependencies of a1.Deps. // That is, if a is a link of package main, a1 is the compile of package main // and a1.Deps is the actions for building packages directly imported by // package main (what the compiler needs). The linker needs all packages // transitively imported by the whole program; addTransitiveLinkDeps // makes sure those are present in a.Deps. // If shlib is non-empty, then a corresponds to the build and installation of shlib, // so any rebuild of shlib should not be added as a dependency. func (b *Builder) addTransitiveLinkDeps(a, a1 *Action, shlib string) { // Expand Deps to include all built packages, for the linker. // Use breadth-first search to find rebuilt-for-test packages // before the standard ones. // TODO(rsc): Eliminate the standard ones from the action graph, // which will require doing a little bit more rebuilding. workq := []*Action{a1} haveDep := map[string]bool{} if a1.Package != nil { haveDep[a1.Package.ImportPath] = true } for i := 0; i < len(workq); i++ { a1 := workq[i] for _, a2 := range a1.Deps { // TODO(rsc): Find a better discriminator than the Mode strings, once the dust settles. if a2.Package == nil || (a2.Mode != "build-install" && a2.Mode != "build") || haveDep[a2.Package.ImportPath] { continue } haveDep[a2.Package.ImportPath] = true a.Deps = append(a.Deps, a2) if a2.Mode == "build-install" { a2 = a2.Deps[0] // walk children of "build" action } workq = append(workq, a2) } } // If this is go build -linkshared, then the link depends on the shared libraries // in addition to the packages themselves. (The compile steps do not.) if cfg.BuildLinkshared { haveShlib := map[string]bool{shlib: true} for _, a1 := range a.Deps { p1 := a1.Package if p1 == nil || p1.Shlib == "" || haveShlib[filepath.Base(p1.Shlib)] { continue } haveShlib[filepath.Base(p1.Shlib)] = true // TODO(rsc): The use of ModeInstall here is suspect, but if we only do ModeBuild, // we'll end up building an overall library or executable that depends at runtime // on other libraries that are out-of-date, which is clearly not good either. // We call it ModeBuggyInstall to make clear that this is not right. a.Deps = append(a.Deps, b.linkSharedAction(ModeBuggyInstall, ModeBuggyInstall, p1.Shlib, nil)) } } } // addInstallHeaderAction adds an install header action to a, if needed. // The action a should be an install action as generated by either // b.CompileAction or b.LinkAction with mode=ModeInstall, // and so a.Deps[0] is the corresponding build action. func (b *Builder) addInstallHeaderAction(a *Action) { // Install header for cgo in c-archive and c-shared modes. p := a.Package if p.UsesCgo() && (cfg.BuildBuildmode == "c-archive" || cfg.BuildBuildmode == "c-shared") { hdrTarget := a.Target[:len(a.Target)-len(filepath.Ext(a.Target))] + ".h" if cfg.BuildContext.Compiler == "gccgo" && cfg.BuildO == "" { // For the header file, remove the "lib" // added by go/build, so we generate pkg.h // rather than libpkg.h. dir, file := filepath.Split(hdrTarget) file = strings.TrimPrefix(file, "lib") hdrTarget = filepath.Join(dir, file) } ah := &Action{ Mode: "install header", Package: a.Package, Deps: []*Action{a.Deps[0]}, Func: (*Builder).installHeader, Objdir: a.Deps[0].Objdir, Target: hdrTarget, } a.Deps = append(a.Deps, ah) } } // buildmodeShared takes the "go build" action a1 into the building of a shared library of a1.Deps. // That is, the input a1 represents "go build pkgs" and the result represents "go build -buidmode=shared pkgs". func (b *Builder) buildmodeShared(mode, depMode BuildMode, args []string, pkgs []*load.Package, a1 *Action) *Action { name, err := libname(args, pkgs) if err != nil { base.Fatalf("%v", err) } return b.linkSharedAction(mode, depMode, name, a1) } // linkSharedAction takes a grouping action a1 corresponding to a list of built packages // and returns an action that links them together into a shared library with the name shlib. // If a1 is nil, shlib should be an absolute path to an existing shared library, // and then linkSharedAction reads that library to find out the package list. func (b *Builder) linkSharedAction(mode, depMode BuildMode, shlib string, a1 *Action) *Action { fullShlib := shlib shlib = filepath.Base(shlib) a := b.cacheAction("build-shlib "+shlib, nil, func() *Action { if a1 == nil { // TODO(rsc): Need to find some other place to store config, // not in pkg directory. See golang.org/issue/22196. pkgs := readpkglist(fullShlib) a1 = &Action{ Mode: "shlib packages", } for _, p := range pkgs { a1.Deps = append(a1.Deps, b.CompileAction(mode, depMode, p)) } } // Fake package to hold ldflags. // As usual shared libraries are a kludgy, abstraction-violating special case: // we let them use the flags specified for the command-line arguments. p := &load.Package{} p.Internal.CmdlinePkg = true p.Internal.Ldflags = load.BuildLdflags.For(p) p.Internal.Gccgoflags = load.BuildGccgoflags.For(p) // Add implicit dependencies to pkgs list. // Currently buildmode=shared forces external linking mode, and // external linking mode forces an import of runtime/cgo (and // math on arm). So if it was not passed on the command line and // it is not present in another shared library, add it here. // TODO(rsc): Maybe this should only happen if "runtime" is in the original package set. // TODO(rsc): This should probably be changed to use load.LinkerDeps(p). // TODO(rsc): We don't add standard library imports for gccgo // because they are all always linked in anyhow. // Maybe load.LinkerDeps should be used and updated. a := &Action{ Mode: "go build -buildmode=shared", Package: p, Objdir: b.NewObjdir(), Func: (*Builder).linkShared, Deps: []*Action{a1}, } a.Target = filepath.Join(a.Objdir, shlib) if cfg.BuildToolchainName != "gccgo" { add := func(a1 *Action, pkg string, force bool) { for _, a2 := range a1.Deps { if a2.Package != nil && a2.Package.ImportPath == pkg { return } } var stk load.ImportStack p := load.LoadPackage(pkg, &stk) if p.Error != nil { base.Fatalf("load %s: %v", pkg, p.Error) } // Assume that if pkg (runtime/cgo or math) // is already accounted for in a different shared library, // then that shared library also contains runtime, // so that anything we do will depend on that library, // so we don't need to include pkg in our shared library. if force || p.Shlib == "" || filepath.Base(p.Shlib) == pkg { a1.Deps = append(a1.Deps, b.CompileAction(depMode, depMode, p)) } } add(a1, "runtime/cgo", false) if cfg.Goarch == "arm" { add(a1, "math", false) } // The linker step still needs all the usual linker deps. // (For example, the linker always opens runtime.a.) for _, dep := range load.LinkerDeps(nil) { add(a, dep, true) } } b.addTransitiveLinkDeps(a, a1, shlib) return a }) // Install result. if (mode == ModeInstall || mode == ModeBuggyInstall) && a.Func != nil { buildAction := a a = b.cacheAction("install-shlib "+shlib, nil, func() *Action { // Determine the eventual install target. // The install target is root/pkg/shlib, where root is the source root // in which all the packages lie. // TODO(rsc): Perhaps this cross-root check should apply to the full // transitive package dependency list, not just the ones named // on the command line? pkgDir := a1.Deps[0].Package.Internal.Build.PkgTargetRoot for _, a2 := range a1.Deps { if dir := a2.Package.Internal.Build.PkgTargetRoot; dir != pkgDir { base.Fatalf("installing shared library: cannot use packages %s and %s from different roots %s and %s", a1.Deps[0].Package.ImportPath, a2.Package.ImportPath, pkgDir, dir) } } // TODO(rsc): Find out and explain here why gccgo is different. if cfg.BuildToolchainName == "gccgo" { pkgDir = filepath.Join(pkgDir, "shlibs") } target := filepath.Join(pkgDir, shlib) a := &Action{ Mode: "go install -buildmode=shared", Objdir: buildAction.Objdir, Func: BuildInstallFunc, Deps: []*Action{buildAction}, Target: target, } for _, a2 := range buildAction.Deps[0].Deps { p := a2.Package if p.Target == "" { continue } a.Deps = append(a.Deps, &Action{ Mode: "shlibname", Package: p, Func: (*Builder).installShlibname, Target: strings.TrimSuffix(p.Target, ".a") + ".shlibname", Deps: []*Action{a.Deps[0]}, }) } return a }) } return a }
work
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/work/testgo.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. // This file contains extra hooks for testing the go command. // +build testgo package work import "os" func init() { if v := os.Getenv("TESTGO_VERSION"); v != "" { runtimeVersion = v } }
work
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/work/buildid.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 work import ( "bytes" "fmt" "io/ioutil" "os" "os/exec" "strings" "cmd/go/internal/base" "cmd/go/internal/cache" "cmd/go/internal/cfg" "cmd/go/internal/load" "cmd/go/internal/str" "cmd/internal/buildid" ) // Build IDs // // Go packages and binaries are stamped with build IDs that record both // the action ID, which is a hash of the inputs to the action that produced // the packages or binary, and the content ID, which is a hash of the action // output, namely the archive or binary itself. The hash is the same one // used by the build artifact cache (see cmd/go/internal/cache), but // truncated when stored in packages and binaries, as the full length is not // needed and is a bit unwieldy. The precise form is // // actionID/[.../]contentID // // where the actionID and contentID are prepared by hashToString below. // and are found by looking for the first or last slash. // Usually the buildID is simply actionID/contentID, but see below for an // exception. // // The build ID serves two primary purposes. // // 1. The action ID half allows installed packages and binaries to serve as // one-element cache entries. If we intend to build math.a with a given // set of inputs summarized in the action ID, and the installed math.a already // has that action ID, we can reuse the installed math.a instead of rebuilding it. // // 2. The content ID half allows the easy preparation of action IDs for steps // that consume a particular package or binary. The content hash of every // input file for a given action must be included in the action ID hash. // Storing the content ID in the build ID lets us read it from the file with // minimal I/O, instead of reading and hashing the entire file. // This is especially effective since packages and binaries are typically // the largest inputs to an action. // // Separating action ID from content ID is important for reproducible builds. // The compiler is compiled with itself. If an output were represented by its // own action ID (instead of content ID) when computing the action ID of // the next step in the build process, then the compiler could never have its // own input action ID as its output action ID (short of a miraculous hash collision). // Instead we use the content IDs to compute the next action ID, and because // the content IDs converge, so too do the action IDs and therefore the // build IDs and the overall compiler binary. See cmd/dist's cmdbootstrap // for the actual convergence sequence. // // The “one-element cache” purpose is a bit more complex for installed // binaries. For a binary, like cmd/gofmt, there are two steps: compile // cmd/gofmt/*.go into main.a, and then link main.a into the gofmt binary. // We do not install gofmt's main.a, only the gofmt binary. Being able to // decide that the gofmt binary is up-to-date means computing the action ID // for the final link of the gofmt binary and comparing it against the // already-installed gofmt binary. But computing the action ID for the link // means knowing the content ID of main.a, which we did not keep. // To sidestep this problem, each binary actually stores an expanded build ID: // // actionID(binary)/actionID(main.a)/contentID(main.a)/contentID(binary) // // (Note that this can be viewed equivalently as: // // actionID(binary)/buildID(main.a)/contentID(binary) // // Storing the buildID(main.a) in the middle lets the computations that care // about the prefix or suffix halves ignore the middle and preserves the // original build ID as a contiguous string.) // // During the build, when it's time to build main.a, the gofmt binary has the // information needed to decide whether the eventual link would produce // the same binary: if the action ID for main.a's inputs matches and then // the action ID for the link step matches when assuming the given main.a // content ID, then the binary as a whole is up-to-date and need not be rebuilt. // // This is all a bit complex and may be simplified once we can rely on the // main cache, but at least at the start we will be using the content-based // staleness determination without a cache beyond the usual installed // package and binary locations. const buildIDSeparator = "/" // actionID returns the action ID half of a build ID. func actionID(buildID string) string { i := strings.Index(buildID, buildIDSeparator) if i < 0 { return buildID } return buildID[:i] } // contentID returns the content ID half of a build ID. func contentID(buildID string) string { return buildID[strings.LastIndex(buildID, buildIDSeparator)+1:] } // hashToString converts the hash h to a string to be recorded // in package archives and binaries as part of the build ID. // We use the first 96 bits of the hash and encode it in base64, // resulting in a 16-byte string. Because this is only used for // detecting the need to rebuild installed files (not for lookups // in the object file cache), 96 bits are sufficient to drive the // probability of a false "do not need to rebuild" decision to effectively zero. // We embed two different hashes in archives and four in binaries, // so cutting to 16 bytes is a significant savings when build IDs are displayed. // (16*4+3 = 67 bytes compared to 64*4+3 = 259 bytes for the // more straightforward option of printing the entire h in hex). func hashToString(h [cache.HashSize]byte) string { const b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" const chunks = 5 var dst [chunks * 4]byte for i := 0; i < chunks; i++ { v := uint32(h[3*i])<<16 | uint32(h[3*i+1])<<8 | uint32(h[3*i+2]) dst[4*i+0] = b64[(v>>18)&0x3F] dst[4*i+1] = b64[(v>>12)&0x3F] dst[4*i+2] = b64[(v>>6)&0x3F] dst[4*i+3] = b64[v&0x3F] } return string(dst[:]) } var oldVet = false // toolID returns the unique ID to use for the current copy of the // named tool (asm, compile, cover, link). // // It is important that if the tool changes (for example a compiler bug is fixed // and the compiler reinstalled), toolID returns a different string, so that old // package archives look stale and are rebuilt (with the fixed compiler). // This suggests using a content hash of the tool binary, as stored in the build ID. // // Unfortunately, we can't just open the tool binary, because the tool might be // invoked via a wrapper program specified by -toolexec and we don't know // what the wrapper program does. In particular, we want "-toolexec toolstash" // to continue working: it does no good if "-toolexec toolstash" is executing a // stashed copy of the compiler but the go command is acting as if it will run // the standard copy of the compiler. The solution is to ask the tool binary to tell // us its own build ID using the "-V=full" flag now supported by all tools. // Then we know we're getting the build ID of the compiler that will actually run // during the build. (How does the compiler binary know its own content hash? // We store it there using updateBuildID after the standard link step.) // // A final twist is that we'd prefer to have reproducible builds for release toolchains. // It should be possible to cross-compile for Windows from either Linux or Mac // or Windows itself and produce the same binaries, bit for bit. If the tool ID, // which influences the action ID half of the build ID, is based on the content ID, // then the Linux compiler binary and Mac compiler binary will have different tool IDs // and therefore produce executables with different action IDs. // To avoids this problem, for releases we use the release version string instead // of the compiler binary's content hash. This assumes that all compilers built // on all different systems are semantically equivalent, which is of course only true // modulo bugs. (Producing the exact same executables also requires that the different // build setups agree on details like $GOROOT and file name paths, but at least the // tool IDs do not make it impossible.) func (b *Builder) toolID(name string) string { if name == "vet" && oldVet { return "" } b.id.Lock() id := b.toolIDCache[name] b.id.Unlock() if id != "" { return id } path := base.Tool(name) desc := "go tool " + name // Special case: undocumented -vettool overrides usual vet, for testing vet. if name == "vet" && VetTool != "" { path = VetTool desc = VetTool } cmdline := str.StringList(cfg.BuildToolexec, path, "-V=full") cmd := exec.Command(cmdline[0], cmdline[1:]...) cmd.Env = base.EnvForDir(cmd.Dir, os.Environ()) var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr if err := cmd.Run(); err != nil { if name == "vet" { oldVet = true return "" } base.Fatalf("%s: %v\n%s%s", desc, err, stdout.Bytes(), stderr.Bytes()) } line := stdout.String() f := strings.Fields(line) if len(f) < 3 || f[0] != name && path != VetTool || f[1] != "version" || f[2] == "devel" && !strings.HasPrefix(f[len(f)-1], "buildID=") { base.Fatalf("%s -V=full: unexpected output:\n\t%s", desc, line) } if f[2] == "devel" { // On the development branch, use the content ID part of the build ID. id = contentID(f[len(f)-1]) } else { // For a release, the output is like: "compile version go1.9.1". Use the whole line. id = f[2] } b.id.Lock() b.toolIDCache[name] = id b.id.Unlock() return id } // gccToolID returns the unique ID to use for a tool that is invoked // by the GCC driver. This is in particular gccgo, but this can also // be used for gcc, g++, gfortran, etc.; those tools all use the GCC // driver under different names. The approach used here should also // work for sufficiently new versions of clang. Unlike toolID, the // name argument is the program to run. The language argument is the // type of input file as passed to the GCC driver's -x option. // // For these tools we have no -V=full option to dump the build ID, // but we can run the tool with -v -### to reliably get the compiler proper // and hash that. That will work in the presence of -toolexec. // // In order to get reproducible builds for released compilers, we // detect a released compiler by the absence of "experimental" in the // --version output, and in that case we just use the version string. func (b *Builder) gccgoToolID(name, language string) (string, error) { key := name + "." + language b.id.Lock() id := b.toolIDCache[key] b.id.Unlock() if id != "" { return id, nil } // Invoke the driver with -### to see the subcommands and the // version strings. Use -x to set the language. Pretend to // compile an empty file on standard input. cmdline := str.StringList(cfg.BuildToolexec, name, "-###", "-x", language, "-c", "-") cmd := exec.Command(cmdline[0], cmdline[1:]...) cmd.Env = base.EnvForDir(cmd.Dir, os.Environ()) // Force untranslated output so that we see the string "version". cmd.Env = append(cmd.Env, "LC_ALL=C") out, err := cmd.CombinedOutput() if err != nil { return "", fmt.Errorf("%s: %v; output: %q", name, err, out) } version := "" lines := strings.Split(string(out), "\n") for _, line := range lines { if fields := strings.Fields(line); len(fields) > 1 && fields[1] == "version" { version = line break } } if version == "" { return "", fmt.Errorf("%s: can not find version number in %q", name, out) } if !strings.Contains(version, "experimental") { // This is a release. Use this line as the tool ID. id = version } else { // This is a development version. The first line with // a leading space is the compiler proper. compiler := "" for _, line := range lines { if len(line) > 1 && line[0] == ' ' { compiler = line break } } if compiler == "" { return "", fmt.Errorf("%s: can not find compilation command in %q", name, out) } fields := strings.Fields(compiler) if len(fields) == 0 { return "", fmt.Errorf("%s: compilation command confusion %q", name, out) } exe := fields[0] if !strings.ContainsAny(exe, `/\`) { if lp, err := exec.LookPath(exe); err == nil { exe = lp } } if _, err := os.Stat(exe); err != nil { return "", fmt.Errorf("%s: can not find compiler %q: %v; output %q", name, exe, err, out) } id = b.fileHash(exe) } b.id.Lock() b.toolIDCache[name] = id b.id.Unlock() return id, nil } // Check if assembler used by gccgo is GNU as. func assemblerIsGas() bool { cmd := exec.Command(BuildToolchain.compiler(), "-print-prog-name=as") assembler, err := cmd.Output() if err == nil { cmd := exec.Command(strings.TrimSpace(string(assembler)), "--version") out, err := cmd.Output() return err == nil && strings.Contains(string(out), "GNU") } else { return false } } // gccgoBuildIDELFFile creates an assembler file that records the // action's build ID in an SHF_EXCLUDE section. func (b *Builder) gccgoBuildIDELFFile(a *Action) (string, error) { sfile := a.Objdir + "_buildid.s" var buf bytes.Buffer if cfg.Goos != "solaris" || assemblerIsGas() { fmt.Fprintf(&buf, "\t"+`.section .go.buildid,"e"`+"\n") } else if cfg.Goarch == "sparc" || cfg.Goarch == "sparc64" { fmt.Fprintf(&buf, "\t"+`.section ".go.buildid",#exclude`+"\n") } else { // cfg.Goarch == "386" || cfg.Goarch == "amd64" fmt.Fprintf(&buf, "\t"+`.section .go.buildid,#exclude`+"\n") } fmt.Fprintf(&buf, "\t.byte ") for i := 0; i < len(a.buildID); i++ { if i > 0 { if i%8 == 0 { fmt.Fprintf(&buf, "\n\t.byte ") } else { fmt.Fprintf(&buf, ",") } } fmt.Fprintf(&buf, "%#02x", a.buildID[i]) } fmt.Fprintf(&buf, "\n") if cfg.Goos != "solaris" { fmt.Fprintf(&buf, "\t"+`.section .note.GNU-stack,"",@progbits`+"\n") fmt.Fprintf(&buf, "\t"+`.section .note.GNU-split-stack,"",@progbits`+"\n") } if cfg.BuildN || cfg.BuildX { for _, line := range bytes.Split(buf.Bytes(), []byte("\n")) { b.Showcmd("", "echo '%s' >> %s", line, sfile) } if cfg.BuildN { return sfile, nil } } if err := ioutil.WriteFile(sfile, buf.Bytes(), 0666); err != nil { return "", err } return sfile, nil } // buildID returns the build ID found in the given file. // If no build ID is found, buildID returns the content hash of the file. func (b *Builder) buildID(file string) string { b.id.Lock() id := b.buildIDCache[file] b.id.Unlock() if id != "" { return id } id, err := buildid.ReadFile(file) if err != nil { id = b.fileHash(file) } b.id.Lock() b.buildIDCache[file] = id b.id.Unlock() return id } // fileHash returns the content hash of the named file. func (b *Builder) fileHash(file string) string { sum, err := cache.FileHash(file) if err != nil { return "" } return hashToString(sum) } // useCache tries to satisfy the action a, which has action ID actionHash, // by using a cached result from an earlier build. At the moment, the only // cached result is the installed package or binary at target. // If useCache decides that the cache can be used, it sets a.buildID // and a.built for use by parent actions and then returns true. // Otherwise it sets a.buildID to a temporary build ID for use in the build // and returns false. When useCache returns false the expectation is that // the caller will build the target and then call updateBuildID to finish the // build ID computation. // When useCache returns false, it may have initiated buffering of output // during a's work. The caller should defer b.flushOutput(a), to make sure // that flushOutput is eventually called regardless of whether the action // succeeds. The flushOutput call must happen after updateBuildID. func (b *Builder) useCache(a *Action, p *load.Package, actionHash cache.ActionID, target string) bool { // The second half of the build ID here is a placeholder for the content hash. // It's important that the overall buildID be unlikely verging on impossible // to appear in the output by chance, but that should be taken care of by // the actionID half; if it also appeared in the input that would be like an // engineered 96-bit partial SHA256 collision. a.actionID = actionHash actionID := hashToString(actionHash) contentID := actionID // temporary placeholder, likely unique a.buildID = actionID + buildIDSeparator + contentID // Executable binaries also record the main build ID in the middle. // See "Build IDs" comment above. if a.Mode == "link" { mainpkg := a.Deps[0] a.buildID = actionID + buildIDSeparator + mainpkg.buildID + buildIDSeparator + contentID } // Check to see if target exists and matches the expected action ID. // If so, it's up to date and we can reuse it instead of rebuilding it. var buildID string if target != "" && !cfg.BuildA { buildID, _ = buildid.ReadFile(target) if strings.HasPrefix(buildID, actionID+buildIDSeparator) { a.buildID = buildID a.built = target // Poison a.Target to catch uses later in the build. a.Target = "DO NOT USE - " + a.Mode return true } } // Special case for building a main package: if the only thing we // want the package for is to link a binary, and the binary is // already up-to-date, then to avoid a rebuild, report the package // as up-to-date as well. See "Build IDs" comment above. // TODO(rsc): Rewrite this code to use a TryCache func on the link action. if target != "" && !cfg.BuildA && !b.NeedExport && a.Mode == "build" && len(a.triggers) == 1 && a.triggers[0].Mode == "link" { buildID, err := buildid.ReadFile(target) if err == nil { id := strings.Split(buildID, buildIDSeparator) if len(id) == 4 && id[1] == actionID { // Temporarily assume a.buildID is the package build ID // stored in the installed binary, and see if that makes // the upcoming link action ID a match. If so, report that // we built the package, safe in the knowledge that the // link step will not ask us for the actual package file. // Note that (*Builder).LinkAction arranged that all of // a.triggers[0]'s dependencies other than a are also // dependencies of a, so that we can be sure that, // other than a.buildID, b.linkActionID is only accessing // build IDs of completed actions. oldBuildID := a.buildID a.buildID = id[1] + buildIDSeparator + id[2] linkID := hashToString(b.linkActionID(a.triggers[0])) if id[0] == linkID { // Best effort attempt to display output from the compile and link steps. // If it doesn't work, it doesn't work: reusing the cached binary is more // important than reprinting diagnostic information. if c := cache.Default(); c != nil { showStdout(b, c, a.actionID, "stdout") // compile output showStdout(b, c, a.actionID, "link-stdout") // link output } // Poison a.Target to catch uses later in the build. a.Target = "DO NOT USE - main build pseudo-cache Target" a.built = "DO NOT USE - main build pseudo-cache built" return true } // Otherwise restore old build ID for main build. a.buildID = oldBuildID } } } // Special case for linking a test binary: if the only thing we // want the binary for is to run the test, and the test result is cached, // then to avoid the link step, report the link as up-to-date. // We avoid the nested build ID problem in the previous special case // by recording the test results in the cache under the action ID half. if !cfg.BuildA && len(a.triggers) == 1 && a.triggers[0].TryCache != nil && a.triggers[0].TryCache(b, a.triggers[0]) { // Best effort attempt to display output from the compile and link steps. // If it doesn't work, it doesn't work: reusing the test result is more // important than reprinting diagnostic information. if c := cache.Default(); c != nil { showStdout(b, c, a.Deps[0].actionID, "stdout") // compile output showStdout(b, c, a.Deps[0].actionID, "link-stdout") // link output } // Poison a.Target to catch uses later in the build. a.Target = "DO NOT USE - pseudo-cache Target" a.built = "DO NOT USE - pseudo-cache built" return true } if b.IsCmdList { // Invoked during go list to compute and record staleness. if p := a.Package; p != nil && !p.Stale { p.Stale = true if cfg.BuildA { p.StaleReason = "build -a flag in use" } else { p.StaleReason = "build ID mismatch" for _, p1 := range p.Internal.Imports { if p1.Stale && p1.StaleReason != "" { if strings.HasPrefix(p1.StaleReason, "stale dependency: ") { p.StaleReason = p1.StaleReason break } if strings.HasPrefix(p.StaleReason, "build ID mismatch") { p.StaleReason = "stale dependency: " + p1.ImportPath } } } } } // Fall through to update a.buildID from the build artifact cache, // which will affect the computation of buildIDs for targets // higher up in the dependency graph. } // Check the build artifact cache. // We treat hits in this cache as being "stale" for the purposes of go list // (in effect, "stale" means whether p.Target is up-to-date), // but we're still happy to use results from the build artifact cache. if c := cache.Default(); c != nil { if !cfg.BuildA { if file, _, err := c.GetFile(actionHash); err == nil { if buildID, err := buildid.ReadFile(file); err == nil { if err := showStdout(b, c, a.actionID, "stdout"); err == nil { a.built = file a.Target = "DO NOT USE - using cache" a.buildID = buildID if p := a.Package; p != nil { // Clearer than explaining that something else is stale. p.StaleReason = "not installed but available in build cache" } return true } } } } // Begin saving output for later writing to cache. a.output = []byte{} } return false } func showStdout(b *Builder, c *cache.Cache, actionID cache.ActionID, key string) error { stdout, stdoutEntry, err := c.GetBytes(cache.Subkey(actionID, key)) if err != nil { return err } if len(stdout) > 0 { if cfg.BuildX || cfg.BuildN { b.Showcmd("", "%s # internal", joinUnambiguously(str.StringList("cat", c.OutputFile(stdoutEntry.OutputID)))) } if !cfg.BuildN { b.Print(string(stdout)) } } return nil } // flushOutput flushes the output being queued in a. func (b *Builder) flushOutput(a *Action) { b.Print(string(a.output)) a.output = nil } // updateBuildID updates the build ID in the target written by action a. // It requires that useCache was called for action a and returned false, // and that the build was then carried out and given the temporary // a.buildID to record as the build ID in the resulting package or binary. // updateBuildID computes the final content ID and updates the build IDs // in the binary. // // Keep in sync with src/cmd/buildid/buildid.go func (b *Builder) updateBuildID(a *Action, target string, rewrite bool) error { if cfg.BuildX || cfg.BuildN { if rewrite { b.Showcmd("", "%s # internal", joinUnambiguously(str.StringList(base.Tool("buildid"), "-w", target))) } if cfg.BuildN { return nil } } // Cache output from compile/link, even if we don't do the rest. if c := cache.Default(); c != nil { switch a.Mode { case "build": c.PutBytes(cache.Subkey(a.actionID, "stdout"), a.output) case "link": // Even though we don't cache the binary, cache the linker text output. // We might notice that an installed binary is up-to-date but still // want to pretend to have run the linker. // Store it under the main package's action ID // to make it easier to find when that's all we have. for _, a1 := range a.Deps { if p1 := a1.Package; p1 != nil && p1.Name == "main" { c.PutBytes(cache.Subkey(a1.actionID, "link-stdout"), a.output) break } } } } // Find occurrences of old ID and compute new content-based ID. r, err := os.Open(target) if err != nil { return err } matches, hash, err := buildid.FindAndHash(r, a.buildID, 0) r.Close() if err != nil { return err } newID := a.buildID[:strings.LastIndex(a.buildID, buildIDSeparator)] + buildIDSeparator + hashToString(hash) if len(newID) != len(a.buildID) { return fmt.Errorf("internal error: build ID length mismatch %q vs %q", a.buildID, newID) } // Replace with new content-based ID. a.buildID = newID if len(matches) == 0 { // Assume the user specified -buildid= to override what we were going to choose. return nil } if rewrite { w, err := os.OpenFile(target, os.O_WRONLY, 0) if err != nil { return err } err = buildid.Rewrite(w, matches, newID) if err != nil { w.Close() return err } if err := w.Close(); err != nil { return err } } // Cache package builds, but not binaries (link steps). // The expectation is that binaries are not reused // nearly as often as individual packages, and they're // much larger, so the cache-footprint-to-utility ratio // of binaries is much lower for binaries. // Not caching the link step also makes sure that repeated "go run" at least // always rerun the linker, so that they don't get too fast. // (We don't want people thinking go is a scripting language.) // Note also that if we start caching binaries, then we will // copy the binaries out of the cache to run them, and then // that will mean the go process is itself writing a binary // and then executing it, so we will need to defend against // ETXTBSY problems as discussed in exec.go and golang.org/issue/22220. if c := cache.Default(); c != nil && a.Mode == "build" { r, err := os.Open(target) if err == nil { if a.output == nil { panic("internal error: a.output not set") } outputID, _, err := c.Put(a.actionID, r) r.Close() if err == nil && cfg.BuildX { b.Showcmd("", "%s # internal", joinUnambiguously(str.StringList("cp", target, c.OutputFile(outputID)))) } if b.NeedExport { if err != nil { return err } a.Package.Export = c.OutputFile(outputID) } } } return nil }
work
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/work/build_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 work import ( "bytes" "fmt" "io/ioutil" "os" "path/filepath" "reflect" "runtime" "strings" "testing" "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/load" ) func TestRemoveDevNull(t *testing.T) { fi, err := os.Lstat(os.DevNull) if err != nil { t.Skip(err) } if fi.Mode().IsRegular() { t.Errorf("Lstat(%s).Mode().IsRegular() = true; expected false", os.DevNull) } mayberemovefile(os.DevNull) _, err = os.Lstat(os.DevNull) if err != nil { t.Errorf("mayberemovefile(%s) did remove it; oops", os.DevNull) } } func TestSplitPkgConfigOutput(t *testing.T) { for _, test := range []struct { in []byte want []string }{ {[]byte(`-r:foo -L/usr/white\ space/lib -lfoo\ bar -lbar\ baz`), []string{"-r:foo", "-L/usr/white space/lib", "-lfoo bar", "-lbar baz"}}, {[]byte(`-lextra\ fun\ arg\\`), []string{`-lextra fun arg\`}}, {[]byte("\textra whitespace\r\n"), []string{"extra", "whitespace"}}, {[]byte(" \r\n "), nil}, {[]byte(`"-r:foo" "-L/usr/white space/lib" "-lfoo bar" "-lbar baz"`), []string{"-r:foo", "-L/usr/white space/lib", "-lfoo bar", "-lbar baz"}}, {[]byte(`"-lextra fun arg\\"`), []string{`-lextra fun arg\`}}, {[]byte(`" \r\n\ "`), []string{` \r\n\ `}}, {[]byte(`""`), nil}, {[]byte(``), nil}, {[]byte(`"\\"`), []string{`\`}}, {[]byte(`"\x"`), []string{`\x`}}, {[]byte(`"\\x"`), []string{`\x`}}, {[]byte(`'\\'`), []string{`\`}}, {[]byte(`'\x'`), []string{`\x`}}, {[]byte(`"\\x"`), []string{`\x`}}, {[]byte(`-fPIC -I/test/include/foo -DQUOTED='"/test/share/doc"'`), []string{"-fPIC", "-I/test/include/foo", `-DQUOTED="/test/share/doc"`}}, {[]byte(`-fPIC -I/test/include/foo -DQUOTED="/test/share/doc"`), []string{"-fPIC", "-I/test/include/foo", "-DQUOTED=/test/share/doc"}}, {[]byte(`-fPIC -I/test/include/foo -DQUOTED=\"/test/share/doc\"`), []string{"-fPIC", "-I/test/include/foo", `-DQUOTED="/test/share/doc"`}}, {[]byte(`-fPIC -I/test/include/foo -DQUOTED='/test/share/doc'`), []string{"-fPIC", "-I/test/include/foo", "-DQUOTED=/test/share/doc"}}, {[]byte(`-DQUOTED='/te\st/share/d\oc'`), []string{`-DQUOTED=/te\st/share/d\oc`}}, {[]byte(`-Dhello=10 -Dworld=+32 -DDEFINED_FROM_PKG_CONFIG=hello\ world`), []string{"-Dhello=10", "-Dworld=+32", "-DDEFINED_FROM_PKG_CONFIG=hello world"}}, {[]byte(`"broken\"" \\\a "a"`), []string{"broken\"", "\\a", "a"}}, } { got, err := splitPkgConfigOutput(test.in) if err != nil { t.Errorf("splitPkgConfigOutput on %v failed with error %v", test.in, err) continue } if !reflect.DeepEqual(got, test.want) { t.Errorf("splitPkgConfigOutput(%v) = %v; want %v", test.in, got, test.want) } } for _, test := range []struct { in []byte want []string }{ // broken quotation {[]byte(`" \r\n `), nil}, {[]byte(`"-r:foo" "-L/usr/white space/lib "-lfoo bar" "-lbar baz"`), nil}, {[]byte(`"-lextra fun arg\\`), nil}, // broken char escaping {[]byte(`broken flag\`), nil}, {[]byte(`extra broken flag \`), nil}, {[]byte(`\`), nil}, {[]byte(`"broken\"" "extra" \`), nil}, } { got, err := splitPkgConfigOutput(test.in) if err == nil { t.Errorf("splitPkgConfigOutput(%v) = %v; haven't failed with error as expected.", test.in, got) } if !reflect.DeepEqual(got, test.want) { t.Errorf("splitPkgConfigOutput(%v) = %v; want %v", test.in, got, test.want) } } } func TestSharedLibName(t *testing.T) { // TODO(avdva) - make these values platform-specific prefix := "lib" suffix := ".so" testData := []struct { args []string pkgs []*load.Package expected string expectErr bool rootedAt string }{ { args: []string{"std"}, pkgs: []*load.Package{}, expected: "std", }, { args: []string{"std", "cmd"}, pkgs: []*load.Package{}, expected: "std,cmd", }, { args: []string{}, pkgs: []*load.Package{pkgImportPath("gopkg.in/somelib")}, expected: "gopkg.in-somelib", }, { args: []string{"./..."}, pkgs: []*load.Package{pkgImportPath("somelib")}, expected: "somelib", rootedAt: "somelib", }, { args: []string{"../somelib", "../somelib"}, pkgs: []*load.Package{pkgImportPath("somelib")}, expected: "somelib", }, { args: []string{"../lib1", "../lib2"}, pkgs: []*load.Package{pkgImportPath("gopkg.in/lib1"), pkgImportPath("gopkg.in/lib2")}, expected: "gopkg.in-lib1,gopkg.in-lib2", }, { args: []string{"./..."}, pkgs: []*load.Package{ pkgImportPath("gopkg.in/dir/lib1"), pkgImportPath("gopkg.in/lib2"), pkgImportPath("gopkg.in/lib3"), }, expected: "gopkg.in", rootedAt: "gopkg.in", }, { args: []string{"std", "../lib2"}, pkgs: []*load.Package{}, expectErr: true, }, { args: []string{"all", "./"}, pkgs: []*load.Package{}, expectErr: true, }, { args: []string{"cmd", "fmt"}, pkgs: []*load.Package{}, expectErr: true, }, } for _, data := range testData { func() { if data.rootedAt != "" { tmpGopath, err := ioutil.TempDir("", "gopath") if err != nil { t.Fatal(err) } oldGopath := cfg.BuildContext.GOPATH defer func() { cfg.BuildContext.GOPATH = oldGopath os.Chdir(base.Cwd) err := os.RemoveAll(tmpGopath) if err != nil { t.Error(err) } }() root := filepath.Join(tmpGopath, "src", data.rootedAt) err = os.MkdirAll(root, 0755) if err != nil { t.Fatal(err) } cfg.BuildContext.GOPATH = tmpGopath os.Chdir(root) } computed, err := libname(data.args, data.pkgs) if err != nil { if !data.expectErr { t.Errorf("libname returned an error %q, expected a name", err.Error()) } } else if data.expectErr { t.Errorf("libname returned %q, expected an error", computed) } else { expected := prefix + data.expected + suffix if expected != computed { t.Errorf("libname returned %q, expected %q", computed, expected) } } }() } } func pkgImportPath(pkgpath string) *load.Package { return &load.Package{ PackagePublic: load.PackagePublic{ ImportPath: pkgpath, }, } } // When installing packages, the installed package directory should // respect the SetGID bit and group name of the destination // directory. // See https://golang.org/issue/18878. func TestRespectSetgidDir(t *testing.T) { switch runtime.GOOS { case "nacl": t.Skip("can't set SetGID bit with chmod on nacl") case "darwin": if runtime.GOARCH == "arm" || runtime.GOARCH == "arm64" { t.Skip("can't set SetGID bit with chmod on iOS") } } var b Builder // Check that `cp` is called instead of `mv` by looking at the output // of `(*Builder).ShowCmd` afterwards as a sanity check. cfg.BuildX = true var cmdBuf bytes.Buffer b.Print = func(a ...interface{}) (int, error) { return cmdBuf.WriteString(fmt.Sprint(a...)) } setgiddir, err := ioutil.TempDir("", "SetGroupID") if err != nil { t.Fatal(err) } defer os.RemoveAll(setgiddir) if runtime.GOOS == "freebsd" { err = os.Chown(setgiddir, os.Getuid(), os.Getgid()) if err != nil { t.Fatal(err) } } // Change setgiddir's permissions to include the SetGID bit. if err := os.Chmod(setgiddir, 0755|os.ModeSetgid); err != nil { t.Fatal(err) } pkgfile, err := ioutil.TempFile("", "pkgfile") if err != nil { t.Fatalf("ioutil.TempFile(\"\", \"pkgfile\"): %v", err) } defer os.Remove(pkgfile.Name()) defer pkgfile.Close() dirGIDFile := filepath.Join(setgiddir, "setgid") if err := b.moveOrCopyFile(dirGIDFile, pkgfile.Name(), 0666, true); err != nil { t.Fatalf("moveOrCopyFile: %v", err) } got := strings.TrimSpace(cmdBuf.String()) want := b.fmtcmd("", "cp %s %s", pkgfile.Name(), dirGIDFile) if got != want { t.Fatalf("moveOrCopyFile(%q, %q): want %q, got %q", dirGIDFile, pkgfile.Name(), want, got) } }
work
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/work/exec.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. // Action graph execution. package work import ( "bytes" "encoding/json" "errors" "fmt" "io" "io/ioutil" "log" "math/rand" "os" "os/exec" "path/filepath" "regexp" "runtime" "strconv" "strings" "sync" "time" "cmd/go/internal/base" "cmd/go/internal/cache" "cmd/go/internal/cfg" "cmd/go/internal/load" "cmd/go/internal/str" ) // actionList returns the list of actions in the dag rooted at root // as visited in a depth-first post-order traversal. func actionList(root *Action) []*Action { seen := map[*Action]bool{} all := []*Action{} var walk func(*Action) walk = func(a *Action) { if seen[a] { return } seen[a] = true for _, a1 := range a.Deps { walk(a1) } all = append(all, a) } walk(root) return all } // do runs the action graph rooted at root. func (b *Builder) Do(root *Action) { if c := cache.Default(); c != nil && !b.IsCmdList { // If we're doing real work, take time at the end to trim the cache. defer c.Trim() } // Build list of all actions, assigning depth-first post-order priority. // The original implementation here was a true queue // (using a channel) but it had the effect of getting // distracted by low-level leaf actions to the detriment // of completing higher-level actions. The order of // work does not matter much to overall execution time, // but when running "go test std" it is nice to see each test // results as soon as possible. The priorities assigned // ensure that, all else being equal, the execution prefers // to do what it would have done first in a simple depth-first // dependency order traversal. all := actionList(root) for i, a := range all { a.priority = i } if cfg.DebugActiongraph != "" { js := actionGraphJSON(root) if err := ioutil.WriteFile(cfg.DebugActiongraph, []byte(js), 0666); err != nil { fmt.Fprintf(os.Stderr, "go: writing action graph: %v\n", err) base.SetExitStatus(1) } } b.readySema = make(chan bool, len(all)) // Initialize per-action execution state. for _, a := range all { for _, a1 := range a.Deps { a1.triggers = append(a1.triggers, a) } a.pending = len(a.Deps) if a.pending == 0 { b.ready.push(a) b.readySema <- true } } // Handle runs a single action and takes care of triggering // any actions that are runnable as a result. handle := func(a *Action) { var err error if a.Func != nil && (!a.Failed || a.IgnoreFail) { if err == nil { err = a.Func(b, a) } } // The actions run in parallel but all the updates to the // shared work state are serialized through b.exec. b.exec.Lock() defer b.exec.Unlock() if err != nil { if err == errPrintedOutput { base.SetExitStatus(2) } else { base.Errorf("%s", err) } a.Failed = true } for _, a0 := range a.triggers { if a.Failed { a0.Failed = true } if a0.pending--; a0.pending == 0 { b.ready.push(a0) b.readySema <- true } } if a == root { close(b.readySema) } } var wg sync.WaitGroup // Kick off goroutines according to parallelism. // If we are using the -n flag (just printing commands) // drop the parallelism to 1, both to make the output // deterministic and because there is no real work anyway. par := cfg.BuildP if cfg.BuildN { par = 1 } for i := 0; i < par; i++ { wg.Add(1) go func() { defer wg.Done() for { select { case _, ok := <-b.readySema: if !ok { return } // Receiving a value from b.readySema entitles // us to take from the ready queue. b.exec.Lock() a := b.ready.pop() b.exec.Unlock() handle(a) case <-base.Interrupted: base.SetExitStatus(1) return } } }() } wg.Wait() } // buildActionID computes the action ID for a build action. func (b *Builder) buildActionID(a *Action) cache.ActionID { p := a.Package h := cache.NewHash("build " + p.ImportPath) // Configuration independent of compiler toolchain. // Note: buildmode has already been accounted for in buildGcflags // and should not be inserted explicitly. Most buildmodes use the // same compiler settings and can reuse each other's results. // If not, the reason is already recorded in buildGcflags. fmt.Fprintf(h, "compile\n") // The compiler hides the exact value of $GOROOT // when building things in GOROOT, // but it does not hide the exact value of $GOPATH. // Include the full dir in that case. // Assume b.WorkDir is being trimmed properly. if !p.Goroot && !strings.HasPrefix(p.Dir, b.WorkDir) { fmt.Fprintf(h, "dir %s\n", p.Dir) } fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch) fmt.Fprintf(h, "import %q\n", p.ImportPath) fmt.Fprintf(h, "omitdebug %v standard %v local %v prefix %q\n", p.Internal.OmitDebug, p.Standard, p.Internal.Local, p.Internal.LocalPrefix) if p.Internal.ForceLibrary { fmt.Fprintf(h, "forcelibrary\n") } if len(p.CgoFiles)+len(p.SwigFiles) > 0 { fmt.Fprintf(h, "cgo %q\n", b.toolID("cgo")) cppflags, cflags, cxxflags, fflags, ldflags, _ := b.CFlags(p) fmt.Fprintf(h, "CC=%q %q %q %q\n", b.ccExe(), cppflags, cflags, ldflags) if len(p.CXXFiles)+len(p.SwigFiles) > 0 { fmt.Fprintf(h, "CXX=%q %q\n", b.cxxExe(), cxxflags) } if len(p.FFiles) > 0 { fmt.Fprintf(h, "FC=%q %q\n", b.fcExe(), fflags) } // TODO(rsc): Should we include the SWIG version or Fortran/GCC/G++/Objective-C compiler versions? } if p.Internal.CoverMode != "" { fmt.Fprintf(h, "cover %q %q\n", p.Internal.CoverMode, b.toolID("cover")) } // Configuration specific to compiler toolchain. switch cfg.BuildToolchainName { default: base.Fatalf("buildActionID: unknown build toolchain %q", cfg.BuildToolchainName) case "gc": fmt.Fprintf(h, "compile %s %q %q\n", b.toolID("compile"), forcedGcflags, p.Internal.Gcflags) if len(p.SFiles) > 0 { fmt.Fprintf(h, "asm %q %q %q\n", b.toolID("asm"), forcedAsmflags, p.Internal.Asmflags) } fmt.Fprintf(h, "GO$GOARCH=%s\n", os.Getenv("GO"+strings.ToUpper(cfg.BuildContext.GOARCH))) // GO386, GOARM, etc // TODO(rsc): Convince compiler team not to add more magic environment variables, // or perhaps restrict the environment variables passed to subprocesses. magic := []string{ "GOCLOBBERDEADHASH", "GOSSAFUNC", "GO_SSA_PHI_LOC_CUTOFF", "GOSSAHASH", } for _, env := range magic { if x := os.Getenv(env); x != "" { fmt.Fprintf(h, "magic %s=%s\n", env, x) } } if os.Getenv("GOSSAHASH") != "" { for i := 0; ; i++ { env := fmt.Sprintf("GOSSAHASH%d", i) x := os.Getenv(env) if x == "" { break } fmt.Fprintf(h, "magic %s=%s\n", env, x) } } if os.Getenv("GSHS_LOGFILE") != "" { // Clumsy hack. Compiler writes to this log file, // so do not allow use of cache at all. // We will still write to the cache but it will be // essentially unfindable. fmt.Fprintf(h, "nocache %d\n", time.Now().UnixNano()) } case "gccgo": id, err := b.gccgoToolID(BuildToolchain.compiler(), "go") if err != nil { base.Fatalf("%v", err) } fmt.Fprintf(h, "compile %s %q %q\n", id, forcedGccgoflags, p.Internal.Gccgoflags) fmt.Fprintf(h, "pkgpath %s\n", gccgoPkgpath(p)) if len(p.SFiles) > 0 { id, err = b.gccgoToolID(BuildToolchain.compiler(), "assembler-with-cpp") // Ignore error; different assembler versions // are unlikely to make any difference anyhow. fmt.Fprintf(h, "asm %q\n", id) } } // Input files. inputFiles := str.StringList( p.GoFiles, p.CgoFiles, p.CFiles, p.CXXFiles, p.FFiles, p.MFiles, p.HFiles, p.SFiles, p.SysoFiles, p.SwigFiles, p.SwigCXXFiles, ) for _, file := range inputFiles { fmt.Fprintf(h, "file %s %s\n", file, b.fileHash(filepath.Join(p.Dir, file))) } for _, a1 := range a.Deps { p1 := a1.Package if p1 != nil { fmt.Fprintf(h, "import %s %s\n", p1.ImportPath, contentID(a1.buildID)) } } return h.Sum() } // needCgoHdr reports whether the actions triggered by this one // expect to be able to access the cgo-generated header file. func (b *Builder) needCgoHdr(a *Action) bool { // If this build triggers a header install, run cgo to get the header. if !b.IsCmdList && (a.Package.UsesCgo() || a.Package.UsesSwig()) && (cfg.BuildBuildmode == "c-archive" || cfg.BuildBuildmode == "c-shared") { for _, t1 := range a.triggers { if t1.Mode == "install header" { return true } } for _, t1 := range a.triggers { for _, t2 := range t1.triggers { if t2.Mode == "install header" { return true } } } } return false } // allowedVersion reports whether the version v is an allowed version of go // (one that we can compile). // v is known to be of the form "1.23". func allowedVersion(v string) bool { // Special case: no requirement. if v == "" { return true } // Special case "1.0" means "go1", which is OK. if v == "1.0" { return true } // Otherwise look through release tags of form "go1.23" for one that matches. for _, tag := range cfg.BuildContext.ReleaseTags { if strings.HasPrefix(tag, "go") && tag[2:] == v { return true } } return false } const ( needBuild uint32 = 1 << iota needCgoHdr needVet needCompiledGoFiles needStale ) // build is the action for building a single package. // Note that any new influence on this logic must be reported in b.buildActionID above as well. func (b *Builder) build(a *Action) (err error) { p := a.Package bit := func(x uint32, b bool) uint32 { if b { return x } return 0 } cached := false need := bit(needBuild, !b.IsCmdList || b.NeedExport) | bit(needCgoHdr, b.needCgoHdr(a)) | bit(needVet, a.needVet) | bit(needCompiledGoFiles, b.NeedCompiledGoFiles) if !p.BinaryOnly { if b.useCache(a, p, b.buildActionID(a), p.Target) { // We found the main output in the cache. // If we don't need any other outputs, we can stop. need &^= needBuild if b.NeedExport { p.Export = a.built } if need&needCompiledGoFiles != 0 && b.loadCachedGoFiles(a) { need &^= needCompiledGoFiles } // Otherwise, we need to write files to a.Objdir (needVet, needCgoHdr). // Remember that we might have them in cache // and check again after we create a.Objdir. cached = true a.output = []byte{} // start saving output in case we miss any cache results } if need == 0 { return nil } defer b.flushOutput(a) } defer func() { if err != nil && err != errPrintedOutput { err = fmt.Errorf("go build %s: %v", a.Package.ImportPath, err) } if err != nil && b.IsCmdList && b.NeedError && p.Error == nil { p.Error = &load.PackageError{Err: err.Error()} } }() if cfg.BuildN { // In -n mode, print a banner between packages. // The banner is five lines so that when changes to // different sections of the bootstrap script have to // be merged, the banners give patch something // to use to find its context. b.Print("\n#\n# " + a.Package.ImportPath + "\n#\n\n") } if cfg.BuildV { b.Print(a.Package.ImportPath + "\n") } if a.Package.BinaryOnly { _, err := os.Stat(a.Package.Target) if err == nil { a.built = a.Package.Target a.Target = a.Package.Target if b.NeedExport { a.Package.Export = a.Package.Target } a.buildID = b.fileHash(a.Package.Target) a.Package.Stale = false a.Package.StaleReason = "binary-only package" return nil } a.Package.Stale = true a.Package.StaleReason = "missing or invalid binary-only package" if b.IsCmdList { return nil } return fmt.Errorf("missing or invalid binary-only package; expected file %q", a.Package.Target) } if p.Module != nil && !allowedVersion(p.Module.GoVersion) { return fmt.Errorf("module requires Go %s", p.Module.GoVersion) } if err := b.Mkdir(a.Objdir); err != nil { return err } objdir := a.Objdir if cached { if need&needCgoHdr != 0 && b.loadCachedCgoHdr(a) { need &^= needCgoHdr } // Load cached vet config, but only if that's all we have left // (need == needVet, not testing just the one bit). // If we are going to do a full build anyway, // we're going to regenerate the files below anyway. if need == needVet && b.loadCachedVet(a) { need &^= needVet } if need == 0 { return nil } } // make target directory dir, _ := filepath.Split(a.Target) if dir != "" { if err := b.Mkdir(dir); err != nil { return err } } gofiles := str.StringList(a.Package.GoFiles) cgofiles := str.StringList(a.Package.CgoFiles) cfiles := str.StringList(a.Package.CFiles) sfiles := str.StringList(a.Package.SFiles) cxxfiles := str.StringList(a.Package.CXXFiles) var objects, cgoObjects, pcCFLAGS, pcLDFLAGS []string if a.Package.UsesCgo() || a.Package.UsesSwig() { if pcCFLAGS, pcLDFLAGS, err = b.getPkgConfigFlags(a.Package); err != nil { return } } // Run SWIG on each .swig and .swigcxx file. // Each run will generate two files, a .go file and a .c or .cxx file. // The .go file will use import "C" and is to be processed by cgo. if a.Package.UsesSwig() { outGo, outC, outCXX, err := b.swig(a, a.Package, objdir, pcCFLAGS) if err != nil { return err } cgofiles = append(cgofiles, outGo...) cfiles = append(cfiles, outC...) cxxfiles = append(cxxfiles, outCXX...) } // If we're doing coverage, preprocess the .go files and put them in the work directory if a.Package.Internal.CoverMode != "" { for i, file := range str.StringList(gofiles, cgofiles) { var sourceFile string var coverFile string var key string if strings.HasSuffix(file, ".cgo1.go") { // cgo files have absolute paths base := filepath.Base(file) sourceFile = file coverFile = objdir + base key = strings.TrimSuffix(base, ".cgo1.go") + ".go" } else { sourceFile = filepath.Join(a.Package.Dir, file) coverFile = objdir + file key = file } coverFile = strings.TrimSuffix(coverFile, ".go") + ".cover.go" cover := a.Package.Internal.CoverVars[key] if cover == nil || base.IsTestFile(file) { // Not covering this file. continue } if err := b.cover(a, coverFile, sourceFile, cover.Var); err != nil { return err } if i < len(gofiles) { gofiles[i] = coverFile } else { cgofiles[i-len(gofiles)] = coverFile } } } // Run cgo. if a.Package.UsesCgo() || a.Package.UsesSwig() { // In a package using cgo, cgo compiles the C, C++ and assembly files with gcc. // There is one exception: runtime/cgo's job is to bridge the // cgo and non-cgo worlds, so it necessarily has files in both. // In that case gcc only gets the gcc_* files. var gccfiles []string gccfiles = append(gccfiles, cfiles...) cfiles = nil if a.Package.Standard && a.Package.ImportPath == "runtime/cgo" { filter := func(files, nongcc, gcc []string) ([]string, []string) { for _, f := range files { if strings.HasPrefix(f, "gcc_") { gcc = append(gcc, f) } else { nongcc = append(nongcc, f) } } return nongcc, gcc } sfiles, gccfiles = filter(sfiles, sfiles[:0], gccfiles) } else { for _, sfile := range sfiles { data, err := ioutil.ReadFile(filepath.Join(a.Package.Dir, sfile)) if err == nil { if bytes.HasPrefix(data, []byte("TEXT")) || bytes.Contains(data, []byte("\nTEXT")) || bytes.HasPrefix(data, []byte("DATA")) || bytes.Contains(data, []byte("\nDATA")) || bytes.HasPrefix(data, []byte("GLOBL")) || bytes.Contains(data, []byte("\nGLOBL")) { return fmt.Errorf("package using cgo has Go assembly file %s", sfile) } } } gccfiles = append(gccfiles, sfiles...) sfiles = nil } outGo, outObj, err := b.cgo(a, base.Tool("cgo"), objdir, pcCFLAGS, pcLDFLAGS, mkAbsFiles(a.Package.Dir, cgofiles), gccfiles, cxxfiles, a.Package.MFiles, a.Package.FFiles) if err != nil { return err } if cfg.BuildToolchainName == "gccgo" { cgoObjects = append(cgoObjects, a.Objdir+"_cgo_flags") } cgoObjects = append(cgoObjects, outObj...) gofiles = append(gofiles, outGo...) switch cfg.BuildBuildmode { case "c-archive", "c-shared": b.cacheCgoHdr(a) } } b.cacheGofiles(a, gofiles) // Running cgo generated the cgo header. need &^= needCgoHdr // Sanity check only, since Package.load already checked as well. if len(gofiles) == 0 { return &load.NoGoError{Package: a.Package} } // Prepare Go vet config if needed. if need&needVet != 0 { buildVetConfig(a, gofiles) need &^= needVet } if need&needCompiledGoFiles != 0 { if !b.loadCachedGoFiles(a) { return fmt.Errorf("failed to cache compiled Go files") } need &^= needCompiledGoFiles } if need == 0 { // Nothing left to do. return nil } // Prepare Go import config. // We start it off with a comment so it can't be empty, so icfg.Bytes() below is never nil. // It should never be empty anyway, but there have been bugs in the past that resulted // in empty configs, which then unfortunately turn into "no config passed to compiler", // and the compiler falls back to looking in pkg itself, which mostly works, // except when it doesn't. var icfg bytes.Buffer fmt.Fprintf(&icfg, "# import config\n") for i, raw := range a.Package.Internal.RawImports { final := a.Package.Imports[i] if final != raw { fmt.Fprintf(&icfg, "importmap %s=%s\n", raw, final) } } for _, a1 := range a.Deps { p1 := a1.Package if p1 == nil || p1.ImportPath == "" || a1.built == "" { continue } fmt.Fprintf(&icfg, "packagefile %s=%s\n", p1.ImportPath, a1.built) } if p.Internal.BuildInfo != "" && cfg.ModulesEnabled { if err := b.writeFile(objdir+"_gomod_.go", load.ModInfoProg(p.Internal.BuildInfo)); err != nil { return err } gofiles = append(gofiles, objdir+"_gomod_.go") } // Compile Go. objpkg := objdir + "_pkg_.a" ofile, out, err := BuildToolchain.gc(b, a, objpkg, icfg.Bytes(), len(sfiles) > 0, gofiles) if len(out) > 0 { b.showOutput(a, a.Package.Dir, a.Package.Desc(), b.processOutput(out)) if err != nil { return errPrintedOutput } } if err != nil { return err } if ofile != objpkg { objects = append(objects, ofile) } // Copy .h files named for goos or goarch or goos_goarch // to names using GOOS and GOARCH. // For example, defs_linux_amd64.h becomes defs_GOOS_GOARCH.h. _goos_goarch := "_" + cfg.Goos + "_" + cfg.Goarch _goos := "_" + cfg.Goos _goarch := "_" + cfg.Goarch for _, file := range a.Package.HFiles { name, ext := fileExtSplit(file) switch { case strings.HasSuffix(name, _goos_goarch): targ := file[:len(name)-len(_goos_goarch)] + "_GOOS_GOARCH." + ext if err := b.copyFile(objdir+targ, filepath.Join(a.Package.Dir, file), 0666, true); err != nil { return err } case strings.HasSuffix(name, _goarch): targ := file[:len(name)-len(_goarch)] + "_GOARCH." + ext if err := b.copyFile(objdir+targ, filepath.Join(a.Package.Dir, file), 0666, true); err != nil { return err } case strings.HasSuffix(name, _goos): targ := file[:len(name)-len(_goos)] + "_GOOS." + ext if err := b.copyFile(objdir+targ, filepath.Join(a.Package.Dir, file), 0666, true); err != nil { return err } } } for _, file := range cfiles { out := file[:len(file)-len(".c")] + ".o" if err := BuildToolchain.cc(b, a, objdir+out, file); err != nil { return err } objects = append(objects, out) } // Assemble .s files. if len(sfiles) > 0 { ofiles, err := BuildToolchain.asm(b, a, sfiles) if err != nil { return err } objects = append(objects, ofiles...) } // For gccgo on ELF systems, we write the build ID as an assembler file. // This lets us set the SHF_EXCLUDE flag. // This is read by readGccgoArchive in cmd/internal/buildid/buildid.go. if a.buildID != "" && cfg.BuildToolchainName == "gccgo" { switch cfg.Goos { case "android", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "solaris": asmfile, err := b.gccgoBuildIDELFFile(a) if err != nil { return err } ofiles, err := BuildToolchain.asm(b, a, []string{asmfile}) if err != nil { return err } objects = append(objects, ofiles...) } } // NOTE(rsc): On Windows, it is critically important that the // gcc-compiled objects (cgoObjects) be listed after the ordinary // objects in the archive. I do not know why this is. // https://golang.org/issue/2601 objects = append(objects, cgoObjects...) // Add system object files. for _, syso := range a.Package.SysoFiles { objects = append(objects, filepath.Join(a.Package.Dir, syso)) } // Pack into archive in objdir directory. // If the Go compiler wrote an archive, we only need to add the // object files for non-Go sources to the archive. // If the Go compiler wrote an archive and the package is entirely // Go sources, there is no pack to execute at all. if len(objects) > 0 { if err := BuildToolchain.pack(b, a, objpkg, objects); err != nil { return err } } if err := b.updateBuildID(a, objpkg, true); err != nil { return err } a.built = objpkg return nil } func (b *Builder) cacheObjdirFile(a *Action, c *cache.Cache, name string) error { f, err := os.Open(a.Objdir + name) if err != nil { return err } defer f.Close() _, _, err = c.Put(cache.Subkey(a.actionID, name), f) return err } func (b *Builder) findCachedObjdirFile(a *Action, c *cache.Cache, name string) (string, error) { file, _, err := c.GetFile(cache.Subkey(a.actionID, name)) if err != nil { return "", err } return file, nil } func (b *Builder) loadCachedObjdirFile(a *Action, c *cache.Cache, name string) error { cached, err := b.findCachedObjdirFile(a, c, name) if err != nil { return err } return b.copyFile(a.Objdir+name, cached, 0666, true) } func (b *Builder) cacheCgoHdr(a *Action) { c := cache.Default() if c == nil { return } b.cacheObjdirFile(a, c, "_cgo_install.h") } func (b *Builder) loadCachedCgoHdr(a *Action) bool { c := cache.Default() if c == nil { return false } err := b.loadCachedObjdirFile(a, c, "_cgo_install.h") return err == nil } func (b *Builder) cacheGofiles(a *Action, gofiles []string) { c := cache.Default() if c == nil { return } var buf bytes.Buffer for _, file := range gofiles { if !strings.HasPrefix(file, a.Objdir) { // not generated buf.WriteString("./") buf.WriteString(file) buf.WriteString("\n") continue } name := file[len(a.Objdir):] buf.WriteString(name) buf.WriteString("\n") if err := b.cacheObjdirFile(a, c, name); err != nil { return } } c.PutBytes(cache.Subkey(a.actionID, "gofiles"), buf.Bytes()) } func (b *Builder) loadCachedVet(a *Action) bool { c := cache.Default() if c == nil { return false } list, _, err := c.GetBytes(cache.Subkey(a.actionID, "gofiles")) if err != nil { return false } var gofiles []string for _, name := range strings.Split(string(list), "\n") { if name == "" { // end of list continue } if strings.HasPrefix(name, "./") { gofiles = append(gofiles, name[2:]) continue } if err := b.loadCachedObjdirFile(a, c, name); err != nil { return false } gofiles = append(gofiles, a.Objdir+name) } buildVetConfig(a, gofiles) return true } func (b *Builder) loadCachedGoFiles(a *Action) bool { c := cache.Default() if c == nil { return false } list, _, err := c.GetBytes(cache.Subkey(a.actionID, "gofiles")) if err != nil { return false } var files []string for _, name := range strings.Split(string(list), "\n") { if name == "" { // end of list continue } if strings.HasPrefix(name, "./") { files = append(files, name[len("./"):]) continue } file, err := b.findCachedObjdirFile(a, c, name) if err != nil { return false } files = append(files, file) } a.Package.CompiledGoFiles = files return true } // vetConfig is the configuration passed to vet describing a single package. type vetConfig struct { Compiler string // compiler name (gc, gccgo) Dir string // directory containing package ImportPath string // canonical import path ("package path") GoFiles []string // absolute paths to package source files ImportMap map[string]string // map import path in source code to package path PackageFile map[string]string // map package path to .a file with export data Standard map[string]bool // map package path to whether it's in the standard library PackageVetx map[string]string // map package path to vetx data from earlier vet run VetxOnly bool // only compute vetx data; don't report detected problems VetxOutput string // write vetx data to this output file SucceedOnTypecheckFailure bool // awful hack; see #18395 and below } func buildVetConfig(a *Action, gofiles []string) { // Pass list of absolute paths to vet, // so that vet's error messages will use absolute paths, // so that we can reformat them relative to the directory // in which the go command is invoked. vcfg := &vetConfig{ Compiler: cfg.BuildToolchainName, Dir: a.Package.Dir, GoFiles: mkAbsFiles(a.Package.Dir, gofiles), ImportPath: a.Package.ImportPath, ImportMap: make(map[string]string), PackageFile: make(map[string]string), Standard: make(map[string]bool), } a.vetCfg = vcfg for i, raw := range a.Package.Internal.RawImports { final := a.Package.Imports[i] vcfg.ImportMap[raw] = final } // Compute the list of mapped imports in the vet config // so that we can add any missing mappings below. vcfgMapped := make(map[string]bool) for _, p := range vcfg.ImportMap { vcfgMapped[p] = true } for _, a1 := range a.Deps { p1 := a1.Package if p1 == nil || p1.ImportPath == "" { continue } // Add import mapping if needed // (for imports like "runtime/cgo" that appear only in generated code). if !vcfgMapped[p1.ImportPath] { vcfg.ImportMap[p1.ImportPath] = p1.ImportPath } if a1.built != "" { vcfg.PackageFile[p1.ImportPath] = a1.built } if p1.Standard { vcfg.Standard[p1.ImportPath] = true } } } // VetTool is the path to an alternate vet tool binary. // The caller is expected to set it (if needed) before executing any vet actions. var VetTool string // VetFlags are the flags to pass to vet. // The caller is expected to set them before executing any vet actions. var VetFlags []string func (b *Builder) vet(a *Action) error { // a.Deps[0] is the build of the package being vetted. // a.Deps[1] is the build of the "fmt" package. a.Failed = false // vet of dependency may have failed but we can still succeed if a.Deps[0].Failed { // The build of the package has failed. Skip vet check. // Vet could return export data for non-typecheck errors, // but we ignore it because the package cannot be compiled. return nil } vcfg := a.Deps[0].vetCfg if vcfg == nil { // Vet config should only be missing if the build failed. return fmt.Errorf("vet config not found") } vcfg.VetxOnly = a.VetxOnly vcfg.VetxOutput = a.Objdir + "vet.out" vcfg.PackageVetx = make(map[string]string) h := cache.NewHash("vet " + a.Package.ImportPath) fmt.Fprintf(h, "vet %q\n", b.toolID("vet")) // Note: We could decide that vet should compute export data for // all analyses, in which case we don't need to include the flags here. // But that would mean that if an analysis causes problems like // unexpected crashes there would be no way to turn it off. // It seems better to let the flags disable export analysis too. fmt.Fprintf(h, "vetflags %q\n", VetFlags) fmt.Fprintf(h, "pkg %q\n", a.Deps[0].actionID) for _, a1 := range a.Deps { if a1.Mode == "vet" && a1.built != "" { fmt.Fprintf(h, "vetout %q %s\n", a1.Package.ImportPath, b.fileHash(a1.built)) vcfg.PackageVetx[a1.Package.ImportPath] = a1.built } } key := cache.ActionID(h.Sum()) if vcfg.VetxOnly { if c := cache.Default(); c != nil && !cfg.BuildA { if file, _, err := c.GetFile(key); err == nil { a.built = file return nil } } } if vcfg.ImportMap["fmt"] == "" { a1 := a.Deps[1] vcfg.ImportMap["fmt"] = "fmt" if a1.built != "" { vcfg.PackageFile["fmt"] = a1.built } vcfg.Standard["fmt"] = true } // During go test, ignore type-checking failures during vet. // We only run vet if the compilation has succeeded, // so at least for now assume the bug is in vet. // We know of at least #18395. // TODO(rsc,gri): Try to remove this for Go 1.11. // // Disabled 2018-04-20. Let's see if we can do without it. vcfg.SucceedOnTypecheckFailure = cfg.CmdName == "test" js, err := json.MarshalIndent(vcfg, "", "\t") if err != nil { return fmt.Errorf("internal error marshaling vet config: %v", err) } js = append(js, '\n') if err := b.writeFile(a.Objdir+"vet.cfg", js); err != nil { return err } env := b.cCompilerEnv() if cfg.BuildToolchainName == "gccgo" { env = append(env, "GCCGO="+BuildToolchain.compiler()) } p := a.Package tool := VetTool if tool == "" { tool = base.Tool("vet") } runErr := b.run(a, p.Dir, p.ImportPath, env, cfg.BuildToolexec, tool, VetFlags, a.Objdir+"vet.cfg") // If vet wrote export data, save it for input to future vets. if f, err := os.Open(vcfg.VetxOutput); err == nil { a.built = vcfg.VetxOutput if c := cache.Default(); c != nil { c.Put(key, f) } f.Close() } return runErr } // linkActionID computes the action ID for a link action. func (b *Builder) linkActionID(a *Action) cache.ActionID { p := a.Package h := cache.NewHash("link " + p.ImportPath) // Toolchain-independent configuration. fmt.Fprintf(h, "link\n") fmt.Fprintf(h, "buildmode %s goos %s goarch %s\n", cfg.BuildBuildmode, cfg.Goos, cfg.Goarch) fmt.Fprintf(h, "import %q\n", p.ImportPath) fmt.Fprintf(h, "omitdebug %v standard %v local %v prefix %q\n", p.Internal.OmitDebug, p.Standard, p.Internal.Local, p.Internal.LocalPrefix) // Toolchain-dependent configuration, shared with b.linkSharedActionID. b.printLinkerConfig(h, p) // Input files. for _, a1 := range a.Deps { p1 := a1.Package if p1 != nil { if a1.built != "" || a1.buildID != "" { buildID := a1.buildID if buildID == "" { buildID = b.buildID(a1.built) } fmt.Fprintf(h, "packagefile %s=%s\n", p1.ImportPath, contentID(buildID)) } // Because we put package main's full action ID into the binary's build ID, // we must also put the full action ID into the binary's action ID hash. if p1.Name == "main" { fmt.Fprintf(h, "packagemain %s\n", a1.buildID) } if p1.Shlib != "" { fmt.Fprintf(h, "packageshlib %s=%s\n", p1.ImportPath, contentID(b.buildID(p1.Shlib))) } } } return h.Sum() } // printLinkerConfig prints the linker config into the hash h, // as part of the computation of a linker-related action ID. func (b *Builder) printLinkerConfig(h io.Writer, p *load.Package) { switch cfg.BuildToolchainName { default: base.Fatalf("linkActionID: unknown toolchain %q", cfg.BuildToolchainName) case "gc": fmt.Fprintf(h, "link %s %q %s\n", b.toolID("link"), forcedLdflags, ldBuildmode) if p != nil { fmt.Fprintf(h, "linkflags %q\n", p.Internal.Ldflags) } fmt.Fprintf(h, "GO$GOARCH=%s\n", os.Getenv("GO"+strings.ToUpper(cfg.BuildContext.GOARCH))) // GO386, GOARM, etc // The linker writes source file paths that say GOROOT_FINAL. fmt.Fprintf(h, "GOROOT=%s\n", cfg.GOROOT_FINAL) // TODO(rsc): Convince linker team not to add more magic environment variables, // or perhaps restrict the environment variables passed to subprocesses. magic := []string{ "GO_EXTLINK_ENABLED", } for _, env := range magic { if x := os.Getenv(env); x != "" { fmt.Fprintf(h, "magic %s=%s\n", env, x) } } // TODO(rsc): Do cgo settings and flags need to be included? // Or external linker settings and flags? case "gccgo": id, err := b.gccgoToolID(BuildToolchain.linker(), "go") if err != nil { base.Fatalf("%v", err) } fmt.Fprintf(h, "link %s %s\n", id, ldBuildmode) // TODO(iant): Should probably include cgo flags here. } } // link is the action for linking a single command. // Note that any new influence on this logic must be reported in b.linkActionID above as well. func (b *Builder) link(a *Action) (err error) { if b.useCache(a, a.Package, b.linkActionID(a), a.Package.Target) || b.IsCmdList { return nil } defer b.flushOutput(a) if err := b.Mkdir(a.Objdir); err != nil { return err } importcfg := a.Objdir + "importcfg.link" if err := b.writeLinkImportcfg(a, importcfg); err != nil { return err } // make target directory dir, _ := filepath.Split(a.Target) if dir != "" { if err := b.Mkdir(dir); err != nil { return err } } if err := BuildToolchain.ld(b, a, a.Target, importcfg, a.Deps[0].built); err != nil { return err } // Update the binary with the final build ID. // But if OmitDebug is set, don't rewrite the binary, because we set OmitDebug // on binaries that we are going to run and then delete. // There's no point in doing work on such a binary. // Worse, opening the binary for write here makes it // essentially impossible to safely fork+exec due to a fundamental // incompatibility between ETXTBSY and threads on modern Unix systems. // See golang.org/issue/22220. // We still call updateBuildID to update a.buildID, which is important // for test result caching, but passing rewrite=false (final arg) // means we don't actually rewrite the binary, nor store the // result into the cache. That's probably a net win: // less cache space wasted on large binaries we are not likely to // need again. (On the other hand it does make repeated go test slower.) // It also makes repeated go run slower, which is a win in itself: // we don't want people to treat go run like a scripting environment. if err := b.updateBuildID(a, a.Target, !a.Package.Internal.OmitDebug); err != nil { return err } a.built = a.Target return nil } func (b *Builder) writeLinkImportcfg(a *Action, file string) error { // Prepare Go import cfg. var icfg bytes.Buffer for _, a1 := range a.Deps { p1 := a1.Package if p1 == nil { continue } fmt.Fprintf(&icfg, "packagefile %s=%s\n", p1.ImportPath, a1.built) if p1.Shlib != "" { fmt.Fprintf(&icfg, "packageshlib %s=%s\n", p1.ImportPath, p1.Shlib) } } return b.writeFile(file, icfg.Bytes()) } // PkgconfigCmd returns a pkg-config binary name // defaultPkgConfig is defined in zdefaultcc.go, written by cmd/dist. func (b *Builder) PkgconfigCmd() string { return envList("PKG_CONFIG", cfg.DefaultPkgConfig)[0] } // splitPkgConfigOutput parses the pkg-config output into a slice of // flags. This implements the algorithm from pkgconf/libpkgconf/argvsplit.c. func splitPkgConfigOutput(out []byte) ([]string, error) { if len(out) == 0 { return nil, nil } var flags []string flag := make([]byte, 0, len(out)) escaped := false quote := byte(0) for _, c := range out { if escaped { if quote != 0 { switch c { case '$', '`', '"', '\\': default: flag = append(flag, '\\') } flag = append(flag, c) } else { flag = append(flag, c) } escaped = false } else if quote != 0 { if c == quote { quote = 0 } else { switch c { case '\\': escaped = true default: flag = append(flag, c) } } } else if strings.IndexByte(" \t\n\v\f\r", c) < 0 { switch c { case '\\': escaped = true case '\'', '"': quote = c default: flag = append(flag, c) } } else if len(flag) != 0 { flags = append(flags, string(flag)) flag = flag[:0] } } if escaped { return nil, errors.New("broken character escaping in pkgconf output ") } if quote != 0 { return nil, errors.New("unterminated quoted string in pkgconf output ") } else if len(flag) != 0 { flags = append(flags, string(flag)) } return flags, nil } // Calls pkg-config if needed and returns the cflags/ldflags needed to build the package. func (b *Builder) getPkgConfigFlags(p *load.Package) (cflags, ldflags []string, err error) { if pcargs := p.CgoPkgConfig; len(pcargs) > 0 { // pkg-config permits arguments to appear anywhere in // the command line. Move them all to the front, before --. var pcflags []string var pkgs []string for _, pcarg := range pcargs { if pcarg == "--" { // We're going to add our own "--" argument. } else if strings.HasPrefix(pcarg, "--") { pcflags = append(pcflags, pcarg) } else { pkgs = append(pkgs, pcarg) } } for _, pkg := range pkgs { if !load.SafeArg(pkg) { return nil, nil, fmt.Errorf("invalid pkg-config package name: %s", pkg) } } var out []byte out, err = b.runOut(p.Dir, nil, b.PkgconfigCmd(), "--cflags", pcflags, "--", pkgs) if err != nil { b.showOutput(nil, p.Dir, b.PkgconfigCmd()+" --cflags "+strings.Join(pcflags, " ")+" -- "+strings.Join(pkgs, " "), string(out)) b.Print(err.Error() + "\n") return nil, nil, errPrintedOutput } if len(out) > 0 { cflags, err = splitPkgConfigOutput(out) if err != nil { return nil, nil, err } if err := checkCompilerFlags("CFLAGS", "pkg-config --cflags", cflags); err != nil { return nil, nil, err } } out, err = b.runOut(p.Dir, nil, b.PkgconfigCmd(), "--libs", pcflags, "--", pkgs) if err != nil { b.showOutput(nil, p.Dir, b.PkgconfigCmd()+" --libs "+strings.Join(pcflags, " ")+" -- "+strings.Join(pkgs, " "), string(out)) b.Print(err.Error() + "\n") return nil, nil, errPrintedOutput } if len(out) > 0 { ldflags = strings.Fields(string(out)) if err := checkLinkerFlags("LDFLAGS", "pkg-config --libs", ldflags); err != nil { return nil, nil, err } } } return } func (b *Builder) installShlibname(a *Action) error { // TODO: BuildN a1 := a.Deps[0] err := ioutil.WriteFile(a.Target, []byte(filepath.Base(a1.Target)+"\n"), 0666) if err != nil { return err } if cfg.BuildX { b.Showcmd("", "echo '%s' > %s # internal", filepath.Base(a1.Target), a.Target) } return nil } func (b *Builder) linkSharedActionID(a *Action) cache.ActionID { h := cache.NewHash("linkShared") // Toolchain-independent configuration. fmt.Fprintf(h, "linkShared\n") fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch) // Toolchain-dependent configuration, shared with b.linkActionID. b.printLinkerConfig(h, nil) // Input files. for _, a1 := range a.Deps { p1 := a1.Package if a1.built == "" { continue } if p1 != nil { fmt.Fprintf(h, "packagefile %s=%s\n", p1.ImportPath, contentID(b.buildID(a1.built))) if p1.Shlib != "" { fmt.Fprintf(h, "packageshlib %s=%s\n", p1.ImportPath, contentID(b.buildID(p1.Shlib))) } } } // Files named on command line are special. for _, a1 := range a.Deps[0].Deps { p1 := a1.Package fmt.Fprintf(h, "top %s=%s\n", p1.ImportPath, contentID(b.buildID(a1.built))) } return h.Sum() } func (b *Builder) linkShared(a *Action) (err error) { if b.useCache(a, nil, b.linkSharedActionID(a), a.Target) || b.IsCmdList { return nil } defer b.flushOutput(a) if err := b.Mkdir(a.Objdir); err != nil { return err } importcfg := a.Objdir + "importcfg.link" if err := b.writeLinkImportcfg(a, importcfg); err != nil { return err } // TODO(rsc): There is a missing updateBuildID here, // but we have to decide where to store the build ID in these files. a.built = a.Target return BuildToolchain.ldShared(b, a, a.Deps[0].Deps, a.Target, importcfg, a.Deps) } // BuildInstallFunc is the action for installing a single package or executable. func BuildInstallFunc(b *Builder, a *Action) (err error) { defer func() { if err != nil && err != errPrintedOutput { // a.Package == nil is possible for the go install -buildmode=shared // action that installs libmangledname.so, which corresponds to // a list of packages, not just one. sep, path := "", "" if a.Package != nil { sep, path = " ", a.Package.ImportPath } err = fmt.Errorf("go %s%s%s: %v", cfg.CmdName, sep, path, err) } }() a1 := a.Deps[0] a.buildID = a1.buildID // If we are using the eventual install target as an up-to-date // cached copy of the thing we built, then there's no need to // copy it into itself (and that would probably fail anyway). // In this case a1.built == a.Target because a1.built == p.Target, // so the built target is not in the a1.Objdir tree that b.cleanup(a1) removes. if a1.built == a.Target { a.built = a.Target if !a.buggyInstall { b.cleanup(a1) } // Whether we're smart enough to avoid a complete rebuild // depends on exactly what the staleness and rebuild algorithms // are, as well as potentially the state of the Go build cache. // We don't really want users to be able to infer (or worse start depending on) // those details from whether the modification time changes during // "go install", so do a best-effort update of the file times to make it // look like we rewrote a.Target even if we did not. Updating the mtime // may also help other mtime-based systems that depend on our // previous mtime updates that happened more often. // This is still not perfect - we ignore the error result, and if the file was // unwritable for some reason then pretending to have written it is also // confusing - but it's probably better than not doing the mtime update. // // But don't do that for the special case where building an executable // with -linkshared implicitly installs all its dependent libraries. // We want to hide that awful detail as much as possible, so don't // advertise it by touching the mtimes (usually the libraries are up // to date). if !a.buggyInstall && !b.IsCmdList { now := time.Now() os.Chtimes(a.Target, now, now) } return nil } // If we're building for go list -export, // never install anything; just keep the cache reference. if b.IsCmdList { a.built = a1.built return nil } if err := b.Mkdir(a.Objdir); err != nil { return err } perm := os.FileMode(0666) if a1.Mode == "link" { switch cfg.BuildBuildmode { case "c-archive", "c-shared", "plugin": default: perm = 0777 } } // make target directory dir, _ := filepath.Split(a.Target) if dir != "" { if err := b.Mkdir(dir); err != nil { return err } } if !a.buggyInstall { defer b.cleanup(a1) } return b.moveOrCopyFile(a.Target, a1.built, perm, false) } // cleanup removes a's object dir to keep the amount of // on-disk garbage down in a large build. On an operating system // with aggressive buffering, cleaning incrementally like // this keeps the intermediate objects from hitting the disk. func (b *Builder) cleanup(a *Action) { if !cfg.BuildWork { if cfg.BuildX { // Don't say we are removing the directory if // we never created it. if _, err := os.Stat(a.Objdir); err == nil || cfg.BuildN { b.Showcmd("", "rm -r %s", a.Objdir) } } os.RemoveAll(a.Objdir) } } // moveOrCopyFile is like 'mv src dst' or 'cp src dst'. func (b *Builder) moveOrCopyFile(dst, src string, perm os.FileMode, force bool) error { if cfg.BuildN { b.Showcmd("", "mv %s %s", src, dst) return nil } // If we can update the mode and rename to the dst, do it. // Otherwise fall back to standard copy. // If the source is in the build cache, we need to copy it. if strings.HasPrefix(src, cache.DefaultDir()) { return b.copyFile(dst, src, perm, force) } // On Windows, always copy the file, so that we respect the NTFS // permissions of the parent folder. https://golang.org/issue/22343. // What matters here is not cfg.Goos (the system we are building // for) but runtime.GOOS (the system we are building on). if runtime.GOOS == "windows" { return b.copyFile(dst, src, perm, force) } // If the destination directory has the group sticky bit set, // we have to copy the file to retain the correct permissions. // https://golang.org/issue/18878 if fi, err := os.Stat(filepath.Dir(dst)); err == nil { if fi.IsDir() && (fi.Mode()&os.ModeSetgid) != 0 { return b.copyFile(dst, src, perm, force) } } // The perm argument is meant to be adjusted according to umask, // but we don't know what the umask is. // Create a dummy file to find out. // This avoids build tags and works even on systems like Plan 9 // where the file mask computation incorporates other information. mode := perm f, err := os.OpenFile(filepath.Clean(dst)+"-go-tmp-umask", os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm) if err == nil { fi, err := f.Stat() if err == nil { mode = fi.Mode() & 0777 } name := f.Name() f.Close() os.Remove(name) } if err := os.Chmod(src, mode); err == nil { if err := os.Rename(src, dst); err == nil { if cfg.BuildX { b.Showcmd("", "mv %s %s", src, dst) } return nil } } return b.copyFile(dst, src, perm, force) } // copyFile is like 'cp src dst'. func (b *Builder) copyFile(dst, src string, perm os.FileMode, force bool) error { if cfg.BuildN || cfg.BuildX { b.Showcmd("", "cp %s %s", src, dst) if cfg.BuildN { return nil } } sf, err := os.Open(src) if err != nil { return err } defer sf.Close() // Be careful about removing/overwriting dst. // Do not remove/overwrite if dst exists and is a directory // or a non-object file. if fi, err := os.Stat(dst); err == nil { if fi.IsDir() { return fmt.Errorf("build output %q already exists and is a directory", dst) } if !force && fi.Mode().IsRegular() && !isObject(dst) { return fmt.Errorf("build output %q already exists and is not an object file", dst) } } // On Windows, remove lingering ~ file from last attempt. if base.ToolIsWindows { if _, err := os.Stat(dst + "~"); err == nil { os.Remove(dst + "~") } } mayberemovefile(dst) df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) if err != nil && base.ToolIsWindows { // Windows does not allow deletion of a binary file // while it is executing. Try to move it out of the way. // If the move fails, which is likely, we'll try again the // next time we do an install of this binary. if err := os.Rename(dst, dst+"~"); err == nil { os.Remove(dst + "~") } df, err = os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) } if err != nil { return err } _, err = io.Copy(df, sf) df.Close() if err != nil { mayberemovefile(dst) return fmt.Errorf("copying %s to %s: %v", src, dst, err) } return nil } // writeFile writes the text to file. func (b *Builder) writeFile(file string, text []byte) error { if cfg.BuildN || cfg.BuildX { b.Showcmd("", "cat >%s << 'EOF' # internal\n%sEOF", file, text) } if cfg.BuildN { return nil } return ioutil.WriteFile(file, text, 0666) } // Install the cgo export header file, if there is one. func (b *Builder) installHeader(a *Action) error { src := a.Objdir + "_cgo_install.h" if _, err := os.Stat(src); os.IsNotExist(err) { // If the file does not exist, there are no exported // functions, and we do not install anything. // TODO(rsc): Once we know that caching is rebuilding // at the right times (not missing rebuilds), here we should // probably delete the installed header, if any. if cfg.BuildX { b.Showcmd("", "# %s not created", src) } return nil } dir, _ := filepath.Split(a.Target) if dir != "" { if err := b.Mkdir(dir); err != nil { return err } } return b.moveOrCopyFile(a.Target, src, 0666, true) } // cover runs, in effect, // go tool cover -mode=b.coverMode -var="varName" -o dst.go src.go func (b *Builder) cover(a *Action, dst, src string, varName string) error { return b.run(a, a.Objdir, "cover "+a.Package.ImportPath, nil, cfg.BuildToolexec, base.Tool("cover"), "-mode", a.Package.Internal.CoverMode, "-var", varName, "-o", dst, src) } var objectMagic = [][]byte{ {'!', '<', 'a', 'r', 'c', 'h', '>', '\n'}, // Package archive {'\x7F', 'E', 'L', 'F'}, // ELF {0xFE, 0xED, 0xFA, 0xCE}, // Mach-O big-endian 32-bit {0xFE, 0xED, 0xFA, 0xCF}, // Mach-O big-endian 64-bit {0xCE, 0xFA, 0xED, 0xFE}, // Mach-O little-endian 32-bit {0xCF, 0xFA, 0xED, 0xFE}, // Mach-O little-endian 64-bit {0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00}, // PE (Windows) as generated by 6l/8l and gcc {0x00, 0x00, 0x01, 0xEB}, // Plan 9 i386 {0x00, 0x00, 0x8a, 0x97}, // Plan 9 amd64 {0x00, 0x00, 0x06, 0x47}, // Plan 9 arm {0x00, 0x61, 0x73, 0x6D}, // WASM } func isObject(s string) bool { f, err := os.Open(s) if err != nil { return false } defer f.Close() buf := make([]byte, 64) io.ReadFull(f, buf) for _, magic := range objectMagic { if bytes.HasPrefix(buf, magic) { return true } } return false } // mayberemovefile removes a file only if it is a regular file // When running as a user with sufficient privileges, we may delete // even device files, for example, which is not intended. func mayberemovefile(s string) { if fi, err := os.Lstat(s); err == nil && !fi.Mode().IsRegular() { return } os.Remove(s) } // fmtcmd formats a command in the manner of fmt.Sprintf but also: // // If dir is non-empty and the script is not in dir right now, // fmtcmd inserts "cd dir\n" before the command. // // fmtcmd replaces the value of b.WorkDir with $WORK. // fmtcmd replaces the value of goroot with $GOROOT. // fmtcmd replaces the value of b.gobin with $GOBIN. // // fmtcmd replaces the name of the current directory with dot (.) // but only when it is at the beginning of a space-separated token. // func (b *Builder) fmtcmd(dir string, format string, args ...interface{}) string { cmd := fmt.Sprintf(format, args...) if dir != "" && dir != "/" { dot := " ." if dir[len(dir)-1] == filepath.Separator { dot += string(filepath.Separator) } cmd = strings.Replace(" "+cmd, " "+dir, dot, -1)[1:] if b.scriptDir != dir { b.scriptDir = dir cmd = "cd " + dir + "\n" + cmd } } if b.WorkDir != "" { cmd = strings.Replace(cmd, b.WorkDir, "$WORK", -1) } return cmd } // showcmd prints the given command to standard output // for the implementation of -n or -x. func (b *Builder) Showcmd(dir string, format string, args ...interface{}) { b.output.Lock() defer b.output.Unlock() b.Print(b.fmtcmd(dir, format, args...) + "\n") } // showOutput prints "# desc" followed by the given output. // The output is expected to contain references to 'dir', usually // the source directory for the package that has failed to build. // showOutput rewrites mentions of dir with a relative path to dir // when the relative path is shorter. This is usually more pleasant. // For example, if fmt doesn't compile and we are in src/html, // the output is // // $ go build // # fmt // ../fmt/print.go:1090: undefined: asdf // $ // // instead of // // $ go build // # fmt // /usr/gopher/go/src/fmt/print.go:1090: undefined: asdf // $ // // showOutput also replaces references to the work directory with $WORK. // // If a is not nil and a.output is not nil, showOutput appends to that slice instead of // printing to b.Print. // func (b *Builder) showOutput(a *Action, dir, desc, out string) { prefix := "# " + desc suffix := "\n" + out if reldir := base.ShortPath(dir); reldir != dir { suffix = strings.Replace(suffix, " "+dir, " "+reldir, -1) suffix = strings.Replace(suffix, "\n"+dir, "\n"+reldir, -1) } suffix = strings.Replace(suffix, " "+b.WorkDir, " $WORK", -1) if a != nil && a.output != nil { a.output = append(a.output, prefix...) a.output = append(a.output, suffix...) return } b.output.Lock() defer b.output.Unlock() b.Print(prefix, suffix) } // errPrintedOutput is a special error indicating that a command failed // but that it generated output as well, and that output has already // been printed, so there's no point showing 'exit status 1' or whatever // the wait status was. The main executor, builder.do, knows not to // print this error. var errPrintedOutput = errors.New("already printed output - no need to show error") var cgoLine = regexp.MustCompile(`\[[^\[\]]+\.(cgo1|cover)\.go:[0-9]+(:[0-9]+)?\]`) var cgoTypeSigRe = regexp.MustCompile(`\b_C2?(type|func|var|macro)_\B`) // run runs the command given by cmdline in the directory dir. // If the command fails, run prints information about the failure // and returns a non-nil error. func (b *Builder) run(a *Action, dir string, desc string, env []string, cmdargs ...interface{}) error { out, err := b.runOut(dir, env, cmdargs...) if len(out) > 0 { if desc == "" { desc = b.fmtcmd(dir, "%s", strings.Join(str.StringList(cmdargs...), " ")) } b.showOutput(a, dir, desc, b.processOutput(out)) if err != nil { err = errPrintedOutput } } return err } // processOutput prepares the output of runOut to be output to the console. func (b *Builder) processOutput(out []byte) string { if out[len(out)-1] != '\n' { out = append(out, '\n') } messages := string(out) // Fix up output referring to cgo-generated code to be more readable. // Replace x.go:19[/tmp/.../x.cgo1.go:18] with x.go:19. // Replace *[100]_Ctype_foo with *[100]C.foo. // If we're using -x, assume we're debugging and want the full dump, so disable the rewrite. if !cfg.BuildX && cgoLine.MatchString(messages) { messages = cgoLine.ReplaceAllString(messages, "") messages = cgoTypeSigRe.ReplaceAllString(messages, "C.") } return messages } // runOut runs the command given by cmdline in the directory dir. // It returns the command output and any errors that occurred. func (b *Builder) runOut(dir string, env []string, cmdargs ...interface{}) ([]byte, error) { cmdline := str.StringList(cmdargs...) for _, arg := range cmdline { // GNU binutils commands, including gcc and gccgo, interpret an argument // @foo anywhere in the command line (even following --) as meaning // "read and insert arguments from the file named foo." // Don't say anything that might be misinterpreted that way. if strings.HasPrefix(arg, "@") { return nil, fmt.Errorf("invalid command-line argument %s in command: %s", arg, joinUnambiguously(cmdline)) } } if cfg.BuildN || cfg.BuildX { var envcmdline string for _, e := range env { if j := strings.IndexByte(e, '='); j != -1 { if strings.ContainsRune(e[j+1:], '\'') { envcmdline += fmt.Sprintf("%s=%q", e[:j], e[j+1:]) } else { envcmdline += fmt.Sprintf("%s='%s'", e[:j], e[j+1:]) } envcmdline += " " } } envcmdline += joinUnambiguously(cmdline) b.Showcmd(dir, "%s", envcmdline) if cfg.BuildN { return nil, nil } } var buf bytes.Buffer cmd := exec.Command(cmdline[0], cmdline[1:]...) cmd.Stdout = &buf cmd.Stderr = &buf cleanup := passLongArgsInResponseFiles(cmd) defer cleanup() cmd.Dir = dir cmd.Env = base.MergeEnvLists(env, base.EnvForDir(cmd.Dir, os.Environ())) err := cmd.Run() // err can be something like 'exit status 1'. // Add information about what program was running. // Note that if buf.Bytes() is non-empty, the caller usually // shows buf.Bytes() and does not print err at all, so the // prefix here does not make most output any more verbose. if err != nil { err = errors.New(cmdline[0] + ": " + err.Error()) } return buf.Bytes(), err } // joinUnambiguously prints the slice, quoting where necessary to make the // output unambiguous. // TODO: See issue 5279. The printing of commands needs a complete redo. func joinUnambiguously(a []string) string { var buf bytes.Buffer for i, s := range a { if i > 0 { buf.WriteByte(' ') } q := strconv.Quote(s) // A gccgo command line can contain -( and -). // Make sure we quote them since they are special to the shell. if s == "" || strings.ContainsAny(s, " ()") || len(q) > len(s)+2 { buf.WriteString(q) } else { buf.WriteString(s) } } return buf.String() } // cCompilerEnv returns environment variables to set when running the // C compiler. This is needed to disable escape codes in clang error // messages that confuse tools like cgo. func (b *Builder) cCompilerEnv() []string { return []string{"TERM=dumb"} } // mkdir makes the named directory. func (b *Builder) Mkdir(dir string) error { // Make Mkdir(a.Objdir) a no-op instead of an error when a.Objdir == "". if dir == "" { return nil } b.exec.Lock() defer b.exec.Unlock() // We can be a little aggressive about being // sure directories exist. Skip repeated calls. if b.mkdirCache[dir] { return nil } b.mkdirCache[dir] = true if cfg.BuildN || cfg.BuildX { b.Showcmd("", "mkdir -p %s", dir) if cfg.BuildN { return nil } } if err := os.MkdirAll(dir, 0777); err != nil { return err } return nil } // symlink creates a symlink newname -> oldname. func (b *Builder) Symlink(oldname, newname string) error { // It's not an error to try to recreate an existing symlink. if link, err := os.Readlink(newname); err == nil && link == oldname { return nil } if cfg.BuildN || cfg.BuildX { b.Showcmd("", "ln -s %s %s", oldname, newname) if cfg.BuildN { return nil } } return os.Symlink(oldname, newname) } // mkAbs returns an absolute path corresponding to // evaluating f in the directory dir. // We always pass absolute paths of source files so that // the error messages will include the full path to a file // in need of attention. func mkAbs(dir, f string) string { // Leave absolute paths alone. // Also, during -n mode we use the pseudo-directory $WORK // instead of creating an actual work directory that won't be used. // Leave paths beginning with $WORK alone too. if filepath.IsAbs(f) || strings.HasPrefix(f, "$WORK") { return f } return filepath.Join(dir, f) } type toolchain interface { // gc runs the compiler in a specific directory on a set of files // and returns the name of the generated output file. gc(b *Builder, a *Action, archive string, importcfg []byte, asmhdr bool, gofiles []string) (ofile string, out []byte, err error) // cc runs the toolchain's C compiler in a directory on a C file // to produce an output file. cc(b *Builder, a *Action, ofile, cfile string) error // asm runs the assembler in a specific directory on specific files // and returns a list of named output files. asm(b *Builder, a *Action, sfiles []string) ([]string, error) // pack runs the archive packer in a specific directory to create // an archive from a set of object files. // typically it is run in the object directory. pack(b *Builder, a *Action, afile string, ofiles []string) error // ld runs the linker to create an executable starting at mainpkg. ld(b *Builder, root *Action, out, importcfg, mainpkg string) error // ldShared runs the linker to create a shared library containing the pkgs built by toplevelactions ldShared(b *Builder, root *Action, toplevelactions []*Action, out, importcfg string, allactions []*Action) error compiler() string linker() string } type noToolchain struct{} func noCompiler() error { log.Fatalf("unknown compiler %q", cfg.BuildContext.Compiler) return nil } func (noToolchain) compiler() string { noCompiler() return "" } func (noToolchain) linker() string { noCompiler() return "" } func (noToolchain) gc(b *Builder, a *Action, archive string, importcfg []byte, asmhdr bool, gofiles []string) (ofile string, out []byte, err error) { return "", nil, noCompiler() } func (noToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error) { return nil, noCompiler() } func (noToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error { return noCompiler() } func (noToolchain) ld(b *Builder, root *Action, out, importcfg, mainpkg string) error { return noCompiler() } func (noToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, out, importcfg string, allactions []*Action) error { return noCompiler() } func (noToolchain) cc(b *Builder, a *Action, ofile, cfile string) error { return noCompiler() } // gcc runs the gcc C compiler to create an object from a single C file. func (b *Builder) gcc(a *Action, p *load.Package, workdir, out string, flags []string, cfile string) error { return b.ccompile(a, p, out, flags, cfile, b.GccCmd(p.Dir, workdir)) } // gxx runs the g++ C++ compiler to create an object from a single C++ file. func (b *Builder) gxx(a *Action, p *load.Package, workdir, out string, flags []string, cxxfile string) error { return b.ccompile(a, p, out, flags, cxxfile, b.GxxCmd(p.Dir, workdir)) } // gfortran runs the gfortran Fortran compiler to create an object from a single Fortran file. func (b *Builder) gfortran(a *Action, p *load.Package, workdir, out string, flags []string, ffile string) error { return b.ccompile(a, p, out, flags, ffile, b.gfortranCmd(p.Dir, workdir)) } // ccompile runs the given C or C++ compiler and creates an object from a single source file. func (b *Builder) ccompile(a *Action, p *load.Package, outfile string, flags []string, file string, compiler []string) error { file = mkAbs(p.Dir, file) desc := p.ImportPath if !filepath.IsAbs(outfile) { outfile = filepath.Join(p.Dir, outfile) } output, err := b.runOut(filepath.Dir(file), b.cCompilerEnv(), compiler, flags, "-o", outfile, "-c", filepath.Base(file)) if len(output) > 0 { // On FreeBSD 11, when we pass -g to clang 3.8 it // invokes its internal assembler with -dwarf-version=2. // When it sees .section .note.GNU-stack, it warns // "DWARF2 only supports one section per compilation unit". // This warning makes no sense, since the section is empty, // but it confuses people. // We work around the problem by detecting the warning // and dropping -g and trying again. if bytes.Contains(output, []byte("DWARF2 only supports one section per compilation unit")) { newFlags := make([]string, 0, len(flags)) for _, f := range flags { if !strings.HasPrefix(f, "-g") { newFlags = append(newFlags, f) } } if len(newFlags) < len(flags) { return b.ccompile(a, p, outfile, newFlags, file, compiler) } } b.showOutput(a, p.Dir, desc, b.processOutput(output)) if err != nil { err = errPrintedOutput } else if os.Getenv("GO_BUILDER_NAME") != "" { return errors.New("C compiler warning promoted to error on Go builders") } } return err } // gccld runs the gcc linker to create an executable from a set of object files. func (b *Builder) gccld(p *load.Package, objdir, out string, flags []string, objs []string) error { var cmd []string if len(p.CXXFiles) > 0 || len(p.SwigCXXFiles) > 0 { cmd = b.GxxCmd(p.Dir, objdir) } else { cmd = b.GccCmd(p.Dir, objdir) } return b.run(nil, p.Dir, p.ImportPath, b.cCompilerEnv(), cmd, "-o", out, objs, flags) } // Grab these before main helpfully overwrites them. var ( origCC = os.Getenv("CC") origCXX = os.Getenv("CXX") ) // gccCmd returns a gcc command line prefix // defaultCC is defined in zdefaultcc.go, written by cmd/dist. func (b *Builder) GccCmd(incdir, workdir string) []string { return b.compilerCmd(b.ccExe(), incdir, workdir) } // gxxCmd returns a g++ command line prefix // defaultCXX is defined in zdefaultcc.go, written by cmd/dist. func (b *Builder) GxxCmd(incdir, workdir string) []string { return b.compilerCmd(b.cxxExe(), incdir, workdir) } // gfortranCmd returns a gfortran command line prefix. func (b *Builder) gfortranCmd(incdir, workdir string) []string { return b.compilerCmd(b.fcExe(), incdir, workdir) } // ccExe returns the CC compiler setting without all the extra flags we add implicitly. func (b *Builder) ccExe() []string { return b.compilerExe(origCC, cfg.DefaultCC(cfg.Goos, cfg.Goarch)) } // cxxExe returns the CXX compiler setting without all the extra flags we add implicitly. func (b *Builder) cxxExe() []string { return b.compilerExe(origCXX, cfg.DefaultCXX(cfg.Goos, cfg.Goarch)) } // fcExe returns the FC compiler setting without all the extra flags we add implicitly. func (b *Builder) fcExe() []string { return b.compilerExe(os.Getenv("FC"), "gfortran") } // compilerExe returns the compiler to use given an // environment variable setting (the value not the name) // and a default. The resulting slice is usually just the name // of the compiler but can have additional arguments if they // were present in the environment value. // For example if CC="gcc -DGOPHER" then the result is ["gcc", "-DGOPHER"]. func (b *Builder) compilerExe(envValue string, def string) []string { compiler := strings.Fields(envValue) if len(compiler) == 0 { compiler = []string{def} } return compiler } // compilerCmd returns a command line prefix for the given environment // variable and using the default command when the variable is empty. func (b *Builder) compilerCmd(compiler []string, incdir, workdir string) []string { // NOTE: env.go's mkEnv knows that the first three // strings returned are "gcc", "-I", incdir (and cuts them off). a := []string{compiler[0], "-I", incdir} a = append(a, compiler[1:]...) // Definitely want -fPIC but on Windows gcc complains // "-fPIC ignored for target (all code is position independent)" if cfg.Goos != "windows" { a = append(a, "-fPIC") } a = append(a, b.gccArchArgs()...) // gcc-4.5 and beyond require explicit "-pthread" flag // for multithreading with pthread library. if cfg.BuildContext.CgoEnabled { switch cfg.Goos { case "windows": a = append(a, "-mthreads") default: a = append(a, "-pthread") } } // disable ASCII art in clang errors, if possible if b.gccSupportsFlag(compiler, "-fno-caret-diagnostics") { a = append(a, "-fno-caret-diagnostics") } // clang is too smart about command-line arguments if b.gccSupportsFlag(compiler, "-Qunused-arguments") { a = append(a, "-Qunused-arguments") } // disable word wrapping in error messages a = append(a, "-fmessage-length=0") // Tell gcc not to include the work directory in object files. if b.gccSupportsFlag(compiler, "-fdebug-prefix-map=a=b") { if workdir == "" { workdir = b.WorkDir } workdir = strings.TrimSuffix(workdir, string(filepath.Separator)) a = append(a, "-fdebug-prefix-map="+workdir+"=/tmp/go-build") } // Tell gcc not to include flags in object files, which defeats the // point of -fdebug-prefix-map above. if b.gccSupportsFlag(compiler, "-gno-record-gcc-switches") { a = append(a, "-gno-record-gcc-switches") } // On OS X, some of the compilers behave as if -fno-common // is always set, and the Mach-O linker in 6l/8l assumes this. // See https://golang.org/issue/3253. if cfg.Goos == "darwin" { a = append(a, "-fno-common") } return a } // gccNoPie returns the flag to use to request non-PIE. On systems // with PIE (position independent executables) enabled by default, // -no-pie must be passed when doing a partial link with -Wl,-r. // But -no-pie is not supported by all compilers, and clang spells it -nopie. func (b *Builder) gccNoPie(linker []string) string { if b.gccSupportsFlag(linker, "-no-pie") { return "-no-pie" } if b.gccSupportsFlag(linker, "-nopie") { return "-nopie" } return "" } // gccSupportsFlag checks to see if the compiler supports a flag. func (b *Builder) gccSupportsFlag(compiler []string, flag string) bool { key := [2]string{compiler[0], flag} b.exec.Lock() defer b.exec.Unlock() if b, ok := b.flagCache[key]; ok { return b } if b.flagCache == nil { b.flagCache = make(map[[2]string]bool) } // We used to write an empty C file, but that gets complicated with // go build -n. We tried using a file that does not exist, but that // fails on systems with GCC version 4.2.1; that is the last GPLv2 // version of GCC, so some systems have frozen on it. // Now we pass an empty file on stdin, which should work at least for // GCC and clang. cmdArgs := str.StringList(compiler, flag, "-c", "-x", "c", "-") if cfg.BuildN || cfg.BuildX { b.Showcmd(b.WorkDir, "%s || true", joinUnambiguously(cmdArgs)) if cfg.BuildN { return false } } cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...) cmd.Dir = b.WorkDir cmd.Env = base.MergeEnvLists([]string{"LC_ALL=C"}, base.EnvForDir(cmd.Dir, os.Environ())) out, _ := cmd.CombinedOutput() // GCC says "unrecognized command line option". // clang says "unknown argument". // Older versions of GCC say "unrecognised debug output level". // For -fsplit-stack GCC says "'-fsplit-stack' is not supported". supported := !bytes.Contains(out, []byte("unrecognized")) && !bytes.Contains(out, []byte("unknown")) && !bytes.Contains(out, []byte("unrecognised")) && !bytes.Contains(out, []byte("is not supported")) b.flagCache[key] = supported return supported } // gccArchArgs returns arguments to pass to gcc based on the architecture. func (b *Builder) gccArchArgs() []string { switch cfg.Goarch { case "386": return []string{"-m32"} case "amd64", "amd64p32": return []string{"-m64"} case "arm": return []string{"-marm"} // not thumb case "s390x": return []string{"-m64", "-march=z196"} case "mips64", "mips64le": return []string{"-mabi=64"} case "mips", "mipsle": return []string{"-mabi=32", "-march=mips32"} } return nil } // envList returns the value of the given environment variable broken // into fields, using the default value when the variable is empty. func envList(key, def string) []string { v := os.Getenv(key) if v == "" { v = def } return strings.Fields(v) } // CFlags returns the flags to use when invoking the C, C++ or Fortran compilers, or cgo. func (b *Builder) CFlags(p *load.Package) (cppflags, cflags, cxxflags, fflags, ldflags []string, err error) { defaults := "-g -O2" if cppflags, err = buildFlags("CPPFLAGS", "", p.CgoCPPFLAGS, checkCompilerFlags); err != nil { return } if cflags, err = buildFlags("CFLAGS", defaults, p.CgoCFLAGS, checkCompilerFlags); err != nil { return } if cxxflags, err = buildFlags("CXXFLAGS", defaults, p.CgoCXXFLAGS, checkCompilerFlags); err != nil { return } if fflags, err = buildFlags("FFLAGS", defaults, p.CgoFFLAGS, checkCompilerFlags); err != nil { return } if ldflags, err = buildFlags("LDFLAGS", defaults, p.CgoLDFLAGS, checkLinkerFlags); err != nil { return } return } func buildFlags(name, defaults string, fromPackage []string, check func(string, string, []string) error) ([]string, error) { if err := check(name, "#cgo "+name, fromPackage); err != nil { return nil, err } return str.StringList(envList("CGO_"+name, defaults), fromPackage), nil } var cgoRe = regexp.MustCompile(`[/\\:]`) func (b *Builder) cgo(a *Action, cgoExe, objdir string, pcCFLAGS, pcLDFLAGS, cgofiles, gccfiles, gxxfiles, mfiles, ffiles []string) (outGo, outObj []string, err error) { p := a.Package cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, cgoFFLAGS, cgoLDFLAGS, err := b.CFlags(p) if err != nil { return nil, nil, err } cgoCPPFLAGS = append(cgoCPPFLAGS, pcCFLAGS...) cgoLDFLAGS = append(cgoLDFLAGS, pcLDFLAGS...) // If we are compiling Objective-C code, then we need to link against libobjc if len(mfiles) > 0 { cgoLDFLAGS = append(cgoLDFLAGS, "-lobjc") } // Likewise for Fortran, except there are many Fortran compilers. // Support gfortran out of the box and let others pass the correct link options // via CGO_LDFLAGS if len(ffiles) > 0 { fc := os.Getenv("FC") if fc == "" { fc = "gfortran" } if strings.Contains(fc, "gfortran") { cgoLDFLAGS = append(cgoLDFLAGS, "-lgfortran") } } if cfg.BuildMSan { cgoCFLAGS = append([]string{"-fsanitize=memory"}, cgoCFLAGS...) cgoLDFLAGS = append([]string{"-fsanitize=memory"}, cgoLDFLAGS...) } // Allows including _cgo_export.h from .[ch] files in the package. cgoCPPFLAGS = append(cgoCPPFLAGS, "-I", objdir) // cgo // TODO: CGO_FLAGS? gofiles := []string{objdir + "_cgo_gotypes.go"} cfiles := []string{"_cgo_export.c"} for _, fn := range cgofiles { f := strings.TrimSuffix(filepath.Base(fn), ".go") gofiles = append(gofiles, objdir+f+".cgo1.go") cfiles = append(cfiles, f+".cgo2.c") } // TODO: make cgo not depend on $GOARCH? cgoflags := []string{} if p.Standard && p.ImportPath == "runtime/cgo" { cgoflags = append(cgoflags, "-import_runtime_cgo=false") } if p.Standard && (p.ImportPath == "runtime/race" || p.ImportPath == "runtime/msan" || p.ImportPath == "runtime/cgo") { cgoflags = append(cgoflags, "-import_syscall=false") } // Update $CGO_LDFLAGS with p.CgoLDFLAGS. // These flags are recorded in the generated _cgo_gotypes.go file // using //go:cgo_ldflag directives, the compiler records them in the // object file for the package, and then the Go linker passes them // along to the host linker. At this point in the code, cgoLDFLAGS // consists of the original $CGO_LDFLAGS (unchecked) and all the // flags put together from source code (checked). cgoenv := b.cCompilerEnv() if len(cgoLDFLAGS) > 0 { flags := make([]string, len(cgoLDFLAGS)) for i, f := range cgoLDFLAGS { flags[i] = strconv.Quote(f) } cgoenv = []string{"CGO_LDFLAGS=" + strings.Join(flags, " ")} } if cfg.BuildToolchainName == "gccgo" { switch cfg.Goarch { case "386", "amd64": cgoCFLAGS = append(cgoCFLAGS, "-fsplit-stack") } cgoflags = append(cgoflags, "-gccgo") if pkgpath := gccgoPkgpath(p); pkgpath != "" { cgoflags = append(cgoflags, "-gccgopkgpath="+pkgpath) } } switch cfg.BuildBuildmode { case "c-archive", "c-shared": // Tell cgo that if there are any exported functions // it should generate a header file that C code can // #include. cgoflags = append(cgoflags, "-exportheader="+objdir+"_cgo_install.h") } if err := b.run(a, p.Dir, p.ImportPath, cgoenv, cfg.BuildToolexec, cgoExe, "-objdir", objdir, "-importpath", p.ImportPath, cgoflags, "--", cgoCPPFLAGS, cgoCFLAGS, cgofiles); err != nil { return nil, nil, err } outGo = append(outGo, gofiles...) // Use sequential object file names to keep them distinct // and short enough to fit in the .a header file name slots. // We no longer collect them all into _all.o, and we'd like // tools to see both the .o suffix and unique names, so // we need to make them short enough not to be truncated // in the final archive. oseq := 0 nextOfile := func() string { oseq++ return objdir + fmt.Sprintf("_x%03d.o", oseq) } // gcc cflags := str.StringList(cgoCPPFLAGS, cgoCFLAGS) for _, cfile := range cfiles { ofile := nextOfile() if err := b.gcc(a, p, a.Objdir, ofile, cflags, objdir+cfile); err != nil { return nil, nil, err } outObj = append(outObj, ofile) } for _, file := range gccfiles { ofile := nextOfile() if err := b.gcc(a, p, a.Objdir, ofile, cflags, file); err != nil { return nil, nil, err } outObj = append(outObj, ofile) } cxxflags := str.StringList(cgoCPPFLAGS, cgoCXXFLAGS) for _, file := range gxxfiles { ofile := nextOfile() if err := b.gxx(a, p, a.Objdir, ofile, cxxflags, file); err != nil { return nil, nil, err } outObj = append(outObj, ofile) } for _, file := range mfiles { ofile := nextOfile() if err := b.gcc(a, p, a.Objdir, ofile, cflags, file); err != nil { return nil, nil, err } outObj = append(outObj, ofile) } fflags := str.StringList(cgoCPPFLAGS, cgoFFLAGS) for _, file := range ffiles { ofile := nextOfile() if err := b.gfortran(a, p, a.Objdir, ofile, fflags, file); err != nil { return nil, nil, err } outObj = append(outObj, ofile) } switch cfg.BuildToolchainName { case "gc": importGo := objdir + "_cgo_import.go" if err := b.dynimport(a, p, objdir, importGo, cgoExe, cflags, cgoLDFLAGS, outObj); err != nil { return nil, nil, err } outGo = append(outGo, importGo) case "gccgo": defunC := objdir + "_cgo_defun.c" defunObj := objdir + "_cgo_defun.o" if err := BuildToolchain.cc(b, a, defunObj, defunC); err != nil { return nil, nil, err } outObj = append(outObj, defunObj) default: noCompiler() } return outGo, outObj, nil } // dynimport creates a Go source file named importGo containing // //go:cgo_import_dynamic directives for each symbol or library // dynamically imported by the object files outObj. func (b *Builder) dynimport(a *Action, p *load.Package, objdir, importGo, cgoExe string, cflags, cgoLDFLAGS, outObj []string) error { cfile := objdir + "_cgo_main.c" ofile := objdir + "_cgo_main.o" if err := b.gcc(a, p, objdir, ofile, cflags, cfile); err != nil { return err } linkobj := str.StringList(ofile, outObj, p.SysoFiles) dynobj := objdir + "_cgo_.o" // we need to use -pie for Linux/ARM to get accurate imported sym ldflags := cgoLDFLAGS if (cfg.Goarch == "arm" && cfg.Goos == "linux") || cfg.Goos == "android" { // -static -pie doesn't make sense, and causes link errors. // Issue 26197. n := make([]string, 0, len(ldflags)) for _, flag := range ldflags { if flag != "-static" { n = append(n, flag) } } ldflags = append(n, "-pie") } if err := b.gccld(p, objdir, dynobj, ldflags, linkobj); err != nil { return err } // cgo -dynimport var cgoflags []string if p.Standard && p.ImportPath == "runtime/cgo" { cgoflags = []string{"-dynlinker"} // record path to dynamic linker } return b.run(a, p.Dir, p.ImportPath, b.cCompilerEnv(), cfg.BuildToolexec, cgoExe, "-dynpackage", p.Name, "-dynimport", dynobj, "-dynout", importGo, cgoflags) } // Run SWIG on all SWIG input files. // TODO: Don't build a shared library, once SWIG emits the necessary // pragmas for external linking. func (b *Builder) swig(a *Action, p *load.Package, objdir string, pcCFLAGS []string) (outGo, outC, outCXX []string, err error) { if err := b.swigVersionCheck(); err != nil { return nil, nil, nil, err } intgosize, err := b.swigIntSize(objdir) if err != nil { return nil, nil, nil, err } for _, f := range p.SwigFiles { goFile, cFile, err := b.swigOne(a, p, f, objdir, pcCFLAGS, false, intgosize) if err != nil { return nil, nil, nil, err } if goFile != "" { outGo = append(outGo, goFile) } if cFile != "" { outC = append(outC, cFile) } } for _, f := range p.SwigCXXFiles { goFile, cxxFile, err := b.swigOne(a, p, f, objdir, pcCFLAGS, true, intgosize) if err != nil { return nil, nil, nil, err } if goFile != "" { outGo = append(outGo, goFile) } if cxxFile != "" { outCXX = append(outCXX, cxxFile) } } return outGo, outC, outCXX, nil } // Make sure SWIG is new enough. var ( swigCheckOnce sync.Once swigCheck error ) func (b *Builder) swigDoVersionCheck() error { out, err := b.runOut("", nil, "swig", "-version") if err != nil { return err } re := regexp.MustCompile(`[vV]ersion +([\d]+)([.][\d]+)?([.][\d]+)?`) matches := re.FindSubmatch(out) if matches == nil { // Can't find version number; hope for the best. return nil } major, err := strconv.Atoi(string(matches[1])) if err != nil { // Can't find version number; hope for the best. return nil } const errmsg = "must have SWIG version >= 3.0.6" if major < 3 { return errors.New(errmsg) } if major > 3 { // 4.0 or later return nil } // We have SWIG version 3.x. if len(matches[2]) > 0 { minor, err := strconv.Atoi(string(matches[2][1:])) if err != nil { return nil } if minor > 0 { // 3.1 or later return nil } } // We have SWIG version 3.0.x. if len(matches[3]) > 0 { patch, err := strconv.Atoi(string(matches[3][1:])) if err != nil { return nil } if patch < 6 { // Before 3.0.6. return errors.New(errmsg) } } return nil } func (b *Builder) swigVersionCheck() error { swigCheckOnce.Do(func() { swigCheck = b.swigDoVersionCheck() }) return swigCheck } // Find the value to pass for the -intgosize option to swig. var ( swigIntSizeOnce sync.Once swigIntSize string swigIntSizeError error ) // This code fails to build if sizeof(int) <= 32 const swigIntSizeCode = ` package main const i int = 1 << 32 ` // Determine the size of int on the target system for the -intgosize option // of swig >= 2.0.9. Run only once. func (b *Builder) swigDoIntSize(objdir string) (intsize string, err error) { if cfg.BuildN { return "$INTBITS", nil } src := filepath.Join(b.WorkDir, "swig_intsize.go") if err = ioutil.WriteFile(src, []byte(swigIntSizeCode), 0666); err != nil { return } srcs := []string{src} p := load.GoFilesPackage(srcs) if _, _, e := BuildToolchain.gc(b, &Action{Mode: "swigDoIntSize", Package: p, Objdir: objdir}, "", nil, false, srcs); e != nil { return "32", nil } return "64", nil } // Determine the size of int on the target system for the -intgosize option // of swig >= 2.0.9. func (b *Builder) swigIntSize(objdir string) (intsize string, err error) { swigIntSizeOnce.Do(func() { swigIntSize, swigIntSizeError = b.swigDoIntSize(objdir) }) return swigIntSize, swigIntSizeError } // Run SWIG on one SWIG input file. func (b *Builder) swigOne(a *Action, p *load.Package, file, objdir string, pcCFLAGS []string, cxx bool, intgosize string) (outGo, outC string, err error) { cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, _, _, err := b.CFlags(p) if err != nil { return "", "", err } var cflags []string if cxx { cflags = str.StringList(cgoCPPFLAGS, pcCFLAGS, cgoCXXFLAGS) } else { cflags = str.StringList(cgoCPPFLAGS, pcCFLAGS, cgoCFLAGS) } n := 5 // length of ".swig" if cxx { n = 8 // length of ".swigcxx" } base := file[:len(file)-n] goFile := base + ".go" gccBase := base + "_wrap." gccExt := "c" if cxx { gccExt = "cxx" } gccgo := cfg.BuildToolchainName == "gccgo" // swig args := []string{ "-go", "-cgo", "-intgosize", intgosize, "-module", base, "-o", objdir + gccBase + gccExt, "-outdir", objdir, } for _, f := range cflags { if len(f) > 3 && f[:2] == "-I" { args = append(args, f) } } if gccgo { args = append(args, "-gccgo") if pkgpath := gccgoPkgpath(p); pkgpath != "" { args = append(args, "-go-pkgpath", pkgpath) } } if cxx { args = append(args, "-c++") } out, err := b.runOut(p.Dir, nil, "swig", args, file) if err != nil { if len(out) > 0 { if bytes.Contains(out, []byte("-intgosize")) || bytes.Contains(out, []byte("-cgo")) { return "", "", errors.New("must have SWIG version >= 3.0.6") } b.showOutput(a, p.Dir, p.Desc(), b.processOutput(out)) // swig error return "", "", errPrintedOutput } return "", "", err } if len(out) > 0 { b.showOutput(a, p.Dir, p.Desc(), b.processOutput(out)) // swig warning } // If the input was x.swig, the output is x.go in the objdir. // But there might be an x.go in the original dir too, and if it // uses cgo as well, cgo will be processing both and will // translate both into x.cgo1.go in the objdir, overwriting one. // Rename x.go to _x_swig.go to avoid this problem. // We ignore files in the original dir that begin with underscore // so _x_swig.go cannot conflict with an original file we were // going to compile. goFile = objdir + goFile newGoFile := objdir + "_" + base + "_swig.go" if err := os.Rename(goFile, newGoFile); err != nil { return "", "", err } return newGoFile, objdir + gccBase + gccExt, nil } // disableBuildID adjusts a linker command line to avoid creating a // build ID when creating an object file rather than an executable or // shared library. Some systems, such as Ubuntu, always add // --build-id to every link, but we don't want a build ID when we are // producing an object file. On some of those system a plain -r (not // -Wl,-r) will turn off --build-id, but clang 3.0 doesn't support a // plain -r. I don't know how to turn off --build-id when using clang // other than passing a trailing --build-id=none. So that is what we // do, but only on systems likely to support it, which is to say, // systems that normally use gold or the GNU linker. func (b *Builder) disableBuildID(ldflags []string) []string { switch cfg.Goos { case "android", "dragonfly", "linux", "netbsd": ldflags = append(ldflags, "-Wl,--build-id=none") } return ldflags } // mkAbsFiles converts files into a list of absolute files, // assuming they were originally relative to dir, // and returns that new list. func mkAbsFiles(dir string, files []string) []string { abs := make([]string, len(files)) for i, f := range files { if !filepath.IsAbs(f) { f = filepath.Join(dir, f) } abs[i] = f } return abs } // passLongArgsInResponseFiles modifies cmd on Windows such that, for // certain programs, long arguments are passed in "response files", a // file on disk with the arguments, with one arg per line. An actual // argument starting with '@' means that the rest of the argument is // a filename of arguments to expand. // // See Issue 18468. func passLongArgsInResponseFiles(cmd *exec.Cmd) (cleanup func()) { cleanup = func() {} // no cleanup by default var argLen int for _, arg := range cmd.Args { argLen += len(arg) } // If we're not approaching 32KB of args, just pass args normally. // (use 30KB instead to be conservative; not sure how accounting is done) if !useResponseFile(cmd.Path, argLen) { return } tf, err := ioutil.TempFile("", "args") if err != nil { log.Fatalf("error writing long arguments to response file: %v", err) } cleanup = func() { os.Remove(tf.Name()) } var buf bytes.Buffer for _, arg := range cmd.Args[1:] { fmt.Fprintf(&buf, "%s\n", arg) } if _, err := tf.Write(buf.Bytes()); err != nil { tf.Close() cleanup() log.Fatalf("error writing long arguments to response file: %v", err) } if err := tf.Close(); err != nil { cleanup() log.Fatalf("error writing long arguments to response file: %v", err) } cmd.Args = []string{cmd.Args[0], "@" + tf.Name()} return cleanup } func useResponseFile(path string, argLen int) bool { // Unless we're on Windows, don't use response files. if runtime.GOOS != "windows" { return false } // Unless the program uses objabi.Flagparse, which understands // response files, don't use response files. // TODO: do we need more commands? asm? cgo? For now, no. prog := strings.TrimSuffix(filepath.Base(path), ".exe") switch prog { case "compile", "link": default: return false } // Windows has a limit of 32 KB arguments. To be conservative and not // worry about whether that includes spaces or not, just use 30 KB. if argLen > (30 << 10) { return true } // On the Go build system, use response files about 10% of the // time, just to excercise this codepath. isBuilder := os.Getenv("GO_BUILDER_NAME") != "" if isBuilder && rand.Intn(10) == 0 { return true } return false }
envcmd
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/envcmd/env.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 envcmd implements the ``go env'' command. package envcmd import ( "encoding/json" "fmt" "os" "path/filepath" "runtime" "strings" "cmd/go/internal/base" "cmd/go/internal/cache" "cmd/go/internal/cfg" "cmd/go/internal/load" "cmd/go/internal/modload" "cmd/go/internal/work" ) var CmdEnv = &base.Command{ UsageLine: "go env [-json] [var ...]", Short: "print Go environment information", Long: ` Env prints Go environment information. By default env prints information as a shell script (on Windows, a batch file). If one or more variable names is given as arguments, env prints the value of each named variable on its own line. The -json flag prints the environment in JSON format instead of as a shell script. For more about environment variables, see 'go help environment'. `, } func init() { CmdEnv.Run = runEnv // break init cycle } var envJson = CmdEnv.Flag.Bool("json", false, "") func MkEnv() []cfg.EnvVar { var b work.Builder b.Init() env := []cfg.EnvVar{ {Name: "GOARCH", Value: cfg.Goarch}, {Name: "GOBIN", Value: cfg.GOBIN}, {Name: "GOCACHE", Value: cache.DefaultDir()}, {Name: "GOEXE", Value: cfg.ExeSuffix}, {Name: "GOFLAGS", Value: os.Getenv("GOFLAGS")}, {Name: "GOHOSTARCH", Value: runtime.GOARCH}, {Name: "GOHOSTOS", Value: runtime.GOOS}, {Name: "GOOS", Value: cfg.Goos}, {Name: "GOPATH", Value: cfg.BuildContext.GOPATH}, {Name: "GOPROXY", Value: os.Getenv("GOPROXY")}, {Name: "GORACE", Value: os.Getenv("GORACE")}, {Name: "GOROOT", Value: cfg.GOROOT}, {Name: "GOTMPDIR", Value: os.Getenv("GOTMPDIR")}, {Name: "GOTOOLDIR", Value: base.ToolDir}, } if work.GccgoBin != "" { env = append(env, cfg.EnvVar{Name: "GCCGO", Value: work.GccgoBin}) } else { env = append(env, cfg.EnvVar{Name: "GCCGO", Value: work.GccgoName}) } switch cfg.Goarch { case "arm": env = append(env, cfg.EnvVar{Name: "GOARM", Value: cfg.GOARM}) case "386": env = append(env, cfg.EnvVar{Name: "GO386", Value: cfg.GO386}) case "mips", "mipsle": env = append(env, cfg.EnvVar{Name: "GOMIPS", Value: cfg.GOMIPS}) case "mips64", "mips64le": env = append(env, cfg.EnvVar{Name: "GOMIPS64", Value: cfg.GOMIPS64}) } cc := cfg.DefaultCC(cfg.Goos, cfg.Goarch) if env := strings.Fields(os.Getenv("CC")); len(env) > 0 { cc = env[0] } cxx := cfg.DefaultCXX(cfg.Goos, cfg.Goarch) if env := strings.Fields(os.Getenv("CXX")); len(env) > 0 { cxx = env[0] } env = append(env, cfg.EnvVar{Name: "CC", Value: cc}) env = append(env, cfg.EnvVar{Name: "CXX", Value: cxx}) if cfg.BuildContext.CgoEnabled { env = append(env, cfg.EnvVar{Name: "CGO_ENABLED", Value: "1"}) } else { env = append(env, cfg.EnvVar{Name: "CGO_ENABLED", Value: "0"}) } return env } func findEnv(env []cfg.EnvVar, name string) string { for _, e := range env { if e.Name == name { return e.Value } } return "" } // ExtraEnvVars returns environment variables that should not leak into child processes. func ExtraEnvVars() []cfg.EnvVar { gomod := "" if modload.Init(); modload.ModRoot != "" { gomod = filepath.Join(modload.ModRoot, "go.mod") } return []cfg.EnvVar{ {Name: "GOMOD", Value: gomod}, } } // ExtraEnvVarsCostly returns environment variables that should not leak into child processes // but are costly to evaluate. func ExtraEnvVarsCostly() []cfg.EnvVar { var b work.Builder b.Init() cppflags, cflags, cxxflags, fflags, ldflags, err := b.CFlags(&load.Package{}) if err != nil { // Should not happen - b.CFlags was given an empty package. fmt.Fprintf(os.Stderr, "go: invalid cflags: %v\n", err) return nil } cmd := b.GccCmd(".", "") return []cfg.EnvVar{ // Note: Update the switch in runEnv below when adding to this list. {Name: "CGO_CFLAGS", Value: strings.Join(cflags, " ")}, {Name: "CGO_CPPFLAGS", Value: strings.Join(cppflags, " ")}, {Name: "CGO_CXXFLAGS", Value: strings.Join(cxxflags, " ")}, {Name: "CGO_FFLAGS", Value: strings.Join(fflags, " ")}, {Name: "CGO_LDFLAGS", Value: strings.Join(ldflags, " ")}, {Name: "PKG_CONFIG", Value: b.PkgconfigCmd()}, {Name: "GOGCCFLAGS", Value: strings.Join(cmd[3:], " ")}, } } func runEnv(cmd *base.Command, args []string) { env := cfg.CmdEnv env = append(env, ExtraEnvVars()...) // Do we need to call ExtraEnvVarsCostly, which is a bit expensive? // Only if we're listing all environment variables ("go env") // or the variables being requested are in the extra list. needCostly := true if len(args) > 0 { needCostly = false for _, arg := range args { switch arg { case "CGO_CFLAGS", "CGO_CPPFLAGS", "CGO_CXXFLAGS", "CGO_FFLAGS", "CGO_LDFLAGS", "PKG_CONFIG", "GOGCCFLAGS": needCostly = true } } } if needCostly { env = append(env, ExtraEnvVarsCostly()...) } if len(args) > 0 { if *envJson { var es []cfg.EnvVar for _, name := range args { e := cfg.EnvVar{Name: name, Value: findEnv(env, name)} es = append(es, e) } printEnvAsJSON(es) } else { for _, name := range args { fmt.Printf("%s\n", findEnv(env, name)) } } return } if *envJson { printEnvAsJSON(env) return } for _, e := range env { if e.Name != "TERM" { switch runtime.GOOS { default: fmt.Printf("%s=\"%s\"\n", e.Name, e.Value) case "plan9": if strings.IndexByte(e.Value, '\x00') < 0 { fmt.Printf("%s='%s'\n", e.Name, strings.Replace(e.Value, "'", "''", -1)) } else { v := strings.Split(e.Value, "\x00") fmt.Printf("%s=(", e.Name) for x, s := range v { if x > 0 { fmt.Printf(" ") } fmt.Printf("%s", s) } fmt.Printf(")\n") } case "windows": fmt.Printf("set %s=%s\n", e.Name, e.Value) } } } } func printEnvAsJSON(env []cfg.EnvVar) { m := make(map[string]string) for _, e := range env { if e.Name == "TERM" { continue } m[e.Name] = e.Value } enc := json.NewEncoder(os.Stdout) enc.SetIndent("", "\t") if err := enc.Encode(m); err != nil { base.Fatalf("%s", err) } }
fix
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/fix/fix.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 fix implements the ``go fix'' command. package fix import ( "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/load" "cmd/go/internal/modload" "cmd/go/internal/str" "fmt" "os" ) var CmdFix = &base.Command{ Run: runFix, UsageLine: "go fix [packages]", Short: "update packages to use new APIs", Long: ` Fix runs the Go fix command on the packages named by the import paths. For more about fix, see 'go doc cmd/fix'. For more about specifying packages, see 'go help packages'. To run fix with specific options, run 'go tool fix'. See also: go fmt, go vet. `, } func runFix(cmd *base.Command, args []string) { printed := false for _, pkg := range load.Packages(args) { if modload.Enabled() && !pkg.Module.Main { if !printed { fmt.Fprintf(os.Stderr, "go: not fixing packages in dependency modules\n") printed = true } continue } // Use pkg.gofiles instead of pkg.Dir so that // the command only applies to this package, // not to packages in subdirectories. files := base.RelPaths(pkg.InternalAllGoFiles()) base.Run(str.StringList(cfg.BuildToolexec, base.Tool("fix"), files)) } }
modload
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modload/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. package modload import ( "bytes" "cmd/go/internal/base" "cmd/go/internal/cache" "cmd/go/internal/cfg" "cmd/go/internal/load" "cmd/go/internal/modconv" "cmd/go/internal/modfetch" "cmd/go/internal/modfetch/codehost" "cmd/go/internal/modfile" "cmd/go/internal/module" "cmd/go/internal/mvs" "cmd/go/internal/search" "encoding/json" "fmt" "io/ioutil" "os" "path" "path/filepath" "regexp" "strconv" "strings" ) var ( cwd string MustUseModules = mustUseModules() initialized bool ModRoot string modFile *modfile.File excluded map[module.Version]bool Target module.Version gopath string CmdModInit bool // running 'go mod init' CmdModModule string // module argument for 'go mod init' ) // ModFile returns the parsed go.mod file. // // Note that after calling ImportPaths or LoadBuildList, // the require statements in the modfile.File are no longer // the source of truth and will be ignored: edits made directly // will be lost at the next call to WriteGoMod. // To make permanent changes to the require statements // in go.mod, edit it before calling ImportPaths or LoadBuildList. func ModFile() *modfile.File { return modFile } func BinDir() string { MustInit() return filepath.Join(gopath, "bin") } // mustUseModules reports whether we are invoked as vgo // (as opposed to go). // If so, we only support builds with go.mod files. func mustUseModules() bool { name := os.Args[0] name = name[strings.LastIndex(name, "/")+1:] name = name[strings.LastIndex(name, `\`)+1:] return strings.HasPrefix(name, "vgo") } var inGOPATH bool // running in GOPATH/src func Init() { if initialized { return } initialized = true env := os.Getenv("GO111MODULE") switch env { default: base.Fatalf("go: unknown environment setting GO111MODULE=%s", env) case "", "auto": // leave MustUseModules alone case "on": MustUseModules = true case "off": if !MustUseModules { return } } // Disable any prompting for passwords by Git. // Only has an effect for 2.3.0 or later, but avoiding // the prompt in earlier versions is just too hard. // If user has explicitly set GIT_TERMINAL_PROMPT=1, keep // prompting. // See golang.org/issue/9341 and golang.org/issue/12706. if os.Getenv("GIT_TERMINAL_PROMPT") == "" { os.Setenv("GIT_TERMINAL_PROMPT", "0") } // Disable any ssh connection pooling by Git. // If a Git subprocess forks a child into the background to cache a new connection, // that child keeps stdout/stderr open. After the Git subprocess exits, // os /exec expects to be able to read from the stdout/stderr pipe // until EOF to get all the data that the Git subprocess wrote before exiting. // The EOF doesn't come until the child exits too, because the child // is holding the write end of the pipe. // This is unfortunate, but it has come up at least twice // (see golang.org/issue/13453 and golang.org/issue/16104) // and confuses users when it does. // If the user has explicitly set GIT_SSH or GIT_SSH_COMMAND, // assume they know what they are doing and don't step on it. // But default to turning off ControlMaster. if os.Getenv("GIT_SSH") == "" && os.Getenv("GIT_SSH_COMMAND") == "" { os.Setenv("GIT_SSH_COMMAND", "ssh -o ControlMaster=no") } var err error cwd, err = os.Getwd() if err != nil { base.Fatalf("go: %v", err) } inGOPATH = false for _, gopath := range filepath.SplitList(cfg.BuildContext.GOPATH) { if gopath == "" { continue } if search.InDir(cwd, filepath.Join(gopath, "src")) != "" { inGOPATH = true break } } if inGOPATH && !MustUseModules { // No automatic enabling in GOPATH. if root, _ := FindModuleRoot(cwd, "", false); root != "" { cfg.GoModInGOPATH = filepath.Join(root, "go.mod") } return } if CmdModInit { // Running 'go mod init': go.mod will be created in current directory. ModRoot = cwd } else { ModRoot, _ = FindModuleRoot(cwd, "", MustUseModules) if !MustUseModules { if ModRoot == "" { return } if search.InDir(ModRoot, os.TempDir()) == "." { // If you create /tmp/go.mod for experimenting, // then any tests that create work directories under /tmp // will find it and get modules when they're not expecting them. // It's a bit of a peculiar thing to disallow but quite mysterious // when it happens. See golang.org/issue/26708. ModRoot = "" fmt.Fprintf(os.Stderr, "go: warning: ignoring go.mod in system temp root %v\n", os.TempDir()) return } } } cfg.ModulesEnabled = true load.ModBinDir = BinDir load.ModLookup = Lookup load.ModPackageModuleInfo = PackageModuleInfo load.ModImportPaths = ImportPaths load.ModPackageBuildInfo = PackageBuildInfo load.ModInfoProg = ModInfoProg load.ModImportFromFiles = ImportFromFiles load.ModDirImportPath = DirImportPath search.SetModRoot(ModRoot) } func init() { load.ModInit = Init // Set modfetch.PkgMod unconditionally, so that go clean -modcache can run even without modules enabled. if list := filepath.SplitList(cfg.BuildContext.GOPATH); len(list) > 0 && list[0] != "" { modfetch.PkgMod = filepath.Join(list[0], "pkg/mod") } } // Enabled reports whether modules are (or must be) enabled. // If modules must be enabled but are not, Enabled returns true // and then the first use of module information will call die // (usually through InitMod and MustInit). func Enabled() bool { if !initialized { panic("go: Enabled called before Init") } return ModRoot != "" || MustUseModules } // MustInit calls Init if needed and checks that // modules are enabled and the main module has been found. // If not, MustInit calls base.Fatalf with an appropriate message. func MustInit() { if Init(); ModRoot == "" { die() } if c := cache.Default(); c == nil { // With modules, there are no install locations for packages // other than the build cache. base.Fatalf("go: cannot use modules with build cache disabled") } } // Failed reports whether module loading failed. // If Failed returns true, then any use of module information will call die. func Failed() bool { Init() return cfg.ModulesEnabled && ModRoot == "" } func die() { if os.Getenv("GO111MODULE") == "off" { base.Fatalf("go: modules disabled by GO111MODULE=off; see 'go help modules'") } if inGOPATH && !MustUseModules { base.Fatalf("go: modules disabled inside GOPATH/src by GO111MODULE=auto; see 'go help modules'") } base.Fatalf("go: cannot find main module; see 'go help modules'") } func InitMod() { MustInit() if modFile != nil { return } list := filepath.SplitList(cfg.BuildContext.GOPATH) if len(list) == 0 || list[0] == "" { base.Fatalf("missing $GOPATH") } gopath = list[0] if _, err := os.Stat(filepath.Join(gopath, "go.mod")); err == nil { base.Fatalf("$GOPATH/go.mod exists but should not") } oldSrcMod := filepath.Join(list[0], "src/mod") pkgMod := filepath.Join(list[0], "pkg/mod") infoOld, errOld := os.Stat(oldSrcMod) _, errMod := os.Stat(pkgMod) if errOld == nil && infoOld.IsDir() && errMod != nil && os.IsNotExist(errMod) { os.Rename(oldSrcMod, pkgMod) } modfetch.PkgMod = pkgMod modfetch.GoSumFile = filepath.Join(ModRoot, "go.sum") codehost.WorkRoot = filepath.Join(pkgMod, "cache/vcs") if CmdModInit { // Running go mod init: do legacy module conversion legacyModInit() modFileToBuildList() WriteGoMod() return } gomod := filepath.Join(ModRoot, "go.mod") data, err := ioutil.ReadFile(gomod) if err != nil { if os.IsNotExist(err) { legacyModInit() modFileToBuildList() WriteGoMod() return } base.Fatalf("go: %v", err) } f, err := modfile.Parse(gomod, data, fixVersion) if err != nil { // Errors returned by modfile.Parse begin with file:line. base.Fatalf("go: errors parsing go.mod:\n%s\n", err) } modFile = f if len(f.Syntax.Stmt) == 0 || f.Module == nil { // Empty mod file. Must add module path. path, err := FindModulePath(ModRoot) if err != nil { base.Fatalf("go: %v", err) } f.AddModuleStmt(path) } if len(f.Syntax.Stmt) == 1 && f.Module != nil { // Entire file is just a module statement. // Populate require if possible. legacyModInit() } excluded = make(map[module.Version]bool) for _, x := range f.Exclude { excluded[x.Mod] = true } modFileToBuildList() WriteGoMod() } // modFileToBuildList initializes buildList from the modFile. func modFileToBuildList() { Target = modFile.Module.Mod list := []module.Version{Target} for _, r := range modFile.Require { list = append(list, r.Mod) } buildList = list } // Allowed reports whether module m is allowed (not excluded) by the main module's go.mod. func Allowed(m module.Version) bool { return !excluded[m] } func legacyModInit() { if modFile == nil { path, err := FindModulePath(ModRoot) if err != nil { base.Fatalf("go: %v", err) } fmt.Fprintf(os.Stderr, "go: creating new go.mod: module %s\n", path) modFile = new(modfile.File) modFile.AddModuleStmt(path) } for _, name := range altConfigs { cfg := filepath.Join(ModRoot, name) data, err := ioutil.ReadFile(cfg) if err == nil { convert := modconv.Converters[name] if convert == nil { return } fmt.Fprintf(os.Stderr, "go: copying requirements from %s\n", base.ShortPath(cfg)) cfg = filepath.ToSlash(cfg) if err := modconv.ConvertLegacyConfig(modFile, cfg, data); err != nil { base.Fatalf("go: %v", err) } if len(modFile.Syntax.Stmt) == 1 { // Add comment to avoid re-converting every time it runs. modFile.AddComment("// go: no requirements found in " + name) } return } } } var altConfigs = []string{ "Gopkg.lock", "GLOCKFILE", "Godeps/Godeps.json", "dependencies.tsv", "glide.lock", "vendor.conf", "vendor.yml", "vendor/manifest", "vendor/vendor.json", ".git/config", } // Exported only for testing. func FindModuleRoot(dir, limit string, legacyConfigOK bool) (root, file string) { dir = filepath.Clean(dir) dir1 := dir limit = filepath.Clean(limit) // Look for enclosing go.mod. for { if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { return dir, "go.mod" } if dir == limit { break } d := filepath.Dir(dir) if d == dir { break } dir = d } // Failing that, look for enclosing alternate version config. if legacyConfigOK { dir = dir1 for { for _, name := range altConfigs { if _, err := os.Stat(filepath.Join(dir, name)); err == nil { return dir, name } } if dir == limit { break } d := filepath.Dir(dir) if d == dir { break } dir = d } } return "", "" } // Exported only for testing. func FindModulePath(dir string) (string, error) { if CmdModModule != "" { // Running go mod init x/y/z; return x/y/z. return CmdModModule, nil } // Cast about for import comments, // first in top-level directory, then in subdirectories. list, _ := ioutil.ReadDir(dir) for _, info := range list { if info.Mode().IsRegular() && strings.HasSuffix(info.Name(), ".go") { if com := findImportComment(filepath.Join(dir, info.Name())); com != "" { return com, nil } } } for _, info1 := range list { if info1.IsDir() { files, _ := ioutil.ReadDir(filepath.Join(dir, info1.Name())) for _, info2 := range files { if info2.Mode().IsRegular() && strings.HasSuffix(info2.Name(), ".go") { if com := findImportComment(filepath.Join(dir, info1.Name(), info2.Name())); com != "" { return path.Dir(com), nil } } } } } // Look for Godeps.json declaring import path. data, _ := ioutil.ReadFile(filepath.Join(dir, "Godeps/Godeps.json")) var cfg1 struct{ ImportPath string } json.Unmarshal(data, &cfg1) if cfg1.ImportPath != "" { return cfg1.ImportPath, nil } // Look for vendor.json declaring import path. data, _ = ioutil.ReadFile(filepath.Join(dir, "vendor/vendor.json")) var cfg2 struct{ RootPath string } json.Unmarshal(data, &cfg2) if cfg2.RootPath != "" { return cfg2.RootPath, nil } // Look for path in GOPATH. for _, gpdir := range filepath.SplitList(cfg.BuildContext.GOPATH) { if gpdir == "" { continue } if rel := search.InDir(dir, filepath.Join(gpdir, "src")); rel != "" && rel != "." { return filepath.ToSlash(rel), nil } } // Look for .git/config with github origin as last resort. data, _ = ioutil.ReadFile(filepath.Join(dir, ".git/config")) if m := gitOriginRE.FindSubmatch(data); m != nil { return "github.com/" + string(m[1]), nil } return "", fmt.Errorf("cannot determine module path for source directory %s (outside GOPATH, no import comments)", dir) } var ( gitOriginRE = regexp.MustCompile(`(?m)^\[remote "origin"\]\r?\n\turl = (?:https://github.com/|git@github.com:|gh:)([^/]+/[^/]+?)(\.git)?\r?\n`) importCommentRE = regexp.MustCompile(`(?m)^package[ \t]+[^ \t\r\n/]+[ \t]+//[ \t]+import[ \t]+(\"[^"]+\")[ \t]*\r?\n`) ) func findImportComment(file string) string { data, err := ioutil.ReadFile(file) if err != nil { return "" } m := importCommentRE.FindSubmatch(data) if m == nil { return "" } path, err := strconv.Unquote(string(m[1])) if err != nil { return "" } return path } var allowWriteGoMod = true // DisallowWriteGoMod causes future calls to WriteGoMod to do nothing at all. func DisallowWriteGoMod() { allowWriteGoMod = false } // AllowWriteGoMod undoes the effect of DisallowWriteGoMod: // future calls to WriteGoMod will update go.mod if needed. // Note that any past calls have been discarded, so typically // a call to AlowWriteGoMod should be followed by a call to WriteGoMod. func AllowWriteGoMod() { allowWriteGoMod = true } // MinReqs returns a Reqs with minimal dependencies of Target, // as will be written to go.mod. func MinReqs() mvs.Reqs { var direct []string for _, m := range buildList[1:] { if loaded.direct[m.Path] { direct = append(direct, m.Path) } } min, err := mvs.Req(Target, buildList, direct, Reqs()) if err != nil { base.Fatalf("go: %v", err) } return &mvsReqs{buildList: append([]module.Version{Target}, min...)} } // WriteGoMod writes the current build list back to go.mod. func WriteGoMod() { // If we're using -mod=vendor we basically ignored // go.mod, so definitely don't try to write back our // incomplete view of the world. if !allowWriteGoMod || cfg.BuildMod == "vendor" { return } if loaded != nil { reqs := MinReqs() min, err := reqs.Required(Target) if err != nil { base.Fatalf("go: %v", err) } var list []*modfile.Require for _, m := range min { list = append(list, &modfile.Require{ Mod: m, Indirect: !loaded.direct[m.Path], }) } modFile.SetRequire(list) } file := filepath.Join(ModRoot, "go.mod") old, _ := ioutil.ReadFile(file) modFile.Cleanup() // clean file after edits new, err := modFile.Format() if err != nil { base.Fatalf("go: %v", err) } if !bytes.Equal(old, new) { if cfg.BuildMod == "readonly" { base.Fatalf("go: updates to go.mod needed, disabled by -mod=readonly") } if err := ioutil.WriteFile(file, new, 0666); err != nil { base.Fatalf("go: %v", err) } } modfetch.WriteGoSum() } func fixVersion(path, vers string) (string, error) { // Special case: remove the old -gopkgin- hack. if strings.HasPrefix(path, "gopkg.in/") && strings.Contains(vers, "-gopkgin-") { vers = vers[strings.Index(vers, "-gopkgin-")+len("-gopkgin-"):] } // fixVersion is called speculatively on every // module, version pair from every go.mod file. // Avoid the query if it looks OK. _, pathMajor, ok := module.SplitPathVersion(path) if !ok { return "", fmt.Errorf("malformed module path: %s", path) } if vers != "" && module.CanonicalVersion(vers) == vers && module.MatchPathMajor(vers, pathMajor) { return vers, nil } info, err := Query(path, vers, nil) if err != nil { return "", err } return info.Version, nil }
modload
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modload/import.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 modload import ( "bytes" "errors" "fmt" "go/build" "os" "path/filepath" "strings" "cmd/go/internal/cfg" "cmd/go/internal/modfetch/codehost" "cmd/go/internal/module" "cmd/go/internal/par" "cmd/go/internal/search" ) type ImportMissingError struct { ImportPath string Module module.Version } func (e *ImportMissingError) Error() string { if e.Module.Path == "" { return "cannot find module providing package " + e.ImportPath } return "missing module for import: " + e.Module.Path + "@" + e.Module.Version + " provides " + e.ImportPath } // Import finds the module and directory in the build list // containing the package with the given import path. // The answer must be unique: Import returns an error // if multiple modules attempt to provide the same package. // Import can return a module with an empty m.Path, for packages in the standard library. // Import can return an empty directory string, for fake packages like "C" and "unsafe". // // If the package cannot be found in the current build list, // Import returns an ImportMissingError as the error. // If Import can identify a module that could be added to supply the package, // the ImportMissingError records that module. func Import(path string) (m module.Version, dir string, err error) { if strings.Contains(path, "@") { return module.Version{}, "", fmt.Errorf("import path should not have @version") } if build.IsLocalImport(path) { return module.Version{}, "", fmt.Errorf("relative import not supported") } if path == "C" || path == "unsafe" { // There's no directory for import "C" or import "unsafe". return module.Version{}, "", nil } // Is the package in the standard library? if search.IsStandardImportPath(path) { if strings.HasPrefix(path, "golang_org/") { return module.Version{}, filepath.Join(cfg.GOROOT, "src/vendor", path), nil } dir := filepath.Join(cfg.GOROOT, "src", path) if _, err := os.Stat(dir); err == nil { return module.Version{}, dir, nil } } // -mod=vendor is special. // Everything must be in the main module or the main module's vendor directory. if cfg.BuildMod == "vendor" { mainDir, mainOK := dirInModule(path, Target.Path, ModRoot, true) vendorDir, vendorOK := dirInModule(path, "", filepath.Join(ModRoot, "vendor"), false) if mainOK && vendorOK { return module.Version{}, "", fmt.Errorf("ambiguous import: found %s in multiple directories:\n\t%s\n\t%s", path, mainDir, vendorDir) } // Prefer to return main directory if there is one, // Note that we're not checking that the package exists. // We'll leave that for load. if !vendorOK && mainDir != "" { return Target, mainDir, nil } readVendorList() return vendorMap[path], vendorDir, nil } // Check each module on the build list. var dirs []string var mods []module.Version for _, m := range buildList { if !maybeInModule(path, m.Path) { // Avoid possibly downloading irrelevant modules. continue } root, isLocal, err := fetch(m) if err != nil { // Report fetch error. // Note that we don't know for sure this module is necessary, // but it certainly _could_ provide the package, and even if we // continue the loop and find the package in some other module, // we need to look at this module to make sure the import is // not ambiguous. return module.Version{}, "", err } dir, ok := dirInModule(path, m.Path, root, isLocal) if ok { mods = append(mods, m) dirs = append(dirs, dir) } } if len(mods) == 1 { return mods[0], dirs[0], nil } if len(mods) > 0 { var buf bytes.Buffer fmt.Fprintf(&buf, "ambiguous import: found %s in multiple modules:", path) for i, m := range mods { fmt.Fprintf(&buf, "\n\t%s", m.Path) if m.Version != "" { fmt.Fprintf(&buf, " %s", m.Version) } fmt.Fprintf(&buf, " (%s)", dirs[i]) } return module.Version{}, "", errors.New(buf.String()) } // Not on build list. // Look up module containing the package, for addition to the build list. // Goal is to determine the module, download it to dir, and return m, dir, ErrMissing. if cfg.BuildMod == "readonly" { return module.Version{}, "", fmt.Errorf("import lookup disabled by -mod=%s", cfg.BuildMod) } m, _, err = QueryPackage(path, "latest", Allowed) if err != nil { if _, ok := err.(*codehost.VCSError); ok { return module.Version{}, "", err } return module.Version{}, "", &ImportMissingError{ImportPath: path} } return m, "", &ImportMissingError{ImportPath: path, Module: m} } // maybeInModule reports whether, syntactically, // a package with the given import path could be supplied // by a module with the given module path (mpath). func maybeInModule(path, mpath string) bool { return mpath == path || len(path) > len(mpath) && path[len(mpath)] == '/' && path[:len(mpath)] == mpath } var haveGoModCache, haveGoFilesCache par.Cache // dirInModule locates the directory that would hold the package named by the given path, // if it were in the module with module path mpath and root mdir. // If path is syntactically not within mpath, // or if mdir is a local file tree (isLocal == true) and the directory // that would hold path is in a sub-module (covered by a go.mod below mdir), // dirInModule returns "", false. // // Otherwise, dirInModule returns the name of the directory where // Go source files would be expected, along with a boolean indicating // whether there are in fact Go source files in that directory. func dirInModule(path, mpath, mdir string, isLocal bool) (dir string, haveGoFiles bool) { // Determine where to expect the package. if path == mpath { dir = mdir } else if mpath == "" { // vendor directory dir = filepath.Join(mdir, path) } else if len(path) > len(mpath) && path[len(mpath)] == '/' && path[:len(mpath)] == mpath { dir = filepath.Join(mdir, path[len(mpath)+1:]) } else { return "", false } // Check that there aren't other modules in the way. // This check is unnecessary inside the module cache // and important to skip in the vendor directory, // where all the module trees have been overlaid. // So we only check local module trees // (the main module, and any directory trees pointed at by replace directives). if isLocal { for d := dir; d != mdir && len(d) > len(mdir); { haveGoMod := haveGoModCache.Do(d, func() interface{} { _, err := os.Stat(filepath.Join(d, "go.mod")) return err == nil }).(bool) if haveGoMod { return "", false } parent := filepath.Dir(d) if parent == d { // Break the loop, as otherwise we'd loop // forever if d=="." and mdir=="". break } d = parent } } // Now committed to returning dir (not ""). // Are there Go source files in the directory? // We don't care about build tags, not even "+build ignore". // We're just looking for a plausible directory. haveGoFiles = haveGoFilesCache.Do(dir, func() interface{} { f, err := os.Open(dir) if err != nil { return false } defer f.Close() names, _ := f.Readdirnames(-1) for _, name := range names { if strings.HasSuffix(name, ".go") { info, err := os.Stat(filepath.Join(dir, name)) if err == nil && info.Mode().IsRegular() { return true } } } return false }).(bool) return dir, haveGoFiles }
modload
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modload/query.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 modload import ( "cmd/go/internal/modfetch" "cmd/go/internal/modfetch/codehost" "cmd/go/internal/module" "cmd/go/internal/semver" "fmt" pathpkg "path" "strings" ) // Query looks up a revision of a given module given a version query string. // The module must be a complete module path. // The version must take one of the following forms: // // - the literal string "latest", denoting the latest available, allowed tagged version, // with non-prereleases preferred over prereleases. // If there are no tagged versions in the repo, latest returns the most recent commit. // - v1, denoting the latest available tagged version v1.x.x. // - v1.2, denoting the latest available tagged version v1.2.x. // - v1.2.3, a semantic version string denoting that tagged version. // - <v1.2.3, <=v1.2.3, >v1.2.3, >=v1.2.3, // denoting the version closest to the target and satisfying the given operator, // with non-prereleases preferred over prereleases. // - a repository commit identifier, denoting that commit. // // If the allowed function is non-nil, Query excludes any versions for which allowed returns false. // // If path is the path of the main module and the query is "latest", // Query returns Target.Version as the version. func Query(path, query string, allowed func(module.Version) bool) (*modfetch.RevInfo, error) { if allowed == nil { allowed = func(module.Version) bool { return true } } // Parse query to detect parse errors (and possibly handle query) // before any network I/O. badVersion := func(v string) (*modfetch.RevInfo, error) { return nil, fmt.Errorf("invalid semantic version %q in range %q", v, query) } var ok func(module.Version) bool var prefix string var preferOlder bool switch { case query == "latest": ok = allowed case strings.HasPrefix(query, "<="): v := query[len("<="):] if !semver.IsValid(v) { return badVersion(v) } if isSemverPrefix(v) { // Refuse to say whether <=v1.2 allows v1.2.3 (remember, @v1.2 might mean v1.2.3). return nil, fmt.Errorf("ambiguous semantic version %q in range %q", v, query) } ok = func(m module.Version) bool { return semver.Compare(m.Version, v) <= 0 && allowed(m) } case strings.HasPrefix(query, "<"): v := query[len("<"):] if !semver.IsValid(v) { return badVersion(v) } ok = func(m module.Version) bool { return semver.Compare(m.Version, v) < 0 && allowed(m) } case strings.HasPrefix(query, ">="): v := query[len(">="):] if !semver.IsValid(v) { return badVersion(v) } ok = func(m module.Version) bool { return semver.Compare(m.Version, v) >= 0 && allowed(m) } preferOlder = true case strings.HasPrefix(query, ">"): v := query[len(">"):] if !semver.IsValid(v) { return badVersion(v) } if isSemverPrefix(v) { // Refuse to say whether >v1.2 allows v1.2.3 (remember, @v1.2 might mean v1.2.3). return nil, fmt.Errorf("ambiguous semantic version %q in range %q", v, query) } ok = func(m module.Version) bool { return semver.Compare(m.Version, v) > 0 && allowed(m) } preferOlder = true case semver.IsValid(query) && isSemverPrefix(query): ok = func(m module.Version) bool { return matchSemverPrefix(query, m.Version) && allowed(m) } prefix = query + "." case semver.IsValid(query): vers := module.CanonicalVersion(query) if !allowed(module.Version{Path: path, Version: vers}) { return nil, fmt.Errorf("%s@%s excluded", path, vers) } return modfetch.Stat(path, vers) default: // Direct lookup of semantic version or commit identifier. info, err := modfetch.Stat(path, query) if err != nil { return nil, err } if !allowed(module.Version{Path: path, Version: info.Version}) { return nil, fmt.Errorf("%s@%s excluded", path, info.Version) } return info, nil } if path == Target.Path { if query != "latest" { return nil, fmt.Errorf("can't query specific version (%q) for the main module (%s)", query, path) } if !allowed(Target) { return nil, fmt.Errorf("internal error: main module version is not allowed") } return &modfetch.RevInfo{Version: Target.Version}, nil } // Load versions and execute query. repo, err := modfetch.Lookup(path) if err != nil { return nil, err } versions, err := repo.Versions(prefix) if err != nil { return nil, err } if preferOlder { for _, v := range versions { if semver.Prerelease(v) == "" && ok(module.Version{Path: path, Version: v}) { return repo.Stat(v) } } for _, v := range versions { if semver.Prerelease(v) != "" && ok(module.Version{Path: path, Version: v}) { return repo.Stat(v) } } } else { for i := len(versions) - 1; i >= 0; i-- { v := versions[i] if semver.Prerelease(v) == "" && ok(module.Version{Path: path, Version: v}) { return repo.Stat(v) } } for i := len(versions) - 1; i >= 0; i-- { v := versions[i] if semver.Prerelease(v) != "" && ok(module.Version{Path: path, Version: v}) { return repo.Stat(v) } } } if query == "latest" { // Special case for "latest": if no tags match, use latest commit in repo, // provided it is not excluded. if info, err := repo.Latest(); err == nil && allowed(module.Version{Path: path, Version: info.Version}) { return info, nil } } return nil, fmt.Errorf("no matching versions for query %q", query) } // isSemverPrefix reports whether v is a semantic version prefix: v1 or v1.2 (not v1.2.3). // The caller is assumed to have checked that semver.IsValid(v) is true. func isSemverPrefix(v string) bool { dots := 0 for i := 0; i < len(v); i++ { switch v[i] { case '-', '+': return false case '.': dots++ if dots >= 2 { return false } } } return true } // matchSemverPrefix reports whether the shortened semantic version p // matches the full-width (non-shortened) semantic version v. func matchSemverPrefix(p, v string) bool { return len(v) > len(p) && v[len(p)] == '.' && v[:len(p)] == p } // QueryPackage looks up a revision of a module containing path. // // If multiple modules with revisions matching the query provide the requested // package, QueryPackage picks the one with the longest module path. // // If the path is in the the main module and the query is "latest", // QueryPackage returns Target as the version. func QueryPackage(path, query string, allowed func(module.Version) bool) (module.Version, *modfetch.RevInfo, error) { if _, ok := dirInModule(path, Target.Path, ModRoot, true); ok { if query != "latest" { return module.Version{}, nil, fmt.Errorf("can't query specific version (%q) for package %s in the main module (%s)", query, path, Target.Path) } if !allowed(Target) { return module.Version{}, nil, fmt.Errorf("internal error: package %s is in the main module (%s), but version is not allowed", path, Target.Path) } return Target, &modfetch.RevInfo{Version: Target.Version}, nil } finalErr := errMissing for p := path; p != "."; p = pathpkg.Dir(p) { info, err := Query(p, query, allowed) if err != nil { if _, ok := err.(*codehost.VCSError); ok { // A VCSError means we know where to find the code, // we just can't. Abort search. return module.Version{}, nil, err } if finalErr == errMissing { finalErr = err } continue } m := module.Version{Path: p, Version: info.Version} root, isLocal, err := fetch(m) if err != nil { return module.Version{}, nil, err } _, ok := dirInModule(path, m.Path, root, isLocal) if ok { return m, info, nil } } return module.Version{}, nil, finalErr }
modload
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modload/search.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 modload import ( "fmt" "os" "path/filepath" "strings" "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/imports" "cmd/go/internal/module" "cmd/go/internal/search" ) // matchPackages returns a list of packages in the list of modules // matching the pattern. Package loading assumes the given set of tags. func matchPackages(pattern string, tags map[string]bool, useStd bool, modules []module.Version) []string { match := func(string) bool { return true } treeCanMatch := func(string) bool { return true } if !search.IsMetaPackage(pattern) { match = search.MatchPattern(pattern) treeCanMatch = search.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 } var pkgs []string walkPkgs := func(root, importPathRoot string) { root = filepath.Clean(root) var cmd string if root == cfg.GOROOTsrc { cmd = filepath.Join(root, "cmd") } filepath.Walk(root, func(path string, fi os.FileInfo, err error) error { if err != nil { return nil } // Don't use GOROOT/src but do walk down into it. if path == root && importPathRoot == "" { return nil } // GOROOT/src/cmd makes use of GOROOT/src/cmd/vendor, // which module mode can't deal with. Eventually we'll stop using // that vendor directory, and then we can remove this exclusion. // golang.org/issue/26924. if path == cmd { return filepath.SkipDir } 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 := importPathRoot + filepath.ToSlash(path[len(root):]) if importPathRoot == "" { name = name[1:] // cut leading slash } 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 path != root { if _, err := os.Stat(filepath.Join(path, "go.mod")); err == nil { return filepath.SkipDir } } if !have[name] { have[name] = true if match(name) { if _, _, err := scanDir(path, tags); err != imports.ErrNoGo { pkgs = append(pkgs, name) } } } if elem == "vendor" { return filepath.SkipDir } return nil }) } if useStd { walkPkgs(cfg.GOROOTsrc, "") } for _, mod := range modules { if !treeCanMatch(mod.Path) { continue } var root string if mod.Version == "" { root = ModRoot } else { var err error root, _, err = fetch(mod) if err != nil { base.Errorf("go: %v", err) continue } } walkPkgs(root, mod.Path) } return pkgs }
modload
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modload/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. package modload import ( "bytes" "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/modfetch" "cmd/go/internal/modinfo" "cmd/go/internal/module" "cmd/go/internal/search" "encoding/hex" "fmt" "os" "path/filepath" "strings" ) var ( infoStart, _ = hex.DecodeString("3077af0c9274080241e1c107e6d618e6") infoEnd, _ = hex.DecodeString("f932433186182072008242104116d8f2") ) func isStandardImportPath(path string) bool { return findStandardImportPath(path) != "" } func findStandardImportPath(path string) string { if search.IsStandardImportPath(path) { dir := filepath.Join(cfg.GOROOT, "src", path) if _, err := os.Stat(dir); err == nil { return dir } dir = filepath.Join(cfg.GOROOT, "src/vendor", path) if _, err := os.Stat(dir); err == nil { return dir } } return "" } func PackageModuleInfo(pkgpath string) *modinfo.ModulePublic { if isStandardImportPath(pkgpath) || !Enabled() { return nil } return moduleInfo(findModule(pkgpath, pkgpath), true) } func ModuleInfo(path string) *modinfo.ModulePublic { if !Enabled() { return nil } if i := strings.Index(path, "@"); i >= 0 { return moduleInfo(module.Version{Path: path[:i], Version: path[i+1:]}, false) } for _, m := range BuildList() { if m.Path == path { return moduleInfo(m, true) } } return &modinfo.ModulePublic{ Path: path, Error: &modinfo.ModuleError{ Err: "module not in current build", }, } } // addUpdate fills in m.Update if an updated version is available. func addUpdate(m *modinfo.ModulePublic) { if m.Version != "" { if info, err := Query(m.Path, "latest", Allowed); err == nil && info.Version != m.Version { m.Update = &modinfo.ModulePublic{ Path: m.Path, Version: info.Version, Time: &info.Time, } } } } // addVersions fills in m.Versions with the list of known versions. func addVersions(m *modinfo.ModulePublic) { m.Versions, _ = versions(m.Path) } func moduleInfo(m module.Version, fromBuildList bool) *modinfo.ModulePublic { if m == Target { info := &modinfo.ModulePublic{ Path: m.Path, Version: m.Version, Main: true, Dir: ModRoot, GoMod: filepath.Join(ModRoot, "go.mod"), } if modFile.Go != nil { info.GoVersion = modFile.Go.Version } return info } info := &modinfo.ModulePublic{ Path: m.Path, Version: m.Version, Indirect: fromBuildList && loaded != nil && !loaded.direct[m.Path], } if loaded != nil { info.GoVersion = loaded.goVersion[m.Path] } if cfg.BuildMod == "vendor" { info.Dir = filepath.Join(ModRoot, "vendor", m.Path) return info } // complete fills in the extra fields in m. complete := func(m *modinfo.ModulePublic) { if m.Version != "" { if q, err := Query(m.Path, m.Version, nil); err != nil { m.Error = &modinfo.ModuleError{Err: err.Error()} } else { m.Version = q.Version m.Time = &q.Time } mod := module.Version{Path: m.Path, Version: m.Version} gomod, err := modfetch.CachePath(mod, "mod") if err == nil { if info, err := os.Stat(gomod); err == nil && info.Mode().IsRegular() { m.GoMod = gomod } } dir, err := modfetch.DownloadDir(mod) if err == nil { if info, err := os.Stat(dir); err == nil && info.IsDir() { m.Dir = dir } } } if cfg.BuildMod == "vendor" { m.Dir = filepath.Join(ModRoot, "vendor", m.Path) } } complete(info) if fromBuildList { if r := Replacement(m); r.Path != "" { info.Replace = &modinfo.ModulePublic{ Path: r.Path, Version: r.Version, GoVersion: info.GoVersion, } if r.Version == "" { if filepath.IsAbs(r.Path) { info.Replace.Dir = r.Path } else { info.Replace.Dir = filepath.Join(ModRoot, r.Path) } } complete(info.Replace) info.Dir = info.Replace.Dir info.GoMod = filepath.Join(info.Dir, "go.mod") info.Error = nil // ignore error loading original module version (it has been replaced) } } return info } func PackageBuildInfo(path string, deps []string) string { if isStandardImportPath(path) || !Enabled() { return "" } target := findModule(path, path) mdeps := make(map[module.Version]bool) for _, dep := range deps { if !isStandardImportPath(dep) { mdeps[findModule(path, dep)] = true } } var mods []module.Version delete(mdeps, target) for mod := range mdeps { mods = append(mods, mod) } module.Sort(mods) var buf bytes.Buffer fmt.Fprintf(&buf, "path\t%s\n", path) tv := target.Version if tv == "" { tv = "(devel)" } fmt.Fprintf(&buf, "mod\t%s\t%s\t%s\n", target.Path, tv, modfetch.Sum(target)) for _, mod := range mods { mv := mod.Version if mv == "" { mv = "(devel)" } r := Replacement(mod) h := "" if r.Path == "" { h = "\t" + modfetch.Sum(mod) } fmt.Fprintf(&buf, "dep\t%s\t%s%s\n", mod.Path, mod.Version, h) if r.Path != "" { fmt.Fprintf(&buf, "=>\t%s\t%s\t%s\n", r.Path, r.Version, modfetch.Sum(r)) } } return buf.String() } func findModule(target, path string) module.Version { // TODO: This should use loaded. if path == "." { return buildList[0] } for _, mod := range buildList { if maybeInModule(path, mod.Path) { return mod } } base.Fatalf("build %v: cannot find module for path %v", target, path) panic("unreachable") } func ModInfoProg(info string) []byte { return []byte(fmt.Sprintf(` package main import _ "unsafe" //go:linkname __debug_modinfo__ runtime/debug.modinfo var __debug_modinfo__ string func init() { __debug_modinfo__ = %q } `, string(infoStart)+info+string(infoEnd))) }
modload
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modload/help.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 modload import "cmd/go/internal/base" // TODO(rsc): The "module code layout" section needs to be written. var HelpModules = &base.Command{ UsageLine: "modules", Short: "modules, module versions, and more", Long: ` A module is a collection of related Go packages. Modules are the unit of source code interchange and versioning. The go command has direct support for working with modules, including recording and resolving dependencies on other modules. Modules replace the old GOPATH-based approach to specifying which source files are used in a given build. Preliminary module support Go 1.11 includes preliminary support for Go modules, including a new module-aware 'go get' command. We intend to keep revising this support, while preserving compatibility, until it can be declared official (no longer preliminary), and then at a later point we may remove support for work in GOPATH and the old 'go get' command. The quickest way to take advantage of the new Go 1.11 module support is to check out your repository into a directory outside GOPATH/src, create a go.mod file (described in the next section) there, and run go commands from within that file tree. For more fine-grained control, the module support in Go 1.11 respects a temporary environment variable, GO111MODULE, which can be set to one of three string values: off, on, or auto (the default). If GO111MODULE=off, then the go command never uses the new module support. Instead it looks in vendor directories and GOPATH to find dependencies; we now refer to this as "GOPATH mode." If GO111MODULE=on, then the go command requires the use of modules, never consulting GOPATH. We refer to this as the command being module-aware or running in "module-aware mode". If GO111MODULE=auto or is unset, then the go command enables or disables module support based on the current directory. Module support is enabled only when the current directory is outside GOPATH/src and itself contains a go.mod file or is below a directory containing a go.mod file. In module-aware mode, GOPATH no longer defines the meaning of imports during a build, but it still stores downloaded dependencies (in GOPATH/pkg/mod) and installed commands (in GOPATH/bin, unless GOBIN is set). Defining a module A module is defined by a tree of Go source files with a go.mod file in the tree's root directory. The directory containing the go.mod file is called the module root. Typically the module root will also correspond to a source code repository root (but in general it need not). The module is the set of all Go packages in the module root and its subdirectories, but excluding subtrees with their own go.mod files. The "module path" is the import path prefix corresponding to the module root. The go.mod file defines the module path and lists the specific versions of other modules that should be used when resolving imports during a build, by giving their module paths and versions. For example, this go.mod declares that the directory containing it is the root of the module with path example.com/m, and it also declares that the module depends on specific versions of golang.org/x/text and gopkg.in/yaml.v2: module example.com/m require ( golang.org/x/text v0.3.0 gopkg.in/yaml.v2 v2.1.0 ) The go.mod file can also specify replacements and excluded versions that only apply when building the module directly; they are ignored when the module is incorporated into a larger build. For more about the go.mod file, see 'go help go.mod'. To start a new module, simply create a go.mod file in the root of the module's directory tree, containing only a module statement. The 'go mod init' command can be used to do this: go mod init example.com/m In a project already using an existing dependency management tool like godep, glide, or dep, 'go mod init' will also add require statements matching the existing configuration. Once the go.mod file exists, no additional steps are required: go commands like 'go build', 'go test', or even 'go list' will automatically add new dependencies as needed to satisfy imports. The main module and the build list The "main module" is the module containing the directory where the go command is run. The go command finds the module root by looking for a go.mod in the current directory, or else the current directory's parent directory, or else the parent's parent directory, and so on. The main module's go.mod file defines the precise set of packages available for use by the go command, through require, replace, and exclude statements. Dependency modules, found by following require statements, also contribute to the definition of that set of packages, but only through their go.mod files' require statements: any replace and exclude statements in dependency modules are ignored. The replace and exclude statements therefore allow the main module complete control over its own build, without also being subject to complete control by dependencies. The set of modules providing packages to builds is called the "build list". The build list initially contains only the main module. Then the go command adds to the list the exact module versions required by modules already on the list, recursively, until there is nothing left to add to the list. If multiple versions of a particular module are added to the list, then at the end only the latest version (according to semantic version ordering) is kept for use in the build. The 'go list' command provides information about the main module and the build list. For example: go list -m # print path of main module go list -m -f={{.Dir}} # print root directory of main module go list -m all # print build list Maintaining module requirements The go.mod file is meant to be readable and editable by both programmers and tools. The go command itself automatically updates the go.mod file to maintain a standard formatting and the accuracy of require statements. Any go command that finds an unfamiliar import will look up the module containing that import and add the latest version of that module to go.mod automatically. In most cases, therefore, it suffices to add an import to source code and run 'go build', 'go test', or even 'go list': as part of analyzing the package, the go command will discover and resolve the import and update the go.mod file. Any go command can determine that a module requirement is missing and must be added, even when considering only a single package from the module. On the other hand, determining that a module requirement is no longer necessary and can be deleted requires a full view of all packages in the module, across all possible build configurations (architectures, operating systems, build tags, and so on). The 'go mod tidy' command builds that view and then adds any missing module requirements and removes unnecessary ones. As part of maintaining the require statements in go.mod, the go command tracks which ones provide packages imported directly by the current module and which ones provide packages only used indirectly by other module dependencies. Requirements needed only for indirect uses are marked with a "// indirect" comment in the go.mod file. Indirect requirements are automatically removed from the go.mod file once they are implied by other direct requirements. Indirect requirements only arise when using modules that fail to state some of their own dependencies or when explicitly upgrading a module's dependencies ahead of its own stated requirements. Because of this automatic maintenance, the information in go.mod is an up-to-date, readable description of the build. The 'go get' command updates go.mod to change the module versions used in a build. An upgrade of one module may imply upgrading others, and similarly a downgrade of one module may imply downgrading others. The 'go get' command makes these implied changes as well. If go.mod is edited directly, commands like 'go build' or 'go list' will assume that an upgrade is intended and automatically make any implied upgrades and update go.mod to reflect them. The 'go mod' command provides other functionality for use in maintaining and understanding modules and go.mod files. See 'go help mod'. The -mod build flag provides additional control over updating and use of go.mod. If invoked with -mod=readonly, the go command is disallowed from the implicit automatic updating of go.mod described above. Instead, it fails when any changes to go.mod are needed. This setting is most useful to check that go.mod does not need updates, such as in a continuous integration and testing system. The "go get" command remains permitted to update go.mod even with -mod=readonly, and the "go mod" commands do not take the -mod flag (or any other build flags). If invoked with -mod=vendor, the go command assumes that the vendor directory holds the correct copies of dependencies and ignores the dependency descriptions in go.mod. Pseudo-versions The go.mod file and the go command more generally use semantic versions as the standard form for describing module versions, so that versions can be compared to determine which should be considered earlier or later than another. A module version like v1.2.3 is introduced by tagging a revision in the underlying source repository. Untagged revisions can be referred to using a "pseudo-version" like v0.0.0-yyyymmddhhmmss-abcdefabcdef, where the time is the commit time in UTC and the final suffix is the prefix of the commit hash. The time portion ensures that two pseudo-versions can be compared to determine which happened later, the commit hash identifes the underlying commit, and the prefix (v0.0.0- in this example) is derived from the most recent tagged version in the commit graph before this commit. There are three pseudo-version forms: vX.0.0-yyyymmddhhmmss-abcdefabcdef is used when there is no earlier versioned commit with an appropriate major version before the target commit. (This was originally the only form, so some older go.mod files use this form even for commits that do follow tags.) vX.Y.Z-pre.0.yyyymmddhhmmss-abcdefabcdef is used when the most recent versioned commit before the target commit is vX.Y.Z-pre. vX.Y.(Z+1)-0.yyyymmddhhmmss-abcdefabcdef is used when the most recent versioned commit before the target commit is vX.Y.Z. Pseudo-versions never need to be typed by hand: the go command will accept the plain commit hash and translate it into a pseudo-version (or a tagged version if available) automatically. This conversion is an example of a module query. Module queries The go command accepts a "module query" in place of a module version both on the command line and in the main module's go.mod file. (After evaluating a query found in the main module's go.mod file, the go command updates the file to replace the query with its result.) A fully-specified semantic version, such as "v1.2.3", evaluates to that specific version. A semantic version prefix, such as "v1" or "v1.2", evaluates to the latest available tagged version with that prefix. A semantic version comparison, such as "<v1.2.3" or ">=v1.5.6", evaluates to the available tagged version nearest to the comparison target (the latest version for < and <=, the earliest version for > and >=). The string "latest" matches the latest available tagged version, or else the underlying source repository's latest untagged revision. A revision identifier for the underlying source repository, such as a commit hash prefix, revision tag, or branch name, selects that specific code revision. If the revision is also tagged with a semantic version, the query evaluates to that semantic version. Otherwise the query evaluates to a pseudo-version for the commit. All queries prefer release versions to pre-release versions. For example, "<v1.2.3" will prefer to return "v1.2.2" instead of "v1.2.3-pre1", even though "v1.2.3-pre1" is nearer to the comparison target. Module versions disallowed by exclude statements in the main module's go.mod are considered unavailable and cannot be returned by queries. For example, these commands are all valid: go get github.com/gorilla/mux@latest # same (@latest is default for 'go get') go get github.com/gorilla/mux@v1.6.2 # records v1.6.2 go get github.com/gorilla/mux@e3702bed2 # records v1.6.2 go get github.com/gorilla/mux@c856192 # records v0.0.0-20180517173623-c85619274f5d go get github.com/gorilla/mux@master # records current meaning of master Module compatibility and semantic versioning The go command requires that modules use semantic versions and expects that the versions accurately describe compatibility: it assumes that v1.5.4 is a backwards-compatible replacement for v1.5.3, v1.4.0, and even v1.0.0. More generally the go command expects that packages follow the "import compatibility rule", which says: "If an old package and a new package have the same import path, the new package must be backwards compatible with the old package." Because the go command assumes the import compatibility rule, a module definition can only set the minimum required version of one of its dependencies: it cannot set a maximum or exclude selected versions. Still, the import compatibility rule is not a guarantee: it may be that v1.5.4 is buggy and not a backwards-compatible replacement for v1.5.3. Because of this, the go command never updates from an older version to a newer version of a module unasked. In semantic versioning, changing the major version number indicates a lack of backwards compatibility with earlier versions. To preserve import compatibility, the go command requires that modules with major version v2 or later use a module path with that major version as the final element. For example, version v2.0.0 of example.com/m must instead use module path example.com/m/v2, and packages in that module would use that path as their import path prefix, as in example.com/m/v2/sub/pkg. Including the major version number in the module path and import paths in this way is called "semantic import versioning". Pseudo-versions for modules with major version v2 and later begin with that major version instead of v0, as in v2.0.0-20180326061214-4fc5987536ef. As a special case, module paths beginning with gopkg.in/ continue to use the conventions established on that system: the major version is always present, and it is preceded by a dot instead of a slash: gopkg.in/yaml.v1 and gopkg.in/yaml.v2, not gopkg.in/yaml and gopkg.in/yaml/v2. The go command treats modules with different module paths as unrelated: it makes no connection between example.com/m and example.com/m/v2. Modules with different major versions can be used together in a build and are kept separate by the fact that their packages use different import paths. In semantic versioning, major version v0 is for initial development, indicating no expectations of stability or backwards compatibility. Major version v0 does not appear in the module path, because those versions are preparation for v1.0.0, and v1 does not appear in the module path either. Code written before the semantic import versioning convention was introduced may use major versions v2 and later to describe the same set of unversioned import paths as used in v0 and v1. To accommodate such code, if a source code repository has a v2.0.0 or later tag for a file tree with no go.mod, the version is considered to be part of the v1 module's available versions and is given an +incompatible suffix when converted to a module version, as in v2.0.0+incompatible. The +incompatible tag is also applied to pseudo-versions derived from such versions, as in v2.0.1-0.yyyymmddhhmmss-abcdefabcdef+incompatible. In general, having a dependency in the build list (as reported by 'go list -m all') on a v0 version, pre-release version, pseudo-version, or +incompatible version is an indication that problems are more likely when upgrading that dependency, since there is no expectation of compatibility for those. See https://research.swtch.com/vgo-import for more information about semantic import versioning, and see https://semver.org/ for more about semantic versioning. Module code layout For now, see https://research.swtch.com/vgo-module for information about how source code in version control systems is mapped to module file trees. Module downloading and verification The go command maintains, in the main module's root directory alongside go.mod, a file named go.sum containing the expected cryptographic checksums of the content of specific module versions. Each time a dependency is used, its checksum is added to go.sum if missing or else required to match the existing entry in go.sum. The go command maintains a cache of downloaded packages and computes and records the cryptographic checksum of each package at download time. In normal operation, the go command checks these pre-computed checksums against the main module's go.sum file, instead of recomputing them on each command invocation. The 'go mod verify' command checks that the cached copies of module downloads still match both their recorded checksums and the entries in go.sum. The go command can fetch modules from a proxy instead of connecting to source control systems directly, according to the setting of the GOPROXY environment variable. See 'go help goproxy' for details about the proxy and also the format of the cached downloaded packages. Modules and vendoring When using modules, the go command completely ignores vendor directories. By default, the go command satisfies dependencies by downloading modules from their sources and using those downloaded copies (after verification, as described in the previous section). To allow interoperation with older versions of Go, or to ensure that all files used for a build are stored together in a single file tree, 'go mod vendor' creates a directory named vendor in the root directory of the main module and stores there all the packages from dependency modules that are needed to support builds and tests of packages in the main module. To build using the main module's top-level vendor directory to satisfy dependencies (disabling use of the usual network sources and local caches), use 'go build -mod=vendor'. Note that only the main module's top-level vendor directory is used; vendor directories in other locations are still ignored. `, } var HelpGoMod = &base.Command{ UsageLine: "go.mod", Short: "the go.mod file", Long: ` A module version is defined by a tree of source files, with a go.mod file in its root. When the go command is run, it looks in the current directory and then successive parent directories to find the go.mod marking the root of the main (current) module. The go.mod file itself is line-oriented, with // comments but no /* */ comments. Each line holds a single directive, made up of a verb followed by arguments. For example: module my/thing require other/thing v1.0.2 require new/thing v2.3.4 exclude old/thing v1.2.3 replace bad/thing v1.4.5 => good/thing v1.4.5 The verbs are module, to define the module path; require, to require a particular module at a given version or later; exclude, to exclude a particular module version from use; and replace, to replace a module version with a different module version. Exclude and replace apply only in the main module's go.mod and are ignored in dependencies. See https://research.swtch.com/vgo-mvs for details. The leading verb can be factored out of adjacent lines to create a block, like in Go imports: require ( new/thing v2.3.4 old/thing v1.2.3 ) The go.mod file is designed both to be edited directly and to be easily updated by tools. The 'go mod edit' command can be used to parse and edit the go.mod file from programs and tools. See 'go help mod edit'. The go command automatically updates go.mod each time it uses the module graph, to make sure go.mod always accurately reflects reality and is properly formatted. For example, consider this go.mod file: module M require ( A v1 B v1.0.0 C v1.0.0 D v1.2.3 E dev ) exclude D v1.2.3 The update rewrites non-canonical version identifiers to semver form, so A's v1 becomes v1.0.0 and E's dev becomes the pseudo-version for the latest commit on the dev branch, perhaps v0.0.0-20180523231146-b3f5c0f6e5f1. The update modifies requirements to respect exclusions, so the requirement on the excluded D v1.2.3 is updated to use the next available version of D, perhaps D v1.2.4 or D v1.3.0. The update removes redundant or misleading requirements. For example, if A v1.0.0 itself requires B v1.2.0 and C v1.0.0, then go.mod's requirement of B v1.0.0 is misleading (superseded by A's need for v1.2.0), and its requirement of C v1.0.0 is redundant (implied by A's need for the same version), so both will be removed. If module M contains packages that directly import packages from B or C, then the requirements will be kept but updated to the actual versions being used. Finally, the update reformats the go.mod in a canonical formatting, so that future mechanical changes will result in minimal diffs. Because the module graph defines the meaning of import statements, any commands that load packages also use and therefore update go.mod, including go build, go get, go install, go list, go test, go mod graph, go mod tidy, and go mod why. `, }
modload
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modload/query_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 modload import ( "internal/testenv" "io/ioutil" "log" "os" "path" "path/filepath" "strings" "testing" "cmd/go/internal/modfetch" "cmd/go/internal/modfetch/codehost" "cmd/go/internal/module" ) func TestMain(m *testing.M) { os.Exit(testMain(m)) } func testMain(m *testing.M) int { dir, err := ioutil.TempDir("", "modload-test-") if err != nil { log.Fatal(err) } defer os.RemoveAll(dir) modfetch.PkgMod = filepath.Join(dir, "pkg/mod") codehost.WorkRoot = filepath.Join(dir, "codework") return m.Run() } var ( queryRepo = "vcs-test.golang.org/git/querytest.git" queryRepoV2 = queryRepo + "/v2" queryRepoV3 = queryRepo + "/v3" // Empty version list (no semver tags), not actually empty. emptyRepo = "vcs-test.golang.org/git/emptytest.git" ) var queryTests = []struct { path string query string allow string vers string err string }{ /* git init echo module vcs-test.golang.org/git/querytest.git >go.mod git add go.mod git commit -m v1 go.mod git tag start for i in v0.0.0-pre1 v0.0.0 v0.0.1 v0.0.2 v0.0.3 v0.1.0 v0.1.1 v0.1.2 v0.3.0 v1.0.0 v1.1.0 v1.9.0 v1.9.9 v1.9.10-pre1; do echo before $i >status git add status git commit -m "before $i" status echo at $i >status git commit -m "at $i" status git tag $i done git tag favorite v0.0.3 git branch v2 start git checkout v2 echo module vcs-test.golang.org/git/querytest.git/v2 >go.mod git commit -m v2 go.mod for i in v2.0.0 v2.1.0 v2.2.0 v2.5.5; do echo before $i >status git add status git commit -m "before $i" status echo at $i >status git commit -m "at $i" status git tag $i done echo after v2.5.5 >status git commit -m 'after v2.5.5' status git checkout master zip -r ../querytest.zip gsutil cp ../querytest.zip gs://vcs-test/git/querytest.zip curl 'https://vcs-test.golang.org/git/querytest?go-get=1' */ {path: queryRepo, query: "<v0.0.0", vers: "v0.0.0-pre1"}, {path: queryRepo, query: "<v0.0.0-pre1", err: `no matching versions for query "<v0.0.0-pre1"`}, {path: queryRepo, query: "<=v0.0.0", vers: "v0.0.0"}, {path: queryRepo, query: ">v0.0.0", vers: "v0.0.1"}, {path: queryRepo, query: ">=v0.0.0", vers: "v0.0.0"}, {path: queryRepo, query: "v0.0.1", vers: "v0.0.1"}, {path: queryRepo, query: "v0.0.1+foo", vers: "v0.0.1"}, {path: queryRepo, query: "v0.0.99", err: `unknown revision v0.0.99`}, {path: queryRepo, query: "v0", vers: "v0.3.0"}, {path: queryRepo, query: "v0.1", vers: "v0.1.2"}, {path: queryRepo, query: "v0.2", err: `no matching versions for query "v0.2"`}, {path: queryRepo, query: "v0.0", vers: "v0.0.3"}, {path: queryRepo, query: "latest", vers: "v1.9.9"}, {path: queryRepo, query: "latest", allow: "NOMATCH", err: `no matching versions for query "latest"`}, {path: queryRepo, query: ">v1.9.9", vers: "v1.9.10-pre1"}, {path: queryRepo, query: ">v1.10.0", err: `no matching versions for query ">v1.10.0"`}, {path: queryRepo, query: ">=v1.10.0", err: `no matching versions for query ">=v1.10.0"`}, {path: queryRepo, query: "6cf84eb", vers: "v0.0.2-0.20180704023347-6cf84ebaea54"}, {path: queryRepo, query: "start", vers: "v0.0.0-20180704023101-5e9e31667ddf"}, {path: queryRepo, query: "7a1b6bf", vers: "v0.1.0"}, {path: queryRepoV2, query: "<v0.0.0", err: `no matching versions for query "<v0.0.0"`}, {path: queryRepoV2, query: "<=v0.0.0", err: `no matching versions for query "<=v0.0.0"`}, {path: queryRepoV2, query: ">v0.0.0", vers: "v2.0.0"}, {path: queryRepoV2, query: ">=v0.0.0", vers: "v2.0.0"}, {path: queryRepoV2, query: "v0.0.1+foo", vers: "v2.0.0-20180704023347-179bc86b1be3"}, {path: queryRepoV2, query: "latest", vers: "v2.5.5"}, {path: queryRepoV3, query: "latest", vers: "v3.0.0-20180704024501-e0cf3de987e6"}, {path: emptyRepo, query: "latest", vers: "v0.0.0-20180704023549-7bb914627242"}, {path: emptyRepo, query: ">v0.0.0", err: `no matching versions for query ">v0.0.0"`}, {path: emptyRepo, query: "<v10.0.0", err: `no matching versions for query "<v10.0.0"`}, } func TestQuery(t *testing.T) { testenv.MustHaveExternalNetwork(t) for _, tt := range queryTests { allow := tt.allow if allow == "" { allow = "*" } allowed := func(m module.Version) bool { ok, _ := path.Match(allow, m.Version) return ok } t.Run(strings.Replace(tt.path, "/", "_", -1)+"/"+tt.query+"/"+allow, func(t *testing.T) { info, err := Query(tt.path, tt.query, allowed) if tt.err != "" { if err != nil && err.Error() == tt.err { return } t.Fatalf("Query(%q, %q, %v): %v, want error %q", tt.path, tt.query, allow, err, tt.err) } if err != nil { t.Fatalf("Query(%q, %q, %v): %v", tt.path, tt.query, allow, err) } if info.Version != tt.vers { t.Errorf("Query(%q, %q, %v) = %v, want %v", tt.path, tt.query, allow, info.Version, tt.vers) } }) } }
modload
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modload/list.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 modload import ( "fmt" "os" "strings" "cmd/go/internal/base" "cmd/go/internal/modinfo" "cmd/go/internal/module" "cmd/go/internal/par" "cmd/go/internal/search" ) func ListModules(args []string, listU, listVersions bool) []*modinfo.ModulePublic { mods := listModules(args) if listU || listVersions { var work par.Work for _, m := range mods { work.Add(m) if m.Replace != nil { work.Add(m.Replace) } } work.Do(10, func(item interface{}) { m := item.(*modinfo.ModulePublic) if listU { addUpdate(m) } if listVersions { addVersions(m) } }) } return mods } func listModules(args []string) []*modinfo.ModulePublic { LoadBuildList() if len(args) == 0 { return []*modinfo.ModulePublic{moduleInfo(buildList[0], true)} } var mods []*modinfo.ModulePublic matchedBuildList := make([]bool, len(buildList)) for _, arg := range args { if strings.Contains(arg, `\`) { base.Fatalf("go: module paths never use backslash") } if search.IsRelativePath(arg) { base.Fatalf("go: cannot use relative path %s to specify module", arg) } if i := strings.Index(arg, "@"); i >= 0 { info, err := Query(arg[:i], arg[i+1:], nil) if err != nil { mods = append(mods, &modinfo.ModulePublic{ Path: arg[:i], Version: arg[i+1:], Error: &modinfo.ModuleError{ Err: err.Error(), }, }) continue } mods = append(mods, moduleInfo(module.Version{Path: arg[:i], Version: info.Version}, false)) continue } // Module path or pattern. var match func(string) bool var literal bool if arg == "all" { match = func(string) bool { return true } } else if strings.Contains(arg, "...") { match = search.MatchPattern(arg) } else { match = func(p string) bool { return arg == p } literal = true } matched := false for i, m := range buildList { if match(m.Path) { matched = true if !matchedBuildList[i] { matchedBuildList[i] = true mods = append(mods, moduleInfo(m, true)) } } } if !matched { if literal { mods = append(mods, &modinfo.ModulePublic{ Path: arg, Error: &modinfo.ModuleError{ Err: fmt.Sprintf("module %q is not a known dependency", arg), }, }) } else { fmt.Fprintf(os.Stderr, "warning: pattern %q matched no module dependencies\n", arg) } } } return mods }
modload
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modload/import_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 modload import ( "internal/testenv" "regexp" "strings" "testing" ) var importTests = []struct { path string err string }{ { path: "golang.org/x/net/context", err: "missing module for import: golang.org/x/net@.* provides golang.org/x/net/context", }, { path: "golang.org/x/net", err: "cannot find module providing package golang.org/x/net", }, { path: "golang.org/x/text", err: "missing module for import: golang.org/x/text@.* provides golang.org/x/text", }, { path: "github.com/rsc/quote/buggy", err: "missing module for import: github.com/rsc/quote@v1.5.2 provides github.com/rsc/quote/buggy", }, { path: "github.com/rsc/quote", err: "missing module for import: github.com/rsc/quote@v1.5.2 provides github.com/rsc/quote", }, { path: "golang.org/x/foo/bar", err: "cannot find module providing package golang.org/x/foo/bar", }, } func TestImport(t *testing.T) { testenv.MustHaveExternalNetwork(t) for _, tt := range importTests { t.Run(strings.Replace(tt.path, "/", "_", -1), func(t *testing.T) { // Note that there is no build list, so Import should always fail. m, dir, err := Import(tt.path) if err == nil { t.Fatalf("Import(%q) = %v, %v, nil; expected error", tt.path, m, dir) } if !regexp.MustCompile(tt.err).MatchString(err.Error()) { t.Fatalf("Import(%q): error %q, want error matching %#q", tt.path, err, tt.err) } }) } }
modload
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modload/load.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 modload import ( "bytes" "errors" "fmt" "go/build" "io/ioutil" "os" "path" "path/filepath" "sort" "strings" "sync" "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/imports" "cmd/go/internal/modfetch" "cmd/go/internal/modfile" "cmd/go/internal/module" "cmd/go/internal/mvs" "cmd/go/internal/par" "cmd/go/internal/search" "cmd/go/internal/semver" "cmd/go/internal/str" ) // buildList is the list of modules to use for building packages. // It is initialized by calling ImportPaths, ImportFromFiles, // LoadALL, or LoadBuildList, each of which uses loaded.load. // // Ideally, exactly ONE of those functions would be called, // and exactly once. Most of the time, that's true. // During "go get" it may not be. TODO(rsc): Figure out if // that restriction can be established, or else document why not. // var buildList []module.Version // loaded is the most recently-used package loader. // It holds details about individual packages. // // Note that loaded.buildList is only valid during a load operation; // afterward, it is copied back into the global buildList, // which should be used instead. var loaded *loader // ImportPaths returns the set of packages matching the args (patterns), // adding modules to the build list as needed to satisfy new imports. func ImportPaths(patterns []string) []*search.Match { InitMod() var matches []*search.Match for _, pattern := range search.CleanPatterns(patterns) { m := &search.Match{ Pattern: pattern, Literal: !strings.Contains(pattern, "...") && !search.IsMetaPackage(pattern), } if m.Literal { m.Pkgs = []string{pattern} } matches = append(matches, m) } fsDirs := make([][]string, len(matches)) loaded = newLoader() updateMatches := func(iterating bool) { for i, m := range matches { switch { case build.IsLocalImport(m.Pattern) || filepath.IsAbs(m.Pattern): // Evaluate list of file system directories on first iteration. if fsDirs[i] == nil { var dirs []string if m.Literal { dirs = []string{m.Pattern} } else { dirs = search.MatchPackagesInFS(m.Pattern).Pkgs } fsDirs[i] = dirs } // Make a copy of the directory list and translate to import paths. // Note that whether a directory corresponds to an import path // changes as the build list is updated, and a directory can change // from not being in the build list to being in it and back as // the exact version of a particular module increases during // the loader iterations. m.Pkgs = str.StringList(fsDirs[i]) for i, pkg := range m.Pkgs { dir := pkg if !filepath.IsAbs(dir) { dir = filepath.Join(cwd, pkg) } else { dir = filepath.Clean(dir) } // Note: The checks for @ here are just to avoid misinterpreting // the module cache directories (formerly GOPATH/src/mod/foo@v1.5.2/bar). // It's not strictly necessary but helpful to keep the checks. if dir == ModRoot { pkg = Target.Path } else if strings.HasPrefix(dir, ModRoot+string(filepath.Separator)) && !strings.Contains(dir[len(ModRoot):], "@") { suffix := filepath.ToSlash(dir[len(ModRoot):]) if strings.HasPrefix(suffix, "/vendor/") { // TODO getmode vendor check pkg = strings.TrimPrefix(suffix, "/vendor/") } else { pkg = Target.Path + suffix } } else if sub := search.InDir(dir, cfg.GOROOTsrc); sub != "" && !strings.Contains(sub, "@") { pkg = filepath.ToSlash(sub) } else if path := pathInModuleCache(dir); path != "" { pkg = path } else { pkg = "" if !iterating { base.Errorf("go: directory %s outside available modules", base.ShortPath(dir)) } } info, err := os.Stat(dir) if err != nil || !info.IsDir() { // If the directory does not exist, // don't turn it into an import path // that will trigger a lookup. pkg = "" if !iterating { if err != nil { base.Errorf("go: no such directory %v", m.Pattern) } else { base.Errorf("go: %s is not a directory", m.Pattern) } } } m.Pkgs[i] = pkg } case strings.Contains(m.Pattern, "..."): m.Pkgs = matchPackages(m.Pattern, loaded.tags, true, buildList) case m.Pattern == "all": loaded.testAll = true if iterating { // Enumerate the packages in the main module. // We'll load the dependencies as we find them. m.Pkgs = matchPackages("...", loaded.tags, false, []module.Version{Target}) } else { // Starting with the packages in the main module, // enumerate the full list of "all". m.Pkgs = loaded.computePatternAll(m.Pkgs) } case search.IsMetaPackage(m.Pattern): // std, cmd if len(m.Pkgs) == 0 { m.Pkgs = search.MatchPackages(m.Pattern).Pkgs } } } } loaded.load(func() []string { var roots []string updateMatches(true) for _, m := range matches { for _, pkg := range m.Pkgs { if pkg != "" { roots = append(roots, pkg) } } } return roots }) // One last pass to finalize wildcards. updateMatches(false) // A given module path may be used as itself or as a replacement for another // module, but not both at the same time. Otherwise, the aliasing behavior is // too subtle (see https://golang.org/issue/26607), and we don't want to // commit to a specific behavior at this point. firstPath := make(map[module.Version]string, len(buildList)) for _, mod := range buildList { src := mod if rep := Replacement(mod); rep.Path != "" { src = rep } if prev, ok := firstPath[src]; !ok { firstPath[src] = mod.Path } else if prev != mod.Path { base.Errorf("go: %s@%s used for two different module paths (%s and %s)", src.Path, src.Version, prev, mod.Path) } } base.ExitIfErrors() WriteGoMod() search.WarnUnmatched(matches) return matches } // pathInModuleCache returns the import path of the directory dir, // if dir is in the module cache copy of a module in our build list. func pathInModuleCache(dir string) string { for _, m := range buildList[1:] { root, err := modfetch.DownloadDir(m) if err != nil { continue } if sub := search.InDir(dir, root); sub != "" { sub = filepath.ToSlash(sub) if !strings.Contains(sub, "/vendor/") && !strings.HasPrefix(sub, "vendor/") && !strings.Contains(sub, "@") { return path.Join(m.Path, filepath.ToSlash(sub)) } } } return "" } // warnPattern returns list, the result of matching pattern, // but if list is empty then first it prints a warning about // the pattern not matching any packages. func warnPattern(pattern string, list []string) []string { if len(list) == 0 { fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern) } return list } // ImportFromFiles adds modules to the build list as needed // to satisfy the imports in the named Go source files. func ImportFromFiles(gofiles []string) { InitMod() imports, testImports, err := imports.ScanFiles(gofiles, imports.Tags()) if err != nil { base.Fatalf("go: %v", err) } loaded = newLoader() loaded.load(func() []string { var roots []string roots = append(roots, imports...) roots = append(roots, testImports...) return roots }) WriteGoMod() } // DirImportPath returns the effective import path for dir, // provided it is within the main module, or else returns ".". func DirImportPath(dir string) string { if !filepath.IsAbs(dir) { dir = filepath.Join(cwd, dir) } else { dir = filepath.Clean(dir) } if dir == ModRoot { return Target.Path } if strings.HasPrefix(dir, ModRoot+string(filepath.Separator)) { suffix := filepath.ToSlash(dir[len(ModRoot):]) if strings.HasPrefix(suffix, "/vendor/") { return strings.TrimPrefix(suffix, "/vendor/") } return Target.Path + suffix } return "." } // LoadBuildList loads and returns the build list from go.mod. // The loading of the build list happens automatically in ImportPaths: // LoadBuildList need only be called if ImportPaths is not // (typically in commands that care about the module but // no particular package). func LoadBuildList() []module.Version { InitMod() ReloadBuildList() WriteGoMod() return buildList } func ReloadBuildList() []module.Version { loaded = newLoader() loaded.load(func() []string { return nil }) return buildList } // LoadALL returns the set of all packages in the current module // and their dependencies in any other modules, without filtering // due to build tags, except "+build ignore". // It adds modules to the build list as needed to satisfy new imports. // This set is useful for deciding whether a particular import is needed // anywhere in a module. func LoadALL() []string { return loadAll(true) } // LoadVendor is like LoadALL but only follows test dependencies // for tests in the main module. Tests in dependency modules are // ignored completely. // This set is useful for identifying the which packages to include in a vendor directory. func LoadVendor() []string { return loadAll(false) } func loadAll(testAll bool) []string { InitMod() loaded = newLoader() loaded.isALL = true loaded.tags = anyTags loaded.testAll = testAll if !testAll { loaded.testRoots = true } all := TargetPackages() loaded.load(func() []string { return all }) WriteGoMod() var paths []string for _, pkg := range loaded.pkgs { if e, ok := pkg.err.(*ImportMissingError); ok && e.Module.Path == "" { continue // Package doesn't actually exist. } paths = append(paths, pkg.path) } return paths } // anyTags is a special tags map that satisfies nearly all build tag expressions. // Only "ignore" and malformed build tag requirements are considered false. var anyTags = map[string]bool{"*": true} // TargetPackages returns the list of packages in the target (top-level) module, // under all build tag settings. func TargetPackages() []string { return matchPackages("...", anyTags, false, []module.Version{Target}) } // BuildList returns the module build list, // typically constructed by a previous call to // LoadBuildList or ImportPaths. // The caller must not modify the returned list. func BuildList() []module.Version { return buildList } // SetBuildList sets the module build list. // The caller is responsible for ensuring that the list is valid. // SetBuildList does not retain a reference to the original list. func SetBuildList(list []module.Version) { buildList = append([]module.Version{}, list...) } // ImportMap returns the actual package import path // for an import path found in source code. // If the given import path does not appear in the source code // for the packages that have been loaded, ImportMap returns the empty string. func ImportMap(path string) string { pkg, ok := loaded.pkgCache.Get(path).(*loadPkg) if !ok { return "" } return pkg.path } // PackageDir returns the directory containing the source code // for the package named by the import path. func PackageDir(path string) string { pkg, ok := loaded.pkgCache.Get(path).(*loadPkg) if !ok { return "" } return pkg.dir } // PackageModule returns the module providing the package named by the import path. func PackageModule(path string) module.Version { pkg, ok := loaded.pkgCache.Get(path).(*loadPkg) if !ok { return module.Version{} } return pkg.mod } // ModuleUsedDirectly reports whether the main module directly imports // some package in the module with the given path. func ModuleUsedDirectly(path string) bool { return loaded.direct[path] } // Lookup returns the source directory, import path, and any loading error for // the package at path. // Lookup requires that one of the Load functions in this package has already // been called. func Lookup(path string) (dir, realPath string, err error) { pkg, ok := loaded.pkgCache.Get(path).(*loadPkg) if !ok { // The loader should have found all the relevant paths. // There are a few exceptions, though: // - during go list without -test, the p.Resolve calls to process p.TestImports and p.XTestImports // end up here to canonicalize the import paths. // - during any load, non-loaded packages like "unsafe" end up here. // - during any load, build-injected dependencies like "runtime/cgo" end up here. // - because we ignore appengine/* in the module loader, // the dependencies of any actual appengine/* library end up here. dir := findStandardImportPath(path) if dir != "" { return dir, path, nil } return "", "", errMissing } return pkg.dir, pkg.path, pkg.err } // A loader manages the process of loading information about // the required packages for a particular build, // checking that the packages are available in the module set, // and updating the module set if needed. // Loading is an iterative process: try to load all the needed packages, // but if imports are missing, try to resolve those imports, and repeat. // // Although most of the loading state is maintained in the loader struct, // one key piece - the build list - is a global, so that it can be modified // separate from the loading operation, such as during "go get" // upgrades/downgrades or in "go mod" operations. // TODO(rsc): It might be nice to make the loader take and return // a buildList rather than hard-coding use of the global. type loader struct { tags map[string]bool // tags for scanDir testRoots bool // include tests for roots isALL bool // created with LoadALL testAll bool // include tests for all packages // reset on each iteration roots []*loadPkg pkgs []*loadPkg work *par.Work // current work queue pkgCache *par.Cache // map from string to *loadPkg // computed at end of iterations direct map[string]bool // imported directly by main module goVersion map[string]string // go version recorded in each module } // LoadTests controls whether the loaders load tests of the root packages. var LoadTests bool func newLoader() *loader { ld := new(loader) ld.tags = imports.Tags() ld.testRoots = LoadTests return ld } func (ld *loader) reset() { ld.roots = nil ld.pkgs = nil ld.work = new(par.Work) ld.pkgCache = new(par.Cache) } // A loadPkg records information about a single loaded package. type loadPkg struct { path string // import path mod module.Version // module providing package dir string // directory containing source code imports []*loadPkg // packages imported by this one err error // error loading package stack *loadPkg // package importing this one in minimal import stack for this pkg test *loadPkg // package with test imports, if we need test testOf *loadPkg testImports []string // test-only imports, saved for use by pkg.test. } var errMissing = errors.New("cannot find package") // load attempts to load the build graph needed to process a set of root packages. // The set of root packages is defined by the addRoots function, // which must call add(path) with the import path of each root package. func (ld *loader) load(roots func() []string) { var err error reqs := Reqs() buildList, err = mvs.BuildList(Target, reqs) if err != nil { base.Fatalf("go: %v", err) } added := make(map[string]bool) for { ld.reset() if roots != nil { // Note: the returned roots can change on each iteration, // since the expansion of package patterns depends on the // build list we're using. for _, path := range roots() { ld.work.Add(ld.pkg(path, true)) } } ld.work.Do(10, ld.doPkg) ld.buildStacks() numAdded := 0 haveMod := make(map[module.Version]bool) for _, m := range buildList { haveMod[m] = true } for _, pkg := range ld.pkgs { if err, ok := pkg.err.(*ImportMissingError); ok && err.Module.Path != "" { if added[pkg.path] { base.Fatalf("go: %s: looping trying to add package", pkg.stackText()) } added[pkg.path] = true numAdded++ if !haveMod[err.Module] { haveMod[err.Module] = true buildList = append(buildList, err.Module) } continue } // Leave other errors for Import or load.Packages to report. } base.ExitIfErrors() if numAdded == 0 { break } // Recompute buildList with all our additions. reqs = Reqs() buildList, err = mvs.BuildList(Target, reqs) if err != nil { base.Fatalf("go: %v", err) } } base.ExitIfErrors() // Compute directly referenced dependency modules. ld.direct = make(map[string]bool) for _, pkg := range ld.pkgs { if pkg.mod == Target { for _, dep := range pkg.imports { if dep.mod.Path != "" { ld.direct[dep.mod.Path] = true } } } } // Add Go versions, computed during walk. ld.goVersion = make(map[string]string) for _, m := range buildList { v, _ := reqs.(*mvsReqs).versions.Load(m) ld.goVersion[m.Path], _ = v.(string) } // Mix in direct markings (really, lack of indirect markings) // from go.mod, unless we scanned the whole module // and can therefore be sure we know better than go.mod. if !ld.isALL && modFile != nil { for _, r := range modFile.Require { if !r.Indirect { ld.direct[r.Mod.Path] = true } } } } // pkg returns the *loadPkg for path, creating and queuing it if needed. // If the package should be tested, its test is created but not queued // (the test is queued after processing pkg). // If isRoot is true, the pkg is being queued as one of the roots of the work graph. func (ld *loader) pkg(path string, isRoot bool) *loadPkg { return ld.pkgCache.Do(path, func() interface{} { pkg := &loadPkg{ path: path, } if ld.testRoots && isRoot || ld.testAll { test := &loadPkg{ path: path, testOf: pkg, } pkg.test = test } if isRoot { ld.roots = append(ld.roots, pkg) } ld.work.Add(pkg) return pkg }).(*loadPkg) } // doPkg processes a package on the work queue. func (ld *loader) doPkg(item interface{}) { // TODO: what about replacements? pkg := item.(*loadPkg) var imports []string if pkg.testOf != nil { pkg.dir = pkg.testOf.dir pkg.mod = pkg.testOf.mod imports = pkg.testOf.testImports } else { if strings.Contains(pkg.path, "@") { // Leave for error during load. return } if build.IsLocalImport(pkg.path) { // Leave for error during load. // (Module mode does not allow local imports.) return } pkg.mod, pkg.dir, pkg.err = Import(pkg.path) if pkg.dir == "" { return } var testImports []string var err error imports, testImports, err = scanDir(pkg.dir, ld.tags) if err != nil { pkg.err = err return } if pkg.test != nil { pkg.testImports = testImports } } for _, path := range imports { pkg.imports = append(pkg.imports, ld.pkg(path, false)) } // Now that pkg.dir, pkg.mod, pkg.testImports are set, we can queue pkg.test. // TODO: All that's left is creating new imports. Why not just do it now? if pkg.test != nil { ld.work.Add(pkg.test) } } // computePatternAll returns the list of packages matching pattern "all", // starting with a list of the import paths for the packages in the main module. func (ld *loader) computePatternAll(paths []string) []string { seen := make(map[*loadPkg]bool) var all []string var walk func(*loadPkg) walk = func(pkg *loadPkg) { if seen[pkg] { return } seen[pkg] = true if pkg.testOf == nil { all = append(all, pkg.path) } for _, p := range pkg.imports { walk(p) } if p := pkg.test; p != nil { walk(p) } } for _, path := range paths { walk(ld.pkg(path, false)) } sort.Strings(all) return all } // scanDir is like imports.ScanDir but elides known magic imports from the list, // so that we do not go looking for packages that don't really exist. // // The standard magic import is "C", for cgo. // // The only other known magic imports are appengine and appengine/*. // These are so old that they predate "go get" and did not use URL-like paths. // Most code today now uses google.golang.org/appengine instead, // but not all code has been so updated. When we mostly ignore build tags // during "go vendor", we look into "// +build appengine" files and // may see these legacy imports. We drop them so that the module // search does not look for modules to try to satisfy them. func scanDir(dir string, tags map[string]bool) (imports_, testImports []string, err error) { imports_, testImports, err = imports.ScanDir(dir, tags) filter := func(x []string) []string { w := 0 for _, pkg := range x { if pkg != "C" && pkg != "appengine" && !strings.HasPrefix(pkg, "appengine/") && pkg != "appengine_internal" && !strings.HasPrefix(pkg, "appengine_internal/") { x[w] = pkg w++ } } return x[:w] } return filter(imports_), filter(testImports), err } // buildStacks computes minimal import stacks for each package, // for use in error messages. When it completes, packages that // are part of the original root set have pkg.stack == nil, // and other packages have pkg.stack pointing at the next // package up the import stack in their minimal chain. // As a side effect, buildStacks also constructs ld.pkgs, // the list of all packages loaded. func (ld *loader) buildStacks() { if len(ld.pkgs) > 0 { panic("buildStacks") } for _, pkg := range ld.roots { pkg.stack = pkg // sentinel to avoid processing in next loop ld.pkgs = append(ld.pkgs, pkg) } for i := 0; i < len(ld.pkgs); i++ { // not range: appending to ld.pkgs in loop pkg := ld.pkgs[i] for _, next := range pkg.imports { if next.stack == nil { next.stack = pkg ld.pkgs = append(ld.pkgs, next) } } if next := pkg.test; next != nil && next.stack == nil { next.stack = pkg ld.pkgs = append(ld.pkgs, next) } } for _, pkg := range ld.roots { pkg.stack = nil } } // stackText builds the import stack text to use when // reporting an error in pkg. It has the general form // // import root -> // import other -> // import other2 -> // import pkg // func (pkg *loadPkg) stackText() string { var stack []*loadPkg for p := pkg.stack; p != nil; p = p.stack { stack = append(stack, p) } var buf bytes.Buffer for i := len(stack) - 1; i >= 0; i-- { p := stack[i] if p.testOf != nil { fmt.Fprintf(&buf, "test ->\n\t") } else { fmt.Fprintf(&buf, "import %q ->\n\t", p.path) } } fmt.Fprintf(&buf, "import %q", pkg.path) return buf.String() } // why returns the text to use in "go mod why" output about the given package. // It is less ornate than the stackText but conatins the same information. func (pkg *loadPkg) why() string { var buf strings.Builder var stack []*loadPkg for p := pkg; p != nil; p = p.stack { stack = append(stack, p) } for i := len(stack) - 1; i >= 0; i-- { p := stack[i] if p.testOf != nil { fmt.Fprintf(&buf, "%s.test\n", p.testOf.path) } else { fmt.Fprintf(&buf, "%s\n", p.path) } } return buf.String() } // Why returns the "go mod why" output stanza for the given package, // without the leading # comment. // The package graph must have been loaded already, usually by LoadALL. // If there is no reason for the package to be in the current build, // Why returns an empty string. func Why(path string) string { pkg, ok := loaded.pkgCache.Get(path).(*loadPkg) if !ok { return "" } return pkg.why() } // WhyDepth returns the number of steps in the Why listing. // If there is no reason for the package to be in the current build, // WhyDepth returns 0. func WhyDepth(path string) int { n := 0 pkg, _ := loaded.pkgCache.Get(path).(*loadPkg) for p := pkg; p != nil; p = p.stack { n++ } return n } // Replacement returns the replacement for mod, if any, from go.mod. // If there is no replacement for mod, Replacement returns // a module.Version with Path == "". func Replacement(mod module.Version) module.Version { if modFile == nil { // Happens during testing. return module.Version{} } var found *modfile.Replace for _, r := range modFile.Replace { if r.Old.Path == mod.Path && (r.Old.Version == "" || r.Old.Version == mod.Version) { found = r // keep going } } if found == nil { return module.Version{} } return found.New } // mvsReqs implements mvs.Reqs for module semantic versions, // with any exclusions or replacements applied internally. type mvsReqs struct { buildList []module.Version cache par.Cache versions sync.Map } // Reqs returns the current module requirement graph. // Future calls to SetBuildList do not affect the operation // of the returned Reqs. func Reqs() mvs.Reqs { r := &mvsReqs{ buildList: buildList, } return r } func (r *mvsReqs) Required(mod module.Version) ([]module.Version, error) { type cached struct { list []module.Version err error } c := r.cache.Do(mod, func() interface{} { list, err := r.required(mod) if err != nil { return cached{nil, err} } for i, mv := range list { for excluded[mv] { mv1, err := r.next(mv) if err != nil { return cached{nil, err} } if mv1.Version == "none" { return cached{nil, fmt.Errorf("%s(%s) depends on excluded %s(%s) with no newer version available", mod.Path, mod.Version, mv.Path, mv.Version)} } mv = mv1 } list[i] = mv } return cached{list, nil} }).(cached) return c.list, c.err } var vendorOnce sync.Once var ( vendorList []module.Version vendorMap map[string]module.Version ) // readVendorList reads the list of vendored modules from vendor/modules.txt. func readVendorList() { vendorOnce.Do(func() { vendorList = nil vendorMap = make(map[string]module.Version) data, _ := ioutil.ReadFile(filepath.Join(ModRoot, "vendor/modules.txt")) var m module.Version for _, line := range strings.Split(string(data), "\n") { if strings.HasPrefix(line, "# ") { f := strings.Fields(line) m = module.Version{} if len(f) == 3 && semver.IsValid(f[2]) { m = module.Version{Path: f[1], Version: f[2]} vendorList = append(vendorList, m) } } else if m.Path != "" { f := strings.Fields(line) if len(f) == 1 { vendorMap[f[0]] = m } } } }) } func (r *mvsReqs) modFileToList(f *modfile.File) []module.Version { var list []module.Version for _, r := range f.Require { list = append(list, r.Mod) } return list } func (r *mvsReqs) required(mod module.Version) ([]module.Version, error) { if mod == Target { if modFile.Go != nil { r.versions.LoadOrStore(mod, modFile.Go.Version) } var list []module.Version return append(list, r.buildList[1:]...), nil } if cfg.BuildMod == "vendor" { // For every module other than the target, // return the full list of modules from modules.txt. readVendorList() return vendorList, nil } origPath := mod.Path if repl := Replacement(mod); repl.Path != "" { if repl.Version == "" { // TODO: need to slip the new version into the tags list etc. dir := repl.Path if !filepath.IsAbs(dir) { dir = filepath.Join(ModRoot, dir) } gomod := filepath.Join(dir, "go.mod") data, err := ioutil.ReadFile(gomod) if err != nil { base.Errorf("go: parsing %s: %v", base.ShortPath(gomod), err) return nil, ErrRequire } f, err := modfile.ParseLax(gomod, data, nil) if err != nil { base.Errorf("go: parsing %s: %v", base.ShortPath(gomod), err) return nil, ErrRequire } if f.Go != nil { r.versions.LoadOrStore(mod, f.Go.Version) } return r.modFileToList(f), nil } mod = repl } if mod.Version == "none" { return nil, nil } if !semver.IsValid(mod.Version) { // Disallow the broader queries supported by fetch.Lookup. base.Fatalf("go: internal error: %s@%s: unexpected invalid semantic version", mod.Path, mod.Version) } data, err := modfetch.GoMod(mod.Path, mod.Version) if err != nil { base.Errorf("go: %s@%s: %v\n", mod.Path, mod.Version, err) return nil, ErrRequire } f, err := modfile.ParseLax("go.mod", data, nil) if err != nil { base.Errorf("go: %s@%s: parsing go.mod: %v", mod.Path, mod.Version, err) return nil, ErrRequire } if f.Module == nil { base.Errorf("go: %s@%s: parsing go.mod: missing module line", mod.Path, mod.Version) return nil, ErrRequire } if mpath := f.Module.Mod.Path; mpath != origPath && mpath != mod.Path { base.Errorf("go: %s@%s: parsing go.mod: unexpected module path %q", mod.Path, mod.Version, mpath) return nil, ErrRequire } if f.Go != nil { r.versions.LoadOrStore(mod, f.Go.Version) } return r.modFileToList(f), nil } // ErrRequire is the sentinel error returned when Require encounters problems. // It prints the problems directly to standard error, so that multiple errors // can be displayed easily. var ErrRequire = errors.New("error loading module requirements") func (*mvsReqs) Max(v1, v2 string) string { if v1 != "" && semver.Compare(v1, v2) == -1 { return v2 } return v1 } // Upgrade is a no-op, here to implement mvs.Reqs. // The upgrade logic for go get -u is in ../modget/get.go. func (*mvsReqs) Upgrade(m module.Version) (module.Version, error) { return m, nil } func versions(path string) ([]string, error) { // Note: modfetch.Lookup and repo.Versions are cached, // so there's no need for us to add extra caching here. repo, err := modfetch.Lookup(path) if err != nil { return nil, err } return repo.Versions("") } // Previous returns the tagged version of m.Path immediately prior to // m.Version, or version "none" if no prior version is tagged. func (*mvsReqs) Previous(m module.Version) (module.Version, error) { list, err := versions(m.Path) if err != nil { return module.Version{}, err } i := sort.Search(len(list), func(i int) bool { return semver.Compare(list[i], m.Version) >= 0 }) if i > 0 { return module.Version{Path: m.Path, Version: list[i-1]}, nil } return module.Version{Path: m.Path, Version: "none"}, nil } // next returns the next version of m.Path after m.Version. // It is only used by the exclusion processing in the Required method, // not called directly by MVS. func (*mvsReqs) next(m module.Version) (module.Version, error) { list, err := versions(m.Path) if err != nil { return module.Version{}, err } i := sort.Search(len(list), func(i int) bool { return semver.Compare(list[i], m.Version) > 0 }) if i < len(list) { return module.Version{Path: m.Path, Version: list[i]}, nil } return module.Version{Path: m.Path, Version: "none"}, nil } func fetch(mod module.Version) (dir string, isLocal bool, err error) { if mod == Target { return ModRoot, true, nil } if r := Replacement(mod); r.Path != "" { if r.Version == "" { dir = r.Path if !filepath.IsAbs(dir) { dir = filepath.Join(ModRoot, dir) } return dir, true, nil } mod = r } dir, err = modfetch.Download(mod) return dir, false, err }
cache
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/cache/default_unix_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. // +build !windows,!darwin,!plan9 package cache import ( "os" "strings" "testing" ) func TestDefaultDir(t *testing.T) { goCacheDir := "/tmp/test-go-cache" xdgCacheDir := "/tmp/test-xdg-cache" homeDir := "/tmp/test-home" // undo env changes when finished defer func(GOCACHE, XDG_CACHE_HOME, HOME string) { os.Setenv("GOCACHE", GOCACHE) os.Setenv("XDG_CACHE_HOME", XDG_CACHE_HOME) os.Setenv("HOME", HOME) }(os.Getenv("GOCACHE"), os.Getenv("XDG_CACHE_HOME"), os.Getenv("HOME")) os.Setenv("GOCACHE", goCacheDir) os.Setenv("XDG_CACHE_HOME", xdgCacheDir) os.Setenv("HOME", homeDir) dir, showWarnings := defaultDir() if dir != goCacheDir { t.Errorf("Cache DefaultDir %q should be $GOCACHE %q", dir, goCacheDir) } if !showWarnings { t.Error("Warnings should be shown when $GOCACHE is set") } os.Unsetenv("GOCACHE") dir, showWarnings = defaultDir() if !strings.HasPrefix(dir, xdgCacheDir+"/") { t.Errorf("Cache DefaultDir %q should be under $XDG_CACHE_HOME %q when $GOCACHE is unset", dir, xdgCacheDir) } if !showWarnings { t.Error("Warnings should be shown when $XDG_CACHE_HOME is set") } os.Unsetenv("XDG_CACHE_HOME") dir, showWarnings = defaultDir() if !strings.HasPrefix(dir, homeDir+"/.cache/") { t.Errorf("Cache DefaultDir %q should be under $HOME/.cache %q when $GOCACHE and $XDG_CACHE_HOME are unset", dir, homeDir+"/.cache") } if !showWarnings { t.Error("Warnings should be shown when $HOME is not /") } os.Unsetenv("HOME") if dir, _ := defaultDir(); dir != "off" { t.Error("Cache not disabled when $GOCACHE, $XDG_CACHE_HOME, and $HOME are unset") } os.Setenv("HOME", "/") if _, showWarnings := defaultDir(); showWarnings { // https://golang.org/issue/26280 t.Error("Cache initalization warnings should be squelched when $GOCACHE and $XDG_CACHE_HOME are unset and $HOME is /") } }
cache
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/cache/hash.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 cache import ( "bytes" "crypto/sha256" "fmt" "hash" "io" "os" "runtime" "sync" ) var debugHash = false // set when GODEBUG=gocachehash=1 // HashSize is the number of bytes in a hash. const HashSize = 32 // A Hash provides access to the canonical hash function used to index the cache. // The current implementation uses salted SHA256, but clients must not assume this. type Hash struct { h hash.Hash name string // for debugging buf *bytes.Buffer // for verify } // hashSalt is a salt string added to the beginning of every hash // created by NewHash. Using the Go version makes sure that different // versions of the go command (or even different Git commits during // work on the development branch) do not address the same cache // entries, so that a bug in one version does not affect the execution // of other versions. This salt will result in additional ActionID files // in the cache, but not additional copies of the large output files, // which are still addressed by unsalted SHA256. var hashSalt = []byte(runtime.Version()) // Subkey returns an action ID corresponding to mixing a parent // action ID with a string description of the subkey. func Subkey(parent ActionID, desc string) ActionID { h := sha256.New() h.Write([]byte("subkey:")) h.Write(parent[:]) h.Write([]byte(desc)) var out ActionID h.Sum(out[:0]) if debugHash { fmt.Fprintf(os.Stderr, "HASH subkey %x %q = %x\n", parent, desc, out) } if verify { hashDebug.Lock() hashDebug.m[out] = fmt.Sprintf("subkey %x %q", parent, desc) hashDebug.Unlock() } return out } // NewHash returns a new Hash. // The caller is expected to Write data to it and then call Sum. func NewHash(name string) *Hash { h := &Hash{h: sha256.New(), name: name} if debugHash { fmt.Fprintf(os.Stderr, "HASH[%s]\n", h.name) } h.Write(hashSalt) if verify { h.buf = new(bytes.Buffer) } return h } // Write writes data to the running hash. func (h *Hash) Write(b []byte) (int, error) { if debugHash { fmt.Fprintf(os.Stderr, "HASH[%s]: %q\n", h.name, b) } if h.buf != nil { h.buf.Write(b) } return h.h.Write(b) } // Sum returns the hash of the data written previously. func (h *Hash) Sum() [HashSize]byte { var out [HashSize]byte h.h.Sum(out[:0]) if debugHash { fmt.Fprintf(os.Stderr, "HASH[%s]: %x\n", h.name, out) } if h.buf != nil { hashDebug.Lock() if hashDebug.m == nil { hashDebug.m = make(map[[HashSize]byte]string) } hashDebug.m[out] = h.buf.String() hashDebug.Unlock() } return out } // In GODEBUG=gocacheverify=1 mode, // hashDebug holds the input to every computed hash ID, // so that we can work backward from the ID involved in a // cache entry mismatch to a description of what should be there. var hashDebug struct { sync.Mutex m map[[HashSize]byte]string } // reverseHash returns the input used to compute the hash id. func reverseHash(id [HashSize]byte) string { hashDebug.Lock() s := hashDebug.m[id] hashDebug.Unlock() return s } var hashFileCache struct { sync.Mutex m map[string][HashSize]byte } // HashFile returns the hash of the named file. // It caches repeated lookups for a given file, // and the cache entry for a file can be initialized // using SetFileHash. // The hash used by FileHash is not the same as // the hash used by NewHash. func FileHash(file string) ([HashSize]byte, error) { hashFileCache.Lock() out, ok := hashFileCache.m[file] hashFileCache.Unlock() if ok { return out, nil } h := sha256.New() f, err := os.Open(file) if err != nil { if debugHash { fmt.Fprintf(os.Stderr, "HASH %s: %v\n", file, err) } return [HashSize]byte{}, err } _, err = io.Copy(h, f) f.Close() if err != nil { if debugHash { fmt.Fprintf(os.Stderr, "HASH %s: %v\n", file, err) } return [HashSize]byte{}, err } h.Sum(out[:0]) if debugHash { fmt.Fprintf(os.Stderr, "HASH %s: %x\n", file, out) } SetFileHash(file, out) return out, nil } // SetFileHash sets the hash returned by FileHash for file. func SetFileHash(file string, sum [HashSize]byte) { hashFileCache.Lock() if hashFileCache.m == nil { hashFileCache.m = make(map[string][HashSize]byte) } hashFileCache.m[file] = sum hashFileCache.Unlock() }
cache
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/cache/hash_test.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 cache import ( "fmt" "io/ioutil" "os" "testing" ) func TestHash(t *testing.T) { oldSalt := hashSalt hashSalt = nil defer func() { hashSalt = oldSalt }() h := NewHash("alice") h.Write([]byte("hello world")) sum := fmt.Sprintf("%x", h.Sum()) want := "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9" if sum != want { t.Errorf("hash(hello world) = %v, want %v", sum, want) } } func TestHashFile(t *testing.T) { f, err := ioutil.TempFile("", "cmd-go-test-") if err != nil { t.Fatal(err) } name := f.Name() fmt.Fprintf(f, "hello world") defer os.Remove(name) if err := f.Close(); err != nil { t.Fatal(err) } var h ActionID // make sure hash result is assignable to ActionID h, err = FileHash(name) if err != nil { t.Fatal(err) } sum := fmt.Sprintf("%x", h) want := "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9" if sum != want { t.Errorf("hash(hello world) = %v, want %v", sum, want) } }
cache
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/cache/default.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 cache import ( "fmt" "io/ioutil" "os" "path/filepath" "runtime" "sync" ) // Default returns the default cache to use, or nil if no cache should be used. func Default() *Cache { defaultOnce.Do(initDefaultCache) return defaultCache } var ( defaultOnce sync.Once defaultCache *Cache ) // cacheREADME is a message stored in a README in the cache directory. // Because the cache lives outside the normal Go trees, we leave the // README as a courtesy to explain where it came from. const cacheREADME = `This directory holds cached build artifacts from the Go build system. Run "go clean -cache" if the directory is getting too large. See golang.org to learn more about Go. ` // initDefaultCache does the work of finding the default cache // the first time Default is called. func initDefaultCache() { dir, showWarnings := defaultDir() if dir == "off" { return } if err := os.MkdirAll(dir, 0777); err != nil { if showWarnings { fmt.Fprintf(os.Stderr, "go: disabling cache (%s) due to initialization failure: %s\n", dir, err) } return } if _, err := os.Stat(filepath.Join(dir, "README")); err != nil { // Best effort. ioutil.WriteFile(filepath.Join(dir, "README"), []byte(cacheREADME), 0666) } c, err := Open(dir) if err != nil { if showWarnings { fmt.Fprintf(os.Stderr, "go: disabling cache (%s) due to initialization failure: %s\n", dir, err) } return } defaultCache = c } // DefaultDir returns the effective GOCACHE setting. // It returns "off" if the cache is disabled. func DefaultDir() string { dir, _ := defaultDir() return dir } // defaultDir returns the effective GOCACHE setting. // It returns "off" if the cache is disabled. // The second return value reports whether warnings should // be shown if the cache fails to initialize. func defaultDir() (string, bool) { dir := os.Getenv("GOCACHE") if dir != "" { return dir, true } // Compute default location. // TODO(rsc): This code belongs somewhere else, // like maybe ioutil.CacheDir or os.CacheDir. showWarnings := true switch runtime.GOOS { case "windows": dir = os.Getenv("LocalAppData") if dir == "" { // Fall back to %AppData%, the old name of // %LocalAppData% on Windows XP. dir = os.Getenv("AppData") } if dir == "" { return "off", true } case "darwin": dir = os.Getenv("HOME") if dir == "" { return "off", true } dir += "/Library/Caches" case "plan9": dir = os.Getenv("home") if dir == "" { return "off", true } // Plan 9 has no established per-user cache directory, // but $home/lib/xyz is the usual equivalent of $HOME/.xyz on Unix. dir += "/lib/cache" default: // Unix // https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html dir = os.Getenv("XDG_CACHE_HOME") if dir == "" { dir = os.Getenv("HOME") if dir == "" { return "off", true } if dir == "/" { // probably docker run with -u flag // https://golang.org/issue/26280 showWarnings = false } dir += "/.cache" } } return filepath.Join(dir, "go-build"), showWarnings }
cache
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/cache/cache.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 cache implements a build artifact cache. package cache import ( "bytes" "crypto/sha256" "encoding/hex" "errors" "fmt" "io" "io/ioutil" "os" "path/filepath" "strconv" "strings" "time" ) // An ActionID is a cache action key, the hash of a complete description of a // repeatable computation (command line, environment variables, // input file contents, executable contents). type ActionID [HashSize]byte // An OutputID is a cache output key, the hash of an output of a computation. type OutputID [HashSize]byte // A Cache is a package cache, backed by a file system directory tree. type Cache struct { dir string log *os.File now func() time.Time } // Open opens and returns the cache in the given directory. // // It is safe for multiple processes on a single machine to use the // same cache directory in a local file system simultaneously. // They will coordinate using operating system file locks and may // duplicate effort but will not corrupt the cache. // // However, it is NOT safe for multiple processes on different machines // to share a cache directory (for example, if the directory were stored // in a network file system). File locking is notoriously unreliable in // network file systems and may not suffice to protect the cache. // func Open(dir string) (*Cache, error) { info, err := os.Stat(dir) if err != nil { return nil, err } if !info.IsDir() { return nil, &os.PathError{Op: "open", Path: dir, Err: fmt.Errorf("not a directory")} } for i := 0; i < 256; i++ { name := filepath.Join(dir, fmt.Sprintf("%02x", i)) if err := os.MkdirAll(name, 0777); err != nil { return nil, err } } f, err := os.OpenFile(filepath.Join(dir, "log.txt"), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) if err != nil { return nil, err } c := &Cache{ dir: dir, log: f, now: time.Now, } return c, nil } // fileName returns the name of the file corresponding to the given id. func (c *Cache) fileName(id [HashSize]byte, key string) string { return filepath.Join(c.dir, fmt.Sprintf("%02x", id[0]), fmt.Sprintf("%x", id)+"-"+key) } var errMissing = errors.New("cache entry not found") const ( // action entry file is "v1 <hex id> <hex out> <decimal size space-padded to 20 bytes> <unixnano space-padded to 20 bytes>\n" hexSize = HashSize * 2 entrySize = 2 + 1 + hexSize + 1 + hexSize + 1 + 20 + 1 + 20 + 1 ) // verify controls whether to run the cache in verify mode. // In verify mode, the cache always returns errMissing from Get // but then double-checks in Put that the data being written // exactly matches any existing entry. This provides an easy // way to detect program behavior that would have been different // had the cache entry been returned from Get. // // verify is enabled by setting the environment variable // GODEBUG=gocacheverify=1. var verify = false // DebugTest is set when GODEBUG=gocachetest=1 is in the environment. var DebugTest = false func init() { initEnv() } func initEnv() { verify = false debugHash = false debug := strings.Split(os.Getenv("GODEBUG"), ",") for _, f := range debug { if f == "gocacheverify=1" { verify = true } if f == "gocachehash=1" { debugHash = true } if f == "gocachetest=1" { DebugTest = true } } } // Get looks up the action ID in the cache, // returning the corresponding output ID and file size, if any. // Note that finding an output ID does not guarantee that the // saved file for that output ID is still available. func (c *Cache) Get(id ActionID) (Entry, error) { if verify { return Entry{}, errMissing } return c.get(id) } type Entry struct { OutputID OutputID Size int64 Time time.Time } // get is Get but does not respect verify mode, so that Put can use it. func (c *Cache) get(id ActionID) (Entry, error) { missing := func() (Entry, error) { fmt.Fprintf(c.log, "%d miss %x\n", c.now().Unix(), id) return Entry{}, errMissing } f, err := os.Open(c.fileName(id, "a")) if err != nil { return missing() } defer f.Close() entry := make([]byte, entrySize+1) // +1 to detect whether f is too long if n, err := io.ReadFull(f, entry); n != entrySize || err != io.ErrUnexpectedEOF { return missing() } if entry[0] != 'v' || entry[1] != '1' || entry[2] != ' ' || entry[3+hexSize] != ' ' || entry[3+hexSize+1+hexSize] != ' ' || entry[3+hexSize+1+hexSize+1+20] != ' ' || entry[entrySize-1] != '\n' { return missing() } eid, entry := entry[3:3+hexSize], entry[3+hexSize:] eout, entry := entry[1:1+hexSize], entry[1+hexSize:] esize, entry := entry[1:1+20], entry[1+20:] etime, entry := entry[1:1+20], entry[1+20:] var buf [HashSize]byte if _, err := hex.Decode(buf[:], eid); err != nil || buf != id { return missing() } if _, err := hex.Decode(buf[:], eout); err != nil { return missing() } i := 0 for i < len(esize) && esize[i] == ' ' { i++ } size, err := strconv.ParseInt(string(esize[i:]), 10, 64) if err != nil || size < 0 { return missing() } i = 0 for i < len(etime) && etime[i] == ' ' { i++ } tm, err := strconv.ParseInt(string(etime[i:]), 10, 64) if err != nil || size < 0 { return missing() } fmt.Fprintf(c.log, "%d get %x\n", c.now().Unix(), id) c.used(c.fileName(id, "a")) return Entry{buf, size, time.Unix(0, tm)}, nil } // GetFile looks up the action ID in the cache and returns // the name of the corresponding data file. func (c *Cache) GetFile(id ActionID) (file string, entry Entry, err error) { entry, err = c.Get(id) if err != nil { return "", Entry{}, err } file = c.OutputFile(entry.OutputID) info, err := os.Stat(file) if err != nil || info.Size() != entry.Size { return "", Entry{}, errMissing } return file, entry, nil } // GetBytes looks up the action ID in the cache and returns // the corresponding output bytes. // GetBytes should only be used for data that can be expected to fit in memory. func (c *Cache) GetBytes(id ActionID) ([]byte, Entry, error) { entry, err := c.Get(id) if err != nil { return nil, entry, err } data, _ := ioutil.ReadFile(c.OutputFile(entry.OutputID)) if sha256.Sum256(data) != entry.OutputID { return nil, entry, errMissing } return data, entry, nil } // OutputFile returns the name of the cache file storing output with the given OutputID. func (c *Cache) OutputFile(out OutputID) string { file := c.fileName(out, "d") c.used(file) return file } // Time constants for cache expiration. // // We set the mtime on a cache file on each use, but at most one per mtimeInterval (1 hour), // to avoid causing many unnecessary inode updates. The mtimes therefore // roughly reflect "time of last use" but may in fact be older by at most an hour. // // We scan the cache for entries to delete at most once per trimInterval (1 day). // // When we do scan the cache, we delete entries that have not been used for // at least trimLimit (5 days). Statistics gathered from a month of usage by // Go developers found that essentially all reuse of cached entries happened // within 5 days of the previous reuse. See golang.org/issue/22990. const ( mtimeInterval = 1 * time.Hour trimInterval = 24 * time.Hour trimLimit = 5 * 24 * time.Hour ) // used makes a best-effort attempt to update mtime on file, // so that mtime reflects cache access time. // // Because the reflection only needs to be approximate, // and to reduce the amount of disk activity caused by using // cache entries, used only updates the mtime if the current // mtime is more than an hour old. This heuristic eliminates // nearly all of the mtime updates that would otherwise happen, // while still keeping the mtimes useful for cache trimming. func (c *Cache) used(file string) { info, err := os.Stat(file) if err == nil && c.now().Sub(info.ModTime()) < mtimeInterval { return } os.Chtimes(file, c.now(), c.now()) } // Trim removes old cache entries that are likely not to be reused. func (c *Cache) Trim() { now := c.now() // We maintain in dir/trim.txt the time of the last completed cache trim. // If the cache has been trimmed recently enough, do nothing. // This is the common case. data, _ := ioutil.ReadFile(filepath.Join(c.dir, "trim.txt")) t, err := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64) if err == nil && now.Sub(time.Unix(t, 0)) < trimInterval { return } // Trim each of the 256 subdirectories. // We subtract an additional mtimeInterval // to account for the imprecision of our "last used" mtimes. cutoff := now.Add(-trimLimit - mtimeInterval) for i := 0; i < 256; i++ { subdir := filepath.Join(c.dir, fmt.Sprintf("%02x", i)) c.trimSubdir(subdir, cutoff) } ioutil.WriteFile(filepath.Join(c.dir, "trim.txt"), []byte(fmt.Sprintf("%d", now.Unix())), 0666) } // trimSubdir trims a single cache subdirectory. func (c *Cache) trimSubdir(subdir string, cutoff time.Time) { // Read all directory entries from subdir before removing // any files, in case removing files invalidates the file offset // in the directory scan. Also, ignore error from f.Readdirnames, // because we don't care about reporting the error and we still // want to process any entries found before the error. f, err := os.Open(subdir) if err != nil { return } names, _ := f.Readdirnames(-1) f.Close() for _, name := range names { // Remove only cache entries (xxxx-a and xxxx-d). if !strings.HasSuffix(name, "-a") && !strings.HasSuffix(name, "-d") { continue } entry := filepath.Join(subdir, name) info, err := os.Stat(entry) if err == nil && info.ModTime().Before(cutoff) { os.Remove(entry) } } } // putIndexEntry adds an entry to the cache recording that executing the action // with the given id produces an output with the given output id (hash) and size. func (c *Cache) putIndexEntry(id ActionID, out OutputID, size int64, allowVerify bool) error { // Note: We expect that for one reason or another it may happen // that repeating an action produces a different output hash // (for example, if the output contains a time stamp or temp dir name). // While not ideal, this is also not a correctness problem, so we // don't make a big deal about it. In particular, we leave the action // cache entries writable specifically so that they can be overwritten. // // Setting GODEBUG=gocacheverify=1 does make a big deal: // in verify mode we are double-checking that the cache entries // are entirely reproducible. As just noted, this may be unrealistic // in some cases but the check is also useful for shaking out real bugs. entry := []byte(fmt.Sprintf("v1 %x %x %20d %20d\n", id, out, size, time.Now().UnixNano())) if verify && allowVerify { old, err := c.get(id) if err == nil && (old.OutputID != out || old.Size != size) { // panic to show stack trace, so we can see what code is generating this cache entry. msg := fmt.Sprintf("go: internal cache error: cache verify failed: id=%x changed:<<<\n%s\n>>>\nold: %x %d\nnew: %x %d", id, reverseHash(id), out, size, old.OutputID, old.Size) panic(msg) } } file := c.fileName(id, "a") if err := ioutil.WriteFile(file, entry, 0666); err != nil { os.Remove(file) return err } os.Chtimes(file, c.now(), c.now()) // mainly for tests fmt.Fprintf(c.log, "%d put %x %x %d\n", c.now().Unix(), id, out, size) return nil } // Put stores the given output in the cache as the output for the action ID. // It may read file twice. The content of file must not change between the two passes. func (c *Cache) Put(id ActionID, file io.ReadSeeker) (OutputID, int64, error) { return c.put(id, file, true) } // PutNoVerify is like Put but disables the verify check // when GODEBUG=goverifycache=1 is set. // It is meant for data that is OK to cache but that we expect to vary slightly from run to run, // like test output containing times and the like. func (c *Cache) PutNoVerify(id ActionID, file io.ReadSeeker) (OutputID, int64, error) { return c.put(id, file, false) } func (c *Cache) put(id ActionID, file io.ReadSeeker, allowVerify bool) (OutputID, int64, error) { // Compute output ID. h := sha256.New() if _, err := file.Seek(0, 0); err != nil { return OutputID{}, 0, err } size, err := io.Copy(h, file) if err != nil { return OutputID{}, 0, err } var out OutputID h.Sum(out[:0]) // Copy to cached output file (if not already present). if err := c.copyFile(file, out, size); err != nil { return out, size, err } // Add to cache index. return out, size, c.putIndexEntry(id, out, size, allowVerify) } // PutBytes stores the given bytes in the cache as the output for the action ID. func (c *Cache) PutBytes(id ActionID, data []byte) error { _, _, err := c.Put(id, bytes.NewReader(data)) return err } // copyFile copies file into the cache, expecting it to have the given // output ID and size, if that file is not present already. func (c *Cache) copyFile(file io.ReadSeeker, out OutputID, size int64) error { name := c.fileName(out, "d") info, err := os.Stat(name) if err == nil && info.Size() == size { // Check hash. if f, err := os.Open(name); err == nil { h := sha256.New() io.Copy(h, f) f.Close() var out2 OutputID h.Sum(out2[:0]) if out == out2 { return nil } } // Hash did not match. Fall through and rewrite file. } // Copy file to cache directory. mode := os.O_RDWR | os.O_CREATE if err == nil && info.Size() > size { // shouldn't happen but fix in case mode |= os.O_TRUNC } f, err := os.OpenFile(name, mode, 0666) if err != nil { return err } defer f.Close() if size == 0 { // File now exists with correct size. // Only one possible zero-length file, so contents are OK too. // Early return here makes sure there's a "last byte" for code below. return nil } // From here on, if any of the I/O writing the file fails, // we make a best-effort attempt to truncate the file f // before returning, to avoid leaving bad bytes in the file. // Copy file to f, but also into h to double-check hash. if _, err := file.Seek(0, 0); err != nil { f.Truncate(0) return err } h := sha256.New() w := io.MultiWriter(f, h) if _, err := io.CopyN(w, file, size-1); err != nil { f.Truncate(0) return err } // Check last byte before writing it; writing it will make the size match // what other processes expect to find and might cause them to start // using the file. buf := make([]byte, 1) if _, err := file.Read(buf); err != nil { f.Truncate(0) return err } h.Write(buf) sum := h.Sum(nil) if !bytes.Equal(sum, out[:]) { f.Truncate(0) return fmt.Errorf("file content changed underfoot") } // Commit cache file entry. if _, err := f.Write(buf); err != nil { f.Truncate(0) return err } if err := f.Close(); err != nil { // Data might not have been written, // but file may look like it is the right size. // To be extra careful, remove cached file. os.Remove(name) return err } os.Chtimes(name, c.now(), c.now()) // mainly for tests return nil }
cache
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/cache/cache_test.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 cache import ( "bytes" "encoding/binary" "fmt" "io/ioutil" "os" "path/filepath" "testing" "time" ) func init() { verify = false // even if GODEBUG is set } func TestBasic(t *testing.T) { dir, err := ioutil.TempDir("", "cachetest-") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) _, err = Open(filepath.Join(dir, "notexist")) if err == nil { t.Fatal(`Open("tmp/notexist") succeeded, want failure`) } cdir := filepath.Join(dir, "c1") if err := os.Mkdir(cdir, 0777); err != nil { t.Fatal(err) } c1, err := Open(cdir) if err != nil { t.Fatalf("Open(c1) (create): %v", err) } if err := c1.putIndexEntry(dummyID(1), dummyID(12), 13, true); err != nil { t.Fatalf("addIndexEntry: %v", err) } if err := c1.putIndexEntry(dummyID(1), dummyID(2), 3, true); err != nil { // overwrite entry t.Fatalf("addIndexEntry: %v", err) } if entry, err := c1.Get(dummyID(1)); err != nil || entry.OutputID != dummyID(2) || entry.Size != 3 { t.Fatalf("c1.Get(1) = %x, %v, %v, want %x, %v, nil", entry.OutputID, entry.Size, err, dummyID(2), 3) } c2, err := Open(cdir) if err != nil { t.Fatalf("Open(c2) (reuse): %v", err) } if entry, err := c2.Get(dummyID(1)); err != nil || entry.OutputID != dummyID(2) || entry.Size != 3 { t.Fatalf("c2.Get(1) = %x, %v, %v, want %x, %v, nil", entry.OutputID, entry.Size, err, dummyID(2), 3) } if err := c2.putIndexEntry(dummyID(2), dummyID(3), 4, true); err != nil { t.Fatalf("addIndexEntry: %v", err) } if entry, err := c1.Get(dummyID(2)); err != nil || entry.OutputID != dummyID(3) || entry.Size != 4 { t.Fatalf("c1.Get(2) = %x, %v, %v, want %x, %v, nil", entry.OutputID, entry.Size, err, dummyID(3), 4) } } func TestGrowth(t *testing.T) { dir, err := ioutil.TempDir("", "cachetest-") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) c, err := Open(dir) if err != nil { t.Fatalf("Open: %v", err) } n := 10000 if testing.Short() { n = 1000 } for i := 0; i < n; i++ { if err := c.putIndexEntry(dummyID(i), dummyID(i*99), int64(i)*101, true); err != nil { t.Fatalf("addIndexEntry: %v", err) } id := ActionID(dummyID(i)) entry, err := c.Get(id) if err != nil { t.Fatalf("Get(%x): %v", id, err) } if entry.OutputID != dummyID(i*99) || entry.Size != int64(i)*101 { t.Errorf("Get(%x) = %x, %d, want %x, %d", id, entry.OutputID, entry.Size, dummyID(i*99), int64(i)*101) } } for i := 0; i < n; i++ { id := ActionID(dummyID(i)) entry, err := c.Get(id) if err != nil { t.Fatalf("Get2(%x): %v", id, err) } if entry.OutputID != dummyID(i*99) || entry.Size != int64(i)*101 { t.Errorf("Get2(%x) = %x, %d, want %x, %d", id, entry.OutputID, entry.Size, dummyID(i*99), int64(i)*101) } } } func TestVerifyPanic(t *testing.T) { os.Setenv("GODEBUG", "gocacheverify=1") initEnv() defer func() { os.Unsetenv("GODEBUG") verify = false }() if !verify { t.Fatal("initEnv did not set verify") } dir, err := ioutil.TempDir("", "cachetest-") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) c, err := Open(dir) if err != nil { t.Fatalf("Open: %v", err) } id := ActionID(dummyID(1)) if err := c.PutBytes(id, []byte("abc")); err != nil { t.Fatal(err) } defer func() { if err := recover(); err != nil { t.Log(err) return } }() c.PutBytes(id, []byte("def")) t.Fatal("mismatched Put did not panic in verify mode") } func TestCacheLog(t *testing.T) { dir, err := ioutil.TempDir("", "cachetest-") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) c, err := Open(dir) if err != nil { t.Fatalf("Open: %v", err) } c.now = func() time.Time { return time.Unix(1e9, 0) } id := ActionID(dummyID(1)) c.Get(id) c.PutBytes(id, []byte("abc")) c.Get(id) c, err = Open(dir) if err != nil { t.Fatalf("Open #2: %v", err) } c.now = func() time.Time { return time.Unix(1e9+1, 0) } c.Get(id) id2 := ActionID(dummyID(2)) c.Get(id2) c.PutBytes(id2, []byte("abc")) c.Get(id2) c.Get(id) data, err := ioutil.ReadFile(filepath.Join(dir, "log.txt")) if err != nil { t.Fatal(err) } want := `1000000000 miss 0100000000000000000000000000000000000000000000000000000000000000 1000000000 put 0100000000000000000000000000000000000000000000000000000000000000 ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad 3 1000000000 get 0100000000000000000000000000000000000000000000000000000000000000 1000000001 get 0100000000000000000000000000000000000000000000000000000000000000 1000000001 miss 0200000000000000000000000000000000000000000000000000000000000000 1000000001 put 0200000000000000000000000000000000000000000000000000000000000000 ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad 3 1000000001 get 0200000000000000000000000000000000000000000000000000000000000000 1000000001 get 0100000000000000000000000000000000000000000000000000000000000000 ` if string(data) != want { t.Fatalf("log:\n%s\nwant:\n%s", string(data), want) } } func dummyID(x int) [HashSize]byte { var out [HashSize]byte binary.LittleEndian.PutUint64(out[:], uint64(x)) return out } func TestCacheTrim(t *testing.T) { dir, err := ioutil.TempDir("", "cachetest-") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) c, err := Open(dir) if err != nil { t.Fatalf("Open: %v", err) } const start = 1000000000 now := int64(start) c.now = func() time.Time { return time.Unix(now, 0) } checkTime := func(name string, mtime int64) { t.Helper() file := filepath.Join(c.dir, name[:2], name) info, err := os.Stat(file) if err != nil { t.Fatal(err) } if info.ModTime().Unix() != mtime { t.Fatalf("%s mtime = %d, want %d", name, info.ModTime().Unix(), mtime) } } id := ActionID(dummyID(1)) c.PutBytes(id, []byte("abc")) entry, _ := c.Get(id) c.PutBytes(ActionID(dummyID(2)), []byte("def")) mtime := now checkTime(fmt.Sprintf("%x-a", id), mtime) checkTime(fmt.Sprintf("%x-d", entry.OutputID), mtime) // Get should not change recent mtimes. now = start + 10 c.Get(id) checkTime(fmt.Sprintf("%x-a", id), mtime) checkTime(fmt.Sprintf("%x-d", entry.OutputID), mtime) // Get should change distant mtimes. now = start + 5000 mtime2 := now if _, err := c.Get(id); err != nil { t.Fatal(err) } c.OutputFile(entry.OutputID) checkTime(fmt.Sprintf("%x-a", id), mtime2) checkTime(fmt.Sprintf("%x-d", entry.OutputID), mtime2) // Trim should leave everything alone: it's all too new. c.Trim() if _, err := c.Get(id); err != nil { t.Fatal(err) } c.OutputFile(entry.OutputID) data, err := ioutil.ReadFile(filepath.Join(dir, "trim.txt")) if err != nil { t.Fatal(err) } checkTime(fmt.Sprintf("%x-a", dummyID(2)), start) // Trim less than a day later should not do any work at all. now = start + 80000 c.Trim() if _, err := c.Get(id); err != nil { t.Fatal(err) } c.OutputFile(entry.OutputID) data2, err := ioutil.ReadFile(filepath.Join(dir, "trim.txt")) if err != nil { t.Fatal(err) } if !bytes.Equal(data, data2) { t.Fatalf("second trim did work: %q -> %q", data, data2) } // Fast forward and do another trim just before the 5 day cutoff. // Note that because of usedQuantum the cutoff is actually 5 days + 1 hour. // We used c.Get(id) just now, so 5 days later it should still be kept. // On the other hand almost a full day has gone by since we wrote dummyID(2) // and we haven't looked at it since, so 5 days later it should be gone. now += 5 * 86400 checkTime(fmt.Sprintf("%x-a", dummyID(2)), start) c.Trim() if _, err := c.Get(id); err != nil { t.Fatal(err) } c.OutputFile(entry.OutputID) mtime3 := now if _, err := c.Get(dummyID(2)); err == nil { // haven't done a Get for this since original write above t.Fatalf("Trim did not remove dummyID(2)") } // The c.Get(id) refreshed id's mtime again. // Check that another 5 days later it is still not gone, // but check by using checkTime, which doesn't bring mtime forward. now += 5 * 86400 c.Trim() checkTime(fmt.Sprintf("%x-a", id), mtime3) checkTime(fmt.Sprintf("%x-d", entry.OutputID), mtime3) // Half a day later Trim should still be a no-op, because there was a Trim recently. // Even though the entry for id is now old enough to be trimmed, // it gets a reprieve until the time comes for a new Trim scan. now += 86400 / 2 c.Trim() checkTime(fmt.Sprintf("%x-a", id), mtime3) checkTime(fmt.Sprintf("%x-d", entry.OutputID), mtime3) // Another half a day later, Trim should actually run, and it should remove id. now += 86400/2 + 1 c.Trim() if _, err := c.Get(dummyID(1)); err == nil { t.Fatal("Trim did not remove dummyID(1)") } }
modget
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/modget/get.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 modget implements the module-aware ``go get'' command. package modget import ( "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/get" "cmd/go/internal/load" "cmd/go/internal/modfetch" "cmd/go/internal/modload" "cmd/go/internal/module" "cmd/go/internal/mvs" "cmd/go/internal/par" "cmd/go/internal/search" "cmd/go/internal/semver" "cmd/go/internal/str" "cmd/go/internal/work" "fmt" "os" pathpkg "path" "path/filepath" "strings" ) var CmdGet = &base.Command{ // Note: -d -m -u are listed explicitly because they are the most common get flags. // Do not send CLs removing them because they're covered by [get flags]. UsageLine: "go get [-d] [-m] [-u] [-v] [-insecure] [build flags] [packages]", Short: "add dependencies to current module and install them", Long: ` Get resolves and adds dependencies to the current development module and then builds and installs them. The first step is to resolve which dependencies to add. For each named package or package pattern, get must decide which version of the corresponding module to use. By default, get chooses the latest tagged release version, such as v0.4.5 or v1.2.3. If there are no tagged release versions, get chooses the latest tagged prerelease version, such as v0.0.1-pre1. If there are no tagged versions at all, get chooses the latest known commit. This default version selection can be overridden by adding an @version suffix to the package argument, as in 'go get golang.org/x/text@v0.3.0'. For modules stored in source control repositories, the version suffix can also be a commit hash, branch identifier, or other syntax known to the source control system, as in 'go get golang.org/x/text@master'. The version suffix @latest explicitly requests the default behavior described above. If a module under consideration is already a dependency of the current development module, then get will update the required version. Specifying a version earlier than the current required version is valid and downgrades the dependency. The version suffix @none indicates that the dependency should be removed entirely. Although get defaults to using the latest version of the module containing a named package, it does not use the latest version of that module's dependencies. Instead it prefers to use the specific dependency versions requested by that module. For example, if the latest A requires module B v1.2.3, while B v1.2.4 and v1.3.1 are also available, then 'go get A' will use the latest A but then use B v1.2.3, as requested by A. (If there are competing requirements for a particular module, then 'go get' resolves those requirements by taking the maximum requested version.) The -u flag instructs get to update dependencies to use newer minor or patch releases when available. Continuing the previous example, 'go get -u A' will use the latest A with B v1.3.1 (not B v1.2.3). The -u=patch flag (not -u patch) instructs get to update dependencies to use newer patch releases when available. Continuing the previous example, 'go get -u=patch A' will use the latest A with B v1.2.4 (not B v1.2.3). In general, adding a new dependency may require upgrading existing dependencies to keep a working build, and 'go get' does this automatically. Similarly, downgrading one dependency may require downgrading other dependenceis, and 'go get' does this automatically as well. The -m flag instructs get to stop here, after resolving, upgrading, and downgrading modules and updating go.mod. When using -m, each specified package path must be a module path as well, not the import path of a package below the module root. The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution. The second step is to download (if needed), build, and install the named packages. If an argument names a module but not a package (because there is no Go source code in the module's root directory), then the install step is skipped for that argument, instead of causing a build failure. For example 'go get golang.org/x/perf' succeeds even though there is no code corresponding to that import path. Note that package patterns are allowed and are expanded after resolving the module versions. For example, 'go get golang.org/x/perf/cmd/...' adds the latest golang.org/x/perf and then installs the commands in that latest version. The -d flag instructs get to download the source code needed to build the named packages, including downloading necessary dependencies, but not to build and install them. With no package arguments, 'go get' applies to the main module, and to the Go package in the current directory, if any. In particular, 'go get -u' and 'go get -u=patch' update all the dependencies of the main module. With no package arguments and also without -u, 'go get' is not much more than 'go install', and 'go get -d' not much more than 'go list'. For more about modules, see 'go help modules'. For more about specifying packages, see 'go help packages'. This text describes the behavior of get using modules to manage source code and dependencies. If instead the go command is running in GOPATH mode, the details of get's flags and effects change, as does 'go help get'. See 'go help modules' and 'go help gopath-get'. See also: go build, go install, go clean, go mod. `, } // Note that this help text is a stopgap to make the module-aware get help text // available even in non-module settings. It should be deleted when the old get // is deleted. It should NOT be considered to set a precedent of having hierarchical // help names with dashes. var HelpModuleGet = &base.Command{ UsageLine: "module-get", Short: "module-aware go get", Long: ` The 'go get' command changes behavior depending on whether the go command is running in module-aware mode or legacy GOPATH mode. This help text, accessible as 'go help module-get' even in legacy GOPATH mode, describes 'go get' as it operates in module-aware mode. Usage: ` + CmdGet.UsageLine + ` ` + CmdGet.Long, } var ( getD = CmdGet.Flag.Bool("d", false, "") getF = CmdGet.Flag.Bool("f", false, "") getFix = CmdGet.Flag.Bool("fix", false, "") getM = CmdGet.Flag.Bool("m", false, "") getT = CmdGet.Flag.Bool("t", false, "") getU upgradeFlag // -insecure is get.Insecure // -v is cfg.BuildV ) // upgradeFlag is a custom flag.Value for -u. type upgradeFlag string func (*upgradeFlag) IsBoolFlag() bool { return true } // allow -u func (v *upgradeFlag) Set(s string) error { if s == "false" { s = "" } *v = upgradeFlag(s) return nil } func (v *upgradeFlag) String() string { return "" } func init() { work.AddBuildFlags(CmdGet) CmdGet.Run = runGet // break init loop CmdGet.Flag.BoolVar(&get.Insecure, "insecure", get.Insecure, "") CmdGet.Flag.Var(&getU, "u", "") } // A task holds the state for processing a single get argument (path@vers). type task struct { arg string // original argument index int path string // package path part of arg forceModulePath bool // path must be interpreted as a module path vers string // version part of arg m module.Version // module version indicated by argument req []module.Version // m's requirement list (not upgraded) } func runGet(cmd *base.Command, args []string) { // -mod=readonly has no effect on "go get". if cfg.BuildMod == "readonly" { cfg.BuildMod = "" } switch getU { case "", "patch", "true": // ok default: base.Fatalf("go get: unknown upgrade flag -u=%s", getU) } if *getF { fmt.Fprintf(os.Stderr, "go get: -f flag is a no-op when using modules\n") } if *getFix { fmt.Fprintf(os.Stderr, "go get: -fix flag is a no-op when using modules\n") } if *getT { fmt.Fprintf(os.Stderr, "go get: -t flag is a no-op when using modules\n") } if cfg.BuildMod == "vendor" { base.Fatalf("go get: disabled by -mod=%s", cfg.BuildMod) } modload.LoadBuildList() // Do not allow any updating of go.mod until we've applied // all the requested changes and checked that the result matches // what was requested. modload.DisallowWriteGoMod() // Build task and install lists. // The command-line arguments are of the form path@version // or simply path, with implicit @latest. path@none is "downgrade away". // At the end of the loop, we've resolved the list of arguments into // a list of tasks (a path@vers that needs further processing) // and a list of install targets (for the "go install" at the end). var tasks []*task var install []string for _, arg := range search.CleanPatterns(args) { // Argument is module query path@vers, or else path with implicit @latest. path := arg vers := "" if i := strings.Index(arg, "@"); i >= 0 { path, vers = arg[:i], arg[i+1:] } if strings.Contains(vers, "@") || arg != path && vers == "" { base.Errorf("go get %s: invalid module version syntax", arg) continue } if vers != "none" { install = append(install, path) } // Deciding which module to upgrade/downgrade for a particular argument is difficult. // Patterns only make it more difficult. // We impose restrictions to avoid needing to interlace pattern expansion, // like in in modload.ImportPaths. // Specifically, these patterns are supported: // // - Relative paths like ../../foo or ../../foo... are restricted to matching directories // in the current module and therefore map to the current module. // It's possible that the pattern matches no packages, but we will still treat it // as mapping to the current module. // TODO: In followup, could just expand the full list and remove the discrepancy. // - The pattern "all" has its usual package meaning and maps to the list of modules // from which the matched packages are drawn. This is potentially a subset of the // module pattern "all". If module A requires B requires C but A does not import // the parts of B that import C, the packages matched by "all" are only from A and B, // so only A and B end up on the tasks list. // TODO: Even in -m mode? // - The patterns "std" and "cmd" expand to packages in the standard library, // which aren't upgradable, so we skip over those. // In -m mode they expand to non-module-paths, so they are disallowed. // - Import path patterns like foo/bar... are matched against the module list, // assuming any package match would imply a module pattern match. // TODO: What about -m mode? // - Import paths without patterns are left as is, for resolution by getQuery (eventually modload.Import). // if search.IsRelativePath(path) { // Check that this relative pattern only matches directories in the current module, // and then record the current module as the target. dir := path if i := strings.Index(path, "..."); i >= 0 { dir, _ = pathpkg.Split(path[:i]) } abs, err := filepath.Abs(dir) if err != nil { base.Errorf("go get %s: %v", arg, err) continue } if !str.HasFilePathPrefix(abs, modload.ModRoot) { base.Errorf("go get %s: directory %s is outside module root %s", arg, abs, modload.ModRoot) continue } // TODO: Check if abs is inside a nested module. tasks = append(tasks, &task{arg: arg, path: modload.Target.Path, vers: ""}) continue } if path == "all" { // TODO: If *getM, should this be the module pattern "all"? // This is the package pattern "all" not the module pattern "all": // enumerate all the modules actually needed by builds of the packages // in the main module, not incidental modules that happen to be // in the package graph (and therefore build list). // Note that LoadALL may add new modules to the build list to // satisfy new imports, but vers == "latest" implicitly anyway, // so we'll assume that's OK. seen := make(map[module.Version]bool) pkgs := modload.LoadALL() for _, pkg := range pkgs { m := modload.PackageModule(pkg) if m.Path != "" && !seen[m] { seen[m] = true tasks = append(tasks, &task{arg: arg, path: m.Path, vers: "latest", forceModulePath: true}) } } continue } if search.IsMetaPackage(path) { // Already handled "all", so this must be "std" or "cmd", // which are entirely in the standard library. if path != arg { base.Errorf("go get %s: cannot use pattern %q with explicit version", arg, arg) } if *getM { base.Errorf("go get %s: cannot use pattern %q with -m", arg, arg) continue } continue } if strings.Contains(path, "...") { // Apply to modules in build list matched by pattern (golang.org/x/...), if any. match := search.MatchPattern(path) matched := false for _, m := range modload.BuildList() { if match(m.Path) || str.HasPathPrefix(path, m.Path) { tasks = append(tasks, &task{arg: arg, path: m.Path, vers: vers, forceModulePath: true}) matched = true } } // If matched, we're done. // Otherwise assume pattern is inside a single module // (golang.org/x/text/unicode/...) and leave for usual lookup. // Unless we're using -m. if matched { continue } if *getM { base.Errorf("go get %s: pattern matches no modules in build list", arg) continue } } tasks = append(tasks, &task{arg: arg, path: path, vers: vers}) } base.ExitIfErrors() // Now we've reduced the upgrade/downgrade work to a list of path@vers pairs (tasks). // Resolve each one in parallel. reqs := modload.Reqs() var lookup par.Work for _, t := range tasks { lookup.Add(t) } lookup.Do(10, func(item interface{}) { t := item.(*task) if t.vers == "none" { // Wait for downgrade step. t.m = module.Version{Path: t.path, Version: "none"} return } m, err := getQuery(t.path, t.vers, t.forceModulePath) if err != nil { base.Errorf("go get %v: %v", t.arg, err) return } t.m = m }) base.ExitIfErrors() // Now we know the specific version of each path@vers. // The final build list will be the union of three build lists: // 1. the original build list // 2. the modules named on the command line (other than @none) // 3. the upgraded requirements of those modules (if upgrading) // Start building those lists. // This loop collects (2). // Also, because the list of paths might have named multiple packages in a single module // (or even the same package multiple times), now that we know the module for each // package, this loop deduplicates multiple references to a given module. // (If a module is mentioned multiple times, the listed target version must be the same each time.) var named []module.Version byPath := make(map[string]*task) for _, t := range tasks { prev, ok := byPath[t.m.Path] if prev != nil && prev.m != t.m { base.Errorf("go get: conflicting versions for module %s: %s and %s", t.m.Path, prev.m.Version, t.m.Version) byPath[t.m.Path] = nil // sentinel to stop errors continue } if ok { continue // already added } byPath[t.m.Path] = t if t.m.Version != "none" { named = append(named, t.m) } } base.ExitIfErrors() // If the modules named on the command line have any dependencies // and we're supposed to upgrade dependencies, // chase down the full list of upgraded dependencies. // This turns required from a not-yet-upgraded (3) to the final (3). // (See list above.) var required []module.Version if getU != "" { upgraded, err := mvs.UpgradeAll(upgradeTarget, &upgrader{ Reqs: modload.Reqs(), targets: named, patch: getU == "patch", tasks: byPath, }) if err != nil { base.Fatalf("go get: %v", err) } required = upgraded[1:] // slice off upgradeTarget base.ExitIfErrors() } // Put together the final build list as described above (1) (2) (3). // If we're not using -u, then len(required) == 0 and ReloadBuildList // chases down the dependencies of all the named module versions // in one operation. var list []module.Version list = append(list, modload.BuildList()...) list = append(list, named...) list = append(list, required...) modload.SetBuildList(list) modload.ReloadBuildList() // note: does not update go.mod base.ExitIfErrors() // Scan for and apply any needed downgrades. var down []module.Version for _, m := range modload.BuildList() { t := byPath[m.Path] if t != nil && semver.Compare(m.Version, t.m.Version) > 0 { down = append(down, module.Version{Path: m.Path, Version: t.m.Version}) } } if len(down) > 0 { list, err := mvs.Downgrade(modload.Target, modload.Reqs(), down...) if err != nil { base.Fatalf("go get: %v", err) } modload.SetBuildList(list) modload.ReloadBuildList() // note: does not update go.mod } base.ExitIfErrors() // Scan for any upgrades lost by the downgrades. lost := make(map[string]string) for _, m := range modload.BuildList() { t := byPath[m.Path] if t != nil && semver.Compare(m.Version, t.m.Version) != 0 { lost[m.Path] = m.Version } } if len(lost) > 0 { desc := func(m module.Version) string { s := m.Path + "@" + m.Version t := byPath[m.Path] if t != nil && t.arg != s { s += " from " + t.arg } return s } downByPath := make(map[string]module.Version) for _, d := range down { downByPath[d.Path] = d } var buf strings.Builder fmt.Fprintf(&buf, "go get: inconsistent versions:") for _, t := range tasks { if lost[t.m.Path] == "" { continue } // We lost t because its build list requires a newer version of something in down. // Figure out exactly what. // Repeatedly constructing the build list is inefficient // if there are MANY command-line arguments, // but at least all the necessary requirement lists are cached at this point. list, err := mvs.BuildList(t.m, reqs) if err != nil { base.Fatalf("go get: %v", err) } fmt.Fprintf(&buf, "\n\t%s", desc(t.m)) sep := " requires" for _, m := range list { if down, ok := downByPath[m.Path]; ok && semver.Compare(down.Version, m.Version) < 0 { fmt.Fprintf(&buf, "%s %s@%s (not %s)", sep, m.Path, m.Version, desc(down)) sep = "," } } if sep != "," { // We have no idea why this happened. // At least report the problem. fmt.Fprintf(&buf, " ended up at %v unexpectedly (please report at golang.org/issue/new)", lost[t.m.Path]) } } base.Fatalf("%v", buf.String()) } // Everything succeeded. Update go.mod. modload.AllowWriteGoMod() modload.WriteGoMod() // If -m was specified, we're done after the module work. No download, no build. if *getM { return } if len(install) > 0 { // All requested versions were explicitly @none. // Note that 'go get -u' without any arguments results in len(install) == 1: // search.CleanImportPaths returns "." for empty args. work.BuildInit() pkgs := load.PackagesAndErrors(install) var todo []*load.Package for _, p := range pkgs { // Ignore "no Go source files" errors for 'go get' operations on modules. if p.Error != nil { if len(args) == 0 && getU != "" && strings.HasPrefix(p.Error.Err, "no Go files") { // Upgrading modules: skip the implicitly-requested package at the // current directory, even if it is not tho module root. continue } if strings.Contains(p.Error.Err, "cannot find module providing") && modload.ModuleInfo(p.ImportPath) != nil { // Explicitly-requested module, but it doesn't contain a package at the // module root. continue } } todo = append(todo, p) } // If -d was specified, we're done after the download: no build. // (The load.PackagesAndErrors is what did the download // of the named packages and their dependencies.) if len(todo) > 0 && !*getD { work.InstallPackages(install, todo) } } } // getQuery evaluates the given package path, version pair // to determine the underlying module version being requested. // If forceModulePath is set, getQuery must interpret path // as a module path. func getQuery(path, vers string, forceModulePath bool) (module.Version, error) { if vers == "" { vers = "latest" } // First choice is always to assume path is a module path. // If that works out, we're done. info, err := modload.Query(path, vers, modload.Allowed) if err == nil { return module.Version{Path: path, Version: info.Version}, nil } // Even if the query fails, if the path must be a real module, then report the query error. if forceModulePath || *getM { return module.Version{}, err } // Otherwise, try a package path. m, _, err := modload.QueryPackage(path, vers, modload.Allowed) return m, err } // An upgrader adapts an underlying mvs.Reqs to apply an // upgrade policy to a list of targets and their dependencies. // If patch=false, the upgrader implements "get -u". // If patch=true, the upgrader implements "get -u=patch". type upgrader struct { mvs.Reqs targets []module.Version patch bool tasks map[string]*task } // upgradeTarget is a fake "target" requiring all the modules to be upgraded. var upgradeTarget = module.Version{Path: "upgrade target", Version: ""} // Required returns the requirement list for m. // Other than the upgradeTarget, we defer to u.Reqs. func (u *upgrader) Required(m module.Version) ([]module.Version, error) { if m == upgradeTarget { return u.targets, nil } return u.Reqs.Required(m) } // Upgrade returns the desired upgrade for m. // If m is a tagged version, then Upgrade returns the latest tagged version. // If m is a pseudo-version, then Upgrade returns the latest tagged version // when that version has a time-stamp newer than m. // Otherwise Upgrade returns m (preserving the pseudo-version). // This special case prevents accidental downgrades // when already using a pseudo-version newer than the latest tagged version. func (u *upgrader) Upgrade(m module.Version) (module.Version, error) { // Allow pkg@vers on the command line to override the upgrade choice v. // If t's version is < v, then we're going to downgrade anyway, // and it's cleaner to avoid moving back and forth and picking up // extraneous other newer dependencies. // If t's version is > v, then we're going to upgrade past v anyway, // and again it's cleaner to avoid moving back and forth picking up // extraneous other newer dependencies. if t := u.tasks[m.Path]; t != nil { return t.m, nil } // Note that query "latest" is not the same as // using repo.Latest. // The query only falls back to untagged versions // if nothing is tagged. The Latest method // only ever returns untagged versions, // which is not what we want. query := "latest" if u.patch { // For patch upgrade, query "v1.2". query = semver.MajorMinor(m.Version) } info, err := modload.Query(m.Path, query, modload.Allowed) if err != nil { // Report error but return m, to let version selection continue. // (Reporting the error will fail the command at the next base.ExitIfErrors.) // Special case: if the error is "no matching versions" then don't // even report the error. Because Query does not consider pseudo-versions, // it may happen that we have a pseudo-version but during -u=patch // the query v0.0 matches no versions (not even the one we're using). if !strings.Contains(err.Error(), "no matching versions") { base.Errorf("go get: upgrading %s@%s: %v", m.Path, m.Version, err) } return m, nil } // If we're on a later prerelease, keep using it, // even though normally an Upgrade will ignore prereleases. if semver.Compare(info.Version, m.Version) < 0 { return m, nil } // If we're on a pseudo-version chronologically after the latest tagged version, keep using it. // This avoids some accidental downgrades. if mTime, err := modfetch.PseudoVersionTime(m.Version); err == nil && info.Time.Before(mTime) { return m, nil } return module.Version{Path: m.Path, Version: info.Version}, nil }
get
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/get/tag_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 get import "testing" var selectTagTestTags = []string{ "go.r58", "go.r58.1", "go.r59", "go.r59.1", "go.r61", "go.r61.1", "go.weekly.2010-01-02", "go.weekly.2011-10-12", "go.weekly.2011-10-12.1", "go.weekly.2011-10-14", "go.weekly.2011-11-01", "go1", "go1.0.1", "go1.999", "go1.9.2", "go5", // these should be ignored: "release.r59", "release.r59.1", "release", "weekly.2011-10-12", "weekly.2011-10-12.1", "weekly", "foo", "bar", "go.f00", "go!r60", "go.1999-01-01", "go.2x", "go.20000000000000", "go.2.", "go.2.0", "go2x", "go20000000000000", "go2.", "go2.0", } var selectTagTests = []struct { version string selected string }{ /* {"release.r57", ""}, {"release.r58.2", "go.r58.1"}, {"release.r59", "go.r59"}, {"release.r59.1", "go.r59.1"}, {"release.r60", "go.r59.1"}, {"release.r60.1", "go.r59.1"}, {"release.r61", "go.r61"}, {"release.r66", "go.r61.1"}, {"weekly.2010-01-01", ""}, {"weekly.2010-01-02", "go.weekly.2010-01-02"}, {"weekly.2010-01-02.1", "go.weekly.2010-01-02"}, {"weekly.2010-01-03", "go.weekly.2010-01-02"}, {"weekly.2011-10-12", "go.weekly.2011-10-12"}, {"weekly.2011-10-12.1", "go.weekly.2011-10-12.1"}, {"weekly.2011-10-13", "go.weekly.2011-10-12.1"}, {"weekly.2011-10-14", "go.weekly.2011-10-14"}, {"weekly.2011-10-14.1", "go.weekly.2011-10-14"}, {"weekly.2011-11-01", "go.weekly.2011-11-01"}, {"weekly.2014-01-01", "go.weekly.2011-11-01"}, {"weekly.3000-01-01", "go.weekly.2011-11-01"}, {"go1", "go1"}, {"go1.1", "go1.0.1"}, {"go1.998", "go1.9.2"}, {"go1.1000", "go1.999"}, {"go6", "go5"}, // faulty versions: {"release.f00", ""}, {"weekly.1999-01-01", ""}, {"junk", ""}, {"", ""}, {"go2x", ""}, {"go200000000000", ""}, {"go2.", ""}, {"go2.0", ""}, */ {"anything", "go1"}, } func TestSelectTag(t *testing.T) { for _, c := range selectTagTests { selected := selectTag(c.version, selectTagTestTags) if selected != c.selected { t.Errorf("selectTag(%q) = %q, want %q", c.version, selected, c.selected) } } }
get
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/get/get.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 get implements the ``go get'' command. package get import ( "fmt" "go/build" "os" "path/filepath" "runtime" "strings" "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/load" "cmd/go/internal/search" "cmd/go/internal/str" "cmd/go/internal/web" "cmd/go/internal/work" ) var CmdGet = &base.Command{ UsageLine: "go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]", Short: "download and install packages and dependencies", Long: ` Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'. The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages. The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original. The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code. The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution. The -t flag instructs get to also download the packages required to build the tests for the specified packages. The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages. The -v flag enables verbose progress and debug output. Get also accepts build flags to control the installation. See 'go help build'. When checking out a new package, get creates the target directory GOPATH/src/<import-path>. If the GOPATH contains multiple entries, get uses the first one. For more details see: 'go help gopath'. When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of Go. The most important rule is that if the local installation is running version "go1", get searches for a branch or tag named "go1". If no such version exists it retrieves the default branch of the package. When go get checks out or updates a Git repository, it also updates any git submodules referenced by the repository. Get never checks out or updates code stored in vendor directories. For more about specifying packages, see 'go help packages'. For more about how 'go get' finds source code to download, see 'go help importpath'. This text describes the behavior of get when using GOPATH to manage source code and dependencies. If instead the go command is running in module-aware mode, the details of get's flags and effects change, as does 'go help get'. See 'go help modules' and 'go help module-get'. See also: go build, go install, go clean. `, } var HelpGopathGet = &base.Command{ UsageLine: "gopath-get", Short: "legacy GOPATH go get", Long: ` The 'go get' command changes behavior depending on whether the go command is running in module-aware mode or legacy GOPATH mode. This help text, accessible as 'go help gopath-get' even in module-aware mode, describes 'go get' as it operates in legacy GOPATH mode. Usage: ` + CmdGet.UsageLine + ` ` + CmdGet.Long, } var ( getD = CmdGet.Flag.Bool("d", false, "") getF = CmdGet.Flag.Bool("f", false, "") getT = CmdGet.Flag.Bool("t", false, "") getU = CmdGet.Flag.Bool("u", false, "") getFix = CmdGet.Flag.Bool("fix", false, "") Insecure bool ) func init() { work.AddBuildFlags(CmdGet) CmdGet.Run = runGet // break init loop CmdGet.Flag.BoolVar(&Insecure, "insecure", Insecure, "") } func runGet(cmd *base.Command, args []string) { if cfg.ModulesEnabled { // Should not happen: main.go should install the separate module-enabled get code. base.Fatalf("go get: modules not implemented") } if cfg.GoModInGOPATH != "" { // Warn about not using modules with GO111MODULE=auto when go.mod exists. // To silence the warning, users can set GO111MODULE=off. fmt.Fprintf(os.Stderr, "go get: warning: modules disabled by GO111MODULE=auto in GOPATH/src;\n\tignoring %s;\n\tsee 'go help modules'\n", base.ShortPath(cfg.GoModInGOPATH)) } work.BuildInit() if *getF && !*getU { base.Fatalf("go get: cannot use -f flag without -u") } // Disable any prompting for passwords by Git. // Only has an effect for 2.3.0 or later, but avoiding // the prompt in earlier versions is just too hard. // If user has explicitly set GIT_TERMINAL_PROMPT=1, keep // prompting. // See golang.org/issue/9341 and golang.org/issue/12706. if os.Getenv("GIT_TERMINAL_PROMPT") == "" { os.Setenv("GIT_TERMINAL_PROMPT", "0") } // Disable any ssh connection pooling by Git. // If a Git subprocess forks a child into the background to cache a new connection, // that child keeps stdout/stderr open. After the Git subprocess exits, // os /exec expects to be able to read from the stdout/stderr pipe // until EOF to get all the data that the Git subprocess wrote before exiting. // The EOF doesn't come until the child exits too, because the child // is holding the write end of the pipe. // This is unfortunate, but it has come up at least twice // (see golang.org/issue/13453 and golang.org/issue/16104) // and confuses users when it does. // If the user has explicitly set GIT_SSH or GIT_SSH_COMMAND, // assume they know what they are doing and don't step on it. // But default to turning off ControlMaster. if os.Getenv("GIT_SSH") == "" && os.Getenv("GIT_SSH_COMMAND") == "" { os.Setenv("GIT_SSH_COMMAND", "ssh -o ControlMaster=no") } // Phase 1. Download/update. var stk load.ImportStack mode := 0 if *getT { mode |= load.GetTestDeps } for _, pkg := range downloadPaths(args) { download(pkg, nil, &stk, mode) } base.ExitIfErrors() // Phase 2. Rescan packages and re-evaluate args list. // Code we downloaded and all code that depends on it // needs to be evicted from the package cache so that // the information will be recomputed. Instead of keeping // track of the reverse dependency information, evict // everything. load.ClearPackageCache() // In order to rebuild packages information completely, // we need to clear commands cache. Command packages are // referring to evicted packages from the package cache. // This leads to duplicated loads of the standard packages. load.ClearCmdCache() pkgs := load.PackagesForBuild(args) // Phase 3. Install. if *getD { // Download only. // Check delayed until now so that importPaths // and packagesForBuild have a chance to print errors. return } work.InstallPackages(args, pkgs) } // downloadPaths prepares the list of paths to pass to download. // It expands ... patterns that can be expanded. If there is no match // for a particular pattern, downloadPaths leaves it in the result list, // in the hope that we can figure out the repository from the // initial ...-free prefix. func downloadPaths(patterns []string) []string { for _, arg := range patterns { if strings.Contains(arg, "@") { base.Fatalf("go: cannot use path@version syntax in GOPATH mode") } } var pkgs []string for _, m := range search.ImportPathsQuiet(patterns) { if len(m.Pkgs) == 0 && strings.Contains(m.Pattern, "...") { pkgs = append(pkgs, m.Pattern) } else { pkgs = append(pkgs, m.Pkgs...) } } return pkgs } // downloadCache records the import paths we have already // considered during the download, to avoid duplicate work when // there is more than one dependency sequence leading to // a particular package. var downloadCache = map[string]bool{} // downloadRootCache records the version control repository // root directories we have already considered during the download. // For example, all the packages in the github.com/google/codesearch repo // share the same root (the directory for that path), and we only need // to run the hg commands to consider each repository once. var downloadRootCache = map[string]bool{} // download runs the download half of the get command // for the package named by the argument. func download(arg string, parent *load.Package, stk *load.ImportStack, mode int) { if mode&load.ResolveImport != 0 { // Caller is responsible for expanding vendor paths. panic("internal error: download mode has useVendor set") } load1 := func(path string, mode int) *load.Package { if parent == nil { return load.LoadPackageNoFlags(path, stk) } return load.LoadImport(path, parent.Dir, parent, stk, nil, mode|load.ResolveModule) } p := load1(arg, mode) if p.Error != nil && p.Error.Hard { base.Errorf("%s", p.Error) return } // loadPackage inferred the canonical ImportPath from arg. // Use that in the following to prevent hysteresis effects // in e.g. downloadCache and packageCache. // This allows invocations such as: // mkdir -p $GOPATH/src/github.com/user // cd $GOPATH/src/github.com/user // go get ./foo // see: golang.org/issue/9767 arg = p.ImportPath // There's nothing to do if this is a package in the standard library. if p.Standard { return } // Only process each package once. // (Unless we're fetching test dependencies for this package, // in which case we want to process it again.) if downloadCache[arg] && mode&load.GetTestDeps == 0 { return } downloadCache[arg] = true pkgs := []*load.Package{p} wildcardOkay := len(*stk) == 0 isWildcard := false // Download if the package is missing, or update if we're using -u. if p.Dir == "" || *getU { // The actual download. stk.Push(arg) err := downloadPackage(p) if err != nil { base.Errorf("%s", &load.PackageError{ImportStack: stk.Copy(), Err: err.Error()}) stk.Pop() return } stk.Pop() args := []string{arg} // If the argument has a wildcard in it, re-evaluate the wildcard. // We delay this until after reloadPackage so that the old entry // for p has been replaced in the package cache. if wildcardOkay && strings.Contains(arg, "...") { if build.IsLocalImport(arg) { args = search.MatchPackagesInFS(arg).Pkgs } else { args = search.MatchPackages(arg).Pkgs } isWildcard = true } // Clear all relevant package cache entries before // doing any new loads. load.ClearPackageCachePartial(args) pkgs = pkgs[:0] for _, arg := range args { // Note: load calls loadPackage or loadImport, // which push arg onto stk already. // Do not push here too, or else stk will say arg imports arg. p := load1(arg, mode) if p.Error != nil { base.Errorf("%s", p.Error) continue } pkgs = append(pkgs, p) } } // Process package, which might now be multiple packages // due to wildcard expansion. for _, p := range pkgs { if *getFix { files := base.RelPaths(p.InternalAllGoFiles()) base.Run(cfg.BuildToolexec, str.StringList(base.Tool("fix"), files)) // The imports might have changed, so reload again. p = load.ReloadPackageNoFlags(arg, stk) if p.Error != nil { base.Errorf("%s", p.Error) return } } if isWildcard { // Report both the real package and the // wildcard in any error message. stk.Push(p.ImportPath) } // Process dependencies, now that we know what they are. imports := p.Imports if mode&load.GetTestDeps != 0 { // Process test dependencies when -t is specified. // (But don't get test dependencies for test dependencies: // we always pass mode 0 to the recursive calls below.) imports = str.StringList(imports, p.TestImports, p.XTestImports) } for i, path := range imports { if path == "C" { continue } // Fail fast on import naming full vendor path. // Otherwise expand path as needed for test imports. // Note that p.Imports can have additional entries beyond p.Internal.Build.Imports. orig := path if i < len(p.Internal.Build.Imports) { orig = p.Internal.Build.Imports[i] } if j, ok := load.FindVendor(orig); ok { stk.Push(path) err := &load.PackageError{ ImportStack: stk.Copy(), Err: "must be imported as " + path[j+len("vendor/"):], } stk.Pop() base.Errorf("%s", err) continue } // If this is a test import, apply module and vendor lookup now. // We cannot pass ResolveImport to download, because // download does caching based on the value of path, // so it must be the fully qualified path already. if i >= len(p.Imports) { path = load.ResolveImportPath(p, path) } download(path, p, stk, 0) } if isWildcard { stk.Pop() } } } // downloadPackage runs the create or download command // to make the first copy of or update a copy of the given package. func downloadPackage(p *load.Package) error { var ( vcs *vcsCmd repo, rootPath string err error blindRepo bool // set if the repo has unusual configuration ) security := web.Secure if Insecure { security = web.Insecure } if p.Internal.Build.SrcRoot != "" { // Directory exists. Look for checkout along path to src. vcs, rootPath, err = vcsFromDir(p.Dir, p.Internal.Build.SrcRoot) if err != nil { return err } repo = "<local>" // should be unused; make distinctive // Double-check where it came from. if *getU && vcs.remoteRepo != nil { dir := filepath.Join(p.Internal.Build.SrcRoot, filepath.FromSlash(rootPath)) remote, err := vcs.remoteRepo(vcs, dir) if err != nil { // Proceed anyway. The package is present; we likely just don't understand // the repo configuration (e.g. unusual remote protocol). blindRepo = true } repo = remote if !*getF && err == nil { if rr, err := RepoRootForImportPath(p.ImportPath, IgnoreMod, security); err == nil { repo := rr.Repo if rr.vcs.resolveRepo != nil { resolved, err := rr.vcs.resolveRepo(rr.vcs, dir, repo) if err == nil { repo = resolved } } if remote != repo && rr.IsCustom { return fmt.Errorf("%s is a custom import path for %s, but %s is checked out from %s", rr.Root, repo, dir, remote) } } } } } else { // Analyze the import path to determine the version control system, // repository, and the import path for the root of the repository. rr, err := RepoRootForImportPath(p.ImportPath, IgnoreMod, security) if err != nil { return err } vcs, repo, rootPath = rr.vcs, rr.Repo, rr.Root } if !blindRepo && !vcs.isSecure(repo) && !Insecure { return fmt.Errorf("cannot download, %v uses insecure protocol", repo) } if p.Internal.Build.SrcRoot == "" { // Package not found. Put in first directory of $GOPATH. list := filepath.SplitList(cfg.BuildContext.GOPATH) if len(list) == 0 { return fmt.Errorf("cannot download, $GOPATH not set. For more details see: 'go help gopath'") } // Guard against people setting GOPATH=$GOROOT. if filepath.Clean(list[0]) == filepath.Clean(cfg.GOROOT) { return fmt.Errorf("cannot download, $GOPATH must not be set to $GOROOT. For more details see: 'go help gopath'") } if _, err := os.Stat(filepath.Join(list[0], "src/cmd/go/alldocs.go")); err == nil { return fmt.Errorf("cannot download, %s is a GOROOT, not a GOPATH. For more details see: 'go help gopath'", list[0]) } p.Internal.Build.Root = list[0] p.Internal.Build.SrcRoot = filepath.Join(list[0], "src") p.Internal.Build.PkgRoot = filepath.Join(list[0], "pkg") } root := filepath.Join(p.Internal.Build.SrcRoot, filepath.FromSlash(rootPath)) if err := checkNestedVCS(vcs, root, p.Internal.Build.SrcRoot); err != nil { return err } // If we've considered this repository already, don't do it again. if downloadRootCache[root] { return nil } downloadRootCache[root] = true if cfg.BuildV { fmt.Fprintf(os.Stderr, "%s (download)\n", rootPath) } // Check that this is an appropriate place for the repo to be checked out. // The target directory must either not exist or have a repo checked out already. meta := filepath.Join(root, "."+vcs.cmd) if _, err := os.Stat(meta); err != nil { // Metadata file or directory does not exist. Prepare to checkout new copy. // Some version control tools require the target directory not to exist. // We require that too, just to avoid stepping on existing work. if _, err := os.Stat(root); err == nil { return fmt.Errorf("%s exists but %s does not - stale checkout?", root, meta) } _, err := os.Stat(p.Internal.Build.Root) gopathExisted := err == nil // Some version control tools require the parent of the target to exist. parent, _ := filepath.Split(root) if err = os.MkdirAll(parent, 0777); err != nil { return err } if cfg.BuildV && !gopathExisted && p.Internal.Build.Root == cfg.BuildContext.GOPATH { fmt.Fprintf(os.Stderr, "created GOPATH=%s; see 'go help gopath'\n", p.Internal.Build.Root) } if err = vcs.create(root, repo); err != nil { return err } } else { // Metadata directory does exist; download incremental updates. if err = vcs.download(root); err != nil { return err } } if cfg.BuildN { // Do not show tag sync in -n; it's noise more than anything, // and since we're not running commands, no tag will be found. // But avoid printing nothing. fmt.Fprintf(os.Stderr, "# cd %s; %s sync/update\n", root, vcs.cmd) return nil } // Select and sync to appropriate version of the repository. tags, err := vcs.tags(root) if err != nil { return err } vers := runtime.Version() if i := strings.Index(vers, " "); i >= 0 { vers = vers[:i] } if err := vcs.tagSync(root, selectTag(vers, tags)); err != nil { return err } return nil } // selectTag returns the closest matching tag for a given version. // Closest means the latest one that is not after the current release. // Version "goX" (or "goX.Y" or "goX.Y.Z") matches tags of the same form. // Version "release.rN" matches tags of the form "go.rN" (N being a floating-point number). // Version "weekly.YYYY-MM-DD" matches tags like "go.weekly.YYYY-MM-DD". // // NOTE(rsc): Eventually we will need to decide on some logic here. // For now, there is only "go1". This matches the docs in go help get. func selectTag(goVersion string, tags []string) (match string) { for _, t := range tags { if t == "go1" { return "go1" } } return "" }
get
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/get/discovery.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 get import ( "encoding/xml" "fmt" "io" "strings" ) // charsetReader returns a reader for the given charset. Currently // it only supports UTF-8 and ASCII. Otherwise, it returns a meaningful // error which is printed by go get, so the user can find why the package // wasn't downloaded if the encoding is not supported. Note that, in // order to reduce potential errors, ASCII is treated as UTF-8 (i.e. characters // greater than 0x7f are not rejected). func charsetReader(charset string, input io.Reader) (io.Reader, error) { switch strings.ToLower(charset) { case "ascii": return input, nil default: return nil, fmt.Errorf("can't decode XML document using charset %q", charset) } } // parseMetaGoImports returns meta imports from the HTML in r. // Parsing ends at the end of the <head> section or the beginning of the <body>. func parseMetaGoImports(r io.Reader, mod ModuleMode) (imports []metaImport, err error) { d := xml.NewDecoder(r) d.CharsetReader = charsetReader d.Strict = false var t xml.Token for { t, err = d.RawToken() if err != nil { if err == io.EOF || len(imports) > 0 { err = nil } break } if e, ok := t.(xml.StartElement); ok && strings.EqualFold(e.Name.Local, "body") { break } if e, ok := t.(xml.EndElement); ok && strings.EqualFold(e.Name.Local, "head") { break } e, ok := t.(xml.StartElement) if !ok || !strings.EqualFold(e.Name.Local, "meta") { continue } if attrValue(e.Attr, "name") != "go-import" { continue } if f := strings.Fields(attrValue(e.Attr, "content")); len(f) == 3 { imports = append(imports, metaImport{ Prefix: f[0], VCS: f[1], RepoRoot: f[2], }) } } // Extract mod entries if we are paying attention to them. var list []metaImport var have map[string]bool if mod == PreferMod { have = make(map[string]bool) for _, m := range imports { if m.VCS == "mod" { have[m.Prefix] = true list = append(list, m) } } } // Append non-mod entries, ignoring those superseded by a mod entry. for _, m := range imports { if m.VCS != "mod" && !have[m.Prefix] { list = append(list, m) } } return list, nil } // attrValue returns the attribute value for the case-insensitive key // `name', or the empty string if nothing is found. func attrValue(attrs []xml.Attr, name string) string { for _, a := range attrs { if strings.EqualFold(a.Name.Local, name) { return a.Value } } return "" }
get
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vgo/vendor/cmd/go/internal/get/vcs.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 get import ( "encoding/json" "errors" "fmt" "internal/singleflight" "log" "net/url" "os" "os/exec" "path/filepath" "regexp" "strings" "sync" "cmd/go/internal/base" "cmd/go/internal/cfg" "cmd/go/internal/web" ) // A vcsCmd describes how to use a version control system // like Mercurial, Git, or Subversion. type vcsCmd struct { name string cmd string // name of binary to invoke command createCmd []string // commands to download a fresh copy of a repository downloadCmd []string // commands to download updates into an existing repository tagCmd []tagCmd // commands to list tags tagLookupCmd []tagCmd // commands to lookup tags before running tagSyncCmd tagSyncCmd []string // commands to sync to specific tag tagSyncDefault []string // commands to sync to default tag scheme []string pingCmd string remoteRepo func(v *vcsCmd, rootDir string) (remoteRepo string, err error) resolveRepo func(v *vcsCmd, rootDir, remoteRepo string) (realRepo string, err error) } var defaultSecureScheme = map[string]bool{ "https": true, "git+ssh": true, "bzr+ssh": true, "svn+ssh": true, "ssh": true, } func (v *vcsCmd) isSecure(repo string) bool { u, err := url.Parse(repo) if err != nil { // If repo is not a URL, it's not secure. return false } return v.isSecureScheme(u.Scheme) } func (v *vcsCmd) isSecureScheme(scheme string) bool { switch v.cmd { case "git": // GIT_ALLOW_PROTOCOL is an environment variable defined by Git. It is a // colon-separated list of schemes that are allowed to be used with git // fetch/clone. Any scheme not mentioned will be considered insecure. if allow := os.Getenv("GIT_ALLOW_PROTOCOL"); allow != "" { for _, s := range strings.Split(allow, ":") { if s == scheme { return true } } return false } } return defaultSecureScheme[scheme] } // A tagCmd describes a command to list available tags // that can be passed to tagSyncCmd. type tagCmd struct { cmd string // command to list tags pattern string // regexp to extract tags from list } // vcsList lists the known version control systems var vcsList = []*vcsCmd{ vcsHg, vcsGit, vcsSvn, vcsBzr, vcsFossil, } // vcsByCmd returns the version control system for the given // command name (hg, git, svn, bzr). func vcsByCmd(cmd string) *vcsCmd { for _, vcs := range vcsList { if vcs.cmd == cmd { return vcs } } return nil } // vcsHg describes how to use Mercurial. var vcsHg = &vcsCmd{ name: "Mercurial", cmd: "hg", createCmd: []string{"clone -U {repo} {dir}"}, downloadCmd: []string{"pull"}, // We allow both tag and branch names as 'tags' // for selecting a version. This lets people have // a go.release.r60 branch and a go1 branch // and make changes in both, without constantly // editing .hgtags. tagCmd: []tagCmd{ {"tags", `^(\S+)`}, {"branches", `^(\S+)`}, }, tagSyncCmd: []string{"update -r {tag}"}, tagSyncDefault: []string{"update default"}, scheme: []string{"https", "http", "ssh"}, pingCmd: "identify {scheme}://{repo}", remoteRepo: hgRemoteRepo, } func hgRemoteRepo(vcsHg *vcsCmd, rootDir string) (remoteRepo string, err error) { out, err := vcsHg.runOutput(rootDir, "paths default") if err != nil { return "", err } return strings.TrimSpace(string(out)), nil } // vcsGit describes how to use Git. var vcsGit = &vcsCmd{ name: "Git", cmd: "git", createCmd: []string{"clone {repo} {dir}", "-go-internal-cd {dir} submodule update --init --recursive"}, downloadCmd: []string{"pull --ff-only", "submodule update --init --recursive"}, tagCmd: []tagCmd{ // tags/xxx matches a git tag named xxx // origin/xxx matches a git branch named xxx on the default remote repository {"show-ref", `(?:tags|origin)/(\S+)$`}, }, tagLookupCmd: []tagCmd{ {"show-ref tags/{tag} origin/{tag}", `((?:tags|origin)/\S+)$`}, }, tagSyncCmd: []string{"checkout {tag}", "submodule update --init --recursive"}, // both createCmd and downloadCmd update the working dir. // No need to do more here. We used to 'checkout master' // but that doesn't work if the default branch is not named master. // DO NOT add 'checkout master' here. // See golang.org/issue/9032. tagSyncDefault: []string{"submodule update --init --recursive"}, scheme: []string{"git", "https", "http", "git+ssh", "ssh"}, pingCmd: "ls-remote {scheme}://{repo}", remoteRepo: gitRemoteRepo, } // scpSyntaxRe matches the SCP-like addresses used by Git to access // repositories by SSH. var scpSyntaxRe = regexp.MustCompile(`^([a-zA-Z0-9_]+)@([a-zA-Z0-9._-]+):(.*)$`) func gitRemoteRepo(vcsGit *vcsCmd, rootDir string) (remoteRepo string, err error) { cmd := "config remote.origin.url" errParse := errors.New("unable to parse output of git " + cmd) errRemoteOriginNotFound := errors.New("remote origin not found") outb, err := vcsGit.run1(rootDir, cmd, nil, false) if err != nil { // if it doesn't output any message, it means the config argument is correct, // but the config value itself doesn't exist if outb != nil && len(outb) == 0 { return "", errRemoteOriginNotFound } return "", err } out := strings.TrimSpace(string(outb)) var repoURL *url.URL if m := scpSyntaxRe.FindStringSubmatch(out); m != nil { // Match SCP-like syntax and convert it to a URL. // Eg, "git@github.com:user/repo" becomes // "ssh://git@github.com/user/repo". repoURL = &url.URL{ Scheme: "ssh", User: url.User(m[1]), Host: m[2], Path: m[3], } } else { repoURL, err = url.Parse(out) if err != nil { return "", err } } // Iterate over insecure schemes too, because this function simply // reports the state of the repo. If we can't see insecure schemes then // we can't report the actual repo URL. for _, s := range vcsGit.scheme { if repoURL.Scheme == s { return repoURL.String(), nil } } return "", errParse } // vcsBzr describes how to use Bazaar. var vcsBzr = &vcsCmd{ name: "Bazaar", cmd: "bzr", createCmd: []string{"branch {repo} {dir}"}, // Without --overwrite bzr will not pull tags that changed. // Replace by --overwrite-tags after http://pad.lv/681792 goes in. downloadCmd: []string{"pull --overwrite"}, tagCmd: []tagCmd{{"tags", `^(\S+)`}}, tagSyncCmd: []string{"update -r {tag}"}, tagSyncDefault: []string{"update -r revno:-1"}, scheme: []string{"https", "http", "bzr", "bzr+ssh"}, pingCmd: "info {scheme}://{repo}", remoteRepo: bzrRemoteRepo, resolveRepo: bzrResolveRepo, } func bzrRemoteRepo(vcsBzr *vcsCmd, rootDir string) (remoteRepo string, err error) { outb, err := vcsBzr.runOutput(rootDir, "config parent_location") if err != nil { return "", err } return strings.TrimSpace(string(outb)), nil } func bzrResolveRepo(vcsBzr *vcsCmd, rootDir, remoteRepo string) (realRepo string, err error) { outb, err := vcsBzr.runOutput(rootDir, "info "+remoteRepo) if err != nil { return "", err } out := string(outb) // Expect: // ... // (branch root|repository branch): <URL> // ... found := false for _, prefix := range []string{"\n branch root: ", "\n repository branch: "} { i := strings.Index(out, prefix) if i >= 0 { out = out[i+len(prefix):] found = true break } } if !found { return "", fmt.Errorf("unable to parse output of bzr info") } i := strings.Index(out, "\n") if i < 0 { return "", fmt.Errorf("unable to parse output of bzr info") } out = out[:i] return strings.TrimSpace(out), nil } // vcsSvn describes how to use Subversion. var vcsSvn = &vcsCmd{ name: "Subversion", cmd: "svn", createCmd: []string{"checkout {repo} {dir}"}, downloadCmd: []string{"update"}, // There is no tag command in subversion. // The branch information is all in the path names. scheme: []string{"https", "http", "svn", "svn+ssh"}, pingCmd: "info {scheme}://{repo}", remoteRepo: svnRemoteRepo, } func svnRemoteRepo(vcsSvn *vcsCmd, rootDir string) (remoteRepo string, err error) { outb, err := vcsSvn.runOutput(rootDir, "info") if err != nil { return "", err } out := string(outb) // Expect: // // ... // URL: <URL> // ... // // Note that we're not using the Repository Root line, // because svn allows checking out subtrees. // The URL will be the URL of the subtree (what we used with 'svn co') // while the Repository Root may be a much higher parent. i := strings.Index(out, "\nURL: ") if i < 0 { return "", fmt.Errorf("unable to parse output of svn info") } out = out[i+len("\nURL: "):] i = strings.Index(out, "\n") if i < 0 { return "", fmt.Errorf("unable to parse output of svn info") } out = out[:i] return strings.TrimSpace(out), nil } // fossilRepoName is the name go get associates with a fossil repository. In the // real world the file can be named anything. const fossilRepoName = ".fossil" // vcsFossil describes how to use Fossil (fossil-scm.org) var vcsFossil = &vcsCmd{ name: "Fossil", cmd: "fossil", createCmd: []string{"-go-internal-mkdir {dir} clone {repo} " + filepath.Join("{dir}", fossilRepoName), "-go-internal-cd {dir} open .fossil"}, downloadCmd: []string{"up"}, tagCmd: []tagCmd{{"tag ls", `(.*)`}}, tagSyncCmd: []string{"up tag:{tag}"}, tagSyncDefault: []string{"up trunk"}, scheme: []string{"https", "http"}, remoteRepo: fossilRemoteRepo, } func fossilRemoteRepo(vcsFossil *vcsCmd, rootDir string) (remoteRepo string, err error) { out, err := vcsFossil.runOutput(rootDir, "remote-url") if err != nil { return "", err } return strings.TrimSpace(string(out)), nil } func (v *vcsCmd) String() string { return v.name } // run runs the command line cmd in the given directory. // keyval is a list of key, value pairs. run expands // instances of {key} in cmd into value, but only after // splitting cmd into individual arguments. // If an error occurs, run prints the command line and the // command's combined stdout+stderr to standard error. // Otherwise run discards the command's output. func (v *vcsCmd) run(dir string, cmd string, keyval ...string) error { _, err := v.run1(dir, cmd, keyval, true) return err } // runVerboseOnly is like run but only generates error output to standard error in verbose mode. func (v *vcsCmd) runVerboseOnly(dir string, cmd string, keyval ...string) error { _, err := v.run1(dir, cmd, keyval, false) return err } // runOutput is like run but returns the output of the command. func (v *vcsCmd) runOutput(dir string, cmd string, keyval ...string) ([]byte, error) { return v.run1(dir, cmd, keyval, true) } // run1 is the generalized implementation of run and runOutput. func (v *vcsCmd) run1(dir string, cmdline string, keyval []string, verbose bool) ([]byte, error) { m := make(map[string]string) for i := 0; i < len(keyval); i += 2 { m[keyval[i]] = keyval[i+1] } args := strings.Fields(cmdline) for i, arg := range args { args[i] = expand(m, arg) } if len(args) >= 2 && args[0] == "-go-internal-mkdir" { var err error if filepath.IsAbs(args[1]) { err = os.Mkdir(args[1], os.ModePerm) } else { err = os.Mkdir(filepath.Join(dir, args[1]), os.ModePerm) } if err != nil { return nil, err } args = args[2:] } if len(args) >= 2 && args[0] == "-go-internal-cd" { if filepath.IsAbs(args[1]) { dir = args[1] } else { dir = filepath.Join(dir, args[1]) } args = args[2:] } _, err := exec.LookPath(v.cmd) if err != nil { fmt.Fprintf(os.Stderr, "go: missing %s command. See https://golang.org/s/gogetcmd\n", v.name) return nil, err } cmd := exec.Command(v.cmd, args...) cmd.Dir = dir cmd.Env = base.EnvForDir(cmd.Dir, os.Environ()) if cfg.BuildX { fmt.Printf("cd %s\n", dir) fmt.Printf("%s %s\n", v.cmd, strings.Join(args, " ")) } out, err := cmd.Output() if err != nil { if verbose || cfg.BuildV { fmt.Fprintf(os.Stderr, "# cd %s; %s %s\n", dir, v.cmd, strings.Join(args, " ")) if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 { os.Stderr.Write(ee.Stderr) } else { fmt.Fprintf(os.Stderr, err.Error()) } } } return out, err } // ping pings to determine scheme to use. func (v *vcsCmd) ping(scheme, repo string) error { return v.runVerboseOnly(".", v.pingCmd, "scheme", scheme, "repo", repo) } // create creates a new copy of repo in dir. // The parent of dir must exist; dir must not. func (v *vcsCmd) create(dir, repo string) error { for _, cmd := range v.createCmd { if err := v.run(".", cmd, "dir", dir, "repo", repo); err != nil { return err } } return nil } // download downloads any new changes for the repo in dir. func (v *vcsCmd) download(dir string) error { for _, cmd := range v.downloadCmd { if err := v.run(dir, cmd); err != nil { return err } } return nil } // tags returns the list of available tags for the repo in dir. func (v *vcsCmd) tags(dir string) ([]string, error) { var tags []string for _, tc := range v.tagCmd { out, err := v.runOutput(dir, tc.cmd) if err != nil { return nil, err } re := regexp.MustCompile(`(?m-s)` + tc.pattern) for _, m := range re.FindAllStringSubmatch(string(out), -1) { tags = append(tags, m[1]) } } return tags, nil } // tagSync syncs the repo in dir to the named tag, // which either is a tag returned by tags or is v.tagDefault. func (v *vcsCmd) tagSync(dir, tag string) error { if v.tagSyncCmd == nil { return nil } if tag != "" { for _, tc := range v.tagLookupCmd { out, err := v.runOutput(dir, tc.cmd, "tag", tag) if err != nil { return err } re := regexp.MustCompile(`(?m-s)` + tc.pattern) m := re.FindStringSubmatch(string(out)) if len(m) > 1 { tag = m[1] break } } } if tag == "" && v.tagSyncDefault != nil { for _, cmd := range v.tagSyncDefault { if err := v.run(dir, cmd); err != nil { return err } } return nil } for _, cmd := range v.tagSyncCmd { if err := v.run(dir, cmd, "tag", tag); err != nil { return err } } return nil } // A vcsPath describes how to convert an import path into a // version control system and repository name. type vcsPath struct { prefix string // prefix this description applies to re string // pattern for import path repo string // repository to use (expand with match of re) vcs string // version control system to use (expand with match of re) check func(match map[string]string) error // additional checks ping bool // ping for scheme to use to download repo regexp *regexp.Regexp // cached compiled form of re } // vcsFromDir inspects dir and its parents to determine the // version control system and code repository to use. // On return, root is the import path // corresponding to the root of the repository. func vcsFromDir(dir, srcRoot string) (vcs *vcsCmd, root string, err error) { // Clean and double-check that dir is in (a subdirectory of) srcRoot. dir = filepath.Clean(dir) srcRoot = filepath.Clean(srcRoot) if len(dir) <= len(srcRoot) || dir[len(srcRoot)] != filepath.Separator { return nil, "", fmt.Errorf("directory %q is outside source root %q", dir, srcRoot) } var vcsRet *vcsCmd var rootRet string origDir := dir for len(dir) > len(srcRoot) { for _, vcs := range vcsList { if _, err := os.Stat(filepath.Join(dir, "."+vcs.cmd)); err == nil { root := filepath.ToSlash(dir[len(srcRoot)+1:]) // Record first VCS we find, but keep looking, // to detect mistakes like one kind of VCS inside another. if vcsRet == nil { vcsRet = vcs rootRet = root continue } // Allow .git inside .git, which can arise due to submodules. if vcsRet == vcs && vcs.cmd == "git" { continue } // Otherwise, we have one VCS inside a different VCS. return nil, "", fmt.Errorf("directory %q uses %s, but parent %q uses %s", filepath.Join(srcRoot, rootRet), vcsRet.cmd, filepath.Join(srcRoot, root), vcs.cmd) } } // Move to parent. ndir := filepath.Dir(dir) if len(ndir) >= len(dir) { // Shouldn't happen, but just in case, stop. break } dir = ndir } if vcsRet != nil { return vcsRet, rootRet, nil } return nil, "", fmt.Errorf("directory %q is not using a known version control system", origDir) } // checkNestedVCS checks for an incorrectly-nested VCS-inside-VCS // situation for dir, checking parents up until srcRoot. func checkNestedVCS(vcs *vcsCmd, dir, srcRoot string) error { if len(dir) <= len(srcRoot) || dir[len(srcRoot)] != filepath.Separator { return fmt.Errorf("directory %q is outside source root %q", dir, srcRoot) } otherDir := dir for len(otherDir) > len(srcRoot) { for _, otherVCS := range vcsList { if _, err := os.Stat(filepath.Join(otherDir, "."+otherVCS.cmd)); err == nil { // Allow expected vcs in original dir. if otherDir == dir && otherVCS == vcs { continue } // Allow .git inside .git, which can arise due to submodules. if otherVCS == vcs && vcs.cmd == "git" { continue } // Otherwise, we have one VCS inside a different VCS. return fmt.Errorf("directory %q uses %s, but parent %q uses %s", dir, vcs.cmd, otherDir, otherVCS.cmd) } } // Move to parent. newDir := filepath.Dir(otherDir) if len(newDir) >= len(otherDir) { // Shouldn't happen, but just in case, stop. break } otherDir = newDir } return nil } // RepoRoot describes the repository root for a tree of source code. type RepoRoot struct { Repo string // repository URL, including scheme Root string // import path corresponding to root of repo IsCustom bool // defined by served <meta> tags (as opposed to hard-coded pattern) VCS string // vcs type ("mod", "git", ...) vcs *vcsCmd // internal: vcs command access } var httpPrefixRE = regexp.MustCompile(`^https?:`) // ModuleMode specifies whether to prefer modules when looking up code sources. type ModuleMode int const ( IgnoreMod ModuleMode = iota PreferMod ) // RepoRootForImportPath analyzes importPath to determine the // version control system, and code repository to use. func RepoRootForImportPath(importPath string, mod ModuleMode, security web.SecurityMode) (*RepoRoot, error) { rr, err := repoRootFromVCSPaths(importPath, "", security, vcsPaths) if err == errUnknownSite { // If there are wildcards, look up the thing before the wildcard, // hoping it applies to the wildcarded parts too. // This makes 'go get rsc.io/pdf/...' work in a fresh GOPATH. lookup := strings.TrimSuffix(importPath, "/...") if i := strings.Index(lookup, "/.../"); i >= 0 { lookup = lookup[:i] } rr, err = repoRootForImportDynamic(lookup, mod, security) if err != nil { err = fmt.Errorf("unrecognized import path %q (%v)", importPath, err) } } if err != nil { rr1, err1 := repoRootFromVCSPaths(importPath, "", security, vcsPathsAfterDynamic) if err1 == nil { rr = rr1 err = nil } } if err == nil && strings.Contains(importPath, "...") && strings.Contains(rr.Root, "...") { // Do not allow wildcards in the repo root. rr = nil err = fmt.Errorf("cannot expand ... in %q", importPath) } return rr, err } var errUnknownSite = errors.New("dynamic lookup required to find mapping") // repoRootFromVCSPaths attempts to map importPath to a repoRoot // using the mappings defined in vcsPaths. // If scheme is non-empty, that scheme is forced. func repoRootFromVCSPaths(importPath, scheme string, security web.SecurityMode, vcsPaths []*vcsPath) (*RepoRoot, error) { // A common error is to use https://packagepath because that's what // hg and git require. Diagnose this helpfully. if loc := httpPrefixRE.FindStringIndex(importPath); loc != nil { // The importPath has been cleaned, so has only one slash. The pattern // ignores the slashes; the error message puts them back on the RHS at least. return nil, fmt.Errorf("%q not allowed in import path", importPath[loc[0]:loc[1]]+"//") } for _, srv := range vcsPaths { if !strings.HasPrefix(importPath, srv.prefix) { continue } m := srv.regexp.FindStringSubmatch(importPath) if m == nil { if srv.prefix != "" { return nil, fmt.Errorf("invalid %s import path %q", srv.prefix, importPath) } continue } // Build map of named subexpression matches for expand. match := map[string]string{ "prefix": srv.prefix, "import": importPath, } for i, name := range srv.regexp.SubexpNames() { if name != "" && match[name] == "" { match[name] = m[i] } } if srv.vcs != "" { match["vcs"] = expand(match, srv.vcs) } if srv.repo != "" { match["repo"] = expand(match, srv.repo) } if srv.check != nil { if err := srv.check(match); err != nil { return nil, err } } vcs := vcsByCmd(match["vcs"]) if vcs == nil { return nil, fmt.Errorf("unknown version control system %q", match["vcs"]) } if srv.ping { if scheme != "" { match["repo"] = scheme + "://" + match["repo"] } else { for _, scheme := range vcs.scheme { if security == web.Secure && !vcs.isSecureScheme(scheme) { continue } if vcs.pingCmd != "" && vcs.ping(scheme, match["repo"]) == nil { match["repo"] = scheme + "://" + match["repo"] goto Found } } // No scheme found. Fall back to the first one. match["repo"] = vcs.scheme[0] + "://" + match["repo"] Found: } } rr := &RepoRoot{ Repo: match["repo"], Root: match["root"], VCS: vcs.cmd, vcs: vcs, } return rr, nil } return nil, errUnknownSite } // repoRootForImportDynamic finds a *RepoRoot for a custom domain that's not // statically known by repoRootForImportPathStatic. // // This handles custom import paths like "name.tld/pkg/foo" or just "name.tld". func repoRootForImportDynamic(importPath string, mod ModuleMode, security web.SecurityMode) (*RepoRoot, error) { slash := strings.Index(importPath, "/") if slash < 0 { slash = len(importPath) } host := importPath[:slash] if !strings.Contains(host, ".") { return nil, errors.New("import path does not begin with hostname") } urlStr, body, err := web.GetMaybeInsecure(importPath, security) if err != nil { msg := "https fetch: %v" if security == web.Insecure { msg = "http/" + msg } return nil, fmt.Errorf(msg, err) } defer body.Close() imports, err := parseMetaGoImports(body, mod) if err != nil { return nil, fmt.Errorf("parsing %s: %v", importPath, err) } // Find the matched meta import. mmi, err := matchGoImport(imports, importPath) if err != nil { if _, ok := err.(ImportMismatchError); !ok { return nil, fmt.Errorf("parse %s: %v", urlStr, err) } return nil, fmt.Errorf("parse %s: no go-import meta tags (%s)", urlStr, err) } if cfg.BuildV { log.Printf("get %q: found meta tag %#v at %s", importPath, mmi, urlStr) } // If the import was "uni.edu/bob/project", which said the // prefix was "uni.edu" and the RepoRoot was "evilroot.com", // make sure we don't trust Bob and check out evilroot.com to // "uni.edu" yet (possibly overwriting/preempting another // non-evil student). Instead, first verify the root and see // if it matches Bob's claim. if mmi.Prefix != importPath { if cfg.BuildV { log.Printf("get %q: verifying non-authoritative meta tag", importPath) } urlStr0 := urlStr var imports []metaImport urlStr, imports, err = metaImportsForPrefix(mmi.Prefix, mod, security) if err != nil { return nil, err } metaImport2, err := matchGoImport(imports, importPath) if err != nil || mmi != metaImport2 { return nil, fmt.Errorf("%s and %s disagree about go-import for %s", urlStr0, urlStr, mmi.Prefix) } } if err := validateRepoRoot(mmi.RepoRoot); err != nil { return nil, fmt.Errorf("%s: invalid repo root %q: %v", urlStr, mmi.RepoRoot, err) } vcs := vcsByCmd(mmi.VCS) if vcs == nil && mmi.VCS != "mod" { return nil, fmt.Errorf("%s: unknown vcs %q", urlStr, mmi.VCS) } rr := &RepoRoot{ Repo: mmi.RepoRoot, Root: mmi.Prefix, IsCustom: true, VCS: mmi.VCS, vcs: vcs, } return rr, nil } // validateRepoRoot returns an error if repoRoot does not seem to be // a valid URL with scheme. func validateRepoRoot(repoRoot string) error { url, err := url.Parse(repoRoot) if err != nil { return err } if url.Scheme == "" { return errors.New("no scheme") } return nil } var fetchGroup singleflight.Group var ( fetchCacheMu sync.Mutex fetchCache = map[string]fetchResult{} // key is metaImportsForPrefix's importPrefix ) // metaImportsForPrefix takes a package's root import path as declared in a <meta> tag // and returns its HTML discovery URL and the parsed metaImport lines // found on the page. // // The importPath is of the form "golang.org/x/tools". // It is an error if no imports are found. // urlStr will still be valid if err != nil. // The returned urlStr will be of the form "https://golang.org/x/tools?go-get=1" func metaImportsForPrefix(importPrefix string, mod ModuleMode, security web.SecurityMode) (urlStr string, imports []metaImport, err error) { setCache := func(res fetchResult) (fetchResult, error) { fetchCacheMu.Lock() defer fetchCacheMu.Unlock() fetchCache[importPrefix] = res return res, nil } resi, _, _ := fetchGroup.Do(importPrefix, func() (resi interface{}, err error) { fetchCacheMu.Lock() if res, ok := fetchCache[importPrefix]; ok { fetchCacheMu.Unlock() return res, nil } fetchCacheMu.Unlock() urlStr, body, err := web.GetMaybeInsecure(importPrefix, security) if err != nil { return setCache(fetchResult{urlStr: urlStr, err: fmt.Errorf("fetch %s: %v", urlStr, err)}) } imports, err := parseMetaGoImports(body, mod) if err != nil { return setCache(fetchResult{urlStr: urlStr, err: fmt.Errorf("parsing %s: %v", urlStr, err)}) } if len(imports) == 0 { err = fmt.Errorf("fetch %s: no go-import meta tag", urlStr) } return setCache(fetchResult{urlStr: urlStr, imports: imports, err: err}) }) res := resi.(fetchResult) return res.urlStr, res.imports, res.err } type fetchResult struct { urlStr string // e.g. "https://foo.com/x/bar?go-get=1" imports []metaImport err error } // metaImport represents the parsed <meta name="go-import" // content="prefix vcs reporoot" /> tags from HTML files. type metaImport struct { Prefix, VCS, RepoRoot string } func splitPathHasPrefix(path, prefix []string) bool { if len(path) < len(prefix) { return false } for i, p := range prefix { if path[i] != p { return false } } return true } // A ImportMismatchError is returned where metaImport/s are present // but none match our import path. type ImportMismatchError struct { importPath string mismatches []string // the meta imports that were discarded for not matching our importPath } func (m ImportMismatchError) Error() string { formattedStrings := make([]string, len(m.mismatches)) for i, pre := range m.mismatches { formattedStrings[i] = fmt.Sprintf("meta tag %s did not match import path %s", pre, m.importPath) } return strings.Join(formattedStrings, ", ") } // matchGoImport returns the metaImport from imports matching importPath. // An error is returned if there are multiple matches. // errNoMatch is returned if none match. func matchGoImport(imports []metaImport, importPath string) (metaImport, error) { match := -1 imp := strings.Split(importPath, "/") errImportMismatch := ImportMismatchError{importPath: importPath} for i, im := range imports { pre := strings.Split(im.Prefix, "/") if !splitPathHasPrefix(imp, pre) { errImportMismatch.mismatches = append(errImportMismatch.mismatches, im.Prefix) continue } if match >= 0 { if imports[match].VCS == "mod" && im.VCS != "mod" { // All the mod entries precede all the non-mod entries. // We have a mod entry and don't care about the rest, // matching or not. break } return metaImport{}, fmt.Errorf("multiple meta tags match import path %q", importPath) } match = i } if match == -1 { return metaImport{}, errImportMismatch } return imports[match], nil } // expand rewrites s to replace {k} with match[k] for each key k in match. func expand(match map[string]string, s string) string { for k, v := range match { s = strings.Replace(s, "{"+k+"}", v, -1) } return s } // vcsPaths defines the meaning of import paths referring to // commonly-used VCS hosting sites (github.com/user/dir) // and import paths referring to a fully-qualified importPath // containing a VCS type (foo.com/repo.git/dir) var vcsPaths = []*vcsPath{ // Github { prefix: "github.com/", re: `^(?P<root>github\.com/[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+)(/[\p{L}0-9_.\-]+)*$`, vcs: "git", repo: "https://{root}", check: noVCSSuffix, }, // Bitbucket { prefix: "bitbucket.org/", re: `^(?P<root>bitbucket\.org/(?P<bitname>[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+))(/[A-Za-z0-9_.\-]+)*$`, repo: "https://{root}", check: bitbucketVCS, }, // IBM DevOps Services (JazzHub) { prefix: "hub.jazz.net/git/", re: `^(?P<root>hub\.jazz\.net/git/[a-z0-9]+/[A-Za-z0-9_.\-]+)(/[A-Za-z0-9_.\-]+)*$`, vcs: "git", repo: "https://{root}", check: noVCSSuffix, }, // Git at Apache { prefix: "git.apache.org/", re: `^(?P<root>git\.apache\.org/[a-z0-9_.\-]+\.git)(/[A-Za-z0-9_.\-]+)*$`, vcs: "git", repo: "https://{root}", }, // Git at OpenStack { prefix: "git.openstack.org/", re: `^(?P<root>git\.openstack\.org/[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+)(\.git)?(/[A-Za-z0-9_.\-]+)*$`, vcs: "git", repo: "https://{root}", }, // chiselapp.com for fossil { prefix: "chiselapp.com/", re: `^(?P<root>chiselapp\.com/user/[A-Za-z0-9]+/repository/[A-Za-z0-9_.\-]+)$`, vcs: "fossil", repo: "https://{root}", }, // General syntax for any server. // Must be last. { re: `^(?P<root>(?P<repo>([a-z0-9.\-]+\.)+[a-z0-9.\-]+(:[0-9]+)?(/~?[A-Za-z0-9_.\-]+)+?)\.(?P<vcs>bzr|fossil|git|hg|svn))(/~?[A-Za-z0-9_.\-]+)*$`, ping: true, }, } // vcsPathsAfterDynamic gives additional vcsPaths entries // to try after the dynamic HTML check. // This gives those sites a chance to introduce <meta> tags // as part of a graceful transition away from the hard-coded logic. var vcsPathsAfterDynamic = []*vcsPath{ // Launchpad. See golang.org/issue/11436. { prefix: "launchpad.net/", re: `^(?P<root>launchpad\.net/((?P<project>[A-Za-z0-9_.\-]+)(?P<series>/[A-Za-z0-9_.\-]+)?|~[A-Za-z0-9_.\-]+/(\+junk|[A-Za-z0-9_.\-]+)/[A-Za-z0-9_.\-]+))(/[A-Za-z0-9_.\-]+)*$`, vcs: "bzr", repo: "https://{root}", check: launchpadVCS, }, } func init() { // fill in cached regexps. // Doing this eagerly discovers invalid regexp syntax // without having to run a command that needs that regexp. for _, srv := range vcsPaths { srv.regexp = regexp.MustCompile(srv.re) } for _, srv := range vcsPathsAfterDynamic { srv.regexp = regexp.MustCompile(srv.re) } } // noVCSSuffix checks that the repository name does not // end in .foo for any version control system foo. // The usual culprit is ".git". func noVCSSuffix(match map[string]string) error { repo := match["repo"] for _, vcs := range vcsList { if strings.HasSuffix(repo, "."+vcs.cmd) { return fmt.Errorf("invalid version control suffix in %s path", match["prefix"]) } } return nil } // bitbucketVCS determines the version control system for a // Bitbucket repository, by using the Bitbucket API. func bitbucketVCS(match map[string]string) error { if err := noVCSSuffix(match); err != nil { return err } var resp struct { SCM string `json:"scm"` } url := expand(match, "https://api.bitbucket.org/2.0/repositories/{bitname}?fields=scm") data, err := web.Get(url) if err != nil { if httpErr, ok := err.(*web.HTTPError); ok && httpErr.StatusCode == 403 { // this may be a private repository. If so, attempt to determine which // VCS it uses. See issue 5375. root := match["root"] for _, vcs := range []string{"git", "hg"} { if vcsByCmd(vcs).ping("https", root) == nil { resp.SCM = vcs break } } } if resp.SCM == "" { return err } } else { if err := json.Unmarshal(data, &resp); err != nil { return fmt.Errorf("decoding %s: %v", url, err) } } if vcsByCmd(resp.SCM) != nil { match["vcs"] = resp.SCM if resp.SCM == "git" { match["repo"] += ".git" } return nil } return fmt.Errorf("unable to detect version control system for bitbucket.org/ path") } // launchpadVCS solves the ambiguity for "lp.net/project/foo". In this case, // "foo" could be a series name registered in Launchpad with its own branch, // and it could also be the name of a directory within the main project // branch one level up. func launchpadVCS(match map[string]string) error { if match["project"] == "" || match["series"] == "" { return nil } _, err := web.Get(expand(match, "https://code.launchpad.net/{project}{series}/.bzr/branch-format")) if err != nil { match["root"] = expand(match, "launchpad.net/{project}") match["repo"] = expand(match, "https://{root}") } return nil }