aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: 87cc151ebc886828f0de5af06973e78551423f6c (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_push(parser, buffer, bytes);
  66. }
  67. end_timer("processing lines");
  68. fclose(fp);
  69. }
  70. if (numfps == 0) {
  71. /*
  72. document = cmark_parse_file(stdin);
  73. print_document(document, ast);
  74. exit(0);
  75. */
  76. while ((bytes = fread(buffer, 1, sizeof(buffer), stdin)) > 0) {
  77. cmark_parser_push(parser, buffer, bytes);
  78. }
  79. }
  80. start_timer();
  81. document = cmark_parser_finish(parser);
  82. end_timer("finishing document");
  83. cmark_parser_free(parser);
  84. start_timer();
  85. print_document(document, ast);
  86. end_timer("print_document");
  87. start_timer();
  88. cmark_node_free(document);
  89. end_timer("free_blocks");
  90. free(files);
  91. return 0;
  92. }