Data-Beacon
view release on metacpan or search on metacpan
Revision history for Perl package Data::Beacon
==============================================
'*' indicates a revision also published at CPAN.
0.3.1 2014-03-22*
- Added abstract to pod, so tools like MetaCPAN can find it
- Added author and copyright/license sections to pod
- Specified 5.8.0 as min version of perl
- Added [AutoPrereqs] to dist.ini so Makefile.PL will get PREREQ_PM
- Added =encoding utf8 to pod, since the pod now contains UTF-8 chars
0.3.0 2012-12-04*
- removed BEACON collection handling
0.2.7 2012-04-10*
- fixed testing bug at *BSD and migrated to dist::Zilla
0.2.5 2010-12-03*
- refactored
0.2.3 2010-11-24
- added simple Beacon collections with DBI
0.2.1 2010-11-02*
- minor fixes and extensions
0.2 2010-11-02
- first full-featured version
0.1 2010-10-27
- first public developer version at github
This software is copyright (c) 2014 by Jakob VoÃ.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
Terms of the Perl programming language system itself
a) the GNU General Public License as published by the Free
Software Foundation; either version 1, or (at your option) any
later version, or
b) the "Artistic License"
--- The GNU General Public License, Version 1, February 1989 ---
This software is Copyright (c) 2014 by Jakob VoÃ.
This is free software, licensed under:
The GNU General Public License, Version 1, February 1989
GNU GENERAL PUBLIC LICENSE
Version 1, February 1989
Copyright (C) 1989 Free Software Foundation, Inc.
51 Franklin St, Suite 500, Boston, MA 02110-1335 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The license agreements of most software companies try to keep users
at the mercy of those companies. By contrast, our General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. The
General Public License applies to the Free Software Foundation's
software and to any other program whose authors commit to using it.
You can use it for your programs, too.
When we speak of free software, we are referring to freedom, not
price. Specifically, the General Public License is designed to make
sure that you have the freedom to give away or sell copies of free
software, that you receive source code or can get it if you want it,
that you can change the software or use pieces of it in new free
programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of a such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must tell them their rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any program or other work which
contains a notice placed by the copyright holder saying it may be
distributed under the terms of this General Public License. The
"Program", below, refers to any such program or work, and a "work based
on the Program" means either the Program or any work containing the
Program or a portion of it, either verbatim or with modifications. Each
licensee is addressed as "you".
1. You may copy and distribute verbatim copies of the Program's source
code as you receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice and
disclaimer of warranty; keep intact all the notices that refer to this
General Public License and to the absence of any warranty; and give any
other recipients of the Program a copy of this General Public License
along with the Program. You may charge a fee for the physical act of
transferring a copy.
2. You may modify your copy or copies of the Program or any portion of
it, and copy and distribute such modifications under the terms of Paragraph
1 above, provided that you also do the following:
a) cause the modified files to carry prominent notices stating that
you changed the files and the date of any change; and
b) cause the whole of any work that you distribute or publish, that
in whole or in part contains the Program or any part thereof, either
with or without modifications, to be licensed at no charge to all
third parties under the terms of this General Public License (except
that you may choose to grant warranty protection to some or all
third parties, at your option).
c) If the modified program normally reads commands interactively when
run, you must cause it, when started running for such interactive use
in the simplest and most usual way, to print or display an
announcement including an appropriate copyright notice and a notice
that there is no warranty (or else, saying that you provide a
warranty) and that users may redistribute the program under these
conditions, and telling the user how to view a copy of this General
Public License.
d) You may charge a fee for the physical act of transferring a
copy, and you may at your option offer warranty protection in
exchange for a fee.
Mere aggregation of another independent work with the Program (or its
derivative) on a volume of a storage or distribution medium does not bring
the other work under the scope of these terms.
3. You may copy and distribute the Program (or a portion or derivative of
it, under Paragraph 2) in object code or executable form under the terms of
Paragraphs 1 and 2 above provided that you also do one of the following:
a) accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of
Paragraphs 1 and 2 above; or,
b) accompany it with a written offer, valid for at least three
years, to give any third party free (except for a nominal charge
for the cost of distribution) a complete machine-readable copy of the
corresponding source code, to be distributed under the terms of
Paragraphs 1 and 2 above; or,
c) accompany it with the information you received as to where the
corresponding source code may be obtained. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form alone.)
Source code for a work means the preferred form of the work for making
modifications to it. For an executable file, complete source code means
all the source code for all modules it contains; but, as a special
exception, it need not include source code for modules which are standard
libraries that accompany the operating system on which the executable
file runs, or for standard header files or definitions files that
accompany that operating system.
4. You may not copy, modify, sublicense, distribute or transfer the
Program except as expressly provided under this General Public License.
Any attempt otherwise to copy, modify, sublicense, distribute or transfer
the Program is void, and will automatically terminate your rights to use
the Program under this License. However, parties who have received
copies, or rights to use copies, from you under this General Public
License will not have their licenses terminated so long as such parties
remain in full compliance.
5. By copying, distributing or modifying the Program (or any work based
on the Program) you indicate your acceptance of this license to do so,
and all its terms and conditions.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the original
licensor to copy, distribute or modify the Program subject to these
terms and conditions. You may not impose any further restrictions on the
recipients' exercise of the rights granted herein.
7. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of the license which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
the license, you may choose any version ever published by the Free Software
Foundation.
8. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
Appendix: How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to humanity, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively convey
the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 19yy <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 1, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) 19xx name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the
appropriate parts of the General Public License. Of course, the
commands you use may be called something other than `show w' and `show
c'; they could even be mouse-clicks or menu items--whatever suits your
program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
program `Gnomovision' (a program to direct compilers to make passes
at assemblers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
That's all there is to it!
--- The Artistic License 1.0 ---
This software is Copyright (c) 2014 by Jakob VoÃ.
This is free software, licensed under:
The Artistic License 1.0
The Artistic License
Preamble
The intent of this document is to state the conditions under which a Package
may be copied, such that the Copyright Holder maintains some semblance of
artistic control over the development of the package, while giving the users of
the package the right to use and distribute the Package in a more-or-less
customary fashion, plus the right to make reasonable modifications.
Definitions:
- "Package" refers to the collection of files distributed by the Copyright
Holder, and derivatives of that collection of files created through
textual modification.
- "Standard Version" refers to such a Package if it has not been modified,
or has been modified in accordance with the wishes of the Copyright
Holder.
- "Copyright Holder" is whoever is named in the copyright or copyrights for
the package.
- "You" is you, if you're thinking about copying or distributing this Package.
- "Reasonable copying fee" is whatever you can justify on the basis of media
cost, duplication charges, time of people involved, and so on. (You will
not be required to justify it to the Copyright Holder, but only to the
computing community at large as a market that must bear the fee.)
- "Freely Available" means that no fee is charged for the item itself, though
there may be fees involved in handling the item. It also means that
recipients of the item may redistribute it under the same conditions they
received it.
1. You may make and give away verbatim copies of the source form of the
Standard Version of this Package without restriction, provided that you
duplicate all of the original copyright notices and associated disclaimers.
2. You may apply bug fixes, portability fixes and other modifications derived
from the Public Domain or from the Copyright Holder. A Package modified in such
a way shall still be considered the Standard Version.
3. You may otherwise modify your copy of this Package in any way, provided that
you insert a prominent notice in each changed file stating how and when you
changed that file, and provided that you do at least ONE of the following:
a) place your modifications in the Public Domain or otherwise make them
Freely Available, such as by posting said modifications to Usenet or an
equivalent medium, or placing the modifications on a major archive site
such as ftp.uu.net, or by allowing the Copyright Holder to include your
modifications in the Standard Version of the Package.
b) use the modified Package only within your corporation or organization.
c) rename any non-standard executables so the names do not conflict with
standard executables, which must also be provided, and provide a separate
manual page for each non-standard executable that clearly documents how it
differs from the Standard Version.
d) make other distribution arrangements with the Copyright Holder.
4. You may distribute the programs of this Package in object code or executable
form, provided that you do at least ONE of the following:
a) distribute a Standard Version of the executables and library files,
together with instructions (in the manual page or equivalent) on where to
get the Standard Version.
b) accompany the distribution with the machine-readable source of the Package
with your modifications.
c) accompany any non-standard executables with their corresponding Standard
Version executables, giving the non-standard executables non-standard
names, and clearly documenting the differences in manual pages (or
equivalent), together with instructions on where to get the Standard
Version.
d) make other distribution arrangements with the Copyright Holder.
5. You may charge a reasonable copying fee for any distribution of this
Package. You may charge any fee you choose for support of this Package. You
may not charge a fee for this Package itself. However, you may distribute this
Package in aggregate with other (possibly commercial) programs as part of a
larger (possibly commercial) software distribution provided that you do not
advertise this Package as a product of your own.
6. The scripts and library files supplied as input to or produced as output
from the programs of this Package do not automatically fall under the copyright
of this Package, but belong to whomever generated them, and may be sold
commercially, and may be aggregated with this Package.
7. C or perl subroutines supplied by you and linked into this Package shall not
be considered part of this Package.
8. The name of the Copyright Holder may not be used to endorse or promote
products derived from this software without specific prior written permission.
9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
The End
# This file was automatically generated by Dist::Zilla::Plugin::Manifest v5.014.
Changes
LICENSE
MANIFEST
META.yml
Makefile.PL
README
TODO
bin/beacon
dist.ini
lib/Data/Beacon.pm
t/beacon.t
t/beacon1.txt
t/beacon2.txt
t/errors.t
t/release-pod-syntax.t
---
abstract: 'BEACON format validating parser and serializer'
author:
- 'Jakob VoÃ'
build_requires:
Test::More: 0
configure_requires:
ExtUtils::MakeMaker: 6.30
dynamic_config: 0
generated_by: 'Dist::Zilla version 5.014, CPAN::Meta::Converter version 2.133380'
license: perl
meta-spec:
url: http://module-build.sourceforge.net/META-spec-v1.4.html
version: 1.4
name: Data-Beacon
requires:
Carp: 0
Exporter: 0
Getopt::Long: 0
Pod::Usage: 0
Scalar::Util: 0
Time::Piece: 0
URI::Escape: 0
base: 0
perl: 5.008
strict: 0
warnings: 0
resources:
bugtracker: https://github.com/nichtich/Data-Beacon/issues
homepage: https://github.com/nichtich/Data-Beacon
repository: https://github.com/nichtich/Data-Beacon.git
version: 0.3.1
Makefile.PL view on Meta::CPAN
# This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v5.014.
use strict;
use warnings;
use 5.008;
use ExtUtils::MakeMaker 6.30;
my %WriteMakefileArgs = (
"ABSTRACT" => "BEACON format validating parser and serializer",
"AUTHOR" => "Jakob Vo\x{df}",
"BUILD_REQUIRES" => {},
"CONFIGURE_REQUIRES" => {
"ExtUtils::MakeMaker" => "6.30"
},
"DISTNAME" => "Data-Beacon",
"EXE_FILES" => [
"bin/beacon"
],
"LICENSE" => "perl",
"NAME" => "Data::Beacon",
"PREREQ_PM" => {
"Carp" => 0,
"Exporter" => 0,
"Getopt::Long" => 0,
"Pod::Usage" => 0,
"Scalar::Util" => 0,
"Time::Piece" => 0,
"URI::Escape" => 0,
"base" => 0,
"strict" => 0,
"warnings" => 0
},
"TEST_REQUIRES" => {
"Test::More" => 0
},
"VERSION" => "0.3.1",
"test" => {
"TESTS" => "t/*.t"
}
);
my %FallbackPrereqs = (
"Carp" => 0,
"Exporter" => 0,
"Getopt::Long" => 0,
"Pod::Usage" => 0,
"Scalar::Util" => 0,
"Test::More" => 0,
"Time::Piece" => 0,
"URI::Escape" => 0,
"base" => 0,
"strict" => 0,
"warnings" => 0
);
unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) {
delete $WriteMakefileArgs{TEST_REQUIRES};
delete $WriteMakefileArgs{BUILD_REQUIRES};
$WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs;
}
delete $WriteMakefileArgs{CONFIGURE_REQUIRES}
unless eval { ExtUtils::MakeMaker->VERSION(6.52) };
WriteMakefile(%WriteMakefileArgs);
This archive contains the distribution Data-Beacon,
version 0.3.1:
BEACON format validating parser and serializer
This software is copyright (c) 2014 by Jakob VoÃ.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
This README file was generated by Dist::Zilla::Plugin::Readme v5.014.
By default, print errors
Easier serialization of BEACON format
beacon(">$file")
beacon( to => $file )
beacon( from => $a, to => $b )
beacon( from => $a, to => $b, links => \&filter ) # needed?
Better document 'appendline/link'
instead of plainbeaconlink
$b->condense( @link ) # auch expanded!
beacon->condense( @link )
Document mixing of raw / expanded
document 'query'
add basic RDF functionality
#!/usr/bin/perl
#PODNAME: beacon
#ABSTRACT: beacon command line client
our $VERSION = '0.3.1'; #VERSION
use strict;
use Getopt::Long;
use Pod::Usage;
use Data::Beacon;
my ($configfile, $file, $name, $testmode, $linksmode, $premeta, $mtime, $dbi,
$help, $man, $quiet, $verbose, $query, $user, $password);
my %commands = map { $_ => 1 }
qw(dump expand about parse query queryexpand);
GetOptions(
"config:s" => \$configfile,
"help|?" => \$help,
"man" => \$man,
"pre:s" => \$premeta,
"file:s" => \$file,
"name:s" => \$name,
"test" => \$testmode,
"quiet" => \$quiet,
"verbose" => \$verbose,
"mtime" => \$mtime,
"dbi:s" => \$dbi,
"user:s" => \$user,
"password:s" => \$password,
# TODO: head and tail
) or pod2usage(2);
my $msg = "beacon version $VERSION";
pod2usage( -msg => $msg, -verbose => 1 )
if $help or (@ARGV and $ARGV[0] eq 'help');
pod2usage(-verbose => 2) if $man;
my %handlers = ( errors => 'print' );
$handlers{errors} = undef if $quiet;
if ( $configfile ) {
open (CNF, $configfile) || failed("could not open config file: $configfile");
my @cnf = grep { $_ ne "" }
map { chomp; $_ =~ s/^\s*|#.*$//g; $_ } <CNF>;
my $line = 0;
my %config = map {
$line++;
$_ =~ /^([^ ]+)\s*=\s*(.*)$/ ||
failed("error in config file $configfile line $line");
$1 => $2
} @cnf;
$dbi ||= $config{dbi};
$user ||= $config{user};
$password ||= $config{password};
}
my $beaconfile;
my $collection;
if ( $dbi ) {
$dbi = "dbi:$dbi" unless $dbi =~ /^dbi:/;
my %opt = (dbi => $dbi);
$opt{user} = $user if defined $user;
$opt{password} = $password if defined $password;
$opt{error} = \&failed unless $quiet;
$collection = Data::Beacon::Collection->new( %opt );
failed( $collection->lasterror ) if $collection->errors;
}
# additional sophisticated command line parsing follows
my %metafields;
while (@ARGV[0] =~ /^([^=]*)=(.*)$/) {
$metafields{$1} = $2;
shift @ARGV;
}
my $cmd = shift @ARGV;
if (defined $cmd) {
if ($cmd eq 'links') {
$cmd = 'dump';
$linksmode = 1;
}
unless ($commands{$cmd}) {
if (defined $file) {
$name = $cmd;
$cmd = shift @ARGV;
} elsif (defined $name) {
$file = $cmd;
$cmd = shift @ARGV;
} else {
$file = $cmd;
$cmd = "parse";
# misspelled command?
failed("File '$file' not found. Use -h for help")
unless ($file eq '-' or -f $file);
}
}
}
unless ($cmd) {
if (defined $file or defined $name) {
$cmd = 'about';
} else {
failed("Please specify at least a command, name, file, or -h or -m for help!\n");
}
}
# parse the metafile first
if (defined $premeta) {
my $m = beacon($premeta);
failed( $m->lasterror ) if $m->errors;
$handlers{pre}= { $m->meta() };
}
$handlers{pre} = { } if (%metafields && !$handlers{pre});
foreach (keys %metafields) {
$handlers{pre}->{$_} = $metafields{$_};
}
sub requirefile {
$file = shift @ARGV unless defined $file;
failed("Please specifiy a file to parse") unless defined $file;
$handlers{mtime} = $file if $mtime;
$beaconfile = beacon( $file, %handlers );
}
sub requirename {
$name = shift @ARGV unless defined $name;
failed("Please specifiy a beacon name!") unless defined $name;
$name = lc($name);
failed("Not a valid beacon name: $name") unless $name =~ /^[a-z][a-z0-9_.-]*$/;
}
sub requirestore {
failed("Command $cmd requires a beacon collection.")
unless $collection;
}
if( $cmd eq 'parse' ) {
requirefile();
} else {
if ($cmd =~ /^((query)?expand|dump|about|query)$/) {
$collection ? requirename() : requirefile();
if ( $cmd =~ /^query(expand)?$/ ) {
$query = shift @ARGV;
failed("Please specifiy an id to query for!") unless defined $query;
};
}
}
# end of additional command line parsing
if ($testmode) {
print "Running in test mode with the following arguments:\n";
print " command: $cmd\n";
print " file: $file\n";
print " name: $name\n";
print " config: $configfile\n";
print " pre: $premeta\n" if defined $premeta;
print " query: $query\n" if $cmd eq 'query';
exit; # TODO: we could perform some more action but read-only
}
my $beacon = $beaconfile;
if ( $collection ) {
if ( $cmd =~ /^(about|dump|(query)?expand|query|delete|update)$/ ) {
$beacon = $collection->get( $name );
if (!$beacon) {
my $msg = $collection->lasterror;
$msg ||= "could not find in collection: $name";
failed($msg);
}
}
}
# Now finally do something
if ( $cmd eq 'parse' ) { # parse a file
if ( !$beaconfile->errors ) { # unless file not found
$beaconfile->parse();
print $beaconfile->metafields();
}
# TODO: show whether there have been errors
} elsif( $cmd eq 'about' ) { # show info about a file or stored beacon
print $beacon->metafields();
} elsif( $cmd eq 'dump' ) { # dump a full, parsed beacon file
print $beacon->metafields() unless $linksmode;
$beacon->parse( links => 'print' );
# TODO: we may warn on errors, wrong count etc.
} elsif( $cmd eq 'expand' ) { # dump a full, parsed beacon file
$beacon->parse( links => 'expand' );
# links => sub { # TODO: implement this method
# print join('|', $beacon->expand(@_)) . "\n";
# });
} elsif( $cmd =~ /^query(expand)?$/ ) {
my $expand = $1;
if ( $beacon->can('query') ) {
my $links = $beacon->query( $query ); # TODO use link handler
if ($links) {
foreach my $l (@$links) {
if ( $expand ) { # TODO move to the library
print join('|', $beacon->expand(@$l)) . "\n";
} else {
print plainbeaconlink(@$l)."\n";
}
}
}
} else {
# start parsing
while ( my @link = $beaconfile->nextlink ) {
print plainbeaconlink(@link)."\n" if $link[0] eq $query;
}
}
}
sub info {
print $_[0] . "\n" if $verbose;
}
sub failed { # error handler
my $msg = shift;
$msg =~ s/\n$//g;
$msg =~ s/ at .+ line \d+//;
print STDERR "$msg!\n";
exit(1);
}
__END__
=pod
=encoding UTF-8
=head1 NAME
beacon - beacon command line client
=head1 VERSION
version 0.3.1
=head1 SYNOPSIS
beacon [ <options> ] {KEY=VALUE} [ <command> <name> ] [ <file> ]
=head1 DESCRIPTION
This command line script can parse, test, and serialize BEACON files.
=head2 COMMANDS
The first command line argument is treated as command or as [file]name,
if it does not match a known command. The following commands are recognized:
=over
=item about
Print the meta fields. This command is the default, if no command is specified.
Parsing BEACON file with this commands stops at the first non-meta line, so
errors in the links will not be detected.
=item parse
Print the meta fields, possibly extended by automatically generated fields,
such as C<COUNT> after parsing the full BEACON file. Use this command to
validate a BEACON file.
=item links
Parse a BEACON file and print all valid links.
=item dump
Parse a BEACON file and print all meta fields (possibly extended),
followed by all valid links.
=item expand
Print all valid links in fully expanded form, without meta fields.
=item query
Query a BEACON file ore stored BEACON for an id (without prefix).
=back
=head1 ARGUMENTS
-file <name> specify a BEACON file (use '-' for stdin)
-name <name> specify a name (for Beacons in a collection)
-pre <file> start with meta fields from a given BEACON file
-mtime use file's modification time if no TIMESTAMP given
-test enable test mode (no stored Beacon is modified)
-quiet suppress all error messages
-help brief help message
-man full documentation with examples
-verbose print additional messages
-dbi <dbi> database connection to a beacon collection
-config <file> specify config file, e.g. for database connection
about <name> show meta information about a file or stored beacon
parse <name> parse a full BEACON file and print meta information
dump <name> parse a BEACON file or dump a stored beacon
links <name> only print links, without meta fields
expand <name> parse and expand a BEACON file or dump a stored Beacon
query <name> <id> query a BEACON file or stored Beacon for an identifier
=head1 EXAMPLES
To show the meta fields of a BEACON file (command C<about>):
beacon about myfile
As C<about> is the default command, alternatively you can use one of:
beacon myfile
beacon -file myfile
beacon -file myfile about
To validate a BEACON file and show errors only:
beacon parse myfile > /dev/null
Prepend meta fields from file C<mfields> to BEACON file C<myfile>.
Use last modification time of C<myfile> as TIMESTAMP if not included
in C<myfile>:
beacon -pre myfields -mtime dump myfile
=head1 NOTE
The command name C<beacon> clashes with a tool of same name from the
ax25-tools package (L<http://www.linux-ax25.org/>). If you need to use
beacon together with hamradio, you need to rename one of the two scripts.
=head1 AUTHOR
Jakob VoÃ
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2014 by Jakob VoÃ.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
name = Data-Beacon
license = Perl_5
version = 0.3.1
copyright_year = 2014
author = Jakob VoÃ
copyright_holder = Jakob VoÃ
[@Basic]
[PodWeaver]
[OurPkgVersion]
[PodSyntaxTests]
[AutoPrereqs]
[PruneFiles]
filename=README.md
[GithubMeta]
issues=1
[Git::Check]
[Git::Tag]
tag_format = %v
tag_message =
[Git::Push]
lib/Data/Beacon.pm view on Meta::CPAN
use strict;
use warnings;
package Data::Beacon;
#ABSTRACT: BEACON format validating parser and serializer
our $VERSION = '0.3.1'; #VERSION
use 5.008;
use Time::Piece;
use Scalar::Util qw(blessed);
use URI::Escape;
use Carp;
use base 'Exporter';
our @EXPORT = qw(plainbeaconlink beacon);
sub new {
my $class = shift;
my $self = bless { }, $class;
$self->_initparams( @_ );
$self->_startparsing;
return $self;
}
sub meta { # TODO: document meta fields
my $self = shift;
return %{$self->{meta}} unless @_;
if (@_ == 1) {
my $key = uc(shift @_);
$key =~ s/^\s+|\s+$//g;
return $self->{meta}->{$key};
}
croak('Wrong number of arguments in SeeAlso::Beacon->meta') if @_ % 2;
my %list = (@_);
foreach my $key (keys %list) {
croak('invalid meta name: "'.$key.'"')
unless $key =~ /^\s*([a-zA-Z_-]+)\s*$/;
my $value = $list{$key};
$key = uc($1);
if ( defined $value ) {
$value =~ s/^\s+|\s+$|\n//g;
} else {
$value = '';
}
if ($value eq '') { # empty field: unset
croak 'You cannot unset meta field #FORMAT' if $key eq 'FORMAT';
delete $self->{meta}->{$key};
} else { # check format of known meta fields
if ($key eq 'TARGET') {
$value =~ s/{id}/{ID}/g;
# TODO: document that {ID} in target is optional (will be appended)
$value .= '{ID}' unless $value =~ /{ID}}/;
my $uri = $value;
$uri =~ s/{ID}//g;
croak 'Invalid #TARGET field: must be an URI pattern'
unless _is_uri($uri);
} elsif ($key eq 'FEED') {
croak 'FEED meta value must be a HTTP/HTTPS URL'
unless $value =~
/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/[^#|]*)?(\?[^#|]*)?$/i;
} elsif ($key eq 'PREFIX') {
croak 'PREFIX meta value must be a URI'
unless _is_uri($value);
} elsif ( $key =~ /^(REVISIT|TIMESTAMP)$/) {
if ($value =~ /^[0-9]+$/) { # seconds since epoch
$value = gmtime($value)->datetime() . 'Z';
# Note that this conversion does not trigger an error
# or warning, but may be dropped in a future version
} else {
# ISO 8601 combined date and time in UTC
$value =~ s/Z$//;
croak $key . ' meta value must be of form YYYY-MM-DDTHH:MM:SSZ'
unless $value = Time::Piece->strptime(
$value, '%Y-%m-%dT%T' );
$value = $value->datetime();
}
} elsif ( $key eq 'FORMAT' ) {
croak 'Invalid FORMAT, must be BEACON or end with -BEACON'
unless $value =~ /^([A-Z]+-)?BEACON$/;
} elsif ( $key eq 'EXAMPLES' ) {
my @examples = map { s/^\s+|\s+$//g; $_ } split '\|', $value;
$self->{examples} = [ grep { $_ ne '' } @examples ];
%{$self->{expected_examples}} =
map { $_ => 1 } @{$self->{examples}};
$value = join '|', @{$self->{examples}};
if ($value eq '') { # yet another edge case: "EXAMPLES: |" etc.
delete $self->{meta}->{EXAMPLES};
$self->{expected_examples} = undef;
next;
}
# Note that examples are not checked for validity,
# because PREFIX may not be set yet.
}
$self->{meta}->{$key} = $value;
}
}
}
sub count {
my $count = $_[0]->meta('COUNT');
return defined $count ? $count : 0;
}
sub line {
return $_[0]->{line};
}
sub lasterror {
return wantarray ? @{$_[0]->{lasterror}} : $_[0]->{lasterror}->[0];
}
sub errors {
return $_[0]->{errors};
}
sub metafields {
my $self = shift;
my %meta = $self->meta();
my %fields = %meta;
# determine default order
my @order = (qw(FORMAT PREFIX TARGET MESSAGE RELATION ANNOTATION),
qw(DESCRIPTION CREATOR CONTACT HOMEPAGE FEED TIMESTAMP UPDATE),
qw(SOURCESET TARGETSET NAME INSTITUTION));
my @lines = map { "#$_: " . $meta{$_} } grep { defined $meta{$_} } @order;
return @lines ? join ("\n", @lines) . "\n" : "";
}
sub parse {
my $self = shift;
$self->_initparams( @_ );
$self->_startparsing if defined $self->{from}; # start from new source
my $line = $self->{lookaheadline};
$line = $self->_readline() unless defined $line;
while (defined $line) {
$self->appendline( $line );
$line = $self->_readline();
}
return $self->errors == 0;
}
sub nextlink {
my $self = shift;
my $line = $self->{lookaheadline};
if (defined $line) {
$self->{lookaheadline} = undef;
} else {
$line = $self->_readline();
return unless defined $line; # undef => EOF
}
do {
my @link = $self->appendline( $line );
return @link if @link; # proceed on empty lines or errors
} while($line = $self->_readline());
return; # EOF
}
sub link {
my $self = shift;
return @{$self->{link}} if $self->{link};
}
sub expanded {
my $self = shift;
if ( $self->{link} ) {
unless ( $self->{expanded} ) {
@{$self->{expanded}} = @{$self->{link}};
$self->_expandlink( $self->{expanded} )
}
return @{$self->{expanded}};
}
}
sub expand {
my $self = shift;
my @fields = @_ > 0 ? @_ : '';
@fields = map { s/^\s+|\s+$//g; $_ }
map { defined $_ ? $_ : '' } @fields;
return if $fields[0] eq '' or (grep { $_ =~ /\||\n|\r/ } @fields);
$self->_expandlink( \@fields );
return unless _is_uri($fields[0]) && _is_uri($fields[3]);
return @fields;
}
sub expandsource {
my ($self, $source) = @_;
return '' unless defined $source;
$source =~ s/^\s+|\s+$//g;
return '' if $source eq '';
$source = $self->{meta}->{PREFIX} . $source
if defined $self->{meta}->{PREFIX};
return _is_uri($source) ? $source : '';
}
sub appendline {
my ($self, $line) = @_;
return unless defined $line;
chomp $line;
$self->{line}++;
$self->{currentline} = $line;
my @parts = split ('\|',$line);
return if (@parts < 1 || $parts[0] =~ /^\s*$/ );
my $link = $self->_fields( @parts );
my $has_link = $self->appendlink( @$link );
$self->{currentline} = undef;
if ( $has_link ) {
return wantarray ? @{ $self->{link} } : 1;
}
return;
}
sub appendlink {
my $self = shift;
my @fields = map { defined $_ ? $_ : '' } @_[0..3];
@fields = map { s/^\s+|\s+$//g; $_ } @fields;
if ( $fields[0] eq '' ) {
$self->_handle_error( 'missing source' );
return;
} elsif ( grep { $_ =~ /\|/ } @fields ) {
$self->_handle_error( 'link fields must not contain \'|\'' );
return;
} elsif ( grep { $_ =~ /[\n\r]/ } @fields ) {
$self->_handle_error( 'link fields must not contain line breaks' );
return;
}
my $msg = $self->_checklink( @fields );
if ( $msg ) {
$self->_handle_error( $msg );
return;
}
# finally got a valid link
$self->{link} = \@fields;
$self->{expanded} = undef;
$self->{meta}->{COUNT}++;
if ( defined $self->{expected_examples} ) { # examples may contain prefix
my @idforms = $fields[0];
my $prefix = $self->{meta}->{PREFIX};
push @idforms, $prefix . $fields[0] if defined $prefix;
foreach my $source (@idforms) {
if ( $self->{expected_examples}->{$source} ) {
delete $self->{expected_examples}->{$source};
$self->{expected_examples} = undef
unless keys %{ $self->{expected_examples} };
}
}
}
if ( $self->{link_handler} ) {
if ( $self->{link_handler} eq 'print' ) {
print plainbeaconlink( @fields ) . "\n";
} elsif ( $self->{link_handler} eq 'expand' ) {
print join('|',$self->expanded) . "\n";
} else {
# TODO: call with expanded link on request
eval { $self->{link_handler}->( @fields ); };
if ( $@ ) {
$self->_handle_error( "link handler died: $@" );
return;
}
}
}
return @fields; # TODO: return expanded on request
}
sub beacon {
return Data::Beacon->new( @_ );
}
sub plainbeaconlink {
shift if ref($_[0]) and UNIVERSAL::isa($_[0],'Data::Beacon');
return '' unless @_;
my @link = map { defined $_ ? $_ : '' } @_[0..3];
@link = map { s/^\s+|\s+$//g; $_; } @link;
return '' if $link[0] eq '';
if ( $link[3] eq '' ){
pop @link;
if ($link[2] eq '') {
pop @link;
pop @link if ($link[1] eq '');
}
} elsif ( _is_uri($link[3]) ) { # only position of _is_uri where argument may be undefined
my $uri = pop @link;
if ($link[2] eq '') {
pop @link;
pop @link if ($link[1] eq '');
}
push @link, $uri;
}
return join('|', @link);
}
sub _initparams {
my $self = shift;
my %param;
if ( @_ % 2 && !blessed($_[0]) && ref($_[0]) && ref($_[0]) eq 'HASH' ) {
my $pre = shift;
%param = @_;
$param{pre} = $pre;
} else {
$self->{from} = (@_ % 2) ? shift(@_) : undef;
%param = @_;
}
$self->{from} = $param{from}
if exists $param{from};
if ( $param{errors} ) {
my $handler = $param{errors};
$handler = $Data::Beacon::ERROR_HANDLERS{lc($handler)}
unless ref($handler);
unless ( ref($handler) and ref($handler) eq 'CODE' ) {
my $msg = 'error handler must be code or '
. join('/',keys %Data::Beacon::ERROR_HANDLERS)
. ', got '
. (defined $handler ? $handler : 'undef');
croak $msg;
}
$self->{error_handler} = $handler;
}
if ( $param{links} ) {
my $handler = $param{links};
croak 'link handler must be code or \'print\' or \'expand\''
unless $handler =~ /^(print|expand)$/
or (ref($handler) and ref($handler) eq 'CODE');
$self->{link_handler} = $handler;
}
if ( defined $param{pre} ) {
croak "pre option must be a hash reference"
unless ref($param{pre}) and ref($param{pre}) eq 'HASH';
$self->{pre} = $param{pre};
} elsif ( exists $param{pre} ) {
$self->{pre} = undef;
}
$self->{mtime} = $param{mtime};
}
sub _startparsing {
my $self = shift;
# we do not init $self->{meta} because it is set in initparams;
$self->{meta} = { 'FORMAT' => 'BEACON' };
$self->meta( %{ $self->{pre} } ) if $self->{pre};
$self->{line} = 0;
$self->{link} = undef;
$self->{expanded} = undef;
$self->{errors} = 0;
$self->{lasterror} = [];
$self->{lookaheadline} = undef;
$self->{fh} = undef;
$self->{inputlines} = [];
$self->{examples} = [];
return unless defined $self->{from};
# decide where to parse from
my $type = ref($self->{from});
if ($type) {
if ($type eq 'SCALAR') {
$self->{inputlines} = [ split("\n",${$self->{from}}) ];
} elsif ($type ne 'CODE') {
$self->_handle_error( "Unknown input $type" );
return;
}
} elsif( $self->{from} eq '-' ) {
$self->{fh} = \*STDIN;
} else {
if(!(open $self->{fh}, $self->{from})) {
$self->_handle_error( 'Failed to open ' . $self->{from} );
return;
}
}
# initlialize TIMESTAMP
if ($self->{mtime}) {
my @stat = stat( $self->{from} );
$self->meta('TIMESTAMP', gmtime( $stat[9] )->datetime() . 'Z' );
}
# start parsing
my $line = $self->_readline();
return unless defined $line;
$line =~ s/^\xEF\xBB\xBF//; # UTF-8 BOM (optional)
do {
$line =~ s/^\s+|\s*\n?$//g;
if ($line eq '') {
$self->{line}++;
} elsif ($line =~ /^#([^:=\s]+)(\s*[:=]?\s*|\s+)(.*)$/) {
$self->{line}++;
eval { $self->meta($1,$3); };
if ($@) {
my $msg = $@; $msg =~ s/ at .*$//;
$self->_handle_error( $msg, $line );
}
} else {
$self->{lookaheadline} = $line;
return;
}
$line = $self->_readline();
} while (defined $line);
}
sub _handle_error {
my $self = shift;
my $msg = shift;
my $line = shift || $self->{currentline} || '';
chomp $line;
$self->{lasterror} = [ $msg, $self->{line}, $line ];
$self->{errors}++;
$self->{error_handler}->( $msg, $self->{line}, $line ) if $self->{error_handler};
}
our %ERROR_HANDLERS = (
'print' => sub {
my ($msg, $lineno) = @_;
$msg .= " at line $lineno" if $lineno ;
print STDERR "$msg\n";
},
'warn' => sub {
my ($msg, $lineno) = @_;
$msg .= " at line $lineno" if $lineno;
carp $msg;
},
'die' => sub {
my ($msg, $lineno) = @_;
$msg .= " at line $lineno" if $lineno;
croak $msg;
}
);
sub _readline {
my $self = shift;
if ($self->{fh}) {
return eval { no warnings; readline $self->{fh} };
} elsif (ref($self->{from}) && ref($self->{from}) eq 'CODE') {
my $line = eval { $self->{from}->(); };
if ($@) { # input handler died
$self->_handle_error( $@, '' );
$self->{from} = undef;
}
return $line;
} else {
return @{$self->{inputlines}} ? shift(@{$self->{inputlines}}) : undef;
}
}
sub _fields {
my $self = shift;
my @parts = @_;
my $n = scalar @parts;
my $link = [shift @parts,"","",""];
my $target = $self->{meta}->{TARGET};
my $targetprefix = $self->{meta}->{TARGETPREFIX};
if ($target or $targetprefix) {
$link->[1] = shift @parts if @parts;
$link->[2] = shift @parts if @parts;
# TODO: do we want both #TARGET links and explicit links in one file?
$link->[3] = shift @parts if @parts;
} else {
$link->[3] = pop @parts
if ($n > 1 && _is_uri($parts[$n-2]));
$link->[1] = shift @parts if @parts;
$link->[2] = shift @parts if @parts;
}
return $link
}
sub _checklink {
my ($self, @fields) = @_;
my @exp = @fields;
# TODO: check only - we don't need full expansion
$self->_expandlink( \@exp );
return "source is no URI: ".$exp[0]
unless _is_uri($exp[0]);
# TODO: we could encode bad characters etc.
return "target is no URI: ".$exp[3]
unless _is_uri($exp[3]);
return undef;
}
sub _expandlink {
my ($self, $link) = @_;
my $prefix = $self->{meta}->{PREFIX};
my $source = $link->[0];
# TODO: document this expansion
if ( $link->[1] =~ /^[0-9]*$/ ) { # if label is number (of hits) or empty
my $label = $link->[1];
my $descr = $link->[2];
# TODO: handle zero hits
my $msg = $self->{meta}->{$label eq '1' ? 'ONEMESSAGE' : 'SOMEMESSAGE'}
|| $self->{meta}->{'MESSAGE'};
if ( defined $msg ) {
_str_replace( $msg, '{id}', $link->[0] ); # unexpanded
_str_replace( $msg, '{hits}', $link->[1] );
_str_replace( $msg, '{label}', $link->[1] );
_str_replace( $msg, '{description}', $link->[2] );
_str_replace( $msg, '{target}', $link->[3] ); # unexpanded
} else {
$msg = $self->{meta}->{'NAME'} || $self->{meta}->{'INSTITUTION'};
}
if ( defined $msg && $msg ne '' ) {
# if ( $link->[1] == "") $descr = $label;
$link->[1] = $msg;
$link->[1] =~ s/^\s+|\s+$//g;
$link->[1] =~ s/\s+/ /g;
}
} else {
_str_replace( $link->[1], '{id}', $link->[0] ); # unexpanded
_str_replace( $link->[1], '{description}', $link->[2] );
_str_replace( $link->[1], '{target}', $link->[3] ); # unexpanded
# trim label, because it may have changed
$link->[1] =~ s/^\s+|\s+$//g;
$link->[1] =~ s/\s+/ /g;
}
# expand source
$link->[0] = $prefix . $link->[0] if defined $prefix;
# expand target
my $target = $self->{meta}->{TARGET};
my $targetprefix = $self->{meta}->{TARGETPREFIX};
if (defined $target) {
$link->[3] = $target;
my $label = $link->[1];
$link->[3] =~ s/{ID}/$source/g;
} elsif( defined $targetprefix ) {
$link->[3] = $targetprefix . $link->[3];
}
return @$link;
}
sub _str_replace {
$_[0] =~ s/\Q$_[1]\E/$_[2]/g;
}
sub _is_uri {
my $value = $_[0];
return unless defined($value);
# check for illegal characters
return if $value =~ /[^a-z0-9\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=\.\-\_\~\%]/i;
# check for hex escapes that aren't complete
return if $value =~ /%[^0-9a-f]/i;
return if $value =~ /%[0-9a-f](:?[^0-9a-f]|$)/i;
# split uri (from RFC 3986)
my($scheme, $authority, $path, $query, $fragment)
= $value =~ m|(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?|;
# scheme and path are required, though the path can be empty
return unless (defined($scheme) && length($scheme) && defined($path));
# if authority is present, the path must be empty or begin with a /
if(defined($authority) && length($authority)){
return unless(length($path) == 0 || $path =~ m!^/!);
} else {
# if authority is not present, the path must not start with //
return if $path =~ m!^//!;
}
# scheme must begin with a letter, then consist of letters, digits, +, ., or -
return unless lc($scheme) =~ m!^[a-z][a-z0-9\+\-\.]*$!;
return 1;
}
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
Data::Beacon - BEACON format validating parser and serializer
=head1 VERSION
version 0.3.1
=head1 SYNOPSIS
use Data::Beacon;
$beacon = beacon(); # create new Beacon object
$beacon = beacon( { # create new Beacon with meta fields
PREFIX => $p, TARGET => $t, XY => $z
} );
$beacon = beacon( $filename ); # open file and parse its meta fields
if ( $b->errors ) { # check for errors
print STDERR $b->lasterror . "\n"
($msg,$lineno,$line) = $b->lasterror;
}
$beacon->parse; # parse all links from opened file
$beacon->parse( links => \&handler ); # parse links, call handler for each
$beacon->parse( errors => \&handler ); # parse links, on error call handler
$beacon->parse( errors => 'print' ); # parse links, print errors to STDERR
$beacon->parse( errors => 'warn' ); # parse links, warn on errors
$beacon->parse( errors => 'die' ); # parse links, die on errors
while ( $beacon->nextlink ) { # parse and iterate all valid links
($source,$label,$descr,$target) = $beacon->link; # raw link as read
($source,$label,$descr,$target) = $beacon->expanded; # full link expanded
}
$descr = $beacon->meta( 'DESCRIPTION' ); # get meta field
$beacon->meta( DESCRIPTION => 'my links' ); # set meta fields
%meta = $beacon->meta; # get all meta fields
print $beacon->metafields; # serialize meta fields
$beacon->parse( \$beaconstring ); # parse from string
$beacon->parse( sub { return $nextline } ); # parse from callback
$beacon->count; # number of parsed links
$beacon->appendline( $line );
$beacon->appendlink( $source, $label, $descr, $target );
=head1 DESCRIPTION
THIS MODULE DOES NOT REFLECT THE CURRENT STATE OF BEACON SPECIFICATION!
This package implements a validating L</BEACON format> parser and serializer.
In short, a "Beacon" is a set of links, together with some meta fields. Each
link at least consists of "source" URI (also referred to as "id") and a "target"
URI. In addition it has a "label" and a "description", which are both Unicode
strings, being the empty string by default.
=head1 BEACON format
B<BEACON format> is the serialization format for Beacons. It defines a very
condense syntax to express links without having to deal much with technical
specifications.
See L<http://gbv.github.com/beaconspec/beacon.html> for a more detailed
description.
=head1 USAGE
=head2 Serializing
To serialize only BEACON meta fields, create a new Beacon object, and set its
meta fields (passed to the constructor, or with L</meta>). You can then get
the meta fields in BEACON format with L</metafields>:
my $beacon = beacon( { PREFIX => ..., TARGET => ... } );
print $beacon->metafields;
The easiest way to serialize links in BEACON format, is to set your Beacon
object's link handler to C<print>, so each link is directly printed to STDOUT.
my $beacon = beacon( \%metafields, links => 'print' );
print $b->metafields();
while ( ... ) {
$beacon->appendlink( $source, $label, $description, $target );
}
Alternatively you can use the function L</plainbeaconlink>. In this case you
should validate links before printing:
if ( $beacon->appendlink( $source, $label, $description, $target ) ) {
print plainbeaconlink( $beacon->link ) . "\n";
}
=head2 Parsing
You can parse BEACON format either as iterator:
my $beacon = beacon( $file );
while ( $beacon->nextlink ) {
my ($source, $label, $description, $target) = $beacon->link;
...
}
Or by push parsing with handler callbacks:
my $beacon = beacon( $file );
$beacon->parse( 'link' => \link_handler );
$errors = $beacon->errors;
Instead of a filename, you can also provide a scalar reference, to parse
from a string. The meta fields are parsed immediately:
my $beacon = beacon( $file );
print $beacon->metafields . "\n";
my $errors = $beacon->errors;
To quickly parse a BEACON file:
use Data::Beacon;
beacon($file)->parse();
=head2 Querying
Data::Beacon does only read or write links. To store links, use one of
its subclasses (to be described later).
=head2 Handlers
To handle errors and links, you can pass handler arguments to the constructor
and to the L</parse> method.
=over
=item C<errors>
By default, errors are silently ignored (C<errors =E<gt> 0>. You should enable
one of the error handlers C<warn> (errors create a warning with C<carp>),
C<die> (errors will let the program die with C<croak>), or C<print> (error
messages will be print to STDERR). Alternatively you can provide a custom error
handler function as code reference. On error this function is provided one to
three arguments: first an error message, second a line number, and third the
content of the current line, if the error resulted in parsing a line of BEACON
format.
=item C<links>
See the L</parse> method for description.
=back
=head1 METHODS
=head2 new ( [ $from ] [, $metafields ] [, $handlers ] )
Create a new Beacon object, optionally from a given file. If you specify a
source via C<$from> argument or as handler C<from =E<gt> $from>, it will be
opened for parsing and all meta fields will immediately be read from it.
Otherwise a new Beacon object will be created, optionally with given meta
fields.
=head2 meta ( [ $key [ => $value [ ... ] ] ] )
Get and/or set one or more meta fields. Returns a hash (no arguments),
or string or undef (one argument), or croaks on invalid arguments. A
meta field can be unset by setting its value to the empty string.
The FORMAT field cannot be unset. This method may also croak if a known
fields, such as FORMAT, PREFIX, FEED, EXAMPLES, REVISIT, TIMESTAMP is
tried to set to an invalid value. Such an error will not change the
error counter of this object or modify C<lasterror>.
=head2 count
If parsing has been started, returns the number of links, successfully read so
far (or zero). If only the meta fields have been parsed, this returns the value
of the meta field. In contrast to C<meta('count')>, this method always returns
a number. Note that all valid links that could be parsed are included, no matter
if processed by a link handler or not.
=head2 line
Returns the current line number or zero.
=head2 lasterror
Returns the last parsing error message (if any). Errors triggered by directly
calling C<meta> are not included. In list context returns a list of error
message, line number, and current line content.
=head2 errors
Returns the number of parsing errors or zero.
=head2 metafields
Return all meta fields, serialized and sorted as string. Althugh the order of
fields is irrelevant, but this implementation always returns the same fields
in same order. To get all meta fields as hash, use the C<meta> method.
=head2 parse ( [ $from ] { handler => coderef | option => $value } )
Parse all remaining links (push parsing). If provided a C<from> parameter,
this starts a new Beacon. That means the following three are equivalent:
$b = new SeeAlso::Beacon( $from );
$b = new SeeAlso::Beacon( from => $from );
$b = new SeeAlso::Beacon;
$b->parse( $from );
If C<from> is a scalar, it is used as file to parse from. Alternatively you
can supply a string reference, or a code reference.
The C<pre> option can be used to set some meta fields before parsing starts.
These fields are cached and reused every time you call C<parse>.
If the C<mtime> option is given, the TIMESTAMP meta value will be initialized
as last modification time of the given file.
By default, all errors are silently ignored, unless you specifiy an error handler
The last error can be retrieved with the C<lasterror> method. The current number
of errors by C<errors>.
Finally, the C<link> handler can be a code reference to a method that is
called for each link (that is each line in the input that contains a valid
link). The following arguments are passed to the handler:
=over
=item C<$source>
Link source as given in BEACON format.
This may be abbreviated but not the empty string.
=item C<$label>
Label as string. This may be the empty string.
=item C<$description>
Description as string. This may be the empty string.
=item C<$target>
Link target as given in BEACON format.
This may be abbreviated or the empty string.
=back
The number of sucessfully parsed links is returned by C<count>.
Errors in link handler and input handler are catched, and produce an
error that is given to the error handler.
=head2 nextlink
Read from the input stream until the next link has been parsed. Empty lines
and invalid lines are skipped, but the error handler is called on invalid
lines. This method can be used for pull parsing. Always returns either the
link as list or an empty list if the end of input has been reached.
=head2 link
Returns the last valid link, that has been read. The link is returned
as list of four values (source, label, description, target) without
expansion. Use the L</expanded> method to get the link with full URIs.
=head2 expanded
Returns the last valid link, that has been read in expanded form. The
link is returned as list of four values (source, label, description,
target), possibly expanded by the meta fields PREFIX, TARGET/TARGETPREFIX,
MESSAGE etc. Use L</expand> to expand an arbitrary link.
=head2 expand ( $source, $label, $description, $target )
Expand a link, consisting of source (mandatory), and label, description,
and target (all optional). Returns the expanded link as array with four
values, or an empty list. This method does append the link to the Beacon
object, nor call any handlers.
=head2 expandsource( $source )
Expand the source part of a link, by prepending the PREFIX meta field, if
given. This method always returns a string, which is the empty string, if
the source parameter could not be expanded to a valid URI.
=head2 appendline( $line )
Append a line of of BEACON format. This method parses the line, and calls the
link handler, or error handler. In scalar context returns whether a link has
been read (that can then be accessed with C<link>). In list context, returns
the parsed link as list, or the empty list, if the line could not be parsed.
=head2 appendlink ( $source [, $label [, $description [, $target ] ] ] )
Append a link. The link is validated and returned as list of four values.
On error the error handler is called and an empty list is returned.
On success the link handler is called.
=head1 FUNCTIONS
The following functions are exported by default.
=head2 beacon ( [ $from ] { handler => coderef } )
Shortcut for C<Data::Beacon-E<gt>new>.
=head2 plainbeaconlink ( $source, $label, $description, $target )
Serialize a link, consisting of source (mandatory), label, description,
and target (all optional) as condensed string in BEACON format. This
function does not check whether the arguments form a valid link or not.
You can pass a simple link, as returned by the L</link> method, or an
expanded link, as returned by L</expanded>.
This function will be removed or renamed.
=head1 INTERNAL METHODS
If you directly call any of this methods, puppies will die.
=head2 _initparams ( [ $from ] { handler => coderef | option => value } | $metafield )
Initialize parameters as passed to C<new> or C<parse>. Known parameters
are C<from>, C<error>, and C<link> (C<from> is not checked here). In
addition you cann pass C<pre> and C<mtime> as options.
=head2 _startparsing
Open a BEACON file and parse all meta fields. Calling this method will reset
the whole object but not the parameters as set with C<_initparams>. If no
source had been specified (with parameter C<from>), this is all the method
does. If a source is given, it is opened and parsed. Parsing stops when the
first non-empty and non-meta field line is encountered. This line is internally
stored as lookahead.
=head2 _handle_error ( $msg [, $line ] )
Internal error handler that calls a custom error handler,
increases the error counter and stores the last error.
=head2 _readline
Internally read and return a line for parsing afterwards. May trigger an error.
=head2 _fields
Gets one or more fields, that are strings, which do not contain C<|> or
newlines. The first string is not empty. Returns a reference to an array
of four fields.
=head2 _expandlink ( $link )
Expand a link, provided as array reference without validation. The link
must have four defined, trimmed fields. After expansion, source and target
must still be checked whether they are valid URIs.
=head2 _is_uri
Check whether a given string is an URI. This function is based on code of
L<Data::Validate::URI>, adopted for performance.
=head1 SEE ALSO
See also L<SeeAlso::Server> for an API to exchange single sets of
beacon links, based on the same source identifier.
=head1 AUTHOR
Jakob VoÃ
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2014 by Jakob VoÃ.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
#!perl -Tw
use strict;
use warnings;
use Test::More;
use_ok('Data::Beacon');
done_testing;
__END__
my $r;
my $b = new Data::Beacon();
isa_ok($b,'Data::Beacon');
$b = beacon();
isa_ok($b,'Data::Beacon');
is( $b->errors, 0 );
# meta fields
my %m = $b->meta();
is_deeply( \%m, { 'FORMAT' => 'BEACON' }, 'meta()' );
is_deeply( $b->meta('fOrMaT'), 'BEACON' );
is_deeply( $b->meta('foo'), undef );
is_deeply( $b->meta( {} ), undef );
# not allowed or bad arguments
my @badmeta = (
[ 'a','b','c' ],
[ 'format' => '' ],
[ ' ' => 'x' ],
[ '~' => 'x' ],
[ 'prefix' => 'htt' ], # invalid PREFIX
[ 'Feed' => 'http://#' ], # invalid FEED
);
foreach my $bad (@badmeta) {
eval { $b->meta( @$bad ); }; ok( $@ );
if (@$bad == 2 && $bad->[0] ne ' ') {
my $line = '#' . join(': ',@$bad) . "\n";
my $c = beacon( \$line );
is( $c->errors, 1, 'bad meta field' );
}
}
is( $b->errors, 0, 'croaking errors are not counted' );
$b->meta( 'prefix' => 'http://foo.org/' );
is_deeply( { $b->meta() }, { 'FORMAT' => 'BEACON', 'PREFIX' => 'http://foo.org/' } );
$b->meta( 'prefix' => 'u:' ); # URI prefix
$b->meta( 'prefix' => '' );
# expandsource
$b = beacon({PREFIX => 'http://foo.org/'});
is( $b->expandsource( 0 ), 'http://foo.org/0', 'expandsource' );
is( $b->expandsource( '' ), '', 'expandsource' );
is( $b->expandsource( undef ), '', 'expandsource' );
is( beacon()->expandsource( 'x' ), '', 'expandsource' );
is( beacon()->expandsource( 'id:0' ), 'id:0', 'expandsource' );
is( beacon()->expandsource( undef ), '', 'expandsource' );
$b->meta('prefix' => undef);
eval { $b->meta( 'revisit' => 'Sun 3rd Nov, 1943' ); };
ok( $@ , 'detect invalid REVISIT');
$b->meta( 'REvisit' => '2010-02-31T12:00:01' );
is_deeply( { $b->meta() },
{ 'FORMAT' => 'BEACON',
'REVISIT' => '2010-03-03T12:00:01' } );
$b->meta( 'REVISIT' => '' );
is( $b->meta( 'EXAMPLES' ), undef );
$b->meta( 'EXAMPLES', 'foo | bar||doz ' );
is( $b->meta('EXAMPLES'), 'foo|bar|doz', 'EXAMPLES' );
$b->meta( 'EXAMPLES', '|' );
is( $b->meta('EXAMPLES'), undef );
$b->meta( 'EXAMPLES', '' );
my $expected = { 'FORMAT' => 'BEACON', 'FOO' => 'bar', 'X' => 'YZ' };
$b->meta('foo' => 'bar ', ' X ' => " Y\nZ");
is_deeply( { $b->meta() }, $expected );
$b->meta('foo',''); # unset
is_deeply( { $b->meta() }, { 'FORMAT' => 'BEACON', 'X' => 'YZ' } );
eval { $b->meta( 'format' => 'foo' ); }; ok( $@, 'detect invalid FORMAT' );
$b->meta( 'format' => 'FOO-BEACON' );
is( $b->meta('format'), 'FOO-BEACON' );
is( $b->meta('COUNT'), undef, 'meta("COUNT")' );
is( $b->count, 0, 'count()' );
$b->meta('count' => 7);
is( $b->count, 7, 'count()' );
is( $b->line, 0, 'line()' );
# {ID} or {LABEL} in #TARGET optional
$b->meta( 'target' => 'u:ri:' );
is ( $b->meta('target'), 'u:ri:{ID}' );
$b = beacon( $expected );
is_deeply( { $b->meta() }, $expected );
is( $b->errors, 0 );
my ($haserror, @l);
$b = beacon( errors => sub { $haserror = 1; } );
$b->meta('PREFIX','x:');
#ok( $b->appendlink('0','','','0'), 'zero is valid source' );
#ok( !$b->errors && !$haserror, 'error handler not called' );
$b = beacon( $expected, errors => sub { $haserror = 1; } );
ok( !$b->errors && !$haserror, 'error handler' );
$b->appendlink('0');
ok( $b->errors && $haserror, 'error handler' );
$b = beacon();
$b->meta( 'feed' => 'http://example.com', 'target' => 'http://example.com/{ID}' );
$b = beacon();
ok (! $b->appendline( undef ), 'undef line');
my %t;
=head1
# split BEACON format link without validating or expanding
# line parsing (invalid URI not checked)
%t = (
"qid" => ["qid","","",""],
"qid|\t" => ["qid","","",""],
"qid|" => ["qid","","",""],
"qid|lab" => ["qid","lab","",""],
"qid| lab |dsc" => ["qid","lab","dsc",""],
"qid| | dsc" => ["qid","","dsc",""],
" qid||dsc" => ["qid","","dsc",""],
"qid |u:ri" => ["qid","","","u:ri"],
"qid |lab |dsc|u:ri" => ["qid","lab","dsc","u:ri"],
"qid|lab|u:ri" => ["qid","lab","","u:ri"],
" \t" => [],
"" => [],
"qid|lab|dsc|u:ri|foo" => ["qid","lab","dsc","u:ri"]
"|qid|u:ri" => [],
"qid|lab|dsc|abc" => "URI part has not valid URI form: abc",
);
while (my ($line, $link) = each(%t)) {
# my @l = $b->appendline( $line );
use Data::Dumper;
print "L:$line\n";
print Dumper(\@l)."\n";
#$r = parsebeaconlink( $line ); # without prefix or target
#is_deeply( \@l, $link );
}
=cut
# with prefix and target
$b = beacon({PREFIX=>'x:',TARGET=>'y:'});
ok( $b->appendline( "0|z" ), 'appendline, scalar' );
%t = ("qid |u:ri" => ['qid','u:ri','','']);
while (my ($line, $link) = each(%t)) {
ok( $b->appendline( $line ), 'appendline, scalar' );
my @l = $b->appendline( $line );
@l = @l[0..3];
is_deeply( \@l, $link, 'appendline, list' );
# TODO: test fullid and fulluri
ok( $b->appendlink( @l ), 'appendlink, scalar' );
my @l2 = $b->appendlink( @l );
@l2 = @l2[0..3];
is_deeply( \@l2, $link, 'appendlink, list' );
}
# with prefix only
$b = beacon({PREFIX=>'x:'});
%t = (
'a|b|http://example.com/bar' => ['x:a','b','','http://example.com/bar'],
"a|b|http://example.com/bar\n" => ['x:a','b','','http://example.com/bar']
);
while (my ($line, $link) = each(%t)) {
ok( $b->appendline($line) );
$b->expanded; # multiple calls should not alter the link
$line =~ s/\n//;
is_deeply( [ $b->expanded ], $link, "expanded with PREFIX: $line" );
}
# file parsing
$b = beacon("~");
is( $b->errors, 1, 'failed to open file' );
$b = beacon( undef );
is( $b->errors, 0, 'no file specified' );
$b = beacon( "t/beacon1.txt" );
is_deeply( { $b->meta() }, {
'FORMAT' => 'BEACON',
'TARGET' => 'http://example.com/{ID}',
'FOO' => 'bar doz',
'PREFIX' => 'x:'
}, "parsing meta fields" );
is( $b->line, 6, 'line()' );
$b->parse();
is( $b->errors, 0 );
is( $b->count, 7 );
$b->parse("~");
is( $b->errors, 1 );
my $e = $b->lasterror;
is( $e, 'Failed to open ~', 'lasterror, scalar context' );
my @es = $b->lasterror;
is_deeply( \@es, [ 'Failed to open ~', 0, '' ], 'lasterror, list context' );
$b->parse( { } );
is( $b->errors, 1, 'cannot parse a hashref' );
# string parsing
$b->parse( \"x:from|x:to\n\n|comment" );
is( $b->count, 1, 'parse from string' );
is( $b->line, 3, '' );
is_deeply( [$b->link], ['x:from','','','x:to'] );
is_deeply( [$b->expanded], ['x:from','','','x:to'] );
$b->parse( \"\xEF\xBB\xBFx:from|x:to", links => sub { @l = @_; } );
is( $b->line, 1 );
is( $b->errors, 0 );
is_deeply( \@l, [ 'x:from', '', '', 'x:to' ], 'BOM' );
my @tmplines = ( '#FOO: bar', '#DOZ', '#BAZ: doz' );
$b->parse( from => sub { return shift @tmplines; } );
is( $b->line, 3, 'parse from code ref' );
is( $b->count, 0, '' );
is( $b->metafields, "#FORMAT: BEACON\n#BAZ: doz\n#FOO: bar\n#COUNT: 0\n" );
is( $b->link, undef, 'no links' );
$b->parse( from => sub { die 'hard'; } );
is( $b->errors, 1 );
ok( $b->lasterror =~ /^hard/, 'dead input will not kill us' );
# expected examples
$b = beacon( \"#EXAMPLES: a:b|c:d\na:b|to:1\nc:d|to:2" );
ok( $b->parse() );
$b = beacon( \"#EXAMPLES: a:b|c\na:b|to:1" );
$b->parse();
is_deeply( [ $b->lasterror ], [ 'examples not found: c',2,''], 'examples' );
$b = beacon( \"#EXAMPLES: a\n#PREFIX x:\na|to:1" );
ok( $b->parse() );
$b = beacon( \"#EXAMPLES: x:a\n#PREFIX x:\na|to:1" );
ok( $b->parse() );
# ensure that IDs are URIs
$b = beacon( \"xxx |foo" );
$b->parse();
is_deeply( [ $b->lasterror ], [ 'source is no URI: xxx',1,'xxx |foo' ],
'skipped non-URI id' );
# pull parsing
$b = beacon( \"\nid:1|t:1\n|comment\n" );
is_deeply( [$b->nextlink], ["id:1","","","t:1"] );
is_deeply( [$b->expanded], ["id:1","","","t:1"] );
is_deeply( [$b->nextlink], [] );
is_deeply( [$b->link], ["id:1","","","t:1"], 'last link' );
$b = beacon( \"id:1|t:1\na b|\nid:2|t:2" );
is_deeply( [$b->nextlink], ["id:1","","","t:1"] );
# a b| is ignored
is_deeply( [$b->nextlink], ["id:2","","","t:2"] );
is_deeply( [$b->link], ["id:2","","","t:2"] );
ok( !$b->nextlink );
is( $b->errors, 1 );
is_deeply( [ $b->lasterror ], [ 'source is no URI: a b',2,'a b|' ] );
# check method 'plainbeaconlink'
my @p = (
["",""],
["","","","http://example.com"]
);
while (@p) {
my $in = shift @p;
is( plainbeaconlink( @{$in} ), '', 'plainbeaconlink = ""');
}
@p = (
["a","b","c ",""], "a|b|c",
["a"," b","",""], "a|b",
["a","","",""], "a",
["a"," b ","c"," z"] => 'a|b|c|z',
["a","","","z"] => 'a|||z',
["a"," "," b "] => 'a||b',
);
while (@p) {
my $in = shift @p;
my $out = shift @p;
my $line = plainbeaconlink( @{$in} );
is( $line, $out, 'plainbeaconlink');
$line = "#PREFIX: http://example.org/\n$line";
$b = beacon( \$line );
ok( !$b->parse ); # TARGET is not an URI
$line = "#TARGET: foo:{ID}\n$line";
$b = beacon( \$line );
my $l = [$b->nextlink];
@$in = map { s/^\s+|\s+$//g; $_; } @$in;
push (@$in,'') while ( @$in < 4 );
is_deeply( $in, $l, 'plainbeaconlink + PREFIX + TARGET' );
my @exp = @$in;
my $id = $in->[0];
$exp[0] = "http://example.org/$id";
$exp[3] = "foo:$id";
is_deeply( [$b->expanded], \@exp, 'plainbeaconlink + PREFIX + TARGET' );
}
@p = ( # with 'to' field
# ["a","b","","u:ri"] => 'a|b|u:ri',
# ["a","","",""] => 'a|u:ri',
["a","b","","foo:x"], "a|b|foo:x",
["a","","","foo:x"], "a|foo:x",
["a","b","c","foo:x"], "a|b|c|foo:x",
#["x","a||","","http://example.com|"], "x|a|http://example.com",
#["x","","|d","foo:bar"], "x||d|foo:bar",
#["x","|","","http://example.com"], "x|http://example.com",
);
while (@p) {
my $in = shift @p;
my $out = shift @p;
my $line = plainbeaconlink( @{$in} );
is( $line, $out, 'plainbeaconlink');
@$in = map { s/\|//g; $_; } @$in;
$line = "#PREFIX: http://example.org/\n$line";
$b = beacon( \$line );
my $l = [$b->nextlink];
#pop @$l; # fullid
#pop @$l; # fulluri
is_deeply($l, $in);
}
# ignore additional params
is('x', plainbeaconlink('x','','','','foo','bar'));
# link expansion
$b = beacon( \"#TARGET: http://foo.org/{LABEL}\nf:rom|x" );
is_deeply( [$b->nextlink], ['f:rom','x','',''] );
is_deeply( [$b->expanded], ['f:rom','x','',,'http://foo.org/x'] );
$b = beacon( \"#TARGET: http://foo.org/{ID}\nx:y" );
is_deeply( [$b->nextlink], ['x:y','','',''] );
is_deeply( [$b->expanded], ['x:y','','',,'http://foo.org/x:y'] );
$b = beacon( \"#PREFIX: u:\n#TARGET: z:{ID}\n\$1" );
is_deeply( [$b->nextlink], ['$1','','','']);
is_deeply( [$b->expanded], ['u:$1','','','z:$1'] );
$b = beacon( \"a:b|c:d" );
is_deeply( [$b->nextlink], ['a:b','','','c:d']);
is_deeply( [$b->expanded], ['a:b','','','c:d'] );
$b = beacon( \"#TARGET: f:{ID}\na:b|c:d" );
is_deeply( [$b->nextlink], ['a:b','c:d','',''] );
is_deeply( [$b->expanded], ['a:b','c:d','','f:a:b'], 'TARGET changes parsing' );
$b = beacon( \"#TARGET: f:{LABEL}\na:b|c:d" );
is_deeply( [$b->nextlink], ['a:b','c:d','','']);
is_deeply( [$b->expanded],['a:b','c:d','','f:c%3Ad'], 'TARGET changes parsing' );
# croaking link handler
$b = beacon( \"#TARGET: f:{LABEL}\na:b|c:d", links => sub { die 'bad' } );
ok(! $b->parse );
ok( $b->lasterror =~ /^link handler died: bad/, 'dead link handler' );
# pre meta fields
$b = beacon( 't/beacon1.txt', 'pre' => { 'BAR' => 'doz', 'prefix' => 'y:' } );
is( $b->meta('bar'), 'doz', 'pre meta fields' );
is( $b->meta('prefix'), 'x:' );
# is( $b->line, 0 ); # 6
$b->parse( \"#PREFIX: z:" );
is( $b->meta('bar'), 'doz' );
is( $b->meta('prefix'), 'z:' );
$b->parse( \"#PREFIX: z:", pre => undef );
is( $b->meta('bar'), undef );
done_testing;
t/beacon1.txt view on Meta::CPAN
#FORMAT: BEACON
#FOO= bar doz
#TARGET: http://example.com/{ID}
#PREFIX: x:
#EXAMPLES:
0|1
1 | 099
2|0
|this is a comment
|this is also a comment
foo
bar||doz||http://another.example.com/
b|7a
c| 7|
t/beacon2.txt view on Meta::CPAN
#FORMAT: BEACON
#PREFIX: baz:
#DESCRIPTION: This is a test
a|http://example.com/foo
a|b|http://example.com/bar
#!perl -Tw
use strict;
use warnings;
use Test::More qw(no_plan);
use_ok('Data::Beacon');
my $b = beacon();
isa_ok($b,'Data::Beacon');
is( $b->errors, 0 );
eval { $b = beacon( errors => 'xxx' ); };
ok( $@, 'invalid handler' );
my ($warn, $die, $sub);
$SIG{__WARN__} = sub { $warn = $_[0]; };
$SIG{__DIE__} = sub { $die = $_[0]; };
foreach my $noerrors (('', undef, 0)) {
$b = beacon( errors => $noerrors );
$b->appendlink('|');
is( $b->errors, 1, 'no errors' );
is( $warn, undef );
is( $die, undef );
}
$b = beacon( errors => 'WaRn' );
$b->appendlink('|');
is( $b->errors, 1, 'warn' );
ok( $warn =~ /link fields must not contain '\|' at .*errors.t/ );
eval {
$b = beacon( errors => 'die' );
$b->appendlink('|');
};
ok( $@ =~ /link fields must not contain '\|' at .*errors.t/, 'die' );
# TODO: test code as handler
t/release-pod-syntax.t view on Meta::CPAN
#!perl
BEGIN {
unless ($ENV{RELEASE_TESTING}) {
require Test::More;
Test::More::plan(skip_all => 'these tests are for release candidate testing');
}
}
# This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests.
use Test::More;
use Test::Pod 1.41;
all_pod_files_ok();
( run in 0.537 second using v1.01-cache-2.11-cpan-a1d94b6210f )