Instantly share code, notes, and snippets.

Embed
What would you like to do?
DataGrip extractor for txt file with fixed length columns
SEPARATOR = "|"
SPACE = " "
CORNER = "+"
LINE = "-"
NEWLINE = System.getProperty("line.separator")
def outRecord(columnLengths, row, separator=SEPARATOR, padding=SPACE) {
OUT.append(separator)
[columnLengths, row].transpose().each { size, value ->
OUT.append(padding + value.padRight(size, padding) + padding + separator)
};
OUT.append(NEWLINE)
}
if (!TRANSPOSED) {
COLUMN_NAMES = COLUMNS.collect { col -> col.name() }
def formattedRows = ROWS.collect { row -> COLUMNS.collect { col -> FORMATTER.format(row, col) } }
def columnLengths = formattedRows.inject(COLUMN_NAMES.collect { col -> col.size() }, { columnLengths, row ->
[columnLengths, row.collect { it.length() }].transpose().collect { collectedSize, size -> Math.max(collectedSize, size) }
})
// OUTPUT
// HEADER
outRecord(columnLengths, COLUMNS.collect { '' }, CORNER, LINE)
outRecord(columnLengths, COLUMN_NAMES)
outRecord(columnLengths, COLUMNS.collect { '' }, CORNER, LINE)
formattedRows.each { row -> outRecord(columnLengths, row) }
outRecord(columnLengths, COLUMNS.collect { '' }, CORNER, LINE)
} else {
def formattedRows = COLUMNS.collect { col -> new ArrayList<String>([col.name()]) }
ROWS.each { row -> COLUMNS.eachWithIndex { col, i -> formattedRows[i].add(FORMATTER.format(row, col)) } }
def columnLengths = (0..formattedRows[0].size-1).collect { idx -> formattedRows.inject(0, { collectedSize, row -> Math.max(collectedSize, row[idx].length()) } ) }
// OUTPUT
outRecord(columnLengths, COLUMNS.collect { '' }, CORNER, LINE)
formattedRows.each { row -> outRecord(columnLengths, row) }
outRecord(columnLengths, COLUMNS.collect { '' }, CORNER, LINE)
}
@mvitaly

This comment has been minimized.

Owner

mvitaly commented Jul 29, 2016

Will not work well for huge output as it's not streaming, it needs to go over all the results first to determine the max size of each column

@nzbart

This comment has been minimized.

nzbart commented Sep 27, 2018

Exactly what I wanted, despite this limitation. Thanks for taking the time to post this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment