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
266
267
268
269
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Microsoft.Build.Framework;
using Task = Microsoft.Build.Utilities.Task;
 
namespace Keysight.OpenTap.Sdk.MSBuild
{
    /// <summary>
    /// MSBuild Task to version the build output using gitversion.
    /// </summary>
    [Serializable]
    public class CalculateVersion : Task, ICancelableTask
    {
        private const string TargetName = "OpenTapSetAssemblyVersion";
        /// <summary>
        /// The build directory containing 'tap.exe' and 'OpenTAP.dll'
        /// </summary>
        public string TapDir { get; set; }
 
        /// <summary>
        /// csproj file. This is needed because OpenTAP supports multiple gitversion files.
        /// Gitversion should be resolved from the directory containing the project file.
        /// </summary>
        public string SourceFile { get; set; }
 
        /// <summary>
        /// Optional input version. This is useful in CI pipelines where shallow clones
        /// are used for performance reasons.
        /// </summary>
        public string InputVersion { get; set; }
        
        /// <summary>
        /// The output shortversion (x.y.z).
        /// </summary>
        [Microsoft.Build.Framework.Output]
        public string OutputShortVersion { get; set; }
 
        /// <summary>
        /// The output gitversion plus informational version (x.y.z-beta.1+hash).
        /// </summary>
        [Microsoft.Build.Framework.Output]
        public string OutputLongVersion { get; set; }
 
        private bool tryParseXElement(string text, out XElement elem)
        {
            try
            {
                elem = XElement.Parse(text, LoadOptions.None);
                return true;
            }
            catch
            {
                elem = null;
                return false;
            }
        }
 
        private bool runProcess(string filename, string arguments, string workingDirectory, out string stdout,
            out string stderr)
        {
            var si = new ProcessStartInfo(filename, arguments)
            {
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                WorkingDirectory = workingDirectory,
            };
            var errStream = new StringBuilder();
            var outStream = new StringBuilder();
            var proc = new Process();
            proc.StartInfo = si;
            proc.OutputDataReceived += (_, data) =>
            {
                if (!string.IsNullOrWhiteSpace(data?.Data)) outStream.Append(data.Data);
            };
            proc.ErrorDataReceived += (_, data) =>
            {
                if (!string.IsNullOrWhiteSpace(data?.Data)) errStream.Append(data.Data);
            };
            proc.Start();
            proc.BeginOutputReadLine();
            proc.BeginErrorReadLine();
            proc.WaitForExit(10000); 
 
            if (!proc.HasExited)
            {
                stdout = stderr = null;
                Log.LogError($"{TargetName}: tap sdk gitversion is hanging.");
                return false;
            }
            stdout = outStream.ToString();
            stderr = errStream.ToString();
 
            return proc.ExitCode == 0;
        }
 
        private bool isWindows()
        {
            switch (Environment.OSVersion.Platform)
            {
                case PlatformID.Win32NT:
                case PlatformID.Win32S:
                case PlatformID.Win32Windows:
                case PlatformID.WinCE:
                    return true;
                default:
                    return false;
            }
        }
 
        // Check if a file with the given name exists in any ancestor directory
        private bool fileIsAncestor(string name, DirectoryInfo root)
        {
            var comparer = isWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
            while (root != null)
            {
                if (root.EnumerateFileSystemInfos().Any(i => i.Name.Equals(name, comparer)))
                    return true;
                root = root.Parent;
            }
 
            return false;
        }
 
        // This does not need to be perfect.
        private static Regex versionRegex = new Regex(@"^\d+\.\d+\.\d+", RegexOptions.Compiled); 
        private bool tryParseVersion(string inputVersion, out string shortVersion, out string longVersion)
        {
            inputVersion = inputVersion.Trim();
            var m = versionRegex.Match(inputVersion);
            if (m.Success)
            {
                shortVersion = m.Value;
                longVersion = inputVersion;
                return true;
            }
 
            shortVersion = longVersion = null;
            return false;
        }
 
        private bool tryCalculateGitversion(out string shortVersion, out string gitversion)
        {
            shortVersion = null;
            gitversion = null;
 
            var workingDirectory = Path.GetDirectoryName(SourceFile);
            var dirInfo = new DirectoryInfo(workingDirectory);
 
            // Ensure this is a git repository
            if (!fileIsAncestor(".git", dirInfo))
            {
                Log.LogError(
                    $"{TargetName}: The project file '{SourceFile}' is not in a git directory. {TargetName} is only supported in git projects.");
                return false;
            }
 
            // And that it uses gitversioning
            if (!fileIsAncestor(".gitversion", dirInfo))
            {
                Log.LogError(
                    $"{TargetName}: This project does not have a .gitversion file. {TargetName} is only supported in gitversion projects.\n" +
                    $"See https://doc.opentap.io/Developer%20Guide/Plugin%20Packaging%20and%20Versioning/Readme.html#git-assisted-versioning");
                return false;
            }
 
            // Start a subprocess to get the gitversion. There are a couple of reasons we don't calculate it in-process:
            // 1. libgit uses a native dll which is annoying to load. OpenTAP already includes logic for this which
            // makes several assumptions that do not apply during dotnet build.
            // 2. GitVersionCalculator is internal, and I would prefer to not make it public.
            // For these reasons, it is much simpler to just start a process and parse the output.
            string tapName = isWindows() ? "tap.exe" : "tap";
            var tap = Path.Combine(TapDir, tapName);
            if (!runProcess(tap, "sdk gitversion", workingDirectory, out var stdout, out var stderr))
            {
                return false;
            }
 
            if (!string.IsNullOrWhiteSpace(stderr))
            {
                // This could indicate a problem, but logging it as an error would fail the build.
                // Log it as a warning instead so the user is at least aware
                Log.LogWarning(stderr);
            }
 
            // There could potentially be multiple lines in the output due diagnostics or warnings from OpenTAP.
            // Find the line that looks like a gitversion
            var lines = stdout.Split('\n').Select(line => line.Trim()).ToArray();
 
            foreach (var l in lines)
            {
                if (tryParseVersion(l, out shortVersion, out gitversion))
                    return true;
            }
 
            Log.LogError($"{TargetName}: Unable to parse gitversion from output:\n{stdout}");
 
            return false;
        } 
 
        public override bool Execute()
        {
            string shortVersion;
            string longVersion;
            string input;
 
            // parse input gitversion. It can have a couple of different formats:
            // 1. A flag, such as '1' or 'true'
            // 2. A semantic version
            // 3. An xml tag enclosing a value, such as <GitVersion>1.2.3</GitVersion>
 
            // Case 1: calculate the version
            if (new[] { "true", "1" , "gitversion", "auto", "git" }.Contains(InputVersion.Trim(), StringComparer.OrdinalIgnoreCase))
            {
                if (tryCalculateGitversion(out shortVersion, out longVersion))
                {
                    OutputShortVersion = shortVersion;
                    OutputLongVersion = longVersion;
                    return true;
                }
 
                return false;
            }
 
            // Case 2/3: parse the provided version from the input
            if (!tryParseXElement($"<{TargetName}>{InputVersion.Trim()}</{TargetName}>", out var elem))
            {
                // This should not be possible since the input is exactly the inner text of the .csproj property element.
                // If the input is not valid xml, then the compilation should have already failed.
                Log.LogError($"{TargetName}: Failed to parse input.");
                return false;
            }
            
            if (elem.Element("Version") is XElement gv)
            {
                input = gv.Value.Trim();
            }
            else if (tryParseVersion(elem.Value.Trim(), out _, out _))
            {
                input = elem.Value.Trim();
            }
            else
            { 
                Log.LogError($"{TargetName}: Expected element named 'Version'.");
                return false;
            }
 
            if (!tryParseVersion(input, out shortVersion, out longVersion))
            {
                Log.LogError($"{TargetName}: Provided version is not a valid semantic version: '{input}'"); 
                return false;
            }
            
            OutputShortVersion = shortVersion;
            OutputLongVersion = longVersion;
            return true; 
        }
 
        public void Cancel()
        {
            // No cancel logic needed
        }
    }
}