blob: 659b6bfa81df6d0bcffb8d0a975492d54d79d6bc [file] [log] [blame]
Daniel Ferreira150791a2019-07-10 20:58:57 -03001#include "test-tool.h"
2#include "git-compat-util.h"
3#include "strbuf.h"
4#include "iterator.h"
5#include "dir-iterator.h"
6
Junio C Hamano90421402019-07-30 10:45:48 -07007static const char *error_name(int error_number)
8{
9 switch (error_number) {
10 case ENOENT: return "ENOENT";
11 case ENOTDIR: return "ENOTDIR";
12 default: return "ESOMETHINGELSE";
13 }
14}
15
Matheus Tavaresfa1da7d2019-07-10 20:59:00 -030016/*
17 * usage:
18 * tool-test dir-iterator [--follow-symlinks] [--pedantic] directory_path
19 */
Daniel Ferreira150791a2019-07-10 20:58:57 -030020int cmd__dir_iterator(int argc, const char **argv)
21{
Daniel Ferreira150791a2019-07-10 20:58:57 -030022 struct dir_iterator *diter;
Matheus Tavaresfa1da7d2019-07-10 20:59:00 -030023 unsigned int flags = 0;
24 int iter_status;
Daniel Ferreira150791a2019-07-10 20:58:57 -030025
Matheus Tavaresfa1da7d2019-07-10 20:59:00 -030026 for (++argv, --argc; *argv && starts_with(*argv, "--"); ++argv, --argc) {
27 if (strcmp(*argv, "--follow-symlinks") == 0)
28 flags |= DIR_ITERATOR_FOLLOW_SYMLINKS;
29 else if (strcmp(*argv, "--pedantic") == 0)
30 flags |= DIR_ITERATOR_PEDANTIC;
31 else
32 die("invalid option '%s'", *argv);
33 }
Daniel Ferreira150791a2019-07-10 20:58:57 -030034
Matheus Tavaresfa1da7d2019-07-10 20:59:00 -030035 if (!*argv || argc != 1)
36 die("dir-iterator needs exactly one non-option argument");
Daniel Ferreira150791a2019-07-10 20:58:57 -030037
René Scharfe7df3bd42019-08-07 13:15:20 +020038 diter = dir_iterator_begin(*argv, flags);
Daniel Ferreira150791a2019-07-10 20:58:57 -030039
Matheus Tavares30123972019-07-10 20:58:59 -030040 if (!diter) {
Junio C Hamano90421402019-07-30 10:45:48 -070041 printf("dir_iterator_begin failure: %s\n", error_name(errno));
Matheus Tavares30123972019-07-10 20:58:59 -030042 exit(EXIT_FAILURE);
43 }
44
Matheus Tavaresfa1da7d2019-07-10 20:59:00 -030045 while ((iter_status = dir_iterator_advance(diter)) == ITER_OK) {
Daniel Ferreira150791a2019-07-10 20:58:57 -030046 if (S_ISDIR(diter->st.st_mode))
47 printf("[d] ");
48 else if (S_ISREG(diter->st.st_mode))
49 printf("[f] ");
Matheus Tavaresfa1da7d2019-07-10 20:59:00 -030050 else if (S_ISLNK(diter->st.st_mode))
51 printf("[s] ");
Daniel Ferreira150791a2019-07-10 20:58:57 -030052 else
53 printf("[?] ");
54
55 printf("(%s) [%s] %s\n", diter->relative_path, diter->basename,
56 diter->path.buf);
57 }
58
Matheus Tavaresfa1da7d2019-07-10 20:59:00 -030059 if (iter_status != ITER_DONE) {
60 printf("dir_iterator_advance failure\n");
61 return 1;
62 }
63
Daniel Ferreira150791a2019-07-10 20:58:57 -030064 return 0;
65}