Merge branch 'master' of git.dolda2000.com:/srv/git/r/utils
authorFredrik Tolf <fredrik@dolda2000.com>
Sat, 30 Nov 2013 15:35:12 +0000 (16:35 +0100)
committerFredrik Tolf <fredrik@dolda2000.com>
Sat, 30 Nov 2013 15:35:12 +0000 (16:35 +0100)
nextep.c

index a7bc746..151db93 100644 (file)
--- a/nextep.c
+++ b/nextep.c
@@ -3,9 +3,39 @@
 #include <unistd.h>
 #include <string.h>
 #include <libgen.h>
+#include <dirent.h>
 #include <errno.h>
 #include <sys/stat.h>
 
+static int ensuredir(char *base, char *dir)
+{
+    if(access(dir, X_OK)) {
+       if((mkdir(base, 0777) && (errno != EEXIST)) || mkdir(dir, 0777))
+           return(1);
+    }
+    return(0);
+}
+
+static void checkempty(char *dir)
+{
+    DIR *dh;
+    int empty;
+    struct dirent *de;
+    
+    if((dh = opendir(dir)) == NULL)
+       return;
+    empty = 1;
+    while((de = readdir(dh)) != NULL) {
+       if(de->d_name[0] != '.') {
+           empty = 0;
+           break;
+       }
+    }
+    closedir(dh);
+    if(empty)
+       rmdir(dir);
+}
+
 static void usage(FILE *out)
 {
     fprintf(out, "usage: nextep [-h] [-f FILE] [-s SET-VALUE] [DIR]\n");
@@ -55,12 +85,6 @@ int main(int argc, char **argv)
     }
     snprintf(buf, sizeof(buf), "%s/.nextep", p);
     snprintf(base, sizeof(base), "%s/%s", buf, dir);
-    if(access(base, X_OK)) {
-       if((mkdir(buf, 0777) && (errno != EEXIST)) || mkdir(base, 0777)) {
-           fprintf(stderr, "nextep: %s: %s\n", base, strerror(errno));
-           exit(1);
-       }
-    }
     snprintf(fpath, sizeof(fpath), "%s/%s", base, file);
     if(value == NULL) {
        if((fp = fopen(fpath, "r")) == NULL) {
@@ -78,7 +102,12 @@ int main(int argc, char **argv)
            fprintf(stderr, "nextep: %s: %s\n", fpath, strerror(errno));
            exit(1);
        }
+       checkempty(base);
     } else {
+       if(ensuredir(buf, base)) {
+           fprintf(stderr, "nextep: %s: %s\n", base, strerror(errno));
+           exit(1);
+       }
        if((fp = fopen(fpath, "w")) == NULL) {
            fprintf(stderr, "nextep: %s: %s\n", fpath, strerror(errno));
            exit(1);