forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDefaultScripts.Text.cs
More file actions
491 lines (412 loc) · 18.5 KB
/
DefaultScripts.Text.cs
File metadata and controls
491 lines (412 loc) · 18.5 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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Text;
namespace ServiceStack.Script
{
// ReSharper disable InconsistentNaming
public class MarkdownTable
{
public bool IncludeHeaders { get; set; } = true;
public bool IncludeRowNumbers { get; set; } = true;
public string Caption { get; set; }
public List<string> Headers { get; } = new List<string>();
public List<List<string>> Rows { get; } = new List<List<string>>();
public string Render()
{
if (Rows.Count == 0)
return null;
var sb = StringBuilderCache.Allocate();
var headersCount = Headers.Count;
var colSize = new int[headersCount];
var i=0;
var rowNumLength = IncludeRowNumbers ? (Rows.Count + 1).ToString().Length : 0;
var noOfCols = IncludeHeaders && headersCount > 0
? headersCount
: Rows[0].Count;
for (; i < noOfCols; i++)
{
colSize[i] = IncludeHeaders && i < headersCount
? Headers[i].Length
: 0;
foreach (var row in Rows)
{
var rowLen = i < row.Count ? row[i]?.Length ?? 0 : 0;
if (rowLen > colSize[i])
colSize[i] = rowLen;
}
}
if (!string.IsNullOrEmpty(Caption))
{
sb.AppendLine(Caption)
.AppendLine();
}
if (IncludeHeaders && headersCount > 0)
{
sb.Append("| ");
if (IncludeRowNumbers)
{
sb.Append("#".PadRight(rowNumLength, ' '))
.Append(" | ");
}
for (i = 0; i < headersCount; i++)
{
var header = Headers[i];
sb.Append(header.PadRight(colSize[i], ' '))
.Append( i + 1 < headersCount ? " | " : " |");
}
sb.AppendLine();
sb.Append("|-");
if (IncludeRowNumbers)
{
sb.Append("".PadRight(rowNumLength, '-'))
.Append("-|-");
}
for (i = 0; i < headersCount; i++)
{
sb.Append("".PadRight(colSize[i], '-'))
.Append( i + 1 < headersCount ? "-|-" : "-|");
}
sb.AppendLine();
}
for (var rowIndex = 0; rowIndex < Rows.Count; rowIndex++)
{
var row = Rows[rowIndex];
sb.Append("| ");
if (IncludeRowNumbers)
{
sb.Append($"{rowIndex + 1}".PadRight(rowNumLength, ' '))
.Append(" | ");
}
for (i = 0; i < headersCount; i++)
{
var field = i < row.Count ? row[i] : null;
sb.Append((field ?? "").PadRight(colSize[i], ' '))
.Append( i + 1 < headersCount ? " | " : " |");
}
sb.AppendLine();
}
sb.AppendLine();
return StringBuilderCache.ReturnAndFree(sb);
}
}
public partial class DefaultScripts
{
public IRawString textList(IEnumerable target) => TextList(target, new TextDumpOptions { Defaults = Context.DefaultMethods }).ToRawString();
public IRawString textList(IEnumerable target, Dictionary<string, object> options) =>
TextList(target, TextDumpOptions.Parse(options, Context.DefaultMethods)).ToRawString();
public IRawString textDump(object target) => TextDump(target, new TextDumpOptions { Defaults = Context.DefaultMethods }).ToRawString();
public IRawString textDump(object target, Dictionary<string, object> options) =>
TextDump(target, TextDumpOptions.Parse(options, Context.DefaultMethods)).ToRawString();
public static string TextList(IEnumerable items, TextDumpOptions options)
{
if (options == null)
options = new TextDumpOptions();
if (items is IDictionary<string, object> single)
items = new[] { single };
var depth = options.Depth;
options.Depth += 1;
try
{
var headerStyle = options.HeaderStyle;
List<string> keys = null;
var table = new MarkdownTable {
IncludeRowNumbers = options.IncludeRowNumbers
};
foreach (var item in items)
{
if (item is IDictionary<string, object> d)
{
if (keys == null)
{
keys = d.Keys.ToList();
foreach (var key in keys)
{
table.Headers.Add(ViewUtils.StyleText(key, headerStyle));
}
}
var row = new List<string>();
foreach (var key in keys)
{
var value = d[key];
if (ReferenceEquals(value, items)) break; // Prevent cyclical deps like 'it' binding
if (!isComplexType(value))
{
row.Add(GetScalarText(value, options.Defaults));
}
else
{
var cellValue = TextDump(value, options);
row.Add(cellValue);
}
}
table.Rows.Add(row);
}
}
var isEmpty = table.Rows.Count == 0;
if (isEmpty)
return options.CaptionIfEmpty ?? string.Empty;
var caption = options.Caption;
if (caption != null && !options.HasCaption)
{
table.Caption = caption;
options.HasCaption = true;
}
var txt = table.Render();
return txt;
}
finally
{
options.Depth = depth;
}
}
public static string TextDump(object target, TextDumpOptions options)
{
if (options == null)
options = new TextDumpOptions();
var depth = options.Depth;
options.Depth += 1;
try
{
target = ConvertDumpType(target);
if (!isComplexType(target))
return GetScalarText(target, options.Defaults);
var headerStyle = options.HeaderStyle;
if (target is IEnumerable e)
{
var objs = e.Map(x => x);
var isEmpty = objs.Count == 0;
if (isEmpty)
return options.CaptionIfEmpty ?? string.Empty;
var first = objs[0];
if (first is IDictionary && objs.Count > 1)
return TextList(objs, options);
var sb = StringBuilderCacheAlt.Allocate();
string writeCaption = null;
var caption = options.Caption;
if (caption != null && !options.HasCaption)
{
writeCaption = caption;
options.HasCaption = true;
}
if (!isEmpty)
{
var keys = new List<string>();
var values = new List<string>();
string TextKvps(StringBuilder s, IEnumerable<KeyValuePair<string, object>> kvps)
{
foreach (var kvp in kvps)
{
if (kvp.Value == target)
break; // Prevent cyclical deps like 'it' binding
keys.Add(ViewUtils.StyleText(kvp.Key, headerStyle) ?? "");
var field = !isComplexType(kvp.Value)
? GetScalarText(kvp.Value, options.Defaults)
: TextDump(kvp.Value, options);
values.Add(field);
}
var keySize = keys.Max(x => x.Length);
var valuesSize = values.Max(x => x.Length);
s.AppendLine(writeCaption != null
? $"| {writeCaption.PadRight(keySize + valuesSize + 2, ' ')} ||"
: $"|||");
s.AppendLine(writeCaption != null
? $"|-{"".PadRight(keySize, '-')}-|-{"".PadRight(valuesSize, '-')}-|"
: "|-|-|");
for (var i = 0; i < keys.Count; i++)
{
s.Append("| ")
.Append(keys[i].PadRight(keySize, ' '))
.Append(" | ")
.Append(values[i].PadRight(valuesSize, ' '))
.Append(" |")
.AppendLine();
}
return StringBuilderCache.ReturnAndFree(s);
}
if (first is KeyValuePair<string, object>)
{
return TextKvps(sb, objs.Cast<KeyValuePair<string, object>>());
}
else
{
if (!isComplexType(first))
{
foreach (var o in objs)
{
values.Add(GetScalarText(o, options.Defaults));
}
var valuesSize = values.Max(MaxLineLength);
if (writeCaption?.Length > valuesSize)
valuesSize = writeCaption.Length;
sb.AppendLine(writeCaption != null
? $"| {writeCaption.PadRight(valuesSize)} |"
: $"||");
sb.AppendLine(writeCaption != null
? $"|-{"".PadRight(valuesSize,'-')}-|"
: "|-|");
foreach (var value in values)
{
sb.Append("| ")
.Append(value.PadRight(valuesSize, ' '))
.Append(" |")
.AppendLine();
}
}
else
{
if (objs.Count > 1)
{
if (writeCaption != null)
sb.AppendLine(writeCaption)
.AppendLine();
var rows = objs.Map(x => x.ToObjectDictionary());
var list = TextList(rows, options);
sb.AppendLine(list);
return StringBuilderCache.ReturnAndFree(sb);
}
else
{
foreach (var o in objs)
{
if (!isComplexType(o))
{
values.Add(GetScalarText(o, options.Defaults));
}
else
{
var body = TextDump(o, options);
values.Add(body);
}
}
var valuesSize = values.Max(MaxLineLength);
if (writeCaption?.Length > valuesSize)
valuesSize = writeCaption.Length;
sb.AppendLine(writeCaption != null
? $"| {writeCaption.PadRight(valuesSize, ' ')} |"
: $"||");
sb.AppendLine(writeCaption != null ? $"|-{"".PadRight(valuesSize,'-')}-|" : "|-|");
foreach (var value in values)
{
sb.Append("| ")
.Append(value.PadRight(valuesSize, ' '))
.Append(" |")
.AppendLine();
}
}
}
}
}
return StringBuilderCache.ReturnAndFree(sb);
}
return TextDump(target.ToObjectDictionary(), options);
}
finally
{
options.Depth = depth;
}
}
internal static object ConvertDumpType(object target)
{
var targetType = target.GetType();
var genericKvps = targetType.GetTypeWithGenericTypeDefinitionOf(typeof(KeyValuePair<,>));
if (genericKvps != null)
{
var keyGetter = TypeProperties.Get(targetType).GetPublicGetter("Key");
var valueGetter = TypeProperties.Get(targetType).GetPublicGetter("Value");
return new Dictionary<string, object> {
{ keyGetter(target).ConvertTo<string>(), valueGetter(target) },
};
}
if (target is IEnumerable e)
{
//Convert IEnumerable<object> to concrete generic collection so generic args can be inferred
if (e is IEnumerable<object> enumObjs)
{
Type elType = null;
foreach (var item in enumObjs)
{
elType = item.GetType();
break;
}
if (elType != null)
{
targetType = typeof(List<>).MakeGenericType(elType);
var genericList = (IList)targetType.CreateInstance();
foreach (var item in e)
{
genericList.Add(item.ConvertTo(elType));
}
target = genericList;
}
}
if (targetType.GetKeyValuePairsTypes(out var keyType, out var valueType, out var kvpType))
{
var keyGetter = TypeProperties.Get(kvpType).GetPublicGetter("Key");
var valueGetter = TypeProperties.Get(kvpType).GetPublicGetter("Value");
string key1 = null, key2 = null;
foreach (var kvp in e)
{
if (key1 == null)
{
key1 = keyGetter(kvp).ConvertTo<string>();
continue;
}
key2 = keyGetter(kvp).ConvertTo<string>();
break;
}
var isColumn = key1 == key2;
if (isColumn)
{
var to = new List<Dictionary<string, object>>();
foreach (var kvp in e)
{
to.Add(new Dictionary<string, object> { {keyGetter(kvp).ConvertTo<string>(), valueGetter(kvp) } });
}
return to;
}
return target.ToObjectDictionary();
}
}
return target;
}
private static int MaxLineLength(string s)
{
if (string.IsNullOrEmpty(s))
return 0;
var len = 0;
foreach (var line in s.ReadLines())
{
if (line.Length > len)
len = line.Length;
}
return len;
}
private static string GetScalarText(object target, DefaultScripts defaults)
{
if (target == null || target.ToString() == string.Empty)
return string.Empty;
if (target is string s)
return s;
if (target is decimal dec)
{
var isMoney = dec == Math.Floor(dec * 100);
if (isMoney)
return defaults?.currency(dec) ?? dec.ToString(defaults.GetDefaultCulture());
}
if (target.GetType().IsNumericType() || target is bool)
return target.ToString();
if (target is DateTime d)
return defaults?.dateFormat(d) ?? d.ToString(defaults.GetDefaultCulture());
if (target is TimeSpan t)
return defaults?.timeFormat(t) ?? t.ToString();
return target.ToString() ?? "";
}
private static bool isComplexType(object first)
{
return !(first == null || first is string || first.GetType().IsValueType);
}
}
}