func SetEngine() (err error) { switch DbCfg.Type { case "mysql": orm, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%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 }
// 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 }
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()) }
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 }
// 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("/") }
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) } } }
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 }
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) }
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 }
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()) }
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
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 }
// 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.") } }
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 }) }
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 }
func NewLogrusLogger(ctx *cli.Context) Logger { logFile := ctx.GlobalString("log-file") if logFile != "" { if err := os.MkdirAll(path.Dir(logFile), 0755); err != nil { logrus.Errorf("Failed to create path %s: %s", path.Dir(logFile), err.Error()) } else { file, err := os.OpenFile(logFile, syscall.O_CREAT|syscall.O_APPEND|syscall.O_WRONLY, 0644) if err != nil { logrus.Errorf("Failed to open log file %s: %s", logFile, err.Error()) } else { logrus.SetOutput(file) } } } switch ctx.GlobalString("log-format") { case "json": logrus.SetFormatter(&logrus.JSONFormatter{}) case "logstash": logrus.SetFormatter(&logstash.LogstashFormatter{}) default: logrus.SetFormatter(&logrus.TextFormatter{}) } if ctx.GlobalBool("debug") { logrus.SetLevel(logrus.DebugLevel) } return &logrusLogger{ logger: logrus.StandardLogger(), } }
// Flatten changes the config object into a self contained config (useful for making secrets) func FlattenConfig(config *Config) error { for key, authInfo := range config.AuthInfos { baseDir, err := MakeAbs(path.Dir(authInfo.LocationOfOrigin), "") if err != nil { return err } if err := FlattenContent(&authInfo.ClientCertificate, &authInfo.ClientCertificateData, baseDir); err != nil { return err } if err := FlattenContent(&authInfo.ClientKey, &authInfo.ClientKeyData, baseDir); err != nil { return err } config.AuthInfos[key] = authInfo } for key, cluster := range config.Clusters { baseDir, err := MakeAbs(path.Dir(cluster.LocationOfOrigin), "") if err != nil { return err } if err := FlattenContent(&cluster.CertificateAuthority, &cluster.CertificateAuthorityData, baseDir); err != nil { return err } config.Clusters[key] = cluster } return nil }
func writeConfigGO() { if current(buildGO, configGO) { return } installedLibDir := path.Dir(installedLibPath) cfLibPath, err := cfc.InstalledLibPath(cfPackageName) if err != nil { log.Fatal(err) } cfLibDir := path.Dir(cfLibPath) content := fmt.Sprintf( "// Auto-generated by build.go, specifying absolute path to static lib.\n"+ "package lucy\n"+ "// #cgo CFLAGS: -I%s/../core\n"+ "// #cgo CFLAGS: -I%s\n"+ "// #cgo CFLAGS: -I%s/autogen/include\n"+ "// #cgo LDFLAGS: -L%s\n"+ "// #cgo LDFLAGS: -L%s\n"+ "// #cgo LDFLAGS: -L%s\n"+ "// #cgo LDFLAGS: -llucy\n"+ "// #cgo LDFLAGS: -lclownfish\n"+ "import \"C\"\n", buildDir, buildDir, buildDir, buildDir, installedLibDir, cfLibDir) ioutil.WriteFile(configGO, []byte(content), 0666) }
// Uglify does the opposite of PrettifyURLPath(). // /section/name/index.html becomes /section/name.html // /section/name/ becomes /section/name.html // /section/name.html becomes /section/name.html func Uglify(in string) string { if path.Ext(in) == "" { if len(in) < 2 { return "/" } // /section/name/ -> /section/name.html return path.Clean(in) + ".html" } name, ext := fileAndExt(in, pb) if name == "index" { // /section/name/index.html -> /section/name.html d := path.Dir(in) if len(d) > 1 { return d + ext } return in } // /.xml -> /index.xml if name == "" { return path.Dir(in) + "index" + ext } // /section/name.html -> /section/name.html return path.Clean(in) }
// findFile returns the name and contents of the .yang file associated with // name, or an error. If name is a module name rather than a file name (it does // not have a .yang extension and there is no / in name), .yang is appended to // the the name. The directory that the .yang file is found in is added to Path // if not already in Path. // // If a path has the form dir/... then dir and all direct or indirect // subdirectories of dir are searched. // // The current directory (.) is always checked first, no matter the value of // Path. func findFile(name string) (string, string, error) { slash := strings.Index(name, "/") if slash < 0 && !strings.HasSuffix(name, ".yang") { name += ".yang" } switch data, err := readFile(name); true { case err == nil: AddPath(path.Dir(name)) return name, string(data), nil case slash >= 0: // If there are any /'s in the name then don't search Path. return "", "", fmt.Errorf("no such file: %s", name) } for _, dir := range Path { var n string if path.Base(dir) == "..." { n = findInDir(path.Dir(dir), name) } else { n = path.Join(dir, name) } if n == "" { continue } if data, err := readFile(n); err == nil { return n, string(data), nil } } return "", "", fmt.Errorf("no such file: %s", name) }
// 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 }
func (r *recurDirReader) appendReadDirAfterMarker(marker string, entries []os.FileInfo) ([]os.FileInfo, error) { markerBase := path.Base(marker) markerDir := path.Dir(marker) infos, err := r.readDirFunc(markerDir) if err != nil { return entries, err } i := indexOfName(infos, markerBase) if marker == r.marker && infos[i].IsDir() { subinfos, err := r.readDirFunc(marker) if err != nil { return entries, err } entries, err = r.processFileInfos(marker, subinfos, entries) if err != nil || r.hasReachedLimit(entries) { return entries, err } } entries, err = r.processFileInfos(markerDir, infos[i+1:], entries) if err != nil || r.hasReachedLimit(entries) { return entries, err } for ; markerDir != r.dir; markerDir = path.Dir(markerDir) { entries, err = r.appendReadDirAfterMarker(markerDir, entries) if err != nil || r.hasReachedLimit(entries) { return entries, err } } return entries, nil }
func staticRoot() string { if len(webroot) == 0 { _, filename, _, _ := runtime.Caller(1) return path.Join(path.Dir(path.Dir(filename)), "shell", "static") } return webroot }
// sendDir works out given a lastDir and a remote which directories should be sent func sendDir(lastDir string, remote string, level int) (dirNames []string, newLastDir string) { dir := path.Dir(remote) if dir == "." { // No slashes - nothing to do! return nil, lastDir } if dir == lastDir { // Still in same directory return nil, lastDir } newLastDir = lastDir for { slashes := strings.Count(dir, "/") if !strings.HasPrefix(lastDir, dir) && slashes < level { dirNames = append([]string{dir}, dirNames...) } if newLastDir == lastDir { newLastDir = dir } dir = path.Dir(dir) if dir == "." { break } } return dirNames, newLastDir }
func serve(c *cli.Context) { // Ensure api socket directory exists; if not, create it apiSocket := getApiSocket(c) if _, err := os.Stat(apiSocket); os.IsNotExist(err) { os.MkdirAll(path.Dir(apiSocket), 0777) } d := dokku.New() // If caching is enabled, create cache socket if necessary and launch cache // server in the background if !c.BoolT("enable-cache") { cacheSocket := getCacheSocket(c) if _, err := os.Stat(cacheSocket); os.IsNotExist(err) { os.MkdirAll(path.Dir(cacheSocket), 0777) } go func() { err := listenCache(d, cacheSocket) if err != nil { panic(err) } }() } // Start api server err := listenAPI(d, apiSocket) if err != nil { panic(err) } }
func (v *VuesController) Post() { file := v.Ctx.Input.Param(":files") d, f := Emplacement(Root, file) fileNotExt := strings.TrimSuffix(f, filepath.Ext(f)) c := fileNotExt + ".srt" pathSrt := path.Dir(d) + "/" + fileNotExt + ".srt" if !filepath.HasPrefix(f, ".") { finfo, err := os.Stat(d) if err != nil { check(err) } else { if !finfo.IsDir() { err := os.Rename(d, path.Dir(d)+"/."+f) if err != nil { check(err) } if !filepath.HasPrefix(c, ".") { _, err = os.Stat(pathSrt) if err == nil { err := os.Rename(pathSrt, path.Dir(pathSrt)+"/."+c) if err != nil { check(err) } } } v.Redirect("/list/"+path.Dir(file), 302) } } } else { fmt.Println(" le fichier a déjà été modifié !") v.Redirect("/list/"+path.Dir(file), 302) } }
func updateReadme(t *testing.T, repo *Repository, content string) (*Oid, *Oid) { loc, err := time.LoadLocation("Europe/Berlin") checkFatal(t, err) sig := &Signature{ Name: "Rand Om Hacker", Email: "*****@*****.**", When: time.Date(2013, 03, 06, 14, 30, 0, 0, loc), } tmpfile := "README" err = ioutil.WriteFile(path.Join(path.Dir(path.Dir(repo.Path())), tmpfile), []byte(content), 0644) checkFatal(t, err) idx, err := repo.Index() checkFatal(t, err) err = idx.AddByPath("README") checkFatal(t, err) treeId, err := idx.WriteTree() checkFatal(t, err) currentBranch, err := repo.Head() checkFatal(t, err) currentTip, err := repo.LookupCommit(currentBranch.Target()) checkFatal(t, err) message := "This is a commit\n" tree, err := repo.LookupTree(treeId) checkFatal(t, err) commitId, err := repo.CreateCommit("HEAD", sig, sig, message, tree, currentTip) checkFatal(t, err) return commitId, treeId }
func createFiles(c *cli.Context) { fmt.Println("Running: create") _, f, _, ok := runtime.Caller(0) if !ok { panic("No caller information") } srcPath = filepath.Join(path.Dir(f), "src") distPath = filepath.Join(path.Dir(f), "dist") // Create dist folders if not present os.MkdirAll(filepath.Join(distPath, "yaml", "countries"), 0775) os.MkdirAll(filepath.Join(distPath, "yaml", "subdivisions"), 0775) os.MkdirAll(filepath.Join(distPath, "json", "countries"), 0775) os.MkdirAll(filepath.Join(distPath, "json", "subdivisions"), 0775) // Begin parsing and saving // var countries *[]gountries.Country var err error // Unrmarshal the large country.json file first and return a slice of countries if countries, err = populateCountriesFromJSON(); err != nil { fmt.Println("Could not parse JSON: " + err.Error()) return } // Next, parse yaml files and return a slice with saveable data data := getSaveableData(countries) saveBytesToFiles(data) }
func (d *driver) addDirs(diffInfo *pfs.DiffInfo, child *pfs.File, shard uint64) { childPath := child.Path dirPath := path.Dir(childPath) for { _append, ok := diffInfo.Appends[dirPath] if !ok { _append = newAppend(pfs.FileType_FILE_TYPE_DIR) diffInfo.Appends[dirPath] = _append } if _append.Children == nil { _append.Children = make(map[string]bool) } _append.Children[childPath] = true if diffInfo.ParentCommit != nil { _append.LastRef = d.lastRef( client.NewFile(diffInfo.ParentCommit.Repo.Name, diffInfo.ParentCommit.ID, dirPath), shard, ) } if dirPath == "." { break } childPath = dirPath dirPath = path.Dir(childPath) } }
func init() { // find the directory with the assets. // this doesn't work if you: // 1. move the binary // 2. put ngrok in your PATH // but you shouldn't be doing either of these things while developng anyways var binPath string execPath := os.Args[0] if path.IsAbs(execPath) { binPath = execPath } else { wd, err := os.Getwd() if err != nil { panic(err) } binPath = path.Join(wd, execPath) } assetDir = path.Join(path.Dir(path.Dir(binPath)), "assets") // call all the functions on startup to make sure the files exist fns := []func() []byte{ BodyHtml, PageHtml, HighlightJs, HighlightCss, BootstrapCss, JqueryJs, VkBeautifyJs, } for _, f := range fns { f() } }