aboutsummaryrefslogtreecommitdiff
path: root/src/fileutils.c
diff options
context:
space:
mode:
authordec05eba <dec05eba@protonmail.com>2021-04-11 09:27:13 +0200
committerdec05eba <dec05eba@protonmail.com>2021-04-11 09:27:13 +0200
commiteaa0851500c111a0fe5a50bc3f8b5aa4354774db (patch)
tree8943d519265aec26e5fac2575f492293d820788c /src/fileutils.c
parentcff81a0630937e0ffd59198a43a18f6c2b66b19a (diff)
Add cleanup option to remove old tracked items
Diffstat (limited to 'src/fileutils.c')
-rw-r--r--src/fileutils.c58
1 files changed, 58 insertions, 0 deletions
diff --git a/src/fileutils.c b/src/fileutils.c
index a66bba6..72d9c29 100644
--- a/src/fileutils.c
+++ b/src/fileutils.c
@@ -10,6 +10,7 @@
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
+#include <dirent.h>
const char* get_home_dir(void) {
const char *home_dir = getenv("HOME");
@@ -83,6 +84,63 @@ int create_directory_recursive(char *path) {
return 0;
}
+static int is_path(const char *path) {
+ struct stat s;
+ if(stat(path, &s) == 0)
+ return S_ISDIR(s.st_mode);
+ return 0;
+}
+
+static int remove_recursive_mutable(char *path) {
+ int path_len = strlen(path);
+ int res = 0;
+
+ struct dirent *dir;
+ DIR *d = opendir(path);
+ if(!d) {
+ fprintf(stderr, "Failed to open directory: %s\n", path);
+ return -1;
+ }
+
+ while((dir = readdir(d)) != NULL) {
+ int filename_len = strlen(dir->d_name);
+ if((filename_len == 1 && dir->d_name[0] == '.') || (filename_len == 2 && dir->d_name[0] == '.' && dir->d_name[1] == '.'))
+ continue;
+
+ path[path_len] = '/';
+ memcpy(path + path_len + 1, dir->d_name, filename_len);
+ path[path_len + 1 + filename_len] = '\0';
+
+ int is_dir = dir->d_type == DT_DIR;
+ if(dir->d_type == DT_UNKNOWN)
+ is_dir = is_path(path);
+
+ if(is_dir) {
+ res = remove_recursive_mutable(path);
+ if(res != 0)
+ goto cleanup;
+ }
+
+ res = remove(path);
+ if(res != 0)
+ goto cleanup;
+ }
+
+ cleanup:
+ path[path_len] = '\0';
+ res |= remove(path);
+ closedir(d);
+ return res;
+}
+
+int remove_recursive(char *path) {
+ int path_len = strlen(path);
+ char fullpath[PATH_MAX];
+ memcpy(fullpath, path, path_len);
+ fullpath[path_len] = '\0';
+ return remove_recursive_mutable(fullpath);
+}
+
int file_exists(const char *path) {
return access(path, F_OK);
}