git.wit.org/jcarr/packr@v1.10.8/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  		bb, err := ioutil.ReadFile(path)
    41  		if err != nil {
    42  			return errors.WithStack(err)
    43  		}
    44  		if b.compress {
    45  			bb, err = compressFile(bb)
    46  			if err != nil {
    47  				return errors.WithStack(err)
    48  			}
    49  		}
    50  		bb, err = json.Marshal(bb)
    51  		if err != nil {
    52  			return errors.WithStack(err)
    53  		}
    54  		f.Contents = strings.Replace(string(bb), "\"", "\\\"", -1)
    55  
    56  		b.Files = append(b.Files, f)
    57  		return nil
    58  	})
    59  }
    60  
    61  func compressFile(bb []byte) ([]byte, error) {
    62  	var buf bytes.Buffer
    63  	writer := gzip.NewWriter(&buf)
    64  	_, err := writer.Write(bb)
    65  	if err != nil {
    66  		return bb, errors.WithStack(err)
    67  	}
    68  	err = writer.Close()
    69  	if err != nil {
    70  		return bb, errors.WithStack(err)
    71  	}
    72  	return buf.Bytes(), nil
    73  }