[PATCH] Add "git grep" helper
[git/jnareb-git/bp-gitweb.git] / quote.c
blob5e6fda311c5f5fdaa20b7e9d64e46c13b7d9cce8
1 #include "cache.h"
2 #include "quote.h"
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.
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'
14 char *sq_quote(const char *src)
16 static char *buf = NULL;
17 int cnt, c;
18 const char *cp;
19 char *bp;
21 /* count bytes needed to store the quoted string. */
22 for (cnt = 3, cp = src; *cp; cnt++, cp++)
23 if (*cp == '\'')
24 cnt += 3;
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;
37 *bp++ = '\'';
38 *bp = 0;
39 return buf;