Re: [PATCH v4 3/5] remove_subtree(): reimplement using iterators
- From
Michael Haggerty <mhagger@alum.mit.edu>
- Date
- Mar 29, 2017, 10:01 UTC
- Message-ID
- <679957e0-bb06-2dd9-bfc5-024da5ab49ce@alum.mit.edu>
- In-Reply-To
- <1490747533-89143-4-git-send-email-bnmvco@gmail.com>
On 03/29/2017 02:32 AM, Daniel Ferreira wrote:
Show 28 quoted lines
> Use dir_iterator to traverse through remove_subtree()'s directory tree,
> avoiding the need for recursive calls to readdir(). Simplify
> remove_subtree()'s code.
>
> A conversion similar in purpose was previously done at 46d092a
> ("for_each_reflog(): reimplement using iterators", 2016-05-21).
>
> Signed-off-by: Daniel Ferreira <bnmvco@gmail.com>
> ---
> entry.c | 31 ++++++++++---------------------
> 1 file changed, 10 insertions(+), 21 deletions(-)
>
> diff --git a/entry.c b/entry.c
> index c6eea24..bbebd16 100644
> --- a/entry.c
> +++ b/entry.c
> @@ -2,6 +2,8 @@
> #include "blob.h"
> #include "dir.h"
> #include "streaming.h"
> +#include "iterator.h"
> +#include "dir-iterator.h"
>
> static void create_directories(const char *path, int path_len,
> const struct checkout *state)
> @@ -46,29 +48,16 @@ static void create_directories(const char *path, int path_len,
>
> static void remove_subtree(struct strbuf *path)The reason that this function took a `strbuf` as argument was that it used to modify the strbuf while it was working. Now that `dir_iterator` does all of that work, you could simplify it to take a `const char *` argument, and change the caller to pass `path.buf`.
Show 28 quoted lines
> {
> - DIR *dir = opendir(path->buf);
> - struct dirent *de;
> - int origlen = path->len;
> -
> - if (!dir)
> - die_errno("cannot opendir '%s'", path->buf);
> - while ((de = readdir(dir)) != NULL) {
> - struct stat st;
> -
> - if (is_dot_or_dotdot(de->d_name))
> - continue;
> -
> - strbuf_addch(path, '/');
> - strbuf_addstr(path, de->d_name);
> - if (lstat(path->buf, &st))
> - die_errno("cannot lstat '%s'", path->buf);
> - if (S_ISDIR(st.st_mode))
> - remove_subtree(path);
> - else if (unlink(path->buf))
> + struct dir_iterator *diter = dir_iterator_begin(path->buf, DIR_ITERATOR_DEPTH_FIRST);
> +
> + while (dir_iterator_advance(diter) == ITER_OK) {
> + if (S_ISDIR(diter->st.st_mode)) {
> + if (rmdir(diter->path.buf))
> + die_errno("cannot rmdir '%s'", path->buf);
> + } else if (unlink(diter->path.buf))
> die_errno("cannot unlink '%s'", path->buf);The two `die_errno()` calls must be changed to use `diter->path.buf` rather than `path->buf`.
Show 7 quoted lines
> - strbuf_setlen(path, origlen);
> }
> - closedir(dir);
> +
> if (rmdir(path->buf))
> die_errno("cannot rmdir '%s'", path->buf);
> }Michael