]> pd.if.org Git - zpackage/blob - zpm-quote.c
add support for notes
[zpackage] / zpm-quote.c
1 #define _POSIX_C_SOURCE 2
2
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <unistd.h>
7
8 /* for quoting against the shell replace ' with '\'' and surround with
9  * single quotes
10  */
11
12 char *quote(char *s, int chi, char *repl, int addquotes) {
13         size_t size = 0, rsize = 0;
14         char *d, *q, *r;
15         char ch = chi;
16
17         if (!s) return NULL;
18         if (!repl) return NULL;
19
20         rsize = strlen(repl);
21
22         for (d = s; *d; d++) {
23                 if (*d == ch) {
24                         size += rsize-1;
25                 }
26                 size++;
27         }
28
29         if (addquotes) {
30                 size += 2;
31         }
32
33         d = q = malloc(size+1);
34
35         if (q) {
36                 if (addquotes) {
37                         *d++ = ch;
38                 }
39
40                 while (*s) {
41                         if (*s == ch) {
42                                 r = repl;
43                                 while (*r) {
44                                         *d++ = *r++;
45                                 }
46                                 s++;
47                         } else {
48                                 *d++ = *s++;
49                         }
50                         *d = 0;
51                 }
52
53                 if (addquotes) {
54                         *d++ = ch;
55                 }
56                 *d = 0;
57         }
58
59         return q;
60 }
61
62 int main(int ac, char **av) {
63         char *quoted;
64         int i;
65         int ch = '\'';
66         int opt, shellmode = 0, addquotes = 0, ident = 0;
67         char *repl = "''";
68
69         while ((opt = getopt(ac, av, "sqi")) != -1) {
70                 switch (opt) {
71                         case 's': shellmode = 1; break;
72                         case 'q': addquotes = 1; break;
73                         case 'i': ident = 1; break;
74                         default:
75                                   exit(EXIT_FAILURE);
76                                   break;
77                 }
78         }
79         int argn = optind;
80
81         if (shellmode) {
82                 repl = "'\\''";
83         } else if (ident) {
84                 ch = '"';
85                 repl = "\"\"";
86         }
87
88         for (i=argn;i<ac;i++) {
89                 quoted = quote(av[i], ch, repl, addquotes);
90                 printf("%s\n", quoted);
91         }
92         return 0;
93 }