NAME
coerce-with-sah - Coerce data
VERSION
This document describes version 0.42 of coerce-with-sah (from Perl distribution App-SahUtils), released on 2017-03-09.
SYNOPSIS
Usage:
% coerce-with-sah [options] <type>
Examples:
% coerce-with-sah date --coerce-to DateTime --data-as-perl '"2016-05-22"'
bless({
formatter => undef,
local_c => {
day => 22,
day_of_quarter => 52,
day_of_week => 7,
day_of_year => 143,
hour => 0,
minute => 0,
month => 5,
quarter => 2,
second => 0,
year => 2016,
},
local_rd_days => 736106,
local_rd_secs => 0,
locale => bless({
am_pm_abbreviated => ["AM", "PM"],
available_formats => {
d => "d",
E => "ccc",
Ed => "d E",
Ehm => "E h:mm a",
EHm => "E HH:mm",
Ehms => "E h:mm:ss a",
EHms => "E HH:mm:ss",
Gy => "y G",
GyMMM => "MMM y G",
GyMMMd => "MMM d, y G",
GyMMMEd => "E, MMM d, y G",
H => "HH",
h => "h a",
hm => "h:mm a",
Hm => "HH:mm",
hms => "h:mm:ss a",
Hms => "HH:mm:ss",
Hmsv => "HH:mm:ss v",
hmsv => "h:mm:ss a v",
Hmv => "HH:mm v",
hmv => "h:mm a v",
M => "L",
Md => "M/d",
MEd => "E, M/d",
MMM => "LLL",
MMMd => "MMM d",
MMMEd => "E, MMM d",
MMMMd => "MMMM d",
ms => "mm:ss",
y => "y",
yM => "M/y",
yMd => "M/d/y",
yMEd => "E, M/d/y",
yMMM => "MMM y",
yMMMd => "MMM d, y",
yMMMEd => "E, MMM d, y",
yMMMM => "MMMM y",
yQQQ => "QQQ y",
yQQQQ => "QQQQ y",
},
code => "en-US",
date_format_full => "EEEE, MMMM d, y",
date_format_long => "MMMM d, y",
date_format_medium => "MMM d, y",
date_format_short => "M/d/yy",
datetime_format_full => "{1} 'at' {0}",
datetime_format_long => "{1} 'at' {0}",
datetime_format_medium => "{1}, {0}",
datetime_format_short => "{1}, {0}",
day_format_abbreviated => ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
day_format_narrow => ["M", "T", "W", "T", "F", "S", "S"],
day_format_wide => [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
],
day_stand_alone_abbreviated => ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
day_stand_alone_narrow => ["M", "T", "W", "T", "F", "S", "S"],
day_stand_alone_wide => [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
],
default_date_format_length => "medium",
default_time_format_length => "medium",
era_abbreviated => ["BC", "AD"],
era_narrow => ["B", "A"],
era_wide => ["Before Christ", "Anno Domini"],
first_day_of_week => 7,
glibc_date_1_format => "%a %b %e %H:%M:%S %Z %Y",
glibc_date_format => "%m/%d/%Y",
glibc_datetime_format => "%a %d %b %Y %r %Z",
glibc_time_12_format => "%I:%M:%S %p",
glibc_time_format => "%r",
language => "English",
month_format_abbreviated => [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
],
month_format_narrow => ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
month_format_wide => [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
],
month_stand_alone_abbreviated => [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
],
month_stand_alone_narrow => ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
month_stand_alone_wide => [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
],
name => "English United States",
native_language => "English",
native_name => "English United States",
native_script => undef,
native_territory => "United States",
native_variant => undef,
quarter_format_abbreviated => ["Q1" .. "Q4"],
quarter_format_narrow => [1 .. 4],
quarter_format_wide => ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"],
quarter_stand_alone_abbreviated => ["Q1" .. "Q4"],
quarter_stand_alone_narrow => [1 .. 4],
quarter_stand_alone_wide => ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"],
script => undef,
territory => "United States",
time_format_full => "h:mm:ss a zzzz",
time_format_long => "h:mm:ss a z",
time_format_medium => "h:mm:ss a",
time_format_short => "h:mm a",
variant => undef,
version => 29,
}, "DateTime::Locale::FromData"),
offset_modifier => 0,
rd_nanosecs => 0,
tz => bless({
is_olson => 1,
max_year => 2026,
name => "Asia/Jakarta",
spans => [
[-Inf, 58904383968, -Inf, 58904409600, 25632, 0, "LMT"],
[
58904383968,
60683964000,
58904409600,
60683989632,
25632,
0,
"BMT",
],
[
60683964000,
60962776800,
60683990400,
60962803200,
26400,
0,
"JAVT",
],
[
60962776800,
61259041800,
60962803800,
61259068800,
27000,
0,
"WIB",
],
[
61259041800,
61369628400,
61259074200,
61369660800,
32400,
0,
"JST",
],
[
61369628400,
61451800200,
61369655400,
61451827200,
27000,
0,
"WIB",
],
[
61451800200,
61514870400,
61451829000,
61514899200,
28800,
0,
"WIB",
],
[
61514870400,
61946267400,
61514897400,
61946294400,
27000,
0,
"WIB",
],
[61946267400, Inf, 61946292600, Inf, 25200, 0, "WIB"],
],
}, "DateTime::TimeZone::Asia::Jakarta"),
utc_rd_days => 736105,
utc_rd_secs => 61200,
utc_year => 2017,
}, "DateTime")
% coerce-with-sah date --coerce-to 'float(epoch)' --multiple-data-as-perl '["2016-05-15", "1463328281"]'
[1463245200, 1463328281]
Show source code:
% coerce-with-sah duration --coerce-to 'float(secs)' -c
require Scalar::Util;
require Time::Duration::Parse::AsHash;
sub {
my $data = shift;
return undef unless defined($data);
(!ref($data) && $data =~ /\A[0-9]+(?:.[0-9]+)\z/) ? ($data) : ((!ref($data) && $data =~ /\AP(?:([0-9]+(?:\.[0-9]+)?)Y)? (?:([0-9]+(?:\.[0-9]+)?)M)? (?:([0-9]+(?:\.[0-9]+)?)W)? (?:([0-9]+(?:\.[0-9]+)?)D)? (?: T (?:([0-9]+(?:\.[0-9]+)?)H)? (?:([0-9]+(?:\.[0-9]+)?)M)? (?:([0-9]+(?:\.[0-9]+)?)S)? )?\z/x) ? ((($1||0)*365.25*86400 + ($2||0)*30.4375*86400 + ($3||0)*7*86400 + ($4||0)*86400 + ($5||0)*3600 + ($6||0)*60 + ($7||0))) : ((Scalar::Util::blessed($data) && $data->isa('DateTime::Duration')) ? (($data->years * 365.25*86400 + $data->months * 30.4375*86400 + $data->weeks * 7*86400 + $data->days * 86400 + $data->hours * 3600 + $data->minutes * 60 + $data->seconds + $data->nanoseconds * 1e-9)) : ((!ref($data) && $data =~ /\d.*[a-z]/) ? (do { my $p = Time::Duration::Parse::AsHash::parse_duration($data); ($p->{years}||0) * 365.25*86400 + ($p->{months}||0) * 30.4375*86400 + ($p->{weeks}||0) * 7*86400 + ($p->{days}||0) * 86400 + ($p->{hours}||0) * 3600 + ($p->{minutes}||0) * 60 + ($p->{seconds}||0) }) : $data)));
}
Show source code, with line number:
% coerce-with-sah duration --coerce-to 'DateTime::Duration' -c -l
1|require DateTime::Duration;
2|require Scalar::Util;
3|require Time::Duration::Parse::AsHash;
4|sub {
5| my $data = shift;
6| return undef unless defined($data);
7| (!ref($data) && $data =~ /\AP(?:([0-9]+(?:\.[0-9]+)?)Y)? (?:([0-9]+(?:\.[0-9]+)?)M)? (?:([0-9]+(?:\.[0-9]+)?)W)? (?:([0-9]+(?:\.[0-9]+)?)D)? (?: T (?:([0-9]+(?:\.[0-9]+)?)H)? (?:([0-9]+(?:\.[0-9]+)?)M)? (?:([0-9]+(?:\.[0-9]+)?)S)? )?\z/x) ? (DateTime::Duration->new( (years=>$1) x !!defined($1), (months=>$2) x !!defined($2), (weeks=>$3) x !!defined($3), (days=>$4) x !!defined($4), (hours=>$5) x !!defined($5), (minutes=>$6) x !!defined($6), (seconds=>$7) x !!defined($7))) : ((Scalar::Util::blessed($data) && $data->isa('DateTime::Duration')) ? ($data) : ((!ref($data) && $data =~ /\A[0-9]+(?:.[0-9]+)\z/) ? (DateTime::Duration->new(seconds => $data)) : ((!ref($data) && $data =~ /\d.*[a-z]/) ? (do { my $p = Time::Duration::Parse::AsHash::parse_duration($data); DateTime::Duration->new( (years=>$p->{years}) x !!defined($p->{years}), (months=>$p->{months}) x !!defined($p->{months}), (weeks=>$p->{weeks}) x !!defined($p->{weeks}), (days=>$p->{days}) x !!defined($p->{days}), (hours=>$p->{hours}) x !!defined($p->{hours}), (minutes=>$p->{minutes}) x !!defined($p->{minutes}), (seconds=>$p->{seconds}) x !!defined($p->{seconds})) }) : $data)));
8|}
Show source code (JavaScript):
% coerce-with-sah date -C js -c
function (data) {
if (data === undefined || data === null) return null;
return ((typeof(data)=='string') ? ((function (_m) { _m = new Date(data); if (isNaN(_m)) throw new Error('Invalid date'); return _m })()) : ((typeof(data)=='number' && data >= 100000000 && data <= 2147483648) ? ((new Date(data * 1000))) : (((data instanceof Date)) ? (isNaN(data) ? (function(){throw new Error('Invalid date')})() : data) : data)));
}
OPTIONS
*
marks required options.
Action selection options
- --show-code, -c
-
Don't coerce data, show generated coercer code only.
- --show-rules
-
Don't coerce data, show coerce rules that will be used.
Coercer specification options
- --coerce-rule=s@
-
Can be specified multiple times.
- --coerce-rules-json=s
-
See
--coerce-rule
. - --coerce-to=s
- --compiler=s, -C
-
Select compiler.
Default value:
"perl"
Valid values:
["perl","js"]
- --return-type=s, -r
-
Default value:
"val"
Valid values:
["val","str+val"]
- --type=sah::type_name*
Configuration options
- --config-path=filename
-
Set path to configuration file.
Can be specified multiple times.
- --config-profile=s
-
Set configuration profile to use.
- --no-config
-
Do not use any configuration file.
Data specification options
- --data-as-json=s
-
Data as JSON.
- --data-as-perl=s
-
Data as Perl code.
- --multiple-data-as-json=s
-
Multiple data as JSON code, JSON data must be an array.
- --multiple-data-as-perl=s
-
Multiple data as Perl code, perl code should return arrayref.
Environment options
Output options
- --data-with-result, -d
-
Show data alongside with coerced result.
The default is to show the coerced result only.
- --format=s
-
Choose output format, e.g. json, text.
Default value:
undef
- --json
-
Set output format to json.
- --linenum, -l
-
When showing source code, add line numbers.
- --no-naked-res
-
When outputing as JSON, add result envelope.
By default, when outputing as JSON, the full enveloped result is returned, e.g.:
[200,"OK",[1,2,3],{"func.extra"=>4}]
The reason is so you can get the status (1st element), status message (2nd element) as well as result metadata/extra result (4th element) instead of just the result (3rd element). However, sometimes you want just the result, e.g. when you want to pipe the result for more post-processing. In this case you can use `--naked-res` so you just get:
[1,2,3]
Other options
COMPLETION
This script has shell tab completion capability with support for several shells.
bash
To activate bash completion for this script, put:
complete -C coerce-with-sah coerce-with-sah
in your bash startup (e.g. ~/.bashrc). Your next shell session will then recognize tab completion for the command. Or, you can also directly execute the line above in your shell to activate immediately.
It is recommended, however, that you install shcompgen which allows you to activate completion scripts for several kinds of scripts on multiple shells. Some CPAN distributions (those that are built with Dist::Zilla::Plugin::GenShellCompletion) will even automatically enable shell completion for their included scripts (using shcompgen) at installation time, so you can immediately have tab completion.
tcsh
To activate tcsh completion for this script, put:
complete coerce-with-sah 'p/*/`coerce-with-sah`/'
in your tcsh startup (e.g. ~/.tcshrc). Your next shell session will then recognize tab completion for the command. Or, you can also directly execute the line above in your shell to activate immediately.
It is also recommended to install shcompgen (see above).
other shells
For fish and zsh, install shcompgen as described above.
FAQ
When there is an error (e.g. in generating coercer code, in coercing) the program returns undef/null, how do I see the error message?
Pass `--no-naked-res` to see the error code and error message. The default is naked for simpler output.
CONFIGURATION FILE
This script can read configuration files. Configuration files are in the format of IOD, which is basically INI with some extra features.
By default, these names are searched for configuration filenames (can be changed using --config-path
): ~/.config/coerce-with-sah.conf, ~/coerce-with-sah.conf, or /etc/coerce-with-sah.conf.
All found files will be read and merged.
To disable searching for configuration files, pass --no-config
.
You can put multiple profiles in a single file by using section names like [profile=SOMENAME]
or [SOMESECTION profile=SOMENAME]
. Those sections will only be read if you specify the matching --config-profile SOMENAME
.
You can also put configuration for multiple programs inside a single file, and use filter program=NAME
in section names, e.g. [program=NAME ...]
or [SOMESECTION program=NAME]
. The section will then only be used when the reading program matches.
Finally, you can filter a section by environment variable using the filter env=CONDITION
in section names. For example if you only want a section to be read if a certain environment variable is true: [env=SOMEVAR ...]
or [SOMESECTION env=SOMEVAR ...]
. If you only want a section to be read when the value of an environment variable has value equals something: [env=HOSTNAME=blink ...]
or [SOMESECTION env=HOSTNAME=blink ...]
. If you only want a section to be read when the value of an environment variable does not equal something: [env=HOSTNAME!=blink ...]
or [SOMESECTION env=HOSTNAME!=blink ...]
. If you only want a section to be read when an environment variable contains something: [env=HOSTNAME*=server ...]
or [SOMESECTION env=HOSTNAME*=server ...]
. Note that currently due to simplistic parsing, there must not be any whitespace in the value being compared because it marks the beginning of a new section filter or section name.
List of available configuration parameters:
coerce_rules (see --coerce-rule)
coerce_to (see --coerce-to)
compiler (see --compiler)
data_as_json (see --data-as-json)
data_as_perl (see --data-as-perl)
data_with_result (see --data-with-result)
format (see --format)
linenum (see --linenum)
multiple_data_as_json (see --multiple-data-as-json)
multiple_data_as_perl (see --multiple-data-as-perl)
naked_res (see --naked-res)
return_type (see --return-type)
show_code (see --show-code)
show_rules (see --show-rules)
type (see --type)
ENVIRONMENT
COERCE_WITH_SAH_OPT => str
Specify additional command-line options.
FILES
~/.config/coerce-with-sah.conf
~/coerce-with-sah.conf
/etc/coerce-with-sah.conf
HOMEPAGE
Please visit the project's homepage at https://metacpan.org/release/App-SahUtils.
SOURCE
Source repository is at https://github.com/perlancar/perl-App-SahUtils.
BUGS
Please report any bugs or feature requests on the bugtracker website https://rt.cpan.org/Public/Dist/Display.html?Name=App-SahUtils
When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature.
AUTHOR
perlancar <perlancar@cpan.org>
COPYRIGHT AND LICENSE
This software is copyright (c) 2017, 2016, 2015 by perlancar@cpan.org.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.