// determine which Command should be run
777366
func findCommand(search string, args []string, commands []*Command) (cmd *Command, name string) {
	if len(args) < 1 {
		return
	}
	if search == "" {
		search = args[0]
	} else {
		search = fmt.Sprintf("%s %s", search, args[0])
	}
	name = search
	for _, c := range commands {
		if c.Name == search {
			cmd = c
			// Clear the usage on flags as we will be printing our own
			// usage after parsing arguments
			c.Flags.Usage = func() {}
			if errHelp := c.Flags.Parse(args[1:]); errHelp != nil {
				printCommandUsage(cmd)
				os.Exit(ERROR_USAGE)
			}
			if len(cmd.Subcommands) != 0 {
				subArgs := cmd.Flags.Args()
				var subCmd *Command
				subCmd, name = findCommand(search, subArgs, cmd.Subcommands)
				if subCmd != nil {
					cmd = subCmd
				}
			}
			break
		}
	}
	return
}
1364434
func (c *cmdable) Command() *CommandsInfoCmd {
	cmd := NewCommandsInfoCmd("command")
	c.process(cmd)
	return cmd
}
957817
func (application Application) CalculatedCommand() string {
	if application.Command.IsSet {
		return application.Command.Value
	}

	return application.DetectedStartCommand.Value
}
600991
func runCommand(cmd string) error {
	log.Debug("Running " + cmd)
	var c *exec.Cmd
	if runtime.GOOS == "windows" {
		c = exec.Command("cmd", "/C", cmd)
	} else {
		c = exec.Command("/bin/sh", "-c", cmd)
	}

	output, err := c.CombinedOutput()
	if err != nil {
		log.Error(fmt.Sprintf("%q", string(output)))
		return err
	}
	log.Debug(fmt.Sprintf("%q", string(output)))
	return nil
}
1373965
func (p *PeriodicDispatch) shouldRun() bool {
	p.l.RLock()
	defer p.l.RUnlock()
	return p.enabled
}
993899
func (a *App) Command(name string) *Command {
	for _, c := range a.Commands {
		if c.HasName(name) {
			return &c
		}
	}

	return nil
}
126734
func (f *FakeCommandRunner) Run(cmd string) error {
	_, err := f.CombinedOutput(cmd)
	return err
}
1048759
func (ar *allocRunner) shouldRun() bool {
	// Do not run allocs that are terminal
	if ar.Alloc().TerminalStatus() {
		ar.logger.Trace("alloc terminal; not running",
			"desired_status", ar.Alloc().DesiredStatus,
			"client_status", ar.Alloc().ClientStatus,
		)
		return false
	}

	// It's possible that the alloc local state was marked terminal before
	// the server copy of the alloc (checked above) was marked as terminal,
	// so check the local state as well.
	switch clientStatus := ar.AllocState().ClientStatus; clientStatus {
	case structs.AllocClientStatusComplete, structs.AllocClientStatusFailed, structs.AllocClientStatusLost:
		ar.logger.Trace("alloc terminal; updating server and not running", "status", clientStatus)
		return false
	}

	return true
}
972166
func (c *diffCommand) Run(ctx *cmd.Context) error {
	client, err := c.getAPI()
	if err != nil {
		return err
	}
	defer func() { _ = client.Close() }()

	// Partially apply our time format
	formatTime := func(t time.Time) string {
		return common.FormatTime(&t, c.isoTime)
	}

	deltas, err := client.BranchInfo(c.branchName, c.detailed, formatTime)
	if err != nil {
		return errors.Trace(err)
	}
	return errors.Trace(c.out.Write(ctx, deltas))
}
456477
func runLocalCommand(cmd string, args ...string) (error, int) {
	osCmd := exec.Command(cmd, args...)
	osCmd.Stderr = os.Stderr
	osCmd.Stdout = os.Stdout
	osCmd.Start()
	err := osCmd.Wait()
	if err != nil {
		// Get the command's exit status if we can
		if exiterr, ok := err.(*exec.ExitError); ok {
			if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
				return nil, status.ExitStatus()
			}
		}
		// Otherwise, generic command error
		return err, -1
	}
	return nil, 0
}
1001018
func (b *stdBackend) command(opCode int, args interface{}) (interface{}, error) {
	cmd := &command{opCode, args, make(chan interface{})}
	b.commandC <- cmd
	resp, ok := <-cmd.respChan
	if !ok {
		return nil, errors.New(ErrMonitoringPanicked, errorMessages)
	}
	if err, ok := resp.(error); ok {
		return nil, err
	}
	return resp, nil
}
1311789
func RunCommand() {
	if len(os.Args) < 2 || os.Args[1] != "orm" {
		return
	}

	BootStrap()

	args := argString(os.Args[2:])
	name := args.Get(0)

	if name == "help" {
		printHelp()
	}

	if cmd, ok := commands[name]; ok {
		cmd.Parse(os.Args[3:])
		cmd.Run()
		os.Exit(0)
	} else {
		if name == "" {
			printHelp()
		} else {
			printHelp(fmt.Sprintf("unknown command %s", name))
		}
	}
}
334358
func Command(scriptName string, args ...string) (*exec.Cmd, error) {
	// Make sure this is a script name, not a path.
	if strings.Contains(scriptName, "/") {
		return nil, fmt.Errorf("not a script name: %v", scriptName)
	}

	// Get the list of available scripts.
	root, err := gitutil.RepositoryRootAbsolutePath()
	if err != nil {
		return nil, err
	}

	scriptsDirPath := filepath.Join(root, config.LocalConfigDirname, ScriptDirname)

	scriptsDir, err := os.Open(scriptsDirPath)
	if err != nil {
		return nil, err
	}
	defer scriptsDir.Close()

	scripts, err := scriptsDir.Readdirnames(-1)
	if err != nil {
		return nil, err
	}

	// Choose the first available script for the given script name.
	// Return a command for that script based on the file extension and platform.
	currentPlatformId := runners.ParsePlatform(runtime.GOOS)

	for _, script := range scripts {
		// To understand the loop:
		//   script     = ${base}.${ext}
		//   base       = ${name}_${platform}
		//   (=> script = ${name}_${platform}.${ext})

		// Get the file extension.
		ext := filepath.Ext(script)
		if ext == "" {
			continue
		}

		// Get the file base, i.e. the filename without the file extension.
		base := script[:len(script)-len(ext)]

		// In case the whole base matches, this is a cross-platform script and we are done.
		// Otherwise we have to parse the base further and decide what to do.
		var platformId runners.Platform
		if base == scriptName {
			platformId = currentPlatformId
		} else {
			// Split the base.
			parts := strings.Split(base, "_")

			// Make sure the platform matches the current platform.
			platform := parts[len(parts)-1]
			platformId = runners.ParsePlatform(platform)
			if platformId != currentPlatformId {
				continue
			}

			// Make sure the name matches the requested script name.
			name := base[:len(base)-len(platform)-1]
			if name != scriptName {
				continue
			}
		}

		// Get the runner for the given file extension.
		// ext contains the dot, which we need to drop.
		runner := runners.GetRunner(ext[1:], platformId)
		if runner == nil {
			continue
		}
		cmd := runner.NewCommand(filepath.Join(scriptsDirPath, script))
		cmd.Args = append(cmd.Args, args...)
		cmd.Dir = root
		return cmd, nil
	}

	return nil, &ErrNotFound{scriptName}
}
1032540
func (o *MustGatherOptions) Run(rsyncCmd *cobra.Command) error {
	if len(o.Image) == 0 {
		return fmt.Errorf("missing an image")
	}

	var err error

	// create namespace
	ns, err := o.Client.CoreV1().Namespaces().Create(&corev1.Namespace{
		ObjectMeta: metav1.ObjectMeta{
			GenerateName: "openshift-must-gather-",
			Labels: map[string]string{
				"openshift.io/run-level": "0",
			},
			Annotations: map[string]string{
				"oc.openshift.io/command": "oc adm must-gather",
			},
		},
	})
	if err != nil {
		return err
	}
	o.PrinterCreated.PrintObj(ns, o.Out)
	if !o.Keep {
		defer func() {
			if err := o.Client.CoreV1().Namespaces().Delete(ns.Name, nil); err != nil {
				fmt.Printf("%v", err)
				return
			}
			o.PrinterDeleted.PrintObj(ns, o.Out)
		}()
	}

	clusterRoleBinding, err := o.Client.RbacV1().ClusterRoleBindings().Create(o.newClusterRoleBinding(ns.Name))
	if err != nil {
		return err
	}
	o.PrinterCreated.PrintObj(clusterRoleBinding, o.Out)
	if !o.Keep {
		defer func() {
			if err := o.Client.RbacV1().ClusterRoleBindings().Delete(clusterRoleBinding.Name, &metav1.DeleteOptions{}); err != nil {
				fmt.Printf("%v", err)
				return
			}
			o.PrinterDeleted.PrintObj(clusterRoleBinding, o.Out)
		}()
	}

	// create pod
	pod, err := o.Client.CoreV1().Pods(ns.Name).Create(o.newPod(o.NodeName))
	if err != nil {
		return err
	}

	// wait for pod to be running (gather has completed)
	if err := o.waitForPodRunning(pod); err != nil {
		return err
	}

	// copy the gathered files into the local destination dir
	err = o.copyFilesFromPod(pod)
	return err
}
1017772
func RunCommandInDirWithEnvsAndReturnExitCode(envs []string, dir, name string, args ...string) (int, error) {
	cmd := exec.Command(name, args...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if dir != "" {
		cmd.Dir = dir
	}
	if len(envs) > 0 {
		cmd.Env = envs
	}

	return RunCmdAndReturnExitCode(cmd)
}
765246
func Cmd(params base.Parameters) *subcommands.Command {
	return &subcommands.Command{
		UsageLine: "semantic-diff SCRIPT CONFIG [CONFIG CONFIG ...]",
		ShortDesc: "interprets a high-level config, compares the result to existing configs",
		LongDesc: `Interprets a high-level config, compares the result to existing configs.

THIS SUBCOMMAND WILL BE DELETED AFTER IT IS NO LONGER USEFUL. DO NOT DEPEND ON
IT IN ANY AUTOMATIC SCRIPTS. FOR MANUAL USE ONLY. IF YOU REALLY-REALLY NEED TO
USE IT FROM AUTOMATION, PLEASE FILE A BUG.

Uses semantic comparison. Normalizes all protos before comparing them via
'git diff'. Intended to be used manually when switching existing *.cfg to be
generated from *.star.

Accepts a path to the entry-point *.star script and paths to existing configs
to diff against. Their filenames (not full paths) will be used to find
corresponding generated files, and also to figure out the proto schema to use.

Example:

  $ lucicfg semantic-diff main.star configs/cr-buildbucket.cfg configs/luci-milo.cfg
`,
		CommandRun: func() subcommands.CommandRun {
			dr := &diffRun{}
			dr.Init(params)
			dr.AddMetaFlags()
			dr.Flags.StringVar(&dr.outputDir, "output-dir", "", "Where to put normalized configs if you want them preserved after the command completes.")
			return dr
		},
	}
}
643613
func (f *CLI) Run() bool {
	err := f.validate()
	if err != nil {
		os.Stderr.WriteString(err.Error() + "\n")
		os.Exit(1)
	}

	switch {
	case f.install:
		f.prompt()
		err = install.Install(f.Name)
	case f.uninstall:
		f.prompt()
		err = install.Uninstall(f.Name)
	default:
		// non of the action flags matched,
		// returning false should make the real program execute
		return false
	}

	if err != nil {
		fmt.Printf("%s failed! %s\n", f.action(), err)
		os.Exit(3)
	}
	fmt.Println("Done!")
	return true
}