forked from pmer/yak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pref.c
97 lines (84 loc) · 1.7 KB
/
pref.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "diagnostic.h"
#include "list.h"
#include "pref.h"
#include "str.h"
struct pref {
struct list_head link;
char value[PREF_MAX_LINE_LEN + 1];
};
static LIST_HEAD(prefs);
char *pref_get(char *name)
{
struct list_head *node;
struct pref *pref;
int len;
len = strlen(name);
list_for_each(node, &prefs) {
pref = list_entry(node, struct pref, link);
if (!strncmp(name, pref->value, len) && pref->value[len] == ' ')
return pref->value + len + 1; /* skip space */
}
return NULL;
}
static char *pref_find_yakrc()
{
/*
* XXX refactor into path.c, rc.c, maybe?
* Use for finding plugins.txt and allow for others.
*/
static char buf[256];
strcpy(buf, "./yakrc");
if (access(buf, R_OK) == 0)
return buf;
strcpy(buf, getenv("HOME"));
strcat(buf, "/.yak/yakrc");
if (access(buf, R_OK) == 0)
return buf;
return NULL;
}
void pref_init()
{
FILE *f;
char *filename;
char line[PREF_MAX_LINE_LEN + 1];
struct pref *pref;
int len;
filename = pref_find_yakrc();
if (!filename) {
err("couldn't find yakrc");
safe_shutdown_and_die(1);
}
f = fopen(filename, "r");
if (!f)
goto err;
while (!ferror(f) && !feof(f)) {
fgets(line, sizeof(line), f);
chomp(line);
if (*line) {
pref = malloc(sizeof(struct pref));
strcpy(pref->value, line);
list_add(&pref->link, &prefs);
}
}
if (ferror(f))
goto err;
fclose(f);
add_shutdown_fn(pref_finish);
return;
err:
err("error reading %s", filename);
safe_shutdown_and_die(1);
}
void pref_finish()
{
struct list_head *node, *next;
struct pref *pref;
list_for_each_safe(node, next, &prefs) {
pref = list_entry(node, struct pref, link);
free(pref);
}
}