// CmdAndCwd returns the effective command and relative_cwd entries
// from the fetched isolated.
//
// Must be called after the Downloader is completed.
//
// Note that new uses of isolated should NOT use cmd or relative_cwd!
481817
func (d *Downloader) CmdAndCwd() ([]string, string, error) {
	d.mu.Lock()
	finished := d.finished
	d.mu.Unlock()
	if !finished {
		return nil, "", errors.New(
			"can only call CumulativeIsolated on a finished Downloader")
	}

	if d.err != nil {
		return nil, "", d.err
	}

	queue := []*isolated.Isolated{d.isoMap[d.rootHash]}

	for len(queue) > 0 {
		iso := queue[0]

		if len(iso.Command) > 0 {
			return iso.Command, iso.RelativeCwd, nil
		}

		toPrepend := []*isolated.Isolated{}
		for _, inc := range iso.Includes {
			toPrepend = append(toPrepend, d.isoMap[inc])
		}
		queue = append(toPrepend, queue[1:]...)
	}

	return nil, "", nil
}
7379
func RunCmdChecks(cmd *cobra.Command, cmdChecks []CmdCheck, skipCmd []string) []error {
	cmdPath := cmd.CommandPath()

	for _, skipCmdPath := range skipCmd {
		if cmdPath == skipCmdPath {
			fmt.Fprintf(os.Stdout, "---+ skipping command %s\n", cmdPath)
			return []error{}
		}
	}

	errors := []error{}

	if cmd.HasSubCommands() {
		for _, subCmd := range cmd.Commands() {
			errors = append(errors, RunCmdChecks(subCmd, cmdChecks, skipCmd)...)
		}
	}

	fmt.Fprintf(os.Stdout, "---+ RUNNING COMMAND CHECKS on %q\n", cmdPath)

	for _, check := range cmdChecks {
		if err := check(cmd); err != nil && len(err) > 0 {
			errors = append(errors, err...)
		}
	}

	return errors
}
27607
func GetDirtyDB(ctx sessionctx.Context) *DirtyDB {
	var udb *DirtyDB
	x := ctx.GetSessionVars().TxnCtx.DirtyDB
	if x == nil {
		udb = &DirtyDB{tables: make(map[int64]*DirtyTable)}
		ctx.GetSessionVars().TxnCtx.DirtyDB = udb
	} else {
		udb = x.(*DirtyDB)
	}
	return udb
}
491007
func (args MasterArgs) GetEtcdBindAddress() string {
	return net.JoinHostPort(args.ListenArg.ListenAddr.Host, strconv.Itoa(args.EtcdAddr.DefaultPort))
}
1097364
func ExecCmdDir(dir, cmdName string, args ...string) (string, string, error) {
	bufOut, bufErr, err := ExecCmdDirBytes(dir, cmdName, args...)
	return string(bufOut), string(bufErr), err
}
824833
func cmdEnsure(params Parameters) *subcommands.Command {
	return &subcommands.Command{
		UsageLine: "ensure [options]",
		ShortDesc: "installs, removes and updates packages in one go",
		LongDesc: "Installs, removes and updates packages in one go.\n\n" +
			"Supposed to be used from scripts and automation. Alternative to 'init', " +
			"'install' and 'remove'. As such, it doesn't try to discover site root " +
			"directory on its own.",
		CommandRun: func() subcommands.CommandRun {
			c := &ensureRun{}
			c.registerBaseFlags()
			c.clientOptions.registerFlags(&c.Flags, params, withRootDir)
			c.ensureFileOptions.registerFlags(&c.Flags, withEnsureOutFlag, withLegacyListFlag)
			return c
		},
	}
}
529582
func ExecCmdDirBytes(dir, cmdName string, args ...string) ([]byte, []byte, error) {
	bufOut := new(bytes.Buffer)
	bufErr := new(bytes.Buffer)

	cmd := exec.Command(cmdName, args...)
	cmd.Dir = dir
	cmd.Stdout = bufOut
	cmd.Stderr = bufErr

	err := cmd.Run()
	return bufOut.Bytes(), bufErr.Bytes(), err
}
242958
func (cmd *command) serveSink(ch io.ReadWriter) error {
	// Validate that if directory mode flag was sent, the target is an actual
	// directory.
	if cmd.Flags.DirectoryMode {
		if len(cmd.Flags.Target) != 1 {
			return trace.BadParameter("in directory mode, only single upload target is allowed, %v provided", len(cmd.Flags.Target))
		}

		fi, err := os.Stat(cmd.Flags.Target[0])
		if err != nil {
			return trace.Wrap(err)
		}
		if mode := fi.Mode(); !mode.IsDir() {
			return trace.BadParameter("target path must be a directory")
		}
	}

	if err := sendOK(ch); err != nil {
		return trace.Wrap(err)
	}
	var st state
	st.path = []string{"."}
	var b = make([]byte, 1)
	scanner := bufio.NewScanner(ch)
	for {
		n, err := ch.Read(b)
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return trace.Wrap(err)
		}

		if n < 1 {
			return trace.Errorf("unexpected error, read 0 bytes")
		}

		if b[0] == OKByte {
			continue
		}

		scanner.Scan()
		if err := scanner.Err(); err != nil {
			return trace.Wrap(err)
		}
		if err := cmd.processCommand(ch, &st, b[0], scanner.Text()); err != nil {
			return trace.Wrap(err)
		}
		if err := sendOK(ch); err != nil {
			return trace.Wrap(err)
		}
	}
}
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
		},
	}
}
84764
func checkAdminCredsSyntax(ctx *cli.Context) {
	if len(ctx.Args()) != 3 {
		cli.ShowCommandHelpAndExit(ctx, credsCmdName, 1) // last argument is exit code
	}
}
591188
func (mc MongoClient) DBRefToCommand(dbRef mgo.DBRef) (c models.Command, err error) {
	s := mc.session.Copy()
	defer s.Close()

	if err = s.DB(mc.database.Name).C(db.Command).Find(bson.M{"_id": dbRef.Id}).One(&c); err != nil {
		return models.Command{}, errorMap(err)
	}
	return
}
89840
func (k *Kubernetes) ensurePKIRolesEtcd(p *PKIVaultBackend) error {
	var result *multierror.Error

	if err := p.WriteRole(k.etcdClientRole()); err != nil {
		result = multierror.Append(result, err)
	}

	if err := p.WriteRole(k.etcdServerRole()); err != nil {
		result = multierror.Append(result, err)
	}

	return result.ErrorOrNil()
}
7324
func (c *ServicedCli) cmdSetConnTimeout(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) != 2 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "set-conn-timeout")
		return
	}

	connTimeout, err := time.ParseDuration(args[1])
	if err != nil {
		fmt.Fprintf(os.Stderr, "could not parse duration: %s\n", err)
		return
	} else if connTimeout < 0 {
		fmt.Fprintln(os.Stderr, "duration cannot be negative")
		return
	}

	pool, err := c.driver.GetResourcePool(args[0])
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	} else if pool == nil {
		fmt.Fprintln(os.Stderr, "pool not found")
		return
	}

	pool.ConnectionTimeout = int(connTimeout.Seconds() * 1000)
	if err := c.driver.UpdateResourcePool(*pool); err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}
}
1041719
func (fbo *folderBlockOps) GetDirtyDirBlockRefs(
	lState *kbfssync.LockState) []data.BlockRef {
	fbo.blockLock.RLock(lState)
	defer fbo.blockLock.RUnlock(lState)
	var dirtyRefs []data.BlockRef
	for ptr := range fbo.dirtyDirs {
		dirtyRefs = append(dirtyRefs, ptr.Ref())
	}
	return dirtyRefs
}
279294
func (c *ServicedCli) cmdServiceAdd(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 3 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "add")
		c.exit(1)
		return
	}

	var (
		parentService *service.ServiceDetails
		err           error
	)
	if parentServiceID := ctx.String("parent-id"); parentServiceID == "" {
		fmt.Fprintln(os.Stderr, "Must specify a parent service ID")
		c.exit(1)
		return
	} else if parentService, _, err = c.searchForService(parentServiceID, ctx.Bool("no-prefix-match")); err != nil {
		fmt.Fprintf(os.Stderr, "Error searching for parent service: %s", err)
		c.exit(1)
		return
	}

	cfg := api.ServiceConfig{
		Name:            args[0],
		ImageID:         args[1],
		Command:         args[2],
		ParentServiceID: parentService.ID,
		LocalPorts:      ctx.Generic("p").(*api.PortMap),
		RemotePorts:     ctx.Generic("q").(*api.PortMap),
	}

	if service, err := c.driver.AddService(cfg); err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
	} else if service == nil {
		fmt.Fprintln(os.Stderr, "received nil service definition")
		c.exit(1)
	} else {
		fmt.Println(service.ID)
	}
	return
}
1046823
func cmdBuild() *subcommands.Command {
	return &subcommands.Command{
		Advanced:  true,
		UsageLine: "pkg-build [options]",
		ShortDesc: "builds a package instance file",
		LongDesc:  "Builds a package instance producing *.cipd file.",
		CommandRun: func() subcommands.CommandRun {
			c := &buildRun{}
			c.registerBaseFlags()
			c.inputOptions.registerFlags(&c.Flags)
			c.hashOptions.registerFlags(&c.Flags)
			c.Flags.StringVar(&c.outputFile, "out", "<path>", "Path to a file to write the final package to.")
			return c
		},
	}
}
34810
func RunCmdAndReturnTrimmedCombinedOutput(cmd *exec.Cmd) (string, error) {
	outBytes, err := cmd.CombinedOutput()
	outStr := string(outBytes)
	return strings.TrimSpace(outStr), err
}