Merge pull request #8709 from poettering/format-table

generic table formatter
This commit is contained in:
Lennart Poettering 2018-04-18 16:20:13 +02:00 committed by GitHub
commit 613bddf7d1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 1958 additions and 401 deletions

7
TODO
View file

@ -24,6 +24,13 @@ Janitorial Clean-ups:
Features:
* Fix DECIMAL_STR_MAX or DECIMAL_STR_WIDTH. One includes a trailing NUL, the
other doesn't. What a desaster. Probably to exclude it. Also
DECIMAL_STR_WIDTH should probably add an extra "-" into account for negative
numbers.
* port systemctl, systemd-inhibit, busctl, … over to format-table.[ch]'s table formatters
* pid1: lock image configured with RootDirectory=/RootImage= using the usual nspawn semantics while the unit is up
* add --vacuum-xyz options to coredumpctl, matching those journalctl already has.

1247
src/basic/format-table.c Normal file

File diff suppressed because it is too large Load diff

62
src/basic/format-table.h Normal file
View file

@ -0,0 +1,62 @@
/* SPDX-License-Identifier: LGPL-2.1+ */
#pragma once
#include <stdbool.h>
#include <stdio.h>
#include <sys/types.h>
#include "macro.h"
typedef enum TableDataType {
TABLE_EMPTY,
TABLE_STRING,
TABLE_BOOLEAN,
TABLE_TIMESTAMP,
TABLE_TIMESPAN,
TABLE_SIZE,
TABLE_UINT32,
_TABLE_DATA_TYPE_MAX,
_TABLE_DATA_TYPE_INVALID = -1,
} TableDataType;
typedef struct Table Table;
typedef struct TableCell TableCell;
Table *table_new_internal(const char *first_header, ...) _sentinel_;
#define table_new(...) table_new_internal(__VA_ARGS__, NULL)
Table *table_new_raw(size_t n_columns);
Table *table_unref(Table *t);
DEFINE_TRIVIAL_CLEANUP_FUNC(Table*, table_unref);
int table_add_cell_full(Table *t, TableCell **ret_cell, TableDataType type, const void *data, size_t minimum_width, size_t maximum_width, unsigned weight, unsigned align_percent, unsigned ellipsize_percent);
static inline int table_add_cell(Table *t, TableCell **ret_cell, TableDataType type, const void *data) {
return table_add_cell_full(t, ret_cell, type, data, (size_t) -1, (size_t) -1, (unsigned) -1, (unsigned) -1, (unsigned) -1);
}
int table_dup_cell(Table *t, TableCell *cell);
int table_set_minimum_width(Table *t, TableCell *cell, size_t minimum_width);
int table_set_maximum_width(Table *t, TableCell *cell, size_t maximum_width);
int table_set_weight(Table *t, TableCell *cell, unsigned weight);
int table_set_align_percent(Table *t, TableCell *cell, unsigned percent);
int table_set_ellipsize_percent(Table *t, TableCell *cell, unsigned percent);
int table_set_color(Table *t, TableCell *cell, const char *color);
int table_add_many_internal(Table *t, TableDataType first_type, ...);
#define table_add_many(t, ...) table_add_many_internal(t, __VA_ARGS__, _TABLE_DATA_TYPE_MAX)
void table_set_header(Table *table, bool b);
void table_set_width(Table *t, size_t width);
int table_set_display(Table *t, size_t first_column, ...);
int table_set_sort(Table *t, size_t first_column, ...);
int table_print(Table *t, FILE *f);
int table_format(Table *t, char **ret);
static inline TableCell* TABLE_HEADER_CELL(size_t i) {
return SIZE_TO_PTR(i + 1);
}
size_t table_get_rows(Table *t);
size_t table_get_columns(Table *t);

View file

@ -365,10 +365,11 @@ const char *special_glyph(SpecialGlyph code) {
[BLACK_CIRCLE] = "*",
[ARROW] = "->",
[MDASH] = "-",
[ELLIPSIS] = "..."
},
/* UTF-8 */
[ true ] = {
[true] = {
[TREE_VERTICAL] = "\342\224\202 ", /* │ */
[TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
[TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
@ -377,6 +378,7 @@ const char *special_glyph(SpecialGlyph code) {
[BLACK_CIRCLE] = "\342\227\217", /* ● */
[ARROW] = "\342\206\222", /* → */
[MDASH] = "\342\200\223", /* */
[ELLIPSIS] = "\342\200\246", /* … */
},
};

View file

@ -53,6 +53,7 @@ typedef enum {
BLACK_CIRCLE,
ARROW,
MDASH,
ELLIPSIS,
_SPECIAL_GLYPH_MAX
} SpecialGlyph;

View file

@ -77,6 +77,8 @@ basic_sources = files('''
fileio-label.h
fileio.c
fileio.h
format-table.c
format-table.h
format-util.h
fs-util.c
fs-util.h
@ -127,6 +129,8 @@ basic_sources = files('''
nss-util.h
ordered-set.c
ordered-set.h
pager.c
pager.h
parse-util.c
parse-util.h
path-util.c

View file

@ -15,6 +15,7 @@
#include "alloc-util.h"
#include "gunicode.h"
#include "locale-util.h"
#include "macro.h"
#include "string-util.h"
#include "terminal-util.h"
@ -452,62 +453,104 @@ bool string_has_cc(const char *p, const char *ok) {
}
static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
size_t x;
size_t x, need_space;
char *r;
assert(s);
assert(percent <= 100);
assert(new_length >= 3);
assert(new_length != (size_t) -1);
if (old_length <= 3 || old_length <= new_length)
if (old_length <= new_length)
return strndup(s, old_length);
r = new0(char, new_length+3);
/* Special case short ellipsations */
switch (new_length) {
case 0:
return strdup("");
case 1:
if (is_locale_utf8())
return strdup("");
else
return strdup(".");
case 2:
if (!is_locale_utf8())
return strdup("..");
break;
default:
break;
}
/* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
* character (""), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
* either for the UTF-8 encoded character or for three ASCII characters. */
need_space = is_locale_utf8() ? 1 : 3;
r = new(char, new_length+3);
if (!r)
return NULL;
x = (new_length * percent) / 100;
assert(new_length >= need_space);
if (x > new_length - 3)
x = new_length - 3;
x = ((new_length - need_space) * percent + 50) / 100;
assert(x <= new_length - need_space);
memcpy(r, s, x);
r[x] = 0xe2; /* tri-dot ellipsis: … */
r[x+1] = 0x80;
r[x+2] = 0xa6;
if (is_locale_utf8()) {
r[x+0] = 0xe2; /* tri-dot ellipsis: … */
r[x+1] = 0x80;
r[x+2] = 0xa6;
} else {
r[x+0] = '.';
r[x+1] = '.';
r[x+2] = '.';
}
memcpy(r + x + 3,
s + old_length - (new_length - x - 1),
new_length - x - 1);
s + old_length - (new_length - x - need_space),
new_length - x - need_space + 1);
return r;
}
char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
size_t x;
char *e;
size_t x, k, len, len2;
const char *i, *j;
unsigned k, len, len2;
char *e;
int r;
/* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
* on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
* strings.
*
* Ellipsation is done in a locale-dependent way:
* 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
* 2. Otherwise, a unicode ellipsis is used ("")
*
* In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
* the current locale is UTF-8.
*/
assert(s);
assert(percent <= 100);
if (new_length == (size_t) -1)
return strndup(s, old_length);
assert(new_length >= 3);
if (new_length == 0)
return strdup("");
/* if no multibyte characters use ascii_ellipsize_mem for speed */
/* If no multibyte characters use ascii_ellipsize_mem for speed */
if (ascii_is_valid(s))
return ascii_ellipsize_mem(s, old_length, new_length, percent);
if (old_length <= 3 || old_length <= new_length)
return strndup(s, old_length);
x = (new_length * percent) / 100;
if (x > new_length - 3)
x = new_length - 3;
x = ((new_length - 1) * percent) / 100;
assert(x <= new_length - 1);
k = 0;
for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
@ -552,7 +595,7 @@ char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigne
*/
memcpy(e, s, len);
e[len] = 0xe2; /* tri-dot ellipsis: … */
e[len + 0] = 0xe2; /* tri-dot ellipsis: … */
e[len + 1] = 0x80;
e[len + 2] = 0xa6;

View file

@ -35,6 +35,7 @@
#include <string.h>
#include "alloc-util.h"
#include "gunicode.h"
#include "hexdecoct.h"
#include "macro.h"
#include "utf8.h"
@ -414,3 +415,23 @@ size_t utf8_n_codepoints(const char *str) {
return n;
}
size_t utf8_console_width(const char *str) {
size_t n = 0;
/* Returns the approximate width a string will take on screen when printed on a character cell
* terminal/console. */
while (*str != 0) {
char32_t c;
if (utf8_encoded_to_unichar(str, &c) < 0)
return (size_t) -1;
str = utf8_next_char(str);
n += unichar_iswide(c) ? 2 : 1;
}
return n;
}

View file

@ -48,3 +48,4 @@ static inline char32_t utf16_surrogate_pair_to_unichar(char16_t lead, char16_t t
}
size_t utf8_n_codepoints(const char *str);
size_t utf8_console_width(const char *str);

View file

@ -111,6 +111,14 @@ static inline void qsort_safe(void *base, size_t nmemb, size_t size, comparison_
qsort_safe((p), (n), sizeof((p)[0]), (__compar_fn_t) _func_); \
})
static inline void qsort_r_safe(void *base, size_t nmemb, size_t size, int (*compar)(const void*, const void*, void*), void *userdata) {
if (nmemb <= 1)
return;
assert(base);
qsort_r(base, nmemb, size, compar, userdata);
}
/**
* Normal memcpy requires src to be nonnull. We do nothing if n is 0.
*/

View file

@ -19,6 +19,7 @@
#include "bus-util.h"
#include "cgroup-show.h"
#include "cgroup-util.h"
#include "format-table.h"
#include "log.h"
#include "logs-show.h"
#include "macro.h"
@ -86,13 +87,39 @@ static int get_session_path(sd_bus *bus, const char *session_id, sd_bus_error *e
return 0;
}
static int show_table(Table *table, const char *word) {
int r;
assert(table);
assert(word);
if (table_get_rows(table) > 1) {
r = table_set_sort(table, (size_t) 0, (size_t) -1);
if (r < 0)
return log_error_errno(r, "Failed to sort table: %m");
table_set_header(table, arg_legend);
r = table_print(table, NULL);
if (r < 0)
return log_error_errno(r, "Failed to show table: %m");
}
if (arg_legend) {
if (table_get_rows(table) > 1)
printf("\n%zu %s listed.\n", table_get_rows(table) - 1, word);
else
printf("No %s.\n", word);
}
return 0;
}
static int list_sessions(int argc, char *argv[], void *userdata) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
const char *id, *user, *seat, *object;
_cleanup_(table_unrefp) Table *table = NULL;
sd_bus *bus = userdata;
unsigned k = 0;
uint32_t uid;
int r;
assert(bus);
@ -107,67 +134,74 @@ static int list_sessions(int argc, char *argv[], void *userdata) {
"org.freedesktop.login1.Manager",
"ListSessions",
&error, &reply,
"");
if (r < 0) {
log_error("Failed to list sessions: %s", bus_error_message(&error, r));
return r;
}
NULL);
if (r < 0)
return log_error_errno(r, "Failed to list sessions: %s", bus_error_message(&error, r));
r = sd_bus_message_enter_container(reply, 'a', "(susso)");
if (r < 0)
return bus_log_parse_error(r);
if (arg_legend)
printf("%10s %10s %-16s %-16s %-16s\n", "SESSION", "UID", "USER", "SEAT", "TTY");
table = table_new("SESSION", "UID", "USER", "SEAT", "TTY");
if (!table)
return log_oom();
while ((r = sd_bus_message_read(reply, "(susso)", &id, &uid, &user, &seat, &object)) > 0) {
_cleanup_(sd_bus_error_free) sd_bus_error error2 = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply2 = NULL;
/* Right-align the first two fields (since they are numeric) */
(void) table_set_align_percent(table, TABLE_HEADER_CELL(0), 100);
(void) table_set_align_percent(table, TABLE_HEADER_CELL(1), 100);
for (;;) {
_cleanup_(sd_bus_error_free) sd_bus_error error_tty = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply_tty = NULL;
const char *id, *user, *seat, *object, *tty = NULL;
_cleanup_free_ char *path = NULL;
const char *tty = NULL;
uint32_t uid;
r = get_session_path(bus, id, &error2, &path);
r = sd_bus_message_read(reply, "(susso)", &id, &uid, &user, &seat, &object);
if (r < 0)
log_warning("Failed to get session path: %s", bus_error_message(&error, r));
return bus_log_parse_error(r);
if (r == 0)
break;
r = sd_bus_get_property(
bus,
"org.freedesktop.login1",
object,
"org.freedesktop.login1.Session",
"TTY",
&error_tty,
&reply_tty,
"s");
if (r < 0)
log_warning_errno(r, "Failed to get TTY for session %s: %s", id, bus_error_message(&error_tty, r));
else {
r = sd_bus_get_property(
bus,
"org.freedesktop.login1",
path,
"org.freedesktop.login1.Session",
"TTY",
&error2,
&reply2,
"s");
r = sd_bus_message_read(reply_tty, "s", &tty);
if (r < 0)
log_warning("Failed to get TTY for session %s: %s",
id, bus_error_message(&error2, r));
else {
r = sd_bus_message_read(reply2, "s", &tty);
if (r < 0)
return bus_log_parse_error(r);
}
return bus_log_parse_error(r);
}
printf("%10s %10"PRIu32" %-16s %-16s %-16s\n", id, uid, user, seat, strna(tty));
k++;
r = table_add_many(table,
TABLE_STRING, id,
TABLE_UINT32, uid,
TABLE_STRING, user,
TABLE_STRING, seat,
TABLE_STRING, strna(tty));
if (r < 0)
return log_error_errno(r, "Failed to add row to table: %m");
}
r = sd_bus_message_exit_container(reply);
if (r < 0)
return bus_log_parse_error(r);
if (arg_legend)
printf("\n%u sessions listed.\n", k);
return 0;
return show_table(table, "sessions");
}
static int list_users(int argc, char *argv[], void *userdata) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
const char *user, *object;
_cleanup_(table_unrefp) Table *table = NULL;
sd_bus *bus = userdata;
unsigned k = 0;
uint32_t uid;
int r;
assert(bus);
@ -182,39 +216,51 @@ static int list_users(int argc, char *argv[], void *userdata) {
"org.freedesktop.login1.Manager",
"ListUsers",
&error, &reply,
"");
if (r < 0) {
log_error("Failed to list users: %s", bus_error_message(&error, r));
return r;
}
NULL);
if (r < 0)
return log_error_errno(r, "Failed to list users: %s", bus_error_message(&error, r));
r = sd_bus_message_enter_container(reply, 'a', "(uso)");
if (r < 0)
return bus_log_parse_error(r);
if (arg_legend)
printf("%10s %-16s\n", "UID", "USER");
table = table_new("UID", "USER");
if (!table)
return log_oom();
while ((r = sd_bus_message_read(reply, "(uso)", &uid, &user, &object)) > 0) {
printf("%10"PRIu32" %-16s\n", uid, user);
k++;
(void) table_set_align_percent(table, TABLE_HEADER_CELL(0), 100);
for (;;) {
const char *user, *object;
uint32_t uid;
r = sd_bus_message_read(reply, "(uso)", &uid, &user, &object);
if (r < 0)
return bus_log_parse_error(r);
if (r == 0)
break;
r = table_add_many(table,
TABLE_UINT32, uid,
TABLE_STRING, user);
if (r < 0)
return log_error_errno(r, "Failed to add row to table: %m");
}
r = sd_bus_message_exit_container(reply);
if (r < 0)
return bus_log_parse_error(r);
if (arg_legend)
printf("\n%u users listed.\n", k);
return 0;
return show_table(table, "users");
}
static int list_seats(int argc, char *argv[], void *userdata) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
const char *seat, *object;
_cleanup_(table_unrefp) Table *table = NULL;
sd_bus *bus = userdata;
unsigned k = 0;
int r;
assert(bus);
assert(argv);
@ -227,30 +273,37 @@ static int list_seats(int argc, char *argv[], void *userdata) {
"org.freedesktop.login1.Manager",
"ListSeats",
&error, &reply,
"");
if (r < 0) {
log_error("Failed to list seats: %s", bus_error_message(&error, r));
return r;
}
NULL);
if (r < 0)
return log_error_errno(r, "Failed to list seats: %s", bus_error_message(&error, r));
r = sd_bus_message_enter_container(reply, 'a', "(so)");
if (r < 0)
return bus_log_parse_error(r);
if (arg_legend)
printf("%-16s\n", "SEAT");
table = table_new("SEAT");
if (!table)
return log_oom();
while ((r = sd_bus_message_read(reply, "(so)", &seat, &object)) > 0) {
printf("%-16s\n", seat);
k++;
for (;;) {
const char *seat, *object;
r = sd_bus_message_read(reply, "(so)", &seat, &object);
if (r < 0)
return bus_log_parse_error(r);
if (r == 0)
break;
r = table_add_cell(table, NULL, TABLE_STRING, seat);
if (r < 0)
return log_error_errno(r, "Failed to add row to table: %m");
}
r = sd_bus_message_exit_container(reply);
if (r < 0)
return bus_log_parse_error(r);
if (arg_legend)
printf("\n%u seats listed.\n", k);
return 0;
return show_table(table, "seats");
}
static int show_unit_cgroup(sd_bus *bus, const char *interface, const char *unit, pid_t leader) {

View file

@ -29,8 +29,10 @@
#include "copy.h"
#include "env-util.h"
#include "fd-util.h"
#include "format-table.h"
#include "hostname-util.h"
#include "import-util.h"
#include "locale-util.h"
#include "log.h"
#include "logs-show.h"
#include "macro.h"
@ -76,8 +78,6 @@ static const char *arg_uid = NULL;
static char **arg_setenv = NULL;
static int arg_addrs = 1;
static int print_addresses(sd_bus *bus, const char *name, int, const char *pr1, const char *pr2, int n_addr);
static OutputFlags get_output_flags(void) {
return
arg_all * OUTPUT_SHOW_ALL |
@ -86,34 +86,8 @@ static OutputFlags get_output_flags(void) {
!arg_quiet * OUTPUT_WARN_CUTOFF;
}
typedef struct MachineInfo {
const char *name;
const char *class;
const char *service;
char *os;
char *version_id;
} MachineInfo;
static int compare_machine_info(const void *a, const void *b) {
const MachineInfo *x = a, *y = b;
return strcmp(x->name, y->name);
}
static void clean_machine_info(MachineInfo *machines, size_t n_machines) {
size_t i;
if (!machines || n_machines == 0)
return;
for (i = 0; i < n_machines; i++) {
free(machines[i].os);
free(machines[i].version_id);
}
free(machines);
}
static int call_get_os_release(sd_bus *bus, const char *method, const char *name, const char *query, ...) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
const char *k, *v, *iter, **query_res = NULL;
size_t count = 0, awaited_args = 0;
@ -134,9 +108,10 @@ static int call_get_os_release(sd_bus *bus, const char *method, const char *name
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
method,
NULL, &reply, "s", name);
&error,
&reply, "s", name);
if (r < 0)
return r;
return log_debug_errno(r, "Failed to call '%s()': %s", method, bus_error_message(&error, r));
r = sd_bus_message_enter_container(reply, 'a', "{ss}");
if (r < 0)
@ -179,16 +154,127 @@ static int call_get_os_release(sd_bus *bus, const char *method, const char *name
return 0;
}
static int list_machines(int argc, char *argv[], void *userdata) {
static int call_get_addresses(sd_bus *bus, const char *name, int ifi, const char *prefix, const char *prefix2, int n_addr, char **ret) {
size_t max_name = STRLEN("MACHINE"), max_class = STRLEN("CLASS"),
max_service = STRLEN("SERVICE"), max_os = STRLEN("OS"), max_version_id = STRLEN("VERSION");
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
_cleanup_free_ char *prefix = NULL;
MachineInfo *machines = NULL;
const char *name, *class, *service, *object;
size_t n_machines = 0, n_allocated = 0, j;
_cleanup_free_ char *addresses = NULL;
bool truncate = false;
unsigned n = 0;
int r;
assert(bus);
assert(name);
assert(prefix);
assert(prefix2);
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"GetMachineAddresses",
NULL,
&reply,
"s", name);
if (r < 0)
return log_debug_errno(r, "Could not get addresses: %s", bus_error_message(&error, r));
addresses = strdup(prefix);
if (!addresses)
return log_oom();
prefix = "";
r = sd_bus_message_enter_container(reply, 'a', "(iay)");
if (r < 0)
return bus_log_parse_error(r);
while ((r = sd_bus_message_enter_container(reply, 'r', "iay")) > 0) {
int family;
const void *a;
size_t sz;
char buf_ifi[DECIMAL_STR_MAX(int) + 2], buffer[MAX(INET6_ADDRSTRLEN, INET_ADDRSTRLEN)];
r = sd_bus_message_read(reply, "i", &family);
if (r < 0)
return bus_log_parse_error(r);
r = sd_bus_message_read_array(reply, 'y', &a, &sz);
if (r < 0)
return bus_log_parse_error(r);
if (n_addr != 0) {
if (family == AF_INET6 && ifi > 0)
xsprintf(buf_ifi, "%%%i", ifi);
else
strcpy(buf_ifi, "");
if (!strextend(&addresses, prefix, inet_ntop(family, a, buffer, sizeof(buffer)), buf_ifi, NULL))
return log_oom();
} else
truncate = true;
r = sd_bus_message_exit_container(reply);
if (r < 0)
return bus_log_parse_error(r);
prefix = prefix2;
if (n_addr > 0)
n_addr --;
n++;
}
if (r < 0)
return bus_log_parse_error(r);
r = sd_bus_message_exit_container(reply);
if (r < 0)
return bus_log_parse_error(r);
if (truncate) {
if (!strextend(&addresses, special_glyph(ELLIPSIS), NULL))
return -ENOMEM;
}
*ret = TAKE_PTR(addresses);
return (int) n;
}
static int show_table(Table *table, const char *word) {
int r;
assert(table);
assert(word);
if (table_get_rows(table) > 1) {
r = table_set_sort(table, (size_t) 0, (size_t) -1);
if (r < 0)
return log_error_errno(r, "Failed to sort table: %m");
table_set_header(table, arg_legend);
r = table_print(table, NULL);
if (r < 0)
return log_error_errno(r, "Failed to show table: %m");
}
if (arg_legend) {
if (table_get_rows(table) > 1)
printf("\n%zu %s listed.\n", table_get_rows(table) - 1, word);
else
printf("No %s.\n", word);
}
return 0;
}
static int list_machines(int argc, char *argv[], void *userdata) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
_cleanup_(table_unrefp) Table *table = NULL;
sd_bus *bus = userdata;
int r;
@ -204,149 +290,73 @@ static int list_machines(int argc, char *argv[], void *userdata) {
&error,
&reply,
NULL);
if (r < 0) {
log_error("Could not get machines: %s", bus_error_message(&error, -r));
return r;
}
if (r < 0)
return log_error_errno(r, "Could not get machines: %s", bus_error_message(&error, r));
table = table_new("MACHINE", "CLASS", "SERVICE", "OS", "VERSION", "ADDRESSES");
if (!table)
return log_oom();
r = sd_bus_message_enter_container(reply, 'a', "(ssso)");
if (r < 0)
return bus_log_parse_error(r);
while ((r = sd_bus_message_read(reply, "(ssso)", &name, &class, &service, &object)) > 0) {
size_t l;
for (;;) {
_cleanup_free_ char *os = NULL, *version_id = NULL, *addresses = NULL;
const char *name, *class, *service, *object;
r = sd_bus_message_read(reply, "(ssso)", &name, &class, &service, &object);
if (r < 0)
return bus_log_parse_error(r);
if (r == 0)
break;
if (name[0] == '.' && !arg_all)
continue;
if (!GREEDY_REALLOC0(machines, n_allocated, n_machines + 1)) {
r = log_oom();
goto out;
}
machines[n_machines].name = name;
machines[n_machines].class = class;
machines[n_machines].service = service;
(void) call_get_os_release(
bus,
"GetMachineOSRelease",
name,
"ID\0"
"VERSION_ID\0",
&machines[n_machines].os,
&machines[n_machines].version_id);
&os,
&version_id);
l = strlen(name);
if (l > max_name)
max_name = l;
(void) call_get_addresses(
bus,
name,
0,
"",
"",
arg_addrs,
&addresses);
l = strlen(class);
if (l > max_class)
max_class = l;
l = strlen(service);
if (l > max_service)
max_service = l;
l = machines[n_machines].os ? strlen(machines[n_machines].os) : 1;
if (l > max_os)
max_os = l;
l = machines[n_machines].version_id ? strlen(machines[n_machines].version_id) : 1;
if (l > max_version_id)
max_version_id = l;
n_machines++;
}
if (r < 0) {
r = bus_log_parse_error(r);
goto out;
r = table_add_many(table,
TABLE_STRING, name,
TABLE_STRING, class,
TABLE_STRING, strdash_if_empty(service),
TABLE_STRING, strdash_if_empty(os),
TABLE_STRING, strdash_if_empty(version_id),
TABLE_STRING, strdash_if_empty(addresses));
if (r < 0)
return log_error_errno(r, "Failed to add table row: %m");
}
r = sd_bus_message_exit_container(reply);
if (r < 0) {
r = bus_log_parse_error(r);
goto out;
}
if (r < 0)
return bus_log_parse_error(r);
qsort_safe(machines, n_machines, sizeof(MachineInfo), compare_machine_info);
/* Allocate for prefix max characters for all fields + spaces between them + STRLEN(",\n") */
r = asprintf(&prefix, "%-*s",
(int) (max_name +
max_class +
max_service +
max_os +
max_version_id + 5 + STRLEN(",\n")),
",\n");
if (r < 0) {
r = log_oom();
goto out;
}
if (arg_legend && n_machines > 0)
printf("%-*s %-*s %-*s %-*s %-*s %s\n",
(int) max_name, "MACHINE",
(int) max_class, "CLASS",
(int) max_service, "SERVICE",
(int) max_os, "OS",
(int) max_version_id, "VERSION",
"ADDRESSES");
for (j = 0; j < n_machines; j++) {
printf("%-*s %-*s %-*s %-*s %-*s ",
(int) max_name, machines[j].name,
(int) max_class, machines[j].class,
(int) max_service, strdash_if_empty(machines[j].service),
(int) max_os, strdash_if_empty(machines[j].os),
(int) max_version_id, strdash_if_empty(machines[j].version_id));
r = print_addresses(bus, machines[j].name, 0, "", prefix, arg_addrs);
if (r <= 0) /* error or no addresses defined? */
fputs("-\n", stdout);
else
fputc('\n', stdout);
}
if (arg_legend) {
if (n_machines > 0)
printf("\n%zu machines listed.\n", n_machines);
else
printf("No machines.\n");
}
r = 0;
out:
clean_machine_info(machines, n_machines);
return r;
}
typedef struct ImageInfo {
const char *name;
const char *type;
bool read_only;
usec_t crtime;
usec_t mtime;
uint64_t size;
} ImageInfo;
static int compare_image_info(const void *a, const void *b) {
const ImageInfo *x = a, *y = b;
return strcmp(x->name, y->name);
return show_table(table, "machines");
}
static int list_images(int argc, char *argv[], void *userdata) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
size_t max_name = STRLEN("NAME"), max_type = STRLEN("TYPE"), max_size = STRLEN("USAGE"), max_crtime = STRLEN("CREATED"), max_mtime = STRLEN("MODIFIED");
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
_cleanup_free_ ImageInfo *images = NULL;
size_t n_images = 0, n_allocated = 0, j;
const char *name, *type, *object;
_cleanup_(table_unrefp) Table *table = NULL;
sd_bus *bus = userdata;
uint64_t crtime, mtime, size;
int read_only, r;
int r;
assert(bus);
@ -359,99 +369,66 @@ static int list_images(int argc, char *argv[], void *userdata) {
"ListImages",
&error,
&reply,
"");
if (r < 0) {
log_error("Could not get images: %s", bus_error_message(&error, -r));
return r;
}
NULL);
if (r < 0)
return log_error_errno(r, "Could not get images: %s", bus_error_message(&error, r));
table = table_new("NAME", "TYPE", "RO", "USAGE", "CREATED", "MODIFIED");
if (!table)
return log_oom();
(void) table_set_align_percent(table, TABLE_HEADER_CELL(3), 100);
r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssbttto)");
if (r < 0)
return bus_log_parse_error(r);
while ((r = sd_bus_message_read(reply, "(ssbttto)", &name, &type, &read_only, &crtime, &mtime, &size, &object)) > 0) {
char buf[MAX(FORMAT_TIMESTAMP_MAX, FORMAT_BYTES_MAX)];
size_t l;
for (;;) {
const char *name, *type, *object;
uint64_t crtime, mtime, size;
TableCell *cell;
bool ro_bool;
int ro_int;
r = sd_bus_message_read(reply, "(ssbttto)", &name, &type, &ro_int, &crtime, &mtime, &size, &object);
if (r < 0)
return bus_log_parse_error(r);
if (r == 0)
break;
if (name[0] == '.' && !arg_all)
continue;
if (!GREEDY_REALLOC(images, n_allocated, n_images + 1))
return log_oom();
r = table_add_many(table,
TABLE_STRING, name,
TABLE_STRING, type);
if (r < 0)
return log_error_errno(r, "Failed to add table row: %m");
images[n_images].name = name;
images[n_images].type = type;
images[n_images].read_only = read_only;
images[n_images].crtime = crtime;
images[n_images].mtime = mtime;
images[n_images].size = size;
ro_bool = ro_int;
r = table_add_cell(table, &cell, TABLE_BOOLEAN, &ro_bool);
if (r < 0)
return log_error_errno(r, "Failed to add table cell: %m");
l = strlen(name);
if (l > max_name)
max_name = l;
l = strlen(type);
if (l > max_type)
max_type = l;
if (crtime != 0) {
l = strlen(strna(format_timestamp(buf, sizeof(buf), crtime)));
if (l > max_crtime)
max_crtime = l;
if (ro_bool) {
r = table_set_color(table, cell, ansi_highlight_red());
if (r < 0)
return log_error_errno(r, "Failed to set table cell color: %m");
}
if (mtime != 0) {
l = strlen(strna(format_timestamp(buf, sizeof(buf), mtime)));
if (l > max_mtime)
max_mtime = l;
}
if (size != (uint64_t) -1) {
l = strlen(strna(format_bytes(buf, sizeof(buf), size)));
if (l > max_size)
max_size = l;
}
n_images++;
r = table_add_many(table,
TABLE_SIZE, size,
TABLE_TIMESTAMP, crtime,
TABLE_TIMESTAMP, mtime);
if (r < 0)
return log_error_errno(r, "Failed to add table row: %m");
}
if (r < 0)
return bus_log_parse_error(r);
r = sd_bus_message_exit_container(reply);
if (r < 0)
return bus_log_parse_error(r);
qsort_safe(images, n_images, sizeof(ImageInfo), compare_image_info);
if (arg_legend && n_images > 0)
printf("%-*s %-*s %-3s %-*s %-*s %-*s\n",
(int) max_name, "NAME",
(int) max_type, "TYPE",
"RO",
(int) max_size, "USAGE",
(int) max_crtime, "CREATED",
(int) max_mtime, "MODIFIED");
for (j = 0; j < n_images; j++) {
char crtime_buf[FORMAT_TIMESTAMP_MAX], mtime_buf[FORMAT_TIMESTAMP_MAX], size_buf[FORMAT_BYTES_MAX];
printf("%-*s %-*s %s%-3s%s %-*s %-*s %-*s\n",
(int) max_name, images[j].name,
(int) max_type, images[j].type,
images[j].read_only ? ansi_highlight_red() : "", yes_no(images[j].read_only), images[j].read_only ? ansi_normal() : "",
(int) max_size, strna(format_bytes(size_buf, sizeof(size_buf), images[j].size)),
(int) max_crtime, strna(format_timestamp(crtime_buf, sizeof(crtime_buf), images[j].crtime)),
(int) max_mtime, strna(format_timestamp(mtime_buf, sizeof(mtime_buf), images[j].mtime)));
}
if (arg_legend) {
if (n_images > 0)
printf("\n%zu images listed.\n", n_images);
else
printf("No images.\n");
}
return 0;
return show_table(table, "images");
}
static int show_unit_cgroup(sd_bus *bus, const char *unit, pid_t leader) {
@ -495,85 +472,17 @@ static int show_unit_cgroup(sd_bus *bus, const char *unit, pid_t leader) {
}
static int print_addresses(sd_bus *bus, const char *name, int ifi, const char *prefix, const char *prefix2, int n_addr) {
_cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
_cleanup_free_ char *addresses = NULL;
bool truncate = false;
unsigned n = 0;
_cleanup_free_ char *s = NULL;
int r;
assert(bus);
assert(name);
assert(prefix);
assert(prefix2);
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"GetMachineAddresses",
NULL,
&reply,
"s", name);
r = call_get_addresses(bus, name, ifi, prefix, prefix2, n_addr, &s);
if (r < 0)
return r;
addresses = strdup(prefix);
if (!addresses)
return log_oom();
prefix = "";
if (r > 0)
fputs(s, stdout);
r = sd_bus_message_enter_container(reply, 'a', "(iay)");
if (r < 0)
return bus_log_parse_error(r);
while ((r = sd_bus_message_enter_container(reply, 'r', "iay")) > 0) {
int family;
const void *a;
size_t sz;
char buf_ifi[DECIMAL_STR_MAX(int) + 2], buffer[MAX(INET6_ADDRSTRLEN, INET_ADDRSTRLEN)];
r = sd_bus_message_read(reply, "i", &family);
if (r < 0)
return bus_log_parse_error(r);
r = sd_bus_message_read_array(reply, 'y', &a, &sz);
if (r < 0)
return bus_log_parse_error(r);
if (n_addr != 0) {
if (family == AF_INET6 && ifi > 0)
xsprintf(buf_ifi, "%%%i", ifi);
else
strcpy(buf_ifi, "");
if (!strextend(&addresses, prefix, inet_ntop(family, a, buffer, sizeof(buffer)), buf_ifi, NULL))
return log_oom();
} else
truncate = true;
r = sd_bus_message_exit_container(reply);
if (r < 0)
return bus_log_parse_error(r);
if (prefix != prefix2)
prefix = prefix2;
if (n_addr > 0)
n_addr -= 1;
n++;
}
if (r < 0)
return bus_log_parse_error(r);
r = sd_bus_message_exit_container(reply);
if (r < 0)
return bus_log_parse_error(r);
if (n > 0)
fprintf(stdout, "%s%s", addresses, truncate ? "..." : "");
return (int) n;
return r;
}
static int print_os_release(sd_bus *bus, const char *method, const char *name, const char *prefix) {

View file

@ -69,8 +69,6 @@ shared_sources = '''
nsflags.h
output-mode.c
output-mode.h
pager.c
pager.h
path-lookup.c
path-lookup.h
ptyfwd.c

View file

@ -178,6 +178,10 @@ tests += [
[],
[]],
[['src/test/test-format-table.c'],
[],
[]],
[['src/test/test-ratelimit.c'],
[],
[]],

View file

@ -17,6 +17,30 @@ static void test_one(const char *p) {
_cleanup_free_ char *t;
t = ellipsize(p, columns(), 70);
puts(t);
free(t);
t = ellipsize(p, columns(), 0);
puts(t);
free(t);
t = ellipsize(p, columns(), 100);
puts(t);
free(t);
t = ellipsize(p, 0, 50);
puts(t);
free(t);
t = ellipsize(p, 1, 50);
puts(t);
free(t);
t = ellipsize(p, 2, 50);
puts(t);
free(t);
t = ellipsize(p, 3, 50);
puts(t);
free(t);
t = ellipsize(p, 4, 50);
puts(t);
free(t);
t = ellipsize(p, 5, 50);
puts(t);
}
int main(int argc, char *argv[]) {

View file

@ -0,0 +1,139 @@
/* SPDX-License-Identifier: LGPL-2.1+ */
#include "alloc-util.h"
#include "format-table.h"
#include "string-util.h"
#include "time-util.h"
int main(int argc, char *argv[]) {
_cleanup_(table_unrefp) Table *t = NULL;
_cleanup_free_ char *formatted = NULL;
assert_se(setenv("COLUMNS", "40", 1) >= 0);
assert_se(t = table_new("ONE", "TWO", "THREE"));
assert_se(table_set_align_percent(t, TABLE_HEADER_CELL(2), 100) >= 0);
assert_se(table_add_many(t,
TABLE_STRING, "xxx",
TABLE_STRING, "yyy",
TABLE_BOOLEAN, true) >= 0);
assert_se(table_add_many(t,
TABLE_STRING, "a long field",
TABLE_STRING, "yyy",
TABLE_BOOLEAN, false) >= 0);
assert_se(table_format(t, &formatted) >= 0);
printf("%s\n", formatted);
assert_se(streq(formatted,
"ONE TWO THREE\n"
"xxx yyy yes\n"
"a long field yyy no\n"));
formatted = mfree(formatted);
table_set_width(t, 40);
assert_se(table_format(t, &formatted) >= 0);
printf("%s\n", formatted);
assert_se(streq(formatted,
"ONE TWO THREE\n"
"xxx yyy yes\n"
"a long field yyy no\n"));
formatted = mfree(formatted);
table_set_width(t, 12);
assert_se(table_format(t, &formatted) >= 0);
printf("%s\n", formatted);
assert_se(streq(formatted,
"ONE TWO THR…\n"
"xxx yyy yes\n"
"a … yyy no\n"));
formatted = mfree(formatted);
table_set_width(t, 5);
assert_se(table_format(t, &formatted) >= 0);
printf("%s\n", formatted);
assert_se(streq(formatted,
"… … …\n"
"… … …\n"
"… … …\n"));
formatted = mfree(formatted);
table_set_width(t, 3);
assert_se(table_format(t, &formatted) >= 0);
printf("%s\n", formatted);
assert_se(streq(formatted,
"… … …\n"
"… … …\n"
"… … …\n"));
formatted = mfree(formatted);
table_set_width(t, (size_t) -1);
assert_se(table_set_sort(t, (size_t) 0, (size_t) 2, (size_t) -1) >= 0);
assert_se(table_format(t, &formatted) >= 0);
printf("%s\n", formatted);
assert_se(streq(formatted,
"ONE TWO THREE\n"
"a long field yyy no\n"
"xxx yyy yes\n"));
formatted = mfree(formatted);
table_set_header(t, false);
assert_se(table_add_many(t,
TABLE_STRING, "fäää",
TABLE_STRING, "uuu",
TABLE_BOOLEAN, true) >= 0);
assert_se(table_add_many(t,
TABLE_STRING, "fäää",
TABLE_STRING, "zzz",
TABLE_BOOLEAN, false) >= 0);
assert_se(table_add_many(t,
TABLE_EMPTY,
TABLE_SIZE, (uint64_t) 4711,
TABLE_TIMESPAN, (usec_t) 5*USEC_PER_MINUTE) >= 0);
assert_se(table_format(t, &formatted) >= 0);
printf("%s\n", formatted);
assert_se(streq(formatted,
"a long field yyy no\n"
"fäää zzz no\n"
"fäää uuu yes\n"
"xxx yyy yes\n"
" 4.6K 5min\n"));
formatted = mfree(formatted);
assert_se(table_set_display(t, (size_t) 2, (size_t) 0, (size_t) 2, (size_t) 0, (size_t) 0, (size_t) -1) >= 0);
assert_se(table_format(t, &formatted) >= 0);
printf("%s\n", formatted);
assert_se(streq(formatted,
" no a long f… no a long f… a long fi…\n"
" no fäää no fäää fäää \n"
" yes fäää yes fäää fäää \n"
" yes xxx yes xxx xxx \n"
"5min 5min \n"));
return 0;
}

View file

@ -26,6 +26,8 @@ static void test_get_locales(void) {
}
static void test_locale_is_valid(void) {
log_info("/* %s */", __func__);
assert_se(locale_is_valid("en_EN.utf8"));
assert_se(locale_is_valid("fr_FR.utf8"));
assert_se(locale_is_valid("fr_FR@euro"));
@ -43,6 +45,8 @@ static void test_keymaps(void) {
char **p;
int r;
log_info("/* %s */", __func__);
assert_se(!keymap_is_valid(""));
assert_se(!keymap_is_valid("/usr/bin/foo"));
assert_se(!keymap_is_valid("\x01gar\x02 bage\x03"));
@ -65,11 +69,31 @@ static void test_keymaps(void) {
assert_se(keymap_is_valid("unicode"));
}
#define dump_glyph(x) log_info(STRINGIFY(x) ": %s", special_glyph(x))
static void dump_special_glyphs(void) {
assert_cc(ELLIPSIS + 1 == _SPECIAL_GLYPH_MAX);
log_info("/* %s */", __func__);
log_info("is_locale_utf8: %s", yes_no(is_locale_utf8()));
dump_glyph(TREE_VERTICAL);
dump_glyph(TREE_BRANCH);
dump_glyph(TREE_RIGHT);
dump_glyph(TREE_SPACE);
dump_glyph(TRIANGULAR_BULLET);
dump_glyph(BLACK_CIRCLE);
dump_glyph(ARROW);
dump_glyph(MDASH);
dump_glyph(ELLIPSIS);
}
int main(int argc, char *argv[]) {
test_get_locales();
test_locale_is_valid();
test_keymaps();
dump_special_glyphs();
return 0;
}

View file

@ -102,6 +102,15 @@ static void test_utf8_n_codepoints(void) {
assert_se(utf8_n_codepoints("\xF1") == (size_t) -1);
}
static void test_utf8_console_width(void) {
assert_se(utf8_console_width("abc") == 3);
assert_se(utf8_console_width("zażółcić gęślą jaźń") == 19);
assert_se(utf8_console_width("") == 2);
assert_se(utf8_console_width("") == 0);
assert_se(utf8_console_width("…👊🔪💐…") == 8);
assert_se(utf8_console_width("\xF1") == (size_t) -1);
}
int main(int argc, char *argv[]) {
test_utf8_is_valid();
test_utf8_is_printable();
@ -111,6 +120,7 @@ int main(int argc, char *argv[]) {
test_utf8_escaping_printable();
test_utf16_to_utf8();
test_utf8_n_codepoints();
test_utf8_console_width();
return 0;
}