shithub: fsgen

ref: e49f718071886411a94f42ebf007f08eca4cfa9d
dir: /files.c/

View raw version
#include <u.h>
#include <libc.h>
#include "dat.h"
#include "fns.h"

VFile *files = nil;

static char**
parsepath(char *path)
{
	char **args;
	char *s;
	int numparts = 1, n;
	
	for (s = path; *s; s++) {
		if (*s == '/')
			numparts++;
	}
	/* root dir, each directory part, ending nil */
	args = mallocz(numparts+1, 1);
	s = strdup(path);
	n = getfields(s, args, numparts, 0, "/");
	assert(s == args[0]);
	if (n == numparts)
		return args;
	free(args);
	free(s);
	werrstr("invalid path");
	return nil;
}

VFile*
addfile(char *path)
{
	VFile *old;
	if (!files) {
		files = mallocz(sizeof(VFile), 1);
	} else {
		old = files;
		files = mallocz(sizeof(VFile), 1);
		files->next = old;
	}
	files->path = strdup(path);
	files->parts = parsepath(path);
	if (!files->parts)
		return nil;
	return files;
}

void
foreachfile(void (*f)(VFile*,void*), void *aux)
{
	VFile *vf;
	
	for (vf = files; vf; vf = vf->next)
		f(vf, aux);
}

static int
Vfmt(Fmt *f)
{
	VFile *v;
	v = va_arg(f->args, VFile*);
	return fmtprint(f, "%s (%s%s%s)", v->path,
		v->isdir ? "D," : "",
		v->hasread ? "R," : "",
		v->haswrite ? "W" : ""
	);
}

void
vfileinit()
{
	fmtinstall('V', Vfmt);
}