2 * Copyright 2006 Jon Loeliger
5 #include "git-compat-util.h"
6 #include "interpolate.h"
9 void interp_set_entry(struct interp *table, int slot, const char *value)
11 char *oldval = table[slot].value;
18 newval = xstrdup(value);
20 table[slot].value = newval;
24 void interp_clear_table(struct interp *table, int ninterps)
28 for (i = 0; i < ninterps; i++) {
29 interp_set_entry(table, i, NULL);
35 * Convert a NUL-terminated string in buffer orig
36 * into the supplied buffer, result, whose length is reslen,
37 * performing substitutions on %-named sub-strings from
38 * the table, interps, with ninterps entries.
42 * { "%H", "example.org"},
47 * Returns the length of the substituted string (not including the final \0).
48 * Like with snprintf, if the result is >= reslen, then it overflowed.
51 unsigned long interpolate(char *result, unsigned long reslen,
53 const struct interp *interps, int ninterps)
55 const char *src = orig;
57 unsigned long newlen = 0;
58 const char *name, *value;
59 unsigned long namelen, valuelen;
65 /* Try to match an interpolation string. */
66 for (i = 0; i < ninterps; i++) {
67 name = interps[i].name;
68 namelen = strlen(name);
69 if (strncmp(src, name, namelen) == 0)
73 /* Check for valid interpolation. */
75 value = interps[i].value;
81 valuelen = strlen(value);
82 if (newlen + valuelen < reslen) {
84 memcpy(dest, value, valuelen);
92 /* Straight copy one non-interpolation character. */
93 if (newlen + 1 < reslen)
99 /* XXX: the previous loop always keep room for the ending NUL,
100 we just need to check if there was room for a NUL in the first place */