github.com/pojntfx/hydrapp/hydrapp@v0.0.0-20240516002902-d08759d6ca9f/pkg/utils/writer.go (about)

     1  package utils
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/pojntfx/hydrapp/hydrapp/pkg/renderers"
     9  )
    10  
    11  func WriteRenders(workdir string, renders []renderers.Renderer, overwrite, ejecting bool) error {
    12  	for _, renderer := range renders {
    13  		if path, content, err := renderer.Render(""); err != nil {
    14  			return err
    15  		} else {
    16  			if err := os.MkdirAll(filepath.Dir(filepath.Join(workdir, path)), 0755); err != nil {
    17  				return err
    18  			}
    19  
    20  			file := filepath.Join(workdir, path)
    21  			exists := true
    22  			if _, err := os.Stat(file); err != nil {
    23  				exists = false
    24  			}
    25  
    26  			if !exists || overwrite {
    27  				if err := ioutil.WriteFile(file, []byte(content), 0664); err != nil {
    28  					return err
    29  				}
    30  			}
    31  
    32  			if exists && !ejecting {
    33  				// Read existing file and allow for templating in them
    34  				t, err := os.ReadFile(file)
    35  				if err != nil {
    36  					return err
    37  				}
    38  
    39  				if _, content, err = renderer.Render(string(t)); err != nil {
    40  					return err
    41  				}
    42  
    43  				if err := ioutil.WriteFile(file, []byte(content), 0664); err != nil {
    44  					return err
    45  				}
    46  			}
    47  		}
    48  	}
    49  
    50  	return nil
    51  }