From 2998af81dfb7be9b5c1cfe6d7e5a5a167ebbfd81 Mon Sep 17 00:00:00 2001 From: Scott Worley Date: Fri, 8 Sep 2023 13:09:13 -0700 Subject: [PATCH] Write timestamps --- tl-append-test.c | 30 ++++++++++++++++++++++++++++-- tl-append.c | 5 +++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/tl-append-test.c b/tl-append-test.c index 57ceb98..4d51c38 100644 --- a/tl-append-test.c +++ b/tl-append-test.c @@ -10,6 +10,8 @@ #include "common.h" +const size_t TIMESTAMP_LEN = 19; + typedef struct expectation { time_t a, b; const char *message; @@ -51,8 +53,32 @@ static ex_t write_to_tl_append(const char *content) { return expectation(start, end, content); } +static void verify_timestamp(const ex_t *ex, const char *line) { + struct tm tm; + + /* localtime_r to set tm's timezone */ + time_t now_time = time(NULL); + if (localtime_r(&now_time, &tm) == NULL) + die_err("Can't unpack current time?"); + + const char *strptime_result = strptime(line, "%Y %m %d %H %M %S", &tm); + if (strptime_result == NULL || strptime_result != &line[TIMESTAMP_LEN]) + die("Wrong contents in log file: Couldn't parse timestamp"); + time_t t = mktime(&tm); + int t_in_range = ex->a <= t && t <= ex->b; + if (!t_in_range) + die("Wrong contents in log file: Wrong time"); +} + static void verify_line(const ex_t *ex, const char *line) { - if (strncmp(ex->message, line, strlen(ex->message) + 1) != 0) + size_t line_len = strlen(line); + if (line_len < TIMESTAMP_LEN + 1) + die("Wrong contents in log file: Line too short"); + verify_timestamp(ex, line); + if (line[TIMESTAMP_LEN] != ' ') + die("Wrong contents in log file: Bad format"); + if (strncmp(ex->message, &line[TIMESTAMP_LEN + 1], strlen(ex->message) + 1) != + 0) die("Wrong contents in log file"); } @@ -62,7 +88,7 @@ static void verify_log_contents(ex_t exps[]) { if (f == NULL) die_err("Error opening log file"); for (size_t i = 0; !is_end(exps[i]); i++) { - size_t len = strlen(exps[i].message); + size_t len = TIMESTAMP_LEN + 1 + strlen(exps[i].message); char *buf = (char *)malloc(len + 2); if (fgets(buf, len + 1, f) == NULL) die("Error reading log file"); diff --git a/tl-append.c b/tl-append.c index c2f476f..f8bacdd 100644 --- a/tl-append.c +++ b/tl-append.c @@ -18,9 +18,14 @@ static void read_line(char *buf) { } static void write_line(const char *line) { + const char *now = encode_time(time(NULL)); FILE *f = fopen(FILENAME, "a"); if (f == NULL) die_err("Error opening output file"); + if (fputs(now, f) == EOF) + die("Error writing to output file"); + if (fputc(' ', f) == EOF) + die("Error writing to output file"); if (fputs(line, f) == EOF) die("Error writing to output file"); if (fclose(f) != 0) -- 2.44.1