[hackers] [sbase][PATCH] test: add -E

From: Mattias Andrée <maandree_AT_kth.se>
Date: Mon, 28 Mar 2016 23:50:42 +0200

This is an non-standard extension.

It tests with a file exists, is a directory, and is empty.
Tests against non-existing files, non-directories and non-empty
directories causes exit status 1.

It is a sane alternative to writing

  test -z "$(ls -A "$1")"

Signed-off-by: Mattias Andrée <maandree_AT_kth.se>
---
 test.1 |  4 +++-
 test.c | 29 +++++++++++++++++++++++++++++
 2 files changed, 32 insertions(+), 1 deletion(-)
diff --git a/test.1 b/test.1
index 539016a..b1d2121 100644
--- a/test.1
+++ b/test.1
_AT_@ -22,13 +22,15 @@ exists and has (any size
 .Op Fl e
 | non-zero size
 .Op Fl s ) .
-.It ( Fl f | Fl d | Fl p | Fl hL | Fl S | Fl b | Fl c ) Ar file
+.It ( Fl f | Fl d | Fl E | Fl p | Fl hL | Fl S | Fl b | Fl c ) Ar file
 .Ar file
 exists and is a
 (regular file
 .Op Fl f
 | directory
 .Op Fl d
+| empty directory
+.Op Fl E
 | named pipe
 .Op Fl p
 | symbolic link
diff --git a/test.c b/test.c
index 3fe12c3..7e27c10 100644
--- a/test.c
+++ b/test.c
_AT_@ -2,6 +2,8 @@
 #include <sys/stat.h>
 
 #include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
 #include <string.h>
 #include <unistd.h>
 
_AT_@ -112,6 +114,32 @@ binary_nt(char *s1, char *s2)
 	return mtimecmp(&buf1, &buf2) > 0;
 }
 
+static int
+unary_E(char *s)
+{
+	struct stat buf;
+        DIR *dir;
+        struct dirent *file;
+
+	if (stat(s, &buf) || !S_ISDIR(buf.st_mode))
+		return 0;
+
+	if (!(dir = opendir(s)))
+                enprintf(2, "opendir %s:", s);
+	while (errno = 0, (file = readdir(dir))) {
+		if (strcmp(file->d_name, ".") && strcmp(file->d_name, "..")) {
+			closedir(dir);
+			return 0;
+		}
+	}
+        if (errno)
+                enprintf(2, "readdir %s:", s);
+        closedir(dir);
+        return 1;
+
+
+}
+
 struct test {
 	char *name;
 	int (*func)();
_AT_@ -121,6 +149,7 @@ static struct test unary[] = {
 	{ "-b", unary_b },
 	{ "-c", unary_c },
 	{ "-d", unary_d },
+	{ "-E", unary_E },
 	{ "-e", unary_e },
 	{ "-f", unary_f },
 	{ "-g", unary_g },
-- 
2.7.4
Received on Mon Mar 28 2016 - 23:50:42 CEST

This archive was generated by hypermail 2.3.0 : Tue Mar 29 2016 - 00:00:52 CEST