| 1 | package Plagger::Plugin::Publish::CSV; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use base qw ( Plagger::Plugin ); | ||
| 5 | |||
| 6 | our $VERSION = 0.02; | ||
| 7 | |||
| 8 | use Encode; | ||
| 9 | use File::Spec; | ||
| 10 | use Text::CSV_PP; | ||
| 11 | use IO::File; | ||
| 12 | |||
| 13 | sub register { | ||
| 14 | my ($self, $context) = @_; | ||
| 15 | $context->register_hook( | ||
| 16 | $self, | ||
| 17 | 'publish.feed' => \&feed, | ||
| 18 | ); | ||
| 19 | } | ||
| 20 | |||
| 21 | sub feed { | ||
| 22 | my ($self, $context, $args) = @_; | ||
| 23 | my $csv = Text::CSV_PP->new({ binary => 1 }); | ||
| 24 | my $append = ($self->conf->{mode} && $self->conf->{mode} eq 'append'); | ||
| 25 | my $dir = $self->conf->{dir}; | ||
| 26 | unless (-e $dir && -d _) { | ||
| 27 | mkdir $dir, 0755 or $context->error("mkdir $dir: $!"); | ||
| 28 | } | ||
| 29 | |||
| 30 | my $file = Plagger::Util::filename_for($args->{feed}, $self->conf->{filename} || "%i.csv"); | ||
| 31 | my $path = File::Spec->catfile($dir, $file); | ||
| 32 | my $io = IO::File->new($append ? ">> $path" : "> $path"); | ||
| 33 | |||
| 34 | my $columns = $self->conf->{column} || [qw(title permalink)]; | ||
| 35 | for my $entry ($args->{feed}->entries) { | ||
| 36 | my $st = $csv->combine(map { $entry->$_ } @$columns); | ||
| 37 | $context->log(error => $self->convert($csv->error_input)) unless $st; | ||
| 38 | $io->printf("%s\n", $self->convert($csv->string)) if $st; | ||
| 39 | } | ||
| 40 | |||
| 41 | $context->log( | ||
| 42 | info => sprintf( | ||
| 43 | "%s to %s: %d entries", | ||
| 44 | $append ? 'Append' : 'Write', | ||
| 45 | $path, | ||
| 46 | $args->{feed}->count | ||
| 47 | ) | ||
| 48 | ); | ||
| 49 | } | ||
| 50 | |||
| 51 | sub convert { | ||
| 52 | my ($self, $str) = @_; | ||
| 53 | utf8::decode($str) unless utf8::is_utf8($str); | ||
| 54 | return encode($self->conf->{encoding} || 'utf8', $str); | ||
| 55 | } | ||
| 56 | |||
| 57 | 1; | ||
| 58 | |||
| 59 | __END__ |