This repository was archived by the owner on Mar 5, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathTextTableParser.cs
More file actions
453 lines (402 loc) · 14.8 KB
/
Copy pathTextTableParser.cs
File metadata and controls
453 lines (402 loc) · 14.8 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Management.Automation;
using System.Text.Json;
namespace TextTableParser
{
public class ColumnInfo {
public int Start;
public int Length;
public int SpaceLength;
}
public class HeaderField {
public string Name;
public int Start;
public int Length;
}
public class ObjectPropertyInfo {
public HeaderField[] HeaderFields;
ObjectPropertyInfo(string line, ColumnInfo[] cInfos)
{
HeaderFields = new HeaderField[cInfos.Length];
for(int i = 0; i < cInfos.Length; i++)
{
HeaderFields[i] = new HeaderField(){
Name = line.Substring(cInfos[i].Start, cInfos[i].Length).Trim(),
Start = cInfos[i].Start,
Length = cInfos[i].Length
};
}
}
}
[Cmdlet("ConvertFrom","TextTable")]
public class ConvertTextTableCommand : PSCmdlet
{
[Parameter()]
public int MaximumWidth { get; set; } = 200;
[Parameter()]
public int AnalyzeRowCount { get; set; } = 0; // 0 is all
[Parameter(ValueFromPipeline=true,Mandatory=true,Position=0)]
[AllowEmptyString()]
public string[] Line { get; set; }
[Parameter()]
public int Skip { get; set; } = 0;
[Parameter()]
public SwitchParameter NoHeader { get; set; }
[Parameter()]
public SwitchParameter AsJson { get; set; }
[Parameter()]
public int[] ColumnOffset { get; set; }
[Parameter()]
public SwitchParameter ConvertPropertyValue { get; set; }
[Parameter()]
public int HeaderLine { get; set; } = 0; // Assume the first line is the header
[Parameter()]
public string[] TypeName { get; set; }
private List<string>Lines = new List<string>();
private int SkippedLines = 0;
protected override void BeginProcessing()
{
if (NoHeader)
{
HeaderLine = -1;
}
}
private int[] SpaceArray;
private string spaceRepresentation;
private bool Analyzed = false;
protected override void ProcessRecord()
{
if (Line is null)
{
return;
}
foreach(string _line in Line)
{
// don't add empty lines
if(string.IsNullOrEmpty(_line))
{
continue;
}
// add the line to the list if we've skipped enough lines
if (SkippedLines++ >= Skip)
{
Lines.Add(_line);
}
if (AnalyzeRowCount == 0)
{
continue;
}
// We've done the analysis, so just emit the object or json.
if(Analyzed)
{
Emit(_line);
continue;
}
if (Lines.Count == 0) { continue; }
// We've collected enough lines to analyze
// analyze what we have and then emit them, set the analyzed flag so we will just emit from now on.
if (! Analyzed && Lines.Count > AnalyzeRowCount)
{
AnalyzeLines(Lines);
Analyzed = true;
foreach(string l in Lines)
{
Emit(l);
}
Lines.Clear(); // unneeded
// Calculate the column widths
}
}
}
protected override void EndProcessing()
{
if (Lines.Count == 0) { return; }
if (!Analyzed)
{
AnalyzeLines(Lines);
foreach(string _line in Lines)
{
Emit(_line);
}
}
}
private void Emit(string line)
{
if (ColumnInfoList != null && columnHeaders != null)
{
if (AsJson)
{
var jsonOptions = new JsonSerializerOptions();
jsonOptions.MaxDepth = 1;
WriteObject(GetJson(ColumnInfoList, line, columnHeaders));
}
else
{
WriteObject(GetPsObject(ColumnInfoList, line, columnHeaders));
}
}
else
{
WriteError(new ErrorRecord(new Exception("No column info"), "NoColumnInfo", ErrorCategory.InvalidOperation, null));
}
}
private List<ColumnInfo> ColumnInfoList { get; set; }
private string[] columnHeaders { get; set; }
private void AnalyzeLines(List<string> lines)
{
if (lines.Count == 0)
{
return;
}
SpaceArray = AnalyzeColumns(Lines);
spaceRepresentation = GetSpaceRepresentation(Lines.Count, SpaceArray);
if (ColumnOffset != null)
{
ColumnInfoList = GetColumnList(ColumnOffset);
}
else
{
ColumnInfoList = GetColumnList(Lines.Count, SpaceArray);
}
if (NoHeader)
{
columnHeaders = new string[ColumnInfoList.Count];
for(int i = 0; i < ColumnInfoList.Count; i++)
{
columnHeaders[i] = string.Format("Property_{0:00}", i+1);
}
}
else
{
columnHeaders = GetHeaderColumns(ColumnInfoList, Lines[HeaderLine]);
Lines.RemoveAt(HeaderLine);
}
}
private string GetSpaceRepresentation(int count, int[] spaceArray)
{
char[] spaceChars = new char[spaceArray.Length];
for(int i = 0; i < spaceArray.Length; i++)
{
if (spaceArray[i] == count)
{
spaceChars[i] = 'S';
}
else
{
spaceChars[i] = ' ';
}
}
return new string(spaceChars);
}
public PSObject GetPsObject(List<ColumnInfo> cInfos, string line, string[] columnHeaders)
{
PSObject o = new PSObject();
if (TypeName != null)
{
foreach (string t in TypeName)
{
o.TypeNames.Insert(0, t);
}
}
object[]data = GetObjectColumnData(cInfos, line);
Debug.Assert(data.Length == columnHeaders.Length);
for(int i = 0; i < cInfos.Count; i++)
{
o.Properties.Add(new PSNoteProperty(columnHeaders[i], data[i]));
}
return o;
}
public string GetJson(List<ColumnInfo> cInfos, string line, string[] columnHeaders)
{
string[]data = GetStringColumnData(cInfos, line);
Debug.Assert(data.Length == columnHeaders.Length);
string[]dataWithHeader = new string[data.Length];
for(int j = 0; j < data.Length; j++)
{
if (data[j] is string)
{
dataWithHeader[j] = string.Format("\"{0}\": \"{1}\"", columnHeaders[j], JsonEncodedText.Encode(data[j]));
}
else
{
dataWithHeader[j] = string.Format("\"{0}\": \"{1}\"", columnHeaders[j], (JsonEncodedText.Encode((string)data[j])));
}
}
return string.Format("{{ {0} }}", string.Join(", ", dataWithHeader));
}
private object[] GetObjectColumnData(List<ColumnInfo> cInfos, string line)
{
object[] data = new object[cInfos.Count];
for(int i = 0; i < cInfos.Count; i++)
{
string value;
if (cInfos[i].Length == -1) // end of line
{
value = line.Substring(cInfos[i].Start).Trim();
}
else
{
value = line.Substring(cInfos[i].Start, cInfos[i].Length).Trim();
}
// If ConvertPropertyValue is specified, try to convert to int, int64, decimal, datetime, or timespan.
if (! ConvertPropertyValue)
{
data[i] = value;
}
else if (LanguagePrimitives.TryConvertTo<int>(value, out int intValue))
{
data[i] = intValue;
}
else if (LanguagePrimitives.TryConvertTo<Int64>(value, out Int64 int64Value))
{
data[i] = int64Value;
}
else if (LanguagePrimitives.TryConvertTo<Decimal>(value, out Decimal decimalValue))
{
data[i] = decimalValue;
}
else if (LanguagePrimitives.TryConvertTo<DateTime>(value, out DateTime dateTimeValue))
{
data[i] = dateTimeValue;
}
else if (LanguagePrimitives.TryConvertTo<TimeSpan>(value, out TimeSpan timeSpanValue))
{
data[i] = timeSpanValue;
}
else if (LanguagePrimitives.TryConvertTo<TimeSpan>(string.Format("0:{0}", value), out TimeSpan exTimeSpanValue))
{
data[i] = exTimeSpanValue;
}
else
{
data[i] = value;
}
}
return data;
}
// This will return the data in the columns as an array of objects.
// We will try to convert the data to a type that makes sense.
private string[] GetStringColumnData(List<ColumnInfo> cInfos, string line)
{
string[] data = new string[cInfos.Count];
for(int i = 0; i < cInfos.Count; i++)
{
string value;
if (cInfos[i].Length == -1) // end of line
{
value = line.Substring(cInfos[i].Start).Trim();
}
else
{
value = line.Substring(cInfos[i].Start, cInfos[i].Length).Trim();
}
data[i] = value;
}
return data;
}
private string[] GetHeaderColumns(List<ColumnInfo> cInfos, string line)
{
string[] columns = new string[cInfos.Count];
for(int i = 0; i < cInfos.Count; i++)
{
if (cInfos[i].Length == -1) // end of line
{
columns[i] = line.Substring(cInfos[i].Start).Trim().Replace(" ", "_");
}
else
{
columns[i] = line.Substring(cInfos[i].Start, cInfos[i].Length).Trim().Replace(" ", "_");
}
}
return columns;
}
private int GetMaxLength(List<string>lines)
{
int maximumLength = 0;
foreach(string line in lines)
{
if (line.Length > maximumLength)
{
maximumLength = line.Length;
}
}
return maximumLength;
}
// Analyze for white space. If we find consistent white space,
// then we can use that to determine the columns.
// If the value in the array element is the same as the number of lines,
// we have a column.
private int[] AnalyzeColumns(List<string>lines)
{
int maximumLength = GetMaxLength(lines);
int[] SpaceArray = new int[maximumLength];
for(int i = 0; i < maximumLength; i++)
{
SpaceArray[i] = 0;
}
foreach(string line in lines)
{
for(int i = 0; i < line.Length; i++)
{
if(char.IsWhiteSpace(line[i]))
{
SpaceArray[i] += 1;
}
}
}
return SpaceArray;
}
private List<ColumnInfo> GetColumnList(int[]StartColumns)
{
List<ColumnInfo> ColumnInfoList = new List<ColumnInfo>();
for(int i = 0; i < StartColumns.Length; i++)
{
int length;
try
{
length = StartColumns[i+1] - StartColumns[i];
}
catch
{
length = -1;
}
ColumnInfoList.Add(new ColumnInfo() { Start = StartColumns[i], Length = length, SpaceLength = 0 });
}
return ColumnInfoList;
}
// Get the column list from the space array.
private List<ColumnInfo> GetColumnList(int count, int[]SpaceArray)
{
List<ColumnInfo> ColumnInfoList = new List<ColumnInfo>();
for(int i = 0; i < SpaceArray.Length; i++) {
ColumnInfoList.Add(
new ColumnInfo() { Start = i, Length = 0, SpaceLength = 0 }
);
// Chew up the spaces
while (i < SpaceArray.Length && SpaceArray[i] == count)
{
ColumnInfoList[ColumnInfoList.Count - 1].SpaceLength++;
ColumnInfoList[ColumnInfoList.Count - 1].Length++;
i++;
}
// chew up the non spaces or end of line
while(i < SpaceArray.Length && SpaceArray[i] != count)
{
ColumnInfoList[ColumnInfoList.Count - 1].Length++;
i++;
}
int totalLength = ColumnInfoList[ColumnInfoList.Count-1].Length + ColumnInfoList[ColumnInfoList.Count-1].Start;
if (totalLength >= SpaceArray.Length)
{
ColumnInfoList[ColumnInfoList.Count - 1].Length = -1;
}
i--;
}
return ColumnInfoList;
}
}
}