File size: 15,151 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Provider;

using Dbg = System.Management.Automation;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// A command to get the content of an item at a specified path.
    /// </summary>
    [Cmdlet(VerbsCommon.Get, "Content", DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096490")]
    public class GetContentCommand : ContentCommandBase
    {
        #region Parameters

        /// <summary>
        /// The number of content items to retrieve per block.
        /// By default this value is 1 which means read one block
        /// at a time.  To read all blocks at once, set this value
        /// to a negative number.
        /// </summary>
        [Parameter(ValueFromPipelineByPropertyName = true)]
        public long ReadCount { get; set; } = 1;

        /// <summary>
        /// The number of content items to retrieve.
        /// </summary>
        [Parameter(ValueFromPipelineByPropertyName = true)]
        [ValidateRange(0, long.MaxValue)]
        [Alias("First", "Head")]
        public long TotalCount { get; set; } = -1;

        /// <summary>
        /// The number of content items to retrieve from the back of the file.
        /// </summary>
        [Parameter(ValueFromPipelineByPropertyName = true)]
        [ValidateRange(0, int.MaxValue)]
        [Alias("Last")]
        public int Tail { get; set; } = -1;

        /// <summary>
        /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets
        /// that require dynamic parameters should override this method and return the
        /// dynamic parameter object.
        /// </summary>
        /// <param name="context">
        /// The context under which the command is running.
        /// </param>
        /// <returns>
        /// An object representing the dynamic parameters for the cmdlet or null if there
        /// are none.
        /// </returns>
        internal override object GetDynamicParameters(CmdletProviderContext context)
        {
            if (Path != null && Path.Length > 0)
            {
                return InvokeProvider.Content.GetContentReaderDynamicParameters(Path[0], context);
            }

            return InvokeProvider.Content.GetContentReaderDynamicParameters(".", context);
        }

        #endregion Parameters

        #region Command code

        /// <summary>
        /// Gets the content of an item at the specified path.
        /// </summary>
        protected override void ProcessRecord()
        {
            // TotalCount and Tail should not be specified at the same time.
            // Throw out terminating error if this is the case.
            if (TotalCount != -1 && Tail != -1)
            {
                string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "TotalCount", "Tail");
                ErrorRecord error = new(new InvalidOperationException(errMsg), "TailAndHeadCannotCoexist", ErrorCategory.InvalidOperation, null);
                WriteError(error);
                return;
            }

            if (TotalCount == 0)
            {
                // Don't read anything
                return;
            }

            // Get the content readers
            CmdletProviderContext currentContext = CmdletProviderContext;
            contentStreams = this.GetContentReaders(Path, currentContext);

            try
            {
                // Iterate through the content holders reading the content
                foreach (ContentHolder holder in contentStreams)
                {
                    long countRead = 0;

                    Dbg.Diagnostics.Assert(holder.Reader != null, "All holders should have a reader assigned");

                    if (Tail != -1 && holder.Reader is not FileSystemContentReaderWriter)
                    {
                        string errMsg = SessionStateStrings.GetContent_TailNotSupported;
                        ErrorRecord error = new(new InvalidOperationException(errMsg), "TailNotSupported", ErrorCategory.InvalidOperation, Tail);
                        WriteError(error);
                        continue;
                    }

                    // If Tail is -1, we are supposed to read all content out. This is same
                    // as reading forwards. So we read forwards in this case.
                    // If Tail is positive, we seek the right position. Or, if the seek failed
                    // because of an unsupported encoding, we scan forward to get the tail content.
                    if (Tail >= 0)
                    {
                        bool seekSuccess = false;

                        try
                        {
                            seekSuccess = SeekPositionForTail(holder.Reader);
                        }
                        catch (Exception e)
                        {
                            ProviderInvocationException providerException =
                                new(
                                    "ProviderContentReadError",
                                    SessionStateStrings.ProviderContentReadError,
                                    holder.PathInfo.Provider,
                                    holder.PathInfo.Path,
                                    e);

                            // Log a provider health event
                            MshLog.LogProviderHealthEvent(
                                this.Context,
                                holder.PathInfo.Provider.Name,
                                providerException,
                                Severity.Warning);

                            WriteError(new ErrorRecord(
                                providerException.ErrorRecord,
                                providerException));

                            continue;
                        }

                        // If the seek was successful, we start to read forwards from that
                        // point. Otherwise, we need to scan forwards to get the tail content.
                        if (!seekSuccess && !ScanForwardsForTail(holder, currentContext))
                        {
                            continue;
                        }
                    }

                    IList results = null;

                    do
                    {
                        long countToRead = ReadCount;

                        // Make sure we only ask for the amount the user wanted
                        // I am using TotalCount - countToRead so that I don't
                        // have to worry about overflow
                        if (TotalCount > 0 && (countToRead == 0 || TotalCount - countToRead < countRead))
                        {
                            countToRead = TotalCount - countRead;
                        }

                        try
                        {
                            results = holder.Reader.Read(countToRead);
                        }
                        catch (Exception e) // Catch-all OK. 3rd party callout
                        {
                            ProviderInvocationException providerException =
                                new(
                                    "ProviderContentReadError",
                                    SessionStateStrings.ProviderContentReadError,
                                    holder.PathInfo.Provider,
                                    holder.PathInfo.Path,
                                    e);

                            // Log a provider health event
                            MshLog.LogProviderHealthEvent(this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning);
                            WriteError(new ErrorRecord(providerException.ErrorRecord, providerException));

                            break;
                        }

                        if (results != null && results.Count > 0)
                        {
                            countRead += results.Count;
                            if (ReadCount == 1)
                            {
                                // Write out the content as a single object
                                WriteContentObject(results[0], countRead, holder.PathInfo, currentContext);
                            }
                            else
                            {
                                // Write out the content as an array of objects
                                WriteContentObject(results, countRead, holder.PathInfo, currentContext);
                            }
                        }
                    } while (results != null && results.Count > 0 && (TotalCount == -1 || countRead < TotalCount));
                }
            }
            finally
            {
                // Close all the content readers

                CloseContent(contentStreams, false);

                // Empty the content holder array
                contentStreams = new List<ContentHolder>();
            }
        }

        /// <summary>
        /// Scan forwards to get the tail content.
        /// </summary>
        /// <param name="holder"></param>
        /// <param name="currentContext"></param>
        /// <returns>
        /// true if no error occurred
        /// false if there was an error
        /// </returns>
        private bool ScanForwardsForTail(in ContentHolder holder, CmdletProviderContext currentContext)
        {
            var fsReader = holder.Reader as FileSystemContentReaderWriter;
            Dbg.Diagnostics.Assert(fsReader != null, "Tail is only supported for FileSystemContentReaderWriter");
            Queue<object> tailResultQueue = new();
            IList results = null;
            ErrorRecord error = null;

            do
            {
                try
                {
                    results = fsReader.ReadWithoutWaitingChanges(ReadCount);
                }
                catch (Exception e)
                {
                    ProviderInvocationException providerException =
                        new(
                            "ProviderContentReadError",
                            SessionStateStrings.ProviderContentReadError,
                            holder.PathInfo.Provider,
                            holder.PathInfo.Path,
                            e);

                    // Log a provider health event
                    MshLog.LogProviderHealthEvent(
                        this.Context,
                        holder.PathInfo.Provider.Name,
                        providerException,
                        Severity.Warning);

                    // Create and save the error record. The error record
                    // will be written outside the while loop.
                    // This is to make sure the accumulated results get written
                    // out before the error record when the 'scanForwardForTail' is true.
                    error = new ErrorRecord(
                        providerException.ErrorRecord,
                        providerException);

                    break;
                }

                if (results != null && results.Count > 0)
                {
                    foreach (object entry in results)
                    {
                        if (tailResultQueue.Count == Tail)
                        {
                            tailResultQueue.Dequeue();
                        }

                        tailResultQueue.Enqueue(entry);
                    }
                }
            } while (results != null && results.Count > 0);

            if (tailResultQueue.Count > 0)
            {
                // Respect the ReadCount parameter.
                // Output single object when ReadCount == 1; Output array otherwise
                int count = 0;
                if (ReadCount <= 0 || (ReadCount >= tailResultQueue.Count && ReadCount != 1))
                {
                    count = tailResultQueue.Count;

                    // Write out the content as an array of objects
                    WriteContentObject(tailResultQueue.ToArray(), count, holder.PathInfo, currentContext);
                }
                else if (ReadCount == 1)
                {
                    // Write out the content as single object
                    while (tailResultQueue.Count > 0)
                    {
                        WriteContentObject(tailResultQueue.Dequeue(), count++, holder.PathInfo, currentContext);
                    }
                }
                else // ReadCount < Queue.Count
                {
                    while (tailResultQueue.Count >= ReadCount)
                    {
                        List<object> outputList = new((int)ReadCount);
                        for (int idx = 0; idx < ReadCount; idx++, count++)
                        {
                            outputList.Add(tailResultQueue.Dequeue());
                        }

                        // Write out the content as an array of objects
                        WriteContentObject(outputList.ToArray(), count, holder.PathInfo, currentContext);
                    }

                    if (tailResultQueue.Count > 0)
                    {
                        // Write out the content as an array of objects
                        WriteContentObject(tailResultQueue.ToArray(), count, holder.PathInfo, currentContext);
                    }
                }
            }

            if (error != null)
            {
                WriteError(error);
                return false;
            }

            return true;
        }

        /// <summary>
        /// Seek position to the right place.
        /// </summary>
        /// <param name="reader">
        /// reader should be able to be casted to FileSystemContentReader
        /// </param>
        /// <returns>
        /// true if the stream pointer is moved to the right place
        /// false if we cannot seek
        /// </returns>
        private bool SeekPositionForTail(IContentReader reader)
        {
            var fsReader = reader as FileSystemContentReaderWriter;
            Dbg.Diagnostics.Assert(fsReader != null, "Tail is only supported for FileSystemContentReaderWriter");

            try
            {
                fsReader.SeekItemsBackward(Tail);
                return true;
            }
            catch (BackReaderEncodingNotSupportedException)
            {
                // Move to the head
                fsReader.Seek(0, SeekOrigin.Begin);
                return false;
            }
        }

        /// <summary>
        /// Be sure to clean up.
        /// </summary>
        protected override void EndProcessing()
        {
            Dispose(true);
        }
        #endregion Command code

    }
}