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


Golang filepath.Dir函数代码示例

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


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

示例1: ReadDir

func (mfs mapFS) ReadDir(p string) ([]os.FileInfo, error) {
	mfs.mu.RLock()
	defer mfs.mu.RUnlock()

	// proxy mapfs.mapFS.ReadDir to not return errors for empty directories
	// created with Mkdir
	p = slash(p)
	fis, err := mfs.FileSystem.ReadDir(p)
	if os.IsNotExist(err) {
		_, ok := mfs.dirs[p]
		if ok {
			// return a list of subdirs and files (the underlying ReadDir impl
			// fails here because it thinks the directories don't exist).
			fis = nil
			for dir, _ := range mfs.dirs {
				if (p != "/" && filepath.Dir(dir) == p) || (p == "/" && filepath.Dir(dir) == "." && dir != "." && dir != "") {
					fis = append(fis, newDirInfo(dir))
				}
			}
			for fn, b := range mfs.m {
				if slashdir(fn) == "/"+p {
					fis = append(fis, newFileInfo(fn, b))
				}
			}
			return fis, nil
		}
	}
	return fis, err
}
开发者ID:sombr,项目名称:ccat,代码行数:29,代码来源:map.go

示例2: importSearchFromVisualization

func (imp Importer) importSearchFromVisualization(file string) error {
	type record struct {
		Title         string `json:"title"`
		SavedSearchID string `json:"savedSearchId"`
	}

	reader, err := ioutil.ReadFile(file)
	if err != nil {
		return nil
	}

	var jsonContent record
	json.Unmarshal(reader, &jsonContent)
	id := jsonContent.SavedSearchID
	if len(id) == 0 {
		// no search used
		return nil
	}

	// directory with the visualizations
	dir := filepath.Dir(file)

	// main directory
	mainDir := filepath.Dir(dir)

	searchFile := path.Join(mainDir, "search", id+".json")

	if searchFile != "" {
		// visualization depends on search
		if err := imp.ImportSearch(searchFile); err != nil {
			return err
		}
	}
	return nil
}
开发者ID:urso,项目名称:beats,代码行数:35,代码来源:import_dashboards.go

示例3: mirrorLocalZoneInfo

// mirrorLocalZoneInfo tries to reproduce the /etc/localtime target in stage1/ to satisfy systemd-nspawn
func mirrorLocalZoneInfo(root string) {
	zif, err := os.Readlink(localtimePath)
	if err != nil {
		return
	}

	// On some systems /etc/localtime is a relative symlink, make it absolute
	if !filepath.IsAbs(zif) {
		zif = filepath.Join(filepath.Dir(localtimePath), zif)
		zif = filepath.Clean(zif)
	}

	src, err := os.Open(zif)
	if err != nil {
		return
	}
	defer src.Close()

	destp := filepath.Join(common.Stage1RootfsPath(root), zif)

	if err = os.MkdirAll(filepath.Dir(destp), 0755); err != nil {
		return
	}

	dest, err := os.OpenFile(destp, os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return
	}
	defer dest.Close()

	_, _ = io.Copy(dest, src)
}
开发者ID:carriercomm,项目名称:rkt,代码行数:33,代码来源:init.go

示例4: ResolveLocalPaths

// ResolveLocalPaths resolves all relative paths in the config object with respect to the stanza's LocationOfOrigin
// this cannot be done directly inside of LoadFromFile because doing so there would make it impossible to load a file without
// modification of its contents.
func ResolveLocalPaths(config *clientcmdapi.Config) error {
	for _, cluster := range config.Clusters {
		if len(cluster.LocationOfOrigin) == 0 {
			continue
		}
		base, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin))
		if err != nil {
			return fmt.Errorf("Could not determine the absolute path of config file %s: %v", cluster.LocationOfOrigin, err)
		}

		if err := ResolvePaths(GetClusterFileReferences(cluster), base); err != nil {
			return err
		}
	}
	for _, authInfo := range config.AuthInfos {
		if len(authInfo.LocationOfOrigin) == 0 {
			continue
		}
		base, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin))
		if err != nil {
			return fmt.Errorf("Could not determine the absolute path of config file %s: %v", authInfo.LocationOfOrigin, err)
		}

		if err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil {
			return err
		}
	}

	return nil
}
开发者ID:Clarifai,项目名称:kubernetes,代码行数:33,代码来源:loader.go

示例5: TestUntarPathWithDestinationFile

// Do the same test as above but with the destination as file, it should fail
func TestUntarPathWithDestinationFile(t *testing.T) {
	tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmpFolder)
	srcFile := filepath.Join(tmpFolder, "src")
	tarFile := filepath.Join(tmpFolder, "src.tar")
	os.Create(filepath.Join(tmpFolder, "src"))

	// Translate back to Unix semantics as next exec.Command is run under sh
	srcFileU := srcFile
	tarFileU := tarFile
	if runtime.GOOS == "windows" {
		tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
		srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
	}
	cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
	_, err = cmd.CombinedOutput()
	if err != nil {
		t.Fatal(err)
	}
	destFile := filepath.Join(tmpFolder, "dest")
	_, err = os.Create(destFile)
	if err != nil {
		t.Fatalf("Fail to create the destination file")
	}
	err = UntarPath(tarFile, destFile)
	if err == nil {
		t.Fatalf("UntarPath should throw an error if the destination if a file")
	}
}
开发者ID:truedays,项目名称:docker,代码行数:33,代码来源:archive_test.go

示例6: AddSnapServices

// AddSnapServices adds service units for the applications from the snap which are services.
func AddSnapServices(s *snap.Info, inter interacter) error {
	for _, app := range s.Apps {
		if app.Daemon == "" {
			continue
		}
		// Generate service file
		content, err := generateSnapServiceFile(app)
		if err != nil {
			return err
		}
		svcFilePath := app.ServiceFile()
		os.MkdirAll(filepath.Dir(svcFilePath), 0755)
		if err := osutil.AtomicWriteFile(svcFilePath, []byte(content), 0644, 0); err != nil {
			return err
		}
		// Generate systemd socket file if needed
		if app.Socket {
			content, err := generateSnapSocketFile(app)
			if err != nil {
				return err
			}
			svcSocketFilePath := app.ServiceSocketFile()
			os.MkdirAll(filepath.Dir(svcSocketFilePath), 0755)
			if err := osutil.AtomicWriteFile(svcSocketFilePath, []byte(content), 0644, 0); err != nil {
				return err
			}
		}
	}

	return nil
}
开发者ID:clobrano,项目名称:snappy,代码行数:32,代码来源:services.go

示例7: getMetaForPath

// Gets meta type and name based on a path
func getMetaForPath(path string) (metaName string, objectName string) {
	parentDir := filepath.Dir(path)
	parentName := filepath.Base(parentDir)
	grandparentName := filepath.Base(filepath.Dir(parentDir))
	fileName := filepath.Base(path)

	for _, mp := range metapaths {
		if mp.hasFolder && grandparentName == mp.path {
			metaName = mp.name
			if mp.onlyFolder {
				objectName = parentName
			} else {
				objectName = parentName + "/" + fileName
			}
			return
		}
		if mp.path == parentName {
			metaName = mp.name
			objectName = fileName
			return
		}
	}

	// Unknown, so use path
	metaName = parentName
	objectName = fileName
	return
}
开发者ID:adamlincoln,项目名称:force,代码行数:29,代码来源:packagebuilder.go

示例8: Open

// Open is part of the intents.file interface. realBSONFiles need to have Open called before
// Read can be called
func (f *realBSONFile) Open() (err error) {
	if f.path == "" {
		// This should not occur normally. All realBSONFile's should have a path
		return fmt.Errorf("error creating BSON file without a path, namespace: %v",
			f.intent.Namespace())
	}
	err = os.MkdirAll(filepath.Dir(f.path), os.ModeDir|os.ModePerm)
	if err != nil {
		return fmt.Errorf("error creating directory for BSON file %v: %v",
			filepath.Dir(f.path), err)
	}

	fileName := f.path
	file, err := os.Create(fileName)
	if err != nil {
		return fmt.Errorf("error creating BSON file %v: %v", fileName, err)
	}
	var writeCloser io.WriteCloser
	if f.gzip {
		writeCloser = gzip.NewWriter(file)
	} else {
		// wrap writer in buffer to reduce load on disk
		writeCloser = writeFlushCloser{
			atomicFlusher{
				bufio.NewWriterSize(file, 32*1024),
			},
		}
	}
	f.WriteCloser = &wrappedWriteCloser{
		WriteCloser: writeCloser,
		inner:       file,
	}

	return nil
}
开发者ID:gabrielrussell,项目名称:mongo-tools,代码行数:37,代码来源:prepare.go

示例9: expandPaths

func expandPaths(paths []string) []string {
	if len(paths) == 0 {
		paths = []string{"."}
	}
	dirs := map[string]bool{}
	for _, path := range paths {
		if strings.HasSuffix(path, "/...") {
			root := filepath.Dir(path)
			_ = filepath.Walk(root, func(p string, i os.FileInfo, err error) error {
				kingpin.FatalIfError(err, "invalid path '"+p+"'")

				base := filepath.Base(p)
				skip := strings.ContainsAny(base[0:1], "_.") && base != "." && base != ".."
				if i.IsDir() {
					if skip {
						return filepath.SkipDir
					}
				} else if !skip && strings.HasSuffix(p, ".go") {
					dirs[filepath.Clean(filepath.Dir(p))] = true
				}
				return nil
			})
		} else {
			dirs[filepath.Clean(path)] = true
		}
	}
	out := make([]string, 0, len(dirs))
	for d := range dirs {
		out = append(out, d)
	}
	return out
}
开发者ID:NichoZhang,项目名称:gometalinter,代码行数:32,代码来源:main.go

示例10: FetchInputDocument

func (context *ExecutionContext) FetchInputDocument(loc string, relativeToSource bool) (doc *xml.XmlDocument) {
	//create the map if needed
	if context.InputDocuments == nil {
		context.InputDocuments = make(map[string]*xml.XmlDocument)
	}

	// rely on caller to tell us how to resolve relative paths
	base := ""
	if relativeToSource {
		base, _ = filepath.Abs(filepath.Dir(context.Source.Uri()))
	} else {
		base, _ = filepath.Abs(filepath.Dir(context.Style.Doc.Uri()))
	}
	resolvedLoc := filepath.Join(base, loc)

	//if abspath in map return existing document
	doc, ok := context.InputDocuments[resolvedLoc]
	if ok {
		return
	}

	//else load the document and add to map
	doc, e := xml.ReadFile(resolvedLoc, xml.StrictParseOption)
	if e != nil {
		fmt.Println(e)
		return
	}
	context.InputDocuments[resolvedLoc] = doc
	return
}
开发者ID:jbowtie,项目名称:ratago,代码行数:30,代码来源:context.go

示例11: TestExecutableMatch

func TestExecutableMatch(t *testing.T) {
	ep, err := GetCurrentExecutePath()
	if err != nil {
		t.Fatalf("Executable failed: %v", err)
	}

	// fullpath to be of the form "dir/prog".
	dir := filepath.Dir(filepath.Dir(ep))
	fullpath, err := filepath.Rel(dir, ep)
	if err != nil {
		t.Fatalf("filepath.Rel: %v", err)
	}
	// Make child start with a relative program path.
	// Alter argv[0] for child to verify getting real path without argv[0].
	cmd := &exec.Cmd{
		Dir:  dir,
		Path: fullpath,
		Env:  []string{fmt.Sprintf("%s=%s", executableEnvVar, executableEnvValueMatch)},
	}
	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("exec(self) failed: %v", err)
	}
	outs := string(out)
	if !filepath.IsAbs(outs) {
		t.Fatalf("Child returned %q, want an absolute path", out)
	}
	if !sameFile(outs, ep) {
		t.Fatalf("Child returned %q, not the same file as %q", out, ep)
	}
}
开发者ID:keysonZZZ,项目名称:kmg,代码行数:31,代码来源:GetCurrentExecutePath_test.go

示例12: UpdateFile

// UpdateFile downloads a file to temp dir and replaces the file only if
// contents have changed. If tempDir is "" default will be os.TempDir().
func UpdateFile(file, url string) error {
	if err := os.MkdirAll(filepath.Dir(file), 0777); err != nil {
		return err
	}

	t, err := ioutil.TempFile(filepath.Dir(file), "sdkUpdateCheck")
	if err != nil {
		return err
	}
	t.Close()
	tempFile := t.Name()
	defer os.Remove(tempFile)

	if err := DownloadFile(tempFile, url); err != nil {
		return err
	}

	equal, err := cmpFileBytes(file, tempFile)
	if os.IsExist(err) { // file may not exist, that is ok
		return err
	}
	if equal {
		plog.Infof("%v is up to date", file)
		return nil
	}

	// not equal so delete any existing file and rename tempFile to file
	if err := os.Rename(tempFile, file); err != nil {
		return err
	}
	return nil
}
开发者ID:chancez,项目名称:mantle,代码行数:34,代码来源:download.go

示例13: winInstaller

func winInstaller(buildos, buildarch, dir string, buildMatrix map[string]Release) error {
	cmd := exec.Command("cp", "script/install.bat.example", filepath.Join(dir, "install.bat"))
	if err := logAndRun(cmd); err != nil {
		return err
	}

	installerPath := filepath.Dir(filepath.Dir(dir))

	name := zipName(buildos, buildarch) + ".zip"
	full := filepath.Join(installerPath, name)
	matches, err := filepath.Glob(dir + "/*")
	if err != nil {
		return err
	}

	addToMatrix(buildMatrix, buildos, buildarch, name)

	args := make([]string, len(matches)+2)
	args[0] = "-j" // junk the zip paths
	args[1] = full
	copy(args[2:], matches)

	cmd = exec.Command("zip", args...)
	return logAndRun(cmd)
}
开发者ID:sanoursa,项目名称:git-lfs,代码行数:25,代码来源:build.go

示例14: parseConfig

func parseConfig() *viper.Viper {
	if verbose {
		logrus.SetLevel(logrus.DebugLevel)
		logrus.SetOutput(os.Stderr)
	}

	// Get home directory for current user
	homeDir, err := homedir.Dir()
	if err != nil {
		fatalf("Cannot get current user home directory: %v", err)
	}
	if homeDir == "" {
		fatalf("Cannot get current user home directory")
	}

	// By default our trust directory (where keys are stored) is in ~/.notary/
	mainViper.SetDefault("trust_dir", filepath.Join(homeDir, filepath.Dir(configDir)))

	// If there was a commandline configFile set, we parse that.
	// If there wasn't we attempt to find it on the default location ~/.notary/config
	if configFile != "" {
		configFileExt = strings.TrimPrefix(filepath.Ext(configFile), ".")
		configFileName = strings.TrimSuffix(filepath.Base(configFile), filepath.Ext(configFile))
		configPath = filepath.Dir(configFile)
	} else {
		configPath = filepath.Join(homeDir, filepath.Dir(configDir))
	}

	// Setup the configuration details into viper
	mainViper.SetConfigName(configFileName)
	mainViper.SetConfigType(configFileExt)
	mainViper.AddConfigPath(configPath)

	// Find and read the config file
	err = mainViper.ReadInConfig()
	if err != nil {
		logrus.Debugf("Configuration file not found, using defaults")
		// If we were passed in a configFile via -c, bail if it doesn't exist,
		// otherwise ignore it: we can use the defaults
		if configFile != "" || !os.IsNotExist(err) {
			fatalf("error opening config file %v", err)
		}
	}

	// At this point we either have the default value or the one set by the config.
	// Either way, the command-line flag has precedence and overwrites the value
	if trustDir != "" {
		mainViper.Set("trust_dir", trustDir)
	}

	// Expands all the possible ~/ that have been given, either through -d or config
	// If there is no error, use it, if not, attempt to use whatever the user gave us
	expandedTrustDir, err := homedir.Expand(mainViper.GetString("trust_dir"))
	if err == nil {
		mainViper.Set("trust_dir", expandedTrustDir)
	}
	logrus.Debugf("Using the following trust directory: %s", mainViper.GetString("trust_dir"))

	return mainViper
}
开发者ID:useidel,项目名称:notary,代码行数:60,代码来源:main.go

示例15: TestStepTempDir_notmpdir

func TestStepTempDir_notmpdir(t *testing.T) {
	tempenv := "TMPDIR"
	if runtime.GOOS == "windows" {
		tempenv = "TMP"
	}
	// Verify empty TMPDIR maps to current working directory
	oldenv := os.Getenv(tempenv)
	os.Setenv(tempenv, "")
	defer os.Setenv(tempenv, oldenv)

	dir1 := testStepTempDir_impl(t)

	// Now set TMPDIR to current directory
	abspath, err := filepath.Abs(".")
	if err != nil {
		t.Fatalf("could not get current working directory")
	}
	os.Setenv(tempenv, abspath)

	dir2 := testStepTempDir_impl(t)

	if filepath.Dir(dir1) != filepath.Dir(dir2) {
		t.Fatalf("temp base directories do not match: %s %s", filepath.Dir(dir1), filepath.Dir(dir2))
	}
}
开发者ID:blairham,项目名称:packer,代码行数:25,代码来源:step_temp_dir_test.go


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