MdParse.pm 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. foreach my $line ( split("\n", $readme_content) ) {
  18. # HEADERS
  19. if ( $line =~ m/^#{1}(?!#)(.*)#$|^#{1}(?!#)(.*)$/ ) {
  20. my $parsed_line;
  21. if ( ! defined $1 || $1 eq "" ) {
  22. $parsed_line = "<h1>$2</h1>";
  23. } else {
  24. $parsed_line = "<h1>$1</h1>";
  25. }
  26. print $fh "$parsed_line";
  27. } elsif ( $line =~ m/^#{2}(?!#)(.*)#{2}$|^#{2}(?!#)(.*)$/ ) {
  28. my $parsed_line;
  29. if ( ! defined $1 || $1 eq "" ) {
  30. $parsed_line = "<h2>$2</h2>";
  31. } else {
  32. $parsed_line = "<h2>$1</h2>";
  33. }
  34. print $fh "$parsed_line";
  35. } elsif ( $line =~ m/^#{3}(?!#)(.*)#{3}$|^#{3}(?!#)(.*)$/ ) {
  36. my $parsed_line;
  37. if ( ! defined $1 || $1 eq "" ) {
  38. $parsed_line = "<h3>$2</h3>";
  39. } else {
  40. $parsed_line = "<h3>$1</h3>";
  41. }
  42. print $fh "$parsed_line";
  43. } elsif ( $line =~ m/^#{4}(?!#)(.*)#{4}$|^#{4}(?!#)(.*)$/ ) {
  44. my $parsed_line;
  45. if ( ! defined $1 || $1 eq "" ) {
  46. $parsed_line = "<h4>$2</h4>";
  47. } else {
  48. $parsed_line = "<h4>$1</h4>";
  49. }
  50. print $fh "$parsed_line";
  51. } elsif ( $line =~ m/^#{5}(?!#)(.*)#{5}$|^#{5}(?!#)(.*)$/ ) {
  52. my $parsed_line;
  53. if ( ! defined $1 || $1 eq "" ) {
  54. $parsed_line = "<h5>$2</h5>";
  55. } else {
  56. $parsed_line = "<h5>$1</h5>";
  57. }
  58. print $fh "$parsed_line";
  59. } elsif ( $line =~ m/^\*(.*)/ ) {
  60. my $parsed_line = "<ul><li>$1</li></ul>";
  61. print $fh "$parsed_line";
  62. }
  63. else {
  64. print $fh "$line</br>";
  65. }
  66. }
  67. print $fh "</br><hr\>";
  68. close $fh;
  69. $logger->info("Parsed README");
  70. return $html_readme;
  71. }
  72. 1;