empty-dirs

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

commit c515a8c1e2dcc5e28b7477a1fb69c9c564c417f0
Author: phoebos <ben@bvnf.space>
Date:   Tue,  1 Aug 2023 15:01:59 +0100

init

Diffstat:
AMakefile | 5+++++
Aempty-dirs.c | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aempty-dirs.lua | 41+++++++++++++++++++++++++++++++++++++++++
3 files changed, 113 insertions(+), 0 deletions(-)

diff --git a/Makefile b/Makefile @@ -0,0 +1,5 @@ +.POSIX: + +all: empty-dirs +clean: + rm -f empty-dirs diff --git a/empty-dirs.c b/empty-dirs.c @@ -0,0 +1,67 @@ +#include <dirent.h> +#include <fcntl.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <unistd.h> + +int +dfs(char *path) { + struct dirent *dp; + int dfd, i; + DIR *d = opendir(path); + if (d == NULL) { + perror(path); + return 1; + } + + dfd = dirfd(d); + + i = 0; + while ((dp = readdir(d)) != NULL) { + struct stat sb; + + if (strcmp(dp->d_name, ".") == 0 || + strcmp(dp->d_name, "..") == 0) + continue; + + i++; + + fstatat(dfd, dp->d_name, &sb, 0); + if (S_ISDIR(sb.st_mode)) { + char *fullpath = calloc(1, strlen(path) + strlen(dp->d_name) + 2); + if (fullpath == NULL) { + perror("calloc"); + exit(1); + } + + strcat(fullpath, path); + strcat(fullpath, "/"); + strcat(fullpath, dp->d_name); + + dfs(fullpath); + free(fullpath); + } + } + if (i == 0) + printf("%s\n", path); + + closedir(d); + + return 0; +} + +int +main(int argc, char **argv) { + if (argc == 1) { + fprintf(stderr, "usage: %s dir...\n", argv[0]); + return 1; + } + + while (*(++argv)) { + dfs(*argv); + } + + return 0; +} diff --git a/empty-dirs.lua b/empty-dirs.lua @@ -0,0 +1,41 @@ +#!/usr/bin/env lua +local sys_stat = require "posix.sys.stat" +local dirent = require "posix.dirent" + +local function recurse(path) + local i = 0 + + for f in dirent.files(path) do + if f ~= "." and f ~= ".." then + local fp = path .. "/" .. f + i = i + 1 + + local sb = sys_stat.stat(fp) + if sb and sys_stat.S_ISDIR(sb.st_mode) ~= 0 then + recurse(fp) + end + end + end + + if i == 0 then + print(path) + end +end + +local function main(arg) + if #arg == 0 then + print("usage: " .. arg[0] .. " dir...") + os.exit(1) + end + + for _,path in ipairs(arg) do + local sb = sys_stat.stat(path) + if not sb or sys_stat.S_ISDIR(sb.st_mode) == 0 then + io.stderr:write(path .. ": not a directory\n") + else + recurse(path) + end + end +end + +main(arg)