github.com/jacobsoderblom/buffalo@v0.11.0/buffalo/cmd/build/archived_assets.go (about) 1 package build 2 3 import ( 4 "archive/zip" 5 "bytes" 6 "io" 7 "os" 8 "path/filepath" 9 "strings" 10 11 "github.com/pkg/errors" 12 "github.com/sirupsen/logrus" 13 ) 14 15 func (b *Builder) buildExtractedAssets() error { 16 err := b.buildAssetsArchive() 17 if err != nil { 18 return errors.WithStack(err) 19 } 20 return b.disableAssetsHandling() 21 } 22 23 func (b *Builder) disableAssetsHandling() error { 24 logrus.Debug("disable asset handling in binary") 25 26 b.transform("actions/app.go", func(body []byte, w io.Writer) error { 27 body = bytes.Replace(body, []byte("app.ServeFiles(\"/assets\""), []byte("//app.ServeFiles(\"/assets\""), 1) 28 _, err := w.Write(body) 29 if err != nil { 30 return errors.WithStack(err) 31 } 32 return nil 33 }) 34 35 return nil 36 } 37 38 func (b *Builder) buildAssetsArchive() error { 39 outputDir := filepath.Dir(filepath.Join(b.Root, b.Bin)) 40 41 target := filepath.Join(outputDir, "assets.zip") 42 source := filepath.Join(b.Root, "public", "assets") 43 44 logrus.Debugf("building assets archive to %s", target) 45 46 zipfile, err := os.Create(target) 47 if err != nil { 48 return errors.WithStack(err) 49 } 50 defer zipfile.Close() 51 52 archive := zip.NewWriter(zipfile) 53 defer archive.Close() 54 55 info, err := os.Stat(source) 56 if err != nil { 57 return errors.WithStack(err) 58 } 59 60 var baseDir string 61 if info.IsDir() { 62 baseDir = filepath.Base(source) 63 } 64 65 filepath.Walk(source, func(path string, info os.FileInfo, err error) error { 66 if err != nil { 67 return errors.WithStack(err) 68 } 69 70 header, err := zip.FileInfoHeader(info) 71 if err != nil { 72 return errors.WithStack(err) 73 } 74 75 if baseDir != "" { 76 header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source)) 77 } 78 79 if info.IsDir() { 80 header.Name += "/" 81 } else { 82 header.Method = zip.Deflate 83 } 84 85 writer, err := archive.CreateHeader(header) 86 if err != nil { 87 return errors.WithStack(err) 88 } 89 90 if info.IsDir() { 91 return nil 92 } 93 94 file, err := os.Open(path) 95 if err != nil { 96 return errors.WithStack(err) 97 } 98 defer file.Close() 99 _, err = io.Copy(writer, file) 100 return errors.WithStack(err) 101 }) 102 103 return errors.WithStack(err) 104 }