1 // SPDX-License-Identifier: GPL-2.0
8 /* Help to copy the thing properly quoted for the shell safety.
9 * any single quote is replaced with '\'', any exclamation point
10 * is replaced with '\!', and the whole thing is enclosed in a
13 * original sq_quote result
14 * name ==> name ==> 'name'
15 * a b ==> a b ==> 'a b'
16 * a'b ==> a'\''b ==> 'a'\''b'
17 * a!b ==> a'\!'b ==> 'a'\!'b'
19 static inline int need_bs_quote(char c
)
21 return (c
== '\'' || c
== '!');
24 static int sq_quote_buf(struct strbuf
*dst
, const char *src
)
30 to_free
= strbuf_detach(dst
, NULL
);
32 ret
= strbuf_addch(dst
, '\'');
33 while (!ret
&& *src
) {
34 size_t len
= strcspn(src
, "'!");
35 ret
= strbuf_add(dst
, src
, len
);
37 while (!ret
&& need_bs_quote(*src
))
38 ret
= strbuf_addf(dst
, "'\\%c\'", *src
++);
41 ret
= strbuf_addch(dst
, '\'');
47 int sq_quote_argv(struct strbuf
*dst
, const char** argv
, size_t maxlen
)
51 /* Copy into destination buffer. */
52 ret
= strbuf_grow(dst
, 255);
53 for (i
= 0; !ret
&& argv
[i
]; ++i
) {
54 ret
= strbuf_addch(dst
, ' ');
57 ret
= sq_quote_buf(dst
, argv
[i
]);
58 if (maxlen
&& dst
->len
> maxlen
)