]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/replace-var.c
Merge pull request #1761 from ssahani/word
[thirdparty/systemd.git] / src / basic / replace-var.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4 This file is part of systemd.
5
6 Copyright 2012 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <string.h>
23
24 #include "alloc-util.h"
25 #include "macro.h"
26 #include "replace-var.h"
27 #include "string-util.h"
28 #include "util.h"
29
30 /*
31 * Generic infrastructure for replacing @FOO@ style variables in
32 * strings. Will call a callback for each replacement.
33 */
34
35 static int get_variable(const char *b, char **r) {
36 size_t k;
37 char *t;
38
39 assert(b);
40 assert(r);
41
42 if (*b != '@')
43 return 0;
44
45 k = strspn(b + 1, UPPERCASE_LETTERS "_");
46 if (k <= 0 || b[k+1] != '@')
47 return 0;
48
49 t = strndup(b + 1, k);
50 if (!t)
51 return -ENOMEM;
52
53 *r = t;
54 return 1;
55 }
56
57 char *replace_var(const char *text, char *(*lookup)(const char *variable, void*userdata), void *userdata) {
58 char *r, *t;
59 const char *f;
60 size_t l;
61
62 assert(text);
63 assert(lookup);
64
65 l = strlen(text);
66 r = new(char, l+1);
67 if (!r)
68 return NULL;
69
70 f = text;
71 t = r;
72 while (*f) {
73 _cleanup_free_ char *v = NULL, *n = NULL;
74 char *a;
75 int k;
76 size_t skip, d, nl;
77
78 k = get_variable(f, &v);
79 if (k < 0)
80 goto oom;
81 if (k == 0) {
82 *(t++) = *(f++);
83 continue;
84 }
85
86 n = lookup(v, userdata);
87 if (!n)
88 goto oom;
89
90 skip = strlen(v) + 2;
91
92 d = t - r;
93 nl = l - skip + strlen(n);
94 a = realloc(r, nl + 1);
95 if (!a)
96 goto oom;
97
98 l = nl;
99 r = a;
100 t = r + d;
101
102 t = stpcpy(t, n);
103 f += skip;
104 }
105
106 *t = 0;
107 return r;
108
109 oom:
110 free(r);
111 return NULL;
112 }