commit 83249f12d4ed47c17f103181ac832e388bfa9715
parent 40a93a63a38d6e1991dbba2f4db56dab34900f95
Author: Jacob R. Edwards <n/a>
Date: Tue, 29 Nov 2022 21:56:47 -0600
Mostly rewrite netquery with additional features
The major difference from the user's perspective is that you may
now have a name point to other queries instead of just URLs.
The resolving program has been moved to netquery_resolve to make
things more modular and easier to read. I believe it is written
better now too, although it's bigger to support pointers (and may
need to store every query in memory at times, instead of just one
at a time).
Diffstat:
2 files changed, 69 insertions(+), 20 deletions(-)
diff --git a/local/bin/bin/netquery b/local/bin/bin/netquery
@@ -1,11 +1,18 @@
#!/bin/sh
# Copyright 2021, 2022 Jacob R. Edwards
+# netquery -- Generate netquery
#
-# Generate a query string by appending the given arguments--concatnated
-# on plus ('+')--to the matched prefix in netquery's config.
+# Generate a query string by appending the given arguments concatnated
+# on '+' to the resolved query string (see netquery_resolve).
#
-# A line in the config might look like this:
-# name https://search.domain.domain?q=
+# There are two distinct types of entries to the config: A name
+# which points to another name, and a name which points to a URL.
+# Example:
+#
+# alt main
+# main https://www.main.net/search.php?q=
+#
+# Providing either 'alt' or 'main' will both resolve to the URL.
if test $# -eq 0; then
echo 'netquery [-name] [word ...]' 1>&2
@@ -13,6 +20,7 @@ if test $# -eq 0; then
fi
config="${XDG_CONFIG_HOME:-"$HOME"/.config}"/netquery
+
case "$1" in
(-*)
name="${1#-}"
@@ -21,19 +29,4 @@ case "$1" in
esac
IFS='+'
-exec awk -vquery="$*" -vname="$name" -F ' ' \
-'/^(#|$)/ {
- next
-}
-
-!name || (length($1) == length(name) && index($1, name)) {
- s = $2 query
- exit
-}
-
-END {
- if (s)
- print s
- else
- exit 1
-}' < "$config"
+netquery_resolve "$name" < "$config" | sed "s/$/$*/"
diff --git a/local/bin/bin/netquery_resolve b/local/bin/bin/netquery_resolve
@@ -0,0 +1,56 @@
+#!/usr/bin/awk -f
+# Copyright 2022 Jacob R. Edwards
+# netquery_resolve -- Resolve netquery query
+
+BEGIN {
+ FS="[ ]"
+ name = ARGV[1]
+ delete ARGV[1]
+ --ARGC
+}
+
+function isurl(s) {
+ # See RFC 1738, 2.1. "The main parts of URLs"
+ return match(s, "^[A-Za-z0-9+.-]+://")
+}
+
+/^([ ]*#|$)/ {
+ next
+}
+
+isurl($1) {
+ error = "Cannot have URL as a query name"
+ exit 1
+}
+
+{
+ if (!name)
+ name = $1
+
+ if ($1 == name) {
+ if (isurl($2)) {
+ query = $2
+ exit
+ }
+
+ name = $2
+ if (t[name]) {
+ if (isurl(t[name])) {
+ query = $2
+ exit
+ }
+ error = "Unresolvable (circularily linked)"
+ exit
+ }
+ }
+ t[$1] = $2
+}
+
+END {
+ if (query)
+ print query
+ else {
+ print error ? error : "Could not resolve query" > "/dev/stderr"
+ exit 1
+ }
+}