forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetContentCommand.cs
More file actions
450 lines (395 loc) · 17.4 KB
/
Copy pathGetContentCommand.cs
File metadata and controls
450 lines (395 loc) · 17.4 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
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 = "http://go.microsoft.com/fwlink/?LinkID=113310")]
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
{
return readCount;
} // get
set
{
readCount = value;
}
} // ReadCount
/// <summary>
/// The number of content items to retrieve. By default this
/// value is -1 which means read all the content
/// </summary>
///
[Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("First", "Head")]
public long TotalCount
{
get
{
return totalCount;
} // get
set
{
totalCount = value;
_totalCountSpecified = true;
}
} // TotalCount
private bool _totalCountSpecified = false;
/// <summary>
/// The number of content items to retrieve from the back of the file.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("Last")]
public int Tail
{
set
{
_backCount = value;
_tailSpecified = true;
}
get { return _backCount; }
}
private int _backCount = -1;
private bool _tailSpecified = false;
/// <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);
} // GetDynamicParameters
#endregion Parameters
#region parameter data
/// <summary>
/// The number of content items to retrieve per block.
/// </summary>
private long readCount = 1;
/// <summary>
/// The number of content items to retrieve.
/// </summary>
private long totalCount = -1;
#endregion parameter data
#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 (_totalCountSpecified && _tailSpecified)
{
string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "TotalCount", "Tail");
ErrorRecord error = new ErrorRecord(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 (_tailSpecified && !(holder.Reader is FileSystemContentReaderWriter))
{
string errMsg = SessionStateStrings.GetContent_TailNotSupported;
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "TailNotSupported", ErrorCategory.InvalidOperation, Tail);
WriteError(error);
continue;
}
// If Tail is negative, 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)
{
CommandsCommon.CheckForSevereException(this, e);
ProviderInvocationException providerException =
new ProviderInvocationException(
"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;
}
}
if (TotalCount != 0)
{
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) && (TotalCount - countToRead < countRead))
{
countToRead = TotalCount - countRead;
}
try
{
results = holder.Reader.Read(countToRead);
}
catch (Exception e) // Catch-all OK. 3rd party callout
{
CommandsCommon.CheckForSevereException(this, e);
ProviderInvocationException providerException =
new ProviderInvocationException(
"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 < 0) || countRead < TotalCount));
}
} // foreach holder in contentStreams
}
finally
{
// close all the content readers
CloseContent(contentStreams, false);
// Empty the content holder array
contentStreams = new List<ContentHolder>();
}
} // ProcessRecord
/// <summary>
/// Scan forwards to get the tail content
/// </summary>
/// <param name="holder"></param>
/// <param name="currentContext"></param>
/// <returns>
/// true if no error occured
/// false if there was an error
/// </returns>
private bool ScanForwardsForTail(ContentHolder holder, CmdletProviderContext currentContext)
{
var fsReader = holder.Reader as FileSystemContentReaderWriter;
Dbg.Diagnostics.Assert(fsReader != null, "Tail is only supported for FileSystemContentReaderWriter");
var tailResultQueue = new Queue<object>();
IList results = null;
ErrorRecord error = null;
do
{
try
{
results = fsReader.ReadWithoutWaitingChanges(ReadCount);
}
catch (Exception e)
{
CommandsCommon.CheckForSevereException(this, e);
ProviderInvocationException providerException =
new ProviderInvocationException(
"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 recrod 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;
ArrayList outputList = new ArrayList();
while (tailResultQueue.Count > 0)
{
outputList.Add(tailResultQueue.Dequeue());
}
// Write out the content as an array of objects
WriteContentObject(outputList.ToArray(), count, holder.PathInfo, currentContext);
}
else if (ReadCount == 1)
{
// Write out the contnet as single object
while (tailResultQueue.Count > 0)
WriteContentObject(tailResultQueue.Dequeue(), count++, holder.PathInfo, currentContext);
}
else // ReadCount < Queue.Count
{
while (tailResultQueue.Count >= ReadCount)
{
ArrayList outputList = new ArrayList();
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);
}
int remainder = tailResultQueue.Count;
if (remainder > 0)
{
ArrayList outputList = new ArrayList();
for (; remainder > 0; remainder--, count++)
outputList.Add(tailResultQueue.Dequeue());
// Write out the content as an array of objects
WriteContentObject(outputList.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
} // GetContentCommand
} // namespace Microsoft.PowerShell.Commands