Xinqi Bao's Git

1575f1d193524e7e582ddcf6cef3e0efd6ce7fdd
[dmenu.git] / dmenu_path.c
1 /* See LICENSE file for copyright and license details. */
2 #include <dirent.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <unistd.h>
7 #include <sys/stat.h>
8
9 #define CACHE ".dmenu_cache"
10
11 static int qstrcmp(const void *a, const void *b);
12 static void die(const char *s);
13 static void scan(void);
14 static int uptodate(void);
15
16 static char **items = NULL;
17 static const char *Home, *Path;
18 static size_t count = 0;
19
20 int
21 main(void) {
22 if(!(Home = getenv("HOME")))
23 die("no $HOME");
24 if(!(Path = getenv("PATH")))
25 die("no $PATH");
26 if(chdir(Home) < 0)
27 die("chdir failed");
28 if(uptodate()) {
29 execlp("cat", "cat", CACHE, NULL);
30 die("exec failed");
31 }
32 scan();
33 return EXIT_SUCCESS;
34 }
35
36 void
37 die(const char *s) {
38 fprintf(stderr, "dmenu_path: %s\n", s);
39 exit(EXIT_FAILURE);
40 }
41
42 int
43 qstrcmp(const void *a, const void *b) {
44 return strcmp(*(const char **)a, *(const char **)b);
45 }
46
47 void
48 scan(void) {
49 char buf[PATH_MAX];
50 char *dir, *path;
51 size_t i;
52 struct dirent *ent;
53 DIR *dp;
54 FILE *cache;
55
56 if(!(path = strdup(Path)))
57 die("strdup failed");
58 for(dir = strtok(path, ":"); dir; dir = strtok(NULL, ":")) {
59 if(!(dp = opendir(dir)))
60 continue;
61 while((ent = readdir(dp))) {
62 snprintf(buf, sizeof buf, "%s/%s", dir, ent->d_name);
63 if(ent->d_name[0] == '.' || access(buf, X_OK) < 0)
64 continue;
65 if(!(items = realloc(items, ++count * sizeof *items)))
66 die("malloc failed");
67 if(!(items[count-1] = strdup(ent->d_name)))
68 die("strdup failed");
69 }
70 closedir(dp);
71 }
72 qsort(items, count, sizeof *items, qstrcmp);
73 if(!(cache = fopen(CACHE, "w")))
74 die("open failed");
75 for(i = 0; i < count; i++) {
76 if(i > 0 && !strcmp(items[i], items[i-1]))
77 continue;
78 fprintf(cache, "%s\n", items[i]);
79 fprintf(stdout, "%s\n", items[i]);
80 }
81 fclose(cache);
82 free(path);
83 }
84
85 int
86 uptodate(void) {
87 char *dir, *path;
88 time_t mtime;
89 struct stat st;
90
91 if(stat(CACHE, &st) < 0)
92 return 0;
93 mtime = st.st_mtime;
94 if(!(path = strdup(Path)))
95 die("strdup failed");
96 for(dir = strtok(path, ":"); dir; dir = strtok(NULL, ":"))
97 if(!stat(dir, &st) && st.st_mtime > mtime)
98 return 0;
99 free(path);
100 return 1;
101 }