v2 / vlib / v / util / env_value.v
50 lines · 48 sloc · 1.56 KB · 50b716b8e354f305d9672915e17b9c24a7181993
Raw
1// Copyright (c) 2025 Alexander Medvednikov. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4module util
5
6import os
7
8// resolve_env_value replaces all occurrences of `$env('ENV_VAR_NAME')`
9// in `str` with the value of the env variable `$ENV_VAR_NAME`.
10pub fn resolve_env_value(str string, check_for_presence bool) !string {
11 env_ident := "\$env('"
12 at := str.index(env_ident) or {
13 return error('no "${env_ident}' + '...\')" could be found in "${str}".')
14 }
15 mut ch := u8(`.`)
16 mut benv_lit := []u8{cap: 20}
17 for i := at + env_ident.len; i < str.len && ch != `)`; i++ {
18 ch = u8(str[i])
19 if ch.is_letter() || ch.is_digit() || ch == `_` {
20 benv_lit << ch
21 } else {
22 if !(ch == `'` || ch == `)`) {
23 if ch == `$` {
24 return error('cannot use string interpolation in compile time \$env() expression')
25 }
26 return error('invalid environment variable name in "${str}", invalid character "${rune(ch)}"')
27 }
28 }
29 }
30 env_lit := benv_lit.bytestr()
31 if env_lit == '' {
32 return error('supply an env variable name like HOME, PATH or USER')
33 }
34 mut env_value := ''
35 if check_for_presence {
36 env_value = os.environ()[env_lit] or {
37 return error('the environment variable "${env_lit}" does not exist.')
38 }
39 if env_value == '' {
40 return error('the environment variable "${env_lit}" is empty.')
41 }
42 } else {
43 env_value = os.getenv(env_lit)
44 }
45 rep := str.replace_once(env_ident + env_lit + "'" + ')', env_value)
46 if rep.contains(env_ident) {
47 return resolve_env_value(rep, check_for_presence)
48 }
49 return rep
50}
51