update_readme.pl 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/perl
  2. # Trizen
  3. # Date: 24 April 2015
  4. # https://github.com/trizen
  5. # Add a given directory to a given section in SUMMARY.md (for gitbooks)
  6. use 5.014;
  7. use strict;
  8. use autodie;
  9. use warnings;
  10. use Cwd qw(getcwd);
  11. use File::Spec qw();
  12. use File::Basename qw(basename dirname);
  13. use URI::Escape qw(uri_escape);
  14. sub add_section {
  15. my ($section, $file) = @_;
  16. my ($before, $middle);
  17. open my $fh, '<', $file;
  18. while (defined(my $line = <$fh>)) {
  19. if ($line =~ /^(#+\h*Summary\s*)$/) {
  20. $middle = "$1\n";
  21. last;
  22. }
  23. else {
  24. $before .= $line;
  25. }
  26. }
  27. close $fh;
  28. open my $out_fh, '>', $file;
  29. print {$out_fh} $before . $middle . $section;
  30. close $out_fh;
  31. }
  32. my $summary_file = 'README.md';
  33. my $main_dir = File::Spec->curdir;
  34. {
  35. my @root;
  36. sub make_section {
  37. my ($dir, $spaces) = @_;
  38. my $cwd = getcwd();
  39. chdir $dir;
  40. my @files = map { {name => $_, path => File::Spec->rel2abs($_)} } glob('*'); # sorting for free
  41. chdir $cwd;
  42. my $make_section_url = sub {
  43. my ($name) = @_;
  44. join('/', basename($main_dir), @root, $name);
  45. };
  46. my $section = '';
  47. foreach my $file (@files) {
  48. my $title = $file->{name} =~ tr/_/ /r;
  49. if (-d $file->{path}) {
  50. $section .= (' ' x $spaces) . "* $title\n";
  51. push @root, $file->{name};
  52. $section .= make_section($file->{path}, $spaces + 4);
  53. }
  54. else {
  55. next if $dir eq $main_dir;
  56. my $naked_title = $title =~ s/\.jl\z//ri;
  57. my $url_path = uri_escape($make_section_url->($file->{name}), ' ');
  58. $section .= (' ' x $spaces) . "* [\u$naked_title]($url_path)\n";
  59. }
  60. }
  61. pop @root;
  62. return $section;
  63. }
  64. }
  65. my $section = make_section($main_dir, 0);
  66. my $section_content = add_section($section, $summary_file);
  67. say "** All done!";