exportify formats vars as a line-separated string of shell export statements. Each line is of the form `export key="value";` with any special characters in value escaped. This means that the shell will always interpret values as literal strings; no variable expansion or command substitution will tak
(w io.Writer, vars map[string]string)
| 57 | // literal strings; no variable expansion or command substitution will take |
| 58 | // place. |
| 59 | func exportify(w io.Writer, vars map[string]string) string { |
| 60 | keys := make([]string, len(vars)) |
| 61 | i := 0 |
| 62 | for k := range vars { |
| 63 | keys[i] = k |
| 64 | i++ |
| 65 | } |
| 66 | slices.Sort(keys) // for reproducibility |
| 67 | |
| 68 | var invalidNames []string |
| 69 | strb := strings.Builder{} |
| 70 | for _, key := range keys { |
| 71 | if strings.HasPrefix(key, "BASH_FUNC_") && strings.HasSuffix(key, "%%") { |
| 72 | // Bash function |
| 73 | funcName := strings.TrimSuffix(key, "%%") |
| 74 | funcName = strings.TrimPrefix(funcName, "BASH_FUNC_") |
| 75 | strb.WriteString(funcName) |
| 76 | strb.WriteString(" ") |
| 77 | strb.WriteString(vars[key]) |
| 78 | strb.WriteString("\nexport -f ") |
| 79 | strb.WriteString(funcName) |
| 80 | strb.WriteString("\n") |
| 81 | } else { |
| 82 | // Regular variable. Skip names that aren't valid shell |
| 83 | // identifiers; exporting them would produce invalid syntax that |
| 84 | // breaks the whole shell (e.g. `export //=...`). |
| 85 | if !isValidEnvName(key) { |
| 86 | invalidNames = append(invalidNames, key) |
| 87 | continue |
| 88 | } |
| 89 | strb.WriteString("export ") |
| 90 | strb.WriteString(key) |
| 91 | strb.WriteString(`="`) |
| 92 | for _, r := range vars[key] { |
| 93 | switch r { |
| 94 | // Special characters inside double quotes: |
| 95 | // https://pubs.opengroup.org/onlinepubs/009604499/utilities/xcu_chap02.html#tag_02_02_03 |
| 96 | case '$', '`', '"', '\\', '\n': |
| 97 | strb.WriteRune('\\') |
| 98 | } |
| 99 | strb.WriteRune(r) |
| 100 | } |
| 101 | strb.WriteString("\";\n") |
| 102 | } |
| 103 | } |
| 104 | warnInvalidEnvNames(w, invalidNames) |
| 105 | return strings.TrimSpace(strb.String()) |
| 106 | } |
| 107 | |
| 108 | // exportifyNushell formats vars as nushell environment variable assignments. |
| 109 | // Each line is of the form `$env.KEY = "value"` with special characters escaped. |