SHARYANTO-Utils-0.53/0000755000175000017500000000000012176106301011534 5ustar s1s1SHARYANTO-Utils-0.53/README0000644000175000017500000000123312176106301012413 0ustar s1s1NAME SHARYANTO::Utils - SHARYANTO's temporary namespace for various routines VERSION version 0.53 FAQ What is this? This distribution is a heterogenous collection of modules that will eventually have their own proper distributions. See SHARYANTO about this temporary namespace. AUTHOR Steven Haryanto COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. DESCRIPTION FUNCTIONS None are exported by default, but they are exportable. SHARYANTO-Utils-0.53/Build.PL0000644000175000017500000000300212176106301013023 0ustar s1s1 use strict; use warnings; use Module::Build 0.3601; my %module_build_args = ( "build_requires" => { "Module::Build" => "0.3601" }, "configure_requires" => { "Module::Build" => "0.3601" }, "dist_abstract" => "SHARYANTO's temporary namespace for various routines", "dist_author" => [ "Steven Haryanto " ], "dist_name" => "SHARYANTO-Utils", "dist_version" => "0.53", "license" => "perl", "module_name" => "SHARYANTO::Utils", "recommends" => {}, "recursive_test_files" => 1, "requires" => { "Data::Clone" => 0, "Data::Structure::Util" => 0, "File::Slurp" => 0, "File::Which" => 0, "HTML::Parser" => 0, "Locale::Maketext::Lexicon" => 0, "Log::Any" => 0, "Moo::Role" => 0, "Parse::Netstat" => 0, "Perinci::Object" => "0.07", "Rinci" => "v1.1.0", "Template::Tiny" => 0, "URI::URL" => 0, "YAML::Syck" => 0, "experimental" => 0, "perl" => "5.010001" }, "script_files" => [], "test_requires" => { "File::chdir" => 0, "Test::Exception" => 0, "Test::More" => "0.98" } ); unless ( eval { Module::Build->VERSION(0.4004) } ) { my $tr = delete $module_build_args{test_requires}; my $br = $module_build_args{build_requires}; for my $mod ( keys %$tr ) { if ( exists $br->{$mod} ) { $br->{$mod} = $tr->{$mod} if $tr->{$mod} > $br->{$mod}; } else { $br->{$mod} = $tr->{$mod}; } } } my $build = Module::Build->new(%module_build_args); $build->create_build_script; SHARYANTO-Utils-0.53/lib/0000755000175000017500000000000012176106301012302 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/0000755000175000017500000000000012176106301013652 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/HTTP/0000755000175000017500000000000012176106301014431 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/HTTP/DetectUA/0000755000175000017500000000000012176106301016067 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/HTTP/DetectUA/Simple.pm0000644000175000017500000001155212176106301017662 0ustar s1s1package SHARYANTO::HTTP::DetectUA::Simple; use 5.010; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(detect_http_ua_simple); our $VERSION = '0.53'; # VERSION our %SPEC; $SPEC{":package"} = { v => 1.1, summary => 'A very simple and generic browser detection library', description => <<'_', I needed a simple and fast routine which can detect whether HTTP client is a GUI browser (like Chrome or Firefox), a text browser (like Lynx or Links), or neither (like curl, or L). Hence, this module. _ }; $SPEC{detect_http_ua_simple} = { v => 1.1, summary => 'Detect whether HTTP client is a GUI/TUI browser', description => <<'_', This function is a simple and fast routine to detect whether HTTP client is a GUI browser (like Chrome or Firefox), a text-based browser (like Lynx or Links), or neither (like curl or LWP). Extra information can be provided in the future. Currently these heuristic rules are used: * check popular browser markers in User-Agent header (e.g. 'Chrome', 'Opera'); * check Accept header for 'image/'; It is several times faster than the other equivalent Perl modules, this is because it does significantly less. _ args => { env => { pos => 0, summary => 'CGI-compatible environment, e.g. \%ENV or PSGI\'s $env', }, }, result => { description => <<'_', * 'is_gui_browser' key will be set to true if HTTP client is a GUI browser. * 'is_text_browser' key will be set to true if HTTP client is a text/TUI browser. * 'is_browser' key will be set to true if either 'is_gui_browser' or 'is_text_browser' is set to true. _ schema => 'hash*', }, links => [ {url => "pm://HTML::ParseBrowser", tags => ['see']}, {url => "pm://HTTP::BrowserDetect", tags => ['see']}, {url => "pm://HTTP::DetectUserAgent", tags => ['see']}, {url => "pm://Parse::HTTP::UserAgent", tags => ['see']}, {url => "pm://HTTP::headers::UserAgent", tags => ['see']}, ], args_as => "array", result_naked => 0, }; sub detect_http_ua_simple { my ($env) = @_; my $res = {}; my $det; my $ua = $env->{HTTP_USER_AGENT}; if ($ua) { # check for popular browser GUI UA if ($ua =~ m!\b(?:Mozilla/|MSIE |Chrome/|Opera/| Profile/MIDP- )!x) { $res->{is_gui_browser} = 1; $det++; } # check for popular webbot UA if ($ua =~ m!\b(?:Links |ELinks/|Lynx/|w3m/)!) { $res->{is_text_browser} = 1; $det++; } } if (!$det) { # check for accept mime type my $ac = $env->{HTTP_ACCEPT}; if ($ac) { if ($ac =~ m!\b(?:image/)!) { $res->{is_gui_browser} = 1; $det++; } } } $res->{is_browser} = 1 if $res->{is_gui_browser} || $res->{is_text_browser}; $res; } 1; # ABSTRACT: A very simple and generic browser detection library __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::HTTP::DetectUA::Simple - A very simple and generic browser detection library =head1 VERSION version 0.53 =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION I needed a simple and fast routine which can detect whether HTTP client is a GUI browser (like Chrome or Firefox), a text browser (like Lynx or Links), or neither (like curl, or L). Hence, this module. =head1 FUNCTIONS None are exported by default, but they are exportable. =head2 detect_http_ua_simple(@args) -> [status, msg, result, meta] This function is a simple and fast routine to detect whether HTTP client is a GUI browser (like Chrome or Firefox), a text-based browser (like Lynx or Links), or neither (like curl or LWP). Extra information can be provided in the future. Currently these heuristic rules are used: =over =item * check popular browser markers in User-Agent header (e.g. 'Chrome', 'Opera'); =item * check Accept header for 'image/'; =back It is several times faster than the other equivalent Perl modules, this is because it does significantly less. Arguments ('*' denotes required arguments): =over 4 =item * B => I CGI-compatible environment, e.g. \%ENV or PSGI's $env. =back Return value: Returns an enveloped result (an array). First element (status) is an integer containing HTTP status code (200 means OK, 4xx caller error, 5xx function error). Second element (msg) is a string containing error message, or 'OK' if status is 200. Third element (result) is optional, the actual result. Fourth element (meta) is called result metadata and is optional, a hash that contains extra information. =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Role/0000755000175000017500000000000012176106301014553 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Role/Doc/0000755000175000017500000000000012176106301015260 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Role/Doc/Section.pm0000644000175000017500000001126112176106301017223 0ustar s1s1package SHARYANTO::Role::Doc::Section; use 5.010; use Log::Any '$log'; use Moo::Role; our $VERSION = '0.53'; # VERSION has doc_sections => (is=>'rw'); has doc_lines => (is => 'rw'); # store final result, array has doc_indent_level => (is => 'rw'); has doc_indent_str => (is => 'rw', default => sub{" "}); # indent characters sub add_doc_section_before { my ($self, $name, $before) = @_; my $ss = $self->doc_sections; return unless $ss; my $i = 0; my $added; while ($i < @$ss && defined($before)) { if ($ss->[$i] eq $before) { my $pos = $i; splice @$ss, $pos, 0, $name; $added++; last; } $i++; } unshift @$ss, $name unless $added; } sub add_doc_section_after { my ($self, $name, $after) = @_; my $ss = $self->doc_sections; return unless $ss; my $i = 0; my $added; while ($i < @$ss && defined($after)) { if ($ss->[$i] eq $after) { my $pos = $i+1; splice @$ss, $pos, 0, $name; $added++; last; } $i++; } push @$ss, $name unless $added; } sub delete_doc_section { my ($self, $name) = @_; my $ss = $self->doc_sections; return unless $ss; my $i = 0; while ($i < @$ss) { if ($ss->[$i] eq $name) { splice @$ss, $i, 1; } else { $i++; } } } sub inc_doc_indent { my ($self, $n) = @_; $n //= 1; $self->{doc_indent_level} += $n; } sub dec_doc_indent { my ($self, $n) = @_; $n //= 1; $self->{doc_indent_level} -= $n; die "BUG: Negative doc indent level" unless $self->{doc_indent_level} >=0; } sub gen_doc { my ($self, %opts) = @_; $log->tracef("-> gen_doc(opts=%s)", \%opts); $self->doc_lines([]); $self->doc_indent_level(0); $self->before_gen_doc(%opts) if $self->can("before_gen_doc"); for my $s (@{ $self->doc_sections // [] }) { my $meth = "gen_doc_section_$s"; $log->tracef("=> $meth()"); $self->$meth(%opts); } $self->after_gen_doc(%opts) if $self->can("after_gen_doc"); $log->tracef("<- gen_doc()"); join("", @{ $self->doc_lines }); } 1; #ABSTRACT: Role for class that generates documentation with sections __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Role::Doc::Section - Role for class that generates documentation with sections =head1 VERSION version 0.53 =head1 DESCRIPTION SHARYANTO::Role::Doc::Section is a role for classes that produce documentation with sections. This role provides a workflow for parsing and generating sections, regulating indentation, and a C method. To generate documentation, first you provide a list of section names in C. Then you run C, which will call C method for each section consecutively, which is supposed to append lines of text to C. Finally all the added lines is concatenated together and returned by C. This module uses L for logging. This module uses L for object system. =head1 ATTRIBUTES =head2 doc_sections => ARRAY Should be set to the names of available sections. =head2 doc_lines => ARRAY =head2 doc_indent_level => INT =head2 doc_indent_str => STR (default ' ' (two spaces)) Character(s) used for indent. =head1 METHODS =head2 add_doc_section_before($name, $anchor) =head2 add_doc_section_after($name, $anchor) =head2 delete_doc_section($name) =head2 inc_doc_indent([N]) =head2 dec_doc_indent([N]) =head2 gen_doc() => STR Generate documentation. The method will first initialize C to an empty array C<[]> and C to 0. It will then call C if the hook method exists, to allow class to do stuffs prior to document generation. L uses this, for example, to retrieve metadata from Riap server. Then, as described in L, for each section listed in C it will call C. After that, it will call C if the hook method exists, to allow class to do stuffs after document generation. Lastly, it returns concatenated C. =head1 SEE ALSO This role is used, among others, by: C modules. L which provides C to add text with optional text wrapping. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 FUNCTIONS None are exported by default, but they are exportable. =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Role/Doc/Section/0000755000175000017500000000000012176106301016664 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Role/Doc/Section/AddTextLines.pm0000644000175000017500000001062312176106301021554 0ustar s1s1package SHARYANTO::Role::Doc::Section::AddTextLines; use 5.010; use Log::Any '$log'; use Moo::Role; our $VERSION = '0.53'; # VERSION requires 'doc_lines'; requires 'doc_indent_level'; requires 'doc_indent_str'; has doc_wrap => (is => 'rw', default => sub {1}); sub add_doc_lines { my $self = shift; my $opts; if (ref($_[0]) eq 'HASH') { $opts = shift } $opts //= {}; my @lines = map { $_ . (/\n\z/s ? "" : "\n") } map {/\n/ ? split /\n/ : $_} @_; # debug #my @c = caller(2); #$c[1] =~ s!.+/!!; #@lines = map {"[from $c[1]:$c[2]]$_"} @ lines; my $indent = $self->doc_indent_str x $self->doc_indent_level; my $wrap = $opts->{wrap} // $self->doc_wrap; if ($wrap) { require Text::Wrap; # split into paragraphs, merge each paragraph text into a single line # first my @para; my $i = 0; my ($start, $type); $type = ''; #$log->warnf("lines=%s", \@lines); for (@lines) { if (/^\s*$/) { if (defined($start) && $type ne 'blank') { push @para, [$type, [@lines[$start..$i-1]]]; undef $start; } $start //= $i; $type = 'blank'; } elsif (/^\s{4,}\S+/ && (!$i || $type eq 'verbatim' || (@para && $para[-1][0] eq 'blank'))) { if (defined($start) && $type ne 'verbatim') { push @para, [$type, [@lines[$start..$i-1]]]; undef $start; } $start //= $i; $type = 'verbatim'; } else { if (defined($start) && $type ne 'normal') { push @para, [$type, [@lines[$start..$i-1]]]; undef $start; } $start //= $i; $type = 'normal'; } #$log->warnf("i=%d, lines=%s, start=%s, type=%s", # $i, $_, $start, $type); $i++; } if (@para && $para[-1][0] eq $type) { push @{ $para[-1][1] }, [$type, [@lines[$start..$i-1]]]; } else { push @para, [$type, [@lines[$start..$i-1]]]; } #$log->warnf("para=%s", \@para); for my $para (@para) { if ($para->[0] eq 'blank') { push @{$self->doc_lines}, @{$para->[1]}; } else { if ($para->[0] eq 'normal') { for (@{$para->[1]}) { s/\n/ /g; } $para->[1] = [join("", @{$para->[1]}) . "\n"]; } #$log->warnf("para=%s", $para); local $Text::Wrap::columns = $ENV{COLUMNS} // 80; push @{$self->doc_lines}, Text::Wrap::wrap($indent, $indent, @{$para->[1]}); } } } else { push @{$self->doc_lines}, map {"$indent$_"} @lines; } } 1; # ABSTRACT: Provide add_doc_lines() to add text with optional text wrapping __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Role::Doc::Section::AddTextLines - Provide add_doc_lines() to add text with optional text wrapping =head1 VERSION version 0.53 =head1 DESCRIPTION This role provides C which can add optionally wrapped text to C. The default column width for wrapping is from C environment variable, or 80. =head1 ATTRIBUTES =head2 doc_wrap => BOOL (default: 1) Whether to do text wrapping. =head1 REQUIRES These methods are provided by, e.g. L. =head2 $o->doc_lines() =head2 $o->doc_indent_level() =head2 $o->doc_lines_str() =head1 METHODS =head2 $o->add_doc_lines([\%opts, ]@lines) Add lines of text, optionally wrapping each line if wrapping is enabled. Available options: =over 4 =item * wrap => BOOL Whether to enable wrapping. Default is from the C attribute. =back =head1 ENVIRONMENT =head2 COLUMNS => INT Used to set column width. =head1 SEE ALSO L =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 FUNCTIONS None are exported by default, but they are exportable. =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Role/I18NMany.pm0000644000175000017500000000430712176106301016421 0ustar s1s1package SHARYANTO::Role::I18NMany; use 5.010; use Log::Any '$log'; use Moo::Role; our $VERSION = '0.53'; # VERSION has langs => ( is => 'rw', default => sub { ['en_US'] }, ); has loc_class => ( is => 'rw', default => sub { my $self = shift; ref($self) . '::I18N'; }, ); sub lh { my ($self, $lang) = @_; die "Please specify lang" unless $lang; state $obj; if (!$obj) { require Module::Load; Module::Load::load($self->loc_class); $obj = $self->loc_class->new; } state $lhs = {}; return $lhs->{$lang} if $lhs->{$lang}; my $lh = $obj->get_handle($lang) or die "Can't get language handle for lang=$lang"; #$log->tracef("lhs=%s, lh=%s", $lhs, $lh); my $c = ref($lh); my %class; for (my ($l, $h) = each %$lhs) { my $c2 = ref($h); die "Lang=$lang falls back to lang=$l (class=$c2)" if $class{$c}; $class{$c2} = $l; } $lhs->{$lang} = $lh; $lh; } sub locl { my ($self, $lang, @args) = @_; $self->lh($lang)->maketext(@args); } 1; # ABSTRACT: Role for internationalized class __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Role::I18NMany - Role for internationalized class =head1 VERSION version 0.53 =head1 DESCRIPTION This role is like L but for class that wants to localize text for more than one languages. Its locl() accepts desired language as its first argument. =head1 ATTRIBUTES =head2 langs => ARRAY Defaults to a single element array with value of LANG or LANGUAGE environment variable, or C. =head2 loc_class => STR Project class name. Defaults to $class::I18N. =head1 METHODS =head2 $doc->lh($lang) => OBJ Get language handle for a certain language. $lang is required. =head2 $doc->locl($lang, @args) => STR Shortcut for C<$doc->lh($lang)->maketext(@args)>. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 FUNCTIONS None are exported by default, but they are exportable. =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Role/I18NRinci.pm0000644000175000017500000000200212176106301016547 0ustar s1s1package SHARYANTO::Role::I18NRinci; use 5.010; use Log::Any '$log'; use Moo::Role; use Perinci::Object; our $VERSION = '0.53'; # VERSION with 'SHARYANTO::Role::I18N'; requires 'lang'; sub langprop { my ($self, $meta, $prop) = @_; my $opts = { lang=>$self->lang, }; rimeta($meta)->langprop($prop, $opts); } 1; # ABSTRACT: Role for class that wants to work with language and Rinci metadata __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Role::I18NRinci - Role for class that wants to work with language and Rinci metadata =head1 VERSION version 0.53 =head1 METHODS =head2 $obj->langprop($meta, $prop) =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION =head1 FUNCTIONS None are exported by default, but they are exportable. =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Role/I18N.pm0000644000175000017500000000442112176106301015571 0ustar s1s1package SHARYANTO::Role::I18N; use 5.010; use Log::Any '$log'; use Moo::Role; our $VERSION = '0.53'; # VERSION has lang => ( is => 'rw', lazy => 1, default => sub { if ($ENV{LANG}) { my $l = $ENV{LANG}; $l =~ s/\W.*//; return $l; } if ($ENV{LANGUAGE}) { my $l = $ENV{LANGUAGE}; $l =~ s/\W.*//; return $l; } "en_US"; }, ); has loc_class => ( is => 'rw', default => sub { my $self = shift; ref($self) . '::I18N'; }, ); has lh => ( is => 'rw', lazy => 1, default => sub { require Module::Load; my $self = shift; Module::Load::load($self->loc_class); my $obj = $self->loc_class->new; my $lh = $obj->get_handle($self->lang) or die "Can't determine language"; $lh; }, ); sub loc { my ($self, @args) = @_; $self->lh->maketext(@args); } sub locopt { my ($self, @args) = @_; my $res = eval { $self->lh->maketext(@args); }; if ($@) { return $args[0]; } else { return $res; } } 1; # ABSTRACT: Role for internationalized class __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Role::I18N - Role for internationalized class =head1 VERSION version 0.53 =head1 DESCRIPTION This role is for class that wants to provide localized text, using L. It provides some convention and defaults. =head1 ATTRIBUTES =head2 lang Defaults to LANG or LANGUAGE environment variable, or C. =head2 loc_class Project class. Defaults to $class::I18N. =head2 lh The language handle, where you ask for localized text using C<< lh->maketext(...) >>. =head1 METHODS =head2 $doc->loc(@args) => STR Shortcut for C<< $doc->lh->maketext(@args) >>. =head2 $doc->locopt(@args) => STR Like loc(), but will trap missing translation. So instead of dying, it will return $args[0] instead. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 FUNCTIONS None are exported by default, but they are exportable. =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Template/0000755000175000017500000000000012176106301015425 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Template/Util.pm0000644000175000017500000000274312176106301016706 0ustar s1s1package SHARYANTO::Template::Util; use 5.010; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(process_tt_recursive); use File::Find; use File::Slurp; use Template::Tiny; our $VERSION = '0.53'; # VERSION # recursively find *.tt and process them. can optionally delete the *.tt files # after processing. sub process_tt_recursive { my ($dir, $vars, $opts) = @_; $opts //= {}; my $tt = Template::Tiny->new; find sub { return unless -f; return unless /\.tt$/; my $newname = $_; $newname =~ s/\.tt$//; my $input = read_file($_); my $output; #$log->debug("Processing template $File::Find::dir/$_ -> $newname ..."); $tt->process(\$input, $vars, \$output); write_file($newname, $output); #$log->debug("Removing $File::Find::dir/$_ ..."); if ($opts->{delete}) { unlink($_) } }, $dir; } 1; # ABSTRACT: Recursively process .tt files __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Template::Util - Recursively process .tt files =head1 VERSION version 0.53 =head1 FUNCTIONS =head2 process_tt_recursive($dir, $vars, $opts) None are exported by default, but they are exportable. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Number/0000755000175000017500000000000012176106301015102 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Number/Util.pm0000644000175000017500000000627712176106301016371 0ustar s1s1package SHARYANTO::Number::Util; use 5.010001; use locale; use strict; use utf8; use warnings; our $VERSION = '0.53'; # VERSION require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(format_metric); sub format_metric { my ($num, $opts) = @_; $opts //= {}; $opts->{base} //= 2; my $im = $opts->{i_mark} // 1; my $base0 = $opts->{base}; my $base = $base0 == 2 ? 1024 : 1000; my $rank; my $prefix; if ($num == 0) { $rank = 0; $prefix = ""; } else { $rank = int(log(abs($num))/log($base)); if ($rank == 0 && abs($num) >= 1) { $prefix = "" } elsif ($rank == 1) { $prefix = $im && $base0==10 ? "ki" : "k" } # kilo elsif ($rank == 2) { $prefix = $im && $base0==10 ? "Mi" : "M" } # mega elsif ($rank == 3) { $prefix = $im && $base0==10 ? "Gi" : "G" } # giga elsif ($rank == 4) { $prefix = $im && $base0==10 ? "Ti" : "T" } # tera elsif ($rank == 5) { $prefix = $im && $base0==10 ? "Pi" : "P" } # peta elsif ($rank >= 8) { $prefix = $im && $base0==10 ? "Yi" : "Y" } # yotta elsif ($rank == 7) { $prefix = $im && $base0==10 ? "Zi" : "Z" } # zetta elsif ($rank == 6) { $prefix = $im && $base0==10 ? "Ei" : "E" } # exa elsif ($rank == 0) { $prefix = "m" } # milli elsif ($rank == -1) { $prefix = "μ" } # micro elsif ($rank == -2) { $prefix = "n" } # nano elsif ($rank == -3) { $prefix = "p" } # pico elsif ($rank == -4) { $prefix = "f" } # femto elsif ($rank == -5) { $prefix = "a" } # atto elsif ($rank == -6) { $prefix = "z" } # zepto elsif ($rank <= -7) { $prefix = "y" } # yocto } my $prec = $opts->{precision} // 1; $num = $num / $base**($rank <= 0 && abs($num) < 1 ? $rank-1 : $rank); if ($opts->{return_array}) { return [$num, $prefix]; } else { my $snum = sprintf("%.${prec}f", $num); return $snum . $prefix; } } 1; # ABSTRACT: Number utilities __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Number::Util - Number utilities =head1 VERSION version 0.53 =head1 SYNOPSIS =head1 FUNCTIONS =head2 format_metric($num, \%opts) => STR Format C<$num> using metric prefix, e.g.: format_metric(14 , {base=>10}); # => "14" format_metric(12000 , {base=> 2, precision=>1}); # => "11.7K" format_metric(12000 , {base=>10, precision=>1}); # => "11.7Ki" format_metric(-0.0017, {base=>10}); # => "1.7m" Known options: =over =item * base => INT (either 2 or 10, default: 2) =item * precision => INT =item * i_mark => BOOL (default: 1) Give "i" suffix to prefixes when in base 10 for K, M, G, T, and so on. =back None are exported by default, but they are exportable. =head1 SEE ALSO Number formatting routines: L, L, L. https://en.wikipedia.org/wiki/Metric_prefix =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/YAML/0000755000175000017500000000000012176106301014414 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/YAML/Any.pm0000644000175000017500000000176112176106301015506 0ustar s1s1package SHARYANTO::YAML::Any_SyckOnly; package SHARYANTO::YAML::Any; # NOTE: temporary namespace, will eventually be refactored, tidied up, and sent # to a more proper namespace. use 5.010; use strict; use Exporter (); our @ISA = qw(Exporter); our @EXPORT = qw(Dump Load); our @EXPORT_OK = qw(DumpFile LoadFile); our $VERSION = '0.72'; use YAML::Syck; $YAML::Syck::ImplicitTyping = 1; 1; # ABSTRACT: Pick a YAML implementation and use it. __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::YAML::Any_SyckOnly - Pick a YAML implementation and use it. =head1 VERSION version 0.53 =for Pod::Coverage .* =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION =head1 FUNCTIONS None are exported by default, but they are exportable. =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/YAML/Any_YAMLAny.pm0000644000175000017500000001237512176106301017003 0ustar s1s1package SHARYANTO::YAML::Any_YAMLAny; package SHARYANTO::YAML::Any; # NOTE: temporary namespace, will eventually be refactored, tidied up, and sent # to a more proper namespace. use 5.005003; use strict; use Exporter (); $SHARYANTO::YAML::Any::VERSION = '0.72'; @SHARYANTO::YAML::Any::ISA = 'Exporter'; @SHARYANTO::YAML::Any::EXPORT = qw(Dump Load); @SHARYANTO::YAML::Any::EXPORT_OK = qw(DumpFile LoadFile); my @dump_options = qw( UseCode DumpCode SpecVersion Indent UseHeader UseVersion SortKeys AnchorPrefix UseBlock UseFold CompressSeries InlineSeries UseAliases Purity Stringify ); my @load_options = qw( UseCode LoadCode ); my @implementations = qw( YAML::Syck YAML::XS YAML::Old YAML YAML::Tiny ); my %implementation_setups = ( "YAML::Syck" => sub { $YAML::Syck::ImplicitTyping = 1; }, ); sub import { __PACKAGE__->implementation; goto &Exporter::import; } sub Dump { no strict 'refs'; my $implementation = __PACKAGE__->implementation; for my $option (@dump_options) { my $var = "$implementation\::$option"; my $value = $$var; local $$var; $$var = defined $value ? $value : ${"YAML::$option"}; } return &{"$implementation\::Dump"}(@_); } sub DumpFile { no strict 'refs'; my $implementation = __PACKAGE__->implementation; for my $option (@dump_options) { my $var = "$implementation\::$option"; my $value = $$var; local $$var; $$var = defined $value ? $value : ${"YAML::$option"}; } return &{"$implementation\::DumpFile"}(@_); } sub Load { no strict 'refs'; my $implementation = __PACKAGE__->implementation; for my $option (@load_options) { my $var = "$implementation\::$option"; my $value = $$var; local $$var; $$var = defined $value ? $value : ${"YAML::$option"}; } return &{"$implementation\::Load"}(@_); } sub LoadFile { no strict 'refs'; my $implementation = __PACKAGE__->implementation; for my $option (@load_options) { my $var = "$implementation\::$option"; my $value = $$var; local $$var; $$var = defined $value ? $value : ${"YAML::$option"}; } return &{"$implementation\::LoadFile"}(@_); } sub order { return @SHARYANTO::YAML::Any::_TEST_ORDER if defined @SHARYANTO::YAML::Any::_TEST_ORDER; return @implementations; } sub implementation { my @order = __PACKAGE__->order; for my $module (@order) { my $path = $module; $path =~ s/::/\//g; $path .= '.pm'; return $module if exists $INC{$path}; if (eval "require $module; 1") { ($implementation_setups{$module} // sub {})->(); return $module; } } croak("SHARYANTO::YAML::Any couldn't find any of these YAML implementations: @order"); } sub croak { require Carp; Carp::Croak(@_); } 1; __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::YAML::Any_YAMLAny =head1 VERSION version 0.53 =head1 SYNOPSIS use SHARYANTO::YAML::Any; $SHARYANTO::YAML::Indent = 3; my $yaml = Dump(@objects); =head1 DESCRIPTION SHARYANTO::YAML::Any is forked from YAML::Any. The difference is the order of implementation selection (YAML::Syck first) and the setting ($YAML::Syck::ImplicitTyping is turned on, as any sane YAML user would do). The rest is YAML::Any's documentation. There are several YAML implementations that support the Dump/Load API. This module selects the best one available and uses it. =head1 ORDER Currently, YAML::Any will choose the first one of these YAML implementations that is installed on your system: YAML::XS YAML::Syck YAML::Old YAML YAML::Tiny =head1 OPTIONS If you specify an option like: $YAML::Indent = 4; And YAML::Any is using YAML::XS, it will use the proper variable: $YAML::XS::Indent. =head1 SUBROUTINES Like all the YAML modules that YAML::Any uses, the following subroutines are exported by default: Dump Load and the following subroutines are exportable by request: DumpFile LoadFile =head1 METHODS YAML::Any provides the following class methods. =for Pod::Coverage .* =over =item YAML::Any->order; This method returns a list of the current possible implementations that YAML::Any will search for. =item YAML::Any->implementation; This method returns the implementation the YAML::Any will use. This result is obtained by finding the first member of YAML::Any->order that is either already loaded in C<%INC> or that can be loaded using C. If no implementation is found, an error will be thrown. =back =head1 ORIGINAL AUTHOR Ingy döt Net =head1 ORIGINAL COPYRIGHT Copyright (c) 2008. Ingy döt Net. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 FUNCTIONS None are exported by default, but they are exportable. =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/YAML/Any_SyckOnly.pm0000644000175000017500000000176112176106301017341 0ustar s1s1package SHARYANTO::YAML::Any_SyckOnly; package SHARYANTO::YAML::Any; # NOTE: temporary namespace, will eventually be refactored, tidied up, and sent # to a more proper namespace. use 5.010; use strict; use Exporter (); our @ISA = qw(Exporter); our @EXPORT = qw(Dump Load); our @EXPORT_OK = qw(DumpFile LoadFile); our $VERSION = '0.72'; use YAML::Syck; $YAML::Syck::ImplicitTyping = 1; 1; # ABSTRACT: Pick a YAML implementation and use it. __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::YAML::Any_SyckOnly - Pick a YAML implementation and use it. =head1 VERSION version 0.53 =for Pod::Coverage .* =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION =head1 FUNCTIONS None are exported by default, but they are exportable. =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/File/0000755000175000017500000000000012176106301014531 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/File/Flock.pm0000644000175000017500000001077212176106301016134 0ustar s1s1package SHARYANTO::File::Flock; use 5.010; use strict; use warnings; use Fcntl ':flock'; our $VERSION = '0.53'; # VERSION sub lock { my ($class, $path, $opts) = @_; $opts //= {}; my %h; defined($path) or die "Please specify path"; $h{path} = $path; $h{retries} = $opts->{retries} // 60; my $self = bless \%h, $class; $self->_lock; $self; } # return 1 if we lock, 0 if already locked. die on failure. sub _lock { my $self = shift; # already locked return 0 if $self->{_fh}; my $path = $self->{path}; my $existed = -f $path; my $exists; my $tries = 0; TRY: while (1) { $tries++; # 1 open $self->{_fh}, ">>", $path or die "Can't open lock file '$path': $!"; # 2 my @st1 = stat($self->{_fh}); # stat before lock # 3 if (flock($self->{_fh}, LOCK_EX | LOCK_NB)) { # if file is unlinked by another process between 1 & 2, @st1 will be # empty and we check here. redo TRY unless @st1; # 4 my @st2 = stat($path); # stat after lock # if file is unlinked between 3 & 4, @st2 will be empty and we check # here. redo TRY unless @st2; # if file is recreated between 2 & 4, @st1 and @st2 will differ in # dev/inode, we check here. redo TRY if $st1[0] != $st2[0] || $st1[1] != $st2[1]; # everything seems okay last; } else { $tries <= $self->{retries} or die "Can't acquire lock on '$path' after $tries seconds"; sleep 1; } } $self->{_created} = !$existed; 1; } # return 1 if we unlock, 0 if already unlocked. die on failure. sub _unlock { my ($self) = @_; my $path = $self->{path}; # don't unlock if we are not holding the lock return 0 unless $self->{_fh}; unlink $self->{path} if $self->{_created} && !(-s $self->{path}); { # to shut up warning about flock on closed filehandle (XXX but why # closed if we are holding the lock?) no warnings; flock $self->{_fh}, LOCK_UN; } close delete($self->{_fh}); 1; } sub release { my $self = shift; $self->_unlock; } sub unlock { my $self = shift; $self->_unlock; } sub DESTROY { my $self = shift; $self->_unlock; } 1; #ABSTRACT: Yet another flock module __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::File::Flock - Yet another flock module =head1 VERSION version 0.53 =head1 SYNOPSIS use SHARYANTO::File::Flock; # try to acquire exclusive lock. if fail to acquire lock within 60s, die. my $lock = SHARYANTO::File::Flock->lock($file); # explicitly unlock $lock->release; # automatically unlock if object is DESTROY-ed. undef $lock; =head1 DESCRIPTION This is yet another flock module. It is a more lightweight alternative to L with some other differences: =over 4 =item * OO interface only =item * Autoretry (by default for 60s) when trying to acquire lock I prefer this approach to blocking/waiting indefinitely or failing immediately. =back =for Pod::Coverage ^(DESTROY)$ =head1 METHODS =head2 $lock = SHARYANTO::File::Flock->lock($path, \%opts) Acquire an exclusive lock on C<$path>. C<$path> will be created if not already exists. If $path is already locked by another process, will retry (by default for 60 seconds). Will die if failed to acquire lock. Will automatically unlock if C<$lock> goes out of scope. Upon unlock, will remove C<$path> if it was created and is still empty (this behavior is the same as File::Flock). Available options: =over =item * retries => INT (default: 60) Number of retries (equals number of seconds, since retry is done every second). =back =head2 $lock->unlock Unlock. =head2 $lock->release Synonym for unlock(). =head1 CAVEATS Not yet tested on Windows. Some filesystems do not support inode? =head1 SEE ALSO L L which is also tiny, but does not have the autoremove and autoretry capability which I want. See also: https://github.com/trinitum/perl-File-Flock-Tiny/issues/1 flock() Perl function. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 FUNCTIONS None are exported by default, but they are exportable. =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/File/Util.pm0000644000175000017500000000603612176106301016011 0ustar s1s1package SHARYANTO::File::Util; use 5.010; use strict; use warnings; use Cwd (); require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(file_exists l_abs_path dir_empty); our $VERSION = '0.53'; # VERSION our %SPEC; sub file_exists { my $path = shift; !(-l $path) && (-e _) || (-l _); } sub l_abs_path { my $path = shift; return Cwd::abs_path($path) unless (-l $path); $path =~ s!/\z!!; my ($parent, $leaf); if ($path =~ m!(.+)/(.+)!s) { $parent = Cwd::abs_path($1); return undef unless defined($path); $leaf = $2; } else { $parent = Cwd::getcwd(); $leaf = $path; } "$parent/$leaf"; } sub dir_empty { my ($dir) = @_; return undef unless (-d $dir); return undef unless opendir my($dh), $dir; my @d = grep {$_ ne '.' && $_ ne '..'} readdir($dh); my $res = !@d; #$log->tracef("dir_is_empty(%s)? %d", $dir, $res); $res; } 1; # ABSTRACT: File-related utilities __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::File::Util - File-related utilities =head1 VERSION version 0.53 =head1 SYNOPSIS use SHARYANTO::File::Util qw(file_exists l_abs_path dir_empty); print "file exists" if file_exists("/path/to/file/or/dir"); print "absolute path = ", l_abs_path("foo"); print "dir exists and is empty" if dir_empty("/path/to/dir"); =head1 DESCRIPTION =head1 FUNCTIONS None are exported by default, but they are exportable. =head2 file_exists($path) => BOOL This routine is just like the B<-e> test, except that it assume symlinks with non-existent target as existing. If C is a symlink to a non-existing target: -e "sym" # false, Perl performs stat() which follows symlink but: -l "sym" # true, Perl performs lstat() -e _ # false This function performs the following test: !(-l "sym") && (-e _) || (-l _) =head2 l_abs_path($path) => STR Just like Cwd::abs_path(), except that it will not follow symlink if $path is symlink (but it will follow symlinks for the parent paths). Example: use Cwd qw(getcwd abs_path); say getcwd(); # /home/steven # s is a symlink to /tmp/foo say abs_path("s"); # /tmp/foo say l_abs_path("s"); # /home/steven/s # s2 is a symlink to /tmp say abs_path("s2/foo"); # /tmp/foo say l_abs_path("s2/foo"); # /tmp/foo Mnemonic: l_abs_path -> abs_path is analogous to lstat -> stat. Note: currently uses hardcoded C as path separator. =head2 dir_empty($dir) => BOOL Will return true if C<$dir> exists and is empty. None are exported by default, but they are exportable. =head1 FAQ =head2 Where is file_empty()? For checking if some path exists, is a regular file, and is empty (content is zero-length), you can simply use the C<-z> filetest operator. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. 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 SHARYANTO-Utils-0.53/lib/SHARYANTO/Color/0000755000175000017500000000000012176106301014730 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Color/Util.pm0000644000175000017500000001506412176106301016211 0ustar s1s1package SHARYANTO::Color::Util; use 5.010; use strict; use warnings; #use List::Util qw(min); require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw( mix_2_rgb_colors rand_rgb_color reverse_rgb_color rgb2grayscale rgb2sepia rgb_luminance tint_rgb_color ); our $VERSION = '0.53'; # VERSION sub mix_2_rgb_colors { my ($rgb1, $rgb2, $pct) = @_; $pct //= 0.5; $rgb1 =~ /^#?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/o or die "Invalid rgb1 color, must be in 'ffffff' form"; my $r1 = hex($1); my $g1 = hex($2); my $b1 = hex($3); $rgb2 =~ /^#?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/o or die "Invalid rgb2 color, must be in 'ffffff' form"; my $r2 = hex($1); my $g2 = hex($2); my $b2 = hex($3); return sprintf("%02x%02x%02x", $r1 + $pct*($r2-$r1), $g1 + $pct*($g2-$g1), $b1 + $pct*($b2-$b1), ); } sub rand_rgb_color { my ($rgb1, $rgb2) = @_; $rgb1 //= '000000'; $rgb1 =~ /^#?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/o or die "Invalid rgb1 color, must be in 'ffffff' form"; my $r1 = hex($1); my $g1 = hex($2); my $b1 = hex($3); $rgb2 //= 'ffffff'; $rgb2 =~ /^#?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/o or die "Invalid rgb2 color, must be in 'ffffff' form"; my $r2 = hex($1); my $g2 = hex($2); my $b2 = hex($3); return sprintf("%02x%02x%02x", $r1 + rand()*($r2-$r1+1), $g1 + rand()*($g2-$g1+1), $b1 + rand()*($b2-$b1+1), ); } sub rgb2grayscale { my ($rgb) = @_; $rgb =~ /^#?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/o or die "Invalid rgb color, must be in 'ffffff' form"; my $r = hex($1); my $g = hex($2); my $b = hex($3); # basically we just average the R, G, B my $avg = int(($r + $g + $b)/3); return sprintf("%02x%02x%02x", $avg, $avg, $avg); } sub rgb2sepia { my ($rgb) = @_; $rgb =~ /^#?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/o or die "Invalid rgb color, must be in 'ffffff' form"; my $r = hex($1); my $g = hex($2); my $b = hex($3); # reference: http://www.techrepublic.com/blog/howdoi/how-do-i-convert-images-to-grayscale-and-sepia-tone-using-c/120 my $or = ($r*0.393) + ($g*0.769) + ($b*0.189); my $og = ($r*0.349) + ($g*0.686) + ($b*0.168); my $ob = ($r*0.272) + ($g*0.534) + ($b*0.131); for ($or, $og, $ob) { $_ = 255 if $_ > 255 } return sprintf("%02x%02x%02x", $or, $og, $ob); } sub reverse_rgb_color { my ($rgb) = @_; $rgb =~ /^#?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/o or die "Invalid rgb color, must be in 'ffffff' form"; my $r = hex($1); my $g = hex($2); my $b = hex($3); return sprintf("%02x%02x%02x", 255-$r, 255-$g, 255-$b); } sub _rgb_luminance { my ($r, $g, $b) = @_; 0.2126*$r/255 + 0.7152*$g/255 + 0.0722*$b/255; } sub rgb_luminance { my ($rgb) = @_; $rgb =~ /^#?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/o or die "Invalid rgb color, must be in 'ffffff' form"; my $r = hex($1); my $g = hex($2); my $b = hex($3); return _rgb_luminance($r, $g, $b); } sub tint_rgb_color { my ($rgb1, $rgb2, $pct) = @_; $pct //= 0.5; $rgb1 =~ /^#?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/o or die "Invalid rgb color, must be in 'ffffff' form"; my $r1 = hex($1); my $g1 = hex($2); my $b1 = hex($3); $rgb2 =~ /^#?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/o or die "Invalid tint color, must be in 'ffffff' form"; my $r2 = hex($1); my $g2 = hex($2); my $b2 = hex($3); my $lum = _rgb_luminance($r1, $g1, $b1); return sprintf("%02x%02x%02x", $r1 + $pct*($r2-$r1)*$lum, $g1 + $pct*($g2-$g1)*$lum, $b1 + $pct*($b2-$b1)*$lum, ); } 1; # ABSTRACT: Color-related utilities __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Color::Util - Color-related utilities =head1 VERSION version 0.53 =head1 SYNOPSIS use SHARYANTO::Color::Util qw( mix_2_rgb_colors rand_rgb_color rgb2grayscale rgb2sepia reverse_rgb_color rgb_luminance ); say mix_2_rgb_colors('#ff0000', '#ffffff'); # pink (red + white) say mix_2_rgb_colors('ff0000', 'ffffff', 0.75); # pink with a whiter shade say rand_rgb_color(); say rand_rgb_color('000000', '333333'); # limit range say rgb2grayscale('0033CC'); # => 555555 say rgb2sepia('0033CC'); # => 4d4535 say reverse_rgb_color('0033CC'); # => ffcc33 say rgb_luminance('d090aa'); # => ffcc33 =head1 DESCRIPTION =head1 FUNCTIONS None are exported by default, but they are exportable. =head2 mix_2_rgb_colors($rgb1, $rgb2, $pct) => STR Mix 2 RGB colors. C<$pct> is a number between 0 and 1, by default 0.5 (halfway), the closer to 1 the closer the resulting color to C<$rgb2>. =head2 rand_rgb_color([$low_limit[, $high_limit]]) => STR Generate a random RGB color. You can specify the limit. Otherwise, they default to the full range (000000 to ffffff). =head2 rgb2grayscale($rgb) => RGB Convert C<$rgb> to grayscale RGB value. =head2 rgb2sepia($rgb) => RGB Convert C<$rgb> to sepia tone RGB value. =head2 reverse_rgb_color($rgb) => RGB Reverse C<$rgb>. =head2 rgb_luminance($rgb) => NUM Calculate standard/objective luminance from RGB value using this formula: (0.2126*R) + (0.7152*G) + (0.0722*B) where R, G, and B range from 0 to 1. Return a number from 0 to 1. =head2 tint_rgb_color($rgb, $tint_rgb, $pct) => RGB Tint C<$rgb> with C<$tint_rgb>. $pct is by default 0.5. It is similar to mixing, but the less luminance the color is the less it is tinted with the tint color. This has the effect of black color still being black instead of becoming tinted. None are exported by default, but they are exportable. =head1 TODO mix_rgb_colors() to mix several RGB colors. Args might be $rgb1, $rgb2, ... or $rgb1, $part1, $rgb2, $part2, ... (e.g. 'ffffff', 1, 'ff0000', 1, '00ff00', 2). =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. 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 SHARYANTO-Utils-0.53/lib/SHARYANTO/Log/0000755000175000017500000000000012176106301014373 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Log/Util.pm0000644000175000017500000000252212176106301015647 0ustar s1s1package SHARYANTO::Log::Util; use 5.010; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(@log_levels $log_levels_re); our $VERSION = '0.53'; # VERSION our @log_levels = (qw/trace debug info warn error fatal/); our $log_levels_re = join("|", @log_levels); $log_levels_re = qr/\A(?:$log_levels_re)\z/; 1; # ABSTRACT: Log-related utilities __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Log::Util - Log-related utilities =head1 VERSION version 0.53 =head1 SYNOPSIS use SHARYANTO::Log::Util qw(@log_levels $log_levels_re); =head1 DESCRIPTION =head1 VARIABLES None are exported by default, but they are exportable. =head2 @log_levels Contains log levels, from lowest to highest. Currently these are: (qw/trace debug info warn error fatal/) They can be used as method names to L ($log->debug, $log->warn, etc). =head2 $log_levels_re Contains regular expression to check valid log levels. =head1 SEE ALSO L =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 FUNCTIONS None are exported by default, but they are exportable. =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Text/0000755000175000017500000000000012176106301014576 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Text/Prompt.pm0000644000175000017500000000352512176106301016422 0ustar s1s1package SHARYANTO::Text::Prompt; use 5.010; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(prompt); our $VERSION = '0.53'; # VERSION sub prompt { my ($text, $opts) = @_; $opts //= {}; my $answer; my $default; if ($opts->{var}) { } $default = ${$opts->{var}} if $opts->{var}; $default = $opts->{default} if defined($opts->{default}); while (1) { # prompt print $text; print " ($default)" if defined($default); print ":" unless $text =~ /[:?]\s*$/; print " "; # get input $answer = ; if (!defined($answer)) { print "\n"; $answer = ""; } chomp($answer); # check+process answer if (defined($default)) { $answer = $default if !length($answer); } my $success = 1; if ($opts->{required}) { $success = 0 if !length($answer); } if ($opts->{regex}) { $success = 0 if $answer !~ /$opts->{regex}/; } last if $success; } ${$opts->{var}} = $answer if $opts->{var}; $answer; } 1; # ABSTRACT: Prompt user question __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Text::Prompt - Prompt user question =head1 VERSION version 0.53 =head1 FUNCTIONS =head2 prompt($text, \%opts) Options: =over 4 =item * var => \$var =item * required => \$var =item * default => VALUE =item * regex => REGEX =back None are exported by default, but they are exportable. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Scalar/0000755000175000017500000000000012176106301015057 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Scalar/Util.pm0000644000175000017500000000467312176106301016344 0ustar s1s1package SHARYANTO::Scalar::Util; use 5.010; use strict; use warnings; use Scalar::Util qw(looks_like_number); use Exporter qw(import); our @EXPORT_OK = qw( looks_like_int looks_like_float looks_like_real ); our $VERSION = '0.53'; # VERSION sub looks_like_int { my $l = looks_like_number($_[0]); $l==1 || $l==2 || $l==9 || $l==10 || $l==4352; } sub looks_like_float { my $l = looks_like_number($_[0]); $l==4 || $l==5 || $l==6 || $l==12 || $l==13 || $l==14 || $l==20 || $l==28 || $l==36 || $l==44 || $l==8704; } sub looks_like_real { my $l = looks_like_number($_[0]); $l==1 || $l==2 || $l==9 || $l==10 || $l==4352 || $l==4 || $l==5 || $l==6 || $l==12 || $l==13 || $l==14 || $l==20 || $l==28 || $l==36 || $l==44 || $l==8704; } 1; # ABSTRACT: Scalar utilities __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Scalar::Util - Scalar utilities =head1 VERSION version 0.53 =head1 SYNOPSIS use SHARYANTO::Scalar::Util qw( looks_like_int looks_like_float looks_like_real ); say looks_like_int(10); # 1, isint() also returns 1 say looks_like_int("1".("0" x 100)); # 1, isint() returns 0 here say looks_like_int("123a"); # 0 say looks_like_float(1.1); # 1 say looks_like_float("1e2"); # 1 say looks_like_float("-Inf"); # 1 say looks_like_float(""); # 0 # either looks like int, or float say looks_like_real(1); # 1 say looks_like_real(1.1); # 1 =head1 FUNCTIONS =head2 looks_like_int($arg) => BOOL Uses L's C to check whether C<$arg> looks like an integer. =head2 looks_like_float($arg) => BOOL Uses L's C to check whether C<$arg> looks like a floating point number. =head2 looks_like_real($arg) => BOOL Uses L's C to check whether C<$arg> looks like a real number (either an integer or a floating point). None are exported by default, but they are exportable. =head1 SEE ALSO L L =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Getopt/0000755000175000017500000000000012176106301015114 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Getopt/Long/0000755000175000017500000000000012176106301016013 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Getopt/Long/Util.pm0000644000175000017500000000332712176106301017273 0ustar s1s1package SHARYANTO::Getopt::Long::Util; use 5.010; use strict; use warnings; our $VERSION = '0.53'; # VERSION require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(gospec2human); sub gospec2human { my $go = shift; my $type = 'flag'; if ($go =~ s/!$//) { $type = 'bool'; } elsif ($go =~ s/(=\w)$//) { $type = $1; } elsif ($go =~ s/\+$//) { # also a flag, increment by one like --more --more --more } elsif ($go !~ /[A-Za-z0-9?]\z/) { die "Sorry, can't parse '$go' yet (probably invalid?)"; } my $res = ""; for (split /\|/, $go) { $res .= ", " if length($res); s/^--?//; if ($type eq 'bool') { $res .= "--(no)$_"; } else { if (length($_) > 1) { $res .= "--$_" . ($type =~ /^=/ ? $type : ""); } else { $res .= "-$_" . ($type =~ /^=/ ? $type : ""); } } } $res; } #ABSTRACT: Utilities for Getopt::Long __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Getopt::Long::Util - Utilities for Getopt::Long =head1 VERSION version 0.53 =head1 FUNCTIONS =head2 gospec2human($gospec) => STR Change something like 'help|h|?' or 'foo=s' or 'debug!' into, respectively, '--help, -h, -?' or '--foo=s' or '--(no)debug'. The output is suitable for including in help/usage text. None are exported by default, but they are exportable. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Utils.pm0000644000175000017500000000153412176106301015313 0ustar s1s1package SHARYANTO::Utils; our $VERSION = '0.53'; # VERSION 1; # ABSTRACT: SHARYANTO's temporary namespace for various routines __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Utils - SHARYANTO's temporary namespace for various routines =head1 VERSION version 0.53 =head1 FAQ =head2 What is this? This distribution is a heterogenous collection of modules that will eventually have their own proper distributions. See L about this temporary namespace. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION =head1 FUNCTIONS None are exported by default, but they are exportable. =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Hash/0000755000175000017500000000000012176106301014535 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Hash/Util.pm0000644000175000017500000000246412176106301016016 0ustar s1s1package SHARYANTO::Hash::Util; use 5.010; use strict; use warnings; use Data::Clone; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(rename_key); our $VERSION = '0.53'; # VERSION sub rename_key { my ($h, $okey, $nkey) = @_; die unless exists $h->{$okey}; die if exists $h->{$nkey}; $h->{$nkey} = delete $h->{$okey}; } 1; # ABSTRACT: Hash utilities __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Hash::Util - Hash utilities =head1 VERSION version 0.53 =head1 SYNOPSIS use SHARYANTO::Hash::Util qw(rename_key); my %h = (a=>1, b=>2); rename_key(\%h, "a", "alpha"); # %h = (alpha=>1, b=>2) =head1 FUNCTIONS =head2 rename_key(\%hash, $old_key, $new_key) Rename key. This is basically C<< $hash{$new_key} = delete $hash{$old_key} >> with a couple of additional checks. It is a shortcut for: die unless exists $hash{$old_key}; die if exists $hash{$new_key}; $hash{$new_key} = delete $hash{$old_key}; None are exported by default, but they are exportable. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Package/0000755000175000017500000000000012176106301015205 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Package/Util.pm0000644000175000017500000000747712176106301016477 0ustar s1s1package SHARYANTO::Package::Util; use 5.010; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw( package_exists list_package_contents list_subpackages ); our $VERSION = '0.53'; # VERSION sub package_exists { no strict 'refs'; my $pkg = shift; return unless $pkg =~ /\A\w+(::\w+)*\z/; if ($pkg =~ s/::(\w+)\z//) { return !!${$pkg . "::"}{$1 . "::"}; } else { return !!$::{$pkg . "::"}; } } # XXX incomplete/improper sub list_package_contents { no strict 'refs'; my $pkg = shift; return () unless !length($pkg) || package_exists($pkg); my $symtbl = \%{$pkg . "::"}; my %res; while (my ($k, $v) = each %$symtbl) { next if $k =~ /::$/; # subpackage my $n; if ("$v" !~ /^\*/) { # constant $res{$k} = $v; next; } if (defined *$v{CODE}) { $res{$k} = *$v{CODE}; # subroutine $n++; } if (defined *$v{HASH}) { $res{"\%$k"} = \%{*$v}; # hash $n++; } if (defined *$v{ARRAY}) { $res{"\@$k"} = \@{*$v}; # array $n++; } if (defined(*$v{SCALAR}) # XXX always defined? && defined(${*$v})) { # currently we filter undef values $res{"\$$k"} = \${*$v}; # scalar $n++; } if (!$n) { $res{"\*$k"} = $v; # glob } } %res; } sub list_subpackages { no strict 'refs'; my ($pkg, $recursive, $cur_res) = @_; return () unless !length($pkg) || package_exists($pkg); my $symtbl = \%{$pkg . "::"}; my $res = $cur_res // []; while (my ($k, $v) = each %$symtbl) { next unless $k =~ s/::$//; my $name = (length($pkg) ? "$pkg\::" : "" ) . $k; push @$res, $name; list_subpackages($name, 1, $res) if $recursive; } @$res; } 1; # ABSTRACT: Package-related utilities __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Package::Util - Package-related utilities =head1 VERSION version 0.53 =head1 SYNOPSIS use SHARYANTO::Package::Util qw( package_exists list_package_contents list_subpackages ); print "Package Foo::Bar exists" if package_exists("Foo::Bar"); my %content = list_package_contents("Foo::Bar"); my @subpkg = list_subpackages("Foo::Bar"); my @allsubpkg = list_subpackages("Foo::Bar", 1); # recursive =head1 DESCRIPTION =head2 package_exists($name) => BOOL Return true if package "exists". By "exists", it means that the package has been defined by C statement or some entries have been created in the symbol table (e.g. C<$Foo::var = 1;> will make the C package "exist"). This function can be used e.g. for checking before aliasing one package to another. Or to casually check whether a module has been loaded. =head2 list_package_contents($name) => %res Return a hash containing package contents. For example: ( sub1 => \&Foo::Bar::sub1, sub2 => \&Foo::Bar::sub2, '%h1' => \%Foo::Bar::h1, '@a1' => \@Foo::Bar::a1, ... ) This module won't list subpackages. Use list_subpackages() for that. =head2 list_subpackages($name[, $recursive]) => @res List subpackages, e.g.: ( "Foo::Bar::Baz", "Foo::Bar::Qux", ... ) If $recursive is true, will also list subpackages of subpackages, and so on. =head1 SEE ALSO L =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 FUNCTIONS None are exported by default, but they are exportable. =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Data/0000755000175000017500000000000012176106301014523 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Data/OldUtil.pm0000644000175000017500000000417712176106301016446 0ustar s1s1package SHARYANTO::Data::OldUtil; use 5.010; use strict; use warnings; #use experimental 'smartmatch'; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(has_circular_ref); our $VERSION = '0.53'; # VERSION our %SPEC; $SPEC{has_circular_ref} = { v => 1.1, summary => 'Check whether data item contains circular references', description => <<'_', Does not deal with weak references. _ args_as => 'array', args => { data => { schema => "any", pos => 0, req => 1, }, }, result_naked => 1, }; sub has_circular_ref { my ($data) = @_; my %refs; my $check; $check = sub { my $x = shift; my $r = ref($x); return 0 if !$r; return 1 if $refs{"$x"}++; if ($r eq 'ARRAY') { for (@$x) { next unless ref($_); return 1 if $check->($_); } } elsif ($r eq 'HASH') { for (values %$x) { next unless ref($_); return 1 if $check->($_); } } 0; }; $check->($data); } 1; # ABSTRACT: Data utilities __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Data::OldUtil - Data utilities =head1 VERSION version 0.53 =head1 SYNOPSIS =head1 DESCRIPTION =head1 FUNCTIONS None are exported by default, but they are exportable. None are exported by default, but they are exportable. =head2 has_circular_ref(@args) -> any Does not deal with weak references. Arguments ('*' denotes required arguments): =over 4 =item * B* => I =back Return value: =head1 SEE ALSO L has the XS/C version of C which is 3 times or more faster than this module's implementation which is pure Perl). Use that instead. This module is however much faster than L. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. 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 SHARYANTO-Utils-0.53/lib/SHARYANTO/Data/Util.pm0000644000175000017500000000656112176106301016006 0ustar s1s1package SHARYANTO::Data::Util; use 5.010; use strict; use warnings; #use experimental 'smartmatch'; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(clone_circular_refs); our $VERSION = '0.53'; # VERSION our %SPEC; $SPEC{clone_circular_refs} = { v => 1.1, summary => 'Remove circular references by deep-copying them', description => <<'_', For example, this data: $x = [1]; $data = [$x, 2, $x]; contains circular references by referring to `$x` twice. After `clone_circular_refs`, data will become: $data = [$x, 2, [1]]; that is, the subsequent circular references will be deep-copied. This makes it safe to transport to JSON, for example. Sometimes it doesn't work, for example: $data = [1]; push @$data, $data; Cloning will still create circular references. This function modifies the data structure in-place, and return true for success and false upon failure. _ args_as => 'array', args => { data => { schema => "any", pos => 0, req => 1, }, }, result_naked => 1, }; sub clone_circular_refs { require Data::Structure::Util; require Data::Clone; my ($data) = @_; my %refs; my $doit; $doit = sub { my $x = shift; my $r = ref($x); return if !$r; if ($r eq 'ARRAY') { for (@$x) { next unless ref($_); if ($refs{"$_"}++) { $_ = Data::Clone::clone($_); } else { $doit->($_); } } } elsif ($r eq 'HASH') { for (keys %$x) { next unless ref($x->{$_}); if ($refs{"$x->{$_}"}++) { $x->{$_} = Data::Clone::clone($x->{$_}); } else { $doit->($_); } } } }; $doit->($data); !Data::Structure::Util::has_circular_ref($data); } 1; # ABSTRACT: Data utilities __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Data::Util - Data utilities =head1 VERSION version 0.53 =head1 SYNOPSIS =head1 DESCRIPTION =head1 FUNCTIONS None are exported by default, but they are exportable. None are exported by default, but they are exportable. =head2 clone_circular_refs(@args) -> any For example, this data: $x = [1]; $data = [$x, 2, $x]; contains circular references by referring to C<$x> twice. After C, data will become: $data = [$x, 2, [1]]; that is, the subsequent circular references will be deep-copied. This makes it safe to transport to JSON, for example. Sometimes it doesn't work, for example: $data = [1]; push @$data, $data; Cloning will still create circular references. This function modifies the data structure in-place, and return true for success and false upon failure. Arguments ('*' denotes required arguments): =over 4 =item * B* => I =back Return value: =head1 SEE ALSO To check for circular references, try C from L. There is also L albeit far slower. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. 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 SHARYANTO-Utils-0.53/lib/SHARYANTO/HTML/0000755000175000017500000000000012176106301014416 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/HTML/Extract/0000755000175000017500000000000012176106301016030 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/HTML/Extract/ImageLinks.pm0000644000175000017500000000550412176106301020415 0ustar s1s1package SHARYANTO::HTML::Extract::ImageLinks; use 5.010; use strict; use warnings; use HTML::Parser; use URI::URL; use Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(extract_image_links); our $VERSION = '0.53'; # VERSION our %SPEC; $SPEC{extract_image_links} = { v => 1.1, summary => 'Extract image links from HTML document', description => <<'_', Either specify either url, html. _ args => { html => { schema => 'str*', req => 1, summary => 'HTML document to extract from', cmdline_src => 'stdin_or_files', }, base => { schema => 'str', summary => 'base URL for images', }, }, }; sub extract_image_links { my %args = @_; my $html = $args{html}; my $base = $args{base}; # get base from if exists if (!$base) { if ($html =~ /]*\bhref\s*=\s*(["']?)(\S+?)\1[^>]*>/is) { $base = $2; } } my %memory; my @res; my $p = HTML::Parser->new( api_version => 3, start_h => [ sub { my ($tagname, $attr) = @_; return unless $tagname =~ /^img$/i; for ($attr->{src}) { s/#.*//; if (++$memory{$_} == 1) { push @res, URI::URL->new($_, $base)->abs()->as_string; } } }, "tagname, attr"], ); $p->parse($html); [200, "OK", \@res]; } 1; # ABSTRACT: Extract image links from HTML document __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::HTML::Extract::ImageLinks - Extract image links from HTML document =head1 VERSION version 0.53 =head1 FUNCTIONS None are exported by default, but they are exportable. None are exported by default, but they are exportable. =head2 extract_image_links(%args) -> [status, msg, result, meta] Either specify either url, html. Arguments ('*' denotes required arguments): =over 4 =item * B => I base URL for images. =item * B* => I HTML document to extract from. =back Return value: Returns an enveloped result (an array). First element (status) is an integer containing HTTP status code (200 means OK, 4xx caller error, 5xx function error). Second element (msg) is a string containing error message, or 'OK' if status is 200. Third element (result) is optional, the actual result. Fourth element (meta) is called result metadata and is optional, a hash that contains extra information. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Proc/0000755000175000017500000000000012176106301014555 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Proc/ChildError.pm0000644000175000017500000000315112176106301017150 0ustar s1s1package SHARYANTO::Proc::ChildError; use 5.010; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(explain_child_error); our $VERSION = '0.53'; # VERSION sub explain_child_error { my ($num, $str); if (defined $_[0]) { $num = $_[0]; $str = $_[1]; } else { $num = $?; $str = $!; } if ($num == -1) { return "failed to execute: ".($str ? "$str ":"")."($num)"; } elsif ($num & 127) { return sprintf( "died with signal %d, %s coredump", ($num & 127), (($num & 128) ? 'with' : 'without')); } else { return sprintf("exited with code %d", $num >> 8); } } 1; # ABSTRACT: Explain process child error __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Proc::ChildError - Explain process child error =head1 VERSION version 0.53 =head1 FUNCTIONS =head2 explain_child_error($child_error, $os_error) => STR Produce a string description of an error number. C<$child_error> defaults to C<$?> if not specified. C<$os_error> defaults to C<$!> if not specified. The algorithm is taken from perldoc -f system. Some sample output: failed to execute: No such file or directory (-1) died with signal 15, with coredump exited with value 3 None are exported by default, but they are exportable. =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Proc/Util.pm0000644000175000017500000000470012176106301016031 0ustar s1s1package SHARYANTO::Proc::Util; use 5.010; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(get_parent_processes); our $VERSION = '0.53'; # VERSION sub get_parent_processes { my ($pid) = @_; $pid //= $$; # things will be simpler if we use the -s option, however not all versions # of pstree supports it. my @lines = `pstree -pA`; return undef unless @lines; my @p; my %proc; for (@lines) { my $i = 0; while (/(?: (\s*(?:\|-?|`-)) | (.+?)\((\d+)\) ) (?: -[+-]- )?/gx) { unless ($1) { my $p = {name=>$2, pid=>$3}; $p[$i] = $p; $p->{ppid} = $p[$i-1]{pid} if $i > 0; $proc{$3} = $p; } $i++; } } #use Data::Dump; dd \%proc; @p = (); my $cur_pid = $pid; while (1) { return if !$proc{$cur_pid}; $proc{$cur_pid}{name} = $1 if $proc{$cur_pid}{name} =~ /\A\{(.+)\}\z/; push @p, $proc{$cur_pid}; $cur_pid = $proc{$cur_pid}{ppid}; last unless $cur_pid; } shift @p; # delete cur process \@p; } # ABSTRACT: OS-process-related routines __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Proc::Util - OS-process-related routines =head1 VERSION version 0.53 =head1 SYNOPSIS =head1 FUNCTIONS None are exported by default, but they are exportable. =head2 get_parent_processes($pid) => ARRAY Return an array containing information about parent processes of C<$pid> up to the parent of all processes (usually C). If C<$pid> is not mentioned, it defaults to C<$$>. The immediate parent is in the first element of array, followed by its parent, and so on. For example: [{name=>"perl",pid=>13134}, {name=>"konsole",pid=>2232}, {name=>"init",pid=>1}] Currently retrieves information by calling B program. Return undef on failure. None are exported by default, but they are exportable. =head1 SEE ALSO L. Pros: does not depend on pstree command, process names not truncated by pstree. Cons: a little bit more heavyweight (uses File::Spec, Cwd, File::Find). =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Proc/Daemon/0000755000175000017500000000000012176106301015760 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Proc/Daemon/Prefork.pm0000644000175000017500000005614712176106301017743 0ustar s1s1package SHARYANTO::Proc::Daemon::Prefork; use 5.010; use strict; use warnings; use Fcntl qw(:DEFAULT :flock); use File::Which; use FindBin; use IO::Select; use POSIX; use Symbol; our $VERSION = '0.53'; # VERSION # --- globals my @daemons; # list of all daemons sub new { my ($class, %args) = @_; # defaults if (!$args{name}) { $args{name} = $0; $args{name} =~ s!.+/!!; } $args{require_root} //= 0; $args{daemonize} //= 1; $args{prefork} //= 3; $args{max_children} //= 150; die "BUG: Please specify main_loop routine" unless $args{main_loop}; if ($args{on_client_disconnect}) { die "netstat is not available in PATH" unless -x which("netstat"); require Parse::Netstat; } $args{parent_pid} = $$; $args{children} = {}; # key = pid my $self = bless \%args, $class; push @daemons, $self; $self; } sub check_pidfile { my ($self) = @_; return unless -f $self->{pid_path}; open my($pid_fh), $self->{pid_path}; my $pid = <$pid_fh>; $pid = $1 if $pid =~ /(\d+)/; # untaint # XXX check timestamp to make sure process is the one meant by pidfile return unless $pid > 0 && kill(0, $pid); $pid; } sub write_pidfile { my ($self) = @_; die "BUG: Overwriting PID without checking it" if $self->check_pidfile; open my($pid_fh), ">$self->{pid_path}"; print $pid_fh $$; close $pid_fh or die "Can't write PID file: $!\n"; } sub unlink_pidfile { my ($self) = @_; my $old_pid = $self->check_pidfile; die "BUG: Deleting active PID which isn't ours" if $old_pid && $old_pid != $$; unlink $self->{pid_path}; } sub kill_running { my ($self) = @_; die "You did not daemonize, so you cannot kill_running()" unless $self->{daemonized}; for ({sig=>"TERM", delay=>1}, {sig=>"TERM", delay=>3}, {sig=>"KILL"}, ) { my $pid = $self->check_pidfile; return unless $pid; kill $_->{sig} => $pid; sleep $_->{delay} // 0; my $pid2 = $self->check_pidfile; return unless $pid2 && $pid2 == $pid; } } sub open_logs { my ($self) = @_; if ($self->{error_log_path}) { open my($fhe), ">>", $self->{error_log_path} or die "Cannot open error log file $self->{error_log_path}: $!\n"; $self->{_error_log} = $fhe; } if ($self->{access_log_path}) { open my($fha), ">>", $self->{access_log_path} or die "Cannot open access log file $self->{access_log_path}: $!\n"; $self->{_access_log} = $fha; } } sub close_logs { my ($self) = @_; if ($self->{_access_log}) { close $self->{_access_log}; } if ($self->{_error_log}) { close $self->{_error_log}; } } sub daemonize { my ($self) = @_; local *ERROR_LOG; $self->open_logs; *ERROR_LOG = $self->{_error_log}; chdir '/' or die "Can't chdir to /: $!\n"; open STDIN, '/dev/null' or die "Can't read /dev/null: $!\n"; open STDOUT, '>&ERROR_LOG' or die "Can't dup ERROR_LOG: $!\n"; defined(my $pid = fork) or die "Can't fork: $!\n"; exit if $pid; unless (0) { #$self->{force}) { my $old_pid = $self->check_pidfile; die "Another daemon already running (PID $old_pid)\n" if $old_pid; } setsid or die "Can't start a new session: $!\n"; open STDERR, '>&STDOUT' or die "Can't dup stdout: $!\n"; $self->{daemonized}++; $self->write_pidfile; $self->{parent_pid} = $$; } sub parent_sig_handlers { my ($self) = @_; die "BUG: Setting parent_sig_handlers must be done in parent" if $self->{parent_pid} ne $$; $SIG{INT} = \&INT_HANDLER; $SIG{TERM} = \&TERM_HANDLER; #$SIG{HUP} = \&RELOAD_HANDLER; $SIG{CHLD} = \&REAPER; } # for children sub child_sig_handlers { my ($self) = @_; die "BUG: Setting child_sig_handlers must be done in children" if $self->{parent_pid} eq $$; $SIG{INT} = 'DEFAULT'; $SIG{TERM} = 'DEFAULT'; $SIG{HUP} = 'DEFAULT'; $SIG{CHLD} = 'DEFAULT'; } sub init { my ($self) = @_; #$self->{scoreboard_path} or die "BUG: Please specify scoreboard_path"; if ($self->{require_root}) { $> and die "Permission denied, daemon must be run as root\n"; } $self->daemonize if $self->{daemonize}; warn "Daemon (PID $$) started at ", scalar(localtime), "\n"; } # XXX use shared memory scoreboard for better performance my $SC_RECSIZE = 20; # the scoreboard file contains fixed-size records, $SC_RECSIZE bytes each. each # record is used by a child process to store its data, and when the child # process is dead, its record will be reused by another child process. # # each record contains the following data: # # - pid of child process (4 bytes), 0 means the record is empty and can be used # for a new child process # # - child start time (4 bytes) # # - number of requests that the child has processed (2 bytes) # # - current request's start time (4 bytes) # # - last update time (4 byte) # # - current state of child process (1 byte, ASCII character): "_" means idle, # "R" is reading request, "W" is writing reply # # - reserved (1 byte) # # total 20 bytes per record. # # when a new daemon is started, the parent process truncates the scoreboard to 0 # bytes. the scoreboard then will grow as new child processes are started. each # child process will find an empty record on the scoreboard and then only write # to that record for the rest of its lifetime. the parent usually only reads the # scoreboard file, but when a child process is dead/reaped it will clean the # scoreboard record of dead processes. the only time a scoreboard file needs to # be locked is when the new child process tries to occupy a new record (so that # two child processes do not get into race condition). at other times, a lock is # not needed. sub init_scoreboard { my ($self) = @_; return unless $self->{scoreboard_path}; sysopen($self->{_scoreboard_fh}, $self->{scoreboard_path}, O_RDWR | O_CREAT | O_TRUNC) or die "Can't initialize scoreboard path: $!"; # for safety against full disk, pre-allocate some empty records syswrite $self->{_scoreboard_fh}, "\x00" x ($SC_RECSIZE*($self->{max_children}+1)); } # used by child process to update its state in the scoreboard file. sub update_scoreboard { my ($self, $data) = @_; return unless $self->{_scoreboard_fh}; # XXX schema die "BUG: data must be hashref" unless ref($data) eq 'HASH'; for (keys %$data) { die "BUG: Unknown key in data: $_" unless /\A(?:child_start_time|num_reqs|req_start_time| state)\z/x; } # if we haven't picked an empty record yet, pick now if (!defined($self->{_scoreboard_recno})) { flock $self->{_scoreboard_fh}, 2; sysseek $self->{_scoreboard_fh}, 0, 0; my $rec; $self->{_scoreboard_recno} = 0; my $pid; while (sysread($self->{_scoreboard_fh}, $rec, $SC_RECSIZE)) { die "Abnormal scoreboard file size (not multiples of $SC_RECSIZE)" if length($rec) && length($rec) < $SC_RECSIZE; # safety $pid = unpack("N", $rec); last if !$pid; # empty record $self->{_scoreboard_recno}++; } # we need to make a new record $self->{_scoreboard_recno}++ if !defined($pid) || $pid; sysseek $self->{_scoreboard_fh}, $self->{_scoreboard_recno}*$SC_RECSIZE, 0; syswrite $self->{_scoreboard_fh}, pack("NNSNNCC", $$, 0,0,0,0,ord("_"),0); flock $self->{_scoreboard_fh}, 8; } sysseek $self->{_scoreboard_fh}, $self->{_scoreboard_recno}*$SC_RECSIZE, 0; # needn't write pid again my $rec; sysread $self->{_scoreboard_fh}, $rec, $SC_RECSIZE; my ($pid, $child_start_time, $num_reqs, $req_start_time, $mtime, $state) = unpack("NNSNNC", $rec); $state = chr($state); sysseek $self->{_scoreboard_fh}, $self->{_scoreboard_recno}*$SC_RECSIZE, 0; syswrite $self->{_scoreboard_fh}, pack("NNSNNCC", $pid, $data->{child_start_time} // $child_start_time // 0, $data->{num_reqs} // $num_reqs // 0, $data->{req_start_time} // $req_start_time // 0, time(), ord($data->{state} // $state // "_"), 0); } # clean records from process(es) that no longer exist. called by parent after # being notified that a child is dead. once in a while, clean not only $pid but # also check all records of dead processes. sub clean_scoreboard { my ($self, $child_pid) = @_; return unless $self->{_scoreboard_fh}; #warn "Cleaning scoreboard (pid $child_pid)\n"; my $check_all = rand()*50 >= 49; my $rec; flock $self->{_scoreboard_fh}, 2; sysseek $self->{_scoreboard_fh}, 0, 0; my $i = -1; while (sysread($self->{_scoreboard_fh}, $rec, $SC_RECSIZE)) { $i++; die "Abnormal scoreboard file size (not multiples of $SC_RECSIZE)" if length($rec) && length($rec) < $SC_RECSIZE; # safety my ($pid) = unpack("N", $rec); next if !$check_all && $pid != $child_pid; next if $check_all && kill(0, $pid); sysseek $self->{_scoreboard_fh}, $i*$SC_RECSIZE, 0; syswrite $self->{_scoreboard_fh}, pack("NNSNNCC", 0, 0,0,0,0,ord("_"),0); last unless $check_all; } flock $self->{_scoreboard_fh}, 8; } sub read_scoreboard { my ($self) = @_; return unless $self->{_scoreboard_fh}; my $rec; my $res = {children=>{}, num_children=>0, num_busy=>0, num_idle=>0}; sysseek $self->{_scoreboard_fh}, 0, 0; while (sysread($self->{_scoreboard_fh}, $rec, $SC_RECSIZE)) { die "Abnormal scoreboard file size (not multiples of $SC_RECSIZE)" if length($rec) && length($rec) < $SC_RECSIZE; # safety my ($pid, $child_start_time, $num_reqs, $req_start_time, $mtime, $state) = unpack("NNSNNC", $rec); $state = chr($state); next unless $pid; $res->{num_children}++; if ($state =~ /^[_.]$/) { $res->{num_idle}++; } else { $res->{num_busy}++; } $res->{children}{$pid} = { pid=>$pid, child_start_time=>$child_start_time, num_reqs=>$num_reqs, req_start_time=>$req_start_time, mtime=>$mtime, state=>$state, }; } $res; } sub run { my ($self) = @_; $self->init; $self->set_label('parent'); $self->{after_init}->() if $self->{after_init}; $self->init_scoreboard; if ($self->{prefork}) { # prefork children for (1 .. $self->{prefork}) { $self->make_new_child(); } $self->parent_sig_handlers; # maintain children population and do cleaning tasks my $i = 0; my $j = 0; # number of increments of child when busy my $k = 0; # number of decrements of child when idle my $max_children_warned; while (1) { sleep 1; if ($self->{auto_reload_check_every} && $i++ >= $self->{auto_reload_check_every}) { $self->check_reload_self; $i = 0; } # top up child pool until at least 'prefork' if (keys(%{$self->{children}}) < $self->{prefork}) { #warn "Topping up child pool to $self->{prefork}\n"; for (my $i = keys(%{$self->{children}}); $i < $self->{prefork}; $i++) { $self->make_new_child(); # top up the child pool } } my $scoreboard; if (rand()*5 >= 4 && $self->{on_client_disconnect}) { { my $output; { local $SIG{CHLD} = 'DEFAULT'; $output = `netstat -anp 2>/dev/null`; } my $res = Parse::Netstat::parse_netstat( output => $output, udp=>0, unix=>0); # currently unix stats is useless, everything is # CONNECTED/CONNECTING and no pid die "Bug: Netstat output can't be parsed: ". "$res->[0] - $res->[1]" unless $res->[0] == 200; my $conns = $res->[2]{active_conns}; my %called_children; for my $conn (@$conns) { my $pid = $conn->{pid}; next unless $pid; next unless $conn->{state} =~ /(?:FIN_WAIT|CLOSE_WAIT)/; next unless $self->{children}{ $pid }; next if $called_children{$pid}++; $self->{on_client_disconnect}->( pid => $pid, local_host => $conn->{local_host}, local_port => $conn->{local_port}, foreign_host => $conn->{foreign_host}, foreign_port => $conn->{foreign_port}, ); } } } # if busy, autoadjust child pool until at least 'max_children', and # decrease it again when idle if (rand()*4 >= 3) { $scoreboard = $self->read_scoreboard; if ($scoreboard) { if ($scoreboard->{num_busy} && $scoreboard->{num_idle} <= 1) { warn "max_children ($self->{max_children} reached, ". "consider increasing it)\n" if $scoreboard->{num_children} >= $self->{max_children} && !$max_children_warned++; $j++; #warn "Autoadjust: increase number of children ". # "($j*2, $scoreboard->{num_children} -> .)\n"; for (1..$j*2) { last if $scoreboard->{num_children} >= $self->{max_children}; $self->make_new_child(); $scoreboard->{num_chilren}++; } } else { $j = 0; } # disable temporarily, not yet working properly if (0 && $scoreboard->{num_idle} >= 3 && $scoreboard->{num_children} > $self->{prefork}) { $k++; #warn "Autoadjust: decrease number of children ". # "($k*2, $scoreboard->{num_children} -> .)\n"; # sort by oldest idle my @pids = sort { $scoreboard->{children}{$a}{mtime} <=> $scoreboard->{children}{$b}{mtime} } grep {$scoreboard->{children}{$_}{state} eq '_'} keys %{$scoreboard->{children}}; for (1..$k*2) { last if $scoreboard->{num_children} <= $self->{prefork}; if (@pids) { # pick oldest idle child and kill it my $pid = shift @pids; if ($pid) { kill TERM => $pid; $scoreboard->{num_chilren}--; delete $scoreboard->{children}{$pid}; delete $scoreboard->{children}{$pid}; #warn "Killed process $pid (num_children=". # "$scoreboard->{num_children})\n"; } } } } else { $k = 0; } } } } } else { $self->{main_loop}->(); } } sub make_new_child { my ($self) = @_; # from perl cookbook: block signal for fork my $sigset = POSIX::SigSet->new(SIGINT); sigprocmask(SIG_BLOCK, $sigset) or die "Can't block SIGINT for fork: $!\n"; my $pid; unless (defined ($pid = fork)) { warn "Can't fork: $!"; sigprocmask(SIG_UNBLOCK, $sigset) or die "Can't unblock SIGINT for fork: $!\n"; return; } if ($pid) { # from perl cookbook: Parent records the child's birth and returns. sigprocmask(SIG_UNBLOCK, $sigset) or die "Can't unblock SIGINT for fork: $!\n"; $self->{children}{$pid} = 1; return; } else { # from perl cookbook: Child can *not* return from this subroutine. $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before sigprocmask(SIG_UNBLOCK, $sigset) or die "Can't unblock SIGINT for fork: $!\n"; $self->child_sig_handlers; $self->set_label('child'); $self->{main_loop}->(); exit; } } sub set_label { my ($self, $label) = @_; $0 = $self->{name} . " [$label]"; } sub kill_children { my ($self) = @_; warn "Killing children processes ...\n" if keys %{$self->{children}}; for my $pid (keys %{$self->{children}}) { kill TERM => $pid; } } sub is_parent { my ($self) = @_; $$ == $self->{parent_pid}; } sub shutdown { my ($self, $reason) = @_; warn "Shutting down daemon".($reason ? " (reason=$reason)" : "")."\n"; $self->{before_shutdown}->() if $self->{before_shutdown}; $self->kill_children if $self->is_parent; if ($self->{daemonized}) { $self->unlink_pidfile; $self->close_logs; } } sub REAPER { $SIG{CHLD} = \&REAPER; my $pid = wait; for (@daemons) { delete $_->{children}{$pid}; $_->clean_scoreboard($pid); } } sub INT_HANDLER { local($SIG{CHLD}) = 'IGNORE'; # from perl cookbook for (@daemons) { $_->shutdown("INT"); } exit 1; } sub TERM_HANDLER { local($SIG{CHLD}) = 'IGNORE'; # from perl cookbook for (@daemons) { $_->shutdown("TERM"); } exit 1; } sub check_reload_self { my ($self) = @_; # XXX use Filesystem watcher instead of manually checking -M state $self_mtime; state $modules_mtime = {}; my $should_reload; { my $new_self_mtime = (-M "$FindBin::Bin/$FindBin::Script"); if (defined($self_mtime)) { do { $should_reload++; last } if $self_mtime != $new_self_mtime; } else { $self_mtime = $new_self_mtime; } for (keys %INC) { # undef entry in %INC can mean require() has failed loading it, skip # this for now next unless defined($INC{$_}); my $new_module_mtime = (-M $INC{$_}); if (defined($modules_mtime->{$_})) { #warn "$$: Comparing file $_ on disk\n"; if ($modules_mtime->{$_} != $new_module_mtime) { #warn "$$: File $_ changes on disk\n"; $should_reload++; last; } } else { $modules_mtime->{$_} = $new_module_mtime; } } } if ($should_reload) { warn "$$: Reloading self because script/one of the modules ". "changed on disk ...\n"; # XXX not yet working, needs --force somewhere $self->{auto_reload_handler}->($self); } } 1; # ABSTRACT: Create preforking, autoreloading daemon __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Proc::Daemon::Prefork - Create preforking, autoreloading daemon =head1 VERSION version 0.53 =for Pod::Coverage .* =head1 METHODS =head2 new(%args) Arguments: =over 4 =item * require_root => BOOL (default 0) If true, bails out if not running as root. =item * error_log_path (required if daemonize=1) =item * access_log_path => STR (required if daemonize=1) =item * pid_path => STR (required if daemonize=1) =item * scoreboard_path => STR (default none) If not set, no scoreboard file will be created/updated. Scoreboard file is used to communicate between parent and child processes. Autoadjustment of number of processes, for example, requires this (see max_children for more details). =item * daemonize => BOOL (default 1) =item * prefork => INT (default 3, 0 means a nonforking/single-threaded daemon) This is like the StartServers setting in Apache webserver (the prefork MPM), the number of children processes to prefork. =item * max_children => INT (default 150) This is like the MaxClients setting in Apache webserver. Initially the number of children spawned will follow the 'prefork' setting. If while serving requests, all children are busy, parent will automatically increase the number of children gradually until 'max_children'. If afterwards these children are idle, they will be gradually killed off until there are 'prefork' number of children again. Note that for this to function, scoreboard_path must be defined since the parent needs to communicate with children. =item * auto_reload_check_every => INT (default undef, meaning never) In seconds. =item * auto_reload_handler => CODEREF (required if auto_reload_check_every is set) =item * after_init => CODEREF (default none) Run after the daemon initializes itself (daemonizes, writes PID file, etc), before spawning children. You usually bind to sockets here (if your daemon is a network server). =item * on_client_disconnect => CODEREF Do something after socket connection between client and child process is closed. This requires scoreboard (see C argument) to record all the children's PIDs, and also the "netstat" command and L module to check for connections. This can be used, for example, to kill child process (cancel job) on disconnect. Will be called for each child server being disconnected. Code will receive a hash containing: C, C, C, C, C, C. Note that monitoring connections is done every few seconds by the parent process, so this code will not be run immediately after closing of connection. Currently only works for TCP connections and not Unix connections, due to lack of information provided by "netstat" for Unix connections. =item * main_loop* => CODEREF Run at the beginning of each child process. This is the main loop for your daemon. You usually do this in your main loop routine: for(my $i=1; $i<=$MAX_REQUESTS_PER_CHILD; $i++) { # accept loop, or process job loop } =item * before_shutdown => CODEREF (optional) Run before killing children and shutting down. =back =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =head1 DESCRIPTION =head1 FUNCTIONS None are exported by default, but they are exportable. =cut SHARYANTO-Utils-0.53/lib/SHARYANTO/Array/0000755000175000017500000000000012176106301014730 5ustar s1s1SHARYANTO-Utils-0.53/lib/SHARYANTO/Array/Util.pm0000644000175000017500000000633112176106301016206 0ustar s1s1package SHARYANTO::Array::Util; use 5.010; use strict; use warnings; use experimental 'smartmatch'; use Data::Clone; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(match_array_or_regex match_regex_or_array); our $VERSION = '0.53'; # VERSION our %SPEC; my $_str_or_re = ['any*'=>{of=>['re*','str*']}]; $SPEC{match_array_or_regex} = { v => 1.1, summary => 'Check whether an item matches (list of) values/regexes', description => <<'_', This routine can be used to match an item against a regex or a list of strings/regexes, e.g. when matching against an ACL. _ examples => [ {args=>{needle=>"abc", haystack=>["abc", "abd"]}, result=>1}, {args=>{needle=>"abc", haystack=>qr/ab./}, result=>1}, {args=>{needle=>"abc", haystack=>[qr/ab./, "abd"]}, result=>1}, ], args_as => 'array', args => { needle => { schema => ["str*"], pos => 0, req => 1, }, haystack => { # XXX checking this schema might actually take longer than matching # the needle! so when arg validation is implemented, provide a way # to skip validating this schema schema => ["any*" => { # turned off temporarily 2012-12-25, Data::Sah is currently broken #of => [$_str_or_re, ["array*"=>{of=>$_str_or_re}]], }], pos => 1, req => 1, }, }, result_naked => 1, }; sub match_array_or_regex { my ($needle, $haystack) = @_; my $ref = ref($haystack); if ($ref eq 'ARRAY') { return $needle ~~ @$haystack; } elsif (!$ref) { return $needle =~ /$haystack/; } elsif ($ref eq 'Regexp') { return $needle =~ $haystack; } else { die "Invalid haystack, must be regex or array of strings/regexes"; } } *match_regex_or_array = \&match_array_or_regex; $SPEC{match_regex_or_array} = clone $SPEC{match_array_or_regex}; $SPEC{match_regex_or_array}{summary} = 'Alias for match_array_or_regex'; 1; # ABSTRACT: Array-related utilities __END__ =pod =encoding utf-8 =head1 NAME SHARYANTO::Array::Util - Array-related utilities =head1 VERSION version 0.53 =head1 SYNOPSIS =head1 DESCRIPTION =head1 FUNCTIONS None are exported by default, but they are exportable. None are exported by default, but they are exportable. =head2 match_array_or_regex(@args) -> any This routine can be used to match an item against a regex or a list of strings/regexes, e.g. when matching against an ACL. Arguments ('*' denotes required arguments): =over 4 =item * B* => I =item * B* => I =back Return value: =head2 match_regex_or_array(@args) -> any This routine can be used to match an item against a regex or a list of strings/regexes, e.g. when matching against an ACL. Arguments ('*' denotes required arguments): =over 4 =item * B* => I =item * B* => I =back Return value: =head1 AUTHOR Steven Haryanto =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. 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 SHARYANTO-Utils-0.53/MANIFEST.SKIP0000644000175000017500000000000312176106301013423 0ustar s1s1~$ SHARYANTO-Utils-0.53/Changes0000644000175000017500000001621512176106301013034 0ustar s1s1Revision history for SHARYANTO-Utils 0.53 2013-07-26 (SHARYANTO) [INCOMPATIBLE CHANGES] - Role::Doc::Section and Role::Doc::Section::AddTextLines: Rename methods to become more consistent and less intrusive. {,before_,after_}generate_doc() becomes {,before_,after_}gen_doc(). Rename doc_gen_*() to gen_doc_section_*(). Remove doc_parse_*() methods as they are implementation details. Rename attributes indent_level to doc_indent_level, indent to doc_indent_str, wrap to doc_wrap. 0.52 2013-07-26 (SHARYANTO) - Move Perinci::To::Text::AddDocLinesRole to SHARYANTO::Role::Doc::Section::AddTextLines. 0.51 2013-07-12 (SHARYANTO) - Add module: Data::Util. - Skip File::Flock test on Windows [CT#86829]. 0.50 2013-07-03 (SHARYANTO) [INCOMPATIBLE CHANGES] - File::Flock: be more like the original File::Flock by removing lock file only if lock file was created during lock, and is empty. This module is created as a more lightweight alternative to the original File::Flock after all. 0.49 2013-07-03 (SHARYANTO) [INCOMPATIBLE CHANGES] - File::Flock: unlink option is by default 1 because this is the convenient behavior. Lock file is removed upon unlock(), not after DESTROY-ed. 0.48 2013-07-02 (SHARYANTO) [BUG FIXES] - File::Flock: handle race condition between flock() and stat() after locking. Thanks Anders Kaseorg. [GH#1] [INCOMPATIBLE CHANGES] - File::Flock: Only unlink lock file if current process is holding the lock. [GH#1] 0.47 2013-05-16 (SHARYANTO) - Color::Util: add rgb_luminance() and tint_rgb_color(). 0.46 2013-05-15 (SHARYANTO) - Role::I18N: add method locopt(). - Proc::ChildError: Skip failing tests on Windows [CT]. 0.45 2013-05-10 (SHARYANTO) - Add module: SHARYANTO::Getopt::Long::Util (gospec2human). 0.44 2013-05-09 (SHARYANTO) [BUG FIXES] - Proc::Util: get_parent_processes should not return information on current process. 0.43 2013-05-09 (SHARYANTO) - Add module: SHARYANTO::Proc::Util (get_parent_processes). 0.42 2013-05-02 (SHARYANTO) - Color::Util: add function reverse_rgb_color(). 0.41 2013-05-02 (SHARYANTO) - Color::Util: add functions rgb2grayscale() and rgb2sepia(). 0.40 2013-04-28 (SHARYANTO) - Color::Util: add function rand_rgb_color(). 0.39 2013-04-27 (SHARYANTO) - Add module: SHARYANTO::Color::Util (mix_2_rgb_colors()). 0.38 2013-04-10 (SHARYANTO) No functional changes. Bug fixes for format_metric(). 0.37 2013-04-10 (SHARYANTO) No functional changes. Tweak internal/private option for format_metric() for dux. 0.36 2013-04-10 (SHARYANTO) - Add module: SHARYANTO::Number::Util (format_metric()). 0.35 2013-02-15 (SHARYANTO) No functional changes. Rewrite tests for l_abs_path() to more clearly show the differences between it and abs_path(), pass on systems where /tmp is symlinked. 0.34 2012-12-28 (SHARYANTO) - File::Flock: Shut up perl warning when unlocking a closed filehandle (usually should be harmless, can happen during DESTROY on error/die). 0.33 2012-12-26 (SHARYANTO) - File::Flock: Forgot to add $VERSION. 0.32 2012-12-25 (SHARYANTO) - File::Flock: stat after open() [suggested by Pavel Shaydo] 0.31 2012-12-25 (SHARYANTO) Merry Christmas! - Add module: SHARYANTO::File::Flock. 0.30 2012-10-02 (SHARYANTO) No functional changes. Fix file_util.t due to failure report by Aaron Holmgren. 0.29 2012-09-13 (SHARYANTO) - Add module: SHARYANTO::Scalar::Util. 0.28 2012-09-07 (SHARYANTO) - Proc::ChildError: explain_child_error(): Include error message $!, add tests. 0.27 2012-08-27 (SHARYANTO) - File::Util: add function: dir_empty(). 0.26 2012-08-24 (SHARYANTO) - File::Util: add function: l_abs_path(). 0.25 2012-07-27 (SHARYANTO) - Add module: SHARYANTO::Log::Util. 0.24 2012-07-27 (SHARYANTO) - Add module: SHARYANTO::File::Util. 0.23 2012-07-17 (SHARYANTO) - Package::Util: Handle constants. 0.22 2012-06-14 (SHARYANTO) No functional changes. - Proc::Daemon::Prefork: 'pid_path' argument is not required unless we daemonize. 0.21 2012-03-29 (SHARYANTO) No functional changes. Add missing dependency to Moo [CT]. 0.20 2012-03-29 (SHARYANTO) [ENHANCEMENTS] - Package::Util: Add list_package_contents() & list_subpackages(). 0.19 2012-03-28 (SHARYANTO) [FIXES] - Small sprintf() fix for Proc::ChildError. 0.18 2012-03-23 (SHARYANTO) No functional changes. Split SHARYANTO::String::Util to its own dist to avoid circular dependency problem with Perinci-Object. 0.17 2012-03-21 (SHARYANTO) [FIXES] - Some fixes to Role::I18Many 0.16 2012-03-20 (SHARYANTO) [ENHANCEMENTS] - Add role: SHARYANTO::Role::I18NMany - Add module: SHARYANTO::String::Util [FIXES] - dzil: Add missing dependency to Log::Any 0.15 2012-03-16 (SHARYANTO) No functional changes. Add dependencies to Locale::Maketext{,::Lexicon} for Role::I18N users. 0.14 2012-03-15 (SHARYANTO) [INCOMPATIBLE CHANGES] - Change (split) SHARYANTO::Doc::Base base class into SHARYANTO::Role::{Doc::Section,I18N,I18NRinci}. 0.13 2012-03-14 (SHARYANTO) Add SHARYANTO::Doc::Base. 0.12 2012-03-06 (SHARYANTO) Add SHARYANTO::Package::Util. 0.11 2012-03-01 (SHARYANTO) Array::Util: allow haystack to be a single string (assumed to be a regex), document that haystack can also be a list of regexes. Updated metadata to 1.1. 0.10 2011-09-29 (SHARYANTO) Add SHARYANTO::HTTP::DetectUA::Simple. 0.09 2011-09-29 (SHARYANTO) Proc::Daemon::Prefork: Add 'on_client_disconnect' option. 0.08 2011-09-22 (SHARYANTO) No functional changes. Rebuild dist with newer Sub::Spec::To::Pod. 0.07 2011-09-22 (SHARYANTO) Array::Util: Add alias function match_regex_or_array, add sub specs. 0.06 2011-09-22 (SHARYANTO) Add SHARYANTO::Array::Util. 0.05 2011-08-05 (SHARYANTO) - Proc::Daemon::Prefork: 'access_log_path' and 'error_log_path' are now optional. 0.04 2011-07-19 (SHARYANTO) [INCOMPATIBLE CHANGES] - Proc::Daemon::Prefork: Rename 'run_as_root' to 'require_root' (less ambiguity), now defaults to 0. 0.03 2011-07-08 (SHARYANTO) [INCOMPATIBLE CHANGES] - Rename SHARYANTO::Proc::Daemon{,::Prefork} 0.02 2011-07-05 (SHARYANTO) [ENHANCEMENTS] - Proc::Daemon: add max_children(), can autoadjust number of processes from prefork() to max_children() according to load. 0.01 2011-06-17 (SHARYANTO) First release. SHARYANTO-Utils-0.53/dist.ini0000644000175000017500000000230512176106301013200 0ustar s1s1version = 0.53 name = SHARYANTO-Utils author = Steven Haryanto license = Perl_5 copyright_holder = Steven Haryanto [MetaResources] homepage = http://search.cpan.org/dist/SHARYANTO-Utils/ repository = http://github.com/sharyanto/perl-SHARYANTO-Utils [@SHARYANTO] [Prereqs / TestRequires] File::chdir=0 Test::Exception=0 Test::More=0.98 [Prereqs] ;!lint-prereqs assume-used # spec Rinci=1.1.0 ; for runtime perl=5.010001 experimental=0 Data::Clone=0 Log::Any=0 ; for SHARYANTO::Data::Util Data::Structure::Util=0 ; for SHARYANTO::HTML::Extract::ImageLinks HTML::Parser=0 URI::URL=0 ; for SHARYANTO::Proc::Daemon::Prefork File::Which=0 Parse::Netstat=0 ; for SHARYANTO::Role::Doc Moo::Role=0 ; for SHARYANTO::Role::I18N and most of its users ;!lint-prereqs assume-used # convenience Locale::Maketext::Lexicon=0 ; for SHARYANTO::Role::I18NRinci Perinci::Object=0.07 ; for SHARYANTO::Template::Util File::Slurp=0 Template::Tiny=0 ; for SHARYANTO::Text::Prompt ; for SHARYANTO::YAML::Any YAML::Syck=0 ; i wanted to exclude some modules from podweaver, doesn't work ;[FileFinder::ByName / NonDzilModules] ;dir = lib ;skip = YAML_*.pm ; ;[PodWeaver] ;finder = :NonDzilModules SHARYANTO-Utils-0.53/LICENSE0000644000175000017500000004366412176106301012556 0ustar s1s1This software is copyright (c) 2013 by Steven Haryanto. 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) 2013 by Steven Haryanto. 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. Copyright (C) 19yy 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. , 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) 2013 by Steven Haryanto. 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 SHARYANTO-Utils-0.53/t/0000755000175000017500000000000012176106301011777 5ustar s1s1SHARYANTO-Utils-0.53/t/00-compile.t0000644000175000017500000000312612176106301014033 0ustar s1s1#!perl use strict; use warnings; use Test::More; use File::Find; use File::Temp qw{ tempdir }; my @modules; find( sub { return if $File::Find::name !~ /\.pm\z/; my $found = $File::Find::name; $found =~ s{^lib/}{}; $found =~ s{[/\\]}{::}g; $found =~ s/\.pm$//; # nothing to skip push @modules, $found; }, 'lib', ); sub _find_scripts { my $dir = shift @_; my @found_scripts = (); find( sub { return unless -f; my $found = $File::Find::name; # nothing to skip open my $FH, '<', $_ or do { note( "Unable to open $found in ( $! ), skipping" ); return; }; my $shebang = <$FH>; return unless $shebang =~ /^#!.*?\bperl\b\s*$/; push @found_scripts, $found; }, $dir, ); return @found_scripts; } my @scripts; do { push @scripts, _find_scripts($_) if -d $_ } for qw{ bin script scripts }; my $plan = scalar(@modules) + scalar(@scripts); $plan ? (plan tests => $plan) : (plan skip_all => "no tests to run"); { # fake home for cpan-testers # no fake requested ## local $ENV{HOME} = tempdir( CLEANUP => 1 ); like( qx{ $^X -Ilib -e "require $_; print '$_ ok'" }, qr/^\s*$_ ok/s, "$_ loaded ok" ) for sort @modules; SKIP: { eval "use Test::Script 1.05; 1;"; skip "Test::Script needed to test script compilation", scalar(@scripts) if $@; foreach my $file ( @scripts ) { my $script = $file; $script =~ s!.*/!!; script_compiles( $file, "$script script compiles" ); } } } SHARYANTO-Utils-0.53/t/log_util.t0000644000175000017500000000047012176106301014003 0ustar s1s1#!perl -T use 5.010; use strict; use warnings; use experimental 'smartmatch'; use Test::More 0.96; use SHARYANTO::Log::Util qw(@log_levels $log_levels_re); ok('warn' ~~ @log_levels); ok('debug' =~ $log_levels_re); ok('foo' !~~ @log_levels); ok('foo' !~ $log_levels_re); DONE_TESTING: done_testing(); SHARYANTO-Utils-0.53/t/package_util.t0000644000175000017500000000335712176106301014624 0ustar s1s1#!perl -T use 5.010; use strict; use warnings; use SHARYANTO::Package::Util qw( package_exists list_package_contents list_subpackages ); use Test::More 0.96; BEGIN { ok(!package_exists("cps61kDkaNlLTrdXC91"), "package_exists 1"); } package cps61kDkaNlLTrdXC91; our $A = 1; our @A = (); our %A = (); our $B = undef; sub A {} #our *C; package main; ok( package_exists("cps61kDkaNlLTrdXC91"), "package_exists 1b"); package cps61kDkaNlLTrdXC92::cps61kDkaNlLTrdXC93; package cps61kDkaNlLTrdXC92::cps61kDkaNlLTrdXC93::cps61kDkaNlLTrdXC94; package main; ok( package_exists("cps61kDkaNlLTrdXC92"), "package_exists 2"); ok( package_exists("cps61kDkaNlLTrdXC92::cps61kDkaNlLTrdXC93"), "package_exists 3"); my %res = list_package_contents("cps61kDkaNlLTrdXC91"); %res = map {$_ => ref($res{$_})} keys %res; #diag explain \%res; is_deeply(\%res, { '$A' => 'SCALAR', '%A' => 'HASH', '*B' => '', '@A' => 'ARRAY', 'A' => 'CODE' }, "list_package_contents 1" ); is_deeply([list_subpackages("cps61kDkaNlLTrdXC92")], ["cps61kDkaNlLTrdXC92::cps61kDkaNlLTrdXC93"], "list_subpackages 1"); is_deeply([list_subpackages("cps61kDkaNlLTrdXC92")], ["cps61kDkaNlLTrdXC92::cps61kDkaNlLTrdXC93"], "list_subpackages 1"); is_deeply([list_subpackages("cps61kDkaNlLTrdXC92", 1)], [ "cps61kDkaNlLTrdXC92::cps61kDkaNlLTrdXC93", "cps61kDkaNlLTrdXC92::cps61kDkaNlLTrdXC93::cps61kDkaNlLTrdXC94", ], "list_subpackages 2"); DONE_TESTING: done_testing(); SHARYANTO-Utils-0.53/t/array_util.t0000644000175000017500000000167012176106301014343 0ustar s1s1#!perl -T use 5.010; use strict; use warnings; use Test::More 0.96; use SHARYANTO::Array::Util qw(match_array_or_regex match_regex_or_array); ok( match_array_or_regex("foo", [qw/foo bar baz/]), "match array 1"); ok(!match_array_or_regex("qux", [qw/foo bar baz/]), "match array 2"); ok( match_array_or_regex("foo", ["foo", qr/bar/]), "match array with regex 1"); ok( match_array_or_regex("bar", ["foo", qr/ba./]), "match array with regex 2"); ok(!match_array_or_regex("qux", ["foo", qr/bar/]), "match array with regex 3"); ok( match_array_or_regex("foo", "foo"), "match regex 0"); ok( match_array_or_regex("foo", qr/foo?/), "match regex 1"); ok(!match_array_or_regex("qux", qr/foo?/), "match regex 2"); eval { match_array_or_regex("foo", {}) }; my $eval_err = $@; ok($eval_err, "match invalid -> dies"); ok( match_regex_or_array("foo", qr/foo?/), "alias 1"); ok(!match_array_or_regex("qux", qr/foo?/), "alias 2"); DONE_TESTING: done_testing(); SHARYANTO-Utils-0.53/t/color_util.t0000644000175000017500000000317012176106301014340 0ustar s1s1#!perl use 5.010; use strict; use warnings; use SHARYANTO::Color::Util qw( mix_2_rgb_colors rand_rgb_color rgb2grayscale rgb2sepia reverse_rgb_color rgb_luminance tint_rgb_color ); use Test::More 0.98; subtest mix_2_rgb_colors => sub { is(mix_2_rgb_colors('#ff8800', '#0033cc'), '7f5d66'); is(mix_2_rgb_colors('ff8800', '0033cc', 0), 'ff8800'); is(mix_2_rgb_colors('FF8800', '0033CC', 1), '0033cc'); is(mix_2_rgb_colors('0033CC', 'FF8800', 0.75), 'bf7233'); is(mix_2_rgb_colors('0033CC', 'FF8800', 0.25), '3f4899'); }; subtest rand_rgb_color => sub { ok "currently not tested"; }; subtest rgb2grayscale => sub { is(rgb2grayscale('0033CC'), '555555'); }; subtest rgb2sepia => sub { is(rgb2sepia('0033CC'), '4d4535'); }; subtest reverse_rgb_color => sub { is(reverse_rgb_color('0033CC'), 'ffcc33'); }; subtest rgb_luminance => sub { ok(abs(0 - rgb_luminance('000000')) < 0.001); ok(abs(1 - rgb_luminance('ffffff')) < 0.001); ok(abs(0.6254 - rgb_luminance('d090aa')) < 0.001); }; subtest tint_rgb_color => sub { is(tint_rgb_color('#ff8800', '#0033cc'), 'b36e3c'); is(tint_rgb_color('ff8800', '0033cc', 0), 'ff8800'); is(tint_rgb_color('FF8800', '0033CC', 1), '675579'); is(tint_rgb_color('0033CC', 'FF8800', 0.75), '263fad'); is(tint_rgb_color('0033CC', 'FF8800', 0.25), '0c37c1'); }; DONE_TESTING: done_testing(); SHARYANTO-Utils-0.53/t/release-pod-coverage.t0000644000175000017500000000076512176106301016165 0ustar s1s1#!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } use Test::More; eval "use Test::Pod::Coverage 1.08"; plan skip_all => "Test::Pod::Coverage 1.08 required for testing POD coverage" if $@; eval "use Pod::Coverage::TrustPod"; plan skip_all => "Pod::Coverage::TrustPod required for testing POD coverage" if $@; all_pod_coverage_ok({ coverage_class => 'Pod::Coverage::TrustPod' }); SHARYANTO-Utils-0.53/t/file_util.t0000644000175000017500000000467712176106301014156 0ustar s1s1#!perl use 5.010; use strict; use warnings; use Cwd qw(abs_path); use File::chdir; use File::Slurp; use File::Spec; use Test::More 0.96; plan skip_all => "symlink() not available" unless eval { symlink "", ""; 1 }; use File::Temp qw(tempfile tempdir); use SHARYANTO::File::Util qw(file_exists l_abs_path dir_empty); subtest file_exists => sub { my ($fh1, $target) = tempfile(); my ($fh2, $symlink) = tempfile(); ok(file_exists($target), "existing file"); unlink($symlink); symlink($target, $symlink); ok(file_exists($symlink), "symlink to existing file"); unlink($target); ok(!file_exists($target), "non-existing file"); ok(file_exists($symlink), "symlink to non-existing file"); unlink($symlink); }; subtest l_abs_path => sub { my $dir = abs_path(tempdir(CLEANUP=>1)); local $CWD = $dir; mkdir("tmp"); write_file("tmp/file", ""); symlink("file", "tmp/symfile"); symlink("$dir/tmp", "tmp/symdir"); symlink("not_exists", "tmp/symnef"); # non-existing file symlink("/not_exists".rand()."/1", "tmp/symnep"); # non-existing path is( abs_path("tmp/file" ), "$dir/tmp/file" , "abs_path file"); is(l_abs_path("tmp/file" ), "$dir/tmp/file" , "l_abs_path file"); is( abs_path("tmp/symfile"), "$dir/tmp/file" , "abs_path symfile"); is(l_abs_path("tmp/symfile"), "$dir/tmp/symfile", "l_abs_path symfile"); is( abs_path("tmp/symdir" ), "$dir/tmp" , "abs_path symdir"); is(l_abs_path("tmp/symdir" ), "$dir/tmp/symdir" , "l_abs_path symdir"); is( abs_path("tmp/symnef" ), "$dir/tmp/not_exists", "abs_path symnef"); is(l_abs_path("tmp/symnef" ), "$dir/tmp/symnef" , "l_abs_path symnef"); ok(! abs_path("tmp/symnep" ), "abs_path symnep"); is(l_abs_path("tmp/symnep" ), "$dir/tmp/symnep" , "l_abs_path symnep"); }; subtest dir_empty => sub { my $dir = tempdir(CLEANUP=>1); local $CWD = $dir; mkdir "empty", 0755; mkdir "hasfiles", 0755; write_file("hasfiles/1", ""); mkdir "hasdotfiles", 0755; write_file("hasdotfiles/.1", ""); mkdir "hasdotdirs", 0755; mkdir "hasdotdirs/.1"; mkdir "unreadable", 0000; ok( dir_empty("empty"), "empty"); ok(!dir_empty("doesntexist"), "doesntexist"); ok(!dir_empty("hasfiles"), "hasfiles"); ok(!dir_empty("hasdotfiles"), "hasdotfiles"); ok(!dir_empty("hasdotdirs"), "hasdotdirs"); ok(!dir_empty("unreadable"), "unreadable"); }; DONE_TESTING: done_testing(); SHARYANTO-Utils-0.53/t/proc_childerror.t0000644000175000017500000000113312176106301015342 0ustar s1s1#!perl use 5.010; use strict; use warnings; use Test::More 0.96; plan skip_all => "Unix only" if $^O =~ /MSWin32/; use SHARYANTO::Proc::ChildError qw(explain_child_error); like(explain_child_error(-1), qr/^failed to execute: \(-1\)/); system "/tmp/ad5f9c00-bcad-d597-cce7-dc602c67546d"; like(explain_child_error(), qr/^failed to execute: \S.+ \(-1\)/); like(explain_child_error(3), qr/^died with signal 3, without coredump$/); like(explain_child_error(3|128), qr/^died with signal 3, with coredump$/); like(explain_child_error(256), qr/^exited with code 1$/); DONE_TESTING: done_testing(); SHARYANTO-Utils-0.53/t/release-pod-syntax.t0000644000175000017500000000045012176106301015707 0ustar s1s1#!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } use Test::More; eval "use Test::Pod 1.41"; plan skip_all => "Test::Pod 1.41 required for testing POD" if $@; all_pod_files_ok(); SHARYANTO-Utils-0.53/t/data_oldutil.t0000644000175000017500000000121512176106301014630 0ustar s1s1#!perl use 5.010; use strict; use warnings; use Test::More 0.98; use SHARYANTO::Data::OldUtil qw( has_circular_ref ); subtest has_circular_ref => sub { ok(!has_circular_ref(undef), "undef"); ok(!has_circular_ref("x"), "x"); ok(!has_circular_ref([]), "[]"); ok(!has_circular_ref([[], []]), "[[], []]"); my $a; $a = []; push @$a, $a; ok( has_circular_ref($a), "circ array 1"); my $b = [1]; $a = [$b, $b]; ok( has_circular_ref($a), "circ array 2"); $a = {k1=>$b, k2=>$b}; ok( has_circular_ref($a), "circ hash 1"); }; DONE_TESTING: done_testing; SHARYANTO-Utils-0.53/t/number_util.t0000644000175000017500000000133212176106301014510 0ustar s1s1#!perl -T use 5.010; use strict; use warnings; use Test::More 0.96; use SHARYANTO::Number::Util qw(format_metric); local $ENV{LANG} = "C"; is(format_metric(1.23 , {precision=>1} ), "1.2" , "precision 1"); is(format_metric(1.23 , {precision=>3} ), "1.230" , "precision 2"); is(format_metric(1.23e3 , {base=>10} ), "1.2ki" , "base 10 1"); is(format_metric(1.23e9 , {base=> 2} ), "1.1G" , "base 2 1"); is(format_metric(1.23e3 , {base=>10, i_mark=>0}), "1.2k" , "i_mark=0"); is(format_metric(1.23e-1 , {base=>10} ), "123.0m", "number smaller than 1 1"); is(format_metric(-1.23e-2, {base=>10} ), "-12.3m", "number smaller than 1 1"); DONE_TESTING: done_testing(); SHARYANTO-Utils-0.53/t/scalar_util.t0000644000175000017500000000236312176106301014472 0ustar s1s1#!perl -T use 5.010; use strict; use warnings; use Test::More 0.96; use SHARYANTO::Scalar::Util qw(looks_like_int looks_like_float looks_like_real); my @ints = (0, 1, -1, "1", "-1", "1111111111111111111111111111111111111111", "-1111111111111111111111111111111111111111"); my @floats = (1.1, -1.1, 1.11e1, -1.11e1, "1.1", "-1.1", "1e10", "-1e10", "1e-1000", "-1e-1000", "11111111111111111111111111111111111111.1", "-11111111111111111111111111111111111111.1", "Inf", "-Inf", "Infinity", "-Infinity", "NaN", "-nan",); my @nonnums = ("", " ", "123a", "1e", "-", "+", "abc"); ok( looks_like_int($_), "looks_like_int($_)=1") for @ints; ok(!looks_like_int($_), "looks_like_int($_)=0") for @floats; ok(!looks_like_int($_), "looks_like_int($_)=0") for @nonnums; ok(!looks_like_float($_), "looks_like_float($_)=0") for @ints; ok( looks_like_float($_), "looks_like_float($_)=1") for @floats; ok(!looks_like_float($_), "looks_like_float($_)=0") for @nonnums; ok( looks_like_real($_), "looks_like_real($_)=1") for @ints; ok( looks_like_real($_), "looks_like_real($_)=1") for @floats; ok(!looks_like_real($_), "looks_like_real($_)=0") for @nonnums; DONE_TESTING: done_testing(); SHARYANTO-Utils-0.53/t/file_flock.t0000644000175000017500000000327212176106301014265 0ustar s1s1#!perl use 5.010; use strict; use warnings; use Cwd qw(abs_path); use File::chdir; use File::Slurp; use File::Spec; use Test::More 0.96; use File::Temp qw(tempdir); use SHARYANTO::File::Flock; plan skip_all => 'Not tested on Windows yet' if $^O =~ /win32/i; my $dir = abs_path(tempdir(CLEANUP=>1)); $CWD = $dir; subtest "create (unlocked)" => sub { ok(!(-f "f1"), "f1 doesn't exist before lock"); my $lock = SHARYANTO::File::Flock->lock("f1"); ok((-f "f1"), "f1 exists after lock"); $lock->unlock; ok(!(-f "f1"), "f1 doesn't exist after unlock"); }; subtest "create (destroyed)" => sub { ok(!(-f "f1"), "f1 doesn't exist before lock"); my $lock = SHARYANTO::File::Flock->lock("f1"); ok((-f "f1"), "f1 exists after lock"); undef $lock; ok(!(-f "f1"), "f1 doesn't exist after DESTROY"); }; subtest "already exists" => sub { write_file("f1", ""); ok((-f "f1"), "f1 exists before lock"); my $lock = SHARYANTO::File::Flock->lock("f1"); ok((-f "f1"), "f1 exists after lock"); undef $lock; ok((-f "f1"), "f1 still exists after DESTROY"); unlink "f1"; }; subtest "was created, but not empty" => sub { ok(!(-f "f1"), "f1 doesn't exist before lock"); my $lock = SHARYANTO::File::Flock->lock("f1"); ok((-f "f1"), "f1 exists after lock"); { open my $f1, ">>", "f1"; print $f1 "a"; close $f1 } undef $lock; ok((-f "f1"), "f1 still exists after DESTROY"); }; DONE_TESTING: done_testing(); if (Test::More->builder->is_passing) { diag "all tests successful, deleting test data dir"; $CWD = "/"; } else { # don't delete test data dir if there are errors diag "there are failing tests, not deleting test data dir $dir"; } SHARYANTO-Utils-0.53/t/release-rinci.t0000644000175000017500000000050412176106301014705 0ustar s1s1#!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } use Test::More; eval "use Test::Rinci 0.01"; plan skip_all => "Test::Rinci 0.01 required for testing Rinci metadata" if $@; metadata_in_all_modules_ok(); SHARYANTO-Utils-0.53/t/detect_http_ua_simple.t0000644000175000017500000000672312176106301016541 0ustar s1s1#!perl -T use 5.010; use strict; use warnings; use Test::More 0.96; use SHARYANTO::HTTP::DetectUA::Simple qw(detect_http_ua_simple); my @tests = ( # ff {env=>{HTTP_USER_AGENT=>'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.12011-10-16 20:23:00'}, gui=>1}, {env=>{HTTP_USER_AGENT=>'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6'}, gui=>1}, # ie {env=>{HTTP_USER_AGENT=>'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'}, gui=>1}, # opera {env=>{HTTP_USER_AGENT=>'Opera/9.20 (Windows NT 6.0; U; en)'}, gui=>1}, # chrome {env=>{HTTP_USER_AGENT=>'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/18.6.872.0 Safari/535.2 UNTRUSTED/1.0 3gpp-gba UNTRUSTED/1.0'}, gui=>1}, # mobile/tablet {env=>{HTTP_USER_AGENT=>'Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:50'}, gui=>1}, {env=>{HTTP_USER_AGENT=>'Mozilla/5.0 (Linux; U; Android 2.3.4; en-us; DROID BIONIC Build/5.5.1_84_DBN-55) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'}, gui=>1}, {env=>{HTTP_USER_AGENT=>'BlackBerry9530/4.7.0.76 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/126'}, gui=>1}, {env=>{HTTP_USER_AGENT=>'User-Agent: Opera/9.80 (J2ME/MIDP; Opera Mini/6.1.25378/25.692; U; en) Presto/2.5.25 Version/10.54'}, gui=>1}, # opera mini {env=>{HTTP_USER_AGENT=>'Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; NOKIA; Lumia 800)'}, gui=>1}, {env=>{HTTP_USER_AGENT=>'NokiaN90-1/3.0545.5.1 Series60/2.8 Profile/MIDP-2.0 Configuration/CLDC-1.1'}, gui=>1}, # GENERIC gui {env=>{HTTP_ACCEPT=>'text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1'}, gui=>1}, # text {env=>{HTTP_USER_AGENT=>'Links (2.5; Linux 3.2.0-1-amd64 x86_64; GNU C 4.6.2;OC text)'}, text=>1}, {env=>{HTTP_USER_AGENT=>'ELinks/0.9.3 (textmode; Linux 2.6.11 i686; 79x24)'}, text=>1}, {env=>{HTTP_USER_AGENT=>'Lynx/2.8.8dev.9 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/2.12.14'}, text=>1}, {env=>{HTTP_USER_AGENT=>'w3m/0.5.1'}, text=>1}, # NEITHER {env=>{HTTP_USER_AGENT=>'Googlebot/2.1 ( http://www.googlebot.com/bot.html) '}}, {env=>{HTTP_USER_AGENT=>'curl/7.23.1 (x86_64-pc-linux-gnu) libcurl/7.23.1 OpenSSL/1.0.0f zlib/1.2.3.4 libidn/1.23 libssh2/1.2.8 librtmp/2.3'}}, {env=>{HTTP_ACCEPT=>'*/*'}}, ); test_detect(%$_) for @tests; DONE_TESTING: done_testing; sub test_detect { my %args = @_; my $env = $args{env}; my $tname = $args{name} // ($env->{HTTP_USER_AGENT} ? "User-Agent $env->{HTTP_USER_AGENT}" : undef) // "Accept $env->{HTTP_ACCEPT}"; subtest $tname => sub { my $res; eval { $res = detect_http_ua_simple($env) }; ok(!$@, "doesnt die"); if ($args{gui}) { ok($res->{is_gui_browser}, "gui"); } else { ok(!$res->{is_gui_browser}, "not gui"); } if ($args{text}) { ok($res->{is_text_browser}, "text browser"); } else { ok(!$res->{is_text_browser}, "not text browser"); } if ($args{gui} || $args{text}) { ok($res->{is_browser}, "browser"); } else { ok(!$res->{is_browser}, "not browser"); } done_testing; }; } SHARYANTO-Utils-0.53/t/hash_util.t0000644000175000017500000000070012176106301014141 0ustar s1s1#!perl -T use 5.010; use strict; use warnings; use Test::Exception; use Test::More 0.96; use SHARYANTO::Hash::Util qw(rename_key); subtest "rename_key" => sub { my %h = (a=>1, b=>2); dies_ok { rename_key(\%h, "c", "d") }, "old key doesn't exist -> die"; dies_ok { rename_key(\%h, "a", "b") }, "new key exists -> die"; rename_key(\%h, "a", "a2"); is_deeply(\%h, {a2=>1, b=>2}, "success 1"); }; DONE_TESTING: done_testing(); SHARYANTO-Utils-0.53/t/getopt_long_util.t0000644000175000017500000000067412176106301015551 0ustar s1s1#!perl use 5.010; use strict; use warnings; use SHARYANTO::Getopt::Long::Util qw( gospec2human ); use Test::More 0.98; subtest gospec2human => sub { is(gospec2human('help|h|?'), '--help, -h, -?'); is(gospec2human('foo=s'), '--foo=s'); is(gospec2human('--foo=s'), '--foo=s'); is(gospec2human('foo|bar=s'), '--foo=s, --bar=s'); }; DONE_TESTING: done_testing(); SHARYANTO-Utils-0.53/t/data_util.t0000644000175000017500000000121712176106301014133 0ustar s1s1#!perl use 5.010; use strict; use warnings; use Test::More 0.98; use SHARYANTO::Data::Util qw( clone_circular_refs ); subtest clone_circular_refs => sub { ok(clone_circular_refs(undef), "undef"); ok(clone_circular_refs("x"), "x"); ok(clone_circular_refs([]), "[]"); ok(clone_circular_refs([[], []]), "[[], []]"); my $b = []; my $a = [$b, $b, $b]; ok(clone_circular_refs($a), "circ 1 status"); is_deeply($a, [[], [], []], "circ 1 result"); my $a; $a = [1]; push @$a, $a; ok(!clone_circular_refs($a), "circ 2 status"); }; DONE_TESTING: done_testing; SHARYANTO-Utils-0.53/weaver.ini0000644000175000017500000000001512176106301013522 0ustar s1s1[@SHARYANTO] SHARYANTO-Utils-0.53/MANIFEST0000644000175000017500000000237412176106301012673 0ustar s1s1Build.PL Changes LICENSE MANIFEST MANIFEST.SKIP META.json META.yml README dist.ini lib/SHARYANTO/Array/Util.pm lib/SHARYANTO/Color/Util.pm lib/SHARYANTO/Data/OldUtil.pm lib/SHARYANTO/Data/Util.pm lib/SHARYANTO/File/Flock.pm lib/SHARYANTO/File/Util.pm lib/SHARYANTO/Getopt/Long/Util.pm lib/SHARYANTO/HTML/Extract/ImageLinks.pm lib/SHARYANTO/HTTP/DetectUA/Simple.pm lib/SHARYANTO/Hash/Util.pm lib/SHARYANTO/Log/Util.pm lib/SHARYANTO/Number/Util.pm lib/SHARYANTO/Package/Util.pm lib/SHARYANTO/Proc/ChildError.pm lib/SHARYANTO/Proc/Daemon/Prefork.pm lib/SHARYANTO/Proc/Util.pm lib/SHARYANTO/Role/Doc/Section.pm lib/SHARYANTO/Role/Doc/Section/AddTextLines.pm lib/SHARYANTO/Role/I18N.pm lib/SHARYANTO/Role/I18NMany.pm lib/SHARYANTO/Role/I18NRinci.pm lib/SHARYANTO/Scalar/Util.pm lib/SHARYANTO/Template/Util.pm lib/SHARYANTO/Text/Prompt.pm lib/SHARYANTO/Utils.pm lib/SHARYANTO/YAML/Any.pm lib/SHARYANTO/YAML/Any_SyckOnly.pm lib/SHARYANTO/YAML/Any_YAMLAny.pm t/00-compile.t t/array_util.t t/color_util.t t/data_oldutil.t t/data_util.t t/detect_http_ua_simple.t t/file_flock.t t/file_util.t t/getopt_long_util.t t/hash_util.t t/log_util.t t/number_util.t t/package_util.t t/proc_childerror.t t/release-pod-coverage.t t/release-pod-syntax.t t/release-rinci.t t/scalar_util.t weaver.ini SHARYANTO-Utils-0.53/META.json0000644000175000017500000000361012176106301013155 0ustar s1s1{ "abstract" : "SHARYANTO's temporary namespace for various routines", "author" : [ "Steven Haryanto " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 4.300035, CPAN::Meta::Converter version 2.131560", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "SHARYANTO-Utils", "prereqs" : { "build" : { "requires" : { "Module::Build" : "0.3601" } }, "configure" : { "requires" : { "Module::Build" : "0.3601" } }, "develop" : { "requires" : { "Pod::Coverage::TrustPod" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "Test::Rinci" : "0.01" } }, "runtime" : { "requires" : { "Data::Clone" : "0", "Data::Structure::Util" : "0", "File::Slurp" : "0", "File::Which" : "0", "HTML::Parser" : "0", "Locale::Maketext::Lexicon" : "0", "Log::Any" : "0", "Moo::Role" : "0", "Parse::Netstat" : "0", "Perinci::Object" : "0.07", "Rinci" : "v1.1.0", "Template::Tiny" : "0", "URI::URL" : "0", "YAML::Syck" : "0", "experimental" : "0", "perl" : "5.010001" } }, "test" : { "requires" : { "File::chdir" : "0", "Test::Exception" : "0", "Test::More" : "0.98" } } }, "release_status" : "stable", "resources" : { "homepage" : "http://search.cpan.org/dist/SHARYANTO-Utils/", "repository" : { "url" : "http://github.com/sharyanto/perl-SHARYANTO-Utils" } }, "version" : "0.53" } SHARYANTO-Utils-0.53/META.yml0000644000175000017500000000166712176106301013017 0ustar s1s1--- abstract: "SHARYANTO's temporary namespace for various routines" author: - 'Steven Haryanto ' build_requires: File::chdir: 0 Module::Build: 0.3601 Test::Exception: 0 Test::More: 0.98 configure_requires: Module::Build: 0.3601 dynamic_config: 0 generated_by: 'Dist::Zilla version 4.300035, CPAN::Meta::Converter version 2.131560' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 name: SHARYANTO-Utils requires: Data::Clone: 0 Data::Structure::Util: 0 File::Slurp: 0 File::Which: 0 HTML::Parser: 0 Locale::Maketext::Lexicon: 0 Log::Any: 0 Moo::Role: 0 Parse::Netstat: 0 Perinci::Object: 0.07 Rinci: v1.1.0 Template::Tiny: 0 URI::URL: 0 YAML::Syck: 0 experimental: 0 perl: 5.010001 resources: homepage: http://search.cpan.org/dist/SHARYANTO-Utils/ repository: http://github.com/sharyanto/perl-SHARYANTO-Utils version: 0.53