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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Text;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// PSTuple is a helper class used to create Tuple from an input array.
    /// </summary>
    internal static class PSTuple
    {
        /// <summary>
        /// ArrayToTuple is a helper method used to create a tuple for the supplied input array.
        /// </summary>
        /// <typeparam name="T">The first generic type parameter.</typeparam>
        /// <param name="inputObjects">Input objects used to create a tuple.</param>
        /// <returns>Tuple object.</returns>
        internal static object ArrayToTuple<T>(IList<T> inputObjects)
        {
            return ArrayToTuple(inputObjects, 0);
        }

        /// <summary>
        /// ArrayToTuple is a helper method used to create a tuple for the supplied input array.
        /// </summary>
        /// <typeparam name="T">The first generic type parameter.</typeparam>
        /// <param name="inputObjects">Input objects used to create a tuple.</param>
        /// <param name="startIndex">Start index of the array from which the objects have to considered for the tuple creation.</param>
        /// <returns>Tuple object.</returns>
        private static object ArrayToTuple<T>(IList<T> inputObjects, int startIndex)
        {
            Diagnostics.Assert(inputObjects != null, "inputObjects is null");
            Diagnostics.Assert(inputObjects.Count > 0, "inputObjects is empty");

            switch (inputObjects.Count - startIndex)
            {
                case 0:
                    return null;
                case 1:
                    return Tuple.Create(inputObjects[startIndex]);
                case 2:
                    return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1]);
                case 3:
                    return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2]);
                case 4:
                    return Tuple.Create(inputObjects[startIndex], inputObjects[startIndex + 1], inputObjects[startIndex + 2], inputObjects[startIndex + 3]);
                case 5:
                    return Tuple.Create(
                        inputObjects[startIndex],
                        inputObjects[startIndex + 1],
                        inputObjects[startIndex + 2],
                        inputObjects[startIndex + 3],
                        inputObjects[startIndex + 4]);
                case 6:
                    return Tuple.Create(
                        inputObjects[startIndex],
                        inputObjects[startIndex + 1],
                        inputObjects[startIndex + 2],
                        inputObjects[startIndex + 3],
                        inputObjects[startIndex + 4],
                        inputObjects[startIndex + 5]);
                case 7:
                    return Tuple.Create(
                        inputObjects[startIndex],
                        inputObjects[startIndex + 1],
                        inputObjects[startIndex + 2],
                        inputObjects[startIndex + 3],
                        inputObjects[startIndex + 4],
                        inputObjects[startIndex + 5],
                        inputObjects[startIndex + 6]);
                case 8:
                    return Tuple.Create(
                        inputObjects[startIndex],
                        inputObjects[startIndex + 1],
                        inputObjects[startIndex + 2],
                        inputObjects[startIndex + 3],
                        inputObjects[startIndex + 4],
                        inputObjects[startIndex + 5],
                        inputObjects[startIndex + 6],
                        inputObjects[startIndex + 7]);
                default:
                    return Tuple.Create(
                        inputObjects[startIndex],
                        inputObjects[startIndex + 1],
                        inputObjects[startIndex + 2],
                        inputObjects[startIndex + 3],
                        inputObjects[startIndex + 4],
                        inputObjects[startIndex + 5],
                        inputObjects[startIndex + 6],
                        ArrayToTuple(inputObjects, startIndex + 7));
            }
        }
    }

    /// <summary>
    /// Emitted by Group-Object when the NoElement option is true.
    /// </summary>
    public sealed class GroupInfoNoElement : GroupInfo
    {
        internal GroupInfoNoElement(OrderByPropertyEntry groupValue) : base(groupValue)
        {
        }

        internal override void Add(PSObject groupValue)
        {
            Count++;
        }
    }

    /// <summary>
    /// Emitted by Group-Object.
    /// </summary>
    [DebuggerDisplay("{Name} ({Count})")]
    public class GroupInfo
    {
        internal GroupInfo(OrderByPropertyEntry groupValue)
        {
            Group = new Collection<PSObject>();
            this.Add(groupValue.inputObject);
            GroupValue = groupValue;
            Name = BuildName(groupValue.orderValues);
        }

        internal virtual void Add(PSObject groupValue)
        {
            Group.Add(groupValue);
            Count++;
        }

        private static string BuildName(List<ObjectCommandPropertyValue> propValues)
        {
            StringBuilder sb = new();
            foreach (ObjectCommandPropertyValue propValue in propValues)
            {
                var propValuePropertyValue = propValue?.PropertyValue;
                if (propValuePropertyValue != null)
                {
                    if (propValuePropertyValue is ICollection propertyValueItems)
                    {
                        sb.Append('{');
                        var length = sb.Length;

                        foreach (object item in propertyValueItems)
                        {
                            sb.Append(CultureInfo.CurrentCulture, $"{item}, ");
                        }

                        sb = sb.Length > length ? sb.Remove(sb.Length - 2, 2) : sb;
                        sb.Append("}, ");
                    }
                    else
                    {
                        sb.Append(CultureInfo.CurrentCulture, $"{propValuePropertyValue}, ");
                    }
                }
            }

            return sb.Length >= 2 ? sb.Remove(sb.Length - 2, 2).ToString() : string.Empty;
        }

        /// <summary>
        /// Gets the values of the group.
        /// </summary>
        public ArrayList Values
        {
            get
            {
                ArrayList values = new();
                foreach (ObjectCommandPropertyValue propValue in GroupValue.orderValues)
                {
                    values.Add(propValue.PropertyValue);
                }

                return values;
            }
        }

        /// <summary>
        /// Gets the number of objects in the group.
        /// </summary>
        public int Count { get; internal set; }

        /// <summary>
        /// Gets the list of objects in this group.
        /// </summary>
        public Collection<PSObject> Group { get; }

        /// <summary>
        /// Gets the name of the group.
        /// </summary>
        public string Name { get; }

        /// <summary>
        /// Gets the OrderByPropertyEntry used to build this group object.
        /// </summary>
        internal OrderByPropertyEntry GroupValue { get; }
    }

    /// <summary>
    /// Group-Object implementation.
    /// </summary>
    [Cmdlet(VerbsData.Group, "Object", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096619", RemotingCapability = RemotingCapability.None)]
    [OutputType(typeof(Hashtable), typeof(GroupInfo))]
    public class GroupObjectCommand : ObjectBase
    {
        #region tracer

        /// <summary>
        /// An instance of the PSTraceSource class used for trace output.
        /// </summary>
        [TraceSource("GroupObjectCommand", "Class that has group base implementation")]
        private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("GroupObjectCommand", "Class that has group base implementation");

        #endregion tracer

        #region Command Line Switches

        /// <summary>
        /// Gets or sets the NoElement parameter indicating of the groups should be flattened.
        /// </summary>
        /// <value></value>
        [Parameter]
        public SwitchParameter NoElement { get; set; }

        /// <summary>
        /// Gets or sets the AsHashTable parameter.
        /// </summary>
        /// <value></value>
        [Parameter(ParameterSetName = "HashTable")]
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "HashTable")]
        [Alias("AHT")]
        public SwitchParameter AsHashTable { get; set; }

        /// <summary>
        /// Gets or sets the AsString parameter.
        /// </summary>
        [Parameter(ParameterSetName = "HashTable")]
        public SwitchParameter AsString { get; set; }

        private readonly List<GroupInfo> _groups = new();
        private readonly OrderByProperty _orderByProperty = new();
        private readonly Dictionary<object, GroupInfo> _tupleToGroupInfoMappingDictionary = new();
        private readonly List<OrderByPropertyEntry> _entriesToOrder = new();
        private OrderByPropertyComparer _orderByPropertyComparer;
        private bool _hasProcessedFirstInputObject;
        private bool _hasDifferentValueTypes;
        private Type[] _propertyTypesCandidate;

        #endregion

        #region utils

        /// <summary>
        /// Utility function called by Group-Object to create Groups.
        /// </summary>
        /// <param name="currentObjectEntry">Input object that needs to be grouped.</param>
        /// <param name="noElement">True if we are not accumulating objects.</param>
        /// <param name="groups">List containing Groups.</param>
        /// <param name="groupInfoDictionary">Dictionary used to keep track of the groups with hash of the property values being the key.</param>
        /// <param name="orderByPropertyComparer">The Comparer to be used while comparing to check if new group has to be created.</param>
        private static void DoGrouping(
            OrderByPropertyEntry currentObjectEntry,
            bool noElement,
            List<GroupInfo> groups,
            Dictionary<object, GroupInfo> groupInfoDictionary,
            OrderByPropertyComparer orderByPropertyComparer)
        {
            var currentObjectOrderValues = currentObjectEntry.orderValues;
            if (currentObjectOrderValues != null && currentObjectOrderValues.Count > 0)
            {
                object currentTupleObject = PSTuple.ArrayToTuple(currentObjectOrderValues);

                if (groupInfoDictionary.TryGetValue(currentTupleObject, out var currentGroupInfo))
                {
                    // add this inputObject to an existing group
                    currentGroupInfo.Add(currentObjectEntry.inputObject);
                }
                else
                {
                    bool isCurrentItemGrouped = false;

                    for (int groupsIndex = 0; groupsIndex < groups.Count; groupsIndex++)
                    {
                        // Check if the current input object can be converted to one of the already known types
                        // by looking up in the type to GroupInfo mapping.
                        if (orderByPropertyComparer.Compare(groups[groupsIndex].GroupValue, currentObjectEntry) == 0)
                        {
                            groups[groupsIndex].Add(currentObjectEntry.inputObject);
                            isCurrentItemGrouped = true;
                            break;
                        }
                    }

                    if (!isCurrentItemGrouped)
                    {
                        // create a new group
                        s_tracer.WriteLine("Create a new group: {0}", currentObjectOrderValues);
                        GroupInfo newObjGrp = noElement ? new GroupInfoNoElement(currentObjectEntry) : new GroupInfo(currentObjectEntry);
                        groups.Add(newObjGrp);

                        groupInfoDictionary.Add(currentTupleObject, newObjGrp);
                    }
                }
            }
        }

        /// <summary>
        /// Utility function called by Group-Object to create Groups.
        /// </summary>
        /// <param name="currentObjectEntry">Input object that needs to be grouped.</param>
        /// <param name="noElement">True if we are not accumulating objects.</param>
        /// <param name="groups">List containing Groups.</param>
        /// <param name="groupInfoDictionary">Dictionary used to keep track of the groups with hash of the property values being the key.</param>
        /// <param name="orderByPropertyComparer">The Comparer to be used while comparing to check if new group has to be created.</param>
        private static void DoOrderedGrouping(
            OrderByPropertyEntry currentObjectEntry,
            bool noElement,
            List<GroupInfo> groups,
            Dictionary<object, GroupInfo> groupInfoDictionary,
            OrderByPropertyComparer orderByPropertyComparer)
        {
            var currentObjectOrderValues = currentObjectEntry.orderValues;
            if (currentObjectOrderValues != null && currentObjectOrderValues.Count > 0)
            {
                object currentTupleObject = PSTuple.ArrayToTuple(currentObjectOrderValues);

                if (groupInfoDictionary.TryGetValue(currentTupleObject, out var currentGroupInfo))
                {
                    // add this inputObject to an existing group
                    currentGroupInfo.Add(currentObjectEntry.inputObject);
                }
                else
                {
                    bool isCurrentItemGrouped = false;

                    if (groups.Count > 0)
                    {
                        var lastGroup = groups[groups.Count - 1];

                        // Check if the current input object can be converted to one of the already known types
                        // by looking up in the type to GroupInfo mapping.
                        if (orderByPropertyComparer.Compare(lastGroup.GroupValue, currentObjectEntry) == 0)
                        {
                            lastGroup.Add(currentObjectEntry.inputObject);
                            isCurrentItemGrouped = true;
                        }
                    }

                    if (!isCurrentItemGrouped)
                    {
                        // create a new group
                        s_tracer.WriteLine("Create a new group: {0}", currentObjectOrderValues);
                        GroupInfo newObjGrp = noElement
                            ? new GroupInfoNoElement(currentObjectEntry)
                            : new GroupInfo(currentObjectEntry);

                        groups.Add(newObjGrp);

                        groupInfoDictionary.Add(currentTupleObject, newObjGrp);
                    }
                }
            }
        }

        private void WriteNonTerminatingError(Exception exception, string resourceIdAndErrorId, ErrorCategory category)
        {
            Exception ex = new(StringUtil.Format(resourceIdAndErrorId), exception);
            WriteError(new ErrorRecord(ex, resourceIdAndErrorId, category, null));
        }

        #endregion utils

        /// <summary>
        /// Process every input object to group them.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (InputObject != null && InputObject != AutomationNull.Value)
            {
                OrderByPropertyEntry currentEntry;

                if (!_hasProcessedFirstInputObject)
                {
                    Property ??= OrderByProperty.GetDefaultKeyPropertySet(InputObject);

                    _orderByProperty.ProcessExpressionParameter(this, Property);

                    if (AsString && !AsHashTable)
                    {
                        ArgumentException ex = new(UtilityCommonStrings.GroupObjectWithHashTable);
                        ErrorRecord er = new(ex, "ArgumentException", ErrorCategory.InvalidArgument, AsString);
                        ThrowTerminatingError(er);
                    }

                    if (AsHashTable && !AsString && (Property != null && (Property.Length > 1 || _orderByProperty.MshParameterList.Count > 1)))
                    {
                        ArgumentException ex = new(UtilityCommonStrings.GroupObjectSingleProperty);
                        ErrorRecord er = new(ex, "ArgumentException", ErrorCategory.InvalidArgument, Property);
                        ThrowTerminatingError(er);
                    }

                    currentEntry = _orderByProperty.CreateOrderByPropertyEntry(this, InputObject, CaseSensitive, _cultureInfo);
                    bool[] ascending = new bool[currentEntry.orderValues.Count];
                    for (int index = 0; index < currentEntry.orderValues.Count; index++)
                    {
                        ascending[index] = true;
                    }

                    _orderByPropertyComparer = new OrderByPropertyComparer(ascending, _cultureInfo, CaseSensitive);

                    _hasProcessedFirstInputObject = true;
                }
                else
                {
                    currentEntry = _orderByProperty.CreateOrderByPropertyEntry(this, InputObject, CaseSensitive, _cultureInfo);
                }

                _entriesToOrder.Add(currentEntry);

                var currentEntryOrderValues = currentEntry.orderValues;
                if (!_hasDifferentValueTypes)
                {
                    UpdateOrderPropertyTypeInfo(currentEntryOrderValues);
                }
            }
        }

        private void UpdateOrderPropertyTypeInfo(List<ObjectCommandPropertyValue> currentEntryOrderValues)
        {
            if (_propertyTypesCandidate == null)
            {
                _propertyTypesCandidate = currentEntryOrderValues.Select(static c => PSObject.Base(c.PropertyValue)?.GetType()).ToArray();
                return;
            }

            if (_propertyTypesCandidate.Length != currentEntryOrderValues.Count)
            {
                _hasDifferentValueTypes = true;
                return;
            }

            // check all the types we group on.
            // if we find more than one set of types, _hasDifferentValueTypes is set to true,
            // and we are forced to take a slower code path when we group our objects
            for (int i = 0; i < _propertyTypesCandidate.Length; i++)
            {
                var candidateType = _propertyTypesCandidate[i];
                var propertyType = PSObject.Base(currentEntryOrderValues[i].PropertyValue)?.GetType();
                if (propertyType == null)
                {
                    // we ignore properties without values. We can always compare against null.
                    continue;
                }

                // if we haven't gotten a type for a property yet, update it when we do get a value
                if (propertyType != candidateType)
                {
                    if (candidateType == null)
                    {
                        _propertyTypesCandidate[i] = propertyType;
                    }
                    else
                    {
                        _hasDifferentValueTypes = true;
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Completes the processing of the gathered group objects.
        /// </summary>
        protected override void EndProcessing()
        {
            if (!_hasDifferentValueTypes)
            {
                // using OrderBy to get stable sort.
                // fast path when we only have the same object types to group
                foreach (var entry in _entriesToOrder.Order(_orderByPropertyComparer))
                {
                    DoOrderedGrouping(entry, NoElement, _groups, _tupleToGroupInfoMappingDictionary, _orderByPropertyComparer);
                    if (Stopping)
                    {
                        return;
                    }
                }
            }
            else
            {
                foreach (var entry in _entriesToOrder)
                {
                    DoGrouping(entry, NoElement, _groups, _tupleToGroupInfoMappingDictionary, _orderByPropertyComparer);
                    if (Stopping)
                    {
                        return;
                    }
                }
            }

            s_tracer.WriteLine(_groups.Count);
            if (_groups.Count > 0)
            {
                if (AsHashTable.IsPresent)
                {
                    StringComparer comparer = CaseSensitive.IsPresent
                        ? StringComparer.CurrentCulture
                        : StringComparer.CurrentCultureIgnoreCase;
                    var hashtable = new Hashtable(comparer);
                    try
                    {
                        if (AsString)
                        {
                            foreach (GroupInfo grp in _groups)
                            {
                                hashtable.Add(grp.Name, grp.Group);
                            }
                        }
                        else
                        {
                            foreach (GroupInfo grp in _groups)
                            {
                                hashtable.Add(PSObject.Base(grp.Values[0]), grp.Group);
                            }
                        }
                    }
                    catch (ArgumentException e)
                    {
                        WriteNonTerminatingError(e, UtilityCommonStrings.InvalidOperation, ErrorCategory.InvalidArgument);
                        return;
                    }

                    WriteObject(hashtable);
                }
                else
                {
                    WriteObject(_groups, true);
                }
            }
        }
    }
}