001/* 002 * Syncany, www.syncany.org 003 * Copyright (C) 2011-2016 Philipp C. Heckel <philipp.heckel@gmail.com> 004 * 005 * This program is free software: you can redistribute it and/or modify 006 * it under the terms of the GNU General Public License as published by 007 * the Free Software Foundation, either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 * GNU General Public License for more details. 014 * 015 * You should have received a copy of the GNU General Public License 016 * along with this program. If not, see <http://www.gnu.org/licenses/>. 017 */ 018package org.syncany.cli.util; 019 020import java.util.List; 021 022import org.syncany.util.StringUtil; 023 024public class CliTableUtil { 025 public static void printTable(CarriageReturnPrinter out, List<String[]> tableValues, String noRowsMessage) { 026 if (tableValues.size() > 0) { 027 Integer[] tableColumnWidths = calculateColumnWidths(tableValues); 028 String tableRowFormat = "%-" + StringUtil.join(tableColumnWidths, "s | %-") + "s\n"; 029 030 printTableHeader(out, tableValues.get(0), tableRowFormat, tableColumnWidths); 031 032 if (tableValues.size() > 1) { 033 printTableBody(out, tableValues, tableRowFormat, tableColumnWidths); 034 } 035 else { 036 out.println(noRowsMessage); 037 } 038 } 039 } 040 041 private static void printTableBody(CarriageReturnPrinter out, List<String[]> tableValues, String tableRowFormat, Integer[] tableColumnWidths) { 042 for (int i = 1; i < tableValues.size(); i++) { 043 out.printf(tableRowFormat, (Object[]) tableValues.get(i)); 044 } 045 } 046 047 private static void printTableHeader(CarriageReturnPrinter out, String[] tableHeader, String tableRowFormat, Integer[] tableColumnWidths) { 048 out.printf(tableRowFormat, (Object[]) tableHeader); 049 050 for (int i = 0; i < tableColumnWidths.length; i++) { 051 if (i > 0) { 052 out.print("-"); 053 } 054 055 for (int j = 0; j < tableColumnWidths[i]; j++) { 056 out.print("-"); 057 } 058 059 if (i < tableColumnWidths.length - 1) { 060 out.print("-"); 061 out.print("+"); 062 } 063 } 064 065 out.println(); 066 } 067 068 private static Integer[] calculateColumnWidths(List<String[]> tableValues) { 069 Integer[] tableColumnWidths = new Integer[tableValues.get(0).length]; 070 071 for (String[] tableRow : tableValues) { 072 for (int i = 0; i < tableRow.length; i++) { 073 if (tableColumnWidths[i] == null || (tableRow[i] != null && tableColumnWidths[i] < tableRow[i].length())) { 074 tableColumnWidths[i] = tableRow[i].length(); 075 } 076 } 077 } 078 079 return tableColumnWidths; 080 } 081}