12 #include <sys/types.h>
14 #include <sys/inotify.h>
16 #include <sys/prctl.h>
20 DELSTATE_NO, /* source file that was accessed, keep it */
21 DELSTATE_MAYBE, /* source file that was not touched so far, delete it if it stays unused */
22 DELSTATE_YES /* generated file in a run with delete_new = true, delete it */
25 // describes a file or a directory that was created during compilation
28 enum delstate delstate;
29 char name[]; /* path relative to project root; hashmap key */
31 file *hashed_files = NULL;
33 // describes a directory that existed before compilation
36 int watch_descriptor; /* hashmap key */
39 file *hashed_dirs = NULL;
43 void *xmalloc(size_t len) {
44 void *ret = malloc(len);
45 if (ret == NULL && len != 0)
46 err(1, "memory allocation failure");
50 static void add_file(const char *file_path) {
52 HASH_FIND_STR(hashed_files, file_path, f);
54 errx(1, "we tried to add the file '%s' twice, probably because you're messing "
55 "around in the filesystem and removing and adding files during the initial scan "
56 "step. stop it.", file_path);
58 f = xmalloc(sizeof(*f) + strlen(file_path) + 1);
59 strcpy(f->name, file_path);
60 f->delstate = DELSTATE_MAYBE;
61 HASH_ADD_STR(hashed_files, name, f);
64 static void add_dir(const char *dir_path) {
65 directory *d = xmalloc(sizeof(*d) + strlen(dir_path) + 1);
66 strcpy(d->name, dir_path);
68 // Don't register watches on files to avoid running into the fs.inotify.max_user_watches limit.
69 // Instead, register watches on all directories. There shouldn't be too many of those.
70 d->watch_descriptor = inotify_add_watch(inotify_fd, dir_path,
71 IN_OPEN | IN_CREATE | IN_MOVED_TO | IN_EXCL_UNLINK | IN_ONLYDIR);
72 if (d->watch_descriptor == -1)
73 err(1, "unable to add inotify watch for '%s'", dir_path);
75 directory *d_existing;
76 HASH_FIND_INT(hashed_dirs, &d->watch_descriptor, d_existing);
78 errx(1, "the kernel says we watched the same directory twice. whatever you're doing "
79 "to make the filesystem behave that way, stop it.");
80 HASH_ADD_INT(hashed_dirs, watch_descriptor, d);
83 static void add_files_recursive(const char *current_path) {
84 DIR *d = opendir(current_path);
86 err(1, "unable to open directory '%s'", current_path);
89 struct dirent *r_entry;
91 if (readdir_r(d, &entry, &r_entry))
92 errx(1, "readdir_r failed");
95 if (strcmp(entry.d_name, ".") == 0 || strcmp(entry.d_name, "..") == 0)
98 char file_path[strlen(current_path) + 1 + strlen(entry.d_name) + 1];
99 sprintf(file_path, "%s/%s", current_path, entry.d_name);
102 if (lstat(file_path, &st))
103 err(1, "unable to stat '%s'", file_path);
104 switch (st.st_mode & S_IFMT) {
109 // First recurse, then add the watch. This avoids spamming ourselves with irrelevant
110 // directory open events.
111 add_files_recursive(file_path);
117 add_dir(current_path);
120 volatile bool child_quit = false;
122 void handle_sigchld(int n) {
123 if (waitpid(-1, NULL, WNOHANG) == -1)
124 err(1, "wait for child failed");
126 puts("processing remaining events...");
130 puts("invocation: cleanmysourcetree <deletenew/keepnew> [<target directory>]");
131 puts("deletenew will cause files and directories created by "
132 "the compilation process to be deleted.");
136 int main(int argc, char **argv) {
141 err(1, "unable to chdir to specified directory");
142 } else if (argc != 2) {
145 if (strcmp(argv[1], "deletenew") == 0) {
147 } else if (strcmp(argv[1], "keepnew") == 0) {
153 // collect filenames, init watches
154 inotify_fd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
155 if (inotify_fd == -1)
156 err(1, "unable to open inotify fd");
157 add_files_recursive(".");
159 sigset_t sigchild_mask;
160 sigemptyset(&sigchild_mask);
161 sigaddset(&sigchild_mask, SIGCHLD);
162 if (sigprocmask(SIG_SETMASK, &sigchild_mask, NULL))
163 err(1, "sigprocmask failed");
164 if (signal(SIGCHLD, handle_sigchld) == SIG_ERR)
165 err(1, "unable to register signal handler");
167 pid_t child = fork();
169 err(1, "can't fork");
171 prctl(PR_SET_PDEATHSIG, SIGTERM); /* stupid racy API :/ */
172 puts("dropping you into an interactive shell now. compile the project, then "
179 // process inotify events until the child is dead
180 // and there are no more pending events
181 struct pollfd fds[1] = { { .fd = inotify_fd, .events = POLLIN } };
182 struct timespec zero_timeout_ts = { .tv_sec = 0, .tv_nsec = 0};
184 sigemptyset(&empty_mask);
186 int r = ppoll(fds, 1, child_quit ? &zero_timeout_ts : NULL, &empty_mask);
187 if (r == -1 && errno == EINTR)
190 err(1, "ppoll failed");
194 char buf[20 * (sizeof(struct inotify_event) + NAME_MAX + 1)];
195 ssize_t read_res = read(inotify_fd, buf, sizeof(buf));
197 err(1, "read from inotify fd failed");
198 if (read_res < sizeof(struct inotify_event))
199 errx(1, "short/empty read from inotify");
200 struct inotify_event *e = (void*)buf;
201 while ((char*)e != buf + read_res) {
202 if (e->mask & IN_Q_OVERFLOW)
203 errx(1, "inotify queue overflow detected");
204 if (e->len != 0 && (e->mask & (IN_OPEN | IN_CREATE | IN_MOVED_TO))) {
206 HASH_FIND_INT(hashed_dirs, &e->wd, dir);
208 errx(1, "unable to find dir by inotify wd, bug!");
209 char path[strlen(dir->name) + e->len];
210 sprintf(path, "%s/%s", dir->name, e->name);
212 HASH_FIND_STR(hashed_files, path, f);
213 // if f is NULL, this is a file/directory generated during compilation
214 // or a pre-existing directory
216 if (f->delstate == DELSTATE_MAYBE)
217 f->delstate = DELSTATE_NO;
218 } else if (delete_new && (e->mask & (IN_CREATE | IN_MOVED_TO))) {
219 f = xmalloc(sizeof(*f) + strlen(path) + 1);
220 strcpy(f->name, path);
221 f->delstate = DELSTATE_YES;
222 HASH_ADD_STR(hashed_files, name, f);
225 // step to next event in buffer. yuck.
226 e = (struct inotify_event *)((char *)e + sizeof(struct inotify_event) + e->len);
230 // reset signal handling
231 signal(SIGCHLD, SIG_DFL);
232 if (sigprocmask(SIG_SETMASK, &empty_mask, NULL))
233 err(1, "sigprocmask failed");
236 puts("inotify event collection phase is over, deleting stuff...");
238 // if we want to delete generated files and folders, we haven't seen
239 // any events for files in generated folders. therefore, to delete
240 // those folders, they need to be rm -rf'ed. I don't want to write
241 // logic for that manually, so just execute rm.
242 for (file *f = hashed_files; f != NULL; f = f->hh.next) {
243 if (f->delstate == DELSTATE_NO) continue;
245 pid_t rm_pid = fork();
247 err(1, "unable to fork for rm");
249 execlp("rm", "rm", "-rfv", "--", f->name, NULL);
250 err(1, "unable to invoke rm");
252 if (wait(NULL) != rm_pid)
253 err(1, "waiting for rm failed");
255 puts("cleanup complete");