File Coverage

blib/lib/ProjectBuilder/Base.pm
Criterion Covered Total %
statement 36 196 18.3
branch 0 102 0.0
condition 0 84 0.0
subroutine 12 31 38.7
pod 19 19 100.0
total 67 432 15.5


line stmt bran cond sub pod time code
1             #!/usr/bin/perl -w
2             #
3             # Base subroutines brought by the the Project-Builder project
4             # which can be easily used by whatever perl project
5             #
6             # Copyright B. Cornec 2007-2012
7             # Eric Anderson's changes are (c) Copyright 2012 Hewlett Packard
8             # Provided under the GPL v2
9             #
10             # $Id$
11             #
12              
13             package ProjectBuilder::Base;
14              
15 2     2   1372 use strict;
  2         3  
  2         74  
16 2     2   1745 use lib qw (lib);
  2         1452  
  2         13  
17 2     2   258 use Carp qw/confess cluck/;
  2         8  
  2         150  
18 2     2   29 use Cwd;
  2         3  
  2         127  
19 2     2   10 use File::Path;
  2         4  
  2         130  
20 2     2   2145 use Data::Dumper;
  2         26718  
  2         172  
21 2     2   1795 use Time::localtime qw(localtime);
  2         16242  
  2         186  
22 2     2   1973 use English;
  2         9552  
  2         14  
23 2     2   4049 use POSIX qw(locale_h);
  2         17045  
  2         15  
24 2     2   5073 use ProjectBuilder::Version;
  2         5  
  2         98  
25              
26             # Inherit from the "Exporter" module which handles exporting functions.
27            
28 2     2   9 use vars qw($VERSION $REVISION @ISA @EXPORT);
  2         4  
  2         107  
29 2     2   11 use Exporter;
  2         2  
  2         8189  
30            
31             # Export, by default, all the functions into the namespace of
32             # any code which uses this module.
33            
34             our $pbdebug = 0; # Global debug level
35             our $pbLOG = \*STDOUT; # File descriptor of the log file
36             our $pbsynmsg = "Error"; # Global error message
37             our $pbdisplaytype = "text";
38             # default display mode for messages
39             our $pblocale = "C";
40              
41             our @ISA = qw(Exporter);
42             our @EXPORT = qw(pb_mkdir_p pb_system pb_rm_rf pb_get_date pb_log pb_log_init pb_get_uri pb_get_content pb_set_content pb_display_file pb_syntax_init pb_syntax pb_temp_init pb_get_arch pb_get_osrelease pb_check_requirements pb_check_req pb_path_expand pb_exit $pbdebug $pbLOG $pbdisplaytype $pblocale);
43             ($VERSION,$REVISION) = pb_version_init();
44              
45             =pod
46              
47             =head1 NAME
48              
49             ProjectBuilder::Base, part of the project-builder.org - module dealing with generic functions suitable for perl project development
50              
51             =head1 DESCRIPTION
52              
53             This module provides generic functions suitable for perl project development
54              
55             =head1 SYNOPSIS
56              
57             use ProjectBuilder::Base;
58              
59             #
60             # Create a directory and its parents
61             #
62             pb_mkdir_p("/tmp/foo/bar");
63              
64             #
65             # Remove recursively a directory and its children
66             #
67             pb_rm_rf("/tmp/foo");
68              
69             #
70             # Encapsulate the system call for better output and return value test
71             #
72             pb_system("ls -l", "Printing directory content");
73              
74             #
75             # Analysis a URI and return its components in a table
76             #
77             my ($scheme, $account, $host, $port, $path) = pb_get_uri("svn+ssh://ac@my.server.org:port/path/to/dir");
78              
79             #
80             # Gives the current date in a table
81             #
82             @date = pb_get_date();
83              
84             #
85             # Manages logs of the program
86             #
87             pb_log_init(2,\*STDOUT);
88             pb_log(1,"Message to print\n");
89              
90             #
91             # Manages content of a file
92             #
93             pb_display_file("/etc/passwd",\*STDERR);
94             my $cnt = pb_get_content("/etc/passwd");
95              
96             =head1 USAGE
97              
98             =over 4
99              
100             =item B
101              
102             Internal mkdir -p function. Forces mode to 755. Supports multiple parameters.
103              
104             Based on File::Path mkpath.
105              
106             =cut
107              
108             sub pb_mkdir_p {
109 0     0 1   my @dir = @_;
110 0           my $ret = eval { mkpath(@dir, 0, 0755) };
  0            
111 0 0         confess "pb_mkdir_p @dir failed in ".getcwd().": $@" if ($@);
112 0           return($ret);
113             }
114              
115             =item B
116              
117             Internal rm -rf function. Supports multiple parameters.
118              
119             Based on File::Path rmtree.
120              
121             =cut
122              
123             sub pb_rm_rf {
124 0     0 1   my @dir = @_;
125 0           my $ret = rmtree(@dir, 0, 0);
126 0           return($ret);
127             }
128              
129             =item B
130              
131             Encapsulate the "system" call for better output and return value test.
132             Needs a $ENV{'PBTMP'} variable which is created by calling the pb_mktemp_init function.
133             Needs pb_log support, so pb_log_init should have been called before.
134              
135             The first parameter is the shell command to call. This command should NOT use redirections.
136             The second parameter is the message to print on screen. If none is given, then the command is printed.
137             The third parameter prints the result of the command after correct execution if value is "verbose". If value is "noredir", it avoids redirecting outputs (e.g. for vi). If value is "quiet", doesn't print anything at all. If value is "mayfail", failure of the command is ok even if $Global::pb_stop_on_error is set, because the caller will be handling the error. A "verbose" can be added to mayfail to have it explain why it failed
138             This function returns as a result the return value of the system command.
139              
140             If no error reported, it prints OK on the screen, just after the message. Else it prints the errors generated.
141              
142             =cut
143              
144             sub pb_system {
145              
146 0     0 1   my $cmd=shift;
147 0   0       my $cmt=shift || $cmd;
148 0   0       my $verbose=shift || undef;
149 0           my $redir = "";
150              
151 0 0 0       pb_log(0,"$cmt... ") if ((! defined $verbose) || ($verbose ne "quiet"));
152 0           pb_log(1,"Executing $cmd\n");
153 0 0         unlink("$ENV{'PBTMP'}/system.$$.log") if (-f "$ENV{'PBTMP'}/system.$$.log");
154 0 0 0       $redir = "2>> $ENV{'PBTMP'}/system.$$.log 1>> $ENV{'PBTMP'}/system.$$.log" if ((! defined $verbose) || ($verbose ne "noredir"));
155              
156             # If sudo used, then be more verbose
157 0 0 0       pb_log(0,"Executing $cmd\n") if (($pbdebug < 1) && ($cmd =~ /^\s*\S*sudo/o) && (defined $Global::pb_show_sudo) && ($Global::pb_show_sudo =~ /true/oi));
      0        
      0        
158              
159 0           system("$cmd $redir");
160 0           my $res = $?;
161             # Exit now if the command may fail
162 0 0 0       if ((defined $verbose) and ($verbose =~ /mayfail/)) {
163 0 0         pb_log(0,"NOT OK but non blocking\n") if ($res != 0);
164 0 0         pb_log(0,"OK\n") if ($res == 0);
165 0 0 0       pb_display_file("$ENV{'PBTMP'}/system.$$.log") if ((-f "$ENV{'PBTMP'}/system.$$.log") and (defined $verbose) and ($verbose =~ /verbose/));
      0        
166 0           return($res)
167             }
168              
169 0           my $cwd = getcwd;
170 0           my $error = undef;
171 0 0         $error = "ERROR: failed to execute ($cmd) in $cwd: $!\n" if ($res == -1);
172 0 0         $error = "ERROR: child ($cmd) died with signal ".($res & 127).", ".($res & 128) ? 'with' : 'without'." coredump\n" if ($res & 127);
    0          
173 0 0         $error = "ERROR: child ($cmd) cwd=$cwd exited with value ".($res >> 8)."\n" if ($res != 0);
174              
175 0 0         if (defined $error) {
176 0 0 0       pb_log(0, $error) if (((! defined $verbose) || ($verbose ne "quiet")) || ($Global::pb_stop_on_error));
      0        
177 0 0 0       pb_display_file("$ENV{'PBTMP'}/system.$$.log") if ((-f "$ENV{'PBTMP'}/system.$$.log") and ((! defined $verbose) || ($verbose ne "quiet") || $Global::pb_stop_on_error));
      0        
178 0 0         if ($Global::pb_stop_on_error) {
179 0           confess("ERROR running command ($cmd) with cwd=$cwd, pid=$$");
180             } else {
181 0           pb_log(0,"ERROR running command ($cmd) with cwd=$cwd, pid=$$\n");
182             }
183             } else {
184 0 0 0       pb_log(0,"OK\n") if ((! defined $verbose) || ($verbose ne "quiet"));
185 0 0 0       pb_display_file("$ENV{'PBTMP'}/system.$$.log") if ((-f "$ENV{'PBTMP'}/system.$$.log") and (defined $verbose) and ($verbose ne "quiet"));
      0        
186             }
187              
188 0           return($res);
189             }
190              
191             =item B
192              
193             This function returns a list of 6 parameters indicating the protocol, account, password, server, port, and path contained in the URI passed in parameter.
194              
195             A URI has the format protocol://[ac@]host[:port][path[?query][#fragment]].
196              
197             Cf man URI.
198              
199             =cut
200              
201             sub pb_get_uri {
202              
203 0   0 0 1   my $uri = shift || undef;
204              
205 0 0         pb_log(2,"DEBUG: uri:" . (defined $uri ? $uri : '') . "\n");
206 0 0         my ($scheme, $authority, $path, $query, $fragment) =
207             $uri =~ m|(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?| if (defined $uri);
208 0 0         my ($account,$host,$port) = $authority =~ m|(?:([^\@]+)\@)?([^:]+)(:(?:[0-9]+))?| if (defined $authority);
209              
210 0 0         $scheme = "" if (not defined $scheme);
211 0 0         $authority = "" if (not defined $authority);
212 0 0         $path = "" if (not defined $path);
213 0 0         $account = "" if (not defined $account);
214 0 0         $host = "" if (not defined $host);
215 0 0         if (not defined $port) {
216 0           $port = ""
217             } else {
218             # Remove extra : at start
219 0           $port =~ s/^://;
220             }
221              
222 0           pb_log(2,"DEBUG: scheme:$scheme ac:$account host:$host port:$port path:$path\n");
223 0           return($scheme, $account, $host, $port, $path);
224             }
225              
226             =item B
227              
228             This function returns a list of 9 parameters indicating the seconds, minutes, hours, day, month, year, day in the week, day in the year, and daylight saving time flag of the current time.
229              
230             Cf: man ctime and description of the struct tm.
231              
232             =cut
233              
234             sub pb_get_date {
235            
236 0     0 1   return(localtime->sec(), localtime->min(), localtime->hour(), localtime->mday(), localtime->mon(), localtime->year(), localtime->wday(), localtime->yday(), localtime->isdst());
237             }
238              
239             =item B
240              
241             This function initializes the global variables used by the pb_log function.
242              
243             The first parameter is the debug level which will be considered during the run of the program?
244             The second parameter is a pointer on a file descriptor used to print the log info.
245              
246             As an example, if you set the debug level to 2 in that function, every call to pb_log which contains a value less or equal than 2 will be printed. Calls with a value greater than 2 won't be printed.
247              
248             The call to B is typically done after getting a parameter on the CLI indicating the level of verbosity expected.
249              
250             =cut
251              
252             sub pb_log_init {
253              
254 0   0 0 1   $pbdebug = shift || 0;
255 0   0       $pbLOG = shift || \*STDOUT;
256 0           pb_log(1,"Debug value: $pbdebug\n");
257              
258             }
259              
260             =item B
261              
262             This function logs the messages passed as the second parameter if the value passed as first parameter is lesser or equal than the value passed to the B function.
263              
264             Here is a usage example:
265              
266             pb_log_init(2,\*STDERR);
267             pb_log(1,"Hello World 1\n");
268             pb_log(2,"Hello World 2\n");
269             pb_log(3,"Hello World 3\n");
270              
271             will print:
272            
273             Hello World 1
274             Hello World 2
275              
276             =cut
277              
278             sub pb_log {
279              
280 0   0 0 1   my $dlevel = shift || 0;
281 0   0       my $msg = shift || "";
282              
283 0 0         $pbLOG = \*STDOUT if (not defined $pbLOG);
284              
285 0 0         print $pbLOG "$msg" if ($dlevel <= $pbdebug);
286 0 0 0       print "$msg" if (($dlevel == 0) && ($pbLOG != \*STDOUT));
287             }
288              
289              
290             =item B
291              
292             This function print the content of the file passed in parameter.
293             If a second parameter is given, this is the descriptor of the logfile to write to in addtion to STDOUT.
294              
295             This is a cat equivalent function.
296              
297             =cut
298              
299             sub pb_display_file {
300              
301 0     0 1   my $file=shift;
302 0   0       my $desc=shift || undef;
303              
304 0 0         return if (not -f $file);
305 0           my $cnt = pb_get_content($file);
306 0           print "$cnt\n";
307 0 0         print $desc "$cnt\n" if (defined $desc);
308             }
309              
310             =item B
311              
312             This function returns the content of the file passed in parameter.
313              
314             =cut
315              
316             sub pb_get_content {
317              
318 0     0 1   my $file=shift;
319              
320 0           my $bkp = $/;
321 0           undef $/;
322 0 0         open(R,$file) || die "Unable to open $file: $!";
323 0           my $content=;
324 0           close(R);
325 0           chomp($content);
326 0           $/ = $bkp;
327 0           return($content);
328             }
329              
330              
331             =item B
332              
333             This function put the content of a variable passed as second parameter into the file passed as first parameter.
334              
335             =cut
336              
337             sub pb_set_content {
338              
339 0     0 1   my $file=shift;
340 0           my $content=shift;
341              
342 0           my $bkp = $/;
343 0           undef $/;
344 0 0         open(R,"> $file") || die "Unable to write to $file: $!";
345 0           print R "$content";
346 0           close(R);
347 0           $/ = $bkp;
348             }
349              
350             =item B
351              
352             Fundtion to call before exiting pb so cleanup is done
353              
354             =cut
355              
356             sub pb_exit {
357              
358 0   0 0 1   my $ret = shift || 0;
359 0 0         pb_log(0,"Please remove manually $ENV{'PBTMP'} after debug analysis\n") if ($pbdebug > 1);
360 0           exit($ret);
361             }
362              
363             =item B
364              
365             This function initializes the global variable used by the pb_syntax function.
366              
367             The parameter is the message string which will be printed when calling pb_syntax
368              
369             =cut
370              
371             sub pb_syntax_init {
372              
373 0   0 0 1   $pbsynmsg = shift || "Error";
374             }
375              
376             =item B
377              
378             This function prints the syntax expected by the application, based on pod2usage, and exits.
379             The first parameter is the return value of the exit.
380             The second parameter is the verbosity as expected by pod2usage.
381              
382             Cf: man Pod::Usage
383              
384             =cut
385              
386             sub pb_syntax {
387              
388 0     0 1   my $exit_status = shift;
389 0           my $verbose_level = shift;
390              
391 0           my $filehandle = \*STDERR;
392              
393             # Don't do it upper as before as when the value is 0
394             # it is considered false and then exit was set to -1
395 0 0         $exit_status = -1 if (not defined $exit_status);
396 0 0         $verbose_level = 0 if (not defined $verbose_level);
397              
398 0 0         $filehandle = \*STDOUT if ($exit_status == 0);
399              
400 0           eval {
401 0           require Pod::Usage;
402 0           Pod::Usage->import();
403             };
404 0 0         if ($@) {
405             # No Pod::Usage found not printing usage. Old perl only
406 0           pb_exit();
407             } else {
408 0           pod2usage( -message => $pbsynmsg,
409             -exitval => $exit_status,
410             -verbose => $verbose_level,
411             -output => $filehandle );
412             }
413             }
414              
415             =item B
416              
417             This function initializes the environemnt variable PBTMP to a random value. This directory can be safely used during the whole program, it will be removed at the end automatically.
418              
419             =cut
420              
421             sub pb_temp_init {
422              
423 0 0   0 1   if (not defined $ENV{'TMPDIR'}) {
424 0           $ENV{'TMPDIR'}="/tmp";
425             }
426              
427             # Makes this function compatible with perl 5.005x
428 0           eval {
429 0           require File::Temp;
430 0           File::Temp->import("tempdir");
431             };
432 0 0         if ($@) {
433             # File::Temp not found, harcoding stuff
434             # Inspired by http://cpansearch.perl.org/src/TGUMMELS/File-MkTemp-1.0.6/File/MkTemp.pm
435             # Copyright 1999|2000 Travis Gummels. All rights reserved.
436             # This may be used and modified however you want.
437 0           my $template = "pb.XXXXXXXXXX";
438 0           my @template = split //, $template;
439 0           my @letters = split(//,"1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
440 0   0       for (my $i = $#template; $i >= 0 && ($template[$i] eq 'X'); $i--){
441 0           $template[$i] = $letters[int(rand 52)];
442             }
443 0           undef $template;
444 0           $template = pack "a" x @template, @template;
445 0           pb_mkdir_p("$ENV{'TMPDIR'}/$template");
446             } else {
447 0 0         if ($pbdebug > 1) {
448 0           $ENV{'PBTMP'} = tempdir( "pb.XXXXXXXXXX", DIR => $ENV{'TMPDIR'});
449 0           pb_log(2,"DEBUG: Creating a non-volatile temporary directory ($ENV{'PBTMP'})\n");
450             } else {
451 0           $ENV{'PBTMP'} = tempdir( "pb.XXXXXXXXXX", DIR => $ENV{'TMPDIR'}, CLEANUP => 1 );
452             }
453             }
454             }
455              
456             =item B
457              
458             This function returns the release of our operating system
459              
460             =cut
461              
462             sub pb_get_osrelease {
463              
464             # On linux can also use /proc/sys/kernel/osrelease
465 0     0 1   my $rel = `uname -r`;
466 0           chomp($rel);
467 0           return($rel);
468             }
469              
470              
471             =item B
472              
473             This function returns the architecture of our local environment and
474             standardize on i386 for those platforms.
475              
476             =cut
477              
478             sub pb_get_arch {
479              
480 0     0 1   my $arch = `uname -m`;
481 0           chomp($arch);
482 0           $arch =~ s/i[3456]86/i386/;
483             # For Solaris
484 0           $arch =~ s/i86pc/i386/;
485              
486 0           return($arch);
487             }
488              
489             =item B
490              
491             This function checks that the commands needed for the subsystem are indeed present.
492             The required commands are passed as a comma separated string as first parameter.
493             The optional commands are passed as a comma separated string as second parameter.
494              
495             =cut
496              
497             sub pb_check_requirements {
498              
499 0   0 0 1   my $req = shift || undef;
500 0   0       my $opt = shift || undef;
501 0   0       my $appname = shift || undef;
502              
503 0           my ($req2,$opt2) = (undef,undef);
504 0 0 0       $req2 = $req->{$appname} if (defined $req and defined $appname);
505 0 0 0       $opt2 = $opt->{$appname} if (defined $opt and defined $appname);
506              
507             # cmds is a string of comma separated commands
508 0 0         if (defined $req2) {
509 0           foreach my $file (split(/,/,$req2)) {
510 0           pb_check_req($file,0);
511             }
512             }
513              
514             # opts is a string of comma separated commands
515 0 0         if (defined $opt2) {
516 0           foreach my $file (split(/,/,$opt2)) {
517 0           pb_check_req($file,1);
518             }
519             }
520             }
521              
522             =item B
523              
524             This function checks existence of a command and return its full pathname or undef if not found.
525             The command name is passed as first parameter.
526             The second parameter should be 0 if the command is mandatory, 1 if optional.
527              
528             =cut
529              
530             sub pb_check_req {
531              
532 0     0 1   my $file = shift;
533 0           my $opt = shift;
534 0           my $found = undef;
535              
536 0 0         $opt = 1 if (not defined $opt);
537              
538 0           pb_log(2,"Checking availability of $file...");
539             # Check for all dirs in the PATH
540 0           foreach my $p (split(/:/,$ENV{'PATH'})) {
541 0 0         if (-x "$p/$file") {
542 0           $found = "$p/$file";
543 0           last;
544             }
545             }
546              
547 0 0         if (not $found) {
548 0           pb_log(2,"KO\n");
549 0 0         if ($opt eq 1) {
550 0           pb_log(2,"Unable to find optional command $file\n");
551             } else {
552 0           die pb_log(0,"Unable to find required command $file\n");
553             }
554             } else {
555 0           pb_log(2,"OK\n");
556             }
557 0           return($found);
558             }
559              
560             =item B
561              
562             Expand out a path by environment variables as ($ENV{XXX}) and ~
563              
564             =cut
565              
566             sub pb_path_expand {
567              
568 0     0 1   my $path = shift;
569              
570 0           eval { $path =~ s/(\$ENV.+\})/$1/eeg; };
  0            
  0            
571 0           $path =~ s/^\~/$ENV{HOME}/;
572              
573 0           return($path);
574             }
575              
576             =back
577              
578             =head1 WEB SITES
579              
580             The main Web site of the project is available at L. Bug reports should be filled using the trac instance of the project at L.
581              
582             =head1 USER MAILING LIST
583              
584             None exists for the moment.
585              
586             =head1 AUTHORS
587              
588             The Project-Builder.org team L lead by Bruno Cornec L.
589              
590             =head1 COPYRIGHT
591              
592             Project-Builder.org is distributed under the GPL v2.0 license
593             described in the file C included with the distribution.
594              
595             =cut
596              
597             1;