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


Golang path.Clean函数代码示例

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


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

示例1: NewTemp

// NewTemp create new Temp structure
func NewTemp(args ...string) (*Temp, error) {
	tempDir := path.Clean(Dir)

	if len(args) != 0 {
		tempDir = path.Clean(args[0])
	}

	if !fsutil.IsExist(tempDir) {
		return nil, fmt.Errorf("Directory %s is not exist", tempDir)
	}

	if !fsutil.IsDir(tempDir) {
		return nil, fmt.Errorf("%s is not a directory", tempDir)
	}

	if !fsutil.IsWritable(tempDir) {
		return nil, fmt.Errorf("Directory %s is not writable", tempDir)
	}

	return &Temp{
		Dir:       tempDir,
		DirPerms:  DefaultDirPerms,
		FilePerms: DefaultFilePerms,
	}, nil
}
开发者ID:essentialkaos,项目名称:ek,代码行数:26,代码来源:tmp.go

示例2: arrangeFilename

func arrangeFilename(filename string) string {
	if len(filename) == 0 {
		return filename
	}

	gopath := path.Join(os.Getenv("GOPATH"), "/src/")
	pwd, _ := os.Getwd()
	mayBeRelPath := path.Clean(path.Join(pwd, filename))
	if strings.HasPrefix(mayBeRelPath, gopath) {
		s := mayBeRelPath[len(gopath):]
		if s[0:1] == "/" {
			filename = s[1:]
		}
	}
	mayBeAbsPath := path.Clean(filename)
	if strings.HasPrefix(mayBeAbsPath, gopath) {
		s := mayBeAbsPath[len(gopath):]
		if s[0:1] == "/" {
			filename = s[1:]
		}
	}

	filename = strings.TrimPrefix(filename, sourceDir)
	return filename
}
开发者ID:paetzke,项目名称:go-dep-graph,代码行数:25,代码来源:main.go

示例3: discoverExecName

/*
  Returns absolute path of executing file.
  WARNING: this must be called before
  changing the current directory
*/
func discoverExecName() string {
	if DEBUG {
		log.Print("Debug: discoverExecName\n")
	}

	f := os.Args[0]
	if path.IsAbs(f) {
		return f
	}

	wd, err := os.Getwd()
	if err != nil {
		panic(fmt.Sprintf("Getwd failed: %s", err))
	}

	_, err = os.Stat(f)
	if err == nil { // relative file exists
		return path.Clean(path.Join(wd, f))
	} // not exists? lookup in path

	f2, err := exec.LookPath(f)
	if err != nil {
		panic(fmt.Sprintf("lookpath failed: %s", err))
	}

	if path.IsAbs(f2) {
		return f2
	}

	return path.Clean(path.Join(wd, f2))
}
开发者ID:BioinformaticsArchive,项目名称:BigDataScript,代码行数:36,代码来源:bds.go

示例4: listBlobFiles

func (b *BlobStore) listBlobFiles(baseURL *url.URL) ([]blob.Blob, error) {
	listResp, err := b.doListRequest(baseURL)
	if err != nil {
		return nil, err
	}

	var blobFiles []blob.Blob
	for _, resp := range listResp.Responses {
		u, err := url.Parse(resp.HREF)
		if err != nil {
			return nil, err
		}

		if path.Clean(u.Path) == path.Clean(baseURL.Path) {
			continue
		}

		blobFiles = append(blobFiles, blob.Blob{
			Path:    strings.Replace(path.Clean(u.Path), "/blobs/", "", 1),
			Created: time.Time(resp.LastModified),
			Size:    resp.ContentLength,
		})
	}

	return blobFiles, nil
}
开发者ID:davidwadden,项目名称:ltc,代码行数:26,代码来源:blob_store.go

示例5: setVolumeMount

func (v *VolumeOptions) setVolumeMount(spec *kapi.PodSpec, info *resource.Info) error {
	opts := v.AddOpts
	containers, _ := selectContainers(spec.Containers, v.Containers)
	if len(containers) == 0 && v.Containers != "*" {
		fmt.Fprintf(v.Err, "warning: %s/%s does not have any containers matching %q\n", info.Mapping.Resource, info.Name, v.Containers)
		return nil
	}

	for _, c := range containers {
		for _, m := range c.VolumeMounts {
			if path.Clean(m.MountPath) == path.Clean(opts.MountPath) && m.Name != v.Name {
				return fmt.Errorf("volume mount '%s' already exists for container '%s'", opts.MountPath, c.Name)
			}
		}
		for i, m := range c.VolumeMounts {
			if m.Name == v.Name {
				c.VolumeMounts = append(c.VolumeMounts[:i], c.VolumeMounts[i+1:]...)
				break
			}
		}
		volumeMount := &kapi.VolumeMount{
			Name:      v.Name,
			MountPath: path.Clean(opts.MountPath),
		}
		c.VolumeMounts = append(c.VolumeMounts, *volumeMount)
	}
	return nil
}
开发者ID:hloganathan,项目名称:origin,代码行数:28,代码来源:volume.go

示例6: posixRel

// posixRel returns a relative path that is lexically equivalent to targpath when
// joined to basepath with an intervening separator.
//
// That is, Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself.
// On success, the returned path will always be relative to basepath,
// even if basepath and targpath share no elements.
// An error is returned if targpath can't be made relative to basepath or if
// knowing the current working directory would be necessary to compute it.
//
// Copy-pasted & slightly edited from Go's lib path/filepath/path.go .
//
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
func posixRel(basepath, targpath string) (string, error) {
	base := path.Clean(basepath)
	targ := path.Clean(targpath)
	if targ == base {
		return ".", nil
	}
	if base == "." {
		base = ""
	}
	if path.IsAbs(base) != path.IsAbs(targ) {
		return "", errors.New("Rel: can't make " + targ + " relative to " + base)
	}
	// Position base[b0:bi] and targ[t0:ti] at the first differing elements.
	bl := len(base)
	tl := len(targ)
	var b0, bi, t0, ti int
	for {
		for bi < bl && base[bi] != '/' {
			bi++
		}
		for ti < tl && targ[ti] != '/' {
			ti++
		}
		if targ[t0:ti] != base[b0:bi] {
			break
		}
		if bi < bl {
			bi++
		}
		if ti < tl {
			ti++
		}
		b0 = bi
		t0 = ti
	}
	if base[b0:bi] == ".." {
		return "", errors.New("Rel: can't make " + targ + " relative to " + base)
	}
	if b0 != bl {
		// Base elements left. Must go up before going down.
		seps := strings.Count(base[b0:bl], string('/'))
		size := 2 + seps*3
		if tl != t0 {
			size += 1 + tl - t0
		}
		buf := make([]byte, size)
		n := copy(buf, "..")
		for i := 0; i < seps; i++ {
			buf[n] = '/'
			copy(buf[n+1:], "..")
			n += 3
		}
		if t0 != tl {
			buf[n] = '/'
			copy(buf[n+1:], targ[t0:])
		}
		return string(buf), nil
	}
	return targ[t0:], nil
}
开发者ID:shishkander,项目名称:luci-go,代码行数:74,代码来源:utils.go

示例7: Uglify

// Uglify does the opposite of PrettifyURLPath().
//     /section/name/index.html becomes /section/name.html
//     /section/name/           becomes /section/name.html
//     /section/name.html       becomes /section/name.html
func Uglify(in string) string {
	if path.Ext(in) == "" {
		if len(in) < 2 {
			return "/"
		}
		// /section/name/  -> /section/name.html
		return path.Clean(in) + ".html"
	}

	name, ext := fileAndExt(in, pb)
	if name == "index" {
		// /section/name/index.html -> /section/name.html
		d := path.Dir(in)
		if len(d) > 1 {
			return d + ext
		}
		return in
	}
	// /.xml -> /index.xml
	if name == "" {
		return path.Dir(in) + "index" + ext
	}
	// /section/name.html -> /section/name.html
	return path.Clean(in)
}
开发者ID:vincentsys,项目名称:hugo,代码行数:29,代码来源:url.go

示例8: Suffix

// Return the suffix of p relative to base
// Both paths must be absolute or both relative.
// Pref can be empty.
// If there's no such suffix, the empty string is returned.
// The suffix starts with '/' and is "/" if b == p
func Suffix(p, pref string) string {
	if len(p) == 0 {
		return ""
	}
	p = path.Clean(p)
	if pref == "" {
		return p
	}
	pref = path.Clean(pref)
	if (pref[0] == '/') != (p[0] == '/') {
		return ""
	}
	if pref == "." || pref == "/" {
		return p
	}
	np := len(p)
	npref := len(pref)
	if np < npref {
		return ""
	}
	switch {
	case !strings.HasPrefix(p, pref):
		return ""
	case np == npref:
		return "/"
	case p[npref] != '/':
		return ""
	default:
		return p[npref:]
	}
}
开发者ID:fjballest,项目名称:clive,代码行数:36,代码来源:util.go

示例9: CommonPrefix

func CommonPrefix(sep string, paths ...string) string {
	// Handle special cases.
	switch len(paths) {
	case 0:
		return ""
	case 1:
		return path.Clean(paths[0])
	}

	c := []byte(path.Clean(paths[0]))

	// Ignore the first path since it's already in c.
	for _, v := range paths[1:] {
		// Clean up each path before testing it.
		v = path.Clean(v)

		// Get the length of the shorter slice.
		shorter := len(v)
		if len(v) > len(c) {
			shorter = len(c)
		}

		// Find the first non-common character and copy up to it into c.
		for i := 0; i < shorter; i++ {
			if v[i] != c[i] {
				c = c[0:i]
				break
			}
		}
	}

	// Correct for problem caused by prepending the actual common path to the
	// list of paths searched through.
	for _, v := range paths {
		if len(v) > len(c) {
			if strings.HasPrefix(v, string(c)) {
				if len(v) > len(c)+len(sep) {
					if v[len(c):len(c)+len(sep)] == sep {
						c = append(c, []byte(sep)...)
						break
					}
				}
			}
		}
	}

	// Remove trailing non-seperator characters.
	for i := len(c) - 1; i >= 0; i-- {
		if i+len(sep) > len(c) {
			continue
		}

		if string(c[i:i+len(sep)]) == sep {
			c = c[0:i]
			break
		}
	}

	return string(c)
}
开发者ID:nellaivijay,项目名称:RosettaCodeData,代码行数:60,代码来源:find-common-directory-path.go

示例10: SetEnvParams

// TODO(phase1+) Move these paramaters to the API group
// we need some params for testing etc, let's keep these hidden for now
func SetEnvParams() *EnvParams {

	envParams := map[string]string{
		"kubernetes_dir":  "/etc/kubernetes",
		"host_pki_path":   "/etc/kubernetes/pki",
		"host_etcd_path":  "/var/lib/etcd",
		"hyperkube_image": "",
		"repo_prefix":     "gcr.io/google_containers",
		"discovery_image": fmt.Sprintf("gcr.io/google_containers/kube-discovery-%s:%s", runtime.GOARCH, "1.0"),
		"etcd_image":      "",
	}

	for k := range envParams {
		if v := strings.TrimSpace(os.Getenv(fmt.Sprintf("KUBE_%s", strings.ToUpper(k)))); v != "" {
			envParams[k] = v
		}
	}

	return &EnvParams{
		KubernetesDir:    path.Clean(envParams["kubernetes_dir"]),
		HostPKIPath:      path.Clean(envParams["host_pki_path"]),
		HostEtcdPath:     path.Clean(envParams["host_etcd_path"]),
		HyperkubeImage:   envParams["hyperkube_image"],
		RepositoryPrefix: envParams["repo_prefix"],
		DiscoveryImage:   envParams["discovery_image"],
		EtcdImage:        envParams["etcd_image"],
	}
}
开发者ID:johscheuer,项目名称:kubernetes,代码行数:30,代码来源:env.go

示例11: SubtestKey

func (ks *KeySuite) SubtestKey(s string, c *C) {
	fixed := path.Clean("/" + s)
	namespaces := strings.Split(fixed, "/")[1:]
	lastNamespace := namespaces[len(namespaces)-1]
	lnparts := strings.Split(lastNamespace, ":")
	ktype := ""
	if len(lnparts) > 1 {
		ktype = strings.Join(lnparts[:len(lnparts)-1], ":")
	}
	kname := lnparts[len(lnparts)-1]

	kchild := path.Clean(fixed + "/cchildd")
	kparent := "/" + strings.Join(append(namespaces[:len(namespaces)-1]), "/")
	kpath := path.Clean(kparent + "/" + ktype)
	kinstance := fixed + ":" + "inst"

	c.Log("Testing: ", NewKey(s))

	c.Check(NewKey(s).String(), Equals, fixed)
	c.Check(NewKey(s), Equals, NewKey(s))
	c.Check(NewKey(s).String(), Equals, NewKey(s).String())
	c.Check(NewKey(s).Name(), Equals, kname)
	c.Check(NewKey(s).Type(), Equals, ktype)
	c.Check(NewKey(s).Path().String(), Equals, kpath)
	c.Check(NewKey(s).Instance("inst").String(), Equals, kinstance)

	c.Check(NewKey(s).Child("cchildd").String(), Equals, kchild)
	c.Check(NewKey(s).Child("cchildd").Parent().String(), Equals, fixed)
	c.Check(NewKey(s).Parent().String(), Equals, kparent)
	c.Check(len(NewKey(s).List()), Equals, len(namespaces))
	c.Check(len(NewKey(s).Namespaces()), Equals, len(namespaces))
	for i, e := range NewKey(s).List() {
		c.Check(namespaces[i], Equals, e)
	}
}
开发者ID:mappum,项目名称:go-ipfs,代码行数:35,代码来源:key_test.go

示例12: url

// url returns a parsed url to the given path. c must not be nil
func (b *Bucket) url(bPath string, c *Config) (*url.URL, error) {

	// parse versionID parameter from path, if included
	// See https://github.com/rlmcpherson/s3gof3r/issues/84 for rationale
	purl, err := url.Parse(bPath)
	if err != nil {
		return nil, err
	}
	var vals url.Values
	if v := purl.Query().Get(versionParam); v != "" {
		vals = make(url.Values)
		vals.Add(versionParam, v)
		bPath = strings.Split(bPath, "?")[0] // remove versionID from path
	}

	// handling for bucket names containing periods / explicit PathStyle addressing
	// http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html for details
	if strings.Contains(b.Name, ".") || c.PathStyle {
		return &url.URL{
			Host:     b.S3.Domain,
			Scheme:   c.Scheme,
			Path:     path.Clean(fmt.Sprintf("/%s/%s", b.Name, bPath)),
			RawQuery: vals.Encode(),
		}, nil
	} else {
		return &url.URL{
			Scheme:   c.Scheme,
			Path:     path.Clean(fmt.Sprintf("/%s", bPath)),
			Host:     path.Clean(fmt.Sprintf("%s.%s", b.Name, b.S3.Domain)),
			RawQuery: vals.Encode(),
		}, nil
	}
}
开发者ID:rlmcpherson,项目名称:s3gof3r,代码行数:34,代码来源:s3gof3r.go

示例13: NewCfIgnore

func NewCfIgnore(text string) CfIgnore {
	patterns := []ignorePattern{}
	inclusions := []glob.Glob{}
	exclusions := []glob.Glob{}

	lines := strings.Split(text, "\n")
	lines = append(DefaultIgnoreFiles, lines...)

	for _, pattern := range lines {
		pattern = strings.TrimSpace(pattern)
		if pattern == "" {
			continue
		}

		if strings.HasPrefix(pattern, "!") {
			pattern := pattern[1:]
			pattern = path.Clean(pattern)
			inclusions = append(inclusions, globsForPattern(pattern)...)
		} else {
			pattern = path.Clean(pattern)
			exclusions = append(exclusions, globsForPattern(pattern)...)
		}
	}

	for _, glob := range exclusions {
		patterns = append(patterns, ignorePattern{true, glob})
	}
	for _, glob := range inclusions {
		patterns = append(patterns, ignorePattern{false, glob})
	}

	return cfIgnore(patterns)
}
开发者ID:knolleary,项目名称:cli,代码行数:33,代码来源:cf_ignore.go

示例14: main

func main() {
	hostPtr := flag.String("host", "localhost", "hostname of the server")
	portPtr := flag.Int("port", 30000, "port that the server runs on")
	keyPtr := flag.String("key", "client.private", "private key for authentication")
	servKeyPtr := flag.String("servkey", "server.public", "public key of the server")
	flag.Parse()

	sock, err := zmq.NewSocket(zmq.REQ)
	condlog.Fatal(err, "Unable to create socket")
	defer sock.Close()
	initSecurity(path.Clean(*keyPtr), path.Clean(*servKeyPtr), sock)

	err = sock.Connect(fmt.Sprintf("tcp://%s:%d", *hostPtr, *portPtr))
	condlog.Fatal(err, "Unable to connect")

	in := bufio.NewScanner(os.Stdin)
	fmt.Print("> ")
	for in.Scan() {
		hand := in.Text()

		results := solve(hand, sock)
		for _, r := range results {
			fmt.Println(r)
		}
		fmt.Print("> ")
	}

	condlog.Fatal(in.Err(), "Unable to read from stdin")
}
开发者ID:hjmat,项目名称:scrabbled,代码行数:29,代码来源:client.go

示例15: expandOutputs

func expandOutputs(output string, dirDst, usePipe bool, tasks *[]task) bool {
	if output != "" {
		output = path.Clean(filepath.ToSlash(output))
		if output[len(output)-1] != '/' {
			info, err := os.Stat(output)
			if err == nil && info.Mode().IsDir() {
				output += "/"
			}
		}
		if dirDst {
			if output[len(output)-1] != '/' {
				output += "/"
			}
			if err := os.MkdirAll(output, 0777); err != nil {
				fmt.Fprintln(os.Stderr, "ERROR: "+err.Error())
				os.Exit(1)
			}
		} else if output[len(output)-1] == '/' {
			output += "out"
		}
	}

	if verbose {
		if output == "" {
			if usePipe {
				fmt.Fprintln(os.Stderr, "INFO:  minify to stdout")
			} else {
				fmt.Fprintln(os.Stderr, "INFO:  minify to overwrite itself")
			}
		} else if output[len(output)-1] != '/' {
			fmt.Fprintf(os.Stderr, "INFO:  minify to output file %v\n", output)
		} else if output == "./" {
			fmt.Fprintf(os.Stderr, "INFO:  minify to current working directory\n")
		} else {
			fmt.Fprintf(os.Stderr, "INFO:  minify to output directory %v\n", output)
		}
	}

	ok := true
	for i, t := range *tasks {
		if !usePipe && output == "" {
			(*tasks)[i].dst = (*tasks)[i].src
		} else {
			(*tasks)[i].dst = output
		}
		if len(output) > 0 && output[len(output)-1] == '/' {
			rel, err := filepath.Rel(t.srcDir, t.src)
			if err != nil {
				fmt.Fprintln(os.Stderr, "ERROR: "+err.Error())
				ok = false
			}
			(*tasks)[i].dst = path.Clean(filepath.ToSlash(path.Join(output, rel)))
		}
	}

	if usePipe && len(*tasks) == 0 {
		*tasks = append(*tasks, task{"", "", output})
	}
	return ok
}
开发者ID:heimonsy,项目名称:minify,代码行数:60,代码来源:main.go


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