dir-iterator: refactor state machine model
[alt-git.git] / dir-iterator.h
blob9b4cb7acd276af590694d57b55bb1b5c3f2933de
1 #ifndef DIR_ITERATOR_H
2 #define DIR_ITERATOR_H
4 #include "strbuf.h"
6 /*
7 * Iterate over a directory tree.
9 * Iterate over a directory tree, recursively, including paths of all
10 * types and hidden paths. Skip "." and ".." entries and don't follow
11 * symlinks except for the original path. Note that the original path
12 * is not included in the iteration.
14 * Every time dir_iterator_advance() is called, update the members of
15 * the dir_iterator structure to reflect the next path in the
16 * iteration. The order that paths are iterated over within a
17 * directory is undefined, directory paths are always given before
18 * their contents.
20 * A typical iteration looks like this:
22 * int ok;
23 * struct dir_iterator *iter = dir_iterator_begin(path);
25 * if (!iter)
26 * goto error_handler;
28 * while ((ok = dir_iterator_advance(iter)) == ITER_OK) {
29 * if (want_to_stop_iteration()) {
30 * ok = dir_iterator_abort(iter);
31 * break;
32 * }
34 * // Access information about the current path:
35 * if (S_ISDIR(iter->st.st_mode))
36 * printf("%s is a directory\n", iter->relative_path);
37 * }
39 * if (ok != ITER_DONE)
40 * handle_error();
42 * Callers are allowed to modify iter->path while they are working,
43 * but they must restore it to its original contents before calling
44 * dir_iterator_advance() again.
47 struct dir_iterator {
48 /* The current path: */
49 struct strbuf path;
52 * The current path relative to the starting path. This part
53 * of the path always uses "/" characters to separate path
54 * components:
56 const char *relative_path;
58 /* The current basename: */
59 const char *basename;
61 /* The result of calling lstat() on path: */
62 struct stat st;
66 * Start a directory iteration over path. On success, return a
67 * dir_iterator that holds the internal state of the iteration.
68 * In case of failure, return NULL and set errno accordingly.
70 * The iteration includes all paths under path, not including path
71 * itself and not including "." or ".." entries.
73 * path is the starting directory. An internal copy will be made.
75 struct dir_iterator *dir_iterator_begin(const char *path);
78 * Advance the iterator to the first or next item and return ITER_OK.
79 * If the iteration is exhausted, free the dir_iterator and any
80 * resources associated with it and return ITER_DONE. On error, free
81 * dir_iterator and associated resources and return ITER_ERROR. It is
82 * a bug to use iterator or call this function again after it has
83 * returned ITER_DONE or ITER_ERROR.
85 int dir_iterator_advance(struct dir_iterator *iterator);
88 * End the iteration before it has been exhausted. Free the
89 * dir_iterator and any associated resources and return ITER_DONE. On
90 * error, free the dir_iterator and return ITER_ERROR.
92 int dir_iterator_abort(struct dir_iterator *iterator);
94 #endif