Gentoo Archives: gentoo-commits

From: Kent Fredric <kentfredric@×××××.com>
To: gentoo-commits@l.g.o
Subject: [gentoo-commits] proj/perl-overlay:master commit in: scripts/lib/
Date: Tue, 28 Feb 2012 21:56:27
Message-Id: 1330465447.723c2e4563ab8e24e219bfce8f371f73d0f26513.kent@gentoo
1 commit: 723c2e4563ab8e24e219bfce8f371f73d0f26513
2 Author: Kent Fredric <kentfredric <AT> gmail <DOT> com>
3 AuthorDate: Tue Feb 28 21:44:07 2012 +0000
4 Commit: Kent Fredric <kentfredric <AT> gmail <DOT> com>
5 CommitDate: Tue Feb 28 21:44:07 2012 +0000
6 URL: http://git.overlays.gentoo.org/gitweb/?p=proj/perl-overlay.git;a=commit;h=723c2e45
7
8 [scripts] factor out my simple option parsing logic to a lib
9
10 ---
11 scripts/lib/optparse.pm | 62 +++++++++++++++++++++++++++++++++++++++++++++++
12 1 files changed, 62 insertions(+), 0 deletions(-)
13
14 diff --git a/scripts/lib/optparse.pm b/scripts/lib/optparse.pm
15 new file mode 100644
16 index 0000000..296184b
17 --- /dev/null
18 +++ b/scripts/lib/optparse.pm
19 @@ -0,0 +1,62 @@
20 +use strict;
21 +use warnings;
22 +
23 +package optparse;
24 +
25 +# FILENAME: optparse.pm
26 +# CREATED: 29/02/12 07:50:47 by Kent Fredric (kentnl) <kentfredric@×××××.com>
27 +# ABSTRACT: Lightweight option parser;
28 +
29 +use Moose;
30 +
31 +has 'help' => ( isa => 'CodeRef', is => 'rw', required => 1 );
32 +has 'argv' => ( isa => 'ArrayRef', is => 'rw', required => 1 );
33 +
34 +has 'long_opts' => ( isa => 'HashRef', is => 'rw', 'lazy_build' => 1 );
35 +has 'opts' => ( isa => 'HashRef', is => 'rw', lazy_build => 1 );
36 +has 'extra_opts' => ( isa => 'ArrayRef', is => 'rw', 'lazy_build' => 1 );
37 +
38 +sub _build_extra_opts {
39 + my $self = shift;
40 + return [ grep { $_ !~ /^--(.+)/ and $_ !~ /^-(\w+)/ } @{ $self->argv } ];
41 +}
42 +
43 +sub _build_opts {
44 + my $self = shift;
45 + my $hash = {};
46 + for my $arg ( @{ $self->argv } ) {
47 + next if $arg =~ /^--(.+)/;
48 + next unless $arg =~ /^-(\w+)/;
49 + $hash->{$1}++;
50 + }
51 + return $hash;
52 +}
53 +
54 +sub _build_long_opts {
55 + my $self = shift;
56 + my $hash = {};
57 + for my $arg ( @{ $self->argv } ) {
58 + next unless $arg =~ /^--(.+)/;
59 + my ($token) = "$1";
60 + if ( $token =~ /^([^=]+)=(.*$)/ ) {
61 + $hash->{$1} = $2;
62 + }
63 + else {
64 + $hash->{$token}++;
65 + }
66 + }
67 + return $hash;
68 +}
69 +
70 +sub BUILD {
71 + my ($self) = shift;
72 + if ( defined $self->opts->{h} or defined $self->long_opts->{help} ) {
73 + $self->help->();
74 + exit 0;
75 + }
76 +}
77 +
78 +no Moose;
79 +__PACKAGE__->meta->make_immutable;
80 +1;
81 +