github.com/gocaveman/caveman@v0.0.0-20191211162744-0ddf99dbdf6e/renderer/includeregistry/includeregistry.go (about) 1 // The includeregistry provides registration for default includes. 2 // Generally used by templates or other things that want to provide paths you can access 3 // through a template call in a Renderer. 4 package includeregistry 5 6 import ( 7 "log" 8 "net/http" 9 10 "github.com/gocaveman/caveman/filesystem/fsutil" 11 "github.com/gocaveman/caveman/webutil" 12 ) 13 14 // OnlyReadableFromMain determines if `Contents()` can be called from packages other than main. 15 // By default we prevent this in order to enforce that object wiring is done in the main package 16 // and not from other components. The intention is to prevent hidden code dependencies from 17 // being introduced. 18 // (TODO: link to doc which explains why in more detail.) 19 var OnlyReadableFromMain = true 20 21 var reg webutil.NamedSequence 22 23 // MustRegister adds a new FileSystem to the include registry. Duplicates (seq, name or value) are not detected or prevented. 24 func MustRegister(seq float64, name string, includeFS http.FileSystem) { 25 log.Printf("includeregistry is deprecated, use tmplregistry instead") 26 reg = append(reg, webutil.NamedSequenceItem{Sequence: seq, Name: name, Value: includeFS}) 27 } 28 29 // Contents returns the current contents of the registry as a NamedSequence. 30 func Contents() webutil.NamedSequence { 31 if OnlyReadableFromMain { 32 webutil.MainOnly(1) 33 } 34 return reg.SortedCopy() 35 } 36 37 // MakeFS sorts the NamedSequence you provide and returns a FileSystem which is 38 // the combination of the Values in this list. Will panic if any value is 39 // not an http.FileSystem. If overrideFS is not nil, it will be included as the 40 // first FileSystem in the stack and will take priority over the rest. 41 // If debug is true then opened files will output debug info to the log. 42 func MakeFS(overrideFS http.FileSystem, contents webutil.NamedSequence, debug bool) http.FileSystem { 43 l := contents.SortedCopy() 44 45 fslist := make([]http.FileSystem, 0, len(l)+1) 46 if overrideFS != nil { 47 48 fs := overrideFS 49 50 if debug { 51 fs = fsutil.NewHTTPFuncFS(func(name string) (http.File, error) { 52 f, err := overrideFS.Open(name) 53 if f != nil { 54 log.Printf("Include file opened from override: %s", name) 55 } 56 return f, err 57 }) 58 } 59 60 fslist = append(fslist, fs) 61 } 62 63 for i := range l { 64 65 item := l[i] 66 67 itemFS := item.Value.(http.FileSystem) 68 fs := itemFS 69 70 if debug { 71 fs = fsutil.NewHTTPFuncFS(func(name string) (http.File, error) { 72 f, err := itemFS.Open(name) 73 if f != nil { 74 log.Printf("Include file opened (sequence=%v, name=%q): %s", item.Sequence, item.Name, name) 75 } 76 return f, err 77 }) 78 } 79 80 fslist = append(fslist, fs) 81 } 82 83 return fsutil.NewHTTPStackedFileSystem(fslist...) 84 }