fs-util: rewrite rmdir_parents() with path_find_last_component()

This commit is contained in:
Yu Watanabe
2021-09-07 14:08:21 +09:00
parent 3008a6f21c
commit 4e046c5c2f
2 changed files with 76 additions and 32 deletions
+21 -32
View File
@@ -45,50 +45,39 @@ int unlink_noerrno(const char *path) {
}
int rmdir_parents(const char *path, const char *stop) {
size_t l;
int r = 0;
char *p;
int r;
assert(path);
assert(stop);
l = strlen(path);
if (!path_is_safe(path))
return -EINVAL;
/* Skip trailing slashes */
while (l > 0 && path[l-1] == '/')
l--;
if (!path_is_safe(stop))
return -EINVAL;
while (l > 0) {
char *t;
p = strdupa(path);
/* Skip last component */
while (l > 0 && path[l-1] != '/')
l--;
for (;;) {
char *slash = NULL;
/* Skip trailing slashes */
while (l > 0 && path[l-1] == '/')
l--;
if (l <= 0)
break;
t = strndup(path, l);
if (!t)
return -ENOMEM;
if (path_startswith(stop, t)) {
free(t);
/* skip the last component. */
r = path_find_last_component(p, /* accept_dot_dot= */ false, (const char **) &slash, NULL);
if (r <= 0)
return r;
if (slash == p)
return 0;
}
r = rmdir(t);
free(t);
assert(*slash == '/');
*slash = '\0';
if (r < 0)
if (errno != ENOENT)
return -errno;
if (path_startswith_full(stop, p, /* accept_dot_dot= */ false))
return 0;
if (rmdir(p) < 0 && errno != ENOENT)
return -errno;
}
return 0;
}
int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {