1 /* vi: set sw=4 ts=4 :*/
2 /* dirtree.c - Functions for dealing with directory trees.
4 * Copyright 2007 Rob Landley <rob@landley.net>
9 // NOTE: This uses toybuf. Possibly it shouldn't do that.
11 // Create a dirtree node from a path.
13 struct dirtree *dirtree_add_node(char *path)
18 // Find last chunk of name.
21 name = strrchr(path, '/');
23 if (!name) name = path;
25 if (*(name+1)) name++;
34 dt = xzalloc(sizeof(struct dirtree)+strlen(name)+1);
35 if (lstat(path, &(dt->st))) {
36 error_msg("Skipped '%s'",name);
40 strcpy(dt->name, name);
45 // Given a directory (in a writeable PATH_MAX buffer), recursively read in a
48 // If callback==NULL, allocate tree of struct dirtree and
49 // return root of tree. Otherwise call callback(node) on each hit, free
50 // structures after use, and return NULL.
52 struct dirtree *dirtree_read(char *path, struct dirtree *parent,
53 int (*callback)(char *path, struct dirtree *node))
55 struct dirtree *dt = NULL, **ddt = &dt;
57 int len = strlen(path);
59 if (!(dir = opendir(path))) perror_msg("No %s", path);
62 struct dirent *entry = readdir(dir);
69 if (entry->d_name[0]=='.') {
70 if (!entry->d_name[1]) continue;
71 if (entry->d_name[1]=='.' && !entry->d_name[2]) continue;
74 snprintf(path+len, sizeof(toybuf)-len, "/%s", entry->d_name);
75 *ddt = dirtree_add_node(path);
77 (*ddt)->parent = parent;
78 (*ddt)->depth = parent ? parent->depth + 1 : 1;
79 if (callback) norecurse = callback(path, *ddt);
80 if (!norecurse && entry->d_type == DT_DIR)
81 (*ddt)->child = dirtree_read(path, *ddt, callback);
82 if (callback) free(*ddt);
83 else ddt = &((*ddt)->next);