diff options
author | Lennart Poettering <lennart@poettering.net> | 2021-01-21 17:36:53 +0100 |
---|---|---|
committer | Lennart Poettering <lennart@poettering.net> | 2021-01-21 18:14:21 +0100 |
commit | e676b4fc8bbf1e7e602d839721b092fd58aacc05 (patch) | |
tree | 158e5ab51902f31fed06cfccf6300d661806dce0 /src | |
parent | 9b25429cb4e9b71e25cd9094ff2bbe3351aa9329 (diff) | |
download | systemd-e676b4fc8bbf1e7e602d839721b092fd58aacc05.tar.gz |
format-table: add new helper table_print_with_pager()
This adds a new function table_print_with_pager() which is a wrapper
around table_print_json()/table_print() but spawns a pager first, if
that's enabled, and optionally turns off the header line of the table.
This addresses the fact that many of our tools actually keep doing very
this very similar stuff, over and over again. Let's unify this in one
place.
Diffstat (limited to 'src')
-rw-r--r-- | src/shared/format-table.c | 27 | ||||
-rw-r--r-- | src/shared/format-table.h | 3 |
2 files changed, 30 insertions, 0 deletions
diff --git a/src/shared/format-table.c b/src/shared/format-table.c index 645e5b9afa..8b9c81664d 100644 --- a/src/shared/format-table.c +++ b/src/shared/format-table.c @@ -2550,3 +2550,30 @@ int table_print_json(Table *t, FILE *f, JsonFormatFlags flags) { return fflush_and_check(f); } + +int table_print_with_pager( + Table *t, + JsonFormatFlags json_format_flags, + PagerFlags pager_flags, + bool show_header) { + + bool saved_header; + int r; + + assert(t); + + /* A all-in-one solution for showing tables, and turning on a pager first. Also optionally suppresses + * the table header and logs about any error. */ + + if (json_format_flags & (JSON_FORMAT_OFF|JSON_FORMAT_PRETTY|JSON_FORMAT_PRETTY_AUTO)) + (void) pager_open(pager_flags); + + saved_header = t->header; + t->header = show_header; + r = table_print_json(t, stdout, json_format_flags); + t->header = saved_header; + if (r < 0) + return table_log_print_error(r); + + return 0; +} diff --git a/src/shared/format-table.h b/src/shared/format-table.h index 965549b60a..6627a291f3 100644 --- a/src/shared/format-table.h +++ b/src/shared/format-table.h @@ -7,6 +7,7 @@ #include "json.h" #include "macro.h" +#include "pager.h" typedef enum TableDataType { TABLE_EMPTY, @@ -129,6 +130,8 @@ const void *table_get_at(Table *t, size_t row, size_t column); int table_to_json(Table *t, JsonVariant **ret); int table_print_json(Table *t, FILE *f, JsonFormatFlags json_flags); +int table_print_with_pager(Table *t, JsonFormatFlags json_format_flags, PagerFlags pager_flags, bool show_header); + #define table_log_add_error(r) \ log_error_errno(r, "Failed to add cell(s) to table: %m") |