]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
format-table: add new helper table_print_with_pager()
authorLennart Poettering <lennart@poettering.net>
Thu, 21 Jan 2021 16:36:53 +0000 (17:36 +0100)
committerLennart Poettering <lennart@poettering.net>
Thu, 21 Jan 2021 17:14:21 +0000 (18:14 +0100)
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.

src/shared/format-table.c
src/shared/format-table.h

index 645e5b9afa193da410cff076da6b3a6755531154..8b9c81664df2baadecf70bc61be119903bbf76dc 100644 (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;
+}
index 965549b60a4def2da03ab42af4208fdf158e0a2e..6627a291f3452e14864f90cd7fa6a701c52efd56 100644 (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")