aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: 1e3a6b384384c1d3a281b092af6c5044844257e0 (plain)
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include "cmark.h"
  6. #include "bench.h"
  7. void print_usage()
  8. {
  9. printf("Usage: cmark [FILE*]\n");
  10. printf("Options: --help, -h Print usage information\n");
  11. printf(" --ast Print AST instead of HTML\n");
  12. printf(" --version Print version\n");
  13. }
  14. static void print_document(node_block *document, bool ast)
  15. {
  16. strbuf html = GH_BUF_INIT;
  17. if (ast) {
  18. cmark_debug_print(document);
  19. } else {
  20. cmark_render_html(&html, document);
  21. printf("%s", html.ptr);
  22. strbuf_free(&html);
  23. }
  24. }
  25. void parse_and_render(node_block *document, FILE *fp, bool ast)
  26. {
  27. start_timer();
  28. document = cmark_parse_file(fp);
  29. end_timer("cmark_parse_file");
  30. start_timer();
  31. print_document(document, ast);
  32. end_timer("print_document");
  33. start_timer();
  34. cmark_free_blocks(document);
  35. end_timer("free_blocks");
  36. }
  37. int main(int argc, char *argv[])
  38. {
  39. int i, numfps = 0;
  40. bool ast = false;
  41. int files[argc];
  42. node_block *document = NULL;
  43. for (i = 1; i < argc; i++) {
  44. if (strcmp(argv[i], "--version") == 0) {
  45. printf("cmark %s", VERSION);
  46. printf(" - CommonMark converter (c) 2014 John MacFarlane\n");
  47. exit(0);
  48. } else if ((strcmp(argv[i], "--help") == 0) ||
  49. (strcmp(argv[i], "-h") == 0)) {
  50. print_usage();
  51. exit(0);
  52. } else if (strcmp(argv[i], "--ast") == 0) {
  53. ast = true;
  54. } else if (*argv[i] == '-') {
  55. print_usage();
  56. exit(1);
  57. } else { // treat as file argument
  58. files[numfps++] = i;
  59. }
  60. }
  61. if (numfps == 0) {
  62. parse_and_render(document, stdin, ast);
  63. } else {
  64. for (i = 0; i < numfps; i++) {
  65. FILE *fp = fopen(argv[files[i]], "r");
  66. if (fp == NULL) {
  67. fprintf(stderr, "Error opening file %s: %s\n",
  68. argv[files[i]], strerror(errno));
  69. exit(1);
  70. }
  71. parse_and_render(document, fp, ast);
  72. fclose(fp);
  73. }
  74. }
  75. return 0;
  76. }