Accept comments on stdin (useful for importing).
[ikiwiki] / ikiwiki-comment.in
1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4 use lib '.'; # For use in nonstandard directory, munged by Makefile.
5 use IkiWiki;
6 use IkiWiki::Plugin::comments;
7
8 sub usage () {
9         die gettext("usage: ikiwiki-comment pagefile"), "\n";
10 }
11
12 sub main {
13         my $pagefile=shift || usage ();
14         my $dir=get_dir($pagefile);
15         my $page=get_page($pagefile);
16
17         IkiWiki::Plugin::comments::checkconfig();
18         my $comment_num=1+IkiWiki::Plugin::comments::num_comments($page, $dir);
19
20         chomp(my $content = join('', <STDIN>)) unless -t STDIN;
21
22         my $comment=get_comment(get_username(), $comment_num, $content);
23
24         # This will yield a hash of the comment before it's edited,
25         # but that's ok; the date provides sufficient entropy to avoid collisions,
26         # and the hash of a comment does not need to match its actual content.
27         # Doing it this way avoids needing to move the file to a final
28         # location after it's edited.
29         my $location=IkiWiki::Plugin::comments::unique_comment_location($page, $comment, $dir)."._comment";
30
31         IkiWiki::writefile($location, $dir, $comment);
32         exec_editor("$dir/$location") if -t STDIN;
33 }
34
35 sub get_dir {
36         my ($file) = @_;
37         my $dir=IkiWiki::dirname($file);
38         $dir="." unless length $dir;
39         return $dir;
40 }
41
42 sub get_page {
43         my ($file) = @_;
44         my $page=IkiWiki::basename($file);
45         $page=~s/\.[^.]+$// unless -d $file;
46         return $page;
47 }
48
49 sub get_username {
50         my $username = getpwuid($<);
51         $username="" unless defined $username;
52         return $username;
53 }
54
55 sub get_comment {
56         my ($username, $comment_num, $content) = @_;
57         $content = '' unless defined $content;
58         my $comment="[[!comment format=mdwn\n";
59         $comment.=" username=\"$username\"\n";
60         $comment.=" subject=\"\"\"comment $comment_num\"\"\"\n";
61         $comment.=" " . IkiWiki::Plugin::comments::commentdate() . "\n";
62         $comment.=" content=\"\"\"\n$content\n\"\"\"]]\n";
63         return $comment;
64 }
65
66 sub exec_editor {
67         my ($file) = @_;
68
69         my @editor="vi";
70         if (-x "/usr/bin/editor") {
71                 @editor="/usr/bin/editor";
72         }
73         if (exists $ENV{EDITOR}) {
74                 @editor=split(' ', $ENV{EDITOR});
75         }
76         if (exists $ENV{VISUAL}) {
77         @editor=split(' ', $ENV{VISUAL});
78         }
79         exec(@editor, $file);
80 }
81
82 main(@ARGV);