X-Git-Url: https://pd.if.org/git/?a=blobdiff_plain;f=src%2Fquote.c;fp=src%2Fquote.c;h=02df6781d319fe626ccff733bc2ca0c0dcc9f4e1;hb=5dd3c3e64a9574112dda77a5afc167f5daa53fd8;hp=0000000000000000000000000000000000000000;hpb=bd21f0a1265b43ad5f05353a39db31c16826f05c;p=zpackage diff --git a/src/quote.c b/src/quote.c new file mode 100644 index 0000000..02df678 --- /dev/null +++ b/src/quote.c @@ -0,0 +1,102 @@ +#define _POSIX_C_SOURCE 2 + +#include +#include +#include +#include + +/* for quoting against the shell replace ' with '\'' and surround with + * single quotes + */ + +char *quote(char *s, int chi, char *repl, int addquotes) { + size_t size = 0, rsize = 0; + char *d, *q, *r; + char ch = chi; + + if (!s) return NULL; + if (!repl) return NULL; + + rsize = strlen(repl); + + for (d = s; *d; d++) { + if (*d == ch) { + size += rsize-1; + } + size++; + } + + if (addquotes) { + size += 2; + } + + d = q = malloc(size+1); + + if (q) { + if (addquotes) { + *d++ = ch; + } + + while (*s) { + if (*s == ch) { + r = repl; + while (*r) { + *d++ = *r++; + } + s++; + } else { + *d++ = *s++; + } + *d = 0; + } + + if (addquotes) { + *d++ = ch; + } + *d = 0; + } + + return q; +} + +int main(int ac, char **av) { + char *quoted; + int i; + int ch = '\''; + int opt, shellmode = 0, addquotes = 0, ident = 0; + char *repl = "''"; + int count = 0; + char *separator = "\n"; + + while ((opt = getopt(ac, av, "sqid:")) != -1) { + switch (opt) { + case 's': shellmode = 1; break; + case 'q': addquotes = 1; break; + case 'i': ident = 1; break; + case 'd': separator = optarg; break; + default: + exit(EXIT_FAILURE); + break; + } + } + int argn = optind; + + if (shellmode) { + repl = "'\\''"; + } else if (ident) { + ch = '"'; + repl = "\"\""; + } + + count = 0; + for (i=argn;i 0 ? separator : "", quoted); + free(quoted); + count++; + } + if (count > 0) { + printf("\n"); + } + return 0; +}