Add new files from gnulib: sh-quote and system-quote.
[libquote.git] / sh-quote.c
blobd5b022885616499422dc39c725ee134d0a6b975e
1 /* Shell quoting.
2 Copyright (C) 2001-2004, 2006, 2009-2022 Free Software Foundation, Inc.
3 Written by Bruno Haible <haible@clisp.cons.org>, 2001.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 /* Specification. */
19 #include "sh-quote.h"
21 #include <stdint.h>
22 #include <string.h>
24 #include "quotearg.h"
26 /* Describes quoting for sh compatible shells. */
27 static const struct quoting_options sh_quoting_options =
29 quoting_style_shell,
31 { 0 },
32 NULL,
33 NULL
36 /* Returns the number of bytes needed for the quoted string. */
37 size_t
38 shell_quote_length (const char *string)
40 return quotearg_buffer (NULL, 0, string, strlen (string),
41 &sh_quoting_options);
44 /* Copies the quoted string to p and returns the incremented p.
45 There must be room for shell_quote_length (string) + 1 bytes at p. */
46 char *
47 shell_quote_copy (char *p, const char *string)
49 return p + quotearg_buffer (p, SIZE_MAX, string, strlen (string), &sh_quoting_options);
52 /* Returns the freshly allocated quoted string. */
53 char *
54 shell_quote (const char *string)
56 return quotearg_allocate (string, strlen (string), &sh_quoting_options);
59 /* Returns a freshly allocated string containing all argument strings, quoted,
60 separated through spaces. */
61 char *
62 shell_quote_argv (const char *const *argv)
64 if (*argv != NULL)
66 const char * const *argp;
67 size_t length;
68 char *command;
69 char *p;
71 length = 0;
73 for (argp = argv;;)
75 length += shell_quote_length (*argp) + 1;
76 argp++;
78 if (*argp == NULL)
79 break;
82 command = malloc (length);
84 if (command == NULL)
85 return NULL;
87 p = command;
89 for (argp = argv;;)
91 p = shell_quote_copy (p, *argp);
92 argp++;
94 if (*argp == NULL)
95 break;
97 *p++ = ' ';
100 *p = '\0';
101 return command;
103 else
104 return strdup ("");