summaryrefslogtreecommitdiff
path: root/src/marlin.core/util/VariableExpander.cs
blob: 3c3636e163b8805c64292c3044fc78b791dc8e20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
namespace marlin.core.util;

using System.Text;
using System.Text.RegularExpressions;

public class VariableExpander
{
    public static string Expand(string format, Dictionary<string, string> variables)
    {
        StringBuilder output = new();

        for (int i = 0; i < format.Length; i++)
        {
            char c = format[i];
            if (c == '{')
            {
                if (i + 1 >= format.Length)
                    throw new UnmatchedBraceException("Trailing expression '{'", i, format[i..]);

                if (format[i + 1] == '{')
                {
                    output.Append('{');
                    i++;
                }
                else
                {
                    string expr = GetExpression(format, ref i);
                    string value = EvaluateExpression(expr, variables);
                    output.Append(value);
                }
            }
            else if (c == '}')
            {
                if (i + 1 >= format.Length)
                    throw new UnmatchedBraceException("Uninitiated expression at '}'", i, format[i..]);

                if (format[i + 1] == '}')
                {
                    output.Append('}');
                    i++;
                }
                else
                {
                    throw new UnmatchedBraceException("Uninitiated expression at '}'", i, format[i..]);
                }
            }
            else
                output.Append(c);
        }

        string result = output.ToString();

        // Clean up extra spaces: collapse multiple consecutive spaces (but preserve other whitespace)
        result = Regex.Replace(result, @" {2,}", " ");
        result = result.Trim();

        return result;
    }

    private static string GetExpression(string format, ref int pos)
    {
        StringBuilder part = new();

        if (format[pos] != '{')
            throw new InvalidExpressionException(format[pos..], "Expected '{' at start of expression");

        pos++;

        for (; pos < format.Length; pos++)
        {
            if (format[pos] == '}')
                break;

            part.Append(format[pos]);
        }

        if (pos >= format.Length || format[pos] != '}')
            throw new UnmatchedBraceException($"Trailing expression {format[pos..]}", pos, format[pos..]);

        return part.ToString();
    }

    private static string EvaluateExpression(string expr, Dictionary<string, string> variables)
    {
        Match match;

        const string identifier = "[a-zA-Z0-9-_.]+"; 
        
        // Variable value
        match = Regex.Match(expr, $"^{identifier}$");
        if (match.Success)
            return GetVariableOrThrow(expr, variables);
        
        // Conditional argument: only included if variable is set.
        // --hello var
        match = Regex.Match(expr, $"^(--?{identifier})\\s+({identifier})$");
        if (match.Success)
        {
            if (variables.TryGetValue(match.Groups[2].Value, out var value))
                return $"{match.Groups[1].Value} {value}";

            else
                return "";
        }
        
        // Default value, if value is unset, uses default
        match = Regex.Match(expr, $@"^({identifier})\s*=\s*(.*)$");
        if (match.Success)
        {
            if (variables.TryGetValue(match.Groups[1].Value, out var value))
                return value;
            else
                return match.Groups[2].Value;
        }

        // Use value if set
        match = Regex.Match(expr, $@"^({identifier})\?\s*(.*)$");
        if (match.Success)
        {
            if (variables.TryGetValue(match.Groups[1].Value, out var value))
            {
                if (string.IsNullOrEmpty(value) || value == "null" || value == "false")
                    return "";

                return match.Groups[2].Value;
            }
            else
                return "";
        }

        throw new InvalidExpressionException(expr);
    }

    private static string GetVariableOrThrow(string variable, Dictionary<string, string> variables)
    {
        return variables.TryGetValue(variable, out var value)
            ? value
            : throw new VariableNotFoundException(variable);
    }
}