github.com/drud/ddev@v1.21.5-alpha1.0.20230226034409-94fcc4b94453/pkg/ddevapp/envfile.go (about)

     1  package ddevapp
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/drud/ddev/pkg/fileutil"
     6  	"github.com/joho/godotenv"
     7  	"regexp"
     8  	"strings"
     9  )
    10  
    11  // ReadProjectEnvFile reads the .env in the project root into a envText and envMap
    12  // The map has the envFile content, but without comments
    13  func ReadProjectEnvFile(envFilePath string) (envMap map[string]string, envText string, err error) {
    14  	// envFilePath := filepath.Join(app.AppRoot, ".env")
    15  	envText, _ = fileutil.ReadFileIntoString(envFilePath)
    16  	envMap, err = godotenv.Read(envFilePath)
    17  
    18  	return envMap, envText, err
    19  }
    20  
    21  // WriteProjectEnvFile writes the passed envText into the project-root .env file
    22  // with all items in envMap changed in envText there
    23  func WriteProjectEnvFile(envFilePath string, envMap map[string]string, envText string) error {
    24  	// envFilePath := filepath.Join(app.AppRoot, ".env")
    25  	for k, v := range envMap {
    26  		// If the item is already in envText, use regex to replace it
    27  		// otherwise, append it to the envText.
    28  		exp := regexp.MustCompile(fmt.Sprintf(`((^|[\r\n]+)%s)=(.*)`, k))
    29  		if exp.MatchString(envText) {
    30  			envText = exp.ReplaceAllString(envText, fmt.Sprintf(`$1="%s"`, v))
    31  		} else {
    32  			envText = strings.TrimSuffix(envText, "\n")
    33  			envText = fmt.Sprintf("%s\n%s=%s\n", envText, k, v)
    34  		}
    35  	}
    36  	err := fileutil.TemplateStringToFile(envText, nil, envFilePath)
    37  	if err != nil {
    38  		return err
    39  	}
    40  	return nil
    41  }