]> git.ipfire.org Git - thirdparty/git.git/blame - quote.c
[PATCH] Make sq_expand() available as sq_quote().
[thirdparty/git.git] / quote.c
CommitLineData
6fb737be
JH
1#include "cache.h"
2#include "quote.h"
3
4/* Help to copy the thing properly quoted for the shell safety.
5 * any single quote is replaced with '\'', and the caller is
6 * expected to enclose the result within a single quote pair.
7 *
8 * E.g.
9 * original sq_quote result
10 * name ==> name ==> 'name'
11 * a b ==> a b ==> 'a b'
12 * a'b ==> a'\''b ==> 'a'\''b'
13 */
14char *sq_quote(const char *src)
15{
16 static char *buf = NULL;
17 int cnt, c;
18 const char *cp;
19 char *bp;
20
21 /* count bytes needed to store the quoted string. */
22 for (cnt = 3, cp = src; *cp; cnt++, cp++)
23 if (*cp == '\'')
24 cnt += 3;
25
26 buf = xmalloc(cnt);
27 bp = buf;
28 *bp++ = '\'';
29 while ((c = *src++)) {
30 if (c != '\'')
31 *bp++ = c;
32 else {
33 bp = strcpy(bp, "'\\''");
34 bp += 4;
35 }
36 }
37 *bp++ = '\'';
38 *bp = 0;
39 return buf;
40}
41