xref: /aosp_15_r20/external/toybox/toys/other/ts.c (revision cf5a6c84e2b8763fc1a7db14496fd4742913b199)
1 /* ts.c - timestamp input lines
2  *
3  * Copyright 2023 Oliver Webb <[email protected]>
4  *
5  * No standard.
6 
7 USE_TS(NEWTOY(ts, "ims", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_LINEBUF))
8 
9 config TS
10   bool "ts"
11   default y
12   help
13     usage: ts [-is] [FORMAT]
14 
15     Add timestamps to each line in pipeline. Default format without options
16     "%b %d %H:%M:%S", with -i or -s "%H:%M:%S".
17 
18     -i	Incremental (since previous line)
19     -m	Add milliseconds
20     -s	Since start
21 */
22 
23 #define FOR_ts
24 #include "toys.h"
25 
26 // because millitime() is monotonic, which returns uptime.
millinow(void)27 static long long millinow(void)
28 {
29   struct timespec ts;
30 
31   clock_gettime(CLOCK_REALTIME, &ts);
32 
33   return ts.tv_sec*1000+ts.tv_nsec/1000000;
34 }
35 
ts_main(void)36 void ts_main(void)
37 {
38   char *line, *mm = toybuf+sizeof(toybuf)-8,
39        *format = toys.optflags ? "%T" : "%b %d %T";
40   long long start = millinow(), now, diff, rel = FLAG(i) || FLAG(s);
41   struct tm *tm;
42   time_t tt;
43 
44   for (; (line = xgetline(stdin)); free(line)) {
45     now = millinow();
46     diff = now - start*rel;
47     if (FLAG(m)) sprintf(mm, ".%03lld", diff%1000);
48     tt = diff/1000;
49     tm = rel ? gmtime(&tt) : localtime(&tt);
50     if (FLAG(i)) start = now;
51     strftime(toybuf, sizeof(toybuf)-16, *toys.optargs ? : format, tm);
52     xprintf("%s%s %s\n", toybuf, mm, line);
53   }
54 }
55