File: MarkdownTable.pm

package info (click to toggle)
libtext-markdowntable-perl 0.3.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 124 kB
  • sloc: perl: 162; makefile: 2
file content (337 lines) | stat: -rw-r--r-- 7,240 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package Text::MarkdownTable;
use strict;
use warnings;
use 5.010;

our $VERSION = '0.3.1';

use Moo;
use IO::File;
use IO::Handle::Util ();

has file => (
    is      => 'ro',
    lazy    => 1,
    default => sub { \*STDOUT },
);

has fh => (
    is      => 'ro',
    lazy    => 1,
    default => sub {
        my $fh = $_[0]->file;
        $fh = ref $fh 
            ? IO::Handle::Util::io_from_ref($fh) : IO::File->new($fh,"w");
        die "invalid option file" if !$fh;
        binmode $fh, $_[0]->encoding;
        $fh;
    }
);

has encoding => (
    is      => 'ro',
    default => sub { ':utf8' }
);

has fields => (
    is     => 'rw',
    trigger => 1,
);

# TODO: ensure that number of columns is number of fields
has columns => (
    is      => 'lazy',
    coerce  => \&_coerce_list,
    builder => sub { $_[0]->fields }
);

has widths => (
    is      => 'lazy',
    coerce  => \&_coerce_list,
    builder => sub {
        $_[0]->_fixed_width(0);
        return [map { defined($_) ? length $_ : 0 } @{$_[0]->columns}]
    },
);

has header => (
    is => 'rw', 
    default => sub { 1 }
);

has edges => (
    is => 'rw',
    default => sub { 1 },
);

has condense => (
    is => 'rw',
);

has streaming => (is => 'rwp');

has _fixed_width => (is => 'rw', default => sub { 1 });

# TODO: duplicated in Catmandu::Exporter::CSV fields-coerce
sub _coerce_list {
    if (ref $_[0]) {
        return $_[0] if ref $_[0] eq 'ARRAY';
        return [sort keys %{$_[0]}] if ref $_[0] eq 'HASH';
    }    
    return [split ',', $_[0]];
}

sub _trigger_fields {
    my ($self, $fields) = @_;
    $self->{fields} = _coerce_list($fields);
    if (ref $fields and ref $fields eq 'HASH') {
        $self->{columns} = [ map { $fields->{$_} // $_ } @{$self->{fields}} ];
    }
}

sub add {
    my ($self, $data) = @_;
    unless ($self->fields) {
        $self->{fields} = [ sort keys %$data ]
    }
    my $fields = $self->fields;
    my $widths = $self->widths; # may set 
    my $row = [ ];

    if (!$self->streaming and ($self->condense or $self->_fixed_width)) {
        $self->_set_streaming(1);
        $self->_print_header if $self->header;
    }

    foreach my $col (0..(@$fields-1)) {
        my $field = $fields->[$col];
        my $width = $widths->[$col];

        my $value = $data->{$field} // "";
        $value =~ s/[\n|]/ /g;

        my $w = length $value;
        if ($self->_fixed_width) {
            if (!$width or $w > $width) {
                if ($width > 5) {
                    $value = substr($value, 0, $width-3) . '...';
                } else {
                    $value = substr($value, 0, $width);
                }
            }
        } else {
            $widths->[$col] = $w if !$width or $w > $width;
        }
        push @$row, $value;
    }

    $self->_add_row($row);
    $self;
}

sub _add_row {
    my ($self, $row) = @_;

    if ($self->streaming) {
        $self->_print_row($row);
    } else {
        push @{$self->{_rows}}, $row;
    }
}

sub done {
    my ($self) = @_;

    if ($self->{_rows}) {
        $self->_print_header if $self->header;
        $self->_print_row($_) for @{$self->{_rows}};
    }
}

sub _print_header {
    my ($self) = @_;
    my $fh     = $self->fh;

    $self->_print_row($self->columns);
    if ($self->condense) {
        $self->_print_row([ map { '-' x length $_ } @{$self->columns} ]);
    } elsif ($self->edges) {
        print $fh '|'.('-' x ($_+2)) for @{$self->widths};
        print $fh "|\n";
    } else {
        print $fh substr(join('|',map { '-' x ($_+2) } @{$self->widths}),1,-1);
        print $fh "\n";
    }
}

has _row_format => (
    is      => 'lazy',
    builder => sub {
        if ( $_[0]->condense ) {
            join("|",map {"%s"} @{$_[0]->fields})."\n"
        } elsif ( $_[0]->edges ) {
            join("",map {"| %-".$_."s "} @{$_[0]->widths})."|\n";
        } else {
            join(" | ",map {"%-".$_."s"} @{$_[0]->widths})."\n";
        }
    }
);

sub _print_row {
    my ($self, $row) = @_;
    printf {$self->fh} $self->_row_format, @{$row};
}

1;
__END__

=head1 NAME

Text::MarkdownTable - Write Markdown syntax tables from data

=begin markdown

# STATUS

[![Build Status](https://travis-ci.org/nichtich/Text-MarkdownTable.png)](https://travis-ci.org/nichtich/Text-MarkdownTable)
[![Coverage Status](https://coveralls.io/repos/nichtich/Text-MarkdownTable/badge.png)](https://coveralls.io/r/nichtich/Text-MarkdownTable)
[![Kwalitee Score](http://cpants.cpanauthors.org/dist/Text-MarkdownTable.png)](http://cpants.cpanauthors.org/dist/Text-MarkdownTable)

=end markdown

=head1 SYNOPSIS

  my $table = Text::MarkdownTable->new;
  $table->add({one=>"a",two=>"table"});
  $table->add({one=>"is",two=>"nice"});
  $table->done;

  | one | two   |
  |-----|-------|
  | a   | table |
  | is  | nice  |

  Text::MarkdownTable->new( columns => ['X','Y','Z'], edges => 0 )
    ->add({a=>1,b=>2,c=>3})->done;

  X | Y | Z
  --|---|--
  1 | 2 | 3
  
=head1 DESCRIPTION

This module can be used to write data in tabular form, formatted in
MultiMarkdown syntax. The resulting format can be used for instance to display
CSV data or to include data tables in Markdown files. Newlines and vertical
bars in table cells are replaced by a space character and cell values can be
truncated.

=head1 CONFIGURATION

=over

=item file

Filename, GLOB, scalar reference or L<IO::Handle> to write to (default STDOUT).

=item fields

Array, hash reference, or comma-separated list of fields/columns.

=item columns

Column names. By default field names are used.

=item widths

Column widths. By default column widths are calculated automatically to the
width of the widest value. With given widths, the table is directly be written
without buffering and large table cell values are truncated.

=item header

Include header lines. Enabled by default.

=item edges

Include border before first column and after last column. Enabled by default.
Note that single-column tables don't not look like tables if edges are
disabled.

=item condense

Write table unbuffered in condense format:

  one|two
  ---|---
  a|table
  is|nice

Note that single-column tables are don't look like tables on condense format.

=back

=head1 METHODS

=over

=item add( $row )

Add a row as hash reference. Returns the table instance.

=item streaming

Returns whether rows are directly written or buffered until C<done> is called.

=item done

Finish and write the table unless it has already been written in C<streaming>
mode.

=back

=head1 SEE ALSO

See L<Catmandu::Exporter::Table> for an application of this module that can be
used to easily convert data to Markdown tables.

Similar table-generating modules include:

=over

=item L<Text::Table::Tiny>

=item L<Text::TabularDisplay>

=item L<Text::SimpleTable>

=item L<Text::Table>

=item L<Text::ANSITable>

=item L<Text::ASCIITable>

=item L<Text::UnicodeBox::Table>

=item L<Table::Simple>

=item L<Text::SimpleTable>

=item L<Text::SimpleTable::AutoWidth>

=back

=encoding utf8

=head1 AUTHOR

Jakob Voß E<lt>jakob.voss@gbv.deE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright 2014- Jakob Voß

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut