From fdd8f1fe2d5ad5b0e09b00c919499d9fe9008c1f Mon Sep 17 00:00:00 2001 From: Anthony Wang Date: Tue, 2 Jan 2024 19:25:44 -0600 Subject: Noninteractive mode This mode accepts inputs with newlines and doesn't disable input buffering. This is useful for using SDC as a backend for GUIs such as https://git.exozy.me/a/SDGUI. --- sd.c | 37 +++++++++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/sd.c b/sd.c index cd8195d..0e39156 100644 --- a/sd.c +++ b/sd.c @@ -10,19 +10,21 @@ int main(int argc, char* argv[]) { char *file = "cards"; bool verbose = false; + bool noninteractive = false; /* Proccess args */ static struct option long_options[] = { - {"file", required_argument, NULL, 'f'}, - {"verbose", no_argument, NULL, 'v'} + {"file", required_argument, NULL, 'f'}, + {"verbose", no_argument, NULL, 'v'}, + {"noninteractive", no_argument, NULL, 'n'} }; while (true) { - int option_index = 0; - int c = getopt_long(argc, argv, "f:v", long_options, &option_index); + int c = getopt_long(argc, argv, "f:vn", long_options, NULL); if (c == -1) break; switch (c) { case 'f': file = optarg; break; case 'v': verbose = true; break; + case 'n': noninteractive = true; break; default: abort(); } } @@ -54,9 +56,11 @@ int main(int argc, char* argv[]) { printf("\n"); } - /* Disable input buffering */ - assert(system("stty -F /dev/tty cbreak min 1") == 0); - assert(system("stty -F /dev/tty -echo") == 0); + if (!noninteractive) { + /* Disable input buffering */ + assert(system("stty -F /dev/tty cbreak min 1") == 0); + assert(system("stty -F /dev/tty -echo") == 0); + } while (true) { /* Make sure sum of weights is positive */ @@ -76,14 +80,28 @@ int main(int argc, char* argv[]) { sqlite3_bind_int(stmt, 1, i); sqlite3_step(stmt); printf("> %s\n", sqlite3_column_text(stmt, 0)); + if (noninteractive) { + fflush(stdout); + } /* Wait for confirmation */ - char b = getchar(); + getchar(); + if (noninteractive) { + /* Skip newline */ + getchar(); + } printf("%s\n", sqlite3_column_text(stmt, 1)); + if (noninteractive) { + fflush(stdout); + } sqlite3_finalize(stmt); /* Read user input */ - b = getchar(); + char b = getchar(); + if (noninteractive) { + /* Skip newline */ + getchar(); + } if (b == 'y') w >>= 1; else if (b == 'n') w <<= 3; else break; @@ -99,5 +117,4 @@ int main(int argc, char* argv[]) { /* Cleanup */ sqlite3_close(db); - assert(system("stty -F /dev/tty echo") == 0); } -- cgit v1.2.3-70-g09d2