From: Scott Worley Date: Fri, 15 Sep 2023 02:37:29 +0000 (-0700) Subject: -f to specify time format X-Git-Tag: v1.0.0~3 X-Git-Url: http://git.scottworley.com/uniqt/commitdiff_plain/48964c1ecbda205291cd3b6aba15bb89a1e66716?ds=sidebyside;hp=be6fd520dc5a19a0d08a308cb2152f2d2a14f71f -f to specify time format --- diff --git a/uniqt.c b/uniqt.c index a42a001..1c7ee3f 100644 --- a/uniqt.c +++ b/uniqt.c @@ -26,6 +26,10 @@ char *encode_time(time_t t) { return out; } +typedef struct { + char *time_format; +} conf_t; + typedef struct { time_t start, end; } time_range_t; @@ -49,18 +53,36 @@ static char *read_line() { return line; } -static void write_line(time_range_t *range, char *line) { +static void format_time(conf_t *conf, char *buf, size_t size, time_t *t) { + struct tm *tm = localtime(t); + if (tm == NULL) + die_err("Couldn't unpack time"); + if (strftime(buf, size, conf->time_format, tm) == 0) + die_err("Couldn't format time"); +} + +static void write_line(conf_t *conf, time_range_t *range, char *line) { if (line == NULL) return; - if (printf("%ld %ld %s\n", range->start, range->end, line) < 0) - die("Couldn't write"); + if (conf->time_format) { + const size_t MAX_TIMESTAMP_LENGTH = 1024; + char a[MAX_TIMESTAMP_LENGTH]; + char b[MAX_TIMESTAMP_LENGTH]; + format_time(conf, a, MAX_TIMESTAMP_LENGTH, &range->start); + format_time(conf, b, MAX_TIMESTAMP_LENGTH, &range->end); + if (printf("%s %s %s\n", a, b, line) < 0) + die("Couldn't write"); + } else { + if (printf("%ld %ld %s\n", range->start, range->end, line) < 0) + die("Couldn't write"); + } if (fflush(stdout) == EOF) die_err("Couldn't flush"); } static int same(char *a, char *b) { return a && b && strcmp(a, b) == 0; } -static void uniqt() { +static void uniqt(conf_t *conf) { char *current_line = NULL; time_range_t current_time_range = make_time_range(NULL_TIME); for (;;) { @@ -72,17 +94,37 @@ static void uniqt() { free(new_line); extend_time_range(¤t_time_range, now); } else { - write_line(¤t_time_range, current_line); + write_line(conf, ¤t_time_range, current_line); free(current_line); current_line = new_line; current_time_range = make_time_range(now); } } - write_line(¤t_time_range, current_line); + write_line(conf, ¤t_time_range, current_line); free(current_line); } -int main() { - uniqt(); +void usage() { die("usage: uniqt [-f time_format]"); } + +conf_t parse_command_line(int argc, char *argv[]) { + conf_t conf; + conf.time_format = NULL; + + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "-f") == 0) { + if (i + 1 >= argc) + die("-f requires an argument"); + i++; + conf.time_format = argv[i]; + } else + usage(); + } + + return conf; +} + +int main(int argc, char *argv[]) { + conf_t conf = parse_command_line(argc, argv); + uniqt(&conf); return 0; }