1
0
Fork 0
dmenu/dmenu_path.c

101 lines
2 KiB
C
Raw Normal View History

2010-10-09 01:24:22 +03:00
/* See LICENSE file for copyright and license details. */
#include <dirent.h>
2010-11-20 11:25:04 +02:00
#include <limits.h>
2010-10-09 01:24:22 +03:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
static void die(const char *s);
2010-10-09 01:36:45 +03:00
static int qstrcmp(const void *a, const void *b);
2010-10-09 01:24:22 +03:00
static void scan(void);
static int uptodate(void);
static char **items = NULL;
2010-10-09 01:36:45 +03:00
static const char *home, *path;
2010-10-09 01:24:22 +03:00
int
main(void) {
2010-10-09 01:36:45 +03:00
if(!(home = getenv("HOME")))
2010-10-09 01:24:22 +03:00
die("no $HOME");
2010-10-09 01:36:45 +03:00
if(!(path = getenv("PATH")))
2010-10-09 01:24:22 +03:00
die("no $PATH");
2010-10-09 01:36:45 +03:00
if(chdir(home) < 0)
2010-10-09 01:24:22 +03:00
die("chdir failed");
if(uptodate()) {
2011-01-07 20:54:40 +02:00
execl("/bin/cat", "cat", CACHE, NULL);
2010-10-09 01:24:22 +03:00
die("exec failed");
}
scan();
return EXIT_SUCCESS;
}
void
die(const char *s) {
fprintf(stderr, "dmenu_path: %s\n", s);
exit(EXIT_FAILURE);
}
int
qstrcmp(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
void
scan(void) {
char buf[PATH_MAX];
2010-10-09 01:36:45 +03:00
char *dir, *p;
size_t i, count;
2010-10-09 01:24:22 +03:00
struct dirent *ent;
DIR *dp;
FILE *cache;
2010-10-09 01:36:45 +03:00
count = 0;
if(!(p = strdup(path)))
2010-10-09 01:24:22 +03:00
die("strdup failed");
2010-10-09 01:36:45 +03:00
for(dir = strtok(p, ":"); dir; dir = strtok(NULL, ":")) {
2010-10-09 01:24:22 +03:00
if(!(dp = opendir(dir)))
continue;
while((ent = readdir(dp))) {
snprintf(buf, sizeof buf, "%s/%s", dir, ent->d_name);
if(ent->d_name[0] == '.' || access(buf, X_OK) < 0)
continue;
if(!(items = realloc(items, ++count * sizeof *items)))
die("malloc failed");
if(!(items[count-1] = strdup(ent->d_name)))
die("strdup failed");
}
closedir(dp);
}
qsort(items, count, sizeof *items, qstrcmp);
if(!(cache = fopen(CACHE, "w")))
die("open failed");
for(i = 0; i < count; i++) {
if(i > 0 && !strcmp(items[i], items[i-1]))
continue;
fprintf(cache, "%s\n", items[i]);
fprintf(stdout, "%s\n", items[i]);
}
fclose(cache);
2010-10-09 01:36:45 +03:00
free(p);
2010-10-09 01:24:22 +03:00
}
int
uptodate(void) {
2010-10-09 01:36:45 +03:00
char *dir, *p;
2010-10-09 01:24:22 +03:00
time_t mtime;
struct stat st;
if(stat(CACHE, &st) < 0)
return 0;
mtime = st.st_mtime;
2010-10-09 01:36:45 +03:00
if(!(p = strdup(path)))
2010-10-09 01:24:22 +03:00
die("strdup failed");
2010-10-09 01:36:45 +03:00
for(dir = strtok(p, ":"); dir; dir = strtok(NULL, ":"))
2010-10-09 01:24:22 +03:00
if(!stat(dir, &st) && st.st_mtime > mtime)
return 0;
2010-10-09 01:36:45 +03:00
free(p);
2010-10-09 01:24:22 +03:00
return 1;
}