Skip to content

Commit df2be69

Browse files
committed
Loading a config file from the startup location if available
1 parent 6ce8704 commit df2be69

File tree

2 files changed

+44
-11
lines changed

2 files changed

+44
-11
lines changed

src/app_config.c

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,32 +4,64 @@ const char *appconf_paths[] = {"./divinus.yaml", "/etc/divinus.yaml"};
44

55
struct AppConfig app_config;
66

7-
static inline void *open_app_config(FILE **file, const char *flags) {
7+
static inline void open_app_config(FILE **file, const char *flags) {
88
const char **path = appconf_paths;
9+
char conf_path[PATH_MAX], exe_path[PATH_MAX];
910
*file = NULL;
1011

12+
ssize_t exe_len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
13+
if (exe_len != -1) {
14+
char *dir = dirname(exe_path);
15+
exe_path[exe_len] = '\0';
16+
snprintf(conf_path, sizeof(conf_path), "%s/divinus.yaml", dir);
17+
if (!access(conf_path, F_OK)) {
18+
if (*flags == 'w') {
19+
char bak_path[PATH_MAX];
20+
sprintf(bak_path, "%s.bak", conf_path);
21+
remove(bak_path);
22+
rename(conf_path, bak_path);
23+
}
24+
*file = fopen(conf_path, flags);
25+
return;
26+
}
27+
}
28+
1129
while (*path) {
1230
if (access(*path++, F_OK)) continue;
1331
if (*flags == 'w') {
14-
char bkPath[32];
15-
sprintf(bkPath, "%s.bak", *(path - 1));
16-
remove(bkPath);
17-
rename(*(path - 1), bkPath);
32+
char bak_path[PATH_MAX];
33+
sprintf(bak_path, "%s.bak", *(path - 1));
34+
remove(bak_path);
35+
rename(*(path - 1), bak_path);
1836
}
1937
*file = fopen(*(path - 1), flags);
2038
break;
2139
}
2240
}
2341

2442
void restore_app_config(void) {
25-
const char **path = appconf_paths;
43+
char conf_path[PATH_MAX], exe_path[PATH_MAX];
44+
45+
ssize_t exe_len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
46+
if (exe_len != -1) {
47+
char bak_path[PATH_MAX], *dir = dirname(exe_path);
48+
exe_path[exe_len] = '\0';
49+
snprintf(conf_path, sizeof(conf_path), "%s/divinus.yaml", dir);
50+
sprintf(bak_path, "%s.bak", conf_path);
51+
if (!access(bak_path, F_OK)) {
52+
remove(conf_path);
53+
rename(bak_path, conf_path);
54+
return;
55+
}
56+
}
2657

58+
const char **path = appconf_paths;
2759
while (*path) {
28-
char bkPath[32];
29-
sprintf(bkPath, "%s.bak", *path);
30-
if (!access(bkPath, F_OK)) {
60+
char bak_path[PATH_MAX];
61+
sprintf(bak_path, "%s.bak", *path);
62+
if (!access(bak_path, F_OK)) {
3163
remove(*path);
32-
rename(bkPath, *path);
64+
rename(bak_path, *path);
3365
}
3466
path++;
3567
}

src/app_config.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#pragma once
22

3-
#include <limits.h>
3+
#include <libgen.h>
4+
#include <linux/limits.h>
45
#include <stdio.h>
56
#include <stdlib.h>
67
#include <string.h>

0 commit comments

Comments
 (0)