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.
This commit is contained in:
Lennart Poettering
2021-01-21 17:36:53 +01:00
parent 9b25429cb4
commit e676b4fc8b
2 changed files with 30 additions and 0 deletions

View File

@@ -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;
}

View File

@@ -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")