aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: 6134b135f4677f557d925f7fde2c843f8166ca39 (plain)
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include "config.h"
  6. #include "cmark.h"
  7. #include "debug.h"
  8. #include "bench.h"
  9. void print_usage()
  10. {
  11. printf("Usage: cmark [FILE*]\n");
  12. printf("Options: --help, -h Print usage information\n");
  13. printf(" --ast Print AST instead of HTML\n");
  14. printf(" --version Print version\n");
  15. }
  16. static void print_document(cmark_node *document, bool ast)
  17. {
  18. char *result;
  19. if (ast) {
  20. result = cmark_render_ast(document);
  21. } else {
  22. result = cmark_render_html(document);
  23. }
  24. printf("%s", result);
  25. free(result);
  26. }
  27. int main(int argc, char *argv[])
  28. {
  29. int i, numfps = 0;
  30. bool ast = false;
  31. int *files;
  32. char buffer[4096];
  33. cmark_parser *parser;
  34. size_t bytes;
  35. cmark_node *document;
  36. parser = cmark_parser_new();
  37. files = (int *)malloc(argc * sizeof(*files));
  38. for (i = 1; i < argc; i++) {
  39. if (strcmp(argv[i], "--version") == 0) {
  40. printf("cmark %s", CMARK_VERSION);
  41. printf(" - CommonMark converter (c) 2014 John MacFarlane\n");
  42. exit(0);
  43. } else if ((strcmp(argv[i], "--help") == 0) ||
  44. (strcmp(argv[i], "-h") == 0)) {
  45. print_usage();
  46. exit(0);
  47. } else if (strcmp(argv[i], "--ast") == 0) {
  48. ast = true;
  49. } else if (*argv[i] == '-') {
  50. print_usage();
  51. exit(1);
  52. } else { // treat as file argument
  53. files[numfps++] = i;
  54. }
  55. }
  56. for (i = 0; i < numfps; i++) {
  57. FILE *fp = fopen(argv[files[i]], "r");
  58. if (fp == NULL) {
  59. fprintf(stderr, "Error opening file %s: %s\n",
  60. argv[files[i]], strerror(errno));
  61. exit(1);
  62. }
  63. start_timer();
  64. while ((bytes = fread(buffer, 1, sizeof(buffer), fp)) > 0) {
  65. cmark_parser_feed(parser, buffer, bytes);
  66. if (bytes < sizeof(buffer)) {
  67. break;
  68. }
  69. }
  70. end_timer("processing lines");
  71. fclose(fp);
  72. }
  73. if (numfps == 0) {
  74. /*
  75. document = cmark_parse_file(stdin);
  76. print_document(document, ast);
  77. exit(0);
  78. */
  79. while ((bytes = fread(buffer, 1, sizeof(buffer), stdin)) > 0) {
  80. cmark_parser_feed(parser, buffer, bytes);
  81. if (bytes < sizeof(buffer)) {
  82. break;
  83. }
  84. }
  85. }
  86. start_timer();
  87. document = cmark_parser_finish(parser);
  88. end_timer("finishing document");
  89. cmark_parser_free(parser);
  90. start_timer();
  91. print_document(document, ast);
  92. end_timer("print_document");
  93. start_timer();
  94. cmark_node_free(document);
  95. end_timer("free_blocks");
  96. free(files);
  97. return 0;
  98. }