micro-utils/builder/builder.c
2023-11-05 21:42:26 +03:00

83 lines
1.7 KiB
C

#include <stdio.h>
#include <errno.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.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");
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] Building %s -> %s\n", src, path);
size_t len = strlen(CC) + strlen(CFLAGS) + strlen(src) + strlen(path) + 7;
char *arg = malloc(len + 1);
if (arg == NULL) {
free(path);
fprintf(stderr, "builder: malloc failed");
exit(1);
}
snprintf(arg, len, "%s %s %s -o %s", CC, CFLAGS, src, path);
system(arg);
free(arg);
free(path);
}
void ListAndCompile(const char *dir, const char *output_dir) {
printf("[CHDIR] %s\n", dir);
if (chdir(dir) < 0) {
fprintf(stderr, "builder: %s: %s\n", dir, strerror(errno));
exit(1);
}
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(libs) / sizeof(char *); i++)
ListAndCompile(objects[i], "../obj"); */
for (size_t i = 0; i < sizeof(objects) / sizeof(char *); i++)
ListAndCompile(objects[i], "../bin");
return 0;
}