doc_extract.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. /* Is A == B ? */
  13. #define streq(a,b) (strcmp((a),(b)) == 0)
  14. /* Does A start with B ? */
  15. #define strstarts(a,b) (strncmp((a),(b),strlen(b)) == 0)
  16. /* This version adds one byte (for nul term) */
  17. static void *grab_file(void *ctx, const char *filename)
  18. {
  19. unsigned int max = 16384, size = 0;
  20. int ret, fd;
  21. char *buffer;
  22. if (streq(filename, "-"))
  23. fd = dup(STDIN_FILENO);
  24. else
  25. fd = open(filename, O_RDONLY, 0);
  26. if (fd < 0)
  27. return NULL;
  28. buffer = talloc_array(ctx, char, max+1);
  29. while ((ret = read(fd, buffer + size, max - size)) > 0) {
  30. size += ret;
  31. if (size == max)
  32. buffer = talloc_realloc(ctx, buffer, char, max*=2 + 1);
  33. }
  34. if (ret < 0) {
  35. talloc_free(buffer);
  36. buffer = NULL;
  37. } else
  38. buffer[size] = '\0';
  39. close(fd);
  40. return buffer;
  41. }
  42. /* This is a dumb one which copies. We could mangle instead. */
  43. static char **split(const char *text)
  44. {
  45. char **lines = NULL;
  46. unsigned int max = 64, num = 0;
  47. lines = talloc_array(text, char *, max+1);
  48. while (*text != '\0') {
  49. unsigned int len = strcspn(text, "\n");
  50. lines[num] = talloc_array(lines, char, len + 1);
  51. memcpy(lines[num], text, len);
  52. lines[num][len] = '\0';
  53. text += len + 1;
  54. if (++num == max)
  55. lines = talloc_realloc(text, lines, char *, max*=2 + 1);
  56. }
  57. lines[num] = NULL;
  58. return lines;
  59. }
  60. int main(int argc, char *argv[])
  61. {
  62. unsigned int i, j;
  63. for (i = 1; i < argc; i++) {
  64. char *file;
  65. char **lines;
  66. bool printing = false, printed = false;
  67. file = grab_file(NULL, argv[i]);
  68. if (!file)
  69. err(1, "Reading file %s", argv[i]);
  70. lines = split(file);
  71. for (j = 0; lines[j]; j++) {
  72. if (streq(lines[j], "/**")) {
  73. printing = true;
  74. if (printed++)
  75. puts("\n");
  76. } else if (streq(lines[j], " */"))
  77. printing = false;
  78. else if (printing) {
  79. if (strstarts(lines[j], " * "))
  80. puts(lines[j] + 3);
  81. else if (strstarts(lines[j], " *"))
  82. puts(lines[j] + 2);
  83. else
  84. errx(1, "Malformed line %s:%u",
  85. argv[i], j);
  86. }
  87. }
  88. talloc_free(file);
  89. }
  90. return 0;
  91. }