Golang EvalSymlinks示例

说明

golang evalsymlinks示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: path/filepath

示例#1
文件: filesystem.go 项目: yanwushuang/pango

func (f *Filesystem) shouldRead(filePath string, fi os.FileInfo) (bool, error) {
	if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
		link, err := filepath.EvalSymlinks(filePath)
		if err != nil {
			jww.ERROR.Printf("Cannot read symbolic link '%s', error was: %s", filePath, err)
			return false, nil
		}
		linkfi, err := os.Stat(link)
		if err != nil {
			jww.ERROR.Printf("Cannot stat '%s', error was: %s", link, err)
			return false, nil
		}
		if !linkfi.Mode().IsRegular() {
			jww.ERROR.Printf("Symbolic links for directories not supported, skipping '%s'", filePath)
		}
		return false, nil
	}

	if fi.IsDir() {
		if f.avoid(filePath) || isNonProcessablePath(filePath) {
			return false, filepath.SkipDir
		}
		return false, nil
	}

	if isNonProcessablePath(filePath) {
		return false, nil
	}
	return true, nil
}

示例#2
文件: metadata.go 项目: jcvernaleo/acdb

func (m *MetadataEncoder) Symlink(path string, fi os.FileInfo) error {
	_, err := m.e.Encode(TypeSymlink)
	if err != nil {
		return err
	}

	var link string
	if filepath.IsAbs(path) {
		link, err = filepath.EvalSymlinks(path)
		if err != nil {
			return err
		}
	} else {
		link, err = filepath.EvalSymlinks(path)
		if err != nil {
			return err
		}
		link, err = filepath.Rel(path, link)
		if err != nil {
			return err
		}
	}

	_, err = m.e.Encode(Symlink{
		Name: path,
		Link: link,
	})
	if err != nil {
		return err
	}

	return nil
}

示例#3
文件: link_test.go 项目: niemeyer/snapd

func (s *linkSuite) TestLinkDoUndoCurrentSymlink(c *C) {
	const yaml = `name: hello
version: 1.0
`

	info := snaptest.MockSnap(c, yaml, &snap.SideInfo{Revision: snap.R(11)})

	err := s.be.LinkSnap(info)
	c.Assert(err, IsNil)

	mountDir := info.MountDir()
	dataDir := info.DataDir()
	currentActiveSymlink := filepath.Join(mountDir, "..", "current")
	currentActiveDir, err := filepath.EvalSymlinks(currentActiveSymlink)
	c.Assert(err, IsNil)
	c.Assert(currentActiveDir, Equals, mountDir)

	currentDataSymlink := filepath.Join(dataDir, "..", "current")
	currentDataDir, err := filepath.EvalSymlinks(currentDataSymlink)
	c.Assert(err, IsNil)
	c.Assert(currentDataDir, Equals, dataDir)

	// undo will remove the symlinks
	err = s.be.UnlinkSnap(info, &s.nullProgress)
	c.Assert(err, IsNil)

	c.Check(osutil.FileExists(currentActiveSymlink), Equals, false)
	c.Check(osutil.FileExists(currentDataSymlink), Equals, false)

}

示例#4
文件: path-base.go 项目: rosrad/grid

func (p ExpBase) StoreName() map[string]string {
	names := make(map[string]string)
	names["exp"], _ = filepath.EvalSymlinks(p.ExpDir())
	names["data"], _ = filepath.EvalSymlinks(p.DataDir())
	names["param"], _ = filepath.EvalSymlinks(p.ParamDir())
	return names
}

示例#5
文件: file.go 项目: kaustubhkurve/cockroach

// GetLogReader returns a reader for the specified filename. In
// restricted mode, the filename must be the base name of a file in
// this process's log directory (this is safe for cases when the
// filename comes from external sources, such as the admin UI via
// HTTP). In unrestricted mode any path is allowed, with the added
// feature that relative paths will be searched in both the current
// directory and this process's log directory.
func GetLogReader(filename string, restricted bool) (io.ReadCloser, error) {
	if !restricted {
		if resolved, err := filepath.EvalSymlinks(filename); err == nil {
			if verifyFile(resolved) == nil {
				return os.Open(resolved)
			}
		}
	}
	// Verify there are no path separators in a restricted-mode pathname.
	if restricted && filepath.Base(filename) != filename {
		return nil, fmt.Errorf("pathnames must be basenames only: %s", filename)
	}
	if !filepath.IsAbs(filename) {
		filename = filepath.Join(*logDir, filename)
	}
	if !restricted {
		var err error
		filename, err = filepath.EvalSymlinks(filename)
		if err != nil {
			return nil, err
		}
	}
	if err := verifyFile(filename); err != nil {
		return nil, err
	}
	return os.Open(filename)
}

示例#6
文件: conf.go 项目: postfix/go-kaldi

func (conf *PathConf) StoreName() map[string]string {
	names := make(map[string]string)
	names["exp"], _ = filepath.EvalSymlinks(conf.Exp)
	names["data"], _ = filepath.EvalSymlinks(conf.FeatData)
	names["param"], _ = filepath.EvalSymlinks(conf.FeatParam)
	return names
}

示例#7
文件: worker_test.go 项目: lht/termite

func TestEndToEndSpecialEntries(t *testing.T) {
	tc := NewTestCase(t)
	defer tc.Clean()

	readlink, _ := filepath.EvalSymlinks(tc.FindBin("readlink"))
	req := WorkRequest{
		Binary: readlink,
		Argv:   []string{"readlink", "proc/self/exe"},
		Env:    testEnv(),
		Dir:    "/",
	}
	rep := tc.Run(req)

	if rep.Exit.ExitStatus() != 0 {
		t.Fatalf("readlink should exit cleanly. Rep %v", rep)
	}

	out, _ := filepath.EvalSymlinks(strings.TrimRight(rep.Stdout, "\n"))
	if out != readlink {
		t.Errorf("proc/self/exe point to wrong location: got %q, expect %q", out, readlink)
	}

	req = WorkRequest{
		Binary: tc.FindBin("ls"),
		Argv:   []string{"ls", "proc/misc"},
		Env:    testEnv(),
		Dir:    "/",
	}
	rep = tc.Run(req)
	if rep.Exit.ExitStatus() == 0 {
		t.Fatalf("ls should have failed", rep)
	}
}

示例#8
文件: set_test.go 项目: robert-ancell/snapd

func (s *SnapTestSuite) TestSetActive(c *C) {
	makeTwoTestSnaps(c, snap.TypeApp)

	path, err := filepath.EvalSymlinks(filepath.Join(dirs.SnapSnapsDir, fooComposedName, "current"))
	c.Assert(err, IsNil)
	c.Check(path, Equals, filepath.Join(dirs.SnapSnapsDir, fooComposedName, "2.0"))

	path, err = filepath.EvalSymlinks(filepath.Join(dirs.SnapDataDir, fooComposedName, "current"))
	c.Assert(err, IsNil)
	c.Check(path, Equals, filepath.Join(dirs.SnapDataDir, fooComposedName, "2.0"))

	meter := &MockProgressMeter{}

	// setActive has some ugly print
	devnull, err := os.Open(os.DevNull)
	c.Assert(err, IsNil)
	oldStdout := os.Stdout
	os.Stdout = devnull
	defer func() {
		os.Stdout = oldStdout
	}()

	err = makeSnapActiveByNameAndVersion("foo", "1.0", meter)
	c.Assert(err, IsNil)
	path, _ = filepath.EvalSymlinks(filepath.Join(dirs.SnapSnapsDir, fooComposedName, "current"))
	c.Check(path, Equals, filepath.Join(dirs.SnapSnapsDir, fooComposedName, "1.0"))
	path, _ = filepath.EvalSymlinks(filepath.Join(dirs.SnapDataDir, fooComposedName, "current"))
	c.Check(path, Equals, filepath.Join(dirs.SnapDataDir, fooComposedName, "1.0"))
}

示例#9
文件: os_file_system.go 项目: Jane4PKU/bosh

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

	actualOldPath, err := filepath.EvalSymlinks(oldPath)
	if err != nil {
		err = bosherr.WrapError(err, "Evaluating symlinks for %s", oldPath)
		return
	}

	existingTargetedPath, err := filepath.EvalSymlinks(newPath)
	if err == nil {
		if existingTargetedPath == actualOldPath {
			return
		}

		err = os.Remove(newPath)
		if err != nil {
			err = bosherr.WrapError(err, "Failed to delete symlimk at %s", newPath)
			return
		}
	}

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

	return os.Symlink(oldPath, newPath)
}

示例#10
文件: watcher_test.go 项目: zchee/go.fsevents

func TestCanGetPath(t *testing.T) {
	t.Parallel()
	base, rm := TempDir()
	defer rm()

	s := New(0, NOW, time.Second/10, CF_FILEEVENTS, base)
	s.Start()
	defer s.Close()

	withNew(base, func(dummyfile string) {
		select {
		case events := <-s.Chan:
			events = getEvents(base, events)
			if len(events) != 1 {
				t.Errorf("Expected 1 event, got %#v.", len(events))
			}
			fullpath, _ := filepath.Abs(dummyfile)
			fullpath, _ = filepath.EvalSymlinks(fullpath)
			evPath, _ := filepath.EvalSymlinks(events[0].Path)
			if evPath != fullpath {
				t.Errorf("Expected %#v to equal %#v.", evPath, fullpath)
			}
		case <-time.After(time.Minute):
			t.Errorf("timed out")
		}
	})
}

示例#11
文件: copy.go 项目: Chandra-TechPassionate/docker

// ResolveHostSourcePath decides real path need to be copied with parameters such as
// whether to follow symbol link or not, if followLink is true, resolvedPath will return
// link target of any symbol link file, else it will only resolve symlink of directory
// but return symbol link file itself without resolving.
func ResolveHostSourcePath(path string, followLink bool) (resolvedPath, rebaseName string, err error) {
	if followLink {
		resolvedPath, err = filepath.EvalSymlinks(path)
		if err != nil {
			return
		}

		resolvedPath, rebaseName = GetRebaseName(path, resolvedPath)
	} else {
		dirPath, basePath := filepath.Split(path)

		// if not follow symbol link, then resolve symbol link of parent dir
		var resolvedDirPath string
		resolvedDirPath, err = filepath.EvalSymlinks(dirPath)
		if err != nil {
			return
		}
		// resolvedDirPath will have been cleaned (no trailing path separators) so
		// we can manually join it with the base path element.
		resolvedPath = resolvedDirPath + string(filepath.Separator) + basePath
		if hasTrailingPathSeparator(path) && filepath.Base(path) != filepath.Base(resolvedPath) {
			rebaseName = filepath.Base(path)
		}
	}
	return resolvedPath, rebaseName, nil
}

示例#12
文件: fix.go 项目: zeebo/tools

// shouldTraverse reports whether the symlink fi should, found in dir,
// should be followed.  It makes sure symlinks were never visited
// before to avoid symlink loops.
func shouldTraverse(dir string, fi os.FileInfo) bool {
	path := filepath.Join(dir, fi.Name())
	target, err := filepath.EvalSymlinks(path)
	if err != nil {
		if !os.IsNotExist(err) {
			fmt.Fprintln(os.Stderr, err)
		}
		return false
	}
	ts, err := os.Stat(target)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return false
	}
	if !ts.IsDir() {
		return false
	}

	realParent, err := filepath.EvalSymlinks(dir)
	if err != nil {
		fmt.Fprint(os.Stderr, err)
		return false
	}
	realPath := filepath.Join(realParent, fi.Name())
	visitedSymlinks.Lock()
	defer visitedSymlinks.Unlock()
	if visitedSymlinks.m == nil {
		visitedSymlinks.m = make(map[string]struct{})
	}
	if _, ok := visitedSymlinks.m[realPath]; ok {
		return false
	}
	visitedSymlinks.m[realPath] = struct{}{}
	return true
}

示例#13
文件: path_windows_test.go 项目: danny8002/go

// TestEvalSymlinksCanonicalNames verify that EvalSymlinks
// returns "canonical" path names on windows.
func TestEvalSymlinksCanonicalNames(t *testing.T) {
	tmp, err := ioutil.TempDir("", "evalsymlinkcanonical")
	if err != nil {
		t.Fatal("creating temp dir:", err)
	}
	defer os.RemoveAll(tmp)

	// ioutil.TempDir might return "non-canonical" name.
	cTmpName, err := filepath.EvalSymlinks(tmp)
	if err != nil {
		t.Errorf("EvalSymlinks(%q) error: %v", tmp, err)
	}

	dirs := []string{
		"test",
		"test/dir",
		"testing_long_dir",
		"TEST2",
	}

	for _, d := range dirs {
		dir := filepath.Join(cTmpName, d)
		err := os.Mkdir(dir, 0755)
		if err != nil {
			t.Fatal(err)
		}
		cname, err := filepath.EvalSymlinks(dir)
		if err != nil {
			t.Errorf("EvalSymlinks(%q) error: %v", dir, err)
			continue
		}
		if dir != cname {
			t.Errorf("EvalSymlinks(%q) returns %q, but should return %q", dir, cname, dir)
			continue
		}
		// test non-canonical names
		test := strings.ToUpper(dir)
		p, err := filepath.EvalSymlinks(test)
		if err != nil {
			t.Errorf("EvalSymlinks(%q) error: %v", test, err)
			continue
		}
		if p != cname {
			t.Errorf("EvalSymlinks(%q) returns %q, but should return %q", test, p, cname)
			continue
		}
		// another test
		test = strings.ToLower(dir)
		p, err = filepath.EvalSymlinks(test)
		if err != nil {
			t.Errorf("EvalSymlinks(%q) error: %v", test, err)
			continue
		}
		if p != cname {
			t.Errorf("EvalSymlinks(%q) returns %q, but should return %q", test, p, cname)
			continue
		}
	}
}

示例#14
文件: app.go 项目: goodeggs/platform

func AppConfigPath(cmd *cobra.Command) (string, error) {
	if configFile, err := cmd.Flags().GetString("filename"); err == nil && configFile != "" {
		fmt.Printf("using config file %s\n", configFile)
		return filepath.EvalSymlinks(configFile)
	}

	return filepath.EvalSymlinks(".ranch.yaml")
}

示例#15
文件: hwmon_linux.go 项目: prometheus/node_exporter

func (c *hwMonCollector) hwmonName(dir string) (string, error) {
	// generate a name for a sensor path

	// sensor numbering depends on the order of linux module loading and
	// is thus unstable.
	// However the path of the device has to be stable:
	// - /sys/devices/<bus>/<device>
	// Some hardware monitors have a "name" file that exports a human
	// readbale name that can be used.

	// human readable names would be bat0 or coretemp, while a path string
	// could be platform_applesmc.768

	// preference 1: construct a name based on device name, always unique

	devicePath, devErr := filepath.EvalSymlinks(path.Join(dir, "device"))
	if devErr == nil {
		devPathPrefix, devName := path.Split(devicePath)
		_, devType := path.Split(strings.TrimRight(devPathPrefix, "/"))

		cleanDevName := cleanMetricName(devName)
		cleanDevType := cleanMetricName(devType)

		if cleanDevType != "" && cleanDevName != "" {
			return cleanDevType + "_" + cleanDevName, nil
		}

		if cleanDevName != "" {
			return cleanDevName, nil
		}
	}

	// preference 2: is there a name file
	sysnameRaw, nameErr := ioutil.ReadFile(path.Join(dir, "name"))
	if nameErr == nil && string(sysnameRaw) != "" {
		cleanName := cleanMetricName(string(sysnameRaw))
		if cleanName != "" {
			return cleanName, nil
		}
	}

	// it looks bad, name and device don't provide enough information
	// return a hwmon[0-9]* name

	realDir, err := filepath.EvalSymlinks(dir)
	if err != nil {
		return "", err
	}

	// take the last path element, this will be hwmonX
	_, name := path.Split(realDir)
	cleanName := cleanMetricName(name)
	if cleanName != "" {
		return cleanName, nil
	}
	return "", errors.New("Could not derive a monitoring name for " + dir)
}

示例#16
文件: parser.go 项目: cyprusteam/swagger

func (parser *Parser) CheckRealPackagePath(packagePath string) string {
	packagePath = strings.Trim(packagePath, "\"")

	if cachedResult, ok := parser.PackagePathCache[packagePath]; ok {
		return cachedResult
	}

	gopath := os.Getenv("GOPATH")
	if gopath == "" {
		log.Fatalf("Please, set $GOPATH environment variable\n")
	}

	// first check GOPATH
	pkgRealpath := ""
	gopathsList := filepath.SplitList(gopath)
	for _, path := range gopathsList {
		if evalutedPath, err := filepath.EvalSymlinks(filepath.Join(path, "src", packagePath)); err == nil {
			if _, err := os.Stat(evalutedPath); err == nil {
				pkgRealpath = evalutedPath
				break
			}
		}
	}

	// next, check GOROOT (/src)
	if pkgRealpath == "" {
		goroot := filepath.Clean(runtime.GOROOT())
		if goroot == "" {
			log.Fatalf("Please, set $GOROOT environment variable\n")
		}
		if evalutedPath, err := filepath.EvalSymlinks(filepath.Join(goroot, "src", packagePath)); err == nil {
			if _, err := os.Stat(evalutedPath); err == nil {
				pkgRealpath = evalutedPath
			}
		}

		// next, check GOROOT (/src/pkg) (for golang < v1.4)
		if pkgRealpath == "" {
			if evalutedPath, err := filepath.EvalSymlinks(filepath.Join(goroot, "src", "pkg", packagePath)); err == nil {
				if _, err := os.Stat(evalutedPath); err == nil {
					pkgRealpath = evalutedPath
				}
			}
		}
	}

	// next, check relative path
	if pkgRealpath == "" {
		if evalutedPath, err := filepath.Abs(packagePath); err == nil {
			pkgRealpath = evalutedPath
		}
	}

	parser.PackagePathCache[packagePath] = pkgRealpath
	return pkgRealpath
}

示例#17
文件: manager_test.go 项目: sarulabs/statix

func TestManagerSymlink(t *testing.T) {
	removeTestFiles()
	createInputFiles()
	defer removeTestFiles()

	m := getManagerTest()
	m.Dump()

	// testing a1 symlink
	symlink, err := m.Symlink("pack", "a1")
	if err != nil {
		t.Errorf(err.Error())
	}
	if !strings.HasSuffix(symlink, "/out/dirOut/a1") {
		t.Errorf("symlink to a1 does not have the correct filename")
	}
	filename, err := filepath.EvalSymlinks(symlink)
	if err != nil {
		t.Errorf(err.Error())
	}
	if !strings.HasSuffix(filename, "/out/dirOut/a1.df54fa5f220b244f5ed919c871fe56f0") {
		t.Error("symlink to a1 is not correct")
	}

	// testing a2.ext symlink
	symlink, err = m.Symlink("pack", "subDir/a2.ext")
	if err != nil {
		t.Errorf(err.Error())
	}
	if !strings.HasSuffix(symlink, "/out/dirOut/subDir/a2.ext") {
		t.Errorf("symlink to a2.ext does not have the correct filename")
	}
	filename, err = filepath.EvalSymlinks(symlink)
	if err != nil {
		t.Errorf(err.Error())
	}
	if !strings.HasSuffix(filename, "/out/dirOut/subDir/a2.4ee925ce5ea7f2ce1d0fe37f273dff23.ext") {
		t.Error("symlink to a2.ext is not correct")
	}

	// testing single.ext symlink
	symlink, err = m.Symlink("single")
	if err != nil {
		t.Errorf(err.Error())
	}
	if !strings.HasSuffix(symlink, "/out/single.ext") {
		t.Errorf("symlink to single.ext does not have the correct filename")
	}
	filename, err = filepath.EvalSymlinks(symlink)
	if err != nil {
		t.Errorf(err.Error())
	}
	if !strings.HasSuffix(filename, "/out/single.b34c31dcb721861cd51bfa6f3d850524.ext") {
		t.Error("symlink to single.ext is not correct")
	}
}

示例#18
文件: path_test.go 项目: rgmabs19357/gcc

func TestEvalSymlinks(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "evalsymlink")
	if err != nil {
		t.Fatal("creating temp dir:", err)
	}
	defer os.RemoveAll(tmpDir)

	// /tmp may itself be a symlink! Avoid the confusion, although
	// it means trusting the thing we're testing.
	tmpDir, err = filepath.EvalSymlinks(tmpDir)
	if err != nil {
		t.Fatal("eval symlink for tmp dir:", err)
	}

	// Create the symlink farm using relative paths.
	for _, d := range EvalSymlinksTestDirs {
		var err error
		path := simpleJoin(tmpDir, d.path)
		if d.dest == "" {
			err = os.Mkdir(path, 0755)
		} else {
			if runtime.GOOS != "windows" {
				err = os.Symlink(d.dest, path)
			}
		}
		if err != nil {
			t.Fatal(err)
		}
	}

	var tests []EvalSymlinksTest
	if runtime.GOOS == "windows" {
		for _, d := range EvalSymlinksTests {
			if d.path == d.dest {
				// will test only real files and directories
				tests = append(tests, d)
			}
		}
	} else {
		tests = EvalSymlinksTests
	}

	// Evaluate the symlink farm.
	for _, d := range tests {
		path := simpleJoin(tmpDir, d.path)
		dest := simpleJoin(tmpDir, d.dest)
		if filepath.IsAbs(d.dest) {
			dest = d.dest
		}
		if p, err := filepath.EvalSymlinks(path); err != nil {
			t.Errorf("EvalSymlinks(%q) error: %v", d.path, err)
		} else if filepath.Clean(p) != filepath.Clean(dest) {
			t.Errorf("Clean(%q)=%q, want %q", path, p, dest)
		}
	}
}

示例#19
文件: lookpath_test.go 项目: 4shome/go.jiri

func pathsMatch(t *testing.T, path1, path2 string) bool {
	eval1, err := filepath.EvalSymlinks(path1)
	if err != nil {
		t.Fatalf("EvalSymlinks(%v) failed: %v", path1, err)
	}
	eval2, err := filepath.EvalSymlinks(path2)
	if err != nil {
		t.Fatalf("EvalSymlinks(%v) failed: %v", path2, err)
	}
	return eval1 == eval2
}

示例#20
文件: push.go 项目: fujitsu-cf/cli

// ProcessPath takes in a director of app files or a zip file which contains
// the app files. If given a zip file, it will extract the zip to a temporary
// location, call the provided callback with that location, and then clean up
// the location after the callback has been executed.
//
// This was done so that the caller of ProcessPath wouldn't need to know if it
// was a zip file or an app dir that it was given, and the caller would not be
// responsible for cleaning up the temporary directory ProcessPath creates when
// given a zip.
func (actor PushActorImpl) ProcessPath(dirOrZipFile string, f func(string) error) error {
	if !actor.zipper.IsZipFile(dirOrZipFile) {
		if filepath.IsAbs(dirOrZipFile) {
			appDir, err := filepath.EvalSymlinks(dirOrZipFile)
			if err != nil {
				return err
			}
			err = f(appDir)
			if err != nil {
				return err
			}
		} else {
			absPath, err := filepath.Abs(dirOrZipFile)
			if err != nil {
				return err
			}
			appDir, err := filepath.EvalSymlinks(absPath)
			if err != nil {
				return err
			}

			err = f(appDir)
			if err != nil {
				return err
			}
		}

		return nil
	}

	tempDir, err := ioutil.TempDir("", "unzipped-app")
	if err != nil {
		return err
	}

	err = actor.zipper.Unzip(dirOrZipFile, tempDir)
	if err != nil {
		return err
	}

	err = f(tempDir)
	if err != nil {
		return err
	}

	err = os.RemoveAll(tempDir)
	if err != nil {
		return err
	}

	return nil
}

示例#21
文件: http.go 项目: henryanand/vitess

// serve an individual query
func handleSnapshot(rw http.ResponseWriter, req *http.Request, snapshotDir string, allowedPaths []string) {
	// if we get any error, we'll try to write a server error
	// (it will fail if the header has already been written, but at least
	// we won't crash vttablet)
	defer func() {
		if x := recover(); x != nil {
			log.Errorf("vttablet http server panic: %v", x)
			http.Error(rw, fmt.Sprintf("500 internal server error: %v", x), http.StatusInternalServerError)
		}
	}()

	// /snapshot must be rewritten to the actual location of the snapshot.
	relative, err := filepath.Rel(mysqlctl.SnapshotURLPath, req.URL.Path)
	if err != nil {
		log.Errorf("bad snapshot relative path %v %v", req.URL.Path, err)
		http.Error(rw, "400 bad request", http.StatusBadRequest)
		return
	}

	// Make sure that realPath is absolute and resolve any escaping from
	// snapshotDir through a symlink.
	realPath, err := filepath.Abs(path.Join(snapshotDir, relative))
	if err != nil {
		log.Errorf("bad snapshot absolute path %v %v", req.URL.Path, err)
		http.Error(rw, "400 bad request", http.StatusBadRequest)
		return
	}

	realPath, err = filepath.EvalSymlinks(realPath)
	if err != nil {
		log.Errorf("bad snapshot symlink eval %v %v", req.URL.Path, err)
		http.Error(rw, "400 bad request", http.StatusBadRequest)
		return
	}

	// Resolve all the possible roots and make sure we're serving
	// from one of them
	for _, allowedPath := range allowedPaths {
		// eval the symlinks of the allowed path
		allowedPath, err := filepath.EvalSymlinks(allowedPath)
		if err != nil {
			continue
		}
		if strings.HasPrefix(realPath, allowedPath) {
			sendFile(rw, req, realPath)
			return
		}
	}

	log.Errorf("bad snapshot real path %v %v", req.URL.Path, realPath)
	http.Error(rw, "400 bad request", http.StatusBadRequest)
}

示例#22
文件: devpage.go 项目: sqp/godock

// New creates a welcome widget with informations about the program.
//
func New(source cftype.Source, log cdtype.Logger, switcher *pageswitch.Switcher) cftype.Grouper {
	const group = "Dev"
	title := tran.Slate("hi")

	// all packages in the application gopath.
	pathGoTest := strings.Join(append(cdglobal.AppBuildPath, "..."), "/")

	pathTestConfCmd := cdglobal.AppBuildPathFull("test", "confcmd", "confcmd.go")
	pathTestConfGUI := cdglobal.AppBuildPathFull("test", "confgui", "confgui.go")
	pathTestConfCmd, _ = filepath.EvalSymlinks(pathTestConfCmd)
	pathTestConfGUI, _ = filepath.EvalSymlinks(pathTestConfGUI)

	printConfig := func(showAll bool) {
		path := source.MainConfigFile()
		def := source.MainConfigDefault()

		otherSw := pageswitch.New()
		defer otherSw.Destroy()
		build, e := cfbuild.NewFromFile(source, log, path, def, "")
		if !log.Err(e, "load current dock config file") {
			// build.BuildSingle("TaskBar")
			build.BuildAll(otherSw)
			println("conf", path, def)
			cfprint.Default(build, showAll)
			build.Destroy()
		}
	}

	buildInfo := cfbuild.TweakAddGroup(group,
		newkey.TextLabel(group, "txt_title", common.Bold(common.Big(title))),
		newkey.Separator(group, "sep_title"),
		newkey.TextLabel(group, "txt_dev_page", "Test page, with useful tools for the developer."),
		newkey.CustomButtonLabel(group, "printConfig", "Print configuration", "show mainconf edited", func() { printConfig(false) }),
		newkey.CustomButtonLabel(group, "printConfig", "Print configuration", "show mainconf all", func() { printConfig(true) }),
		newkey.Separator(group, "sep_go_area"),
		newkey.TextLabel(group, "txt_go_area", "<b>Those commands requires the application sources in their Go environment</b>."),
		newkey.Separator(group, "sep_tests_gui"),
		newkey.LaunchCommand(group, "testConfGUI", "Launch config GUI test", "go run "+pathTestConfGUI),
		newkey.Separator(group, "sep_tests_cmd"),
		newkey.LaunchCommand(group, "testConfGUI", "Launch config console test", "go run "+pathTestConfCmd),
		newkey.LaunchCommand(group, "testConfGUI", "Launch config console mainconf diff", "go run "+pathTestConfCmd+" "+source.MainConfigFile()),
		newkey.Separator(group, "sep_tests_go"),
		newkey.LaunchCommand(group, "gotest", "Launch go tests", "go test "+pathGoTest),
		newkey.LaunchCommand(group, "golint", "Launch go lint", "golint "+pathGoTest),
		newkey.LaunchCommand(group, "govet", "Launch go vet", "go vet "+pathGoTest),
	)

	build := cfbuild.NewVirtual(source, log, "", "", "").BuildAll(switcher, buildInfo)

	build.ShowAll()
	return build
}

示例#23
文件: startup_test.go 项目: robmurtha/goq

func TestStartupInHomeDir(t *testing.T) {

	cv.Convey("On 'goq serve' startup, the process should Chdir to GOQ_HOME", t, func() {

		var jobserv *JobServ
		var err error
		var jobservPid int
		remote := false

		// *** universal test cfg setup
		skipbye := false

		// this will move us to a new tempdir
		cfg := NewTestConfig()

		// now move away so we can check that there is a Chdir
		cv.So(cfg.tempdir, cv.ShouldNotEqual, cfg.origdir)

		err = os.Chdir("..")
		if err != nil {
			panic(err)
		}
		pwd, err := os.Getwd()
		if err != nil {
			panic(err)
		}
		cv.So(pwd, cv.ShouldNotEqual, cfg.Home)

		defer cfg.ByeTestConfig(&skipbye)
		// *** end universal test setup

		cfg.DebugMode = true // reply to badsig packets

		// local only, because we use Getwd() to see what dir we are in.
		jobserv, err = NewJobServ(cfg)
		if err != nil {
			panic(err)
		}
		defer CleanupServer(cfg, jobservPid, jobserv, remote, &skipbye)
		defer CleanupOutdir(cfg)

		pwd, err = os.Getwd()
		if err != nil {
			panic(err)
		}
		epwd, _ := filepath.EvalSymlinks(pwd)
		ecfg, _ := filepath.EvalSymlinks(cfg.Home)

		cv.So(epwd, cv.ShouldEqual, ecfg)
	})
}

示例#24
文件: path_test.go 项目: jacobsa/go

func TestEvalSymlinks(t *testing.T) {
	switch runtime.GOOS {
	case "android", "nacl", "plan9":
		t.Skipf("skipping on %s", runtime.GOOS)
	}
	if !supportsSymlinks {
		t.Skip("skipping because symlinks are not supported")
	}

	tmpDir, err := ioutil.TempDir("", "evalsymlink")
	if err != nil {
		t.Fatal("creating temp dir:", err)
	}
	defer os.RemoveAll(tmpDir)

	// /tmp may itself be a symlink! Avoid the confusion, although
	// it means trusting the thing we're testing.
	tmpDir, err = filepath.EvalSymlinks(tmpDir)
	if err != nil {
		t.Fatal("eval symlink for tmp dir:", err)
	}

	// Create the symlink farm using relative paths.
	for _, d := range EvalSymlinksTestDirs {
		var err error
		path := simpleJoin(tmpDir, d.path)
		if d.dest == "" {
			err = os.Mkdir(path, 0755)
		} else {
			err = os.Symlink(d.dest, path)
		}
		if err != nil {
			t.Fatal(err)
		}
	}

	// Evaluate the symlink farm.
	for _, d := range EvalSymlinksTests {
		path := simpleJoin(tmpDir, d.path)
		dest := simpleJoin(tmpDir, d.dest)
		if filepath.IsAbs(d.dest) || os.IsPathSeparator(d.dest[0]) {
			dest = d.dest
		}
		if p, err := filepath.EvalSymlinks(path); err != nil {
			t.Errorf("EvalSymlinks(%q) error: %v", d.path, err)
		} else if filepath.Clean(p) != filepath.Clean(dest) {
			t.Errorf("Clean(%q)=%q, want %q", path, p, dest)
		}
	}
}

示例#25
文件: eval_symlinks.go 项目: datawolf/go-study

func main() {
	link := "link_file"
	dest, err := filepath.EvalSymlinks(link)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(dest)

	link = "regular_file.txt"
	dest, err = filepath.EvalSymlinks(link)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(dest)
}

示例#26

// shouldTraverse checks if fi, found in dir, is a directory or a symlink to a directory.
// It makes sure symlinks were never visited before to avoid symlink loops.
func shouldTraverse(dir string, fi os.FileInfo) bool {
	if fi.IsDir() {
		if skipDir(fi) {
			if Debug {
				log.Printf("skipping directory %q under %s", fi.Name(), dir)
			}
			return false
		}
		return true
	}

	if fi.Mode()&os.ModeSymlink == 0 {
		return false
	}
	path := filepath.Join(dir, fi.Name())
	target, err := filepath.EvalSymlinks(path)
	if err != nil {
		if !os.IsNotExist(err) {
			fmt.Fprintln(os.Stderr, err)
		}
		return false
	}
	ts, err := os.Stat(target)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return false
	}
	if !ts.IsDir() {
		return false
	}

	realParent, err := filepath.EvalSymlinks(dir)
	if err != nil {
		fmt.Fprint(os.Stderr, err)
		return false
	}
	realPath := filepath.Join(realParent, fi.Name())
	visitedSymlinks.Lock()
	defer visitedSymlinks.Unlock()
	if visitedSymlinks.m == nil {
		visitedSymlinks.m = make(map[string]struct{})
	}
	if _, ok := visitedSymlinks.m[realPath]; ok {
		return false
	}
	visitedSymlinks.m[realPath] = struct{}{}
	return true
}

示例#27
文件: gce_util.go 项目: hortonworks/kubernetes-yarn

// Unmounts the device and detaches the disk from the kubelet's host machine.
// Expects a GCE device path symlink. Ex: /dev/disk/by-id/google-mydisk-part1
func (util *GCEDiskUtil) DetachDisk(pd *gcePersistentDisk, devicePath string) error {
	// Follow the symlink to the actual device path.
	canonicalDevicePath, err := filepath.EvalSymlinks(devicePath)
	if err != nil {
		return err
	}
	deviceName, err := getDeviceName(devicePath, canonicalDevicePath)
	if err != nil {
		return err
	}
	globalPDPath := makeGlobalPDName(pd.plugin.host, deviceName, pd.readOnly)
	if err := pd.mounter.Unmount(globalPDPath, 0); err != nil {
		return err
	}
	if err := os.RemoveAll(globalPDPath); err != nil {
		return err
	}
	gce, err := cloudprovider.GetCloudProvider("gce", nil)
	if err != nil {
		return err
	}
	if err := gce.(*gce_cloud.GCECloud).DetachDisk(deviceName); err != nil {
		return err
	}
	return nil
}

示例#28
文件: gonrun.go 项目: ssrl/gonrun

// RunFile returns the directory and file location where the binary generated
// for sourcefile should be put.  In case the directory does not yet exist, it
// will be created by RunDir.
func RunFile(sourcefile string) (rundir, runfile string, err os.Error) {

	rundir, err = RunDir()
	if err != nil {
		return "", "", err
	}
	sourcefile, err = filepath.Abs(sourcefile)
	if err != nil {
		return "", "", err
	}
	sourcefile, err = filepath.EvalSymlinks(sourcefile)
	if err != nil {
		return "", "", err
	}
	runfile = strings.Replace(sourcefile, "%", "%%", -1)
	if os.Getenv("GOOS") != "windows" {
		runfile = strings.Replace(runfile, string(filepath.Separator), "%", -1)
		runfile = runfile
	} else {
		runfile = strings.Replace(runfile, string(filepath.Separator), "_", -1)
		runfile = strings.Replace(runfile, ":", "_", -1)
	}
	runfile = filepath.Join(rundir, runfile)
	return rundir, runfile, nil
}

示例#29
文件: snapp.go 项目: strukturag/snappy

func (s *SnapLocalRepository) partsForGlobExpr(globExpr string) (parts []Part, err error) {
	matches, err := filepath.Glob(globExpr)
	if err != nil {
		return nil, err
	}

	for _, yamlfile := range matches {

		// skip "current" and similar symlinks
		realpath, err := filepath.EvalSymlinks(yamlfile)
		if err != nil {
			return nil, err
		}
		if realpath != yamlfile {
			continue
		}

		origin, _ := originFromYamlPath(realpath)
		snap, err := NewInstalledSnapPart(realpath, origin)
		if err != nil {
			return nil, err
		}
		parts = append(parts, snap)

	}

	return parts, nil
}

示例#30
文件: mount.go 项目: maisem/kubernetes

// GetDeviceNameFromMount: given a mnt point, find the device from /proc/mounts
// returns the device name, reference count, and error code
func GetDeviceNameFromMount(mounter Interface, mountPath string) (string, int, error) {
	mps, err := mounter.List()
	if err != nil {
		return "", 0, err
	}

	// Find the device name.
	// FIXME if multiple devices mounted on the same mount path, only the first one is returned
	device := ""
	// If mountPath is symlink, need get its target path.
	slTarget, err := filepath.EvalSymlinks(mountPath)
	if err != nil {
		slTarget = mountPath
	}
	for i := range mps {
		if mps[i].Path == slTarget {
			device = mps[i].Device
			break
		}
	}

	// Find all references to the device.
	refCount := 0
	for i := range mps {
		if mps[i].Device == device {
			refCount++
		}
	}
	return device, refCount, nil
}

展开阅读全文