This repository was archived by the owner on Mar 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathStat.cs
More file actions
579 lines (533 loc) · 25.7 KB
/
Stat.cs
File metadata and controls
579 lines (533 loc) · 25.7 KB
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
/*! \file
Copyright (C) 2016-2018 Verizon. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;
namespace AcUtils
{
/*! \ingroup acenum */
/// <summary>
/// Indicates the element's type. By default, AccuRev determines
/// the element type for a newly created version automatically.
/// </summary>
/*! \accunote_ A defect exists where the XML \e elem_type attribute value
can be the string \"<b>* unknown *</b>\". */
/*! \accunote_ (\e external)(\e elink) elements are grayed out in the Mac GUI and cannot be
added to the depot. Defect 1101826. */
/*! \sa [acxType extension method](@ref AcUtils#Extensions#acxType) */
public enum ElementType {
/*! \var unknown
Should not occur normally except for noted defect. */
unknown = 0,
/*! \var dir
1: The element is a folder. */
dir = 1,
/*! \var text
2: The element is a text file. */
text = 2,
/*! \var binary
3: The element is a binary file. */
binary = 3,
/*! \var ptext
4: Text files that are handled the same as binary files with no end-of-line manipulation. */
ptext = 4,
/*! \var elink
5: An element-link. */
elink = 5,
/*! \var slink
6: A symbolic-link. */
slink = 6,
/*! \var unsupported
99: An unsupported type. */
unsupported = 99
};
/// <summary>
/// Defines the attributes of an element from the \c stat command.
/// </summary>
[Serializable]
[DebuggerDisplay("{EID} {Location} {Status} {NamedVersion}")]
public sealed class Element : IFormattable, IEquatable<Element>, IComparable<Element>, IComparable
{
#region class variables
private string _location;
private bool _folder;
private bool _executable;
private int _eid;
private ElementType _elementType;
private long? _size;
private DateTime? _modTime;
private string _hierType;
private int _virStreamNumber;
private int _virVersionNumber;
private string _namedVersion; // named stream\version number format, e.g. MARS_STAGE\7 or MARS_STAGE_barnyrd\24
private int _realStreamNumber;
private int _realVersionNumber;
private string _lapStream;
// AccuRev tech support, overlapInWs "was put in place for a feature that was started
// and then shelved and may be removed in a future release. Currently it is always true."
// private bool _overlapInWs;
private string _timeBasedStream;
private string _status;
#endregion
#region Equality comparison
/*! \name Equality comparison */
/**@{*/
/// <summary>IEquatable implementation to determine the equality of instances of type Element.</summary>
/// <remarks>Uses the element's EID, virtual stream/version numbers, real stream/version numbers,
/// and named version to compare instances.</remarks>
/// <param name="other">The Element object being compared to \e this instance.</param>
/// <returns>\e true if Element \e other is the same, \e false otherwise.</returns>
public bool Equals(Element other)
{
if (ReferenceEquals(other, null)) return false;
if (ReferenceEquals(this, other)) return true;
var left = Tuple.Create(EID, VirStreamNumber, VirVersionNumber, RealStreamNumber, RealVersionNumber, NamedVersion);
var right = Tuple.Create(other.EID, other.VirStreamNumber, other.VirVersionNumber,
other.RealStreamNumber, other.RealVersionNumber, other.NamedVersion);
return left.Equals(right);
}
/// <summary>
/// Overridden to determine equality.
/// </summary>
/// <returns>Return value of generic [Equals(Element)](@ref AcUtils#Element#Equals) version.</returns>
public override bool Equals(object other)
{
if (ReferenceEquals(other, null)) return false;
if (ReferenceEquals(this, other)) return true;
if (GetType() != other.GetType()) return false;
return Equals(other as Element);
}
/// <summary>
/// Override appropriate for type Element.
/// </summary>
/// <returns>Hash of element's EID, virtual stream/version numbers, real stream/version numbers,
/// and named version.</returns>
public override int GetHashCode()
{
var hash = Tuple.Create(EID, VirStreamNumber, VirVersionNumber, RealStreamNumber, RealVersionNumber, NamedVersion);
return hash.GetHashCode();
}
/**@}*/
#endregion
#region Order comparison
/*! \name Order comparison */
/**@{*/
/// <summary>
/// Generic IComparable implementation (default) for comparing Element objects
/// to sort by [element location](@ref AcUtils#Element#Location).
/// </summary>
/// <param name="other">An Element object to compare with this instance.</param>
/// <returns>Value indicating the relative order of the Element objects based on location.</returns>
public int CompareTo(Element other)
{
int result;
if (Element.ReferenceEquals(this, other))
result = 0;
else
result = Location.CompareTo(other.Location);
return result;
}
/// <summary>
/// Pre-generic interface implementation for code using reflection.
/// </summary>
/// <param name="other">An Element object to compare with this instance.</param>
/// <returns>Return value of generic [CompareTo(Element)](@ref AcUtils#Element#CompareTo) version.</returns>
/// <exception cref="ArgumentException">thrown if argument is not an Element object.</exception>
int IComparable.CompareTo(object other)
{
if (!(other is Element))
throw new ArgumentException("Argument is not an Element", "other");
Element o = (Element)other;
return this.CompareTo(o);
}
/**@}*/
#endregion
/// <summary>
/// Depot-relative path of the element.
/// </summary>
public string Location
{
get { return _location ?? String.Empty; }
internal set { _location = value; }
}
/// <summary>
/// \e true if the element is a folder, \e false otherwise.
/// </summary>
public bool Folder
{
get { return _folder; }
internal set { _folder = value; }
}
/// <summary>
/// UNIX/Linux systems only: \e true if the executable bit is set, \e false if cleared.
/// </summary>
/*! \sa [AccuRev chmode command](https://www.microfocus.com/documentation/accurev/72/WebHelp/wwhelp/wwhimpl/js/html/wwhelp.htm#href=AccuRev_User_CLI/cli_ref_chmod.html) */
public bool Executable
{
get { return _executable; }
internal set { _executable = value; }
}
/// <summary>
/// The element ID.
/// </summary>
public int EID
{
get { return _eid; }
internal set { _eid = value; }
}
/// <summary>
/// The element's type: \e dir, \e text, \e binary, \e ptext, \e elink, or \e slink.
/// </summary>
public ElementType ElementType
{
get { return _elementType; }
internal set { _elementType = value; }
}
/// <summary>
/// File size in bytes.
/// </summary>
/*! \sa [Convert file size bytes to megabyte/gigabyte string using C#](http://www.joe-stevens.com/2009/10/21/convert-file-size-bytes-to-megabytegigabyte-string-using-c/) */
public long? Size
{
get { return _size; }
internal set { _size = value; }
}
/// <summary>
/// The element's modification time.
/// </summary>
public DateTime? ModTime
{
get { return _modTime; }
internal set { _modTime = value; }
}
/// <summary>
/// "Hierarchy type" of the element: \e parallel or \e serial.
/// </summary>
public string HierType
{
get { return _hierType ?? String.Empty; }
internal set { _hierType = value; }
}
/// <summary>
/// Virtual stream number.
/// </summary>
public int VirStreamNumber
{
get { return _virStreamNumber; }
internal set { _virStreamNumber = value; }
}
/// <summary>
/// Virtual version number.
/// </summary>
public int VirVersionNumber
{
get { return _virVersionNumber; }
internal set { _virVersionNumber = value; }
}
/// <summary>
/// Named stream\\version number designation, e.g. \c MARS_MAINT3\17 or \c MARS_MAINT3_barnyrd\22
/// </summary>
public string NamedVersion
{
get { return _namedVersion ?? String.Empty; }
internal set { _namedVersion = value; }
}
/// <summary>
/// Real stream number.
/// </summary>
public int RealStreamNumber
{
get { return _realStreamNumber; }
internal set { _realStreamNumber = value; }
}
/// <summary>
/// Real version number.
/// </summary>
public int RealVersionNumber
{
get { return _realVersionNumber; }
internal set { _realVersionNumber = value; }
}
/// <summary>
/// Stream where the element is located when it has (\e underlap)(\e member) or (\e overlap)(\e member) status.
/// </summary>
/// <remarks>Include the \c -B option in the \c stat command to initialize this field.</remarks>
/*! \sa [Example XML from stat command](@ref findOvrUnder) */
public string LapStream
{
get { return _lapStream ?? String.Empty; }
internal set { _lapStream = value; }
}
/// <summary>
/// Name of the first time-based stream found when <tt>stat -s \<stream\> -o -B -fox</tt> is
/// used to retrieve elements with (\e overlap) and/or (\e underlap) status in the specified stream and higher.
/// Returns the specified <tt>-s \<stream\></tt> name if it is a time-based stream.
/// </summary>
/// <remarks>Without \c -B, the \c -fo option does nothing. It should be viewed as a modifier of the \c -B option,
/// as it causes the search to include (\e overlap) and (\e underlap) elements above time-based streams.
/// (\c -B without \c -fo stops when the first time-based stream is encountered and does not include these elements.)
/// The \c -fox option is required to initialize this property. The \c -o option is required in all cases.
/// The XML emitted via \c -fx includes the element-ID, so there's no need to include 'e' as in \c -foex to ensure
/// [Element.EID](@ref AcUtils#Element#EID) is initialized.</remarks>
/*! \sa [Example XML from stat command](@ref findOvrUnder) */
public string TimeBasedStream
{
get { return _timeBasedStream ?? String.Empty; }
internal set { _timeBasedStream = value; }
}
/// <summary>
/// The version's status, e.g. (\e kept)(\e member)
/// </summary>
public string Status
{
get { return _status ?? String.Empty; }
internal set { _status = value; }
}
#region ToString
/// <summary>
/// The ToString implementation.
/// </summary>
/// <param name="format">The format specifier to use, e.g. <b>Console.WriteLine(elem.ToString("fs"));</b></param>
/// <param name="provider">Allow clients to format output for their own types
/// using [ICustomFormatter](https://msdn.microsoft.com/en-us/library/system.icustomformatter.aspx).</param>
/// <returns>The formatted string.</returns>
/// <exception cref="FormatException">thrown if an invalid format string is specified.</exception>
/// \par Format specifiers:
/// \arg \c LV Long version (verbose).
/// \arg \c G Location, the depot-relative path of the element (default when not using a format specifier).
/// \arg \c F \e True if the element is a folder, \e False otherwise.
/// \arg \c E \e True if the executable bit is set, \e False if cleared. UNIX/Linux systems only.
/// \arg \c I Element ID.
/// \arg \c T The element's type: \e dir, \e text, \e binary, \e ptext, \e elink, or \e slink.
/// \arg \c FS File size in bytes.
/// \arg \c MT Element's modification time.
/// \arg \c H "Hierarchy type" of the element, one of two possible values: \e parallel or \e serial.
/// \arg \c V Virtual stream\\version number format, e.g. \c 5\12
/// \arg \c R Real stream\\version number format.
/// \arg \c N The named stream-name\\version-number designation, e.g. \c MARS_STAGE\7 or \c MARS_STAGE_barnyrd\24
/// \arg \c L Stream where the element is located when it has (\e underlap)(\e member) or (\e overlap)(\e member) status.
/// \arg \c TB Name of first time-based stream found when <tt>stat -s \<stream\> -o -B -fox</tt> is used to retrieve elements with (\e overlap) and/or (\e underlap) status.
/// \arg \c S The version's status, e.g. (\e kept)(\e member)
public string ToString(string format, IFormatProvider provider)
{
if (provider != null)
{
ICustomFormatter fmt = provider.GetFormat(this.GetType()) as ICustomFormatter;
if (fmt != null)
return fmt.Format(format, this, provider);
}
if (String.IsNullOrEmpty(format))
format = "G";
switch (format.ToUpperInvariant())
{
case "LV": // long version (verbose)
{
if (_modTime != null)
return $"{Location}, {Status}{Environment.NewLine}" +
$"\tEID: {EID} {{{ElementType}}}, Size: {Size}, ModTime: {ModTime},{Environment.NewLine}" +
$"\t{NamedVersion}, Virtual: {VirStreamNumber}\\{VirVersionNumber}, Real: {RealStreamNumber}\\{RealVersionNumber}";
else
return $"{Location}, {Status}{Environment.NewLine}" +
$"\tEID: {EID} {{{ElementType}}}{Environment.NewLine}" +
$"\t{NamedVersion}, Virtual: {VirStreamNumber}\\{VirVersionNumber}, Real: {RealStreamNumber}\\{RealVersionNumber}";
}
case "G": // location, the depot-relative path of the element (default when not using a format specifier)
return Location;
case "F": // True if the element is a folder, False otherwise
return Folder.ToString();
case "E": // UNIX/Linux systems only: True if the executable bit is set, False if cleared
return Executable.ToString();
case "I": // element ID
return EID.ToString();
case "T": // element's type: dir, text, binary, ptext, elink, or slink
return ElementType.ToString();
case "FS": // file size in bytes
return (Size == null) ? String.Empty : Size.ToString();
case "MT": // element's modification time
return ModTime.ToString();
case "H": // hierarchy type: parallel or serial
return HierType;
case "V": // virtual stream\\version number designation, e.g. 5\12
return $"{VirStreamNumber}\\{VirVersionNumber}";
case "R": // real stream\\version number designation, e.g. 5\12
return $"{RealStreamNumber}\\{RealVersionNumber}";
case "N": // named stream\version number format, e.g. MARS_STAGE\7 or MARS_STAGE_barnyrd\24
return NamedVersion;
case "L": // stream where element is located when it has (\e underlap)(\e member) or (\e overlap)(\e member) status
return LapStream;
case "TB": // first time-based stream found when 'stat -s stream -o -B -fox' is used to retrieve elements with (overlap) and/or (underlap) status
return TimeBasedStream;
case "S": // version's status, e.g. (kept)(member)
return Status;
default:
throw new FormatException($"The {format} format string is not supported.");
}
}
// Calls ToString(string, IFormatProvider) version with a null IFormatProvider argument.
public string ToString(string format)
{
return ToString(format, null);
}
// Calls ToString(string, IFormatProvider) version with the general format and a null IFormatProvider argument.
public override string ToString()
{
return ToString("G", null);
}
#endregion ToString
}
/// <summary>
/// The list of Element objects from the \c stat command.
/// </summary>
/*! \code
try {
AcResult result = await AcCommand.runAsync(@"stat -foix -B -d -s ""NEPTUNE_DEV2_barnyrd""");
if (result == null || result.RetVal != 0) return false; // error occurred, check log file
if (Stat.init(result.CmdResult)) // populate list using XML from the stat command
foreach (Element elem in Stat.Elements.OrderBy(n => n.Location).ThenByDescending(n => n.ModTime))
Console.WriteLine(elem.ToString("LV"));
}
catch (AcUtilsException ecx)
{
Console.WriteLine($"AcUtilsException caught in Program.show{Environment.NewLine}{ecx.Message}");
}
catch (Exception ecx)
{
Console.WriteLine($"Exception caught in Program.show{Environment.NewLine}{ecx.Message}");
}
\endcode */
[Serializable]
public static class Stat
{
#region class variables
private static List<Element> _elements = new List<Element>();
[NonSerialized] private static readonly object _locker = new object();
#endregion
/// <summary>
/// The list of Element objects.
/// </summary>
public static List<Element> Elements
{
get { return _elements; }
private set { _elements = value; }
}
/// <summary>
/// Remove all elements from the (static) element's list.
/// </summary>
public static void clear()
{
_elements.Clear();
}
/// <summary>
/// Populate this list with elements from the XML emitted by the
/// [stat](https://www.microfocus.com/documentation/accurev/72/WebHelp/wwhelp/wwhimpl/js/html/wwhelp.htm#href=AccuRev_User_CLI/cli_ref_stat.html) command.
/// </summary>
/// <param name="xml">XML from the AccuRev \c stat command.</param>
/// <returns>\e true if parsing was successful, \e false otherwise.</returns>
/// <exception cref="Exception">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
/// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on failure to handle a range of exceptions.</exception>
public static bool init(string xml)
{
bool ret = false; // assume failure
try
{
XElement elements = XElement.Parse(xml);
IEnumerable<XElement> query = from e in elements.Elements("element")
where !e.Attribute("status").Value.Contains("no such elem")
select e;
foreach (XElement e in query)
{
Element element = new Element();
element.Status = (string)e.Attribute("status") ?? String.Empty;
element.Location = (string)e.Attribute("location") ?? String.Empty;
string dir = (string)e.Attribute("dir") ?? String.Empty;
element.Folder = String.Equals(dir, "yes");
string exe = (string)e.Attribute("executable") ?? String.Empty;
element.Executable = String.Equals(exe, "yes");
element.EID = (int?)e.Attribute("id") ?? 0;
element.ElementType = e.acxType("elemType");
element.Size = (long?)e.Attribute("size");
element.ModTime = e.acxTime("modTime");
element.HierType = (string)e.Attribute("hierType") ?? String.Empty;
int ival;
string vir = (string)e.Attribute("Virtual") ?? String.Empty;
if (!String.IsNullOrEmpty(vir))
{
string[] arrVir = vir.Split('\\');
if (Int32.TryParse(arrVir[0], NumberStyles.Integer, null, out ival))
element.VirStreamNumber = ival;
if (Int32.TryParse(arrVir[1], NumberStyles.Integer, null, out ival))
element.VirVersionNumber = ival;
}
element.NamedVersion = (string)e.Attribute("namedVersion") ?? String.Empty;
string real = (string)e.Attribute("Real") ?? String.Empty;
if (!String.IsNullOrEmpty(real))
{
string[] arrReal = real.Split('\\');
if (Int32.TryParse(arrReal[0], NumberStyles.Integer, null, out ival))
element.RealStreamNumber = ival;
if (Int32.TryParse(arrReal[1], NumberStyles.Integer, null, out ival))
element.RealVersionNumber = ival;
}
element.LapStream = (string)e.Attribute("overlapStream") ?? String.Empty;
element.TimeBasedStream = (string)e.Attribute("timeBasisStream") ?? String.Empty;
lock (_locker) { _elements.Add(element); }
}
ret = true; // operation succeeded
}
catch (Exception ecx)
{
AcDebug.Log($"Exception caught and logged in Stat.init{Environment.NewLine}{ecx.Message}");
}
return ret;
}
/// <summary>
/// Get the \c stat command's Element object from this list that corresponds to the \e version element in a transaction from the \c hist command.
/// </summary>
/// <param name="version">The version element to query.</param>
/*! \code
<version path="\.\foo.java" eid="65" virtual="11/8" real="19/5" virtualNamedVersion="MARS_DEV2/8" realNamedVersion="MARS_DEV2_barnyrd/5" elem_type="text" dir="no" />
\endcode */
/// <returns>The Element object that corresponds to the \e version element if found, otherwise \e null.</returns>
/*!
The Element object and \e version element relate when all of the following conditions are true:
- Their element ID's match.
- Their respective virtual and real stream/version numbers match.
- The Element.NamedVersion stream name matches the version's \e virtualNamedVersion or \e realNamedVersion stream name.
*/
/*! \sa <a href="_latest_promotions_8cs-example.html">LatestPromotions.cs</a>, <a href="_latest_overlaps_8cs-example.html">LatestOverlaps.cs</a> */
public static Element getElement(XElement version)
{
Debug.Assert(version.Name == "version", @"version.Name == ""version""");
int? virEID = (int?)version.Attribute("eid");
if (virEID == null) return null;
int[] virStreamVersion = version.acxStreamVersion(RealVirtual.Virtual);
if (virStreamVersion == null) return null;
int[] realStreamVersion = version.acxStreamVersion(RealVirtual.Real);
if (realStreamVersion == null) return null;
string virStream = version.acxStreamName(RealVirtual.Virtual);
if (virStream == null) return null;
string realStream = version.acxStreamName(RealVirtual.Real);
if (realStream == null) return null;
IEnumerable<Element> query = from e in _elements
where e.EID == virEID &&
e.VirStreamNumber == virStreamVersion[0] && e.VirVersionNumber == virStreamVersion[1] &&
e.RealStreamNumber == realStreamVersion[0] && e.RealVersionNumber == realStreamVersion[1] &&
(e.NamedVersion.StartsWith(virStream) || e.NamedVersion.StartsWith(realStream))
select e;
return query.FirstOrDefault();
}
}
}