Skip to content

Commit

Permalink
Support CSV format in @table output
Browse files Browse the repository at this point in the history
  • Loading branch information
dblevins committed Feb 3, 2024
1 parent e783cfc commit e18e4e0
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -205,4 +205,12 @@ public enum Border {
* </pre>
*/
tsv,

/**
* id,project,releaseDate,version
* 9,Apache TomEE,A2016-05-17,A7.0.x
* 523456789,ATomcat,A2018-01-17,A9.0.x
* 14,AApache ActiveMQ Classic,A2022-03-09,A5.17.x
*/
csv,
}
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,35 @@ public static Border.Builder tsv() {
.escape(s -> s.replace("\t", " "));
}

public static Border.Builder csv() {
return builder()
.first(null)
.header(null)
.inner(null)
.row(Line.builder().left("").inner(",").right("").padded(false))
.last(null)
.escape(string -> {
/*
* Check if input contains commas, double quotes, or newlines
*/
if (string.contains(",") || string.contains("\"") || string.contains("\n")) {

/* Double any internal double quotes */
final String escapedInput = string.replace("\"", "\"\"");

/* Enclose in double quotes */
return "\"" + escapedInput + "\"";

} else {

return string;
}
});
}




public static Builder builder() {
return new Builder();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,33 @@ public void tsvEscaping() {
"This is a row with only one cell\t\t\t\n", actual);
}

@Test
public void csv() {
assertTable(Border::csv, "" +
"Col1,Col2,Col3,Numeric Column\n" +
"Value 1,Value 2,123,10.0\n" +
"Separate,cols,with a tab or 4 spaces,\"-2,027.1\"\n" +
"This is a row with only one cell,,,\n");
}

@Test
public void csvEscaping() {
final Data data = Data.builder().headings(true)
.row("Col1", "Col2", "Col3", "Numeric Column")
.row("Value,1", "Value \"2", "123", "10.0")
.row("Separate", "cols", "with a \"tab\" or, 4 spaces", "-2,027.1")
.row("This is a row with only one cell")
.build();

final Table table = new Table(data, ((Supplier<Border.Builder>) Border::csv).get().build(), 300);
final String actual = table.format();
Assert.assertEquals("" +
"Col1,Col2,Col3,Numeric Column\n" +
"\"Value,1\",\"Value \"\"2\",123,10.0\n" +
"Separate,cols,\"with a \"\"tab\"\" or, 4 spaces\",\"-2,027.1\"\n" +
"This is a row with only one cell,,,\n", actual);
}


public void assertTable(final Supplier<Border.Builder> border, final String expected) {
final Table table = new Table(data, border.get().build(), 300);
Expand Down

0 comments on commit e18e4e0

Please sign in to comment.