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