Add strbuf_append_shell_quote() function

This commit is contained in:
Andrew Bettison 2012-07-26 18:30:24 +09:30
parent 81cafe9d6f
commit 99ead3b9b1
2 changed files with 23 additions and 11 deletions

View File

@ -70,6 +70,19 @@ static int is_shellmeta(char c)
return !(isalnum(c) || c == '.' || c == '-' || c == '/' || c == ':' || c == '+' || c == '_' || c == ',');
}
strbuf strbuf_append_shell_quote(strbuf sb, const char *word)
{
strbuf_putc(sb, '\'');
const char *p;
for (p = word; *p; ++p)
if (*p == '\'')
strbuf_puts(sb, "'\\''");
else
strbuf_putc(sb, *p);
strbuf_putc(sb, '\'');
return sb;
}
strbuf strbuf_append_shell_quotemeta(strbuf sb, const char *word)
{
const char *p;
@ -77,17 +90,10 @@ strbuf strbuf_append_shell_quotemeta(strbuf sb, const char *word)
for (p = word; *p && !hasmeta; ++p)
if (is_shellmeta(*p))
hasmeta = 1;
if (hasmeta) {
strbuf_putc(sb, '\'');
for (p = word; *p; ++p)
if (*p == '\'')
strbuf_puts(sb, "'\\''");
else
strbuf_putc(sb, *p);
strbuf_putc(sb, '\'');
} else {
if (!word[0] || hasmeta)
strbuf_append_shell_quote(sb, word);
else
strbuf_puts(sb, word);
}
return sb;
}

View File

@ -27,7 +27,13 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
strbuf strbuf_append_poll_events(strbuf sb, short events);
/* Append a string with shell metacharacters and spaces quoted.
/* Append a string as a quoted shell word.
* @author Andrew Bettison <andrew@servalproject.com>
*/
strbuf strbuf_append_shell_quote(strbuf sb, const char *word);
/* Append a string as a shell word, quoted if it contains shell metacharacters
* or spaces.
* @author Andrew Bettison <andrew@servalproject.com>
*/
strbuf strbuf_append_shell_quotemeta(strbuf sb, const char *word);