Use new string.h strsplit() everywhere.
[ccan] / tools / doc_extract.c
1 /* This merely extracts, doesn't do XML or anything. */
2 #include <err.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <string.h>
7 #include <sys/types.h>
8 #include <sys/stat.h>
9 #include <fcntl.h>
10 #include <stdbool.h>
11 #include "talloc/talloc.h"
12 #include "string/string.h"
13
14 /* This version adds one byte (for nul term) */
15 static void *grab_file(void *ctx, const char *filename)
16 {
17         unsigned int max = 16384, size = 0;
18         int ret, fd;
19         char *buffer;
20
21         if (streq(filename, "-"))
22                 fd = dup(STDIN_FILENO);
23         else
24                 fd = open(filename, O_RDONLY, 0);
25
26         if (fd < 0)
27                 return NULL;
28
29         buffer = talloc_array(ctx, char, max+1);
30         while ((ret = read(fd, buffer + size, max - size)) > 0) {
31                 size += ret;
32                 if (size == max)
33                         buffer = talloc_realloc(ctx, buffer, char, max*=2 + 1);
34         }
35         if (ret < 0) {
36                 talloc_free(buffer);
37                 buffer = NULL;
38         } else
39                 buffer[size] = '\0';
40         close(fd);
41         return buffer;
42 }
43
44 int main(int argc, char *argv[])
45 {
46         unsigned int i, j;
47
48         for (i = 1; i < argc; i++) {
49                 char *file;
50                 char **lines;
51                 bool printing = false, printed = false;
52
53                 file = grab_file(NULL, argv[i]);
54                 if (!file)
55                         err(1, "Reading file %s", argv[i]);
56                 lines = strsplit(file, file, "\n", NULL);
57
58                 for (j = 0; lines[j]; j++) {
59                         if (streq(lines[j], "/**")) {
60                                 printing = true;
61                                 if (printed++)
62                                         puts("\n");
63                         } else if (streq(lines[j], " */"))
64                                 printing = false;
65                         else if (printing) {
66                                 if (strstarts(lines[j], " * "))
67                                         puts(lines[j] + 3);
68                                 else if (strstarts(lines[j], " *"))
69                                         puts(lines[j] + 2);
70                                 else
71                                         errx(1, "Malformed line %s:%u",
72                                              argv[i], j);
73                         }
74                 }
75                 talloc_free(file);
76         }
77         return 0;
78 }
79
80                 
81