]>
Commit | Line | Data |
---|---|---|
6e6fb527 LP |
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 "macro.h" | |
25 | #include "util.h" | |
26 | #include "replace-var.h" | |
27 | ||
28 | /* | |
29 | * Generic infrastructure for replacing @FOO@ style variables in | |
30 | * strings. Will call a callback for each replacement. | |
31 | */ | |
32 | ||
33 | static int get_variable(const char *b, char **r) { | |
34 | size_t k; | |
35 | char *t; | |
36 | ||
37 | assert(b); | |
38 | assert(r); | |
39 | ||
40 | if (*b != '@') | |
41 | return 0; | |
42 | ||
43 | k = strspn(b + 1, "ABCDEFGHIJKLMNOPQRSTUVWXYZ_"); | |
44 | if (k <= 0 || b[k+1] != '@') | |
45 | return 0; | |
46 | ||
47 | t = strndup(b + 1, k); | |
48 | if (!t) | |
49 | return -ENOMEM; | |
50 | ||
51 | *r = t; | |
52 | return 1; | |
53 | } | |
54 | ||
55 | char *replace_var(const char *text, char *(*lookup)(const char *variable, void*userdata), void *userdata) { | |
56 | char *r, *t; | |
57 | const char *f; | |
58 | size_t l; | |
59 | ||
60 | assert(text); | |
61 | assert(lookup); | |
62 | ||
63 | l = strlen(text); | |
64 | r = new(char, l+1); | |
65 | if (!r) | |
66 | return NULL; | |
67 | ||
68 | f = text; | |
69 | t = r; | |
70 | while (*f) { | |
71 | _cleanup_free_ char *v = NULL, *n = NULL; | |
72 | char *a; | |
73 | int k; | |
74 | size_t skip, d, nl; | |
75 | ||
76 | k = get_variable(f, &v); | |
77 | if (k < 0) | |
78 | goto oom; | |
79 | if (k == 0) { | |
80 | *(t++) = *(f++); | |
81 | continue; | |
82 | } | |
83 | ||
84 | n = lookup(v, userdata); | |
85 | if (!n) | |
86 | goto oom; | |
87 | ||
88 | skip = strlen(v) + 2; | |
89 | ||
90 | d = t - r; | |
91 | nl = l - skip + strlen(n); | |
92 | a = realloc(r, nl + 1); | |
93 | if (!a) | |
94 | goto oom; | |
95 | ||
96 | l = nl; | |
97 | r = a; | |
98 | t = r + d; | |
99 | ||
100 | t = stpcpy(t, n); | |
101 | f += skip; | |
102 | } | |
103 | ||
104 | *t = 0; | |
105 | return r; | |
106 | ||
107 | oom: | |
108 | free(r); | |
109 | return NULL; | |
110 | } |