Example #1
0
func RunExternalAndStdout(cmd, wd string, argv []string) (stdout []byte, err os.Error) {
	argv = SplitArgs(argv)
	var c *exec.Cmd
	if len(argv) > 0 {
		c = exec.Command(cmd, argv...)
	} else {
		c = exec.Command(cmd)
	}
	c.Dir = wd
	c.Env = os.Environ()

	bStdout := bytes.NewBuffer(nil)
	bStderr := bytes.NewBuffer(nil)
	c.Stdout = bStdout
	c.Stderr = bStderr

	err = c.Run()

	if wmsg, ok := err.(*os.Waitmsg); ok {
		if wmsg.ExitStatus() != 0 {
			err = os.NewError(fmt.Sprintf("command: %s %v\n%s\n", cmd, argv, bStderr.String()))
		} else {
			err = nil
		}
	} else {
		stdout = bStdout.Bytes()
	}
	return
}
Example #2
0
func MoveChapter(source string, dest string, resize bool) {
	files, _ := ioutil.ReadDir(source)
	for _, v := range files {

		if !validImage(v.Name) {
			fmt.Println("ignorando " + source + "/" + v.Name)
			continue
		}
		newName := ClearPageName(v.Name)

		canResize, needR := needResize(source + "/" + v.Name)

		var err os.Error
		cmd := "/usr/local/bin/convert"

		if resize && canResize {
			if needR {
				_, err = exec.Command(cmd, "-resize", "900x1600", "-quality", "50", source+"/"+v.Name, dest+"/"+newName).CombinedOutput()
				fmt.Println("Recodificando e diminuindo " + source + "/" + v.Name + " para " + dest + "/" + newName)
			} else {
				_, err = exec.Command(cmd, "-quality", "50", source+"/"+v.Name, dest+"/"+newName).CombinedOutput()
				fmt.Println("recodificando " + source + "/" + v.Name + " para " + dest + "/" + newName)
			}
			if err != nil {
				fmt.Println("falha ao mover e recodificar arquivo " + source + "/" + v.Name + ": " + err.String())
				os.Exit(1)
			}
		} else {
			/*if canResize{
			    fmt.Println("movendo " + source + "/" + v.Name + " para " + dest + "/" + newName)
			}else{
			}*/

			if ext := strings.ToLower(path.Ext(v.Name)); ext == ".png" {
				fmt.Println("não foi possível codificar, movendo " + source + "/" + v.Name + " para " + dest + "/" + newName)
				if err = os.Rename(source+"/"+v.Name, dest+"/"+newName); err != nil {
					fmt.Println("falha ao mover " + source + "/" + v.Name + " para " + dest + "/" + newName + ": " + err.String())
				}

			} else {

				fmt.Println("recodificando " + source + "/" + v.Name + " para " + dest + "/" + newName)
				_, err = exec.Command(cmd, "-quality", "50", source+"/"+v.Name, dest+"/"+newName).CombinedOutput()

				if err != nil {
					fmt.Println("não foi possível codificar, movendo " + source + "/" + v.Name + " para " + dest + "/" + newName)
					if err = os.Rename(source+"/"+v.Name, dest+"/"+newName); err != nil {
						fmt.Println("falha ao mover " + source + "/" + v.Name + " para " + dest + "/" + newName + ": " + err.String())
					}
				}
			}
		}
		// time.Sleep(1000000000)
	}
}
Example #3
0
/*
Set the standard in and out screens to raw mode.
Always call ResetRaw() when you are done.

Post:
	ResetRaw() will reset standard in and out to pre-raw settings
*/
func MakeRaw() {
	c := exec.Command("stty", "raw")
	set_exec(c)
	c.Run()

	ResetRaw = func() {
		c := exec.Command("stty", "-raw")
		set_exec(c)
		c.Run()
	}
}
Example #4
0
func OpenURL(url string) os.Error {
	if runtime.GOOS == "windows" {
		return exec.Command("cmd.exe", "/C", "start "+url).Run()
	}

	if runtime.GOOS == "darwin" {
		return exec.Command("open", url).Run()
	}

	return exec.Command("xdg-open", url).Run()
}
Example #5
0
func BenchmarkCFuseThreadedStat(b *testing.B) {
	log.Println("benchmarking CFuse")

	lines := GetTestLines()
	unique := map[string]int{}
	for _, l := range lines {
		unique[l] = 1
		dir, _ := filepath.Split(l)
		for dir != "/" && dir != "" {
			unique[dir] = 1
			dir = filepath.Clean(dir)
			dir, _ = filepath.Split(dir)
		}
	}

	out := []string{}
	for k, _ := range unique {
		out = append(out, k)
	}

	f, err := ioutil.TempFile("", "")
	CheckSuccess(err)
	sort.Strings(out)
	for _, k := range out {
		f.Write([]byte(fmt.Sprintf("/%s\n", k)))
	}
	f.Close()

	log.Println("Written:", f.Name())
	mountPoint, _ := ioutil.TempDir("", "stat_test")
	wd, _ := os.Getwd()
	cmd := exec.Command(wd+"/cstatfs", mountPoint)
	cmd.Env = append(os.Environ(), fmt.Sprintf("STATFS_INPUT=%s", f.Name()))
	cmd.Start()

	bin, err := exec.LookPath("fusermount")
	CheckSuccess(err)
	stop := exec.Command(bin, "-u", mountPoint)
	CheckSuccess(err)
	defer stop.Run()

	for i, l := range lines {
		lines[i] = filepath.Join(mountPoint, l)
	}

	// Wait for the daemon to mount.
	time.Sleep(0.2e9)
	ttl := 1.0
	log.Println("N = ", b.N)
	threads := runtime.GOMAXPROCS(0)
	results := TestingBOnePass(b, threads, ttl*1.2, lines)
	AnalyzeBenchmarkRuns(results)
}
Example #6
0
// Run executes the Cmd.
func (c *Cmd) Run() error {
	if c.Args[0] == "mkdir" {
		for _, p := range c.Output {
			if err := os.MkdirAll(p, 0777); err != nil {
				return fmt.Errorf("command %q: %v", c, err)
			}
		}
		return nil
	}
	out := new(bytes.Buffer)
	cmd := exec.Command(c.Args[0], c.Args[1:]...)
	cmd.Dir = c.Dir
	cmd.Env = c.Env
	cmd.Stdout = out
	cmd.Stderr = out
	if c.Stdout != "" {
		f, err := os.Create(c.Stdout)
		if err != nil {
			return err
		}
		defer f.Close()
		cmd.Stdout = f
	}
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("command %q: %v\n%v", c, err, out)
	}
	return nil
}
Example #7
0
func RunExternalDump(cmd, wd string, argv []string, dump *os.File) (err error) {
	argv = SplitArgs(argv)

	if Verbose {
		fmt.Printf("%s\n", argv)
	}

	c := exec.Command(cmd, argv[1:]...)
	c.Dir = wd
	c.Env = os.Environ()

	c.Stdout = dump
	c.Stderr = os.Stderr

	err = c.Run()

	if wmsg, ok := err.(*os.Waitmsg); ok {
		if wmsg.ExitStatus() != 0 {
			err = errors.New(fmt.Sprintf("%v: %s\n", argv, wmsg.String()))
		} else {
			err = nil
		}
	}
	return
}
Example #8
0
File: main.go Project: jnwhiteh/go
// run runs the command argv, resolving argv[0] if necessary by searching $PATH.
// It provides input on standard input to the command.
func run(argv []string, input []byte) (out string, err os.Error) {
	if len(argv) < 1 {
		err = os.EINVAL
		goto Error
	}

	prog, ok := lookPathCache[argv[0]]
	if !ok {
		prog, err = exec.LookPath(argv[0])
		if err != nil {
			goto Error
		}
		lookPathCache[argv[0]] = prog
	}

	cmd := exec.Command(prog, argv[1:]...)
	if len(input) > 0 {
		cmd.Stdin = bytes.NewBuffer(input)
	}
	bs, err := cmd.CombinedOutput()
	if err == nil {
		return string(bs), nil
	}

Error:
	err = &runError{dup(argv), err}
	return
}
Example #9
0
func TestRmRf(t *testing.T) {
	t.Log("TestRemoveAll")
	wd, clean := setupUfs(t)
	defer clean()

	err := os.MkdirAll(wd+"/ro/dir/subdir", 0755)
	CheckSuccess(err)

	contents := "hello"
	fn := wd + "/ro/dir/subdir/y"
	err = ioutil.WriteFile(fn, []byte(contents), 0644)
	CheckSuccess(err)

	cmd := exec.Command("/bin/rm", "-rf", wd+"/mount/dir")
	err = cmd.Run()
	if err != nil {
		t.Fatal("rm -rf returned error:", err)
	}

	for _, f := range []string{"dir/subdir/y", "dir/subdir", "dir"} {
		if fi, _ := os.Lstat(filepath.Join(wd, "mount", f)); fi != nil {
			t.Errorf("file %s should have disappeared: %v", f, fi)
		}
	}

	names, err := Readdirnames(wd + "/rw/DELETIONS")
	CheckSuccess(err)
	if len(names) != 3 {
		t.Fatal("unexpected names", names)
	}
}
Example #10
0
func main() {
	ps := exec.Command("ps", "-e", "-opid,ppid,comm")
	output, _ := ps.Output()
	child := make(map[int]*vector.IntVector)
	for i, s := range strings.Split(string(output), "\n") {
		if i == 0 || len(s) == 0 { // Kill first and last line
			continue
		}
		f := strings.Fields(s)
		fpp, _ := strconv.Atoi(f[1]) // the parent's pid
		fp, _ := strconv.Atoi(f[0])  // the child's pid
		if _, present := child[fpp]; !present {
			v := new(vector.IntVector)
			child[fpp] = v
		}
		child[fpp].Push(fp) // Save the child PIDs on a vector
	}
	schild := make([]int, len(child))
	i := 0
	for k, _ := range child {
		schild[i] = k
		i++
	}
	sort.Ints(schild)
	for _, ppid := range schild { // Walk through the sorted list
		fmt.Printf("Pid %d has %d child", ppid, child[ppid].Len())
		if child[ppid].Len() == 1 {
			fmt.Printf(": %v\n", []int(*child[ppid]))
		} else {
			fmt.Printf("ren: %v\n", []int(*child[ppid]))
		}
	}
}
Example #11
0
// Refresh the cache every hour or so.
func init() {
	go func() {
		for {

			albumsFilename := "data/picasa/albums.json"
			jsonutil.DecodeFromFile(albumsFilename, &cachedAlbums)
			for _, album := range cachedAlbums {
				fmt.Println("album Link: ", album.Link, ", album ID: ", album.AlbumId)
				photosFilename := "data/picasa/albums/" + album.Link + ".json"
				var photos []Photo
				jsonutil.DecodeFromFile(photosFilename, &photos)
				cachedPhotos[album.Link] = photos
			}

			// Note, when setting this, that updating the feed
			// Causes lots of things to be swapped out in
			// Low-memory enviroments. Choose a balance.
			time.Sleep(1000e9) // 1000 seconds.

			// Why, you may ask, is this down here? Well, because i don't want to have to wait for all of the photos to load each time i start the module for debugging.
			updater := exec.Command("bin/picasa-updater")
			err := updater.Run()
			if err != nil {
				fmt.Println("Error running photos updater:", err)
				continue
			}
			updater.Wait()
		}
	}()
}
Example #12
0
func TestDump(t *testing.T) {
	// empty

	// func ParseFile(filename string, src interface{}, scope *ast.Scope, mode uint) (*ast.File, os.Error)
	/*
		file, e := parser.ParseFile(nil, "dump_test.go", nil, parser.ParseComments)
		if e != nil {
			fmt.Println("error", e)
		} else {
	*/
	//		fmt.Printf("%#v\n", file);
	//		Dump(file)
	Dump(map[string]int{"satu": 1, "dua": 2})
	Dump([]int{1, 2, 3})
	Dump([3]int{1, 2, 3})
	Dump(&[][]int{[]int{1, 2, 3}, []int{1, 2, 3}, []int{1, 2, 3}})
	Dump(&emptyString)
	Dump(T{S{1, 2}, 3})
	Dump(token.STRING)

	bulet := make([]Circular, 3)
	bulet[0].c = &bulet[1]
	bulet[1].c = &bulet[2]
	bulet[2].c = &bulet[0]

	Dump(struct{ a []Circular }{bulet})
	cmd := exec.Command("ls", "-la")
	Dump(cmd)
	//	}
}
// run executes the specified command and returns its output and an error.
func run(args ...string) ([]byte, os.Error) {
	var buf bytes.Buffer
	cmd := exec.Command(args[0], args[1:]...)
	cmd.Stdout = &buf
	cmd.Stderr = cmd.Stdout

	// Start command and leave in 'running'.
	running.Lock()
	if running.cmd != nil {
		defer running.Unlock()
		return nil, fmt.Errorf("already running %s", running.cmd.Path)
	}
	if err := cmd.Start(); err != nil {
		running.Unlock()
		return nil, err
	}
	running.cmd = cmd
	running.Unlock()

	// Wait for the command.  Clean up,
	err := cmd.Wait()
	running.Lock()
	if running.cmd == cmd {
		running.cmd = nil
	}
	running.Unlock()
	return buf.Bytes(), err
}
Example #14
0
func runTest(toolchain, test string) (stderr string, err os.Error) {
	cmd := exec.Command(path.Join(toolchain, "bin/llc"), "-O0", "-stats", "--time-passes",
		"-relocation-model=pic", "-O0", "-asm-verbose=false")
	var data []byte
	if data, err = ioutil.ReadFile(test); err != nil {
		return
	}
	cmd.Stdin = bytes.NewBuffer(data)
	var outPipe, errPipe io.Reader

	if errPipe, err = cmd.StderrPipe(); err != nil {
		return
	}
	if outPipe, err = cmd.StdoutPipe(); err != nil {
		return
	}
	if err = cmd.Start(); err != nil {
		return "", fmt.Errorf("cmd.Start: %v", err)
	}
	if _, err = ioutil.ReadAll(outPipe); err != nil {
		return "", fmt.Errorf("ioutil.ReadAll(outPipe): %v", err)
	}
	var stderrData []byte
	if stderrData, err = ioutil.ReadAll(errPipe); err != nil {
		return "", fmt.Errorf("ioutil.ReadAll(errPipe): %v", err)
	}
	if err = cmd.Wait(); err != nil {
		return "", fmt.Errorf("cmd.Wait: %v", err)
	}
	stderr = string(stderrData)
	return
}
Example #15
0
func diff(b1, b2 []byte) (data []byte, err os.Error) {
	f1, err := ioutil.TempFile("", "gofmt")
	if err != nil {
		return
	}
	defer os.Remove(f1.Name())
	defer f1.Close()

	f2, err := ioutil.TempFile("", "gofmt")
	if err != nil {
		return
	}
	defer os.Remove(f2.Name())
	defer f2.Close()

	f1.Write(b1)
	f2.Write(b2)

	data, err = exec.Command("diff", "-u", f1.Name(), f2.Name()).CombinedOutput()
	if len(data) > 0 {
		// diff exits with a non-zero status when the files don't match.
		// Ignore that failure as long as we get output.
		err = nil
	}
	return

}
Example #16
0
// runLog runs a process and returns the combined stdout/stderr,
// as well as writing it to logfile (if specified). It returns
// process combined stdout and stderr output, exit status and error.
// The error returned is nil, if process is started successfully,
// even if exit status is not 0.
func runLog(envv []string, logfile, dir string, argv ...string) (string, int, os.Error) {
	if *verbose {
		log.Println("runLog", argv)
	}
	argv = useBash(argv)

	b := new(bytes.Buffer)
	var w io.Writer = b
	if logfile != "" {
		f, err := os.OpenFile(logfile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			return "", 0, err
		}
		defer f.Close()
		w = io.MultiWriter(f, b)
	}

	cmd := exec.Command(argv[0], argv[1:]...)
	cmd.Dir = dir
	cmd.Env = envv
	cmd.Stdout = w
	cmd.Stderr = w

	err := cmd.Run()
	if err != nil {
		if ws, ok := err.(*os.Waitmsg); ok {
			return b.String(), ws.ExitStatus(), nil
		}
	}
	return b.String(), 0, nil
}
Example #17
0
// updateRepo gets a list of tags in the repository and
// checks out the tag closest to the current runtime.Version.
// If no matching tag is found, it just updates to tip.
func (v *vcs) updateRepo(dst string) os.Error {
	if v.tagList == "" || v.tagListRe == nil {
		// TODO(adg): fix for svn
		return run(dst, nil, v.cmd, v.update)
	}

	// Get tag list.
	stderr := new(bytes.Buffer)
	cmd := exec.Command(v.cmd, v.tagList)
	cmd.Dir = dst
	cmd.Stderr = stderr
	b, err := cmd.Output()
	if err != nil {
		errorf("%s %s: %s\n", v.cmd, v.tagList, stderr)
		return err
	}
	var tags []string
	for _, m := range v.tagListRe.FindAllStringSubmatch(string(b), -1) {
		tags = append(tags, m[1])
	}

	// Only use the tag component of runtime.Version.
	ver := strings.Split(runtime.Version(), " ")[0]

	// Select tag.
	if tag := selectTag(ver, tags); tag != "" {
		printf("selecting revision %q\n", tag)
		return run(dst, nil, v.cmd, v.checkout, v.updateRevFlag+tag)
	}

	// No matching tag found, make default selection.
	printf("selecting tip\n")
	return run(dst, nil, v.cmd, v.update)
}
Example #18
0
func backupCopy(dir string) {
	_, err := exec.Command("cp", "-r", dir, dir+"__").Output()
	if err != nil {
		fmt.Println("falha ao criar backup " + err.String())
		panic(err.String())
	}
}
Example #19
0
File: handy.go Project: ssrl/mgd
func StdExecve(argv []string, stopOnTrouble bool) bool {

	var err os.Error
	var cmd *exec.Cmd

	switch len(argv) {
	case 0:
		if stopOnTrouble {
			log.Fatalf("[ERROR] len(argv) == 0\n")
		}
		return false
	case 1:
		cmd = exec.Command(argv[0])
	default:
		cmd = exec.Command(argv[0], argv[1:]...)
	}

	// pass-through
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Stdin = os.Stdin

	err = cmd.Start()

	if err != nil {
		if stopOnTrouble {
			log.Fatalf("[ERROR] %s\n", err)
		} else {
			log.Printf("[ERROR] %s\n", err)
			return false
		}
	}

	err = cmd.Wait()

	if err != nil {
		if stopOnTrouble {
			log.Fatalf("[ERROR] %s\n", err)
		} else {
			log.Printf("[ERROR] %s\n", err)
			return false
		}
	}

	return true
}
Example #20
0
func run(command string) os.Error {
	output, err := exec.Command("/bin/sh", "-c", command).CombinedOutput()
	if err != nil {
		msg := fmt.Sprintf("Failed to execute: %s: %s\n%s", command, err.String(), string(output))
		return os.NewError(msg)
	}
	return nil
}
Example #21
0
func (git GitRepository) Commit(message string) os.Error {
	var (
		commitcmd = exec.Command("git", "commit",
			"-a", "-m", "Empty project generated by gonew.")
		errCommit = commitcmd.Run()
	)
	return errCommit
}
Example #22
0
func (r *Request) GetPIN() (pin string, outerr os.Error) {
	defer catch(&outerr)
	bin, err := exec.LookPath("pinentry")
	if err != nil {
		return r.getPINNaïve()
	}
	cmd := exec.Command(bin)
	stdin, _ := cmd.StdinPipe()
	stdout, _ := cmd.StdoutPipe()
	check(cmd.Start())
	defer cmd.Wait()
	defer stdin.Close()
	br := bufio.NewReader(stdout)
	lineb, _, err := br.ReadLine()
	if err != nil {
		return "", fmt.Errorf("Failed to get getpin greeting")
	}
	line := string(lineb)
	if !strings.HasPrefix(line, "OK") {
		return "", fmt.Errorf("getpin greeting said %q", line)
	}
	set := func(cmd string, val string) {
		if val == "" {
			return
		}
		fmt.Fprintf(stdin, "%s %s\n", cmd, val)
		line, _, err := br.ReadLine()
		if err != nil {
			panic("Failed to " + cmd)
		}
		if string(line) != "OK" {
			panic("Response to " + cmd + " was " + string(line))
		}
	}
	set("SETPROMPT", r.Prompt)
	set("SETDESC", r.Desc)
	set("SETOK", r.OK)
	set("SETCANCEL", r.Cancel)
	set("SETERROR", r.Error)
	set("OPTION", "ttytype="+os.Getenv("TERM"))
	tty, err := os.Readlink("/proc/self/fd/0")
	if err == nil {
		set("OPTION", "ttyname="+tty)
	}
	fmt.Fprintf(stdin, "GETPIN\n")
	lineb, _, err = br.ReadLine()
	if err != nil {
		return "", fmt.Errorf("Failed to read line after GETPIN: %v", err)
	}
	line = string(lineb)
	if strings.HasPrefix(line, "D ") {
		return line[2:], nil
	}
	if strings.HasPrefix(line, "ERR 83886179 ") {
		return "", ErrCancel
	}
	return "", fmt.Errorf("GETPIN response didn't start with D; got %q", line)
}
Example #23
0
func runDoozer(a ...string) *exec.Cmd {
	path := "/home/kr/src/go/bin/doozerd"
	args := append([]string{path}, a...)
	c := exec.Command(path, args...)
	if err := c.Run(); err != nil {
		panic(err)
	}
	return c
}
Example #24
0
func rsyncFromGerrit(dest string) {
	for {
		err := exec.Command("rsync", "-avPW", *gerritUser+"@"+*gerritHost+":gerrit/git/", dest+"/").Run()
		if err != nil {
			log.Printf("rsync from gerrit = %v", err)
		}
		time.Sleep(10e9)
	}
}
Example #25
0
func loadRedis() {
	cmd := exec.Command("ruby", "loader.rb")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		log.Fatalln("Unable to load messages into Redis", err)
	}
}
Example #26
0
// hgup
func releaseDoFirst() {

	if os.Getenv("GOOS") == "windows" {
		fmt.Println("\n[ release ]\n")
		fmt.Println(" this target only works on Linux/Unix/Mac\n")
		os.Exit(1)
	}

	goroot := os.Getenv("GOROOT")

	if goroot == "" {
		log.Fatalf("[ERROR] missing GOROOT variable\n")
	}

	srcdir := filepath.Join(goroot, "src")

	say.Printf("> \u001B[32mcd $GOROOT/src\u001B[0m\n")
	e := os.Chdir(srcdir)
	quitter(e)

	current, e := exec.Command("hg", "id", "-i").CombinedOutput()
	quitter(e)

	say.Println("> \u001B[32mhg pull\u001B[0m")
	run([]string{"hg", "pull"})

	say.Println("> \u001B[32mhg update release\u001B[0m")
	run([]string{"hg", "update", "release"})

	updated, e := exec.Command("hg", "id", "-i").CombinedOutput()

	if e != nil {
		log.Fatalf("[ERROR] %s\n", e)
	}

	if string(current) != string(updated) {
		say.Println("> \u001B[32mbash make.bash\u001B[0m")
		run([]string{"bash", "make.bash"})
	} else {
		say.Println("[\u001B[32m already at release version\u001B[0m ]")
	}

	os.Exit(0)
}
Example #27
0
func compile(t *testing.T, dirname, filename string) {
	cmd := exec.Command(gcPath, filename)
	cmd.Dir = dirname
	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Errorf("%s %s failed: %s", gcName, filename, err)
		return
	}
	t.Logf("%s", string(out))
}
Example #28
0
func execute(c string, args ...string) {
	cmd := exec.Command(c, args...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		log.Fatal(err.String())
	}
}
func openUrl(url string) {
	try := []string{"xdg-open", "google-chrome", "open"}
	for _, bin := range try {
		err := exec.Command(bin, url).Run()
		if err == nil {
			return
		}
	}
	log.Printf("Error opening URL in browser.")
}
Example #30
0
func (git GitRepository) Add(paths ...string) os.Error {
	var cmdslice = make([]string, len(paths)+1)
	cmdslice[0] = "add"
	copy(cmdslice[1:], paths)
	var (
		addcmd = exec.Command("git", cmdslice...)
		errAdd = addcmd.Run()
	)
	return errAdd
}