micro-utils/builder/builder.c

95 lines
1.9 KiB
C
Raw Normal View History

2023-11-04 22:06:27 +03:00
#include <stdio.h>
2023-11-05 13:46:39 +03:00
#include <errno.h>
2023-11-04 22:06:27 +03:00
#include <dirent.h>
2023-11-05 13:46:39 +03:00
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
2023-11-08 11:05:04 +03:00
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
2023-11-05 13:46:39 +03:00
#include "make_path.h"
2023-11-04 22:06:27 +03:00
#include "config.h"
2023-11-05 13:46:39 +03:00
void remove_suffix(char *base, const char *suffix) {
char *ptr = base + strlen(base) - strlen(suffix);
if (!strcmp(ptr, suffix))
*ptr = '\0';
}
2023-11-05 18:31:17 +03:00
char *MakePath(const char *src, const char *output_dir) {
2023-11-05 13:46:39 +03:00
char *dup = strdup(src);
if (dup == NULL) {
fprintf(stderr, "builder: strdup failed");
exit(1);
}
remove_suffix(dup, ".c");
2023-11-05 18:31:17 +03:00
char *new_path = mu_make_path("builder", output_dir, dup);
2023-11-05 13:46:39 +03:00
if (new_path == NULL) {
free(dup);
exit(1);
}
free(dup);
return new_path;
}
2023-11-05 18:31:17 +03:00
void Compile(const char *src, const char *output_dir) {
char *path = MakePath(src, output_dir);
2023-11-05 21:42:26 +03:00
printf("[CC] Building %s -> %s\n", src, path);
2023-11-05 13:46:39 +03:00
2023-11-08 11:05:04 +03:00
pid_t pid;
if ((pid = fork()) == 0) {
2023-11-08 19:47:09 +03:00
if (pid == 1)
exit(1);
execlp(CC, CC, CFLAGS, src, "-o", path, NULL);
// kill(getppid(), 9);
// Probably doesn't need it as the child is resulted with exit(1)
2023-11-08 11:05:04 +03:00
/* If compiler return 1 */
exit(1);
} else if (pid == -1) {
fprintf(stderr, "%s", "builder: fork failed");
exit(1);
2023-11-08 11:05:04 +03:00
}
2023-11-08 19:47:09 +03:00
free(path);
2023-11-08 11:05:04 +03:00
int status = 0;
waitpid(pid, &status, 0);
if (status)
exit(1);
2023-11-05 13:46:39 +03:00
}
2023-11-05 18:31:17 +03:00
void ListAndCompile(const char *dir, const char *output_dir) {
2023-11-05 21:42:26 +03:00
if (chdir(dir) < 0) {
fprintf(stderr, "builder: %s: %s\n", dir, strerror(errno));
2023-11-05 13:46:39 +03:00
exit(1);
}
2023-11-08 19:47:09 +03:00
printf("[CHDIR] %s\n", dir);
2023-11-05 21:42:26 +03:00
DIR *dp = opendir(".");
2023-11-05 13:46:39 +03:00
struct dirent *ep;
while ((ep = readdir(dp)) != NULL) {
if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
continue;
2023-11-05 18:31:17 +03:00
Compile(ep->d_name, output_dir);
2023-11-05 13:46:39 +03:00
}
closedir(dp);
chdir("..");
}
2023-11-04 22:06:27 +03:00
int main(void) {
2023-11-05 18:31:17 +03:00
/* for (size_t i = 0; i < sizeof(libs) / sizeof(char *); i++)
ListAndCompile(objects[i], "../obj"); */
2023-11-05 13:46:39 +03:00
for (size_t i = 0; i < sizeof(objects) / sizeof(char *); i++)
2023-11-05 18:31:17 +03:00
ListAndCompile(objects[i], "../bin");
2023-11-05 13:46:39 +03:00
2023-11-04 22:06:27 +03:00
return 0;
}