Skip to content

Commit

Permalink
print csv header even if record stream is empty
Browse files Browse the repository at this point in the history
  • Loading branch information
nics committed Dec 4, 2017
1 parent 837fbdb commit feee60e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
20 changes: 15 additions & 5 deletions lib/Catmandu/Exporter/CSV.pm
Expand Up @@ -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;
Expand Down
16 changes: 16 additions & 0 deletions t/Catmandu-Exporter-CSV.t
Expand Up @@ -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 = <<EOF;
a,b
EOF

done_testing;

0 comments on commit feee60e

Please sign in to comment.