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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//            Copyright Keysight Technologies 2012-2019
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, you can obtain one at http://mozilla.org/MPL/2.0/.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using LibGit2Sharp;
using OpenTap.Cli;
 
namespace OpenTap.Package
{
    /// <summary>
    /// CLI sub command `tap sdk gitversion` that can calculate a version number based on the git history and a .gitversion file.
    /// </summary>
    [Display("gitversion", Group: "sdk", Description: "Calculate the semantic version number for a specific git commit.")]
    public class GitVersionAction : OpenTap.Cli.ICliAction
    {
        private static readonly TraceSource log = Log.CreateSource("GitVersion");
 
        /// <summary>
        /// Represents the --gitlog command line argument which prints git log for the last n commits including version numbers for each commit.
        /// </summary>
        [CommandLineArgument("gitlog",     Description = "Print the git log for the last <arg> commits including their semantic version number.")]
        public string PrintLog { get; set; }
 
        /// <summary>
        /// Represents an unnamed command line argument which specifies for which git ref a version should be calculated.
        /// </summary>
        [UnnamedCommandLineArgument("ref", Required = false, Description = "An optional sha ref to a specific commit. If not specified, the current HEAD is used.")]
        public string Sha { get; set; }
 
        /// <summary>
        /// Represents the --replace command line argument which causes this command to replace all occurrences of $(GitVersion) in the specified file. Cannot be used together with --gitlog.
        /// </summary>
        [CommandLineArgument("replace", Description = "Replace all occurrences of $(GitVersion) in the specified file\nwith the calculated semantic version number. It cannot be used with --gitlog.")]
        public string ReplaceFile { get; set; }
 
        /// <summary>
        /// Represents the --fields command line argument which specifies the number of version fields to print/replace.
        /// </summary>
        [CommandLineArgument("fields",  Description = "Number of version fields to print/replace. The fields are: major, minor, patch,\n" +
                                                      "pre-release, and build metadata. E.g., --fields=2 results in a version number\n" +
                                                      "containing only the major and minor field. The default is 5 (all fields).")]
        public int FieldCount { get; set; }
 
        /// <summary>
        /// Represents the --dir command line argument which specifies the directory in which the git repository to use is located.
        /// </summary>
        [CommandLineArgument("dir",     Description = "Directory containing the git repository to calculate the version number from.")]
        public string RepoPath { get; set; }
 
        /// <summary>
        /// Constructs new action with default values for arguments.
        /// </summary>
        public GitVersionAction()
        {
            RepoPath = Directory.GetCurrentDirectory();
            FieldCount = 5;
        }
 
        /// <summary>
        /// Executes this action.
        /// </summary>
        /// <returns>Returns 0 to indicate success.</returns>
        public int Execute(CancellationToken cancellationToken)
        {
            if (FieldCount < 1 || FieldCount > 5)
            {
                log.Error("The argument for --fields ({0}) must be an integer between 1 and 5.", FieldCount);
                return (int)ExitCodes.ArgumentError;
            }
 
            if (!String.IsNullOrEmpty(PrintLog))
            {
                int nLines = 0;
                if (!int.TryParse(PrintLog, out nLines) || nLines <= 0)
                {
                    log.Error("The argument for --gitlog ({0}) must be an integer greater than 0.", PrintLog);
                    return (int)ExitCodes.ArgumentError;
                }
                return DoPrintLog(cancellationToken);
            }
 
            string versionString = null;
            using (GitVersionCalulator calc = new GitVersionCalulator(RepoPath))
            {
                try
                {
                    if (String.IsNullOrEmpty(Sha))
                        versionString = calc.GetVersion().ToString(FieldCount);
                    else
                        versionString = calc.GetVersion(Sha).ToString(FieldCount);
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("object not found - no match for id"))
                    {
                        throw new ExitCodeException((int) ExitCodes.GeneralException,
                            "Failed getting git version because the repository history is incomplete.\n" +
                            "Please ensure that the repository has a full version history (git fetch --unshallow).\n" +
                            "If this is occurring on a gitlab runner, ensure 'Git shallow clone' is set to 0.");
                    }
                    throw;
                }
            }
            if (!String.IsNullOrEmpty(ReplaceFile))
            {
                if (!File.Exists(ReplaceFile))
                {
                    log.Error("File '{0}' given in --replace argument could not be found.", Path.GetFullPath(ReplaceFile));
                    return (int)ExitCodes.ArgumentError;
                }
                int replaceLineCount = DoReplaceFile(ReplaceFile, versionString);
                if (replaceLineCount == 0)
                    log.Warning("Nothing to replace. '$(GitVersion)' was not found in {0}.", ReplaceFile);
                else
                    log.Info("Replaced '$(GitVersion)' with '{0}' in {1} line(s) of {2}", versionString, replaceLineCount, ReplaceFile);
                return (int)ExitCodes.Success;
            }
            log.Info(versionString);
            return (int)ExitCodes.Success;
        }
 
        private static int DoReplaceFile(string fileName, string versionString)
        {
            int replaceLineCount = 0;
            using (var input = File.OpenText(fileName))
            using (var output = new StreamWriter(fileName + ".tmp"))
            {
                string line;
                while (null != (line = input.ReadLine()))
                {
                    if (line.Contains("$(GitVersion)"))
                    {
                        replaceLineCount++;
                        line = line.Replace("$(GitVersion)", versionString);
                    }
                    if (line.Contains("$(GitLongVersion)"))
                    {
                        replaceLineCount++;
                        line = line.Replace("$(GitLongVersion)", versionString);
                    }
                    output.WriteLine(line);
                }
            }
            //File.Replace(fileName + ".tmp", fileName, fileName + ".org");
            File.Replace(fileName + ".tmp", fileName, null);
            return replaceLineCount;
        }
 
        private int DoPrintLog(CancellationToken cancellationToken)
        {
            ConsoleColor defaultColor = Console.ForegroundColor;
            ConsoleColor graphColor = ConsoleColor.DarkYellow;
            ConsoleColor versionColor = ConsoleColor.DarkRed;
 
            using (GitVersionCalulator versionCalculater = new GitVersionCalulator(RepoPath))
            using (LibGit2Sharp.Repository repo = new LibGit2Sharp.Repository(RepoPath))
            {
                Commit tip = repo.Head.Tip;
                if (!string.IsNullOrEmpty(Sha))
                {
                    tip = repo.Lookup<Commit>(Sha);
                    if(tip == null)
                    {
                        log.Error($"The commit with reference {Sha} does not exist in the repository.");
                        return (int)ExitCodes.ArgumentError;
                    }
                }
                IEnumerable<Commit> History = repo.Commits.QueryBy(new CommitFilter() { IncludeReachableFrom = tip, SortBy = CommitSortStrategies.Topological });
 
 
                // Run through to determine max Position (number of concurrent branches) to be able to indent correctly later
                int maxLines = int.Parse(PrintLog);
                int lineCount = 0;
                Dictionary<Commit, int> commitPosition = new Dictionary<Commit, int>();
                commitPosition.Add(History.First(), 0);
                int maxPosition = 0;
                foreach (Commit c in History)
                {
                    cancellationToken.ThrowIfCancellationRequested();
 
                    if (maxPosition < commitPosition[c])
                        maxPosition = commitPosition[c];
 
                    if(!c.Parents.Any())
                    {
                        // this is the very first commit in the repo. Stop here.
                        maxLines = ++lineCount;
                        break;
                    }
                    Commit p1 = c.Parents.First();
                    if (c.Parents.Count() > 1)
                    {
                        Commit p2 = c.Parents.Last();
 
                        if (commitPosition.ContainsKey(p1))
                            if (commitPosition[p1] != commitPosition[c])
                            {
                                int startPos = Math.Min(commitPosition[p1], commitPosition[c]);
                                int endPos = Math.Max(commitPosition[p1], commitPosition[c]);
 
                                commitPosition[c] = startPos;
 
                                foreach (var kvp in commitPosition.Where((KeyValuePair<Commit, int> kvp) => kvp.Value == endPos).ToList())
                                {
                                    commitPosition.Remove(kvp.Key);
                                }
                            }
 
                        if (!commitPosition.ContainsKey(p2))
                        {
                            // move out to an position out for the new branch
                            int newPosition = commitPosition[c] + 1;
                            while (commitPosition.ContainsValue(newPosition) &&
                                    (newPosition <= commitPosition.Values.Max()))
                                newPosition++;
                            commitPosition[p2] = newPosition;
 
                            commitPosition[p1] = commitPosition[c];
                        }
                        else if (!commitPosition.ContainsKey(p1))
                        {
                            commitPosition[p1] = commitPosition[c];
                        }
                    }
                    else
                    {
                        if (!commitPosition.ContainsKey(p1))
                            commitPosition[p1] = commitPosition[c];
 
                        if (commitPosition[p1] != commitPosition[c])
                        {
                            int startPos = Math.Min(commitPosition[p1], commitPosition[c]);
                            int endPos = Math.Max(commitPosition[p1], commitPosition[c]);
 
                            // c is now merged back, no need to keep track of it (or any other commit on this branch)
                            // this way we can reuse the position for another branch 
                            foreach (var kvp in commitPosition.Where((KeyValuePair<Commit, int> kvp) => kvp.Value == endPos).ToList())
                            {
                                commitPosition.Remove(kvp.Key);
                            }
                            commitPosition[p1] = startPos;
                            foreach (var kvp in commitPosition.Where((KeyValuePair<Commit, int> kvp) => kvp.Value == startPos).ToList())
                            {
                                if(kvp.Key != p1)
                                    commitPosition.Remove(kvp.Key);
                            }
                        }
                    }
                    if (++lineCount >= maxLines)
                        break;
                }
                {
                    maxPosition++;
                }
 
                {
                    // Run through again to print
                    lineCount = 0;
                    commitPosition = new Dictionary<Commit, int>();
                    commitPosition.Add(History.First(), 0);
                    HashSet<Commit> taggedCommits = repo.Tags.Select(t => t.Target.Peel<Commit>()).ToHashSet();
                    foreach (Commit c in History)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        void DrawPositionSpacer(int fromPos,int toPos)
                        {
                            for (int i = fromPos; i < toPos; i++)
                            {
                                if(commitPosition.ContainsValue(i))
                                    Console.Write("\u2502 ");
                                else
                                    Console.Write("  ");
                            }
                        }
                        void DrawMergePositionSpacer(int fromPos, int toPos)
                        {
                            for (int i = fromPos; i < toPos; i++)
                            {
                                if (commitPosition.ContainsValue(i))
                                    Console.Write("\u2502\u2500");
                                else
                                    Console.Write("\u2500\u2500");
                            }
                        }
 
                        Console.ForegroundColor = graphColor;
                        DrawPositionSpacer(0, commitPosition[c]);
                        Console.ForegroundColor = defaultColor;
                        if (taggedCommits.Contains(c))
                            Console.Write("v ");
                        else
                            Console.Write("* ");
                        Console.ForegroundColor = graphColor;
                        DrawPositionSpacer(commitPosition[c] + 1, maxPosition);
 
                        Console.ForegroundColor = versionColor;
                        Console.Write(versionCalculater.GetVersion(c).ToString(FieldCount));
                        Console.ForegroundColor = defaultColor;
 
                        Console.Write(" - ");
                        Console.Write(c.MessageShort.Trim());
 
                        if (++lineCount >= maxLines)
                        {
                            Console.WriteLine();
                            break;
                        }
 
                        if (c.Parents.Any())
                        {
                            Commit p1 = c.Parents.First();
                            //Console.Write("Parent1: " + p1.Sha.Substring(0,8));
                            Console.WriteLine();
                            Console.ForegroundColor = graphColor;
                            if (c.Parents.Count() > 1)
                            {
                                Commit p2 = c.Parents.Last();
 
                                int startPos;
                                int endPos;
 
                                if (commitPosition.ContainsKey(p1))
                                    if (commitPosition[p1] != commitPosition[c])
                                    {
                                        startPos = Math.Min(commitPosition[p1], commitPosition[c]);
                                        // something we already printed has the current commit as its parent, draw the line to that commit now
                                        DrawPositionSpacer(0, startPos);
                                        // Draw ├─┘
                                        Console.Write("\u251C\u2500");
                                        endPos = Math.Max(commitPosition[p1], commitPosition[c]);
                                        DrawMergePositionSpacer(startPos + 1, endPos);
                                        Console.Write("\u2518 ");
                                        DrawPositionSpacer(endPos + 1, maxPosition);
                                        Console.WriteLine();
                                        commitPosition[c] = startPos;
                                        foreach (var kvp in commitPosition.Where((KeyValuePair<Commit, int> kvp) => kvp.Value == endPos).ToList())
                                        {
                                            commitPosition.Remove(kvp.Key);
                                        }
                                    }
 
                                if (!commitPosition.ContainsKey(p2))
                                {
                                    DrawPositionSpacer(0, commitPosition[c]);
                                    // move out to an position out for the new branch
                                    int newPosition = commitPosition[c] + 1;
                                    while (commitPosition.ContainsValue(newPosition) &&
                                            (newPosition <= commitPosition.Values.Max()))
                                        newPosition++;
                                    commitPosition[p2] = newPosition;
 
                                    commitPosition[p1] = commitPosition[c];
                                    // Draw ├─┐
                                    Console.Write("\u251C\u2500");
                                    DrawMergePositionSpacer(commitPosition[c] + 1, commitPosition[p2]);
                                    Console.Write("\u2510 ");
                                    DrawPositionSpacer(commitPosition[p2] + 1, maxPosition);
                                    Console.WriteLine();
                                }
                                else if (!commitPosition.ContainsKey(p1))
                                {
                                    commitPosition[p1] = commitPosition[c];
                                    // this branch is merged several times
                                    startPos = Math.Min(commitPosition[p2], commitPosition[c]);
                                    DrawPositionSpacer(0, startPos);
                                    // draws something like: ├─┤
                                    Console.Write("\u251C\u2500");
                                    endPos = Math.Max(commitPosition[p2], commitPosition[c]);
                                    DrawMergePositionSpacer(startPos + 1, endPos);
                                    Console.Write("\u2524 ");
                                    DrawPositionSpacer(endPos + 1, maxPosition);
                                    Console.WriteLine();
                                }
                                //else
                                //{
                                //    DrawPositionSpacer(0, commitPosition[p2]);
                                //    Console.Write("\u251C\u2500");
                                //    DrawMergePositionSpacer(commitPosition[p2] + 1, commitPosition[c]);
                                //    Console.WriteLine("\u2524");
                                //}
                            }
                            else
                            {
                                if (!commitPosition.ContainsKey(p1))
                                    commitPosition[p1] = commitPosition[c];
 
                                if (commitPosition[p1] != commitPosition[c])
                                {
                                    int startPos = Math.Min(commitPosition[p1], commitPosition[c]);
                                    DrawPositionSpacer(0, startPos);
                                    // Draw ├─┘
                                    Console.Write("\u251C\u2500");
                                    int endPos = Math.Max(commitPosition[p1], commitPosition[c]);
                                    DrawMergePositionSpacer(startPos + 1, endPos);
                                    Console.Write("\u2518 ");
                                    DrawPositionSpacer(endPos + 1, maxPosition);
                                    Console.WriteLine();
                                    // c is now merged back, no need to keep track of it (or any other commit on this branch)
                                    // this way we can reuse the position for another branch 
                                    foreach (var kvp in commitPosition.Where((KeyValuePair<Commit, int> kvp) => kvp.Value == endPos).ToList())
                                    {
                                        commitPosition.Remove(kvp.Key);
                                    }
                                    commitPosition[p1] = startPos;
                                    foreach (var kvp in commitPosition.Where((KeyValuePair<Commit, int> kvp) => kvp.Value == startPos).ToList())
                                    {
                                        if(kvp.Key != p1)
                                            commitPosition.Remove(kvp.Key);
                                    }
 
                                }
                            }
                        }
                    }
                }
            }
            return (int)ExitCodes.Success;
        }
    }
 
    /// <summary>
    /// Defines the UseVersion XML element that can be used as a child element to the File element in package.xml 
    /// to indicate that a package should take its version from the AssemblyInfo in that file.
    /// </summary>
    [Display("UseVersion")]
    public class UseVersionData : ICustomPackageData
    {
    }
}