#pragma prototyped
#include <ast.h>
#include <error.h>
#include <ls.h>
#define directory(p,s) (stat((p),(s))>=0&&S_ISDIR((s)->st_mode))
#define regular(p,s) (stat((p),(s))>=0&&(S_ISREG((s)->st_mode)||streq(p,"/dev/null")))
typedef struct Dir_s
{
struct Dir_s* next;
char dir[1];
} Dir_t;
static struct
{
Dir_t* head;
Dir_t* tail;
} state;
int
pathinclude(const char* dir)
{
register Dir_t* dp;
struct stat st;
if (dir && *dir && !streq(dir, ".") && directory(dir, &st))
{
for (dp = state.head; dp; dp = dp->next)
if (streq(dir, dp->dir))
return 0;
if (!(dp = oldof(0, Dir_t, 1, strlen(dir))))
return -1;
strcpy(dp->dir, dir);
dp->next = 0;
if (state.tail)
state.tail = state.tail->next = dp;
else
state.head = state.tail = dp;
}
return 0;
}
char*
pathfind(const char* name, const char* lib, const char* type, char* buf, size_t size)
{
register Dir_t* dp;
register char* s;
char tmp[PATH_MAX];
struct stat st;
if (((s = strrchr(name, '/')) || (s = (char*)name)) && strchr(s, '.'))
type = 0;
if (regular(name, &st))
{
strncopy(buf, name, size);
return buf;
}
if (type)
{
sfsprintf(buf, size, "%s.%s", name, type);
if (regular(buf, &st))
return buf;
}
if (*name == '/')
return 0;
if (error_info.file && (s = strrchr(error_info.file, '/')))
{
sfsprintf(buf, size, "%-.*s%s", s - error_info.file + 1, error_info.file, name);
if (regular(buf, &st))
return buf;
if (type)
{
sfsprintf(buf, size, "%-.*s%s%.s", s - error_info.file + 1, error_info.file, name, type);
if (regular(buf, &st))
return buf;
}
}
for (dp = state.head; dp; dp = dp->next)
{
sfsprintf(tmp, sizeof(tmp), "%s/%s", dp->dir, name);
if (pathpath(tmp, "", PATH_REGULAR, buf, size))
return buf;
if (type)
{
sfsprintf(tmp, sizeof(tmp), "%s/%s.%s", dp->dir, name, type);
if (pathpath(tmp, "", PATH_REGULAR, buf, size))
return buf;
}
}
if (lib)
{
if (s = strrchr((char*)lib, ':'))
lib = (const char*)s + 1;
sfsprintf(tmp, sizeof(tmp), "lib/%s/%s", lib, name);
if (pathpath(tmp, "", PATH_REGULAR, buf, size))
return buf;
if (type)
{
sfsprintf(tmp, sizeof(tmp), "lib/%s/%s.%s", lib, name, type);
if (pathpath(tmp, "", PATH_REGULAR, buf, size))
return buf;
}
}
return 0;
}