当前位置: 首页>>代码示例>>Golang>>正文


Golang filepath.Clean函数代码示例

本文整理汇总了Golang中path/filepath.Clean函数的典型用法代码示例。如果您正苦于以下问题:Golang Clean函数的具体用法?Golang Clean怎么用?Golang Clean使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Clean函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Symlink

func (fs *osFileSystem) Symlink(oldPath, newPath string) error {
	fs.logger.Debug(fs.logTag, "Symlinking oldPath %s with newPath %s", oldPath, newPath)

	source, target, err := fs.symlinkPaths(oldPath, newPath)
	if err != nil {
		bosherr.WrapErrorf(err, "Getting absolute paths for target and path links: %s %s", oldPath, newPath)
	}
	if fi, err := fs.Lstat(target); err == nil {
		if fi.Mode()&os.ModeSymlink != 0 {
			// Symlink
			new, err := fs.Readlink(target)
			if err != nil {
				return bosherr.WrapErrorf(err, "Reading link for %s", target)
			}
			if filepath.Clean(source) == filepath.Clean(new) {
				return nil
			}
		}
		if err := fs.RemoveAll(target); err != nil {
			return bosherr.WrapErrorf(err, "Removing new path at %s", target)
		}
	}

	containingDir := filepath.Dir(target)
	if !fs.FileExists(containingDir) {
		fs.MkdirAll(containingDir, os.FileMode(0700))
	}

	return fsWrapper.Symlink(source, target)
}
开发者ID:mattcui,项目名称:bosh-agent,代码行数:30,代码来源:os_file_system.go

示例2: vcsForDir

// vcsForDir inspects dir and its parents to determine the
// version control system and code repository to use.
// On return, root is the import path
// corresponding to the root of the repository
// (thus root is a prefix of importPath).
func vcsForDir(p *Package) (vcs *vcsCmd, root string, err error) {
	// Clean and double-check that dir is in (a subdirectory of) srcRoot.
	dir := filepath.Clean(p.Dir)
	srcRoot := filepath.Clean(p.build.SrcRoot)
	if len(dir) <= len(srcRoot) || dir[len(srcRoot)] != filepath.Separator {
		return nil, "", fmt.Errorf("directory %q is outside source root %q", dir, srcRoot)
	}

	origDir := dir
	for len(dir) > len(srcRoot) {
		for _, vcs := range vcsList {
			if fi, err := os.Stat(filepath.Join(dir, "."+vcs.cmd)); err == nil && fi.IsDir() {
				return vcs, dir[len(srcRoot)+1:], nil
			}
		}

		// Move to parent.
		ndir := filepath.Dir(dir)
		if len(ndir) >= len(dir) {
			// Shouldn't happen, but just in case, stop.
			break
		}
		dir = ndir
	}

	return nil, "", fmt.Errorf("directory %q is not using a known version control system", origDir)
}
开发者ID:klobucar,项目名称:go,代码行数:32,代码来源:vcs.go

示例3: AbsPathify

func AbsPathify(inPath string) string {
	if filepath.IsAbs(inPath) {
		return filepath.Clean(inPath)
	}

	return filepath.Clean(filepath.Join(viper.GetString("WorkingDir"), inPath))
}
开发者ID:GeertJohan,项目名称:hugo,代码行数:7,代码来源:path.go

示例4: MoveAllCmd

func MoveAllCmd(args []string) (err error) {
	if len(args) != 2 {
		return MakeErr("Usage: gorf [flags] moveall <old path> <new path>")
	}

	oldPath, newPath := filepath.Clean(args[0]), filepath.Clean(args[1])

	err = ScanAllForImports(LocalRoot)
	if err != nil {
		return
	}

	prefix := fmt.Sprintf("%s%c", oldPath, filepath.Separator)
	fmt.Println("prefix:", prefix)
	for opath := range PackageTops {
		opath = fmt.Sprintf("%s%c", filepath.Clean(opath), filepath.Separator)
		if strings.HasPrefix(opath, prefix) {
			tail := opath[len(prefix):]
			npath := filepath.Join(newPath, tail)
			err = MoveCmd([]string{opath, npath})
			if err != nil {
				return
			}
		}
	}

	return
}
开发者ID:rwl,项目名称:gorf,代码行数:28,代码来源:move.go

示例5: TestClean

func TestClean(t *testing.T) {
	tests := cleantests
	if runtime.GOOS == "windows" {
		for i := range tests {
			tests[i].result = filepath.FromSlash(tests[i].result)
		}
		tests = append(tests, wincleantests...)
	}
	for _, test := range tests {
		if s := filepath.Clean(test.path); s != test.result {
			t.Errorf("Clean(%q) = %q, want %q", test.path, s, test.result)
		}
		if s := filepath.Clean(test.result); s != test.result {
			t.Errorf("Clean(%q) = %q, want %q", test.result, s, test.result)
		}
	}

	if testing.Short() {
		t.Skip("skipping malloc count in short mode")
	}
	if runtime.GOMAXPROCS(0) > 1 {
		t.Log("skipping AllocsPerRun checks; GOMAXPROCS>1")
		return
	}

	for _, test := range tests {
		allocs := testing.AllocsPerRun(100, func() { filepath.Clean(test.result) })
		if allocs > 0 {
			t.Errorf("Clean(%q): %v allocs, want zero", test.result, allocs)
		}
	}
}
开发者ID:fjballest,项目名称:golang,代码行数:32,代码来源:path_test.go

示例6: parseBindMountSpec

func parseBindMountSpec(spec string) (*volumeMount, error) {
	arr := strings.Split(spec, ":")

	mnt := &volumeMount{}
	switch len(arr) {
	case 2:
		mnt.hostPath = arr[0]
		mnt.containerPath = arr[1]
		mnt.writable = true
	case 3:
		mnt.hostPath = arr[0]
		mnt.containerPath = arr[1]
		mnt.writable = validMountMode(arr[2]) && arr[2] == "rw"
	default:
		return nil, fmt.Errorf("Invalid volume specification: %s", spec)
	}

	if !filepath.IsAbs(mnt.hostPath) {
		return nil, fmt.Errorf("cannot bind mount volume: %s volume paths must be absolute.", mnt.hostPath)
	}

	mnt.hostPath = filepath.Clean(mnt.hostPath)
	mnt.containerPath = filepath.Clean(mnt.containerPath)
	return mnt, nil
}
开发者ID:colebrumley,项目名称:docker,代码行数:25,代码来源:volumes.go

示例7: CopyResource

// CopyResource performs an archive copy from the given source path to the
// given destination path. The source path MUST exist and the destination
// path's parent directory must exist.
func CopyResource(srcPath, dstPath string) error {
	var (
		srcInfo CopyInfo
		err     error
	)

	// Ensure in platform semantics
	srcPath = normalizePath(srcPath)
	dstPath = normalizePath(dstPath)

	// Clean the source and destination paths.
	srcPath = PreserveTrailingDotOrSeparator(filepath.Clean(srcPath), srcPath)
	dstPath = PreserveTrailingDotOrSeparator(filepath.Clean(dstPath), dstPath)

	if srcInfo, err = CopyInfoSourcePath(srcPath); err != nil {
		return err
	}

	content, err := TarResource(srcInfo)
	if err != nil {
		return err
	}
	defer content.Close()

	return CopyTo(content, srcInfo, dstPath)
}
开发者ID:lunohq,项目名称:captain,代码行数:29,代码来源:copy.go

示例8: handleFileChange

func handleFileChange(event fsnotify.Event) {

	validC, _ := regexp.MatchString(validCString, event.Name)
	validH, _ := regexp.MatchString(validHString, event.Name)

	db := <-writer
	defer func() { writer <- db }()

	switch {
	case validC:
		switch {
		case event.Op&(fsnotify.Create|fsnotify.Write) != 0:
			files <- event.Name
		case event.Op&(fsnotify.Remove|fsnotify.Rename) != 0:
			db.RemoveFileReferences(event.Name)
		}
	case validH:
		exist, uptodate, _, err := db.UptodateFile(event.Name)
		switch {
		case err != nil:
			return
		case event.Op&(fsnotify.Write) != 0:
			if exist && !uptodate {
				removeFileAndReparseDepends(filepath.Clean(event.Name), db)
			}
		case event.Op&(fsnotify.Remove|fsnotify.Rename) != 0:
			if exist {
				removeFileAndReparseDepends(filepath.Clean(event.Name), db)
			}
		}
	}
}
开发者ID:rahulpathakgit,项目名称:navc,代码行数:32,代码来源:files.go

示例9: MakeParser

func MakeParser(src, projectPath, scriptPath, fileName string, isRootFile bool, compilingMixer bool, layers []string, appliedLayers string) *Parser {
	fullpath := filepath.Join(projectPath, scriptPath, fileName)
	fullpath, _ = filepath.Abs(fullpath)
	scriptPath = filepath.Clean(scriptPath)
	projectPath = filepath.Clean(projectPath)
	p := &Parser{
		Tokenizer:      MakeTokenizer([]byte(src)),
		ProjectPath:    projectPath, // the project path (probably absolute)
		ScriptPath:     scriptPath,  // the folder containing the script file being parsed (relative to the project path)
		FileName:       fileName,    // the base-name of the script file being parsed
		FullPath:       fullpath,
		Lookahead:      nil,
		counter:        0,
		RootFile:       isRootFile,
		Namespaces:     make([]string, 1),
		Defspace:       "tritium",
		inFunc:         false,
		CompilingMixer: compilingMixer,
		Layers:         layers,
		AppliedLayers:  appliedLayers,
	}
	p.Namespaces[0] = "tritium"
	p.pop()
	return p
}
开发者ID:nmakiya,项目名称:tritium,代码行数:25,代码来源:squid_parser.go

示例10: main

func main() {
	flag.Parse()

	args := flag.Args()
	if len(args) < 2 {
		logrus.Fatal("Expecting source and target directory")
	}

	targetDir, err := filepath.Abs(args[len(args)-1])
	if err != nil {
		logrus.Fatal("Error resolving target directory %s: %v", args[len(args)-1], err)
	}
	targetDir = filepath.Clean(targetDir)

	for _, bundleDir := range args[:len(args)-1] {
		absDir, err := filepath.Abs(bundleDir)
		if err != nil {
			logrus.Fatalf("Error resolving directory %s: %v", bundleDir, err)
		}
		bundleDir = filepath.Clean(absDir)
		logrus.Infof("Copying %s to %s", bundleDir, targetDir)
		if err := buildutil.CopyBundleBinaries(bundleDir, targetDir); err != nil {
			logrus.Fatalf("Error copying binaries: %v", err)
		}
	}
}
开发者ID:dmcgowan,项目名称:dockerdevtools,代码行数:26,代码来源:main.go

示例11: LoadConfig

func LoadConfig() {
	var cp = os.Getenv("ICECONFIGPATH")
	if cp == "" {
		dir, err := os.Getwd()
		if err != nil {
			panic(err)
		}
		cp = findEnv(dir)
	} else {
		cp = path.Join(path.Clean(cp), ".env")
	}

	fs, err := os.Open(cp)
	if err != nil {
		panic("Error opening config file " + cp + err.Error())
	}
	defer fs.Close()

	err = ParseJSON(fs, &Config)
	if err != nil {
		panic("Error parsing config file " + err.Error())
	}
	Config.ConfigRoot = path.Dir(cp)
	if !path.IsAbs(Config.MigrationPath) {
		Config.MigrationPath = path.Clean(path.Join(Config.ConfigRoot, Config.MigrationPath))
	}

	if Config.Settings == nil {
		Config.Settings = make(map[string]string)
	}
}
开发者ID:codking7,项目名称:ice,代码行数:31,代码来源:config.go

示例12: sqlclusterPath

func sqlclusterPath() string {
	dir := scriptDir()

	// If you're using our build script, sqlcluster will be a
	// directory down from octopus.
	p := filepath.Clean(filepath.Join(dir, "../sqlcluster"))
	if isExecutable(p) {
		return p
	}

	// See whether you built it somewhere in your GOPATH
	search := strings.Split(os.Getenv("GOPATH"), ":")
	for _, d := range search {
		p := filepath.Clean(filepath.Join(d, "src/stripe-ctf.com/sqlcluster/sqlcluster"))
		if isExecutable(p) {
			return p
		}

		p = filepath.Clean(filepath.Join(d, "bin/sqlcluster"))
		if isExecutable(p) {
			return p
		}
	}

	// As a last ditch, see whether it's in our path
	p, err := exec.LookPath("sqlcluster")
	if err == nil {
		return p
	}

	return ""
}
开发者ID:WIZARD-CXY,项目名称:golang-devops-stuff,代码行数:32,代码来源:defaults.go

示例13: LoadPackages

func (r *Repository) LoadPackages(funcMap GoTemplate.FuncMap) {
	log.Trace.Printf("Loading packages from %s ", filepath.Clean(r.configDirectory+"/packages.json"))
	ok := r.loadPackagesFromFile(filepath.Clean(r.configDirectory+"/packages.json"), funcMap)
	if !ok {
		log.Warning.Printf("Could not load packages from packages.json")
	}

	_, err := os.Stat(filepath.Clean(r.configDirectory + "/conf.d/"))
	if err == nil {
		log.Trace.Printf("Loading packages from %s ", filepath.Clean(r.configDirectory+"/conf.d"))
		files, _ := filepath.Glob(filepath.Clean(r.configDirectory + "/conf.d/*.json"))
		for _, f := range files {
			ok := r.loadPackagesFromFile(f, funcMap)
			if !ok {
				log.Info.Printf("Could not load packages from file: %s", f)
			}
		}
	}

	if r.packages == nil || len(r.packages) <= 0 {
		log.Warning.Printf("No package definitions were found")
	} else {
		log.Info.Printf("%d packages have been loaded", len(r.packages))
	}
}
开发者ID:cchamplin,项目名称:deployd,代码行数:25,代码来源:repository.go

示例14: PostProcess

// 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)
	}
}
开发者ID:shishkander,项目名称:luci-go,代码行数:29,代码来源:isolate.go

示例15: WalkDirectory

func WalkDirectory(walkDirectories []string) (directoryList []string, fileList []string, templateList []string, err error) {
	for _, value := range walkDirectories {
		log.Debugf("+ Going to Walk %s", value)
		if DirectoryExists(value) {
			err = filepath.Walk(value, func(path string, f os.FileInfo, err error) error {
				log.Debugf("  + %s", f.Name())
				if f.IsDir() {
					directoryList = append(directoryList, filepath.Clean(path))
				} else {
					if strings.HasPrefix(f.Name(), ".") {
						return nil
					}
					if !strings.Contains(f.Name(), ".mustache") {
						fileList = append(fileList, filepath.Clean(path))
					} else {
						if !strings.Contains(f.Name(), ".after") || !strings.Contains(f.Name(), ".before") {
							templateList = append(templateList, filepath.Clean(path))
						}
					}
				}
				return nil
			})
		}
		if err != nil {
			return []string{}, []string{}, []string{}, err
		}
	}
	return directoryList, fileList, templateList, nil
}
开发者ID:flexiant,项目名称:tt,代码行数:29,代码来源:utils.go


注:本文中的path/filepath.Clean函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。