github.com/sean-/go@v0.0.0-20151219100004-97f854cd7bb6/src/go/build/build.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package build 6 7 import ( 8 "bytes" 9 "errors" 10 "fmt" 11 "go/ast" 12 "go/doc" 13 "go/parser" 14 "go/token" 15 "io" 16 "io/ioutil" 17 "log" 18 "os" 19 pathpkg "path" 20 "path/filepath" 21 "runtime" 22 "sort" 23 "strconv" 24 "strings" 25 "unicode" 26 "unicode/utf8" 27 ) 28 29 // A Context specifies the supporting context for a build. 30 type Context struct { 31 GOARCH string // target architecture 32 GOOS string // target operating system 33 GOROOT string // Go root 34 GOPATH string // Go path 35 CgoEnabled bool // whether cgo can be used 36 UseAllFiles bool // use files regardless of +build lines, file names 37 Compiler string // compiler to assume when computing target paths 38 39 // The build and release tags specify build constraints 40 // that should be considered satisfied when processing +build lines. 41 // Clients creating a new context may customize BuildTags, which 42 // defaults to empty, but it is usually an error to customize ReleaseTags, 43 // which defaults to the list of Go releases the current release is compatible with. 44 // In addition to the BuildTags and ReleaseTags, build constraints 45 // consider the values of GOARCH and GOOS as satisfied tags. 46 BuildTags []string 47 ReleaseTags []string 48 49 // The install suffix specifies a suffix to use in the name of the installation 50 // directory. By default it is empty, but custom builds that need to keep 51 // their outputs separate can set InstallSuffix to do so. For example, when 52 // using the race detector, the go command uses InstallSuffix = "race", so 53 // that on a Linux/386 system, packages are written to a directory named 54 // "linux_386_race" instead of the usual "linux_386". 55 InstallSuffix string 56 57 // By default, Import uses the operating system's file system calls 58 // to read directories and files. To read from other sources, 59 // callers can set the following functions. They all have default 60 // behaviors that use the local file system, so clients need only set 61 // the functions whose behaviors they wish to change. 62 63 // JoinPath joins the sequence of path fragments into a single path. 64 // If JoinPath is nil, Import uses filepath.Join. 65 JoinPath func(elem ...string) string 66 67 // SplitPathList splits the path list into a slice of individual paths. 68 // If SplitPathList is nil, Import uses filepath.SplitList. 69 SplitPathList func(list string) []string 70 71 // IsAbsPath reports whether path is an absolute path. 72 // If IsAbsPath is nil, Import uses filepath.IsAbs. 73 IsAbsPath func(path string) bool 74 75 // IsDir reports whether the path names a directory. 76 // If IsDir is nil, Import calls os.Stat and uses the result's IsDir method. 77 IsDir func(path string) bool 78 79 // HasSubdir reports whether dir is a subdirectory of 80 // (perhaps multiple levels below) root. 81 // If so, HasSubdir sets rel to a slash-separated path that 82 // can be joined to root to produce a path equivalent to dir. 83 // If HasSubdir is nil, Import uses an implementation built on 84 // filepath.EvalSymlinks. 85 HasSubdir func(root, dir string) (rel string, ok bool) 86 87 // ReadDir returns a slice of os.FileInfo, sorted by Name, 88 // describing the content of the named directory. 89 // If ReadDir is nil, Import uses ioutil.ReadDir. 90 ReadDir func(dir string) (fi []os.FileInfo, err error) 91 92 // OpenFile opens a file (not a directory) for reading. 93 // If OpenFile is nil, Import uses os.Open. 94 OpenFile func(path string) (r io.ReadCloser, err error) 95 } 96 97 // joinPath calls ctxt.JoinPath (if not nil) or else filepath.Join. 98 func (ctxt *Context) joinPath(elem ...string) string { 99 if f := ctxt.JoinPath; f != nil { 100 return f(elem...) 101 } 102 return filepath.Join(elem...) 103 } 104 105 // splitPathList calls ctxt.SplitPathList (if not nil) or else filepath.SplitList. 106 func (ctxt *Context) splitPathList(s string) []string { 107 if f := ctxt.SplitPathList; f != nil { 108 return f(s) 109 } 110 return filepath.SplitList(s) 111 } 112 113 // isAbsPath calls ctxt.IsAbsPath (if not nil) or else filepath.IsAbs. 114 func (ctxt *Context) isAbsPath(path string) bool { 115 if f := ctxt.IsAbsPath; f != nil { 116 return f(path) 117 } 118 return filepath.IsAbs(path) 119 } 120 121 // isDir calls ctxt.IsDir (if not nil) or else uses os.Stat. 122 func (ctxt *Context) isDir(path string) bool { 123 if f := ctxt.IsDir; f != nil { 124 return f(path) 125 } 126 fi, err := os.Stat(path) 127 return err == nil && fi.IsDir() 128 } 129 130 // hasSubdir calls ctxt.HasSubdir (if not nil) or else uses 131 // the local file system to answer the question. 132 func (ctxt *Context) hasSubdir(root, dir string) (rel string, ok bool) { 133 if f := ctxt.HasSubdir; f != nil { 134 return f(root, dir) 135 } 136 137 // Try using paths we received. 138 if rel, ok = hasSubdir(root, dir); ok { 139 return 140 } 141 142 // Try expanding symlinks and comparing 143 // expanded against unexpanded and 144 // expanded against expanded. 145 rootSym, _ := filepath.EvalSymlinks(root) 146 dirSym, _ := filepath.EvalSymlinks(dir) 147 148 if rel, ok = hasSubdir(rootSym, dir); ok { 149 return 150 } 151 if rel, ok = hasSubdir(root, dirSym); ok { 152 return 153 } 154 return hasSubdir(rootSym, dirSym) 155 } 156 157 func hasSubdir(root, dir string) (rel string, ok bool) { 158 const sep = string(filepath.Separator) 159 root = filepath.Clean(root) 160 if !strings.HasSuffix(root, sep) { 161 root += sep 162 } 163 dir = filepath.Clean(dir) 164 if !strings.HasPrefix(dir, root) { 165 return "", false 166 } 167 return filepath.ToSlash(dir[len(root):]), true 168 } 169 170 // readDir calls ctxt.ReadDir (if not nil) or else ioutil.ReadDir. 171 func (ctxt *Context) readDir(path string) ([]os.FileInfo, error) { 172 if f := ctxt.ReadDir; f != nil { 173 return f(path) 174 } 175 return ioutil.ReadDir(path) 176 } 177 178 // openFile calls ctxt.OpenFile (if not nil) or else os.Open. 179 func (ctxt *Context) openFile(path string) (io.ReadCloser, error) { 180 if fn := ctxt.OpenFile; fn != nil { 181 return fn(path) 182 } 183 184 f, err := os.Open(path) 185 if err != nil { 186 return nil, err // nil interface 187 } 188 return f, nil 189 } 190 191 // isFile determines whether path is a file by trying to open it. 192 // It reuses openFile instead of adding another function to the 193 // list in Context. 194 func (ctxt *Context) isFile(path string) bool { 195 f, err := ctxt.openFile(path) 196 if err != nil { 197 return false 198 } 199 f.Close() 200 return true 201 } 202 203 // gopath returns the list of Go path directories. 204 func (ctxt *Context) gopath() []string { 205 var all []string 206 for _, p := range ctxt.splitPathList(ctxt.GOPATH) { 207 if p == "" || p == ctxt.GOROOT { 208 // Empty paths are uninteresting. 209 // If the path is the GOROOT, ignore it. 210 // People sometimes set GOPATH=$GOROOT. 211 // Do not get confused by this common mistake. 212 continue 213 } 214 if strings.HasPrefix(p, "~") { 215 // Path segments starting with ~ on Unix are almost always 216 // users who have incorrectly quoted ~ while setting GOPATH, 217 // preventing it from expanding to $HOME. 218 // The situation is made more confusing by the fact that 219 // bash allows quoted ~ in $PATH (most shells do not). 220 // Do not get confused by this, and do not try to use the path. 221 // It does not exist, and printing errors about it confuses 222 // those users even more, because they think "sure ~ exists!". 223 // The go command diagnoses this situation and prints a 224 // useful error. 225 // On Windows, ~ is used in short names, such as c:\progra~1 226 // for c:\program files. 227 continue 228 } 229 all = append(all, p) 230 } 231 return all 232 } 233 234 // SrcDirs returns a list of package source root directories. 235 // It draws from the current Go root and Go path but omits directories 236 // that do not exist. 237 func (ctxt *Context) SrcDirs() []string { 238 var all []string 239 if ctxt.GOROOT != "" { 240 dir := ctxt.joinPath(ctxt.GOROOT, "src") 241 if ctxt.isDir(dir) { 242 all = append(all, dir) 243 } 244 } 245 for _, p := range ctxt.gopath() { 246 dir := ctxt.joinPath(p, "src") 247 if ctxt.isDir(dir) { 248 all = append(all, dir) 249 } 250 } 251 return all 252 } 253 254 // Default is the default Context for builds. 255 // It uses the GOARCH, GOOS, GOROOT, and GOPATH environment variables 256 // if set, or else the compiled code's GOARCH, GOOS, and GOROOT. 257 var Default Context = defaultContext() 258 259 // Also known to cmd/dist/build.go. 260 var cgoEnabled = map[string]bool{ 261 "darwin/386": true, 262 "darwin/amd64": true, 263 "darwin/arm": true, 264 "darwin/arm64": true, 265 "dragonfly/amd64": true, 266 "freebsd/386": true, 267 "freebsd/amd64": true, 268 "freebsd/arm": true, 269 "linux/386": true, 270 "linux/amd64": true, 271 "linux/arm": true, 272 "linux/arm64": true, 273 "linux/ppc64le": true, 274 "android/386": true, 275 "android/amd64": true, 276 "android/arm": true, 277 "netbsd/386": true, 278 "netbsd/amd64": true, 279 "netbsd/arm": true, 280 "openbsd/386": true, 281 "openbsd/amd64": true, 282 "solaris/amd64": true, 283 "windows/386": true, 284 "windows/amd64": true, 285 } 286 287 func defaultContext() Context { 288 var c Context 289 290 c.GOARCH = envOr("GOARCH", runtime.GOARCH) 291 c.GOOS = envOr("GOOS", runtime.GOOS) 292 c.GOROOT = pathpkg.Clean(runtime.GOROOT()) 293 c.GOPATH = envOr("GOPATH", "") 294 c.Compiler = runtime.Compiler 295 296 // Each major Go release in the Go 1.x series should add a tag here. 297 // Old tags should not be removed. That is, the go1.x tag is present 298 // in all releases >= Go 1.x. Code that requires Go 1.x or later should 299 // say "+build go1.x", and code that should only be built before Go 1.x 300 // (perhaps it is the stub to use in that case) should say "+build !go1.x". 301 c.ReleaseTags = []string{"go1.1", "go1.2", "go1.3", "go1.4", "go1.5", "go1.6"} 302 303 switch os.Getenv("CGO_ENABLED") { 304 case "1": 305 c.CgoEnabled = true 306 case "0": 307 c.CgoEnabled = false 308 default: 309 // cgo must be explicitly enabled for cross compilation builds 310 if runtime.GOARCH == c.GOARCH && runtime.GOOS == c.GOOS { 311 c.CgoEnabled = cgoEnabled[c.GOOS+"/"+c.GOARCH] 312 break 313 } 314 c.CgoEnabled = false 315 } 316 317 return c 318 } 319 320 func envOr(name, def string) string { 321 s := os.Getenv(name) 322 if s == "" { 323 return def 324 } 325 return s 326 } 327 328 // An ImportMode controls the behavior of the Import method. 329 type ImportMode uint 330 331 const ( 332 // If FindOnly is set, Import stops after locating the directory 333 // that should contain the sources for a package. It does not 334 // read any files in the directory. 335 FindOnly ImportMode = 1 << iota 336 337 // If AllowBinary is set, Import can be satisfied by a compiled 338 // package object without corresponding sources. 339 AllowBinary 340 341 // If ImportComment is set, parse import comments on package statements. 342 // Import returns an error if it finds a comment it cannot understand 343 // or finds conflicting comments in multiple source files. 344 // See golang.org/s/go14customimport for more information. 345 ImportComment 346 347 // If AllowVendor is set, Import searches vendor directories 348 // that apply in the given source directory before searching 349 // the GOROOT and GOPATH roots. 350 // If an Import finds and returns a package using a vendor 351 // directory, the resulting ImportPath is the complete path 352 // to the package, including the path elements leading up 353 // to and including "vendor". 354 // For example, if Import("y", "x/subdir", AllowVendor) finds 355 // "x/vendor/y", the returned package's ImportPath is "x/vendor/y", 356 // not plain "y". 357 // See golang.org/s/go15vendor for more information. 358 AllowVendor 359 ) 360 361 // A Package describes the Go package found in a directory. 362 type Package struct { 363 Dir string // directory containing package sources 364 Name string // package name 365 ImportComment string // path in import comment on package statement 366 Doc string // documentation synopsis 367 ImportPath string // import path of package ("" if unknown) 368 Root string // root of Go tree where this package lives 369 SrcRoot string // package source root directory ("" if unknown) 370 PkgRoot string // package install root directory ("" if unknown) 371 PkgTargetRoot string // architecture dependent install root directory ("" if unknown) 372 BinDir string // command install directory ("" if unknown) 373 Goroot bool // package found in Go root 374 PkgObj string // installed .a file 375 AllTags []string // tags that can influence file selection in this directory 376 ConflictDir string // this directory shadows Dir in $GOPATH 377 378 // Source files 379 GoFiles []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles) 380 CgoFiles []string // .go source files that import "C" 381 IgnoredGoFiles []string // .go source files ignored for this build 382 InvalidGoFiles []string // .go source files with detected problems (parse error, wrong package name, and so on) 383 CFiles []string // .c source files 384 CXXFiles []string // .cc, .cpp and .cxx source files 385 MFiles []string // .m (Objective-C) source files 386 HFiles []string // .h, .hh, .hpp and .hxx source files 387 SFiles []string // .s source files 388 SwigFiles []string // .swig files 389 SwigCXXFiles []string // .swigcxx files 390 SysoFiles []string // .syso system object files to add to archive 391 392 // Cgo directives 393 CgoCFLAGS []string // Cgo CFLAGS directives 394 CgoCPPFLAGS []string // Cgo CPPFLAGS directives 395 CgoCXXFLAGS []string // Cgo CXXFLAGS directives 396 CgoLDFLAGS []string // Cgo LDFLAGS directives 397 CgoPkgConfig []string // Cgo pkg-config directives 398 399 // Dependency information 400 Imports []string // imports from GoFiles, CgoFiles 401 ImportPos map[string][]token.Position // line information for Imports 402 403 // Test information 404 TestGoFiles []string // _test.go files in package 405 TestImports []string // imports from TestGoFiles 406 TestImportPos map[string][]token.Position // line information for TestImports 407 XTestGoFiles []string // _test.go files outside package 408 XTestImports []string // imports from XTestGoFiles 409 XTestImportPos map[string][]token.Position // line information for XTestImports 410 } 411 412 // IsCommand reports whether the package is considered a 413 // command to be installed (not just a library). 414 // Packages named "main" are treated as commands. 415 func (p *Package) IsCommand() bool { 416 return p.Name == "main" 417 } 418 419 // ImportDir is like Import but processes the Go package found in 420 // the named directory. 421 func (ctxt *Context) ImportDir(dir string, mode ImportMode) (*Package, error) { 422 return ctxt.Import(".", dir, mode) 423 } 424 425 // NoGoError is the error used by Import to describe a directory 426 // containing no buildable Go source files. (It may still contain 427 // test files, files hidden by build tags, and so on.) 428 type NoGoError struct { 429 Dir string 430 } 431 432 func (e *NoGoError) Error() string { 433 return "no buildable Go source files in " + e.Dir 434 } 435 436 // MultiplePackageError describes a directory containing 437 // multiple buildable Go source files for multiple packages. 438 type MultiplePackageError struct { 439 Dir string // directory containing files 440 Packages []string // package names found 441 Files []string // corresponding files: Files[i] declares package Packages[i] 442 } 443 444 func (e *MultiplePackageError) Error() string { 445 // Error string limited to two entries for compatibility. 446 return fmt.Sprintf("found packages %s (%s) and %s (%s) in %s", e.Packages[0], e.Files[0], e.Packages[1], e.Files[1], e.Dir) 447 } 448 449 func nameExt(name string) string { 450 i := strings.LastIndex(name, ".") 451 if i < 0 { 452 return "" 453 } 454 return name[i:] 455 } 456 457 // Import returns details about the Go package named by the import path, 458 // interpreting local import paths relative to the srcDir directory. 459 // If the path is a local import path naming a package that can be imported 460 // using a standard import path, the returned package will set p.ImportPath 461 // to that path. 462 // 463 // In the directory containing the package, .go, .c, .h, and .s files are 464 // considered part of the package except for: 465 // 466 // - .go files in package documentation 467 // - files starting with _ or . (likely editor temporary files) 468 // - files with build constraints not satisfied by the context 469 // 470 // If an error occurs, Import returns a non-nil error and a non-nil 471 // *Package containing partial information. 472 // 473 func (ctxt *Context) Import(path string, srcDir string, mode ImportMode) (*Package, error) { 474 p := &Package{ 475 ImportPath: path, 476 } 477 if path == "" { 478 return p, fmt.Errorf("import %q: invalid import path", path) 479 } 480 481 var pkgtargetroot string 482 var pkga string 483 var pkgerr error 484 suffix := "" 485 if ctxt.InstallSuffix != "" { 486 suffix = "_" + ctxt.InstallSuffix 487 } 488 switch ctxt.Compiler { 489 case "gccgo": 490 pkgtargetroot = "pkg/gccgo_" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix 491 case "gc": 492 pkgtargetroot = "pkg/" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix 493 default: 494 // Save error for end of function. 495 pkgerr = fmt.Errorf("import %q: unknown compiler %q", path, ctxt.Compiler) 496 } 497 setPkga := func() { 498 switch ctxt.Compiler { 499 case "gccgo": 500 dir, elem := pathpkg.Split(p.ImportPath) 501 pkga = pkgtargetroot + "/" + dir + "lib" + elem + ".a" 502 case "gc": 503 pkga = pkgtargetroot + "/" + p.ImportPath + ".a" 504 } 505 } 506 setPkga() 507 508 binaryOnly := false 509 if IsLocalImport(path) { 510 pkga = "" // local imports have no installed path 511 if srcDir == "" { 512 return p, fmt.Errorf("import %q: import relative to unknown directory", path) 513 } 514 if !ctxt.isAbsPath(path) { 515 p.Dir = ctxt.joinPath(srcDir, path) 516 } 517 // Determine canonical import path, if any. 518 // Exclude results where the import path would include /testdata/. 519 inTestdata := func(sub string) bool { 520 return strings.Contains(sub, "/testdata/") || strings.HasSuffix(sub, "/testdata") || strings.HasPrefix(sub, "testdata/") || sub == "testdata" 521 } 522 if ctxt.GOROOT != "" { 523 root := ctxt.joinPath(ctxt.GOROOT, "src") 524 if sub, ok := ctxt.hasSubdir(root, p.Dir); ok && !inTestdata(sub) { 525 p.Goroot = true 526 p.ImportPath = sub 527 p.Root = ctxt.GOROOT 528 goto Found 529 } 530 } 531 all := ctxt.gopath() 532 for i, root := range all { 533 rootsrc := ctxt.joinPath(root, "src") 534 if sub, ok := ctxt.hasSubdir(rootsrc, p.Dir); ok && !inTestdata(sub) { 535 // We found a potential import path for dir, 536 // but check that using it wouldn't find something 537 // else first. 538 if ctxt.GOROOT != "" { 539 if dir := ctxt.joinPath(ctxt.GOROOT, "src", sub); ctxt.isDir(dir) { 540 p.ConflictDir = dir 541 goto Found 542 } 543 } 544 for _, earlyRoot := range all[:i] { 545 if dir := ctxt.joinPath(earlyRoot, "src", sub); ctxt.isDir(dir) { 546 p.ConflictDir = dir 547 goto Found 548 } 549 } 550 551 // sub would not name some other directory instead of this one. 552 // Record it. 553 p.ImportPath = sub 554 p.Root = root 555 goto Found 556 } 557 } 558 // It's okay that we didn't find a root containing dir. 559 // Keep going with the information we have. 560 } else { 561 if strings.HasPrefix(path, "/") { 562 return p, fmt.Errorf("import %q: cannot import absolute path", path) 563 } 564 565 // tried records the location of unsuccessful package lookups 566 var tried struct { 567 vendor []string 568 goroot string 569 gopath []string 570 } 571 gopath := ctxt.gopath() 572 573 // Vendor directories get first chance to satisfy import. 574 if mode&AllowVendor != 0 && srcDir != "" { 575 searchVendor := func(root string, isGoroot bool) bool { 576 sub, ok := ctxt.hasSubdir(root, srcDir) 577 if !ok || !strings.HasPrefix(sub, "src/") || strings.Contains(sub, "/testdata/") { 578 return false 579 } 580 for { 581 vendor := ctxt.joinPath(root, sub, "vendor") 582 if ctxt.isDir(vendor) { 583 dir := ctxt.joinPath(vendor, path) 584 if ctxt.isDir(dir) { 585 p.Dir = dir 586 p.ImportPath = strings.TrimPrefix(pathpkg.Join(sub, "vendor", path), "src/") 587 p.Goroot = isGoroot 588 p.Root = root 589 setPkga() // p.ImportPath changed 590 return true 591 } 592 tried.vendor = append(tried.vendor, dir) 593 } 594 i := strings.LastIndex(sub, "/") 595 if i < 0 { 596 break 597 } 598 sub = sub[:i] 599 } 600 return false 601 } 602 if searchVendor(ctxt.GOROOT, true) { 603 goto Found 604 } 605 for _, root := range gopath { 606 if searchVendor(root, false) { 607 goto Found 608 } 609 } 610 } 611 612 // Determine directory from import path. 613 if ctxt.GOROOT != "" { 614 dir := ctxt.joinPath(ctxt.GOROOT, "src", path) 615 isDir := ctxt.isDir(dir) 616 binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(ctxt.GOROOT, pkga)) 617 if isDir || binaryOnly { 618 p.Dir = dir 619 p.Goroot = true 620 p.Root = ctxt.GOROOT 621 goto Found 622 } 623 tried.goroot = dir 624 } 625 for _, root := range gopath { 626 dir := ctxt.joinPath(root, "src", path) 627 isDir := ctxt.isDir(dir) 628 binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(root, pkga)) 629 if isDir || binaryOnly { 630 p.Dir = dir 631 p.Root = root 632 goto Found 633 } 634 tried.gopath = append(tried.gopath, dir) 635 } 636 637 // package was not found 638 var paths []string 639 format := "\t%s (vendor tree)" 640 for _, dir := range tried.vendor { 641 paths = append(paths, fmt.Sprintf(format, dir)) 642 format = "\t%s" 643 } 644 if tried.goroot != "" { 645 paths = append(paths, fmt.Sprintf("\t%s (from $GOROOT)", tried.goroot)) 646 } else { 647 paths = append(paths, "\t($GOROOT not set)") 648 } 649 format = "\t%s (from $GOPATH)" 650 for _, dir := range tried.gopath { 651 paths = append(paths, fmt.Sprintf(format, dir)) 652 format = "\t%s" 653 } 654 if len(tried.gopath) == 0 { 655 paths = append(paths, "\t($GOPATH not set)") 656 } 657 return p, fmt.Errorf("cannot find package %q in any of:\n%s", path, strings.Join(paths, "\n")) 658 } 659 660 Found: 661 if p.Root != "" { 662 p.SrcRoot = ctxt.joinPath(p.Root, "src") 663 p.PkgRoot = ctxt.joinPath(p.Root, "pkg") 664 p.BinDir = ctxt.joinPath(p.Root, "bin") 665 if pkga != "" { 666 p.PkgTargetRoot = ctxt.joinPath(p.Root, pkgtargetroot) 667 p.PkgObj = ctxt.joinPath(p.Root, pkga) 668 } 669 } 670 671 if mode&FindOnly != 0 { 672 return p, pkgerr 673 } 674 if binaryOnly && (mode&AllowBinary) != 0 { 675 return p, pkgerr 676 } 677 678 dirs, err := ctxt.readDir(p.Dir) 679 if err != nil { 680 return p, err 681 } 682 683 var badGoError error 684 var Sfiles []string // files with ".S" (capital S) 685 var firstFile, firstCommentFile string 686 imported := make(map[string][]token.Position) 687 testImported := make(map[string][]token.Position) 688 xTestImported := make(map[string][]token.Position) 689 allTags := make(map[string]bool) 690 fset := token.NewFileSet() 691 for _, d := range dirs { 692 if d.IsDir() { 693 continue 694 } 695 696 name := d.Name() 697 ext := nameExt(name) 698 699 badFile := func(err error) { 700 if badGoError == nil { 701 badGoError = err 702 } 703 p.InvalidGoFiles = append(p.InvalidGoFiles, name) 704 } 705 706 match, data, filename, err := ctxt.matchFile(p.Dir, name, true, allTags) 707 if err != nil { 708 badFile(err) 709 continue 710 } 711 if !match { 712 if ext == ".go" { 713 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name) 714 } 715 continue 716 } 717 718 // Going to save the file. For non-Go files, can stop here. 719 switch ext { 720 case ".c": 721 p.CFiles = append(p.CFiles, name) 722 continue 723 case ".cc", ".cpp", ".cxx": 724 p.CXXFiles = append(p.CXXFiles, name) 725 continue 726 case ".m": 727 p.MFiles = append(p.MFiles, name) 728 continue 729 case ".h", ".hh", ".hpp", ".hxx": 730 p.HFiles = append(p.HFiles, name) 731 continue 732 case ".s": 733 p.SFiles = append(p.SFiles, name) 734 continue 735 case ".S": 736 Sfiles = append(Sfiles, name) 737 continue 738 case ".swig": 739 p.SwigFiles = append(p.SwigFiles, name) 740 continue 741 case ".swigcxx": 742 p.SwigCXXFiles = append(p.SwigCXXFiles, name) 743 continue 744 case ".syso": 745 // binary objects to add to package archive 746 // Likely of the form foo_windows.syso, but 747 // the name was vetted above with goodOSArchFile. 748 p.SysoFiles = append(p.SysoFiles, name) 749 continue 750 } 751 752 pf, err := parser.ParseFile(fset, filename, data, parser.ImportsOnly|parser.ParseComments) 753 if err != nil { 754 badFile(err) 755 continue 756 } 757 758 pkg := pf.Name.Name 759 if pkg == "documentation" { 760 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name) 761 continue 762 } 763 764 isTest := strings.HasSuffix(name, "_test.go") 765 isXTest := false 766 if isTest && strings.HasSuffix(pkg, "_test") { 767 isXTest = true 768 pkg = pkg[:len(pkg)-len("_test")] 769 } 770 771 if p.Name == "" { 772 p.Name = pkg 773 firstFile = name 774 } else if pkg != p.Name { 775 badFile(&MultiplePackageError{ 776 Dir: p.Dir, 777 Packages: []string{p.Name, pkg}, 778 Files: []string{firstFile, name}, 779 }) 780 p.InvalidGoFiles = append(p.InvalidGoFiles, name) 781 } 782 if pf.Doc != nil && p.Doc == "" { 783 p.Doc = doc.Synopsis(pf.Doc.Text()) 784 } 785 786 if mode&ImportComment != 0 { 787 qcom, line := findImportComment(data) 788 if line != 0 { 789 com, err := strconv.Unquote(qcom) 790 if err != nil { 791 badFile(fmt.Errorf("%s:%d: cannot parse import comment", filename, line)) 792 } else if p.ImportComment == "" { 793 p.ImportComment = com 794 firstCommentFile = name 795 } else if p.ImportComment != com { 796 badFile(fmt.Errorf("found import comments %q (%s) and %q (%s) in %s", p.ImportComment, firstCommentFile, com, name, p.Dir)) 797 } 798 } 799 } 800 801 // Record imports and information about cgo. 802 isCgo := false 803 for _, decl := range pf.Decls { 804 d, ok := decl.(*ast.GenDecl) 805 if !ok { 806 continue 807 } 808 for _, dspec := range d.Specs { 809 spec, ok := dspec.(*ast.ImportSpec) 810 if !ok { 811 continue 812 } 813 quoted := spec.Path.Value 814 path, err := strconv.Unquote(quoted) 815 if err != nil { 816 log.Panicf("%s: parser returned invalid quoted string: <%s>", filename, quoted) 817 } 818 if isXTest { 819 xTestImported[path] = append(xTestImported[path], fset.Position(spec.Pos())) 820 } else if isTest { 821 testImported[path] = append(testImported[path], fset.Position(spec.Pos())) 822 } else { 823 imported[path] = append(imported[path], fset.Position(spec.Pos())) 824 } 825 if path == "C" { 826 if isTest { 827 badFile(fmt.Errorf("use of cgo in test %s not supported", filename)) 828 } else { 829 cg := spec.Doc 830 if cg == nil && len(d.Specs) == 1 { 831 cg = d.Doc 832 } 833 if cg != nil { 834 if err := ctxt.saveCgo(filename, p, cg); err != nil { 835 badFile(err) 836 } 837 } 838 isCgo = true 839 } 840 } 841 } 842 } 843 if isCgo { 844 allTags["cgo"] = true 845 if ctxt.CgoEnabled { 846 p.CgoFiles = append(p.CgoFiles, name) 847 } else { 848 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name) 849 } 850 } else if isXTest { 851 p.XTestGoFiles = append(p.XTestGoFiles, name) 852 } else if isTest { 853 p.TestGoFiles = append(p.TestGoFiles, name) 854 } else { 855 p.GoFiles = append(p.GoFiles, name) 856 } 857 } 858 if badGoError != nil { 859 return p, badGoError 860 } 861 if len(p.GoFiles)+len(p.CgoFiles)+len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 { 862 return p, &NoGoError{p.Dir} 863 } 864 865 for tag := range allTags { 866 p.AllTags = append(p.AllTags, tag) 867 } 868 sort.Strings(p.AllTags) 869 870 p.Imports, p.ImportPos = cleanImports(imported) 871 p.TestImports, p.TestImportPos = cleanImports(testImported) 872 p.XTestImports, p.XTestImportPos = cleanImports(xTestImported) 873 874 // add the .S files only if we are using cgo 875 // (which means gcc will compile them). 876 // The standard assemblers expect .s files. 877 if len(p.CgoFiles) > 0 { 878 p.SFiles = append(p.SFiles, Sfiles...) 879 sort.Strings(p.SFiles) 880 } 881 882 return p, pkgerr 883 } 884 885 func findImportComment(data []byte) (s string, line int) { 886 // expect keyword package 887 word, data := parseWord(data) 888 if string(word) != "package" { 889 return "", 0 890 } 891 892 // expect package name 893 _, data = parseWord(data) 894 895 // now ready for import comment, a // or /* */ comment 896 // beginning and ending on the current line. 897 for len(data) > 0 && (data[0] == ' ' || data[0] == '\t' || data[0] == '\r') { 898 data = data[1:] 899 } 900 901 var comment []byte 902 switch { 903 case bytes.HasPrefix(data, slashSlash): 904 i := bytes.Index(data, newline) 905 if i < 0 { 906 i = len(data) 907 } 908 comment = data[2:i] 909 case bytes.HasPrefix(data, slashStar): 910 data = data[2:] 911 i := bytes.Index(data, starSlash) 912 if i < 0 { 913 // malformed comment 914 return "", 0 915 } 916 comment = data[:i] 917 if bytes.Contains(comment, newline) { 918 return "", 0 919 } 920 } 921 comment = bytes.TrimSpace(comment) 922 923 // split comment into `import`, `"pkg"` 924 word, arg := parseWord(comment) 925 if string(word) != "import" { 926 return "", 0 927 } 928 929 line = 1 + bytes.Count(data[:cap(data)-cap(arg)], newline) 930 return strings.TrimSpace(string(arg)), line 931 } 932 933 var ( 934 slashSlash = []byte("//") 935 slashStar = []byte("/*") 936 starSlash = []byte("*/") 937 newline = []byte("\n") 938 ) 939 940 // skipSpaceOrComment returns data with any leading spaces or comments removed. 941 func skipSpaceOrComment(data []byte) []byte { 942 for len(data) > 0 { 943 switch data[0] { 944 case ' ', '\t', '\r', '\n': 945 data = data[1:] 946 continue 947 case '/': 948 if bytes.HasPrefix(data, slashSlash) { 949 i := bytes.Index(data, newline) 950 if i < 0 { 951 return nil 952 } 953 data = data[i+1:] 954 continue 955 } 956 if bytes.HasPrefix(data, slashStar) { 957 data = data[2:] 958 i := bytes.Index(data, starSlash) 959 if i < 0 { 960 return nil 961 } 962 data = data[i+2:] 963 continue 964 } 965 } 966 break 967 } 968 return data 969 } 970 971 // parseWord skips any leading spaces or comments in data 972 // and then parses the beginning of data as an identifier or keyword, 973 // returning that word and what remains after the word. 974 func parseWord(data []byte) (word, rest []byte) { 975 data = skipSpaceOrComment(data) 976 977 // Parse past leading word characters. 978 rest = data 979 for { 980 r, size := utf8.DecodeRune(rest) 981 if unicode.IsLetter(r) || '0' <= r && r <= '9' || r == '_' { 982 rest = rest[size:] 983 continue 984 } 985 break 986 } 987 988 word = data[:len(data)-len(rest)] 989 if len(word) == 0 { 990 return nil, nil 991 } 992 993 return word, rest 994 } 995 996 // MatchFile reports whether the file with the given name in the given directory 997 // matches the context and would be included in a Package created by ImportDir 998 // of that directory. 999 // 1000 // MatchFile considers the name of the file and may use ctxt.OpenFile to 1001 // read some or all of the file's content. 1002 func (ctxt *Context) MatchFile(dir, name string) (match bool, err error) { 1003 match, _, _, err = ctxt.matchFile(dir, name, false, nil) 1004 return 1005 } 1006 1007 // matchFile determines whether the file with the given name in the given directory 1008 // should be included in the package being constructed. 1009 // It returns the data read from the file. 1010 // If returnImports is true and name denotes a Go program, matchFile reads 1011 // until the end of the imports (and returns that data) even though it only 1012 // considers text until the first non-comment. 1013 // If allTags is non-nil, matchFile records any encountered build tag 1014 // by setting allTags[tag] = true. 1015 func (ctxt *Context) matchFile(dir, name string, returnImports bool, allTags map[string]bool) (match bool, data []byte, filename string, err error) { 1016 if strings.HasPrefix(name, "_") || 1017 strings.HasPrefix(name, ".") { 1018 return 1019 } 1020 1021 i := strings.LastIndex(name, ".") 1022 if i < 0 { 1023 i = len(name) 1024 } 1025 ext := name[i:] 1026 1027 if !ctxt.goodOSArchFile(name, allTags) && !ctxt.UseAllFiles { 1028 return 1029 } 1030 1031 switch ext { 1032 case ".go", ".c", ".cc", ".cxx", ".cpp", ".m", ".s", ".h", ".hh", ".hpp", ".hxx", ".S", ".swig", ".swigcxx": 1033 // tentatively okay - read to make sure 1034 case ".syso": 1035 // binary, no reading 1036 match = true 1037 return 1038 default: 1039 // skip 1040 return 1041 } 1042 1043 filename = ctxt.joinPath(dir, name) 1044 f, err := ctxt.openFile(filename) 1045 if err != nil { 1046 return 1047 } 1048 1049 if strings.HasSuffix(filename, ".go") { 1050 data, err = readImports(f, false, nil) 1051 } else { 1052 data, err = readComments(f) 1053 } 1054 f.Close() 1055 if err != nil { 1056 err = fmt.Errorf("read %s: %v", filename, err) 1057 return 1058 } 1059 1060 // Look for +build comments to accept or reject the file. 1061 if !ctxt.shouldBuild(data, allTags) && !ctxt.UseAllFiles { 1062 return 1063 } 1064 1065 match = true 1066 return 1067 } 1068 1069 func cleanImports(m map[string][]token.Position) ([]string, map[string][]token.Position) { 1070 all := make([]string, 0, len(m)) 1071 for path := range m { 1072 all = append(all, path) 1073 } 1074 sort.Strings(all) 1075 return all, m 1076 } 1077 1078 // Import is shorthand for Default.Import. 1079 func Import(path, srcDir string, mode ImportMode) (*Package, error) { 1080 return Default.Import(path, srcDir, mode) 1081 } 1082 1083 // ImportDir is shorthand for Default.ImportDir. 1084 func ImportDir(dir string, mode ImportMode) (*Package, error) { 1085 return Default.ImportDir(dir, mode) 1086 } 1087 1088 var slashslash = []byte("//") 1089 1090 // shouldBuild reports whether it is okay to use this file, 1091 // The rule is that in the file's leading run of // comments 1092 // and blank lines, which must be followed by a blank line 1093 // (to avoid including a Go package clause doc comment), 1094 // lines beginning with '// +build' are taken as build directives. 1095 // 1096 // The file is accepted only if each such line lists something 1097 // matching the file. For example: 1098 // 1099 // // +build windows linux 1100 // 1101 // marks the file as applicable only on Windows and Linux. 1102 // 1103 func (ctxt *Context) shouldBuild(content []byte, allTags map[string]bool) bool { 1104 // Pass 1. Identify leading run of // comments and blank lines, 1105 // which must be followed by a blank line. 1106 end := 0 1107 p := content 1108 for len(p) > 0 { 1109 line := p 1110 if i := bytes.IndexByte(line, '\n'); i >= 0 { 1111 line, p = line[:i], p[i+1:] 1112 } else { 1113 p = p[len(p):] 1114 } 1115 line = bytes.TrimSpace(line) 1116 if len(line) == 0 { // Blank line 1117 end = len(content) - len(p) 1118 continue 1119 } 1120 if !bytes.HasPrefix(line, slashslash) { // Not comment line 1121 break 1122 } 1123 } 1124 content = content[:end] 1125 1126 // Pass 2. Process each line in the run. 1127 p = content 1128 allok := true 1129 for len(p) > 0 { 1130 line := p 1131 if i := bytes.IndexByte(line, '\n'); i >= 0 { 1132 line, p = line[:i], p[i+1:] 1133 } else { 1134 p = p[len(p):] 1135 } 1136 line = bytes.TrimSpace(line) 1137 if bytes.HasPrefix(line, slashslash) { 1138 line = bytes.TrimSpace(line[len(slashslash):]) 1139 if len(line) > 0 && line[0] == '+' { 1140 // Looks like a comment +line. 1141 f := strings.Fields(string(line)) 1142 if f[0] == "+build" { 1143 ok := false 1144 for _, tok := range f[1:] { 1145 if ctxt.match(tok, allTags) { 1146 ok = true 1147 } 1148 } 1149 if !ok { 1150 allok = false 1151 } 1152 } 1153 } 1154 } 1155 } 1156 1157 return allok 1158 } 1159 1160 // saveCgo saves the information from the #cgo lines in the import "C" comment. 1161 // These lines set CFLAGS, CPPFLAGS, CXXFLAGS and LDFLAGS and pkg-config directives 1162 // that affect the way cgo's C code is built. 1163 func (ctxt *Context) saveCgo(filename string, di *Package, cg *ast.CommentGroup) error { 1164 text := cg.Text() 1165 for _, line := range strings.Split(text, "\n") { 1166 orig := line 1167 1168 // Line is 1169 // #cgo [GOOS/GOARCH...] LDFLAGS: stuff 1170 // 1171 line = strings.TrimSpace(line) 1172 if len(line) < 5 || line[:4] != "#cgo" || (line[4] != ' ' && line[4] != '\t') { 1173 continue 1174 } 1175 1176 // Split at colon. 1177 line = strings.TrimSpace(line[4:]) 1178 i := strings.Index(line, ":") 1179 if i < 0 { 1180 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig) 1181 } 1182 line, argstr := line[:i], line[i+1:] 1183 1184 // Parse GOOS/GOARCH stuff. 1185 f := strings.Fields(line) 1186 if len(f) < 1 { 1187 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig) 1188 } 1189 1190 cond, verb := f[:len(f)-1], f[len(f)-1] 1191 if len(cond) > 0 { 1192 ok := false 1193 for _, c := range cond { 1194 if ctxt.match(c, nil) { 1195 ok = true 1196 break 1197 } 1198 } 1199 if !ok { 1200 continue 1201 } 1202 } 1203 1204 args, err := splitQuoted(argstr) 1205 if err != nil { 1206 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig) 1207 } 1208 var ok bool 1209 for i, arg := range args { 1210 if arg, ok = expandSrcDir(arg, di.Dir); !ok { 1211 return fmt.Errorf("%s: malformed #cgo argument: %s", filename, arg) 1212 } 1213 args[i] = arg 1214 } 1215 1216 switch verb { 1217 case "CFLAGS": 1218 di.CgoCFLAGS = append(di.CgoCFLAGS, args...) 1219 case "CPPFLAGS": 1220 di.CgoCPPFLAGS = append(di.CgoCPPFLAGS, args...) 1221 case "CXXFLAGS": 1222 di.CgoCXXFLAGS = append(di.CgoCXXFLAGS, args...) 1223 case "LDFLAGS": 1224 di.CgoLDFLAGS = append(di.CgoLDFLAGS, args...) 1225 case "pkg-config": 1226 di.CgoPkgConfig = append(di.CgoPkgConfig, args...) 1227 default: 1228 return fmt.Errorf("%s: invalid #cgo verb: %s", filename, orig) 1229 } 1230 } 1231 return nil 1232 } 1233 1234 // expandSrcDir expands any occurrence of ${SRCDIR}, making sure 1235 // the result is safe for the shell. 1236 func expandSrcDir(str string, srcdir string) (string, bool) { 1237 // "\" delimited paths cause safeCgoName to fail 1238 // so convert native paths with a different delimeter 1239 // to "/" before starting (eg: on windows). 1240 srcdir = filepath.ToSlash(srcdir) 1241 1242 // Spaces are tolerated in ${SRCDIR}, but not anywhere else. 1243 chunks := strings.Split(str, "${SRCDIR}") 1244 if len(chunks) < 2 { 1245 return str, safeCgoName(str, false) 1246 } 1247 ok := true 1248 for _, chunk := range chunks { 1249 ok = ok && (chunk == "" || safeCgoName(chunk, false)) 1250 } 1251 ok = ok && (srcdir == "" || safeCgoName(srcdir, true)) 1252 res := strings.Join(chunks, srcdir) 1253 return res, ok && res != "" 1254 } 1255 1256 // NOTE: $ is not safe for the shell, but it is allowed here because of linker options like -Wl,$ORIGIN. 1257 // We never pass these arguments to a shell (just to programs we construct argv for), so this should be okay. 1258 // See golang.org/issue/6038. 1259 const safeString = "+-.,/0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz:$" 1260 const safeSpaces = " " 1261 1262 var safeBytes = []byte(safeSpaces + safeString) 1263 1264 func safeCgoName(s string, spaces bool) bool { 1265 if s == "" { 1266 return false 1267 } 1268 safe := safeBytes 1269 if !spaces { 1270 safe = safe[len(safeSpaces):] 1271 } 1272 for i := 0; i < len(s); i++ { 1273 if c := s[i]; c < 0x80 && bytes.IndexByte(safe, c) < 0 { 1274 return false 1275 } 1276 } 1277 return true 1278 } 1279 1280 // splitQuoted splits the string s around each instance of one or more consecutive 1281 // white space characters while taking into account quotes and escaping, and 1282 // returns an array of substrings of s or an empty list if s contains only white space. 1283 // Single quotes and double quotes are recognized to prevent splitting within the 1284 // quoted region, and are removed from the resulting substrings. If a quote in s 1285 // isn't closed err will be set and r will have the unclosed argument as the 1286 // last element. The backslash is used for escaping. 1287 // 1288 // For example, the following string: 1289 // 1290 // a b:"c d" 'e''f' "g\"" 1291 // 1292 // Would be parsed as: 1293 // 1294 // []string{"a", "b:c d", "ef", `g"`} 1295 // 1296 func splitQuoted(s string) (r []string, err error) { 1297 var args []string 1298 arg := make([]rune, len(s)) 1299 escaped := false 1300 quoted := false 1301 quote := '\x00' 1302 i := 0 1303 for _, rune := range s { 1304 switch { 1305 case escaped: 1306 escaped = false 1307 case rune == '\\': 1308 escaped = true 1309 continue 1310 case quote != '\x00': 1311 if rune == quote { 1312 quote = '\x00' 1313 continue 1314 } 1315 case rune == '"' || rune == '\'': 1316 quoted = true 1317 quote = rune 1318 continue 1319 case unicode.IsSpace(rune): 1320 if quoted || i > 0 { 1321 quoted = false 1322 args = append(args, string(arg[:i])) 1323 i = 0 1324 } 1325 continue 1326 } 1327 arg[i] = rune 1328 i++ 1329 } 1330 if quoted || i > 0 { 1331 args = append(args, string(arg[:i])) 1332 } 1333 if quote != 0 { 1334 err = errors.New("unclosed quote") 1335 } else if escaped { 1336 err = errors.New("unfinished escaping") 1337 } 1338 return args, err 1339 } 1340 1341 // match reports whether the name is one of: 1342 // 1343 // $GOOS 1344 // $GOARCH 1345 // cgo (if cgo is enabled) 1346 // !cgo (if cgo is disabled) 1347 // ctxt.Compiler 1348 // !ctxt.Compiler 1349 // tag (if tag is listed in ctxt.BuildTags or ctxt.ReleaseTags) 1350 // !tag (if tag is not listed in ctxt.BuildTags or ctxt.ReleaseTags) 1351 // a comma-separated list of any of these 1352 // 1353 func (ctxt *Context) match(name string, allTags map[string]bool) bool { 1354 if name == "" { 1355 if allTags != nil { 1356 allTags[name] = true 1357 } 1358 return false 1359 } 1360 if i := strings.Index(name, ","); i >= 0 { 1361 // comma-separated list 1362 ok1 := ctxt.match(name[:i], allTags) 1363 ok2 := ctxt.match(name[i+1:], allTags) 1364 return ok1 && ok2 1365 } 1366 if strings.HasPrefix(name, "!!") { // bad syntax, reject always 1367 return false 1368 } 1369 if strings.HasPrefix(name, "!") { // negation 1370 return len(name) > 1 && !ctxt.match(name[1:], allTags) 1371 } 1372 1373 if allTags != nil { 1374 allTags[name] = true 1375 } 1376 1377 // Tags must be letters, digits, underscores or dots. 1378 // Unlike in Go identifiers, all digits are fine (e.g., "386"). 1379 for _, c := range name { 1380 if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' { 1381 return false 1382 } 1383 } 1384 1385 // special tags 1386 if ctxt.CgoEnabled && name == "cgo" { 1387 return true 1388 } 1389 if name == ctxt.GOOS || name == ctxt.GOARCH || name == ctxt.Compiler { 1390 return true 1391 } 1392 if ctxt.GOOS == "android" && name == "linux" { 1393 return true 1394 } 1395 1396 // other tags 1397 for _, tag := range ctxt.BuildTags { 1398 if tag == name { 1399 return true 1400 } 1401 } 1402 for _, tag := range ctxt.ReleaseTags { 1403 if tag == name { 1404 return true 1405 } 1406 } 1407 1408 return false 1409 } 1410 1411 // goodOSArchFile returns false if the name contains a $GOOS or $GOARCH 1412 // suffix which does not match the current system. 1413 // The recognized name formats are: 1414 // 1415 // name_$(GOOS).* 1416 // name_$(GOARCH).* 1417 // name_$(GOOS)_$(GOARCH).* 1418 // name_$(GOOS)_test.* 1419 // name_$(GOARCH)_test.* 1420 // name_$(GOOS)_$(GOARCH)_test.* 1421 // 1422 // An exception: if GOOS=android, then files with GOOS=linux are also matched. 1423 func (ctxt *Context) goodOSArchFile(name string, allTags map[string]bool) bool { 1424 if dot := strings.Index(name, "."); dot != -1 { 1425 name = name[:dot] 1426 } 1427 1428 // Before Go 1.4, a file called "linux.go" would be equivalent to having a 1429 // build tag "linux" in that file. For Go 1.4 and beyond, we require this 1430 // auto-tagging to apply only to files with a non-empty prefix, so 1431 // "foo_linux.go" is tagged but "linux.go" is not. This allows new operating 1432 // systems, such as android, to arrive without breaking existing code with 1433 // innocuous source code in "android.go". The easiest fix: cut everything 1434 // in the name before the initial _. 1435 i := strings.Index(name, "_") 1436 if i < 0 { 1437 return true 1438 } 1439 name = name[i:] // ignore everything before first _ 1440 1441 l := strings.Split(name, "_") 1442 if n := len(l); n > 0 && l[n-1] == "test" { 1443 l = l[:n-1] 1444 } 1445 n := len(l) 1446 if n >= 2 && knownOS[l[n-2]] && knownArch[l[n-1]] { 1447 if allTags != nil { 1448 allTags[l[n-2]] = true 1449 allTags[l[n-1]] = true 1450 } 1451 if l[n-1] != ctxt.GOARCH { 1452 return false 1453 } 1454 if ctxt.GOOS == "android" && l[n-2] == "linux" { 1455 return true 1456 } 1457 return l[n-2] == ctxt.GOOS 1458 } 1459 if n >= 1 && knownOS[l[n-1]] { 1460 if allTags != nil { 1461 allTags[l[n-1]] = true 1462 } 1463 if ctxt.GOOS == "android" && l[n-1] == "linux" { 1464 return true 1465 } 1466 return l[n-1] == ctxt.GOOS 1467 } 1468 if n >= 1 && knownArch[l[n-1]] { 1469 if allTags != nil { 1470 allTags[l[n-1]] = true 1471 } 1472 return l[n-1] == ctxt.GOARCH 1473 } 1474 return true 1475 } 1476 1477 var knownOS = make(map[string]bool) 1478 var knownArch = make(map[string]bool) 1479 1480 func init() { 1481 for _, v := range strings.Fields(goosList) { 1482 knownOS[v] = true 1483 } 1484 for _, v := range strings.Fields(goarchList) { 1485 knownArch[v] = true 1486 } 1487 } 1488 1489 // ToolDir is the directory containing build tools. 1490 var ToolDir = filepath.Join(runtime.GOROOT(), "pkg/tool/"+runtime.GOOS+"_"+runtime.GOARCH) 1491 1492 // IsLocalImport reports whether the import path is 1493 // a local import path, like ".", "..", "./foo", or "../foo". 1494 func IsLocalImport(path string) bool { 1495 return path == "." || path == ".." || 1496 strings.HasPrefix(path, "./") || strings.HasPrefix(path, "../") 1497 } 1498 1499 // ArchChar returns "?" and an error. 1500 // In earlier versions of Go, the returned string was used to derive 1501 // the compiler and linker tool names, the default object file suffix, 1502 // and the default linker output name. As of Go 1.5, those strings 1503 // no longer vary by architecture; they are compile, link, .o, and a.out, respectively. 1504 func ArchChar(goarch string) (string, error) { 1505 return "?", errors.New("architecture letter no longer used") 1506 }