summaryrefslogtreecommitdiffstats
path: root/src/basic/replace-var.c
blob: 4813ac3d2ba82e793b1a510805181490d3bd55c9 (plain)
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
/* SPDX-License-Identifier: LGPL-2.1-or-later */

#include <errno.h>
#include <stddef.h>
#include <stdlib.h>

#include "alloc-util.h"
#include "macro.h"
#include "replace-var.h"
#include "string-util.h"

/*
 * Generic infrastructure for replacing @FOO@ style variables in
 * strings. Will call a callback for each replacement.
 */

static int get_variable(const char *b, char **r) {
        size_t k;
        char *t;

        assert(b);
        assert(r);

        if (*b != '@')
                return 0;

        k = strspn(b + 1, UPPERCASE_LETTERS "_");
        if (k <= 0 || b[k+1] != '@')
                return 0;

        t = strndup(b + 1, k);
        if (!t)
                return -ENOMEM;

        *r = t;
        return 1;
}

char* replace_var(const char *text, char *(*lookup)(const char *variable, void *userdata), void *userdata) {
        char *r, *t;
        const char *f;
        size_t l;

        assert(text);
        assert(lookup);

        l = strlen(text);
        r = new(char, l+1);
        if (!r)
                return NULL;

        f = text;
        t = r;
        while (*f) {
                _cleanup_free_ char *v = NULL, *n = NULL;
                char *a;
                int k;
                size_t skip, d, nl;

                k = get_variable(f, &v);
                if (k < 0)
                        goto oom;
                if (k == 0) {
                        *(t++) = *(f++);
                        continue;
                }

                n = lookup(v, userdata);
                if (!n)
                        goto oom;

                skip = strlen(v) + 2;

                d = t - r;
                nl = l - skip + strlen(n);
                a = realloc(r, nl + 1);
                if (!a)
                        goto oom;

                l = nl;
                r = a;
                t = r + d;

                t = stpcpy(t, n);
                f += skip;
        }

        *t = 0;
        return r;

oom:
        return mfree(r);
}