]> git.scottworley.com Git - uniqt/blobdiff - uniqt.c
-f to specify time format
[uniqt] / uniqt.c
diff --git a/uniqt.c b/uniqt.c
index b755f4eb9def577608ff1bd738a6489b12b38fb0..1c7ee3f169279e3ac1d71c9b8a6422a584397e8c 100644 (file)
--- 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,16 +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 (;;) {
@@ -70,17 +94,37 @@ static void uniqt() {
       free(new_line);
       extend_time_range(&current_time_range, now);
     } else {
-      write_line(&current_time_range, current_line);
+      write_line(conf, &current_time_range, current_line);
       free(current_line);
       current_line = new_line;
       current_time_range = make_time_range(now);
     }
   }
-  write_line(&current_time_range, current_line);
+  write_line(conf, &current_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;
 }