From c6bf9dff3a6e6a071b55755b57f8d44bbefe9cca Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Thu, 10 Nov 2022 12:52:08 +0100 Subject: format-table: add an explicit "vertical" mode Originally, the table formatting code was written to display a number of records, one per line, and within each line multiple fields of the same record. The first line contains the column names. It was then started to be used in a "vertical" mode however, i.e. with field names on the left instead of the top. Let's support such a mode explicitly, so that we can provide systematic styling, and can properly convert this mode to JSON. A new constructor "table_new_vertical()" is added creating such "vertical" tables. Internally, this is a table with two columns: "key" and "value". When outputting this as JSON we'll output a single JSON object, with key/value as fields. (Which is different from the traditional output where we'd use the first line as JSON field names, and output an array of objects). A new cell type TABLE_FIELD is added for specifically marking the "field" cells, i.e. the cells in the first column. We'll automatically suffic ":" to these fields on output. --- src/test/test-format-table.c | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'src/test/test-format-table.c') diff --git a/src/test/test-format-table.c b/src/test/test-format-table.c index 60d5fee71f..14341b97b4 100644 --- a/src/test/test-format-table.c +++ b/src/test/test-format-table.c @@ -534,6 +534,37 @@ TEST(table) { "5min 5min \n")); } +TEST(vertical) { + _cleanup_(table_unrefp) Table *t = NULL; + _cleanup_free_ char *formatted = NULL; + + assert_se(t = table_new_vertical()); + + assert_se(table_add_many(t, + TABLE_FIELD, "pfft aa", TABLE_STRING, "foo", + TABLE_FIELD, "uuu o", TABLE_SIZE, UINT64_C(1024), + TABLE_FIELD, "lllllllllllo", TABLE_STRING, "jjjjjjjjjjjjjjjjj") >= 0); + + assert_se(table_set_json_field_name(t, 1, "dimpfelmoser") >= 0); + + assert_se(table_format(t, &formatted) >= 0); + + assert_se(streq(formatted, + " pfft aa: foo\n" + " uuu o: 1.0K\n" + "lllllllllllo: jjjjjjjjjjjjjjjjj\n")); + + _cleanup_(json_variant_unrefp) JsonVariant *a = NULL, *b = NULL; + assert_se(table_to_json(t, &a) >= 0); + + assert_se(json_build(&b, JSON_BUILD_OBJECT( + JSON_BUILD_PAIR("pfft_aa", JSON_BUILD_STRING("foo")), + JSON_BUILD_PAIR("dimpfelmoser", JSON_BUILD_UNSIGNED(1024)), + JSON_BUILD_PAIR("lllllllllllo", JSON_BUILD_STRING("jjjjjjjjjjjjjjjjj")))) >= 0); + + assert_se(json_variant_equal(a, b)); +} + static int intro(void) { assert_se(setenv("SYSTEMD_COLORS", "0", 1) >= 0); assert_se(setenv("COLUMNS", "40", 1) >= 0); -- cgit v1.2.3