all repos — cgit @ e1ad15d368bdeb1bffea588b93a29055c5dfb7f4

a hyperfast web frontend for git written in c

configfile.c (view raw)

 1/* configfile.c: parsing of config files
 2 *
 3 * Copyright (C) 2006-2014 cgit Development Team <cgit@lists.zx2c4.com>
 4 *
 5 * Licensed under GNU General Public License v2
 6 *   (see COPYING for full license text)
 7 */
 8
 9#include <git-compat-util.h>
10#include "configfile.h"
11
12static int next_char(FILE *f)
13{
14	int c = fgetc(f);
15	if (c == '\r') {
16		c = fgetc(f);
17		if (c != '\n') {
18			ungetc(c, f);
19			c = '\r';
20		}
21	}
22	return c;
23}
24
25static void skip_line(FILE *f)
26{
27	int c;
28
29	while ((c = next_char(f)) && c != '\n' && c != EOF)
30		;
31}
32
33static int read_config_line(FILE *f, struct strbuf *name, struct strbuf *value)
34{
35	int c = next_char(f);
36
37	strbuf_reset(name);
38	strbuf_reset(value);
39
40	/* Skip comments and preceding spaces. */
41	for(;;) {
42		if (c == EOF)
43			return 0;
44		else if (c == '#' || c == ';')
45			skip_line(f);
46		else if (!isspace(c))
47			break;
48		c = next_char(f);
49	}
50
51	/* Read variable name. */
52	while (c != '=') {
53		if (c == '\n' || c == EOF)
54			return 0;
55		strbuf_addch(name, c);
56		c = next_char(f);
57	}
58
59	/* Read variable value. */
60	c = next_char(f);
61	while (c != '\n' && c != EOF) {
62		strbuf_addch(value, c);
63		c = next_char(f);
64	}
65
66	return 1;
67}
68
69int parse_configfile(const char *filename, configfile_value_fn fn)
70{
71	static int nesting;
72	struct strbuf name = STRBUF_INIT;
73	struct strbuf value = STRBUF_INIT;
74	FILE *f;
75
76	/* cancel deeply nested include-commands */
77	if (nesting > 8)
78		return -1;
79	if (!(f = fopen(filename, "r")))
80		return -1;
81	nesting++;
82	while (read_config_line(f, &name, &value))
83		fn(name.buf, value.buf);
84	nesting--;
85	fclose(f);
86	strbuf_release(&name);
87	strbuf_release(&value);
88	return 0;
89}
90