update_readme.pl 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 24 April 2015
  5. # Website: https://github.com/trizen
  6. # Updated the README.md file by adding new scripts to the summary.
  7. use 5.016;
  8. use strict;
  9. use autodie;
  10. use warnings;
  11. use Cwd qw(getcwd);
  12. use File::Spec qw();
  13. use File::Basename qw(basename dirname);
  14. use URI::Escape qw(uri_escape);
  15. sub add_section {
  16. my ($section, $file) = @_;
  17. my ($before, $middle);
  18. open my $fh, '<', $file;
  19. while (defined(my $line = <$fh>)) {
  20. if ($line =~ /^(#+\h*Summary\s*)$/) {
  21. $middle = "$1\n";
  22. last;
  23. }
  24. else {
  25. $before .= $line;
  26. }
  27. }
  28. close $fh;
  29. open my $out_fh, '>', $file;
  30. print {$out_fh} $before . $middle . $section;
  31. close $out_fh;
  32. }
  33. my $summary_file = 'README.md';
  34. my $main_dir = File::Spec->curdir;
  35. # Directories to ignore
  36. my %ignore = (
  37. 'Resources' => 1,
  38. 'Yet to solve' => 1,
  39. 'Trashed attempts' => 1,
  40. );
  41. {
  42. my @root;
  43. sub make_section {
  44. my ($dir, $spaces) = @_;
  45. my $cwd = getcwd();
  46. chdir $dir;
  47. my @files = sort { $a->{key} cmp $b->{key} }
  48. map { {key => fc(s/\.\w+\z//r), name => $_, path => File::Spec->rel2abs($_)} } glob('*');
  49. chdir $cwd;
  50. my $make_section_url = sub {
  51. my ($name) = @_;
  52. join('/', basename($main_dir), @root, $name);
  53. };
  54. my $section = '';
  55. foreach my $file (@files) {
  56. my $title = $file->{name} =~ tr/_/ /r =~ s/ s /'s /gr;
  57. if ($file->{name} =~ /\.\w+\z/) {
  58. $file->{name} =~ /^\d+ / or next;
  59. }
  60. if (-d $file->{path}) {
  61. next if $ignore{$title}; # ignore directory
  62. $section .= (' ' x $spaces) . "* $title\n";
  63. push @root, $file->{name};
  64. $section .= make_section($file->{path}, $spaces + 4);
  65. }
  66. else {
  67. next if $dir eq $main_dir;
  68. my $naked_title = $title =~ s/\.\w{2,3}\z//r;
  69. $naked_title =~ s/.*\K -- (.*)/ ($1)/;
  70. my $url_path = uri_escape($make_section_url->($file->{name}), ' ?');
  71. $section .= (' ' x $spaces) . "* [$naked_title]($url_path)\n";
  72. }
  73. }
  74. pop @root;
  75. return $section;
  76. }
  77. }
  78. my $section = make_section($main_dir, 0);
  79. my $section_content = add_section($section, $summary_file);
  80. say "** All done!";