Skip to content

Commit 4a92d1b

Browse files
raalkmlspearce
authored andcommitted
Add remove_path: a function to remove as much as possible of a path
The function has two potential users which both managed to get wrong their implementations (the one in builtin-rm.c one has a memleak, and builtin-merge-recursive.c scribles over its const argument). Signed-off-by: Alex Riesen <raa.lkml@gmail.com> Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
1 parent b9b378a commit 4a92d1b

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

dir.c

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -837,3 +837,23 @@ void setup_standard_excludes(struct dir_struct *dir)
837837
if (excludes_file && !access(excludes_file, R_OK))
838838
add_excludes_from_file(dir, excludes_file);
839839
}
840+
841+
int remove_path(const char *name)
842+
{
843+
char *slash;
844+
845+
if (unlink(name) && errno != ENOENT)
846+
return -1;
847+
848+
slash = strrchr(name, '/');
849+
if (slash) {
850+
char *dirs = xstrdup(name);
851+
slash = dirs + (slash - name);
852+
do {
853+
*slash = '\0';
854+
} while (rmdir(dirs) && (slash = strrchr(dirs, '/')));
855+
free(dirs);
856+
}
857+
return 0;
858+
}
859+

dir.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,7 @@ extern int is_inside_dir(const char *dir);
8181
extern void setup_standard_excludes(struct dir_struct *dir);
8282
extern int remove_dir_recursively(struct strbuf *path, int only_empty);
8383

84+
/* tries to remove the path with empty directories along it, ignores ENOENT */
85+
extern int remove_path(const char *path);
86+
8487
#endif

0 commit comments

Comments
 (0)