github.com/zachgersh/packr@v1.11.1/builder/box.go (about)

     1  package builder
     2  
     3  import (
     4  	"bytes"
     5  	"compress/gzip"
     6  	"encoding/json"
     7  	"io/ioutil"
     8  	"os"
     9  	"path/filepath"
    10  	"strings"
    11  
    12  	"github.com/pkg/errors"
    13  )
    14  
    15  type box struct {
    16  	Name     string
    17  	Files    []file
    18  	compress bool
    19  }
    20  
    21  func (b *box) Walk(root string) error {
    22  	root, err := filepath.EvalSymlinks(root)
    23  	if err != nil {
    24  		return errors.WithStack(err)
    25  	}
    26  	if _, err := os.Stat(root); err != nil {
    27  		// return nil
    28  		return errors.Errorf("could not find folder for box: %s", root)
    29  	}
    30  	return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
    31  		if info == nil || info.IsDir() || strings.HasSuffix(info.Name(), "-packr.go") {
    32  			return nil
    33  		}
    34  		name := strings.Replace(path, root+string(os.PathSeparator), "", 1)
    35  		name = strings.Replace(name, "\\", "/", -1)
    36  		f := file{
    37  			Name: name,
    38  		}
    39  
    40  		DebugLog("packing file %s\n", f.Name)
    41  
    42  		bb, err := ioutil.ReadFile(path)
    43  		if err != nil {
    44  			return errors.WithStack(err)
    45  		}
    46  		if b.compress {
    47  			bb, err = compressFile(bb)
    48  			if err != nil {
    49  				return errors.WithStack(err)
    50  			}
    51  		}
    52  		bb, err = json.Marshal(bb)
    53  		if err != nil {
    54  			return errors.WithStack(err)
    55  		}
    56  		f.Contents = strings.Replace(string(bb), "\"", "\\\"", -1)
    57  
    58  		DebugLog("packed file %s\n", f.Name)
    59  		b.Files = append(b.Files, f)
    60  		return nil
    61  	})
    62  }
    63  
    64  func compressFile(bb []byte) ([]byte, error) {
    65  	var buf bytes.Buffer
    66  	writer := gzip.NewWriter(&buf)
    67  	_, err := writer.Write(bb)
    68  	if err != nil {
    69  		return bb, errors.WithStack(err)
    70  	}
    71  	err = writer.Close()
    72  	if err != nil {
    73  		return bb, errors.WithStack(err)
    74  	}
    75  	return buf.Bytes(), nil
    76  }