本文整理汇总了Golang中path/filepath.Base函数的典型用法代码示例。如果您正苦于以下问题:Golang Base函数的具体用法?Golang Base怎么用?Golang Base使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Base函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestNewResourceId
func TestNewResourceId(t *testing.T) {
r, err := NewRepository(testBaseDir)
// something wrong with constructor
if err != nil {
t.Errorf("could not create the directories")
}
id, fp := r.NewResourceIdWithSubdir(SubdirDefault)
if id == "" || filepath.Dir(fp) != filepath.Join(r.basedir, SubdirDefault) || filepath.Base(fp) != id {
t.Errorf("something went wrong with id generation")
}
// test cached id
id, fp = r.NewResourceIdWithSubdir(SubdirCache)
if id == "" || filepath.Dir(fp) != filepath.Join(r.basedir, SubdirCache) || filepath.Base(fp) != id {
t.Errorf("something went wrong with id generation")
}
// test a local id
id, fp = r.NewResourceId()
if id == "" || filepath.Dir(fp) != filepath.Join(r.basedir, SubdirDefault) || filepath.Base(fp) != id {
t.Errorf("something went wrong with id generation")
}
// test invalid dir
AssertPanic(t, func() {
r.NewResourceIdWithSubdir("nonsense")
})
}
示例2: 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")
}
}
示例3: TestCommandRelativeName
func TestCommandRelativeName(t *testing.T) {
if runtime.GOOS == "darwin" && runtime.GOARCH == "arm" {
t.Skip("skipping on darwin/arm")
}
// Run our own binary as a relative path
// (e.g. "_test/exec.test") our parent directory.
base := filepath.Base(os.Args[0]) // "exec.test"
dir := filepath.Dir(os.Args[0]) // "/tmp/go-buildNNNN/os/exec/_test"
if dir == "." {
t.Skip("skipping; running test at root somehow")
}
parentDir := filepath.Dir(dir) // "/tmp/go-buildNNNN/os/exec"
dirBase := filepath.Base(dir) // "_test"
if dirBase == "." {
t.Skipf("skipping; unexpected shallow dir of %q", dir)
}
cmd := exec.Command(filepath.Join(dirBase, base), "-test.run=TestHelperProcess", "--", "echo", "foo")
cmd.Dir = parentDir
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
out, err := cmd.Output()
if err != nil {
t.Errorf("echo: %v", err)
}
if g, e := string(out), "foo\n"; g != e {
t.Errorf("echo: want %q, got %q", e, g)
}
}
示例4: ProcessRename
func ProcessRename(page *Page, args []string) {
if len(args) < 1 {
errhandle(fmt.Errorf("'rename' rule needs an argument"))
}
dest := args[0]
if strings.Contains(dest, "*") {
if !strings.Contains(page.Pattern, "*") {
errhandle(fmt.Errorf(
"'rename' rule cannot rename '%s' to '%s'",
page.Pattern, dest))
}
group := fmt.Sprintf("([^%c]*)", filepath.Separator)
base := filepath.Base(page.Pattern)
pat := strings.Replace(regexp.QuoteMeta(base), "\\*", group, 1)
re, err := regexp.Compile(pat)
errhandle(err)
m := re.FindStringSubmatch(filepath.Base(page.Path))
dest = strings.Replace(dest, "*", m[1], 1)
}
page.Path = filepath.Join(filepath.Dir(page.Path), dest)
}
示例5: 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
}
示例6: StartSnapServices
// StartSnapServices starts service units for the applications from the snap which are services.
func StartSnapServices(s *snap.Info, inter interacter) error {
for _, app := range s.Apps {
if app.Daemon == "" {
continue
}
// daemon-reload and enable plus start
serviceName := filepath.Base(app.ServiceFile())
sysd := systemd.New(dirs.GlobalRootDir, inter)
if err := sysd.DaemonReload(); err != nil {
return err
}
if err := sysd.Enable(serviceName); err != nil {
return err
}
if err := sysd.Start(serviceName); err != nil {
return err
}
if app.Socket {
socketName := filepath.Base(app.ServiceSocketFile())
// enable the socket
if err := sysd.Enable(socketName); err != nil {
return err
}
if err := sysd.Start(socketName); err != nil {
return err
}
}
}
return nil
}
示例7: discoverSingle
func (c *config) discoverSingle(glob string, m *map[string]string) error {
matches, err := filepath.Glob(glob)
if err != nil {
return err
}
if *m == nil {
*m = make(map[string]string)
}
prefix := filepath.Base(glob)
prefix = prefix[:strings.Index(prefix, "*")]
for _, match := range matches {
file := filepath.Base(match)
// If the filename has a ".", trim up to there
if idx := strings.Index(file, "."); idx >= 0 {
file = file[:idx]
}
// Look for foo-bar-baz. The plugin name is "baz"
plugin := file[len(prefix):]
log.Printf("[DEBUG] Discovered plugin: %s = %s", plugin, match)
(*m)[plugin] = match
}
return nil
}
示例8: NewPackageBuilder
// NewPackageBuilder creates a new Builder based on the go package in dir.
func NewPackageBuilder(dir string, target io.Writer, options *Options) (Builder, error) {
abs, err := filepath.Abs(dir)
if err != nil {
return nil, err
}
b := NewBuilder(target, options).(*builder)
b.pkgName = abs
files, err := filepath.Glob(filepath.Join(dir, "*.go"))
if err != nil {
return nil, err
}
var f *os.File
for _, file := range files {
f, err = os.Open(filepath.Join(dir, filepath.Base(file)))
if err != nil {
return nil, err
}
// make a copy in order to be able to close the file
var buf bytes.Buffer
_, err = io.Copy(&buf, f)
if err != nil {
f.Close()
return nil, err
}
b.Add(filepath.Base(file), &buf)
f.Close()
}
return b, nil
}
示例9: CopyInfoSourcePath
// CopyInfoSourcePath stats the given path to create a CopyInfo
// struct representing that resource for the source of an archive copy
// operation. The given path should be an absolute local path. A source path
// has all symlinks evaluated that appear before the last path separator ("/"
// on Unix). As it is to be a copy source, the path must exist.
func CopyInfoSourcePath(path string) (CopyInfo, error) {
// Split the given path into its Directory and Base components. We will
// evaluate symlinks in the directory component then append the base.
dirPath, basePath := filepath.Split(path)
resolvedDirPath, err := filepath.EvalSymlinks(dirPath)
if err != nil {
return CopyInfo{}, err
}
// 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
var rebaseName string
if HasTrailingPathSeparator(path) && filepath.Base(path) != filepath.Base(resolvedPath) {
// In the case where the path had a trailing separator and a symlink
// evaluation has changed the last path component, we will need to
// rebase the name in the archive that is being copied to match the
// originally requested name.
rebaseName = filepath.Base(path)
}
stat, err := os.Lstat(resolvedPath)
if err != nil {
return CopyInfo{}, err
}
return CopyInfo{
Path: resolvedPath,
Exists: true,
IsDir: stat.IsDir(),
RebaseName: rebaseName,
}, nil
}
示例10: CreateSnapshot
// CreateSnapshot will create hardlinks for all tsm and tombstone files
// in the path provided
func (f *FileStore) CreateSnapshot() (string, error) {
f.traceLogger.Printf("Creating snapshot in %s", f.dir)
files := f.Files()
f.mu.Lock()
f.currentTempDirID += 1
f.mu.Unlock()
f.mu.RLock()
defer f.mu.RUnlock()
// get a tmp directory name
tmpPath := fmt.Sprintf("%s/%d.tmp", f.dir, f.currentTempDirID)
err := os.Mkdir(tmpPath, 0777)
if err != nil {
return "", err
}
for _, tsmf := range files {
newpath := filepath.Join(tmpPath, filepath.Base(tsmf.Path()))
if err := os.Link(tsmf.Path(), newpath); err != nil {
return "", fmt.Errorf("error creating tsm hard link: %q", err)
}
// Check for tombstones and link those as well
for _, tf := range tsmf.TombstoneFiles() {
newpath := filepath.Join(tmpPath, filepath.Base(tf.Path))
if err := os.Link(tf.Path, newpath); err != nil {
return "", fmt.Errorf("error creating tombstone hard link: %q", err)
}
}
}
return tmpPath, nil
}
示例11: deleteApiImageHandler
// API function to delete an image by its filename.
func deleteApiImageHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
userName := authentication.GetUserName(r)
if userName != "" { // TODO: Check if the user has permissions to delete the image
// Get the file name from the json data
decoder := json.NewDecoder(r.Body)
var json JsonImage
err := decoder.Decode(&json)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = filepath.Walk(filenames.ImagesFilepath, func(filePath string, info os.FileInfo, err error) error {
if !info.IsDir() && filepath.Base(filePath) == filepath.Base(json.Filename) {
err := os.Remove(filePath)
if err != nil {
return err
}
}
return nil
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("Image deleted!"))
return
} else {
http.Error(w, "Not logged in!", http.StatusInternalServerError)
return
}
}
示例12: createDummyPackage
// createDummyPackage is deprecated
func createDummyPackage(name string) bool {
if f, e := os.Create(filepath.Join(filepath.Dir(name), "dummy")); e == nil {
f.Close()
} else {
return false
}
c := NewExcmd("jar")
c.SetDir(filepath.Dir(name))
if !c.Run("DummyPackage", "cf", filepath.Base(name), "dummy") {
return false
}
if e := os.Remove(filepath.Join(filepath.Dir(name), "dummy")); e != nil {
Fatal("remove: %v (%v)\n", "dummy", e)
}
c = NewExcmd("zip")
c.SetDir(filepath.Dir(name))
if !c.Run("DummyPackage", "-qd", filepath.Base(name), "dummy") {
return false
}
return true
}
示例13: ResolveHostSourcePath
// 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
}
示例14: NewPageSet
func NewPageSet(dir string) *PageSet {
p := &PageSet{Sitemap: true}
p.Path = filepath.Base(dir)
p.pages = make(map[string]*Page)
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err == nil {
if !info.IsDir() {
switch {
case filepath.Ext(path) == ".md":
if page, err := Parse(path, false); err != nil {
panic(err)
} else {
p.Add(page.FrontMatter.Slug, page)
}
case filepath.Base(path) == "penny.yml":
p.Configure(path)
}
}
}
return err
})
p.Link()
PageSets[dir] = p
return p
}
示例15: archiveLegacyConfig
func archiveLegacyConfig() {
pat := filepath.Join(confDir, "*.idx.gz*")
idxs, err := filepath.Glob(pat)
if err == nil && len(idxs) > 0 {
// There are legacy indexes. This is probably the first time we run as v0.9.
backupDir := filepath.Join(confDir, "backup-of-v0.8")
err = os.MkdirAll(backupDir, 0700)
if err != nil {
l.Warnln("Cannot archive config/indexes:", err)
return
}
for _, idx := range idxs {
l.Infof("Archiving %s", filepath.Base(idx))
os.Rename(idx, filepath.Join(backupDir, filepath.Base(idx)))
}
src, err := os.Open(filepath.Join(confDir, "config.xml"))
if err != nil {
l.Warnf("Cannot archive config:", err)
return
}
defer src.Close()
dst, err := os.Create(filepath.Join(backupDir, "config.xml"))
if err != nil {
l.Warnf("Cannot archive config:", err)
return
}
defer src.Close()
l.Infoln("Archiving config.xml")
io.Copy(dst, src)
}
}