File: OutputBindings.pm

package info (click to toggle)
libapp-perlrdf-command-query-perl 0.004-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 172 kB
  • sloc: perl: 433; makefile: 2; sh: 1
file content (120 lines) | stat: -rw-r--r-- 2,260 bytes parent folder | download | duplicates (3)
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
package App::perlrdf::FileSpec::OutputBindings;

use 5.010;
use autodie;
use strict;
use warnings;
use utf8;

BEGIN {
	$App::perlrdf::FileSpec::OutputBindings::AUTHORITY = 'cpan:TOBYINK';
	$App::perlrdf::FileSpec::OutputBindings::VERSION   = '0.004';
}

use Any::Moose;
use File::Temp qw(tempfile);
use JSON qw(from_json);
use RDF::Trine;
use Spreadsheet::Wright;
use YAML::XS qw(Dump);

use namespace::clean;

extends 'App::perlrdf::FileSpec::OutputFile';

sub _build_format
{
	my $self = shift;
	return 'YAML'    if $self->uri =~ /\.ya?ml/i;
	return 'XML'     if $self->uri =~ /\.xml/i;
	return 'JSON'    if $self->uri =~ /\.json/i;
	return 'CSV'     if $self->uri =~ /\.csv/i;
	return 'XLS'     if $self->uri =~ /\.xls/i;
	return 'HTML'    if $self->uri =~ /\.html?/i;
	return 'XHTML'   if $self->uri =~ /\.xhtml/i;
	return 'ODS'     if $self->uri =~ /\.ods/i;
	return 'Text';
}

sub serialize_iterator
{
	my ($self, $iter) = @_;

	if ($self->format =~ /json/i)
	{
		$self->handle->print($iter->as_json);
	}
	elsif ($self->format =~ /yaml/i)
	{
		$self->handle->print(Dump from_json($iter->as_json));
	}
	elsif ($self->format =~ /xml/i)
	{
		$iter->print_xml($self->handle);
	}
	elsif ($self->format =~ /te?xt/i)
	{
		$self->handle->print($iter->as_string);
	}
	else
	{
		my ($dummyfh, $filename) = tempfile();
		$dummyfh->close;
		my $s = Spreadsheet::Wright->new(
			filename   => $filename,
			format     => $self->format,
		);
		$s->addrow(map {+{
			font_weight => 'bold',
			font_style  => 'italic',
			content     => $_,
		}} $iter->binding_names);
		while (my $row = $iter->next)
		{
			my %row = %$row;
			$s->addrow(map
			{
				if ($_->is_resource)
				{
					+{
						color       => 'blue',
						content     => $_->as_ntriples,
					}
				}
				elsif ($_->is_literal)
				{
					+{
						color       => 'black',
						content     => $_->as_ntriples,
					}
				}
				elsif (defined $_)
				{
					+{
						color       => 'green',
						content     => $_->as_ntriples,
					}
				}
				else
				{
					+{
						color       => 'black',
						content     => q(),
					}
				}
			}
			@row{ $iter->binding_names });
		}
		$s->close;
		
		local @ARGV = $filename;
		while (<>)
		{
			$self->handle->print($_);
		}
	}
	
	$self->handle->close;
}
	
1;