templates.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2020 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package templates
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "path"
  11. "strings"
  12. "gopkg.in/macaron.v1"
  13. "gogs.io/gogs/internal/osutil"
  14. )
  15. //go:generate go-bindata -nomemcopy -ignore="\\.DS_Store" -pkg=templates -prefix=../../../templates -debug=false -o=templates_gen.go ../../../templates/...
  16. // fileSystem implements the macaron.TemplateFileSystem interface.
  17. type fileSystem struct {
  18. files []macaron.TemplateFile
  19. }
  20. func (fs *fileSystem) ListFiles() []macaron.TemplateFile {
  21. return fs.files
  22. }
  23. func (fs *fileSystem) Get(name string) (io.Reader, error) {
  24. for i := range fs.files {
  25. if fs.files[i].Name()+fs.files[i].Ext() == name {
  26. return bytes.NewReader(fs.files[i].Data()), nil
  27. }
  28. }
  29. return nil, fmt.Errorf("file %q not found", name)
  30. }
  31. // NewTemplateFileSystem returns a macaron.TemplateFileSystem instance for embedded assets.
  32. // The argument "dir" can be used to serve subset of embedded assets. Template file
  33. // found under the "customDir" on disk has higher precedence over embedded assets.
  34. func NewTemplateFileSystem(dir, customDir string) macaron.TemplateFileSystem {
  35. if dir != "" && !strings.HasSuffix(dir, "/") {
  36. dir += "/"
  37. }
  38. var files []macaron.TemplateFile
  39. names := AssetNames()
  40. for _, name := range names {
  41. if !strings.HasPrefix(name, dir) {
  42. continue
  43. }
  44. // Check if corresponding custom file exists
  45. var err error
  46. var data []byte
  47. fpath := path.Join(customDir, name)
  48. if osutil.IsFile(fpath) {
  49. data, err = ioutil.ReadFile(fpath)
  50. } else {
  51. data, err = Asset(name)
  52. }
  53. if err != nil {
  54. panic(err)
  55. }
  56. name = strings.TrimPrefix(name, dir)
  57. ext := path.Ext(name)
  58. name = strings.TrimSuffix(name, ext)
  59. files = append(files, macaron.NewTplFile(name, data, ext))
  60. }
  61. return &fileSystem{files: files}
  62. }