blib/lib/XAS/Utils.pm untested

filter: Statementstmt 0.0% 0 / 256 Branchbran 0.0% 0 / 30 Conditioncond 0.0% 0 / 9 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 37 Podpod 0.0% 0 / 26 totaltotal 0.0% 0 / 358 CC 16 SCAR 21.6
CC
16
Cov
0%
spawn
42.0
_do_fork
12.0
init_module
12.0
CRAP 8.7
1 package XAS::Utils;
2  
3 our $VERSION = '0.04';
4  
5 use DateTime;
6 use Try::Tiny;
7 use XAS::Exception;
8 use DateTime::Format::Pg;
9 use Digest::MD5 'md5_hex';
10 use Params::Validate ':all';
11 use DateTime::Format::Strptime;
12 use POSIX qw(:sys_wait_h setsid);
13  
14 use XAS::Class
15 debug => 0,
16 version => $VERSION,
17 base => 'Badger::Utils XAS::Base',
18 constants => 'HASH ARRAY',
19 filesystem => 'Dir File',
20 constant => {
21 ERRMSG => 'invalid parameters passed from %s at line %s',
22 },
23 exports => {
24 all => 'db2dt dt2db trim ltrim rtrim daemonize hash_walk
25 load_module bool init_module load_module compress exitcode
26 kill_proc spawn _do_fork glob2regex dir_walk
27 env_store env_restore env_create env_parse env_dump
28 left right mid instr',
29 any => 'db2dt dt2db trim ltrim rtrim daemonize hash_walk
30 load_module bool init_module load_module compress exitcode
31 kill_proc spawn _do_fork glob2regex dir_walk
32 env_store env_restore env_create env_parse env_dump
33 left right mid instr',
34 tags => {
35 dates => 'db2dt dt2db',
36 env => 'env_store env_restore env_create env_parse env_dump',
37 modules => 'init_module load_module',
38 strings => 'trim ltrim rtrim compress left right mid instr',
39 process => 'daemonize spawn kill_proc exitcode _do_fork',
40 }
41 }
42 ;
43  
44 Params::Validate::validation_options(
45 on_fail => sub {
46 my $params = shift;
47 my $class = __PACKAGE__;
48 XAS::Base::validation_exception($params, $class);
49 }
50 );
51  
52 #use Data::Dumper;
53  
54 # ----------------------------------------------------------------------
55 # Public Methods
56 # ----------------------------------------------------------------------
57  
58 # recursively walk a HOH
59 sub hash_walk {
60  
61 my %p = validate(@_, {
62 -hash => { type => HASHREF },
63 -keys => { type => ARRAYREF },
64 -callback => { type => CODEREF },
65 });
66  
67 my $hash = $p{'-hash'};
68 my $key_list = $p{'-keys'};
69 my $callback = $p{'-callback'};
70  
71 while (my ($k, $v) = each %$hash) {
72  
73 # Keep track of the hierarchy of keys, in case
74 # our callback needs it.
75  
76 push(@$key_list, $k);
77  
78 if (ref($v) eq 'HASH') {
79  
80 # Recurse.
81  
82 hash_walk(-hash => $v, -keys => $key_list, -callback => $callback);
83  
84 } else {
85 # Otherwise, invoke our callback, passing it
86 # the current key and value, along with the
87 # full parentage of that key.
88  
89 $callback->($k, $v, $key_list);
90  
91 }
92  
93 pop(@$key_list);
94  
95 }
96  
97 }
98  
99 # recursively walk a directory structure
100 sub dir_walk {
101 my %p = validate_with(
102 params => \@_,
103 spec => {
104 -directory => { isa => 'Badger::Filesystem::Directory' },
105 -callback => { type => CODEREF },
106 -filter => { optional => 1, default => qr/.*/, callbacks => {
107 'must be a compiled regex' => sub {
108 return (ref shift() eq 'Regexp') ? 1 : 0;
109 }
110 }},
111 },
112 on_fail => sub {
113 my $param = shift;
114 my $class = (caller(1))[3];
115 XAS::Base::validation_exception($param, $class);
116 }
117 );
118  
119 my $folder = $p{'-directory'};
120 my $filter = $p{'-filter'};
121 my $callback = $p{'-callback'};
122  
123 my @files = grep ( $_->path =~ /$filter/, $folder->files() );
124 my @folders = $folder->dirs;
125  
126 foreach my $file (@files) {
127  
128 $callback->($file);
129  
130 }
131  
132 foreach my $folder (@folders) {
133  
134 dir_walk(-directory => $folder, -filter => $filter, -callback => $callback);
135  
136 }
137  
138 }
139  
140 # Perl trim function to remove whitespace from the start and end of the string
141 sub trim {
142 my $string = shift;
143  
144 $string =~ s/^\s+//;
145 $string =~ s/\s+$//;
146  
147 return $string;
148  
149 }
150  
151 # Left trim function to remove leading whitespace
152 sub ltrim {
153 my $string = shift;
154  
155 $string =~ s/^\s+//;
156  
157 return $string;
158  
159 }
160  
161 # Right trim function to remove trailing whitespace
162 sub rtrim {
163 my $string = shift;
164  
165 $string =~ s/\s+$//;
166  
167 return $string;
168  
169 }
170  
171 # replace multiple whitspace with a single space
172 sub compress {
173 my $string = shift;
174  
175 $string =~ s/\s+/ /gms;
176  
177 return $string;
178  
179 }
180  
181 # emulate Basics string function left()
182 sub left {
183 my $string = shift;
184 my $offset = shift;
185  
186 return substr($string, 0, $offset);
187  
188 }
189  
190 # emulate Basics string function right()
191 sub right {
192 my $string = shift;
193 my $offset = shift;
194  
195 return substr($string, -($offset));
196  
197 }
198  
199 # emulate Basics string function mid()
200 sub mid {
201 my $string = shift;
202 my $start = shift;
203 my $length = shift;
204  
205 return substr($string, $start - 1, $length);
206  
207 }
208  
209 # emulate Basics string function instr()
210 sub instr {
211 my $start = shift;
212 my $string = shift;
213 my $compare = shift;
214  
215 if ($start =~ /^[0-9\-]+/) {
216  
217 $start++;
218  
219 } else {
220  
221 $compare = $string;
222 $string = $start;
223 $start = 0;
224  
225 }
226  
227 return index($string, $compare, $start) + 1;
228  
229 }
230  
231 sub bool {
232 my $item = shift;
233  
234 my @truth = qw(yes true 1 0e0);
235 return grep {lc($item) eq $_} @truth;
236  
237 }
238  
239 sub spawn {
240  
241 my %p = validate(@_, {
242 -command => 1,
243 -timeout => { optional => 1, default => 0 },
244 });
245  
246 local $SIG{ALRM} = sub {
247 my $sig_name = shift;
248 die "$sig_name";
249 };
250  
251 my $kid;
252 my @output;
253  
254 defined( my $pid = open($kid, "-|" ) ) or do {
255  
256 my $ex = XAS::Exception->new(
257 info => "unable to fork, reason: $!",
258 type => 'xas.utils.spawn'
259 );
260  
261 $ex->throw;
262  
263 };
264  
265 if ($pid) {
266  
267 # parent
268  
269 try {
270  
271 alarm( $p{'-timeout'} );
272  
273 while (<$kid>) {
274  
275 chomp;
276 push @output, $_;
277  
278 }
279  
280 alarm(0);
281  
282 } catch {
283  
284 my $ex = $_;
285  
286 alarm(0);
287  
288 if ($ex =~ /alrm/i) {
289  
290 unless (kill_proc(-signal => 'TERM', -pid => $pid)) {
291  
292 unless (kill_proc(-signal => 'KILL', -pid => $pid)) {
293  
294 my $ex = Badger::Exception->new(
295 type => 'xas.utils.spawn',
296 info => 'unable to kill ' . $pid
297 );
298  
299 $ex->throw;
300  
301 }
302  
303 }
304  
305 } else {
306  
307 die $ex;
308  
309 }
310  
311 };
312  
313 } else {
314  
315 # child
316  
317 # set the child process to be a group leader, so that
318 # kill -9 will kill it and all its descendents
319  
320 setpgrp(0, 0);
321 exec $p{'-command'};
322 exit;
323  
324 }
325  
326 wantarray ? @output : join( "\n", @output );
327  
328 }
329  
330 sub kill_proc {
331  
332 my %p = validate(@_, {
333 -signal => 1,
334 -pid => 1,
335 });
336  
337 my $time = 10;
338 my $status = 0;
339 my $pid = $p{'-pid'};
340 my $signal = $p{'-signal'};
341  
342 kill($signal, $pid);
343  
344 do {
345  
346 sleep 1;
347 $status = waitpid($pid, WNOHANG);
348 $time--;
349  
350 } while ($time && not $status);
351  
352 return $status;
353  
354 }
355  
356 sub exitcode {
357  
358 my $rc = $? >> 8; # return code of command
359 my $sig = $? & 127; # signal it was killed with
360  
361 return $rc, $sig;
362  
363 }
364  
365 sub _do_fork {
366  
367 my $child = fork();
368  
369 unless (defined($child)) {
370  
371 my $ex = XAS::Exception->new(
372 type => 'xas.utils.daemonize',
373 info => "unable to fork, reason: $!"
374 );
375  
376 $ex->throw;
377  
378 }
379  
380 exit(0) if ($child);
381  
382 }
383  
384 sub daemonize {
385  
386 _do_fork(); # initial fork
387 setsid(); # become session leader
388 _do_fork(); # second fork to prevent aquiring a controlling terminal
389  
390 # change directory to a netural place and set the umask
391  
392 chdir('/');
393 umask(0);
394  
395 # redirect our standard file handles
396  
397 open(STDIN, '<', '/dev/null');
398 open(STDOUT, '>', '/dev/null');
399 open(STDERR, '>', '/dev/null');
400  
401 }
402  
403 sub db2dt {
404 my ($p) = shift;
405  
406 my $dt;
407 my $parser;
408  
409 if ($p =~ m/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/) {
410  
411 $parser = DateTime::Format::Strptime->new(
412 pattern => '%Y-%m-%d %H:%M:%S',
413 time_zone => 'local',
414 on_error => sub {
415 my ($obj, $err) = @_;
416 my $ex = XAS::Exception->new(
417 type => 'xas.utils.db2dt',
418 info => $err
419 );
420 $ex->throw;
421 }
422 );
423  
424 $dt = $parser->parse_datetime($p);
425  
426 } else {
427  
428 my ($package, $file, $line) = caller;
429 my $ex = XAS::Exception->new(
430 type => 'xas.utils.db2dt',
431 info => sprintf(ERRMSG, $package, $line)
432 );
433  
434 $ex->throw;
435  
436 }
437  
438 return $dt;
439  
440 }
441  
442 sub dt2db {
443 my ($p) = shift;
444  
445 my $ft;
446 my $parser;
447  
448 my $ref = ref($p);
449  
450 if ($ref && $p->isa('DateTime')) {
451  
452 $parser = DateTime::Format::Strptime->new(
453 pattern => '%Y-%m-%d %H:%M:%S',
454 time_zone => 'local',
455 on_error => sub {
456 my ($obj, $err) = @_;
457 my $ex = XAS::Exception->new(
458 type => 'xas.utils.dt2db',
459 info => $err
460 );
461 $ex->throw;
462 }
463 );
464  
465 $ft = $parser->format_datetime($p);
466  
467 } else {
468  
469 my ($package, $file, $line) = caller;
470 my $ex = XAS::Exception->new(
471 type => 'xas.utils.dt2db',
472 info => sprintf(ERRMSG, $package, $line)
473 );
474  
475 $ex->throw;
476  
477 }
478  
479 return $ft;
480  
481 }
482  
483 sub init_module {
484 my ($module, $params) = validate_pos(@_,
485 1,
486 {optional => 1, type => HASHREF}
487 );
488  
489 my $obj;
490 my @parts;
491 my $filename;
492  
493 $params = {} unless (defined($params));
494  
495 if ($module) {
496  
497 @parts = split("::", $module);
498 $filename = File(@parts);
499  
500 try {
501  
502 require $filename . '.pm';
503 $module->import();
504 $obj = $module->new($params);
505  
506 } catch {
507  
508 my $x = $_;
509 my $ex = Badger::Exception->new(
510 type => 'xas.utils.init_module',
511 info => $x
512 );
513  
514 $ex->throw;
515  
516 };
517  
518 } else {
519  
520 my $ex = Badger::Exception->new(
521 type => 'xas.utils.init_module',
522 info => 'no module was defined'
523 );
524  
525 $ex->throw;
526  
527 }
528  
529 return $obj;
530  
531 }
532  
533 sub load_module {
534 my $module = shift;
535  
536 my @parts;
537 my $filename;
538  
539 if ($module) {
540  
541 @parts = split("::", $module);
542 $filename = File(@parts);
543  
544 try {
545  
546 require $filename . '.pm';
547 $module->import();
548  
549 } catch {
550  
551 my $x = $_;
552 my $ex = XAS::Exception->new(
553 type => 'xas.utils.load_module',
554 info => $x
555 );
556  
557 $ex->throw;
558  
559 };
560  
561 } else {
562  
563 my $ex = XAS::Exception->new(
564 type => 'xas.utils.load_module',
565 info => 'no module was defined'
566 );
567  
568 $ex->throw;
569  
570 }
571  
572 }
573  
574 sub glob2regex {
575 my $globstr = shift;
576  
577 my %patmap = (
578 '*' => '.*',
579 '?' => '.',
580 '[' => '[',
581 ']' => ']',
582 );
583  
584 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
585  
586 return '^' . $globstr . '$';
587  
588 }
589  
590 sub env_store {
591  
592 my %env;
593  
594 while ((my $key, my $value) = each(%ENV)) {
595  
596 delete $ENV{$key};
597 $env{$key} = $value;
598  
599 }
600  
601 return \%env;
602  
603 }
604  
605 sub env_restore {
606 my $env = shift;
607  
608 while ((my $key, my $value) = each(%ENV)) {
609  
610 delete $ENV{$key};
611  
612 }
613  
614 while ((my $key, my $value) = each(%{$env})) {
615  
616 $ENV{$key} = $value;
617  
618 }
619  
620 }
621  
622 sub env_create {
623 my $env = shift;
624  
625 while ((my $key, my $value) = each(%{$env})) {
626  
627 $ENV{$key} = $value;
628  
629 }
630  
631 }
632  
633 sub env_parse {
634 my $env = shift;
635  
636 my ($key, $value, %env);
637 my @envs = split(';;', $env);
638  
639 foreach my $y (@envs) {
640  
641 ($key, $value) = split('=', $y);
642 $env{$key} = $value;
643  
644 }
645  
646 return \%env;
647  
648 }
649  
650 sub env_dump {
651  
652 my $env;
653  
654 while ((my $key, my $value) = each(%ENV)) {
655  
656 $env .= "$key=$value;;";
657  
658 }
659  
660 # remove the ;; at the end
661  
662 chop $env;
663 chop $env;
664  
665 return $env;
666  
667 }
668  
669 1;
670  
671 __END__
672  
673 =head1 NAME
674  
675 XAS::Utils - A Perl extension for the XAS environment
676  
677 =head1 SYNOPSIS
678  
679 use XAS::Class
680 version => '0.01',
681 base => 'XAS::Base',
682 utils => 'db2dt dt2db'
683 ;
684  
685 printf("%s\n", dt2db($dt));
686  
687 =head1 DESCRIPTION
688  
689 This module provides utility routines that can by loaded into your current
690 namespace.
691  
692 =head1 METHODS
693  
694 =head2 db2dt($datestring)
695  
696 This routine will take a date format of YYYY-MM-DD HH:MM:SS and convert it
697 into a DateTime object.
698  
699 =head2 dt2db($datetime)
700  
701 This routine will take a DateTime object and convert it into the following
702 string: YYYY-MM-DD HH:MM:SS
703  
704 =head2 trim($string)
705  
706 Trim the whitespace from the beginning and end of $string.
707  
708 =head2 ltrim($string)
709  
710 Trim the whitespace from the end of $string.
711  
712 =head2 rtrim($string)
713  
714 Trim the whitespace from the beginning of $string.
715  
716 =head2 compress($string)
717  
718 Reduces multiple whitespace to a single space in $string.
719  
720 =head2 left($string, $offset)
721  
722 Return the left chunk of $string up to $offset. Useful for porting
723 VBS code. Makes allowances that VBS strings are ones based while
724 Perls are zero based.
725  
726 =head2 right($string, $offset)
727  
728 Return the right chunk of $string starting at $offset. Useful for porting
729 VBS code. Makes allowances that VBS strings are ones based while Perls
730 are zero based.
731  
732 =head2 mid($string, $offset, $length)
733  
734 Return the chunk of $string starting at $offset for $length characters.
735 Useful for porting VBS code. Makes allowances that VBS strings are ones
736 based while Perls are zero based.
737  
738 =head2 instr($start, $string, $compare)
739  
740 Return the position in $string of $compare. You may offset within the
741 string with $start. Useful for porting VBS code. Makes allowances that
742 VBS strings are one based while Perls are zero based.
743  
744 =head2 spawn
745  
746 Run a cli command with timeout. Returns output from that command.
747  
748 =over 4
749  
750 =item B<-command>
751  
752 The command string to run.
753  
754 =item B<-timeout>
755  
756 An optional timeout in seconds. Default is none.
757  
758 =back
759  
760 =head2 exitcode
761  
762 Decodes Perls version of the exit code from a cli process. Returns two items.
763  
764 Example:
765  
766 my @output = spawn(-command => "ls -l");
767 my ($rc, $sig) = exitcode();
768  
769 =head2 daemonize
770  
771 Become a daemon. This will set the process as a session lead, change to '/',
772 clear the protection mask and redirect stdin, stdout and stderr to /dev/null.
773  
774 =head2 glob2regx($glob)
775  
776 This method will take a shell glob pattern and convert it into a Perl regex.
777 This also works with DOS/Windows wildcards.
778  
779 =over 4
780  
781 =item B<$glob>
782  
783 The wildcard to convert.
784  
785 =back
786  
787 =head2 hash_walk
788  
789 This routine will walk a HOH and does a callback on the key/values that are
790 found. It takes these parameters:
791  
792 =over 4
793  
794 =item B<-hash>
795  
796 The hashref of the HOH.
797  
798 =item B<-keys>
799  
800 An arrayref of the key levels.
801  
802 =item B<-callback>
803  
804 The routine to call with these parameters:
805  
806 =over 4
807  
808 =item B<$key>
809  
810 The current hash key.
811  
812 =item B<$value>
813  
814 The value of that key.
815  
816 =item B<$key_list>
817  
818 A list of the key depth.
819  
820 =back
821  
822 =back
823  
824 =head2 dir_walk
825  
826 This will walk a directory structure and execute a callback for the found
827 files. It takes these parameters:
828  
829 =over 4
830  
831 =item B<-directory>
832  
833 The root directory to start from.
834  
835 =item B<-filter>
836  
837 A compiled regex to compare files against.
838  
839 =item B<-callback>
840  
841 The callback to execute when matching files are found.
842  
843 =back
844  
845 =head2 init_module($module, $options)
846  
847 This routine will load and initialize a module. It takes one required parameter
848 and one optinal parameter.
849  
850 =over 4
851  
852 =item B<$module>
853  
854 The name of the module.
855  
856 =item B<$options>
857  
858 A hashref of optional options to use with the module.
859  
860 =back
861  
862 =head2 load_module($module)
863  
864 This routine will load a module.
865  
866 =over 4
867  
868 =item B<$module>
869  
870 The name of the module.
871  
872 =back
873  
874 =head2 env_store
875  
876 Remove all items from the $ENV variable and store them in a hash variable.
877  
878 Example:
879 my $env = env_store();
880  
881 =head2 env_restore
882  
883 Remove all items from $ENV variable and restore it back to a saved hash variable.
884  
885 Example:
886 env_restore($env);
887  
888 =head2 env_create
889  
890 Store all the items from a hash variable into the $ENV varable.
891  
892 Example:
893 env_create($env);
894  
895 =head2 env_parse
896  
897 Take a formated string and parse it into a hash variable. The string must have
898 this format: "item=value;;item2=value2";
899  
900 Example:
901 my $string = "item=value;;item2=value2";
902 my $env = env_parse($string);
903 env_create($env);
904  
905 =head2 env_dump
906  
907 Take the items from the current $ENV variable and create a formated string.
908  
909 Example:
910 my $string = env_dump();
911 my $env = env_create($string);
912  
913 =head1 SEE ALSO
914  
915 =over 4
916  
917 =item L<XAS|XAS>
918  
919 =item L<Badger::Utils|http://badgerpower.com/docs/Badger/Utils.html>
920  
921 =back
922  
923 =head1 AUTHOR
924  
925 Kevin L. Esteb, E<lt>kevin@kesteb.usE<gt>
926  
927 =head1 COPYRIGHT AND LICENSE
928  
929 Copyright (C) 2014 Kevin L. Esteb
930  
931 This library is free software; you can redistribute it and/or modify
932 it under the same terms as Perl itself, either Perl version 5.8.8 or,
933 at your option, any later version of Perl 5 you may have available.
934  
935 See L<http://dev.perl.org/licenses/> for more information.
936  
937 =cut