// run generates assets.gen.go file with all assets discovered in the directory.
321133
func run(dir string, extraExts []string) error {
	exts := defaultExts.Union(stringset.NewFromSlice(extraExts...)).ToSlice()
	sort.Strings(exts)

	pkg, err := build.ImportDir(dir, build.ImportComment)
	if err != nil {
		return fmt.Errorf("can't import dir %q - %s", dir, err)
	}

	assets, err := findAssets(pkg.Dir, exts)
	if err != nil {
		return fmt.Errorf("can't find assets in %s - %s", pkg.Dir, err)
	}

	err = generate(assetsGenGoTmpl, pkg, assets, exts, filepath.Join(pkg.Dir, "assets.gen.go"))
	if err != nil {
		return fmt.Errorf("can't generate assets.gen.go - %s", err)
	}

	err = generate(assetsTestTmpl, pkg, assets, exts, filepath.Join(pkg.Dir, "assets_test.go"))
	if err != nil {
		return fmt.Errorf("can't generate assets_test.go - %s", err)
	}

	return nil
}
50319
func (c *CmdGitMddel) Run() error {
	cli, err := GetGitClient(c.G())
	if err != nil {
		return err
	}

	folder, err := ParseTLF(c.folder)
	if err != nil {
		return err
	}

	return cli.DeleteGitMetadata(context.Background(), keybase1.DeleteGitMetadataArg{
		Folder:   folder,
		RepoName: keybase1.GitRepoName(c.repoName),
	})
}
677192
func (fsf *FindSegmentsFile) run(commit IndexCommit) (interface{}, error) {
	// fmt.Println("Finding segments file...")
	if commit != nil {
		if fsf.directory != commit.Directory() {
			return nil, errors.New("the specified commit does not match the specified Directory")
		}
		return fsf.doBody(commit.SegmentsFileName())
	}

	lastGen := int64(-1)
	gen := int64(0)
	genLookaheadCount := 0
	var exc error
	retryCount := 0

	useFirstMethod := true

	// Loop until we succeed in calling doBody() without
	// hitting an IOException.  An IOException most likely
	// means a commit was in process and has finished, in
	// the time it took us to load the now-old infos files
	// (and segments files).  It's also possible it's a
	// true error (corrupt index).  To distinguish these,
	// on each retry we must see "forward progress" on
	// which generation we are trying to load.  If we
	// don't, then the original error is real and we throw
	// it.

	// We have three methods for determining the current
	// generation.  We try the first two in parallel (when
	// useFirstMethod is true), and fall back to the third
	// when necessary.

	for {
		// fmt.Println("Trying...")
		if useFirstMethod {
			// fmt.Println("Trying first method...")
			// List the directory and use the highest
			// segments_N file.  This method works well as long
			// as there is no stale caching on the directory
			// contents (NOTE: NFS clients often have such stale
			// caching):
			genA := int64(-1)

			files, err := fsf.directory.ListAll()
			if err != nil {
				return nil, err
			}
			if files != nil {
				genA = LastCommitGeneration(files)
			}

			// message("directory listing genA=%v", genA)

			// Also open segments.gen and read its
			// contents.  Then we take the larger of the two
			// gens.  This way, if either approach is hitting
			// a stale cache (NFS) we have a better chance of
			// getting the right generation.
			genB := int64(-1)
			genInput, err := fsf.directory.OpenChecksumInput(INDEX_FILENAME_SEGMENTS_GEN, store.IO_CONTEXT_READ)
			if err != nil {
				message("segments.gen open: %v", err)
			} else {
				defer genInput.Close()
				// fmt.Println("Reading segments info...")

				var version int32
				if version, err = genInput.ReadInt(); err != nil {
					return nil, err
				}
				// fmt.Printf("Version: %v\n", version)
				if version == FORMAT_SEGMENTS_GEN_47 || version == FORMAT_SEGMENTS_GEN_CURRENT {
					// fmt.Println("Version is current.")
					var gen0, gen1 int64
					if gen0, err = genInput.ReadLong(); err != nil {
						return nil, err
					}
					if gen1, err = genInput.ReadLong(); err != nil {
						return nil, err
					}
					message("fallback check: %v; %v", gen0, gen1)
					if version == FORMAT_SEGMENTS_GEN_CHECKSUM {
						if _, err = codec.CheckFooter(genInput); err != nil {
							return nil, err
						}
					} else {
						if err = codec.CheckEOF(genInput); err != nil {
							return nil, err
						}
					}
					if gen0 == gen1 {
						// The file is consistent.
						genB = gen0
					}
				} else {
					return nil, codec.NewIndexFormatTooNewError(genInput, version,
						FORMAT_SEGMENTS_GEN_CURRENT, FORMAT_SEGMENTS_GEN_CURRENT)
				}
			}

			message("%v check: genB=%v", INDEX_FILENAME_SEGMENTS_GEN, genB)

			// Pick the larger of the two gen's:
			gen = genA
			if genB > gen {
				gen = genB
			}

			if gen == -1 {
				// Neither approach found a generation
				return nil, errors.New(fmt.Sprintf("no segments* file found in %v: files: %#v", fsf.directory, files))
			}
		}

		if useFirstMethod && lastGen == gen && retryCount >= 2 {
			// Give up on first method -- this is 3rd cycle on
			// listing directory and checking gen file to
			// attempt to locate the segments file.
			useFirstMethod = false
		}

		// Second method: since both directory cache and
		// file contents cache seem to be stale, just
		// advance the generation.
		if !useFirstMethod {
			if genLookaheadCount < fsf.defaultGenLookaheadCount {
				gen++
				genLookaheadCount++
				message("look ahead increment gen to %v", gen)
			} else {
				// All attempts have failed -- throw first exc:
				return nil, exc
			}
		} else if lastGen == gen {
			// This means we're about to try the same
			// segments_N last tried.
			retryCount++
		} else {
			// Segment file has advanced since our last loop
			// (we made "progress"), so reset retryCount:
			retryCount = 0
		}

		lastGen = gen
		segmentFileName := util.FileNameFromGeneration(INDEX_FILENAME_SEGMENTS, "", gen)
		// fmt.Printf("SegmentFileName: %v\n", segmentFileName)

		var v interface{}
		var err error
		if v, err = fsf.doBody(segmentFileName); err == nil {
			message("success on %v", segmentFileName)
			return v, nil
		}
		// Save the original root cause:
		if exc == nil {
			exc = err
		}

		message("primary Exception on '%v': %v; will retry: retryCount = %v; gen = %v",
			segmentFileName, err, retryCount, gen)

		if gen > 1 && useFirstMethod && retryCount == 1 {
			// This is our second time trying this same segments
			// file (because retryCount is 1), and, there is
			// possibly a segments_(N-1) (because gen > 1).
			// So, check if the segments_(N-1) exists and
			// try it if so:
			prevSegmentFileName := util.FileNameFromGeneration(INDEX_FILENAME_SEGMENTS, "", gen-1)

			if prevExists := fsf.directory.FileExists(prevSegmentFileName); prevExists {
				message("fallback to prior segment file '%v'", prevSegmentFileName)
				if v, err = fsf.doBody(prevSegmentFileName); err != nil {
					message("secondary Exception on '%v': %v; will retry", prevSegmentFileName, err)
				} else {
					message("success on fallback %v", prevSegmentFileName)
					return v, nil
				}
			}
		}
	}
}
1068337
func (u *DropsondeUnmarshallerCollection) Run(inputChan <-chan []byte, outputChan chan<- *events.Envelope, waitGroup *sync.WaitGroup) {
	for _, unmarshaller := range u.unmarshallers {
		go func(um *DropsondeUnmarshaller) {
			defer waitGroup.Done()
			um.Run(inputChan, outputChan)
		}(unmarshaller)
	}
}
627051
func (g *getCmd) run() error {
	res, err := g.client.ReleaseContent(g.release, helm.ContentReleaseVersion(g.version))
	if err != nil {
		return prettyError(err)
	}
	return printRelease(g.out, res.Release)
}
487297
func (s *StepOutputDir) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	ui := state.Get("ui").(packer.Ui)

	if _, err := os.Stat(s.Path); err == nil && s.Force {
		ui.Say("Deleting previous output directory...")
		os.RemoveAll(s.Path)
	}

	// Create the directory
	if err := os.MkdirAll(s.Path, 0755); err != nil {
		state.Put("error", err)
		return multistep.ActionHalt
	}

	// Make sure we can write in the directory
	f, err := os.Create(filepath.Join(s.Path, "_packer_perm_check"))
	if err != nil {
		err = fmt.Errorf("Couldn't write to output directory: %s", err)
		state.Put("error", err)
		return multistep.ActionHalt
	}
	f.Close()
	os.Remove(f.Name())

	s.success = true
	return multistep.ActionContinue
}
597361
func (d *StaticDiscovery) Run(looper director.Looper) {
	var err error

	d.Targets, err = d.ParseConfig(d.ConfigFile)
	if err != nil {
		log.Errorf("StaticDiscovery cannot parse: %s", err.Error())
		looper.Done(nil)
	}
}
676375
func (e *DeviceKeygen) Run(m libkb.MetaContext) (err error) {
	defer m.Trace("DeviceKeygen#Run", func() error { return err })()

	e.setup(m)
	e.generate(m)
	e.localSave(m)
	return e.runErr
}
941062
func (t *Typescript) Run(logger func(format string, a ...interface{})) {
	c := t.Config
	if c.Tsconfig == nil {
		tsC := DefaultTsconfig()
		c.Tsconfig = &tsC
	}

	if c.Dir == "" {
		c.Tsconfig.CompilerOptions.OutDir = c.Dir
	}

	if c.Dir == "" {
		c.Dir = "./"
	}

	if !strings.Contains(c.Ignore, nodeModules) {
		c.Ignore += "," + nodeModules
	}

	if logger == nil {
		logger = NoOpLogger
	}

	t.log = logger

	t.start()
}
757721
func (r *Runc) Run(context context.Context, id, bundle string, opts *CreateOpts) (int, error) {
	args := []string{"run", "--bundle", bundle}
	if opts != nil {
		oargs, err := opts.args()
		if err != nil {
			return -1, err
		}
		args = append(args, oargs...)
	}
	cmd := r.command(context, append(args, id)...)
	if opts != nil && opts.IO != nil {
		opts.Set(cmd)
	}
	ec, err := Monitor.Start(cmd)
	if err != nil {
		return -1, err
	}
	return Monitor.Wait(cmd, ec)
}
864809
func (p *Project) run(path string, stream chan Response, stop <-chan bool) (err error) {
	var args []string
	var build *exec.Cmd
	var r Response
	defer func() {
		// https://github.com/golang/go/issues/5615
		// https://github.com/golang/go/issues/6720
		if build != nil {
			build.Process.Signal(os.Interrupt)
			build.Process.Wait()
		}
	}()

	// custom error pattern
	isErrorText := func(string) bool {
		return false
	}
	errRegexp, err := regexp.Compile(p.ErrPattern)
	if err != nil {
		r.Err = err
		stream <- r
	} else {
		isErrorText = errRegexp.MatchString
	}

	// add additional arguments
	for _, arg := range p.Args {
		a := strings.FieldsFunc(arg, func(i rune) bool {
			return i == '"' || i == '=' || i == '\''
		})
		args = append(args, a...)
	}
	dirPath := os.Getenv("GOBIN")
	if p.Tools.Run.Path != "" {
		dirPath, _ = filepath.Abs(p.Tools.Run.Path)
	}
	name := filepath.Base(path)
	if path == "." && p.Tools.Run.Path == "" {
		name = filepath.Base(Wdir())
	} else if p.Tools.Run.Path != "" {
		name = filepath.Base(dirPath)
	}
	path = filepath.Join(dirPath, name)
	if p.Tools.Run.Method != "" {
		path = p.Tools.Run.Method
	}
	if _, err := os.Stat(path); err == nil {
		build = exec.Command(path, args...)
	} else if _, err := os.Stat(path + RExtWin); err == nil {
		build = exec.Command(path+RExtWin, args...)
	} else {
		if _, err = os.Stat(path); err == nil {
			build = exec.Command(path, args...)
		} else if _, err = os.Stat(path + RExtWin); err == nil {
			build = exec.Command(path+RExtWin, args...)
		} else {
			return errors.New("project not found")
		}
	}
	appendEnvs := p.buildEnvs()
	if len(appendEnvs) > 0 {
		build.Env = append(build.Env, appendEnvs...)
	}
	// scan project stream
	stdout, err := build.StdoutPipe()
	stderr, err := build.StderrPipe()
	if err != nil {
		return err
	}
	if p.Tools.Run.Dir != "" {
		build.Dir = p.Tools.Run.Dir
	}
	if err := build.Start(); err != nil {
		return err
	}
	execOutput, execError := bufio.NewScanner(stdout), bufio.NewScanner(stderr)
	stopOutput, stopError := make(chan bool, 1), make(chan bool, 1)
	scanner := func(stop chan bool, output *bufio.Scanner, isError bool) {
		for output.Scan() {
			text := output.Text()
			if isError && !isErrorText(text) {
				r.Err = errors.New(text)
				stream <- r
				r.Err = nil
			} else {
				r.Out = text
				stream <- r
				r.Out = ""
			}
		}
		close(stop)
	}
	go scanner(stopOutput, execOutput, false)
	go scanner(stopError, execError, true)
	for {
		select {
		case <-stop:
			return
		case <-stopOutput:
			return
		case <-stopError:
			return
		}
	}
}
942981
func (c *ImageStreamController) Run(workers int, stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()
	defer c.queue.ShutDown()

	klog.Infof("Starting image stream controller")

	// Wait for the stream store to sync before starting any work in this controller.
	if !cache.WaitForCacheSync(stopCh, c.listerSynced) {
		utilruntime.HandleError(fmt.Errorf("timed out waiting for caches to sync"))
		return
	}

	for i := 0; i < workers; i++ {
		go wait.Until(c.worker, time.Second, stopCh)
	}

	metrics.InitializeImportCollector(false, c.importCounter.Collect)

	<-stopCh
	klog.Infof("Shutting down image stream controller")
}
886542
func (g *Generator) Run(rootPath string, data Data) error {
	// defer g.fmt(rootPath)
	dd := Data{}
	for k, v := range data {
		dd[k] = v
	}
	for k, v := range g.Data {
		dd[k] = v
	}
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	return chdir(rootPath, func() error {
		if g.Should != nil {
			b := g.Should(dd)
			if !b {
				return nil
			}
		}
		err := os.MkdirAll(rootPath, 0755)
		if err != nil {
			return errors.WithStack(err)
		}
		err = os.Chdir(rootPath)
		if err != nil {
			return errors.WithStack(err)
		}
		for _, r := range g.Runners {
			select {
			case <-ctx.Done():
				break
			default:
				err := r.Run(rootPath, dd)
				if err != nil {
					return errors.WithStack(err)
				}
			}
		}
		return nil
	})
}
893644
func (c *bundleDiffCommand) Run(ctx *cmd.Context) error {
	apiRoot, err := c.newAPIRoot()
	if err != nil {
		return errors.Trace(err)
	}
	defer apiRoot.Close()

	// Load up the bundle data, with includes and overlays.
	bundle, bundleDir, err := c.readBundle(ctx)
	if err != nil {
		return errors.Trace(err)
	}
	if err := composeBundle(bundle, ctx, bundleDir, c.bundleOverlays); err != nil {
		return errors.Trace(err)
	}
	if err := verifyBundle(bundle, bundleDir); err != nil {
		return errors.Trace(err)
	}

	// Extract the information from the current model.
	model, err := c.readModel(apiRoot)
	if err != nil {
		return errors.Trace(err)
	}
	// Get the differences between them.
	diff, err := bundlechanges.BuildDiff(bundlechanges.DiffConfig{
		Bundle:             bundle,
		Model:              model,
		Logger:             logger,
		IncludeAnnotations: c.annotations,
	})

	if err != nil {
		return errors.Trace(err)
	}

	encoder := yaml.NewEncoder(ctx.Stdout)
	defer encoder.Close()
	err = encoder.Encode(diff)
	if err != nil {
		return errors.Trace(err)
	}
	return nil
}
461003
func (cmd *GenerateConfigCommand) Run(_ context.Context) error {
	conf := server.NewConfig()
	ret, err := toml.Marshal(*conf)
	if err != nil {
		return errors.Wrap(err, "unmarshalling default config")
	}
	fmt.Fprintf(cmd.Stdout, "%s\n", ret)
	return nil
}
1288205
func (r *Runner) Run(p *Params) {
	for fileName := range r.start {

		color.Green("Running %s...\n", p.Get("run"))

		cmd, err := runCommand(fileName, p.Package...)
		if err != nil {
			log.Printf("Could not run the go binary: %s \n", err)
			r.kill(cmd)

			continue
		}

		r.cmd = cmd
		removeFile(fileName)

		go func(cmd *exec.Cmd) {
			if err := cmd.Wait(); err != nil {
				log.Printf("process interrupted: %s \n", err)
				r.kill(cmd)
			}
		}(r.cmd)
	}
}
809568
func (c *exportBundleCommand) Run(ctx *cmd.Context) error {
	client, err := c.newAPIFunc()
	if err != nil {
		return err
	}
	defer client.Close()

	result, err := client.ExportBundle()
	if err != nil {
		return err
	}

	if c.Filename == "" {
		_, err := fmt.Fprintf(ctx.Stdout, "%v", result)
		return err
	}
	filename := c.Filename
	file, err := os.Create(filename)
	if err != nil {
		return errors.Annotate(err, "while creating local file")
	}
	defer file.Close()

	_, err = file.WriteString(result)
	if err != nil {
		return errors.Annotate(err, "while copying in local file")
	}

	fmt.Fprintln(ctx.Stdout, "Bundle successfully exported to", filename)

	return nil
}