Example #1
2
func (s *Source) extract() (err error) {
	var cmd *exec.Cmd

	if strings.HasSuffix(s.Path, ".tar") {
		cmd = exec.Command("tar", "--no-same-owner", "-xf", s.Path)
	} else if strings.HasSuffix(s.Path, ".zip") {
		cmd = exec.Command("unzip", s.Path)
	} else {
		split := strings.Split(s.Path, ".")
		if len(split) > 2 && split[len(split)-2] == "tar" {
			cmd = exec.Command("tar", "--no-same-owner", "-xf", s.Path)
		} else {
			return
		}
	}

	cmd.Dir = s.Output
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	err = cmd.Run()
	if err != nil {
		err = &GetError{
			errors.Wrapf(err, "builder: Failed to extract source '%s'",
				s.Source),
		}
		return
	}

	return
}
func cleanup(directory string) {
	temp, err := ioutil.TempDir("", "")
	isError(err, "")
	files, err := ioutil.ReadDir(directory)
	isError(err, "")
	if 1 == len(files) {
		folder := filepath.Join(directory, files[0].Name())
		// Move to a tmp directory
		files, err = ioutil.ReadDir(folder)
		isError(err, "")
		for _, file := range files {
			var cmd *exec.Cmd
			cmd = exec.Command("mv", file.Name(), temp)
			cmd.Dir = folder
			output, err := cmd.CombinedOutput()
			isError(err, string(output))
		}
		err = os.RemoveAll(folder)
		isError(err, "")
		// move to the directory
		files, err = ioutil.ReadDir(temp)
		isError(err, "")
		for _, file := range files {
			var cmd *exec.Cmd
			cmd = exec.Command("mv", file.Name(), directory)
			cmd.Dir = temp
			output, err := cmd.CombinedOutput()
			isError(err, string(output))
		}
	}
}
Example #3
0
func (r *AgRecipe) Build(ctx *types.BuildContext) error {
	log.Info("Building the_silver_searcher")
	srcdir := r.UnpackedDir(ctx, r.Info())

	var cmd *exec.Cmd

	// Run autotools
	cmd = exec.Command("autoreconf", "-i")
	cmd.Dir = srcdir
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		log.WithField("err", err).Error("Could not run autotools")
		return err
	}

	log.Infof("Running ./configure")
	cmd = exec.Command(
		"./configure",
		"--host="+ctx.CrossPrefix,
		"--build=i686",
		"PKG_CONFIG=/bin/true",
	)
	cmd.Dir = srcdir
	cmd.Env = ctx.Env.
		Append("CC", ctx.StaticFlags).
		Set("CFLAGS", "-fPIC "+ctx.StaticFlags).
		Set("PCRE_LIBS", ctx.DependencyEnv["pcre"]["LDFLAGS"]).
		Set("PCRE_CFLAGS", ctx.DependencyEnv["pcre"]["CFLAGS"]).
		Set("LZMA_LIBS", ctx.DependencyEnv["lzma"]["LDFLAGS"]).
		Set("LZMA_CFLAGS", ctx.DependencyEnv["lzma"]["CFLAGS"]).
		Set("ZLIB_LIBS", ctx.DependencyEnv["zlib"]["LDFLAGS"]).
		Set("ZLIB_CFLAGS", ctx.DependencyEnv["zlib"]["CFLAGS"]).
		AsSlice()
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stdout

	if err := cmd.Run(); err != nil {
		log.WithField("err", err).Error("Could not run configure")
		return err
	}

	cmd = exec.Command("make")
	cmd.Dir = srcdir
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stdout

	if err := cmd.Run(); err != nil {
		log.WithField("err", err).Error("Could not run make")
		return err
	}

	log.Info("Finished building the_silver_searcher")
	return nil
}
Example #4
0
func (r *PvRecipe) Build(ctx *types.BuildContext) error {
	log.Info("Building pv")
	srcdir := r.UnpackedDir(ctx, r.Info())

	var cmd *exec.Cmd

	// 1. Configure
	log.Infof("Running ./configure")
	cmd = exec.Command(
		"./configure",
		"--host="+ctx.CrossPrefix,
		"--build=i686",
	)
	cmd.Dir = srcdir
	cmd.Env = ctx.Env.
		Append("CC", ctx.StaticFlags).
		Set("CFLAGS", ctx.StaticFlags).
		AsSlice()
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stdout

	if err := cmd.Run(); err != nil {
		log.WithField("err", err).Error("Could not run configure")
		return err
	}

	// 2. Fix linker in Makefile
	cmd = exec.Command(
		"sed",
		"-i",
		fmt.Sprintf("/^CC =/a LD = %s", ctx.Env.Get("LD")),
		filepath.Join(srcdir, "Makefile"),
	)
	if err := cmd.Run(); err != nil {
		log.WithField("err", err).Error("Could not patch Makefile")
		return err
	}

	// 3. Run build
	cmd = exec.Command("make")
	cmd.Dir = srcdir
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stdout

	if err := cmd.Run(); err != nil {
		log.WithField("err", err).Error("Could not run make")
		return err
	}

	log.Info("Finished building pv")
	return nil
}
Example #5
0
func TestDoAll_cached_sample(t *testing.T) {
	cleanup("go-cache")

	var gitCmd *exec.Cmd
	var srcCmd *exec.Cmd
	gitCmd = exec.Command("git", "checkout", "071610bf3a597bc41aae05e27c5407444b7ea0d1")
	gitCmd.Dir = filepath.Join(testdataPath, "go-cached")
	if o, err := gitCmd.CombinedOutput(); err != nil {
		t.Fatal(string(o), err)
	}
	srcCmd = exec.Command("src", "do-all")
	srcCmd.Dir = filepath.Join(testdataPath, "go-cached")
	srcCmd.Env = append([]string{"SRCLIBPATH=" + srclibPath}, os.Environ()...)
	if o, err := srcCmd.CombinedOutput(); err != nil {
		t.Fatal(string(o), err)
	}
	gitCmd = exec.Command("git", "checkout", "34dd0f240fe12cdd8c9c6e24620cc0013518a55e")
	gitCmd.Dir = filepath.Join(testdataPath, "go-cached")
	if o, err := gitCmd.CombinedOutput(); err != nil {
		t.Fatal(string(o), err)
	}
	srcCmd = exec.Command("src", "do-all")
	srcCmd.Dir = filepath.Join(testdataPath, "go-cached")
	srcCmd.Env = append([]string{"SRCLIBPATH=" + srclibPath}, os.Environ()...)
	if o, err := srcCmd.CombinedOutput(); err != nil {
		t.Fatal(string(o), err)
	}
	firstOne, err := ioutil.ReadFile(filepath.Join(testdataPath, "go-cached", buildstore.BuildDataDirName, "071610bf3a597bc41aae05e27c5407444b7ea0d1", "one", "sample.graph.json"))
	if err != nil {
		t.Fatal(err)
	}
	secondOne, err := ioutil.ReadFile(filepath.Join(testdataPath, "go-cached", buildstore.BuildDataDirName, "34dd0f240fe12cdd8c9c6e24620cc0013518a55e", "one", "sample.graph.json"))
	if err != nil {
		t.Fatal(err)
	}
	if string(firstOne) != string(secondOne) {
		t.Error("Source unit \"one\" should have been cached: string(firstOne) != string(secondOne)")
	}
	firstTwo, err := ioutil.ReadFile(filepath.Join(testdataPath, "go-cached", buildstore.BuildDataDirName, "071610bf3a597bc41aae05e27c5407444b7ea0d1", "two", "sample.graph.json"))
	if err != nil {
		t.Fatal(err)
	}
	secondTwo, err := ioutil.ReadFile(filepath.Join(testdataPath, "go-cached", buildstore.BuildDataDirName, "34dd0f240fe12cdd8c9c6e24620cc0013518a55e", "two", "sample.graph.json"))
	if err != nil {
		t.Fatal(err)
	}
	if string(firstTwo) == string(secondTwo) {
		t.Error("Source unit \"two\" should not be cached: string(firstTwo) == string(secondTwo)")
	}
	cleanup("go-cache")
}
Example #6
0
func runGet(cmd *Command, args []string) {
	if len(args) == 0 {
		args = []string{"."}
	}

	err := command("go", "get", "-d", args).Run()
	if err != nil {
		log.Fatalln(err)
	}

	// group import paths by Godeps location
	groups := make(map[string][]string)
	for _, pkg := range MustLoadPackages(args...) {
		if pkg.Error.Err != "" {
			log.Fatalln(pkg.Error.Err)
		}
		dir, _ := findInParents(pkg.Dir, "Godeps")
		groups[dir] = append(groups[dir], pkg.ImportPath)
	}
	for dir, packages := range groups {
		var c *exec.Cmd
		if dir == "" {
			c = command("go", "install", packages)
		} else {
			c = command("godep", "go", "install", packages)
			c.Dir = dir
		}
		if err := c.Run(); err != nil {
			log.Fatalln(err)
		}
	}
}
Example #7
0
// getRevisionFromPath takes a path like /home/csparr/go/src/github.com/sparrc/gdm
// and the VCS Repository information and returns the currently checked out
// revision, ie, 759e96ebaffb01c3cba0e8b129ef29f56507b323
func getRevisionFromPath(fullpath string, root *vcs.RepoRoot) string {
	// Check that we have the executable available
	_, err := exec.LookPath(root.VCS.Cmd)
	if err != nil {
		fmt.Fprintf(os.Stderr, "gdm missing %s command.\n", root.VCS.Name)
		os.Exit(1)
	}

	// Determine command to get the current hash
	var cmd *exec.Cmd
	switch root.VCS.Cmd {
	case "git":
		cmd = exec.Command("git", "rev-parse", "HEAD")
	case "hg":
		cmd = exec.Command("hg", "id", "-i")
	case "bzr":
		cmd = exec.Command("bzr", "revno")
	default:
		fmt.Fprintf(os.Stderr, "gdm does not support %s\n", root.VCS.Cmd)
		os.Exit(1)
	}
	cmd.Dir = fullpath

	output, err := cmd.Output()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error getting revision hash at %s, %s\n",
			fullpath, err.Error())
		os.Exit(1)
	}
	return strings.TrimSpace(string(output))
}
Example #8
0
// Log returns an array of Commit objects, representing the history as like
// git log. Newest commit is at index zero, oldest at the end. Leave hashish
// as a blank string to get the default "git log" result.
func Log(path, hashish string) ([]*Commit, error) {
	logFormat := "%H" // Just the hashes
	var cmd *exec.Cmd

	if hashish == "" {
		cmd = command("git", "log", "--pretty="+logFormat)
	} else {
		cmd = command("git", "log", "--pretty="+logFormat, hashish)
	}
	cmd.Dir = path
	output, err := cmd.Output()
	if err != nil {
		return []*Commit{}, err
	}

	lineBytes := bytes.Split(output, []byte{'\n'})
	// The last split is just an empty string, right?
	lineBytes = lineBytes[0 : len(lineBytes)-1]
	commits := make([]*Commit, len(lineBytes))

	for x := 0; x < len(lineBytes); x++ {
		commit, commitErr := NewCommit(path, string(lineBytes[x]))
		if commitErr != nil {
			return []*Commit{}, commitErr
		}
		commits[x] = commit
	}

	return commits, nil
}
Example #9
0
func execute(path string, vcs string, vcs_verb string) {
	if vcs_verb == "" {
		return
	}
	a := func(wd string, vcs string, vcs_verb string, seq bool) {
		msg := "=== @{!" + vcs_color[vcs] + "} "
		msg += filepath.Base(path)
		msg += "@| (@!" + vcs + "@|) ==="
		var cmd exec.Cmd
		cmd.Dir = wd
		cmd.Args = strings.Split(vcs_verb, " ")
		path, err := exec.LookPath(cmd.Args[0])
		if err != nil {
			path = cmd.Args[0]
		}
		cmd.Path = path
		out, err := cmd.CombinedOutput()
		if err != nil {
			br := color.Colorize("!r")
			rst := color.Colorize("|")
			fmt.Printf(color.Sprint(msg)+"\n%s\n%s%s%s\n\n", out, br, err, rst)
		} else {
			fmt.Printf(color.Sprint(msg)+"\n%s\n", out)
		}
		if !seq {
			quit <- 0
		}
	}
	if *sequential {
		a(path, vcs, vcs_verb, *sequential)
	} else {
		count += 1
		go a(path, vcs, vcs_verb, *sequential)
	}
}
Example #10
0
func updateLocalRepo(url, dir string) (bool, error) {
	var cmd *exec.Cmd

	_, err := os.Stat(dir)
	if os.IsNotExist(err) {
		cmd = exec.Command("git", "clone", url, dir)
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		return true, cmd.Run()
	} else {
		cmd = exec.Command("git", "pull", url)
		cmd.Dir = dir

		out, err := cmd.CombinedOutput()
		if err != nil {
			return false, err
		}

		res := string(out)
		fmt.Fprint(os.Stderr, res)

		updated := true
		if strings.Contains(res, "Already up-to-date.") {
			updated = false
		}

		return updated, nil
	}
}
Example #11
0
func fetchFullNDK() error {
	url := "https://dl.google.com/android/ndk/android-" + ndkVersion + "-" + goos + "-" + ndkarch + "."
	if goos == "windows" {
		url += "exe"
	} else {
		url += "bin"
	}
	archive, err := fetch(url)
	if err != nil {
		return err
	}

	// The self-extracting ndk dist file for Windows terminates
	// with an error (error code 2 - corrupted or incomplete file)
	// but there are no details on what caused this.
	//
	// Strangely, if the file is launched from file browser or
	// unzipped with 7z.exe no error is reported.
	//
	// In general we use the stripped NDK, so this code path
	// is not used, and 7z.exe is not a normal dependency.
	var inflate *exec.Cmd
	if goos != "windows" {
		// The downloaded archive is executed on linux and os x to unarchive.
		// To do this execute permissions are needed.
		os.Chmod(archive, 0755)

		inflate = exec.Command(archive)
	} else {
		inflate = exec.Command("7z.exe", "x", archive)
	}
	inflate.Dir = tmpdir
	return runCmd(inflate)
}
Example #12
0
func RunWithEnvAndWd(command string, args []string, env []string, wd string) (proc *exec.Cmd, err error) {
	//log.Println(command, args)
	//hho := exec.PassThrough
	args = prepend(args, command)
	env = mergeEnv(os.Environ(), env)

	binpath, err := findCmd(findEnv(env, "PATH"), command)
	if err != nil {
		return nil, err
	}

	cmd := new(exec.Cmd)
	cmd.Path = binpath
	cmd.Args = args
	cmd.Env = env
	cmd.Dir = wd
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stdout

	err = cmd.Start()
	if err != nil {
		log.Print("Error running command ", command, ": ", err, "\n")
		return nil, err
	}
	return cmd, nil
}
Example #13
0
func GetDiff(repoPath, commitid string) (*Diff, error) {
	repo, err := git.OpenRepository(repoPath)
	if err != nil {
		return nil, err
	}

	commit, err := repo.GetCommit(commitid)
	if err != nil {
		return nil, err
	}

	rd, wr := io.Pipe()
	var cmd *exec.Cmd
	// First commit of repository.
	if commit.ParentCount() == 0 {
		cmd = exec.Command("git", "show", commitid)
	} else {
		c, _ := commit.Parent(0)
		cmd = exec.Command("git", "diff", c.Id.String(), commitid)
	}
	cmd.Dir = repoPath
	cmd.Stdout = wr
	cmd.Stdin = os.Stdin
	cmd.Stderr = os.Stderr
	go func() {
		cmd.Run()
		wr.Close()
	}()
	defer rd.Close()
	return ParsePatch(cmd, rd)
}
Example #14
0
func (project *Project) build(runIT bool, debug bool) (int, error) {
	app, err := exec.LookPath("mvn")
	var cmd *exec.Cmd
	if runIT {
		cmd = exec.Command(app, "clean", "install", "-Pintegration-tests")
	} else {
		cmd = exec.Command(app, "clean", "install")
	}

	path := strings.Replace(project.FullPath, "pom.xml", "", 1)
	cmd.Dir = path
	stdout, err := cmd.StdoutPipe()
	check(err)

	err = cmd.Start()
	check(err)

	in := bufio.NewScanner(stdout)

	for in.Scan() {
		if debug {
			log.Printf(in.Text())
		}
	}

	err = cmd.Wait()
	if err != nil {
		log.Println(err)
		return 1, err
	}
	return 0, nil
}
Example #15
0
//复杂命令 管道操作等
func ComplexCommand(command string, dir string) string {
	if dir == "" {
		dir = "/root/"
	}
	command = strings.TrimSpace(command)
	if command == "" {
		log.Println("lost command")
	}
	parts := strings.Fields(command)
	var cmd *exec.Cmd
	if len(parts) == 1 {
		cmd = exec.Command(command)
	} else {
		cmd = exec.Command("/bin/bash", "-c", command)
	}
	cmd.Dir = dir
	cmd.Env = []string{
		"SHELL=/bin/bash",
		"PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/go/bin:/root/bin",
		"LC_ALL=en_US.UTF-8",
	}
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	checkErr(err)
	//fmt.Println(out.String())
	return out.String()
}
Example #16
0
//执行指定命令,简单命令,不包含管道操作、&&等
func SpecifiedCommand(command string, dir string) string {
	if dir == "" {
		dir = "/root/"
	}
	command = strings.TrimSpace(command)
	if command == "" {
		log.Println("lost command")
	}
	parts := strings.Fields(command)
	var cmd *exec.Cmd
	if len(parts) == 1 {
		cmd = exec.Command(command)
	} else {
		commandFile := parts[0]
		parts = parts[1:len(parts)]
		commandSlice := []string{}
		for _, param := range parts {
			commandSlice = append(commandSlice, param)
		}
		cmd = exec.Command(commandFile, commandSlice...)
		///usr/bin/wc -l /root/goproject/svntest/test/1.txt
		//cmd = exec.Command("/usr/bin/wc", "-l", "/root/goproject/svntest/test/1.txt")
	}
	cmd.Dir = dir
	env := "/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/go/bin:/root/bin"
	cmd.Env = strings.Split(env, ":")
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	checkErr(err)
	//fmt.Println(out.String())
	return out.String()
}
Example #17
0
func Md5sumCheck(runUser, workdir, tarfile, md5file string) error {
	var cmd *exec.Cmd
	var md5Actual string
	if "darwin" == runtime.GOOS {
		cmd = BuildCommand(runUser, "md5", "-q", path.Join(workdir, tarfile))
	} else {
		cmd = BuildCommand(runUser, "md5sum", path.Join(workdir, tarfile))
	}
	cmd.Dir = file.SelfDir()
	bs, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("cd %s; md5sum -c %s fail", workdir, md5file)
	}
	strMd5file, _ := file.ToString(path.Join(workdir, md5file))
	if "" == strMd5file {
		return fmt.Errorf("md5file is empty")
	}

	if "darwin" == runtime.GOOS {
		md5Actual = strings.Replace(string(bs), "\n", "", -1)
	} else {
		md5Actual = strings.Fields(string(bs))[0]
	}

	md5Except := strings.Fields(strMd5file)[0]

	if md5Actual == md5Except {
		return nil
	}
	return fmt.Errorf("md5Actual:%s, md5Except:%s<<<===end", md5Actual, md5Except)
}
Example #18
0
func (lc *LocalCommand) Start() error {
	if lc.Shell == "" {
		lc.Shell = "sh"
	}

	var cmd *exec.Cmd
	if lc.ScriptMode {
		cmd = exec.Command(lc.Shell)
		cmd.Stdin = strings.NewReader(lc.CmdString)
	} else {
		cmd = exec.Command(lc.Shell, "-c", lc.CmdString)
	}

	// create the command, set the options
	if lc.WorkingDirectory != "" {
		cmd.Dir = lc.WorkingDirectory
	}
	cmd.Env = lc.Environment
	if cmd.Env == nil {
		cmd.Env = os.Environ()
	}
	cmd.Stdout = lc.Stdout
	cmd.Stderr = lc.Stderr

	// cache the command running
	lc.Cmd = cmd

	// start the command
	return cmd.Start()
}
Example #19
0
func ExecCmd(path string, arg1 string, args ...string) (string, error) {
	var cmd *exec.Cmd

	argsNew := make([]string, len(args))

	for i, a := range args {
		argsNew[i] = a
	}

	cmd = exec.Command(arg1, argsNew...)
	cmd.Dir = path
	// cmd.stdin = os.Stdin
	stderr, err := cmd.StderrPipe()
	if err != nil {
		log.Fatal("stderr err %v", err)
	}

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatalf("stdout err %v", err)
	}

	var retStr string
	err = cmd.Start()
	if err != nil {
		retb, _ := ioutil.ReadAll(stderr)
		retStr = string(retb)
		// stdoutReader.ReadRune()
	} else {
		retb, _ := ioutil.ReadAll(stdout)
		retStr = string(retb)
	}

	return retStr, err
}
Example #20
0
func (self *LocalCommand) Start() error {
	var cmd *exec.Cmd
	if self.ScriptMode {
		cmd = exec.Command("sh")
		cmd.Stdin = strings.NewReader(self.CmdString)
	} else {
		cmd = exec.Command("sh", "-c", self.CmdString)
	}

	// create the command, set the options
	if self.WorkingDirectory != "" {
		cmd.Dir = self.WorkingDirectory
	}
	cmd.Env = self.Environment
	if cmd.Env == nil {
		cmd.Env = os.Environ()
	}
	cmd.Stdout = self.Stdout
	cmd.Stderr = self.Stderr

	// cache the command running
	self.Cmd = cmd

	// start the command
	return cmd.Start()
}
Example #21
0
File: builder.go Project: leyra/gin
func (b *builder) Build() error {
	var command *exec.Cmd

	if b.customBuild != "" {
		parts := strings.Split(b.customBuild, " ")
		args := []string{}
		for k, v := range parts {
			if k > 0 {
				args = append(args, v)
			}
		}
		command = exec.Command(parts[0], args...)
	} else if b.useGodep {
		command = exec.Command("godep", "go", "build", "-o", b.binary)
	} else {
		command = exec.Command("go", "build", "-o", b.binary)
	}
	command.Dir = b.dir

	output, err := command.CombinedOutput()

	if command.ProcessState.Success() {
		b.errors = ""
	} else {
		b.errors = string(output)
	}

	if len(b.errors) > 0 {
		return fmt.Errorf(b.errors)
	}

	return err
}
Example #22
0
func buildCmd(cmd Cmd) *Result {
	var execCmd *exec.Cmd
	switch len(cmd.Command) {
	case 1:
		execCmd = exec.Command(cmd.Command[0])
	default:
		execCmd = exec.Command(cmd.Command[0], cmd.Command[1:]...)
	}
	outBuffer := new(lockedBuffer)
	errBuffer := new(lockedBuffer)

	execCmd.Stdin = cmd.Stdin
	execCmd.Dir = cmd.Dir
	execCmd.Env = cmd.Env
	if cmd.Stdout != nil {
		execCmd.Stdout = io.MultiWriter(outBuffer, cmd.Stdout)
	} else {
		execCmd.Stdout = outBuffer
	}
	execCmd.Stderr = errBuffer
	return &Result{
		Cmd:       execCmd,
		outBuffer: outBuffer,
		errBuffer: errBuffer,
	}
}
Example #23
0
func ExecGenCmd(args []string) (string, error) {
	var cmd *exec.Cmd

	argsNew := make([]string, len(args)+1)
	argsNew[0] = "generate"
	for i, a := range args {
		argsNew[i+1] = a
	}

	cmd = exec.Command("./ocitools", argsNew...)
	cmd.Dir = "./plugins"
	// cmd.stdin = os.Stdin
	stderr, err := cmd.StderrPipe()
	if err != nil {
		log.Fatal("stderr err %v", err)
	}

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatalf("stdout err %v", err)
	}

	var retStr string
	err = cmd.Start()
	if err != nil {
		retb, _ := ioutil.ReadAll(stderr)
		retStr = string(retb)
		// stdoutReader.ReadRune()
	} else {
		retb, _ := ioutil.ReadAll(stdout)
		retStr = string(retb)
	}

	return retStr, err
}
Example #24
0
func writeGitRepositoryArchive(w io.Writer, path string, ref GitCommitRef) error {
	var cmd *exec.Cmd
	// TODO: Stream as tar with gzip
	if ref == EmptyGitCommitRef {
		cmd = exec.Command("/usr/bin/git", "archive", "--format", "zip", "master")
	} else {
		cmd = exec.Command("/usr/bin/git", "archive", "--format", "zip", string(ref))
	}
	cmd.Env = []string{}
	cmd.Dir = path
	var stderr bytes.Buffer
	cmd.Stderr = utils.LimitWriter(&stderr, 20*1024)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return err
	}
	if err := cmd.Start(); err != nil {
		return err
	}
	io.Copy(w, stdout)
	if err := cmd.Wait(); err != nil {
		return errors.New(fmt.Sprintf("Failed to archive repository: %s\n", err.Error()) + stderr.String())
	}
	return nil
}
Example #25
0
// Handle receives a string message and decides whether to respond to the message
func (c *MessageResponder) Handle(direct bool, content string, args []string, responder func(string) error) (bool, error) {
	// if the executable file begins with _, that can respond to any message and is therefore passed every message
	// otherwise, the filename must match the command
	var cmd *exec.Cmd
	if direct && len(args) > 0 && args[0] == c.Name {
		cmd = exec.Command(c.Path, args[1:]...)
	} else if !direct && c.Name[0] == '_' {
		cmd = exec.Command(c.Path, content)
	} else {
		return false, nil
	}
	// set the exe's CWD to it's directory
	cmd.Dir = filepath.Dir(c.Path)
	output, err := runCommand(cmd)
	if err != nil {
		return true, err
	}
	go func() {
		// listen to the output generated and pass it to the responder func
		for o := range output {
			if len(o) == 0 { // ignore blank lines
				continue
			}
			if err := responder(o); err != nil {
				log.Printf("Error responding to command: %v", err)
				return
			}
		}
	}()
	return true, nil
}
Example #26
0
func (b *builder) Build() error {
	var command *exec.Cmd
	if b.useGodep {
		command = exec.Command("godep", "go", "build", "-o", b.binary)
	} else {
		command = exec.Command("go", "build", "-o", b.binary)
	}
	command.Dir = b.dir

	output, err := command.CombinedOutput()
	if err != nil {
		return err
	}

	if command.ProcessState.Success() {
		b.errors = ""
	} else {
		b.errors = string(output)
	}

	if len(b.errors) > 0 {
		return fmt.Errorf(b.errors)
	}

	return nil
}
Example #27
0
// execGit runs the git command with gitArgs. All the other arguments are only
// relevant if *gitContainer, in which case we run in a docker container.
func execGit(workdir string, containerName string, mounts map[string]string, gitArgs ...string) *exec.Cmd {
	var cmd *exec.Cmd
	if *gitContainer {
		removeContainer(containerName)
		args := []string{
			"run",
			"--rm",
			"--name=" + containerName,
		}
		for host, container := range mounts {
			args = append(args, "-v", host+":"+container+":ro")
		}
		args = append(args, []string{
			"-v", workdir + ":" + workdir,
			"--workdir=" + workdir,
			"camlistore/git",
			"git"}...)
		args = append(args, gitArgs...)
		cmd = exec.Command("docker", args...)
	} else {
		cmd = exec.Command("git", gitArgs...)
		cmd.Dir = workdir
	}
	return cmd
}
Example #28
0
func (repository *gitRepository) runGitCommand(cmd *exec.Cmd) (string, error) {
	cmd.Dir = repository.DirPath
	out, err := cmd.Output()
	if err != nil {
		return "", err
	}
	return strings.Trim(string(out), " \n"), nil
}
Example #29
0
func runCommand(cmd *exec.Cmd, dir string) error {
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Dir = dir
	trace(cmd)

	return cmd.Run()
}
Example #30
0
func execute(cmd *exec.Cmd, workspace *drone.Workspace) error {
	trace(cmd)

	cmd.Dir = workspace.Path
	cmd.Stderr = os.Stderr
	cmd.Stdin = os.Stdin

	return cmd.Run()
}