Golang IsAbs示例

说明

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

编程语言: Golang

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

示例#1
文件: validate.go 项目: ilkka/docker

func validateMounts(mounts []api.Mount) error {
	for _, mount := range mounts {
		// Target must always be absolute
		if !filepath.IsAbs(mount.Target) {
			return fmt.Errorf("invalid mount target, must be an absolute path: %s", mount.Target)
		}

		switch mount.Type {
		// The checks on abs paths are required due to the container API confusing
		// volume mounts as bind mounts when the source is absolute (and vice-versa)
		// See #25253
		// TODO: This is probably not neccessary once #22373 is merged
		case api.MountTypeBind:
			if !filepath.IsAbs(mount.Source) {
				return fmt.Errorf("invalid bind mount source, must be an absolute path: %s", mount.Source)
			}
		case api.MountTypeVolume:
			if filepath.IsAbs(mount.Source) {
				return fmt.Errorf("invalid volume mount source, must not be an absolute path: %s", mount.Source)
			}
		case api.MountTypeTmpfs:
			if mount.Source != "" {
				return fmt.Errorf("invalid tmpfs source, source must be empty")
			}
		default:
			return fmt.Errorf("invalid mount type: %s", mount.Type)
		}
	}
	return nil
}

示例#2
文件: tar_gz_pack_command.go 项目: amidvidy/evergreen

// Execute builds the archive.
func (self *TarGzPackCommand) Execute(pluginLogger plugin.Logger,
	pluginCom plugin.PluginCommunicator,
	conf *model.TaskConfig,
	stop chan bool) error {

	// if the source dir is a relative path, join it to the working dir
	if !filepath.IsAbs(self.SourceDir) {
		self.SourceDir = filepath.Join(conf.WorkDir, self.SourceDir)
	}

	// if the target is a relative path, join it to the working dir
	if !filepath.IsAbs(self.Target) {
		self.Target = filepath.Join(conf.WorkDir, self.Target)
	}

	errChan := make(chan error)
	go func() {
		errChan <- self.BuildArchive(conf.WorkDir, pluginLogger)
	}()

	select {
	case err := <-errChan:
		return err
	case <-stop:
		pluginLogger.LogExecution(slogger.INFO, "Received signal to terminate"+
			" execution of targz pack command")
		return nil
	}

}

示例#3
文件: json.go 项目: nenew/v2ray-core

func LoadConfig(file string) (*Config, error) {
	fixedFile := os.ExpandEnv(file)
	rawConfig, err := ioutil.ReadFile(fixedFile)
	if err != nil {
		log.Error("Failed to read point config file (%s): %v", file, err)
		return nil, err
	}

	config := &Config{}
	err = json.Unmarshal(rawConfig, config)
	if err != nil {
		log.Error("Failed to load point config: %v", err)
		return nil, err
	}

	if !filepath.IsAbs(config.InboundConfigValue.File) && len(config.InboundConfigValue.File) > 0 {
		config.InboundConfigValue.File = filepath.Join(filepath.Dir(fixedFile), config.InboundConfigValue.File)
	}

	if !filepath.IsAbs(config.OutboundConfigValue.File) && len(config.OutboundConfigValue.File) > 0 {
		config.OutboundConfigValue.File = filepath.Join(filepath.Dir(fixedFile), config.OutboundConfigValue.File)
	}

	return config, err
}

示例#4
文件: isolate.go 项目: shishkander/luci-go

// PostProcess post-processes the flags to fix any compatibility issue.
func (a *ArchiveOptions) PostProcess(cwd string) {
	// Set default blacklist only if none is set.
	if len(a.Blacklist) == 0 {
		// This cannot be generalized as ".*" as there is known use that require
		// a ".pki" directory to be mapped.
		a.Blacklist = common.Strings{
			".git",
			".hg",
			".svn",
		}
	}
	if !filepath.IsAbs(a.Isolate) {
		a.Isolate = filepath.Join(cwd, a.Isolate)
	}
	a.Isolate = filepath.Clean(a.Isolate)

	if !filepath.IsAbs(a.Isolated) {
		a.Isolated = filepath.Join(cwd, a.Isolated)
	}
	a.Isolated = filepath.Clean(a.Isolated)

	for k, v := range a.PathVariables {
		// This is due to a Windows + GYP specific issue, where double-quoted paths
		// would get mangled in a way that cannot be resolved unless a space is
		// injected.
		a.PathVariables[k] = strings.TrimSpace(v)
	}
}

示例#5
文件: path_test.go 项目: TomHoenderdos/go-sunos

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)
		}
	}
}

示例#6
文件: template.go 项目: tnozicka/goenvtemplator

func generateFile(templatePath, destinationPath string, debugTemplates bool) error {
	if !filepath.IsAbs(templatePath) {
		return fmt.Errorf("Template path '%s' is not absolute!", templatePath)
	}

	if !filepath.IsAbs(destinationPath) {
		return fmt.Errorf("Destination path '%s' is not absolute!", destinationPath)
	}

	var slice []byte
	var err error
	if slice, err = ioutil.ReadFile(templatePath); err != nil {
		return err
	}
	s := string(slice)
	result, err := generateTemplate(s, filepath.Base(templatePath))
	if err != nil {
		return err
	}

	if debugTemplates {
		log.Printf("Printing parsed template to stdout. (It's delimited by 2 character sequence of '\\x00\\n'.)\n%s\x00\n", result)
	}

	if err = ioutil.WriteFile(destinationPath, []byte(result), 0664); err != nil {
		return err
	}

	return nil
}

示例#7
文件: folderconfiguration.go 项目: hotelzululima/syncthing

func (f *FolderConfiguration) cleanedPath() string {
	cleaned := f.RawPath

	// Attempt tilde expansion; leave unchanged in case of error
	if path, err := osutil.ExpandTilde(cleaned); err == nil {
		cleaned = path
	}

	// Attempt absolutification; leave unchanged in case of error
	if !filepath.IsAbs(cleaned) {
		// Abs() looks like a fairly expensive syscall on Windows, while
		// IsAbs() is a whole bunch of string mangling. I think IsAbs() may be
		// somewhat faster in the general case, hence the outer if...
		if path, err := filepath.Abs(cleaned); err == nil {
			cleaned = path
		}
	}

	// Attempt to enable long filename support on Windows. We may still not
	// have an absolute path here if the previous steps failed.
	if runtime.GOOS == "windows" && filepath.IsAbs(cleaned) && !strings.HasPrefix(f.RawPath, `\\`) {
		return `\\?\` + cleaned
	}

	return cleaned
}

示例#8
文件: local.go 项目: pombredanne/rclone

// filterPath cleans and makes absolute the path passed in.
//
// On windows it makes the path UNC also.
func (f *Fs) filterPath(s string) string {
	s = filterFragment(s)
	if runtime.GOOS == "windows" {
		if !filepath.IsAbs(s) && !strings.HasPrefix(s, "\\") {
			s2, err := filepath.Abs(s)
			if err == nil {
				s = s2
			}
		}

		if f.nounc {
			return s
		}
		// Convert to UNC
		return uncPath(s)
	}

	if !filepath.IsAbs(s) {
		s2, err := filepath.Abs(s)
		if err == nil {
			s = s2
		}
	}

	return s
}

示例#9
文件: ln.go 项目: XiaoboYuan/myblog_article_code

func main() {

	if len(os.Args) != 3 {
		fmt.Println("ln target linkname")
		os.Exit(1)
	}

	curDir, _ := os.Getwd()

	target := os.Args[1]
	if !filepath.IsAbs(target) {
		target = curDir + string(os.PathSeparator) + target
	}

	linkname := os.Args[2]
	if !filepath.IsAbs(linkname) {
		linkname = curDir + string(os.PathSeparator) + linkname
	}

	err := os.Symlink(target, linkname)

	if err != nil {
		fmt.Printf("创建失败:%s\n", err)
		os.Exit(2)
	}
}

示例#10
文件: config.go 项目: modulexcite/syncthing-cli

func (f FolderConfiguration) Path() string {
	// This is intentionally not a pointer method, because things like
	// cfg.Folders["default"].Path() should be valid.

	// Attempt tilde expansion; leave unchanged in case of error
	if path, err := osutil.ExpandTilde(f.RawPath); err == nil {
		f.RawPath = path
	}

	// Attempt absolutification; leave unchanged in case of error
	if !filepath.IsAbs(f.RawPath) {
		// Abs() looks like a fairly expensive syscall on Windows, while
		// IsAbs() is a whole bunch of string mangling. I think IsAbs() may be
		// somewhat faster in the general case, hence the outer if...
		if path, err := filepath.Abs(f.RawPath); err == nil {
			f.RawPath = path
		}
	}

	// Attempt to enable long filename support on Windows. We may still not
	// have an absolute path here if the previous steps failed.
	if runtime.GOOS == "windows" && filepath.IsAbs(f.RawPath) && !strings.HasPrefix(f.RawPath, `\\`) {
		return `\\?\` + f.RawPath
	}

	return f.RawPath
}

示例#11
文件: env.go 项目: ustbgaofan/gadget

func (s *Serve) Run() {
	if root == "" {
		if wd, err := os.Getwd(); err != nil {
			panic(err)
		} else {
			root = wd
		}
	} else if !filepath.IsAbs(root) {
		panic("fileroot must be an absolute path")
	}
	var writer io.Writer
	if logFilePath != "" {
		if !filepath.IsAbs(logFilePath) {
			logFilePath = AbsPath(logFilePath)
		}
		if f, err := os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE, 0666); err != nil {
			panic(err)
		} else {
			writer = f
		}
	} else {
		writer = os.Stdout
	}
	logger = log.New(writer, "", 0)
	serveStatic()
	http.HandleFunc("/", Handler)
	Log("Running Gadget at 0.0.0.0:" + Port + "...")
	err := http.ListenAndServe(":"+Port, nil)
	if err != nil {
		panic(err)
	}
}

示例#12
文件: config.go 项目: krets/infra-inventory

func LoadConfig(cfgfile string) (cfg *InventoryConfig, err error) {

	if !filepath.IsAbs(cfgfile) {
		cfgfile, _ = filepath.Abs(cfgfile)
	}

	var b []byte

	if b, err = ioutil.ReadFile(cfgfile); err != nil {
		return
	}
	if err = json.Unmarshal(b, &cfg); err != nil {
		return
	}

	if !filepath.IsAbs(cfg.Datastore.Config.MappingFile) {
		cfg.Datastore.Config.MappingFile, _ = filepath.Abs(cfg.Datastore.Config.MappingFile)
	}

	if !filepath.IsAbs(cfg.Datastore.BackupDir) {
		cfg.Datastore.BackupDir, _ = filepath.Abs(cfg.Datastore.BackupDir)
	}

	if !filepath.IsAbs(cfg.Auth.GroupsFile) {
		cfg.Auth.GroupsFile, _ = filepath.Abs(cfg.Auth.GroupsFile)
	}

	return
}

示例#13
文件: parse.go 项目: rahulpathakgit/navc

func fixCompDirArg(argDir, path string) string {
	if filepath.IsAbs(path) {
		if filepath.IsAbs(argDir) {
			return argDir
		} else {
			abs, err := filepath.Abs(argDir)
			if err != nil {
				log.Panic("unable to get absolute path: ",
					err)
			}
			return filepath.Clean(abs)
		}
	} else {
		if filepath.IsAbs(argDir) {
			wd, err := os.Getwd()
			if err != nil {
				log.Panic("unable to get working directoy: ",
					err)
			}
			rel, err := filepath.Rel(wd, argDir)
			if err != nil {
				log.Panic("unable to get relative path: ",
					err)
			}
			return filepath.Clean(rel)
		} else {
			return filepath.Clean(path + "/" + argDir)
		}
	}
}

示例#14
文件: read.go 项目: pauek/garzon.old

func findRoot(dir string) (root, relative string, err error) {
	abspath, err := filepath.Abs(dir)
	if err != nil {
		return "", "", fmt.Errorf("Cannot get abs of '%s': %s\n", dir)
	}
	grzpath := RootList()
	if len(grzpath) == 0 {
		return "", "", fmt.Errorf("No roots (GRZ_PATH empty)")
	}
	for _, path := range grzpath {
		if len(path) == 0 || !filepath.IsAbs(path) {
			return "", "", fmt.Errorf("path '%s' is not absolute", path)
		}
		if strings.HasPrefix(abspath, path) {
			if relative, err = filepath.Rel(path, abspath); err != nil {
				return "", "", err
			}
			root = path
			break
		}
	}
	if root == "" {
		if !filepath.IsAbs(dir) {
			pwd, err := os.Getwd()
			if err != nil {
				return "", "", fmt.Errorf("Cannot get working dir: %s\n", err)
			}
			root, relative = pwd, dir
		} else {
			return "", "", fmt.Errorf("Root directory '/' not allowed")
		}
	}
	return
}

示例#15
文件: sys_darwin.go 项目: rfjakob/gocryptfs

// Poor man's Renameat
func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) {
	chdirMutex.Lock()
	defer chdirMutex.Unlock()
	// Unless both paths are absolute we have to save the old working dir and
	// Chdir(oldWd) back to it in the end. If we error out before the first
	// chdir, Chdir(oldWd) is unneccassary but does no harm.
	if !filepath.IsAbs(oldpath) || !filepath.IsAbs(newpath) {
		oldWd, err := os.Getwd()
		if err != nil {
			return err
		}
		defer os.Chdir(oldWd)
	}
	// Make oldpath absolute
	oldpath, err = dirfdAbs(olddirfd, oldpath)
	if err != nil {
		return err
	}
	// Make newpath absolute
	newpath, err = dirfdAbs(newdirfd, newpath)
	if err != nil {
		return err
	}
	return syscall.Rename(oldpath, newpath)
}

示例#16
文件: git.go 项目: nathanmpark/hub

func Dir() (string, error) {
	output, err := gitOutput("rev-parse", "-q", "--git-dir")
	if err != nil {
		return "", fmt.Errorf("Not a git repository (or any of the parent directories): .git")
	}

	var chdir string
	for i, flag := range GlobalFlags {
		if flag == "-C" {
			dir := GlobalFlags[i+1]
			if filepath.IsAbs(dir) {
				chdir = dir
			} else {
				chdir = filepath.Join(chdir, dir)
			}
		}
	}

	gitDir := output[0]

	if !filepath.IsAbs(gitDir) {
		if chdir != "" {
			gitDir = filepath.Join(chdir, gitDir)
		}

		gitDir, err = filepath.Abs(gitDir)
		if err != nil {
			return "", err
		}

		gitDir = filepath.Clean(gitDir)
	}

	return gitDir, nil
}

示例#17
文件: paths.go 项目: sinfomicien/rkt

func (p *configurablePathsV1) parse(config *Config, raw []byte) error {
	var dirs configurablePathsV1
	if err := json.Unmarshal(raw, &dirs); err != nil {
		return err
	}
	if dirs.Data != "" {
		if config.Paths.DataDir != "" {
			return fmt.Errorf("data directory is already specified")
		}
		if !filepath.IsAbs(dirs.Data) {
			return fmt.Errorf("data directory must be an absolute path")
		}
		config.Paths.DataDir = dirs.Data
	}
	if dirs.Stage1Images != "" {
		if config.Paths.Stage1ImagesDir != "" {
			return fmt.Errorf("stage1 images directory is already specified")
		}
		if !filepath.IsAbs(dirs.Stage1Images) {
			return fmt.Errorf("stage1 images directory must be an absolute path")
		}
		config.Paths.Stage1ImagesDir = dirs.Stage1Images
	}

	return nil
}

示例#18
文件: local.go 项目: wernight/rclone

func (f *Fs) filterPath(s string) string {
	s = filepath.Clean(s)
	if runtime.GOOS == "windows" {
		s = strings.Replace(s, `/`, `\`, -1)

		if !filepath.IsAbs(s) && !strings.HasPrefix(s, "\\") {
			s2, err := filepath.Abs(s)
			if err == nil {
				s = s2
			}
		}

		if f.nounc {
			return s
		}
		// Convert to UNC
		return uncPath(s)
	}

	if !filepath.IsAbs(s) {
		s2, err := filepath.Abs(s)
		if err == nil {
			s = s2
		}
	}

	return s
}

示例#19
文件: lookpath.go 项目: 4shome/go.jiri

// LookPath inputs a command name and searches the PATH environment
// variable of the snapshot for an executable file that would be run
// had this command actually been invoked. The function returns an
// absolute path to the executable file. In other words, LookPath
// implements functionality similar to the UNIX "which" command
// relative to the snapshot environment.
func LookPath(file string, env map[string]string) (string, error) {
	if filepath.IsAbs(file) {
		ok, err := isExistingExecutable(file)
		if err != nil {
			return "", err
		} else if ok {
			return file, nil
		}
		return "", fmt.Errorf("failed to find %v", file)
	}
	envPath := env["PATH"]
	for _, dir := range strings.Split(envPath, string(os.PathListSeparator)) {
		path := filepath.Join(dir, file)
		ok, err := isExistingExecutable(path)
		if err != nil {
			return "", err
		} else if ok {
			if !filepath.IsAbs(path) {
				var err error
				path, err = filepath.Abs(path)
				if err != nil {
					return "", fmt.Errorf("Abs(%v) failed: %v", path, err)
				}
			}
			return path, nil
		}
	}
	return "", fmt.Errorf("failed to find %v in %q", file, envPath)
}

示例#20
文件: config.go 项目: nebulon42/magnacarto

func (m *Magnacarto) Locator() Locator {
	locator := &LookupLocator{baseDir: m.BaseDir}
	for _, dir := range m.Datasources.SQLiteDirs {
		if !filepath.IsAbs(dir) {
			dir = filepath.Join(m.BaseDir, dir)
		}
		locator.AddSQLiteDir(dir)
	}
	for _, dir := range m.Datasources.ImageDirs {
		if !filepath.IsAbs(dir) {
			dir = filepath.Join(m.BaseDir, dir)
		}
		locator.AddImageDir(dir)
	}
	for _, dir := range m.Datasources.ShapefileDirs {
		if !filepath.IsAbs(dir) {
			dir = filepath.Join(m.BaseDir, dir)
		}
		locator.AddShapeDir(dir)
	}
	for _, dir := range m.Mapnik.FontDirs {
		if !filepath.IsAbs(dir) {
			dir = filepath.Join(m.BaseDir, dir)
		}
		locator.AddFontDir(dir)
	}
	locator.SetPGConfig(m.PostGIS)
	return locator
}

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

func TestAbs(t *testing.T) {
	oldwd, err := os.Getwd()
	if err != nil {
		t.Fatal("Getwd failed: " + err.String())
	}
	defer os.Chdir(oldwd)
	goroot := os.Getenv("GOROOT")
	cwd := filepath.Join(goroot, "src")
	os.Chdir(cwd)
	for _, path := range abstests {
		path = strings.Replace(path, "$GOROOT", goroot, -1)
		abspath, err := filepath.Abs(path)
		if err != nil {
			t.Errorf("Abs(%q) error: %v", path, err)
		}
		info, err := os.Stat(path)
		if err != nil {
			t.Errorf("%s: %s", path, err)
		}
		absinfo, err := os.Stat(abspath)
		if err != nil || absinfo.Ino != info.Ino {
			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)
		}
	}
}

示例#22
文件: phantom.go 项目: huih/pholcus

func (self *Phantom) setFile(js string) (string, error) {
	self.Mutex.Lock()
	defer self.Mutex.Unlock()
	jshash := util.MakeHash(js)
	fullFileName := self.FullTempJsFilePrefix + jshash
	if self.FullTempJsFiles[fullFileName] {
		return fullFileName, nil
	}
	if !filepath.IsAbs(fullFileName) {
		fullFileName, _ = filepath.Abs(fullFileName)
	}
	if !filepath.IsAbs(self.FullPhantomjsName) {
		self.FullPhantomjsName, _ = filepath.Abs(self.FullPhantomjsName)
	}

	// 创建/打开目录
	p, _ := filepath.Split(fullFileName)
	d, err := os.Stat(p)
	if err != nil || !d.IsDir() {
		if err := os.MkdirAll(p, 0777); err != nil {
			return "", err
		}
	}

	// 创建并写入文件
	f, _ := os.Create(fullFileName)
	f.Write([]byte(js))
	f.Close()
	self.FullTempJsFiles[fullFileName] = true
	return fullFileName, nil
}

示例#23
文件: storage_transport.go 项目: containers/image

func (s storageTransport) ValidatePolicyConfigurationScope(scope string) error {
	// Check that there's a store location prefix.  Values we're passed are
	// expected to come from PolicyConfigurationIdentity or
	// PolicyConfigurationNamespaces, so if there's no store location,
	// something's wrong.
	if scope[0] != '[' {
		return ErrInvalidReference
	}
	// Parse the store location prefix.
	closeIndex := strings.IndexRune(scope, ']')
	if closeIndex < 1 {
		return ErrInvalidReference
	}
	storeSpec := scope[1:closeIndex]
	scope = scope[closeIndex+1:]
	storeInfo := strings.SplitN(storeSpec, "@", 2)
	if len(storeInfo) == 1 && storeInfo[0] != "" {
		// One component: the graph root.
		if !filepath.IsAbs(storeInfo[0]) {
			return ErrPathNotAbsolute
		}
	} else if len(storeInfo) == 2 && storeInfo[0] != "" && storeInfo[1] != "" {
		// Two components: the driver type and the graph root.
		if !filepath.IsAbs(storeInfo[1]) {
			return ErrPathNotAbsolute
		}
	} else {
		// Anything else: store specified in a form we don't
		// recognize.
		return ErrInvalidReference
	}
	// That might be all of it, and that's okay.
	if scope == "" {
		return nil
	}
	// But if there is anything left, it has to be a name, with or without
	// a tag, with or without an ID, since we don't return namespace values
	// that are just bare IDs.
	scopeInfo := strings.SplitN(scope, "@", 2)
	if len(scopeInfo) == 1 && scopeInfo[0] != "" {
		_, err := reference.ParseNamed(scopeInfo[0])
		if err != nil {
			return err
		}
	} else if len(scopeInfo) == 2 && scopeInfo[0] != "" && scopeInfo[1] != "" {
		_, err := reference.ParseNamed(scopeInfo[0])
		if err != nil {
			return err
		}
		_, err = ddigest.Parse("sha256:" + scopeInfo[1])
		if err != nil {
			return err
		}
	} else {
		return ErrInvalidReference
	}
	return nil
}

示例#24
文件: parse_driver_test.go 项目: runt18/mojo

// doOSFileProviderTest is the workhorse for TestOSFileProvider.
func doOSFileProviderTest(t *testing.T, specifiedPath string, importedFrom *FileReference,
	globalImports []string, expectedContents string) FileReference {
	fileProvider := new(OSFileProvider)
	fileProvider.importDirs = globalImports
	fileReference := FileReference{specifiedPath: specifiedPath}
	fileReference.importedFrom = importedFrom

	// Invoke findFile()
	if err := fileProvider.findFile(&fileReference); err != nil {
		t.Fatalf(err.Error())
	}

	// Check that the absolutePath has been populated to the absolute path of a file.
	if fileReference.absolutePath == "" {
		t.Fatalf("absolutePath is not set for %s", fileReference.specifiedPath)
	}
	if !filepath.IsAbs(fileReference.absolutePath) {
		t.Fatalf("absolutePath is not absolute for %s: %s", fileReference.specifiedPath, fileReference.absolutePath)
	}
	info, err := os.Stat(fileReference.absolutePath)
	if err != nil {
		t.Fatalf("cannot stat absolutePath %s: %s", fileReference.absolutePath, err.Error())
	}
	if info.IsDir() {
		t.Fatalf("absolutePath refers to a directory: %s", fileReference.absolutePath)
	}

	// Check that the dirPath has been populated to the absolute path of a directory.
	if fileReference.directoryPath == "" {
		t.Fatalf("directoryPath is not set for %s", fileReference.specifiedPath)
	}
	if !filepath.IsAbs(fileReference.directoryPath) {
		t.Fatalf("directoryPath is not absolute for %s: %s", fileReference.specifiedPath, fileReference.directoryPath)
	}
	info, err = os.Stat(fileReference.directoryPath)
	if err != nil {
		t.Fatalf("cannot stat directoryPath %s: %s", fileReference.directoryPath, err.Error())
	}
	if !info.IsDir() {
		t.Fatalf("directoryPath does not refer to a directory: %s", fileReference.directoryPath)
	}
	if filepath.Dir(fileReference.absolutePath) != fileReference.directoryPath {
		t.Fatalf("wrong directoryPath expected parent of %s got %s", fileReference.absolutePath, fileReference.directoryPath)
	}

	contents, err := fileProvider.provideContents(&fileReference)
	if err != nil {
		t.Errorf("Error from provideContents for %v: %s", fileReference, err.Error())
	}
	if !strings.Contains(contents, expectedContents) {
		t.Errorf("Wrong file contents for %v. Expecting %s got %s.", fileReference, expectedContents, contents)
	}

	return fileReference
}

示例#25
文件: mapserver.go 项目: kaiCu/magnacarto

func MapServer(bin, mapfile string, mapReq Request) ([]byte, error) {
	if !filepath.IsAbs(mapfile) {
		if wd, err := os.Getwd(); err == nil {
			mapfile = filepath.Join(wd, mapfile)
		}
	}

	q := url.Values{}
	q.Set("REQUEST", "GetMap")
	q.Set("SERVICE", "WMS")
	q.Set("VERSION", "1.1.1")
	q.Set("STYLES", "")
	q.Set("LAYERS", "map")
	q.Set("MAP", mapfile)

	q.Set("BBOX", fmt.Sprintf("%f,%f,%f,%f", mapReq.BBOX[0], mapReq.BBOX[1], mapReq.BBOX[2], mapReq.BBOX[3]))
	q.Set("WIDTH", fmt.Sprintf("%d", mapReq.Width))
	q.Set("HEIGHT", fmt.Sprintf("%d", mapReq.Height))
	q.Set("SRS", fmt.Sprintf("EPSG:%d", mapReq.EPSGCode))
	q.Set("FORMAT", mapReq.Format)

	if !filepath.IsAbs(bin) {
		for _, path := range strings.Split(os.Getenv("PATH"), string(filepath.ListSeparator)) {
			if fi, _ := os.Stat(filepath.Join(path, bin)); fi != nil {
				bin = filepath.Join(path, bin)
				break
			}
		}
	}

	wd := filepath.Dir(mapfile)
	handler := cgi.Handler{
		Path: bin,
		Dir:  wd,
	}

	w := &httptest.ResponseRecorder{
		Body: bytes.NewBuffer(nil),
	}

	req, err := http.NewRequest("GET", "/?"+q.Encode(), nil)
	if err != nil {
		return nil, err
	}

	handler.ServeHTTP(w, req)

	if w.Code != 200 {
		return nil, fmt.Errorf("error while calling mapserv CGI (status %d): %v", w.Code, string(w.Body.Bytes()))
	}
	if ct := w.Header().Get("Content-type"); ct != "" && !strings.HasPrefix(ct, "image") {
		return nil, fmt.Errorf(" mapserv CGI did not return image (%v)\n%v", w.Header(), string(w.Body.Bytes()))
	}
	return w.Body.Bytes(), nil
}

示例#26
文件: util_test.go 项目: zieckey/gsnake

func TestGetAbsPath(t *testing.T) {
	var dir string
	if runtime.GOOS == "windows" {
		dir = "c:/"
		assert.Equal(t, filepath.IsAbs(dir), true)
	} else {
		dir = "/etc"
		assert.Equal(t, filepath.IsAbs(dir), true)
	}
	assert.Equal(t, GetAbsPath(dir), dir)
}

示例#27
文件: main.go 项目: nuaajeff/v2ray-core

func main() {
	flag.Parse()

	if *version {
		fmt.Printf("V2Ray version %s (%s): %s", core.Version, core.Codename, core.Intro)
		fmt.Println()
		return
	}

	switch *logLevel {
	case "debug":
		log.SetLogLevel(log.DebugLevel)
	case "info":
		log.SetLogLevel(log.InfoLevel)
	case "warning":
		log.SetLogLevel(log.WarningLevel)
	case "error":
		log.SetLogLevel(log.ErrorLevel)
	}

	if configFile == nil || len(*configFile) == 0 {
		panic(log.Error("Config file is not set."))
	}
	rawVConfig, err := ioutil.ReadFile(*configFile)
	if err != nil {
		panic(log.Error("Failed to read config file (%s): %v", *configFile, err))
	}
	vconfig, err := core.LoadConfig(rawVConfig)
	if err != nil {
		panic(log.Error("Failed to parse Config: %v", err))
	}

	if !filepath.IsAbs(vconfig.InboundConfig.File) && len(vconfig.InboundConfig.File) > 0 {
		vconfig.InboundConfig.File = filepath.Join(filepath.Dir(*configFile), vconfig.InboundConfig.File)
	}

	if !filepath.IsAbs(vconfig.OutboundConfig.File) && len(vconfig.OutboundConfig.File) > 0 {
		vconfig.OutboundConfig.File = filepath.Join(filepath.Dir(*configFile), vconfig.OutboundConfig.File)
	}

	vPoint, err := core.NewPoint(vconfig)
	if err != nil {
		panic(log.Error("Failed to create Point server: %v", err))
	}

	err = vPoint.Start()
	if err != nil {
		log.Error("Error starting Point server: %v", err)
	}

	finish := make(chan bool)
	<-finish
}

示例#28
文件: bundle.go 项目: bac/juju

// addCharm adds a charm to the environment.
func (h *bundleHandler) addCharm(id string, p bundlechanges.AddCharmParams) (*charm.URL, csparams.Channel, *macaroon.Macaroon, error) {
	// First attempt to interpret as a local path.
	if strings.HasPrefix(p.Charm, ".") || filepath.IsAbs(p.Charm) {
		charmPath := p.Charm
		if !filepath.IsAbs(charmPath) {
			charmPath = filepath.Join(h.bundleDir, charmPath)
		}

		var noChannel csparams.Channel
		series := p.Series
		if series == "" {
			series = h.data.Series
		}
		ch, curl, err := charmrepo.NewCharmAtPath(charmPath, series)
		if err != nil && !os.IsNotExist(err) {
			return nil, noChannel, nil, errors.Annotatef(err, "cannot deploy local charm at %q", charmPath)
		}
		if err == nil {
			if curl, err = h.api.AddLocalCharm(curl, ch); err != nil {
				return nil, noChannel, nil, err
			}
			logger.Debugf("added charm %s", curl)
			h.results[id] = curl.String()
			return curl, noChannel, nil, nil
		}
	}

	// Not a local charm, so grab from the store.
	ch, err := charm.ParseURL(p.Charm)
	if err != nil {
		return nil, "", nil, errors.Trace(err)
	}
	modelCfg, err := getModelConfig(h.api)
	if err != nil {
		return nil, "", nil, errors.Trace(err)
	}

	url, channel, _, err := h.api.Resolve(modelCfg, ch)
	if err != nil {
		return nil, channel, nil, errors.Annotatef(err, "cannot resolve URL %q", p.Charm)
	}
	if url.Series == "bundle" {
		return nil, channel, nil, errors.Errorf("expected charm URL, got bundle URL %q", p.Charm)
	}
	var csMac *macaroon.Macaroon
	url, csMac, err = addCharmFromURL(h.api, url, channel)
	if err != nil {
		return nil, channel, nil, errors.Annotatef(err, "cannot add charm %q", p.Charm)
	}
	logger.Debugf("added charm %s", url)
	h.results[id] = url.String()
	return url, channel, csMac, nil
}

示例#29
文件: template.go 项目: pombredanne/pongo

// Reads a template from file. If there's no templateLocator provided,
// one will be created to search for files in the same directory the template
// file is located. file_path can either be an absolute filepath or a relative one.
func FromFile(file_path string, locator templateLocator) (*Template, error) {
	var err error

	// What is file_path?
	if !filepath.IsAbs(file_path) {
		file_path, err = filepath.Abs(file_path)
		if err != nil {
			return nil, err
		}
	}

	buf, err := ioutil.ReadFile(file_path)
	if err != nil {
		return nil, err
	}

	file_base := filepath.Dir(file_path)

	if locator == nil {
		// Create a default locator
		locator = func(name *string) (*string, error) {
			filename := *name
			if !filepath.IsAbs(filename) {
				filename = filepath.Join(file_base, filename)
			}

			buf, err := ioutil.ReadFile(filename)
			if err != nil {
				return nil, errors.New(fmt.Sprintf("Could not find the template '%s' (default file locator): %v", filename, err))
			}

			bufstr := string(buf)
			return &bufstr, nil
		}
	}

	// Get file name from filepath
	name := filepath.Base(file_path)

	strbuf := string(buf)
	tpl, err := newTemplate(name, &strbuf, locator)
	if err != nil {
		return nil, err
	}

	err = tpl.parse()
	if err != nil {
		return nil, err
	}

	return tpl, nil
}

示例#30
文件: config.go 项目: nebulon42/magnacarto

func (l *LookupLocator) find(basename string, dirs []string) (fname string, ok bool) {
	defer func() {
		if fname == "" {
			if l.missing == nil {
				l.missing = make(map[string]struct{})
			}
			l.missing[basename] = struct{}{}
			fname = basename
		} else {
			absfname, err := filepath.Abs(fname)
			if err == nil {
				fname = absfname
			}
		}

		if l.relative {
			relfname, err := filepath.Rel(l.outDir, fname)
			if err == nil {
				fname = relfname
			}
		} else {
			if !filepath.IsAbs(fname) { // for missing files
				fname = filepath.Join(l.outDir, fname)
			}
		}
	}()

	check := func(dir string) string {
		fname := filepath.Join(dir, basename)
		if _, err := os.Stat(fname); err == nil {
			return fname
		}
		return ""
	}

	if filepath.IsAbs(basename) {
		if fname := check(""); fname != "" {
			return fname, true
		}
	}

	for _, d := range dirs {
		if fname := check(d); fname != "" {
			return fname, true
		}
	}
	if fname := check(l.baseDir); fname != "" {
		return fname, true
	}

	return "", false
}

展开阅读全文