bootstrap/src/config.c

72 lines
1.5 KiB
C
Raw Normal View History

2023-11-25 02:35:22 +00:00
#include "config.h"
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "path.h"
struct Error *config_new(
2023-11-23 15:07:22 +00:00
const char *cwd,
2023-11-23 11:09:32 +00:00
const char *root_dir,
const char *target,
2023-11-23 14:40:17 +00:00
struct Config **config
2023-11-23 11:09:32 +00:00
) {
2023-11-25 17:37:41 +00:00
assert(target);
2023-11-23 15:07:22 +00:00
if (cwd == 0) {
return ERROR_NEW(ERROR_CONFIG_ENV_CWD_INVALID, "Could not retrieve $CWD.");
}
2023-11-23 15:07:22 +00:00
if (root_dir == 0) {
return ERROR_NEW(
ERROR_CONFIG_ENV_ROOT_DIR_INVALID, "No specified root directory."
);
}
const char *segments[] = {root_dir, target};
2023-11-25 17:37:41 +00:00
const char *filepath =
join_path_segments(sizeof(segments) / sizeof(char *), segments);
struct stat sb;
int stat_res = stat(filepath, &sb);
struct Error *error = 0;
if (stat_res == -1) {
if (errno == ENOENT) {
error = ERROR_NEW(
ERROR_CONFIG_TARGET_NOT_FOUND, "Spec ", filepath, " not found."
);
} else {
error = ERROR_NEW(
ERROR_CONFIG_TARGET_INVALID, "Spec ", filepath, " is invalid."
);
}
goto cleanup;
}
if (!S_ISDIR(sb.st_mode)) {
error = ERROR_NEW(
ERROR_CONFIG_TARGET_NOT_DIR, "Spec ", filepath, " is not a directory."
);
goto cleanup;
}
2023-11-23 14:40:17 +00:00
*config = malloc(sizeof(struct Config));
2023-11-23 15:07:22 +00:00
(*config)->cwd = cwd;
2023-11-23 14:40:17 +00:00
(*config)->root_dir = root_dir;
2023-11-23 15:07:22 +00:00
(*config)->target = target;
cleanup:
2023-11-25 17:37:41 +00:00
free((void *)filepath);
return error;
}
2023-11-23 14:40:17 +00:00
void config_free(struct Config *config) {
if (!config) {
return;
}
free(config);
2023-11-25 03:29:24 +00:00
config = 0;
}