aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: 96e53ce4d63d58bdcdf3943667b6677f1bcea3cc (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. cmark_debug_print(document);
  21. } else {
  22. result = cmark_render_html(document);
  23. printf("%s", result);
  24. free(result);
  25. }
  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_doc_parser *parser;
  34. size_t offset;
  35. cmark_node *document;
  36. parser = cmark_new_doc_parser();
  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 (fgets((char *)buffer, sizeof(buffer), fp)) {
  65. offset = strlen((char *)buffer);
  66. cmark_process_line(parser, buffer, offset);
  67. }
  68. end_timer("processing lines");
  69. fclose(fp);
  70. }
  71. if (numfps == 0) {
  72. /*
  73. document = cmark_parse_file(stdin);
  74. print_document(document, ast);
  75. exit(0);
  76. */
  77. while (fgets((char *)buffer, sizeof(buffer), stdin)) {
  78. offset = strlen((char *)buffer);
  79. cmark_process_line(parser, buffer, offset);
  80. }
  81. }
  82. start_timer();
  83. document = cmark_finish(parser);
  84. end_timer("finishing document");
  85. cmark_free_doc_parser(parser);
  86. start_timer();
  87. print_document(document, ast);
  88. end_timer("print_document");
  89. start_timer();
  90. cmark_free_nodes(document);
  91. end_timer("free_blocks");
  92. free(files);
  93. return 0;
  94. }