...

Source file src/cmd/go/internal/run/run.go

Documentation: cmd/go/internal/run

     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 run implements the “go run” command.
     6  package run
     7  
     8  import (
     9  	"context"
    10  	"go/build"
    11  	"path"
    12  	"path/filepath"
    13  	"strings"
    14  
    15  	"cmd/go/internal/base"
    16  	"cmd/go/internal/cfg"
    17  	"cmd/go/internal/load"
    18  	"cmd/go/internal/modload"
    19  	"cmd/go/internal/str"
    20  	"cmd/go/internal/work"
    21  )
    22  
    23  var CmdRun = &base.Command{
    24  	UsageLine: "go run [build flags] [-exec xprog] package [arguments...]",
    25  	Short:     "compile and run Go program",
    26  	Long: `
    27  Run compiles and runs the named main Go package.
    28  Typically the package is specified as a list of .go source files from a single
    29  directory, but it may also be an import path, file system path, or pattern
    30  matching a single known package, as in 'go run .' or 'go run my/cmd'.
    31  
    32  If the package argument has a version suffix (like @latest or @v1.0.0),
    33  "go run" builds the program in module-aware mode, ignoring the go.mod file in
    34  the current directory or any parent directory, if there is one. This is useful
    35  for running programs without affecting the dependencies of the main module.
    36  
    37  If the package argument doesn't have a version suffix, "go run" may run in
    38  module-aware mode or GOPATH mode, depending on the GO111MODULE environment
    39  variable and the presence of a go.mod file. See 'go help modules' for details.
    40  If module-aware mode is enabled, "go run" runs in the context of the main
    41  module.
    42  
    43  By default, 'go run' runs the compiled binary directly: 'a.out arguments...'.
    44  If the -exec flag is given, 'go run' invokes the binary using xprog:
    45  	'xprog a.out arguments...'.
    46  If the -exec flag is not given, GOOS or GOARCH is different from the system
    47  default, and a program named go_$GOOS_$GOARCH_exec can be found
    48  on the current search path, 'go run' invokes the binary using that program,
    49  for example 'go_js_wasm_exec a.out arguments...'. This allows execution of
    50  cross-compiled programs when a simulator or other execution method is
    51  available.
    52  
    53  By default, 'go run' compiles the binary without generating the information
    54  used by debuggers, to reduce build time. To include debugger information in
    55  the binary, use 'go build'.
    56  
    57  The exit status of Run is not the exit status of the compiled binary.
    58  
    59  For more about build flags, see 'go help build'.
    60  For more about specifying packages, see 'go help packages'.
    61  
    62  See also: go build.
    63  	`,
    64  }
    65  
    66  func init() {
    67  	CmdRun.Run = runRun // break init loop
    68  
    69  	work.AddBuildFlags(CmdRun, work.DefaultBuildFlags)
    70  	if cfg.Experiment != nil && cfg.Experiment.CoverageRedesign {
    71  		work.AddCoverFlags(CmdRun, nil)
    72  	}
    73  	CmdRun.Flag.Var((*base.StringsFlag)(&work.ExecCmd), "exec", "")
    74  }
    75  
    76  func runRun(ctx context.Context, cmd *base.Command, args []string) {
    77  	if shouldUseOutsideModuleMode(args) {
    78  		// Set global module flags for 'go run cmd@version'.
    79  		// This must be done before modload.Init, but we need to call work.BuildInit
    80  		// before loading packages, since it affects package locations, e.g.,
    81  		// for -race and -msan.
    82  		modload.ForceUseModules = true
    83  		modload.RootMode = modload.NoRoot
    84  		modload.AllowMissingModuleImports()
    85  		modload.Init()
    86  	} else {
    87  		modload.InitWorkfile()
    88  	}
    89  
    90  	work.BuildInit()
    91  	b := work.NewBuilder("")
    92  	defer func() {
    93  		if err := b.Close(); err != nil {
    94  			base.Fatal(err)
    95  		}
    96  	}()
    97  
    98  	i := 0
    99  	for i < len(args) && strings.HasSuffix(args[i], ".go") {
   100  		i++
   101  	}
   102  	pkgOpts := load.PackageOpts{MainOnly: true}
   103  	var p *load.Package
   104  	if i > 0 {
   105  		files := args[:i]
   106  		for _, file := range files {
   107  			if strings.HasSuffix(file, "_test.go") {
   108  				// GoFilesPackage is going to assign this to TestGoFiles.
   109  				// Reject since it won't be part of the build.
   110  				base.Fatalf("go: cannot run *_test.go files (%s)", file)
   111  			}
   112  		}
   113  		p = load.GoFilesPackage(ctx, pkgOpts, files)
   114  	} else if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
   115  		arg := args[0]
   116  		var pkgs []*load.Package
   117  		if strings.Contains(arg, "@") && !build.IsLocalImport(arg) && !filepath.IsAbs(arg) {
   118  			var err error
   119  			pkgs, err = load.PackagesAndErrorsOutsideModule(ctx, pkgOpts, args[:1])
   120  			if err != nil {
   121  				base.Fatal(err)
   122  			}
   123  		} else {
   124  			pkgs = load.PackagesAndErrors(ctx, pkgOpts, args[:1])
   125  		}
   126  
   127  		if len(pkgs) == 0 {
   128  			base.Fatalf("go: no packages loaded from %s", arg)
   129  		}
   130  		if len(pkgs) > 1 {
   131  			var names []string
   132  			for _, p := range pkgs {
   133  				names = append(names, p.ImportPath)
   134  			}
   135  			base.Fatalf("go: pattern %s matches multiple packages:\n\t%s", arg, strings.Join(names, "\n\t"))
   136  		}
   137  		p = pkgs[0]
   138  		i++
   139  	} else {
   140  		base.Fatalf("go: no go files listed")
   141  	}
   142  	cmdArgs := args[i:]
   143  	load.CheckPackageErrors([]*load.Package{p})
   144  
   145  	if cfg.Experiment.CoverageRedesign && cfg.BuildCover {
   146  		load.PrepareForCoverageBuild([]*load.Package{p})
   147  	}
   148  
   149  	p.Internal.OmitDebug = true
   150  	p.Target = "" // must build - not up to date
   151  	if p.Internal.CmdlineFiles {
   152  		//set executable name if go file is given as cmd-argument
   153  		var src string
   154  		if len(p.GoFiles) > 0 {
   155  			src = p.GoFiles[0]
   156  		} else if len(p.CgoFiles) > 0 {
   157  			src = p.CgoFiles[0]
   158  		} else {
   159  			// this case could only happen if the provided source uses cgo
   160  			// while cgo is disabled.
   161  			hint := ""
   162  			if !cfg.BuildContext.CgoEnabled {
   163  				hint = " (cgo is disabled)"
   164  			}
   165  			base.Fatalf("go: no suitable source files%s", hint)
   166  		}
   167  		p.Internal.ExeName = src[:len(src)-len(".go")]
   168  	} else {
   169  		p.Internal.ExeName = path.Base(p.ImportPath)
   170  	}
   171  
   172  	a1 := b.LinkAction(work.ModeBuild, work.ModeBuild, p)
   173  	a := &work.Action{Mode: "go run", Actor: work.ActorFunc(buildRunProgram), Args: cmdArgs, Deps: []*work.Action{a1}}
   174  	b.Do(ctx, a)
   175  }
   176  
   177  // shouldUseOutsideModuleMode returns whether 'go run' will load packages in
   178  // module-aware mode, ignoring the go.mod file in the current directory. It
   179  // returns true if the first argument contains "@", does not begin with "-"
   180  // (resembling a flag) or end with ".go" (a file). The argument must not be a
   181  // local or absolute file path.
   182  //
   183  // These rules are slightly different than other commands. Whether or not
   184  // 'go run' uses this mode, it interprets arguments ending with ".go" as files
   185  // and uses arguments up to the last ".go" argument to comprise the package.
   186  // If there are no ".go" arguments, only the first argument is interpreted
   187  // as a package path, since there can be only one package.
   188  func shouldUseOutsideModuleMode(args []string) bool {
   189  	// NOTE: "@" not allowed in import paths, but it is allowed in non-canonical
   190  	// versions.
   191  	return len(args) > 0 &&
   192  		!strings.HasSuffix(args[0], ".go") &&
   193  		!strings.HasPrefix(args[0], "-") &&
   194  		strings.Contains(args[0], "@") &&
   195  		!build.IsLocalImport(args[0]) &&
   196  		!filepath.IsAbs(args[0])
   197  }
   198  
   199  // buildRunProgram is the action for running a binary that has already
   200  // been compiled. We ignore exit status.
   201  func buildRunProgram(b *work.Builder, ctx context.Context, a *work.Action) error {
   202  	cmdline := str.StringList(work.FindExecCmd(), a.Deps[0].Target, a.Args)
   203  	if cfg.BuildN || cfg.BuildX {
   204  		b.Shell(a).ShowCmd("", "%s", strings.Join(cmdline, " "))
   205  		if cfg.BuildN {
   206  			return nil
   207  		}
   208  	}
   209  
   210  	base.RunStdin(cmdline)
   211  	return nil
   212  }
   213  

View as plain text