-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOutputFormatter.cs
More file actions
193 lines (166 loc) · 5.34 KB
/
OutputFormatter.cs
File metadata and controls
193 lines (166 loc) · 5.34 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
using System.Text;
using System.Text.Json;
namespace DbCli;
public enum OutputFormat
{
Json,
Table,
Csv
}
public static class OutputFormatter
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
public static string Format(List<Dictionary<string, object>> data, OutputFormat format)
{
return format switch
{
OutputFormat.Json => FormatJson(data),
OutputFormat.Table => FormatTable(data),
OutputFormat.Csv => FormatCsv(data),
_ => FormatJson(data)
};
}
public static string FormatResult(int affectedRows, OutputFormat format)
{
var result = new { AffectedRows = affectedRows, Success = true };
return format switch
{
OutputFormat.Json => JsonSerializer.Serialize(result, JsonOptions),
OutputFormat.Table => $"Affected Rows: {affectedRows}",
OutputFormat.Csv => $"AffectedRows\n{affectedRows}",
_ => JsonSerializer.Serialize(result, JsonOptions)
};
}
public static string FormatError(string message, OutputFormat format)
{
var result = new { Error = message, Success = false };
return format switch
{
OutputFormat.Json => JsonSerializer.Serialize(result, JsonOptions),
OutputFormat.Table => $"Error: {message}",
OutputFormat.Csv => $"Error\n\"{message.Replace("\"", "\"\"")}\"",
_ => JsonSerializer.Serialize(result, JsonOptions)
};
}
private static string FormatJson(List<Dictionary<string, object>> data)
{
return JsonSerializer.Serialize(data, JsonOptions);
}
private static string FormatTable(List<Dictionary<string, object>> data)
{
if (data.Count == 0)
return "(No rows returned)";
var columns = data[0].Keys.ToList();
var columnWidths = new Dictionary<string, int>();
foreach (var col in columns)
{
columnWidths[col] = col.Length;
}
foreach (var row in data)
{
foreach (var col in columns)
{
var value = row[col]?.ToString() ?? "NULL";
columnWidths[col] = Math.Max(columnWidths[col], GetDisplayWidth(value));
}
}
foreach (var col in columns)
{
columnWidths[col] = Math.Min(columnWidths[col], 50);
}
var sb = new StringBuilder();
var separator = "+" + string.Join("+", columns.Select(c => new string('-', columnWidths[c] + 2))) + "+";
sb.AppendLine(separator);
sb.Append("|");
foreach (var col in columns)
{
sb.Append($" {PadRight(col, columnWidths[col])} |");
}
sb.AppendLine();
sb.AppendLine(separator);
foreach (var row in data)
{
sb.Append("|");
foreach (var col in columns)
{
var value = Truncate(row[col]?.ToString() ?? "NULL", 50);
sb.Append($" {PadRight(value, columnWidths[col])} |");
}
sb.AppendLine();
}
sb.AppendLine(separator);
sb.AppendLine($"({data.Count} row(s))");
return sb.ToString();
}
private static string FormatCsv(List<Dictionary<string, object>> data)
{
if (data.Count == 0)
return string.Empty;
var columns = data[0].Keys.ToList();
var sb = new StringBuilder();
sb.AppendLine(string.Join(",", columns.Select(EscapeCsv)));
foreach (var row in data)
{
var values = columns.Select(c => EscapeCsv(row[c]?.ToString() ?? ""));
sb.AppendLine(string.Join(",", values));
}
return sb.ToString();
}
private static string EscapeCsv(string value)
{
if (value.Contains(',') || value.Contains('"') || value.Contains('\n') || value.Contains('\r'))
{
return $"\"{value.Replace("\"", "\"\"")}\"";
}
return value;
}
private static int GetDisplayWidth(string s)
{
int width = 0;
foreach (var c in s)
{
width += c > 127 ? 2 : 1;
}
return width;
}
private static string PadRight(string s, int totalWidth)
{
var currentWidth = GetDisplayWidth(s);
if (currentWidth >= totalWidth)
return s;
return s + new string(' ', totalWidth - currentWidth);
}
private static string Truncate(string s, int maxLength)
{
if (GetDisplayWidth(s) <= maxLength)
return s;
var result = new StringBuilder();
int width = 0;
foreach (var c in s)
{
var charWidth = c > 127 ? 2 : 1;
if (width + charWidth > maxLength - 3)
{
result.Append("...");
break;
}
result.Append(c);
width += charWidth;
}
return result.ToString();
}
public static OutputFormat ParseFormat(string format)
{
return format.ToLower() switch
{
"json" => OutputFormat.Json,
"table" => OutputFormat.Table,
"csv" => OutputFormat.Csv,
_ => OutputFormat.Json
};
}
}