aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: f0ecb823a04a061e044bc77d39129fad62b479eb (plain)
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include "bstrlib.h"
  4. #include "stmd.h"
  5. #include "debug.h"
  6. void print_usage()
  7. {
  8. printf("Usage: stmd [FILE*]\n");
  9. printf("Options: --help, -h Print usage information\n");
  10. printf(" --ast Print AST instead of HTML\n");
  11. printf(" --version Print version\n");
  12. }
  13. int main(int argc, char *argv[]) {
  14. int i;
  15. bool ast = false;
  16. int g = 0;
  17. int numfps = 0;
  18. int files[argc];
  19. for (i=1; i < argc; i++) {
  20. if (strcmp(argv[i], "--version") == 0) {
  21. printf("stmd %s", VERSION);
  22. printf(" - CommonMark converter (c) 2014 John MacFarlane\n");
  23. exit(0);
  24. } else if ((strcmp(argv[i], "--help") == 0) ||
  25. (strcmp(argv[i], "-h") == 0)) {
  26. print_usage();
  27. exit(0);
  28. } else if (strcmp(argv[i], "--ast") == 0) {
  29. ast = true;
  30. } else if (*argv[i] == '-') {
  31. print_usage();
  32. exit(1);
  33. } else { // treat as file argument
  34. files[g] = i;
  35. g++;
  36. }
  37. }
  38. numfps = g;
  39. bstring s = NULL;
  40. bstring html;
  41. g = 0;
  42. block * cur = make_document();
  43. int linenum = 1;
  44. extern int errno;
  45. FILE * fp = NULL;
  46. if (numfps == 0) {
  47. // read from stdin
  48. while ((s = bgets((bNgetc) fgetc, stdin, '\n'))) {
  49. check(incorporate_line(s, linenum, &cur) == 0,
  50. "error incorporating line %d", linenum);
  51. bdestroy(s);
  52. linenum++;
  53. }
  54. } else {
  55. // iterate over input file pointers
  56. for (g=0; g < numfps; g++) {
  57. fp = fopen(argv[files[g]], "r");
  58. if (fp == NULL) {
  59. fprintf(stderr, "Error opening file %s: %s\n",
  60. argv[files[g]], strerror(errno));
  61. exit(1);
  62. }
  63. while ((s = bgets((bNgetc) fgetc, fp, '\n'))) {
  64. check(incorporate_line(s, linenum, &cur) == 0,
  65. "error incorporating line %d", linenum);
  66. bdestroy(s);
  67. linenum++;
  68. }
  69. fclose(fp);
  70. }
  71. }
  72. while (cur != cur->top) {
  73. finalize(cur, linenum);
  74. cur = cur->parent;
  75. }
  76. check(cur == cur->top, "problems finalizing open containers");
  77. finalize(cur, linenum);
  78. process_inlines(cur, cur->attributes.refmap);
  79. if (ast) {
  80. print_blocks(cur, 0);
  81. } else {
  82. check(blocks_to_html(cur, &html, false) == 0, "could not format as HTML");
  83. printf("%s", html->data);
  84. bdestroy(html);
  85. }
  86. free_blocks(cur);
  87. return 0;
  88. error:
  89. return -1;
  90. }