-
Notifications
You must be signed in to change notification settings - Fork 368
/
PlainTextSummaryFormatter.cs
103 lines (81 loc) · 2.9 KB
/
PlainTextSummaryFormatter.cs
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
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
namespace Microsoft.DotNet.Interactive.Formatting;
public static class PlainTextSummaryFormatter
{
// FIX: (PlainTextSummaryFormatter) rename this
public const string MimeType = "text/plain+summary";
public static ITypeFormatter GetPreferredFormatterFor(Type type)
{
return Formatter.GetPreferredFormatterFor(type, MimeType);
}
internal static ITypeFormatter[] DefaultFormatters { get; } =
{
new AnonymousTypeFormatter<Type>((value, context) =>
{
var formatter = PlainTextFormatter.GetPreferredFormatterFor<Type>();
return formatter.Format(value, context);
}, MimeType),
new AnonymousTypeFormatter<string>((value, context) =>
{
if (value is null)
{
context.Writer.Write(Formatter.NullString);
return true;
}
context.Writer.Write(Truncate(value));
return true;
}, MimeType),
new AnonymousTypeFormatter<IEnumerable>((obj, context) =>
{
if (obj is null)
{
context.Writer.Write(Formatter.NullString);
return true;
}
var type = obj.GetType();
var formatter = FormattersForAnyEnumerable.GetOrCreateFormatterForType(type);
context.DisableRecursion();
var result = formatter.Format(obj, context);
context.EnableRecursion();
return result;
}, MimeType),
new AnonymousTypeFormatter<object>((value, context) =>
{
if (value is null)
{
context.Writer.Write(Formatter.NullString);
}
else
{
try
{
context.Writer.Write(Truncate(value));
}
catch (Exception exception)
{
var formatter = GetPreferredFormatterFor(exception.GetType());
formatter.Format(exception, context);
}
}
return true;
}, MimeType)
};
private static string Truncate(object value)
{
var formatted = value.ToString()
.Trim()
.Replace("\r", "\\r")
.Replace("\n", "\\n");
var length = 300;
if (formatted.Length > length)
{
formatted = formatted[..length] + "...";
}
return formatted;
}
internal static FormatterMapByType FormattersForAnyEnumerable =
new(typeof(PlainTextFormatter<>), nameof(PlainTextFormatter<object>.CreateForAnyEnumerable));
}