loader.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. // Copyright 2016 José Santos <henrique_1609@me.com>
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package jet
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "os"
  21. "path"
  22. "path/filepath"
  23. "sync"
  24. )
  25. // Loader is a minimal interface required for loading templates.
  26. //
  27. // Jet will build an absolute path (with slash delimiters) before looking up templates by resolving paths in extends/import/include statements:
  28. //
  29. // - `{{ extends "/bar.jet" }}` will make Jet look up `/bar.jet` in the Loader unchanged, no matter where it occurs (since it's an absolute path)
  30. // - `{{ include("\views\bar.jet") }}` will make Jet look up `/views/bar.jet` in the Loader, no matter where it occurs
  31. // - `{{ import "bar.jet" }}` in `/views/foo.jet` will result in a lookup of `/views/bar.jet`
  32. // - `{{ extends "./bar.jet" }}` in `/views/foo.jet` will result in a lookup of `/views/bar.jet`
  33. // - `{{ import "../views\bar.jet" }}` in `/views/foo.jet` will result in a lookup of `/views/bar.jet`
  34. // - `{{ include("../bar.jet") }}` in `/views/foo.jet` will result in a lookup of `/bar.jet`
  35. // - `{{ import "../views/../bar.jet" }}` in `/views/foo.jet` will result in a lookup of `/bar.jet`
  36. //
  37. // This means that the same template will always be looked up using the same path.
  38. //
  39. // Jet will also try appending multiple file endings for convenience: `{{ extends "/bar" }}` will lookup `/bar`, `/bar.jet`,
  40. // `/bar.html.jet` and `/bar.jet.html` (in that order). To avoid unneccessary lookups, use the full file name in your templates (so the first lookup
  41. // is always a hit, or override this list of extensions using Set.SetExtensions().
  42. type Loader interface {
  43. // Exists returns whether or not a template exists under the requested path.
  44. Exists(templatePath string) bool
  45. // Open returns the template's contents or an error if something went wrong.
  46. // Calls to Open() will always be preceded by a call to Exists() with the same `templatePath`.
  47. // It is the caller's duty to close the template.
  48. Open(templatePath string) (io.ReadCloser, error)
  49. }
  50. // OSFileSystemLoader implements Loader interface using OS file system (os.File).
  51. type OSFileSystemLoader struct {
  52. dir string
  53. }
  54. // compile time check that we implement Loader
  55. var _ Loader = (*OSFileSystemLoader)(nil)
  56. // NewOSFileSystemLoader returns an initialized OSFileSystemLoader.
  57. func NewOSFileSystemLoader(dirPath string) *OSFileSystemLoader {
  58. return &OSFileSystemLoader{
  59. dir: filepath.FromSlash(dirPath),
  60. }
  61. }
  62. // Exists returns true if a file is found under the template path after converting it to a file path
  63. // using the OS's path seperator and joining it with the loader's directory path.
  64. func (l *OSFileSystemLoader) Exists(templatePath string) bool {
  65. templatePath = filepath.Join(l.dir, filepath.FromSlash(templatePath))
  66. stat, err := os.Stat(templatePath)
  67. if err == nil && !stat.IsDir() {
  68. return true
  69. }
  70. return false
  71. }
  72. // Open returns the result of `os.Open()` on the file located using the same logic as Exists().
  73. func (l *OSFileSystemLoader) Open(templatePath string) (io.ReadCloser, error) {
  74. return os.Open(filepath.Join(l.dir, filepath.FromSlash(templatePath)))
  75. }
  76. // InMemLoader is a simple in-memory loader storing template contents in a simple map.
  77. // InMemLoader normalizes paths passed to its methods by converting any input path to a slash-delimited path,
  78. // turning it into an absolute path by prepending a "/" if neccessary, and cleaning it (see path.Clean()).
  79. // It is safe for concurrent use.
  80. type InMemLoader struct {
  81. lock sync.RWMutex
  82. files map[string][]byte
  83. }
  84. // compile time check that we implement Loader
  85. var _ Loader = (*InMemLoader)(nil)
  86. // NewInMemLoader return a new InMemLoader.
  87. func NewInMemLoader() *InMemLoader {
  88. return &InMemLoader{
  89. files: map[string][]byte{},
  90. }
  91. }
  92. func (l *InMemLoader) normalize(templatePath string) string {
  93. templatePath = filepath.ToSlash(templatePath)
  94. return path.Join("/", templatePath)
  95. }
  96. // Open returns a template's contents, or an error if no template was added under this path using Set().
  97. func (l *InMemLoader) Open(templatePath string) (io.ReadCloser, error) {
  98. templatePath = l.normalize(templatePath)
  99. l.lock.RLock()
  100. defer l.lock.RUnlock()
  101. f, ok := l.files[templatePath]
  102. if !ok {
  103. return nil, fmt.Errorf("%s does not exist", templatePath)
  104. }
  105. return ioutil.NopCloser(bytes.NewReader(f)), nil
  106. }
  107. // Exists returns whether or not a template is indexed under this path.
  108. func (l *InMemLoader) Exists(templatePath string) bool {
  109. templatePath = l.normalize(templatePath)
  110. l.lock.RLock()
  111. defer l.lock.RUnlock()
  112. _, ok := l.files[templatePath]
  113. return ok
  114. }
  115. // Set adds a template to the loader.
  116. func (l *InMemLoader) Set(templatePath, contents string) {
  117. templatePath = l.normalize(templatePath)
  118. l.lock.Lock()
  119. defer l.lock.Unlock()
  120. l.files[templatePath] = []byte(contents)
  121. }
  122. // Delete removes whatever contents are stored under the given path.
  123. func (l *InMemLoader) Delete(templatePath string) {
  124. templatePath = l.normalize(templatePath)
  125. l.lock.Lock()
  126. defer l.lock.Unlock()
  127. delete(l.files, templatePath)
  128. }