func main() { userdata, err := user.Current() if err != nil { log.Fatal(err) } wd, err := os.Getwd() if err != nil { log.Fatal(err) } savedir := userdata.HomeDir scandir := filepath.VolumeName(wd) if filepath.VolumeName(savedir) != scandir { savedir = scandir } savedir += string(filepath.Separator) scandir += string(filepath.Separator) log.Println("Scanning Volume:", scandir) log.Println("Saving Index to:", savedir) data := index(scandir) log.Println("Encoding Index") save(savedir+"index.fed", data) log.Println("Finished") }
// MakeFileURL returns a proper file URL for the given path/directory func MakeFileURL(in string) string { var volumeName string if strings.HasPrefix(in, "file://") { volumeName = filepath.VolumeName(strings.TrimPrefix(in, "file://")) } else { volumeName = filepath.VolumeName(in) } if volumeName != "" { // Strip colon volumeName = strings.TrimSuffix(volumeName, ":") // Do not apply function twice if strings.HasPrefix(in, "file://\\\\localhost\\") { return in } in = filepath.ToSlash(in) prefix := "file://\\\\localhost\\" + volumeName + "$" if strings.HasPrefix(in, volumeName) { return prefix + strings.TrimPrefix(in, volumeName+":") } if strings.HasPrefix(in, "file://"+volumeName) { return prefix + strings.TrimPrefix(in, "file://"+volumeName+":") } } return in }
func CommonRoot(pa, pb string) string { if pa == "" || pb == "" { return "" } pac := filepath.Clean(pa) pbc := filepath.Clean(pb) va := filepath.VolumeName(pac) vb := filepath.VolumeName(pbc) if va != vb { return "" } sa := pac[len(va):] sb := pbc[len(vb):] na := len(sa) nb := len(sb) var cursor, lastSep int lastSep = -1 for { if cursor < na && cursor < nb && sa[cursor] == sb[cursor] { if sa[cursor] == filepath.Separator { lastSep = cursor } cursor++ } else { break } } if cursor == na && na == nb { return pac } if cursor == na && na < nb && sb[na] == filepath.Separator { return pac } if cursor == nb && nb < na && sa[nb] == filepath.Separator { return pbc } if lastSep == -1 { return va + string(filepath.Separator) } res := pac[0 : len(va)+lastSep] if res == "" && filepath.Separator == '/' { return "/" } return res }
func expadGoPath(path string) (r string) { r = path if filepath.VolumeName(path) == "" { r = filepath.Join(gGoPath, path) } return }
func withConfigFixture(t *testing.T, name string, callback func()) { oldHome := os.Getenv("HOME") oldHomePath := os.Getenv("HOMEPATH") oldHomeDrive := os.Getenv("HOMEDRIVE") defer func() { os.Setenv("HOMEDRIVE", oldHomeDrive) os.Setenv("HOMEPATH", oldHomePath) os.Setenv("HOME", oldHome) }() defer func() { singleton = nil }() cwd, err := os.Getwd() assert.NoError(t, err) fixturePath := filepath.Join(cwd, fmt.Sprintf("../../fixtures/config/%s", name)) os.Setenv("HOME", fixturePath) volumeName := filepath.VolumeName(fixturePath) if volumeName != "" { relativePath := strings.Replace(fixturePath, volumeName, "", 1) os.Setenv("HOMEPATH", relativePath) os.Setenv("HOMEDRIVE", volumeName) } callback() }
// This test assumes registry state of NtfsDisable8dot3NameCreation is 2, // the default (Volume level setting). func TestEvalSymlinksCanonicalNamesWith8dot3Disabled(t *testing.T) { if !*runFSModifyTests { t.Skip("skipping test that modifies file system setting; enable with -run_fs_modify_tests") } tempVol := filepath.VolumeName(os.TempDir()) if len(tempVol) != 2 { t.Fatalf("unexpected temp volume name %q", tempVol) } err := checkVolume8dot3Setting(tempVol, true) if err != nil { t.Fatal(err) } err = setVolume8dot3Setting(tempVol, false) if err != nil { t.Fatal(err) } defer func() { err := setVolume8dot3Setting(tempVol, true) if err != nil { t.Fatal(err) } err = checkVolume8dot3Setting(tempVol, true) if err != nil { t.Fatal(err) } }() err = checkVolume8dot3Setting(tempVol, false) if err != nil { t.Fatal(err) } TestEvalSymlinksCanonicalNames(t) }
// EnsureBaseDir ensures that path is always prefixed by baseDir, // allowing for the fact that path might have a Window drive letter in // it. func EnsureBaseDir(baseDir, path string) string { if baseDir == "" { return path } volume := filepath.VolumeName(path) return filepath.Join(baseDir, path[len(volume):]) }
// isLocalPath returns whether the given path is local (/foo ./foo ../foo . ..) // Windows paths that starts with drive letter (c:\foo c:foo) are considered local. func isLocalPath(s string) bool { const sep = string(filepath.Separator) return s == "." || s == ".." || filepath.HasPrefix(s, sep) || filepath.HasPrefix(s, "."+sep) || filepath.HasPrefix(s, ".."+sep) || filepath.VolumeName(s) != "" }
func EvaluateTargets(t []string) string { h := syscall.MustLoadDLL("kernel32.dll") c := h.MustFindProc("GetDiskFreeSpaceExW") var maxFreeBytes uint64 var bestTarget string for _, p := range t { var freeBytes uint64 vol := filepath.VolumeName(p) ptr1 := unsafe.Pointer(syscall.StringToUTF16Ptr(vol)) ptr2 := unsafe.Pointer(&freeBytes) c.Call( uintptr(ptr1), uintptr(ptr2), uintptr(0), uintptr(0), ) if freeBytes > maxFreeBytes { maxFreeBytes = freeBytes bestTarget = p } } return bestTarget }
func withFakeHome(t *testing.T, callback func()) { oldHome := os.Getenv("HOME") oldHomePath := os.Getenv("HOMEPATH") oldHomeDrive := os.Getenv("HOMEDRIVE") defer func() { os.Setenv("HOMEDRIVE", oldHomeDrive) os.Setenv("HOMEPATH", oldHomePath) os.Setenv("HOME", oldHome) }() defer func() { NewConfigurationDiskRepository().Delete() }() fileutils.TempDir("test-config", func(dir string, err error) { os.Setenv("HOME", dir) volumeName := filepath.VolumeName(dir) if volumeName != "" { relativePath := strings.Replace(dir, volumeName, "", 1) os.Setenv("HOMEPATH", relativePath) os.Setenv("HOMEDRIVE", volumeName) } callback() }) }
func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s", Help) os.Exit(1) } flag.Parse() dir, err := os.Getwd() if err != nil { fatal.Fatalln(err) } // "To flush all open files on a volume, call FlushFileBuffers with a handle to the volume. // The caller must have administrative privileges. For more information, see Running with Special Privileges." // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364439(v=vs.85).aspx fp := filepath.VolumeName(dir) file, err := os.Open(fp) if err != nil { fatal.Fatalln(err) } err = syscall.Fsync(syscall.Handle(file.Fd())) if err != nil { fatal.Fatalln(err) } }
func (u *Untar) resolveDestination(name string) (string, error) { pathParts := strings.Split(name, string(os.PathSeparator)) // walk the path parts to find at what point the resolvedLinks deviates i := 0 for i, _ = range pathParts { if (i < len(u.resolvedLinks)) && pathParts[i] == u.resolvedLinks[i].src { continue } break } // truncate the slice to only the matching pieces u.resolvedLinks = u.resolvedLinks[0:i] // special handling for an empty array... // normally it begins with the previous dest, but if it is empty we need to // start with resolving the first path piece if len(u.resolvedLinks) == 0 { p := pathParts[i] if p == "" { // Path shouldn't start empty; resolve it from the root. if runtime.GOOS == "windows" { p = filepath.VolumeName(name) } else { p = string(os.PathSeparator) } } dst, err := u.convertToDestination(p) if err != nil { return "", err } u.resolvedLinks = append( u.resolvedLinks, resolvedLink{src: pathParts[i], dst: dst}) i++ } // build up the resolution for the rest of the pieces for j := i; j < len(pathParts); j++ { testPath := filepath.Join( u.resolvedLinks[len(u.resolvedLinks)-1].dst, pathParts[j]) dst, err := u.convertToDestination(testPath) if err != nil { return "", err } u.resolvedLinks = append( u.resolvedLinks, resolvedLink{src: pathParts[j], dst: dst}) } // the last entry is the full resolution return u.resolvedLinks[len(u.resolvedLinks)-1].dst, nil }
func Cleanname(name string) string { name = filepath.Clean(name) if len(Flagd) > 0 && filepath.VolumeName(name) == "" { name = filepath.Clean(Flagd) + string(os.PathSeparator) + name } return name }
// isRoot returns true iff a path is a root. // On Unix: "/". // On Windows: "C:\", "D:\", ... func isRoot(p string) bool { p = filepath.Clean(p) volume := filepath.VolumeName(p) p = strings.TrimPrefix(p, volume) p = filepath.ToSlash(p) return p == "/" }
func (s windowsSuite) TestVolumeName(c *gc.C) { volumeName := s.renderer.VolumeName(s.path) c.Check(volumeName, gc.Equals, "c:") if s.matchesRuntime() { goresult := gofilepath.VolumeName(s.path) c.Check(volumeName, gc.Equals, goresult) } }
// SetHome sets the os-specific home path in the environment func SetHome(s string) error { v := filepath.VolumeName(s) if v != "" { if err := os.Setenv("HOMEDRIVE", v); err != nil { return err } } return os.Setenv("HOMEPATH", s[len(v):]) }
func GetInfo() map[string]interface{} { path := "/" if runtime.GOOS == "windows" { file, _ := exec.LookPath(os.Args[0]) path = filepath.VolumeName(file) } diskinfo := disk.UsageStat{} if v, err := disk.Usage(path); err == nil { var i interface{} i = v switch inst := i.(type) { case disk.UsageStat: diskinfo = inst break case *disk.UsageStat: if inst != nil { diskinfo = *inst } break } } diskinfo.Total /= 1024 * 1024 diskinfo.Used /= 1024 * 1024 vm := mem.VirtualMemoryStat{} sm := mem.SwapMemoryStat{} if v, err := mem.VirtualMemory(); err == nil { vm = *v } vm.Total /= 1024 * 1024 vm.Used /= 1024 * 1024 if v, err := mem.SwapMemory(); err == nil { sm = *v } sm.Total /= 1024 * 1024 sm.Used /= 1024 * 1024 var cpupercent float64 ps, err := cpu.Percent(time.Millisecond, true) if err == nil && len(ps) > 0 { for _, v := range ps { cpupercent += v } cpupercent /= float64(len(ps)) } return map[string]interface{}{ "DiskInfo": diskinfo, "SwapMemory": sm, "VirtualMemory": vm, "CpuPercent": cpupercent * 100, } }
func zipifyPath(path string) string { path = filepath.Clean(path) volume := filepath.VolumeName(path) if volume != "" { path = path[len(volume):] } return filepath.ToSlash(strings.TrimPrefix(path, "/")) }
func normalizePath(path string) string { if filepath.VolumeName(path) == "" && filepath.HasPrefix(path, "\\") { var err error path, err = syscall.FullPath(path) if err != nil { panic(err) } } return path }
func normalizePath(path string) (string, error) { var err error if filepath.VolumeName(path) == "" && filepath.HasPrefix(path, "\\") { path, err = syscall.FullPath(path) if err != nil { return "", iodine.New(err, nil) } } return path, nil }
func TestVolumeName(t *testing.T) { if runtime.GOOS != "windows" { return } for _, v := range volumenametests { if vol := filepath.VolumeName(v.path); vol != v.vol { t.Errorf("VolumeName(%q)=%q, want %q", v.path, vol, v.vol) } } }
func (r root) addroot(name string) node { if vol := filepath.VolumeName(name); vol != "" { root, ok := r.nd.Child[vol] if !ok { root = r.nd.addchild(vol, vol) } return root } return r.nd }
func (r root) root(name string) (node, error) { if vol := filepath.VolumeName(name); vol != "" { nd, ok := r.nd.Child[vol] if !ok { return node{}, errnotexist(name) } return nd, nil } return r.nd, nil }
// hasFilePathPrefix reports whether the filesystem path s begins with the // elements in prefix. func hasFilePathPrefix(s, prefix string) bool { sv := strings.ToUpper(filepath.VolumeName(s)) pv := strings.ToUpper(filepath.VolumeName(prefix)) s = s[len(sv):] prefix = prefix[len(pv):] switch { default: return false case sv != pv: return false case len(s) == len(prefix): return s == prefix case len(s) > len(prefix): if prefix != "" && prefix[len(prefix)-1] == filepath.Separator { return strings.HasPrefix(s, prefix) } return s[len(prefix)] == filepath.Separator && s[:len(prefix)] == prefix } }
func TestToNorm(t *testing.T) { stubBase := func(path string) (string, error) { vol := filepath.VolumeName(path) path = path[len(vol):] if strings.Contains(path, "/") { return "", fmt.Errorf("invalid path is given to base: %s", vol+path) } if path == "" || path == "." || path == `\` { return "", fmt.Errorf("invalid path is given to base: %s", vol+path) } i := strings.LastIndexByte(path, filepath.Separator) if i == len(path)-1 { // trailing '\' is invalid return "", fmt.Errorf("invalid path is given to base: %s", vol+path) } if i == -1 { return strings.ToUpper(path), nil } return strings.ToUpper(path[i+1:]), nil } // On this test, toNorm should be same as string.ToUpper(filepath.Clean(path)) except empty string. tests := []struct { arg string want string }{ {"", ""}, {".", "."}, {"./foo/bar", `FOO\BAR`}, {"/", `\`}, {"/foo/bar", `\FOO\BAR`}, {"/foo/bar/baz/qux", `\FOO\BAR\BAZ\QUX`}, {"foo/bar", `FOO\BAR`}, {"C:/foo/bar", `C:\FOO\BAR`}, {"C:foo/bar", `C:FOO\BAR`}, {"c:/foo/bar", `C:\FOO\BAR`}, {"C:/foo/bar", `C:\FOO\BAR`}, {"C:/foo/bar/", `C:\FOO\BAR`}, {`C:\foo\bar`, `C:\FOO\BAR`}, {`C:\foo/bar\`, `C:\FOO\BAR`}, {"C:/ふー/バー", `C:\ふー\バー`}, } for _, test := range tests { got, err := filepath.ToNorm(test.arg, stubBase) if err != nil { t.Errorf("unexpected toNorm error, arg: %s, err: %v\n", test.arg, err) } else if got != test.want { t.Errorf("toNorm error, arg: %s, want: %s, got: %s\n", test.arg, test.want, got) } } }
func (d dir) glob(pattern string) (files []string, err error) { // unify path so that pattern will match files on Windows unifiedPath := strings.TrimPrefix(filepath.ToSlash(d.path), filepath.VolumeName(d.path)) globPattern := path.Join(unifiedPath, pattern) glob, err := CompileGlob(globPattern) if err != nil { err = wrapError(err, "Compiling glob for pattern %s", pattern) return } filepath.Walk(d.path, func(path string, info os.FileInfo, inErr error) (err error) { path = strings.TrimPrefix(filepath.ToSlash(path), filepath.VolumeName(path)) if inErr != nil { err = inErr return } if glob.Match(path) { files = append(files, strings.Replace(path, unifiedPath+"/", "", 1)) } return }) // Ruby Dir.glob will include *.log when looking for **/*.log // Our glob implementation will not do it automatically if strings.Contains(pattern, "**/*") { var extraFiles []string updatedPattern := strings.Replace(pattern, "**/*", "*", 1) extraFiles, err = d.glob(updatedPattern) if err != nil { err = wrapError(err, "Recursing into pattern %s", updatedPattern) return } files = append(files, extraFiles...) } return }
func convert_rel_path(gs []*comm.Group, cfgs []*comm.Config, vs_path string) { //所有的代码文件路径全部改成相对的,这个防止工程文件移动位置或者复制一份新的时候vs2010还是引用了原来的位置 for _, g := range gs { for i := 0; i < len(g.Files); i++ { g.Files[i], _ = filepath.Rel(vs_path, g.Files[i]) //fmt.Println(g.Files[i]) } } prj_volume_name := filepath.VolumeName(vs_path) //include文件有选择的改路径:同一个盘符下的就改 for _, c := range cfgs { for i := 0; i < len(c.Include); i++ { if filepath.VolumeName(c.Include[i]) == prj_volume_name { c.Include[i], _ = filepath.Rel(vs_path, c.Include[i]) } } } }
func (a *ArtifactUploader) WorkingDirectory(path string) string { if filepath.IsAbs(path) { if runtime.GOOS == "windows" { return filepath.VolumeName(path) } else { return "/" } } else { dir, _ := os.Getwd() return dir } }
// Calcualtes the glob root for a path. func Root(path string) string { if filepath.IsAbs(path) { if runtime.GOOS == "windows" { return filepath.VolumeName(path) } else { return "/" } } else { dir, _ := os.Getwd() return dir } }
func TestSameWindowsFile(t *testing.T) { temp, err := ioutil.TempDir("", "TestSameWindowsFile") if err != nil { t.Fatal(err) } defer os.RemoveAll(temp) wd, err := os.Getwd() if err != nil { t.Fatal(err) } err = os.Chdir(temp) if err != nil { t.Fatal(err) } defer os.Chdir(wd) f, err := os.Create("a") if err != nil { t.Fatal(err) } f.Close() ia1, err := os.Stat("a") if err != nil { t.Fatal(err) } path, err := filepath.Abs("a") if err != nil { t.Fatal(err) } ia2, err := os.Stat(path) if err != nil { t.Fatal(err) } if !os.SameFile(ia1, ia2) { t.Errorf("files should be same") } p := filepath.VolumeName(path) + filepath.Base(path) if err != nil { t.Fatal(err) } ia3, err := os.Stat(p) if err != nil { t.Fatal(err) } if !os.SameFile(ia1, ia3) { t.Errorf("files should be same") } }