From 7de090ce91715ac3a50c01085d69510369fc5d2d Mon Sep 17 00:00:00 2001
From: Kubat <mael.martin31@gmail.com>
Date: Sun, 2 May 2021 00:02:23 +0200
Subject: [PATCH] LKT: Try to produce a cleaner code

---
 inc/lektor/common.h |   1 +
 src/main/lkt.c      | 165 ++++++++++++++++++--------------------------
 2 files changed, 70 insertions(+), 96 deletions(-)

diff --git a/inc/lektor/common.h b/inc/lektor/common.h
index d6dd82e2..0c391461 100644
--- a/inc/lektor/common.h
+++ b/inc/lektor/common.h
@@ -49,6 +49,7 @@ extern EXIT_FUNCTION ___not_implemented(const char *func, char *file, int line);
 #define RETURN_UNLESS(cond, msg, ret) RETURN_IF(!(cond), msg, ret)
 #define NOTHING                       /* Usefull to return nothing in previous macros */
 
+#define STRTOL_ERROR(integer) (errno == ERANGE || (errno != 0 && (integer) == 0))
 #define STRTOL(ret, str, endptr, err_flag)                                                                             \
     ({                                                                                                                 \
         err_flag = 0;                                                                                                  \
diff --git a/src/main/lkt.c b/src/main/lkt.c
index 748cbd19..75d2e224 100644
--- a/src/main/lkt.c
+++ b/src/main/lkt.c
@@ -27,7 +27,7 @@
     if (STR_NMATCH(buffer, "OK", 2)) {                                                                                 \
         ok;                                                                                                            \
     } else if (STR_NMATCH(buffer, "ACK", 3))                                                                           \
-        exit(EXIT_FAILURE);
+        LOG_FATAL("Got the 'ACK' status from lektord: %s", buffer);
 
 /* Type definition. */
 
@@ -41,9 +41,12 @@ typedef struct {
 
 /* Global variables. */
 
+#define LKT_MAX_OPTIONS 3 /* Number of options that can be passed to lkt before the commands. */
 static const char *host;
 static const char *port;
 static const char *password;
+
+/* Default queue length to query */
 static const char *LKT_QUEUE_DEFAULT[] = { "10" };
 
 /* Communication functions and fonction that interact with lektor stuff. */
@@ -151,7 +154,8 @@ static int
 read_socket(FILE *sock, char *buff, size_t max_len)
 {
     size_t i, len;
-    for (i = 0; i < max_len; ++i) {
+    memset(buff, 0, max_len * sizeof(char));
+    for (i = 0; i < max_len - 1; ++i) {
         len = fread(buff + i, sizeof(char), 1, sock);
         if (buff[i] == '\n' || len != 1)
             break;
@@ -223,12 +227,11 @@ lkt_connect(void)
 static void
 write_socket(FILE *sock, const char *format, ...)
 {
-    int size;
     char buff[LKT_MESSAGE_MAX];
     va_list ap;
 
     va_start(ap, format);
-    size = safe_vsnprintf(buff, LKT_MESSAGE_MAX - 1, format, ap);
+    int size = safe_vsnprintf(buff, LKT_MESSAGE_MAX - 1, format, ap);
 
     FAIL_IF(size < 0, "Connexion error");
     FAIL_IF(fwrite(buff, sizeof(char), size, sock) < (unsigned int)size, "Connexion error");
@@ -374,29 +377,19 @@ rescan_or_update__(struct cmd_args *args, const char *cmd)
     exit(EXIT_SUCCESS);
 }
 
-EXIT_FUNCTION
-rescan__(struct cmd_args *args)
-{
-    rescan_or_update__(args, "rescan");
-}
-
-EXIT_FUNCTION
-update__(struct cmd_args *args)
-{
-    rescan_or_update__(args, "update");
-}
-
-EXIT_FUNCTION
-import__(struct cmd_args *args)
-{
-    rescan_or_update__(args, "__import");
-}
-
-EXIT_FUNCTION
-populate__(struct cmd_args *args)
-{
-    rescan_or_update__(args, "__rescan");
-}
+#define ___just_send_with_password(func, cmd)                                                                          \
+    EXIT_FUNCTION                                                                                                      \
+    func(struct cmd_args *args)                                                                                        \
+    {                                                                                                                  \
+        rescan_or_update__(args, cmd);                                                                                 \
+    }                                                                                                                  \
+// clang-format off
+___just_send_with_password(rescan__, "rescan");
+___just_send_with_password(update__, "update");
+___just_send_with_password(import__, "__import");
+___just_send_with_password(populate__, "__rescan");
+// clang-format on
+#undef ___just_send_with_password
 
 EXIT_FUNCTION
 queue_replace__(struct cmd_args *args)
@@ -417,10 +410,7 @@ queue_replace__(struct cmd_args *args)
             break;
         }
 
-        if (STR_NMATCH(buff, "OK", 2))
-            break;
-        else if (STR_NMATCH(buff, "ACK", 3))
-            LOG_FATAL("ACK");
+        ___HANDLE_STATUS(buff, { break; });
     }
 
     fclose(sock);
@@ -439,7 +429,7 @@ config__(struct cmd_args *args)
 {
     int ret = EXIT_SUCCESS;
     if (args->argc == 0)
-        fwrite(lkt_default_config_file, sizeof(char), strlen(lkt_default_config_file), stdout);
+        fprintf(stdout, "%s", lkt_default_config_file);
     exit(ret);
 }
 
@@ -615,11 +605,19 @@ status__(struct cmd_args *args)
     char buff[LKT_MESSAGE_MAX];
     char flags[24];
 
-    bool play = false, stopped = true, is_updating = false;
-    int time_pos = 0, time_duration = 0, song_index = 0, plt_len = 0, it = 0;
-    int update_count = 0, update_tick = 0;
+    bool play        = false;
+    bool stopped     = true;
+    bool is_updating = false;
+
+    int time_pos      = 0;
+    int time_duration = 0;
+    int song_index    = 0;
+    int plt_len       = 0;
+    int it            = 0;
+    int update_count  = 0;
+    int update_tick   = 0;
+    time_t update_ts  = 0;
     size_t len;
-    time_t update_ts = 0;
 
     memset(flags, 0, 24 * sizeof(char));
     FILE *sock = lkt_connect();
@@ -647,9 +645,8 @@ status__(struct cmd_args *args)
     /* Get lektor's status */
     write_socket(sock, status_str__);
     FOR_EVER {
-        len       = read_socket(sock, buff, LKT_MESSAGE_MAX - 1);
-        buff[len] = '\0';
-        len       = strcspn(buff, LKT_KEY_VALUE_SEP);
+        read_socket(sock, buff, LKT_MESSAGE_MAX - 1);
+        len = strcspn(buff, LKT_KEY_VALUE_SEP);
 
         if (STR_NMATCH(buff, "state", len)) {
             char *it = lkt_skip_key(buff);
@@ -668,9 +665,8 @@ status__(struct cmd_args *args)
     /* Get lektor's stats */
     write_socket(sock, stats_str__);
     FOR_EVER {
-        len       = read_socket(sock, buff, LKT_MESSAGE_MAX - 1);
-        buff[len] = '\0';
-        len       = strcspn(buff, LKT_KEY_VALUE_SEP);
+        read_socket(sock, buff, LKT_MESSAGE_MAX - 1);
+        len = strcspn(buff, LKT_KEY_VALUE_SEP);
 
         assign_int("__is_updating", is_updating) assign_int("db_update", update_ts);
         assign_two_int("__update_progress", update_tick, update_count);
@@ -689,10 +685,10 @@ status__(struct cmd_args *args)
     len             = strftime(buff, LKT_MESSAGE_MAX - 1, "%F %H:%M:%S", p_tm);
     buff[len]       = '\0';
 
-    int pla_m  = time_pos / 60;
-    char pla_s = time_pos % 60;
-    int dur_m  = time_duration / 60;
-    char dur_s = time_duration % 60;
+    int pla_m = time_pos / 60;
+    int pla_s = time_pos % 60;
+    int dur_m = time_duration / 60;
+    int dur_s = time_duration % 60;
 
     printf("Lektor: %s\n"
            "Queue: #%d/%d\n"
@@ -778,12 +774,10 @@ queue_seek__(struct cmd_args *args)
     FAIL_IF(args->argc != 1, "The seek command needs one argument: queue seek <id>");
 
     char *endptr, buf[3];
+    errno   = 0;
     long id = strtol(args->argv[0], &endptr, 0);
 
-    errno = 0;
-    FAIL_IF(errno == ERANGE || (errno != 0 && id == 0) || (endptr == args->argv[0]),
-            "Invalid argument, not an integer");
-
+    FAIL_IF(STRTOL_ERROR(id) || (endptr == args->argv[0]), "Invalid argument, not an integer");
     FAIL_IF(*endptr != '\0', "Invalid argument, must be only one integer");
 
     FILE *sock = lkt_connect();
@@ -799,11 +793,11 @@ queue_pos__(struct cmd_args *args)
     FAIL_IF(args->argc != 1,
             "Invalid argument for the pos command: queue pos <arg> where arg is a position or a range");
 
-    long continuation = 0, up = 0;
+    long up           = 0;
+    errno             = 0;
+    long continuation = strtol(args->argv[0], &endptr, 0);
 
-    errno        = 0;
-    continuation = strtol(args->argv[0], &endptr, 0);
-    FAIL_IF(errno == ERANGE || (errno != 0 && continuation == 0) || (endptr == args->argv[0]),
+    FAIL_IF(STRTOL_ERROR(continuation) || (endptr == args->argv[0]),
             "Invalid argument, not an integer: queue pos <arg> where arg is a position or a range");
 
     if (*endptr != '\0') {
@@ -832,11 +826,7 @@ redo:
             }
         }
 
-        if (STR_NMATCH(buff, "OK", 2))
-            exit(EXIT_SUCCESS);
-        else if (STR_NMATCH(buff, "ACK", 3))
-            exit(EXIT_FAILURE);
-
+        ___HANDLE_STATUS(buff, { exit(EXIT_SUCCESS); });
         fprintf(stdout, "%s", buff);
     }
 }
@@ -857,9 +847,7 @@ queue_list__(struct cmd_args *args)
         FAIL_IF(args->argc != 1, "Invalid argument: queue <count?>");
 
     continuation = strtol(args->argv[0], &endptr, 0);
-    FAIL_IF(errno == ERANGE || (errno != 0 && continuation == 0) || (endptr == args->argv[0]),
-            "Invalid argument, not an integer");
-
+    FAIL_IF(STRTOL_ERROR(continuation) || (endptr == args->argv[0]), "Invalid argument, not an integer");
     FAIL_IF(*endptr != '\0', "Invalid argument");
 
     /* Get the current pos to get limits for the playlist command. */
@@ -879,10 +867,7 @@ queue_list__(struct cmd_args *args)
         assign_int("song", song_index);
 
         /* At this point every key has been parsed. */
-        if (STR_NMATCH(buff, "OK", 2))
-            break;
-        else if (STR_NMATCH(buff, "ACK", 3))
-            exit(EXIT_FAILURE);
+        ___HANDLE_STATUS(buff, { break; });
     }
 #undef assign_int
     fclose(sock);
@@ -956,10 +941,7 @@ stickers_get__(struct cmd_args *args)
     FOR_EVER {
         memset(buff, 0, LKT_MESSAGE_MAX * sizeof(char));
         read_socket(sock, buff, LKT_MESSAGE_MAX - 1);
-        if (STR_NMATCH(buff, "OK", 2))
-            exit(EXIT_SUCCESS);
-        else if (STR_NMATCH(buff, "ACK", 3))
-            exit(EXIT_FAILURE);
+        ___HANDLE_STATUS(buff, { exit(EXIT_SUCCESS); });
         fprintf(stdout, "%s", buff);
     }
 }
@@ -996,6 +978,7 @@ __continuation_calls(const char *cmd)
     char buff[LKT_MESSAGE_MAX];
     int continuation = 0;
     FILE *sock       = NULL;
+
 redo:
     sock = lkt_connect();
 
@@ -1010,15 +993,13 @@ redo:
             goto redo;
         }
 
-        if (STR_NMATCH(buff, "OK", 2))
-            exit(EXIT_SUCCESS);
-        else if (STR_NMATCH(buff, "ACK", 3))
-            exit(EXIT_FAILURE);
+        ___HANDLE_STATUS(buff, { exit(EXIT_SUCCESS); });
 
         if (STR_NMATCH(buff, "name: ", strlen("name: "))) {
             char *real_line = buff + sizeof("name: ") - sizeof(char);
             memmove(buff, real_line, (1 + strlen(real_line)) * sizeof(char));
         }
+
         fprintf(stdout, "%s", buff);
     }
 }
@@ -1064,11 +1045,7 @@ redo:
             goto redo;
         }
 
-        if (STR_NMATCH(buff, "OK", 2))
-            exit(EXIT_SUCCESS);
-        else if (STR_NMATCH(buff, "ACK", 3))
-            exit(EXIT_FAILURE);
-
+        ___HANDLE_STATUS(buff, { exit(EXIT_SUCCESS); });
         fprintf(stdout, "%s", buff);
     }
 }
@@ -1086,10 +1063,7 @@ search_get__(struct cmd_args *args)
     FOR_EVER {
         memset(buff, 0, LKT_MESSAGE_MAX * sizeof(char));
         read_socket(sock, buff, LKT_MESSAGE_MAX - 1);
-        if (STR_NMATCH(buff, "OK", 2))
-            exit(EXIT_SUCCESS);
-        else if (STR_NMATCH(buff, "ACK", 3))
-            exit(EXIT_FAILURE);
+        ___HANDLE_STATUS(buff, { exit(EXIT_SUCCESS); });
         sink = write(1, buff, strlen(buff));
     }
 }
@@ -1113,6 +1087,7 @@ search_plt__(struct cmd_args *args)
 
     FAIL_IF(args->argc < 2, "Invalid number of arguments");
     FAIL_IF(lkt_get_query_type(&args_regex, regex, LKT_MESSAGE_MAX), "Query is invalid");
+
 redo:
     sock = lkt_connect();
     write_socket(sock, "%d listplaylistinfo %s %s\n", continuation, args->argv[0], regex);
@@ -1127,11 +1102,7 @@ redo:
             goto redo;
         }
 
-        if (STR_NMATCH(buff, "OK", 2))
-            exit(EXIT_SUCCESS);
-        else if (STR_NMATCH(buff, "ACK", 3))
-            exit(EXIT_FAILURE);
-
+        ___HANDLE_STATUS(buff, { exit(EXIT_SUCCESS); });
         fprintf(stdout, "%s", buff);
     }
 }
@@ -1141,8 +1112,11 @@ redo:
     {                                                                                                                  \
         search_with_cmd__(args, #cmd);                                                                                 \
     }
-search_with_cmd(search_db__, search) search_with_cmd(search_count__, count);
+// clang-format off
+search_with_cmd(search_db__, search);
+search_with_cmd(search_count__, count);
 search_with_cmd(search_queue__, playlistfind);
+// clang-format on
 #undef search_with_cmd
 
 /* Parsing stuff. */
@@ -1264,19 +1238,18 @@ parse_args(args_t *args, int argc, const char **argv)
     int i, got = 0;
     size_t len;
 
-    /* XXX: Here 4 is the max number of arguments... */
-    for (i = 1; i < argc && i < 4; ++i) {
+    for (i = 1; i < argc && i < LKT_MAX_OPTIONS; ++i) {
         len = strcspn(argv[i], "=:");
 
-#define __get_args(name)                                                                                               \
+#define ___get_args(name)                                                                                              \
     if (STR_NMATCH(#name, argv[i], len)) {                                                                             \
         args->name = (argv[i] + len + 1);                                                                              \
         ++got;                                                                                                         \
     }
-        __get_args(host);
-        __get_args(port);
-        __get_args(pwd);
-#undef __get_args
+        ___get_args(host);
+        ___get_args(port);
+        ___get_args(pwd);
+#undef ___get_args
     }
 
     args->argv = &argv[got + 1];
-- 
GitLab