func (v *VuesController) Post() { file := v.Ctx.Input.Param(":files") d, f := Emplacement(Root, file) fileNotExt := strings.TrimSuffix(f, filepath.Ext(f)) c := fileNotExt + ".srt" pathSrt := path.Dir(d) + "/" + fileNotExt + ".srt" if !filepath.HasPrefix(f, ".") { finfo, err := os.Stat(d) if err != nil { check(err) } else { if !finfo.IsDir() { err := os.Rename(d, path.Dir(d)+"/."+f) if err != nil { check(err) } if !filepath.HasPrefix(c, ".") { _, err = os.Stat(pathSrt) if err == nil { err := os.Rename(pathSrt, path.Dir(pathSrt)+"/."+c) if err != nil { check(err) } } } v.Redirect("/list/"+path.Dir(file), 302) } } } else { fmt.Println(" le fichier a déjà été modifié !") v.Redirect("/list/"+path.Dir(file), 302) } }
// 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) != "" }
// relevantImport will determine whether this import should be instrumented as well func (i *Instrumentable) relevantImport(imp string) bool { if i.basepkg == "*" || build.IsLocalImport(imp) { return true } else if i.IsInGopath() || i.basepkg != "" { return filepath.HasPrefix(imp, i.basepkg) || filepath.HasPrefix(i.basepkg, imp) } return false }
func isSkipURL(url string) bool { if filepath.HasPrefix(url, "http://") { return true } if filepath.HasPrefix(url, "https://") { return true } return false }
// relevantImport will determine whether this import should be instrumented as well func (i *Instrumentable) relevantImport(imp string) bool { switch { case imp == "C": return false case i.gorootPkgs[imp] && !i.InstrumentGoroot: return false case i.basepkg == "*" || build.IsLocalImport(imp): return true case i.IsInGopath() || i.basepkg != "": return filepath.HasPrefix(imp, i.basepkg) || filepath.HasPrefix(i.basepkg, imp) } return false }
func getPackagePath(curpath string) (packpath string) { gopath := os.Getenv("GOPATH") Debugf("gopath:%s", gopath) if gopath == "" { ColorLog("[ERRO] you should set GOPATH in the env") os.Exit(2) } appsrcpath := "" haspath := false wgopath := filepath.SplitList(gopath) for _, wg := range wgopath { wg, _ = filepath.EvalSymlinks(path.Join(wg, "src")) if filepath.HasPrefix(strings.ToLower(curpath), strings.ToLower(wg)) { haspath = true appsrcpath = wg break } } if !haspath { ColorLog("[ERRO] Can't generate application code outside of GOPATH '%s'\n", gopath) os.Exit(2) } packpath = strings.Join(strings.Split(curpath[len(appsrcpath)+1:], string(filepath.Separator)), "/") return }
func FindParentPaths(fileName string) []string { cwd, _ := os.Getwd() paths := make([]string, 0) // special case if homedir is not in current path then check there anyway homedir := homedir() if !filepath.HasPrefix(cwd, homedir) { path := filepath.Join(homedir, fileName) if _, err := os.Stat(path); err == nil { paths = append(paths, path) } } path := filepath.Join(cwd, fileName) if _, err := os.Stat(path); err == nil { paths = append(paths, path) } for true { cwd = filepath.Dir(cwd) path := filepath.Join(cwd, fileName) if _, err := os.Stat(path); err == nil { paths = append(paths, path) } if cwd[len(cwd)-1] == filepath.Separator { break } } return paths }
// FindTree takes an import or filesystem path and returns the // tree where the package source should be and the package import path. func FindTree(path string) (tree *Tree, pkg string, err error) { if isLocalPath(path) { if path, err = filepath.Abs(path); err != nil { return } if path, err = filepath.EvalSymlinks(path); err != nil { return } for _, t := range Path { tpath := t.SrcDir() + string(filepath.Separator) if !filepath.HasPrefix(path, tpath) { continue } tree = t pkg = path[len(tpath):] return } err = fmt.Errorf("path %q not inside a GOPATH", path) return } tree = defaultTree pkg = path for _, t := range Path { if t.HasSrc(pkg) { tree = t return } } if tree == nil { err = ErrTreeNotFound } else { err = ErrNotFound } return }
// walkExt returns all FileInfos with specific extension. // Make sure to prefix the extension name with dot. // For example, to find all go files, pass ".go". func walkExt(targetDir, ext string) (map[os.FileInfo]string, error) { rmap := make(map[os.FileInfo]string) visit := func(path string, f os.FileInfo, err error) error { if f != nil { if !f.IsDir() { if filepath.Ext(path) == ext { if !filepath.HasPrefix(path, ".") && !strings.Contains(path, "/.") { if _, ok := rmap[f]; !ok { wd, err := os.Getwd() if err != nil { return err } thepath := filepath.Join(wd, strings.Replace(path, wd, "", -1)) rmap[f] = thepath } } } } } return nil } err := filepath.Walk(targetDir, visit) if err != nil { return nil, err } return rmap, nil }
// readFileFromBackup copies the next file from the archive into the shard. // The file is skipped if it does not have a matching shardRelativePath prefix. func (e *Engine) readFileFromBackup(tr *tar.Reader, shardRelativePath string) error { // Read next archive file. hdr, err := tr.Next() if err != nil { return err } // Skip file if it does not have a matching prefix. if !filepath.HasPrefix(hdr.Name, shardRelativePath) { return nil } path, err := filepath.Rel(shardRelativePath, hdr.Name) if err != nil { return err } // Create new file on disk. f, err := os.OpenFile(filepath.Join(e.path, path), os.O_CREATE|os.O_RDWR, 0666) if err != nil { return err } defer f.Close() // Copy from archive to the file. if _, err := io.CopyN(f, tr, hdr.Size); err != nil { return err } // Sync to disk & close. if err := f.Sync(); err != nil { return err } return f.Close() }
func TestCommandDetection(t *testing.T) { srcDirs := build.Default.SrcDirs() t.Logf("SRC DIRS: %v\n", srcDirs) commands := make(map[string]string) for _, srcDir := range srcDirs { // Skip stuff that is in the GOROOT if filepath.HasPrefix(srcDir, goroot) { continue } filepath.Walk(srcDir, func(path string, info os.FileInfo, err error) error { if info.IsDir() { pkg, err := build.Default.ImportDir(path, 0) if err == nil && pkg.IsCommand() { t.Logf("PKG: %v\n", pkg.ImportPath) commands[pkg.ImportPath] = filepath.Base(pkg.ImportPath) } } return nil }) } t.Logf("MAP: %v\n", commands) }
// ReadAt returns a reader for a file at the path relative to the alloc dir func (d *AllocDir) ReadAt(path string, offset int64) (io.ReadCloser, error) { if escapes, err := structs.PathEscapesAllocDir(path); err != nil { return nil, fmt.Errorf("Failed to check if path escapes alloc directory: %v", err) } else if escapes { return nil, fmt.Errorf("Path escapes the alloc directory") } p := filepath.Join(d.AllocDir, path) // Check if it is trying to read into a secret directory for _, dir := range d.TaskDirs { sdir := filepath.Join(dir, TaskSecrets) if filepath.HasPrefix(p, sdir) { return nil, fmt.Errorf("Reading secret file prohibited: %s", path) } } f, err := os.Open(p) if err != nil { return nil, err } if _, err := f.Seek(offset, 0); err != nil { return nil, fmt.Errorf("can't seek to offset %q: %v", offset, err) } return f, nil }
// Search images file. func search(e Engine, dir string) filepath.WalkFunc { // Implements "filepath.WalkFunc". return func(path string, info os.FileInfo, err error) error { if err != nil { return nil } if info.IsDir() { log.Printf(" + checking: %q\n", path) } // Skip directories and hidden files if info.IsDir() || filepath.HasPrefix(info.Name(), ".") { return nil } if e.IsImage(path) { p := NewPhoto(path, dir) p = e.repo.AddPhoto(p) log.Printf("----------------------------") log.Printf("Id => %d\n", p.Id) log.Printf("Name => %s\n", p.Name) log.Printf("Album => %s\n", p.Album) log.Printf("Directory => %s\n", p.Directory) log.Printf("File => %s\n", p.File) log.Printf("Width => %d\n", p.Width) log.Printf("Height => %d\n", p.Height) log.Printf("Aspect => %f\n", p.Aspect()) } return nil } }
func findAbsoluteLinks(ch chan *absoluteLink, errch chan error, root string) { di, err := os.Open(root) if err != nil { errch <- err return } files, err := di.Readdir(-1) if err != nil { errch <- err return } di.Close() for _, file := range files { pathname := filepath.Join(root, file.Name()) if file.IsDir() { findAbsoluteLinks(ch, errch, pathname) continue } if (file.Mode() & os.ModeSymlink) != 0 { target, err := os.Readlink(pathname) if err != nil { errch <- err } if filepath.IsAbs(target) && !filepath.HasPrefix(target, sysroot) { ch <- &absoluteLink{pathname, target} } } } }
func (s *HTTPStaticServer) hJSONList(w http.ResponseWriter, r *http.Request) { requestPath := mux.Vars(r)["path"] localPath := filepath.Join(s.Root, requestPath) search := r.FormValue("search") // path string -> info os.FileInfo fileInfoMap := make(map[string]os.FileInfo, 0) if search != "" { results := s.findIndex(search) if len(results) > 50 { // max 50 results = results[:50] } for _, item := range results { if filepath.HasPrefix(item.Path, requestPath) { fileInfoMap[item.Path] = item.Info } } } else { infos, err := ioutil.ReadDir(localPath) if err != nil { http.Error(w, err.Error(), 500) return } for _, info := range infos { fileInfoMap[filepath.Join(requestPath, info.Name())] = info } } lrs := make([]ListResponse, 0) for path, info := range fileInfoMap { lr := ListResponse{ Name: info.Name(), Path: path, } if search != "" { name, err := filepath.Rel(requestPath, path) if err != nil { log.Println(requestPath, path, err) } lr.Name = filepath.ToSlash(name) // fix for windows } if info.IsDir() { name := deepPath(localPath, info.Name()) lr.Name = name lr.Path = filepath.Join(filepath.Dir(path), name) lr.Type = "dir" lr.Size = "-" } else { lr.Type = "file" lr.Size = formatSize(info) } lrs = append(lrs, lr) } data, _ := json.Marshal(lrs) w.Header().Set("Content-Type", "application/json") w.Write(data) }
func keep(pathname string) bool { if !filepath.HasPrefix(pathname, sysroot) { // never delete anything outside of our sysroot. return false } for _, k := range dirsToKeep { if filepath.HasPrefix(pathname, k) { return true } // Don't delete directories that are prefixes of paths // to keep. if filepath.HasPrefix(k, pathname) { return true } } return false }
// List lists files under the path // TODO: it only returns file without any directories. func (m *MemConfig) List(path string) (map[string][]byte, error) { f := make(map[string][]byte) for name, content := range m.files { if filepath.HasPrefix(name, path) { f[name] = content } } return f, nil }
func IsGo(pwd string) (bool, string) { pathes := SplitPATH(os.Getenv("GOPATH")) for _, path := range pathes { if filepath.HasPrefix(pwd, path) { return true, strings.TrimPrefix(pwd, filepath.Join(path, "src")+"/") } } return false, "" }
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 ChildDirs(path string) ([]string, error) { children, err := ioutil.ReadDir(path) if err != nil { return nil, NewNewtError(err.Error()) } childDirs := []string{} for _, child := range children { name := child.Name() if !filepath.HasPrefix(name, ".") && !filepath.HasPrefix(name, "..") && child.IsDir() { childDirs = append(childDirs, name) } } return childDirs, nil }
func serveLocalFile(resp http.ResponseWriter, req *http.Request) { logRequest(req) er := req.ParseForm() if er != nil { resp.WriteHeader(http.StatusInternalServerError) ErrorPage(resp, CommonData{}, http.StatusInternalServerError, er) return } filename := req.Form.Get("path") // file path sanity checks. switch { case !filepath.IsAbs(filename), filepath.HasPrefix(filename, "/etc"), filepath.HasPrefix(filename, "/home"), filepath.HasPrefix(filename, "/var"), filepath.HasPrefix(filename, "/tmp"): resp.WriteHeader(http.StatusForbidden) er := fmt.Errorf("access to %s is forbidden", filename) ErrorPage(resp, CommonData{}, http.StatusForbidden, er) return } info, er := os.Stat(filename) switch { case er != nil: resp.WriteHeader(http.StatusNotFound) ErrorPage(resp, CommonData{}, http.StatusNotFound, er) return case info.Mode()&os.ModeType != 0: // not a regular file. resp.WriteHeader(http.StatusForbidden) ErrorPage(resp, CommonData{}, http.StatusForbidden, errSpecialFile) return case !isPackageFilepath(filename): // not a package file resp.WriteHeader(http.StatusForbidden) ErrorPage(resp, CommonData{}, http.StatusForbidden, errNonPackageFile) return } http.ServeFile(resp, req, filename) }
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 }
// CleanImport gets a package import path and returns it as is if it is absolute. // Otherwise, it tryes to convert it to an absolute form. func CleanImport(imp string) (string, error) { // If the path is not relative, return it as is. impNorm := filepath.ToSlash(imp) if impNorm != "." && impNorm != ".." && !filepath.HasPrefix(impNorm, "./") && !filepath.HasPrefix(impNorm, "../") { // Get rid of trailing slashes. return strings.TrimRight(impNorm, "/"), nil } // Find a full absolute path to the requested import. abs, err := filepath.Abs(filepath.FromSlash(imp)) if err != nil { return "", err } // Extract package's import from it. return AbsoluteToImport(abs) }
func (m *mockLibrary) cleanup() { // Remove the tmp directory if filepath.HasPrefix(m.tmpDir, os.TempDir()) { os.RemoveAll(m.tmpDir) } else { panic("trying to work in a non temporary directory") } // Close the server if m.httpServer != nil { m.httpServer.Close() } }
func shouldKeep(cmdWithFlags []string, oFile string, cFile string, pkg string, lastBuild string, currentBuild string) bool { lastBuildObj := filepath.Join(lastBuild, pkg, "_obj") currentBuildObj := filepath.Join(currentBuild, pkg, "_obj") if cFile == "" { return true } oFileBase := filepath.Base(oFile) // Compare the c/cpp file and o if IsANewerThanB(cFile, filepath.Join(lastBuildObj, oFileBase)) { if printKeep { fmt.Printf("* Keep %v: source file newer.\n", filepath.Base(cFile)) } return true } // Compare dependencies. out, err := run(append(append([]string(nil), cmdWithFlags...), "-M", cFile)) if err != nil { return true } deps := parseDependencies(string(out)) for _, dep := range deps { if filepath.HasPrefix(filepath.Clean(dep), currentBuildObj) { // This dependency is generated by cgo. Compare content. lastBuildDep := filepath.Join(lastBuildObj, filepath.Base(dep)) if IsFileContentDifferent(dep, lastBuildDep) { if printKeep { fmt.Printf("* Keep %v: dependency %v modified.\n", filepath.Base(cFile), filepath.Base(dep)) } return true } } else { lastBuildOfile := filepath.Join(lastBuildObj, oFileBase) if IsANewerThanB(dep, lastBuildOfile) { if printKeep { fmt.Printf("* Keep %v: dependency %v newer.\n", filepath.Base(cFile), filepath.Base(dep)) } return true } } } lastBuildOfile := filepath.Join(lastBuildObj, oFileBase) if _, err := CopyFile(oFile, lastBuildOfile); err != nil { panic(err) } return false }
func (p *PasVuesController) Post() { file := p.Ctx.Input.Param(":files") d, f := Emplacement(Root, file) fileNotExt := strings.TrimSuffix(f, filepath.Ext(f)) c := fileNotExt + ".srt" pathSrt := path.Dir(d) + "/" + fileNotExt + ".srt" if filepath.HasPrefix(f, ".") { finfo, err := os.Stat(d) if err != nil { check(err) } else { if !finfo.IsDir() { err := os.Rename(d, path.Dir(d)+"/"+strings.Replace(f, ".", "", 1)) if err != nil { check(err) } if filepath.HasPrefix(c, ".") { fmt.Println(pathSrt, path.Dir(pathSrt)+"/"+strings.Replace(c, ".", "", 1)) _, err = os.Stat(pathSrt) if err == nil { err := os.Rename(pathSrt, path.Dir(pathSrt)+"/"+strings.Replace(c, ".", "", 1)) if err != nil { check(err) } } } p.Redirect("/list/"+path.Dir(file)+"/", 302) } } } else { p.Redirect("/list/"+path.Dir(file), 302) } p.Layout = "index.tpl" p.TplNames = "list.tpl" p.Data["title"] = strings.Title("liste") }
// getGoPath checks the source codes absolute path // in reference to the host operating system's GOPATH // to correctly determine the code's package path. This // is Go-specific, since Go code must exist in // $GOPATH/src/github.com/{owner}/{name} func getGoPath(dir string) (string, bool) { path := os.Getenv("GOPATH") if len(path) == 0 { return "", false } // append src to the GOPATH, since // the code will be stored in the src dir path = filepath.Join(path, "src") if !filepath.HasPrefix(dir, path) { return "", false } // remove the prefix from the directory // this should leave us with the go package name return dir[len(path):], true }
// SubDir returns a FileSystem corresponding to the given directory in the // original FileSystem. func (fs *FileSystem) SubDir(dir string) *FileSystem { newLocal := "" if fs.local != "" { newLocal = filepath.Join(fs.local, dir) } newFiles := make(map[string][]byte) for p, b := range fs.files { if filepath.HasPrefix(p, dir) { k := p[len(dir)+1:] newFiles[k] = b } } return &FileSystem{ files: newFiles, local: newLocal, } }
// Get file content and parse it from Markdown to HTML without using cache. func GetFileNoCache(f string) []byte { if !filepath.HasPrefix(f, baseDir) { f = baseDir + f } md, err := readFile(f) if err != nil { log.Println(err) return nil } html := blackfriday.MarkdownBasic(md) cache.Set(f, html) return html }
func buildFuncInfo(i interface{}) FuncInfo { fi := FuncInfo{} frame := getCallerFrame(i) goPathSrc := filepath.Join(os.Getenv("GOPATH"), "src") if frame == nil { fi.Unresolvable = true return fi } pkgName := getPkgName(frame.File) if pkgName == "chi" { fi.Unresolvable = true } funcPath := frame.Func.Name() idx := strings.Index(funcPath, "/"+pkgName) if idx > 0 { fi.Pkg = funcPath[:idx+1+len(pkgName)] fi.Func = funcPath[idx+2+len(pkgName):] } else { fi.Func = funcPath } if strings.Index(fi.Func, ".func") > 0 { fi.Anonymous = true } fi.File = frame.File fi.Line = frame.Line if filepath.HasPrefix(fi.File, goPathSrc) { fi.File = fi.File[len(goPathSrc)+1:] } // Check if file info is unresolvable if !strings.Contains(funcPath, pkgName) { fi.Unresolvable = true } if !fi.Unresolvable { fi.Comment = getFuncComment(frame.File, frame.Line) } return fi }