chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
 
namespace OpenTap.Package
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    internal class DependsOnAttribute : Attribute
    {
        public Type Dependent { get; set; }
 
        public DependsOnAttribute(Type dependent)
        {
            if (TypeData.FromType(dependent).DescendsTo(typeof(IElementExpander)) == false)
                throw new Exception($"Type '{dependent.Name}' is not an {nameof(IElementExpander)}.");
            Dependent = dependent;
        }
    }
 
    internal interface IElementExpander
    {
        /// <summary>
        /// Expand all attributes and text on the input element
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        void Expand(XElement element);
    }
 
    [DependsOn(typeof(VariableExpander))]
    [DependsOn(typeof(EnvironmentVariableExpander))]
    [DependsOn(typeof(GitVersionExpander))]
    [DependsOn(typeof(DefaultVariableExpander))]
    internal class ConditionExpander : IElementExpander
    {
        private static TraceSource log = Log.CreateSource("Condition Evaluator");
        /// <summary>
        /// Evaluate any 'Condition' attribute and remove the element if it is not satisfied
        /// Otherwise remove the condition
        /// </summary>
        /// <param name="element"></param>
        public void Expand(XElement element)
        {
            foreach (var condition in element.Attributes("Condition").ToArray())
            {
                if (EvaluateCondition(condition) && condition.Parent != null)
                    condition.Remove();
                else
                {
                    if (element.Parent != null)
                        element.Remove();
                    break;
                }
            }
        }
 
        internal string GetExpansion(string condition)
        {
            string normalize(string str)
            {
                // Trim leading and trailing space
                str = str.Trim();
 
                if (str == string.Empty) return string.Empty;
 
                // Remove one level of quotes if present
                if ((str[0] == '\'' || str[0] == '"') && str.First() == str.Last())
                    str = str.Substring(1, str.Length - 2);
                return str;
            }
 
            // Check if the condition is a literal
            var norm = normalize(condition);
 
            if (string.IsNullOrWhiteSpace(norm)) return string.Empty;
 
            if (norm.IndexOf("==", StringComparison.Ordinal) < 0 &&
                norm.IndexOf("!=", StringComparison.Ordinal) < 0)
                return norm;
 
            condition = condition.Trim();
            var parts = condition.Split(new string[] { "==", "!=" }, StringSplitOptions.None)
                .Select(p => p.Trim())
                .ToArray();
 
            var lhs = normalize(parts[0]);
            var rhs = normalize(parts[1]);
 
            var isEquals = condition.IndexOf("==", StringComparison.Ordinal) >= 0;
            var areEqual = lhs.Equals(rhs, StringComparison.Ordinal);
            return isEquals == areEqual ? "true" : string.Empty;
        }
 
        bool EvaluateCondition(XAttribute attr)
        {
            var condition = attr.Value;
            var result = GetExpansion(condition).Any();
            if (attr.Parent is IXmlLineInfo li && li.HasLineInfo())
            {
                log.Debug($@"XML Line {li.LineNumber}: Evaluated Condition=""{condition}"" to ""{result}""");
            }
            return result;
        }
    }
 
    [DependsOn(typeof(GitVersionExpander))]
    internal class VariableExpander : IElementExpander
    {
        private static TraceSource log = Log.CreateSource(nameof(VariableExpander));
        public VariableExpander(ElementExpander s)
        {
            Stack = s;
        }
 
        internal void InitVariables(IEnumerable<XElement> variablesGroup)
        {
            foreach (var propertyGroup in variablesGroup)
            {
                var desc = propertyGroup.Descendants().ToArray();
                foreach (var variable in desc)
                {
                    var k = variable.Name.LocalName;
                    // Overriding an existing key is fine here
                    // It could be intentional. E.g.
                    // <PATH>$(PATH):abc</PATH>
                    // followed by
                    // <PATH>$(PATH):def</PATH>
                    Stack.ExpandElement(variable);
                    // The variable may have been removed from the document if its condition was 'false'
                    // In this case, do not add its value as a property.
                    if (variable.Parent != null)
                        Variables[k] = variable.Value;
                }
            }
 
            log.Debug($"Initialized variable expander:");
            foreach (var kvp in Variables)
            {
                log.Debug($"{kvp.Key} = '{kvp.Value}'");
            }
        }
 
        private Dictionary<string, string> Variables { get; } = new Dictionary<string, string>();
        public ElementExpander Stack { get; set; }
        public void Expand(XElement element)
        {
            foreach (var key in Variables.Keys)
            {
                ExpansionHelper.ReplaceToken(element, key, Variables[key].ToString());
            }
        }
    }
 
    [DependsOn(typeof(GitVersionExpander))]
    [DependsOn(typeof(VariableExpander))]
    internal class EnvironmentVariableExpander : IElementExpander
    {
        public EnvironmentVariableExpander()
        {
            Variables = Environment.GetEnvironmentVariables();
            Keys = Variables.Keys.OfType<string>().ToArray();
        }
 
        private IDictionary Variables { get; }
        private string[] Keys { get; }
 
        public void Expand(XElement element)
        {
            foreach (var key in Keys)
            {
                ExpansionHelper.ReplaceToken(element, key, Variables[key].ToString());
            }
        }
    }
 
    [DependsOn(typeof(GitVersionExpander))]
    [DependsOn(typeof(VariableExpander))]
    [DependsOn(typeof(EnvironmentVariableExpander))]
    internal class DefaultVariableExpander : IElementExpander
    {
        private static Regex VariableRegex = new Regex("\\$!?\\(.*?\\)");
        public HashSet<string> UndefinedVariables = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
 
        /// <summary>
        /// Replace all variables with an empty string. E.g. '$(whatever) -> '')'
        /// </summary>
        /// <param name="element"></param>
        public void Expand(XElement element)
        {
            var textNodes = element.Nodes().OfType<XText>().ToArray();
 
            foreach (var textNode in textNodes)
            {
                foreach (Match match in VariableRegex.Matches(textNode.Value))
                {
                    if (match.Value.StartsWith("$!("))
                        UndefinedVariables.Add(match.Value.Substring(3, match.Value.Length - 4));
                    textNode.Value = textNode.Value.Replace(match.Value, "");
                }
            }
 
            var attributeNodes = element.Attributes().ToArray();
            foreach (var attribute in attributeNodes)
            {
                foreach (Match match in VariableRegex.Matches(attribute.Value))
                {
                    if (match.Value.StartsWith("$!("))
                        UndefinedVariables.Add(match.Value.Substring(3, match.Value.Length - 4));
                    attribute.Value = attribute.Value.Replace(match.Value, "");
                }
            } 
        }
    }
 
    internal class GitVersionExpander : IElementExpander
    {
        public GitVersionExpander(string projectDir)
        {
            ProjectDir = projectDir;
        }
 
        private string ProjectDir { get; }
 
        private string longVersion = null;
 
        private string version = null;
 
        private static TraceSource log = Log.CreateSource(nameof(GitVersionExpander));
 
        public void Expand(XElement element)
        {
            ReplaceVersion("GitVersion", 5, ref version);
            ReplaceVersion("GitLongVersion", 4, ref longVersion);
 
            void ReplaceVersion(string versionName, int fieldCount, ref string cachedVersion)
            {
                if (!element.ToString().Contains("$(" + versionName + ")"))
                    return;
 
                if (cachedVersion == null && string.IsNullOrWhiteSpace(ProjectDir) == false)
                {
                    try
                    {
                        var calc = new GitVersionCalulator(ProjectDir);
                        cachedVersion = calc.GetVersion().ToString(fieldCount);
                        log.Info("Package {1} is {0}", cachedVersion, versionName);
                    }
                    catch (Exception ex)
                    {
                        log.ErrorOnce(cachedVersion, "Failed to calculate {0}.", versionName);
                        log.Debug(ex);
                    }
                }
 
                // If 'GitVersion' could not be resolved, don't replace it
                if (cachedVersion != null)
                    ExpansionHelper.ReplaceToken(element, versionName, cachedVersion);
            }
        }
    }
}