Golang SplitList示例

说明

golang splitlist示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: path/filepath

示例#1
文件: doc.go 项目: dsnet/gotab

// Expand GOROOT and GOPATH with respect to some dirPath.
func makePaths(dirPath string) (paths []string) {
	if strings.HasPrefix(dirPath, ".") {
		cwd, err := os.Getwd()
		if err != nil {
			log.Fatal(err)
		}
		dirPath = filepath.Join(cwd, dirPath[1:])
		for _, dir := range filepath.SplitList(build.Default.GOPATH) {
			if dir != "" && strings.HasPrefix(cwd, dir) {
				paths = append(paths, dirPath)
			}
		}
		return
	}
	// TODO(jtsai): Can dirPath be an absolute path?
	for _, dir := range filepath.SplitList(build.Default.GOPATH) {
		if dir != "" {
			paths = append(paths, path.Join(dir, "src", dirPath))
		}
	}
	if dir := build.Default.GOROOT; dir != "" {
		paths = append(paths, path.Join(dir, "src", dirPath))
	}
	return
}

示例#2
文件: basedir.go 项目: rkoesters/xdg

func init() {
	Home = os.Getenv("HOME")
	if Home == "" {
		u, err := user.Current()
		if err == nil {
			Home = u.HomeDir
		} else {
			Home = filepath.Join(os.TempDir(), os.Args[0])
		}
	}

	DataHome = getenv("XDG_DATA_HOME", filepath.Join(Home, ".local/share"))
	ConfigHome = getenv("XDG_CONFIG_HOME", filepath.Join(Home, ".config"))
	CacheHome = getenv("XDG_CACHE_HOME", filepath.Join(Home, ".cache"))
	RuntimeDir = getenv("XDG_RUNTIME_DIR", CacheHome)

	DataDirs = filepath.SplitList(os.Getenv("XDG_DATA_DIRS"))
	if len(DataDirs) == 0 {
		DataDirs = []string{"/usr/local/share", "/usr/share"}
	}

	ConfigDirs = filepath.SplitList(os.Getenv("XDG_CONFIG_DIRS"))
	if len(ConfigDirs) == 0 {
		ConfigDirs = []string{"/etc/xdg"}
	}
}

示例#3
文件: toolchain_cmd.go 项目: vkz/srclib

func symlinkToGopath(toolchain string) (skip string, err error) {
	gopath := os.Getenv("GOPATH")
	if gopath == "" {
		return "", fmt.Errorf("GOPATH not set")
	}

	srcDir := filepath.Join(filepath.SplitList(gopath)[0], "src")
	gopathDir := filepath.Join(srcDir, toolchain)
	srclibpathDir := filepath.Join(filepath.SplitList(srclib.Path)[0], toolchain)

	if fi, err := os.Lstat(gopathDir); os.IsNotExist(err) {
		log.Printf("mkdir -p %s", filepath.Dir(gopathDir))
		if err := os.MkdirAll(filepath.Dir(gopathDir), 0700); err != nil {
			return "", err
		}
		log.Printf("ln -s %s %s", srclibpathDir, gopathDir)
		if err := os.Symlink(srclibpathDir, gopathDir); err != nil {
			log.Printf("Symlink failed %s", err)
			return "", err
		}
	} else if err != nil {
		return "", err
	} else if fi.Mode()&os.ModeSymlink == 0 {
		return fmt.Sprintf("toolchain dir in GOPATH (%s) is not a symlink (assuming you intentionally cloned the toolchain repo to your GOPATH; not modifying it)", gopathDir), nil
	}

	log.Printf("Symlinked toolchain %s into your GOPATH at %s", toolchain, gopathDir)
	return "", nil
}

示例#4
文件: config.go 项目: qbit/client

func mergeIntoPath(g *libkb.GlobalContext, p2 string) error {

	svcPath := os.Getenv("PATH")
	g.Log.Debug("mergeIntoPath: service path = %s", svcPath)
	g.Log.Debug("mergeIntoPath: merge path   = %s", p2)

	pathenv := filepath.SplitList(svcPath)
	pathset := make(map[string]bool)
	for _, p := range pathenv {
		pathset[p] = true
	}

	var clientAdditions []string
	for _, dir := range filepath.SplitList(p2) {
		if _, ok := pathset[dir]; ok {
			continue
		}
		clientAdditions = append(clientAdditions, dir)
	}

	pathenv = append(pathenv, clientAdditions...)
	combined := strings.Join(pathenv, string(os.PathListSeparator))

	if combined == svcPath {
		g.Log.Debug("No path changes needed")
		return nil
	}

	g.Log.Debug("mergeIntoPath: merged path = %s", combined)
	os.Setenv("PATH", combined)
	return nil
}

示例#5
文件: toolchain_cmd.go 项目: ildarisaev/srclib-go

func symlinkToGopath(toolchain string) error {
	gopath := os.Getenv("GOPATH")
	if gopath == "" {
		return fmt.Errorf("GOPATH not set")
	}

	srcDir := filepath.Join(filepath.SplitList(gopath)[0], "src")
	gopathDir := filepath.Join(srcDir, toolchain)
	srclibpathDir := filepath.Join(filepath.SplitList(srclib.Path)[0], toolchain)

	if fi, err := os.Lstat(gopathDir); os.IsNotExist(err) {
		log.Printf("mkdir -p %s", filepath.Dir(gopathDir))
		if err := os.MkdirAll(filepath.Dir(gopathDir), 0700); err != nil {
			return err
		}
		log.Printf("ln -s %s %s", srclibpathDir, gopathDir)
		if err := os.Symlink(srclibpathDir, gopathDir); err != nil {
			return err
		}
	} else if err != nil {
		return err
	} else if fi.Mode()&os.ModeSymlink == 0 {
		// toolchain dir in GOPATH is not a symlink, so assume they
		// intentionally cloned the toolchain repo into their GOPATH.
		return nil
	}

	log.Printf("Symlinked toolchain %s into your GOPATH at %s", toolchain, gopathDir)
	return nil
}

示例#6
文件: declcache.go 项目: uvelichitel/compl

func find_global_file(imp string, env *gocode_env) (string, bool) {
	// gocode synthetically generates the builtin package
	// "unsafe", since the "unsafe.a" package doesn't really exist.
	// Thus, when the user request for the package "unsafe" we
	// would return synthetic global file that would be used
	// just as a key name to find this synthetic package
	if imp == "unsafe" {
		return "unsafe", true
	}

	pkgfile := fmt.Sprintf("%s.a", imp)

	// if lib-path is defined, use it
	if g_config.LibPath != "" {
		for _, p := range filepath.SplitList(g_config.LibPath) {
			pkg_path := filepath.Join(p, pkgfile)
			if file_exists(pkg_path) {
				return pkg_path, true
			}
		}
	}
	pkgdir := fmt.Sprintf("%s_%s", env.GOOS, env.GOARCH)
	pkgpath := filepath.Join("pkg", pkgdir, pkgfile)

	if env.GOPATH != "" {
		for _, p := range filepath.SplitList(env.GOPATH) {
			gopath_pkg := filepath.Join(p, pkgpath)
			if file_exists(gopath_pkg) {
				return gopath_pkg, true
			}
		}
	}
	goroot_pkg := filepath.Join(env.GOROOT, pkgpath)
	return goroot_pkg, file_exists(goroot_pkg)
}

示例#7
文件: cov_test.go 项目: BenLubar/goveralls

func TestParseCov(t *testing.T) {
	if output, err := exec.Command("go", "get", "github.com/axw/gocov/gocov").CombinedOutput(); err != nil {
		t.Log(string(output))
		t.Fatal(err)
		return
	}

	path := filepath.SplitList(os.Getenv("PATH"))
	for _, gopath := range filepath.SplitList(os.Getenv("GOPATH")) {
		path = append(path, filepath.Join(gopath, "bin"))
	}
	os.Setenv("PATH", strings.Join(path, string(filepath.ListSeparator)))

	cmd := exec.Command("gocov", "test", "github.com/BenLubar/goveralls/goveralls-test")
	cmd.Stderr = os.Stderr
	cov, err := cmd.Output()
	if err != nil {
		t.Fatal(err)
		return
	}

	wd, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
		return
	}

	files := ParseCov(cov, wd)
	if err != nil {
		t.Fatal(err)
		return
	}

	expectedJson, err := ioutil.ReadFile("goveralls-test/expected.json")
	if err != nil {
		t.Fatal(err)
		return
	}
	var expected []*File
	err = json.Unmarshal(expectedJson, &expected)
	if err != nil {
		t.Fatal(err)
		return
	}

	filesJson, _ := json.Marshal(files)
	expectedJson, _ = json.Marshal(expected)
	if !bytes.Equal(filesJson, expectedJson) {
		t.Errorf("Actual:  \t%q", filesJson)
		t.Errorf("Expected:\t%q", expectedJson)
	}
}

示例#8
文件: declcache.go 项目: ntcong/sublime-text-2-config

func find_global_file(imp string) (string, bool) {
	// gocode synthetically generates the builtin package
	// "unsafe", since the "unsafe.a" package doesn't really exist.
	// Thus, when the user request for the package "unsafe" we
	// would return synthetic global file that would be used
	// just as a key name to find this synthetic package
	if imp == "unsafe" {
		return "unsafe", true
	}

	pkgfile := fmt.Sprintf("%s.a", imp)

	// if lib-path is defined, use it
	if g_config.LibPath != "" {
		for _, p := range filepath.SplitList(g_config.LibPath) {
			pkg_path := filepath.Join(p, pkgfile)
			if file_exists(pkg_path) {
				return pkg_path, true
			}
		}
	}

	// otherwise figure out the default lib-path
	gopath := os.Getenv("GOPATH")
	goroot := os.Getenv("GOROOT")
	goarch := os.Getenv("GOARCH")
	goos := os.Getenv("GOOS")
	if goroot == "" {
		goroot = runtime.GOROOT()
	}
	if goarch == "" {
		goarch = runtime.GOARCH
	}
	if goos == "" {
		goos = runtime.GOOS
	}

	pkgdir := fmt.Sprintf("%s_%s", goos, goarch)
	pkgpath := filepath.Join("pkg", pkgdir, pkgfile)

	if gopath != "" {
		for _, p := range filepath.SplitList(gopath) {
			gopath_pkg := filepath.Join(p, pkgpath)
			if file_exists(gopath_pkg) {
				return gopath_pkg, true
			}
		}
	}
	goroot_pkg := filepath.Join(goroot, pkgpath)
	return goroot_pkg, file_exists(goroot_pkg)
}

示例#9
文件: config.go 项目: ildarisaev/srclib-go

// apply applies the configuration.
func (c *srcfileConfig) apply() error {
	var versionValid bool
	for _, v := range validVersions {
		if config.GOVERSION == v {
			versionValid = true
			goBinaryName = fmt.Sprintf("go%s", config.GOVERSION)
			if config.GOVERSION != "" && config.GOROOT == "" {
				// If GOROOT is empty, assign $GOROOT<version_num> to it.
				newGOROOT := os.Getenv(fmt.Sprintf("GOROOT%s", strings.Replace(config.GOVERSION, ".", "", -1)))
				if newGOROOT != "" {
					config.GOROOTForCmd = newGOROOT
				}
			}
			break
		}
	}
	if !versionValid {
		return fmt.Errorf("The version %s is not valid. Use one of the following: %v", config.GOVERSION, validVersions)
	}

	if config.GOROOT != "" {
		// clean/absolutize all paths
		config.GOROOT = filepath.Clean(config.GOROOT)
		if !filepath.IsAbs(config.GOROOT) {
			config.GOROOT = filepath.Join(cwd, config.GOROOT)
		}

		buildContext.GOROOT = c.GOROOT
		loaderConfig.Build = &buildContext
	}

	if config.GOPATH != "" {
		// clean/absolutize all paths
		dirs := cleanDirs(filepath.SplitList(config.GOPATH))
		config.GOPATH = strings.Join(dirs, string(filepath.ListSeparator))

		dirs = append(dirs, filepath.SplitList(buildContext.GOPATH)...)
		buildContext.GOPATH = strings.Join(uniq(dirs), string(filepath.ListSeparator))
		loaderConfig.Build = &buildContext
	}

	config.VendorDirs = cleanDirs(config.VendorDirs)

	if config.GOROOTForCmd == "" {
		config.GOROOTForCmd = buildContext.GOROOT
	}

	return nil
}

示例#10
文件: localcluster.go 项目: danieldeb/cockroach

func defaultBinary() string {
	gopath := filepath.SplitList(os.Getenv("GOPATH"))
	if len(gopath) == 0 {
		return ""
	}
	return gopath[0] + "/bin/linux_amd64/cockroach"
}

示例#11
文件: which.go 项目: ngpestelos/someutils

func Which(call []string) error {
	options := WhichOptions{}
	flagSet := uggo.NewFlagSetDefault("which", "[-a] args", VERSION)
	flagSet.BoolVar(&options.all, "a", false, "Print all matching executables in PATH, not just the first.")

	err := flagSet.Parse(call[1:])
	if err != nil {
		println("Error parsing flags")
		return err
	}
	if flagSet.ProcessHelpOrVersion() {
		return nil
	}

	args := flagSet.Args()
	path := os.Getenv("PATH")
	if runtime.GOOS == "windows" {
		path = ".;" + path
	}
	pl := filepath.SplitList(path)
	for _, arg := range args {
		checkPathParts(arg, pl, options)
		/*
			if err != nil {
				return err
			}*/
	}
	return nil
}

示例#12
文件: bind_test.go 项目: andreinechaev/mobile

func TestBindAndroid(t *testing.T) {
	if os.Getenv("ANDROID_HOME") == "" {
		t.Skip("ANDROID_HOME not found, skipping bind")
	}

	buf := new(bytes.Buffer)
	defer func() {
		xout = os.Stderr
		buildN = false
		buildX = false
	}()
	xout = buf
	buildN = true
	buildX = true
	buildO = "asset.aar"
	buildTarget = "android"
	gopath = filepath.SplitList(os.Getenv("GOPATH"))[0]
	if goos == "windows" {
		os.Setenv("HOMEDRIVE", "C:")
	}
	cmdBind.flag.Parse([]string{"github.com/c-darwin/mobile/asset"})
	err := runBind(cmdBind)
	if err != nil {
		t.Log(buf.String())
		t.Fatal(err)
	}

	diff, err := diffOutput(buf.String(), bindAndroidTmpl)
	if err != nil {
		t.Fatalf("computing diff failed: %v", err)
	}
	if diff != "" {
		t.Errorf("unexpected output:\n%s", diff)
	}
}

示例#13
文件: build_test.go 项目: pankona/mobile

func TestAndroidBuild(t *testing.T) {
	buf := new(bytes.Buffer)
	defer func() {
		xout = os.Stderr
		buildN = false
		buildX = false
	}()
	xout = buf
	buildN = true
	buildX = true
	buildO = "basic.apk"
	buildTarget = "android"
	gopath = filepath.ToSlash(filepath.SplitList(os.Getenv("GOPATH"))[0])
	if goos == "windows" {
		os.Setenv("HOMEDRIVE", "C:")
	}
	cmdBuild.flag.Parse([]string{"golang.org/x/mobile/example/basic"})
	ctx.BuildTags = []string{"tag1"}
	err := runBuild(cmdBuild)
	if err != nil {
		t.Log(buf.String())
		t.Fatal(err)
	}

	diff, err := diffOutput(buf.String(), androidBuildTmpl)
	if err != nil {
		t.Fatalf("computing diff failed: %v", err)
	}
	if diff != "" {
		t.Errorf("unexpected output:\n%s", diff)
	}
}

示例#14
文件: lp_unix.go 项目: Xiahl1990/go

// LookPath searches for an executable binary named file
// in the directories named by the PATH environment variable.
// If file contains a slash, it is tried directly and the PATH is not consulted.
// The result may be an absolute path or a path relative to the current directory.
func LookPath(file string) (string, error) {
	// NOTE(rsc): I wish we could use the Plan 9 behavior here
	// (only bypass the path if file begins with / or ./ or ../)
	// but that would not match all the Unix shells.

	if strings.Contains(file, "/") {
		err := findExecutable(file)
		if err == nil {
			return file, nil
		}
		return "", &Error{file, err}
	}
	path := os.Getenv("PATH")
	for _, dir := range filepath.SplitList(path) {
		if dir == "" {
			// Unix shell semantics: path element "" means "."
			dir = "."
		}
		path := filepath.Join(dir, file)
		if err := findExecutable(path); err == nil {
			return path, nil
		}
	}
	return "", &Error{file, ErrNotFound}
}

示例#15
文件: main.go 项目: kisielk/vendorize

func main() {
	flag.BoolVar(&fake, "n", false, "If true, don't actually do anything")
	flag.BoolVar(&verbose, "v", false, "Provide verbose output")
	flag.Var(&ignorePrefixes, "ignore", "Package prefix to ignore. Can be given multiple times.")
	flag.Parse()

	gopaths := filepath.SplitList(os.Getenv("GOPATH"))
	if len(gopaths) == 0 {
		log.Fatal("GOPATH must be set")
	}
	pkgName := flag.Arg(0)
	if pkgName == "" {
		log.Fatal("need a package name")
	}
	dest := flag.Arg(1)
	if dest == "" {
		log.Fatal("need a destination path")
	}

	ignorePrefixes = append(ignorePrefixes, pkgName)
	ignorePrefixes = append(ignorePrefixes, dest)
	rewrites = make(map[string]string)
	visited = make(map[string]bool)

	err := vendorize(pkgName, chooseGOPATH(gopaths, dest), dest)
	if err != nil {
		log.Fatal(err)
	}
}

示例#16
文件: build.go 项目: bac/juju

func findExecutable(execFile string) (string, error) {
	logger.Debugf("looking for: %s", execFile)
	if filepath.IsAbs(execFile) {
		return execFile, nil
	}

	dir, file := filepath.Split(execFile)

	// Now we have two possibilities:
	//   file == path indicating that the PATH was searched
	//   dir != "" indicating that it is a relative path

	if dir == "" {
		path := os.Getenv("PATH")
		for _, name := range filepath.SplitList(path) {
			result := filepath.Join(name, file)
			// Use exec.LookPath() to check if the file exists and is executable`
			f, err := exec.LookPath(result)
			if err == nil {
				return f, nil
			}
		}

		return "", fmt.Errorf("could not find %q in the path", file)
	}
	cwd, err := os.Getwd()
	if err != nil {
		return "", err
	}
	return filepath.Clean(filepath.Join(cwd, execFile)), nil
}

示例#17
文件: toolchain_cmd.go 项目: ildarisaev/srclib-go

func installBasicToolchain() error {
	const toolchain = "sourcegraph.com/sourcegraph/srclib-basic"

	reqCmds := []string{"java"}
	for _, cmd := range reqCmds {
		if _, err := exec.LookPath(cmd); isExecErrNotFound(err) {
			return fmt.Errorf(`
Refusing to install Basic toolchain because %s is not installed or is not on the system path.

-> Please install %s and run this command again`, cmd, cmd)
		} else if err != nil {
			return err
		}
	}

	srclibpathDir := filepath.Join(filepath.SplitList(srclib.Path)[0], toolchain) // toolchain dir under SRCLIBPATH
	if err := os.MkdirAll(filepath.Dir(srclibpathDir), 0700); err != nil {
		return err
	}

	log.Println("Downloading Basic toolchain in", srclibpathDir)
	if err := cloneToolchain(srclibpathDir, toolchain); err != nil {
		return err
	}

	log.Println("Building Basic toolchain program")
	if err := execCmdInDir(srclibpathDir, "make"); err != nil {
		return err
	}

	return nil
}

示例#18
文件: godeps.go 项目: ToQoz/godeps

func mustConvertImportPathToPath(importPath string) (path string) {
	path = filepath.Join(importPath, filepath.Join(build.Default.GOROOT, "src"))

	_, err := os.Stat(path)

	if err != nil {
		return path
	}

	for _, gopath := range filepath.SplitList(build.Default.GOPATH) {
		// * see build.Context.gopath()
		if gopath == "" || gopath == build.Default.GOROOT {
			continue
		}

		// * see build.Context.gopath()
		if strings.HasPrefix(gopath, "~") {
			continue
		}

		path = filepath.Join(importPath, filepath.Join(gopath, "src", "pkg"))

		_, err := os.Stat(path)

		if err != nil {
			return path
		}
	}

	panic(fmt.Errorf("mustConvertImportPathPath: %v must be in $GOROOT nor $GOPATH.", path))
}

示例#19
文件: writer.go 项目: hyperledger/fabric

//WriteGopathSrc tars up files under gopath src
func WriteGopathSrc(tw *tar.Writer, excludeDir string) error {
	gopath := os.Getenv("GOPATH")
	// Only take the first element of GOPATH
	gopath = filepath.SplitList(gopath)[0]

	rootDirectory := filepath.Join(gopath, "src")
	vmLogger.Infof("rootDirectory = %s", rootDirectory)

	if err := WriteFolderToTarPackage(tw, rootDirectory, excludeDir, includeFileTypes, nil); err != nil {
		vmLogger.Errorf("Error writing folder to tar package %s", err)
		return err
	}

	// Add the certificates to tar
	if viper.GetBool("peer.tls.enabled") {
		err := WriteFileToPackage(viper.GetString("peer.tls.cert.file"), "src/certs/cert.pem", tw)
		if err != nil {
			return fmt.Errorf("Error writing cert file to package: %s", err)
		}
	}

	// Write the tar file out
	if err := tw.Close(); err != nil {
		return err
	}
	//ioutil.WriteFile("/tmp/chaincode_deployment.tar", inputbuf.Bytes(), 0644)
	return nil
}

示例#20
文件: util_test.go 项目: CNDonny/scope

func TestContainingPackage(t *testing.T) {
	// unvirtualized:
	goroot := runtime.GOROOT()
	gopath := filepath.SplitList(os.Getenv("GOPATH"))[0]

	for _, test := range [][2]string{
		{goroot + "/src/fmt/print.go", "fmt"},
		{goroot + "/src/encoding/json/foo.go", "encoding/json"},
		{goroot + "/src/encoding/missing/foo.go", "(not found)"},
		{gopath + "/src/golang.org/x/tools/go/buildutil/util_test.go",
			"golang.org/x/tools/go/buildutil"},
	} {
		file, want := test[0], test[1]
		bp, err := buildutil.ContainingPackage(&build.Default, ".", file)
		got := bp.ImportPath
		if err != nil {
			got = "(not found)"
		}
		if got != want {
			t.Errorf("ContainingPackage(%q) = %s, want %s", file, got, want)
		}
	}

	// TODO(adonovan): test on virtualized GOPATH too.
}

示例#21
文件: lookup_xdg.go 项目: rkoesters/stdpaths

func lookupSystemData() []string {
	dirs := os.Getenv("XDG_DATA_DIRS")
	if len(dirs) != 0 {
		return filepath.SplitList(dirs)
	}
	return []string{"/usr/local/share", "/usr/share"}
}

示例#22
文件: lookup_xdg.go 项目: rkoesters/stdpaths

func lookupSystemConfig() []string {
	dirs := os.Getenv("XDG_CONFIG_DIRS")
	if len(dirs) != 0 {
		return filepath.SplitList(dirs)
	}
	return []string{"/etc/xdg"}
}

示例#23
文件: path_test.go 项目: WXB506/golang

func TestSplitList(t *testing.T) {
	for _, test := range splitlisttests {
		if l := filepath.SplitList(test.list); !reflect.DeepEqual(l, test.result) {
			t.Errorf("SplitList(%q) = %s, want %s", test.list, l, test.result)
		}
	}
}

示例#24
文件: configvars.go 项目: tiberiuc/web-compiler

func NewConfigvars(m *Manager) *Configvars {
	p := &Configvars{m: m}

	p.files = m.Config.Configvars.Files

	files := filepath.SplitList(p.files)

	p.vars = make(map[string]string, 0)

	for _, file := range files {
		src, err := ioutil.ReadFile(file)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error loading Configvars file %s\n\n%s\n", file, err.Error())
			os.Exit(2)
		}

		lines := strings.Split(string(src), "\n")
		for _, line := range lines {
			p.processLineVar(line)
		}
	}

	// process added vars
	for _, line := range m.Config.Configvars.addedvars {
		p.processLineVar(line)
	}

	p.processExtensions()

	return p
}

示例#25
文件: revel.go 项目: jlujan/revel

// findSrcPaths uses the "go/build" package to find the source root for Revel
// and the app.
func findSrcPaths(importPath string) (revelSourcePath, appSourcePath string) {
	var (
		gopaths = filepath.SplitList(build.Default.GOPATH)
		goroot  = build.Default.GOROOT
	)

	if len(gopaths) == 0 {
		ERROR.Fatalln("GOPATH environment variable is not set. ",
			"Please refer to http://golang.org/doc/code.html to configure your Go environment.")
	}

	if ContainsString(gopaths, goroot) {
		ERROR.Fatalf("GOPATH (%s) must not include your GOROOT (%s). "+
			"Please refer to http://golang.org/doc/code.html to configure your Go environment.",
			gopaths, goroot)
	}

	appPkg, err := build.Import(importPath, "", build.FindOnly)
	if err != nil {
		ERROR.Fatalln("Failed to import", importPath, "with error:", err)
	}

	revelPkg, err := build.Import(REVEL_IMPORT_PATH, "", build.FindOnly)
	if err != nil {
		ERROR.Fatalln("Failed to find Revel with error:", err)
	}

	return revelPkg.SrcRoot, appPkg.SrcRoot
}

示例#26
文件: harness.go 项目: runner-mei/revel_cmd

// Run the harness, which listens for requests and proxies them to the app
// server, which it runs and rebuilds as necessary.
func (h *Harness) Run() {
	var paths []string
	if revel.Config.BoolDefault("watch.gopath", false) {
		gopaths := filepath.SplitList(build.Default.GOPATH)
		paths = append(paths, gopaths...)
	}
	paths = append(paths, revel.CodePaths...)
	watcher = revel.NewWatcher()
	watcher.Listen(h, paths...)

	go func() {
		addr := fmt.Sprintf("%s:%d", revel.HttpAddr, revel.HttpPort)
		revel.INFO.Printf("Listening on %s", addr)

		var err error
		if revel.HttpSsl {
			err = http.ListenAndServeTLS(addr, revel.HttpSslCert,
				revel.HttpSslKey, h)
		} else {
			err = http.ListenAndServe(addr, h)
		}
		if err != nil {
			revel.ERROR.Fatalln("Failed to start reverse proxy:", err)
		}
	}()

	// Kill the app on signal.
	ch := make(chan os.Signal)
	signal.Notify(ch, os.Interrupt, os.Kill)
	<-ch
	if h.app != nil {
		h.app.Kill()
	}
	os.Exit(1)
}

示例#27
文件: g_appcode.go 项目: huangjiasingle/bee

func getPackagePath(curpath string) (packpath string) {
	gopath := os.Getenv("GOPATH")
	Debugf("gopath:%s", gopath)
	if gopath == "" {
		ColorLog("[ERRO] you should set GOPATH in the env")
		os.Exit(2)
	}

	appsrcpath := ""
	haspath := false
	wgopath := filepath.SplitList(gopath)

	for _, wg := range wgopath {
		wg, _ = filepath.EvalSymlinks(path.Join(wg, "src"))

		if filepath.HasPrefix(strings.ToLower(curpath), strings.ToLower(wg)) {
			haspath = true
			appsrcpath = wg
			break
		}
	}

	if !haspath {
		ColorLog("[ERRO] Can't generate application code outside of GOPATH '%s'\n", gopath)
		os.Exit(2)
	}
	packpath = strings.Join(strings.Split(curpath[len(appsrcpath)+1:], string(filepath.Separator)), "/")
	return
}

示例#28
文件: build.go 项目: kpsmith/gopherjs

func Import(path string, mode build.ImportMode, archSuffix string) (*build.Package, error) {
	if path == "C" {
		return nil, &ImportCError{}
	}

	buildContext := NewBuildContext(archSuffix)
	if path == "runtime" || path == "syscall" {
		buildContext.GOARCH = build.Default.GOARCH
		buildContext.InstallSuffix = archSuffix
	}
	pkg, err := buildContext.Import(path, "", mode)
	if path == "hash/crc32" {
		pkg.GoFiles = []string{"crc32.go", "crc32_generic.go"}
	}
	if pkg.IsCommand() {
		pkg.PkgObj = filepath.Join(pkg.BinDir, filepath.Base(pkg.ImportPath)+".js")
	}
	if _, err := os.Stat(pkg.PkgObj); os.IsNotExist(err) && strings.HasPrefix(pkg.PkgObj, build.Default.GOROOT) {
		// fall back to GOPATH
		firstGopathWorkspace := filepath.SplitList(build.Default.GOPATH)[0] // TODO: Need to check inside all GOPATH workspaces.
		gopathPkgObj := filepath.Join(firstGopathWorkspace, pkg.PkgObj[len(build.Default.GOROOT):])
		if _, err := os.Stat(gopathPkgObj); err == nil {
			pkg.PkgObj = gopathPkgObj
		}
	}
	return pkg, err
}

示例#29
文件: model_test.go 项目: tomschlenkhoff/syncthing

func genDeepFiles(n, d int) []protocol.FileInfo {
	rand.Seed(int64(n))
	files := make([]protocol.FileInfo, n)
	t := time.Now().Unix()
	for i := 0; i < n; i++ {
		path := ""
		for i := 0; i <= d; i++ {
			path = filepath.Join(path, strconv.Itoa(rand.Int()))
		}

		sofar := ""
		for _, path := range filepath.SplitList(path) {
			sofar = filepath.Join(sofar, path)
			files[i] = protocol.FileInfo{
				Name: sofar,
			}
			i++
		}

		files[i].Modified = t
		files[i].Blocks = []protocol.BlockInfo{{0, 100, []byte("some hash bytes")}}
	}

	return files
}

示例#30
文件: path.go 项目: aubonbeurre/gcc

// set up Path: parse and validate GOROOT and GOPATH variables
func init() {
	root := runtime.GOROOT()
	t, err := newTree(root)
	if err != nil {
		log.Printf("go/build: invalid GOROOT %q: %v", root, err)
	} else {
		t.Goroot = true
		Path = []*Tree{t}
	}

	for _, p := range filepath.SplitList(os.Getenv("GOPATH")) {
		if p == "" {
			continue
		}
		t, err := newTree(p)
		if err != nil {
			log.Printf("go/build: invalid GOPATH %q: %v", p, err)
			continue
		}
		Path = append(Path, t)
		gcImportArgs = append(gcImportArgs, "-I", t.PkgDir())
		ldImportArgs = append(ldImportArgs, "-L", t.PkgDir())

		// select first GOPATH entry as default
		if defaultTree == nil {
			defaultTree = t
		}
	}

	// use GOROOT if no valid GOPATH specified
	if defaultTree == nil && len(Path) > 0 {
		defaultTree = Path[0]
	}
}

展开阅读全文