File Coverage

blib/lib/App/Info.pm
Criterion Covered Total %
statement 44 94 46.8
branch 6 22 27.3
condition 3 13 23.1
subroutine 12 35 34.3
pod 30 30 100.0
total 95 194 49.0


line stmt bran cond sub pod time code
1             package App::Info;
2              
3             # $Id: Info.pm 3154 2006-09-16 00:01:20Z theory $
4              
5             =head1 NAME
6            
7             App::Info - Information about software packages on a system
8            
9             =head1 SYNOPSIS
10            
11             use App::Info::Category::FooApp;
12            
13             my $app = App::Info::Category::FooApp->new;
14            
15             if ($app->installed) {
16             print "App name: ", $app->name, "\n";
17             print "Version: ", $app->version, "\n";
18             print "Bin dir: ", $app->bin_dir, "\n";
19             } else {
20             print "App not installed on your system. :-(\n";
21             }
22            
23             =head1 DESCRIPTION
24            
25             App::Info is an abstract base class designed to provide a generalized
26             interface for subclasses that provide metadata about software packages
27             installed on a system. The idea is that these classes can be used in Perl
28             application installers in order to determine whether software dependencies
29             have been fulfilled, and to get necessary metadata about those software
30             packages.
31            
32             App::Info provides an event model for handling events triggered by App::Info
33             subclasses. The events are classified as "info", "error", "unknown", and
34             "confirm" events, and multiple handlers may be specified to handle any or all
35             of these event types. This allows App::Info clients to flexibly handle events
36             in any way they deem necessary. Implementing new event handlers is
37             straight-forward, and use the triggering of events by App::Info subclasses is
38             likewise kept easy-to-use.
39            
40             A few L<sample subclasses|"SEE ALSO"> are provided with the distribution, but
41             others are invited to write their own subclasses and contribute them to the
42             CPAN. Contributors are welcome to extend their subclasses to provide more
43             information relevant to the application for which data is to be provided (see
44             L<App::Info::HTTPD::Apache|App::Info::HTTPD::Apache> for an example), but are
45             encouraged to, at a minimum, implement the abstract methods defined here and
46             in the category abstract base classes (e.g.,
47             L<App::Info::HTTPD|App::Info::HTTPD> and L<App::Info::Lib|App::Info::Lib>).
48             See L<Subclassing|"SUBCLASSING"> for more information on implementing new
49             subclasses.
50            
51             =cut
52              
53 2     2   26 use strict;
  2         17  
  2         25  
54 2     2   29 use Carp ();
  2         17  
  2         21  
55 2     2   116 use App::Info::Handler;
  2         22  
  2         35  
56 2     2   81 use App::Info::Request;
  2         21  
  2         39  
57 2     2   33 use vars qw($VERSION);
  2         19  
  2         26  
58              
59             $VERSION = '0.51';
60              
61             ##############################################################################
62             ##############################################################################
63             # This code ref is used by the abstract methods to throw an exception when
64             # they're called directly.
65             my $croak = sub {
66                 my ($caller, $meth) = @_;
67                 $caller = ref $caller || $caller;
68                 if ($caller eq __PACKAGE__) {
69                     $meth = __PACKAGE__ . '::' . $meth;
70                     Carp::croak(__PACKAGE__ . " is an abstract base class. Attempt to " .
71                                 " call non-existent method $meth");
72                 } else {
73                     Carp::croak("Class $caller inherited from the abstract base class " .
74                                 __PACKAGE__ . ", but failed to redefine the $meth() " .
75                                 "method. Attempt to call non-existent method " .
76                                 "${caller}::$meth");
77                 }
78             };
79              
80             ##############################################################################
81             # This code reference is used by new() and the on_* error handler methods to
82             # set the error handlers.
83             my $set_handlers = sub {
84                 my $on_key = shift;
85             # Default is to do nothing.
86                 return unless $on_key;
87                 my $ref = ref $on_key;
88                 if ($ref) {
89                     $on_key = [$on_key] unless $ref eq 'ARRAY';
90             # Make sure they're all handlers.
91                     foreach my $h (@$on_key) {
92                         if (my $r = ref $h) {
93                             Carp::croak("$r object is not an App::Info::Handler")
94                               unless UNIVERSAL::isa($h, 'App::Info::Handler');
95                         } else {
96             # Look up the handler.
97                             $h = App::Info::Handler->new( key => $h);
98                         }
99                     }
100             # Return 'em!
101                     return @$on_key;
102                 } else {
103             # Look up the handler.
104                     return App::Info::Handler->new( key => $on_key);
105                 }
106             };
107              
108             ##############################################################################
109             ##############################################################################
110              
111             =head1 INTERFACE
112            
113             This section documents the public interface of App::Info.
114            
115             =head2 Constructor
116            
117             =head3 new
118            
119             my $app = App::Info::Category::FooApp->new(@params);
120            
121             Constructs an App::Info object and returns it. The @params arguments define
122             attributes that can be used to help the App::Info object search for
123             application information on the file system, as well as how the App::Info
124             object will respond to certain events. The event parameters correspond to
125             their like-named methods. See the L<"Event Handler Object Methods"> section
126             for more information on App::Info events and how to handle them. The search
127             parameters that can be passed to C<new()> are:
128            
129             =over
130            
131             =item search_exe_names
132            
133             An array reference of possible names for binary executables. These may be used
134             by subclases to search for application programs that can be used to retreive
135             application information, such as version numbers. The subclasses generally
136             provide reasonable defaults for most cases.
137            
138             =item search_bin_dirs
139            
140             An array reference of local directories in which to search for executables.
141             These may be used to search for the value of the C<bin_dir> attribute in
142             addition to and in preference to the defaults used by each subclass.
143            
144             =item search_lib_names
145            
146             An array reference of possible names for library files. These may be used by
147             subclases to search for library files for the application. The subclasses
148             generally provide reasonable defaults for most cases.
149            
150             =item search_so_lib_names
151            
152             An array reference of possible names for shared object library files. These
153             may be used by subclases to search for shared object library files for the
154             application. The subclasses generally provide reasonable defaults for most
155             cases.
156            
157             =item search_lib_dirs
158            
159             An array reference of local directories in which to search for libraries.
160             These may be used to search for the value of the C<lib_dir> and C<so_lib_dir>
161             attributes in addition to and in preference to the defaults used by each
162             subclass.
163            
164             =item search_inc_names
165            
166             An array reference of possible names for include files. These may be used by
167             subclases to search for include files for the application. The subclasses
168             generally provide reasonable defaults for most cases.
169            
170             =item search_inc_dirs
171            
172             An array reference of local directories in which to search for include
173             files. These may be used to search for the value of the C<inc_dir> attribute
174             in addition to and in preference to the defaults used by each subclass.
175            
176             =back
177            
178             The parameters to C<new()> for the different types of App::Info events are:
179            
180             =over 4
181            
182             =item on_info
183            
184             =item on_error
185            
186             =item on_unknown
187            
188             =item on_confirm
189            
190             =back
191            
192             When passing event handlers to C<new()>, the list of handlers for each type
193             should be an anonymous array, for example:
194            
195             my $app = App::Info::Category::FooApp->new( on_info => \@handlers );
196            
197             =cut
198              
199             sub new {
200 2     2 1 33     my ($pkg, %p) = @_;
201 2   33     37     my $class = ref $pkg || $pkg;
202             # Fail if the method isn't overridden.
203 2 50       25     $croak->($pkg, 'new') if $class eq __PACKAGE__;
204              
205             # Set up handlers.
206 2         21     for (qw(on_error on_unknown on_info on_confirm)) {
207 8         220         $p{$_} = [$set_handlers->($p{$_})];
208                 }
209              
210             # Set up search defaults.
211 2         22     for (qw(bin_dirs lib_dirs inc_dirs exe_names lib_names inc_names
212             so_lib_names)) {
213 14         131         local $_ = "search_$_";
214 14 100       132         if (exists $p{$_}) {
215 8 50       112             $p{$_} = [$p{$_}] unless ref $p{$_} eq 'ARRAY';
216                     } else {
217 6         69             $p{$_} = [];
218                     }
219                 }
220              
221             # Do it!
222 2         34     return bless \%p, $class;
223             }
224              
225             ##############################################################################
226             ##############################################################################
227              
228             =head2 Metadata Object Methods
229            
230             These are abstract methods in App::Info and must be provided by its
231             subclasses. They provide the essential metadata of the software package
232             supported by the App::Info subclass.
233            
234             =head3 key_name
235            
236             my $key_name = $app->key_name;
237            
238             Returns a string that uniquely identifies the software for which the App::Info
239             subclass provides data. This value should be unique across all App::Info
240             classes. Typically, it's simply the name of the software.
241            
242             =cut
243              
244 0     0 1 0 sub key_name { $croak->(shift, 'key_name') }
245              
246             =head3 installed
247            
248             if ($app->installed) {
249             print "App is installed.\n"
250             } else {
251             print "App is not installed.\n"
252             }
253            
254             Returns a true value if the application is installed, and a false value if it
255             is not.
256            
257             =cut
258              
259 0     0 1 0 sub installed { $croak->(shift, 'installed') }
260              
261             ##############################################################################
262              
263             =head3 name
264            
265             my $name = $app->name;
266            
267             Returns the name of the application.
268            
269             =cut
270              
271 0     0 1 0 sub name { $croak->(shift, 'name') }
272              
273             ##############################################################################
274              
275             =head3 version
276            
277             my $version = $app->version;
278            
279             Returns the full version number of the application.
280            
281             =cut
282              
283             ##############################################################################
284              
285 0     0 1 0 sub version { $croak->(shift, 'version') }
286              
287             =head3 major_version
288            
289             my $major_version = $app->major_version;
290            
291             Returns the major version number of the application. For example, if
292             C<version()> returns "7.1.2", then this method returns "7".
293            
294             =cut
295              
296 0     0 1 0 sub major_version { $croak->(shift, 'major_version') }
297              
298             ##############################################################################
299              
300             =head3 minor_version
301            
302             my $minor_version = $app->minor_version;
303            
304             Returns the minor version number of the application. For example, if
305             C<version()> returns "7.1.2", then this method returns "1".
306            
307             =cut
308              
309 0     0 1 0 sub minor_version { $croak->(shift, 'minor_version') }
310              
311             ##############################################################################
312              
313             =head3 patch_version
314            
315             my $patch_version = $app->patch_version;
316            
317             Returns the patch version number of the application. For example, if
318             C<version()> returns "7.1.2", then this method returns "2".
319            
320             =cut
321              
322 0     0 1 0 sub patch_version { $croak->(shift, 'patch_version') }
323              
324             ##############################################################################
325              
326             =head3 bin_dir
327            
328             my $bin_dir = $app->bin_dir;
329            
330             Returns the full path the application's bin directory, if it exists.
331            
332             =cut
333              
334 0     0 1 0 sub bin_dir { $croak->(shift, 'bin_dir') }
335              
336             ##############################################################################
337              
338             =head3 executable
339            
340             my $executable = $app->executable;
341            
342             Returns the full path the application's bin directory, if it exists.
343            
344             =cut
345              
346 0     0 1 0 sub executable { $croak->(shift, 'executable') }
347              
348             ##############################################################################
349              
350             =head3 inc_dir
351            
352             my $inc_dir = $app->inc_dir;
353            
354             Returns the full path the application's include directory, if it exists.
355            
356             =cut
357              
358 0     0 1 0 sub inc_dir { $croak->(shift, 'inc_dir') }
359              
360             ##############################################################################
361              
362             =head3 lib_dir
363            
364             my $lib_dir = $app->lib_dir;
365            
366             Returns the full path the application's lib directory, if it exists.
367            
368             =cut
369              
370 0     0 1 0 sub lib_dir { $croak->(shift, 'lib_dir') }
371              
372             ##############################################################################
373              
374             =head3 so_lib_dir
375            
376             my $so_lib_dir = $app->so_lib_dir;
377            
378             Returns the full path the application's shared library directory, if it
379             exists.
380            
381             =cut
382              
383 0     0 1 0 sub so_lib_dir { $croak->(shift, 'so_lib_dir') }
384              
385             ##############################################################################
386              
387             =head3 home_url
388            
389             my $home_url = $app->home_url;
390            
391             The URL for the software's home page.
392            
393             =cut
394              
395 0     0 1 0 sub home_url { $croak->(shift, 'home_url') }
396              
397             ##############################################################################
398              
399             =head3 download_url
400            
401             my $download_url = $app->download_url;
402            
403             The URL for the software's download page.
404            
405             =cut
406              
407 0     0 1 0 sub download_url { $croak->(shift, 'download_url') }
408              
409             ##############################################################################
410             ##############################################################################
411              
412             =head2 Search Attributes
413            
414             These methods return lists of things to look for on the local file system when
415             searching for appliation programs, library files, and include files. They are
416             empty by default, since each subclass generally relies on its own settings,
417             but you can add your own as preferred search parameters by specifying them
418             as parameters to the C<new()> constructor.
419            
420             =head3 exe_names
421            
422             my @search_exe_names = $app->search_exe_names;
423            
424             Returns a list of possible names for an executable. Typically used by the
425             C<new()> constructor to search fo an executable to execute and collect
426             application info.
427            
428             =cut
429              
430 2     2 1 19 sub search_exe_names { @{shift->{search_exe_names}} }
  2         56  
431              
432             ##############################################################################
433              
434             =head3 search_bin_dirs
435            
436             my @search_bin_dirs = $app->search_bin_dirs;
437            
438             Returns a list of possible directories in which to search an executable.
439             Typically used by the C<new()> constructor to find an executable to execute
440             and collect application info. The found directory will also generally then
441             be returned by the C<bin_dir> method.
442            
443             =cut
444              
445 2     2 1 106 sub search_bin_dirs { @{shift->{search_bin_dirs}} }
  2         59  
446              
447             ##############################################################################
448              
449             =head3 lib_names
450            
451             my @search_lib_names = $app->search_lib_names;
452            
453             Returns a list of possible names for library files. Typically used by the
454             C<lib_dir()> method to find library files.
455            
456             =cut
457              
458 0     0 1 0 sub search_lib_names { @{shift->{search_lib_names}} }
  0         0  
459              
460             ##############################################################################
461              
462             =head3 so_lib_names
463            
464             my @search_so_lib_names = $app->search_so_lib_names;
465            
466             Returns a list of possible names for library files. Typically used by the
467             C<so_lib_dir()> method to find shared object library files.
468            
469             =cut
470              
471 0     0 1 0 sub search_so_lib_names { @{shift->{search_so_lib_names}} }
  0         0  
472              
473             ##############################################################################
474              
475             =head3 search_lib_dirs
476            
477             my @search_lib_dirs = $app->search_lib_dirs;
478            
479             Returns a list of possible directories in which to search for libraries.
480             Typically used by the C<lib_dir()> and C<so_lib_dir()> methods to find
481             library files.
482            
483             =cut
484              
485 2     2 1 56 sub search_lib_dirs { @{shift->{search_lib_dirs}} }
  2         53  
486              
487             ##############################################################################
488              
489             =head3 inc_names
490            
491             my @search_inc_names = $app->search_inc_names;
492            
493             Returns a list of possible names for include files. Typically used by the
494             C<inc_dir()> method to find include files.
495            
496             =cut
497              
498 0     0 1 0 sub search_inc_names { @{shift->{search_inc_names}} }
  0         0  
499              
500             ##############################################################################
501              
502             =head3 search_inc_dirs
503            
504             my @search_inc_dirs = $app->search_inc_dirs;
505            
506             Returns a list of possible directories in which to search for includes.
507             Typically used by the C<inc_dir()> method to find include files.
508            
509             =cut
510              
511 2     2 1 19 sub search_inc_dirs { @{shift->{search_inc_dirs}} }
  2         97  
512              
513             ##############################################################################
514             ##############################################################################
515              
516             =head2 Event Handler Object Methods
517            
518             These methods provide control over App::Info event handling. Events can be
519             handled by one or more objects of subclasses of App::Info::Handler. The first
520             to return a true value will be the last to execute. This approach allows
521             handlers to be stacked, and makes it relatively easy to create new handlers.
522             L<App::Info::Handler|App::Info::Handler> for information on writing event
523             handlers.
524            
525             Each of the event handler methods takes a list of event handlers as its
526             arguments. If none are passed, the existing list of handlers for the relevant
527             event type will be returned. If new handlers are passed in, they will be
528             returned.
529            
530             The event handlers may be specified as one or more objects of the
531             App::Info::Handler class or subclasses, as one or more strings that tell
532             App::Info construct such handlers itself, or a combination of the two. The
533             strings can only be used if the relevant App::Info::Handler subclasses have
534             registered strings with App::Info. For example, the App::Info::Handler::Print
535             class included in the App::Info distribution registers the strings "stderr"
536             and "stdout" when it starts up. These strings may then be used to tell
537             App::Info to construct App::Info::Handler::Print objects that print to STDERR
538             or to STDOUT, respectively. See the App::Info::Handler subclasses for what
539             strings they register with App::Info.
540            
541             =head3 on_info
542            
543             my @handlers = $app->on_info;
544             $app->on_info(@handlers);
545            
546             Info events are triggered when the App::Info subclass wants to send an
547             informational status message. By default, these events are ignored, but a
548             common need is for such messages to simply print to STDOUT. Use the
549             L<App::Info::Handler::Print|App::Info::Handler::Print> class included with the
550             App::Info distribution to have info messages print to STDOUT:
551            
552             use App::Info::Handler::Print;
553             $app->on_info('stdout');
554             # Or:
555             my $stdout_handler = App::Info::Handler::Print->new('stdout');
556             $app->on_info($stdout_handler);
557            
558             =cut
559              
560             sub on_info {
561 0     0 1 0     my $self = shift;
562 0 0       0     @{ $self->{on_info} } = $set_handlers->(\@_) if @_;
  0         0  
563 0         0     return @{ $self->{on_info} };
  0         0  
564             }
565              
566             =head3 on_error
567            
568             my @handlers = $app->on_error;
569             $app->on_error(@handlers);
570            
571             Error events are triggered when the App::Info subclass runs into an unexpected
572             but not fatal problem. (Note that fatal problems will likely throw an
573             exception.) By default, these events are ignored. A common way of handling
574             these events is to print them to STDERR, once again using the
575             L<App::Info::Handler::Print|App::Info::Handler::Print> class included with the
576             App::Info distribution:
577            
578             use App::Info::Handler::Print;
579             my $app->on_error('stderr');
580             # Or:
581             my $stderr_handler = App::Info::Handler::Print->new('stderr');
582             $app->on_error($stderr_handler);
583            
584             Another approach might be to turn such events into fatal exceptions. Use the
585             included L<App::Info::Handler::Carp|App::Info::Handler::Carp> class for this
586             purpose:
587            
588             use App::Info::Handler::Carp;
589             my $app->on_error('croak');
590             # Or:
591             my $croaker = App::Info::Handler::Carp->new('croak');
592             $app->on_error($croaker);
593            
594             =cut
595              
596             sub on_error {
597 0     0 1 0     my $self = shift;
598 0 0       0     @{ $self->{on_error} } = $set_handlers->(\@_) if @_;
  0         0  
599 0         0     return @{ $self->{on_error} };
  0         0  
600             }
601              
602             =head3 on_unknown
603            
604             my @handlers = $app->on_unknown;
605             $app->on_uknown(@handlers);
606            
607             Unknown events are trigged when the App::Info subclass cannot find the value
608             to be returned by a method call. By default, these events are ignored. A
609             common way of handling them is to have the application prompt the user for the
610             relevant data. The App::Info::Handler::Prompt class included with the
611             App::Info distribution can do just that:
612            
613             use App::Info::Handler::Prompt;
614             my $app->on_unknown('prompt');
615             # Or:
616             my $prompter = App::Info::Handler::Prompt;
617             $app->on_unknown($prompter);
618            
619             See L<App::Info::Handler::Prompt|App::Info::Handler::Prompt> for information
620             on how it works.
621            
622             =cut
623              
624             sub on_unknown {
625 0     0 1 0     my $self = shift;
626 0 0       0     @{ $self->{on_unknown} } = $set_handlers->(\@_) if @_;
  0         0  
627 0         0     return @{ $self->{on_unknown} };
  0         0  
628             }
629              
630             =head3 on_confirm
631            
632             my @handlers = $app->on_confirm;
633             $app->on_confirm(@handlers);
634            
635             Confirm events are triggered when the App::Info subclass has found an
636             important piece of information (such as the location of the executable it'll
637             use to collect information for the rest of its methods) and wants to confirm
638             that the information is correct. These events will most often be triggered
639             during the App::Info subclass object construction. Here, too, the
640             App::Info::Handler::Prompt class included with the App::Info distribution can
641             help out:
642            
643             use App::Info::Handler::Prompt;
644             my $app->on_confirm('prompt');
645             # Or:
646             my $prompter = App::Info::Handler::Prompt;
647             $app->on_confirm($prompter);
648            
649             =cut
650              
651             sub on_confirm {
652 0     0 1 0     my $self = shift;
653 0 0       0     @{ $self->{on_confirm} } = $set_handlers->(\@_) if @_;
  0         0  
654 0         0     return @{ $self->{on_confirm} };
  0         0  
655             }
656              
657             ##############################################################################
658             ##############################################################################
659              
660             =head1 SUBCLASSING
661            
662             As an abstract base class, App::Info is not intended to be used directly.
663             Instead, you'll use concrete subclasses that implement the interface it
664             defines. These subclasses each provide the metadata necessary for a given
665             software package, via the interface outlined above (plus any additional
666             methods the class author deems sensible for a given application).
667            
668             This section describes the facilities App::Info provides for subclassing. The
669             goal of the App::Info design has been to make subclassing straight-forward, so
670             that developers can focus on gathering the data they need for their
671             application and minimize the work necessary to handle unknown values or to
672             confirm values. As a result, there are essentially three concepts that
673             developers need to understand when subclassing App::Info: organization,
674             utility methods, and events.
675            
676             =head2 Organization
677            
678             The organizational idea behind App::Info is to name subclasses by broad
679             software categories. This approach allows the categories themselves to
680             function as abstract base classes that extend App::Info, so that they can
681             specify more methods for all of their base classes to implement. For example,
682             App::Info::HTTPD has specified the C<httpd_root()> abstract method that its
683             subclasses must implement. So as you get ready to implement your own subclass,
684             think about what category of software you're gathering information about.
685             New categories can be added as necessary.
686            
687             =head2 Utility Methods
688            
689             Once you've decided on the proper category, you can start implementing your
690             App::Info concrete subclass. As you do so, take advantage of App::Info::Util,
691             wherein I've tried to encapsulate common functionality to make subclassing
692             easier. I found that most of what I was doing repetitively was looking for
693             files and directories, and searching through files. Thus, App::Info::Util
694             subclasses L<File::Spec|File::Spec> in order to offer easy access to
695             commonly-used methods from that class, e.g., C<path()>. Plus, it has several
696             of its own methods to assist you in finding files and directories in lists of
697             files and directories, as well as methods for searching through files and
698             returning the values found in those files. See
699             L<App::Info::Util|App::Info::Util> for more information, and the App::Info
700             subclasses in this distribution for usage examples.
701            
702             I recommend the use of a package-scoped lexical App::Info::Util object. That
703             way it's nice and handy when you need to carry out common tasks. If you find
704             you're doing something over and over that's not already addressed by an
705             App::Info::Util method, consider submitting a patch to App::Info::Util to add
706             the functionality you need.
707            
708             =head2 Events
709            
710             Use the methods described below to trigger events. Events are designed to
711             provide a simple way for App::Info subclass developers to send status messages
712             and errors, to confirm data values, and to request a value when the class
713             caonnot determine a value itself. Events may optionally be handled by module
714             users who assign App::Info::Handler subclass objects to your App::Info
715             subclass object using the event handling methods described in the L<"Event
716             Handler Object Methods"> section.
717            
718             =cut
719              
720             ##############################################################################
721             # This code reference is used by the event methods to manage the stack of
722             # event handlers that may be available to handle each of the events.
723             my $handler = sub {
724                 my ($self, $meth, $params) = @_;
725              
726             # Sanity check. We really want to keep control over this.
727                 Carp::croak("Cannot call protected method $meth()")
728                   unless UNIVERSAL::isa($self, scalar caller(1));
729              
730             # Create the request object.
731                 $params->{type} ||= $meth;
732                 my $req = App::Info::Request->new(%$params);
733              
734             # Do the deed. The ultimate handling handler may die.
735                 foreach my $eh (@{$self->{"on_$meth"}}) {
736                     last if $eh->handler($req);
737                 }
738              
739             # Return the request.
740                 return $req;
741             };
742              
743             ##############################################################################
744              
745             =head3 info
746            
747             $self->info(@message);
748            
749             Use this method to display status messages for the user. You may wish to use
750             it to inform users that you're searching for a particular file, or attempting
751             to parse a file or some other resource for the data you need. For example, a
752             common use might be in the object constructor: generally, when an App::Info
753             object is created, some important initial piece of information is being
754             sought, such as an executable file. That file may be in one of many locations,
755             so it makes sense to let the user know that you're looking for it:
756            
757             $self->info("Searching for executable");
758            
759             Note that, due to the nature of App::Info event handlers, your informational
760             message may be used or displayed any number of ways, or indeed not at all (as
761             is the default behavior).
762            
763             The C<@message> will be joined into a single string and stored in the
764             C<message> attribute of the App::Info::Request object passed to info event
765             handlers.
766            
767             =cut
768              
769             sub info {
770 20     20 1 737     my $self = shift;
771             # Execute the handler sequence.
772 20         1455     my $req = $handler->($self, 'info', { message => join '', @_ });
773             }
774              
775             ##############################################################################
776              
777             =head3 error
778            
779             $self->error(@error);
780            
781             Use this method to inform the user that something unexpected has happened. An
782             example might be when you invoke another program to parse its output, but it's
783             output isn't what you expected:
784            
785             $self->error("Unable to parse version from `/bin/myapp -c`");
786            
787             As with all events, keep in mind that error events may be handled in any
788             number of ways, or not at all.
789            
790             The C<@erorr> will be joined into a single string and stored in the C<message>
791             attribute of the App::Info::Request object passed to error event handlers. If
792             that seems confusing, think of it as an "error message" rather than an "error
793             error." :-)
794            
795             =cut
796              
797             sub error {
798 0     0 1 0     my $self = shift;
799             # Execute the handler sequence.
800 0         0     my $req = $handler->($self, 'error', { message => join '', @_ });
801             }
802              
803             ##############################################################################
804              
805             =head3 unknown
806            
807             my $val = $self->unknown(@params);
808            
809             Use this method when a value is unknown. This will give the user the option --
810             assuming the appropriate handler handles the event -- to provide the needed
811             data. The value entered will be returned by C<unknown()>. The parameters are
812             as follows:
813            
814             =over 4
815            
816             =item key
817            
818             The C<key> parameter uniquely identifies the data point in your class, and is
819             used by App::Info to ensure that an unknown event is handled only once, no
820             matter how many times the method is called. The same value will be returned by
821             subsequent calls to C<unknown()> as was returned by the first call, and no
822             handlers will be activated. Typical values are "version" and "lib_dir".
823            
824             =item prompt
825            
826             The C<prompt> parameter is the prompt to be displayed should an event handler
827             decide to prompt for the appropriate value. Such a prompt might be something
828             like "Path to your httpd executable?". If this parameter is not provided,
829             App::Info will construct one for you using your class' C<key_name()> method
830             and the C<key> parameter. The result would be something like "Enter a valid
831             FooApp version". The C<prompt> parameter value will be stored in the
832             C<message> attribute of the App::Info::Request object passed to event
833             handlers.
834            
835             =item callback
836            
837             Assuming a handler has collected a value for your unknown data point, it might
838             make sense to validate the value. For example, if you prompt the user for a
839             directory location, and the user enters one, it makes sense to ensure that the
840             directory actually exists. The C<callback> parameter allows you to do this. It
841             is a code reference that takes the new value or values as its arguments, and
842             returns true if the value is valid, and false if it is not. For the sake of
843             convenience, the first argument to the callback code reference is also stored
844             in C<$_> .This makes it easy to validate using functions or operators that,
845             er, operate on C<$_> by default, but still allows you to get more information
846             from C<@_> if necessary. For the directory example, a good callback might be
847             C<sub { -d }>. The C<callback> parameter code reference will be stored in the
848             C<callback> attribute of the App::Info::Request object passed to event
849             handlers.
850            
851             =item error
852            
853             The error parameter is the error message to display in the event that the
854             C<callback> code reference returns false. This message may then be used by the
855             event handler to let the user know what went wrong with the data she entered.
856             For example, if the unknown value was a directory, and the user entered a
857             value that the C<callback> identified as invalid, a message to display might
858             be something like "Invalid directory path". Note that if the C<error>
859             parameter is not provided, App::Info will supply the generic error message
860             "Invalid value". This value will be stored in the C<error> attribute of the
861             App::Info::Request object passed to event handlers.
862            
863             =back
864            
865             This may be the event method you use most, as it should be called in every
866             metadata method if you cannot provide the data needed by that method. It will
867             typically be the last part of the method. Here's an example demonstrating each
868             of the above arguments:
869            
870             my $dir = $self->unknown( key => 'lib_dir',
871             prompt => "Enter lib directory path",
872             callback => sub { -d },
873             error => "Not a directory");
874            
875             =cut
876              
877             sub unknown {
878 0     0 1 0     my ($self, %params) = @_;
879 0 0       0     my $key = $params{key}
880                   or Carp::croak("No key parameter passed to unknown()");
881             # Just return the value if we've already handled this value. Ideally this
882             # shouldn't happen.
883 0 0       0     return $self->{__unknown__}{$key} if exists $self->{__unknown__}{$key};
884              
885             # Create a prompt and error message, if necessary.
886 0   0     0     $params{message} = delete $params{prompt} ||
887                   "Enter a valid " . $self->key_name . " $key";
888 0   0     0     $params{error} ||= 'Invalid value';
889              
890             # Execute the handler sequence.
891 0         0     my $req = $handler->($self, "unknown", \%params);
892              
893             # Mark that we've provided this value and then return it.
894 0         0     $self->{__unknown__}{$key} = $req->value;
895 0         0     return $self->{__unknown__}{$key};
896             }
897              
898             ##############################################################################
899              
900             =head3 confirm
901            
902             my $val = $self->confirm(@params);
903            
904             This method is very similar to C<unknown()>, but serves a different purpose.
905             Use this method for significant data points where you've found an appropriate
906             value, but want to ensure it's really the correct value. A "significant data
907             point" is usually a value essential for your class to collect metadata values.
908             For example, you might need to locate an executable that you can then call to
909             collect other data. In general, this will only happen once for an object --
910             during object construction -- but there may be cases in which it is needed
911             more than that. But hopefully, once you've confirmed in the constructor that
912             you've found what you need, you can use that information to collect the data
913             needed by all of the metadata methods and can assume that they'll be right
914             because that first, significant data point has been confirmed.
915            
916             Other than where and how often to call C<confirm()>, its use is quite similar
917             to that of C<unknown()>. Its parameters are as follows:
918            
919             =over
920            
921             =item key
922            
923             Same as for C<unknown()>, a string that uniquely identifies the data point in
924             your class, and ensures that the event is handled only once for a given key.
925             The same value will be returned by subsequent calls to C<confirm()> as was
926             returned by the first call for a given key.
927            
928             =item prompt
929            
930             Same as for C<unknown()>. Although C<confirm()> is called to confirm a value,
931             typically the prompt should request the relevant value, just as for
932             C<unknown()>. The difference is that the handler I<should> use the C<value>
933             parameter as the default should the user not provide a value. The C<prompt>
934             parameter will be stored in the C<message> attribute of the App::Info::Request
935             object passed to event handlers.
936            
937             =item value
938            
939             The value to be confirmed. This is the value you've found, and it will be
940             provided to the user as the default option when they're prompted for a new
941             value. This value will be stored in the C<value> attribute of the
942             App::Info::Request object passed to event handlers.
943            
944             =item callback
945            
946             Same as for C<unknown()>. Because the user can enter data to replace the
947             default value provided via the C<value> parameter, you might want to validate
948             it. Use this code reference to do so. The callback will be stored in the
949             C<callback> attribute of the App::Info::Request object passed to event
950             handlers.
951            
952             =item error
953            
954             Same as for C<unknown()>: an error message to display in the event that a
955             value entered by the user isn't validated by the C<callback> code reference.
956             This value will be stored in the C<error> attribute of the App::Info::Request
957             object passed to event handlers.
958            
959             =back
960            
961             Here's an example usage demonstrating all of the above arguments:
962            
963             my $exe = $self->confirm( key => 'shell',
964             prompt => 'Path to your shell?',
965             value => '/bin/sh',
966             callback => sub { -x },
967             error => 'Not an executable');
968            
969            
970             =cut
971              
972             sub confirm {
973 4     4 1 211     my ($self, %params) = @_;
974 4 50       49     my $key = $params{key}
975                   or Carp::croak("No key parameter passed to confirm()");
976 4 50       51     return $self->{__confirm__}{$key} if exists $self->{__confirm__}{$key};
977              
978             # Create a prompt and error message, if necessary.
979 4   33     54     $params{message} = delete $params{prompt} ||
980                   "Enter a valid " . $self->key_name . " $key";
981 4   50     96     $params{error} ||= 'Invalid value';
982              
983             # Execute the handler sequence.
984 4         49     my $req = $handler->($self, "confirm", \%params);
985              
986             # Mark that we've confirmed this value.
987 4         90     $self->{__confirm__}{$key} = $req->value;
988              
989 4         307     return $self->{__confirm__}{$key}
990             }
991              
992             1;
993             __END__
994            
995             =head2 Event Examples
996            
997             Below I provide some examples demonstrating the use of the event methods.
998             These are meant to emphasize the contexts in which it's appropriate to use
999             them.
1000            
1001             Let's start with the simplest, first. Let's say that to find the version
1002             number for an application, you need to search a file for the relevant data.
1003             Your App::Info concrete subclass might have a private method that handles this
1004             work, and this method is the appropriate place to use the C<info()> and, if
1005             necessary, C<error()> methods.
1006            
1007             sub _find_version {
1008             my $self = shift;
1009            
1010             # Try to find the revelant file. We cover this method below.
1011             # Just return if we cant' find it.
1012             my $file = $self->_find_file('version.conf') or return;
1013            
1014             # Send a status message.
1015             $self->info("Searching '$file' file for version");
1016            
1017             # Search the file. $util is an App::Info::Util object.
1018             my $ver = $util->search_file($file, qr/^Version\s+(.*)$/);
1019            
1020             # Trigger an error message, if necessary. We really think we'll have the
1021             # value, but we have to cover our butts in the unlikely event that we're
1022             # wrong.
1023             $self->error("Unable to find version in file '$file'") unless $ver;
1024            
1025             # Return the version number.
1026             return $ver;
1027             }
1028            
1029             Here we've used the C<info()> method to display a status message to let the
1030             user know what we're doing. Then we used the C<error()> method when something
1031             unexpected happened, which in this case was that we weren't able to find the
1032             version number in the file.
1033            
1034             Note the C<_find_file()> method we've thrown in. This might be a method that
1035             we call whenever we need to find a file that might be in one of a list of
1036             directories. This method, too, will be an appropriate place for an C<info()>
1037             method call. But rather than call the C<error()> method when the file can't be
1038             found, you might want to give an event handler a chance to supply that value
1039             for you. Use the C<unknown()> method for a case such as this:
1040            
1041             sub _find_file {
1042             my ($self, $file) = @_;
1043            
1044             # Send a status message.
1045             $self->info("Searching for '$file' file");
1046            
1047             # Look for the file. See App::Info:Utility for its interface.
1048             my @paths = qw(/usr/conf /etc/conf /foo/conf);
1049             my $found = $util->first_cat_path($file, @paths);
1050            
1051             # If we didn't find it, trigger an unknown event to
1052             # give a handler a chance to get the value.
1053             $found ||= $self->unknown( key => "file_$file",
1054             prompt => "Location of '$file' file?",
1055             callback => sub { -f },
1056             error => "Not a file");
1057            
1058             # Now return the file name, regardless of whether we found it or not.
1059             return $found;
1060             }
1061            
1062             Note how in this method, we've tried to locate the file ourselves, but if we
1063             can't find it, we trigger an unknown event. This allows clients of our
1064             App::Info subclass to try to establish the value themselves by having an
1065             App::Info::Handler subclass handle the event. If a value is found by an
1066             App::Info::Handler subclass, it will be returned by C<unknown()> and we can
1067             continue. But we can't assume that the unknown event will even be handled, and
1068             thus must expect that an unknown value may remain unknown. This is why the
1069             C<_find_version()> method above simply returns if C<_find_file()> doesn't
1070             return a file name; there's no point in searching through a file that doesn't
1071             exist.
1072            
1073             Attentive readers may be left to wonder how to decide when to use C<error()>
1074             and when to use C<unknown()>. To a large extent, this decision must be based
1075             on one's own understanding of what's most appropriate. Nevertheless, I offer
1076             the following simple guidelines: Use C<error()> when you expect something to
1077             work and then it just doesn't (as when a file exists and should contain the
1078             information you seek, but then doesn't). Use C<unknown()> when you're less
1079             sure of your processes for finding the value, and also for any of the values
1080             that should be returned by any of the L<metadata object methods|"Metadata
1081             Object Methods">. And of course, C<error()> would be more appropriate when you
1082             encounter an unexpected condition and don't think that it could be handled in
1083             any other way.
1084            
1085             Now, more than likely, a method such C<_find_version()> would be called by the
1086             C<version()> method, which is a metadata method mandated by the App::Info
1087             abstract base class. This is an appropriate place to handle an unknown version
1088             value. Indeed, every one of your metadata methods should make use of the
1089             C<unknown()> method. The C<version()> method then should look something like
1090             this:
1091            
1092             sub version {
1093             my $self = shift;
1094            
1095             unless (exists $self->{version}) {
1096             # Try to find the version number.
1097             $self->{version} = $self->_find_version ||
1098             $self->unknown( key => 'version',
1099             prompt => "Enter the version number");
1100             }
1101            
1102             # Now return the version number.
1103             return $self->{version};
1104             }
1105            
1106             Note how this method only tries to find the version number once. Any
1107             subsequent calls to C<version()> will return the same value that was returned
1108             the first time it was called. Of course, thanks to the C<key> parameter in the
1109             call to C<unknown()>, we could have have tried to enumerate the version number
1110             every time, as C<unknown()> will return the same value every time it is called
1111             (as, indeed, should C<_find_version()>. But by checking for the C<version> key
1112             in C<$self> ourselves, we save some of the overhead.
1113            
1114             But as I said before, every metadata method should make use of the
1115             C<unknown()> method. Thus, the C<major()> method might looks something like
1116             this:
1117            
1118             sub major {
1119             my $self = shift;
1120            
1121             unless (exists $self->{major}) {
1122             # Try to get the major version from the full version number.
1123             ($self->{major}) = $self->version =~ /^(\d+)\./;
1124             # Handle an unknown value.
1125             $self->{major} = $self->unknown( key => 'major',
1126             prompt => "Enter major version",
1127             callback => sub { /^\d+$/ },
1128             error => "Not a number")
1129             unless defined $self->{major};
1130             }
1131            
1132             return $self->{version};
1133             }
1134            
1135             Finally, the C<confirm()> method should be used to verify core pieces of data
1136             that significant numbers of other methods rely on. Typically such data are
1137             executables or configuration files from which will be drawn other metadata.
1138             Most often, such major data points will be sought in the object constructor.
1139             Here's an example:
1140            
1141             sub new {
1142             # Construct the object so that handlers will work properly.
1143             my $self = shift->SUPER::new(@_);
1144            
1145             # Try to find the executable.
1146             $self->info("Searching for executable");
1147             if (my $exe = $util->first_exe('/bin/myapp', '/usr/bin/myapp')) {
1148             # Confirm it.
1149             $self->{exe} =
1150             $self->confirm( key => 'binary',
1151             prompt => 'Path to your executable?',
1152             value => $exe,
1153             callback => sub { -x },
1154             error => 'Not an executable');
1155             } else {
1156             # Handle an unknown value.
1157             $self->{exe} =
1158             $self->unknown( key => 'binary',
1159             prompt => 'Path to your executable?',
1160             callback => sub { -x },
1161             error => 'Not an executable');
1162             }
1163            
1164             # We're done.
1165             return $self;
1166             }
1167            
1168             By now, most of what's going on here should be quite familiar. The use of the
1169             C<confirm()> method is quite similar to that of C<unknown()>. Really the only
1170             difference is that the value is known, but we need verification or a new value
1171             supplied if the value we found isn't correct. Such may be the case when
1172             multiple copies of the executable have been installed on the system, we found
1173             F</bin/myapp>, but the user may really be interested in F</usr/bin/myapp>.
1174             Thus the C<confirm()> event gives the user the chance to change the value if
1175             the confirm event is handled.
1176            
1177             The final thing to note about this constructor is the first line:
1178            
1179             my $self = shift->SUPER::new(@_);
1180            
1181             The first thing an App::Info subclass should do is execute this line to allow
1182             the super class to construct the object first. Doing so allows any event
1183             handling arguments to set up the event handlers, so that when we call
1184             C<confirm()> or C<unknown()> the event will be handled as the client expects.
1185            
1186             If we needed our subclass constructor to take its own parameter argumente, the
1187             approach is to specify the same C<key => $arg> syntax as is used by
1188             App::Info's C<new()> method. Say we wanted to allow clients of our App::Info
1189             subclass to pass in a list of alternate executable locations for us to search.
1190             Such an argument would most make sense as an array reference. So we specify
1191             that the key be C<alt_paths> and allow the user to construct an object like
1192             this:
1193            
1194             my $app = App::Info::Category::FooApp->new( alt_paths => \@paths );
1195            
1196             This approach allows the super class constructor arguments to pass unmolested
1197             (as long as we use unique keys!):
1198            
1199             my $app = App::Info::Category::FooApp->new( on_error => \@handlers,
1200             alt_paths => \@paths );
1201            
1202             Then, to retrieve these paths inside our C<new()> constructor, all we need do
1203             is access them directly from the object:
1204            
1205             my $self = shift->SUPER::new(@_);
1206             my $alt_paths = $self->{alt_paths};
1207            
1208             =head2 Subclassing Guidelines
1209            
1210             To summarize, here are some guidelines for subclassing App::Info.
1211            
1212             =over 4
1213            
1214             =item *
1215            
1216             Always subclass an App::Info category subclass. This will help to keep the
1217             App::Info namespace well-organized. New categories can be added as needed.
1218            
1219             =item *
1220            
1221             When you create the C<new()> constructor, always call C<SUPER::new(@_)>. This
1222             ensures that the event handling methods methods defined by the App::Info base
1223             classes (e.g., C<error()>) will work properly.
1224            
1225             =item *
1226            
1227             Use a package-scoped lexical App::Info::Util object to carry out common tasks.
1228             If you find you're doing something over and over that's not already addressed
1229             by an App::Info::Util method, and you think that others might find your
1230             solution useful, consider submitting a patch to App::Info::Util to add the
1231             functionality you need. See L<App::Info::Util|App::Info::Util> for complete
1232             documentation of its interface.
1233            
1234             =item *
1235            
1236             Use the C<info()> event triggering method to send messages to users of your
1237             subclass.
1238            
1239             =item *
1240            
1241             Use the C<error()> event triggering method to alert users of unexpected
1242             conditions. Fatal errors should still be fatal; use C<Carp::croak()> to throw
1243             exceptions for fatal errors.
1244            
1245             =item *
1246            
1247             Use the C<unknown()> event triggering method when a metadata or other
1248             important value is unknown and you want to give any event handlers the chance
1249             to provide the data.
1250            
1251             =item *
1252            
1253             Use the C<confirm()> event triggering method when a core piece of data is
1254             known (such as the location of an executable in the C<new()> constructor) and
1255             you need to make sure that you have the I<correct> information.
1256            
1257             =item *
1258            
1259             Be sure to implement B<all> of the abstract methods defined by App::Info and
1260             by your category abstract base class -- even if they don't do anything. Doing
1261             so ensures that all App::Info subclasses share a common interface, and can, if
1262             necessary, be used without regard to subclass. Any method not implemented but
1263             called on an object will generate a fatal exception.
1264            
1265             =back
1266            
1267             Otherwise, have fun! There are a lot of software packages for which relevant
1268             information might be collected and aggregated into an App::Info concrete
1269             subclass (witness all of the Automake macros in the world!), and folks who are
1270             knowledgeable about particular software packages or categories of software are
1271             warmly invited to contribute. As more subclasses are implemented, it will make
1272             sense, I think, to create separate distributions based on category -- or even,
1273             when necessary, on a single software package. Broader categories can then be
1274             aggregated in Bundle distributions.
1275            
1276             But I get ahead of myself...
1277            
1278             =head1 BUGS
1279            
1280             Please send bug reports to <bug-app-info@rt.cpan.org> or file them at
1281             L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=App-Info>.
1282            
1283             =head1 AUTHOR
1284            
1285             David Wheeler <david@justatheory.com>
1286            
1287             =head1 SEE ALSO
1288            
1289             The following classes define a few software package categories in which
1290             App::Info subclasses can be placed. Check them out for ideas on how to
1291             create new category subclasses.
1292            
1293             =over 4
1294            
1295             =item L<App::Info::HTTP|App::Info::HTTPD>
1296            
1297             =item L<App::Info::RDBMS|App::Info::RDBMS>
1298            
1299             =item L<App::Info::Lib|App::Info::Lib>
1300            
1301             =back
1302            
1303             The following classes implement the App::Info interface for various software
1304             packages. Check them out for examples of how to implement new App::Info
1305             concrete subclasses.
1306            
1307             =over
1308            
1309             =item L<App::Info::HTTPD::Apache|App::Info::HTTPD::Apache>
1310            
1311             =item L<App::Info::RDBMS::PostgreSQL|App::Info::RDBMS::PostgreSQL>
1312            
1313             =item L<App::Info::Lib::Expat|App::Info::Lib::Expat>
1314            
1315             =item L<App::Info::Lib::Iconv|App::Info::Lib::Iconv>
1316            
1317             =back
1318            
1319             L<App::Info::Util|App::Info::Util> provides utility methods for App::Info
1320             subclasses.
1321            
1322             L<App::Info::Handler|App::Info::Handler> defines an interface for event
1323             handlers to subclass. Consult its documentation for information on creating
1324             custom event handlers.
1325            
1326             The following classes implement the App::Info::Handler interface to offer some
1327             simple event handling. Check them out for examples of how to implement new
1328             App::Info::Handler subclasses.
1329            
1330             =over 4
1331            
1332             =item L<App::Info::Handler::Print|App::Info::Handler::Print>
1333            
1334             =item L<App::Info::Handler::Carp|App::Info::Handler::Carp>
1335            
1336             =item L<App::Info::Handler::Prompt|App::Info::Handler::Prompt>
1337            
1338             =back
1339            
1340             =head1 COPYRIGHT AND LICENSE
1341            
1342             Copyright (c) 2002-2006, David Wheeler. All Rights Reserved.
1343            
1344             This module is free software; you can redistribute it and/or modify it under
1345             the same terms as Perl itself.
1346            
1347             =cut
1348