aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGravatar Benjamin Barenblat <bbaren@google.com>2019-09-16 11:21:44 -0400
committerGravatar Benjamin Barenblat <bbaren@google.com>2019-09-16 11:21:44 -0400
commit66cdcec22a236171d2f630747e04d69c590f7dfc (patch)
tree9b0c19ea67aad041f54c1be207b37c4609e44f40
parent82cd3de3f4acb0e7a19ebec91baa0eba0d23bd9b (diff)
Support --help option
-rwxr-xr-xsor42
-rw-r--r--walk.c39
2 files changed, 78 insertions, 3 deletions
diff --git a/sor b/sor
index 12f5652..0960db8 100755
--- a/sor
+++ b/sor
@@ -13,6 +13,48 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+short_usage() {
+ echo 'Usage: sor SNIPPET...'
+}
+
+help() {
+ short_usage
+ cat <<EOF
+For each line from standard input, evaluate the specified SNIPPETs under Bash
+with the line as the argument. Print the line if any snippet exits with
+status 0.
+
+ --help display this help and exit
+EOF
+}
+
+ask_for_help() {
+ echo "Try 'sor --help' for more information."
+}
+
+if ! temp=$(getopt -s bash -n sor -o '' -l help -- "$@"); then
+ ask_for_help >&2
+ exit 1
+fi
+eval set -- "$temp"
+unset temp
+while true; do
+ case "$1" in
+ --help)
+ help
+ exit 0
+ ;;
+ --)
+ shift
+ break
+ ;;
+ *)
+ echo >&2 'Internal error; please report.'
+ exit 1
+ ;;
+ esac
+done
+
while read file; do
for test in "$@"; do
if eval "$test \"$file\""; then
diff --git a/walk.c b/walk.c
index 6cce89a..8c20fd0 100644
--- a/walk.c
+++ b/walk.c
@@ -13,11 +13,22 @@
// limitations under the License.
#include <errno.h>
+#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
+#include <getopt.h>
+
+static const char SHORT_USAGE[] = "Usage: walk [DIRECTORY...]\n";
+
+static const char HELP[] =
+ "Recursively walk the specified directories (or current directory, if none is\n"
+ "specified.\n\n"
+ " --help display this help and exit\n";
+
+static const char ASK_FOR_HELP[] = "Try 'walk --help' for more information.\n";
static const char *const JUST_CURRENT_DIRECTORY[] = {".", NULL};
@@ -86,11 +97,33 @@ static int walk(const char dirname[])
return r;
}
-int main(const int argc, const char *const argv[])
+int main(const int argc, char *const argv[])
{
+ static const struct option long_options[] = {
+ {"help", no_argument, NULL, 'h'},
+ {NULL, 0, NULL, 0},
+ };
+ while (true) {
+ const int c = getopt_long(argc, argv, "", long_options, NULL);
+ if (c == -1)
+ break;
+ switch (c) {
+ case 'h':
+ fputs(SHORT_USAGE, stdout);
+ fputs(HELP, stdout);
+ return 0;
+ case '?':
+ fputs(ASK_FOR_HELP, stderr);
+ return 1;
+ default:
+ fputs("Internal error; please report.\n", stderr);
+ return 1;
+ }
+ }
+
int r = 0;
- const char *const *const dirs =
- argc == 1 ? JUST_CURRENT_DIRECTORY : argv + 1;
+ const char *const *const dirs = argc == optind ? JUST_CURRENT_DIRECTORY
+ : (const char *const *)argv + optind;
for (int i = 0; dirs[i]; ++i) {
puts(dirs[i]);
r |= walk(dirs[i]);