github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/src/cmd/go/main.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 main 6 7 import ( 8 "bytes" 9 "flag" 10 "fmt" 11 "go/build" 12 "io" 13 "log" 14 "os" 15 "os/exec" 16 "path" 17 "path/filepath" 18 "regexp" 19 "runtime" 20 "strings" 21 "sync" 22 "text/template" 23 "unicode" 24 "unicode/utf8" 25 ) 26 27 // A Command is an implementation of a go command 28 // like go build or go fix. 29 type Command struct { 30 // Run runs the command. 31 // The args are the arguments after the command name. 32 Run func(cmd *Command, args []string) 33 34 // UsageLine is the one-line usage message. 35 // The first word in the line is taken to be the command name. 36 UsageLine string 37 38 // Short is the short description shown in the 'go help' output. 39 Short string 40 41 // Long is the long message shown in the 'go help <this-command>' output. 42 Long string 43 44 // Flag is a set of flags specific to this command. 45 Flag flag.FlagSet 46 47 // CustomFlags indicates that the command will do its own 48 // flag parsing. 49 CustomFlags bool 50 } 51 52 // Name returns the command's name: the first word in the usage line. 53 func (c *Command) Name() string { 54 name := c.UsageLine 55 i := strings.Index(name, " ") 56 if i >= 0 { 57 name = name[:i] 58 } 59 return name 60 } 61 62 func (c *Command) Usage() { 63 fmt.Fprintf(os.Stderr, "usage: %s\n\n", c.UsageLine) 64 fmt.Fprintf(os.Stderr, "%s\n", strings.TrimSpace(c.Long)) 65 os.Exit(2) 66 } 67 68 // Runnable reports whether the command can be run; otherwise 69 // it is a documentation pseudo-command such as importpath. 70 func (c *Command) Runnable() bool { 71 return c.Run != nil 72 } 73 74 // Commands lists the available commands and help topics. 75 // The order here is the order in which they are printed by 'go help'. 76 var commands = []*Command{ 77 cmdBuild, 78 cmdClean, 79 cmdEnv, 80 cmdFix, 81 cmdFmt, 82 cmdGet, 83 cmdInstall, 84 cmdList, 85 cmdRun, 86 cmdTest, 87 cmdTool, 88 cmdVersion, 89 cmdVet, 90 91 helpC, 92 helpFileType, 93 helpGopath, 94 helpImportPath, 95 helpPackages, 96 helpTestflag, 97 helpTestfunc, 98 } 99 100 var exitStatus = 0 101 var exitMu sync.Mutex 102 103 func setExitStatus(n int) { 104 exitMu.Lock() 105 if exitStatus < n { 106 exitStatus = n 107 } 108 exitMu.Unlock() 109 } 110 111 func main() { 112 _ = go11tag 113 flag.Usage = usage 114 flag.Parse() 115 log.SetFlags(0) 116 117 args := flag.Args() 118 if len(args) < 1 { 119 usage() 120 } 121 122 if args[0] == "help" { 123 help(args[1:]) 124 return 125 } 126 127 // Diagnose common mistake: GOPATH==GOROOT. 128 // This setting is equivalent to not setting GOPATH at all, 129 // which is not what most people want when they do it. 130 if gopath := os.Getenv("GOPATH"); gopath == runtime.GOROOT() { 131 fmt.Fprintf(os.Stderr, "warning: GOPATH set to GOROOT (%s) has no effect\n", gopath) 132 } else { 133 for _, p := range filepath.SplitList(gopath) { 134 // Note: using HasPrefix instead of Contains because a ~ can appear 135 // in the middle of directory elements, such as /tmp/git-1.8.2~rc3 136 // or C:\PROGRA~1. Only ~ as a path prefix has meaning to the shell. 137 if strings.HasPrefix(p, "~") { 138 fmt.Fprintf(os.Stderr, "go: GOPATH entry cannot start with shell metacharacter '~': %q\n", p) 139 os.Exit(2) 140 } 141 if build.IsLocalImport(p) { 142 fmt.Fprintf(os.Stderr, "go: GOPATH entry is relative; must be absolute path: %q.\nRun 'go help gopath' for usage.\n", p) 143 os.Exit(2) 144 } 145 } 146 } 147 148 if fi, err := os.Stat(goroot); err != nil || !fi.IsDir() { 149 fmt.Fprintf(os.Stderr, "go: cannot find GOROOT directory: %v\n", goroot) 150 os.Exit(2) 151 } 152 153 for _, cmd := range commands { 154 if cmd.Name() == args[0] && cmd.Run != nil { 155 cmd.Flag.Usage = func() { cmd.Usage() } 156 if cmd.CustomFlags { 157 args = args[1:] 158 } else { 159 cmd.Flag.Parse(args[1:]) 160 args = cmd.Flag.Args() 161 } 162 cmd.Run(cmd, args) 163 exit() 164 return 165 } 166 } 167 168 fmt.Fprintf(os.Stderr, "go: unknown subcommand %q\nRun 'go help' for usage.\n", args[0]) 169 setExitStatus(2) 170 exit() 171 } 172 173 var usageTemplate = `Go is a tool for managing Go source code. 174 175 Usage: 176 177 go command [arguments] 178 179 The commands are: 180 {{range .}}{{if .Runnable}} 181 {{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}} 182 183 Use "go help [command]" for more information about a command. 184 185 Additional help topics: 186 {{range .}}{{if not .Runnable}} 187 {{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}} 188 189 Use "go help [topic]" for more information about that topic. 190 191 ` 192 193 var helpTemplate = `{{if .Runnable}}usage: go {{.UsageLine}} 194 195 {{end}}{{.Long | trim}} 196 ` 197 198 var documentationTemplate = `// Copyright 2011 The Go Authors. All rights reserved. 199 // Use of this source code is governed by a BSD-style 200 // license that can be found in the LICENSE file. 201 202 // DO NOT EDIT THIS FILE. GENERATED BY mkdoc.sh. 203 // Edit the documentation in other files and rerun mkdoc.sh to generate this one. 204 205 /* 206 {{range .}}{{if .Short}}{{.Short | capitalize}} 207 208 {{end}}{{if .Runnable}}Usage: 209 210 go {{.UsageLine}} 211 212 {{end}}{{.Long | trim}} 213 214 215 {{end}}*/ 216 package main 217 ` 218 219 // tmpl executes the given template text on data, writing the result to w. 220 func tmpl(w io.Writer, text string, data interface{}) { 221 t := template.New("top") 222 t.Funcs(template.FuncMap{"trim": strings.TrimSpace, "capitalize": capitalize}) 223 template.Must(t.Parse(text)) 224 if err := t.Execute(w, data); err != nil { 225 panic(err) 226 } 227 } 228 229 func capitalize(s string) string { 230 if s == "" { 231 return s 232 } 233 r, n := utf8.DecodeRuneInString(s) 234 return string(unicode.ToTitle(r)) + s[n:] 235 } 236 237 func printUsage(w io.Writer) { 238 tmpl(w, usageTemplate, commands) 239 } 240 241 func usage() { 242 // special case "go test -h" 243 if len(os.Args) > 1 && os.Args[1] == "test" { 244 help([]string{"testflag"}) 245 os.Exit(2) 246 } 247 printUsage(os.Stderr) 248 os.Exit(2) 249 } 250 251 // help implements the 'help' command. 252 func help(args []string) { 253 if len(args) == 0 { 254 printUsage(os.Stdout) 255 // not exit 2: succeeded at 'go help'. 256 return 257 } 258 if len(args) != 1 { 259 fmt.Fprintf(os.Stderr, "usage: go help command\n\nToo many arguments given.\n") 260 os.Exit(2) // failed at 'go help' 261 } 262 263 arg := args[0] 264 265 // 'go help documentation' generates doc.go. 266 if arg == "documentation" { 267 buf := new(bytes.Buffer) 268 printUsage(buf) 269 usage := &Command{Long: buf.String()} 270 tmpl(os.Stdout, documentationTemplate, append([]*Command{usage}, commands...)) 271 return 272 } 273 274 for _, cmd := range commands { 275 if cmd.Name() == arg { 276 tmpl(os.Stdout, helpTemplate, cmd) 277 // not exit 2: succeeded at 'go help cmd'. 278 return 279 } 280 } 281 282 fmt.Fprintf(os.Stderr, "Unknown help topic %#q. Run 'go help'.\n", arg) 283 os.Exit(2) // failed at 'go help cmd' 284 } 285 286 // importPathsNoDotExpansion returns the import paths to use for the given 287 // command line, but it does no ... expansion. 288 func importPathsNoDotExpansion(args []string) []string { 289 if len(args) == 0 { 290 return []string{"."} 291 } 292 var out []string 293 for _, a := range args { 294 // Arguments are supposed to be import paths, but 295 // as a courtesy to Windows developers, rewrite \ to / 296 // in command-line arguments. Handles .\... and so on. 297 if filepath.Separator == '\\' { 298 a = strings.Replace(a, `\`, `/`, -1) 299 } 300 301 // Put argument in canonical form, but preserve leading ./. 302 if strings.HasPrefix(a, "./") { 303 a = "./" + path.Clean(a) 304 if a == "./." { 305 a = "." 306 } 307 } else { 308 a = path.Clean(a) 309 } 310 if a == "all" || a == "std" { 311 out = append(out, allPackages(a)...) 312 continue 313 } 314 out = append(out, a) 315 } 316 return out 317 } 318 319 // importPaths returns the import paths to use for the given command line. 320 func importPaths(args []string) []string { 321 args = importPathsNoDotExpansion(args) 322 var out []string 323 for _, a := range args { 324 if strings.Contains(a, "...") { 325 if build.IsLocalImport(a) { 326 out = append(out, allPackagesInFS(a)...) 327 } else { 328 out = append(out, allPackages(a)...) 329 } 330 continue 331 } 332 out = append(out, a) 333 } 334 return out 335 } 336 337 var atexitFuncs []func() 338 339 func atexit(f func()) { 340 atexitFuncs = append(atexitFuncs, f) 341 } 342 343 func exit() { 344 for _, f := range atexitFuncs { 345 f() 346 } 347 os.Exit(exitStatus) 348 } 349 350 func fatalf(format string, args ...interface{}) { 351 errorf(format, args...) 352 exit() 353 } 354 355 func errorf(format string, args ...interface{}) { 356 log.Printf(format, args...) 357 setExitStatus(1) 358 } 359 360 var logf = log.Printf 361 362 func exitIfErrors() { 363 if exitStatus != 0 { 364 exit() 365 } 366 } 367 368 func run(cmdargs ...interface{}) { 369 cmdline := stringList(cmdargs...) 370 if buildN || buildX { 371 fmt.Printf("%s\n", strings.Join(cmdline, " ")) 372 if buildN { 373 return 374 } 375 } 376 377 cmd := exec.Command(cmdline[0], cmdline[1:]...) 378 cmd.Stdout = os.Stdout 379 cmd.Stderr = os.Stderr 380 if err := cmd.Run(); err != nil { 381 errorf("%v", err) 382 } 383 } 384 385 func runOut(dir string, cmdargs ...interface{}) []byte { 386 cmdline := stringList(cmdargs...) 387 cmd := exec.Command(cmdline[0], cmdline[1:]...) 388 cmd.Dir = dir 389 out, err := cmd.CombinedOutput() 390 if err != nil { 391 os.Stderr.Write(out) 392 errorf("%v", err) 393 out = nil 394 } 395 return out 396 } 397 398 // envForDir returns a copy of the environment 399 // suitable for running in the given directory. 400 // The environment is the current process's environment 401 // but with an updated $PWD, so that an os.Getwd in the 402 // child will be faster. 403 func envForDir(dir string) []string { 404 env := os.Environ() 405 // Internally we only use rooted paths, so dir is rooted. 406 // Even if dir is not rooted, no harm done. 407 return mergeEnvLists([]string{"PWD=" + dir}, env) 408 } 409 410 // mergeEnvLists merges the two environment lists such that 411 // variables with the same name in "in" replace those in "out". 412 func mergeEnvLists(in, out []string) []string { 413 NextVar: 414 for _, inkv := range in { 415 k := strings.SplitAfterN(inkv, "=", 2)[0] 416 for i, outkv := range out { 417 if strings.HasPrefix(outkv, k) { 418 out[i] = inkv 419 continue NextVar 420 } 421 } 422 out = append(out, inkv) 423 } 424 return out 425 } 426 427 // matchPattern(pattern)(name) reports whether 428 // name matches pattern. Pattern is a limited glob 429 // pattern in which '...' means 'any string' and there 430 // is no other special syntax. 431 func matchPattern(pattern string) func(name string) bool { 432 re := regexp.QuoteMeta(pattern) 433 re = strings.Replace(re, `\.\.\.`, `.*`, -1) 434 // Special case: foo/... matches foo too. 435 if strings.HasSuffix(re, `/.*`) { 436 re = re[:len(re)-len(`/.*`)] + `(/.*)?` 437 } 438 reg := regexp.MustCompile(`^` + re + `$`) 439 return func(name string) bool { 440 return reg.MatchString(name) 441 } 442 } 443 444 // hasPathPrefix reports whether the path s begins with the 445 // elements in prefix. 446 func hasPathPrefix(s, prefix string) bool { 447 switch { 448 default: 449 return false 450 case len(s) == len(prefix): 451 return s == prefix 452 case len(s) > len(prefix): 453 if prefix != "" && prefix[len(prefix)-1] == '/' { 454 return strings.HasPrefix(s, prefix) 455 } 456 return s[len(prefix)] == '/' && s[:len(prefix)] == prefix 457 } 458 } 459 460 // treeCanMatchPattern(pattern)(name) reports whether 461 // name or children of name can possibly match pattern. 462 // Pattern is the same limited glob accepted by matchPattern. 463 func treeCanMatchPattern(pattern string) func(name string) bool { 464 wildCard := false 465 if i := strings.Index(pattern, "..."); i >= 0 { 466 wildCard = true 467 pattern = pattern[:i] 468 } 469 return func(name string) bool { 470 return len(name) <= len(pattern) && hasPathPrefix(pattern, name) || 471 wildCard && strings.HasPrefix(name, pattern) 472 } 473 } 474 475 // allPackages returns all the packages that can be found 476 // under the $GOPATH directories and $GOROOT matching pattern. 477 // The pattern is either "all" (all packages), "std" (standard packages) 478 // or a path including "...". 479 func allPackages(pattern string) []string { 480 pkgs := matchPackages(pattern) 481 if len(pkgs) == 0 { 482 fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern) 483 } 484 return pkgs 485 } 486 487 func matchPackages(pattern string) []string { 488 match := func(string) bool { return true } 489 treeCanMatch := func(string) bool { return true } 490 if pattern != "all" && pattern != "std" { 491 match = matchPattern(pattern) 492 treeCanMatch = treeCanMatchPattern(pattern) 493 } 494 495 have := map[string]bool{ 496 "builtin": true, // ignore pseudo-package that exists only for documentation 497 } 498 if !buildContext.CgoEnabled { 499 have["runtime/cgo"] = true // ignore during walk 500 } 501 var pkgs []string 502 503 // Commands 504 cmd := filepath.Join(goroot, "src/cmd") + string(filepath.Separator) 505 filepath.Walk(cmd, func(path string, fi os.FileInfo, err error) error { 506 if err != nil || !fi.IsDir() || path == cmd { 507 return nil 508 } 509 name := path[len(cmd):] 510 if !treeCanMatch(name) { 511 return filepath.SkipDir 512 } 513 // Commands are all in cmd/, not in subdirectories. 514 if strings.Contains(name, string(filepath.Separator)) { 515 return filepath.SkipDir 516 } 517 518 // We use, e.g., cmd/gofmt as the pseudo import path for gofmt. 519 name = "cmd/" + name 520 if have[name] { 521 return nil 522 } 523 have[name] = true 524 if !match(name) { 525 return nil 526 } 527 _, err = buildContext.ImportDir(path, 0) 528 if err != nil { 529 if _, noGo := err.(*build.NoGoError); !noGo { 530 log.Print(err) 531 } 532 return nil 533 } 534 pkgs = append(pkgs, name) 535 return nil 536 }) 537 538 for _, src := range buildContext.SrcDirs() { 539 if pattern == "std" && src != gorootSrcPkg { 540 continue 541 } 542 src = filepath.Clean(src) + string(filepath.Separator) 543 filepath.Walk(src, func(path string, fi os.FileInfo, err error) error { 544 if err != nil || !fi.IsDir() || path == src { 545 return nil 546 } 547 548 // Avoid .foo, _foo, and testdata directory trees. 549 _, elem := filepath.Split(path) 550 if strings.HasPrefix(elem, ".") || strings.HasPrefix(elem, "_") || elem == "testdata" { 551 return filepath.SkipDir 552 } 553 554 name := filepath.ToSlash(path[len(src):]) 555 if pattern == "std" && strings.Contains(name, ".") { 556 return filepath.SkipDir 557 } 558 if !treeCanMatch(name) { 559 return filepath.SkipDir 560 } 561 if have[name] { 562 return nil 563 } 564 have[name] = true 565 if !match(name) { 566 return nil 567 } 568 _, err = buildContext.ImportDir(path, 0) 569 if err != nil { 570 if _, noGo := err.(*build.NoGoError); noGo { 571 return nil 572 } 573 } 574 pkgs = append(pkgs, name) 575 return nil 576 }) 577 } 578 return pkgs 579 } 580 581 // allPackagesInFS is like allPackages but is passed a pattern 582 // beginning ./ or ../, meaning it should scan the tree rooted 583 // at the given directory. There are ... in the pattern too. 584 func allPackagesInFS(pattern string) []string { 585 pkgs := matchPackagesInFS(pattern) 586 if len(pkgs) == 0 { 587 fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern) 588 } 589 return pkgs 590 } 591 592 func matchPackagesInFS(pattern string) []string { 593 // Find directory to begin the scan. 594 // Could be smarter but this one optimization 595 // is enough for now, since ... is usually at the 596 // end of a path. 597 i := strings.Index(pattern, "...") 598 dir, _ := path.Split(pattern[:i]) 599 600 // pattern begins with ./ or ../. 601 // path.Clean will discard the ./ but not the ../. 602 // We need to preserve the ./ for pattern matching 603 // and in the returned import paths. 604 prefix := "" 605 if strings.HasPrefix(pattern, "./") { 606 prefix = "./" 607 } 608 match := matchPattern(pattern) 609 610 var pkgs []string 611 filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error { 612 if err != nil || !fi.IsDir() { 613 return nil 614 } 615 if path == dir { 616 // filepath.Walk starts at dir and recurses. For the recursive case, 617 // the path is the result of filepath.Join, which calls filepath.Clean. 618 // The initial case is not Cleaned, though, so we do this explicitly. 619 // 620 // This converts a path like "./io/" to "io". Without this step, running 621 // "cd $GOROOT/src/pkg; go list ./io/..." would incorrectly skip the io 622 // package, because prepending the prefix "./" to the unclean path would 623 // result in "././io", and match("././io") returns false. 624 path = filepath.Clean(path) 625 } 626 627 // Avoid .foo, _foo, and testdata directory trees, but do not avoid "." or "..". 628 _, elem := filepath.Split(path) 629 dot := strings.HasPrefix(elem, ".") && elem != "." && elem != ".." 630 if dot || strings.HasPrefix(elem, "_") || elem == "testdata" { 631 return filepath.SkipDir 632 } 633 634 name := prefix + filepath.ToSlash(path) 635 if !match(name) { 636 return nil 637 } 638 if _, err = build.ImportDir(path, 0); err != nil { 639 if _, noGo := err.(*build.NoGoError); !noGo { 640 log.Print(err) 641 } 642 return nil 643 } 644 pkgs = append(pkgs, name) 645 return nil 646 }) 647 return pkgs 648 } 649 650 // stringList's arguments should be a sequence of string or []string values. 651 // stringList flattens them into a single []string. 652 func stringList(args ...interface{}) []string { 653 var x []string 654 for _, arg := range args { 655 switch arg := arg.(type) { 656 case []string: 657 x = append(x, arg...) 658 case string: 659 x = append(x, arg) 660 default: 661 panic("stringList: invalid argument") 662 } 663 } 664 return x 665 } 666 667 // toFold returns a string with the property that 668 // strings.EqualFold(s, t) iff toFold(s) == toFold(t) 669 // This lets us test a large set of strings for fold-equivalent 670 // duplicates without making a quadratic number of calls 671 // to EqualFold. Note that strings.ToUpper and strings.ToLower 672 // have the desired property in some corner cases. 673 func toFold(s string) string { 674 // Fast path: all ASCII, no upper case. 675 // Most paths look like this already. 676 for i := 0; i < len(s); i++ { 677 c := s[i] 678 if c >= utf8.RuneSelf || 'A' <= c && c <= 'Z' { 679 goto Slow 680 } 681 } 682 return s 683 684 Slow: 685 var buf bytes.Buffer 686 for _, r := range s { 687 // SimpleFold(x) cycles to the next equivalent rune > x 688 // or wraps around to smaller values. Iterate until it wraps, 689 // and we've found the minimum value. 690 for { 691 r0 := r 692 r = unicode.SimpleFold(r0) 693 if r <= r0 { 694 break 695 } 696 } 697 // Exception to allow fast path above: A-Z => a-z 698 if 'A' <= r && r <= 'Z' { 699 r += 'a' - 'A' 700 } 701 buf.WriteRune(r) 702 } 703 return buf.String() 704 } 705 706 // foldDup reports a pair of strings from the list that are 707 // equal according to strings.EqualFold. 708 // It returns "", "" if there are no such strings. 709 func foldDup(list []string) (string, string) { 710 clash := map[string]string{} 711 for _, s := range list { 712 fold := toFold(s) 713 if t := clash[fold]; t != "" { 714 if s > t { 715 s, t = t, s 716 } 717 return s, t 718 } 719 clash[fold] = s 720 } 721 return "", "" 722 }