From feee60ed9179504a3b7ed94ee19e4a8e4ac025e2 Mon Sep 17 00:00:00 2001 From: Nicolas Steenlant Date: Mon, 4 Dec 2017 13:38:22 +0100 Subject: [PATCH] print csv header even if record stream is empty --- lib/Catmandu/Exporter/CSV.pm | 20 +++++++++++++++----- t/Catmandu-Exporter-CSV.t | 16 ++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/lib/Catmandu/Exporter/CSV.pm b/lib/Catmandu/Exporter/CSV.pm index 37bf5c9f3..e76cd327d 100644 --- a/lib/Catmandu/Exporter/CSV.pm +++ b/lib/Catmandu/Exporter/CSV.pm @@ -42,14 +42,24 @@ sub add { $val; } @$fields ]; - my $fh = $self->fh; - # header + $self->_print_header; + $self->csv->print($self->fh, $row); +} + +sub commit { + my ($self) = @_; + + # ensure header gets printed even if there are no records + $self->_print_header; +} + +sub _print_header { + my ($self) = @_; if (!$self->count && $self->header) { - $self->csv->print($fh, $self->columns || $fields); + my $row = $self->columns || $self->fields; + $self->csv->print($self->fh, $row) if $row && @$row; } - - $self->csv->print($fh, $row); } 1; diff --git a/t/Catmandu-Exporter-CSV.t b/t/Catmandu-Exporter-CSV.t index 353dc96e8..a953b2d63 100644 --- a/t/Catmandu-Exporter-CSV.t +++ b/t/Catmandu-Exporter-CSV.t @@ -75,4 +75,20 @@ $exporter->add_many($fixer->fix($importer)); $csv = "fob\ntest\n"; is $out, $csv, "custom column names as HASH with reject fix"; +# empty exports +$out = ""; +$exporter = $pkg->new(file => \$out, header => 0); +$exporter->commit; +is $out, ""; +$out = ""; +$exporter = $pkg->new(file => \$out); +$exporter->commit; +is $out, ""; +$out = ""; +$exporter = $pkg->new(file => \$out, fields => 'a,b'); +$exporter->commit; +$csv = <