doc_extract.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. /* This version adds one byte (for nul term) */
  14. static void *grab_file(void *ctx, const char *filename)
  15. {
  16. unsigned int max = 16384, size = 0;
  17. int ret, fd;
  18. char *buffer;
  19. if (streq(filename, "-"))
  20. fd = dup(STDIN_FILENO);
  21. else
  22. fd = open(filename, O_RDONLY, 0);
  23. if (fd < 0)
  24. return NULL;
  25. buffer = talloc_array(ctx, char, max+1);
  26. while ((ret = read(fd, buffer + size, max - size)) > 0) {
  27. size += ret;
  28. if (size == max)
  29. buffer = talloc_realloc(ctx, buffer, char, max*=2 + 1);
  30. }
  31. if (ret < 0) {
  32. talloc_free(buffer);
  33. buffer = NULL;
  34. } else
  35. buffer[size] = '\0';
  36. close(fd);
  37. return buffer;
  38. }
  39. int main(int argc, char *argv[])
  40. {
  41. unsigned int i, j;
  42. for (i = 1; i < argc; i++) {
  43. char *file;
  44. char **lines;
  45. bool printing = false, printed = false;
  46. file = grab_file(NULL, argv[i]);
  47. if (!file)
  48. err(1, "Reading file %s", argv[i]);
  49. lines = strsplit(file, file, "\n", NULL);
  50. for (j = 0; lines[j]; j++) {
  51. if (streq(lines[j], "/**")) {
  52. printing = true;
  53. if (printed++)
  54. puts("\n");
  55. } else if (streq(lines[j], " */"))
  56. printing = false;
  57. else if (printing) {
  58. if (strstarts(lines[j], " * "))
  59. puts(lines[j] + 3);
  60. else if (strstarts(lines[j], " *"))
  61. puts(lines[j] + 2);
  62. else
  63. errx(1, "Malformed line %s:%u",
  64. argv[i], j);
  65. }
  66. }
  67. talloc_free(file);
  68. }
  69. return 0;
  70. }