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