MdParse.pm 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package Gsg::MdParse;
  2. use strict;
  3. use warnings;
  4. use Log::Log4perl qw(:easy);
  5. use Exporter qw(import);
  6. our @EXPORT_OK = qw(render_readme);
  7. # README content is passed in as a var, sub returned an HTML version of the parsed markdown
  8. sub render_readme($$) {
  9. my $readme_content = shift;
  10. my $logger = shift;
  11. my $html_readme;
  12. # Might be a better way to do this? TODO
  13. open my $fh, '>>', \$html_readme or die "Can't open variable: $!";
  14. # Main parsing logic, doing it line by line
  15. # I have some ideas on how to make this more robust/efficient,
  16. # but starting with below for POC
  17. my @readme_lines = split("\n", $readme_content);
  18. my $inside_code = 0;
  19. foreach my $line ( @readme_lines ) {
  20. # HEADERS
  21. if ( $line =~ m/^#{1}(?!#)(.*)#$|^#{1}(?!#)(.*)$/ && $inside_code == 0 ) {
  22. my $parsed_line;
  23. if ( ! defined $1 || $1 eq "" ) {
  24. $parsed_line = "<h1>$2</h1>";
  25. } else {
  26. $parsed_line = "<h1>$1</h1>";
  27. }
  28. print $fh "$parsed_line";
  29. } elsif ( $line =~ m/^#{2}(?!#)(.*)#{2}$|^#{2}(?!#)(.*)$/ && $inside_code == 0) {
  30. my $parsed_line;
  31. if ( ! defined $1 || $1 eq "" ) {
  32. $parsed_line = "<h2>$2</h2>";
  33. } else {
  34. $parsed_line = "<h2>$1</h2>";
  35. }
  36. print $fh "$parsed_line";
  37. } elsif ( $line =~ m/^#{3}(?!#)(.*)#{3}$|^#{3}(?!#)(.*)$/ && $inside_code == 0) {
  38. my $parsed_line;
  39. if ( ! defined $1 || $1 eq "" ) {
  40. $parsed_line = "<h3>$2</h3>";
  41. } else {
  42. $parsed_line = "<h3>$1</h3>";
  43. }
  44. print $fh "$parsed_line";
  45. } elsif ( $line =~ m/^#{4}(?!#)(.*)#{4}$|^#{4}(?!#)(.*)$/ && $inside_code == 0) {
  46. my $parsed_line;
  47. if ( ! defined $1 || $1 eq "" ) {
  48. $parsed_line = "<h4>$2</h4>";
  49. } else {
  50. $parsed_line = "<h4>$1</h4>";
  51. }
  52. print $fh "$parsed_line";
  53. } elsif ( $line =~ m/^#{5}(?!#)(.*)#{5}$|^#{5}(?!#)(.*)$/ && $inside_code == 0) {
  54. my $parsed_line;
  55. if ( ! defined $1 || $1 eq "" ) {
  56. $parsed_line = "<h5>$2</h5>";
  57. } else {
  58. $parsed_line = "<h5>$1</h5>";
  59. }
  60. print $fh "$parsed_line";
  61. } elsif ( $line =~ m/^\*(.*)/ && $inside_code == 0) {
  62. my $parsed_line = "<ul><li>$1</li></ul>";
  63. print $fh "$parsed_line";
  64. } elsif ( $line =~ m/^```$/ ) {
  65. if ( $inside_code == 0 ) {
  66. $inside_code = 1;
  67. print $fh "<br>";
  68. } elsif ( $inside_code == 1 ) {
  69. $inside_code = 0;
  70. }
  71. } elsif ( $inside_code == 1 ) {
  72. print $fh "<code>$line</code><br>";
  73. }
  74. else {
  75. print $fh "$line<br>";
  76. }
  77. }
  78. close $fh;
  79. $logger->info("Parsed README");
  80. return $html_readme;
  81. }
  82. 1;