Exemple #1
0
func initOSVars() {
	var err error

	switch runtime.GOOS {
	case "darwin":
		if dbg {
			workingDir, err = os.Getwd()
		} else {
			workingDir = "/Applications/5DPrint.app/Contents/MacOS"
		}

		launchBrowserArgs = []string{"open"}
	case "windows":
		workingDir, err = os.Getwd()
		launchBrowserArgs = []string{"cmd", "/c", "start"}
	default:
		workingDir, err = os.Getwd()
		launchBrowserArgs = []string{"xdg-open"}
	}

	if err != nil {
		log.Println("initOSVars: ", err)
		os.Exit(1)
	}
}
Exemple #2
0
// Construct file locations of of scanner resources based on the operating system.
//
// Example:
//
// 	fileLocations := goNessus.ConstructFileLocations()
func ConstructFileLocations() FileLocations {
	if runtime.GOOS == "linux" {
		fileLocations := FileLocations{Base_directory: "/opt/scanner"}
		fileLocations.Temp_directory = fmt.Sprintf("%s/temp%d", fileLocations.Base_directory, os.Getpid())
		fileLocations.Archive_directory = fmt.Sprintf("%s/targets/archive", fileLocations.Base_directory)
		fileLocations.Incoming_directory = fmt.Sprintf("%s/targets/incoming", fileLocations.Base_directory)
		fileLocations.Results_directory = fmt.Sprintf("%s/results", fileLocations.Base_directory)
		return fileLocations
	} else if runtime.GOOS == "darwin" {
		// Use PWD since don't really know where to put this type of thing
		pwd, err := os.Getwd()
		CheckErr(err)

		fileLocations := FileLocations{Base_directory: pwd}
		fileLocations.Temp_directory = fmt.Sprintf("%s/temp%d", fileLocations.Base_directory, os.Getpid())
		fileLocations.Archive_directory = fmt.Sprintf("%s/targets/archive", fileLocations.Base_directory)
		fileLocations.Incoming_directory = fmt.Sprintf("%s/targets/incoming", fileLocations.Base_directory)
		fileLocations.Results_directory = fmt.Sprintf("%s/results", fileLocations.Base_directory)
		return fileLocations
	} else {
		// Use PWD since don't really know where to put this type of thing
		pwd, err := os.Getwd()
		CheckErr(err)

		fileLocations := FileLocations{Base_directory: pwd}
		fileLocations.Temp_directory = fmt.Sprintf("%s/temp%d", fileLocations.Base_directory, os.Getpid())
		fileLocations.Archive_directory = fmt.Sprintf("%s/targets/archive", fileLocations.Base_directory)
		fileLocations.Incoming_directory = fmt.Sprintf("%s/targets/incoming", fileLocations.Base_directory)
		fileLocations.Results_directory = fmt.Sprintf("%s/results", fileLocations.Base_directory)
		return fileLocations
	}
}
Exemple #3
0
func TestdirectoryContents(t *testing.T) {
	// setup
	save_pwd, _ := os.Getwd()
	if err := os.MkdirAll("test/artifacts/.amber", 0700); err != nil {
		t.Error("Error creating artifacts: ", err)
	}
	defer os.RemoveAll("test/artifacts")
	defer os.Chdir(save_pwd)

	// test
	actual, err := directoryContents("test/artifacts")
	if err != nil {
		t.Error(err)
	}

	// verify pwd same
	if pwd, _ := os.Getwd(); save_pwd != pwd {
		t.Errorf("Expected: %v, actual: %v", save_pwd, pwd)
	}

	// verify
	expected := []string{".amber"}
	if !stringSlicesEqual(expected, actual) {
		t.Errorf("Expected: %v, actual: %v", expected, actual)
	}
}
Exemple #4
0
func TestPushdPopd(t *testing.T) {
	sh := gosh.NewShell(t)
	defer sh.Cleanup()

	startDir, err := os.Getwd()
	ok(t, err)
	parentDir := filepath.Dir(startDir)
	neq(t, startDir, parentDir)
	sh.Pushd(parentDir)
	cwd, err := os.Getwd()
	ok(t, err)
	eq(t, cwd, parentDir)
	sh.Pushd(startDir)
	cwd, err = os.Getwd()
	ok(t, err)
	eq(t, cwd, startDir)
	sh.Popd()
	cwd, err = os.Getwd()
	ok(t, err)
	eq(t, cwd, parentDir)
	sh.Popd()
	cwd, err = os.Getwd()
	ok(t, err)
	eq(t, cwd, startDir)
	// The next sh.Popd() will fail.
	setsErr(t, sh, func() { sh.Popd() })
}
Exemple #5
0
func testGetwd() {
	// 获取程序当前目录,main go文件的目录
	dir, err := os.Getwd()
	olddir := dir
	if err != nil {
		fmt.Println("Error : ", err)
		return
	}
	fmt.Println("当前 dir = ", dir)

	// 系统的目录分隔符
	ps := os.PathSeparator
	fmt.Println("PathSeparator : ", string(ps))

	// 切换目录
	os.Chdir(dir + "/mytest")

	dir, err = os.Getwd()
	if err != nil {
		fmt.Println("Error : ", err)
		return
	}
	fmt.Println("切换后 dir = ", dir)

	// 切换目录
	os.Chdir(olddir)

}
Exemple #6
0
func main() {
	file, _ := os.Getwd()
	//	log.Println("current path:", file)
	//	fmt.Println(os.Args[0])
	//	file, _ = exec.LookPath(os.Args[0])
	abs := fmt.Sprintf(`%s/metronic/templates/admin/extra_profile.html`, file)
	//	fmt.Println(abs)
	file, _ = exec.LookPath(fmt.Sprintf(`%smetronic/templates/admin/extra_profile.html`, file))
	//	fmt.Printf("%T", os.Args[0])
	//	fmt.Println(file)
	log.Println("exec path:", file)
	filename := path.Dir(abs)
	os.MkdirAll(filename, 0777)
	dir, _ := path.Split(file)
	log.Println("exec folder relative path:", dir)
	os.OpenFile(file, os.O_CREATE, 0777)
	os.Chdir(dir)
	wd, _ := os.Getwd()
	log.Println("exec folder absolute path:", wd)

	fmt.Println("\n")
	m := map[string]map[string]string{}
	m["dasdfsdf"]["dfsadfasf"] = "sdfdsfsfsfddsfww"
	if m["dasdfsssdf"] == "" {
		fmt.Println(m["dasdfsdf"])
	}

}
Exemple #7
0
func TestAbs(t *testing.T) {
	oldwd, err := os.Getwd()
	if err != nil {
		t.Fatal("Getwd failed: ", err)
	}
	defer os.Chdir(oldwd)

	root, err := ioutil.TempDir("", "TestAbs")
	if err != nil {
		t.Fatal("TempDir failed: ", err)
	}
	defer os.RemoveAll(root)

	wd, err := os.Getwd()
	if err != nil {
		t.Fatal("getwd failed: ", err)
	}
	err = os.Chdir(root)
	if err != nil {
		t.Fatal("chdir failed: ", err)
	}
	defer os.Chdir(wd)

	for _, dir := range absTestDirs {
		err = os.Mkdir(dir, 0777)
		if err != nil {
			t.Fatal("Mkdir failed: ", err)
		}
	}

	err = os.Chdir(absTestDirs[0])
	if err != nil {
		t.Fatal("chdir failed: ", err)
	}

	for _, path := range absTests {
		path = strings.Replace(path, "$", root, -1)
		info, err := os.Stat(path)
		if err != nil {
			t.Errorf("%s: %s", path, err)
			continue
		}

		abspath, err := filepath.Abs(path)
		if err != nil {
			t.Errorf("Abs(%q) error: %v", path, err)
			continue
		}
		absinfo, err := os.Stat(abspath)
		if err != nil || !os.SameFile(absinfo, info) {
			t.Errorf("Abs(%q)=%q, not the same file", path, abspath)
		}
		if !filepath.IsAbs(abspath) {
			t.Errorf("Abs(%q)=%q, not an absolute path", path, abspath)
		}
		if filepath.IsAbs(path) && abspath != filepath.Clean(path) {
			t.Errorf("Abs(%q)=%q, isn't clean", path, abspath)
		}
	}
}
Exemple #8
0
// ReadComposeVolumes reads a docker-compose.yml and return a slice of
// directories to sync into the Docker Host
//
// "." and "./." is converted to the current directory parity is running from.
// Any volume starting with "/" will be treated as an absolute path.
// All other volumes (e.g. starting with "./" or without a prefix "/") will be treated as
// relative paths.
func ReadComposeVolumes() []string {
	var volumes []string

	files := FindDockerComposeFiles()
	for i, file := range files {
		if _, err := os.Stat(file); err == nil {
			project, err := docker.NewProject(&docker.Context{
				Context: project.Context{
					ComposeFiles: []string{file},
					ProjectName:  fmt.Sprintf("parity-%d", i),
				},
			})

			if err != nil {
				log.Info("Could not parse compose file")
			}

			for _, c := range project.Configs {
				for _, v := range c.Volumes {
					v = strings.SplitN(v, ":", 2)[0]

					if v == "." || v == "./." {
						v, _ = os.Getwd()
					} else if strings.Index(v, "/") != 0 {
						cwd, _ := os.Getwd()
						v = fmt.Sprintf("%s/%s", cwd, v)
					}
					volumes = append(volumes, mutils.LinuxPath(v))
				}
			}
		}
	}

	return volumes
}
Exemple #9
0
func loadConfig() {
	var temp Config

	if err := decodeConfig(bytes.NewBufferString(defaultConfig), &temp); err != nil {
		log.Fatal(err)
	}

	//Look for a configuration file in the following order:
	// Environment:  MAPWRAP_CONFIG
	// Current Directory: mapwrap.json
	configFile := os.Getenv("MAPWRAP_CONFIG")
	if configFile == "" {
		cwd, err := os.Getwd()
		if err != nil {
			log.Fatal(err)
		}
		configFile = filepath.Join(cwd, "mapwrap.json")
	}

	f, err := os.Open(configFile)
	defer f.Close()

	if err != nil {
		log.Printf("Error opening configuration file: %s\n", configFile)
		log.Fatal(err)
	}

	if err := decodeConfig(f, &temp); err != nil {
		log.Printf("Error loading configuration file: %s\n", configFile)
		log.Fatal(err)
	}
	//Set the working directory if it's not already set
	if temp.Directory == "" {
		temp.Directory, err = os.Getwd()
		if err != nil {
			log.Fatal(err)
		}
	}
	//Make sure the directory exists
	_, err = os.Stat(temp.Directory)
	if err != nil {
		log.Fatal(err)
	}

	if temp.Mapserv == "" {
		out, err := exec.Command("which", "mapserv").Output()

		if err != nil {
			log.Fatal("Error attempting to find mapserv: ", err)
		}
		temp.Mapserv = string(out)
	}
	_, err = exec.Command(temp.Mapserv).Output()
	if err != nil {
		log.Fatal("Error attempting to run mapserv: ", err)
	}

	config = &temp

}
Exemple #10
0
func findEntomon() os.Error {
	origd, err := os.Getwd()
	if err != nil {
		// If we can't read our working directory, let's just fail!
		return err
	}
	oldd := origd
	for !isEntomonHere() {
		err = os.Chdir("..")
		if err != nil {
			// If we can't cd .. then we'll just use the original directory.
			goto giveup
		}
		newd, err := os.Getwd()
		if err != nil || newd == oldd {
			// Either something weird happened or we're at the root
			// directory.  In either case, we'll just go with the original
			// directory.
			goto giveup
		}
		oldd = newd
	}
	return nil
giveup:
	// If nothing else works we'll just use the original directory.
	err = os.Chdir(origd)
	if err != nil {
		return err
	}
	return os.MkdirAll(".entomon", 0777)
}
Exemple #11
0
// TODO(urgent): don't rely on os.Args[0]
func GetExeDir() (string, error) {
	// Path with which the exe was ran.
	arg := os.Args[0]

	// This is the absolute path.
	if arg[0] == '/' {
		return path.Dir(arg), nil
	}

	// Running from within directory.
	if arg[0] == '.' && arg[1] == '/' {
		curDir, err := os.Getwd()
		if err != nil {
			return "", err
		}

		return curDir, nil
	}

	if existsIn('/', arg) {
		curDir, err := os.Getwd()
		if err != nil {
			return "", err
		}

		return path.Dir(path.Join(curDir, arg)), nil
	}

	return "", errors.New("Could not find exe path.")
}
Exemple #12
0
func main() {
	if len(os.Args) > 1 {
		var err error
		if port, err = strconv.Atoi(os.Args[1]); err != nil {
			printUsage()
			return
		} else {
			if len(os.Args) > 2 {
				rootPath = os.Args[2]
				if rootStat, err := os.Stat(rootPath); err != nil || !rootStat.IsDir() {
					printUsage()
					return
				}
			} else {
				rootPath, _ = os.Getwd()
			}
		}
	} else {
		port = 80
		rootPath, _ = os.Getwd()
	}
	cacheFile = make(map[string]*FileRecord)
	go PeriodUpdate(periodSec)
	server := http.NewServeMux()
	server.HandleFunc("/", service)
	if err := http.ListenAndServe(":"+strconv.Itoa(port), server); err != nil {
		fmt.Println(err)
	}
}
Exemple #13
0
func TestDirUnix(t *testing.T) {
	if skipTest(t) || runtime.GOOS == "windows" {
		return
	}

	cwd, _ := os.Getwd()
	h := &Handler{
		Path: "testdata/test.cgi",
		Root: "/test.cgi",
		Dir:  cwd,
	}
	expectedMap := map[string]string{
		"cwd": cwd,
	}
	runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)

	cwd, _ = os.Getwd()
	cwd = filepath.Join(cwd, "testdata")
	h = &Handler{
		Path: "testdata/test.cgi",
		Root: "/test.cgi",
	}
	abswd, _ := filepath.EvalSymlinks(cwd)
	expectedMap = map[string]string{
		"cwd": abswd,
	}
	runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
}
Exemple #14
0
func TestDirUnix(t *testing.T) {
	check(t)
	if runtime.GOOS == "windows" {
		t.Skipf("skipping test on %q", runtime.GOOS)
	}
	cwd, _ := os.Getwd()
	h := &Handler{
		Path: "testdata/test.cgi",
		Root: "/test.cgi",
		Dir:  cwd,
	}
	expectedMap := map[string]string{
		"cwd": cwd,
	}
	runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)

	cwd, _ = os.Getwd()
	cwd = filepath.Join(cwd, "testdata")
	h = &Handler{
		Path: "testdata/test.cgi",
		Root: "/test.cgi",
	}
	expectedMap = map[string]string{
		"cwd": cwd,
	}
	runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
}
func main() {
	mypath, _ := os.Getwd()
	println(mypath + ":" + os.Args[0])
	d, _ := path.Split(os.Args[0])
	os.Chdir(d)
	fmt.Println(os.Getwd())
	mypath, _ = os.Getwd()
	println(mypath + ":" + os.Args[0])
	mybytes := make(TestBytes, 100)
	println(mybytes)
	processMap["server"] = &Command{name: "server", command: "mhive", dir: mypath, args: []string{"mhive", "-r"}}
	processMap["client"] = &Command{name: "client", command: "mhive", dir: mypath, args: []string{"mhive", "-i"}}
	processMap["web"] = &Command{name: "web", command: "mhive", dir: mypath, args: []string{"mhive", "-w"}}

	flag.Parse()
	if flag.Arg(0) == "s" {
		fmt.Println("starting server")
		//go processListener(processMap)
		server()
		<-make(chan int)
	} else if flag.Arg(0) == "stop" {
		fmt.Println("stopping client")
		stopclient("localhost", 1234)
	} else {
		fmt.Println("starting client")
		client(flag.Arg(0), 1234)
	}
}
func LoadConfig(cfgfile string) (*Config, error) {
	var (
		cfg *Config
		err error
		wd  string
	)

	if cfg, err = loadJsonConfig(cfgfile); err != nil {
		return cfg, err
	}

	if cfg.Http.Webroot != "" && !strings.HasPrefix(cfg.Http.Webroot, "/") {
		if wd, err = os.Getwd(); err == nil {
			cfg.Http.Webroot = wd + "/" + cfg.Http.Webroot
		} else {
			return cfg, err
		}
	}

	if !strings.HasPrefix(cfg.Http.ClientConf, "/") {
		if wd, err = os.Getwd(); err == nil {
			cfg.Http.ClientConf = wd + "/" + cfg.Http.ClientConf
		} else {
			return cfg, err
		}
	}

	return cfg, nil
}
Exemple #17
0
func main() {
	flag.Usage = usage
	flag.Parse()

	args := flag.Args()

	switch len(args) {
	case 0:
		root, _ = os.Getwd()
	case 1:
		temp := path.Clean(args[0])
		if temp[0] != '/' {
			cwd, _ := os.Getwd()
			root = path.Join(cwd, temp)
		} else {
			root = temp
		}
	default:
		usage()
	}

	err := initWindow()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		return
	}

	for word := range events() {
		if len(word) >= 6 && word[0:6] == "DotDot" {
			doDotDot()
			continue
		}
		if len(word) >= 6 && word[0:6] == "Hidden" {
			toggleHidden()
			continue
		}
		if len(word) >= 3 && word[0:3] == "Win" {
			if PLAN9 != "" {
				cmd := path.Join(PLAN9, "bin/win")
				doExec(word[3:len(word)], cmd)
			}
			continue
		}
		// yes, this does not cover all possible cases. I'll do better if anyone needs it.
		if len(word) >= 5 && word[0:5] == "Xplor" {
			cmd, err := exec.LookPath("xplor")
			if err != nil {
				fmt.Fprintf(os.Stderr, err.Error())
				continue
			}
			doExec(word[5:len(word)], cmd)
			continue
		}
		if word[0] == 'X' {
			onExec(word[1:len(word)])
			continue
		}
		onLook(word)
	}
}
Exemple #18
0
func main() {
	flag.Usage = Usage
	flag.Parse()

	if *showVersion {
		fmt.Println("Version - ", version)
		return
	}

	if *port == "" || *remote == "" {
		flag.Usage()
		os.Exit(1)
	}

	if !*skipVerCheck {
		if vercheck.HasMinorUpdate(
			"https://raw.github.com/ciju/gotunnel/master/VERSION",
			version,
		) {
			l.Info("\nNew version of Gotunnel is available. Please update your code and run again. Or start with option -sc to continue with this version.\n")
			os.Exit(0)
		}
	}

	if *fileServer {
		dir := ""
		// Simple file server.
		if *port == "" {
			fmt.Fprintf(os.Stderr, "-fs needs -p (port) option")
			flag.Usage()
			os.Exit(1)
		}
		if *serveDir == "" {
			dir, _ = os.Getwd()
		} else {
			if path.IsAbs(*serveDir) {
				dir = path.Clean(*serveDir)
			} else {
				wd, _ := os.Getwd()
				dir = path.Clean(path.Join(wd, *serveDir))
			}
		}
		go hs.NewSimpleHTTPServer(*port, dir)
	}

	servInfo := make(chan string)

	go func() {
		serverat := <-servInfo
		fmt.Printf("Your site should be available at: \033[1;34m%s\033[0m\n", serverat)
	}()

	if !gtclient.SetupClient(*port, *remote, *subdomain, servInfo) {
		flag.Usage()
		os.Exit(1)
	} else {
		os.Exit(0)
	}
}
Exemple #19
0
func main() {
	flag.Parse()

	// Open a new logger with an appropriate log level.
	if *fQuiet {
		LogLevel = -1 // Disable ALL output
		//	} else if *fVerbose {
		//		LogLevel = log.INFO
	} else if *fDebug {
		LogLevel = log.DEBUG
	}
	l, _ = log.NewLevel(LogLevel, true, os.Stdout, "", log.Ltime)

	// If any of the 'show' flags are set, print the relevant variable
	// and exit.
	switch {
	case *fShowVersion:
		l.Println(Version)
		return
	case *fShowFVersion:
		l.Println(Version)
		return
	case *fShowBind:
		l.Println(Bind)
		return
	case *fShowPort:
		l.Println(Port)
		return
	case *fShowRes:
		l.Println(Resources)
		return
	}

	l.Infof("Starting Grove version %s\n", Version)

	var repodir string
	if flag.NArg() > 0 {
		repodir = path.Clean(flag.Arg(0))

		if !path.IsAbs(repodir) {
			wd, err := os.Getwd()
			if err != nil {
				l.Fatalf("Error getting working directory: %s\n", err)
			}
			repodir = path.Join(wd, repodir)
		}
	} else {
		wd, err := os.Getwd()
		if err != nil {
			l.Fatalf("Error getting working directory: %s\n", err)
		}
		repodir = wd
	}

	Serve(repodir)
}
Exemple #20
0
func main() {
	args := os.Args[1:]

	if len(args) < 1 {
		fmt.Println("Usage: goexec [-w work_path] <program_name> [arguments...]")
		os.Exit(0)
	}

	var workPath string
	var fileName string

	if args[0] == "-w" {
		if len(args) < 3 {
			fmt.Println("Usage: goexec [-w work_path] <program_name> [arguments...]")
			os.Exit(0)
		}
		workPath = args[1]
		fileName = args[2]
		args = args[2:]
		if len(workPath) > 0 && workPath[0] == '.' {
			wd, err := os.Getwd()
			if err == nil {
				workPath = path.Join(wd, workPath)
			}
		}
	} else {
		workPath, _ = os.Getwd()
		fileName = args[0]
	}
	filePath, err := exec.LookPath(fileName)
	if err != nil {
		filePath, err = exec.LookPath("./" + fileName)
	}
	if err != nil {
		fmt.Println(err)
		wait_exit()
	}

	fmt.Println("---- Starting Process", filePath, strings.Join(args[1:], " "), "----")

	cmd := exec.Command(filePath, args[1:]...)
	cmd.Dir = workPath
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	err = cmd.Run()

	if err != nil {
		fmt.Println("\n---- End Process", err, "----")
	} else {
		fmt.Println("\n---- End Process", "exit status 0", "----")
	}

	wait_exit()
}
Exemple #21
0
func main() {
	func() {
		wd, err := os.Getwd()
		if err != nil {
			panic(err)
		}
		cf, err := ioutil.TempFile(wd, "hello")
		if err != nil {
			panic(err)
		}
		fmt.Println(cf.Name())
		os.Remove(cf.Name())
	}()

	func() {
		wd, err := os.Getwd()
		if err != nil {
			panic(err)
		}
		cf, err := ioutil.TempFile(wd, "hello")
		if err != nil {
			panic(err)
		}
		op := cf.Name()
		os.Rename(op, "new_name")
		fmt.Println(op, "to new_name")
		os.Remove("new_name")
	}()

	func() {
		tmp := os.TempDir()
		f, err := ioutil.TempFile(tmp, "hello")
		if err != nil {
			panic(err)
		}
		fpath, err := filepath.Abs(f.Name())
		if err != nil {
			panic(err)
		}
		fmt.Println(fpath)

		wd, err := os.Getwd()
		if err != nil {
			panic(err)
		}
		npath := filepath.Join(wd, "hello")
		if err := copy(fpath, npath); err != nil {
			panic(err)
		}

		os.Remove(fpath)
		os.Remove(npath)
	}()
}
Exemple #22
0
func main() {
	dir, _ := os.Getwd()
	fmt.Println(dir)
	f, _ := os.Open("views")
	err := f.Chdir()
	if err != nil {
		fmt.Println(err)
	}
	dir1, _ := os.Getwd()
	fmt.Println(dir1)
}
Exemple #23
0
func main() {
	// Normally this is run via go:generate from the command folder so we need
	// to cd .. first. But when developing it's easier to use go run, so we'll
	// support that too.
	wd, _ := os.Getwd()
	if filepath.Base(wd) != "packer" {
		os.Chdir("..")
		wd, _ = os.Getwd()
		if filepath.Base(wd) != "packer" {
			log.Fatalf("This program must be invoked in the packer project root; in %s", wd)
		}
	}

	// Collect all of the data we need about plugins we have in the project
	builders, err := discoverBuilders()
	if err != nil {
		log.Fatalf("Failed to discover builders: %s", err)
	}

	provisioners, err := discoverProvisioners()
	if err != nil {
		log.Fatalf("Failed to discover provisioners: %s", err)
	}

	postProcessors, err := discoverPostProcessors()
	if err != nil {
		log.Fatalf("Failed to discover post processors: %s", err)
	}

	// Do some simple code generation and templating
	output := source
	output = strings.Replace(output, "IMPORTS", makeImports(builders, provisioners, postProcessors), 1)
	output = strings.Replace(output, "BUILDERS", makeMap("Builders", "Builder", builders), 1)
	output = strings.Replace(output, "PROVISIONERS", makeMap("Provisioners", "Provisioner", provisioners), 1)
	output = strings.Replace(output, "POSTPROCESSORS", makeMap("PostProcessors", "PostProcessor", postProcessors), 1)

	// TODO sort the lists of plugins so we are not subjected to random OS ordering of the plugin lists
	// TODO format the file

	// Write our generated code to the command/plugin.go file
	file, err := os.Create(target)
	defer file.Close()
	if err != nil {
		log.Fatalf("Failed to open %s for writing: %s", target, err)
	}

	_, err = file.WriteString(output)
	if err != nil {
		log.Fatalf("Failed writing to %s: %s", target, err)
	}

	log.Printf("Generated %s", target)
}
Exemple #24
0
// processConfigOptions processes the options --print-config and --write-config
func (o *Options) processConfigOptions() error {
	if o.PrintConfig {
		if homedir := getHomeDir(); homedir != "" {
			globalConfigFilePath := filepath.Join(homedir, SiftConfigFile)
			fmt.Fprintf(os.Stderr, "Global config file path: %s\n", globalConfigFilePath)
		} else {
			errorLogger.Println("could not detect user home directory.")
		}

		curdir, err := os.Getwd()
		if err != nil {
			curdir = "."
		}
		localConfigFilePath := filepath.Join(curdir, SiftConfigFile)
		fmt.Fprintf(os.Stderr, "Local config file path: %s\n", localConfigFilePath)

		conf, err := json.MarshalIndent(o, "", "    ")
		if err != nil {
			return fmt.Errorf("cannot convert config to JSON: %s", err)
		}
		fmt.Println(string(conf))
		os.Exit(0)
	}

	if o.WriteConfig {
		var configFilePath string
		curdir, err := os.Getwd()
		if err != nil {
			curdir = "."
		}
		if _, err := os.Stat(filepath.Join(curdir, SiftConfigFile)); err == nil {
			configFilePath = filepath.Join(curdir, SiftConfigFile)
		} else {
			if user, err := user.Current(); err == nil {
				configFilePath = filepath.Join(user.HomeDir, SiftConfigFile)
			} else {
				return errors.New("could not detect user home directory")
			}
		}
		conf, err := json.MarshalIndent(o, "", "    ")
		if err != nil {
			return fmt.Errorf("cannot convert config to JSON: %s", err)
		}
		if err := ioutil.WriteFile(configFilePath, conf, os.ModePerm); err != nil {
			return fmt.Errorf("cannot write config file: %s", err)
		}
		fmt.Printf("Saved config to '%s'.\n", configFilePath)
		os.Exit(0)
	}

	return nil
}
Exemple #25
0
/**
New 基于资源路径 uri 新建一个 Template.
先对 uri 进行绝对路径计算, 计算出 rootdir 和是否要加载文件.

参数:
	uri 资源路径可以是目录或者文件, 无扩展名当作目录, 否则当作文件.
		如果 uri 为空, 用 os.Getwd() 获取目录.
		如果 uri 以 `./` 或 `.\` 开头自动加当前路径, 否则当作绝对路径.
		如果 uri 含扩展当作模板文件, 使用 ParseFiles 解析.
		uri 所指的目录被设置为 rootdir, 后续载入的文件被限制在此目录下.

	funcMap 可选自定义 FuncMap.
		当 uri 为文件时, funcMap 参数可保障正确解析模板中的函数.
返回:
	模板实例和发生的错误.
*/
func New(uri string, funcMap ...FuncMap) (*Template, error) {

	var err error

	if uri == "" {
		uri, err = os.Getwd()
		if err != nil {
			return nil, err
		}
	} else if len(uri) > 1 && (uri[:2] == `./` ||
		uri[:2] == `.\`) {

		dir, err := os.Getwd()
		if err != nil {
			return nil, err
		}
		uri = dir + `/` + uri
	}

	rootdir := cleanURI(uri)
	if rootdir == "" {
		return nil, fmt.Errorf("template: invalid uri: %q", uri)
	}

	ext := path.Ext(rootdir)

	t := &Template{
		text: newText(),
		html: newHtml(),
	}

	if ext == "" {
		t.base = newBase(rootdir)
	} else {
		t.base = newBase(path.Dir(rootdir))
	}

	t.initFuncs() // init import

	for _, funcs := range funcMap {
		t.Funcs(funcs)
	}

	if ext != "" {
		err = t.ParseFiles(rootdir)
	}

	if err != nil {
		return nil, err
	}
	return t, nil
}
Exemple #26
0
func (ts *HTestSuite) TestChdir(c *C) {
	tmpdir := c.MkDir()

	cwd, err := os.Getwd()
	c.Assert(err, IsNil)
	c.Assert(cwd, Not(Equals), tmpdir)
	ChDir(tmpdir, func() error {
		cwd, err := os.Getwd()
		c.Assert(err, IsNil)
		c.Assert(cwd, Equals, tmpdir)
		return err
	})
}
Exemple #27
0
func main() {

	// カレントディレクトリを取得し出力
	current, _ := os.Getwd()
	fmt.Println(current)

	// カレントディレクトリを親ディレクトリに変更
	os.Chdir("..")

	// 再びカレントディレクトリを出力
	current, _ = os.Getwd()
	fmt.Println(current)
}
Exemple #28
0
func TestStartupInHomeDir(t *testing.T) {

	cv.Convey("On 'goq serve' startup, the process should Chdir to GOQ_HOME", t, func() {

		var jobserv *JobServ
		var err error
		var jobservPid int
		remote := false

		// *** universal test cfg setup
		skipbye := false

		// this will move us to a new tempdir
		cfg := NewTestConfig()

		// now move away so we can check that there is a Chdir
		cv.So(cfg.tempdir, cv.ShouldNotEqual, cfg.origdir)

		err = os.Chdir("..")
		if err != nil {
			panic(err)
		}
		pwd, err := os.Getwd()
		if err != nil {
			panic(err)
		}
		cv.So(pwd, cv.ShouldNotEqual, cfg.Home)

		defer cfg.ByeTestConfig(&skipbye)
		// *** end universal test setup

		cfg.DebugMode = true // reply to badsig packets

		// local only, because we use Getwd() to see what dir we are in.
		jobserv, err = NewJobServ(cfg)
		if err != nil {
			panic(err)
		}
		defer CleanupServer(cfg, jobservPid, jobserv, remote, &skipbye)
		defer CleanupOutdir(cfg)

		pwd, err = os.Getwd()
		if err != nil {
			panic(err)
		}
		epwd, _ := filepath.EvalSymlinks(pwd)
		ecfg, _ := filepath.EvalSymlinks(cfg.Home)

		cv.So(epwd, cv.ShouldEqual, ecfg)
	})
}
Exemple #29
0
func getPackageName(impPath, srcPath string) (string, error) {
	// Special case for the magic "C" package
	if impPath == "C" {
		return "", nil
	}

	name, found := pkgNames[impPath]
	if found {
		return name, nil
	}

	cache := true
	lookupPath := impPath

	if strings.HasPrefix(impPath, "./") {
		// relative import, no caching, need to change directory
		cwd, err := os.Getwd()
		if err != nil {
			return "", err
		}
		defer os.Chdir(cwd)

		os.Chdir(srcPath)
		cache = false
	}

	if strings.HasPrefix(impPath, "_/") {
		// outside of GOPATH, need to change directory and use "." for the
		// lookup path

		cwd, err := os.Getwd()
		if err != nil {
			return "", err
		}
		defer os.Chdir(cwd)

		os.Chdir(impPath[1:])
		lookupPath = "."
	}

	name, err := GetOutput("go", "list", "-f", "{{.Name}}", lookupPath)
	if err != nil {
		return "", fmt.Errorf("Failed to get name for '%s': %s", impPath, err)
	}

	if cache {
		pkgNames[impPath] = name
	}

	return name, nil
}
Exemple #30
0
func TestIn(t *testing.T) {
	var output bytes.Buffer
	old, _ := os.Getwd()
	if runtime.GOOS == "windows" {
		Call("foo.cmd").In("test").Pipe(Stdout, &output).Run()
	} else {
		Call("bash foo.sh").In("test").Pipe(Stdout, &output).Run()
	}

	assert.Equal(t, "FOOBAR", strings.Trim(output.String(), " "))

	now, _ := os.Getwd()
	assert.Equal(t, now, old, "In failed to reset work directory")
}