// ConvertToMP3 converts given file into .mp3 file // Example: ConvertToMP3("oldAudio", "newAudio") // Result: newAudio.mp3 // If only one argument is passed, than result will have the same name func ConvertToMP3(filenames ...string) error { var toFilename string var fromFilename string = filenames[0] switch len(filenames) { case 1: toFilename = cutExtension(filenames[0]) break case 0: return errors.New("error: no arguements passed") default: toFilename = cutExtension(filenames[1]) } os.Remove(toFilename + ".mp3") // Convert to MP3 switch path.Ext(fromFilename) { case ".amr": comm := exec.Command("ffmpeg", "-i", fromFilename, "-ar", AudioSamplingRateMP3, toFilename+".mp3") if err := comm.Run(); err != nil { return ConvertError } default: return fmt.Errorf("Unsupported format: %v", path.Ext(fromFilename)) } return nil }
// When a test is skipped or fails, runtime.Goexit() is called which destroys the callstack. // This means the name of the test case is lost, so we need to grab a copy of pc before. func Report(t testing.TB) { // If the goroutine panics, Fatal()s, or Skip()s, the function name is at the 3rd callstack // layer. On success, its at 1st. Since it's hard to check which happened, just try both. pcs := make([]uintptr, 10) total := runtime.Callers(1, pcs) var name string for _, pc := range pcs[:total] { fn := runtime.FuncForPC(pc) fullName := fn.Name() if strings.HasPrefix(path.Ext(fullName), ".Test") { // Skip the leading . name = string([]byte(path.Ext(fullName))[1:]) break } } if name == "" { return } allCaseInfos.lock.Lock() defer allCaseInfos.lock.Unlock() allCaseInfos.Cases = append(allCaseInfos.Cases, &caseInfo{ Name: name, Passed: !t.Failed() && !t.Skipped(), Skipped: t.Skipped(), Fatal: t.Failed() && !strings.HasPrefix(name, "TestSoon"), }) }
func (this *SunnyEndPoint) GetRequestedEndPoint(r *http.Request, upath []string, data []string) *RequestedEndPoint { handlers := this.Handlers() if h, exists := handlers[r.Method]; exists && h != nil { var pdata = make(map[string]string) for i, value := range data { if this.varnames[i] != "_" { pdata[this.varnames[i]] = value } } ext := "" lastele := len(upath) - 1 if lastele >= 0 && strings.Contains(upath[lastele], ".") { ext = path.Ext(upath[lastele]) upath[lastele] = strings.TrimSuffix(upath[lastele], ext) } else { ext = path.Ext(strings.TrimRight(r.URL.Path, "/")) } return &RequestedEndPoint{ Ext: ext, UPath: web.UPath(upath), PData: web.PData(pdata), Method: r.Method, Handler: h, EndPoint: this, } } return nil }
// Reads an array from a file. func ReadFile(fname string) *host.Array { readFunc, ok := inputFormats[path.Ext(fname)] if !ok { panic(InputErrF("Can not load file with extension ", path.Ext(fname))) } return readFunc(fname) }
// AddFile saves to Response.Files preparing for Pipeline func (self *Response) AddFile(name ...string) { file := map[string]interface{}{ "Body": self.Response.Body, } _, s := path.Split(self.GetUrl()) n := strings.Split(s, "?")[0] // 初始化 baseName := strings.Split(n, ".")[0] ext := path.Ext(n) if len(name) > 0 { _, n = path.Split(name[0]) if baseName2 := strings.Split(n, ".")[0]; baseName2 != "" { baseName = baseName2 } if ext == "" { ext = path.Ext(n) } } if ext == "" { ext = ".html" } file["Name"] = baseName + ext self.files = append(self.files, file) }
func (fs *gopherJSFS) openSource(path string) (http.File, error) { f, err := fs.source.Open(path) if err != nil { return nil, err } fi, err := f.Stat() if err != nil { f.Close() return nil, err } switch { // Files with .go and ".inc.js" extensions are consumed and no longer exist // in output filesystem. case !fi.IsDir() && pathpkg.Ext(fi.Name()) == ".go": fallthrough case !fi.IsDir() && strings.HasSuffix(fi.Name(), ".inc.js"): f.Close() return nil, &os.PathError{Op: "open", Path: path, Err: os.ErrNotExist} case !fi.IsDir(): return f, nil } defer f.Close() fis, err := f.Readdir(0) if err != nil { return nil, err } // Include all subfolders, non-.go files. var entries []os.FileInfo var haveGo []os.FileInfo for _, fi := range fis { switch { case !fi.IsDir() && pathpkg.Ext(fi.Name()) == ".go": haveGo = append(haveGo, fi) case !fi.IsDir() && strings.HasSuffix(fi.Name(), ".inc.js"): // TODO: Handle ".inc.js" files correctly. entries = append(entries, fi) default: entries = append(entries, fi) } } // If it has any .go files, present the Go package compiled with GopherJS as an additional virtual file. if len(haveGo) > 0 { entries = append(entries, &file{ name: fi.Name() + ".js", size: 0, // TODO. modTime: time.Time{}, // TODO. }) } return &dir{ name: fi.Name(), entries: entries, modTime: fi.ModTime(), }, nil }
// ConvertToM4A converts given file into .m4a file // Example: ConvertToM4A("oldAudio", "newAudio") // Result: newAudio.M4A // If only one argument is passed, than result will have the same name func ConvertToM4A(fromFilename string, length string) error { toFilename := cutExtension(fromFilename) fmt.Println(fromFilename, toFilename, length) os.Remove(toFilename + ".m4a") // Convert to M4A switch path.Ext(fromFilename) { case ".amr": // fileSize (in bytes) / bit-rate (bits/secs)*8 // ffmpeg -t 2 -i test.amr -ar 8k test1.m4a var comm *exec.Cmd if length != "" { fmt.Println("ffmpeg", "-t", length, "-i", fromFilename, toFilename+".m4a") comm = exec.Command("ffmpeg", "-t", length, "-i", fromFilename, toFilename+".m4a") } else { comm = exec.Command("ffmpeg", "-i", fromFilename, toFilename+".m4a") } if err := comm.Run(); err != nil { return ConvertError } default: return fmt.Errorf("Unsupported format: %v", path.Ext(fromFilename)) } return nil }
// This getKey interprets key IDs as paths, and loads private keys from the // specified file func getKey(keyid string) (crypto.PrivateKey, error) { fileContents, err := ioutil.ReadFile(keyid) if err != nil { return nil, err } if path.Ext(keyid) == ".ed25519secret" { if got, want := len(fileContents), ed25519.PrivateKeySize; got != want { return nil, fmt.Errorf("ed25519 private key %s has wrong size %d (want %d)", keyid, got, want) } var keyArray [ed25519.PrivateKeySize]uint8 copy(keyArray[:], fileContents) return &keyArray, nil } else if path.Ext(keyid) == ".vrfsecret" { if got, want := len(fileContents), vrf.SecretKeySize; got != want { return nil, fmt.Errorf("VRF private key %s has wrong size %d (want %d)", keyid, got, want) } var keyArray [vrf.SecretKeySize]uint8 copy(keyArray[:], fileContents) return &keyArray, nil } else { keyPEM := fileContents var keyDER *pem.Block for { keyDER, keyPEM = pem.Decode(keyPEM) if keyDER == nil { return nil, fmt.Errorf("failed to parse key PEM in %s", keyid) } if keyDER.Type == "PRIVATE KEY" || strings.HasSuffix(keyDER.Type, " PRIVATE KEY") { break } } return parsePrivateKey(keyDER.Bytes) } }
func (s *processedAsset) requiredPaths(rx *regexp.Regexp) ([]string, error) { f, err := os.Open(s.static.pathname) if err != nil { return nil, err } defer f.Close() buf := bufio.NewReader(f) paths := make([]string, 0) for { line, err := buf.ReadString('\n') if err == io.EOF { break } else if err != nil { return nil, err } if strings.TrimSpace(line) != "" && !strings.HasPrefix(line, "//") { break } matches := rx.FindStringSubmatch(line) if len(matches) > 1 { match := matches[1] if path.Ext(match) == "" { match += path.Ext(s.static.logical) } paths = append(paths, match) } } return paths, nil }
// TypeByExtension returns the MIME type associated with the file extension ext. // 获取文件类型,选项ContentType使用 func TypeByExtension(filePath string) string { typ := mime.TypeByExtension(path.Ext(filePath)) if typ == "" { typ = extToMimeType[strings.ToLower(path.Ext(filePath))] } return typ }
func main() { argsWithoutProg := os.Args[1:] if len(argsWithoutProg) <= 0 { fmt.Println("Please enter a directory or file path.\r\[email protected]") return } target, err := os.Stat(argsWithoutProg[0]) if os.IsNotExist(err) { fmt.Printf("No such file or directory: %s", argsWithoutProg[0]) return } //process directory if target.IsDir() { files, _ := ioutil.ReadDir(argsWithoutProg[0]) for _, file := range files { if file.IsDir() { continue } else { filePath := path.Join(argsWithoutProg[0], file.Name()) if path.Ext(filePath) == FILE_EXT { PatchFile(filePath) } } } } else { if path.Ext(argsWithoutProg[0]) == FILE_EXT { PatchFile(argsWithoutProg[0]) } } }
func getTemplates() (*template.Template, error) { t := template.New("") root := "app/tpl" err := filepath.Walk(root, func(p string, info os.FileInfo, err error) error { if info.IsDir() { return nil } if path.Ext(p) != ".tpl" { return nil } if err != nil { return err } contents, err := ioutil.ReadFile(p) if err != nil { return err } nm := strings.Replace(p, "\\", "/", -1) nm = nm[len(root):] nm = nm[:len(nm)-len(path.Ext(nm))] child := t.New(nm) _, err = child.Parse(string(contents)) return err }) return t, err }
func (r *Response) detectContentType() (sure bool) { if r.CertainType { return true } defer func() { r.CertainType = sure }() if t := r.Header.Get("Content-Type"); t != "" { r.ContentType = t return true } if r.NewURL != nil || r.ContentLocation != nil { var pth, ext string if r.NewURL != nil { pth = r.NewURL.Path ext = path.Ext(pth) } if ext == "" && r.ContentLocation != nil { pth = r.ContentLocation.Path ext = path.Ext(pth) } if ext != "" { if t := mime.TypeByExtension(ext); t != "" { r.ContentType = t return true } } else if strings.HasSuffix(pth, "/") { r.ContentType = "text/html" return false } } r.ContentType = string(media.UNKNOWN) return false }
func isYaml(filename string) bool { if path.Ext(filename) == ".yml" || path.Ext(filename) == ".yaml" { return true } return false }
func Handler(nc *blobserv.Client, w http.ResponseWriter, r *http.Request) { defer util.DeferWrite(w) c = nc tmpl := template.Must(template.ParseFiles(appserv.Static("pics/index.tmpl"))) if picIndex == nil { loadPicIndex() } updateIndex() pth := strings.Trim(r.URL.Path, "/") if pth == "pics" { links := picLinks(picIndex.Newest(10)) err := tmpl.Execute(w, links) util.Check(err) } else if strings.HasPrefix(pth, "pics/ref/") { ref := path.Base(pth) ref = ref[:len(ref)-len(path.Ext(ref))] fblob, err := c.ObjectTip(ref) util.Check(err) m, data, err := c.ReconstituteFile(fblob.Ref()) util.Check(err) ext := path.Ext(m.Name) w.Header().Set("Content-Type", mime.TypeByExtension(ext)) w.Write(data) } else { err := util.LoadStatic(appserv.Static(pth), w) util.Check(err) } }
func (c *appContext) uploadPic(a *multipart.FileHeader) (string, string) { log.Println("In upload pic territory") bucket := c.bucket file, err := a.Open() defer file.Close() if err != nil { panic(err.Error()) } if err != nil { panic(err) } buf, _ := ioutil.ReadAll(file) fn := uuid.New() fname := "places/" + fn + path.Ext(a.Filename) thumbname := "placesthumb/" + fn + path.Ext(a.Filename) log.Println(fname) b := "http://s3-us-west-2.amazonaws.com/" + c.bucket.Name + "/" + fname d := "http://s3-us-west-2.amazonaws.com/" + c.bucket.Name + "/" + thumbname filetype := http.DetectContentType(buf) err = bucket.Put(fname, buf, filetype, s3.PublicRead) if err != nil { log.Println("bucket put error for main image") panic(err.Error()) } log.Print("added a full image") img, err := jpeg.Decode(bytes.NewReader(buf)) if err != nil { log.Println(err.Error()) } m := resize.Resize(200, 200, img, resize.Lanczos2) buf2 := new(bytes.Buffer) err = jpeg.Encode(buf2, m, nil) if err != nil { fmt.Println(err.Error()) } thumb := buf2.Bytes() filetype2 := http.DetectContentType(thumb) err = bucket.Put(thumbname, thumb, filetype2, s3.PublicRead) if err != nil { log.Println("bucket put error for thumbnail") panic(err.Error()) } log.Println("uploaded one thumb image") return b, d }
// 输出文件。 // name指定文件名,为空时默认保持原文件名不变。 func (self *Context) FileOutput(name ...string) { _, s := path.Split(self.GetUrl()) n := strings.Split(s, "?")[0] // 初始化 baseName := strings.Split(n, ".")[0] ext := path.Ext(n) if len(name) > 0 { p, n := path.Split(name[0]) if baseName2 := strings.Split(n, ".")[0]; baseName2 != "" { baseName = p + baseName2 } if ext == "" { ext = path.Ext(n) } } if ext == "" { ext = ".html" } self.Lock() self.files = append(self.files, data.GetFileCell(self.GetRuleName(), baseName+ext, self.Response.Body)) self.Unlock() }
// 输出文件。 // name指定文件名,为空时默认保持原文件名不变。 func (self *Context) FileOutput(name ...string) { // 读取完整文件流 bytes, err := ioutil.ReadAll(self.Response.Body) self.Response.Body.Close() if err != nil { panic(err.Error()) return } // 智能设置完整文件名 _, s := path.Split(self.GetUrl()) n := strings.Split(s, "?")[0] baseName := strings.Split(n, ".")[0] var ext string if len(name) > 0 { p, n := path.Split(name[0]) if baseName2 := strings.Split(n, ".")[0]; baseName2 != "" { baseName = p + baseName2 } ext = path.Ext(n) } if ext == "" { ext = path.Ext(n) } if ext == "" { ext = ".html" } // 保存到文件临时队列 self.Lock() self.files = append(self.files, data.GetFileCell(self.GetRuleName(), baseName+ext, bytes)) self.Unlock() }
// AddFont takes a font filename and compiles it into Report.FontCompiledPath // with the encoding specified. It strips the filename extension and replaces // it with .json automatically. The extension-less string becomes the name of // the font family to use with Report.AddStyle(). For example: // // r.AddFont("OpenSans-Bold.ttf", "cp1252") // r.AddStyle("header", "OpenSans-Bold", "", 64, AlignmentTop | AlignmentLeft) // // The following encodings are supported: // // cp1250 // cp1251 // cp1252 // cp1253 // cp1254 // cp1255 // cp1257 // cp1258 // cp874 // iso-8859-1 // iso-8859-11 // iso-8859-15 // iso-8859-16 // iso-8859-2 // iso-8859-4 // iso-8859-5 // iso-8859-7 // iso-8859-9 // koi8-r // koi8-u func (r *Report) AddFont(filename, encoding string) error { var err error err = r.PrepareFontCompiledPath() if err != nil { return err } ext := path.Ext(filename) familyName := filename[:len(filename)-len(ext)] // auto compiles if path.Ext(filename) == ".json" { if r.IsCompiledFile(filename) { r.Pdf.AddFont(familyName, "", filename) } else { return fmt.Errorf("Cache font file not found: %s", filename) } } else { if r.IsSourcedFont(filename) { compiledFilename, err := r.CompileFont(filename, encoding) if err != nil { return fmt.Errorf("Could not compile font: %v", err) } r.Pdf.AddFont(familyName, "", compiledFilename) } else { return fmt.Errorf("Source font file not found: %s", filename) } } return nil }
// ConvertToAMR converts given file into .amr file // Example: ConvertToMP3("oldAudio", "newAudio") // Result: newAudio.amr // If only one argument is passed, than result will have the same name func ConvertToAMR(fromFilename string, length string) error { toFilename := cutExtension(fromFilename) _ = length os.Remove(toFilename + ".amr") switch path.Ext(fromFilename) { case ".mp3", ".m4a": // Convert to WAV comm := exec.Command("ffmpeg", "-i", fromFilename, "-f", "wav", toFilename+".wav") if err := comm.Run(); err != nil { return ConvertError } // Convert to AMR comm = exec.Command("ffmpeg", "-i", toFilename+".wav", "-ab", AudioBitRate, "-ac", NumberOfAudioChannels, "-ar", AudioSamplingRateAMR, toFilename+".amr") if err := comm.Run(); err != nil { return ConvertError } // Delete tmp file if err := os.Remove(toFilename + ".wav"); err != nil { log.Println(err) } default: return fmt.Errorf("Unsupported format: %v", path.Ext(fromFilename)) } return nil }
func main() { flag.Parse() if flag.NArg() == 0 { log.Fatal("missing file name") } name := flag.Args()[0] f, err := os.Open(name) if err != nil { log.Fatal(err) } defer f.Close() var r io.Reader if path.Ext(name) == ".gz" { gz, err := gzip.NewReader(f) if err != nil { log.Fatal(err) } name = strings.TrimSuffix(name, ".gz") r = gz } else { r = f } var aDok *sparse.DOK switch path.Ext(name) { case ".mtx": aDok, err = readMatrixMarket(r) case ".rsa": log.Fatal("reading of Harwell-Boeing format not yet implemented") default: log.Fatal("unknown file extension") } if err != nil { log.Fatal(err) } a := sparse.NewCSR(aDok) n, _ := a.Dims() x := make([]float64, n) for i := range x { x[i] = 1 } b := make([]float64, n) sparse.MulMatVec(1, false, a, x, 1, 0, b, 1) for i := range x { x[i] = 0 } result, err := iterative.Solve(a, b, x, nil, &iterative.CG{}) if err != nil { log.Fatal(err) } if len(result.X) > 10 { fmt.Println("Solution[:10]:", result.X[:10]) } else { fmt.Println("Solution:", result.X) } }
// Checks whether the incoming request has the same expected type as an // over-ride specification. func matchTypes(spec string, req string) bool { smime := _getType(path.Ext(spec)) rmime := _getType(path.Ext(req)) if smime == rmime { return true } return false }
func compile(cmd *cobra.Command, args []string) { if len(args) < 1 { log.Fatal("You need to specify a level directory to compile!") } levelDir = args[0] if levelFile == "" { levelFile = path.Base(levelDir) + ".lvl" } log.Println("will compile to", levelFile) lvlMan := &data.Level{} buf, err := ioutil.ReadFile(levelDir + "/Manifest.json") if err != nil { log.Fatal("Error reading file: ", err) } err = json.Unmarshal(buf, lvlMan) if err != nil { log.Fatal("Error reading level manifest: ", err) } fmt.Println(lvlMan) for k, _ := range lvlMan.Layers { log.Println("Processing layer: ", k) dirlist, derr := ioutil.ReadDir(levelDir + "/" + k) if derr != nil { log.Println("Layer directory error: ", derr) } else { lvlMan.Layers[k].Frames = make(map[int]([][]rune)) for _, fi := range dirlist { if path.Ext(fi.Name()) == ".frame" { log.Println(fi.Name()) fdata, derr := ioutil.ReadFile(levelDir + "/" + k + "/" + fi.Name()) if derr != nil { log.Println("Error reading frame: ", derr) } else { rdata := make([][]rune, 0, 25) for _, line := range strings.Split(string(fdata), "\n") { rdata = append(rdata, []rune(line)) } idx, ierr := strconv.Atoi(strings.TrimSuffix(fi.Name(), path.Ext(fi.Name()))) if ierr != nil { log.Printf("Invalid Index in Filename: ", ierr) } else { lvlMan.Layers[k].Frames[idx] = rdata } } } } } } obuf := &bytes.Buffer{} enc := gob.NewEncoder(obuf) enc.Encode(&lvlMan) ioutil.WriteFile(levelFile, obuf.Bytes(), 0644) log.Println("done.") }
// FromArg gets the json/yaml file from args func (f *File) FromArg(read bool) error { // (length - 1) arg := os.Args[len(os.Args)-1:][0] // get extension ext := path.Ext(arg) if len(ext) > 1 { ext = ext[1:] // remove dot } // when json/yaml file isn't found on last arg // it searches for a ".json" or ".yaml" string in all args if ext != "json" && ext != "yaml" { // loop through args for _, a := range os.Args { // get extension ext := path.Ext(a) // check for valid extensions if ext == ".json" || ext == ".yaml" { f.Mode = ext[1:] // remove dot ext = f.Mode arg = a break } } } else { f.Mode = ext } // check if extension is json or yaml // then get it's absolute path if ext == "json" || ext == "yaml" { abs := filepath.IsAbs(arg) if !abs { dir, err := utils.GetCurrentDir() if err != nil { return err } arg = filepath.Clean(dir + "/" + arg) } f.FilePath = arg // so we can test without reading a file if read { if !utils.Exists(f.FilePath) { return errors.New("Error: I Can't find the config file at [" + f.FilePath + "]") } } } else { return errors.New("Error: You must specify a json or yaml file") } return nil }
func (p *JSMin) ProcessedFileName(fileName string) (string, bool) { ext := path.Ext(fileName) baseName := fileName[:len(fileName)-len(ext)] ext2 := path.Ext(baseName) if ext == ".js" && ext2 != ".min" { return baseName + ".min.js", true } return fileName, false }
func (p *JSMin) ReverseFileName(fileName string) (string, bool) { ext := path.Ext(fileName) baseName := fileName[:len(fileName)-len(ext)] ext2 := path.Ext(baseName) baseName = baseName[:len(baseName)-len(ext2)] if ext == ".js" && ext2 == ".min" { return baseName + ".js", true } return fileName, false }
func ReadAssetsFunc(filePath, assetUrl string, found func(filePath string, content string)) (filePaths []string, err error) { fileExt := path.Ext(filePath) fileExtPattern := patternExt(fileExt) var cacheKey string if cacheKey, err = generateCacheKey(filePath); err != nil { err = errors.New("Asset Not Found: " + assetUrl) return } requiredAssetUrls, content, hit := readFromCache(cacheKey) if !hit { content, err = ReadRawAsset(filePath, assetUrl) if err != nil { return } header := FindDirectivesHeader(&content, fileExtPattern) content, err = ReadRawAndCompileAsset(filePath, assetUrl) content = hotFixSASSCommentLines(content, fileExt) if len(header) != 0 { content = strings.Replace(content, header, "", 1) for _, line := range strings.Split(header, "\n") { if !patterns[fileExtPattern]["require"].Match([]byte(line)) { continue } requiredAssetUrl := string(patterns[fileExtPattern]["require"].ReplaceAll([]byte(line), []byte(""))) if len(requiredAssetUrl) == 0 { continue } requiredAssetUrls = append(requiredAssetUrls, requiredAssetUrl) } } writeToCache(cacheKey, requiredAssetUrls, content) } for _, requiredAssetUrl := range requiredAssetUrls { var paths []string requiredFilePath := ResolvePath(requiredAssetUrl + fileExt) requiredFileExt := path.Ext(requiredFilePath) paths, err = ReadAssetsFunc(requiredFilePath, requiredAssetUrl+requiredFileExt, found) if err != nil { err = errors.New(fmt.Sprintf("%s\n--- required by %s", err.Error(), assetUrl)) return } filePaths = append(filePaths, paths...) } found(filePath, content) filePaths = append(filePaths, filePath) return }
func fetchAndRenderDoc(user, repo, ref, doc string) (string, error) { template := make(chan string) templateName := "template" templateRecv := false defer func() { if !templateRecv { <-template } }() if doc == "index.md" { templateName = "home" } go fetchTemplate(template, user, repo, ref, templateName) // https://github.com/github/markup/blob/master/lib/github/markups.rb#L1 mdExts := markdownExtensions() if ok, _ := mdExts[path.Ext(doc)]; !ok { doc += ".md" } bodyStr, err := fetchDoc(user, repo, ref, "docs/"+doc) if err != nil { return "", err } resp, err := http.Post("https://api.github.com/markdown/raw?access_token="+os.Getenv("ACCESS_TOKEN"), "text/x-markdown", strings.NewReader(bodyStr)) if err != nil { return "", err } body, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { return "", err } pagesClass := strings.Replace(doc, "/", "-", -1) pagesClass = pagesClass[:len(pagesClass)-len(path.Ext(pagesClass))] output := strings.Replace(<-template, "{{CONTENT}}", string(body), 1) templateRecv = true output = strings.Replace(output, "{{NAME}}", repo, -1) output = strings.Replace(output, "{{USER}}", user, -1) output = strings.Replace(output, "{{PAGE_CLASS}}", pagesClass, -1) // Fix relative links output, err = fixRelativeLinks(doc, repo, ref, output) if err != nil { return "", err } return output, nil }
func (app *App) importAssets(included *includedApp) error { im := included.app.assetsManager if !app.shouldImportAssets() { im.SetPrefix(included.prefix + im.Prefix()) return nil } m := app.assetsManager prefix := strings.ToLower(included.name) renames := make(map[string]string) err := vfs.Walk(im.VFS(), "/", func(fs vfs.VFS, p string, info os.FileInfo, err error) error { if err != nil || info.IsDir() { return err } if p != "" && p[0] == '/' { p = p[1:] } log.Debugf("will import asset %v from app %s", p, included.name) src, err := im.Load(p) if err != nil { return err } defer src.Close() seeker, err := assets.Seeker(src) if err != nil { return err } sum := hashutil.Fnv32a(seeker) nonExt := p[:len(p)-len(path.Ext(p))] dest := path.Join(prefix, nonExt+".gen."+sum+path.Ext(p)) renames[p] = dest log.Debugf("importing asset %q as %q", p, dest) if m.Has(dest) { return nil } f, err := m.Create(dest, true) if err != nil { return err } defer f.Close() if _, err := seeker.Seek(0, os.SEEK_SET); err != nil { return err } if _, err := io.Copy(f, seeker); err != nil { return err } return nil }) if err != nil { return err } included.renames = renames return nil }
// IsDuplicate returns true if the date isn't unique. func (rename *Rename) IsDuplicate(renames []*Rename) bool { var i int for _, r := range renames { if r.date == rename.date && path.Ext(r.origPath) == path.Ext(rename.origPath) { i++ } if i == 2 { return true } } return false }