github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/shell/variables/expand.go (about)

     1  package variables
     2  
     3  import (
     4  	"regexp"
     5  	"strings"
     6  
     7  	"github.com/lmorg/murex/lang"
     8  	"github.com/lmorg/murex/utils/home"
     9  )
    10  
    11  var (
    12  	rxVars = regexp.MustCompile(`(\$[_.a-zA-Z0-9]+)`)
    13  	rxHome = regexp.MustCompile(`(~[_\-.a-zA-Z0-9]+)`)
    14  )
    15  
    16  // ExpandString finds variables in a string and replaces it with the value of the variable
    17  func ExpandString(line string) string {
    18  	escape := string([]byte{0, 1, 2, 0})
    19  	hat := string([]byte{0, 1, 2, 1})
    20  
    21  	line = strings.ReplaceAll(line, `\$`, escape)
    22  	line = strings.ReplaceAll(line, `^$`, hat)
    23  
    24  	match := rxVars.FindAllString(line, -1)
    25  	for i := range match {
    26  		s, _ := lang.ShellProcess.Variables.GetString(match[i][1:])
    27  		line = strings.Replace(line, match[i], s, -1)
    28  	}
    29  
    30  	line = strings.ReplaceAll(line, escape, `\$`)
    31  	line = strings.ReplaceAll(line, hat, `^$`)
    32  
    33  	match = rxHome.FindAllString(line, -1)
    34  	for i := range match {
    35  		line = rxHome.ReplaceAllString(line, home.UserDir(match[i][1:]))
    36  	}
    37  
    38  	line = strings.Replace(line, "~", home.MyDir, -1)
    39  	return line
    40  }
    41  
    42  // Expand finds variables in a line and replaces it with the value of the variable
    43  func Expand(line []rune) []rune {
    44  	return []rune(ExpandString(string(line)))
    45  }