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


Golang path.Dir函数代码示例

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


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

示例1: SetEngine

func SetEngine() (err error) {
	switch DbCfg.Type {
	case "mysql":
		orm, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%[email protected](%s)/%s?charset=utf8",
			DbCfg.User, DbCfg.Pwd, DbCfg.Host, DbCfg.Name))
	case "postgres":
		orm, err = xorm.NewEngine("postgres", fmt.Sprintf("user=%s password=%s dbname=%s sslmode=%s",
			DbCfg.User, DbCfg.Pwd, DbCfg.Name, DbCfg.SslMode))
	case "sqlite3":
		os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
		orm, err = xorm.NewEngine("sqlite3", DbCfg.Path)
	default:
		return fmt.Errorf("Unknown database type: %s", DbCfg.Type)
	}
	if err != nil {
		return fmt.Errorf("models.init(fail to conntect database): %v", err)
	}

	// WARNNING: for serv command, MUST remove the output to os.stdout,
	// so use log file to instead print to stdout.
	execDir, _ := base.ExecDir()
	logPath := execDir + "/log/xorm.log"
	os.MkdirAll(path.Dir(logPath), os.ModePerm)

	f, err := os.Create(logPath)
	if err != nil {
		return fmt.Errorf("models.init(fail to create xorm.log): %v", err)
	}
	orm.Logger = f

	orm.ShowSQL = true
	orm.ShowDebug = true
	orm.ShowErr = true
	return nil
}
开发者ID:popospectre,项目名称:gogs,代码行数:35,代码来源:models.go

示例2: TenetCfgPathRecusive

// TenetCfgPathRecusive looks for a config file at cfgPath. If the config
// file name is equal to DefaultTenetCfgPath, the func recursively searches the
// parent directory until a file with that name is found. In the case that
// none is found "" is retuned.
func TenetCfgPathRecusive(cfgPath string) (string, error) {
	var err error
	cfgPath, err = filepath.Abs(cfgPath)
	if err != nil {
		return "", err
	}

	if _, err := os.Stat(cfgPath); os.IsNotExist(err) {
		dir, file := path.Split(cfgPath)
		if file == DefaultTenetCfgPath {
			if dir == "/" {
				// we've reached the end of the line. Fall back to default:
				usr, err := user.Current()
				if err != nil {
					return "", err
				}

				lHome, err := util.LingoHome()
				if err != nil {
					return "", errors.Trace(err)
				}
				defaultTenets := path.Join(usr.HomeDir, lHome, DefaultTenetCfgPath)
				if _, err := os.Stat(defaultTenets); err != nil {
					return "", err
				}
				return defaultTenets, nil
			}
			parent := path.Dir(path.Dir(dir))
			return TenetCfgPathRecusive(parent + "/" + DefaultTenetCfgPath)
		}
		return "", err
	}
	return cfgPath, nil
}
开发者ID:howbazaar,项目名称:lingo,代码行数:38,代码来源:common.go

示例3: execManPage

func execManPage(page string) {
	binaryPath := os.Args[0]
	gemDir := path.Dir(path.Dir(binaryPath))
	manDir := path.Join(gemDir, "man/build")
	zeus := path.Join(manDir, page)
	syscall.Exec("/usr/bin/env", []string{"/usr/bin/env", "man", zeus}, os.Environ())
}
开发者ID:burke,项目名称:zeus,代码行数:7,代码来源:zeus.go

示例4: regenerate

func (p *FileProvider) regenerate(oldsid, sid string) (err error) {
	p.lock.Lock()
	defer p.lock.Unlock()

	filename := p.filepath(sid)
	if com.IsExist(filename) {
		return fmt.Errorf("new sid '%s' already exists", sid)
	}

	oldname := p.filepath(oldsid)
	if !com.IsFile(oldname) {
		data, err := EncodeGob(make(map[interface{}]interface{}))
		if err != nil {
			return err
		}
		if err = os.MkdirAll(path.Dir(oldname), os.ModePerm); err != nil {
			return err
		}
		if err = ioutil.WriteFile(oldname, data, os.ModePerm); err != nil {
			return err
		}
	}

	if err = os.MkdirAll(path.Dir(filename), os.ModePerm); err != nil {
		return err
	}
	if err = os.Rename(oldname, filename); err != nil {
		return err
	}
	return nil
}
开发者ID:RezaDKhan,项目名称:terraform,代码行数:31,代码来源:file.go

示例5: PostEdit

// POST /problem/edit
func (p *Problem) PostEdit(problem models.Problem,
	inputTest, outputTest []byte) revel.Result {
	defer func() {
		delete(p.Session, ID)
	}()
	if inputTest != nil {
		problem.InputTestPath = path.Dir(problem.InputTestPath) +
			"/inputTest"
		_, err := util.WriteFile(problem.InputTestPath, inputTest)
		if err != nil {
			log.Println(err)
		}

	}
	if outputTest != nil {
		problem.OutputTestPath = path.Dir(problem.OutputTestPath) +
			"/outputTest"
		_, err := util.WriteFile(problem.OutputTestPath, outputTest)
		if err != nil {
			log.Println(err)
		}
	}
	id, err := strconv.ParseInt(p.Session[ID], 10, 64)
	if err != nil {
		p.Flash.Error("id error")
		log.Println(err)
		return p.Redirect("/")
	}
	_, err = engine.Id(id).Update(problem)
	if err != nil {
		log.Println(err)
	}
	return p.Redirect("/")
}
开发者ID:jango2015,项目名称:OJ,代码行数:35,代码来源:problem.go

示例6: watcherCallback

func (fs *memFileSystem) watcherCallback() {
	for {
		select {
		case e := <-fs.watcher.Event:
			if e.IsCreate() {
				fi := fs.reloadFile(e.Name)
				if fi != nil && fi.IsDir() {
					err := fs.watcher.Watch(e.Name)
					if err != nil {
						logger.Printf("failed to add watch: %s err: %v", e.Name, err)
					}
				}
				fs.reloadFile(path.Dir(e.Name))
			}
			if e.IsModify() {
				fs.reloadFile(e.Name)
			}
			if e.IsDelete() || e.IsRename() {
				fi := fs.deleteFile(e.Name)
				if fi != nil && fi.IsDir() {
					err := fs.watcher.RemoveWatch(e.Name)
					if err != nil {
						logger.Printf("failed to remove watch: %s err: %v", e.Name, err)
					}
				}
				fs.reloadFile(path.Dir(e.Name))
			}
		case err := <-fs.watcher.Error:
			logger.Printf("watcher error: %v", err)
		}
	}
}
开发者ID:ranveerkunal,项目名称:memfs,代码行数:32,代码来源:fs.go

示例7: InjectLinks

func InjectLinks(adID string, content string, r *http.Request) string {

	// log.Println(r.Host)
	// log.Println(r.URL)
	timeNow = time.Now()

	host := r.Host

	//Get the last directory

	var curPath = ""
	prefixPth, err := regexp.MatchString("^[\\./]", r.URL.Path)
	if prefixPth && err == nil {
		curPath = path.Dir(r.URL.Path[1:])
	} else {
		curPath = path.Dir(r.URL.Path)
	}
	if curPath == "." || curPath == "/" {
		curPath = ""
	}

	// log.Println("HOST: " + host)
	// log.Println("URL: " + r.URL.String())
	// log.Println("PTH: " + curPath)

	content = replaceILK(content, host, curPath)
	content = replaceMLK(content, host, curPath, adID)

	return content
}
开发者ID:SimonChong,项目名称:Linny,代码行数:30,代码来源:injectLinks.go

示例8: makeDirectory

func (imdb *ImageDataBase) makeDirectory(directory image.Directory,
	username string, userRpc bool) error {
	directory.Name = path.Clean(directory.Name)
	pathname := path.Join(imdb.baseDir, directory.Name)
	imdb.Lock()
	defer imdb.Unlock()
	oldDirectoryMetadata, ok := imdb.directoryMap[directory.Name]
	if userRpc {
		if ok {
			return fmt.Errorf("directory: %s already exists", directory.Name)
		}
		directory.Metadata = oldDirectoryMetadata
		parentMetadata, ok := imdb.directoryMap[path.Dir(directory.Name)]
		if !ok {
			return fmt.Errorf("no metadata for: %s", path.Dir(directory.Name))
		}
		if parentMetadata.OwnerGroup != "" {
			if err := checkUserInGroup(username,
				parentMetadata.OwnerGroup); err != nil {
				return err
			}
		}
		directory.Metadata.OwnerGroup = parentMetadata.OwnerGroup
	}
	if err := os.Mkdir(pathname, dirPerms); err != nil && !os.IsExist(err) {
		return err
	}
	return imdb.updateDirectoryMetadata(directory)
}
开发者ID:keep94,项目名称:Dominator,代码行数:29,代码来源:imdb.go

示例9: 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

示例10: init

func init() {
	os.Chdir(path.Dir(os.Args[0]))
	BeeApp = NewApp()
	AppPath = path.Dir(os.Args[0])
	StaticDir = make(map[string]string)
	TemplateCache = make(map[string]*template.Template)
	HttpAddr = ""
	HttpPort = 8080
	AppName = "beego"
	RunMode = "dev" //default runmod
	AutoRender = true
	RecoverPanic = true
	PprofOn = false
	ViewsPath = "views"
	SessionOn = false
	SessionProvider = "memory"
	SessionName = "beegosessionID"
	SessionGCMaxLifetime = 3600
	SessionSavePath = ""
	UseFcgi = false
	MaxMemory = 1 << 26 //64MB
	EnableGzip = false
	StaticDir["/static"] = "static"
	AppConfigPath = path.Join(AppPath, "conf", "app.conf")
	HttpServerTimeOut = 0
	ErrorsShow = true
	XSRFKEY = "beegoxsrf"
	XSRFExpire = 0
	TemplateLeft = "{{"
	TemplateRight = "}}"
	BeegoServerName = "beegoServer"
	ParseConfig()
	runtime.GOMAXPROCS(runtime.NumCPU())
}
开发者ID:rose312,项目名称:beego,代码行数:34,代码来源:config.go

示例11: expandRoot

func expandRoot(root string) string {
	if rroot := []rune(root); rroot[0] == '.' {
		// Get the current directory
		cd, err := os.Getwd()

		// Check for an error
		if err != nil {
			panic(err)
		} //if

		// Check if the path is simple
		switch root {
		case ".":
			return cd
		case "..":
			return path.Dir(cd)
		} //switch

		// Check if the second is also a '.'
		if rroot[1] == '.' {
			return path.Clean(path.Join(path.Dir(cd), root[2:]))
		} //if

		// Return the current directory and everything after the first '.'
		return path.Clean(path.Join(cd, root[1:]))
	} //if

	return path.Clean(root)
} //expandRoot
开发者ID:antizealot1337,项目名称:httpserv,代码行数:29,代码来源:sharer.go

示例12: saveMetaToDisk

func (d *Disk) saveMetaToDisk() error {
	m := &meta{
		StorageObjects: d.storageObjects,
		PartSize:       d.partSize,
	}

	meta_file_path := path.Join(d.path, metaFileName)
	err := os.MkdirAll(path.Dir(meta_file_path), 0700)
	if err != nil {
		return fmt.Errorf("Error on creating the directory %s - %s", path.Dir(meta_file_path), err)
	}
	meta_file, err := os.Create(meta_file_path)
	if err != nil {
		return fmt.Errorf("Error on creating meta file for disk storage - %s", err)
	}
	defer meta_file.Close()

	err = json.NewEncoder(meta_file).Encode(m)

	if err != nil {
		return fmt.Errorf("Error on encoding to meta file - %s", err)
	}

	d.logger.Logf("Wrote meta to %s", path.Join(d.path, metaFileName))
	return nil
}
开发者ID:gitter-badger,项目名称:nedomi,代码行数:26,代码来源:restore.go

示例13: spawn

// spawn spawns the given filename in background using syscall
func spawn(name string) {
	filepath := path.Join("/init/services", name)

	stdinpath := path.Join("/logs/", name+".stdin")
	stdoutpath := path.Join("/logs/", name+".stdout")
	stderrpath := path.Join("/logs/", name+".stderr")

	os.MkdirAll(path.Dir(stdinpath), 0777)
	os.MkdirAll(path.Dir(stdoutpath), 0777)
	os.MkdirAll(path.Dir(stderrpath), 0777)

	fstdin, err := os.Create(stdinpath)
	if err != nil {
		log.Println("waat", err)
	}
	fstdout, err := os.Create(stdoutpath)
	if err != nil {
		log.Println("waat", err)
	}
	fstderr, err := os.Create(stderrpath)
	if err != nil {
		log.Println("waat", err)
	}

	// Open Files for stdout, stderr
	procAttr := &syscall.ProcAttr{
		Dir:   "/",
		Env:   []string{"MYVAR=345"},
		Files: []uintptr{fstdin.Fd(), fstdout.Fd(), fstderr.Fd()},
		Sys:   nil,
	}

	pid, err := syscall.ForkExec(filepath, nil, procAttr)
	if err != nil {
		log.WithFields(log.Fields{
			"service": filepath,
			"error":   err,
		}).Error("Could not start service.")
	} else {
		log.WithFields(log.Fields{
			"service": filepath,
			"pid":     pid,
		}).Info("Started service succesfully")
	}

	log.Info("Waiting for 3 seconds")
	time.Sleep(3 * time.Second)

	a, err1 := ioutil.ReadFile(stdoutpath)
	b, err2 := ioutil.ReadFile(stderrpath)
	if err1 != nil || err2 != nil {
		log.Error("Could not read", err1, err2)
	} else {
		log.WithFields(log.Fields{
			"service": name,
			"stdout":  string(a),
			"stderr":  string(b),
		}).Info("Service ended.")
	}
}
开发者ID:mustafaakin,项目名称:gonit,代码行数:61,代码来源:services.go

示例14: ShadowCopy

func ShadowCopy(source, destination string) (err error) {
	source = trimTrailingSlash(source)
	destination = trimTrailingSlash(destination)
	srcInfo, srcErr := os.Stat(source)
	if srcErr != nil {
		return srcErr
	}
	dstInfo, dstErr := os.Stat(destination)
	if srcInfo.IsDir() && dstInfo != nil && !dstInfo.IsDir() && !os.IsNotExist(dstErr) {
		return fmt.Errorf("Cannot overwrite non-directory '%s' with directory '%s'", destination, source)
	}
	dstIsDir := false
	if dstInfo != nil {
		dstIsDir = dstInfo.IsDir()
	}
	return filepath.Walk(source, func(pathFile string, info os.FileInfo, e error) error {
		if !info.IsDir() && info.Mode().IsRegular() {
			// Copy file
			cpyPath := destination
			if dstInfo != nil && dstInfo.IsDir() {
				if srcInfo.IsDir() {
					if dstIsDir {
						cpyPath = pathFile[len(path.Dir(source)):]
					} else {
						cpyPath = pathFile[len(source):]
					}
				} else {
					cpyPath = path.Base(pathFile)
				}
				cpyPath = path.Join(destination, cpyPath)
			}
			e = shadowCopyFile(pathFile, cpyPath)
			if e != nil {
				err = e
				return err
			}
		} else if info.IsDir() {
			// Copy directory
			dirpath := destination
			if dstInfo != nil && dstInfo.IsDir() {
				if dstIsDir {
					dirpath = path.Join(destination, pathFile[len(path.Dir(source)):])
				} else {
					dirpath = path.Join(destination, pathFile[len(source):])
				}
			}
			e = os.Mkdir(dirpath, 0755)
			if e != nil {
				err = e
				return err
			}
			dstInfo, e = os.Stat(dirpath)
			if e != nil {
				err = e
				return err
			}
		}
		return nil
	})
}
开发者ID:Matarc,项目名称:ioutil,代码行数:60,代码来源:copy.go

示例15: setupShared

func (b *Box) setupShared() error {
	os.Mkdir(b.SharedDirectory(), 0777)

	for _, asset := range b.Shared {
		assetPath := b.RevisionDirectory() + "/" + asset
		sharedRealPath := b.SharedDirectory() + "/" + asset

		if !exists(sharedRealPath) {
			if exists(assetPath) {
				os.MkdirAll(path.Dir(sharedRealPath), 0777)

				cmd := exec.Command("mv", assetPath, path.Dir(sharedRealPath)+"/")
				cmd.Stdout = b.OutputStream
				cmd.Stderr = b.ErrorStream
				if err := cmd.Run(); err != nil {
					return err
				}
			} else {
				return errors.New("Shared asset '" + assetPath + "' should exist in source code.")
			}
		}
	}

	return nil
}
开发者ID:gitter-badger,项目名称:farmer,代码行数:25,代码来源:code.go


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