#############################################################################*/
#include <errno.h>
+#include <libgen.h>
#include <linux/limits.h>
#include <stdlib.h>
#include <string.h>
#include <pakfire/constants.h>
#include <pakfire/file.h>
+#include <pakfire/logging.h>
#include <pakfire/pakfire.h>
#include <pakfire/private.h>
#include <pakfire/util.h>
if (chksum)
file->chksum = strdup(chksum);
}
+
+static int pakfire_file_levels(PakfireFile file) {
+ if (!*file->path)
+ return 0;
+
+ int levels = 0;
+
+ for (char* p = file->path; *p; p++) {
+ if (*p == '/')
+ levels++;
+ }
+
+ return levels;
+}
+
+/*
+ This function tries to remove the file after it has been packaged.
+
+ It will try to delete any parent directories as well and ignore if directories
+ cannot be deleted because they might contain other files
+*/
+int pakfire_file_cleanup(PakfireFile file) {
+ char path[PATH_MAX];
+
+ if (!*file->abspath) {
+ errno = EINVAL;
+ return 1;
+ }
+
+ DEBUG(file->pakfire, "Removing %s...\n", file->path);
+
+ int r = remove(file->abspath);
+ if (r) {
+ // Ignore when we could not remove directories
+ if (errno == ENOTEMPTY)
+ return 0;
+
+ ERROR(file->pakfire, "Could not remove %s (%s): %s\n",
+ file->path, file->abspath, strerror(errno));
+ }
+
+ // Create a working copy of abspath
+ r = pakfire_string_set(path, file->abspath);
+ if (r < 0)
+ return r;
+
+ // See how many levels this file has
+ int levels = pakfire_file_levels(file);
+
+ // Walk all the way up and remove all parent directories if possible
+ while (--levels) {
+ dirname(path);
+
+ // Break if path is suddenly empty
+ if (!*path)
+ break;
+
+ r = rmdir(path);
+ if (r) {
+ if (errno == ENOTEMPTY)
+ return 0;
+
+ return r;
+ }
+ }
+
+ return r;
+}