gawk

[old] Sed-like interface to the Gopher protocol
Log | Files | Refs | LICENSE

commit 6b5020147b2463f76edc94b6035ea3b6373f1a22
parent 9f979287ca878ea53868ba6159f44ef09d26001f
Author: Jacob R. Edwards <jacobouno@protonmail.com>
Date:   Sun, 20 Dec 2020 20:07:16 -0800

Improve `p` command

Allow restricting what is printed by item type and a case insensitive
substring match.

Diffstat:
Mmain.c | 61+++++++++++++++++++++++++++++--------------------------------
1 file changed, 29 insertions(+), 32 deletions(-)

diff --git a/main.c b/main.c @@ -67,7 +67,10 @@ wfopen(const char *path, const char *mode) int wfclose(FILE *fp) { - if (fclose(fp) == EOF) { + int error; + + error = ferror(fp); + if (fclose(fp) || error) { warn("unable to close file"); return EOF; } @@ -204,7 +207,6 @@ fetch(int sock, const char *path) { FILE *fp; char buf[BUFSIZE]; - int error; ssize_t bytes; struct pollfd pfd; @@ -230,36 +232,12 @@ fetch(int sock, const char *path) } } - error = ferror(fp); - if (wfclose(fp) || error) + if (wfclose(fp)) return 1; return 0; } int -fput(FILE *fp) -{ - char buf[BUFSIZE]; - size_t bytes; - - while ((bytes = fread(buf, 1, sizeof(buf), fp)) > 0) { - /* NOTE: using fwrite and `stdout` causes piping - * to not work. - */ - if (write(STDOUT_FILENO, buf, bytes) != bytes) { - warn("unable to write buffer"); - return 1; - } - } - - if (ferror(fp)) { - warn("putfd FILE"); - return 1; - } - return 0; -} - -int gphsend(int sock, const char *request) { if (send(sock, request, strlen(request), 0) == -1) { @@ -388,18 +366,37 @@ cback(int argc, const char **argv) return back; } +/* argv[0], if present, restricts item types to one type contained + * in it, `.' is a wildcard. argv[1], if present, restricts by + * matches to strcasecmp. + */ int -cputs(const char *path, int argc, const char **argv) +cmatch(const char *path, int argc, const char **argv) { FILE *fp; - int status; + char *line; + size_t size; + int anytype; fp = wfopen(path, "r"); if (fp == NULL) return 1; - status = fput(fp); - if (wfclose(fp) || status) + if (!argv[0] || strchr(argv[0], '.')) + anytype = 1; + else anytype = 0; + + line = NULL; + size = 0; + while (getline(&line, &size, fp) != -1) { + if (anytype || argc < 1 || strchr(argv[0], *line)) { + if (argc < 2 || strcasestr(line, argv[1])) + dprintf(STDOUT_FILENO, "%s", line); + } + } + free(line); + + if (wfclose(fp)) return 1; return 0; } @@ -414,7 +411,7 @@ execute(int command, int argc, const char **argv, int depth, const char *cache, goto too_many_args; return depth; case 'p': - efmt(cputs, cache, argc, argv); + efmt(cmatch, cache, argc, argv); return 0; case 'b': if (argc > 1)