root/trunk/lib/Perlbal/ManageCommand.pm

Revision 687, 2.3 kB (checked in by jacques, 2 years ago)

Bump copyright and fixed typo in Interactive

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# class representing a one-liner management command.  all the responses
2# to a command should be done through this instance (out, err, ok, etc)
3#
4# Copyright 2005-2007, Six Apart, Ltd.
5#
6
7package Perlbal::ManageCommand;
8use strict;
9use warnings;
10no  warnings qw(deprecated);
11
12use fields (
13            'base', # the base command name (like "proc")
14            'cmd',
15            'ok',
16            'err',
17            'out',
18            'orig',
19            'argn',
20            'ctx',
21            );
22
23sub new {
24    my ($class, $base, $cmd, $out, $ok, $err, $orig, $ctx) = @_;
25    my $self = fields::new($class);
26
27    $self->{base} = $base;
28    $self->{cmd}  = $cmd;
29    $self->{ok}   = $ok;
30    $self->{err}  = $err;
31    $self->{out}  = $out;
32    $self->{orig} = $orig;
33    $self->{ctx}  = $ctx;
34    $self->{argn}    = [];
35    return $self;
36}
37
38# returns an managecommand object for functions that need one, but
39# this does nothing but explode if there any problems.
40sub loud_crasher {
41    use Carp qw(confess);
42    __PACKAGE__->new(undef, undef, sub {}, sub {}, sub { confess "MC:err: @_" }, "", Perlbal::CommandContext->new);
43}
44
45sub out   { my $mc = shift; return @_ ? $mc->{out}->(@_) : $mc->{out}; }
46sub ok    { my $mc = shift; return $mc->{ok}->(@_);  }
47
48sub err   {
49    my ($mc, $err) = @_;
50    $err =~ s/\n$//;
51    $mc->{err}->($err);
52}
53
54sub cmd   { my $mc = shift; return $mc->{cmd};       }
55sub orig  { my $mc = shift; return $mc->{orig};      }
56sub end   { my $mc = shift; $mc->{out}->(".");    1; }
57
58sub parse {
59    my $mc = shift;
60    my $regexp = shift;
61    my $usage = shift;
62
63    my @ret = ($mc->{cmd} =~ /$regexp/);
64    $mc->parse_error($usage) unless @ret;
65
66    my $i = 0;
67    foreach (@ret) {
68        $mc->{argn}[$i++] = $_;
69    }
70    return $mc;
71}
72
73sub arg {
74    my $mc = shift;
75    my $n = shift;   # 1-based array, to correspond with $1, $2, $3
76    return $mc->{argn}[$n - 1];
77}
78
79sub args {
80    my $mc = shift;
81    return @{$mc->{argn}};
82}
83
84sub parse_error {
85    my $mc = shift;
86    my $usage = shift;
87    $usage .= "\n" if $usage && $usage !~ /\n$/;
88    die $usage || "Invalid syntax to '$mc->{base}' command\n"
89}
90
91sub no_opts {
92    my $mc = shift;
93    die "The '$mc->{base}' command takes no arguments\n"
94        unless $mc->{cmd} eq $mc->{base};
95    return $mc;
96}
97
981;
99
100# Local Variables:
101# mode: perl
102# c-basic-indent: 4
103# indent-tabs-mode: nil
104# End:
Note: See TracBrowser for help on using the browser.