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


Golang path.Base函数代码示例

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


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

示例1: activate

func (group *TailGroup) activate(match string) {
	tail, ok := group.Tails[match]
	if !ok {
		fi, _ := os.Stat(match)
		for _, tail = range group.Tails {
			tfi, _ := tail.Stat()
			if os.SameFile(fi, tfi) {
				tail.Close()
				delete(group.Tails, tail.Path)
				off := tail.Offset()
				tail.SetOffset(0)
				tail.WriteOffset()
				base := path.Base(match)
				offset := path.Join(group.OffsetDir, base+".ptr")
				tail = NewTail(group.NewParser(base), group.maxBackfill, match, offset, off)
				group.Tails[match] = tail
				return
			}
		}
		base := path.Base(match)
		offset := path.Join(group.OffsetDir, base+".ptr")
		tail = NewTail(group.NewParser(base), group.maxBackfill, match, offset, 0)
		group.Tails[match] = tail

	}
}
开发者ID:srid,项目名称:dendrite,代码行数:26,代码来源:tail_group.go

示例2: importSingle

func (fs *FileSystemImporter) importSingle(scan *ScanResult, opts *ImportOptions) error {
	//process is now:
	// find mime type.
	// inspect, which gives us the item.
	// look up existing, merge tags
	// overwrite added if needed
	// if created.isZero() then use file mtime
	// set in store
	// index
	// see if exportable -> export
	prefixError := func(e error) error {
		return fmt.Errorf("error importing `%s`: %s", path.Base(scan.Path), e)
	}

	rd, err := os.Open(scan.Path)
	if err != nil {
		return prefixError(err)
	}
	defer rd.Close()
	item, err := Inspect(NewInspectableFile(rd, scan.Mime, path.Base(scan.Path)))
	if err != nil {
		return prefixError(err)
	}

	//check for existing
	if existing, err := fs.service.store.Meta(item.Hash); err == nil {
		//merge!
		mergeItemData(item, existing)
		//we just need to update!
		err = fs.service.store.Update(item)
		if err != nil {
			return prefixError(err)
		}
	} else {
		//new item
		rd.Seek(0, 0) //rewind
		err = fs.service.store.Set(item, rd)
		if err != nil {
			return prefixError(err)
		}
		//generate thumbnail now! saves load time later...
		getItemThumbnail(fs.service, item, THUMBNAIL_LARGE)
	}
	//(re)index
	if err = fs.service.indexer.Index(item); err != nil {
		return prefixError(err)
	}
	// if err = fs.service.exporter.ExportItem(item, store); err != nil {
	//  errs <- err
	//  //we don't need to continue here. We rebuild the index occasionally,
	//  //so we'll pick it up.
	// }
	if opts.DeleteAfterImport {
		if err = os.Remove(scan.Path); err != nil {
			return prefixError(err)
		}
	}
	log.Printf("Import success: %s (%s)\n", item.Name, item.Type)
	return nil
}
开发者ID:thechriswalker,项目名称:opfs,代码行数:60,代码来源:importer_fs.go

示例3: waitNodes

func (d *discovery) waitNodes(nodes []*client.Node, size int, index uint64) ([]*client.Node, error) {
	if len(nodes) > size {
		nodes = nodes[:size]
	}
	// watch from the next index
	w := d.c.Watcher(d.cluster, &client.WatcherOptions{AfterIndex: index, Recursive: true})
	all := make([]*client.Node, len(nodes))
	copy(all, nodes)
	for _, n := range all {
		if path.Base(n.Key) == path.Base(d.selfKey()) {
			plog.Noticef("found self %s in the cluster", path.Base(d.selfKey()))
		} else {
			plog.Noticef("found peer %s in the cluster", path.Base(n.Key))
		}
	}

	// wait for others
	for len(all) < size {
		plog.Noticef("found %d peer(s), waiting for %d more", len(all), size-len(all))
		resp, err := w.Next(context.Background())
		if err != nil {
			if ce, ok := err.(*client.ClusterError); ok {
				plog.Error(ce.Detail())
				return d.waitNodesRetry()
			}
			return nil, err
		}
		plog.Noticef("found peer %s in the cluster", path.Base(resp.Node.Key))
		all = append(all, resp.Node)
	}
	plog.Noticef("found %d needed peer(s)", len(all))
	return all, nil
}
开发者ID:XiangrongFan,项目名称:etcd,代码行数:33,代码来源:discovery.go

示例4: ReadDirAll

// ReadDirAll reads the contents of the directory
func (d *Dir) ReadDirAll(ctx context.Context) (dirents []fuse.Dirent, err error) {
	fs.Debug(d.path, "Dir.ReadDirAll")
	err = d.readDir()
	if err != nil {
		fs.Debug(d.path, "Dir.ReadDirAll error: %v", err)
		return nil, err
	}
	d.mu.RLock()
	defer d.mu.RUnlock()
	for _, item := range d.items {
		var dirent fuse.Dirent
		switch x := item.o.(type) {
		case fs.Object:
			dirent = fuse.Dirent{
				// Inode FIXME ???
				Type: fuse.DT_File,
				Name: path.Base(x.Remote()),
			}
		case *fs.Dir:
			dirent = fuse.Dirent{
				// Inode FIXME ???
				Type: fuse.DT_Dir,
				Name: path.Base(x.Remote()),
			}
		default:
			err = errors.Errorf("unknown type %T", item)
			fs.ErrorLog(d.path, "Dir.ReadDirAll error: %v", err)
			return nil, err
		}
		dirents = append(dirents, dirent)
	}
	fs.Debug(d.path, "Dir.ReadDirAll OK with %d entries", len(dirents))
	return dirents, nil
}
开发者ID:ncw,项目名称:rclone,代码行数:35,代码来源:dir.go

示例5: LoadPCM

// load a PCM from <<pathTo>>, which if not explicitly pointing into a folder with the <<Sample Rate>>, numerically as its name, will look into a sub-folder with the sampleRate indicated by the PCM parameter, and if that's zero will load any samplerate available. Also adds extension ".pcm".
func LoadPCM(pathTo string, p *PCM) (err error) {
	sampleRate, err := strconv.ParseUint(path.Base(path.Dir(pathTo)), 10, 32)
	if err != nil {
		if p.samplePeriod == 0 {
			var files []os.FileInfo
			files, err = ioutil.ReadDir(path.Dir(pathTo))
			if err != nil {
				return
			}
			for _, file := range files {
				if file.IsDir() && file.Size() > 0 {
					sampleRate, err = strconv.ParseUint(file.Name(), 10, 32)
					if err == nil {
						pathTo = path.Join(path.Dir(pathTo), file.Name(), path.Base(pathTo))
						break
					}
				}
			}
		} else {
			pathTo = path.Join(path.Dir(pathTo), strconv.FormatInt(int64(unitX/x(p.samplePeriod)), 10), path.Base(pathTo))
		}
	} else {
		p.samplePeriod = X(1 / float32(sampleRate))
	}
	p.Data, err = ioutil.ReadFile(pathTo + ".pcm")
	return
}
开发者ID:splace,项目名称:signals,代码行数:28,代码来源:PCM.go

示例6: fileCp

func fileCp(srcPath, dstPath string) error {
	dstIsDir := dstPath[len(dstPath)-1] == '/'
	srcPath = fixZkPath(srcPath)
	dstPath = fixZkPath(dstPath)

	if !isZkFile(srcPath) && !isZkFile(dstPath) {
		return fmt.Errorf("cp: neither src nor dst is a /zk file: exitting")
	}

	data, err := getPathData(srcPath)
	if err != nil {
		return fmt.Errorf("cp: cannot read %v: %v", srcPath, err)
	}

	// If we are copying to a local directory - say '.', make the filename
	// the same as the source.
	if !isZkFile(dstPath) {
		fileInfo, err := os.Stat(dstPath)
		if err != nil {
			if err.(*os.PathError).Err != syscall.ENOENT {
				return fmt.Errorf("cp: cannot stat %v: %v", dstPath, err)
			}
		} else if fileInfo.IsDir() {
			dstPath = path.Join(dstPath, path.Base(srcPath))
		}
	} else if dstIsDir {
		// If we are copying into zk, interpret trailing slash as treating the
		// dstPath as a directory.
		dstPath = path.Join(dstPath, path.Base(srcPath))
	}
	if err := setPathData(dstPath, data); err != nil {
		return fmt.Errorf("cp: cannot write %v: %v", dstPath, err)
	}
	return nil
}
开发者ID:CowLeo,项目名称:vitess,代码行数:35,代码来源:zkcmd.go

示例7: syncFile

// syncFile syncs the given file
func syncFile(file string) {
	// Read file
	buf, err := ioutil.ReadFile(file)
	if err != nil {
		cli.LogErr.Fatal(err)
	}

	syncIt := true

	// Pull docker images
	if dockerPullFlag {
		cli.LogOut.Printf("syncing %s\n", path.Base(file))
		if err := findAndPullDockerImages(string(buf)); err != nil {
			cli.LogErr.Println("failed to sync " + path.Base(file) + " due to " + err.Error())
			syncIt = false
		}
	}

	// Add the job
	if syncIt {
		if err := nomadClient.AddJob(string(buf)); err != nil {
			cli.LogErr.Fatal(err)
		} else {
			cli.LogOut.Printf("%s is synced\n", path.Base(file))
		}
	}
}
开发者ID:yieldbot,项目名称:nomad-syncer,代码行数:28,代码来源:main.go

示例8: buildName

func buildName(dstPath string) (relpath string, author string, err error) {
	fname := path.Base(dstPath)
	curPath := path.Dir(dstPath)
	parts := []string{}

	for !fileExists(path.Join(curPath, configFile)) {
		parts = append([]string{path.Base(curPath)}, parts...)
		newCurPath := path.Dir(curPath)

		if newCurPath == curPath {
			fail("Couldn't find %s. Did you create it?", configFile)
		}

		curPath = newCurPath
	}

	// TODO: This is ugly. Fix by making a real config file.
	bs, err := ioutil.ReadFile(path.Join(curPath, configFile))
	if err != nil {
		return "", "", err
	}

	parts = append([]string{path.Base(curPath)}, parts...)
	parts = append(parts, fname)
	return path.Join(parts...), string(bs), nil
}
开发者ID:shaladdle,项目名称:hgen,代码行数:26,代码来源:hgen.go

示例9: main

func main() {
	flag.Parse()

	if flags.Help {
		flag.Usage()
		os.Exit(2)
	}

	if flags.Version {
		fmt.Printf("%s main: %s, data: %s\n",
			path.Base(os.Args[0]), cbgt.VERSION, cbgt.VERSION)
		os.Exit(0)
	}

	cmd.MainCommon(cbgt.VERSION, flagAliases)

	cfg, err := cmd.MainCfgClient(path.Base(os.Args[0]), flags.CfgConnect)
	if err != nil {
		log.Fatalf("%v", err)
		return
	}

	if flags.IndexTypes != "" {
		cmd.RegisterIndexTypes(strings.Split(flags.IndexTypes, ","))
	}

	nodesToRemove := []string(nil)
	if len(flags.RemoveNodes) > 0 {
		nodesToRemove = strings.Split(flags.RemoveNodes, ",")
	}

	var steps map[string]bool
	if flags.Steps != "" {
		steps = cbgt.StringsToMap(strings.Split(flags.Steps, ","))
	}

	// ------------------------------------------------

	if steps == nil || steps["rebalance"] {
		log.Printf("main: step rebalance")

		err := runRebalance(cfg, flags.Server, nodesToRemove,
			flags.FavorMinNodes, flags.DryRun, flags.Verbose)
		if err != nil {
			log.Fatalf("%v", err)
			return
		}
	}

	// ------------------------------------------------

	err = cmd.PlannerSteps(steps, cfg, cbgt.VERSION,
		flags.Server, nodesToRemove, flags.DryRun)
	if err != nil {
		log.Fatalf("%v", err)
		return
	}

	log.Printf("main: done")
}
开发者ID:nimishzynga,项目名称:cbgt,代码行数:60,代码来源:main.go

示例10: handleTestRequest

func handleTestRequest(rw http.ResponseWriter, req *http.Request) {
	file := path.Base(req.URL.Path) + ".html"
	if strings.HasPrefix(req.URL.Path, "/importers/") {
		file = path.Base(req.URL.Path) + "-importers.json"
	}
	http.ServeFile(rw, req, path.Join("testdata", file))
}
开发者ID:ernesto-jimenez,项目名称:gocompatible,代码行数:7,代码来源:godoc_test.go

示例11: TestConfigsUsed

func TestConfigsUsed(t *testing.T) {
	defer restoreDflts(dfltFiles, dfltDirs)
	tmpdir, err := ioutil.TempDir("", "tmp1")
	assert.NoError(t, err)
	defer os.Remove(tmpdir)

	cntFile, err := ioutil.TempFile(tmpdir, "nf_conntrack_count")
	maxFile, err := ioutil.TempFile(tmpdir, "nf_conntrack_max")
	assert.NoError(t, err)

	dfltDirs = []string{tmpdir}
	cntFname := path.Base(cntFile.Name())
	maxFname := path.Base(maxFile.Name())
	dfltFiles = []string{cntFname, maxFname}

	count := 1234321
	max := 9999999
	ioutil.WriteFile(cntFile.Name(), []byte(strconv.Itoa(count)), 0660)
	ioutil.WriteFile(maxFile.Name(), []byte(strconv.Itoa(max)), 0660)
	c := &Conntrack{}
	acc := &testutil.Accumulator{}

	c.Gather(acc)

	fix := func(s string) string {
		return strings.Replace(s, "nf_", "ip_", 1)
	}

	acc.AssertContainsFields(t, inputName,
		map[string]interface{}{
			fix(cntFname): float64(count),
			fix(maxFname): float64(max),
		})
}
开发者ID:jeichorn,项目名称:telegraf,代码行数:34,代码来源:conntrack_test.go

示例12: handleUnmarshalError

func handleUnmarshalError(f string, content []byte, err error) error {
	switch e := err.(type) {
	case *json.SyntaxError:
		line, ctx, off := getContext(content, e.Offset)

		if off <= 1 {
			return fmt.Errorf("Error: No policy")
		}

		preoff := off - 1
		pre := make([]byte, preoff)
		copy(pre, ctx[:preoff])
		for i := 0; i < preoff && i < len(pre); i++ {
			if pre[i] != '\t' {
				pre[i] = ' '
			}
		}

		return fmt.Errorf("Error: %s:%d: Syntax error at offset %d:\n%s\n%s^",
			path.Base(f), line, off, ctx, pre)
	case *json.UnmarshalTypeError:
		line, ctx, off := getContext(content, e.Offset)
		return fmt.Errorf("Error: %s:%d: Unable to assign value '%s' to type '%v':\n%s\n%*c",
			path.Base(f), line, e.Value, e.Type, ctx, off, '^')
	default:
		return fmt.Errorf("Error: %s: Unknown error:%s", path.Base(f), err)
	}
}
开发者ID:cilium-team,项目名称:cilium,代码行数:28,代码来源:main.go

示例13: Prettify

func Prettify(logMessage *events.LogMessage) string {
	entry := chug.ChugLogMessage(logMessage)

	var sourceType, sourceTypeColorized, sourceInstance, sourceInstanceColorized string

	sourceType = path.Base(entry.LogMessage.GetSourceType())
	sourceInstance = entry.LogMessage.GetSourceInstance()

	// TODO: Or, do we use GetSourceType() for raw and Json source for pretty?
	color, ok := colorLookup[path.Base(strings.Split(sourceType, ":")[0])]
	if ok {
		sourceTypeColorized = colors.Colorize(color, sourceType)
		sourceInstanceColorized = colors.Colorize(color, sourceInstance)
	} else {
		sourceTypeColorized = sourceType
		sourceInstanceColorized = sourceInstance
	}

	prefix := fmt.Sprintf("[%s|%s]", sourceTypeColorized, sourceInstanceColorized)

	colorWidth := len(sourceTypeColorized+sourceInstanceColorized) - len(sourceType+sourceInstance)

	components := append([]string(nil), fmt.Sprintf("%-"+strconv.Itoa(34+colorWidth)+"s", prefix))

	var whichFunc func(chug.Entry) []string
	if entry.IsLager {
		whichFunc = prettyPrintLog
	} else {
		whichFunc = prettyPrintRaw
	}

	components = append(components, whichFunc(entry)...)
	return strings.Join(components, " ")
}
开发者ID:cloudfoundry-incubator,项目名称:ltc,代码行数:34,代码来源:prettify.go

示例14: TestTransactionCommands

func TestTransactionCommands(t *testing.T) {
	// add two blobs, and then delete one
	blob1 := uploadstring(t, "POST", "/upload", "hello world")
	t.Log("blob1 =", blob1)
	blob2 := uploadstring(t, "POST", "/upload", "delete me")
	t.Log("blob2 =", blob2)

	itemid := "zxcvbnm" + randomid()
	checkStatus(t, "GET", "/item/"+itemid, 404)
	txpath := sendtransaction(t, "/item/"+itemid+"/transaction",
		[][]string{{"add", path.Base(blob1)},
			{"add", path.Base(blob2)}}, 202)
	t.Log("got tx path", txpath)
	// tx is processed async from the commit above.
	waitTransaction(t, txpath)
	checkStatus(t, "GET", "/item/"+itemid, 200)
	text := getbody(t, "GET", "/blob/"+itemid+"/2", 200)
	if text != "delete me" {
		t.Errorf("Received %#v, expected %#v", text, "delete me")
	}
	// now delete blob 2
	txpath = sendtransaction(t, "/item/"+itemid+"/transaction",
		[][]string{{"delete", "2"}}, 202)
	t.Log("got tx path", txpath)
	waitTransaction(t, txpath)
	text = getbody(t, "GET", "/blob/"+itemid+"/1", 200)
	if text != "hello world" {
		t.Errorf("Received %#v, expected %#v", text, "hello world")
	}
	text = getbody(t, "GET", "/blob/"+itemid+"/2", 404)
	if text != "Blob has been deleted\n" {
		t.Errorf("Received %#v, expected %#v", text, "Blob has been deleted\n")
	}
}
开发者ID:ndlib,项目名称:bendo,代码行数:34,代码来源:server_test.go

示例15: uploadFiles

func uploadFiles(client *github.Client, owner string, repo string, id int, files []string) error {
	assets, _, err := client.Repositories.ListReleaseAssets(owner, repo, id, &github.ListOptions{})
	if err != nil {
		return fmt.Errorf("Failed to fetch existing assets: %s", err)
	}

	for _, file := range files {
		handle, err := os.Open(file)
		if err != nil {
			return fmt.Errorf("Failed to read %s artifact: %s", file, err)
		}

		for _, asset := range assets {
			if *asset.Name == path.Base(file) {
				if _, err := client.Repositories.DeleteReleaseAsset(owner, repo, *asset.ID); err != nil {
					return fmt.Errorf("Failed to delete %s artifact: %s", file, err)
				}
				fmt.Printf("Successfully deleted old %s artifact\n", *asset.Name)
			}
		}

		uo := &github.UploadOptions{Name: path.Base(file)}
		if _, _, err = client.Repositories.UploadReleaseAsset(owner, repo, id, uo, handle); err != nil {
			return fmt.Errorf("Failed to upload %s artifact: %s", file, err)
		}

		fmt.Printf("Successfully uploaded %s artifact\n", file)
	}

	return nil
}
开发者ID:casualjim,项目名称:drone-github-release,代码行数:31,代码来源:main.go


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