aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDag-Erling Smørgrav <des@FreeBSD.org>2025-10-23 10:28:44 +0000
committerDag-Erling Smørgrav <des@FreeBSD.org>2025-10-23 10:29:01 +0000
commit4d5789532a940144c869d66505e756ce816f8a50 (patch)
treeaa09b1e0a45e875b67b1054ac2cedea7d91872bb
parentbfda98a42027417b2fa74738c63327532013e93b (diff)
w: Trim whitespace and commas from time and uptime
When producing formatted output, trim leading whitespace and trailing commas from the human-readable time and uptime before emitting them. The text output remains unchanged. PR: 290089 Fixes: 6e6febb54da9 ("w: Fix idle time in json output, add login/idle times to json output") Reviewed by: marius.h_lden.org Differential Revision: https://reviews.freebsd.org/D53167
-rw-r--r--usr.bin/w/w.c33
1 files changed, 25 insertions, 8 deletions
diff --git a/usr.bin/w/w.c b/usr.bin/w/w.c
index ac1df96077d3..502bf5a412b9 100644
--- a/usr.bin/w/w.c
+++ b/usr.bin/w/w.c
@@ -473,7 +473,7 @@ main(int argc, char *argv[])
static void
pr_header(time_t *nowp, int nusers)
{
- char buf[64];
+ char buf[64], *s, *e;
struct sbuf upbuf;
double avenrun[3];
struct timespec tp;
@@ -484,8 +484,15 @@ pr_header(time_t *nowp, int nusers)
* Print time of day.
*/
if (strftime(buf, sizeof(buf),
- use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp)) != 0)
- xo_emit("{:time-of-day/%s} ", buf);
+ use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp)) != 0) {
+ s = buf;
+ if (xo_get_style(NULL) != XO_STYLE_TEXT) {
+ /* trim leading whitespace */
+ while (isspace((unsigned char)*s))
+ s++;
+ }
+ xo_emit("{:time-of-day/%s} ", s);
+ }
/*
* Print how long system has been up.
*/
@@ -516,21 +523,31 @@ pr_header(time_t *nowp, int nusers)
if (days > 0)
sbuf_printf(&upbuf, " %ld day%s,",
- days, days > 1 ? "s" : "");
+ days, days > 1 ? "s" : "");
if (hrs > 0 && mins > 0)
sbuf_printf(&upbuf, " %2ld:%02ld,", hrs, mins);
else if (hrs > 0)
sbuf_printf(&upbuf, " %ld hr%s,",
- hrs, hrs > 1 ? "s" : "");
+ hrs, hrs > 1 ? "s" : "");
else if (mins > 0)
sbuf_printf(&upbuf, " %ld min%s,",
- mins, mins > 1 ? "s" : "");
+ mins, mins > 1 ? "s" : "");
else
sbuf_printf(&upbuf, " %ld sec%s,",
- secs, secs > 1 ? "s" : "");
+ secs, secs > 1 ? "s" : "");
if (sbuf_finish(&upbuf) != 0)
xo_err(1, "Could not generate output");
- xo_emit("{:uptime-human/%s}", sbuf_data(&upbuf));
+ s = sbuf_data(&upbuf);
+ if (xo_get_style(NULL) != XO_STYLE_TEXT) {
+ e = s + sbuf_len(&upbuf) - 1;
+ /* trim leading whitespace */
+ while (isspace((unsigned char)*s))
+ s++;
+ /* trim trailing comma */
+ if (e > s && *e == ',')
+ *e = '\0';
+ }
+ xo_emit("{:uptime-human/%s}", s);
sbuf_delete(&upbuf);
}