github.com/replicatedhq/ship@v0.55.0/pkg/templates/util.go (about)

     1  package templates
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  
     7  	"github.com/pkg/errors"
     8  	"github.com/spf13/afero"
     9  )
    10  
    11  func BuildDir(buildPath string, fs *afero.Afero, builder *Builder) error {
    12  	isDir, err := fs.IsDir(buildPath)
    13  	if err != nil {
    14  		return errors.Wrapf(err, "check if dir %s", buildPath)
    15  	}
    16  	if !isDir {
    17  		return buildFile(buildPath, fs, builder)
    18  	}
    19  
    20  	files, err := fs.ReadDir(buildPath)
    21  	if err != nil {
    22  		return errors.Wrapf(err, "read dir %s", buildPath)
    23  	}
    24  	for _, file := range files {
    25  		childPath := filepath.Join(buildPath, file.Name())
    26  		if file.IsDir() {
    27  			err = BuildDir(childPath, fs, builder)
    28  			if err != nil {
    29  				return errors.Wrapf(err, "build dir %s", childPath)
    30  			}
    31  		} else {
    32  			err = buildFile(childPath, fs, builder)
    33  			if err != nil {
    34  				return errors.Wrapf(err, "build file %s", childPath)
    35  			}
    36  		}
    37  	}
    38  
    39  	return nil
    40  }
    41  
    42  func buildFile(buildPath string, fs *afero.Afero, builder *Builder) error {
    43  	fileContents, err := fs.ReadFile(buildPath)
    44  	if err != nil {
    45  		return errors.Wrapf(err, "read file %s", buildPath)
    46  	}
    47  
    48  	newContents, err := builder.String(string(fileContents))
    49  	if err != nil {
    50  		return errors.Wrapf(err, "template file %s", buildPath)
    51  	}
    52  
    53  	err = fs.WriteFile(buildPath, []byte(newContents), os.FileMode(777))
    54  	if err != nil {
    55  		return errors.Wrapf(err, "write file %s", buildPath)
    56  	}
    57  	return nil
    58  }