forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatchString.cs
More file actions
1868 lines (1661 loc) · 66.7 KB
/
Copy pathMatchString.cs
File metadata and controls
1868 lines (1661 loc) · 66.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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Context information about a match.
/// </summary>
public sealed class MatchInfoContext : ICloneable
{
internal MatchInfoContext()
{
}
/// <summary>
/// Lines found before a match.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] PreContext { get; set; }
/// <summary>
/// Lines found after a match.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] PostContext { get; set; }
/// <summary>
/// Lines found before a match. Does not include
/// overlapping context and thus can be used to
/// display contiguous match regions.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] DisplayPreContext { get; set; }
/// <summary>
/// Lines found after a match. Does not include
/// overlapping context and thus can be used to
/// display contiguous match regions.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] DisplayPostContext { get; set; }
/// <summary>
/// Produce a deep copy of this object.
/// </summary>
public object Clone()
{
MatchInfoContext clone = new MatchInfoContext();
clone.PreContext = (clone.PreContext != null) ? (string[])PreContext.Clone() : null;
clone.PostContext = (clone.PostContext != null) ? (string[])PostContext.Clone() : null;
clone.DisplayPreContext = (clone.DisplayPreContext != null) ? (string[])DisplayPreContext.Clone() : null;
clone.DisplayPostContext = (clone.DisplayPostContext != null) ? (string[])DisplayPostContext.Clone() : null;
return clone;
}
}
/// <summary>
/// The object returned by select-string representing the result of a match.
/// </summary>
public class MatchInfo
{
private static string s_inputStream = "InputStream";
/// <summary>
/// Indicates if the match was done ignoring case.
/// </summary>
/// <value>True if case was ignored.</value>
public bool IgnoreCase { get; set; }
/// <summary>
/// Returns the number of the matching line.
/// </summary>
/// <value>The number of the matching line.</value>
public int LineNumber { get; set; }
/// <summary>
/// Returns the text of the matching line.
/// </summary>
/// <value>The text of the matching line.</value>
public string Line { get; set; } = "";
/// <summary>
/// Returns the base name of the file containing the matching line.
/// <remarks>
/// It will be the string "InputStream" if the object came from the input stream.
/// This is a readonly property calculated from the path. <see cref="Path"/>
/// </remarks>
/// </summary>
/// <value>The file name</value>
public string Filename
{
get
{
if (!_pathSet)
return s_inputStream;
return _filename ?? (_filename = System.IO.Path.GetFileName(_path));
}
}
private string _filename;
/// <summary>
/// The full path of the file containing the matching line.
/// <remarks>
/// It will be "InputStream" if the object came from the input stream.
/// </remarks>
/// </summary>
/// <value>The path name</value>
public string Path
{
get
{
if (!_pathSet)
return s_inputStream;
return _path;
}
set
{
_path = value;
_pathSet = true;
}
}
private string _path = s_inputStream;
private bool _pathSet;
/// <summary>
/// Returns the pattern that was used in the match.
/// </summary>
/// <value>The pattern string</value>
public string Pattern { get; set; }
/// <summary>
/// The context for the match, or null if -context was not
/// specified.
/// </summary>
public MatchInfoContext Context { get; set; }
/// <summary>
/// Returns the path of the matching file truncated relative to the <paramref name="directory"/> parameter.
/// <remarks>
/// For example, if the matching path was c:\foo\bar\baz.c and the directory argument was c:\foo
/// the routine would return bar\baz.c
/// </remarks>
/// </summary>
/// <param name="directory">The directory base the truncation on.</param>
/// <returns>The relative path that was produced.</returns>
public string RelativePath(string directory)
{
if (!_pathSet)
return this.Path;
string relPath = _path;
if (!String.IsNullOrEmpty(directory))
{
if (relPath.StartsWith(directory, StringComparison.OrdinalIgnoreCase))
{
int offset = directory.Length;
if (offset < relPath.Length)
{
if (directory[offset - 1] == '\\' || directory[offset - 1] == '/')
relPath = relPath.Substring(offset);
else if (relPath[offset] == '\\' || relPath[offset] == '/')
relPath = relPath.Substring(offset + 1);
}
}
}
return relPath;
}
private const string MatchFormat = "{0}{1}:{2}:{3}";
private const string SimpleFormat = "{0}{1}";
// Prefixes used by formatting: Match and Context prefixes
// are used when context-tracking is enabled, otherwise
// the empty prefix is used.
private const string MatchPrefix = "> ";
private const string ContextPrefix = " ";
private const string EmptyPrefix = "";
/// <summary>
/// Returns the string representation of this object. The format
/// depends on whether a path has been set for this object or not.
/// <remarks>
/// If the path component is set, as would be the case when matching
/// in a file, ToString() would return the path, line number and line text.
/// If path is not set, then just the line text is presented.
/// </remarks>
/// </summary>
/// <returns>The string representation of the match object</returns>
public override string ToString()
{
return ToString(null);
}
/// <summary>
/// Returns the string representation of the match object same format as ToString()
/// but trims the path to be relative to the <paramref name="directory"/> argument.
/// </summary>
/// <param name="directory">Directory to use as the root when calculating the relative path</param>
/// <returns>The string representation of the match object</returns>
public string ToString(string directory)
{
string displayPath = (directory != null) ? RelativePath(directory) : _path;
// Just return a single line if the user didn't
// enable context-tracking.
if (Context == null)
{
return FormatLine(Line, this.LineNumber, displayPath, EmptyPrefix);
}
// Otherwise, render the full context.
List<string> lines = new List<string>(Context.DisplayPreContext.Length + Context.DisplayPostContext.Length + 1);
int displayLineNumber = this.LineNumber - Context.DisplayPreContext.Length;
foreach (string contextLine in Context.DisplayPreContext)
{
lines.Add(FormatLine(contextLine, displayLineNumber++, displayPath, ContextPrefix));
}
lines.Add(FormatLine(Line, displayLineNumber++, displayPath, MatchPrefix));
foreach (string contextLine in Context.DisplayPostContext)
{
lines.Add(FormatLine(contextLine, displayLineNumber++, displayPath, ContextPrefix));
}
return String.Join(System.Environment.NewLine, lines.ToArray());
}
/// <summary>
/// Formats a line for use in ToString.
/// </summary>
/// <param name="lineStr">The line to format.</param>
/// <param name="displayLineNumber">The line number to display.</param>
/// <param name="displayPath">The file path, formatted for display.</param>
/// <param name="prefix">The match prefix.</param>
/// <returns>The formatted line as a string.</returns>
private string FormatLine(string lineStr, int displayLineNumber, string displayPath, string prefix)
{
if (_pathSet)
return StringUtil.Format(MatchFormat, prefix, displayPath, displayLineNumber, lineStr);
else
return StringUtil.Format(SimpleFormat, prefix, lineStr);
}
/// <summary>
/// A list of all Regex matches on the matching line.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Match[] Matches { get; set; } = new Match[] { };
/// <summary>
/// Create a deep copy of this MatchInfo instance.
/// </summary>
internal MatchInfo Clone()
{
// Just do a shallow copy and then deep-copy the
// fields that need it.
MatchInfo clone = (MatchInfo)this.MemberwiseClone();
if (clone.Context != null)
{
clone.Context = (MatchInfoContext)clone.Context.Clone();
}
// Regex match objects are immutable, so we can get away
// with just copying the array.
clone.Matches = (Match[])clone.Matches.Clone();
return clone;
}
}
/// <summary>
/// A cmdlet to search through strings and files for particular patterns.
/// </summary>
[Cmdlet(VerbsCommon.Select, "String", DefaultParameterSetName = "File", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113388")]
[OutputType(typeof(MatchInfo), typeof(bool))]
public sealed class SelectStringCommand : PSCmdlet
{
/// <summary>
/// A generic circular buffer.
/// </summary>
private class CircularBuffer<T> : ICollection<T>
{
// Ring of items
private T[] _items;
// Current length, as opposed to the total capacity
// Current start of the list. Starts at 0, but may
// move forwards or wrap around back to 0 due to
// rotation.
private int _firstIndex;
/// <summary>
/// Construct a new buffer of the specified capacity.
/// </summary>
/// <param name="capacity">The maximum capacity of the buffer.</param>
/// <exception cref="ArgumentOutOfRangeException">If <paramref name="capacity" /> is negative.</exception>
public CircularBuffer(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException("capacity");
_items = new T[capacity];
Clear();
}
/// <summary>
/// The maximum capacity of the buffer. If more items
/// are added than the buffer has capacity for, then
/// older items will be removed from the buffer with
/// a first-in, first-out policy.
/// </summary>
public int Capacity
{
get
{
return _items.Length;
}
}
/// <summary>
/// Whether or not the buffer is at capacity.
/// </summary>
public bool IsFull
{
get
{
return Count == Capacity;
}
}
/// <summary>
/// Convert from a 0-based index to a buffer index which
/// has been properly offset and wrapped.
/// </summary>
/// <param name="zeroBasedIndex">The index to wrap.</param>
/// <exception cref="ArgumentOutOfRangeException">If <paramref name="zeroBasedIndex" /> is out of range.</exception>
/// <returns>
/// The actual index that <param ref="zeroBasedIndex" />
/// maps to.
/// </returns>
private int WrapIndex(int zeroBasedIndex)
{
if (Capacity == 0 || zeroBasedIndex < 0)
{
throw new ArgumentOutOfRangeException("zeroBasedIndex");
}
return (zeroBasedIndex + _firstIndex) % Capacity;
}
#region IEnumerable<T> implementation.
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < Count; i++)
{
yield return _items[WrapIndex(i)];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}
#endregion
#region ICollection<T> implementation
public int Count { get; private set; }
public bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Adds an item to the buffer. If the buffer is already
/// full, the oldest item in the list will be removed,
/// and the new item added at the logical end of the list.
/// </summary>
/// <param name="item">The item to add.</param>
public void Add(T item)
{
if (Capacity == 0)
{
return;
}
int itemIndex;
if (IsFull)
{
itemIndex = _firstIndex;
_firstIndex = (_firstIndex + 1) % Capacity;
}
else
{
itemIndex = _firstIndex + Count;
Count++;
}
_items[itemIndex] = item;
}
public void Clear()
{
_firstIndex = 0;
Count = 0;
}
public bool Contains(T item)
{
throw new NotImplementedException();
}
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex");
if (Count > (array.Length - arrayIndex))
throw new ArgumentException("arrayIndex");
// Iterate through the buffer in correct order.
foreach (T item in this)
{
array[arrayIndex++] = item;
}
}
public bool Remove(T item)
{
throw new NotImplementedException();
}
#endregion
/// <summary>
/// Create an array of the items in the buffer. Items
/// will be in the same order they were added.
/// </summary>
/// <returns>The new array.</returns>
public T[] ToArray()
{
T[] result = new T[Count];
CopyTo(result, 0);
return result;
}
/// <summary>
/// Access an item in the buffer. Indexing is based off
/// of the order items were added, rather than any
/// internal ordering the buffer may be maintaining.
/// </summary>
/// <param name="index">The index of the item to access.</param>
public T this[int index]
{
get
{
if (!(index >= 0 && index < Count))
{
throw new ArgumentOutOfRangeException("index");
}
return _items[WrapIndex(index)];
}
}
}
/// <summary>
/// An interface to a context tracking algorithm.
/// </summary>
private interface IContextTracker
{
/// <summary>
/// Matches with completed context information
/// that are ready to be emitted into the pipeline.
/// </summary>
IList<MatchInfo> EmitQueue { get; }
/// <summary>
/// Track a non-matching line for context.
/// </summary>
/// <param name="line">The line to track.</param>
void TrackLine(string line);
/// <summary>
/// Track a matching line.
/// </summary>
/// <param name="match">The line to track.</param>
void TrackMatch(MatchInfo match);
/// <summary>
/// Track having reached the end of the file,
/// giving the tracker a chance to process matches with
/// incomplete context information.
/// </summary>
void TrackEOF();
}
/// <summary>
/// A state machine to track display context for each match.
/// </summary>
private class DisplayContextTracker : IContextTracker
{
private enum ContextState
{
InitialState,
CollectPre,
CollectPost,
}
private ContextState _contextState = ContextState.InitialState;
private int _preContext = 0;
private int _postContext = 0;
// The context leading up to the match.
private CircularBuffer<string> _collectedPreContext = null;
// The context after the match.
private List<string> _collectedPostContext = null;
// Current match info we are tracking postcontext for.
// At any given time, if set, this value will not be
// in the emitQueue but will be the next to be added.
private MatchInfo _matchInfo = null;
/// <summary>
/// Constructor for DisplayContextTracker.
/// </summary>
/// <param name="preContext">How much precontext to collect at most.</param>
/// <param name="postContext">How much precontext to collect at most.</param>
public DisplayContextTracker(int preContext, int postContext)
{
_preContext = preContext;
_postContext = postContext;
_collectedPreContext = new CircularBuffer<string>(preContext);
_collectedPostContext = new List<string>(postContext);
_emitQueue = new List<MatchInfo>();
Reset();
}
#region IContextTracker implementation
public IList<MatchInfo> EmitQueue
{
get
{
return _emitQueue;
}
}
private List<MatchInfo> _emitQueue = null;
// Track non-matching line
public void TrackLine(string line)
{
switch (_contextState)
{
case ContextState.InitialState:
break;
case ContextState.CollectPre:
_collectedPreContext.Add(line);
break;
case ContextState.CollectPost:
// We're not done collecting post-context.
_collectedPostContext.Add(line);
if (_collectedPostContext.Count >= _postContext)
{
// Now we're done.
UpdateQueue();
}
break;
}
}
// Track matching line
public void TrackMatch(MatchInfo match)
{
// Update the queue in case we were in the middle
// of collecting postcontext for an older match...
if (_contextState == ContextState.CollectPost)
UpdateQueue();
// Update the current matchInfo.
_matchInfo = match;
// If postContext is set, then we need to hold
// onto the match for a while and gather context.
// Otherwise, immediately move the match onto the queue
// and let UpdateQueue update our state instead.
if (_postContext > 0)
_contextState = ContextState.CollectPost;
else
UpdateQueue();
}
// Track having reached the end of the file.
public void TrackEOF()
{
// If we're in the middle of collecting postcontext, we
// already have a match and it's okay to queue it up
// early since there are no more lines to track context
// for.
if (_contextState == ContextState.CollectPost)
UpdateQueue();
}
#endregion
/// <summary>
/// Moves matchInfo, if set, to the emitQueue and
/// resets the tracking state.
/// </summary>
private void UpdateQueue()
{
if (_matchInfo != null)
{
_emitQueue.Add(_matchInfo);
if (_matchInfo.Context != null)
{
_matchInfo.Context.DisplayPreContext = _collectedPreContext.ToArray();
_matchInfo.Context.DisplayPostContext = _collectedPostContext.ToArray();
}
Reset();
}
}
// Reset tracking state. Does not reset the emit queue.
private void Reset()
{
_contextState = (_preContext > 0)
? ContextState.CollectPre
: ContextState.InitialState;
_collectedPreContext.Clear();
_collectedPostContext.Clear();
_matchInfo = null;
}
}
/// <summary>
/// A class to track logical context for each match.
/// </summary>
/// <remarks>
/// The difference between logical and display context is
/// that logical context includes as many context lines
/// as possible for a given match, up to the specified
/// limit, including context lines which overlap between
/// matches and other matching lines themselves. Display
/// context, on the other hand, is designed to display
/// a possibly-continuous set of matches by excluding
/// overlapping context (lines will only appear once)
/// and other matching lines (since they will appear
/// as their own match entries.)
/// </remarks>
private class LogicalContextTracker : IContextTracker
{
// A union: string | MatchInfo. Needed since
// context lines could be either proper matches
// or non-matching lines.
private class ContextEntry
{
public string Line = null;
public MatchInfo Match = null;
public ContextEntry(string line)
{
Line = line;
}
public ContextEntry(MatchInfo match)
{
Match = match;
}
public override string ToString()
{
return (Match != null) ? Match.Line : Line;
}
}
// Whether or not early entries found
// while still filling up the context buffer
// have been added to the emit queue.
// Used by UpdateQueue.
private bool _hasProcessedPreEntries = false;
private int _preContext;
private int _postContext;
// A circular buffer tracking both precontext and postcontext.
//
// Essentially, the buffer is separated into regions:
// | prectxt region (older entries, length = precontext) |
// | match region (length = 1) |
// | postctxt region (newer entries, length = postcontext) |
//
// When context entries containing a match reach the "middle"
// (the position between the pre/post context regions)
// of this buffer, and the buffer is full, we will know
// enough context to populate the Context properties of the
// match. At that point, we will add the match object
// to the emit queue.
private CircularBuffer<ContextEntry> _collectedContext = null;
/// <summary>
/// Constructor for LogicalContextTracker.
/// </summary>
/// <param name="preContext">How much precontext to collect at most.</param>
/// <param name="postContext">How much postcontext to collect at most.</param>
public LogicalContextTracker(int preContext, int postContext)
{
_preContext = preContext;
_postContext = postContext;
_collectedContext = new CircularBuffer<ContextEntry>(preContext + postContext + 1);
_emitQueue = new List<MatchInfo>();
}
#region IContextTracker implementation
public IList<MatchInfo> EmitQueue
{
get
{
return _emitQueue;
}
}
private List<MatchInfo> _emitQueue = null;
public void TrackLine(string line)
{
ContextEntry entry = new ContextEntry(line);
_collectedContext.Add(entry);
UpdateQueue();
}
public void TrackMatch(MatchInfo match)
{
ContextEntry entry = new ContextEntry(match);
_collectedContext.Add(entry);
UpdateQueue();
}
public void TrackEOF()
{
// If the buffer is already full,
// check for any matches with incomplete
// postcontext and add them to the emit queue.
// These matches can be identified by being past
// the "middle" of the context buffer (still in
// the postcontext region.
//
// If the buffer isn't full, then nothing will have
// ever been emitted and everything is still waiting
// on postcontext. So process the whole buffer.
int startIndex = (_collectedContext.IsFull) ? _preContext + 1 : 0;
EmitAllInRange(startIndex, _collectedContext.Count - 1);
}
#endregion
/// <summary>
/// Add all matches found in the specified range
/// to the emit queue, collecting as much context
/// as possible up to the limits specified in the ctor.
/// </summary>
/// <remarks>
/// The range is inclusive; the entries at
/// startIndex and endIndex will both be checked.
/// </remarks>
/// <param name="startIndex">The beginning of the match range.</param>
/// <param name="endIndex">The ending of the match range.</param>
private void EmitAllInRange(int startIndex, int endIndex)
{
for (int i = startIndex; i <= endIndex; i++)
{
MatchInfo match = _collectedContext[i].Match;
if (match != null)
{
int preStart = Math.Max(i - _preContext, 0);
int postLength = Math.Min(_postContext, _collectedContext.Count - i - 1);
Emit(match, preStart, i - preStart, i + 1, postLength);
}
}
}
/// <summary>
/// Add match(es) found in the match region to the
/// emit queue. Should be called every time an entry
/// is added to the context buffer.
/// </summary>
private void UpdateQueue()
{
// Are we at capacity and thus have enough postcontext?
// Is there a match in the "middle" of the buffer
// that we know the pre/post context for?
//
// If this is the first time we've reached full capacity,
// hasProcessedPreEntries will not be set, and we
// should go through the entire context, because it might
// have entries that never collected enough
// precontext. Otherwise, we should just look at the
// middle region.
if (_collectedContext.IsFull)
{
if (_hasProcessedPreEntries)
{
// Only process a potential match with exactly
// enough pre and post-context.
EmitAllInRange(_preContext, _preContext);
}
else
{
// Some of our early entries may not
// have enough precontext. Process them too.
EmitAllInRange(0, _preContext);
_hasProcessedPreEntries = true;
}
}
}
/// <summary>
/// Collects context from the specified ranges. Populates
/// the specified match with the collected context
/// and adds it to the emit queue.
/// </summary>
/// <remarks>
/// Context ranges must be within the bounds of the context
/// buffer.
/// </remarks>
/// <param name="match">The match to operate on.</param>
/// <param name="preStartIndex">The start index of the precontext range.</param>
/// <param name="preLength">The length of the precontext range.</param>
/// <param name="postStartIndex">The start index of the postcontext range.</param>
/// <param name="postLength">The length of the precontext range.</param>
private void Emit(MatchInfo match, int preStartIndex, int preLength, int postStartIndex, int postLength)
{
if (match.Context != null)
{
match.Context.PreContext = CopyContext(preStartIndex, preLength);
match.Context.PostContext = CopyContext(postStartIndex, postLength);
}
_emitQueue.Add(match);
}
/// <summary>
/// Collects context from the specified ranges.
/// </summary>
/// <remarks>
/// The range must be within the bounds of the context buffer.
/// </remarks>
/// <param name="startIndex">The index to start at.</param>
/// <param name="length">The length of the range.</param>
private string[] CopyContext(int startIndex, int length)
{
string[] result = new string[length];
for (int i = 0; i < length; i++)
{
result[i] = _collectedContext[startIndex + i].ToString();
}
return result;
}
}
/// <summary>
/// A class to track both logical and display contexts.
/// </summary>
private class ContextTracker : IContextTracker
{
private IContextTracker _displayTracker;
private IContextTracker _logicalTracker;
/// <summary>
/// Constructor for LogicalContextTracker.
/// </summary>
/// <param name="preContext">How much precontext to collect at most.</param>
/// <param name="postContext">How much postcontext to collect at most.</param>
public ContextTracker(int preContext, int postContext)
{
_displayTracker = new DisplayContextTracker(preContext, postContext);
_logicalTracker = new LogicalContextTracker(preContext, postContext);
EmitQueue = new List<MatchInfo>();
}
#region IContextTracker implementation
public IList<MatchInfo> EmitQueue { get; }
public void TrackLine(string line)
{
_displayTracker.TrackLine(line);
_logicalTracker.TrackLine(line);
UpdateQueue();
}
public void TrackMatch(MatchInfo match)
{
_displayTracker.TrackMatch(match);
_logicalTracker.TrackMatch(match);
UpdateQueue();
}
public void TrackEOF()
{
_displayTracker.TrackEOF();
_logicalTracker.TrackEOF();
UpdateQueue();
}
#endregion
/// <summary>
/// Update the emit queue based on the wrapped trackers.
/// </summary>
private void UpdateQueue()
{
// Look for completed matches in the logical
// tracker's queue. Since the logical tracker
// will try to collect as much context as
// possible, the display tracker will have either
// already finished collecting its context for the
// match or will have completed it at the same
// time as the logical tracker, so we can
// be sure the matches will have both logical
// and display context already populated.
foreach (MatchInfo match in _logicalTracker.EmitQueue)
{
EmitQueue.Add(match);
}
_logicalTracker.EmitQueue.Clear();
_displayTracker.EmitQueue.Clear();
}
}
/// <summary>
/// This parameter specifies the current pipeline object
/// </summary>
[Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "Object")]
[AllowNull]
[AllowEmptyString]
public PSObject InputObject
{
get
{
return _inputObject;
}
set
{
_inputObject = LanguagePrimitives.IsNull(value) ? PSObject.AsPSObject("") : value;
}
}
private PSObject _inputObject = AutomationNull.Value;
/// <summary>
/// String index to start from the beginning.
///
/// If the value is negative, the length is counted from the
/// end of the string.
/// </summary>
///
[Parameter(Mandatory = true, Position = 0)]
public string[] Pattern { get; set; }
private Regex[] _regexPattern;
/// <summary>
/// file to read from
/// Globbing is done on these
/// </summary>
[Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "File")]
[FileinfoToString]
public string[] Path { get; set; }
/// <summary>
/// Literal file to read from