luce.cr 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #
  2. # Copyright (c) 2021, 2023 supercell
  3. #
  4. # SPDX-License-Identifier: BSD-3-Clause
  5. #
  6. require "../src/luce"
  7. require "option_parser"
  8. EXTENSION_SETS = {
  9. "none": Luce::ExtensionSet::NONE,
  10. "CommonMark": Luce::ExtensionSet::COMMON_MARK,
  11. "GitHubFlavoured": Luce::ExtensionSet::GITHUB_FLAVOURED,
  12. "GitHubWeb": Luce::ExtensionSet::GITHUB_WEB,
  13. }
  14. extension_set = EXTENSION_SETS["CommonMark"]
  15. parser = OptionParser.new
  16. parser.banner = "Usage: #{PROGRAM_NAME} [options] [file]"
  17. parser.on("-h", "--help", description: "Print help text and exit") do
  18. puts parser
  19. puts
  20. puts <<-USAGE
  21. Parse [file] as Markdown and print resulting HTML. If [file] is
  22. omitted, use STDIN as input.
  23. By default, CommonMark Markdown will be parsed. This can be changed with
  24. the --extension-set flag.
  25. USAGE
  26. exit 0
  27. end
  28. parser.on("-v", "--version", description: "Print version and exit") do
  29. puts Luce::VERSION
  30. exit 0
  31. end
  32. parser.on("--extension-set=SET", description: "Specify a set of extensions") do |set|
  33. if EXTENSION_SETS[set]?
  34. extension_set = EXTENSION_SETS[set]
  35. else
  36. STDERR.puts "Chosen extension '#{set}' not valid"
  37. puts "Choose one of [none, CommonMark, GitHubFlavoured, GitHubWeb]."
  38. exit(1)
  39. end
  40. end
  41. parser.missing_option do |flag|
  42. STDERR.puts "#{flag} is missing an option."
  43. end
  44. parser.invalid_option do |flag|
  45. STDERR.puts "#{flag} is not a valid option. Please use --help if you need"
  46. exit 1
  47. end
  48. parser.parse
  49. if ARGV.size > 1
  50. puts parser
  51. puts
  52. puts <<-USAGE
  53. Parse [file] as Markdown and print resulting HTML. If [file] is
  54. omitted, use STDIN as input.
  55. By default, CommonMark Markdown will be parsed. THis can be changed with
  56. the --extension-set flag.
  57. USAGE
  58. exit(1)
  59. end
  60. if ARGV.size == 1
  61. # Read argument as a file path
  62. unless File.exists? ARGV.first
  63. STDERR.puts %{File "#{ARGV.first}" doesn't exist}
  64. exit(1)
  65. end
  66. input = File.read(ARGV.first)
  67. puts Luce.to_html(input, extension_set: extension_set)
  68. exit 0
  69. end
  70. # Read from STDIN
  71. builder = String::Builder.new
  72. while line = gets(chomp: false)
  73. builder << line
  74. end
  75. puts Luce.to_html(builder.to_s, extension_set: extension_set)