aboutsummaryrefslogtreecommitdiff
path: root/lib/dirtree.c
blob: 71f644939cae6cdb60dec41796abb44f5dae5997 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/* vi: set sw=4 ts=4 :*/
/* dirtree.c - Functions for dealing with directory trees.
 *
 * Copyright 2007 Rob Landley <rob@landley.net>
 */

#include "toys.h"

// NOTE: This uses toybuf.  Possibly it shouldn't do that.

// Create a dirtree node from a path.

struct dirtree *dirtree_add_node(char *path)
{
	struct dirtree *dt;
	char *name;

	// Find last chunk of name.

	for (;;) {
		name = strrchr(path, '/');

		if (!name) name = path;
		else {
			if (*(name+1)) name++;
			else {
				*name=0;
				continue;
			}
		}
		break;
	}

   	dt = xzalloc(sizeof(struct dirtree)+strlen(name)+1);
	if (lstat(path, &(dt->st))) {
		error_msg("Skipped '%s'",name);
		free(dt);
		return 0;
	}
	strcpy(dt->name, name);

	return dt;
}

// Given a directory (in a writeable PATH_MAX buffer), recursively read in a
// directory tree.
//
// If callback==NULL, allocate tree of struct dirtree and
// return root of tree.  Otherwise call callback(node) on each hit, free
// structures after use, and return NULL.

struct dirtree *dirtree_read(char *path, struct dirtree *parent,
					int (*callback)(struct dirtree *node))
{
	struct dirtree *dt = NULL, **ddt = &dt;
	DIR *dir;
	int len = strlen(path);

	if (!(dir = opendir(path))) perror_msg("No %s", path);

	for (;;) {
		struct dirent *entry = readdir(dir);
		if (!entry) break;

		// Skip "." and ".."
		if (entry->d_name[0]=='.') {
			if (!entry->d_name[1]) continue;
			if (entry->d_name[1]=='.' && !entry->d_name[2]) continue;
		}

		snprintf(path+len, sizeof(toybuf)-len, "/%s", entry->d_name);
		*ddt = dirtree_add_node(path);
		if (!*ddt) continue;
		(*ddt)->parent = parent;
		if (callback) callback(*ddt);
		if (entry->d_type == DT_DIR)
			(*ddt)->child = dirtree_read(path, *ddt, callback);
		if (callback) free(*ddt);
		else ddt = &((*ddt)->next);
		path[len]=0;
	}

	return dt;
}