micro-utils/builder/builder.c

85 lines
1.6 KiB
C

#include <stdio.h>
#include <errno.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include "make_path.h"
#include "config.h"
void remove_suffix(char *base, const char *suffix) {
char *ptr = base + strlen(base) - strlen(suffix);
if (!strcmp(ptr, suffix))
*ptr = '\0';
}
char *MakePath(const char *src, const char *output_dir) {
char *dup = strdup(src);
if (dup == NULL) {
fprintf(stderr, "builder: strdup failed\n");
exit(1);
}
remove_suffix(dup, ".c");
char *new_path = mu_make_path("builder", output_dir, dup);
if (new_path == NULL) {
free(dup);
exit(1);
}
free(dup);
return new_path;
}
void Compile(const char *src, const char *output_dir) {
char *path = MakePath(src, output_dir);
printf(CC_FMT, src, path);
pid_t pid;
if ((pid = fork()) == 0)
execlp(CC, CC, CFLAGS, src, "-o", path, NULL);
else if (pid == -1) {
fprintf(stderr, "builder: fork failed\n");
exit(1);
}
free(path);
int status = 0;
waitpid(pid, &status, 0);
if (status)
exit(status);
}
void ListAndCompile(const char *dir, const char *output_dir) {
if (chdir(dir) < 0) {
fprintf(stderr, "builder: %s: %s\n", dir, strerror(errno));
exit(1);
}
printf(CHDIR_FMT, dir);
DIR *dp = opendir(".");
struct dirent *ep;
while ((ep = readdir(dp)) != NULL) {
if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
continue;
Compile(ep->d_name, output_dir);
}
closedir(dp);
chdir("..");
}
int main(void) {
for (size_t i = 0; i < sizeof(objects) / sizeof(char *); i++)
ListAndCompile(objects[i], "../bin");
return 0;
}