summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/autoindex.pm
blob: bb08091aefdf97b4f3043470f3bb8703f2f47a88 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki::Plugin::autoindex;
  3. use warnings;
  4. use strict;
  5. use IkiWiki 2.00;
  6. use Encode;
  7. sub import {
  8. hook(type => "getsetup", id => "autoindex", call => \&getsetup);
  9. hook(type => "refresh", id => "autoindex", call => \&refresh);
  10. }
  11. sub getsetup () {
  12. return
  13. plugin => {
  14. safe => 1,
  15. rebuild => 0,
  16. },
  17. }
  18. sub genindex ($) {
  19. my $page=shift;
  20. my $file=newpagefile($page, $config{default_pageext});
  21. my $template=template("autoindex.tmpl");
  22. $template->param(page => $page);
  23. writefile($file, $config{srcdir}, $template->output);
  24. if ($config{rcs}) {
  25. IkiWiki::rcs_add($file);
  26. }
  27. }
  28. sub refresh () {
  29. eval q{use File::Find};
  30. error($@) if $@;
  31. my (%pages, %dirs);
  32. foreach my $dir ($config{srcdir}, @{$config{underlaydirs}}, $config{underlaydir}) {
  33. find({
  34. no_chdir => 1,
  35. wanted => sub {
  36. $_=decode_utf8($_);
  37. if (IkiWiki::file_pruned($_, $dir)) {
  38. $File::Find::prune=1;
  39. }
  40. elsif (! -l $_) {
  41. my ($f)=/$config{wiki_file_regexp}/; # untaint
  42. return unless defined $f;
  43. $f=~s/^\Q$dir\E\/?//;
  44. return unless length $f;
  45. return if $f =~ /\._([^.]+)$/; # skip internal page
  46. if (! -d _) {
  47. $pages{pagename($f)}=1;
  48. }
  49. elsif ($dir eq $config{srcdir}) {
  50. $dirs{$f}=1;
  51. }
  52. }
  53. }
  54. }, $dir);
  55. }
  56. my %deleted;
  57. if (ref $pagestate{index}{autoindex}{deleted}) {
  58. %deleted=%{$pagestate{index}{autoindex}{deleted}};
  59. foreach my $dir (keys %deleted) {
  60. # remove deleted page state if the deleted page is re-added,
  61. # or if all its subpages are deleted
  62. if ($deleted{$dir} && (exists $pages{$dir} ||
  63. ! grep /^$dir\/.*/, keys %pages)) {
  64. delete $deleted{$dir};
  65. }
  66. }
  67. $pagestate{index}{autoindex}{deleted}=\%deleted;
  68. }
  69. my @needed;
  70. foreach my $dir (keys %dirs) {
  71. if (! exists $pages{$dir} && ! $deleted{$dir} &&
  72. grep /^$dir\/.*/, keys %pages) {
  73. if (exists $IkiWiki::pagemtime{$dir}) {
  74. # This page must have just been deleted, so
  75. # don't re-add it. And remember it was
  76. # deleted.
  77. if (! ref $pagestate{index}{autoindex}{deleted}) {
  78. $pagestate{index}{autoindex}{deleted}={};
  79. }
  80. ${$pagestate{index}{autoindex}{deleted}}{$dir}=1;
  81. }
  82. else {
  83. push @needed, $dir;
  84. }
  85. }
  86. }
  87. if (@needed) {
  88. if ($config{rcs}) {
  89. IkiWiki::disable_commit_hook();
  90. }
  91. foreach my $page (@needed) {
  92. genindex($page);
  93. }
  94. if ($config{rcs}) {
  95. IkiWiki::rcs_commit_staged(
  96. gettext("automatic index generation"),
  97. undef, undef);
  98. IkiWiki::enable_commit_hook();
  99. }
  100. }
  101. }
  102. 1