From f53e2094790674845fec940a57c190727637962a Mon Sep 17 00:00:00 2001 From: Christopher Moussa Date: Wed, 16 Oct 2024 14:25:16 -0700 Subject: [PATCH] view-user --parsable: improve output formatting Problem: Since the formatting of the columns in the output of view-user --parsable is dependent on the length of the longest column name, the width of every column is forced to match, which can result in some ugly screen wrapping even in a relatively small font. Improve the view-user --parsable formatting option by making the width of each column dynamic based on the length of each column name instead of based on the length of the longest column name. --- .../fluxacct/accounting/user_subcommands.py | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/bindings/python/fluxacct/accounting/user_subcommands.py b/src/bindings/python/fluxacct/accounting/user_subcommands.py index 861a5925..bc8c0502 100755 --- a/src/bindings/python/fluxacct/accounting/user_subcommands.py +++ b/src/bindings/python/fluxacct/accounting/user_subcommands.py @@ -130,21 +130,26 @@ def create_json_object(conn, user): def get_user_rows(conn, user, headers, rows, parsable, json_fmt): - user_str = "" - if parsable is True: - # find length of longest column name - col_width = len(sorted(headers, key=len)[-1]) + # fetch column names and determine width of each column + col_widths = [ + max(len(str(value)) for value in [col] + [row[i] for row in rows]) + for i, col in enumerate(headers) + ] - for header in headers: - user_str += header.ljust(col_width) - user_str += "\n" - for row in rows: - for col in list(row): - user_str += str(col).ljust(col_width) + def format_row(row): + return " | ".join( + [f"{str(value).ljust(col_widths[i])}" for i, value in enumerate(row)] + ) - return user_str + header = format_row(headers) + separator = "-+-".join(["-" * width for width in col_widths]) + data_rows = "\n".join([format_row(row) for row in rows]) + table = f"{header}\n{separator}\n{data_rows}" + + return table + user_str = "" if json_fmt is True: user_str += create_json_object(conn, user)