SingleRecordFormatter: escape whitespace characters in the same way as in TabularFormatter
3 * Copyright © 2013 František Kučera (frantovo.cz)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package info.globalcode.sql.dk.formatting;
20 import info.globalcode.sql.dk.ColorfulPrintWriter;
21 import static info.globalcode.sql.dk.ColorfulPrintWriter.*;
22 import info.globalcode.sql.dk.Functions;
23 import static info.globalcode.sql.dk.Functions.lpad;
24 import static info.globalcode.sql.dk.Functions.rpad;
25 import static info.globalcode.sql.dk.Functions.repeat;
26 import info.globalcode.sql.dk.configuration.PropertyDeclaration;
27 import static info.globalcode.sql.dk.formatting.CommonProperties.COLORFUL;
28 import static info.globalcode.sql.dk.formatting.CommonProperties.COLORFUL_DESCRIPTION;
29 import java.util.List;
33 * Prints human-readable output – tables of result sets and text messages with update counts.
37 * Longer values might break the table – overflow the cells – see alternative tabular formatters
38 * and the {@linkplain #PROPERTY_TRIM} property.
41 * @author Ing. František Kučera (frantovo.cz)
42 * @see TabularPrefetchingFormatter
43 * @see TabularWrappingFormatter
45 @PropertyDeclaration(name = COLORFUL, defaultValue = "true", type = Boolean.class, description = COLORFUL_DESCRIPTION)
46 @PropertyDeclaration(name = TabularFormatter.PROPERTY_ASCII, defaultValue = "false", type = Boolean.class, description = "whether to use ASCII table borders instead of unicode ones")
47 @PropertyDeclaration(name = TabularFormatter.PROPERTY_TRIM, defaultValue = "false", type = Boolean.class, description = "whether to trim the values to fit the column width")
48 public class TabularFormatter extends AbstractFormatter {
50 public static final String NAME = "tabular"; // bash-completion:formatter
51 private static final String HEADER_TYPE_PREFIX = " (";
52 private static final String HEADER_TYPE_SUFFIX = ")";
53 public static final String PROPERTY_ASCII = "ascii";
54 public static final String PROPERTY_TRIM = "trim";
55 protected ColorfulPrintWriter out;
56 private boolean firstResult = true;
57 private int[] columnWidth;
59 * use ASCII borders instead of unicode ones
61 private final boolean asciiNostalgia;
63 * Trim values if they are longer than cell size
65 private final boolean trimValues;
67 public TabularFormatter(FormatterContext formatterContext) {
68 super(formatterContext);
69 out = new ColorfulPrintWriter(formatterContext.getOutputStream());
70 asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
71 trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
72 out.setColorful(formatterContext.getProperties().getBoolean(COLORFUL, true));
76 public void writeStartResultSet(ColumnsHeader header) {
77 super.writeStartResultSet(header);
78 printResultSeparator();
80 initColumnWidths(header.getColumnCount());
83 printTableBorder("╭");
85 List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
87 for (ColumnDescriptor cd : columnDescriptors) {
88 // padding: make header cell at least same width as data cells in this column
89 int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
90 cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
91 updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
93 if (!cd.isFirstColumn()) {
94 printTableBorder("┬");
96 printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
98 printTableBorder("╮");
101 for (ColumnDescriptor cd : columnDescriptors) {
102 if (cd.isFirstColumn()) {
104 printTableBorder("│ ");
106 printTableBorder(" │ ");
108 out.print(TerminalStyle.Bright, cd.getLabel());
109 out.print(HEADER_TYPE_PREFIX);
110 out.print(cd.getTypeName());
111 out.print(HEADER_TYPE_SUFFIX);
112 if (cd.isLastColumn()) {
113 printTableBorder(" │");
119 printTableBorder("├");
120 for (int i = 1; i <= header.getColumnCount(); i++) {
122 printTableBorder("┼");
124 printTableBorder(repeat('─', getColumnWidth(i) + 2));
126 printTableBorder("┤");
133 * Must be called before
134 * {@linkplain #updateColumnWidth(int, int)}
135 * and {@linkplain #getColumnWidth(int)}
136 * for each result set.
138 * @param columnCount number of columns in current result set
140 protected void initColumnWidths(int columnCount) {
141 if (columnWidth == null) {
142 columnWidth = new int[columnCount];
146 protected void cleanColumnWidths() {
151 public void writeColumnValue(Object value) {
152 super.writeColumnValue(value);
153 writeColumnValueInternal(value);
156 protected void writeColumnValueInternal(Object value) {
158 if (isCurrentColumnFirst()) {
160 printTableBorder("│ ");
162 printTableBorder(" │ ");
165 Functions.printValueWithWhitespaceReplaced(out, toString(value), TerminalColor.Cyan, TerminalColor.Red);
167 if (isCurrentColumnLast()) {
168 printTableBorder(" │");
173 protected int getColumnWidth(int columnNumber) {
174 return columnWidth[columnNumber - 1];
177 private void setColumnWidth(int columnNumber, int width) {
178 columnWidth[columnNumber - 1] = width;
181 protected void updateColumnWidth(int columnNumber, int width) {
182 int oldWidth = getColumnWidth(columnNumber);
183 setColumnWidth(columnNumber, Math.max(width, oldWidth));
187 protected String toString(Object value) {
188 final int width = getColumnWidth(getCurrentColumnsCount());
190 if (value instanceof Number || value instanceof Boolean) {
191 result = lpad(String.valueOf(value), width);
193 result = rpad(String.valueOf(value), width);
195 // ? value = (boolean) value ? "✔" : "✗";
197 if (trimValues && result.length() > width) {
198 result = result.substring(0, width - 1) + "…";
205 public void writeEndRow() {
207 writeEndRowInternal();
210 public void writeEndRowInternal() {
216 public void writeEndResultSet() {
217 int columnCount = getCurrentColumnsHeader().getColumnCount();
218 super.writeEndResultSet();
221 printTableBorder("╰");
222 for (int i = 1; i <= columnCount; i++) {
224 printTableBorder("┴");
226 printTableBorder(repeat('─', getColumnWidth(i) + 2));
228 printTableBorder("╯");
233 out.print(TerminalColor.Yellow, "Record count: ");
234 out.println(getCurrentRowCount());
240 public void writeUpdatesResult(int updatedRowsCount) {
241 super.writeUpdatesResult(updatedRowsCount);
242 printResultSeparator();
243 out.print(TerminalColor.Red, "Updated records: ");
244 out.println(updatedRowsCount);
250 public void writeEndDatabase() {
251 super.writeEndDatabase();
255 private void printResultSeparator() {
263 protected void printTableBorder(String border) {
264 if (asciiNostalgia) {
265 border = border.replaceAll("─", "-");
266 border = border.replaceAll("│", "|");
267 border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
270 out.print(TerminalColor.Green, border);
273 protected void printTableIndent() {