// append a path separator if needed and escape regexp meta characters func fileMatchRegexp(logRoot, fileMatch string) *regexp.Regexp { if !os.IsPathSeparator(logRoot[len(logRoot)-1]) && !os.IsPathSeparator(fileMatch[0]) { logRoot += string(os.PathSeparator) } return regexp.MustCompile("^" + regexp.QuoteMeta(logRoot) + fileMatch) }
func walkLinks(path string, linksWalked *int) (string, error) { switch dir, file := Split(path); { case dir == "": newpath, _, err := walkLink(file, linksWalked) return newpath, err case file == "": if isDriveLetter(dir) { return dir, nil } if os.IsPathSeparator(dir[len(dir)-1]) { if isRoot(dir) { return dir, nil } return walkLinks(dir[:len(dir)-1], linksWalked) } newpath, _, err := walkLink(dir, linksWalked) return newpath, err default: newdir, err := walkLinks(dir, linksWalked) if err != nil { return "", err } newpath, islink, err := walkLink(Join(newdir, file), linksWalked) if err != nil { return "", err } if !islink { return newpath, nil } if IsAbs(newpath) || os.IsPathSeparator(newpath[0]) { return newpath, nil } return Join(newdir, newpath), nil } }
func mrtFileOpen(filename string, interval uint64) (*os.File, error) { realname := filename if interval != 0 { realname = time.Now().Format(filename) } i := len(realname) for i > 0 && os.IsPathSeparator(realname[i-1]) { // skip trailing path separators i-- } j := i for j > 0 && !os.IsPathSeparator(realname[j-1]) { j-- } if j > 0 { if err := os.MkdirAll(realname[0:j-1], 0755); err != nil { log.Warn(err) return nil, err } } file, err := os.OpenFile(realname, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644) if err != nil { log.Warn(err) } return file, err }
// FindAndParseIndexYAML walks up from the directory specified by path until it // finds a `index.yaml` or `index.yml` file. If an index YAML file // is found, it opens and parses the file, and returns all the indexes found. // If path is a relative path, it is converted into an absolute path // relative to the calling test file. To determine the path of the calling test // file, FindAndParseIndexYAML walks upto a maximum of 100 call stack frames // looking for a file ending with `_test.go`. // // FindAndParseIndexYAML returns a non-nil error if the root of the drive is // reached without finding an index YAML file, if there was // an error reading the found index YAML file, or if the calling test file could // not be located in the case of a relative path argument. func FindAndParseIndexYAML(path string) ([]*IndexDefinition, error) { var currentDir string if filepath.IsAbs(path) { currentDir = path } else { testPath, err := getCallingTestFilePath(100) if err != nil { return nil, err } currentDir = filepath.Join(filepath.Dir(testPath), path) } isRoot := func(dir string) bool { parentDir := filepath.Dir(dir) return os.IsPathSeparator(dir[len(dir)-1]) && os.IsPathSeparator(parentDir[len(parentDir)-1]) } for { for _, filename := range []string{"index.yml", "index.yaml"} { file, err := os.Open(filepath.Join(currentDir, filename)) if err == nil { defer file.Close() return ParseIndexYAML(file) } } if isRoot(currentDir) { return nil, fmt.Errorf("datastore: failed to find index YAML file") } currentDir = filepath.Dir(currentDir) } }
func simplifyFilePath(path string) string { pathLen := len(path) if strings.HasPrefix(path, goroot) && pathLen > len(goroot) { return path[len(goroot):] } for _, tmpPath := range sourcePaths { var check string if len(tmpPath) > 1 && os.IsPathSeparator(tmpPath[0]) { check = tmpPath[1:] } else { check = tmpPath } if strings.HasPrefix(path, check) && pathLen > len(check) { var src, pkg string src = path + "src" + string(os.PathSeparator) pkg = path + "pkg" + string(os.PathSeparator) if strings.HasPrefix(path, src) && pathLen > len(src) { return path[len(src):] } else if strings.HasPrefix(path, pkg) && pathLen > len(pkg) { return path[len(pkg):] } else { return path[len(check):] } } } if pathLen > 1 && os.IsPathSeparator(path[0]) { path = path[1:] } return path }
func (c *Client) MkdirAll(path string) error { dir, err := c.Stat(path) if err == nil { if dir.IsDir() { return nil } } i := len(path) for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. i-- } j := i for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. j-- } if j > 1 { // Create parent err = c.MkdirAll(path[0 : j-1]) if err != nil { return err } } err = c.Mkdir(path) if err != nil { return err } return nil }
func mkdirAll(path string, hdr Metadata) (stack []string, topMTime time.Time, err error) { // Following code derives from the golang standard library, so you can consider it BSDish if you like. // Our changes are licensed under Apache for the sake of overall license simplicity of the project. // Ref: https://github.com/golang/go/blob/883bc6ed0ea815293fe6309d66f967ea60630e87/src/os/path.go#L12 // Fast path: if we can tell whether path is a directory or file, stop with success or error. dir, err := os.Stat(path) if err == nil { if dir.IsDir() { return nil, dir.ModTime(), nil } return nil, dir.ModTime(), &os.PathError{"mkdir", path, syscall.ENOTDIR} } // Slow path: make sure parent exists and then call Mkdir for path. i := len(path) for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. i-- } j := i for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. j-- } if j > 1 { // Create parent stack, topMTime, err = mkdirAll(path[0:j-1], hdr) if err != nil { return stack, topMTime, err } } // Parent now exists; invoke Mkdir and use its result. err = os.Mkdir(path, 0755) if err != nil { // Handle arguments like "foo/." by // double-checking that directory doesn't exist. dir, err1 := os.Lstat(path) if err1 == nil && dir.IsDir() { return stack, topMTime, nil } return stack, topMTime, err } stack = append(stack, path) // Apply standardizations. if err := os.Lchown(path, hdr.Uid, hdr.Gid); err != nil { return stack, topMTime, err } if err := os.Chmod(path, hdr.FileMode()); err != nil { return stack, topMTime, err } // Except for time, because as usual with dirs, that requires walking backwards again at the end. // That'll be done one function out. return stack, topMTime, nil }
func walkSymlinks(path string) (string, error) { const maxIter = 255 originalPath := path // consume path by taking each frontmost path element, // expanding it if it's a symlink, and appending it to b var b bytes.Buffer for n := 0; path != ""; n++ { if n > maxIter { return "", errors.New("EvalSymlinks: too many links in " + originalPath) } // find next path component, p var i = -1 for j, c := range path { if c < utf8RuneSelf && os.IsPathSeparator(uint8(c)) { i = j break } } var p string if i == -1 { p, path = path, "" } else { p, path = path[:i], path[i+1:] } if p == "" { if b.Len() == 0 { // must be absolute path b.WriteRune(Separator) } continue } fi, err := os.Lstat(b.String() + p) if err != nil { return "", err } if fi.Mode()&os.ModeSymlink == 0 { b.WriteString(p) if path != "" || (b.Len() == 2 && len(p) == 2 && p[1] == ':') { b.WriteRune(Separator) } continue } // it's a symlink, put it at the front of path dest, err := os.Readlink(b.String() + p) if err != nil { return "", err } if IsAbs(dest) || os.IsPathSeparator(dest[0]) { b.Reset() } path = dest + string(Separator) + path } return Clean(b.String()), nil }
// mkdirall is a custom version of os.MkdirAll modified for use on Windows // so that it is both volume path aware, and can create a directory with // a DACL. func mkdirall(path string, adminAndLocalSystem bool) error { if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) { return nil } // The rest of this method is largely copied from os.MkdirAll and should be kept // as-is to ensure compatibility. // Fast path: if we can tell whether path is a directory or file, stop with success or error. dir, err := os.Stat(path) if err == nil { if dir.IsDir() { return nil } return &os.PathError{ Op: "mkdir", Path: path, Err: syscall.ENOTDIR, } } // Slow path: make sure parent exists and then call Mkdir for path. i := len(path) for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. i-- } j := i for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. j-- } if j > 1 { // Create parent err = mkdirall(path[0:j-1], false) if err != nil { return err } } // Parent now exists; invoke os.Mkdir or mkdirWithACL and use its result. if adminAndLocalSystem { err = mkdirWithACL(path) } else { err = os.Mkdir(path, 0) } if err != nil { // Handle arguments like "foo/." by // double-checking that directory doesn't exist. dir, err1 := os.Lstat(path) if err1 == nil && dir.IsDir() { return nil } return err } return nil }
// Like os.MkdirAll but new components created have the given UID and GID. func mkdirAllWithOwner(absPath string, perm os.FileMode, uid, gid int) error { // From os/path.go. // Fast path: if we can tell whether path is a directory or file, stop with success or error. dir, err := os.Stat(absPath) if err == nil { if dir.IsDir() { return nil } return &os.PathError{"mkdir", absPath, syscall.ENOTDIR} } // Slow path: make sure parent exists and then call Mkdir for path. i := len(absPath) for i > 0 && os.IsPathSeparator(absPath[i-1]) { // Skip trailing path separator. i-- } j := i for j > 0 && !os.IsPathSeparator(absPath[j-1]) { // Scan backward over element. j-- } if j > 1 { // Create parent err = mkdirAllWithOwner(absPath[0:j-1], perm, uid, gid) if err != nil { return err } } // Parent now exists; invoke Mkdir and use its result. err = os.Mkdir(absPath, perm) if err != nil { // Handle arguments like "foo/." by double-checking that directory // doesn't exist. dir, err1 := os.Lstat(absPath) if err1 == nil && dir.IsDir() { return nil } return err } if uid >= 0 || gid >= 0 { if uid < 0 { uid = os.Getuid() } if gid < 0 { gid = os.Getgid() } err = os.Lchown(absPath, uid, gid) // ignore errors in case we aren't root log.Errore(err, "cannot chown ", absPath) } return nil }
/** * Remove a string's leading and trailing slashes * * @param *string */ func removeSlashes(s *string) { for { if os.IsPathSeparator(((*s)[len(*s)-1 : len(*s)])[0]) { *s = (*s)[0 : len(*s)-1] } else if os.IsPathSeparator(((*s)[0:1])[0]) { *s = (*s)[1:len(*s)] } else { break } } }
// isRoot returns true if path is root of file system // (`/` on unix and `/`, `\`, `c:\` or `c:/` on windows). func isRoot(path string) bool { if runtime.GOOS != "windows" { return path == "/" } switch len(path) { case 1: return os.IsPathSeparator(path[0]) case 3: return path[1] == ':' && os.IsPathSeparator(path[2]) } return false }
// GetParentDir calculate the parent dir of param path, no matter whether path exists. func GetParentDir(path string) string { i := len(path) for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. i-- } j := i for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. j-- } return path[0 : j-1] }
func MkdirAllOwner(path string, perm os.FileMode, uid int, gid int) error { // This function is a slightly modified version of MkdirAll from the Go standard library. // https://golang.org/src/os/path.go?s=488:535#L9 // Fast path: if we can tell whether path is a directory or file, stop with success or error. dir, err := os.Stat(path) if err == nil { if dir.IsDir() { return nil } return fmt.Errorf("path exists but isn't a directory") } // Slow path: make sure parent exists and then call Mkdir for path. i := len(path) for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. i-- } j := i for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. j-- } if j > 1 { // Create parent err = MkdirAllOwner(path[0:j-1], perm, uid, gid) if err != nil { return err } } // Parent now exists; invoke Mkdir and use its result. err = os.Mkdir(path, perm) err_chown := os.Chown(path, uid, gid) if err_chown != nil { return err_chown } if err != nil { // Handle arguments like "foo/." by // double-checking that directory doesn't exist. dir, err1 := os.Lstat(path) if err1 == nil && dir.IsDir() { return nil } return err } return nil }
// mkdirAll creates a directory named path, // along with any necessary parents, and returns nil, // or else returns an error. The permission bits perm are used // for all directories that mkdirAll creates. If path is already // a directory, mkdirAll does nothing and returns nil. func mkdirAll(path string, perm os.FileMode) error { path = preparePath(path) // Fast path: if we can tell whether path is a directory or file, stop with success or error. dir, err := os.Stat(path) if err == nil { if dir.IsDir() { return nil } return &os.PathError{ Op: "mkdir", Path: path, Err: syscall.ENOTDIR, } } // Slow path: make sure parent exists and then call Mkdir for path. i := len(path) for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. i-- } j := i for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. j-- } if j > 1 { // Create parent parent := path[0 : j-1] if parent != filepath.VolumeName(parent) { err = mkdirAll(parent, perm) if err != nil { return err } } } // Parent now exists; invoke Mkdir and use its result. err = os.Mkdir(path, perm) if err != nil { // Handle arguments like "foo/." by // double-checking that directory doesn't exist. dir, err1 := os.Lstat(path) if err1 == nil && dir.IsDir() { return nil } return err } return nil }
func OsSeparator() string { separator := "/" if os.IsPathSeparator('\\') { separator = "\\" } return separator }
func trimPathSeparator(path string) string { last := len(path) - 1 if last > 0 && os.IsPathSeparator(path[last]) { path = path[:last] } return path }
/*Example: Both print C:\Windows\ vfp.Addbs( "C:\\Windows" ) vfp.Addbs( "C:\\Windows\\" ) */ func Addbs(zpath string) (zret string) { if !os.IsPathSeparator(zpath[len(zpath)-1]) { return zpath + string(os.PathSeparator) } return zpath }
func WriteTar(srcPath string, dest io.Writer) error { absPath, err := filepath.Abs(srcPath) if err != nil { return err } tw := tar.NewWriter(dest) defer tw.Close() err = filepath.Walk(absPath, func(path string, info os.FileInfo, err error) error { if err != nil { return err } var relative string if os.IsPathSeparator(srcPath[len(srcPath)-1]) { relative, err = filepath.Rel(absPath, path) } else { relative, err = filepath.Rel(filepath.Dir(absPath), path) } relative = filepath.ToSlash(relative) if err != nil { return err } return addTarFile(path, relative, tw) }) return err }
// Split splits path immediately following the final Separator, // partitioning it into a directory and a file name components. // If there are no separators in path, Split returns an empty base // and file set to path. func Split(path string) (dir, file string) { i := len(path) - 1 for i >= 0 && !os.IsPathSeparator(path[i]) { i-- } return path[:i+1], path[i+1:] }
// Dir returns all but the last element of path, typically the path's directory. // Trailing path separators are removed before processing. // If the path is empty, Dir returns ".". // If the path consists entirely of separators, Dir returns a single separator. // The returned path does not end in a separator unless it is the root directory. func Dir(path string) string { vol := VolumeName(path) i := len(path) - 1 for i >= len(vol) && !os.IsPathSeparator(path[i]) { i-- } dir := Clean(path[len(vol) : i+1]) last := len(dir) - 1 if last > 0 && os.IsPathSeparator(dir[last]) { dir = dir[:last] } if dir == "" { dir = "." } return vol + dir }
// toOutputDir returns the file name relocated, if required, to outputDir. // Simple implementation to avoid pulling in path/filepath. func toOutputDir(path string) string { if *outputDir == "" || path == "" { return path } if runtime.GOOS == "windows" { // On Windows, it's clumsy, but we can be almost always correct // by just looking for a drive letter and a colon. // Absolute paths always have a drive letter (ignoring UNC). // Problem: if path == "C:A" and outputdir == "C:\Go" it's unclear // what to do, but even then path/filepath doesn't help. // TODO: Worth doing better? Probably not, because we're here only // under the management of go test. if len(path) >= 2 { letter, colon := path[0], path[1] if ('a' <= letter && letter <= 'z' || 'A' <= letter && letter <= 'Z') && colon == ':' { // If path starts with a drive letter we're stuck with it regardless. return path } } } if os.IsPathSeparator(path[0]) { return path } return fmt.Sprintf("%s%c%s", *outputDir, os.PathSeparator, path) }
// Ext returns the file name extension used by path. // The extension is the suffix beginning at the final dot // in the final element of path; it is empty if there is // no dot. func Ext(path string) string { for i := len(path) - 1; i >= 0 && !os.IsPathSeparator(path[i]); i-- { if path[i] == '.' { return path[i:] } } return "" }
// Split splits path immediately following the final Separator, // separating it into a directory and file name component. // If there is no Separator in path, Split returns an empty dir // and file set to path. // The returned values have the property that path = dir+file. func Split(path string) (dir, file string) { vol := VolumeName(path) i := len(path) - 1 for i >= len(vol) && !os.IsPathSeparator(path[i]) { i-- } return path[:i+1], path[i+1:] }
func checkStringForPathSeparator(s string, c *rune) bool { for _, *c = range s { if os.IsPathSeparator(uint8(*c)) { return true } } return false }
// Ext it's modified function standart "path/filepath" pkg func Ext(fullname string) (name, ext string) { for i := len(fullname) - 1; i >= 0 && !os.IsPathSeparator(fullname[i]); i-- { if fullname[i] == '.' { return fullname[:i], fullname[i:] } } return "", "" }
// mkdirAll creates a directory named path, along with any necessary parents, // and returns nil, or else returns an error. The permission bits perm are used // for all directories that mkdirAll creates. Also given uid and gid are set. If // path is already a directory, mkdirAll does nothing and returns nil. // // This function is a copy of os.MkdirAll with uid and gid setting. // // TODO: this version should check and ensure that given perm is set for all // path parts func mkdirAll(path string, perm os.FileMode, uid uint, gid uint) error { // {{{ // If path exists, stop with success or error. dir, err := os.Stat(path) if err == nil { if dir.IsDir() { return nil } return &os.PathError{"mkdir", path, syscall.ENOTDIR} } // Doesn't already exist; make sure parent does. i := len(path) for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. i-- } j := i for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. j-- } if j > 1 { // Create parent err = mkdirAll(path[0:j-1], perm, uid, gid) if err != nil { return err } } // Now parent exists, try to create. err = os.Mkdir(path, perm) if err != nil { // Handle arguments like "foo/." by // double-checking that directory doesn't exist. dir, err1 := os.Lstat(path) if err1 == nil && dir.IsDir() { return nil } return err } // Change user and group id if err1 := os.Chown(path, int(uid), int(gid)); err1 != nil { return err1 } return nil } // }}}
// SplitExt returns pair of file name and extension. // // It will truncated a dot of extension. // e.g. When the given path is "path/to/image.png", SplitExt returns ("path/to/image", "png"). func SplitExt(path string) (name, ext string) { for i := len(path) - 1; i >= 0 && !os.IsPathSeparator(path[i]); i-- { if path[i] == '.' { return path[:i], path[i+1:] } } return path, "" }
//编辑器管理 func (c *Kindeditor) Manager(upload *models.Upload) revel.Result { file := make(map[string]interface{}) //判断是否是系统的分隔符 separator := "/" if os.IsPathSeparator('\\') { separator = "\\" } else { separator = "/" } basepath, _ := filepath.Abs("") config_file := (revel.BasePath + "/conf/config.conf") config_file = strings.Replace(config_file, "/", separator, -1) config_conf, _ := config.ReadDefault(config_file) //上传文件目录 upload_dir, _ := config_conf.String("upload", "upload.dir") //允许上传的后缀名 filesuffix, _ := config_conf.String("upload", "upload.filesuffix") revel.WARN.Println(filesuffix) //前台网站地址 sitedomain, _ := config_conf.String("website", "website.sitedomain") //根目录路径,可以指定绝对路径,比如 /var/www/attached/ root_path := fmt.Sprintf("%s/www/%s/", basepath, upload_dir) //根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/ root_url := sitedomain + upload_dir //目录名 dir_name := c.Params.Get("dir") if dir_name != "" { root_path += dir_name + "/" root_url += dir_name + "/" } //相对于根目录的上一级目录 file["moveup_dir_path"] = "" //相对于根目录的当前目录 file["current_dir_path"] = "" //当前目录的URL file["current_url"] = "" //文件数 file["total_count"] = 10 //文件列表数组 file["file_list"] = "" return c.RenderJson(file) }
// Dir returns all but the last element of path, typically the path's directory. // After dropping the final element, the path is Cleaned and trailing // slashes are removed. // If the path is empty, Dir returns ".". // If the path consists entirely of separators, Dir returns a single separator. // The returned path does not end in a separator unless it is the root directory. func Dir(path string) string { vol := VolumeName(path) i := len(path) - 1 for i >= len(vol) && !os.IsPathSeparator(path[i]) { i-- } dir := Clean(path[len(vol) : i+1]) return vol + dir }