Filters variables by prefix and removes the prefix from keys. Variables without the prefix are excluded. For example, with the prefix "MY_APP_" and variables: MY_APP_TOKEN=topsecret MY_APP_NAME=hello FOO=bar the resulting environment will contain: TOKEN=topsecret NAME=hello
(ctx context.Context, prefix string)
| 175 | // TOKEN=topsecret |
| 176 | // NAME=hello |
| 177 | func (ef *EnvFile) Namespace(ctx context.Context, prefix string) (*EnvFile, error) { |
| 178 | // use raw variables here given that they'll get expanded later when used |
| 179 | vars, err := ef.Variables(ctx, true) |
| 180 | if err != nil { |
| 181 | return nil, fmt.Errorf("Evaluate env file: %w", err) |
| 182 | } |
| 183 | result := &EnvFile{ |
| 184 | Expand: ef.Expand, |
| 185 | // Preserve any hidden expansion context already carried by the source. |
| 186 | Context: slices.Clone(ef.Context), |
| 187 | } |
| 188 | for _, variable := range vars { |
| 189 | if after, match := cutFlexPrefix(variable.Name, prefix); match { |
| 190 | result.add(after, variable.Value) |
| 191 | } else { |
| 192 | // Keep non-matching variables as hidden expansion context so that |
| 193 | // namespaced values referencing them (e.g. SOURCE=${ROOT_DIR}) can |
| 194 | // still be expanded later. They are not exposed as defaults. |
| 195 | result.Context = append(result.Context, variable.Name+"="+variable.Value) |
| 196 | } |
| 197 | } |
| 198 | return result, nil |
| 199 | } |
| 200 | |
| 201 | // A flexible prefix check, for maximum user convenience |
| 202 | func cutFlexPrefix(s, flexPrefix string) (after string, found bool) { |
no test coverage detected