Beispiel #1
0
//to build the project with gobuild or make after generating .go source files
func build(b int, s string) (err os.Error) {
	p := strings.Fields(s)
	params := make([]string, len(p)+1)
	params[0] = ""
	for i, param := range p {
		params[i+1] = param
	}
	m := b == MAKE
	g := b == GOBUILD
	//fd := []*os.File{os.Stdin, os.Stdout, os.Stderr}
	if m {
		err = os.Exec("/usr/bin/make", params, os.Environ())
		if err != nil {
			panic("Cannot call make")
		}
	} else if g {
		gobuild := os.Getenv("GOBIN")
		if len(gobuild) == 0 {
			gobuild = path.Join(os.Getenv("HOME"), "bin", "gobuild")
		} else {
			gobuild = path.Join(gobuild, "gobuild")
		}
		err := os.Exec(gobuild, params, os.Environ())
		if err != nil {
			panic("Cannot call gobuild")
		}
	}
	return
}
Beispiel #2
0
func main() {
	if len(os.Args) < 2 {
		fmt.Printf("Usage: %s <script file>\n", os.Args[0])
		return
	}
	namehash_hash := md5.New()
	io.WriteString(namehash_hash, os.Args[1])
	namehash := hex.EncodeToString(namehash_hash.Sum())
	tempfile := temp_dir() + "/" + namehash

	readpipe, writepipe, _ := os.Pipe()
	stdfiles := [](*os.File){readpipe, os.Stdout, os.Stderr}

	syscall.Umask(0077)
	srcfile, err := os.Open(os.Args[1], os.O_RDONLY, 0)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	srcinfo, _ := srcfile.Stat()
	outfile, err := os.Open(tempfile+".ld", os.O_RDONLY, 0)
	var outinfo (*os.FileInfo)
	if err == nil {
		outinfo, _ = outfile.Stat()
		outfile.Close()
	}

	if err != nil || outinfo.Mtime_ns < srcinfo.Mtime_ns {
		//fmt.Printf("Compiling...")
		cpid, cerr := os.ForkExec(GOBIN+"8g", []string{GOBIN + "8g", "-o", tempfile + ".cd", "/dev/stdin"}, nil, "", stdfiles)

		src := textproto.NewReader(bufio.NewReader(srcfile))
		firstline := true
		for {
			s, err := src.ReadLine()
			if err != nil {
				break
			}
			if (len(s) > 0) && (s[0] == '#') && firstline {
				continue
			}
			firstline = false
			writepipe.WriteString(s + "\n")
		}
		writepipe.Close()
		srcfile.Close()

		stage_check(cpid, cerr, "compile")

		lpid, err := os.ForkExec(GOBIN+"8l", []string{GOBIN + "8l", "-o", tempfile + ".ld", tempfile + ".cd"}, nil, "", stdfiles)
		stage_check(lpid, err, "link")
		os.Chmod(tempfile+".ld", 0700)
		//fmt.Println("done.")
	} else {
		//fmt.Println("Running cached.")
	}
	err = os.Exec(tempfile+".ld", os.Args[1:], nil)
	fmt.Println(err)
	os.Exit(1)
}
Beispiel #3
0
func main() {

	err := os.MkdirAll(storedir, dirperms)
	if err != nil {
		log.Fatalln(err)
	}

	if len(os.Args) < 2 { //no filename
		log.Fatalln("No filename given")
	}
	scriptname := os.Args[1]
	scriptfile, err := os.Open(scriptname, os.O_RDONLY, 0)
	if err != nil {
		log.Fatalln(err)
	}
	defer scriptfile.Close()

	hash := hasht.New()
	io.Copy(hash, scriptfile)                //feed data to hash func
	hashstr := fmt.Sprintf("%x", hash.Sum()) //get hash as hex string

	table, err := readTable(dbfilename) //get our data ready
	if err != nil {
		log.Fatalln(err)
	}

	metadata, ok := table[hashstr] //look for record of scriptfile
	if !ok {
		err = compile(scriptfile, hashstr)
		if err != nil {
			log.Fatalln(err)
		}
	} else {
		if _, err = os.Stat(path.Join(storedir, hashstr)); err != nil {
			err = compile(scriptfile, hashstr)
			if err != nil {
				log.Fatalln(err)
			}
		}
	}
	metadata.Hash = hashstr
	metadata.Lastused, _, err = os.Time()
	if err != nil {
		log.Println(err)
		metadata.Lastused = latestTime
	}
	metadata.Filename = scriptname
	table[hashstr] = metadata
	if err := writeTable(table, dbfilename); err != nil {
		log.Println(err)
	}

	os.Exec(path.Join(storedir, hashstr), os.Args[1:], os.Environ())
}
Beispiel #4
0
// tests if all the komokuSource-files exist
func TestRelPathToAbs(t *testing.T) {
	// The tests are normally invoked through a Makefile. We first check if every file exists...
	for _, rel := range komokuSource {
		abs := relPathToAbs(rel)
		fi, err := os.Stat(abs)
		if err != nil || !fi.IsRegular() {
			t.Fatalf("%s is no regular file", abs)
		}
	}
	// Then run the whole common_test executable from the system
	os.Exec("./common_test", nil, nil)
}
Beispiel #5
0
func kill_process(pid int) {
	argv3 := []string{"", strconv.Itoa(pid)}
	cmd3, _ := exec.LookPath("kill")
	err3 := os.Exec(cmd3, argv3, nil)
	w.Printf("pid=%v, err3=%v", pid, err3.String())

	msg := "err3=" + err3.String() + "\n"
	w.Println(msg)
	w.Println("Done !\n")
	if err3 != nil {
		println("warning: godoc process still running in background !")
	}

}
Beispiel #6
0
func main() {
	args := os.Args[1:]
	if len(args) == 0 {
		fmt.Fprintln(os.Stderr, "go main-program [arg0 [arg1 ...]]")
		os.Exit(1)
	}

	target := path.Clean(args[0])
	if path.Ext(target) == ".go" {
		target = target[0 : len(target)-3]
	}

	files, error := CollectSourceFiles(target)
	if error != nil {
		fmt.Fprintf(os.Stderr, "Can't %v\n", error)
		os.Exit(1)
	}

	// Compiling source files
	for k := len(files) - 1; k >= 0; k-- {
		v := files[k]
		if v != "" {
			compile(v)
		} else {
			files[k] = "", false
		}
	}

	targets := make([]string, len(files)+3)
	targets[0] = path.Join(envbin, arch+"l")
	targets[1] = "-o"
	targets[2] = target
	doLink := false
	for i, v := range files {
		targets[i+3] = v + "." + arch
		if !doLink {
			if shouldUpdate, _ := shouldUpdate(targets[i+3], target); shouldUpdate {
				doLink = true
			}
		}
	}
	if doLink {
		exec(targets, "")
	}
	os.Exec(path.Join(curdir, target), args, os.Environ())
	fmt.Fprintf(os.Stderr, "Error running %v\n", args)
	os.Exit(1)
}
Beispiel #7
0
func editdoc(line string) {
	dir, name := getdir(line), getname(line)
	if name == "" {
		return
	}
	os.Chdir(os.Getenv("HOME"))
	if dir != "" {
		if err := os.Chdir(dir); err != nil {
			fmt.Println("error: " + err.String())
		}
	}
	vimpath, _ := exec.LookPath("gvim")
	args := []string{vimpath, name}
	if err := os.Exec(vimpath, args, os.Environ()); err != nil {
		fmt.Println("error: " + err.String())
	}
}
Beispiel #8
0
// formats the source code using gofmt
func Format(source string) (err os.Error) {
	gofmt := os.Getenv("GOBIN")
	if len(gofmt) == 0 {
		gofmt = path.Join(os.Getenv("HOME"), "bin", "gofmt")
	} else {
		gofmt = path.Join(gofmt, "gofmt")
	}
	//fd := []*os.File{os.Stdin, os.Stdout, os.Stderr}
	_, file := path.Split(source)
	//id, err := os.ForkExec(gofmt, []string{"", "-w", file}, os.Environ(), dir, fd)
	//id, err := os.Exec(gofmt, []string{"", "-w", file}, os.Environ())
	err = os.Exec(gofmt, []string{"", "-w", file}, os.Environ())
	if err != nil {
		panic("exec returned but succeeded")
	}
	/*} else {
		os.Wait(id, 0)
	}*/
	return err
}
Beispiel #9
0
// Run compiles and links the Go source file on args[0] and
// runs it with arguments args[1:].
func Run(args []string, useGd bool) os.Error {
	sourcefile := args[0]
	rundir, runfile, err := RunFile(sourcefile)
	if err != nil {
		return err
	}

	compile := false

	// Nanoseconds must be called before Stat of sourcefile below,
	// so that changing the file between Stat and Chtimes still
	// causes the file to be updated on the next run.
	now := time.Nanoseconds()

	sstat, err := os.Stat(sourcefile)
	if err != nil {
		return err
	}

	rstat, err := os.Stat(runfile)
	switch {
	case err != nil:
		compile = true
	case !rstat.IsRegular():
		return os.NewError("not a file: " + runfile)
	case rstat.Mtime_ns < sstat.Mtime_ns || rstat.Permission()&0700 != 0700:
		compile = true
	default:
		// We have spare cycles. Maybe remove old files.
		if err := os.Chtimes(runfile, now, now); err == nil {
			CleanDir(rundir, now)
		}
	}

	for retry := 3; retry > 0; retry-- {
		if compile {
			ec := Compile(sourcefile, runfile, useGd)
			if ec != nil {
				return ec
			}
			// If sourcefile was changed, will be updated on next run.
			os.Chtimes(runfile, sstat.Mtime_ns, sstat.Mtime_ns)
		}

		if os.Getenv("GOOS") == "windows" {
			attr := &os.ProcAttr{Env: os.Environ(), Files: []*os.File{os.Stdin, os.Stdout, os.Stderr}}
			p, err := os.StartProcess(runfile, args, attr)
			if err != nil {
				panic(err)
			} else {
				_, _ = p.Wait(0)
				p.Release()
				os.Exit(0)
			}
		} else {
			err = os.Exec(runfile, args, os.Environ())
		}

		eNoEntError := os.ENOENT
		if os.Getenv("GOOS") == "windows" {
			eNoEntError = os.NewError("The system cannot find the path specified.")
		}
		if perr, ok := err.(*os.PathError); ok && perr.Error.String() == eNoEntError.String() {
			// Got cleaned up under our feet.
			compile = true
			continue
		}
		break
	}

	if err != nil {
		panic("exec returned but succeeded")
	}
	return err
}
Beispiel #10
0
func main() {
	// Defer this first to ensure cleanup gets done properly
	//
	// Any error of type GracefulError is handled with an exit(1)
	// rather than by handing the user a backtrace.
	//
	// An error of type RestartSignal is technically not an error
	// but is the cleanest way to ensure no defers are skipped.
	defer func() {
		problem := recover()
		if problem == nil {
			return
		}
		switch problem.(type) {
		case GracefulError:
			fmt.Println(problem)
			os.Exit(1)
		case RestartSignal:
			fmt.Println(problem)
			// Probably requires closing any fds still open
			// Will investigate later
			os.Exec(os.Args[0], os.Args, os.Envs)
			// If we're still here something went wrong.
			fmt.Println("Couldn't restart. You'll have to restart manually.")
			os.Exit(0)
		default:
			panic(problem)
		}
	}()

	flag.Parse()

	if *basedir == "" {
		*basedir = dirname(os.Args[0])
	}

	fmt.Println("Switching dir to", *basedir)
	os.Chdir(*basedir)

	parseConfig(*conffile)
	parseNameSpaces(conf["namespace_file"])

	// Check for any new databases, including initial startup, and
	// perform pre-processing.
	hadFiles := performUpdates()

	// Load in the title cache
	if !loadTitleFile() {
		if hadFiles {
			fmt.Println("Unable to read Title cache file: Invalid format?")
		} else {
			fmt.Println("\n\nNo wiki files found and unable to read title cache.\n\nIf you never downloaded a wikipedia dump, you will have to do that now.\nIf you have, something went wrong or the cache format changed.\nYou will probably have to supply a new dump or put back your old one.")
		}
		return
	}
	prepSearchRoutines()
	prepRecents()

	fmt.Println("Loaded! Starting webserver . . .")

	// /wiki/... are pages.
	http.HandleFunc("/wiki/", pageHandle)
	// /search/ look for given text
	http.HandleFunc("/search/", searchHandle)
	// /recent, a list of recent searches
	http.HandleFunc("/recent", recentHandle)

	// Everything else is served from the web dir.
	http.Handle("/", http.FileServer(http.Dir(conf["web_dir"])))

	fmt.Printf("Forcing Go to use %d max threads.\n", searchRoutines)
	runtime.GOMAXPROCS(searchRoutines)

	fmt.Println("Starting Web server on port", conf["listen"])

	err := http.ListenAndServe(conf["listen"], nil)
	if err != nil {
		fmt.Println("Fatal error:", err.String())
	}
}
Beispiel #11
0
func main() {

	/*
	 *TODO:
	 *   1) replace the pause by a test to check if the server responding
	 */

	var e os.Error
	f, e = os.Open("log.txt", os.O_WRONLY|os.O_CREAT, 0666)
	w = log.New(f, ">>>", 0)
	w.Printf("testing log !\n")

	if e != nil {
		println("Open log file failed !")
	}

	defer f.Close()

	/*
	   //---------------
	   // Test for os.ForkExec
	   //---------------
	   streams := []*os.File{ os.Stdin, os.Stdout, os.Stderr}

	   //---------------
	   // test
	   //---------------
	   argv0 := []string{"ls", "-lAF",  "/"}
	   cmd0, _ := exec.LookPath("ls")
	   pid, err0 := os.ForkExec(cmd0, argv0, nil, "", streams)
	   fmt.Printf("pid = %d\n", pid)
	   if err0 != nil {
	       println("test with ls Failed !")
	   }
	*/

	//---------------
	// Starting server
	//---------------
	cmd, err := exec.LookPath("godoc")

	//fmt.Printf("path=%v, err=%v\n", cmd, err)
	if err != nil {
		println("Please check that godoc is installed\n")
	}
	argv := []string{"godoc", "-http=:8090"}
	pid1, err1 := syscall.ForkExec(cmd, argv, nil, "", nil)
	w.Printf("err1=%v, pid=%v\n", err1, pid1)

	//pause in the parent process to allow the server to start
	time.Sleep(1e9)

	// Waiting for the server to complete
	os.Wait(pid1, os.WNOHANG)

	//---------------
	// Starting browser
	//---------------
	cmd2, err2 := exec.LookPath("links")
	if err2 != nil {
		println("In order to run godocs, links needs to be installed")
		println("- Linux: apt-get install links")
		println("- Mac: Fink install links\n")
	}

	argv2 := []string{"links", "http://localhost:8090/pkg"}
	//pid2, err2 := os.ForkExec(cmd2, argv2, nil, "", nil)
	err3 := os.Exec(cmd2, argv2, nil)
	w.Printf("err2=%v\n", err3)

	// Waiting for the browser to complete
	//os.Wait(pid2, os.WNOHANG)
	// Waiting for the server to complete
	os.Wait(pid1, os.WNOHANG)

	// deferred closing the server.
	defer kill_process(pid1)
	// Closing the browser.
	//defer kill_process(pid2)
}