repo
string | commit
string | message
string | diff
string |
---|---|---|---|
rjbs/Data-Hive
|
689b72cfa930e212dac3a804f4c5a1aedf739754
|
move Hash to Hash::Nested
|
diff --git a/lib/Data/Hive/Store/Hash.pm b/lib/Data/Hive/Store/Hash.pm
index b6ae420..40137bd 100644
--- a/lib/Data/Hive/Store/Hash.pm
+++ b/lib/Data/Hive/Store/Hash.pm
@@ -1,233 +1,130 @@
use strict;
use warnings;
package Data::Hive::Store::Hash;
-# ABSTRACT: store a hive in nested hashrefs
+# ABSTRACT: store a hive in a flat hashref
=head1 DESCRIPTION
-This is a simple store, primarily for testing, that will store hives in nested
-hashrefs. All hives are represented as hashrefs, and their values are stored
-in the entry for the empty string.
+This is a simple store, primarily for testing, that will store hives in a flat
+hashref. Paths are packed into strings and used as keys. The structure does
+not recurse -- for that, see L<Data::Hive::Store::Hash::Nested>.
So, we could do this:
my $href = {};
my $hive = Data::Hive->NEW({
store_class => 'Hash',
store_args => [ $href ],
});
$hive->foo->SET(1);
$hive->foo->bar->baz->SET(2);
-We would end up with C<$href> containing:
+We would end up with C<$href> containing something like:
{
- foo => {
- '' => 1,
- bar => {
- baz => {
- '' => 2,
- },
- },
- },
+ foo => 1,
+ 'foo.bar.baz' => 2
}
-Using empty keys results in a bigger, uglier dump, but allows a given hive to
-contain both a value and subhives. B<Please note> that this is different
-behavior compared with earlier releases, in which empty keys were not used and
-it was not legal to have a value and a hive at a given path. It is possible,
-although fairly unlikely, that this format will change again. The Hash store
-should generally be used for testing things that use a hive, as opposed for
-building hashes that will be used for anything else.
-
=method new
- my $store = Data::Hive::Store::Hash->new(\%hash);
+ my $store = Data::Hive::Store::Hash->new(\%hash, \%arg);
The only argument expected for C<new> is a hashref, which is the hashref in
which hive entries are stored.
If no hashref is provided, a new, empty hashref will be used.
+The extra arguments may include:
+
+=for :list
+= path_packer
+A L<Data::Hive::PathPacker>-like object used to convert between paths
+(arrayrefs) and hash keys.
+
=cut
sub new {
- my ($class, $href) = @_;
- $href = {} unless defined $href;
+ my ($class, $href, $arg) = @_;
+ $href = {} unless $href;
+ $arg = {} unless $arg;
+
+ my $guts = {
+ store => $href,
+ path_packer => $arg->{path_packer} || do {
+ require Data::Hive::PathPacker::Basic;
+ Data::Hive::PathPacker::Basic->new;
+ },
+ };
- return bless { store => $href } => $class;
+ return bless $guts => $class;
}
=method hash_store
This method returns the hashref in which things are being used. You should not
alter its contents!
=cut
-sub hash_store {
- $_[0]->{store}
-}
+sub hash_store { $_[0]->{store} }
+sub path_packer { $_[0]->{path_packer} }
sub _die {
require Carp::Clan;
Carp::Clan->import('^Data::Hive($|::)');
croak(shift);
}
-my $BREAK = "BREAK\n";
-
-# Wow, this is quite a little machine! Here's a slightly simplified overview
-# of what it does: -- rjbs, 2010-08-27
-#
-# As long as cond->(\@remaining_path) is true, execute step->($next,
-# $current_hashref, \@remaining_path)
-#
-# If it dies with $BREAK, stop looping and return. Once the cond returns
-# false, return end->($current_hashref, \@remaining_path)
-sub _descend {
- my ($self, $orig_path, $arg) = @_;
- my @path = @$orig_path;
-
- $arg ||= {};
- $arg->{step} or die "step is required";
- $arg->{cond} ||= sub { @{ shift() } };
- $arg->{end} ||= sub { $_[0] };
-
- my $node = $self->hash_store;
-
- while ($arg->{cond}->(\@path)) {
- my $seg = shift @path;
-
- {
- local $SIG{__DIE__};
- eval { $arg->{step}->($seg, $node, \@path) };
- }
-
- return if $@ and $@ eq $BREAK;
- die $@ if $@;
- $node = $node->{$seg} ||= {};
- }
-
- return $arg->{end}->($node, \@path);
-}
-
sub get {
my ($self, $path) = @_;
- return $self->_descend(
- $path, {
- end => sub { $_[0]->{''} },
- step => sub {
- my ($seg, $node) = @_;
-
- if (defined $node and not ref $node) {
- # We found a bogus entry in the store! -- rjbs, 2010-08-27
- _die("can't get key '$seg' of non-ref value '$node'");
- }
-
- die $BREAK unless exists $node->{$seg};
- }
- }
- );
+ return $self->hash_store->{ $self->name($path) };
}
sub set {
my ($self, $path, $value) = @_;
- return $self->_descend(
- $path, {
- step => sub {
- my ($seg, $node, $path) = @_;
- if (exists $node->{$seg} and not ref $node->{$seg}) {
- _die("can't overwrite existing non-ref value: '$node->{$seg}'");
- }
- },
- cond => sub { @{ shift() } > 1 },
- end => sub {
- my ($node, $path) = @_;
- $node->{$path->[0]}{''} = $value;
- },
- },
- );
+ $self->hash_store->{ $self->name($path) } = $value;
}
-=method name
-
-The name returned by the Hash store is a string, potentially suitable for
-eval-ing, describing a hash dereference of a variable called C<< $STORE >>.
-
- "$STORE->{foo}->{bar}"
-
-This is probably not very useful.
-
-=cut
-
sub name {
my ($self, $path) = @_;
- return join '->', '$STORE', map { "{'$_'}" } @$path;
+ $self->path_packer->pack_path($path);
}
sub exists {
my ($self, $path) = @_;
- return $self->_descend(
- $path, {
- step => sub {
- my ($seg, $node) = @_;
- die $BREAK unless exists $node->{$seg};
- },
- end => sub { return exists $_[0]->{''}; },
- },
- );
+ exists $self->hash_store->{ $self->name($path) };
}
sub delete {
my ($self, $path) = @_;
- return $self->_descend(
- $path, {
- step => sub {
- my ($seg, $node) = @_;
- die $BREAK unless exists $node->{$seg};
- },
- cond => sub { @{ shift() } > 1 },
- end => sub {
- my ($node, $final_path) = @_;
- my $this = $node->{ $final_path->[0] };
- my $rv = delete $this->{''};
-
- # Cleanup empty trees after deletion! It would be convenient to have
- # ->_ascend, but I'm not likely to bother with writing it just yet.
- # -- rjbs, 2010-08-27
- $self->_descend(
- $path, {
- step => sub {
- my ($seg, $node) = @_;
- return if keys %{ $node->{$seg} };
- delete $node->{$seg};
- die $BREAK;
- },
- }
- );
-
- return $rv;
- },
- },
- );
+ delete $self->hash_store->{ $self->name($path) };
}
sub keys {
my ($self, $path) = @_;
- return $self->_descend($path, {
- step => sub {
- my ($seg, $node) = @_;
- die $BREAK unless exists $node->{$seg};
- },
- end => sub {
- return grep { length } keys %{ $_[0] };
- },
- });
+ my $method = $self->{method};
+ my @names = keys %{ $self->hash_store };
+
+ my %is_key;
+
+ PATH: for my $name (@names) {
+ my $this_path = $self->path_packer->unpack_path($name);
+
+ next unless @$this_path > @$path;
+
+ for my $i (0 .. $#$path) {
+ next PATH unless $this_path->[$i] eq $path->[$i];
+ }
+
+ $is_key{ $this_path->[ $#$path + 1 ] } = 1;
+ }
+
+ return keys %is_key;
}
1;
diff --git a/lib/Data/Hive/Store/Hash/Nested.pm b/lib/Data/Hive/Store/Hash/Nested.pm
new file mode 100644
index 0000000..c98fe3d
--- /dev/null
+++ b/lib/Data/Hive/Store/Hash/Nested.pm
@@ -0,0 +1,234 @@
+use strict;
+use warnings;
+package Data::Hive::Store::Hash::Nested;
+# ABSTRACT: store a hive in nested hashrefs
+
+=head1 DESCRIPTION
+
+This is a simple store, primarily for testing, that will store hives in nested
+hashrefs. All hives are represented as hashrefs, and their values are stored
+in the entry for the empty string.
+
+So, we could do this:
+
+ my $href = {};
+
+ my $hive = Data::Hive->NEW({
+ store_class => 'Hash',
+ store_args => [ $href ],
+ });
+
+ $hive->foo->SET(1);
+ $hive->foo->bar->baz->SET(2);
+
+We would end up with C<$href> containing:
+
+ {
+ foo => {
+ '' => 1,
+ bar => {
+ baz => {
+ '' => 2,
+ },
+ },
+ },
+ }
+
+Using empty keys results in a bigger, uglier dump, but allows a given hive to
+contain both a value and subhives. B<Please note> that this is different
+behavior compared with earlier releases, in which empty keys were not used and
+it was not legal to have a value and a hive at a given path. It is possible,
+although fairly unlikely, that this format will change again. The Hash store
+should generally be used for testing things that use a hive, as opposed for
+building hashes that will be used for anything else.
+
+=method new
+
+ my $store = Data::Hive::Store::Hash->new(\%hash);
+
+The only argument expected for C<new> is a hashref, which is the hashref in
+which hive entries are stored.
+
+If no hashref is provided, a new, empty hashref will be used.
+
+=cut
+
+sub new {
+ my ($class, $href) = @_;
+ $href = {} unless defined $href;
+
+ return bless { store => $href } => $class;
+}
+
+=method hash_store
+
+This method returns the hashref in which things are being used. You should not
+alter its contents!
+
+=cut
+
+sub hash_store {
+ $_[0]->{store}
+}
+
+sub _die {
+ require Carp::Clan;
+ Carp::Clan->import('^Data::Hive($|::)');
+ croak(shift);
+}
+
+my $BREAK = "BREAK\n";
+
+# Wow, this is quite a little machine! Here's a slightly simplified overview
+# of what it does: -- rjbs, 2010-08-27
+#
+# As long as cond->(\@remaining_path) is true, execute step->($next,
+# $current_hashref, \@remaining_path)
+#
+# If it dies with $BREAK, stop looping and return. Once the cond returns
+# false, return end->($current_hashref, \@remaining_path)
+sub _descend {
+ my ($self, $orig_path, $arg) = @_;
+ my @path = @$orig_path;
+
+ $arg ||= {};
+ $arg->{step} or die "step is required";
+ $arg->{cond} ||= sub { @{ shift() } };
+ $arg->{end} ||= sub { $_[0] };
+
+ my $node = $self->hash_store;
+
+ while ($arg->{cond}->(\@path)) {
+ my $seg = shift @path;
+
+ {
+ local $SIG{__DIE__};
+ eval { $arg->{step}->($seg, $node, \@path) };
+ }
+
+ return if $@ and $@ eq $BREAK;
+ die $@ if $@;
+ $node = $node->{$seg} ||= {};
+ }
+
+ return $arg->{end}->($node, \@path);
+}
+
+sub get {
+ my ($self, $path) = @_;
+ return $self->_descend(
+ $path, {
+ end => sub { $_[0]->{''} },
+ step => sub {
+ my ($seg, $node) = @_;
+
+ if (defined $node and not ref $node) {
+ # We found a bogus entry in the store! -- rjbs, 2010-08-27
+ _die("can't get key '$seg' of non-ref value '$node'");
+ }
+
+ die $BREAK unless exists $node->{$seg};
+ }
+ }
+ );
+}
+
+sub set {
+ my ($self, $path, $value) = @_;
+ return $self->_descend(
+ $path, {
+ step => sub {
+ my ($seg, $node, $path) = @_;
+ if (exists $node->{$seg} and not ref $node->{$seg}) {
+ _die("can't overwrite existing non-ref value: '$node->{$seg}'");
+ }
+ },
+ cond => sub { @{ shift() } > 1 },
+ end => sub {
+ my ($node, $path) = @_;
+ $node->{$path->[0]}{''} = $value;
+ },
+ },
+ );
+}
+
+=method name
+
+The name returned by the Hash store is a string, potentially suitable for
+eval-ing, describing a hash dereference of a variable called C<< $STORE >>.
+
+ "$STORE->{foo}->{bar}"
+
+This is probably not very useful.
+
+=cut
+
+sub name {
+ my ($self, $path) = @_;
+ return join '->', '$STORE', map { "{'$_'}" } @$path;
+}
+
+sub exists {
+ my ($self, $path) = @_;
+ return $self->_descend(
+ $path, {
+ step => sub {
+ my ($seg, $node) = @_;
+ die $BREAK unless exists $node->{$seg};
+ },
+ end => sub { return exists $_[0]->{''}; },
+ },
+ );
+}
+
+sub delete {
+ my ($self, $path) = @_;
+
+ my @to_check;
+
+ return $self->_descend(
+ $path, {
+ step => sub {
+ my ($seg, $node) = @_;
+ die $BREAK unless exists $node->{$seg};
+ push @to_check, [ $node, $seg ];
+ },
+ cond => sub { @{ shift() } > 1 },
+ end => sub {
+ my ($node, $final_path) = @_;
+ my $this = $node->{ $final_path->[0] };
+ my $rv = delete $this->{''};
+
+ # Cleanup empty trees after deletion! It would be convenient to have
+ # ->_ascend, but I'm not likely to bother with writing it just yet.
+ # -- rjbs, 2010-08-27
+ for my $to_check (
+ [ $node, $final_path->[0] ],
+ reverse @to_check
+ ) {
+ my ($node, $seg) = @$to_check;
+ last if keys %{ $node->{$seg} };
+ delete $node->{ $seg };
+ }
+
+ return $rv;
+ },
+ },
+ );
+}
+
+sub keys {
+ my ($self, $path) = @_;
+
+ return $self->_descend($path, {
+ step => sub {
+ my ($seg, $node) = @_;
+ die $BREAK unless exists $node->{$seg};
+ },
+ end => sub {
+ return grep { length } keys %{ $_[0] };
+ },
+ });
+}
+
+1;
diff --git a/t/hash-nested.t b/t/hash-nested.t
new file mode 100644
index 0000000..3398b6b
--- /dev/null
+++ b/t/hash-nested.t
@@ -0,0 +1,154 @@
+#!perl
+use strict;
+use warnings;
+
+use Data::Hive;
+use Data::Hive::Store::Hash::Nested;
+
+use Data::Hive::Test;
+
+use Test::More 0.88;
+
+Data::Hive::Test->test_new_hive(
+ 'basic hash store',
+ { store => Data::Hive::Store::Hash::Nested->new },
+);
+
+for my $class (qw(
+ Hash::Nested
+ +Data::Hive::Store::Hash::Nested
+ =Data::Hive::Store::Hash::Nested
+)) {
+ my $hive = Data::Hive->NEW({ store_class => $class });
+
+ isa_ok($hive->STORE, 'Data::Hive::Store::Hash::Nested', "store from $class");
+}
+
+my $hive = Data::Hive->NEW({
+ store_class => 'Hash::Nested',
+});
+
+my $tmp;
+
+isa_ok($hive, 'Data::Hive', 'top-level hive');
+
+isa_ok($hive->foo, 'Data::Hive', '"foo" subhive');
+
+$hive->foo->SET(1);
+
+is_deeply(
+ $hive->STORE->hash_store,
+ { foo => { '' => 1 } },
+ 'changes made to store',
+);
+
+$hive->bar->baz->GET;
+
+is_deeply(
+ $hive->STORE->hash_store,
+ { foo => { '' => 1 } },
+ 'did not autovivify'
+);
+
+$hive->baz->quux->SET(2);
+
+is_deeply(
+ $hive->STORE->hash_store,
+ {
+ foo => { '' => 1 },
+ baz => { quux => { '' => 2 } },
+ },
+ 'deep set',
+);
+
+is(
+ $hive->foo->GET,
+ 1,
+ "get the 1 from ->foo",
+);
+
+is(
+ $hive->foo->bar->GET,
+ undef,
+ "find nothing at ->foo->bar",
+);
+
+$hive->foo->bar->SET(3);
+
+is(
+ $hive->foo->bar->GET,
+ 3,
+ "wrote and retrieved 3 from ->foo->bar",
+);
+
+ok ! $hive->not->EXISTS, "non-existent key doesn't EXISTS";
+ok $hive->foo->EXISTS, "existing key does EXISTS";
+
+$hive->baz->quux->frotz->SET(4);
+
+is_deeply(
+ $hive->STORE->hash_store,
+ {
+ foo => { '' => 1, bar => { '' => 3 } },
+ baz => { quux => { '' => 2, frotz => { '' => 4 } } },
+ },
+ "deep delete"
+);
+
+my $quux = $hive->baz->quux;
+is($quux->GET, 2, "get from saved leaf");
+is($quux->DELETE, 2, "delete returned old value");
+is($quux->GET, undef, "after deletion, hive has no value");
+
+is_deeply(
+ $hive->STORE->hash_store,
+ {
+ foo => { '' => 1, bar => { '' => 3 } },
+ baz => { quux => { frotz => { '' => 4 } } },
+ },
+ "deep delete"
+);
+
+my $frotz = $hive->baz->quux->frotz;
+is($frotz->GET, 4, "get from saved leaf");
+is($frotz->DELETE, 4, "delete returned old value");
+is($frotz->GET, undef, "after deletion, hive has no value");
+
+is_deeply(
+ $hive->STORE->hash_store,
+ {
+ foo => { '' => 1, bar => { '' => 3 } },
+ },
+ "deep delete: after a hive had no keys, it is deleted, too"
+);
+
+{
+ my $hive = Data::Hive->NEW({
+ store_class => 'Hash::Nested',
+ });
+
+ $hive->HIVE('and/or')->SET(1);
+ $hive->foo->bar->SET(4);
+ $hive->foo->bar->baz->SET(5);
+ $hive->foo->quux->baz->SET(6);
+
+ is_deeply(
+ [ sort $hive->KEYS ],
+ [ qw(and/or foo) ],
+ "get the top level KEYS",
+ );
+
+ is_deeply(
+ [ sort $hive->foo->KEYS ],
+ [ qw(bar quux) ],
+ "get the KEYS under foo",
+ );
+
+ is_deeply(
+ [ sort $hive->foo->bar->KEYS ],
+ [ qw(baz) ],
+ "get the KEYS under foo/bar",
+ );
+}
+
+done_testing;
diff --git a/t/hash.t b/t/hash.t
index ab61742..dddc8c2 100644
--- a/t/hash.t
+++ b/t/hash.t
@@ -1,155 +1,158 @@
#!perl
use strict;
use warnings;
use Data::Hive;
use Data::Hive::Store::Hash;
use Data::Hive::Test;
use Test::More 0.88;
Data::Hive::Test->test_new_hive(
'basic hash store',
{ store => Data::Hive::Store::Hash->new },
);
for my $class (qw(
Hash
+Data::Hive::Store::Hash
=Data::Hive::Store::Hash
)) {
my $hive = Data::Hive->NEW({ store_class => $class });
isa_ok($hive->STORE, 'Data::Hive::Store::Hash', "store from $class");
}
my $hive = Data::Hive->NEW({
store_class => 'Hash',
});
my $tmp;
isa_ok($hive, 'Data::Hive', 'top-level hive');
isa_ok($hive->foo, 'Data::Hive', '"foo" subhive');
$hive->foo->SET(1);
is_deeply(
$hive->STORE->hash_store,
- { foo => { '' => 1 } },
+ { foo => 1 },
'changes made to store',
);
$hive->bar->baz->GET;
is_deeply(
$hive->STORE->hash_store,
- { foo => { '' => 1 } },
+ { foo => 1 },
'did not autovivify'
);
$hive->baz->quux->SET(2);
is_deeply(
$hive->STORE->hash_store,
{
- foo => { '' => 1 },
- baz => { quux => { '' => 2 } },
+ foo => 1,
+ 'baz.quux' => 2,
},
'deep set',
);
is(
$hive->foo->GET,
1,
"get the 1 from ->foo",
);
is(
$hive->foo->bar->GET,
undef,
"find nothing at ->foo->bar",
);
$hive->foo->bar->SET(3);
is(
$hive->foo->bar->GET,
3,
"wrote and retrieved 3 from ->foo->bar",
);
ok ! $hive->not->EXISTS, "non-existent key doesn't EXISTS";
ok $hive->foo->EXISTS, "existing key does EXISTS";
$hive->baz->quux->frotz->SET(4);
is_deeply(
$hive->STORE->hash_store,
{
- foo => { '' => 1, bar => { '' => 3 } },
- baz => { quux => { '' => 2, frotz => { '' => 4 } } },
+ foo => 1,
+ 'foo.bar' => 3,
+ 'baz.quux' => 2,
+ 'baz.quux.frotz' => 4,
},
"deep delete"
);
my $quux = $hive->baz->quux;
is($quux->GET, 2, "get from saved leaf");
is($quux->DELETE, 2, "delete returned old value");
is($quux->GET, undef, "after deletion, hive has no value");
is_deeply(
$hive->STORE->hash_store,
{
- foo => { '' => 1, bar => { '' => 3 } },
- baz => { quux => { frotz => { '' => 4 } } },
+ foo => 1,
+ 'foo.bar' => 3,
+ 'baz.quux.frotz' => 4,
},
"deep delete"
);
my $frotz = $hive->baz->quux->frotz;
is($frotz->GET, 4, "get from saved leaf");
is($frotz->DELETE, 4, "delete returned old value");
is($frotz->GET, undef, "after deletion, hive has no value");
is_deeply(
$hive->STORE->hash_store,
{
- foo => { '' => 1, bar => { '' => 3 } },
- baz => { quux => { } },
+ foo => 1,
+ 'foo.bar' => 3,
},
"deep delete: after a hive had no keys, it is deleted, too"
);
{
my $hive = Data::Hive->NEW({
store_class => 'Hash',
});
$hive->HIVE('and/or')->SET(1);
$hive->foo->bar->SET(4);
$hive->foo->bar->baz->SET(5);
$hive->foo->quux->baz->SET(6);
is_deeply(
[ sort $hive->KEYS ],
[ qw(and/or foo) ],
"get the top level KEYS",
);
is_deeply(
[ sort $hive->foo->KEYS ],
[ qw(bar quux) ],
"get the KEYS under foo",
);
is_deeply(
[ sort $hive->foo->bar->KEYS ],
[ qw(baz) ],
"get the KEYS under foo/bar",
);
}
done_testing;
|
rjbs/Data-Hive
|
bebe8eda5b908249872e1eeb71c88b8ec353d06a
|
split out pathpacker for re-use elsewhere
|
diff --git a/lib/Data/Hive/PathPacker/Basic.pm b/lib/Data/Hive/PathPacker/Basic.pm
new file mode 100644
index 0000000..58165aa
--- /dev/null
+++ b/lib/Data/Hive/PathPacker/Basic.pm
@@ -0,0 +1,75 @@
+use strict;
+use warnings;
+package Data::Hive::PathPacker::Basic;
+
+=begin :list
+
+= escape and unescape
+
+These coderefs are used to escape and path parts so that they can be split and
+joined without ambiguity. The callbacks will be called like this:
+
+ my $result = do {
+ local $_ = $path_part;
+ $store->$callback( $path_part );
+ }
+
+The default escape routine uses URI-like encoding on non-word characters.
+
+= join, split, and separator
+
+The C<join> coderef is used to join pre-escaped path parts. C<split> is used
+to split up a complete name before unescaping the parts.
+
+By default, they will use a simple perl join and split on the character given
+in the C<separator> option.
+
+=end :list
+
+=cut
+
+sub new {
+ my ($class, $arg) = @_;
+ $arg ||= {};
+
+ my $guts = {
+ separator => $arg->{separator} || '.',
+
+ escape => $arg->{escape} || sub {
+ my ($self, $str) = @_;
+ $str =~ s/([^a-z0-9_])/sprintf("%%%x", ord($1))/gie;
+ return $str;
+ },
+
+ unescape => $arg->{unescape} || sub {
+ my ($self, $str) = @_;
+ $str =~ s/%([0-9a-f]{2})/chr(hex($1))/ge;
+ return $str;
+ },
+
+ join => $arg->{join} || sub { join $_[0]{separator}, @{$_[1]} },
+ split => $arg->{split} || sub { split /\Q$_[0]{separator}/, $_[1] },
+ };
+
+ return bless $guts => $class;
+}
+
+sub pack_path {
+ my ($self, $path) = @_;
+
+ my $escape = $self->{escape};
+ my $join = $self->{join};
+
+ return $self->$join([ map {; $self->$escape($_) } @$path ]);
+}
+
+sub unpack_path {
+ my ($self, $str) = @_;
+
+ my $split = $self->{split};
+ my $unescape = $self->{unescape};
+
+ return [ map {; $self->$unescape($_) } $self->$split($str) ];
+}
+
+1;
diff --git a/lib/Data/Hive/Store.pm b/lib/Data/Hive/Store.pm
index 32fc335..bc0a430 100644
--- a/lib/Data/Hive/Store.pm
+++ b/lib/Data/Hive/Store.pm
@@ -1,66 +1,66 @@
use strict;
use warnings;
package Data::Hive::Store;
# ABSTRACT: a backend storage driver for Data::Hive
use Carp ();
=head1 DESCRIPTION
Data::Hive::Store is a generic interface to a backend store
for Data::Hive.
=head1 METHODS
All methods are passed at least a 'path' (arrayref of namespace pieces). Store
classes exist to operate on the entities found at named paths.
=head2 get
print $store->get(\@path, \%opt);
Return the resource represented by the given path.
=head2 set
$store->set(\@path, $value, \%opt);
Analogous to C<< get >>.
=head2 name
print $store->name(\@path, \%opt);
Return a store-specific name for the given path. This is primarily useful for
stores that may be accessed independently of the hive.
=head2 exists
if ($store->exists(\@path, \%opt)) { ... }
Returns true if the given path exists in the store.
=head2 delete
$store->delete(\@path, \%opt);
Delete the given path from the store. Return the previous value, if any.
=head2 keys
my @keys = $store->keys(\@path, \%opt);
-This returns a list of next-level path elements that exist. For more
-information on the expected behavior, see the L<KEYS method|Data:Hive/keys> in
-Data::Hive.
+This returns a list of next-level path elements that lead toward existing
+values. For more information on the expected behavior, see the L<KEYS
+method|Data:Hive/keys> in Data::Hive.
=cut
BEGIN {
for my $meth (qw(get set name exists delete keys)) {
no strict 'refs';
*$meth = sub { Carp::croak("$_[0] does not implement $meth") };
}
}
1;
diff --git a/lib/Data/Hive/Store/Param.pm b/lib/Data/Hive/Store/Param.pm
index 26f3fdb..00b966d 100644
--- a/lib/Data/Hive/Store/Param.pm
+++ b/lib/Data/Hive/Store/Param.pm
@@ -1,207 +1,165 @@
use strict;
use warnings;
package Data::Hive::Store::Param;
# ABSTRACT: CGI::param-like store for Data::Hive
=head1 DESCRIPTION
This hive store will soon be overhauled.
Basically, it expects to access a hive in an object with CGI's C<param> method,
or the numerous other things with that interface.
=method new
# use default method name 'param'
my $store = Data::Hive::Store::Param->new($obj);
# use different method name 'info'
my $store = Data::Hive::Store::Param->new($obj, { method => 'info' });
# escape certain characters in keys
my $store = Data::Hive::Store::Param->new($obj, { escape => './!' });
Return a new Param store.
Several interesting arguments can be passed in a hashref after the first
(mandatory) object argument.
=begin :list
= method
Use a different method name on the object (default is 'param').
This method should have the "usual" behavior for a C<param> method:
=for :list
* calling C<< $obj->param >> with no arguments returns all param names
* calling C<< $obj->param($name) >> returns the value for that name
* calling C<< $obj->param($name, $value) >> sets the value for the name
The Param store does not check the types of values, but for interoperation with
other stores, sticking to simple scalars is a good idea.
-= escape and unescape
+= path_packer
-These coderefs are used to escape and path parts so that they can be split and
-joined without ambiguity. The callbacks will be called like this:
+This is an object providing the L<Data::Hive::PathPacker> interface. It will
+convert a string to a path (arrayref) or the reverse.
- my $result = do {
- local $_ = $path_part;
- $store->$callback( $path_part );
- }
-
-The default escape routine uses URI-like encoding on non-word characters.
-
-= join, split, and separator
-
-The C<join> coderef is used to join pre-escaped path parts. C<split> is used
-to split up a complete name before unescaping the parts.
-
-By default, they will use a simple perl join and split on the character given
-in the C<separator> option.
= exists
This is a coderef used to check whether a given parameter name exists. It will
be called as a method on the Data::Hive::Store::Param object with the path name
as its argument.
The default behavior gets a list of all parameters and checks whether the given
name appears in it.
= delete
This is a coderef used to delete the value for a path from the hive. It will
be called as a method on the Data::Hive::Store::Param object with the path name
as its argument.
The default behavior is to call the C<delete> method on the object providing
the C<param> method.
=end :list
=cut
-sub escaped_path {
- my ($self, $path) = @_;
-
- my $escape = $self->{escape};
- my $join = $self->{join};
-
- return $self->$join([ map {; $self->$escape($_) } @$path ]);
-}
+sub path_packer { $_[0]{path_packer} }
-sub name { $_[0]->escaped_path($_[1]) }
-
-sub parsed_path {
- my ($self, $str) = @_;
-
- my $split = $self->{split};
- my $unescape = $self->{unescape};
-
- return [ map {; $self->$unescape($_) } $self->$split($str) ];
-}
+sub name { $_[0]->path_packer->pack_path($_[1]) }
sub new {
my ($class, $obj, $arg) = @_;
$arg ||= {};
my $guts = {
- obj => $obj,
+ obj => $obj,
- separator => $arg->{separator} || '.',
-
- escape => $arg->{escape} || sub {
- my ($self, $str) = @_;
- $str =~ s/([^a-z0-9_])/sprintf("%%%x", ord($1))/gie;
- return $str;
- },
-
- unescape => $arg->{unescape} || sub {
- my ($self, $str) = @_;
- $str =~ s/%([0-9a-f]{2})/chr(hex($1))/ge;
- return $str;
+ path_packer => $arg->{path_packer} || do {
+ require Data::Hive::PathPacker::Basic;
+ Data::Hive::PathPacker::Basic->new;
},
- join => $arg->{join} || sub { join $_[0]{separator}, @{$_[1]} },
- split => $arg->{split} || sub { split /\Q$_[0]{separator}/, $_[1] },
-
- method => $arg->{method} || 'param',
+ method => $arg->{method} || 'param',
- exists => $arg->{exists} || sub {
+ exists => $arg->{exists} || sub {
my ($self, $key) = @_;
my $method = $self->{method};
my $exists = grep { $key eq $_ } $self->param_store->$method;
return ! ! $exists;
},
- delete => $arg->{delete} || sub {
+ delete => $arg->{delete} || sub {
my ($self, $key) = @_;
$self->param_store->delete($key);
},
};
return bless $guts => $class;
}
sub param_store { $_[0]{obj} }
sub _param {
my $self = shift;
my $meth = $self->{method};
my $path = $self->name(shift);
return $self->param_store->$meth($path, @_);
}
sub get {
my ($self, $path) = @_;
return $self->_param($path);
}
sub set {
my ($self, $path, $val) = @_;
return $self->_param($path => $val);
}
sub exists {
my ($self, $path) = @_;
my $code = $self->{exists};
my $key = $self->name($path);
return $self->$code($key);
}
sub delete {
my ($self, $path) = @_;
my $code = $self->{delete};
my $key = $self->name($path);
return $self->$code($key);
}
sub keys {
my ($self, $path) = @_;
my $method = $self->{method};
my @names = $self->param_store->$method;
my %is_key;
PATH: for my $name (@names) {
- my $this_path = $self->parsed_path($name);
+ my $this_path = $self->path_packer->unpack_path($name);
next unless @$this_path > @$path;
for my $i (0 .. $#$path) {
next PATH unless $this_path->[$i] eq $path->[$i];
}
$is_key{ $this_path->[ $#$path + 1 ] } = 1;
}
return keys %is_key;
}
1;
diff --git a/t/param.t b/t/param.t
index 6dc5491..aefc698 100644
--- a/t/param.t
+++ b/t/param.t
@@ -1,92 +1,93 @@
#!perl
use strict;
use warnings;
use Test::More;
use Data::Hive;
use Data::Hive::Store::Param;
+use Data::Hive::PathPacker::Basic;
use Data::Hive::Test;
{
package Infostore;
sub new { bless {} => $_[0] }
sub info {
my ($self, $key, $val) = @_;
return keys %$self if @_ == 1;
$self->{$key} = $val if @_ > 2;
return $self->{$key};
}
sub delete {
my ($self, $key) = @_;
return delete $self->{$key};
}
}
Data::Hive::Test->test_new_hive(
"basic Param backed hive",
{
store_class => 'Param',
store_args => [ Infostore->new, { method => 'info' } ],
},
);
my $infostore = Infostore->new;
my $hive = Data::Hive->NEW({
store_class => 'Param',
store_args => [ $infostore, {
- method => 'info',
- separator => '/',
+ method => 'info',
+ path_packer => Data::Hive::PathPacker::Basic->new({ separator => '/' }),
} ],
});
$infostore->info(foo => 1);
$infostore->info('bar/baz' => 2);
is $hive->bar->baz->GET, 2, 'GET';
$hive->foo->SET(3);
is_deeply $infostore, { foo => 3, 'bar/baz' => 2 }, 'SET';
is $hive->bar->baz->NAME, 'bar/baz', 'NAME';
ok ! $hive->not->EXISTS, "non-existent key doesn't EXISTS";
ok $hive->foo->EXISTS, "existing key does EXISTS";
$hive->ITEM("and/or")->SET(17);
is_deeply $infostore, { foo => 3, 'bar/baz' => 2, 'and%2for' => 17 },
'SET (with escape)';
is $hive->ITEM("and/or")->GET, 17, 'GET (with escape)';
is $hive->bar->baz->DELETE, 2, "delete returns old value";
is_deeply $infostore, { foo => 3, 'and%2for' => 17 }, "delete removed item";
$hive->foo->bar->SET(4);
$hive->foo->bar->baz->SET(5);
$hive->foo->quux->baz->SET(6);
is_deeply(
[ sort $hive->KEYS ],
[ qw(and/or foo) ],
"get the top level KEYS",
);
is_deeply(
[ sort $hive->foo->KEYS ],
[ qw(bar quux) ],
"get the KEYS under foo",
);
is_deeply(
[ sort $hive->foo->bar->KEYS ],
[ qw(baz) ],
"get the KEYS under foo/bar",
);
done_testing;
|
rjbs/Data-Hive
|
73d03d171b5d6d8c1e548c2b09d8e7161ef3a791
|
clean up code and docs for Param
|
diff --git a/lib/Data/Hive/Store/Param.pm b/lib/Data/Hive/Store/Param.pm
index b167219..26f3fdb 100644
--- a/lib/Data/Hive/Store/Param.pm
+++ b/lib/Data/Hive/Store/Param.pm
@@ -1,207 +1,207 @@
use strict;
use warnings;
package Data::Hive::Store::Param;
# ABSTRACT: CGI::param-like store for Data::Hive
=head1 DESCRIPTION
This hive store will soon be overhauled.
Basically, it expects to access a hive in an object with CGI's C<param> method,
or the numerous other things with that interface.
=method new
# use default method name 'param'
my $store = Data::Hive::Store::Param->new($obj);
# use different method name 'info'
my $store = Data::Hive::Store::Param->new($obj, { method => 'info' });
# escape certain characters in keys
my $store = Data::Hive::Store::Param->new($obj, { escape => './!' });
Return a new Param store.
Several interesting arguments can be passed in a hashref after the first
(mandatory) object argument.
=begin :list
= method
Use a different method name on the object (default is 'param').
This method should have the "usual" behavior for a C<param> method:
=for :list
* calling C<< $obj->param >> with no arguments returns all param names
* calling C<< $obj->param($name) >> returns the value for that name
* calling C<< $obj->param($name, $value) >> sets the value for the name
The Param store does not check the types of values, but for interoperation with
other stores, sticking to simple scalars is a good idea.
-= escape
+= escape and unescape
-This should be a coderef that will escape each part of the path before joining
-them with C<join>. It will be called like this:
+These coderefs are used to escape and path parts so that they can be split and
+joined without ambiguity. The callbacks will be called like this:
- my $escaped_part = do {
+ my $result = do {
local $_ = $path_part;
- $store->$escape( $path_part );
+ $store->$callback( $path_part );
}
-The default escape routine URI encodes non-word characters.
+The default escape routine uses URI-like encoding on non-word characters.
-= separator
+= join, split, and separator
-String to join path segments together with; defaults to either the first
-character of the C<< escape >> option (if given) or '.'.
+The C<join> coderef is used to join pre-escaped path parts. C<split> is used
+to split up a complete name before unescaping the parts.
+
+By default, they will use a simple perl join and split on the character given
+in the C<separator> option.
= exists
-Coderef that describes how to see if a given parameter name (C<< separator
->>-joined path) exists. The default is to treat the object like a hashref and
-look inside it.
+This is a coderef used to check whether a given parameter name exists. It will
+be called as a method on the Data::Hive::Store::Param object with the path name
+as its argument.
+
+The default behavior gets a list of all parameters and checks whether the given
+name appears in it.
= delete
-Coderef that describes how to delete a given parameter name. The default is to
-treat the object like a hashref and call C<delete> on it.
+This is a coderef used to delete the value for a path from the hive. It will
+be called as a method on the Data::Hive::Store::Param object with the path name
+as its argument.
+
+The default behavior is to call the C<delete> method on the object providing
+the C<param> method.
=end :list
=cut
-sub _escape {
- my ($self, $str) = @_;
-
- $str =~ s/([^a-z0-9_])/sprintf("%%%x", ord($1))/gie;
-
- return $str;
-}
-
-sub _unescape {
- my ($self, $str) = @_;
-
- $str =~ s/%([0-9a-f]{2})/chr(hex($1))/ge;
-
- return $str;
-}
-
sub escaped_path {
my ($self, $path) = @_;
my $escape = $self->{escape};
my $join = $self->{join};
return $self->$join([ map {; $self->$escape($_) } @$path ]);
}
+sub name { $_[0]->escaped_path($_[1]) }
+
sub parsed_path {
my ($self, $str) = @_;
my $split = $self->{split};
my $unescape = $self->{unescape};
return [ map {; $self->$unescape($_) } $self->$split($str) ];
}
sub new {
my ($class, $obj, $arg) = @_;
$arg ||= {};
my $guts = {
obj => $obj,
separator => $arg->{separator} || '.',
- escape => $arg->{escape} || \&_escape,
- unescape => $arg->{unescape} || \&_unescape,
+ escape => $arg->{escape} || sub {
+ my ($self, $str) = @_;
+ $str =~ s/([^a-z0-9_])/sprintf("%%%x", ord($1))/gie;
+ return $str;
+ },
+
+ unescape => $arg->{unescape} || sub {
+ my ($self, $str) = @_;
+ $str =~ s/%([0-9a-f]{2})/chr(hex($1))/ge;
+ return $str;
+ },
join => $arg->{join} || sub { join $_[0]{separator}, @{$_[1]} },
split => $arg->{split} || sub { split /\Q$_[0]{separator}/, $_[1] },
method => $arg->{method} || 'param',
exists => $arg->{exists} || sub {
my ($self, $key) = @_;
my $method = $self->{method};
my $exists = grep { $key eq $_ } $self->param_store->$method;
return ! ! $exists;
},
delete => $arg->{delete} || sub {
my ($self, $key) = @_;
$self->param_store->delete($key);
},
};
return bless $guts => $class;
}
sub param_store { $_[0]{obj} }
sub _param {
my $self = shift;
my $meth = $self->{method};
- my $path = $self->escaped_path(shift);
+ my $path = $self->name(shift);
return $self->param_store->$meth($path, @_);
}
sub get {
my ($self, $path) = @_;
return $self->_param($path);
}
sub set {
my ($self, $path, $val) = @_;
return $self->_param($path => $val);
}
-sub name {
- my ($self, $path) = @_;
- return $self->escaped_path($path);
-}
-
sub exists {
my ($self, $path) = @_;
my $code = $self->{exists};
- my $key = $self->escaped_path($path);
+ my $key = $self->name($path);
return $self->$code($key);
}
sub delete {
my ($self, $path) = @_;
my $code = $self->{delete};
- my $key = $self->escaped_path($path);
+ my $key = $self->name($path);
return $self->$code($key);
}
sub keys {
my ($self, $path) = @_;
my $method = $self->{method};
my @names = $self->param_store->$method;
my %is_key;
PATH: for my $name (@names) {
my $this_path = $self->parsed_path($name);
next unless @$this_path > @$path;
for my $i (0 .. $#$path) {
next PATH unless $this_path->[$i] eq $path->[$i];
}
$is_key{ $this_path->[ $#$path + 1 ] } = 1;
}
return keys %is_key;
}
1;
|
rjbs/Data-Hive
|
5f59d31b19649341feae7e537ccf8a47609d66fa
|
eliminate need for URI::escape, add docs
|
diff --git a/lib/Data/Hive/Store/Param.pm b/lib/Data/Hive/Store/Param.pm
index c2cf0b8..b167219 100644
--- a/lib/Data/Hive/Store/Param.pm
+++ b/lib/Data/Hive/Store/Param.pm
@@ -1,206 +1,207 @@
use strict;
use warnings;
package Data::Hive::Store::Param;
# ABSTRACT: CGI::param-like store for Data::Hive
-use URI::Escape ();
-
=head1 DESCRIPTION
This hive store will soon be overhauled.
Basically, it expects to access a hive in an object with CGI's C<param> method,
or the numerous other things with that interface.
=method new
# use default method name 'param'
my $store = Data::Hive::Store::Param->new($obj);
# use different method name 'info'
my $store = Data::Hive::Store::Param->new($obj, { method => 'info' });
# escape certain characters in keys
my $store = Data::Hive::Store::Param->new($obj, { escape => './!' });
Return a new Param store.
Several interesting arguments can be passed in a hashref after the first
(mandatory) object argument.
=begin :list
= method
Use a different method name on the object (default is 'param').
+This method should have the "usual" behavior for a C<param> method:
+
+=for :list
+* calling C<< $obj->param >> with no arguments returns all param names
+* calling C<< $obj->param($name) >> returns the value for that name
+* calling C<< $obj->param($name, $value) >> sets the value for the name
+
+The Param store does not check the types of values, but for interoperation with
+other stores, sticking to simple scalars is a good idea.
+
= escape
This should be a coderef that will escape each part of the path before joining
them with C<join>. It will be called like this:
my $escaped_part = do {
local $_ = $path_part;
$store->$escape( $path_part );
}
The default escape routine URI encodes non-word characters.
= separator
String to join path segments together with; defaults to either the first
character of the C<< escape >> option (if given) or '.'.
= exists
Coderef that describes how to see if a given parameter name (C<< separator
>>-joined path) exists. The default is to treat the object like a hashref and
look inside it.
= delete
Coderef that describes how to delete a given parameter name. The default is to
treat the object like a hashref and call C<delete> on it.
=end :list
=cut
sub _escape {
my ($self, $str) = @_;
$str =~ s/([^a-z0-9_])/sprintf("%%%x", ord($1))/gie;
return $str;
}
sub _unescape {
my ($self, $str) = @_;
- URI::Escape::uri_unescape($str);
+ $str =~ s/%([0-9a-f]{2})/chr(hex($1))/ge;
+
+ return $str;
}
sub escaped_path {
my ($self, $path) = @_;
my $escape = $self->{escape};
my $join = $self->{join};
return $self->$join([ map {; $self->$escape($_) } @$path ]);
}
sub parsed_path {
my ($self, $str) = @_;
my $split = $self->{split};
my $unescape = $self->{unescape};
return [ map {; $self->$unescape($_) } $self->$split($str) ];
}
sub new {
my ($class, $obj, $arg) = @_;
$arg ||= {};
my $guts = {
obj => $obj,
separator => $arg->{separator} || '.',
escape => $arg->{escape} || \&_escape,
unescape => $arg->{unescape} || \&_unescape,
join => $arg->{join} || sub { join $_[0]{separator}, @{$_[1]} },
split => $arg->{split} || sub { split /\Q$_[0]{separator}/, $_[1] },
method => $arg->{method} || 'param',
exists => $arg->{exists} || sub {
my ($self, $key) = @_;
my $method = $self->{method};
my $exists = grep { $key eq $_ } $self->param_store->$method;
return ! ! $exists;
},
delete => $arg->{delete} || sub {
my ($self, $key) = @_;
$self->param_store->delete($key);
},
};
return bless $guts => $class;
}
sub param_store { $_[0]{obj} }
sub _param {
my $self = shift;
my $meth = $self->{method};
my $path = $self->escaped_path(shift);
return $self->param_store->$meth($path, @_);
}
sub get {
my ($self, $path) = @_;
return $self->_param($path);
}
sub set {
my ($self, $path, $val) = @_;
return $self->_param($path => $val);
}
sub name {
my ($self, $path) = @_;
return $self->escaped_path($path);
}
sub exists {
my ($self, $path) = @_;
my $code = $self->{exists};
my $key = $self->escaped_path($path);
return $self->$code($key);
}
sub delete {
my ($self, $path) = @_;
my $code = $self->{delete};
my $key = $self->escaped_path($path);
return $self->$code($key);
}
sub keys {
my ($self, $path) = @_;
my $method = $self->{method};
my @names = $self->param_store->$method;
my %is_key;
PATH: for my $name (@names) {
my $this_path = $self->parsed_path($name);
next unless @$this_path > @$path;
for my $i (0 .. $#$path) {
next PATH unless $this_path->[$i] eq $path->[$i];
}
$is_key{ $this_path->[ $#$path + 1 ] } = 1;
}
return keys %is_key;
}
-=head1 BUGS
-
-The interaction between escapes and separators is not very well formalized or
-tested. If you change things much, you'll probably be frustrated.
-
-Fixes and/or tests would be lovely.
-
-=cut
-
1;
|
rjbs/Data-Hive
|
a4084866f7e7b72630a6e4784e6fac03f6b983af
|
big overhaul to args to Param
|
diff --git a/lib/Data/Hive/Store/Param.pm b/lib/Data/Hive/Store/Param.pm
index 611aada..c2cf0b8 100644
--- a/lib/Data/Hive/Store/Param.pm
+++ b/lib/Data/Hive/Store/Param.pm
@@ -1,162 +1,206 @@
use strict;
use warnings;
package Data::Hive::Store::Param;
# ABSTRACT: CGI::param-like store for Data::Hive
use URI::Escape ();
=head1 DESCRIPTION
This hive store will soon be overhauled.
Basically, it expects to access a hive in an object with CGI's C<param> method,
or the numerous other things with that interface.
=method new
# use default method name 'param'
my $store = Data::Hive::Store::Param->new($obj);
# use different method name 'info'
my $store = Data::Hive::Store::Param->new($obj, { method => 'info' });
# escape certain characters in keys
my $store = Data::Hive::Store::Param->new($obj, { escape => './!' });
Return a new Param store.
Several interesting arguments can be passed in a hashref after the first
(mandatory) object argument.
=begin :list
= method
Use a different method name on the object (default is 'param').
= escape
-List of characters to escape (via URI encoding) in keys.
+This should be a coderef that will escape each part of the path before joining
+them with C<join>. It will be called like this:
-Defaults to the C<< separator >>.
+ my $escaped_part = do {
+ local $_ = $path_part;
+ $store->$escape( $path_part );
+ }
+
+The default escape routine URI encodes non-word characters.
= separator
String to join path segments together with; defaults to either the first
character of the C<< escape >> option (if given) or '.'.
= exists
Coderef that describes how to see if a given parameter name (C<< separator
>>-joined path) exists. The default is to treat the object like a hashref and
look inside it.
= delete
Coderef that describes how to delete a given parameter name. The default is to
treat the object like a hashref and call C<delete> on it.
=end :list
=cut
sub _escape {
my ($self, $str) = @_;
- my $escape = $self->{escape} or return $str;
- $str =~ s/([\Q$escape\E%])/sprintf("%%%x", ord($1))/ge;
+
+ $str =~ s/([^a-z0-9_])/sprintf("%%%x", ord($1))/gie;
+
return $str;
}
-sub _path {
+sub _unescape {
+ my ($self, $str) = @_;
+
+ URI::Escape::uri_unescape($str);
+}
+
+sub escaped_path {
my ($self, $path) = @_;
- return join $self->{separator}, map { $self->_escape($_) } @$path;
+
+ my $escape = $self->{escape};
+ my $join = $self->{join};
+
+ return $self->$join([ map {; $self->$escape($_) } @$path ]);
+}
+
+sub parsed_path {
+ my ($self, $str) = @_;
+
+ my $split = $self->{split};
+ my $unescape = $self->{unescape};
+
+ return [ map {; $self->$unescape($_) } $self->$split($str) ];
}
sub new {
my ($class, $obj, $arg) = @_;
$arg ||= {};
my $guts = {
obj => $obj,
- escape => $arg->{escape} || $arg->{separator} || '.',
- separator => $arg->{separator} || substr($arg->{escape}, 0, 1),
+
+ separator => $arg->{separator} || '.',
+
+ escape => $arg->{escape} || \&_escape,
+ unescape => $arg->{unescape} || \&_unescape,
+
+ join => $arg->{join} || sub { join $_[0]{separator}, @{$_[1]} },
+ split => $arg->{split} || sub { split /\Q$_[0]{separator}/, $_[1] },
+
method => $arg->{method} || 'param',
+
exists => $arg->{exists} || sub {
my ($self, $key) = @_;
my $method = $self->{method};
- my $exists = grep { $key eq $_ } $self->{obj}->$method;
+ my $exists = grep { $key eq $_ } $self->param_store->$method;
return ! ! $exists;
},
+
delete => $arg->{delete} || sub {
my ($self, $key) = @_;
- $self->{obj}->delete($key);
+ $self->param_store->delete($key);
},
};
return bless $guts => $class;
}
+sub param_store { $_[0]{obj} }
+
sub _param {
my $self = shift;
my $meth = $self->{method};
- my $path = $self->_path(shift);
- return $self->{obj}->$meth($path, @_);
+ my $path = $self->escaped_path(shift);
+ return $self->param_store->$meth($path, @_);
}
sub get {
my ($self, $path) = @_;
return $self->_param($path);
}
sub set {
my ($self, $path, $val) = @_;
return $self->_param($path => $val);
}
sub name {
my ($self, $path) = @_;
- return $self->_path($path);
+ return $self->escaped_path($path);
}
sub exists {
my ($self, $path) = @_;
my $code = $self->{exists};
- my $key = $self->_path($path);
+ my $key = $self->escaped_path($path);
+
return $self->$code($key);
}
sub delete {
my ($self, $path) = @_;
my $code = $self->{delete};
- my $key = $self->_path($path);
+ my $key = $self->escaped_path($path);
return $self->$code($key);
}
sub keys {
my ($self, $path) = @_;
my $method = $self->{method};
- my @names = $self->{obj}->$method;
+ my @names = $self->param_store->$method;
+
+ my %is_key;
+
+ PATH: for my $name (@names) {
+ my $this_path = $self->parsed_path($name);
- my $name = $self->_path($path);
+ next unless @$this_path > @$path;
- my $sep = $self->{separator};
+ for my $i (0 .. $#$path) {
+ next PATH unless $this_path->[$i] eq $path->[$i];
+ }
- my $start = length $name ? "$name$sep" : q{};
- my %seen = map { /\A\Q$start\E(.+?)(\z|\Q$sep\E)/ ? ($1 => 1) : () } @names;
+ $is_key{ $this_path->[ $#$path + 1 ] } = 1;
+ }
- my @keys = map { URI::Escape::uri_unescape($_) } keys %seen;
- return @keys;
+ return keys %is_key;
}
=head1 BUGS
The interaction between escapes and separators is not very well formalized or
tested. If you change things much, you'll probably be frustrated.
Fixes and/or tests would be lovely.
=cut
1;
diff --git a/t/param.t b/t/param.t
index b50627a..6dc5491 100644
--- a/t/param.t
+++ b/t/param.t
@@ -1,95 +1,92 @@
#!perl
use strict;
use warnings;
use Test::More;
use Data::Hive;
use Data::Hive::Store::Param;
use Data::Hive::Test;
{
package Infostore;
sub new { bless {} => $_[0] }
sub info {
my ($self, $key, $val) = @_;
return keys %$self if @_ == 1;
$self->{$key} = $val if @_ > 2;
return $self->{$key};
}
sub delete {
my ($self, $key) = @_;
return delete $self->{$key};
}
}
Data::Hive::Test->test_new_hive(
"basic Param backed hive",
{
store_class => 'Param',
- store_args => [ Infostore->new, {
- method => 'info',
- separator => '/',
- } ],
+ store_args => [ Infostore->new, { method => 'info' } ],
},
);
my $infostore = Infostore->new;
my $hive = Data::Hive->NEW({
store_class => 'Param',
store_args => [ $infostore, {
method => 'info',
separator => '/',
} ],
});
$infostore->info(foo => 1);
$infostore->info('bar/baz' => 2);
is $hive->bar->baz->GET, 2, 'GET';
$hive->foo->SET(3);
is_deeply $infostore, { foo => 3, 'bar/baz' => 2 }, 'SET';
is $hive->bar->baz->NAME, 'bar/baz', 'NAME';
ok ! $hive->not->EXISTS, "non-existent key doesn't EXISTS";
ok $hive->foo->EXISTS, "existing key does EXISTS";
$hive->ITEM("and/or")->SET(17);
is_deeply $infostore, { foo => 3, 'bar/baz' => 2, 'and%2for' => 17 },
'SET (with escape)';
is $hive->ITEM("and/or")->GET, 17, 'GET (with escape)';
is $hive->bar->baz->DELETE, 2, "delete returns old value";
is_deeply $infostore, { foo => 3, 'and%2for' => 17 }, "delete removed item";
$hive->foo->bar->SET(4);
$hive->foo->bar->baz->SET(5);
$hive->foo->quux->baz->SET(6);
is_deeply(
[ sort $hive->KEYS ],
[ qw(and/or foo) ],
"get the top level KEYS",
);
is_deeply(
[ sort $hive->foo->KEYS ],
[ qw(bar quux) ],
"get the KEYS under foo",
);
is_deeply(
[ sort $hive->foo->bar->KEYS ],
[ qw(baz) ],
"get the KEYS under foo/bar",
);
done_testing;
|
rjbs/Data-Hive
|
594c1f6c427e4857d082ad42f9f440018508b494
|
make ->exists in Param more universal
|
diff --git a/lib/Data/Hive/Store/Param.pm b/lib/Data/Hive/Store/Param.pm
index 5af4579..611aada 100644
--- a/lib/Data/Hive/Store/Param.pm
+++ b/lib/Data/Hive/Store/Param.pm
@@ -1,154 +1,162 @@
use strict;
use warnings;
package Data::Hive::Store::Param;
# ABSTRACT: CGI::param-like store for Data::Hive
use URI::Escape ();
=head1 DESCRIPTION
This hive store will soon be overhauled.
Basically, it expects to access a hive in an object with CGI's C<param> method,
or the numerous other things with that interface.
=method new
# use default method name 'param'
my $store = Data::Hive::Store::Param->new($obj);
# use different method name 'info'
my $store = Data::Hive::Store::Param->new($obj, { method => 'info' });
# escape certain characters in keys
my $store = Data::Hive::Store::Param->new($obj, { escape => './!' });
Return a new Param store.
Several interesting arguments can be passed in a hashref after the first
(mandatory) object argument.
=begin :list
= method
Use a different method name on the object (default is 'param').
= escape
List of characters to escape (via URI encoding) in keys.
Defaults to the C<< separator >>.
= separator
String to join path segments together with; defaults to either the first
character of the C<< escape >> option (if given) or '.'.
= exists
Coderef that describes how to see if a given parameter name (C<< separator
>>-joined path) exists. The default is to treat the object like a hashref and
look inside it.
= delete
Coderef that describes how to delete a given parameter name. The default is to
treat the object like a hashref and call C<delete> on it.
=end :list
=cut
sub _escape {
my ($self, $str) = @_;
my $escape = $self->{escape} or return $str;
$str =~ s/([\Q$escape\E%])/sprintf("%%%x", ord($1))/ge;
return $str;
}
sub _path {
my ($self, $path) = @_;
return join $self->{separator}, map { $self->_escape($_) } @$path;
}
sub new {
my ($class, $obj, $arg) = @_;
$arg ||= {};
my $guts = {
obj => $obj,
escape => $arg->{escape} || $arg->{separator} || '.',
separator => $arg->{separator} || substr($arg->{escape}, 0, 1),
method => $arg->{method} || 'param',
- exists => $arg->{exists} || sub { exists $obj->{ shift() } },
- delete => $arg->{delete} || sub { delete $obj->{ shift() } },
+ exists => $arg->{exists} || sub {
+ my ($self, $key) = @_;
+ my $method = $self->{method};
+ my $exists = grep { $key eq $_ } $self->{obj}->$method;
+ return ! ! $exists;
+ },
+ delete => $arg->{delete} || sub {
+ my ($self, $key) = @_;
+ $self->{obj}->delete($key);
+ },
};
return bless $guts => $class;
}
sub _param {
my $self = shift;
my $meth = $self->{method};
my $path = $self->_path(shift);
return $self->{obj}->$meth($path, @_);
}
sub get {
my ($self, $path) = @_;
return $self->_param($path);
}
sub set {
my ($self, $path, $val) = @_;
return $self->_param($path => $val);
}
sub name {
my ($self, $path) = @_;
return $self->_path($path);
}
sub exists {
my ($self, $path) = @_;
my $code = $self->{exists};
my $key = $self->_path($path);
- return ref($code) ? $code->($key) : $self->{obj}->$code($key);
+ return $self->$code($key);
}
sub delete {
my ($self, $path) = @_;
my $code = $self->{delete};
my $key = $self->_path($path);
- return $self->{obj}->$code($key);
+ return $self->$code($key);
}
sub keys {
my ($self, $path) = @_;
my $method = $self->{method};
my @names = $self->{obj}->$method;
my $name = $self->_path($path);
my $sep = $self->{separator};
my $start = length $name ? "$name$sep" : q{};
my %seen = map { /\A\Q$start\E(.+?)(\z|\Q$sep\E)/ ? ($1 => 1) : () } @names;
my @keys = map { URI::Escape::uri_unescape($_) } keys %seen;
return @keys;
}
=head1 BUGS
The interaction between escapes and separators is not very well formalized or
tested. If you change things much, you'll probably be frustrated.
Fixes and/or tests would be lovely.
=cut
1;
diff --git a/t/param.t b/t/param.t
index 65e049f..b50627a 100644
--- a/t/param.t
+++ b/t/param.t
@@ -1,104 +1,95 @@
#!perl
use strict;
use warnings;
use Test::More;
use Data::Hive;
use Data::Hive::Store::Param;
use Data::Hive::Test;
{
package Infostore;
sub new { bless {} => $_[0] }
sub info {
my ($self, $key, $val) = @_;
return keys %$self if @_ == 1;
$self->{$key} = $val if @_ > 2;
return $self->{$key};
}
- sub info_exists {
- my ($self, $key) = @_;
- return exists $self->{$key};
- }
-
- sub info_delete {
+ sub delete {
my ($self, $key) = @_;
return delete $self->{$key};
}
}
Data::Hive::Test->test_new_hive(
"basic Param backed hive",
{
store_class => 'Param',
store_args => [ Infostore->new, {
method => 'info',
separator => '/',
- exists => 'info_exists',
- delete => 'info_delete',
} ],
},
);
my $infostore = Infostore->new;
my $hive = Data::Hive->NEW({
store_class => 'Param',
store_args => [ $infostore, {
method => 'info',
separator => '/',
- exists => 'info_exists',
- delete => 'info_delete',
} ],
});
$infostore->info(foo => 1);
$infostore->info('bar/baz' => 2);
is $hive->bar->baz->GET, 2, 'GET';
$hive->foo->SET(3);
is_deeply $infostore, { foo => 3, 'bar/baz' => 2 }, 'SET';
is $hive->bar->baz->NAME, 'bar/baz', 'NAME';
ok ! $hive->not->EXISTS, "non-existent key doesn't EXISTS";
ok $hive->foo->EXISTS, "existing key does EXISTS";
$hive->ITEM("and/or")->SET(17);
is_deeply $infostore, { foo => 3, 'bar/baz' => 2, 'and%2for' => 17 },
'SET (with escape)';
is $hive->ITEM("and/or")->GET, 17, 'GET (with escape)';
is $hive->bar->baz->DELETE, 2, "delete returns old value";
is_deeply $infostore, { foo => 3, 'and%2for' => 17 }, "delete removed item";
$hive->foo->bar->SET(4);
$hive->foo->bar->baz->SET(5);
$hive->foo->quux->baz->SET(6);
is_deeply(
[ sort $hive->KEYS ],
[ qw(and/or foo) ],
"get the top level KEYS",
);
is_deeply(
[ sort $hive->foo->KEYS ],
[ qw(bar quux) ],
"get the KEYS under foo",
);
is_deeply(
[ sort $hive->foo->bar->KEYS ],
[ qw(baz) ],
"get the KEYS under foo/bar",
);
done_testing;
|
rjbs/Data-Hive
|
50fe1c609b4daf5001cfefeca1ca887574cf010b
|
tweak Param->new prepping to fix it
|
diff --git a/lib/Data/Hive/Store/Param.pm b/lib/Data/Hive/Store/Param.pm
index 59bf05e..5af4579 100644
--- a/lib/Data/Hive/Store/Param.pm
+++ b/lib/Data/Hive/Store/Param.pm
@@ -1,150 +1,154 @@
use strict;
use warnings;
package Data::Hive::Store::Param;
# ABSTRACT: CGI::param-like store for Data::Hive
use URI::Escape ();
=head1 DESCRIPTION
This hive store will soon be overhauled.
Basically, it expects to access a hive in an object with CGI's C<param> method,
or the numerous other things with that interface.
=method new
# use default method name 'param'
my $store = Data::Hive::Store::Param->new($obj);
# use different method name 'info'
my $store = Data::Hive::Store::Param->new($obj, { method => 'info' });
# escape certain characters in keys
my $store = Data::Hive::Store::Param->new($obj, { escape => './!' });
Return a new Param store.
Several interesting arguments can be passed in a hashref after the first
(mandatory) object argument.
=begin :list
= method
Use a different method name on the object (default is 'param').
= escape
List of characters to escape (via URI encoding) in keys.
Defaults to the C<< separator >>.
= separator
String to join path segments together with; defaults to either the first
character of the C<< escape >> option (if given) or '.'.
= exists
Coderef that describes how to see if a given parameter name (C<< separator
>>-joined path) exists. The default is to treat the object like a hashref and
look inside it.
= delete
Coderef that describes how to delete a given parameter name. The default is to
treat the object like a hashref and call C<delete> on it.
=end :list
=cut
sub _escape {
my ($self, $str) = @_;
my $escape = $self->{escape} or return $str;
$str =~ s/([\Q$escape\E%])/sprintf("%%%x", ord($1))/ge;
return $str;
}
sub _path {
my ($self, $path) = @_;
return join $self->{separator}, map { $self->_escape($_) } @$path;
}
sub new {
my ($class, $obj, $arg) = @_;
- $arg ||= {};
- $arg->{escape} ||= $arg->{separator} || '.';
- $arg->{separator} ||= substr($arg->{escape}, 0, 1);
- $arg->{method} ||= 'param';
- $arg->{exists} ||= sub { exists $obj->{shift()} };
- $arg->{delete} ||= sub { delete $obj->{shift()} };
- $arg->{obj} = $obj;
- return bless { %$arg } => $class;
+ $arg ||= {};
+
+ my $guts = {
+ obj => $obj,
+ escape => $arg->{escape} || $arg->{separator} || '.',
+ separator => $arg->{separator} || substr($arg->{escape}, 0, 1),
+ method => $arg->{method} || 'param',
+ exists => $arg->{exists} || sub { exists $obj->{ shift() } },
+ delete => $arg->{delete} || sub { delete $obj->{ shift() } },
+ };
+
+ return bless $guts => $class;
}
sub _param {
my $self = shift;
my $meth = $self->{method};
my $path = $self->_path(shift);
return $self->{obj}->$meth($path, @_);
}
sub get {
my ($self, $path) = @_;
return $self->_param($path);
}
sub set {
my ($self, $path, $val) = @_;
return $self->_param($path => $val);
}
sub name {
my ($self, $path) = @_;
return $self->_path($path);
}
sub exists {
my ($self, $path) = @_;
my $code = $self->{exists};
my $key = $self->_path($path);
return ref($code) ? $code->($key) : $self->{obj}->$code($key);
}
sub delete {
my ($self, $path) = @_;
my $code = $self->{delete};
my $key = $self->_path($path);
return $self->{obj}->$code($key);
}
sub keys {
my ($self, $path) = @_;
my $method = $self->{method};
my @names = $self->{obj}->$method;
my $name = $self->_path($path);
my $sep = $self->{separator};
my $start = length $name ? "$name$sep" : q{};
my %seen = map { /\A\Q$start\E(.+?)(\z|\Q$sep\E)/ ? ($1 => 1) : () } @names;
my @keys = map { URI::Escape::uri_unescape($_) } keys %seen;
return @keys;
}
=head1 BUGS
The interaction between escapes and separators is not very well formalized or
tested. If you change things much, you'll probably be frustrated.
Fixes and/or tests would be lovely.
=cut
1;
|
rjbs/Data-Hive
|
511d5492a1e100bbbec7b76b17b7b12ac36a03a8
|
fix a bug in ->EXISTS on intermediate empty hives
|
diff --git a/lib/Data/Hive/Store/Hash.pm b/lib/Data/Hive/Store/Hash.pm
index fb29ae4..b6ae420 100644
--- a/lib/Data/Hive/Store/Hash.pm
+++ b/lib/Data/Hive/Store/Hash.pm
@@ -1,232 +1,233 @@
use strict;
use warnings;
package Data::Hive::Store::Hash;
# ABSTRACT: store a hive in nested hashrefs
=head1 DESCRIPTION
This is a simple store, primarily for testing, that will store hives in nested
hashrefs. All hives are represented as hashrefs, and their values are stored
in the entry for the empty string.
So, we could do this:
my $href = {};
my $hive = Data::Hive->NEW({
store_class => 'Hash',
store_args => [ $href ],
});
$hive->foo->SET(1);
$hive->foo->bar->baz->SET(2);
We would end up with C<$href> containing:
{
foo => {
'' => 1,
bar => {
baz => {
'' => 2,
},
},
},
}
Using empty keys results in a bigger, uglier dump, but allows a given hive to
contain both a value and subhives. B<Please note> that this is different
behavior compared with earlier releases, in which empty keys were not used and
it was not legal to have a value and a hive at a given path. It is possible,
although fairly unlikely, that this format will change again. The Hash store
should generally be used for testing things that use a hive, as opposed for
building hashes that will be used for anything else.
=method new
my $store = Data::Hive::Store::Hash->new(\%hash);
The only argument expected for C<new> is a hashref, which is the hashref in
which hive entries are stored.
If no hashref is provided, a new, empty hashref will be used.
=cut
sub new {
my ($class, $href) = @_;
$href = {} unless defined $href;
return bless { store => $href } => $class;
}
=method hash_store
This method returns the hashref in which things are being used. You should not
alter its contents!
=cut
sub hash_store {
$_[0]->{store}
}
sub _die {
require Carp::Clan;
Carp::Clan->import('^Data::Hive($|::)');
croak(shift);
}
my $BREAK = "BREAK\n";
# Wow, this is quite a little machine! Here's a slightly simplified overview
# of what it does: -- rjbs, 2010-08-27
#
# As long as cond->(\@remaining_path) is true, execute step->($next,
# $current_hashref, \@remaining_path)
#
# If it dies with $BREAK, stop looping and return. Once the cond returns
# false, return end->($current_hashref, \@remaining_path)
sub _descend {
my ($self, $orig_path, $arg) = @_;
my @path = @$orig_path;
$arg ||= {};
$arg->{step} or die "step is required";
$arg->{cond} ||= sub { @{ shift() } };
$arg->{end} ||= sub { $_[0] };
my $node = $self->hash_store;
while ($arg->{cond}->(\@path)) {
my $seg = shift @path;
{
local $SIG{__DIE__};
eval { $arg->{step}->($seg, $node, \@path) };
}
return if $@ and $@ eq $BREAK;
die $@ if $@;
$node = $node->{$seg} ||= {};
}
return $arg->{end}->($node, \@path);
}
sub get {
my ($self, $path) = @_;
return $self->_descend(
$path, {
end => sub { $_[0]->{''} },
step => sub {
my ($seg, $node) = @_;
if (defined $node and not ref $node) {
# We found a bogus entry in the store! -- rjbs, 2010-08-27
_die("can't get key '$seg' of non-ref value '$node'");
}
die $BREAK unless exists $node->{$seg};
}
}
);
}
sub set {
my ($self, $path, $value) = @_;
return $self->_descend(
$path, {
step => sub {
my ($seg, $node, $path) = @_;
if (exists $node->{$seg} and not ref $node->{$seg}) {
_die("can't overwrite existing non-ref value: '$node->{$seg}'");
}
},
cond => sub { @{ shift() } > 1 },
end => sub {
my ($node, $path) = @_;
$node->{$path->[0]}{''} = $value;
},
},
);
}
=method name
The name returned by the Hash store is a string, potentially suitable for
eval-ing, describing a hash dereference of a variable called C<< $STORE >>.
"$STORE->{foo}->{bar}"
This is probably not very useful.
=cut
sub name {
my ($self, $path) = @_;
return join '->', '$STORE', map { "{'$_'}" } @$path;
}
sub exists {
my ($self, $path) = @_;
return $self->_descend(
$path, {
step => sub {
my ($seg, $node) = @_;
die $BREAK unless exists $node->{$seg};
},
+ end => sub { return exists $_[0]->{''}; },
},
);
}
sub delete {
my ($self, $path) = @_;
return $self->_descend(
$path, {
step => sub {
my ($seg, $node) = @_;
die $BREAK unless exists $node->{$seg};
},
cond => sub { @{ shift() } > 1 },
end => sub {
my ($node, $final_path) = @_;
my $this = $node->{ $final_path->[0] };
my $rv = delete $this->{''};
# Cleanup empty trees after deletion! It would be convenient to have
# ->_ascend, but I'm not likely to bother with writing it just yet.
# -- rjbs, 2010-08-27
$self->_descend(
$path, {
step => sub {
my ($seg, $node) = @_;
return if keys %{ $node->{$seg} };
delete $node->{$seg};
die $BREAK;
},
}
);
return $rv;
},
},
);
}
sub keys {
my ($self, $path) = @_;
return $self->_descend($path, {
step => sub {
my ($seg, $node) = @_;
die $BREAK unless exists $node->{$seg};
},
end => sub {
return grep { length } keys %{ $_[0] };
},
});
}
1;
|
rjbs/Data-Hive
|
e92fdcd37a3fcee53c39e9271b953543f79a800b
|
better Data::Hive::Test tests
|
diff --git a/lib/Data/Hive/Test.pm b/lib/Data/Hive/Test.pm
index 84cb389..347acb9 100644
--- a/lib/Data/Hive/Test.pm
+++ b/lib/Data/Hive/Test.pm
@@ -1,127 +1,168 @@
use strict;
use warnings;
package Data::Hive::Test;
# ABSTRACT: a bundle of tests for Data::Hive stores
use Data::Hive;
use Test::More 0.94; # subtest
=head1 SYNOPSIS
use Test::More;
use Data::Hive::Test;
use Data::Hive::Store::MyNewStore;
Data::Hive::Test->test_new_hive({ store_class => 'MyNewStore' });
# rest of your tests for your store
done_testing;
=head1 DESCRIPTION
Data::Hive::Test is a library of tests that should be passable for any
conformant L<Data::Hive::Store> implementation. It provides a method for
running a suite of tests -- which may expand or change -- that check the
behavior of a hive store by building a hive around it and testing its behavior.
=method test_new_hive
Data::Hive::Test->test_new_hive( $desc, \%args_to_NEW );
This method expects an (optional) description followed by a hashref of
arguments to be passed to Data::Hive's C<L<NEW|Data::Hive/NEW>> method. A new
hive will be constructed with those arguments and a single subtest will be run,
including subtests that should pass against any conformant Data::Hive::Store
implementation.
If the tests pass, the method will return the hive. If they fail, the method
will return false.
=cut
sub test_new_hive {
my ($self, $desc, $arg) = @_;
if (@_ == 2) {
$arg = $desc;
$desc = "hive tests from Data::Hive::Test";
}
$desc = "Data::Hive::Test: $desc";
my $hive;
my $passed = subtest $desc => sub {
$hive = Data::Hive->NEW($arg);
isa_ok($hive, 'Data::Hive');
subtest 'value of one' => sub {
ok(! $hive->one->EXISTS, "before being set, ->one doesn't EXISTS");
$hive->one->SET(1);
ok($hive->one->EXISTS, "after being set, ->one EXISTS");
is($hive->one->GET, 1, "->one->GET is 1");
is($hive->one->GET(10), 1, "->one->GET(10) is 1");
};
subtest 'value of zero' => sub {
ok(! $hive->zero->EXISTS, "before being set, ->zero doesn't EXISTS");
$hive->zero->SET(0);
ok($hive->zero->EXISTS, "after being set, ->zero EXISTS");
is($hive->zero->GET, 0, "->zero->GET is 0");
is($hive->zero->GET(10), 0, "->zero->GET(10) is 0");
};
subtest 'value of empty string' => sub {
ok(! $hive->empty->EXISTS, "before being set, ->empty doesn't EXISTS");
$hive->empty->SET('');
ok($hive->empty->EXISTS, "after being set, ->empty EXISTS");
- is($hive->empty->GET, '', "/empty is ''");
+ is($hive->empty->GET, '', "->empty->GET is ''");
is($hive->empty->GET(10), '', "->empty->GET(10) is ''");
};
subtest 'undef, existing value' => sub {
ok(! $hive->undef->EXISTS, "before being set, ->undef doesn't EXISTS");
$hive->undef->SET(undef);
ok($hive->undef->EXISTS, "after being set, ->undef EXISTS");
- is($hive->undef->GET, undef, "/undef is undef");
+ is($hive->undef->GET, undef, "->undef->GET is undef");
+ is($hive->undef->GET(10), 10, "->undef->GET(10) is undef");
};
subtest 'non-existing value' => sub {
ok(! $hive->missing->EXISTS, "before being set, ->missing doesn't EXISTS");
is($hive->missing->GET, undef, "->missing is undef");
ok(! $hive->missing->EXISTS, "mere GET-ing won't cause ->missing to EXIST");
- is($hive->missing->GET(1), 1, " == ->missing->GET(1)");
- is($hive->missing->GET(0), 0, "0 == ->missing->GET(0)");
- is($hive->missing->GET(''), '', "'' == ->missing->GET('')");
+ is($hive->missing->GET(10), 10, "->missing->GET(10) is 10");
+ };
+
+ subtest 'nested value' => sub {
+ ok(
+ ! $hive->two->EXISTS,
+ "before setting ->two->deep, ->two doesn't EXISTS"
+ );
+
+ ok(
+ ! $hive->two->deep->EXISTS,
+ "before setting ->two->deep, ->two->deep doesn't EXISTS"
+ );
+
+ is(
+ $hive->two->deep->GET,
+ undef,
+ "before being set, ->two->deep is undef"
+ );
+
+ $hive->two->deep->SET('2D');
+
+ ok(
+ ! $hive->two->EXISTS,
+ "after setting ->two->deep, ->two still doesn't EXISTS"
+ );
+
+ ok(
+ $hive->two->deep->EXISTS,
+ "after setting ->two->deep, ->two->deep EXISTS"
+ );
+
+ is(
+ $hive->two->deep->GET,
+ '2D',
+ "after being set, ->two->deep->GET returns '2D'",
+ );
+
+ is(
+ $hive->two->deep->GET(10),
+ '2D',
+ "after being set, ->two->deep->GET(10) returns '2D'",
+ );
};
is_deeply(
[ sort $hive->KEYS ],
- [ qw(empty one undef zero) ],
- "we have the right top-level keys",
+ [ qw(empty one two undef zero) ],
+ "in the end, we have the right top-level keys",
);
};
return $passed ? $hive : ();
}
1;
|
rjbs/Data-Hive
|
c4d95e58f3ee02b52f47534d076dfec34a3e84be
|
document the deprecation of GETSTR, GETNUM, and overload
|
diff --git a/lib/Data/Hive.pm b/lib/Data/Hive.pm
index 6f521f9..d6edb7b 100644
--- a/lib/Data/Hive.pm
+++ b/lib/Data/Hive.pm
@@ -1,371 +1,373 @@
use strict;
use warnings;
package Data::Hive;
# ABSTRACT: convenient access to hierarchical data
use Carp ();
=head1 SYNOPSIS
use Data::Hive;
my $hive = Data::Hive->NEW(\%arg);
$hive->foo->bar->quux->SET(17);
print $hive->foo->bar->baz->quux->GET; # 17
=head1 DESCRIPTION
Data::Hive doesn't do very much. Its main purpose is to provide a simple,
consistent interface for accessing simple, nested data dictionaries. The
mechanism for storing or consulting these dictionaries is abstract, so it can
be replaced without altering any of the code that reads or writes the hive.
A hive is like a set of nested hash references, but with a few crucial
differences:
=begin :list
* a hive is always accessed by methods, never by dereferencing with C<< ->{} >>
For example, these two lines perform similar tasks:
$href->{foo}->{bar}->{baz}
$hive->foo->bar->baz->GET
* every key may have a value as well as children
With nested hashrefs, each entry is either another hashref (representing
children in the tree) or a leaf node. With a hive, each entry may be either or
both. For example, we can do this:
$hive->entry->SET(1);
$hive->entry->child->SET(1)
This wouldn't be possible with a hashref, because C<< $href->{entry} >> could
not hold both another node and a simple value.
It also means that along the ways to existing values in a hive, there might be
paths with no existing value.
$hive->NEW(...); # create a new hive with no entries
$hive->foo->bar->baz->SET(1); # set a single value
$hive->foo->EXISTS; # false! no value exists here
grep { 'foo' eq $_ } $hive->KEYS; # true! we can descent down this path
$hive->foo->bar->baz->EXISTS; # true! there is a value here
* hives are accessed by path, not by name
When you call C<< $hive->foo->bar->baz->GET >>, you're not accessing several
substructures. You're accessing I<one> hive. When the C<GET> method is
reached, the intervening names are converted into an entry path and I<that> is
accessed. Paths are made of zero or more non-empty strings. In other words,
while this is legal:
$href->{foo}->{''}->baz;
It is not legal to have an empty part in a hive path.
=end :list
=head1 WHY??
By using method access, the behavior of hives can be augmented as needed during
testing or development. Hives can be easily collapsed to single key/value
pairs using simple notations whereby C<< $hive->foo->bar->baz->SET(1) >>
becomes C<< $storage->{"foo.bar.baz"} = 1 >> or something similar.
This, along with the L<Data::Hive::Store> API makes it very easy to swap out
the storage and retrieval mechanism used for keeping hives in persistent
storage. It's trivial to persist entire hives into a database, flatfile, CGI
query, or many other structures, without using weird tricks beyond the weird
trick that is Data::Hive itself.
=head1 METHODS
=head2 hive path methods
All lowercase methods are used to travel down hive paths.
When you call C<< $hive->some_name >>, the return value is another Data::Hive
object using the same store as C<$hive> but with a starting path of
C<some_name>. With that hive, you can descend to deeper hives or you can get
or set its value.
Once you've reached the path where you want to perform a lookup or alteration,
you call an all-uppercase method. These are detailed below.
=head2 hive access methods
These methods are thin wrappers around required modules in L<Data::Hive::Store>
subclasses. These methods all basically call a method on the store with the
same (but lowercased) name and pass it the hive's path:
=for :list
* EXISTS
* GET
* SET
* NAME
* DELETE
* KEYS
=head2 NEW
This constructs a new hive object. Note that the name is C<NEW> and not
C<new>! The C<new> method is just another method to pick a hive path part.
The following are valid arguments for C<NEW>.
=begin :list
= store
a L<Data::Hive::Store> object, or one with a compatible interface; this will be
used as the hive's backend storage driver; do not supply C<store_class> or
C<store_args> if C<store> is supplied
= store_class
This names a class from which to instantiate a storage driver. The classname
will have C<Data::Hive::Store::> prepended; to avoid this, prefix it with a '='
(C<=My::Store>). A plus sign can be used instead of an equal sign, for
historical reasons.
= store_args
If C<store_class> has been provided instead of C<store>, this argument may be
given as an arrayref of arguments to pass (dereferenced) to the store class's
C<new> method.
=end :list
=cut
sub NEW {
my ($class, $arg) = @_;
$arg ||= {};
my @path = @{ $arg->{path} || [] };
my $self = bless { path => \@path } => ref($class) || $class;
if ($arg->{store_class}) {
die "don't use 'store' with 'store_class' and 'store_args'"
if $arg->{store};
$arg->{store_class} = "Data::Hive::Store::$arg->{store_class}"
unless $arg->{store_class} =~ s/^[+=]//;
$self->{store} = $arg->{store_class}->new(@{ $arg->{store_args} || [] });
} elsif ($arg->{store}) {
$self->{store} = $arg->{store};
} else {
Carp::croak "can't create a hive with no store";
}
return $self;
}
=head2 GET
my $value = $hive->some->path->GET( $default );
The C<GET> method gets the hive value. If there is no defined value at the
path and a default has been supplied, the default will be returned instead.
-=head2 GETNUM
+This method may also be called as C<GETSTR> or C<GETNUM> for backward
+compatibility, but this is deprecated and will be removed in a future release.
-=head2 GETSTR
+=head3 overloading
-These are provided soley for Perl 5.6.1 compatability, where returning undef
-from overloaded numification/stringification can cause a segfault. They are
-used internally by the deprecated overloadings for hives.
+Hives are overloaded for stringification and numification so that they behave
+like their value when used without an explicit C<GET>. This behavior is
+deprecated and will be removed in a future release. Always use C<GET> to get
+the value of a hive.
=cut
use overload (
q{""} => sub {
Carp::carp "using hive as string for implicit GET is deprecated";
shift->GET(@_);
},
q{0+} => sub {
Carp::carp "using hive as number for implicit GET is deprecated";
shift->GET(@_);
},
fallback => 1,
);
sub GET {
my ($self, $default) = @_;
my $value = $self->STORE->get($self->{path});
return defined $value ? $value : $default;
}
sub GETNUM {
Carp::carp "GETNUM method is deprecated";
shift->GET(@_);
}
sub GETSTR {
Carp::carp "GETSTR method is deprecated";
shift->GET(@_);
}
=head2 SET
$hive->some->path->SET(10);
This method sets (replacing, if necessary) the hive value.
Its return value is not defined.
=cut
sub SET {
my $self = shift;
return $self->STORE->set($self->{path}, @_);
}
=head2 EXISTS
if ($hive->foo->bar->EXISTS) { ... }
This method tests whether a value (even an undefined one) exists for the hive.
=cut
sub EXISTS {
my $self = shift;
return $self->STORE->exists($self->{path});
}
=head2 DELETE
$hive->foo->bar->DELETE;
This method deletes the hive's value. The deleted value is returned. If no
value had existed, C<undef> is returned.
=cut
sub DELETE {
my $self = shift;
return $self->STORE->delete($self->{path});
}
=head2 KEYS
my @keys = $hive->KEYS;
This returns a list of next-level path elements that exist. For example, given
a hive with values for the following paths:
foo
foo/bar
foo/bar/baz
foo/xyz/abc
foo/xyz/def
foo/123
This shows the expected results:
keys of | returns
-------------+------------
foo | bar, xyz, 123
foo/bar | baz
foo/bar/baz |
foo/xyz | abc, def
foo/123 |
=cut
sub KEYS {
my ($self) = @_;
return $self->STORE->keys($self->{path});
}
=head2 HIVE
$hive->HIVE('foo'); # equivalent to $hive->foo
This method returns a subhive of the current hive. In most cases, it is
simpler to use the lowercase hive access method. This method is useful when
you must, for some reason, access an entry whose name is not a valid Perl
method name.
It is also needed if you must access a path with the same name as a method in
C<UNIVERSAL>. In general, only C<import>, C<isa>, and C<can> should fall into
this category, but some libraries unfortunately add methods to C<UNIVERSAL>.
Common offenders include C<moniker>, C<install_sub>, C<reinstall_sub>.
This method should be needed fairly rarely. It may also be called as C<ITEM>
for historical reasons.
=cut
sub ITEM {
my ($self, @rest) = @_;
return $self->HIVE(@rest);
}
sub HIVE {
my ($self, $key) = @_;
if (! defined $key or ! length $key or ref $key) {
$key = '(undef)' unless defined $key;
Carp::croak "illegal hive path part: $key";
}
return $self->NEW({
%$self,
path => [ @{$self->{path}}, $key ],
});
}
=head2 NAME
This method returns a name that can be used to represent the hive's path. This
name is B<store-dependent>, and should not be relied upon if the store may
change. It is provided primarily for debugging.
=cut
sub NAME {
my $self = shift;
return $self->STORE->name($self->{path});
}
=head2 STORE
This method returns the storage driver being used by the hive.
=cut
sub STORE {
return $_[0]->{store}
}
sub AUTOLOAD {
my $self = shift;
our $AUTOLOAD;
(my $method = $AUTOLOAD) =~ s/.*:://;
die "AUTOLOAD for '$method' called on non-object" unless ref $self;
return if $method eq 'DESTROY';
if ($method =~ /^[A-Z]+$/) {
Carp::croak("all-caps method names are reserved: '$method'");
}
return $self->HIVE($method);
}
1;
|
rjbs/Data-Hive
|
770d3ab284304c1bb5f45448d6aee2de0ecaa430
|
document test library
|
diff --git a/lib/Data/Hive/Test.pm b/lib/Data/Hive/Test.pm
index 3c5cac1..84cb389 100644
--- a/lib/Data/Hive/Test.pm
+++ b/lib/Data/Hive/Test.pm
@@ -1,90 +1,127 @@
use strict;
use warnings;
package Data::Hive::Test;
# ABSTRACT: a bundle of tests for Data::Hive stores
-use Test::More;
+use Data::Hive;
+
+use Test::More 0.94; # subtest
+
+=head1 SYNOPSIS
+
+ use Test::More;
+
+ use Data::Hive::Test;
+ use Data::Hive::Store::MyNewStore;
+
+ Data::Hive::Test->test_new_hive({ store_class => 'MyNewStore' });
+
+ # rest of your tests for your store
+
+ done_testing;
+
+=head1 DESCRIPTION
+
+Data::Hive::Test is a library of tests that should be passable for any
+conformant L<Data::Hive::Store> implementation. It provides a method for
+running a suite of tests -- which may expand or change -- that check the
+behavior of a hive store by building a hive around it and testing its behavior.
+
+=method test_new_hive
+
+ Data::Hive::Test->test_new_hive( $desc, \%args_to_NEW );
+
+This method expects an (optional) description followed by a hashref of
+arguments to be passed to Data::Hive's C<L<NEW|Data::Hive/NEW>> method. A new
+hive will be constructed with those arguments and a single subtest will be run,
+including subtests that should pass against any conformant Data::Hive::Store
+implementation.
+
+If the tests pass, the method will return the hive. If they fail, the method
+will return false.
+
+=cut
sub test_new_hive {
my ($self, $desc, $arg) = @_;
if (@_ == 2) {
$arg = $desc;
$desc = "hive tests from Data::Hive::Test";
}
$desc = "Data::Hive::Test: $desc";
my $hive;
my $passed = subtest $desc => sub {
$hive = Data::Hive->NEW($arg);
isa_ok($hive, 'Data::Hive');
subtest 'value of one' => sub {
ok(! $hive->one->EXISTS, "before being set, ->one doesn't EXISTS");
$hive->one->SET(1);
ok($hive->one->EXISTS, "after being set, ->one EXISTS");
is($hive->one->GET, 1, "->one->GET is 1");
is($hive->one->GET(10), 1, "->one->GET(10) is 1");
};
subtest 'value of zero' => sub {
ok(! $hive->zero->EXISTS, "before being set, ->zero doesn't EXISTS");
$hive->zero->SET(0);
ok($hive->zero->EXISTS, "after being set, ->zero EXISTS");
is($hive->zero->GET, 0, "->zero->GET is 0");
is($hive->zero->GET(10), 0, "->zero->GET(10) is 0");
};
subtest 'value of empty string' => sub {
ok(! $hive->empty->EXISTS, "before being set, ->empty doesn't EXISTS");
$hive->empty->SET('');
ok($hive->empty->EXISTS, "after being set, ->empty EXISTS");
is($hive->empty->GET, '', "/empty is ''");
is($hive->empty->GET(10), '', "->empty->GET(10) is ''");
};
subtest 'undef, existing value' => sub {
ok(! $hive->undef->EXISTS, "before being set, ->undef doesn't EXISTS");
$hive->undef->SET(undef);
ok($hive->undef->EXISTS, "after being set, ->undef EXISTS");
is($hive->undef->GET, undef, "/undef is undef");
};
subtest 'non-existing value' => sub {
ok(! $hive->missing->EXISTS, "before being set, ->missing doesn't EXISTS");
is($hive->missing->GET, undef, "->missing is undef");
ok(! $hive->missing->EXISTS, "mere GET-ing won't cause ->missing to EXIST");
is($hive->missing->GET(1), 1, " == ->missing->GET(1)");
is($hive->missing->GET(0), 0, "0 == ->missing->GET(0)");
is($hive->missing->GET(''), '', "'' == ->missing->GET('')");
};
is_deeply(
[ sort $hive->KEYS ],
[ qw(empty one undef zero) ],
"we have the right top-level keys",
);
};
return $passed ? $hive : ();
}
1;
|
rjbs/Data-Hive
|
6c3e7b43369dabf4313897f1db3287d650e74611
|
refactor the default tests into a reusable library
|
diff --git a/lib/Data/Hive.pm b/lib/Data/Hive.pm
index ad4ac52..6f521f9 100644
--- a/lib/Data/Hive.pm
+++ b/lib/Data/Hive.pm
@@ -1,362 +1,371 @@
use strict;
use warnings;
package Data::Hive;
# ABSTRACT: convenient access to hierarchical data
use Carp ();
=head1 SYNOPSIS
use Data::Hive;
my $hive = Data::Hive->NEW(\%arg);
$hive->foo->bar->quux->SET(17);
print $hive->foo->bar->baz->quux->GET; # 17
=head1 DESCRIPTION
Data::Hive doesn't do very much. Its main purpose is to provide a simple,
consistent interface for accessing simple, nested data dictionaries. The
mechanism for storing or consulting these dictionaries is abstract, so it can
be replaced without altering any of the code that reads or writes the hive.
A hive is like a set of nested hash references, but with a few crucial
differences:
=begin :list
* a hive is always accessed by methods, never by dereferencing with C<< ->{} >>
For example, these two lines perform similar tasks:
$href->{foo}->{bar}->{baz}
$hive->foo->bar->baz->GET
* every key may have a value as well as children
With nested hashrefs, each entry is either another hashref (representing
children in the tree) or a leaf node. With a hive, each entry may be either or
both. For example, we can do this:
$hive->entry->SET(1);
$hive->entry->child->SET(1)
This wouldn't be possible with a hashref, because C<< $href->{entry} >> could
not hold both another node and a simple value.
It also means that along the ways to existing values in a hive, there might be
paths with no existing value.
$hive->NEW(...); # create a new hive with no entries
$hive->foo->bar->baz->SET(1); # set a single value
$hive->foo->EXISTS; # false! no value exists here
grep { 'foo' eq $_ } $hive->KEYS; # true! we can descent down this path
$hive->foo->bar->baz->EXISTS; # true! there is a value here
* hives are accessed by path, not by name
When you call C<< $hive->foo->bar->baz->GET >>, you're not accessing several
substructures. You're accessing I<one> hive. When the C<GET> method is
reached, the intervening names are converted into an entry path and I<that> is
accessed. Paths are made of zero or more non-empty strings. In other words,
while this is legal:
$href->{foo}->{''}->baz;
It is not legal to have an empty part in a hive path.
=end :list
=head1 WHY??
By using method access, the behavior of hives can be augmented as needed during
testing or development. Hives can be easily collapsed to single key/value
pairs using simple notations whereby C<< $hive->foo->bar->baz->SET(1) >>
becomes C<< $storage->{"foo.bar.baz"} = 1 >> or something similar.
This, along with the L<Data::Hive::Store> API makes it very easy to swap out
the storage and retrieval mechanism used for keeping hives in persistent
storage. It's trivial to persist entire hives into a database, flatfile, CGI
query, or many other structures, without using weird tricks beyond the weird
trick that is Data::Hive itself.
=head1 METHODS
=head2 hive path methods
All lowercase methods are used to travel down hive paths.
When you call C<< $hive->some_name >>, the return value is another Data::Hive
object using the same store as C<$hive> but with a starting path of
C<some_name>. With that hive, you can descend to deeper hives or you can get
or set its value.
Once you've reached the path where you want to perform a lookup or alteration,
you call an all-uppercase method. These are detailed below.
=head2 hive access methods
These methods are thin wrappers around required modules in L<Data::Hive::Store>
subclasses. These methods all basically call a method on the store with the
same (but lowercased) name and pass it the hive's path:
=for :list
* EXISTS
* GET
* SET
* NAME
* DELETE
* KEYS
=head2 NEW
This constructs a new hive object. Note that the name is C<NEW> and not
C<new>! The C<new> method is just another method to pick a hive path part.
The following are valid arguments for C<NEW>.
=begin :list
= store
a L<Data::Hive::Store> object, or one with a compatible interface; this will be
used as the hive's backend storage driver; do not supply C<store_class> or
C<store_args> if C<store> is supplied
= store_class
This names a class from which to instantiate a storage driver. The classname
will have C<Data::Hive::Store::> prepended; to avoid this, prefix it with a '='
(C<=My::Store>). A plus sign can be used instead of an equal sign, for
historical reasons.
= store_args
If C<store_class> has been provided instead of C<store>, this argument may be
given as an arrayref of arguments to pass (dereferenced) to the store class's
C<new> method.
=end :list
=cut
sub NEW {
my ($class, $arg) = @_;
$arg ||= {};
my @path = @{ $arg->{path} || [] };
my $self = bless { path => \@path } => ref($class) || $class;
if ($arg->{store_class}) {
die "don't use 'store' with 'store_class' and 'store_args'"
if $arg->{store};
$arg->{store_class} = "Data::Hive::Store::$arg->{store_class}"
unless $arg->{store_class} =~ s/^[+=]//;
$self->{store} = $arg->{store_class}->new(@{ $arg->{store_args} || [] });
} elsif ($arg->{store}) {
$self->{store} = $arg->{store};
} else {
Carp::croak "can't create a hive with no store";
}
return $self;
}
=head2 GET
my $value = $hive->some->path->GET( $default );
The C<GET> method gets the hive value. If there is no defined value at the
path and a default has been supplied, the default will be returned instead.
=head2 GETNUM
=head2 GETSTR
These are provided soley for Perl 5.6.1 compatability, where returning undef
from overloaded numification/stringification can cause a segfault. They are
used internally by the deprecated overloadings for hives.
=cut
use overload (
- q{""} => 'GETSTR',
- q{0+} => 'GETNUM',
+ q{""} => sub {
+ Carp::carp "using hive as string for implicit GET is deprecated";
+ shift->GET(@_);
+ },
+ q{0+} => sub {
+ Carp::carp "using hive as number for implicit GET is deprecated";
+ shift->GET(@_);
+ },
fallback => 1,
);
sub GET {
my ($self, $default) = @_;
my $value = $self->STORE->get($self->{path});
return defined $value ? $value : $default;
}
-sub GETNUM { shift->GET(@_) || 0 }
+sub GETNUM {
+ Carp::carp "GETNUM method is deprecated";
+ shift->GET(@_);
+}
sub GETSTR {
- my $rv = shift->GET(@_);
- return defined($rv) ? $rv : '';
+ Carp::carp "GETSTR method is deprecated";
+ shift->GET(@_);
}
=head2 SET
$hive->some->path->SET(10);
This method sets (replacing, if necessary) the hive value.
Its return value is not defined.
=cut
sub SET {
my $self = shift;
return $self->STORE->set($self->{path}, @_);
}
=head2 EXISTS
if ($hive->foo->bar->EXISTS) { ... }
This method tests whether a value (even an undefined one) exists for the hive.
=cut
sub EXISTS {
my $self = shift;
return $self->STORE->exists($self->{path});
}
=head2 DELETE
$hive->foo->bar->DELETE;
This method deletes the hive's value. The deleted value is returned. If no
value had existed, C<undef> is returned.
=cut
sub DELETE {
my $self = shift;
return $self->STORE->delete($self->{path});
}
=head2 KEYS
my @keys = $hive->KEYS;
This returns a list of next-level path elements that exist. For example, given
a hive with values for the following paths:
foo
foo/bar
foo/bar/baz
foo/xyz/abc
foo/xyz/def
foo/123
This shows the expected results:
keys of | returns
-------------+------------
foo | bar, xyz, 123
foo/bar | baz
foo/bar/baz |
foo/xyz | abc, def
foo/123 |
=cut
sub KEYS {
my ($self) = @_;
return $self->STORE->keys($self->{path});
}
=head2 HIVE
$hive->HIVE('foo'); # equivalent to $hive->foo
This method returns a subhive of the current hive. In most cases, it is
simpler to use the lowercase hive access method. This method is useful when
you must, for some reason, access an entry whose name is not a valid Perl
method name.
It is also needed if you must access a path with the same name as a method in
C<UNIVERSAL>. In general, only C<import>, C<isa>, and C<can> should fall into
this category, but some libraries unfortunately add methods to C<UNIVERSAL>.
Common offenders include C<moniker>, C<install_sub>, C<reinstall_sub>.
This method should be needed fairly rarely. It may also be called as C<ITEM>
for historical reasons.
=cut
sub ITEM {
my ($self, @rest) = @_;
return $self->HIVE(@rest);
}
sub HIVE {
my ($self, $key) = @_;
if (! defined $key or ! length $key or ref $key) {
$key = '(undef)' unless defined $key;
Carp::croak "illegal hive path part: $key";
}
return $self->NEW({
%$self,
path => [ @{$self->{path}}, $key ],
});
}
=head2 NAME
This method returns a name that can be used to represent the hive's path. This
name is B<store-dependent>, and should not be relied upon if the store may
change. It is provided primarily for debugging.
=cut
sub NAME {
my $self = shift;
return $self->STORE->name($self->{path});
}
=head2 STORE
This method returns the storage driver being used by the hive.
=cut
sub STORE {
return $_[0]->{store}
}
sub AUTOLOAD {
my $self = shift;
our $AUTOLOAD;
(my $method = $AUTOLOAD) =~ s/.*:://;
die "AUTOLOAD for '$method' called on non-object" unless ref $self;
return if $method eq 'DESTROY';
if ($method =~ /^[A-Z]+$/) {
Carp::croak("all-caps method names are reserved: '$method'");
}
return $self->HIVE($method);
}
1;
diff --git a/lib/Data/Hive/Test.pm b/lib/Data/Hive/Test.pm
new file mode 100644
index 0000000..3c5cac1
--- /dev/null
+++ b/lib/Data/Hive/Test.pm
@@ -0,0 +1,90 @@
+use strict;
+use warnings;
+package Data::Hive::Test;
+# ABSTRACT: a bundle of tests for Data::Hive stores
+
+use Test::More;
+
+sub test_new_hive {
+ my ($self, $desc, $arg) = @_;
+
+ if (@_ == 2) {
+ $arg = $desc;
+ $desc = "hive tests from Data::Hive::Test";
+ }
+
+ $desc = "Data::Hive::Test: $desc";
+
+ my $hive;
+
+ my $passed = subtest $desc => sub {
+ $hive = Data::Hive->NEW($arg);
+
+ isa_ok($hive, 'Data::Hive');
+
+ subtest 'value of one' => sub {
+ ok(! $hive->one->EXISTS, "before being set, ->one doesn't EXISTS");
+
+ $hive->one->SET(1);
+
+ ok($hive->one->EXISTS, "after being set, ->one EXISTS");
+
+ is($hive->one->GET, 1, "->one->GET is 1");
+ is($hive->one->GET(10), 1, "->one->GET(10) is 1");
+ };
+
+ subtest 'value of zero' => sub {
+ ok(! $hive->zero->EXISTS, "before being set, ->zero doesn't EXISTS");
+
+ $hive->zero->SET(0);
+
+ ok($hive->zero->EXISTS, "after being set, ->zero EXISTS");
+
+ is($hive->zero->GET, 0, "->zero->GET is 0");
+ is($hive->zero->GET(10), 0, "->zero->GET(10) is 0");
+ };
+
+ subtest 'value of empty string' => sub {
+ ok(! $hive->empty->EXISTS, "before being set, ->empty doesn't EXISTS");
+
+ $hive->empty->SET('');
+
+ ok($hive->empty->EXISTS, "after being set, ->empty EXISTS");
+
+ is($hive->empty->GET, '', "/empty is ''");
+ is($hive->empty->GET(10), '', "->empty->GET(10) is ''");
+ };
+
+ subtest 'undef, existing value' => sub {
+ ok(! $hive->undef->EXISTS, "before being set, ->undef doesn't EXISTS");
+
+ $hive->undef->SET(undef);
+
+ ok($hive->undef->EXISTS, "after being set, ->undef EXISTS");
+
+ is($hive->undef->GET, undef, "/undef is undef");
+ };
+
+ subtest 'non-existing value' => sub {
+ ok(! $hive->missing->EXISTS, "before being set, ->missing doesn't EXISTS");
+
+ is($hive->missing->GET, undef, "->missing is undef");
+
+ ok(! $hive->missing->EXISTS, "mere GET-ing won't cause ->missing to EXIST");
+
+ is($hive->missing->GET(1), 1, " == ->missing->GET(1)");
+ is($hive->missing->GET(0), 0, "0 == ->missing->GET(0)");
+ is($hive->missing->GET(''), '', "'' == ->missing->GET('')");
+ };
+
+ is_deeply(
+ [ sort $hive->KEYS ],
+ [ qw(empty one undef zero) ],
+ "we have the right top-level keys",
+ );
+ };
+
+ return $passed ? $hive : ();
+}
+
+1;
diff --git a/t/default.t b/t/default.t
deleted file mode 100644
index dadc5c2..0000000
--- a/t/default.t
+++ /dev/null
@@ -1,102 +0,0 @@
-#!perl
-use strict;
-use warnings;
-
-use Test::More;
-use Data::Hive;
-use Data::Hive::Store::Hash;
-
-{
- my $hive = Data::Hive->NEW({ store => Data::Hive::Store::Hash->new });
-
- isa_ok($hive, 'Data::Hive');
-
- subtest 'value of zero' => sub {
- $hive->zero->SET(0);
-
- is($hive->zero->GET, 0, "/zero is 0");
- is($hive->zero->GETSTR, 0, "/zero is 0");
- is($hive->zero->GETNUM, 0, "/zero is 0");
- };
-
- subtest 'value of one' => sub {
- $hive->one->SET(1);
-
- is($hive->one->GET, 1, "/one is 1");
- is($hive->one->GETSTR, 1, "... via GETSTR is 1");
- is($hive->one->GETNUM, 1, "... via GETNUM is 1");
- };
-
- subtest 'value of empty string' => sub {
- $hive->empty->SET('');
-
- is($hive->empty->GET, '', "/empty is 1");
- is($hive->empty->GETSTR, '', "... via GETSTR is ''");
- is($hive->empty->GETNUM, 0, "... via GETNUM is 0");
- };
-
- subtest 'undef, existing value' => sub {
- $hive->undef->SET(undef);
-
- is($hive->undef->GET, undef, "/undef is undef");
- is($hive->undef->GETSTR, '', "... via GETSTR is ''");
- is($hive->undef->GETNUM, 0, "... via GETNUM is 0");
-
- {
- no warnings 'uninitialized';
- is( 0 + $hive->undef, 0, q{... 0 + $hive->undef == 0});
- is('' . $hive->undef, '', q{... '' . $hive->undef eq ''});
- }
- };
-
- subtest 'non-existing value' => sub {
- is($hive->missing->GET, undef, "/missing is undef");
- is($hive->missing->GETSTR, '', "... via GETSTR is ''");
- is($hive->missing->GETNUM, 0, "... via GETNUM is 0");
-
- {
- no warnings 'uninitialized';
- is( 0 + $hive->missing, 0, q{... 0 + $hive->missing == 0});
- is('' . $hive->missing, '', q{... '' . $hive->missing eq ''});
- }
- };
-
- is($hive->missing->GET(1), 1, " == ->missing->GET(1)");
- is($hive->missing->GET(0), 0, "0 == ->missing->GET(0)");
- is($hive->missing->GET(''), '', "'' == ->missing->GET('')");
-
- is($hive->missing->GETNUM, 0, "0 == ->missing->GETNUM");
- is($hive->missing->GETNUM(1), 1, "1 == ->missing->GETNUM(1)");
-
- is($hive->missing->GETNUM(1), 1, "1 == ->missing->GETNUM(1)");
-
-
- is_deeply(
- [ sort $hive->KEYS ],
- [ qw(empty one undef zero) ],
- "we have the right top-level keys",
- );
-
- is_deeply(
- $hive->STORE->hash_store,
- {
- one => { '' => 1 },
- empty => { '' => '' },
- undef => { '' => undef },
- zero => { '' => 0 },
- },
- 'did not autovivify'
- );
-}
-
-for my $class (qw(
- Hash
- +Data::Hive::Store::Hash
- =Data::Hive::Store::Hash
-)) {
- my $hive = Data::Hive->NEW({ store_class => $class });
-
- isa_ok($hive->STORE, 'Data::Hive::Store::Hash', "store from $class");
-}
-
-done_testing;
diff --git a/t/errors.t b/t/errors.t
index 694acde..0a2766e 100644
--- a/t/errors.t
+++ b/t/errors.t
@@ -1,37 +1,37 @@
use strict;
use warnings;
use Test::More 0.88;
use Data::Hive;
use Data::Hive::Store::Hash;
use Try::Tiny;
sub exception (&) {
my ($code) = @_;
return try { $code->(); return } catch { return $_ };
}
isnt(
exception { Data::Hive->NEW },
undef,
"we can't create a hive with no means to make a store",
);
isnt(
exception { Data::Hive->NEW({}) },
undef,
"we can't create a hive with no means to make a store",
);
-like(
+ok(
exception {
my $store = Data::Hive::Store::Hash->new;
- Data::Hive->NEW({ store => $store, store_class => (ref $store) }) },
- undef,
- "we can't create a hive with no means to make a store",
+ Data::Hive->NEW({ store => $store, store_class => 'Hash' });
+ },
+ "we can't make a hive with both a store and a store_class",
);
done_testing;
diff --git a/t/hash.t b/t/hash.t
index 0e52b9d..ab61742 100644
--- a/t/hash.t
+++ b/t/hash.t
@@ -1,138 +1,155 @@
#!perl
use strict;
use warnings;
use Data::Hive;
use Data::Hive::Store::Hash;
+use Data::Hive::Test;
+
use Test::More 0.88;
-my $hive = Data::Hive->NEW({
+Data::Hive::Test->test_new_hive(
+ 'basic hash store',
+ { store => Data::Hive::Store::Hash->new },
+);
+
+for my $class (qw(
+ Hash
+ +Data::Hive::Store::Hash
+ =Data::Hive::Store::Hash
+)) {
+ my $hive = Data::Hive->NEW({ store_class => $class });
+
+ isa_ok($hive->STORE, 'Data::Hive::Store::Hash', "store from $class");
+}
+
+my $hive = Data::Hive->NEW({
store_class => 'Hash',
});
my $tmp;
isa_ok($hive, 'Data::Hive', 'top-level hive');
isa_ok($hive->foo, 'Data::Hive', '"foo" subhive');
$hive->foo->SET(1);
is_deeply(
$hive->STORE->hash_store,
{ foo => { '' => 1 } },
'changes made to store',
);
$hive->bar->baz->GET;
is_deeply(
$hive->STORE->hash_store,
{ foo => { '' => 1 } },
'did not autovivify'
);
$hive->baz->quux->SET(2);
is_deeply(
$hive->STORE->hash_store,
{
foo => { '' => 1 },
baz => { quux => { '' => 2 } },
},
'deep set',
);
is(
$hive->foo->GET,
1,
"get the 1 from ->foo",
);
is(
$hive->foo->bar->GET,
undef,
"find nothing at ->foo->bar",
);
$hive->foo->bar->SET(3);
is(
$hive->foo->bar->GET,
3,
"wrote and retrieved 3 from ->foo->bar",
);
ok ! $hive->not->EXISTS, "non-existent key doesn't EXISTS";
ok $hive->foo->EXISTS, "existing key does EXISTS";
$hive->baz->quux->frotz->SET(4);
is_deeply(
$hive->STORE->hash_store,
{
foo => { '' => 1, bar => { '' => 3 } },
baz => { quux => { '' => 2, frotz => { '' => 4 } } },
},
"deep delete"
);
my $quux = $hive->baz->quux;
is($quux->GET, 2, "get from saved leaf");
is($quux->DELETE, 2, "delete returned old value");
is($quux->GET, undef, "after deletion, hive has no value");
is_deeply(
$hive->STORE->hash_store,
{
foo => { '' => 1, bar => { '' => 3 } },
baz => { quux => { frotz => { '' => 4 } } },
},
"deep delete"
);
my $frotz = $hive->baz->quux->frotz;
is($frotz->GET, 4, "get from saved leaf");
is($frotz->DELETE, 4, "delete returned old value");
is($frotz->GET, undef, "after deletion, hive has no value");
is_deeply(
$hive->STORE->hash_store,
{
foo => { '' => 1, bar => { '' => 3 } },
baz => { quux => { } },
},
"deep delete: after a hive had no keys, it is deleted, too"
);
{
my $hive = Data::Hive->NEW({
store_class => 'Hash',
});
$hive->HIVE('and/or')->SET(1);
$hive->foo->bar->SET(4);
$hive->foo->bar->baz->SET(5);
$hive->foo->quux->baz->SET(6);
is_deeply(
[ sort $hive->KEYS ],
[ qw(and/or foo) ],
"get the top level KEYS",
);
is_deeply(
[ sort $hive->foo->KEYS ],
[ qw(bar quux) ],
"get the KEYS under foo",
);
is_deeply(
[ sort $hive->foo->bar->KEYS ],
[ qw(baz) ],
"get the KEYS under foo/bar",
);
}
done_testing;
diff --git a/t/param.t b/t/param.t
index fd2a16e..65e049f 100644
--- a/t/param.t
+++ b/t/param.t
@@ -1,88 +1,104 @@
#!perl
use strict;
use warnings;
use Test::More;
use Data::Hive;
use Data::Hive::Store::Param;
+use Data::Hive::Test;
+
{
package Infostore;
sub new { bless {} => $_[0] }
sub info {
my ($self, $key, $val) = @_;
return keys %$self if @_ == 1;
$self->{$key} = $val if @_ > 2;
return $self->{$key};
}
sub info_exists {
my ($self, $key) = @_;
return exists $self->{$key};
}
sub info_delete {
my ($self, $key) = @_;
return delete $self->{$key};
}
}
+Data::Hive::Test->test_new_hive(
+ "basic Param backed hive",
+ {
+ store_class => 'Param',
+ store_args => [ Infostore->new, {
+ method => 'info',
+ separator => '/',
+ exists => 'info_exists',
+ delete => 'info_delete',
+ } ],
+ },
+);
+
my $infostore = Infostore->new;
my $hive = Data::Hive->NEW({
store_class => 'Param',
store_args => [ $infostore, {
method => 'info',
separator => '/',
exists => 'info_exists',
delete => 'info_delete',
} ],
});
$infostore->info(foo => 1);
$infostore->info('bar/baz' => 2);
-is $hive->bar->baz, 2, 'GET';
+is $hive->bar->baz->GET, 2, 'GET';
$hive->foo->SET(3);
is_deeply $infostore, { foo => 3, 'bar/baz' => 2 }, 'SET';
is $hive->bar->baz->NAME, 'bar/baz', 'NAME';
ok ! $hive->not->EXISTS, "non-existent key doesn't EXISTS";
ok $hive->foo->EXISTS, "existing key does EXISTS";
$hive->ITEM("and/or")->SET(17);
is_deeply $infostore, { foo => 3, 'bar/baz' => 2, 'and%2for' => 17 },
'SET (with escape)';
-is $hive->ITEM("and/or"), 17, 'GET (with escape)';
+
+is $hive->ITEM("and/or")->GET, 17, 'GET (with escape)';
is $hive->bar->baz->DELETE, 2, "delete returns old value";
is_deeply $infostore, { foo => 3, 'and%2for' => 17 }, "delete removed item";
$hive->foo->bar->SET(4);
$hive->foo->bar->baz->SET(5);
$hive->foo->quux->baz->SET(6);
is_deeply(
[ sort $hive->KEYS ],
[ qw(and/or foo) ],
"get the top level KEYS",
);
is_deeply(
[ sort $hive->foo->KEYS ],
[ qw(bar quux) ],
"get the KEYS under foo",
);
is_deeply(
[ sort $hive->foo->bar->KEYS ],
[ qw(baz) ],
"get the KEYS under foo/bar",
);
done_testing;
|
rjbs/Data-Hive
|
14cb80fdf08252bb558f0068ffe06754b3972f8f
|
improving test coverage and layout
|
diff --git a/lib/Data/Hive.pm b/lib/Data/Hive.pm
index 01d0337..ad4ac52 100644
--- a/lib/Data/Hive.pm
+++ b/lib/Data/Hive.pm
@@ -1,360 +1,362 @@
use strict;
use warnings;
package Data::Hive;
# ABSTRACT: convenient access to hierarchical data
use Carp ();
=head1 SYNOPSIS
use Data::Hive;
my $hive = Data::Hive->NEW(\%arg);
$hive->foo->bar->quux->SET(17);
print $hive->foo->bar->baz->quux->GET; # 17
=head1 DESCRIPTION
Data::Hive doesn't do very much. Its main purpose is to provide a simple,
consistent interface for accessing simple, nested data dictionaries. The
mechanism for storing or consulting these dictionaries is abstract, so it can
be replaced without altering any of the code that reads or writes the hive.
A hive is like a set of nested hash references, but with a few crucial
differences:
=begin :list
* a hive is always accessed by methods, never by dereferencing with C<< ->{} >>
For example, these two lines perform similar tasks:
$href->{foo}->{bar}->{baz}
$hive->foo->bar->baz->GET
* every key may have a value as well as children
With nested hashrefs, each entry is either another hashref (representing
children in the tree) or a leaf node. With a hive, each entry may be either or
both. For example, we can do this:
$hive->entry->SET(1);
$hive->entry->child->SET(1)
This wouldn't be possible with a hashref, because C<< $href->{entry} >> could
not hold both another node and a simple value.
-It also means that a hive might non-existant entries found along the ways to
-entries that exist:
+It also means that along the ways to existing values in a hive, there might be
+paths with no existing value.
$hive->NEW(...); # create a new hive with no entries
$hive->foo->bar->baz->SET(1); # set a single value
$hive->foo->EXISTS; # false! no value exists here
grep { 'foo' eq $_ } $hive->KEYS; # true! we can descent down this path
$hive->foo->bar->baz->EXISTS; # true! there is a value here
* hives are accessed by path, not by name
When you call C<< $hive->foo->bar->baz->GET >>, you're not accessing several
substructures. You're accessing I<one> hive. When the C<GET> method is
reached, the intervening names are converted into an entry path and I<that> is
accessed. Paths are made of zero or more non-empty strings. In other words,
while this is legal:
$href->{foo}->{''}->baz;
It is not legal to have an empty part in a hive path.
=end :list
=head1 WHY??
By using method access, the behavior of hives can be augmented as needed during
testing or development. Hives can be easily collapsed to single key/value
pairs using simple notations whereby C<< $hive->foo->bar->baz->SET(1) >>
becomes C<< $storage->{"foo.bar.baz"} = 1 >> or something similar.
This, along with the L<Data::Hive::Store> API makes it very easy to swap out
the storage and retrieval mechanism used for keeping hives in persistent
storage. It's trivial to persist entire hives into a database, flatfile, CGI
query, or many other structures, without using weird tricks beyond the weird
trick that is Data::Hive itself.
=head1 METHODS
=head2 hive path methods
All lowercase methods are used to travel down hive paths.
When you call C<< $hive->some_name >>, the return value is another Data::Hive
object using the same store as C<$hive> but with a starting path of
C<some_name>. With that hive, you can descend to deeper hives or you can get
or set its value.
Once you've reached the path where you want to perform a lookup or alteration,
you call an all-uppercase method. These are detailed below.
=head2 hive access methods
These methods are thin wrappers around required modules in L<Data::Hive::Store>
subclasses. These methods all basically call a method on the store with the
same (but lowercased) name and pass it the hive's path:
=for :list
* EXISTS
* GET
* SET
* NAME
* DELETE
* KEYS
=head2 NEW
This constructs a new hive object. Note that the name is C<NEW> and not
C<new>! The C<new> method is just another method to pick a hive path part.
The following are valid arguments for C<NEW>.
=begin :list
= store
a L<Data::Hive::Store> object, or one with a compatible interface; this will be
used as the hive's backend storage driver; do not supply C<store_class> or
C<store_args> if C<store> is supplied
= store_class
This names a class from which to instantiate a storage driver. The classname
will have C<Data::Hive::Store::> prepended; to avoid this, prefix it with a '='
(C<=My::Store>). A plus sign can be used instead of an equal sign, for
historical reasons.
= store_args
If C<store_class> has been provided instead of C<store>, this argument may be
given as an arrayref of arguments to pass (dereferenced) to the store class's
C<new> method.
=end :list
=cut
sub NEW {
my ($class, $arg) = @_;
$arg ||= {};
my @path = @{ $arg->{path} || [] };
my $self = bless { path => \@path } => ref($class) || $class;
if ($arg->{store_class}) {
die "don't use 'store' with 'store_class' and 'store_args'"
if $arg->{store};
$arg->{store_class} = "Data::Hive::Store::$arg->{store_class}"
unless $arg->{store_class} =~ s/^[+=]//;
$self->{store} = $arg->{store_class}->new(@{ $arg->{store_args} || [] });
- } else {
+ } elsif ($arg->{store}) {
$self->{store} = $arg->{store};
+ } else {
+ Carp::croak "can't create a hive with no store";
}
return $self;
}
=head2 GET
my $value = $hive->some->path->GET( $default );
The C<GET> method gets the hive value. If there is no defined value at the
path and a default has been supplied, the default will be returned instead.
=head2 GETNUM
=head2 GETSTR
These are provided soley for Perl 5.6.1 compatability, where returning undef
from overloaded numification/stringification can cause a segfault. They are
used internally by the deprecated overloadings for hives.
=cut
use overload (
q{""} => 'GETSTR',
q{0+} => 'GETNUM',
fallback => 1,
);
sub GET {
my ($self, $default) = @_;
my $value = $self->STORE->get($self->{path});
return defined $value ? $value : $default;
}
sub GETNUM { shift->GET(@_) || 0 }
sub GETSTR {
my $rv = shift->GET(@_);
return defined($rv) ? $rv : '';
}
=head2 SET
$hive->some->path->SET(10);
This method sets (replacing, if necessary) the hive value.
Its return value is not defined.
=cut
sub SET {
my $self = shift;
return $self->STORE->set($self->{path}, @_);
}
=head2 EXISTS
if ($hive->foo->bar->EXISTS) { ... }
This method tests whether a value (even an undefined one) exists for the hive.
=cut
sub EXISTS {
my $self = shift;
return $self->STORE->exists($self->{path});
}
=head2 DELETE
$hive->foo->bar->DELETE;
This method deletes the hive's value. The deleted value is returned. If no
value had existed, C<undef> is returned.
=cut
sub DELETE {
my $self = shift;
return $self->STORE->delete($self->{path});
}
=head2 KEYS
my @keys = $hive->KEYS;
This returns a list of next-level path elements that exist. For example, given
a hive with values for the following paths:
foo
foo/bar
foo/bar/baz
foo/xyz/abc
foo/xyz/def
foo/123
This shows the expected results:
keys of | returns
-------------+------------
foo | bar, xyz, 123
foo/bar | baz
foo/bar/baz |
foo/xyz | abc, def
foo/123 |
=cut
sub KEYS {
my ($self) = @_;
return $self->STORE->keys($self->{path});
}
=head2 HIVE
$hive->HIVE('foo'); # equivalent to $hive->foo
This method returns a subhive of the current hive. In most cases, it is
simpler to use the lowercase hive access method. This method is useful when
you must, for some reason, access an entry whose name is not a valid Perl
method name.
It is also needed if you must access a path with the same name as a method in
C<UNIVERSAL>. In general, only C<import>, C<isa>, and C<can> should fall into
this category, but some libraries unfortunately add methods to C<UNIVERSAL>.
Common offenders include C<moniker>, C<install_sub>, C<reinstall_sub>.
This method should be needed fairly rarely. It may also be called as C<ITEM>
for historical reasons.
=cut
sub ITEM {
my ($self, @rest) = @_;
return $self->HIVE(@rest);
}
sub HIVE {
my ($self, $key) = @_;
if (! defined $key or ! length $key or ref $key) {
$key = '(undef)' unless defined $key;
Carp::croak "illegal hive path part: $key";
}
return $self->NEW({
%$self,
path => [ @{$self->{path}}, $key ],
});
}
=head2 NAME
This method returns a name that can be used to represent the hive's path. This
name is B<store-dependent>, and should not be relied upon if the store may
change. It is provided primarily for debugging.
=cut
sub NAME {
my $self = shift;
return $self->STORE->name($self->{path});
}
=head2 STORE
This method returns the storage driver being used by the hive.
=cut
sub STORE {
return $_[0]->{store}
}
sub AUTOLOAD {
my $self = shift;
our $AUTOLOAD;
(my $method = $AUTOLOAD) =~ s/.*:://;
die "AUTOLOAD for '$method' called on non-object" unless ref $self;
return if $method eq 'DESTROY';
if ($method =~ /^[A-Z]+$/) {
Carp::croak("all-caps method names are reserved: '$method'");
}
- return $self->ITEM($method);
+ return $self->HIVE($method);
}
1;
diff --git a/t/default.t b/t/default.t
index 41acada..dadc5c2 100644
--- a/t/default.t
+++ b/t/default.t
@@ -1,31 +1,102 @@
#!perl
-
use strict;
use warnings;
-use Test::More 'no_plan';
-use ok 'Data::Hive';
-use ok 'Data::Hive::Store::Hash';
+use Test::More;
+use Data::Hive;
+use Data::Hive::Store::Hash;
-my $hive = Data::Hive->NEW({
- store => Data::Hive::Store::Hash->new(
- my $store = {}
- ),
-});
+{
+ my $hive = Data::Hive->NEW({ store => Data::Hive::Store::Hash->new });
-isa_ok($hive, 'Data::Hive');
+ isa_ok($hive, 'Data::Hive');
-$hive->foo->SET(1);
+ subtest 'value of zero' => sub {
+ $hive->zero->SET(0);
-is(0 + $hive->bar, 0, "0 == ->bar");
+ is($hive->zero->GET, 0, "/zero is 0");
+ is($hive->zero->GETSTR, 0, "/zero is 0");
+ is($hive->zero->GETNUM, 0, "/zero is 0");
+ };
-{
- no warnings;
- is(0 + $hive->bar->GET, 0, "0 == ->bar->GET");
+ subtest 'value of one' => sub {
+ $hive->one->SET(1);
+
+ is($hive->one->GET, 1, "/one is 1");
+ is($hive->one->GETSTR, 1, "... via GETSTR is 1");
+ is($hive->one->GETNUM, 1, "... via GETNUM is 1");
+ };
+
+ subtest 'value of empty string' => sub {
+ $hive->empty->SET('');
+
+ is($hive->empty->GET, '', "/empty is 1");
+ is($hive->empty->GETSTR, '', "... via GETSTR is ''");
+ is($hive->empty->GETNUM, 0, "... via GETNUM is 0");
+ };
+
+ subtest 'undef, existing value' => sub {
+ $hive->undef->SET(undef);
+
+ is($hive->undef->GET, undef, "/undef is undef");
+ is($hive->undef->GETSTR, '', "... via GETSTR is ''");
+ is($hive->undef->GETNUM, 0, "... via GETNUM is 0");
+
+ {
+ no warnings 'uninitialized';
+ is( 0 + $hive->undef, 0, q{... 0 + $hive->undef == 0});
+ is('' . $hive->undef, '', q{... '' . $hive->undef eq ''});
+ }
+ };
+
+ subtest 'non-existing value' => sub {
+ is($hive->missing->GET, undef, "/missing is undef");
+ is($hive->missing->GETSTR, '', "... via GETSTR is ''");
+ is($hive->missing->GETNUM, 0, "... via GETNUM is 0");
+
+ {
+ no warnings 'uninitialized';
+ is( 0 + $hive->missing, 0, q{... 0 + $hive->missing == 0});
+ is('' . $hive->missing, '', q{... '' . $hive->missing eq ''});
+ }
+ };
+
+ is($hive->missing->GET(1), 1, " == ->missing->GET(1)");
+ is($hive->missing->GET(0), 0, "0 == ->missing->GET(0)");
+ is($hive->missing->GET(''), '', "'' == ->missing->GET('')");
+
+ is($hive->missing->GETNUM, 0, "0 == ->missing->GETNUM");
+ is($hive->missing->GETNUM(1), 1, "1 == ->missing->GETNUM(1)");
+
+ is($hive->missing->GETNUM(1), 1, "1 == ->missing->GETNUM(1)");
+
+
+ is_deeply(
+ [ sort $hive->KEYS ],
+ [ qw(empty one undef zero) ],
+ "we have the right top-level keys",
+ );
+
+ is_deeply(
+ $hive->STORE->hash_store,
+ {
+ one => { '' => 1 },
+ empty => { '' => '' },
+ undef => { '' => undef },
+ zero => { '' => 0 },
+ },
+ 'did not autovivify'
+ );
}
-is(0 + $hive->bar->GETNUM, 0, "0 == ->bar->GETNUM");
-is(0 + $hive->bar->GET(1), 1, "1 == ->bar->GET(1)");
-is(0 + $hive->bar->GETNUM(1), 1, "1 == ->bar->GETNUM(1)");
+for my $class (qw(
+ Hash
+ +Data::Hive::Store::Hash
+ =Data::Hive::Store::Hash
+)) {
+ my $hive = Data::Hive->NEW({ store_class => $class });
+
+ isa_ok($hive->STORE, 'Data::Hive::Store::Hash', "store from $class");
+}
-is_deeply($store, { foo => { '' => 1 } }, 'did not autovivify');
+done_testing;
diff --git a/t/errors.t b/t/errors.t
new file mode 100644
index 0000000..694acde
--- /dev/null
+++ b/t/errors.t
@@ -0,0 +1,37 @@
+use strict;
+use warnings;
+
+use Test::More 0.88;
+
+use Data::Hive;
+use Data::Hive::Store::Hash;
+
+use Try::Tiny;
+
+sub exception (&) {
+ my ($code) = @_;
+
+ return try { $code->(); return } catch { return $_ };
+}
+
+isnt(
+ exception { Data::Hive->NEW },
+ undef,
+ "we can't create a hive with no means to make a store",
+);
+
+isnt(
+ exception { Data::Hive->NEW({}) },
+ undef,
+ "we can't create a hive with no means to make a store",
+);
+
+like(
+ exception {
+ my $store = Data::Hive::Store::Hash->new;
+ Data::Hive->NEW({ store => $store, store_class => (ref $store) }) },
+ undef,
+ "we can't create a hive with no means to make a store",
+);
+
+done_testing;
|
rjbs/Data-Hive
|
fd80efa009287d2a667891bfed2cdadd3fed0801
|
fix typo in pod
|
diff --git a/lib/Data/Hive.pm b/lib/Data/Hive.pm
index 060075c..01d0337 100644
--- a/lib/Data/Hive.pm
+++ b/lib/Data/Hive.pm
@@ -1,360 +1,360 @@
use strict;
use warnings;
package Data::Hive;
# ABSTRACT: convenient access to hierarchical data
use Carp ();
=head1 SYNOPSIS
use Data::Hive;
my $hive = Data::Hive->NEW(\%arg);
$hive->foo->bar->quux->SET(17);
print $hive->foo->bar->baz->quux->GET; # 17
=head1 DESCRIPTION
Data::Hive doesn't do very much. Its main purpose is to provide a simple,
consistent interface for accessing simple, nested data dictionaries. The
mechanism for storing or consulting these dictionaries is abstract, so it can
be replaced without altering any of the code that reads or writes the hive.
A hive is like a set of nested hash references, but with a few crucial
differences:
=begin :list
-* a hive is always accessed by methods, never by dereferencing with C<<->{}>>
+* a hive is always accessed by methods, never by dereferencing with C<< ->{} >>
For example, these two lines perform similar tasks:
$href->{foo}->{bar}->{baz}
$hive->foo->bar->baz->GET
* every key may have a value as well as children
With nested hashrefs, each entry is either another hashref (representing
children in the tree) or a leaf node. With a hive, each entry may be either or
both. For example, we can do this:
$hive->entry->SET(1);
$hive->entry->child->SET(1)
This wouldn't be possible with a hashref, because C<< $href->{entry} >> could
not hold both another node and a simple value.
It also means that a hive might non-existant entries found along the ways to
entries that exist:
$hive->NEW(...); # create a new hive with no entries
$hive->foo->bar->baz->SET(1); # set a single value
$hive->foo->EXISTS; # false! no value exists here
grep { 'foo' eq $_ } $hive->KEYS; # true! we can descent down this path
$hive->foo->bar->baz->EXISTS; # true! there is a value here
* hives are accessed by path, not by name
When you call C<< $hive->foo->bar->baz->GET >>, you're not accessing several
substructures. You're accessing I<one> hive. When the C<GET> method is
reached, the intervening names are converted into an entry path and I<that> is
accessed. Paths are made of zero or more non-empty strings. In other words,
while this is legal:
$href->{foo}->{''}->baz;
It is not legal to have an empty part in a hive path.
=end :list
=head1 WHY??
By using method access, the behavior of hives can be augmented as needed during
testing or development. Hives can be easily collapsed to single key/value
pairs using simple notations whereby C<< $hive->foo->bar->baz->SET(1) >>
becomes C<< $storage->{"foo.bar.baz"} = 1 >> or something similar.
This, along with the L<Data::Hive::Store> API makes it very easy to swap out
the storage and retrieval mechanism used for keeping hives in persistent
storage. It's trivial to persist entire hives into a database, flatfile, CGI
query, or many other structures, without using weird tricks beyond the weird
trick that is Data::Hive itself.
=head1 METHODS
=head2 hive path methods
All lowercase methods are used to travel down hive paths.
When you call C<< $hive->some_name >>, the return value is another Data::Hive
object using the same store as C<$hive> but with a starting path of
C<some_name>. With that hive, you can descend to deeper hives or you can get
or set its value.
Once you've reached the path where you want to perform a lookup or alteration,
you call an all-uppercase method. These are detailed below.
=head2 hive access methods
These methods are thin wrappers around required modules in L<Data::Hive::Store>
subclasses. These methods all basically call a method on the store with the
same (but lowercased) name and pass it the hive's path:
=for :list
* EXISTS
* GET
* SET
* NAME
* DELETE
* KEYS
=head2 NEW
This constructs a new hive object. Note that the name is C<NEW> and not
C<new>! The C<new> method is just another method to pick a hive path part.
The following are valid arguments for C<NEW>.
=begin :list
= store
a L<Data::Hive::Store> object, or one with a compatible interface; this will be
used as the hive's backend storage driver; do not supply C<store_class> or
C<store_args> if C<store> is supplied
= store_class
This names a class from which to instantiate a storage driver. The classname
will have C<Data::Hive::Store::> prepended; to avoid this, prefix it with a '='
(C<=My::Store>). A plus sign can be used instead of an equal sign, for
historical reasons.
= store_args
If C<store_class> has been provided instead of C<store>, this argument may be
given as an arrayref of arguments to pass (dereferenced) to the store class's
C<new> method.
=end :list
=cut
sub NEW {
my ($class, $arg) = @_;
$arg ||= {};
my @path = @{ $arg->{path} || [] };
my $self = bless { path => \@path } => ref($class) || $class;
if ($arg->{store_class}) {
die "don't use 'store' with 'store_class' and 'store_args'"
if $arg->{store};
$arg->{store_class} = "Data::Hive::Store::$arg->{store_class}"
unless $arg->{store_class} =~ s/^[+=]//;
$self->{store} = $arg->{store_class}->new(@{ $arg->{store_args} || [] });
} else {
$self->{store} = $arg->{store};
}
return $self;
}
=head2 GET
my $value = $hive->some->path->GET( $default );
The C<GET> method gets the hive value. If there is no defined value at the
path and a default has been supplied, the default will be returned instead.
=head2 GETNUM
=head2 GETSTR
These are provided soley for Perl 5.6.1 compatability, where returning undef
from overloaded numification/stringification can cause a segfault. They are
used internally by the deprecated overloadings for hives.
=cut
use overload (
q{""} => 'GETSTR',
q{0+} => 'GETNUM',
fallback => 1,
);
sub GET {
my ($self, $default) = @_;
my $value = $self->STORE->get($self->{path});
return defined $value ? $value : $default;
}
sub GETNUM { shift->GET(@_) || 0 }
sub GETSTR {
my $rv = shift->GET(@_);
return defined($rv) ? $rv : '';
}
=head2 SET
$hive->some->path->SET(10);
This method sets (replacing, if necessary) the hive value.
Its return value is not defined.
=cut
sub SET {
my $self = shift;
return $self->STORE->set($self->{path}, @_);
}
=head2 EXISTS
if ($hive->foo->bar->EXISTS) { ... }
This method tests whether a value (even an undefined one) exists for the hive.
=cut
sub EXISTS {
my $self = shift;
return $self->STORE->exists($self->{path});
}
=head2 DELETE
$hive->foo->bar->DELETE;
This method deletes the hive's value. The deleted value is returned. If no
value had existed, C<undef> is returned.
=cut
sub DELETE {
my $self = shift;
return $self->STORE->delete($self->{path});
}
=head2 KEYS
my @keys = $hive->KEYS;
This returns a list of next-level path elements that exist. For example, given
a hive with values for the following paths:
foo
foo/bar
foo/bar/baz
foo/xyz/abc
foo/xyz/def
foo/123
This shows the expected results:
keys of | returns
-------------+------------
foo | bar, xyz, 123
foo/bar | baz
foo/bar/baz |
foo/xyz | abc, def
foo/123 |
=cut
sub KEYS {
my ($self) = @_;
return $self->STORE->keys($self->{path});
}
=head2 HIVE
$hive->HIVE('foo'); # equivalent to $hive->foo
This method returns a subhive of the current hive. In most cases, it is
simpler to use the lowercase hive access method. This method is useful when
you must, for some reason, access an entry whose name is not a valid Perl
method name.
It is also needed if you must access a path with the same name as a method in
C<UNIVERSAL>. In general, only C<import>, C<isa>, and C<can> should fall into
this category, but some libraries unfortunately add methods to C<UNIVERSAL>.
Common offenders include C<moniker>, C<install_sub>, C<reinstall_sub>.
This method should be needed fairly rarely. It may also be called as C<ITEM>
for historical reasons.
=cut
sub ITEM {
my ($self, @rest) = @_;
return $self->HIVE(@rest);
}
sub HIVE {
my ($self, $key) = @_;
if (! defined $key or ! length $key or ref $key) {
$key = '(undef)' unless defined $key;
Carp::croak "illegal hive path part: $key";
}
return $self->NEW({
%$self,
path => [ @{$self->{path}}, $key ],
});
}
=head2 NAME
This method returns a name that can be used to represent the hive's path. This
name is B<store-dependent>, and should not be relied upon if the store may
change. It is provided primarily for debugging.
=cut
sub NAME {
my $self = shift;
return $self->STORE->name($self->{path});
}
=head2 STORE
This method returns the storage driver being used by the hive.
=cut
sub STORE {
return $_[0]->{store}
}
sub AUTOLOAD {
my $self = shift;
our $AUTOLOAD;
(my $method = $AUTOLOAD) =~ s/.*:://;
die "AUTOLOAD for '$method' called on non-object" unless ref $self;
return if $method eq 'DESTROY';
if ($method =~ /^[A-Z]+$/) {
Carp::croak("all-caps method names are reserved: '$method'");
}
return $self->ITEM($method);
}
1;
|
rjbs/Data-Hive
|
6f2f87bc865e880dc5e3f2bfa1a8791e81d64f27
|
v1.000
|
diff --git a/Changes b/Changes
index bf97b31..b9f40e8 100644
--- a/Changes
+++ b/Changes
@@ -1,37 +1,45 @@
Revision history for Data-Hive
{{$NEXT}}
+1.000 2010-08-27 21:48:58 America/New_York
+ significant documentation overhaul
+
+ add the ->KEYS method to Data::Hive and the core stores
+
+ allow the Hash store to have a value and subhives per path name
+ (this break backcompat with existing hash structure)
+
0.054 2010-08-26 14:58:29 America/New_York
minor tweaks, mostly to enable use of Dist::Zilla
0.053 2008-09-12
->GET($default) added
0.052 2007-11-19
Fix bug where Store::Hash was inadvertently destroying state
information it shouldn't have in some cases
0.051 2007-11-15
Guard eval with local $SIG{__DIE__} in case someone else has been
careless with theirs
Remove useless t/boilerplate.t
0.050 2007-04-02
Add GETSTR to avoid stupid SEGVs
Add DELETE
0.040 2006-08-28
Freshen Module::Install
0.03 2006-07-03
Add missing dep for Test::MockObject.
0.02 2006-06-08
Add EXISTS.
0.01 2006-06-05
First version, released on an unsuspecting world.
|
rjbs/Data-Hive
|
b59797ee900df3e813b343335f22edd1f1ac1593
|
reorganize docs a bit more
|
diff --git a/lib/Data/Hive.pm b/lib/Data/Hive.pm
index baa25eb..060075c 100644
--- a/lib/Data/Hive.pm
+++ b/lib/Data/Hive.pm
@@ -1,338 +1,360 @@
use strict;
use warnings;
package Data::Hive;
# ABSTRACT: convenient access to hierarchical data
use Carp ();
=head1 SYNOPSIS
use Data::Hive;
my $hive = Data::Hive->NEW(\%arg);
$hive->foo->bar->quux->SET(17);
print $hive->foo->bar->baz->quux->GET; # 17
=head1 DESCRIPTION
Data::Hive doesn't do very much. Its main purpose is to provide a simple,
consistent interface for accessing simple, nested data dictionaries. The
mechanism for storing or consulting these dictionaries is abstract, so it can
be replaced without altering any of the code that reads or writes the hive.
A hive is like a set of nested hash references, but with a few crucial
differences:
=begin :list
* a hive is always accessed by methods, never by dereferencing with C<<->{}>>
For example, these two lines perform similar tasks:
$href->{foo}->{bar}->{baz}
$hive->foo->bar->baz->GET
* every key may have a value as well as children
With nested hashrefs, each entry is either another hashref (representing
children in the tree) or a leaf node. With a hive, each entry may be either or
both. For example, we can do this:
$hive->entry->SET(1);
$hive->entry->child->SET(1)
This wouldn't be possible with a hashref, because C<< $href->{entry} >> could
not hold both another node and a simple value.
It also means that a hive might non-existant entries found along the ways to
entries that exist:
$hive->NEW(...); # create a new hive with no entries
$hive->foo->bar->baz->SET(1); # set a single value
$hive->foo->EXISTS; # false! no value exists here
grep { 'foo' eq $_ } $hive->KEYS; # true! we can descent down this path
$hive->foo->bar->baz->EXISTS; # true! there is a value here
* hives are accessed by path, not by name
When you call C<< $hive->foo->bar->baz->GET >>, you're not accessing several
substructures. You're accessing I<one> hive. When the C<GET> method is
reached, the intervening names are converted into an entry path and I<that> is
accessed. Paths are made of zero or more non-empty strings. In other words,
while this is legal:
$href->{foo}->{''}->baz;
It is not legal to have an empty part in a hive path.
=end :list
=head1 WHY??
By using method access, the behavior of hives can be augmented as needed during
testing or development. Hives can be easily collapsed to single key/value
pairs using simple notations whereby C<< $hive->foo->bar->baz->SET(1) >>
becomes C<< $storage->{"foo.bar.baz"} = 1 >> or something similar.
This, along with the L<Data::Hive::Store> API makes it very easy to swap out
the storage and retrieval mechanism used for keeping hives in persistent
storage. It's trivial to persist entire hives into a database, flatfile, CGI
query, or many other structures, without using weird tricks beyond the weird
trick that is Data::Hive itself.
=head1 METHODS
=head2 hive path methods
All lowercase methods are used to travel down hive paths.
When you call C<< $hive->some_name >>, the return value is another Data::Hive
object using the same store as C<$hive> but with a starting path of
C<some_name>. With that hive, you can descend to deeper hives or you can get
or set its value.
Once you've reached the path where you want to perform a lookup or alteration,
you call an all-uppercase method. These are detailed below.
=head2 hive access methods
These methods are thin wrappers around required modules in L<Data::Hive::Store>
subclasses. These methods all basically call a method on the store with the
same (but lowercased) name and pass it the hive's path:
=for :list
* EXISTS
* GET
* SET
* NAME
* DELETE
* KEYS
=head2 NEW
This constructs a new hive object. Note that the name is C<NEW> and not
C<new>! The C<new> method is just another method to pick a hive path part.
The following are valid arguments for C<NEW>.
=begin :list
= store
a L<Data::Hive::Store> object, or one with a compatible interface; this will be
used as the hive's backend storage driver; do not supply C<store_class> or
C<store_args> if C<store> is supplied
= store_class
This names a class from which to instantiate a storage driver. The classname
will have C<Data::Hive::Store::> prepended; to avoid this, prefix it with a '='
(C<=My::Store>). A plus sign can be used instead of an equal sign, for
historical reasons.
= store_args
If C<store_class> has been provided instead of C<store>, this argument may be
given as an arrayref of arguments to pass (dereferenced) to the store class's
C<new> method.
=end :list
=cut
sub NEW {
my ($class, $arg) = @_;
$arg ||= {};
my @path = @{ $arg->{path} || [] };
my $self = bless { path => \@path } => ref($class) || $class;
if ($arg->{store_class}) {
die "don't use 'store' with 'store_class' and 'store_args'"
if $arg->{store};
$arg->{store_class} = "Data::Hive::Store::$arg->{store_class}"
unless $arg->{store_class} =~ s/^[+=]//;
$self->{store} = $arg->{store_class}->new(@{ $arg->{store_args} || [] });
} else {
$self->{store} = $arg->{store};
}
return $self;
}
=head2 GET
my $value = $hive->some->path->GET( $default );
The C<GET> method gets the hive value. If there is no defined value at the
path and a default has been supplied, the default will be returned instead.
=head2 GETNUM
=head2 GETSTR
These are provided soley for Perl 5.6.1 compatability, where returning undef
from overloaded numification/stringification can cause a segfault. They are
used internally by the deprecated overloadings for hives.
=cut
use overload (
q{""} => 'GETSTR',
q{0+} => 'GETNUM',
fallback => 1,
);
sub GET {
my ($self, $default) = @_;
my $value = $self->STORE->get($self->{path});
return defined $value ? $value : $default;
}
sub GETNUM { shift->GET(@_) || 0 }
sub GETSTR {
my $rv = shift->GET(@_);
return defined($rv) ? $rv : '';
}
=head2 SET
$hive->some->path->SET(10);
This method sets (replacing, if necessary) the hive value.
Its return value is not defined.
=cut
sub SET {
my $self = shift;
return $self->STORE->set($self->{path}, @_);
}
=head2 EXISTS
if ($hive->foo->bar->EXISTS) { ... }
This method tests whether a value (even an undefined one) exists for the hive.
=cut
sub EXISTS {
my $self = shift;
return $self->STORE->exists($self->{path});
}
=head2 DELETE
$hive->foo->bar->DELETE;
This method deletes the hive's value. The deleted value is returned. If no
value had existed, C<undef> is returned.
=cut
sub DELETE {
my $self = shift;
return $self->STORE->delete($self->{path});
}
-=item KEYS
+=head2 KEYS
+
+ my @keys = $hive->KEYS;
+
+This returns a list of next-level path elements that exist. For example, given
+a hive with values for the following paths:
+
+ foo
+ foo/bar
+ foo/bar/baz
+ foo/xyz/abc
+ foo/xyz/def
+ foo/123
+
+This shows the expected results:
+
+ keys of | returns
+ -------------+------------
+ foo | bar, xyz, 123
+ foo/bar | baz
+ foo/bar/baz |
+ foo/xyz | abc, def
+ foo/123 |
=cut
sub KEYS {
my ($self) = @_;
return $self->STORE->keys($self->{path});
}
=head2 HIVE
$hive->HIVE('foo'); # equivalent to $hive->foo
This method returns a subhive of the current hive. In most cases, it is
simpler to use the lowercase hive access method. This method is useful when
you must, for some reason, access an entry whose name is not a valid Perl
method name.
It is also needed if you must access a path with the same name as a method in
C<UNIVERSAL>. In general, only C<import>, C<isa>, and C<can> should fall into
this category, but some libraries unfortunately add methods to C<UNIVERSAL>.
Common offenders include C<moniker>, C<install_sub>, C<reinstall_sub>.
This method should be needed fairly rarely. It may also be called as C<ITEM>
for historical reasons.
=cut
sub ITEM {
my ($self, @rest) = @_;
return $self->HIVE(@rest);
}
sub HIVE {
my ($self, $key) = @_;
if (! defined $key or ! length $key or ref $key) {
$key = '(undef)' unless defined $key;
Carp::croak "illegal hive path part: $key";
}
return $self->NEW({
%$self,
path => [ @{$self->{path}}, $key ],
});
}
=head2 NAME
This method returns a name that can be used to represent the hive's path. This
name is B<store-dependent>, and should not be relied upon if the store may
change. It is provided primarily for debugging.
=cut
sub NAME {
my $self = shift;
return $self->STORE->name($self->{path});
}
=head2 STORE
This method returns the storage driver being used by the hive.
=cut
sub STORE {
return $_[0]->{store}
}
sub AUTOLOAD {
my $self = shift;
our $AUTOLOAD;
(my $method = $AUTOLOAD) =~ s/.*:://;
die "AUTOLOAD for '$method' called on non-object" unless ref $self;
return if $method eq 'DESTROY';
if ($method =~ /^[A-Z]+$/) {
Carp::croak("all-caps method names are reserved: '$method'");
}
return $self->ITEM($method);
}
1;
diff --git a/lib/Data/Hive/Store.pm b/lib/Data/Hive/Store.pm
index fddf4a6..32fc335 100644
--- a/lib/Data/Hive/Store.pm
+++ b/lib/Data/Hive/Store.pm
@@ -1,82 +1,66 @@
use strict;
use warnings;
package Data::Hive::Store;
# ABSTRACT: a backend storage driver for Data::Hive
use Carp ();
=head1 DESCRIPTION
Data::Hive::Store is a generic interface to a backend store
for Data::Hive.
=head1 METHODS
All methods are passed at least a 'path' (arrayref of namespace pieces). Store
classes exist to operate on the entities found at named paths.
=head2 get
print $store->get(\@path, \%opt);
Return the resource represented by the given path.
=head2 set
$store->set(\@path, $value, \%opt);
Analogous to C<< get >>.
=head2 name
print $store->name(\@path, \%opt);
Return a store-specific name for the given path. This is primarily useful for
stores that may be accessed independently of the hive.
=head2 exists
if ($store->exists(\@path, \%opt)) { ... }
Returns true if the given path exists in the store.
=head2 delete
$store->delete(\@path, \%opt);
Delete the given path from the store. Return the previous value, if any.
=head2 keys
my @keys = $store->keys(\@path, \%opt);
-This returns a list of next-level path elements that exist. For example, given
-a hive with values for the following paths:
-
- foo
- foo/bar
- foo/bar/baz
- foo/xyz/abc
- foo/xyz/def
- foo/123
-
-This shows the expected results:
-
- keys of | returns
- -------------+------------
- foo | bar, xyz, 123
- foo/bar | baz
- foo/bar/baz |
- foo/xyz | abc, def
- foo/123 |
+This returns a list of next-level path elements that exist. For more
+information on the expected behavior, see the L<KEYS method|Data:Hive/keys> in
+Data::Hive.
=cut
BEGIN {
for my $meth (qw(get set name exists delete keys)) {
no strict 'refs';
*$meth = sub { Carp::croak("$_[0] does not implement $meth") };
}
}
1;
diff --git a/lib/Data/Hive/Store/Hash.pm b/lib/Data/Hive/Store/Hash.pm
index 634faa0..fb29ae4 100644
--- a/lib/Data/Hive/Store/Hash.pm
+++ b/lib/Data/Hive/Store/Hash.pm
@@ -1,265 +1,232 @@
use strict;
use warnings;
package Data::Hive::Store::Hash;
# ABSTRACT: store a hive in nested hashrefs
=head1 DESCRIPTION
This is a simple store, primarily for testing, that will store hives in nested
hashrefs. All hives are represented as hashrefs, and their values are stored
in the entry for the empty string.
So, we could do this:
my $href = {};
my $hive = Data::Hive->NEW({
store_class => 'Hash',
store_args => [ $href ],
});
$hive->foo->SET(1);
$hive->foo->bar->baz->SET(2);
We would end up with C<$href> containing:
{
foo => {
'' => 1,
bar => {
baz => {
'' => 2,
},
},
},
}
Using empty keys results in a bigger, uglier dump, but allows a given hive to
contain both a value and subhives. B<Please note> that this is different
behavior compared with earlier releases, in which empty keys were not used and
it was not legal to have a value and a hive at a given path. It is possible,
although fairly unlikely, that this format will change again. The Hash store
should generally be used for testing things that use a hive, as opposed for
building hashes that will be used for anything else.
=method new
my $store = Data::Hive::Store::Hash->new(\%hash);
The only argument expected for C<new> is a hashref, which is the hashref in
which hive entries are stored.
If no hashref is provided, a new, empty hashref will be used.
=cut
sub new {
my ($class, $href) = @_;
$href = {} unless defined $href;
return bless { store => $href } => $class;
}
=method hash_store
This method returns the hashref in which things are being used. You should not
alter its contents!
=cut
sub hash_store {
$_[0]->{store}
}
-=method get
-
-Use given C<< \@path >> as nesting keys in the hashref store.
-
-=cut
-
sub _die {
require Carp::Clan;
Carp::Clan->import('^Data::Hive($|::)');
croak(shift);
}
my $BREAK = "BREAK\n";
# Wow, this is quite a little machine! Here's a slightly simplified overview
# of what it does: -- rjbs, 2010-08-27
#
# As long as cond->(\@remaining_path) is true, execute step->($next,
# $current_hashref, \@remaining_path)
#
# If it dies with $BREAK, stop looping and return. Once the cond returns
# false, return end->($current_hashref, \@remaining_path)
sub _descend {
my ($self, $orig_path, $arg) = @_;
my @path = @$orig_path;
$arg ||= {};
$arg->{step} or die "step is required";
$arg->{cond} ||= sub { @{ shift() } };
$arg->{end} ||= sub { $_[0] };
my $node = $self->hash_store;
while ($arg->{cond}->(\@path)) {
my $seg = shift @path;
{
local $SIG{__DIE__};
eval { $arg->{step}->($seg, $node, \@path) };
}
return if $@ and $@ eq $BREAK;
die $@ if $@;
$node = $node->{$seg} ||= {};
}
return $arg->{end}->($node, \@path);
}
sub get {
my ($self, $path) = @_;
return $self->_descend(
$path, {
end => sub { $_[0]->{''} },
step => sub {
my ($seg, $node) = @_;
if (defined $node and not ref $node) {
# We found a bogus entry in the store! -- rjbs, 2010-08-27
_die("can't get key '$seg' of non-ref value '$node'");
}
die $BREAK unless exists $node->{$seg};
}
}
);
}
-=method set
-
-See C<L</get>>. Dies if you try to set a key underneath an existing
-non-hashref key, e.g.:
-
- $hash = { foo => 1 };
- $store->set([ 'foo', 'bar' ], 2); # dies
-
-=cut
-
sub set {
my ($self, $path, $value) = @_;
return $self->_descend(
$path, {
step => sub {
my ($seg, $node, $path) = @_;
if (exists $node->{$seg} and not ref $node->{$seg}) {
_die("can't overwrite existing non-ref value: '$node->{$seg}'");
}
},
cond => sub { @{ shift() } > 1 },
end => sub {
my ($node, $path) = @_;
$node->{$path->[0]}{''} = $value;
},
},
);
}
=method name
-Returns a string, potentially suitable for eval-ing, describing a hash
-dereference of a variable called C<< $STORE >>.
+The name returned by the Hash store is a string, potentially suitable for
+eval-ing, describing a hash dereference of a variable called C<< $STORE >>.
"$STORE->{foo}->{bar}"
This is probably not very useful.
=cut
sub name {
my ($self, $path) = @_;
return join '->', '$STORE', map { "{'$_'}" } @$path;
}
-=method exists
-
-Descend the hash and return false if any of the path's parts do not exist, or
-true if they all do.
-
-=cut
-
sub exists {
my ($self, $path) = @_;
return $self->_descend(
$path, {
step => sub {
my ($seg, $node) = @_;
die $BREAK unless exists $node->{$seg};
},
},
);
}
-=method delete
-
-Descend the hash and delete the given path. Only deletes the leaf.
-
-=cut
-
sub delete {
my ($self, $path) = @_;
return $self->_descend(
$path, {
step => sub {
my ($seg, $node) = @_;
die $BREAK unless exists $node->{$seg};
},
cond => sub { @{ shift() } > 1 },
end => sub {
my ($node, $final_path) = @_;
my $this = $node->{ $final_path->[0] };
my $rv = delete $this->{''};
# Cleanup empty trees after deletion! It would be convenient to have
# ->_ascend, but I'm not likely to bother with writing it just yet.
# -- rjbs, 2010-08-27
$self->_descend(
$path, {
step => sub {
my ($seg, $node) = @_;
return if keys %{ $node->{$seg} };
delete $node->{$seg};
die $BREAK;
},
}
);
return $rv;
},
},
);
}
-=head2 keys
-
-=cut
-
sub keys {
my ($self, $path) = @_;
return $self->_descend($path, {
step => sub {
my ($seg, $node) = @_;
die $BREAK unless exists $node->{$seg};
},
end => sub {
return grep { length } keys %{ $_[0] };
},
});
}
1;
diff --git a/lib/Data/Hive/Store/Param.pm b/lib/Data/Hive/Store/Param.pm
index 41a1314..59bf05e 100644
--- a/lib/Data/Hive/Store/Param.pm
+++ b/lib/Data/Hive/Store/Param.pm
@@ -1,177 +1,150 @@
use strict;
use warnings;
package Data::Hive::Store::Param;
# ABSTRACT: CGI::param-like store for Data::Hive
use URI::Escape ();
+=head1 DESCRIPTION
+
+This hive store will soon be overhauled.
+
+Basically, it expects to access a hive in an object with CGI's C<param> method,
+or the numerous other things with that interface.
+
=method new
# use default method name 'param'
my $store = Data::Hive::Store::Param->new($obj);
# use different method name 'info'
my $store = Data::Hive::Store::Param->new($obj, { method => 'info' });
# escape certain characters in keys
my $store = Data::Hive::Store::Param->new($obj, { escape => './!' });
Return a new Param store.
Several interesting arguments can be passed in a hashref after the first
(mandatory) object argument.
=begin :list
= method
Use a different method name on the object (default is 'param').
= escape
List of characters to escape (via URI encoding) in keys.
Defaults to the C<< separator >>.
= separator
String to join path segments together with; defaults to either the first
character of the C<< escape >> option (if given) or '.'.
= exists
Coderef that describes how to see if a given parameter name (C<< separator
>>-joined path) exists. The default is to treat the object like a hashref and
look inside it.
= delete
Coderef that describes how to delete a given parameter name. The default is to
treat the object like a hashref and call C<delete> on it.
=end :list
=cut
sub _escape {
my ($self, $str) = @_;
my $escape = $self->{escape} or return $str;
$str =~ s/([\Q$escape\E%])/sprintf("%%%x", ord($1))/ge;
return $str;
}
sub _path {
my ($self, $path) = @_;
return join $self->{separator}, map { $self->_escape($_) } @$path;
}
sub new {
my ($class, $obj, $arg) = @_;
$arg ||= {};
$arg->{escape} ||= $arg->{separator} || '.';
$arg->{separator} ||= substr($arg->{escape}, 0, 1);
$arg->{method} ||= 'param';
$arg->{exists} ||= sub { exists $obj->{shift()} };
$arg->{delete} ||= sub { delete $obj->{shift()} };
$arg->{obj} = $obj;
return bless { %$arg } => $class;
}
sub _param {
my $self = shift;
my $meth = $self->{method};
my $path = $self->_path(shift);
return $self->{obj}->$meth($path, @_);
}
-=method get
-
-Join the path together with the C<< separator >> and get it from the object.
-
-=cut
-
sub get {
my ($self, $path) = @_;
return $self->_param($path);
}
-=method set
-
-See L</get>.
-
-=cut
-
sub set {
my ($self, $path, $val) = @_;
return $self->_param($path => $val);
}
-
-=method name
-
-Join path together with C<< separator >> and return it.
-
-=cut
sub name {
my ($self, $path) = @_;
return $self->_path($path);
}
-=method exists
-
-Return true if the C<< name >> of this hive is a parameter.
-
-=cut
-
sub exists {
my ($self, $path) = @_;
my $code = $self->{exists};
my $key = $self->_path($path);
return ref($code) ? $code->($key) : $self->{obj}->$code($key);
}
-=method delete
-
-Delete the entry for the C<< name >> of this hive and return its old value.
-
-=cut
-
sub delete {
my ($self, $path) = @_;
my $code = $self->{delete};
my $key = $self->_path($path);
return $self->{obj}->$code($key);
}
-=method keys
-
-=cut
-
sub keys {
my ($self, $path) = @_;
my $method = $self->{method};
my @names = $self->{obj}->$method;
my $name = $self->_path($path);
my $sep = $self->{separator};
my $start = length $name ? "$name$sep" : q{};
my %seen = map { /\A\Q$start\E(.+?)(\z|\Q$sep\E)/ ? ($1 => 1) : () } @names;
my @keys = map { URI::Escape::uri_unescape($_) } keys %seen;
return @keys;
}
=head1 BUGS
The interaction between escapes and separators is not very well formalized or
tested. If you change things much, you'll probably be frustrated.
Fixes and/or tests would be lovely.
=cut
1;
|
rjbs/Data-Hive
|
df220172e0a494b72796736dcb09362f341cadd9
|
keys implementation for Hash
|
diff --git a/lib/Data/Hive/Store/Hash.pm b/lib/Data/Hive/Store/Hash.pm
index aa0c7b6..634faa0 100644
--- a/lib/Data/Hive/Store/Hash.pm
+++ b/lib/Data/Hive/Store/Hash.pm
@@ -1,247 +1,265 @@
use strict;
use warnings;
package Data::Hive::Store::Hash;
# ABSTRACT: store a hive in nested hashrefs
=head1 DESCRIPTION
This is a simple store, primarily for testing, that will store hives in nested
hashrefs. All hives are represented as hashrefs, and their values are stored
in the entry for the empty string.
So, we could do this:
my $href = {};
my $hive = Data::Hive->NEW({
store_class => 'Hash',
store_args => [ $href ],
});
$hive->foo->SET(1);
$hive->foo->bar->baz->SET(2);
We would end up with C<$href> containing:
{
foo => {
'' => 1,
bar => {
baz => {
'' => 2,
},
},
},
}
Using empty keys results in a bigger, uglier dump, but allows a given hive to
contain both a value and subhives. B<Please note> that this is different
behavior compared with earlier releases, in which empty keys were not used and
it was not legal to have a value and a hive at a given path. It is possible,
although fairly unlikely, that this format will change again. The Hash store
should generally be used for testing things that use a hive, as opposed for
building hashes that will be used for anything else.
=method new
my $store = Data::Hive::Store::Hash->new(\%hash);
The only argument expected for C<new> is a hashref, which is the hashref in
which hive entries are stored.
If no hashref is provided, a new, empty hashref will be used.
=cut
sub new {
my ($class, $href) = @_;
$href = {} unless defined $href;
return bless { store => $href } => $class;
}
=method hash_store
This method returns the hashref in which things are being used. You should not
alter its contents!
=cut
sub hash_store {
$_[0]->{store}
}
=method get
Use given C<< \@path >> as nesting keys in the hashref store.
=cut
sub _die {
require Carp::Clan;
Carp::Clan->import('^Data::Hive($|::)');
croak(shift);
}
my $BREAK = "BREAK\n";
# Wow, this is quite a little machine! Here's a slightly simplified overview
# of what it does: -- rjbs, 2010-08-27
#
# As long as cond->(\@remaining_path) is true, execute step->($next,
# $current_hashref, \@remaining_path)
#
# If it dies with $BREAK, stop looping and return. Once the cond returns
# false, return end->($current_hashref, \@remaining_path)
sub _descend {
my ($self, $orig_path, $arg) = @_;
my @path = @$orig_path;
$arg ||= {};
$arg->{step} or die "step is required";
$arg->{cond} ||= sub { @{ shift() } };
$arg->{end} ||= sub { $_[0] };
my $node = $self->hash_store;
while ($arg->{cond}->(\@path)) {
my $seg = shift @path;
{
local $SIG{__DIE__};
eval { $arg->{step}->($seg, $node, \@path) };
}
return if $@ and $@ eq $BREAK;
die $@ if $@;
$node = $node->{$seg} ||= {};
}
return $arg->{end}->($node, \@path);
}
sub get {
my ($self, $path) = @_;
return $self->_descend(
$path, {
end => sub { $_[0]->{''} },
step => sub {
my ($seg, $node) = @_;
if (defined $node and not ref $node) {
# We found a bogus entry in the store! -- rjbs, 2010-08-27
_die("can't get key '$seg' of non-ref value '$node'");
}
die $BREAK unless exists $node->{$seg};
}
}
);
}
=method set
See C<L</get>>. Dies if you try to set a key underneath an existing
non-hashref key, e.g.:
$hash = { foo => 1 };
$store->set([ 'foo', 'bar' ], 2); # dies
=cut
sub set {
my ($self, $path, $value) = @_;
return $self->_descend(
$path, {
step => sub {
my ($seg, $node, $path) = @_;
if (exists $node->{$seg} and not ref $node->{$seg}) {
_die("can't overwrite existing non-ref value: '$node->{$seg}'");
}
},
cond => sub { @{ shift() } > 1 },
end => sub {
my ($node, $path) = @_;
$node->{$path->[0]}{''} = $value;
},
},
);
}
=method name
Returns a string, potentially suitable for eval-ing, describing a hash
dereference of a variable called C<< $STORE >>.
"$STORE->{foo}->{bar}"
This is probably not very useful.
=cut
sub name {
my ($self, $path) = @_;
return join '->', '$STORE', map { "{'$_'}" } @$path;
}
=method exists
Descend the hash and return false if any of the path's parts do not exist, or
true if they all do.
=cut
sub exists {
my ($self, $path) = @_;
return $self->_descend(
$path, {
step => sub {
my ($seg, $node) = @_;
die $BREAK unless exists $node->{$seg};
},
},
);
}
=method delete
Descend the hash and delete the given path. Only deletes the leaf.
=cut
sub delete {
my ($self, $path) = @_;
return $self->_descend(
$path, {
step => sub {
my ($seg, $node) = @_;
die $BREAK unless exists $node->{$seg};
},
cond => sub { @{ shift() } > 1 },
end => sub {
my ($node, $final_path) = @_;
my $this = $node->{ $final_path->[0] };
my $rv = delete $this->{''};
# Cleanup empty trees after deletion! It would be convenient to have
# ->_ascend, but I'm not likely to bother with writing it just yet.
# -- rjbs, 2010-08-27
$self->_descend(
$path, {
step => sub {
my ($seg, $node) = @_;
return if keys %{ $node->{$seg} };
delete $node->{$seg};
die $BREAK;
},
}
);
return $rv;
},
},
);
}
+=head2 keys
+
+=cut
+
+sub keys {
+ my ($self, $path) = @_;
+
+ return $self->_descend($path, {
+ step => sub {
+ my ($seg, $node) = @_;
+ die $BREAK unless exists $node->{$seg};
+ },
+ end => sub {
+ return grep { length } keys %{ $_[0] };
+ },
+ });
+}
+
1;
diff --git a/t/hash.t b/t/hash.t
index a903c08..0e52b9d 100644
--- a/t/hash.t
+++ b/t/hash.t
@@ -1,109 +1,138 @@
#!perl
use strict;
use warnings;
use Data::Hive;
use Data::Hive::Store::Hash;
use Test::More 0.88;
my $hive = Data::Hive->NEW({
store_class => 'Hash',
});
my $tmp;
isa_ok($hive, 'Data::Hive', 'top-level hive');
isa_ok($hive->foo, 'Data::Hive', '"foo" subhive');
$hive->foo->SET(1);
is_deeply(
$hive->STORE->hash_store,
{ foo => { '' => 1 } },
'changes made to store',
);
$hive->bar->baz->GET;
is_deeply(
$hive->STORE->hash_store,
{ foo => { '' => 1 } },
'did not autovivify'
);
$hive->baz->quux->SET(2);
is_deeply(
$hive->STORE->hash_store,
{
foo => { '' => 1 },
baz => { quux => { '' => 2 } },
},
'deep set',
);
is(
$hive->foo->GET,
1,
"get the 1 from ->foo",
);
is(
$hive->foo->bar->GET,
undef,
"find nothing at ->foo->bar",
);
$hive->foo->bar->SET(3);
is(
$hive->foo->bar->GET,
3,
"wrote and retrieved 3 from ->foo->bar",
);
ok ! $hive->not->EXISTS, "non-existent key doesn't EXISTS";
ok $hive->foo->EXISTS, "existing key does EXISTS";
$hive->baz->quux->frotz->SET(4);
is_deeply(
$hive->STORE->hash_store,
{
foo => { '' => 1, bar => { '' => 3 } },
baz => { quux => { '' => 2, frotz => { '' => 4 } } },
},
"deep delete"
);
my $quux = $hive->baz->quux;
is($quux->GET, 2, "get from saved leaf");
is($quux->DELETE, 2, "delete returned old value");
is($quux->GET, undef, "after deletion, hive has no value");
is_deeply(
$hive->STORE->hash_store,
{
foo => { '' => 1, bar => { '' => 3 } },
baz => { quux => { frotz => { '' => 4 } } },
},
"deep delete"
);
my $frotz = $hive->baz->quux->frotz;
is($frotz->GET, 4, "get from saved leaf");
is($frotz->DELETE, 4, "delete returned old value");
is($frotz->GET, undef, "after deletion, hive has no value");
is_deeply(
$hive->STORE->hash_store,
{
foo => { '' => 1, bar => { '' => 3 } },
baz => { quux => { } },
},
"deep delete: after a hive had no keys, it is deleted, too"
-) or note explain $hive->STORE->hash_store;
+);
+
+{
+ my $hive = Data::Hive->NEW({
+ store_class => 'Hash',
+ });
+
+ $hive->HIVE('and/or')->SET(1);
+ $hive->foo->bar->SET(4);
+ $hive->foo->bar->baz->SET(5);
+ $hive->foo->quux->baz->SET(6);
+
+ is_deeply(
+ [ sort $hive->KEYS ],
+ [ qw(and/or foo) ],
+ "get the top level KEYS",
+ );
+
+ is_deeply(
+ [ sort $hive->foo->KEYS ],
+ [ qw(bar quux) ],
+ "get the KEYS under foo",
+ );
+
+ is_deeply(
+ [ sort $hive->foo->bar->KEYS ],
+ [ qw(baz) ],
+ "get the KEYS under foo/bar",
+ );
+}
done_testing;
|
rjbs/Data-Hive
|
2f9fb6afcae8b49edf9ceb9e72389a87f8e863a7
|
lousy-but-working first pass at keys for Param
|
diff --git a/lib/Data/Hive/Store/Param.pm b/lib/Data/Hive/Store/Param.pm
index a22fec9..41a1314 100644
--- a/lib/Data/Hive/Store/Param.pm
+++ b/lib/Data/Hive/Store/Param.pm
@@ -1,158 +1,177 @@
use strict;
use warnings;
package Data::Hive::Store::Param;
# ABSTRACT: CGI::param-like store for Data::Hive
+use URI::Escape ();
+
=method new
# use default method name 'param'
my $store = Data::Hive::Store::Param->new($obj);
# use different method name 'info'
my $store = Data::Hive::Store::Param->new($obj, { method => 'info' });
# escape certain characters in keys
my $store = Data::Hive::Store::Param->new($obj, { escape => './!' });
Return a new Param store.
Several interesting arguments can be passed in a hashref after the first
(mandatory) object argument.
=begin :list
= method
Use a different method name on the object (default is 'param').
= escape
List of characters to escape (via URI encoding) in keys.
Defaults to the C<< separator >>.
= separator
String to join path segments together with; defaults to either the first
character of the C<< escape >> option (if given) or '.'.
= exists
Coderef that describes how to see if a given parameter name (C<< separator
>>-joined path) exists. The default is to treat the object like a hashref and
look inside it.
= delete
Coderef that describes how to delete a given parameter name. The default is to
treat the object like a hashref and call C<delete> on it.
=end :list
=cut
sub _escape {
my ($self, $str) = @_;
my $escape = $self->{escape} or return $str;
$str =~ s/([\Q$escape\E%])/sprintf("%%%x", ord($1))/ge;
return $str;
}
sub _path {
my ($self, $path) = @_;
return join $self->{separator}, map { $self->_escape($_) } @$path;
}
sub new {
my ($class, $obj, $arg) = @_;
$arg ||= {};
$arg->{escape} ||= $arg->{separator} || '.';
$arg->{separator} ||= substr($arg->{escape}, 0, 1);
$arg->{method} ||= 'param';
$arg->{exists} ||= sub { exists $obj->{shift()} };
$arg->{delete} ||= sub { delete $obj->{shift()} };
$arg->{obj} = $obj;
return bless { %$arg } => $class;
}
sub _param {
my $self = shift;
my $meth = $self->{method};
my $path = $self->_path(shift);
return $self->{obj}->$meth($path, @_);
}
=method get
Join the path together with the C<< separator >> and get it from the object.
=cut
sub get {
my ($self, $path) = @_;
return $self->_param($path);
}
=method set
See L</get>.
=cut
sub set {
my ($self, $path, $val) = @_;
return $self->_param($path => $val);
}
=method name
Join path together with C<< separator >> and return it.
=cut
sub name {
my ($self, $path) = @_;
return $self->_path($path);
}
=method exists
Return true if the C<< name >> of this hive is a parameter.
=cut
sub exists {
my ($self, $path) = @_;
my $code = $self->{exists};
my $key = $self->_path($path);
return ref($code) ? $code->($key) : $self->{obj}->$code($key);
}
=method delete
Delete the entry for the C<< name >> of this hive and return its old value.
=cut
sub delete {
my ($self, $path) = @_;
my $code = $self->{delete};
my $key = $self->_path($path);
return $self->{obj}->$code($key);
}
=method keys
=cut
sub keys {
my ($self, $path) = @_;
my $method = $self->{method};
my @names = $self->{obj}->$method;
- warn "@names\n";
+ my $name = $self->_path($path);
+
+ my $sep = $self->{separator};
+
+ my $start = length $name ? "$name$sep" : q{};
+ my %seen = map { /\A\Q$start\E(.+?)(\z|\Q$sep\E)/ ? ($1 => 1) : () } @names;
+
+ my @keys = map { URI::Escape::uri_unescape($_) } keys %seen;
+ return @keys;
}
+=head1 BUGS
+
+The interaction between escapes and separators is not very well formalized or
+tested. If you change things much, you'll probably be frustrated.
+
+Fixes and/or tests would be lovely.
+
+=cut
+
1;
diff --git a/t/param.t b/t/param.t
index d9837f0..fd2a16e 100644
--- a/t/param.t
+++ b/t/param.t
@@ -1,68 +1,88 @@
#!perl
use strict;
use warnings;
use Test::More;
use Data::Hive;
use Data::Hive::Store::Param;
{
package Infostore;
sub new { bless {} => $_[0] }
sub info {
my ($self, $key, $val) = @_;
return keys %$self if @_ == 1;
$self->{$key} = $val if @_ > 2;
return $self->{$key};
}
sub info_exists {
my ($self, $key) = @_;
return exists $self->{$key};
}
sub info_delete {
my ($self, $key) = @_;
return delete $self->{$key};
}
}
my $infostore = Infostore->new;
my $hive = Data::Hive->NEW({
store_class => 'Param',
store_args => [ $infostore, {
method => 'info',
separator => '/',
exists => 'info_exists',
delete => 'info_delete',
} ],
});
$infostore->info(foo => 1);
$infostore->info('bar/baz' => 2);
is $hive->bar->baz, 2, 'GET';
$hive->foo->SET(3);
is_deeply $infostore, { foo => 3, 'bar/baz' => 2 }, 'SET';
is $hive->bar->baz->NAME, 'bar/baz', 'NAME';
ok ! $hive->not->EXISTS, "non-existent key doesn't EXISTS";
ok $hive->foo->EXISTS, "existing key does EXISTS";
$hive->ITEM("and/or")->SET(17);
is_deeply $infostore, { foo => 3, 'bar/baz' => 2, 'and%2for' => 17 },
'SET (with escape)';
is $hive->ITEM("and/or"), 17, 'GET (with escape)';
is $hive->bar->baz->DELETE, 2, "delete returns old value";
is_deeply $infostore, { foo => 3, 'and%2for' => 17 }, "delete removed item";
-$hive->KEYS;
+$hive->foo->bar->SET(4);
+$hive->foo->bar->baz->SET(5);
+$hive->foo->quux->baz->SET(6);
+
+is_deeply(
+ [ sort $hive->KEYS ],
+ [ qw(and/or foo) ],
+ "get the top level KEYS",
+);
+
+is_deeply(
+ [ sort $hive->foo->KEYS ],
+ [ qw(bar quux) ],
+ "get the KEYS under foo",
+);
+
+is_deeply(
+ [ sort $hive->foo->bar->KEYS ],
+ [ qw(baz) ],
+ "get the KEYS under foo/bar",
+);
done_testing;
|
rjbs/Data-Hive
|
4ae2786b7315229ccfc4d867785d70815c86702d
|
start to add keys support to Param
|
diff --git a/lib/Data/Hive/Store/Param.pm b/lib/Data/Hive/Store/Param.pm
index 21dfda9..a22fec9 100644
--- a/lib/Data/Hive/Store/Param.pm
+++ b/lib/Data/Hive/Store/Param.pm
@@ -1,145 +1,158 @@
use strict;
use warnings;
package Data::Hive::Store::Param;
# ABSTRACT: CGI::param-like store for Data::Hive
=method new
# use default method name 'param'
my $store = Data::Hive::Store::Param->new($obj);
# use different method name 'info'
my $store = Data::Hive::Store::Param->new($obj, { method => 'info' });
# escape certain characters in keys
my $store = Data::Hive::Store::Param->new($obj, { escape => './!' });
Return a new Param store.
Several interesting arguments can be passed in a hashref after the first
(mandatory) object argument.
=begin :list
= method
Use a different method name on the object (default is 'param').
= escape
-List of characters to escape (prepend '\' to) in keys.
+List of characters to escape (via URI encoding) in keys.
Defaults to the C<< separator >>.
= separator
String to join path segments together with; defaults to either the first
character of the C<< escape >> option (if given) or '.'.
= exists
Coderef that describes how to see if a given parameter name (C<< separator
>>-joined path) exists. The default is to treat the object like a hashref and
look inside it.
= delete
Coderef that describes how to delete a given parameter name. The default is to
treat the object like a hashref and call C<delete> on it.
=end :list
=cut
sub _escape {
my ($self, $str) = @_;
my $escape = $self->{escape} or return $str;
$str =~ s/([\Q$escape\E%])/sprintf("%%%x", ord($1))/ge;
return $str;
}
sub _path {
my ($self, $path) = @_;
return join $self->{separator}, map { $self->_escape($_) } @$path;
}
sub new {
my ($class, $obj, $arg) = @_;
$arg ||= {};
$arg->{escape} ||= $arg->{separator} || '.';
$arg->{separator} ||= substr($arg->{escape}, 0, 1);
$arg->{method} ||= 'param';
$arg->{exists} ||= sub { exists $obj->{shift()} };
$arg->{delete} ||= sub { delete $obj->{shift()} };
$arg->{obj} = $obj;
return bless { %$arg } => $class;
}
sub _param {
my $self = shift;
my $meth = $self->{method};
my $path = $self->_path(shift);
return $self->{obj}->$meth($path, @_);
}
=method get
Join the path together with the C<< separator >> and get it from the object.
=cut
sub get {
my ($self, $path) = @_;
return $self->_param($path);
}
=method set
See L</get>.
=cut
sub set {
my ($self, $path, $val) = @_;
return $self->_param($path => $val);
}
=method name
Join path together with C<< separator >> and return it.
=cut
sub name {
my ($self, $path) = @_;
return $self->_path($path);
}
=method exists
Return true if the C<< name >> of this hive is a parameter.
=cut
sub exists {
my ($self, $path) = @_;
my $code = $self->{exists};
my $key = $self->_path($path);
return ref($code) ? $code->($key) : $self->{obj}->$code($key);
}
=method delete
Delete the entry for the C<< name >> of this hive and return its old value.
=cut
sub delete {
my ($self, $path) = @_;
my $code = $self->{delete};
my $key = $self->_path($path);
return $self->{obj}->$code($key);
}
+=method keys
+
+=cut
+
+sub keys {
+ my ($self, $path) = @_;
+
+ my $method = $self->{method};
+ my @names = $self->{obj}->$method;
+
+ warn "@names\n";
+}
+
1;
diff --git a/t/param.t b/t/param.t
index 4032355..d9837f0 100644
--- a/t/param.t
+++ b/t/param.t
@@ -1,66 +1,68 @@
#!perl
use strict;
use warnings;
use Test::More;
use Data::Hive;
use Data::Hive::Store::Param;
{
package Infostore;
sub new { bless {} => $_[0] }
sub info {
my ($self, $key, $val) = @_;
return keys %$self if @_ == 1;
$self->{$key} = $val if @_ > 2;
return $self->{$key};
}
sub info_exists {
my ($self, $key) = @_;
return exists $self->{$key};
}
sub info_delete {
my ($self, $key) = @_;
return delete $self->{$key};
}
}
my $infostore = Infostore->new;
my $hive = Data::Hive->NEW({
store_class => 'Param',
store_args => [ $infostore, {
method => 'info',
separator => '/',
exists => 'info_exists',
delete => 'info_delete',
} ],
});
$infostore->info(foo => 1);
$infostore->info('bar/baz' => 2);
is $hive->bar->baz, 2, 'GET';
$hive->foo->SET(3);
is_deeply $infostore, { foo => 3, 'bar/baz' => 2 }, 'SET';
is $hive->bar->baz->NAME, 'bar/baz', 'NAME';
ok ! $hive->not->EXISTS, "non-existent key doesn't EXISTS";
ok $hive->foo->EXISTS, "existing key does EXISTS";
$hive->ITEM("and/or")->SET(17);
is_deeply $infostore, { foo => 3, 'bar/baz' => 2, 'and%2for' => 17 },
'SET (with escape)';
is $hive->ITEM("and/or"), 17, 'GET (with escape)';
is $hive->bar->baz->DELETE, 2, "delete returns old value";
is_deeply $infostore, { foo => 3, 'and%2for' => 17 }, "delete removed item";
+$hive->KEYS;
+
done_testing;
|
rjbs/Data-Hive
|
7df9d6c6ab43d466a6880d649ef6e1daf7243234
|
cleaning up the Params tests
|
diff --git a/lib/Data/Hive/Store/Param.pm b/lib/Data/Hive/Store/Param.pm
index 190cee8..21dfda9 100644
--- a/lib/Data/Hive/Store/Param.pm
+++ b/lib/Data/Hive/Store/Param.pm
@@ -1,144 +1,145 @@
use strict;
use warnings;
package Data::Hive::Store::Param;
# ABSTRACT: CGI::param-like store for Data::Hive
=method new
# use default method name 'param'
my $store = Data::Hive::Store::Param->new($obj);
# use different method name 'info'
my $store = Data::Hive::Store::Param->new($obj, { method => 'info' });
# escape certain characters in keys
my $store = Data::Hive::Store::Param->new($obj, { escape => './!' });
Return a new Param store.
Several interesting arguments can be passed in a hashref after the first
(mandatory) object argument.
=begin :list
= method
Use a different method name on the object (default is 'param').
= escape
List of characters to escape (prepend '\' to) in keys.
Defaults to the C<< separator >>.
= separator
String to join path segments together with; defaults to either the first
character of the C<< escape >> option (if given) or '.'.
= exists
Coderef that describes how to see if a given parameter name (C<< separator
>>-joined path) exists. The default is to treat the object like a hashref and
look inside it.
= delete
Coderef that describes how to delete a given parameter name. The default is to
treat the object like a hashref and call C<delete> on it.
=end :list
=cut
sub _escape {
my ($self, $str) = @_;
my $escape = $self->{escape} or return $str;
$str =~ s/([\Q$escape\E%])/sprintf("%%%x", ord($1))/ge;
return $str;
}
sub _path {
my ($self, $path) = @_;
return join $self->{separator}, map { $self->_escape($_) } @$path;
}
sub new {
my ($class, $obj, $arg) = @_;
$arg ||= {};
$arg->{escape} ||= $arg->{separator} || '.';
$arg->{separator} ||= substr($arg->{escape}, 0, 1);
$arg->{method} ||= 'param';
$arg->{exists} ||= sub { exists $obj->{shift()} };
$arg->{delete} ||= sub { delete $obj->{shift()} };
$arg->{obj} = $obj;
return bless { %$arg } => $class;
}
sub _param {
my $self = shift;
my $meth = $self->{method};
my $path = $self->_path(shift);
return $self->{obj}->$meth($path, @_);
}
=method get
Join the path together with the C<< separator >> and get it from the object.
=cut
sub get {
my ($self, $path) = @_;
return $self->_param($path);
}
=method set
See L</get>.
=cut
sub set {
my ($self, $path, $val) = @_;
return $self->_param($path => $val);
}
=method name
Join path together with C<< separator >> and return it.
=cut
sub name {
my ($self, $path) = @_;
return $self->_path($path);
}
=method exists
Return true if the C<< name >> of this hive is a parameter.
=cut
sub exists {
my ($self, $path) = @_;
my $code = $self->{exists};
my $key = $self->_path($path);
return ref($code) ? $code->($key) : $self->{obj}->$code($key);
}
=method delete
Delete the entry for the C<< name >> of this hive and return its old value.
=cut
sub delete {
my ($self, $path) = @_;
my $code = $self->{delete};
my $key = $self->_path($path);
- return ref($code) ? $code->($key) : $self->{obj}->$code($key);
+
+ return $self->{obj}->$code($key);
}
1;
diff --git a/t/param.t b/t/param.t
index 45f69b8..4032355 100644
--- a/t/param.t
+++ b/t/param.t
@@ -1,65 +1,66 @@
#!perl
use strict;
use warnings;
-use Test::More 'no_plan';
-use Test::MockObject;
-
-use ok 'Data::Hive';
-use ok 'Data::Hive::Store::Param';
-
-my $obj = Test::MockObject->new;
-my $param = {};
-$obj->mock(
- info => sub {
- my (undef, $key, $val) = @_;
- $param->{$key} = $val if @_ > 2;
- return $param->{$key};
- },
-);
-$obj->mock(
- info_exists => sub {
- my (undef, $key) = @_;
- return exists $param->{$key};
+use Test::More;
+
+use Data::Hive;
+use Data::Hive::Store::Param;
+
+{
+ package Infostore;
+ sub new { bless {} => $_[0] }
+
+ sub info {
+ my ($self, $key, $val) = @_;
+ return keys %$self if @_ == 1;
+ $self->{$key} = $val if @_ > 2;
+ return $self->{$key};
+ }
+
+ sub info_exists {
+ my ($self, $key) = @_;
+ return exists $self->{$key};
}
-);
-$obj->mock(
- info_delete => sub {
- my (undef, $key) = @_;
- return delete $param->{$key};
- },
-);
+
+ sub info_delete {
+ my ($self, $key) = @_;
+ return delete $self->{$key};
+ }
+}
+
+my $infostore = Infostore->new;
my $hive = Data::Hive->NEW({
store_class => 'Param',
- store_args => [ $obj, {
- method => 'info',
+ store_args => [ $infostore, {
+ method => 'info',
separator => '/',
exists => 'info_exists',
delete => 'info_delete',
} ],
});
-%$param = (
- foo => 1,
- 'bar/baz' => 2,
-);
+$infostore->info(foo => 1);
+$infostore->info('bar/baz' => 2);
is $hive->bar->baz, 2, 'GET';
$hive->foo->SET(3);
-is_deeply $param, { foo => 3, 'bar/baz' => 2 }, 'SET';
+is_deeply $infostore, { foo => 3, 'bar/baz' => 2 }, 'SET';
is $hive->bar->baz->NAME, 'bar/baz', 'NAME';
ok ! $hive->not->EXISTS, "non-existent key doesn't EXISTS";
ok $hive->foo->EXISTS, "existing key does EXISTS";
$hive->ITEM("and/or")->SET(17);
-is_deeply $param, { foo => 3, 'bar/baz' => 2, 'and%2for' => 17 },
+is_deeply $infostore, { foo => 3, 'bar/baz' => 2, 'and%2for' => 17 },
'SET (with escape)';
is $hive->ITEM("and/or"), 17, 'GET (with escape)';
is $hive->bar->baz->DELETE, 2, "delete returns old value";
-is_deeply $param, { foo => 3, 'and%2for' => 17 }, "delete removed item";
+is_deeply $infostore, { foo => 3, 'and%2for' => 17 }, "delete removed item";
+
+done_testing;
|
rjbs/Data-Hive
|
33b6d1cd85241fd44884f694de5e58c843717aa6
|
start adding the much-needed KEYS method
|
diff --git a/lib/Data/Hive.pm b/lib/Data/Hive.pm
index b55c7e1..baa25eb 100644
--- a/lib/Data/Hive.pm
+++ b/lib/Data/Hive.pm
@@ -1,330 +1,338 @@
use strict;
use warnings;
package Data::Hive;
# ABSTRACT: convenient access to hierarchical data
use Carp ();
=head1 SYNOPSIS
use Data::Hive;
my $hive = Data::Hive->NEW(\%arg);
$hive->foo->bar->quux->SET(17);
print $hive->foo->bar->baz->quux->GET; # 17
=head1 DESCRIPTION
Data::Hive doesn't do very much. Its main purpose is to provide a simple,
consistent interface for accessing simple, nested data dictionaries. The
mechanism for storing or consulting these dictionaries is abstract, so it can
be replaced without altering any of the code that reads or writes the hive.
A hive is like a set of nested hash references, but with a few crucial
differences:
=begin :list
* a hive is always accessed by methods, never by dereferencing with C<<->{}>>
For example, these two lines perform similar tasks:
$href->{foo}->{bar}->{baz}
$hive->foo->bar->baz->GET
* every key may have a value as well as children
With nested hashrefs, each entry is either another hashref (representing
children in the tree) or a leaf node. With a hive, each entry may be either or
both. For example, we can do this:
$hive->entry->SET(1);
$hive->entry->child->SET(1)
This wouldn't be possible with a hashref, because C<< $href->{entry} >> could
not hold both another node and a simple value.
It also means that a hive might non-existant entries found along the ways to
entries that exist:
$hive->NEW(...); # create a new hive with no entries
$hive->foo->bar->baz->SET(1); # set a single value
$hive->foo->EXISTS; # false! no value exists here
grep { 'foo' eq $_ } $hive->KEYS; # true! we can descent down this path
$hive->foo->bar->baz->EXISTS; # true! there is a value here
* hives are accessed by path, not by name
When you call C<< $hive->foo->bar->baz->GET >>, you're not accessing several
substructures. You're accessing I<one> hive. When the C<GET> method is
reached, the intervening names are converted into an entry path and I<that> is
accessed. Paths are made of zero or more non-empty strings. In other words,
while this is legal:
$href->{foo}->{''}->baz;
It is not legal to have an empty part in a hive path.
=end :list
=head1 WHY??
By using method access, the behavior of hives can be augmented as needed during
testing or development. Hives can be easily collapsed to single key/value
pairs using simple notations whereby C<< $hive->foo->bar->baz->SET(1) >>
becomes C<< $storage->{"foo.bar.baz"} = 1 >> or something similar.
This, along with the L<Data::Hive::Store> API makes it very easy to swap out
the storage and retrieval mechanism used for keeping hives in persistent
storage. It's trivial to persist entire hives into a database, flatfile, CGI
query, or many other structures, without using weird tricks beyond the weird
trick that is Data::Hive itself.
=head1 METHODS
=head2 hive path methods
All lowercase methods are used to travel down hive paths.
When you call C<< $hive->some_name >>, the return value is another Data::Hive
object using the same store as C<$hive> but with a starting path of
C<some_name>. With that hive, you can descend to deeper hives or you can get
or set its value.
Once you've reached the path where you want to perform a lookup or alteration,
you call an all-uppercase method. These are detailed below.
=head2 hive access methods
These methods are thin wrappers around required modules in L<Data::Hive::Store>
subclasses. These methods all basically call a method on the store with the
same (but lowercased) name and pass it the hive's path:
=for :list
* EXISTS
* GET
* SET
* NAME
* DELETE
* KEYS
=head2 NEW
This constructs a new hive object. Note that the name is C<NEW> and not
C<new>! The C<new> method is just another method to pick a hive path part.
The following are valid arguments for C<NEW>.
=begin :list
= store
a L<Data::Hive::Store> object, or one with a compatible interface; this will be
used as the hive's backend storage driver; do not supply C<store_class> or
C<store_args> if C<store> is supplied
= store_class
This names a class from which to instantiate a storage driver. The classname
will have C<Data::Hive::Store::> prepended; to avoid this, prefix it with a '='
(C<=My::Store>). A plus sign can be used instead of an equal sign, for
historical reasons.
= store_args
If C<store_class> has been provided instead of C<store>, this argument may be
given as an arrayref of arguments to pass (dereferenced) to the store class's
C<new> method.
=end :list
=cut
sub NEW {
my ($class, $arg) = @_;
$arg ||= {};
my @path = @{ $arg->{path} || [] };
my $self = bless { path => \@path } => ref($class) || $class;
if ($arg->{store_class}) {
die "don't use 'store' with 'store_class' and 'store_args'"
if $arg->{store};
$arg->{store_class} = "Data::Hive::Store::$arg->{store_class}"
unless $arg->{store_class} =~ s/^[+=]//;
$self->{store} = $arg->{store_class}->new(@{ $arg->{store_args} || [] });
} else {
$self->{store} = $arg->{store};
}
return $self;
}
=head2 GET
my $value = $hive->some->path->GET( $default );
The C<GET> method gets the hive value. If there is no defined value at the
path and a default has been supplied, the default will be returned instead.
=head2 GETNUM
=head2 GETSTR
These are provided soley for Perl 5.6.1 compatability, where returning undef
from overloaded numification/stringification can cause a segfault. They are
used internally by the deprecated overloadings for hives.
=cut
use overload (
q{""} => 'GETSTR',
q{0+} => 'GETNUM',
fallback => 1,
);
sub GET {
my ($self, $default) = @_;
my $value = $self->STORE->get($self->{path});
return defined $value ? $value : $default;
}
sub GETNUM { shift->GET(@_) || 0 }
sub GETSTR {
my $rv = shift->GET(@_);
return defined($rv) ? $rv : '';
}
=head2 SET
$hive->some->path->SET(10);
This method sets (replacing, if necessary) the hive value.
Its return value is not defined.
=cut
sub SET {
my $self = shift;
return $self->STORE->set($self->{path}, @_);
}
=head2 EXISTS
if ($hive->foo->bar->EXISTS) { ... }
This method tests whether a value (even an undefined one) exists for the hive.
=cut
sub EXISTS {
my $self = shift;
return $self->STORE->exists($self->{path});
}
=head2 DELETE
$hive->foo->bar->DELETE;
This method deletes the hive's value. The deleted value is returned. If no
value had existed, C<undef> is returned.
=cut
sub DELETE {
my $self = shift;
return $self->STORE->delete($self->{path});
}
+=item KEYS
+
+=cut
+
+sub KEYS {
+ my ($self) = @_;
+ return $self->STORE->keys($self->{path});
+}
=head2 HIVE
$hive->HIVE('foo'); # equivalent to $hive->foo
This method returns a subhive of the current hive. In most cases, it is
simpler to use the lowercase hive access method. This method is useful when
you must, for some reason, access an entry whose name is not a valid Perl
method name.
It is also needed if you must access a path with the same name as a method in
C<UNIVERSAL>. In general, only C<import>, C<isa>, and C<can> should fall into
this category, but some libraries unfortunately add methods to C<UNIVERSAL>.
Common offenders include C<moniker>, C<install_sub>, C<reinstall_sub>.
This method should be needed fairly rarely. It may also be called as C<ITEM>
for historical reasons.
=cut
sub ITEM {
my ($self, @rest) = @_;
return $self->HIVE(@rest);
}
sub HIVE {
my ($self, $key) = @_;
if (! defined $key or ! length $key or ref $key) {
$key = '(undef)' unless defined $key;
Carp::croak "illegal hive path part: $key";
}
return $self->NEW({
%$self,
path => [ @{$self->{path}}, $key ],
});
}
=head2 NAME
This method returns a name that can be used to represent the hive's path. This
name is B<store-dependent>, and should not be relied upon if the store may
change. It is provided primarily for debugging.
=cut
sub NAME {
my $self = shift;
return $self->STORE->name($self->{path});
}
=head2 STORE
This method returns the storage driver being used by the hive.
=cut
sub STORE {
return $_[0]->{store}
}
sub AUTOLOAD {
my $self = shift;
our $AUTOLOAD;
(my $method = $AUTOLOAD) =~ s/.*:://;
die "AUTOLOAD for '$method' called on non-object" unless ref $self;
return if $method eq 'DESTROY';
if ($method =~ /^[A-Z]+$/) {
Carp::croak("all-caps method names are reserved: '$method'");
}
return $self->ITEM($method);
}
1;
|
rjbs/Data-Hive
|
360bd617879429691cd3f25d72ecd9c75628b680
|
renaming ITEM to HIVE makes it clearer
|
diff --git a/lib/Data/Hive.pm b/lib/Data/Hive.pm
index 8f2f836..b55c7e1 100644
--- a/lib/Data/Hive.pm
+++ b/lib/Data/Hive.pm
@@ -1,323 +1,330 @@
use strict;
use warnings;
package Data::Hive;
# ABSTRACT: convenient access to hierarchical data
use Carp ();
=head1 SYNOPSIS
use Data::Hive;
my $hive = Data::Hive->NEW(\%arg);
$hive->foo->bar->quux->SET(17);
print $hive->foo->bar->baz->quux->GET; # 17
=head1 DESCRIPTION
Data::Hive doesn't do very much. Its main purpose is to provide a simple,
consistent interface for accessing simple, nested data dictionaries. The
mechanism for storing or consulting these dictionaries is abstract, so it can
be replaced without altering any of the code that reads or writes the hive.
A hive is like a set of nested hash references, but with a few crucial
differences:
=begin :list
* a hive is always accessed by methods, never by dereferencing with C<<->{}>>
For example, these two lines perform similar tasks:
$href->{foo}->{bar}->{baz}
$hive->foo->bar->baz->GET
* every key may have a value as well as children
With nested hashrefs, each entry is either another hashref (representing
children in the tree) or a leaf node. With a hive, each entry may be either or
both. For example, we can do this:
$hive->entry->SET(1);
$hive->entry->child->SET(1)
This wouldn't be possible with a hashref, because C<< $href->{entry} >> could
not hold both another node and a simple value.
It also means that a hive might non-existant entries found along the ways to
entries that exist:
$hive->NEW(...); # create a new hive with no entries
$hive->foo->bar->baz->SET(1); # set a single value
$hive->foo->EXISTS; # false! no value exists here
grep { 'foo' eq $_ } $hive->KEYS; # true! we can descent down this path
$hive->foo->bar->baz->EXISTS; # true! there is a value here
* hives are accessed by path, not by name
When you call C<< $hive->foo->bar->baz->GET >>, you're not accessing several
substructures. You're accessing I<one> hive. When the C<GET> method is
reached, the intervening names are converted into an entry path and I<that> is
accessed. Paths are made of zero or more non-empty strings. In other words,
while this is legal:
$href->{foo}->{''}->baz;
It is not legal to have an empty part in a hive path.
=end :list
=head1 WHY??
By using method access, the behavior of hives can be augmented as needed during
testing or development. Hives can be easily collapsed to single key/value
pairs using simple notations whereby C<< $hive->foo->bar->baz->SET(1) >>
becomes C<< $storage->{"foo.bar.baz"} = 1 >> or something similar.
This, along with the L<Data::Hive::Store> API makes it very easy to swap out
the storage and retrieval mechanism used for keeping hives in persistent
storage. It's trivial to persist entire hives into a database, flatfile, CGI
query, or many other structures, without using weird tricks beyond the weird
trick that is Data::Hive itself.
=head1 METHODS
=head2 hive path methods
All lowercase methods are used to travel down hive paths.
When you call C<< $hive->some_name >>, the return value is another Data::Hive
object using the same store as C<$hive> but with a starting path of
C<some_name>. With that hive, you can descend to deeper hives or you can get
or set its value.
Once you've reached the path where you want to perform a lookup or alteration,
you call an all-uppercase method. These are detailed below.
=head2 hive access methods
These methods are thin wrappers around required modules in L<Data::Hive::Store>
subclasses. These methods all basically call a method on the store with the
same (but lowercased) name and pass it the hive's path:
=for :list
* EXISTS
* GET
* SET
* NAME
* DELETE
* KEYS
=head2 NEW
This constructs a new hive object. Note that the name is C<NEW> and not
C<new>! The C<new> method is just another method to pick a hive path part.
The following are valid arguments for C<NEW>.
=begin :list
= store
a L<Data::Hive::Store> object, or one with a compatible interface; this will be
used as the hive's backend storage driver; do not supply C<store_class> or
C<store_args> if C<store> is supplied
= store_class
This names a class from which to instantiate a storage driver. The classname
will have C<Data::Hive::Store::> prepended; to avoid this, prefix it with a '='
(C<=My::Store>). A plus sign can be used instead of an equal sign, for
historical reasons.
= store_args
If C<store_class> has been provided instead of C<store>, this argument may be
given as an arrayref of arguments to pass (dereferenced) to the store class's
C<new> method.
=end :list
=cut
sub NEW {
my ($class, $arg) = @_;
$arg ||= {};
my @path = @{ $arg->{path} || [] };
my $self = bless { path => \@path } => ref($class) || $class;
if ($arg->{store_class}) {
die "don't use 'store' with 'store_class' and 'store_args'"
if $arg->{store};
$arg->{store_class} = "Data::Hive::Store::$arg->{store_class}"
unless $arg->{store_class} =~ s/^[+=]//;
$self->{store} = $arg->{store_class}->new(@{ $arg->{store_args} || [] });
} else {
$self->{store} = $arg->{store};
}
return $self;
}
=head2 GET
my $value = $hive->some->path->GET( $default );
The C<GET> method gets the hive value. If there is no defined value at the
path and a default has been supplied, the default will be returned instead.
=head2 GETNUM
=head2 GETSTR
These are provided soley for Perl 5.6.1 compatability, where returning undef
from overloaded numification/stringification can cause a segfault. They are
used internally by the deprecated overloadings for hives.
=cut
use overload (
q{""} => 'GETSTR',
q{0+} => 'GETNUM',
fallback => 1,
);
sub GET {
my ($self, $default) = @_;
my $value = $self->STORE->get($self->{path});
return defined $value ? $value : $default;
}
sub GETNUM { shift->GET(@_) || 0 }
sub GETSTR {
my $rv = shift->GET(@_);
return defined($rv) ? $rv : '';
}
=head2 SET
$hive->some->path->SET(10);
This method sets (replacing, if necessary) the hive value.
Its return value is not defined.
=cut
sub SET {
my $self = shift;
return $self->STORE->set($self->{path}, @_);
}
=head2 EXISTS
if ($hive->foo->bar->EXISTS) { ... }
This method tests whether a value (even an undefined one) exists for the hive.
=cut
sub EXISTS {
my $self = shift;
return $self->STORE->exists($self->{path});
}
=head2 DELETE
$hive->foo->bar->DELETE;
This method deletes the hive's value. The deleted value is returned. If no
value had existed, C<undef> is returned.
=cut
sub DELETE {
my $self = shift;
return $self->STORE->delete($self->{path});
}
-=head2 ITEM
- $hive->ITEM('foo'); # equivalent to $hive->foo
+=head2 HIVE
+
+ $hive->HIVE('foo'); # equivalent to $hive->foo
This method returns a subhive of the current hive. In most cases, it is
simpler to use the lowercase hive access method. This method is useful when
you must, for some reason, access an entry whose name is not a valid Perl
method name.
It is also needed if you must access a path with the same name as a method in
C<UNIVERSAL>. In general, only C<import>, C<isa>, and C<can> should fall into
this category, but some libraries unfortunately add methods to C<UNIVERSAL>.
Common offenders include C<moniker>, C<install_sub>, C<reinstall_sub>.
-This method should be needed fairly rarely.
+This method should be needed fairly rarely. It may also be called as C<ITEM>
+for historical reasons.
=cut
sub ITEM {
+ my ($self, @rest) = @_;
+ return $self->HIVE(@rest);
+}
+
+sub HIVE {
my ($self, $key) = @_;
if (! defined $key or ! length $key or ref $key) {
$key = '(undef)' unless defined $key;
Carp::croak "illegal hive path part: $key";
}
return $self->NEW({
%$self,
path => [ @{$self->{path}}, $key ],
});
}
=head2 NAME
This method returns a name that can be used to represent the hive's path. This
name is B<store-dependent>, and should not be relied upon if the store may
change. It is provided primarily for debugging.
=cut
sub NAME {
my $self = shift;
return $self->STORE->name($self->{path});
}
=head2 STORE
This method returns the storage driver being used by the hive.
=cut
sub STORE {
return $_[0]->{store}
}
sub AUTOLOAD {
my $self = shift;
our $AUTOLOAD;
(my $method = $AUTOLOAD) =~ s/.*:://;
die "AUTOLOAD for '$method' called on non-object" unless ref $self;
return if $method eq 'DESTROY';
if ($method =~ /^[A-Z]+$/) {
Carp::croak("all-caps method names are reserved: '$method'");
}
return $self->ITEM($method);
}
1;
|
rjbs/Data-Hive
|
9936375347f94e40c071aa285a9e6f3d6bfc0653
|
warning about the vicissitudes of the hash format
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..5a462c7
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+Data-Hive-*
+.build
diff --git a/Changes b/Changes
new file mode 100644
index 0000000..bf97b31
--- /dev/null
+++ b/Changes
@@ -0,0 +1,37 @@
+Revision history for Data-Hive
+
+{{$NEXT}}
+
+0.054 2010-08-26 14:58:29 America/New_York
+ minor tweaks, mostly to enable use of Dist::Zilla
+
+0.053 2008-09-12
+ ->GET($default) added
+
+0.052 2007-11-19
+ Fix bug where Store::Hash was inadvertently destroying state
+ information it shouldn't have in some cases
+
+0.051 2007-11-15
+ Guard eval with local $SIG{__DIE__} in case someone else has been
+ careless with theirs
+
+ Remove useless t/boilerplate.t
+
+0.050 2007-04-02
+ Add GETSTR to avoid stupid SEGVs
+ Add DELETE
+
+0.040 2006-08-28
+
+ Freshen Module::Install
+
+0.03 2006-07-03
+ Add missing dep for Test::MockObject.
+
+0.02 2006-06-08
+ Add EXISTS.
+
+0.01 2006-06-05
+ First version, released on an unsuspecting world.
+
diff --git a/dist.ini b/dist.ini
new file mode 100644
index 0000000..2e09b3f
--- /dev/null
+++ b/dist.ini
@@ -0,0 +1,12 @@
+name = Data-Hive
+authors = Hans Dieter Pearcey <[email protected]>
+authors = Ricardo Signes <[email protected]>
+copyright_year = 2006
+copyright_holder = Hans Dieter Pearcey
+
+[@Filter]
+bundle = @RJBS
+remove = AutoVersion
+
+[BumpVersionFromGit]
+version_regexp = ^([0-9]+\.[0-9]+)$
diff --git a/lib/Data/Hive.pm b/lib/Data/Hive.pm
new file mode 100644
index 0000000..8f2f836
--- /dev/null
+++ b/lib/Data/Hive.pm
@@ -0,0 +1,323 @@
+use strict;
+use warnings;
+package Data::Hive;
+# ABSTRACT: convenient access to hierarchical data
+
+use Carp ();
+
+=head1 SYNOPSIS
+
+ use Data::Hive;
+
+ my $hive = Data::Hive->NEW(\%arg);
+
+ $hive->foo->bar->quux->SET(17);
+
+ print $hive->foo->bar->baz->quux->GET; # 17
+
+=head1 DESCRIPTION
+
+Data::Hive doesn't do very much. Its main purpose is to provide a simple,
+consistent interface for accessing simple, nested data dictionaries. The
+mechanism for storing or consulting these dictionaries is abstract, so it can
+be replaced without altering any of the code that reads or writes the hive.
+
+A hive is like a set of nested hash references, but with a few crucial
+differences:
+
+=begin :list
+
+* a hive is always accessed by methods, never by dereferencing with C<<->{}>>
+
+For example, these two lines perform similar tasks:
+
+ $href->{foo}->{bar}->{baz}
+
+ $hive->foo->bar->baz->GET
+
+* every key may have a value as well as children
+
+With nested hashrefs, each entry is either another hashref (representing
+children in the tree) or a leaf node. With a hive, each entry may be either or
+both. For example, we can do this:
+
+ $hive->entry->SET(1);
+
+ $hive->entry->child->SET(1)
+
+This wouldn't be possible with a hashref, because C<< $href->{entry} >> could
+not hold both another node and a simple value.
+
+It also means that a hive might non-existant entries found along the ways to
+entries that exist:
+
+ $hive->NEW(...); # create a new hive with no entries
+
+ $hive->foo->bar->baz->SET(1); # set a single value
+
+ $hive->foo->EXISTS; # false! no value exists here
+
+ grep { 'foo' eq $_ } $hive->KEYS; # true! we can descent down this path
+
+ $hive->foo->bar->baz->EXISTS; # true! there is a value here
+
+* hives are accessed by path, not by name
+
+When you call C<< $hive->foo->bar->baz->GET >>, you're not accessing several
+substructures. You're accessing I<one> hive. When the C<GET> method is
+reached, the intervening names are converted into an entry path and I<that> is
+accessed. Paths are made of zero or more non-empty strings. In other words,
+while this is legal:
+
+ $href->{foo}->{''}->baz;
+
+It is not legal to have an empty part in a hive path.
+
+=end :list
+
+=head1 WHY??
+
+By using method access, the behavior of hives can be augmented as needed during
+testing or development. Hives can be easily collapsed to single key/value
+pairs using simple notations whereby C<< $hive->foo->bar->baz->SET(1) >>
+becomes C<< $storage->{"foo.bar.baz"} = 1 >> or something similar.
+
+This, along with the L<Data::Hive::Store> API makes it very easy to swap out
+the storage and retrieval mechanism used for keeping hives in persistent
+storage. It's trivial to persist entire hives into a database, flatfile, CGI
+query, or many other structures, without using weird tricks beyond the weird
+trick that is Data::Hive itself.
+
+=head1 METHODS
+
+=head2 hive path methods
+
+All lowercase methods are used to travel down hive paths.
+
+When you call C<< $hive->some_name >>, the return value is another Data::Hive
+object using the same store as C<$hive> but with a starting path of
+C<some_name>. With that hive, you can descend to deeper hives or you can get
+or set its value.
+
+Once you've reached the path where you want to perform a lookup or alteration,
+you call an all-uppercase method. These are detailed below.
+
+=head2 hive access methods
+
+These methods are thin wrappers around required modules in L<Data::Hive::Store>
+subclasses. These methods all basically call a method on the store with the
+same (but lowercased) name and pass it the hive's path:
+
+=for :list
+* EXISTS
+* GET
+* SET
+* NAME
+* DELETE
+* KEYS
+
+=head2 NEW
+
+This constructs a new hive object. Note that the name is C<NEW> and not
+C<new>! The C<new> method is just another method to pick a hive path part.
+
+The following are valid arguments for C<NEW>.
+
+=begin :list
+
+= store
+
+a L<Data::Hive::Store> object, or one with a compatible interface; this will be
+used as the hive's backend storage driver; do not supply C<store_class> or
+C<store_args> if C<store> is supplied
+
+= store_class
+
+This names a class from which to instantiate a storage driver. The classname
+will have C<Data::Hive::Store::> prepended; to avoid this, prefix it with a '='
+(C<=My::Store>). A plus sign can be used instead of an equal sign, for
+historical reasons.
+
+= store_args
+
+If C<store_class> has been provided instead of C<store>, this argument may be
+given as an arrayref of arguments to pass (dereferenced) to the store class's
+C<new> method.
+
+=end :list
+
+=cut
+
+sub NEW {
+ my ($class, $arg) = @_;
+ $arg ||= {};
+
+ my @path = @{ $arg->{path} || [] };
+
+ my $self = bless { path => \@path } => ref($class) || $class;
+
+ if ($arg->{store_class}) {
+ die "don't use 'store' with 'store_class' and 'store_args'"
+ if $arg->{store};
+
+ $arg->{store_class} = "Data::Hive::Store::$arg->{store_class}"
+ unless $arg->{store_class} =~ s/^[+=]//;
+
+ $self->{store} = $arg->{store_class}->new(@{ $arg->{store_args} || [] });
+ } else {
+ $self->{store} = $arg->{store};
+ }
+
+ return $self;
+}
+
+=head2 GET
+
+ my $value = $hive->some->path->GET( $default );
+
+The C<GET> method gets the hive value. If there is no defined value at the
+path and a default has been supplied, the default will be returned instead.
+
+=head2 GETNUM
+
+=head2 GETSTR
+
+These are provided soley for Perl 5.6.1 compatability, where returning undef
+from overloaded numification/stringification can cause a segfault. They are
+used internally by the deprecated overloadings for hives.
+
+=cut
+
+use overload (
+ q{""} => 'GETSTR',
+ q{0+} => 'GETNUM',
+ fallback => 1,
+);
+
+sub GET {
+ my ($self, $default) = @_;
+ my $value = $self->STORE->get($self->{path});
+ return defined $value ? $value : $default;
+}
+
+sub GETNUM { shift->GET(@_) || 0 }
+
+sub GETSTR {
+ my $rv = shift->GET(@_);
+ return defined($rv) ? $rv : '';
+}
+
+=head2 SET
+
+ $hive->some->path->SET(10);
+
+This method sets (replacing, if necessary) the hive value.
+
+Its return value is not defined.
+
+=cut
+
+sub SET {
+ my $self = shift;
+ return $self->STORE->set($self->{path}, @_);
+}
+
+=head2 EXISTS
+
+ if ($hive->foo->bar->EXISTS) { ... }
+
+This method tests whether a value (even an undefined one) exists for the hive.
+
+=cut
+
+sub EXISTS {
+ my $self = shift;
+ return $self->STORE->exists($self->{path});
+}
+
+=head2 DELETE
+
+ $hive->foo->bar->DELETE;
+
+This method deletes the hive's value. The deleted value is returned. If no
+value had existed, C<undef> is returned.
+
+=cut
+
+sub DELETE {
+ my $self = shift;
+ return $self->STORE->delete($self->{path});
+}
+
+=head2 ITEM
+
+ $hive->ITEM('foo'); # equivalent to $hive->foo
+
+This method returns a subhive of the current hive. In most cases, it is
+simpler to use the lowercase hive access method. This method is useful when
+you must, for some reason, access an entry whose name is not a valid Perl
+method name.
+
+It is also needed if you must access a path with the same name as a method in
+C<UNIVERSAL>. In general, only C<import>, C<isa>, and C<can> should fall into
+this category, but some libraries unfortunately add methods to C<UNIVERSAL>.
+Common offenders include C<moniker>, C<install_sub>, C<reinstall_sub>.
+
+This method should be needed fairly rarely.
+
+=cut
+
+sub ITEM {
+ my ($self, $key) = @_;
+
+ if (! defined $key or ! length $key or ref $key) {
+ $key = '(undef)' unless defined $key;
+ Carp::croak "illegal hive path part: $key";
+ }
+
+ return $self->NEW({
+ %$self,
+ path => [ @{$self->{path}}, $key ],
+ });
+}
+
+=head2 NAME
+
+This method returns a name that can be used to represent the hive's path. This
+name is B<store-dependent>, and should not be relied upon if the store may
+change. It is provided primarily for debugging.
+
+=cut
+
+sub NAME {
+ my $self = shift;
+ return $self->STORE->name($self->{path});
+}
+
+=head2 STORE
+
+This method returns the storage driver being used by the hive.
+
+=cut
+
+sub STORE {
+ return $_[0]->{store}
+}
+
+sub AUTOLOAD {
+ my $self = shift;
+ our $AUTOLOAD;
+
+ (my $method = $AUTOLOAD) =~ s/.*:://;
+ die "AUTOLOAD for '$method' called on non-object" unless ref $self;
+
+ return if $method eq 'DESTROY';
+
+ if ($method =~ /^[A-Z]+$/) {
+ Carp::croak("all-caps method names are reserved: '$method'");
+ }
+
+ return $self->ITEM($method);
+}
+
+1;
diff --git a/lib/Data/Hive/Store.pm b/lib/Data/Hive/Store.pm
new file mode 100644
index 0000000..fddf4a6
--- /dev/null
+++ b/lib/Data/Hive/Store.pm
@@ -0,0 +1,82 @@
+use strict;
+use warnings;
+package Data::Hive::Store;
+# ABSTRACT: a backend storage driver for Data::Hive
+
+use Carp ();
+
+=head1 DESCRIPTION
+
+Data::Hive::Store is a generic interface to a backend store
+for Data::Hive.
+
+=head1 METHODS
+
+All methods are passed at least a 'path' (arrayref of namespace pieces). Store
+classes exist to operate on the entities found at named paths.
+
+=head2 get
+
+ print $store->get(\@path, \%opt);
+
+Return the resource represented by the given path.
+
+=head2 set
+
+ $store->set(\@path, $value, \%opt);
+
+Analogous to C<< get >>.
+
+=head2 name
+
+ print $store->name(\@path, \%opt);
+
+Return a store-specific name for the given path. This is primarily useful for
+stores that may be accessed independently of the hive.
+
+=head2 exists
+
+ if ($store->exists(\@path, \%opt)) { ... }
+
+Returns true if the given path exists in the store.
+
+=head2 delete
+
+ $store->delete(\@path, \%opt);
+
+Delete the given path from the store. Return the previous value, if any.
+
+=head2 keys
+
+ my @keys = $store->keys(\@path, \%opt);
+
+This returns a list of next-level path elements that exist. For example, given
+a hive with values for the following paths:
+
+ foo
+ foo/bar
+ foo/bar/baz
+ foo/xyz/abc
+ foo/xyz/def
+ foo/123
+
+This shows the expected results:
+
+ keys of | returns
+ -------------+------------
+ foo | bar, xyz, 123
+ foo/bar | baz
+ foo/bar/baz |
+ foo/xyz | abc, def
+ foo/123 |
+
+=cut
+
+BEGIN {
+ for my $meth (qw(get set name exists delete keys)) {
+ no strict 'refs';
+ *$meth = sub { Carp::croak("$_[0] does not implement $meth") };
+ }
+}
+
+1;
diff --git a/lib/Data/Hive/Store/Hash.pm b/lib/Data/Hive/Store/Hash.pm
new file mode 100644
index 0000000..aa0c7b6
--- /dev/null
+++ b/lib/Data/Hive/Store/Hash.pm
@@ -0,0 +1,247 @@
+use strict;
+use warnings;
+package Data::Hive::Store::Hash;
+# ABSTRACT: store a hive in nested hashrefs
+
+=head1 DESCRIPTION
+
+This is a simple store, primarily for testing, that will store hives in nested
+hashrefs. All hives are represented as hashrefs, and their values are stored
+in the entry for the empty string.
+
+So, we could do this:
+
+ my $href = {};
+
+ my $hive = Data::Hive->NEW({
+ store_class => 'Hash',
+ store_args => [ $href ],
+ });
+
+ $hive->foo->SET(1);
+ $hive->foo->bar->baz->SET(2);
+
+We would end up with C<$href> containing:
+
+ {
+ foo => {
+ '' => 1,
+ bar => {
+ baz => {
+ '' => 2,
+ },
+ },
+ },
+ }
+
+Using empty keys results in a bigger, uglier dump, but allows a given hive to
+contain both a value and subhives. B<Please note> that this is different
+behavior compared with earlier releases, in which empty keys were not used and
+it was not legal to have a value and a hive at a given path. It is possible,
+although fairly unlikely, that this format will change again. The Hash store
+should generally be used for testing things that use a hive, as opposed for
+building hashes that will be used for anything else.
+
+=method new
+
+ my $store = Data::Hive::Store::Hash->new(\%hash);
+
+The only argument expected for C<new> is a hashref, which is the hashref in
+which hive entries are stored.
+
+If no hashref is provided, a new, empty hashref will be used.
+
+=cut
+
+sub new {
+ my ($class, $href) = @_;
+ $href = {} unless defined $href;
+
+ return bless { store => $href } => $class;
+}
+
+=method hash_store
+
+This method returns the hashref in which things are being used. You should not
+alter its contents!
+
+=cut
+
+sub hash_store {
+ $_[0]->{store}
+}
+
+=method get
+
+Use given C<< \@path >> as nesting keys in the hashref store.
+
+=cut
+
+sub _die {
+ require Carp::Clan;
+ Carp::Clan->import('^Data::Hive($|::)');
+ croak(shift);
+}
+
+my $BREAK = "BREAK\n";
+
+# Wow, this is quite a little machine! Here's a slightly simplified overview
+# of what it does: -- rjbs, 2010-08-27
+#
+# As long as cond->(\@remaining_path) is true, execute step->($next,
+# $current_hashref, \@remaining_path)
+#
+# If it dies with $BREAK, stop looping and return. Once the cond returns
+# false, return end->($current_hashref, \@remaining_path)
+sub _descend {
+ my ($self, $orig_path, $arg) = @_;
+ my @path = @$orig_path;
+
+ $arg ||= {};
+ $arg->{step} or die "step is required";
+ $arg->{cond} ||= sub { @{ shift() } };
+ $arg->{end} ||= sub { $_[0] };
+
+ my $node = $self->hash_store;
+
+ while ($arg->{cond}->(\@path)) {
+ my $seg = shift @path;
+
+ {
+ local $SIG{__DIE__};
+ eval { $arg->{step}->($seg, $node, \@path) };
+ }
+
+ return if $@ and $@ eq $BREAK;
+ die $@ if $@;
+ $node = $node->{$seg} ||= {};
+ }
+
+ return $arg->{end}->($node, \@path);
+}
+
+sub get {
+ my ($self, $path) = @_;
+ return $self->_descend(
+ $path, {
+ end => sub { $_[0]->{''} },
+ step => sub {
+ my ($seg, $node) = @_;
+
+ if (defined $node and not ref $node) {
+ # We found a bogus entry in the store! -- rjbs, 2010-08-27
+ _die("can't get key '$seg' of non-ref value '$node'");
+ }
+
+ die $BREAK unless exists $node->{$seg};
+ }
+ }
+ );
+}
+
+=method set
+
+See C<L</get>>. Dies if you try to set a key underneath an existing
+non-hashref key, e.g.:
+
+ $hash = { foo => 1 };
+ $store->set([ 'foo', 'bar' ], 2); # dies
+
+=cut
+
+sub set {
+ my ($self, $path, $value) = @_;
+ return $self->_descend(
+ $path, {
+ step => sub {
+ my ($seg, $node, $path) = @_;
+ if (exists $node->{$seg} and not ref $node->{$seg}) {
+ _die("can't overwrite existing non-ref value: '$node->{$seg}'");
+ }
+ },
+ cond => sub { @{ shift() } > 1 },
+ end => sub {
+ my ($node, $path) = @_;
+ $node->{$path->[0]}{''} = $value;
+ },
+ },
+ );
+}
+
+=method name
+
+Returns a string, potentially suitable for eval-ing, describing a hash
+dereference of a variable called C<< $STORE >>.
+
+ "$STORE->{foo}->{bar}"
+
+This is probably not very useful.
+
+=cut
+
+sub name {
+ my ($self, $path) = @_;
+ return join '->', '$STORE', map { "{'$_'}" } @$path;
+}
+
+=method exists
+
+Descend the hash and return false if any of the path's parts do not exist, or
+true if they all do.
+
+=cut
+
+sub exists {
+ my ($self, $path) = @_;
+ return $self->_descend(
+ $path, {
+ step => sub {
+ my ($seg, $node) = @_;
+ die $BREAK unless exists $node->{$seg};
+ },
+ },
+ );
+}
+
+=method delete
+
+Descend the hash and delete the given path. Only deletes the leaf.
+
+=cut
+
+sub delete {
+ my ($self, $path) = @_;
+
+ return $self->_descend(
+ $path, {
+ step => sub {
+ my ($seg, $node) = @_;
+ die $BREAK unless exists $node->{$seg};
+ },
+ cond => sub { @{ shift() } > 1 },
+ end => sub {
+ my ($node, $final_path) = @_;
+ my $this = $node->{ $final_path->[0] };
+ my $rv = delete $this->{''};
+
+ # Cleanup empty trees after deletion! It would be convenient to have
+ # ->_ascend, but I'm not likely to bother with writing it just yet.
+ # -- rjbs, 2010-08-27
+ $self->_descend(
+ $path, {
+ step => sub {
+ my ($seg, $node) = @_;
+ return if keys %{ $node->{$seg} };
+ delete $node->{$seg};
+ die $BREAK;
+ },
+ }
+ );
+
+ return $rv;
+ },
+ },
+ );
+}
+
+1;
diff --git a/lib/Data/Hive/Store/Param.pm b/lib/Data/Hive/Store/Param.pm
new file mode 100644
index 0000000..190cee8
--- /dev/null
+++ b/lib/Data/Hive/Store/Param.pm
@@ -0,0 +1,144 @@
+use strict;
+use warnings;
+package Data::Hive::Store::Param;
+# ABSTRACT: CGI::param-like store for Data::Hive
+
+=method new
+
+ # use default method name 'param'
+ my $store = Data::Hive::Store::Param->new($obj);
+
+ # use different method name 'info'
+ my $store = Data::Hive::Store::Param->new($obj, { method => 'info' });
+
+ # escape certain characters in keys
+ my $store = Data::Hive::Store::Param->new($obj, { escape => './!' });
+
+Return a new Param store.
+
+Several interesting arguments can be passed in a hashref after the first
+(mandatory) object argument.
+
+=begin :list
+
+= method
+
+Use a different method name on the object (default is 'param').
+
+= escape
+
+List of characters to escape (prepend '\' to) in keys.
+
+Defaults to the C<< separator >>.
+
+= separator
+
+String to join path segments together with; defaults to either the first
+character of the C<< escape >> option (if given) or '.'.
+
+= exists
+
+Coderef that describes how to see if a given parameter name (C<< separator
+>>-joined path) exists. The default is to treat the object like a hashref and
+look inside it.
+
+= delete
+
+Coderef that describes how to delete a given parameter name. The default is to
+treat the object like a hashref and call C<delete> on it.
+
+=end :list
+
+=cut
+
+sub _escape {
+ my ($self, $str) = @_;
+ my $escape = $self->{escape} or return $str;
+ $str =~ s/([\Q$escape\E%])/sprintf("%%%x", ord($1))/ge;
+ return $str;
+}
+
+sub _path {
+ my ($self, $path) = @_;
+ return join $self->{separator}, map { $self->_escape($_) } @$path;
+}
+
+sub new {
+ my ($class, $obj, $arg) = @_;
+ $arg ||= {};
+ $arg->{escape} ||= $arg->{separator} || '.';
+ $arg->{separator} ||= substr($arg->{escape}, 0, 1);
+ $arg->{method} ||= 'param';
+ $arg->{exists} ||= sub { exists $obj->{shift()} };
+ $arg->{delete} ||= sub { delete $obj->{shift()} };
+ $arg->{obj} = $obj;
+ return bless { %$arg } => $class;
+}
+
+sub _param {
+ my $self = shift;
+ my $meth = $self->{method};
+ my $path = $self->_path(shift);
+ return $self->{obj}->$meth($path, @_);
+}
+
+=method get
+
+Join the path together with the C<< separator >> and get it from the object.
+
+=cut
+
+sub get {
+ my ($self, $path) = @_;
+ return $self->_param($path);
+}
+
+=method set
+
+See L</get>.
+
+=cut
+
+sub set {
+ my ($self, $path, $val) = @_;
+ return $self->_param($path => $val);
+}
+
+=method name
+
+Join path together with C<< separator >> and return it.
+
+=cut
+
+sub name {
+ my ($self, $path) = @_;
+ return $self->_path($path);
+}
+
+=method exists
+
+Return true if the C<< name >> of this hive is a parameter.
+
+=cut
+
+sub exists {
+ my ($self, $path) = @_;
+ my $code = $self->{exists};
+ my $key = $self->_path($path);
+ return ref($code) ? $code->($key) : $self->{obj}->$code($key);
+}
+
+=method delete
+
+Delete the entry for the C<< name >> of this hive and return its old value.
+
+=cut
+
+sub delete {
+ my ($self, $path) = @_;
+ my $code = $self->{delete};
+ my $key = $self->_path($path);
+ return ref($code) ? $code->($key) : $self->{obj}->$code($key);
+}
+
+1;
diff --git a/t/00-load.t b/t/00-load.t
new file mode 100644
index 0000000..da1baec
--- /dev/null
+++ b/t/00-load.t
@@ -0,0 +1,9 @@
+#!perl -T
+
+use Test::More tests => 1;
+
+BEGIN {
+ use_ok( 'Data::Hive' );
+}
+
+diag( "Testing Data::Hive $Data::Hive::VERSION, Perl $], $^X" );
diff --git a/t/default.t b/t/default.t
new file mode 100644
index 0000000..41acada
--- /dev/null
+++ b/t/default.t
@@ -0,0 +1,31 @@
+#!perl
+
+use strict;
+use warnings;
+
+use Test::More 'no_plan';
+use ok 'Data::Hive';
+use ok 'Data::Hive::Store::Hash';
+
+my $hive = Data::Hive->NEW({
+ store => Data::Hive::Store::Hash->new(
+ my $store = {}
+ ),
+});
+
+isa_ok($hive, 'Data::Hive');
+
+$hive->foo->SET(1);
+
+is(0 + $hive->bar, 0, "0 == ->bar");
+
+{
+ no warnings;
+ is(0 + $hive->bar->GET, 0, "0 == ->bar->GET");
+}
+
+is(0 + $hive->bar->GETNUM, 0, "0 == ->bar->GETNUM");
+is(0 + $hive->bar->GET(1), 1, "1 == ->bar->GET(1)");
+is(0 + $hive->bar->GETNUM(1), 1, "1 == ->bar->GETNUM(1)");
+
+is_deeply($store, { foo => { '' => 1 } }, 'did not autovivify');
diff --git a/t/hash.t b/t/hash.t
new file mode 100644
index 0000000..a903c08
--- /dev/null
+++ b/t/hash.t
@@ -0,0 +1,109 @@
+#!perl
+use strict;
+use warnings;
+
+use Data::Hive;
+use Data::Hive::Store::Hash;
+
+use Test::More 0.88;
+
+my $hive = Data::Hive->NEW({
+ store_class => 'Hash',
+});
+
+my $tmp;
+
+isa_ok($hive, 'Data::Hive', 'top-level hive');
+
+isa_ok($hive->foo, 'Data::Hive', '"foo" subhive');
+
+$hive->foo->SET(1);
+
+is_deeply(
+ $hive->STORE->hash_store,
+ { foo => { '' => 1 } },
+ 'changes made to store',
+);
+
+$hive->bar->baz->GET;
+
+is_deeply(
+ $hive->STORE->hash_store,
+ { foo => { '' => 1 } },
+ 'did not autovivify'
+);
+
+$hive->baz->quux->SET(2);
+
+is_deeply(
+ $hive->STORE->hash_store,
+ {
+ foo => { '' => 1 },
+ baz => { quux => { '' => 2 } },
+ },
+ 'deep set',
+);
+
+is(
+ $hive->foo->GET,
+ 1,
+ "get the 1 from ->foo",
+);
+
+is(
+ $hive->foo->bar->GET,
+ undef,
+ "find nothing at ->foo->bar",
+);
+
+$hive->foo->bar->SET(3);
+
+is(
+ $hive->foo->bar->GET,
+ 3,
+ "wrote and retrieved 3 from ->foo->bar",
+);
+
+ok ! $hive->not->EXISTS, "non-existent key doesn't EXISTS";
+ok $hive->foo->EXISTS, "existing key does EXISTS";
+
+$hive->baz->quux->frotz->SET(4);
+
+is_deeply(
+ $hive->STORE->hash_store,
+ {
+ foo => { '' => 1, bar => { '' => 3 } },
+ baz => { quux => { '' => 2, frotz => { '' => 4 } } },
+ },
+ "deep delete"
+);
+
+my $quux = $hive->baz->quux;
+is($quux->GET, 2, "get from saved leaf");
+is($quux->DELETE, 2, "delete returned old value");
+is($quux->GET, undef, "after deletion, hive has no value");
+
+is_deeply(
+ $hive->STORE->hash_store,
+ {
+ foo => { '' => 1, bar => { '' => 3 } },
+ baz => { quux => { frotz => { '' => 4 } } },
+ },
+ "deep delete"
+);
+
+my $frotz = $hive->baz->quux->frotz;
+is($frotz->GET, 4, "get from saved leaf");
+is($frotz->DELETE, 4, "delete returned old value");
+is($frotz->GET, undef, "after deletion, hive has no value");
+
+is_deeply(
+ $hive->STORE->hash_store,
+ {
+ foo => { '' => 1, bar => { '' => 3 } },
+ baz => { quux => { } },
+ },
+ "deep delete: after a hive had no keys, it is deleted, too"
+) or note explain $hive->STORE->hash_store;
+
+done_testing;
diff --git a/t/param.t b/t/param.t
new file mode 100644
index 0000000..45f69b8
--- /dev/null
+++ b/t/param.t
@@ -0,0 +1,65 @@
+#!perl
+
+use strict;
+use warnings;
+
+use Test::More 'no_plan';
+use Test::MockObject;
+
+use ok 'Data::Hive';
+use ok 'Data::Hive::Store::Param';
+
+my $obj = Test::MockObject->new;
+my $param = {};
+$obj->mock(
+ info => sub {
+ my (undef, $key, $val) = @_;
+ $param->{$key} = $val if @_ > 2;
+ return $param->{$key};
+ },
+);
+$obj->mock(
+ info_exists => sub {
+ my (undef, $key) = @_;
+ return exists $param->{$key};
+ }
+);
+$obj->mock(
+ info_delete => sub {
+ my (undef, $key) = @_;
+ return delete $param->{$key};
+ },
+);
+
+my $hive = Data::Hive->NEW({
+ store_class => 'Param',
+ store_args => [ $obj, {
+ method => 'info',
+ separator => '/',
+ exists => 'info_exists',
+ delete => 'info_delete',
+ } ],
+});
+
+%$param = (
+ foo => 1,
+ 'bar/baz' => 2,
+);
+
+is $hive->bar->baz, 2, 'GET';
+$hive->foo->SET(3);
+is_deeply $param, { foo => 3, 'bar/baz' => 2 }, 'SET';
+
+is $hive->bar->baz->NAME, 'bar/baz', 'NAME';
+
+ok ! $hive->not->EXISTS, "non-existent key doesn't EXISTS";
+ok $hive->foo->EXISTS, "existing key does EXISTS";
+
+$hive->ITEM("and/or")->SET(17);
+
+is_deeply $param, { foo => 3, 'bar/baz' => 2, 'and%2for' => 17 },
+ 'SET (with escape)';
+is $hive->ITEM("and/or"), 17, 'GET (with escape)';
+
+is $hive->bar->baz->DELETE, 2, "delete returns old value";
+is_deeply $param, { foo => 3, 'and%2for' => 17 }, "delete removed item";
|
jdcampbell/classfiles
|
beef0777af5f0559ebd121b3aa444d8532f2e466
|
changed
|
diff --git a/Document.rtf b/Document.rtf
index 76d4072..7fea4ab 100644
Binary files a/Document.rtf and b/Document.rtf differ
|
jdcampbell/classfiles
|
8de305f19b761fe002274c22cb904572934121be
|
Class Files 2-4-09 Josh Campbell
|
diff --git a/Block Vs. Inline.odt b/Block Vs. Inline.odt
new file mode 100644
index 0000000..3d79f5f
Binary files /dev/null and b/Block Vs. Inline.odt differ
diff --git a/CSS and Microformat.docx b/CSS and Microformat.docx
new file mode 100644
index 0000000..abef133
Binary files /dev/null and b/CSS and Microformat.docx differ
diff --git a/CodeTemplate.txt b/CodeTemplate.txt
new file mode 100644
index 0000000..ef3ae89
--- /dev/null
+++ b/CodeTemplate.txt
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8">
+<!DOCTYPE html PUBLIC "-//DTD XHTML 1.1//EN" "http:www.w3.org/TR/xhtm111?DTD/xhtml.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
+ <head> <Josh Campbell My WebSite>
+ <title>Josh's Sweet Site</title>
+
+ <script src="js/main.js" type="text/javascript"></script>
+
+ <link rel="stylesheet" href="css/main.css" type="text/css" media="screen" />
+ <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+ <meta http-equiv="imagetoolbar" content="no" />
+ <meta name="description" content="" />
+ <meta name="keywords" content="" />
+ <meta name="robots" content="all, index, follow" />
+ <meta name="revisit-after" content="14 days" />
+ <meta name="resource-type" content="document" />
+ <meta name="rating" content="general" />
+ </head>
+ <body>
+
+ </body>
+</html>
\ No newline at end of file
diff --git a/Document.rtf b/Document.rtf
new file mode 100644
index 0000000..76d4072
Binary files /dev/null and b/Document.rtf differ
diff --git a/Internet Timeline.docx b/Internet Timeline.docx
new file mode 100644
index 0000000..7b90467
Binary files /dev/null and b/Internet Timeline.docx differ
diff --git a/MySite.htm b/MySite.htm
new file mode 100644
index 0000000..c6c5a46
--- /dev/null
+++ b/MySite.htm
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE html PUBLIC "-//DTD XHTML 1.1//EN" "http:www.w3.org/TR/xhtm111?DTD/xhtml.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
+ <head> Josh Campbell My WebSite
+ <title>Josh's Sweet Site</title>
+
+ <script src="js/main.js" type="text/javascript"></script>
+
+ <link rel="stylesheet" href="css/main.css" type="text/css" media="screen" />
+ <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+ <meta http-equiv="imagetoolbar" content="no" />
+ <meta name="description" content="" />
+ <meta name="keywords" content="" />
+ <meta name="robots" content="all, index, follow" />
+ <meta name="revisit-after" content="14 days" />
+ <meta name="resource-type" content="document" />
+ <meta name="rating" content="general" />
+ </head>
+ <body>
+ <h1>Josh</h1>
+ <h3>Bio</h3>
+ <div> Information about me </div>
+ <h3>Intrests</h3>
+ <div> Information about Intrests </div>
+ <h3>Links</h3>
+ <div> Some Links i think are worth linking </div>
+ </body>
+</html>
\ No newline at end of file
diff --git a/MySite.txt b/MySite.txt
new file mode 100644
index 0000000..147222d
--- /dev/null
+++ b/MySite.txt
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8">
+<!DOCTYPE html PUBLIC "-//DTD XHTML 1.1//EN" "http:www.w3.org/TR/xhtm111?DTD/xhtml.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
+ <head> Josh Campbell My WebSite
+ <title>Josh's Sweet Site</title>
+
+ <script src="js/main.js" type="text/javascript"></script>
+
+ <link rel="stylesheet" href="css/main.css" type="text/css" media="screen" />
+ <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+ <meta http-equiv="imagetoolbar" content="no" />
+ <meta name="description" content="" />
+ <meta name="keywords" content="" />
+ <meta name="robots" content="all, index, follow" />
+ <meta name="revisit-after" content="14 days" />
+ <meta name="resource-type" content="document" />
+ <meta name="rating" content="general" />
+ </head>
+ <body>
+ <h1>Josh</h1>
+ <h3>Bio</h3>
+ <div> Information about me </div>
+ <h3>Intrests</h3>
+ <div> Information about Intrests </div>
+ <h3>Links</h3>
+ <div> Some Links i think are worth linking </div>
+ </body>
+</html>
\ No newline at end of file
diff --git a/Subversion.docx b/Subversion.docx
new file mode 100644
index 0000000..8177744
Binary files /dev/null and b/Subversion.docx differ
diff --git a/html_css_demo/about.html b/html_css_demo/about.html
new file mode 100644
index 0000000..f8cdc54
--- /dev/null
+++ b/html_css_demo/about.html
@@ -0,0 +1,49 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
+ <head>
+ <title>About Bubble Under: who we are, what this site is for</title>
+ <!-- Stylesheets -->
+ <link rel="stylesheet" href="css/main.css" type="text/css" media="screen" />
+
+ <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+ <meta http-equiv="imagetoolbar" content="no" />
+ </head>
+ <body>
+ <div id="header">
+ <div id="sitebranding">
+ <h1>BubbleUnder.com</h1>
+ </div>
+ <div id="tagline">
+ <p>Diving club for the south-west UK - let's make a splash!</p>
+ </div>
+ </div> <!-- end of header div -->
+ <div id="navigation">
+ <ul>
+ <li><a href="index.html">Home</a></li>
+ <li><a href="about.html">About Us</a></li>
+ <li><a href="contact.html">Contact Us</a></li>
+ </ul>
+ </div> <!-- end of navigation div -->
+ <div id="bodycontent">
+ <h2>About Us</h2>
+ <p>Bubble Under is a group of diving enthusiasts based in the
+ south-west UK who meet up for diving trips in the summer
+ months when the weather is good and the bacon rolls are
+ flowing. We arrange weekends away as small groups to cut
+ the costs of accommodation and travel and to ensure that
+ everyone gets a trustworthy dive buddy.</p>
+ <p>Although we're based in the south-west, we don't stay on
+ our own turf: past diving weekends away have included
+ trips up to Scapa Flow in Scotland and to Malta's numerous
+ wreck sites.</p>
+ <p>When we're not diving, we often meet up in a local pub to
+ talk about our recent adventures (any excuse, eh?).</p>
+ <p>Or as our man Bob Dobalina would put it:</p>
+ <blockquote>
+ <p>"Happiness is a dip in the ocean followed by a pint or
+ two of Old Speckled Hen. You can quote me on that!"</p>
+ </blockquote>
+ </div> <!-- end of bodycontent div -->
+ </body>
+</html>
diff --git a/html_css_demo/contact.html b/html_css_demo/contact.html
new file mode 100644
index 0000000..927b0a5
--- /dev/null
+++ b/html_css_demo/contact.html
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
+ <head>
+ <title>Contact Us at Bubble Under</title>
+ <!-- Stylesheets -->
+ <link rel="stylesheet" href="css/main.css" type="text/css" media="screen" />
+
+ <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+ <meta http-equiv="imagetoolbar" content="no" />
+ </head>
+ <body>
+ <div id="header">
+ <div id="sitebranding">
+ <h1>BubbleUnder.com</h1>
+ </div>
+ <div id="tagline">
+ <p>Diving club for the south-west UK - let's make a splash!</p>
+ </div>
+ </div> <!-- end of header div -->
+ <div id="navigation">
+ <ul>
+ <li><a href="index.html">Home</a></li>
+ <li><a href="about.html">About Us</a></li>
+ <li><a href="contact.html">Contact Us</a></li>
+ </ul>
+ </div> <!-- end of navigation div -->
+ <div id="bodycontent">
+ <h2>Contact Us</h2>
+ <p>To find out more, contact Club Secretary Bob Dobalina on 01793 641207 or <a href="mailto:[email protected]">email [email protected]</a>.</p>
+ </div><!-- end of bodycontent div -->
+ </body>
+</html>
diff --git a/html_css_demo/css/main.css b/html_css_demo/css/main.css
new file mode 100644
index 0000000..b11a2fd
--- /dev/null
+++ b/html_css_demo/css/main.css
@@ -0,0 +1,23 @@
+body {font-family:Verdana, Helvatica, Arial, sans-serif;
+background-color:#e2edff;
+line-height:125%;
+padding:15px;}
+p {color:Navy;
+font-size:small;}
+#tagline {font-style:italic;
+font-family:Georgia, "Times New Roman", Serif;}
+h1 {font-family:"Trebuchet MS", Helvatica, Arial, sans-serif;
+font-size:x-large;
+background-color:Navy;
+color:white;}
+ul {font-size:small;}
+h2 {color:blue;
+font-size:medium;
+font-weight:normal;
+background-color:Navy;
+color:white;}
+em {text-transform:uppercase;}
+a {font-weight:bold;}
+.fun {color:#399;
+font-family:Georgia, "Times New Roman", serif;
+font-size:.05em;}
\ No newline at end of file
diff --git a/html_css_demo/css/reset.css b/html_css_demo/css/reset.css
new file mode 100644
index 0000000..d709810
--- /dev/null
+++ b/html_css_demo/css/reset.css
@@ -0,0 +1,46 @@
+html, body, div, span, applet, object, iframe,
+h1, h2, h3, h4, h5, h6, p, blockquote, pre,
+a, abbr, acronym, address, big, cite, code,
+del, dfn, em, font, img, ins, kbd, q, s, samp,
+small, strike, strong, sub, sup, tt, var,
+dl, dt, dd, ol, ul, li,
+fieldset, form, label, legend,
+table, caption, tbody, tfoot, thead, tr, th, td {
+ margin: 0;
+ padding: 0;
+ border: 0;
+ outline: 0;
+ font-weight: inherit;
+ font-style: inherit;
+ font-size: 100%;
+ font-family: inherit;
+ vertical-align: baseline;
+}
+/* remember to define focus styles! */
+:focus {
+ outline: 0;
+}
+body {
+ line-height: 1;
+ color: black;
+ background: white;
+}
+ol, ul {
+ list-style: none;
+}
+/* tables still need 'cellspacing="0"' in the markup */
+table {
+ border-collapse: separate;
+ border-spacing: 0;
+}
+caption, th, td {
+ text-align: left;
+ font-weight: normal;
+}
+blockquote:before, blockquote:after,
+q:before, q:after {
+ content: "";
+}
+blockquote, q {
+ quotes: "" "";
+}
diff --git a/html_css_demo/img/divers-circle.jpg b/html_css_demo/img/divers-circle.jpg
new file mode 100644
index 0000000..6f5e455
Binary files /dev/null and b/html_css_demo/img/divers-circle.jpg differ
diff --git a/html_css_demo/index.html b/html_css_demo/index.html
new file mode 100644
index 0000000..e2abd54
--- /dev/null
+++ b/html_css_demo/index.html
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
+ <head>
+ <title>Bubble Under - The diving club for the south-west UK</title>
+ <!-- Stylesheets -->
+ <link rel="stylesheet" href="css/main.css" type="text/css" media="screen" />
+
+ <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+ <meta http-equiv="imagetoolbar" content="no" />
+ </head>
+ <body>
+ <div id="header">
+ <div id="sitebranding">
+ <h1>BubbleUnder.com</h1>
+ </div>
+ <div id="tagline">
+ <p>Diving club for the south-west UK - let's make a splash!</p>
+ </div>
+ </div> <!-- end of header div -->
+ <div id="navigation">
+ <ul>
+ <li><a href="index.html">Home</a></li>
+ <li><a href="about.html">About Us</a></li>
+ <li><a href="contact.html">Contact Us</a></li>
+ </ul>
+ </div> <!-- end of navigation div -->
+ <div id="bodycontent">
+ <h2>Welcome to our super-dooper Scuba site</h2>
+ <p><img src="img/divers-circle.jpg" width="200" height="162"
+ alt="A circle of divers practice their skills" /></p>
+ <p>Glad you could drop in and share some air with us! You've passed
+ your underwater navigation skills and successfully found your way to
+ the start point - or in this case, our home page.</p>
+ </div> <!-- end of bodycontent div -->
+ </body>
+</html>
|
richardc/perl-mail-thread-chronological
|
dfba0aac86b9d969c6acb43679bde08e4ebd3a69
|
fix horizontal stretching
|
diff --git a/Changes b/Changes
index b257937..4a25288 100644
--- a/Changes
+++ b/Changes
@@ -1,3 +1,8 @@
+1.22 Saturday, 7th June 2003
+ Fixed case for orphaned messages.
+ Fixed small glitch in horizontal stretching logic
+ Killed a 5.6ism that had crept in
+
1.21 Friday, 6th June 2003
First release (pulled out from Mariachis svn repository as the
Mariachi code was starting to get very large)
diff --git a/lib/Mail/Thread/Chronological.pm b/lib/Mail/Thread/Chronological.pm
index 94882e1..d9260d9 100644
--- a/lib/Mail/Thread/Chronological.pm
+++ b/lib/Mail/Thread/Chronological.pm
@@ -1,280 +1,284 @@
use strict;
package Mail::Thread::Chronological;
use Mail::Thread ();
use Date::Parse qw( str2time );
use List::Util qw( max );
-our $VERSION = '1.21';
+use vars qw/$VERSION/;
+$VERSION = '1.22';
use constant debug => 0;
=head1 NAME
Mail::Thread::Chronological - rearrange Mail::Thread::Containers into a Chronological structure
=head1 SYNOPSIS
use Mail::Thread;
use Mail::Thread::Chronological;
my $threader = Mail::Thread->new( @messages );
my $lurker = Mail::Thread::Chronological->new;
$threader->thread;
for my $thread ($threader->rootset) {
for my $row ( $lurker->arrange( $thread ) ) {
my $container = grep { ref $_ } @$row;
print join('', map { ref $_ ? '*' : $_ } @$row),
" ", $container->messageid, "\n";
}
}
=head1 DESCRIPTION
Given a Mail::Thread::Container, Mail::Thread::Chronological transforms the
tree structure into a 2-dimensional array representing the history of
a given thread in time.
The output is similar to that of the Lurker mail archiving system,
with a couple of small exceptions:
=over
=item Characters used
The grid is populated with the characters ' ' (space), '-', '+', '|',
'{', or Mail::Thread::Container objects. Lurker uses [a-g], and
differentiates T-junctions from corners for you, this module assumes
you will do that for yourself.
The characters mean:
=over
=item space
empty cell
=item -
horizontal line
=item +
T junction or corner
=item |
vertical line
=item {
vertical line crossing over a horizontal line
=back
=item Vertical stream crossing is permitted
In the original lurker crossing a path vertically is not allowed, this
results in a lot of horizontal space being used.
=back
=head1 METHODS
=head2 new
your common or garden constructor
=cut
sub new { bless {}, $_[0] }
=head2 arrange
Returns an array of arrays representing the thread tree.
=cut
# identify the co-ordinates of something
sub _cell {
my $cells = shift;
my $find = shift;
for (my $y = 0; $y < @$cells; ++$y) {
for (my $x = 0; $x < @{ $cells->[$y] }; ++$x) {
my $here = $cells->[$y][$x];
return [$y, $x] if ref $here && $here == $find;
}
}
return;
}
sub _draw_cells {
my $cells = shift;
# and again in their new state
print map { $_ % 10 } 0..20;
print "\n";
for my $row (@$cells) {
my $this;
for (@$row) {
$this = $_ if ref $_;
print ref $_ ? '*' : $_ ? $_ : ' ';
}
print "\t", $this->messageid, "\n";
}
print "\n";
}
sub arrange {
my $self = shift;
my $thread = shift;
# show them in the old order, and take a copy of the containers
# with messages on while we're at it
my @messages;
$thread->iterate_down(
sub {
my ($c, $d) = @_;
print ' ' x $d, $c->messageid, "\n" if debug;
push @messages, $c if $c->message;
} );
# cells is the 2-d representation, row, col. the first
# message will be at [0][0], it's first reply, [0][1]
my @cells;
# okay, wander them in date order
@messages = sort { $self->extract_time( $a ) <=>
$self->extract_time( $b ) } @messages;
for (my $row = 0; $row < @messages; ++$row) {
my $c = $messages[$row];
# and place them in cells
# the first one - [0][0]
unless (@cells) {
$cells[$row][0] = $c;
next;
}
# look up our parent
my $first_parent = $c->parent;
while ($first_parent && !$first_parent->message) {
$first_parent = $first_parent->parent;
}
unless ($first_parent && $first_parent->message &&
_cell(\@cells, $first_parent) ) {
# just drop it randomly to one side, since it doesn't
# have a clearly identifiable parent
my $col = (max map { scalar @$_ } @cells );
$cells[$row][$col] = $c;
+ next;
}
my $col;
my ($parent_row, $parent_col) = @{ _cell( \@cells, $first_parent ) };
if ($first_parent->child == $c) {
# if we're the first child, then we directly beneath
# them
$col = $parent_col;
}
else {
# otherwise, we have to shuffle accross into the first
# free column
# okay, figure out what the max col is
$col = my $max_col = (max map { scalar @$_ } @cells );
# would drawing the simple horizontal line cross the streams?
if (grep {
($cells[$parent_row][$_] || '') eq '|'
} $parent_col+1..$max_col) {
# we must not cross the streams (that would be bad).
# if given this tree:
# a + +
# b | |
# c |
# d
#
# e arrives, and is a reply to b, we can't just do this:
# a + +
# b - - +
# c | |
# d |
# e
#
# it's messy and confusing. instead we have to do
# extra work so we end up at
# a - + +
# b + | |
# | c |
# | d
# e
print "Crossing the streams, horizontally\n" if debug;
# we want to end up in $parent_col + 1 and
# everything in that column needs to get shuffled
# over one
$col = $parent_col + 1;
for my $r (@cells[0 .. $row - 1]) {
next if @$r < $col;
my $here = $r->[$col] || '';
- splice(@$r, $col, 0, $here eq '+' ? '-' : undef);
+ # what to splice in
+ my $splice = $here =~/[+\-]/ ? '-' : ' ';
+ splice(@$r, $col, 0, $splice);
}
$col = $parent_col + 1;
}
# the path is now clear, add the line in
for ($parent_col..$col) {
$cells[$parent_row][$_] ||= '-';
}
$cells[$parent_row][$col] = '+';
}
# place the message
$cells[$row][$col] = $c;
# link with vertical dashes
for ($parent_row+1..$row-1) {
$cells[$_][$col] = ($cells[$_][$col] || '') eq '-' ? '{' : '|';
}
_draw_cells(\@cells) if debug;
}
# pad the rows with spaces
my $maxcol = max map { scalar @$_ } @cells;
for my $row (@cells) {
$row->[$_] ||= ' ' for (0..$maxcol-1);
}
return @cells;
}
=head2 extract_time( $container )
Extracts the time from a Mail::Thread::Container, returned as epoch
seconds used to decide the order of adding messages to the rows.
=cut
sub extract_time {
my $self = shift;
my $container = shift;
my $date = Mail::Thread->_get_hdr( $container->message, 'date' );
return str2time( $date );
}
1;
__END__
=head1 AUTHOR
Richard Clamp <[email protected]>
=head1 SEE ALSO
L<Lurker|http://lurker.sourceforge.net/>, the application that seems
to have originated this form of time-based thread display.
L<Mail::Thread>, L<Mariachi>
=cut
diff --git a/t/lurker.t b/t/lurker.t
index 2d873e0..4c58f8f 100644
--- a/t/lurker.t
+++ b/t/lurker.t
@@ -1,6 +1,13 @@
#!perl -w
use strict;
use Test::More tests => 1;
use_ok('Mail::Thread::Chronological');
# TODO real live testing
+
+eval "use Test::Differences";
+# a beefed up is_deeply
+sub deeply ($$;$) {
+ goto &eq_or_diff if defined &eq_or_diff;
+ goto &is_deeply;
+}
|
richardc/perl-mail-thread-chronological
|
cca029d335dc9356a2d668c5d376a86a419314c9
|
I guess this is a release
|
diff --git a/Changes b/Changes
new file mode 100644
index 0000000..b257937
--- /dev/null
+++ b/Changes
@@ -0,0 +1,3 @@
+1.21 Friday, 6th June 2003
+ First release (pulled out from Mariachis svn repository as the
+ Mariachi code was starting to get very large)
diff --git a/MANIFEST b/MANIFEST
index c393053..40a30ca 100644
--- a/MANIFEST
+++ b/MANIFEST
@@ -1,7 +1,8 @@
MANIFEST
-lib/Mail/Thread/Lurker.pm
+Changes
+lib/Mail/Thread/Chronological.pm
t/lurker.t
Build.PL
Makefile.PL
META.yml
SIGNATURE
|
richardc/perl-mail-thread-chronological
|
bf8dd8f1e5ff0bce2d408f5dd8970b793f4811ff
|
grand rename
|
diff --git a/Build.PL b/Build.PL
index b5ccff5..9e39bb6 100644
--- a/Build.PL
+++ b/Build.PL
@@ -1,18 +1,18 @@
use strict;
use Module::Build;
Module::Build
- ->new( module_name => "Mail::Thread::Lurker",
+ ->new( module_name => "Mail::Thread::Chronological",
license => 'perl',
requires => {
'Mail::Thread' => 0,
'Date::Parse' => 0,
'List::Util' => 0,
'Test::More' => 0,
},
create_makefile_pl => 'traditional',
sign => 1,
)
->create_build_script;
diff --git a/lib/Mail/Thread/Lurker.pm b/lib/Mail/Thread/Chronological.pm
similarity index 95%
rename from lib/Mail/Thread/Lurker.pm
rename to lib/Mail/Thread/Chronological.pm
index 8ebda18..94882e1 100644
--- a/lib/Mail/Thread/Lurker.pm
+++ b/lib/Mail/Thread/Chronological.pm
@@ -1,280 +1,280 @@
use strict;
-package Mail::Thread::Lurker;
+package Mail::Thread::Chronological;
use Mail::Thread ();
use Date::Parse qw( str2time );
use List::Util qw( max );
our $VERSION = '1.21';
use constant debug => 0;
=head1 NAME
-Mail::Thread::Lurker - rearrange Mail::Thread::Containers into a Lurker-like structure
+Mail::Thread::Chronological - rearrange Mail::Thread::Containers into a Chronological structure
=head1 SYNOPSIS
use Mail::Thread;
- use Mail::Thread::Lurker;
+ use Mail::Thread::Chronological;
my $threader = Mail::Thread->new( @messages );
- my $lurker = Mail::Thread::Lurker->new;
+ my $lurker = Mail::Thread::Chronological->new;
$threader->thread;
for my $thread ($threader->rootset) {
for my $row ( $lurker->arrange( $thread ) ) {
my $container = grep { ref $_ } @$row;
print join('', map { ref $_ ? '*' : $_ } @$row),
" ", $container->messageid, "\n";
}
}
=head1 DESCRIPTION
-Given a Mail::Thread::Container, Mail::Thread::Lurker transforms the
+Given a Mail::Thread::Container, Mail::Thread::Chronological transforms the
tree structure into a 2-dimensional array representing the history of
a given thread in time.
The output is similar to that of the Lurker mail archiving system,
with a couple of small exceptions:
=over
=item Characters used
The grid is populated with the characters ' ' (space), '-', '+', '|',
'{', or Mail::Thread::Container objects. Lurker uses [a-g], and
differentiates T-junctions from corners for you, this module assumes
you will do that for yourself.
The characters mean:
=over
=item space
empty cell
=item -
horizontal line
=item +
T junction or corner
=item |
vertical line
=item {
vertical line crossing over a horizontal line
=back
=item Vertical stream crossing is permitted
In the original lurker crossing a path vertically is not allowed, this
results in a lot of horizontal space being used.
=back
=head1 METHODS
=head2 new
your common or garden constructor
=cut
sub new { bless {}, $_[0] }
=head2 arrange
Returns an array of arrays representing the thread tree.
=cut
# identify the co-ordinates of something
sub _cell {
my $cells = shift;
my $find = shift;
for (my $y = 0; $y < @$cells; ++$y) {
for (my $x = 0; $x < @{ $cells->[$y] }; ++$x) {
my $here = $cells->[$y][$x];
return [$y, $x] if ref $here && $here == $find;
}
}
return;
}
sub _draw_cells {
my $cells = shift;
# and again in their new state
print map { $_ % 10 } 0..20;
print "\n";
for my $row (@$cells) {
my $this;
for (@$row) {
$this = $_ if ref $_;
print ref $_ ? '*' : $_ ? $_ : ' ';
}
print "\t", $this->messageid, "\n";
}
print "\n";
}
sub arrange {
my $self = shift;
my $thread = shift;
# show them in the old order, and take a copy of the containers
# with messages on while we're at it
my @messages;
$thread->iterate_down(
sub {
my ($c, $d) = @_;
print ' ' x $d, $c->messageid, "\n" if debug;
push @messages, $c if $c->message;
} );
# cells is the 2-d representation, row, col. the first
# message will be at [0][0], it's first reply, [0][1]
my @cells;
# okay, wander them in date order
@messages = sort { $self->extract_time( $a ) <=>
$self->extract_time( $b ) } @messages;
for (my $row = 0; $row < @messages; ++$row) {
my $c = $messages[$row];
# and place them in cells
# the first one - [0][0]
unless (@cells) {
$cells[$row][0] = $c;
next;
}
# look up our parent
my $first_parent = $c->parent;
while ($first_parent && !$first_parent->message) {
$first_parent = $first_parent->parent;
}
unless ($first_parent && $first_parent->message &&
_cell(\@cells, $first_parent) ) {
# just drop it randomly to one side, since it doesn't
# have a clearly identifiable parent
my $col = (max map { scalar @$_ } @cells );
$cells[$row][$col] = $c;
}
my $col;
my ($parent_row, $parent_col) = @{ _cell( \@cells, $first_parent ) };
if ($first_parent->child == $c) {
# if we're the first child, then we directly beneath
# them
$col = $parent_col;
}
else {
# otherwise, we have to shuffle accross into the first
# free column
# okay, figure out what the max col is
$col = my $max_col = (max map { scalar @$_ } @cells );
# would drawing the simple horizontal line cross the streams?
if (grep {
($cells[$parent_row][$_] || '') eq '|'
} $parent_col+1..$max_col) {
# we must not cross the streams (that would be bad).
# if given this tree:
# a + +
# b | |
# c |
# d
#
# e arrives, and is a reply to b, we can't just do this:
# a + +
# b - - +
# c | |
# d |
# e
#
# it's messy and confusing. instead we have to do
# extra work so we end up at
# a - + +
# b + | |
# | c |
# | d
# e
print "Crossing the streams, horizontally\n" if debug;
# we want to end up in $parent_col + 1 and
# everything in that column needs to get shuffled
# over one
$col = $parent_col + 1;
for my $r (@cells[0 .. $row - 1]) {
next if @$r < $col;
my $here = $r->[$col] || '';
splice(@$r, $col, 0, $here eq '+' ? '-' : undef);
}
$col = $parent_col + 1;
}
# the path is now clear, add the line in
for ($parent_col..$col) {
$cells[$parent_row][$_] ||= '-';
}
$cells[$parent_row][$col] = '+';
}
# place the message
$cells[$row][$col] = $c;
# link with vertical dashes
for ($parent_row+1..$row-1) {
$cells[$_][$col] = ($cells[$_][$col] || '') eq '-' ? '{' : '|';
}
_draw_cells(\@cells) if debug;
}
# pad the rows with spaces
my $maxcol = max map { scalar @$_ } @cells;
for my $row (@cells) {
$row->[$_] ||= ' ' for (0..$maxcol-1);
}
return @cells;
}
=head2 extract_time( $container )
Extracts the time from a Mail::Thread::Container, returned as epoch
seconds used to decide the order of adding messages to the rows.
=cut
sub extract_time {
my $self = shift;
my $container = shift;
my $date = Mail::Thread->_get_hdr( $container->message, 'date' );
return str2time( $date );
}
1;
__END__
=head1 AUTHOR
Richard Clamp <[email protected]>
=head1 SEE ALSO
L<Lurker|http://lurker.sourceforge.net/>, the application that seems
to have originated this form of time-based thread display.
L<Mail::Thread>, L<Mariachi>
=cut
diff --git a/t/lurker.t b/t/lurker.t
index cdd7be6..2d873e0 100644
--- a/t/lurker.t
+++ b/t/lurker.t
@@ -1,6 +1,6 @@
#!perl -w
use strict;
use Test::More tests => 1;
-use_ok('Mail::Thread::Lurker');
+use_ok('Mail::Thread::Chronological');
# TODO real live testing
|
richardc/perl-mail-thread-chronological
|
e7d9316c5b9724e163f47fbbeeb1b82813e85e1c
|
rename
|
diff --git a/Build.PL b/Build.PL
new file mode 100644
index 0000000..b5ccff5
--- /dev/null
+++ b/Build.PL
@@ -0,0 +1,18 @@
+use strict;
+use Module::Build;
+
+Module::Build
+ ->new( module_name => "Mail::Thread::Lurker",
+ license => 'perl',
+ requires => {
+ 'Mail::Thread' => 0,
+ 'Date::Parse' => 0,
+ 'List::Util' => 0,
+ 'Test::More' => 0,
+ },
+ create_makefile_pl => 'traditional',
+ sign => 1,
+ )
+ ->create_build_script;
+
+
diff --git a/MANIFEST b/MANIFEST
new file mode 100644
index 0000000..c393053
--- /dev/null
+++ b/MANIFEST
@@ -0,0 +1,7 @@
+MANIFEST
+lib/Mail/Thread/Lurker.pm
+t/lurker.t
+Build.PL
+Makefile.PL
+META.yml
+SIGNATURE
diff --git a/MANIFEST.SKIP b/MANIFEST.SKIP
new file mode 100644
index 0000000..97f159b
--- /dev/null
+++ b/MANIFEST.SKIP
@@ -0,0 +1,7 @@
+blib
+_build
+Makefile
+Build
+~$
+MANIFEST.SKIP
+\.svn
diff --git a/lib/Mail/Thread/Lurker.pm b/lib/Mail/Thread/Lurker.pm
new file mode 100644
index 0000000..8ebda18
--- /dev/null
+++ b/lib/Mail/Thread/Lurker.pm
@@ -0,0 +1,280 @@
+use strict;
+package Mail::Thread::Lurker;
+use Mail::Thread ();
+use Date::Parse qw( str2time );
+use List::Util qw( max );
+our $VERSION = '1.21';
+
+use constant debug => 0;
+
+=head1 NAME
+
+Mail::Thread::Lurker - rearrange Mail::Thread::Containers into a Lurker-like structure
+
+=head1 SYNOPSIS
+
+ use Mail::Thread;
+ use Mail::Thread::Lurker;
+
+ my $threader = Mail::Thread->new( @messages );
+ my $lurker = Mail::Thread::Lurker->new;
+
+ $threader->thread;
+
+ for my $thread ($threader->rootset) {
+ for my $row ( $lurker->arrange( $thread ) ) {
+ my $container = grep { ref $_ } @$row;
+ print join('', map { ref $_ ? '*' : $_ } @$row),
+ " ", $container->messageid, "\n";
+ }
+ }
+
+=head1 DESCRIPTION
+
+Given a Mail::Thread::Container, Mail::Thread::Lurker transforms the
+tree structure into a 2-dimensional array representing the history of
+a given thread in time.
+
+The output is similar to that of the Lurker mail archiving system,
+with a couple of small exceptions:
+
+=over
+
+=item Characters used
+
+The grid is populated with the characters ' ' (space), '-', '+', '|',
+'{', or Mail::Thread::Container objects. Lurker uses [a-g], and
+differentiates T-junctions from corners for you, this module assumes
+you will do that for yourself.
+
+The characters mean:
+
+=over
+
+=item space
+
+empty cell
+
+=item -
+
+horizontal line
+
+=item +
+
+T junction or corner
+
+=item |
+
+vertical line
+
+=item {
+
+vertical line crossing over a horizontal line
+
+=back
+
+=item Vertical stream crossing is permitted
+
+In the original lurker crossing a path vertically is not allowed, this
+results in a lot of horizontal space being used.
+
+=back
+
+=head1 METHODS
+
+=head2 new
+
+your common or garden constructor
+
+=cut
+
+sub new { bless {}, $_[0] }
+
+=head2 arrange
+
+Returns an array of arrays representing the thread tree.
+
+=cut
+
+
+# identify the co-ordinates of something
+sub _cell {
+ my $cells = shift;
+ my $find = shift;
+ for (my $y = 0; $y < @$cells; ++$y) {
+ for (my $x = 0; $x < @{ $cells->[$y] }; ++$x) {
+ my $here = $cells->[$y][$x];
+ return [$y, $x] if ref $here && $here == $find;
+ }
+ }
+ return;
+}
+
+sub _draw_cells {
+ my $cells = shift;
+ # and again in their new state
+ print map { $_ % 10 } 0..20;
+ print "\n";
+ for my $row (@$cells) {
+ my $this;
+ for (@$row) {
+ $this = $_ if ref $_;
+ print ref $_ ? '*' : $_ ? $_ : ' ';
+ }
+ print "\t", $this->messageid, "\n";
+ }
+ print "\n";
+}
+
+sub arrange {
+ my $self = shift;
+ my $thread = shift;
+
+ # show them in the old order, and take a copy of the containers
+ # with messages on while we're at it
+ my @messages;
+ $thread->iterate_down(
+ sub {
+ my ($c, $d) = @_;
+ print ' ' x $d, $c->messageid, "\n" if debug;
+ push @messages, $c if $c->message;
+ } );
+
+ # cells is the 2-d representation, row, col. the first
+ # message will be at [0][0], it's first reply, [0][1]
+ my @cells;
+
+ # okay, wander them in date order
+ @messages = sort { $self->extract_time( $a ) <=>
+ $self->extract_time( $b ) } @messages;
+ for (my $row = 0; $row < @messages; ++$row) {
+ my $c = $messages[$row];
+ # and place them in cells
+
+ # the first one - [0][0]
+ unless (@cells) {
+ $cells[$row][0] = $c;
+ next;
+ }
+
+ # look up our parent
+ my $first_parent = $c->parent;
+ while ($first_parent && !$first_parent->message) {
+ $first_parent = $first_parent->parent;
+ }
+
+ unless ($first_parent && $first_parent->message &&
+ _cell(\@cells, $first_parent) ) {
+ # just drop it randomly to one side, since it doesn't
+ # have a clearly identifiable parent
+ my $col = (max map { scalar @$_ } @cells );
+ $cells[$row][$col] = $c;
+ }
+ my $col;
+ my ($parent_row, $parent_col) = @{ _cell( \@cells, $first_parent ) };
+ if ($first_parent->child == $c) {
+ # if we're the first child, then we directly beneath
+ # them
+ $col = $parent_col;
+ }
+ else {
+ # otherwise, we have to shuffle accross into the first
+ # free column
+
+ # okay, figure out what the max col is
+ $col = my $max_col = (max map { scalar @$_ } @cells );
+
+ # would drawing the simple horizontal line cross the streams?
+ if (grep {
+ ($cells[$parent_row][$_] || '') eq '|'
+ } $parent_col+1..$max_col) {
+ # we must not cross the streams (that would be bad).
+ # if given this tree:
+ # a + +
+ # b | |
+ # c |
+ # d
+ #
+ # e arrives, and is a reply to b, we can't just do this:
+ # a + +
+ # b - - +
+ # c | |
+ # d |
+ # e
+ #
+ # it's messy and confusing. instead we have to do
+ # extra work so we end up at
+ # a - + +
+ # b + | |
+ # | c |
+ # | d
+ # e
+
+ print "Crossing the streams, horizontally\n" if debug;
+ # we want to end up in $parent_col + 1 and
+ # everything in that column needs to get shuffled
+ # over one
+ $col = $parent_col + 1;
+ for my $r (@cells[0 .. $row - 1]) {
+ next if @$r < $col;
+ my $here = $r->[$col] || '';
+ splice(@$r, $col, 0, $here eq '+' ? '-' : undef);
+ }
+ $col = $parent_col + 1;
+ }
+
+ # the path is now clear, add the line in
+ for ($parent_col..$col) {
+ $cells[$parent_row][$_] ||= '-';
+ }
+ $cells[$parent_row][$col] = '+';
+ }
+
+ # place the message
+ $cells[$row][$col] = $c;
+ # link with vertical dashes
+ for ($parent_row+1..$row-1) {
+ $cells[$_][$col] = ($cells[$_][$col] || '') eq '-' ? '{' : '|';
+ }
+ _draw_cells(\@cells) if debug;
+ }
+
+ # pad the rows with spaces
+ my $maxcol = max map { scalar @$_ } @cells;
+ for my $row (@cells) {
+ $row->[$_] ||= ' ' for (0..$maxcol-1);
+ }
+
+ return @cells;
+}
+
+=head2 extract_time( $container )
+
+Extracts the time from a Mail::Thread::Container, returned as epoch
+seconds used to decide the order of adding messages to the rows.
+
+=cut
+
+sub extract_time {
+ my $self = shift;
+ my $container = shift;
+
+ my $date = Mail::Thread->_get_hdr( $container->message, 'date' );
+ return str2time( $date );
+}
+
+1;
+__END__
+
+=head1 AUTHOR
+
+Richard Clamp <[email protected]>
+
+=head1 SEE ALSO
+
+L<Lurker|http://lurker.sourceforge.net/>, the application that seems
+to have originated this form of time-based thread display.
+
+L<Mail::Thread>, L<Mariachi>
+
+=cut
diff --git a/t/lurker.t b/t/lurker.t
new file mode 100644
index 0000000..cdd7be6
--- /dev/null
+++ b/t/lurker.t
@@ -0,0 +1,6 @@
+#!perl -w
+use strict;
+use Test::More tests => 1;
+
+use_ok('Mail::Thread::Lurker');
+# TODO real live testing
|
mccolin/axtags
|
67179c95ee8f9d72c1423ff7d77dee5cb963079f
|
some depth to README; tweak version file inclusion in gemspec
|
diff --git a/README.rdoc b/README.rdoc
index 92312b4..4144fc9 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -1,9 +1,73 @@
+= Ax Tags
-== Ax Tags
+A flexible, extensible custom tag and template-parsing framework built around the
+{Radius templating framework}[https://github.com/jlong/radius]. A lighter-weight
+alternative to systems like Liquid with XML-style input and output.
-Flexible, extensible custom tag and template-parsing framework built around the
-{Radius templating framework}[https://github.com/jlong/radius].
+With AxTags, you create a library of available tags, define their functionality
+against your application (standalone, rails, sinatra, or any other) and begin parsing
+documents containing your custom markup with ease.
+
+
+== Installation
+
+Get up and running fast:
+
+ gem install axtags
+
+Hook up your Gemfile powered applications:
+
+ gem "axtags"
+
+
+== Usage
+
+Getting going with AxTags involves creating a library of tags and then passing documents
+containing your tags through the +parse+ method.
+
+
+=== Build a Tag Library
+
+Your custom TagLibrary class provides the direct interface for both defining tags, passing
+local variables to the parser, and managing the parsing process. To get started, simply
+create your library as a descendant of the +TagLibrary+ class:
+
+ class MyTagLibrary < AxTags::TagLibrary
+ tag "myanchor" do |t|
+ %{<a href="http://awesometown.com/">I am Awesome!</a>}
+ end
+ end
+
+You can see from the example, above, that we've created a tag +myanchor+ which expands to
+an HTML anchor tag with a link to awesometown.com. You can see how this works by attempting
+to parse a document containing your new tag:
+
+ MyTagLibrary.parse("Here is an awesome link: <ax:myanchor/>")
+ => "Here is an awesome link: <a href=\"http://awesometown.com/\">I am awesome!</a>"
+
+
+It's possible to add tags at runtime, as well, by working with the Radius context directly.
+You can accomplish that like so:
+
+ MyTagLibrary.build_tags do |context|
+ context.define_tag("foo") do |t|
+ %{<span class="foo">Bar</span>}
+ end
+ end
+
+This example adds support for the "<ax:foo/>" tag, which would expand on parsing to
+"<span class=\"foo\">Bar</span>".
+
+
+=== Advanced Tags
+
+Tags can be nested, access XML-style attributes, and pass along scope and context to text nodes
+within tags.
+
+Tags can provide looping or repetitive behavior, as well.
+
+_Documentation still pending..._
Copyright (C) 2013 Awexome Labs, LLC
diff --git a/axtags.gemspec b/axtags.gemspec
index d2fce07..538b9b0 100644
--- a/axtags.gemspec
+++ b/axtags.gemspec
@@ -1,58 +1,63 @@
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "axtags"
s.version = "0.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Awexome Labs"]
s.date = "2013-01-16"
s.description = "Flexible, extensible custom tag and template framework with safe execution and HTML-like style. Wraps a cleaner API around the Radius templating framework."
s.email = "[email protected]"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
+ "Gemfile",
+ "Gemfile.lock",
+ "LICENSE.txt",
"README.rdoc",
+ "Rakefile",
"VERSION",
+ "axtags.gemspec",
"lib/axtags.rb",
"lib/axtags/ax_context.rb",
"lib/axtags/ax_parser.rb",
"lib/axtags/tag_library.rb",
- "lib/version.rb"
+ "spec/axtags_spec.rb"
]
s.homepage = "http://github.com/mccolin/axtags"
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.24"
s.summary = "Flexible, extensible custom tag and template framework with safe execution and HTML-like style"
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<radius>, ["~> 0.7.3"])
s.add_development_dependency(%q<bundler>, ["~> 1.2.1"])
s.add_development_dependency(%q<jeweler>, ["~> 1.8.4"])
s.add_development_dependency(%q<rdoc>, ["~> 3.12"])
s.add_development_dependency(%q<rspec>, [">= 2.11.0"])
else
s.add_dependency(%q<radius>, ["~> 0.7.3"])
s.add_dependency(%q<bundler>, ["~> 1.2.1"])
s.add_dependency(%q<jeweler>, ["~> 1.8.4"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<rspec>, [">= 2.11.0"])
end
else
s.add_dependency(%q<radius>, ["~> 0.7.3"])
s.add_dependency(%q<bundler>, ["~> 1.2.1"])
s.add_dependency(%q<jeweler>, ["~> 1.8.4"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<rspec>, [">= 2.11.0"])
end
end
|
mccolin/axtags
|
34b7202754f5ddc88b642de5b3d5df7780eaa918
|
stub out a spec
|
diff --git a/lib/axtags.rb b/lib/axtags.rb
index 8694b48..73f1022 100644
--- a/lib/axtags.rb
+++ b/lib/axtags.rb
@@ -1,19 +1,19 @@
# AWEXOME LABS
# AxTags
#
# A flexible, extensible custom tag and template framework with safe execution of user
# submitting templating.
require "radius"
-require "axtags/ax_content"
+require "axtags/ax_context"
require "axtags/ax_parser"
require "axtags/tag_library"
module AxTags
def self.version
Gem.loaded_specs["axtags"].version.to_s
end
end # AxTags
diff --git a/spec/axtags_spec.rb b/spec/axtags_spec.rb
new file mode 100644
index 0000000..0e3a547
--- /dev/null
+++ b/spec/axtags_spec.rb
@@ -0,0 +1,59 @@
+# AWEXOME LABS
+# AxTags Test Suite
+
+$LOAD_PATH.unshift(File.dirname(__FILE__))
+$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib"))
+
+require "rubygems"
+require "bundler"
+Bundler.setup(:default, :development)
+
+require "axtags"
+require "rspec"
+require "rspec/autorun"
+
+root = File.expand_path(File.join(File.dirname(__FILE__), ".."))
+
+RSpec.configure do |config|
+end
+
+
+# Create a testable tag library:
+class TestLibrary < AxTags::TagLibrary
+ tag "anchor" do |t|
+ %{<a class="awesome_anchor" href="http://awesometown.com/">I am Awesome!</a>}
+ end
+end
+
+# Test AxTags parsing and management:
+describe "axtags" do
+
+ before(:each) do
+ end
+
+ after(:each) do
+ end
+
+
+ it "defines simple tags" do
+ end
+
+ it "defines content tags" do
+ end
+
+ it "defines nested tags" do
+ end
+
+ it "properly renders simple tag content" do
+ tmpl = %{<ax:anchor/>}
+ TestLibrary.parse(tmpl) == %{<a class="awesome_anchor" href="http://awesometown.com/">I am Awesome!</a>}
+ end
+
+ it "properly renders content tags" do
+ end
+
+ it "properly renders nested tag content" do
+ end
+
+
+end # axtags
|
mccolin/axtags
|
a9ebcbf377543c8434b9f5f213ab465068073205
|
gitignore
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a9c888f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,49 @@
+# rcov generated
+coverage
+coverage.data
+
+# rdoc generated
+rdoc
+
+# yard generated
+doc
+.yardoc
+
+# bundler
+.bundle
+
+# jeweler generated
+pkg
+
+# Have editor/IDE/OS specific files you need to ignore? Consider using a global gitignore:
+#
+# * Create a file at ~/.gitignore
+# * Include files you want ignored
+# * Run: git config --global core.excludesfile ~/.gitignore
+#
+# After doing this, these files will be ignored in all your git projects,
+# saving you from having to 'pollute' every project you touch with them
+#
+# Not sure what to needs to be ignored for particular editors/OSes? Here's some ideas to get you started. (Remember, remove the leading # of the line)
+#
+# For MacOS:
+#
+#.DS_Store
+
+# For TextMate
+#*.tmproj
+#tmtags
+
+# For emacs:
+#*~
+#\#*
+#.\#*
+
+# For vim:
+#*.swp
+
+# For redcar:
+#.redcar
+
+# For rubinius:
+#*.rbc
|
mccolin/axtags
|
de11b0bb712f4f8a3cd0e6652ec7186e726cc588
|
more gem-ification
|
diff --git a/Gemfile b/Gemfile
new file mode 100644
index 0000000..0522441
--- /dev/null
+++ b/Gemfile
@@ -0,0 +1,17 @@
+# AWEXOME LABS AX TAGS
+# Gemfile
+
+source "http://rubygems.org"
+
+# Runtime dependencies:
+
+# The gem builds a different API to Radius:
+gem "radius", "~> 0.7.3"
+
+# Development dependencies:
+group :development do
+ gem "bundler", "~> 1.2.1"
+ gem "jeweler", "~> 1.8.4"
+ gem "rdoc", "~> 3.12"
+ gem "rspec", ">= 2.11.0"
+end
diff --git a/Gemfile.lock b/Gemfile.lock
new file mode 100644
index 0000000..d5ec6be
--- /dev/null
+++ b/Gemfile.lock
@@ -0,0 +1,33 @@
+GEM
+ remote: http://rubygems.org/
+ specs:
+ diff-lcs (1.1.3)
+ git (1.2.5)
+ jeweler (1.8.4)
+ bundler (~> 1.0)
+ git (>= 1.2.5)
+ rake
+ rdoc
+ json (1.7.5)
+ radius (0.7.3)
+ rake (10.0.3)
+ rdoc (3.12)
+ json (~> 1.4)
+ rspec (2.11.0)
+ rspec-core (~> 2.11.0)
+ rspec-expectations (~> 2.11.0)
+ rspec-mocks (~> 2.11.0)
+ rspec-core (2.11.1)
+ rspec-expectations (2.11.3)
+ diff-lcs (~> 1.1.3)
+ rspec-mocks (2.11.2)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ bundler (~> 1.2.1)
+ jeweler (~> 1.8.4)
+ radius (~> 0.7.3)
+ rdoc (~> 3.12)
+ rspec (>= 2.11.0)
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 0000000..03b5aee
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,20 @@
+Copyright (c) 2013 Awexome Labs, LLC
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.rdoc b/README.rdoc
index 9b7b172..92312b4 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -1,5 +1,9 @@
-==AX TAGS
-Flexible, extensible custom tag and template-parsing framework built around the Radius templating framework.
+== Ax Tags
-Copyright (c)2010
+Flexible, extensible custom tag and template-parsing framework built around the
+{Radius templating framework}[https://github.com/jlong/radius].
+
+
+
+Copyright (C) 2013 Awexome Labs, LLC
diff --git a/Rakefile b/Rakefile
new file mode 100644
index 0000000..3446f38
--- /dev/null
+++ b/Rakefile
@@ -0,0 +1,65 @@
+# encoding: utf-8
+
+require "rubygems"
+require "bundler"
+begin
+ Bundler.setup(:default, :development)
+rescue Bundler::BundlerError => e
+ $stderr.puts e.message
+ $stderr.puts "Run `bundle install` to install missing gems"
+ exit e.status_code
+end
+require "rake"
+
+require "jeweler"
+Jeweler::Tasks.new do |gem|
+ # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
+ gem.name = "axtags"
+ gem.homepage = "http://github.com/mccolin/axtags"
+ gem.license = "MIT"
+ gem.summary = %Q{Flexible, extensible custom tag and template framework with safe execution and HTML-like style}
+ gem.description = %Q{Flexible, extensible custom tag and template framework with safe execution and HTML-like style. Wraps a cleaner API around the Radius templating framework.}
+ gem.email = "[email protected]"
+ gem.authors = ["Awexome Labs"]
+ # dependencies defined in Gemfile
+end
+Jeweler::RubygemsDotOrgTasks.new
+
+require "rspec/core"
+require "rspec/core/rake_task"
+RSpec::Core::RakeTask.new(:spec) do |spec|
+end
+
+RSpec::Core::RakeTask.new(:rcov) do |spec|
+ spec.rcov = true
+end
+
+task :default => :spec
+
+# require "rake/testtask"
+# Rake::TestTask.new(:test) do |test|
+# test.libs << "lib" << "test"
+# test.pattern = "test/**/test_*.rb"
+# test.verbose = true
+# end
+
+# require "rcov/rcovtask"
+# Rcov::RcovTask.new do |test|
+# test.libs << "test"
+# test.pattern = "test/**/test_*.rb"
+# test.verbose = true
+# test.rcov_opts << "--exclude "gems/*""
+# end
+
+# task :default => :test
+
+require "rdoc/task"
+Rake::RDocTask.new do |rdoc|
+ version = File.exist?("VERSION") ? File.read("VERSION") : ""
+
+ rdoc.rdoc_dir = "rdoc"
+ rdoc.title = "AxTags #{version}"
+ rdoc.rdoc_files.include("README*")
+ rdoc.rdoc_files.include("LICENSE*")
+ rdoc.rdoc_files.include("lib/**/*.rb")
+end
diff --git a/VERSION b/VERSION
index bd52db8..6c6aa7c 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.0.0
\ No newline at end of file
+0.1.0
\ No newline at end of file
diff --git a/axtags.gemspec b/axtags.gemspec
new file mode 100644
index 0000000..d2fce07
--- /dev/null
+++ b/axtags.gemspec
@@ -0,0 +1,58 @@
+# Generated by jeweler
+# DO NOT EDIT THIS FILE DIRECTLY
+# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
+# -*- encoding: utf-8 -*-
+
+Gem::Specification.new do |s|
+ s.name = "axtags"
+ s.version = "0.1.0"
+
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
+ s.authors = ["Awexome Labs"]
+ s.date = "2013-01-16"
+ s.description = "Flexible, extensible custom tag and template framework with safe execution and HTML-like style. Wraps a cleaner API around the Radius templating framework."
+ s.email = "[email protected]"
+ s.extra_rdoc_files = [
+ "LICENSE.txt",
+ "README.rdoc"
+ ]
+ s.files = [
+ "README.rdoc",
+ "VERSION",
+ "lib/axtags.rb",
+ "lib/axtags/ax_context.rb",
+ "lib/axtags/ax_parser.rb",
+ "lib/axtags/tag_library.rb",
+ "lib/version.rb"
+ ]
+ s.homepage = "http://github.com/mccolin/axtags"
+ s.licenses = ["MIT"]
+ s.require_paths = ["lib"]
+ s.rubygems_version = "1.8.24"
+ s.summary = "Flexible, extensible custom tag and template framework with safe execution and HTML-like style"
+
+ if s.respond_to? :specification_version then
+ s.specification_version = 3
+
+ if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
+ s.add_runtime_dependency(%q<radius>, ["~> 0.7.3"])
+ s.add_development_dependency(%q<bundler>, ["~> 1.2.1"])
+ s.add_development_dependency(%q<jeweler>, ["~> 1.8.4"])
+ s.add_development_dependency(%q<rdoc>, ["~> 3.12"])
+ s.add_development_dependency(%q<rspec>, [">= 2.11.0"])
+ else
+ s.add_dependency(%q<radius>, ["~> 0.7.3"])
+ s.add_dependency(%q<bundler>, ["~> 1.2.1"])
+ s.add_dependency(%q<jeweler>, ["~> 1.8.4"])
+ s.add_dependency(%q<rdoc>, ["~> 3.12"])
+ s.add_dependency(%q<rspec>, [">= 2.11.0"])
+ end
+ else
+ s.add_dependency(%q<radius>, ["~> 0.7.3"])
+ s.add_dependency(%q<bundler>, ["~> 1.2.1"])
+ s.add_dependency(%q<jeweler>, ["~> 1.8.4"])
+ s.add_dependency(%q<rdoc>, ["~> 3.12"])
+ s.add_dependency(%q<rspec>, [">= 2.11.0"])
+ end
+end
+
diff --git a/lib/axtags.rb b/lib/axtags.rb
index a38a52e..8694b48 100644
--- a/lib/axtags.rb
+++ b/lib/axtags.rb
@@ -1,13 +1,19 @@
-# AX TAGS
-# Flexible, extensible custom tag and template-parsing framework built
-# around the Radius templating framework.
+# AWEXOME LABS
+# AxTags
#
+# A flexible, extensible custom tag and template framework with safe execution of user
+# submitting templating.
-# The library composites functionality from Radius:
require "radius"
-# And offers specialized context, parser, and library features:
-require "ax_context"
-require "ax_parser"
-require "tag_library"
+require "axtags/ax_content"
+require "axtags/ax_parser"
+require "axtags/tag_library"
+module AxTags
+
+ def self.version
+ Gem.loaded_specs["axtags"].version.to_s
+ end
+
+end # AxTags
diff --git a/lib/axtags/ax_context.rb b/lib/axtags/ax_context.rb
index e6dcf4a..c538f95 100644
--- a/lib/axtags/ax_context.rb
+++ b/lib/axtags/ax_context.rb
@@ -1,24 +1,24 @@
# AX TAGS
# Flexible, extensible custom tag and template-parsing framework built
# around the Radius templating framework.
#
# AxContext - A context contains a dictionary of tags that can be used
# in template parsing. Context objects are passed to parsers alongside
# templates to enable parsing.
#
module AxTags
class AxContext < Radius::Context
-
- # A catch-call for any missing tags:
+
+ # A catch-call for handling an unsupported tag included in a template:
def tag_missing(tag, attr, &block)
- "<strong>ERROR: Undefined tag `#{tag}'#{!attr.empty? ? " with attributes #{attr.inspect}" : ""}</strong>"
+ %{<span class="error parse-error ui-state-error">Tag "#{tag}" is unknown. Attributes provided: #{attr.inspect}</span>}
end
-
+
# A method in-reserve for generic error-reporting to the end-user:
def tag_error(tag, error_text)
- "<strong>ERROR: While rendering tag `#{tag}'; #{error_text}</strong>"
+ %{<span class="error parse-error ui-state-error">Error in rendering tag \"#{tag}\"; #{error_text}</span>}
end
-
+
end
end
diff --git a/lib/axtags/ax_parser.rb b/lib/axtags/ax_parser.rb
index ea6f2e7..2d61d43 100644
--- a/lib/axtags/ax_parser.rb
+++ b/lib/axtags/ax_parser.rb
@@ -1,14 +1,13 @@
# AX TAGS
# Flexible, extensible custom tag and template-parsing framework built
# around the Radius templating framework.
#
# AxParser - Does the heavy lifting of sifting tags out of template
# documents and leverages the contents of a context object to build an
# output result document
#
module AxTags
class AxParser < Radius::Parser
-
- end
-end
+ end # AxParser
+end # AxTags
diff --git a/lib/axtags/tag_library.rb b/lib/axtags/tag_library.rb
index 32f232b..8cc56cc 100644
--- a/lib/axtags/tag_library.rb
+++ b/lib/axtags/tag_library.rb
@@ -1,68 +1,68 @@
# AX TAGS
# Flexible, extensible custom tag and template-parsing framework built
# around the Radius templating framework.
#
-# TagLibrary - Composed of an AxTagContext and an AxTagParser, each library
+# TagLibrary - Composed of an AxContext and an AxParser, each library
# class provides the direct interface for defining tags in a given context,
# passing local variables to the parser, and managing the parsing process. Best
# use calls for the application to create any number of descendant classes of
# this class in which they define tags and call parsing actions upon. For
# example:
#
# class MyTagLibrary < AxTags::TagLibrary
# tag "myanchor" do |t|
# "<a class='awesome_anchor' href='http://awesometown.com/'>I am Awesome!</a>"
# end
# end
#
# MyTagLibrary.parse("Here is an awesome link: <ax:myanchor/>")
# => "Here is an awesome link: <a class='awesome_anchor' href='http://awesometown.com/'>I am awesome!</a>"
#
# Because tags are defined at a class level, it's not generally recommended to
# use the parent class as your API to tag definition and parsing, though it is
# possible to access the context and parsers directly and define tags and call
# parsing on them. That would look some like this:
#
# AxTags::TagLibrary.context.with do |c|
# c.define_tag "myanchor" do |t|
# "<a class='awesome_anchor' href='http://awesometown.com/'>I am Awesome!</a>"
# end
# end
# AxTags::TagLibrary.parse("Here is an awesome link: <ax:myanchor/>")
# => "Here is an awesome link: <a class='awesome_anchor' href='http://awesometown.com/'>I am awesome!</a>"
#
# This introduces the complication of having only one global tag library in which
# all tags in your system would exist, which is why the first example is the preferred
# method for optimal extensibility and namespacing.
#
module AxTags
class TagLibrary
-
+
def self.context
@@context ||= AxContext.new
end
-
+
def self.parser
@@parser ||= AxParser.new(context, :tag_prefix=>"ax")
end
-
+
def self.parse(document, options={})
if locals = options.delete(:locals)
locals.each {|arg, value| context.globals.send("#{arg}=", value) }
end
parser.parse(document)
end
-
+
def self.build_tags(&block)
yield context
end
-
+
def self.tag(name, options={}, &block)
build_tags do |c|
c.define_tag(name, options, &block)
end
end
-
+
end
end
|
mccolin/axtags
|
4f88443b62c6c65f9f82dd1cdf15aa5826f4bf7c
|
Version bump to 0.0.0
|
diff --git a/README b/README.rdoc
similarity index 100%
rename from README
rename to README.rdoc
diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000..bd52db8
--- /dev/null
+++ b/VERSION
@@ -0,0 +1 @@
+0.0.0
\ No newline at end of file
|
fiorix/nitgen-bsp
|
8fa24c622719470c526869757443e9da5e912ec4
|
Fixed typo
|
diff --git a/README.rst b/README.rst
index 4da2f6c..e63442d 100644
--- a/README.rst
+++ b/README.rst
@@ -1,52 +1,52 @@
=========
NitgenBSP
=========
:Info: See `github <http://github.com/fiorix/nitgen-bsp>`_ for the latest source.
:Author: Alexandre Fiori <[email protected]>
About
=====
-NitgenBSP is a Python extentension based on the `Nitgen SDK for Linux <http://www.nitgen.com/eng/product/enbsp_sdk.html>`_. It currently supports Nitgen fingerprint recognition devices such as `Fingkey Hamster <http://www.nitgen.com/eng/product/finkey.html>`_ and `Fingkey Hamster II <http://www.nitgen.com/eng/product/finkey2.html>`_.
+NitgenBSP is a Python extension based on the `Nitgen SDK for Linux <http://www.nitgen.com/eng/product/enbsp_sdk.html>`_. It currently supports Nitgen fingerprint recognition devices such as `Fingkey Hamster <http://www.nitgen.com/eng/product/finkey.html>`_ and `Fingkey Hamster II <http://www.nitgen.com/eng/product/finkey2.html>`_.
Implementation details
----------------------
- It has been tested under Ubuntu Linux 9.10
- Require root access level (actually depends on file permission of /dev/nitgen0)
- Only supports the device auto-detection mode (I don't have 2 devices do try manual selection)
- Supports verification with the FIR Handle and Text-Encoded FIR (not the FULL FIR)
- Allows the Text-Encoded FIR to be saved on remote database for later verification
- Text-Encoded FIR does not allow multi-byte encoding, however, supports adding payload (user data) within
- Ships with `PIL <http://www.pythonware.com/products/pil/>`_ support and allows saving fingerprint images as JPG, PNG, etc
- Supports the Nitgen in-memory Search Engine API
Documentation and Examples
==========================
The source code ships with built-in Python Docstring documentation for class reference. It also ships with examples in the `examples/ <http://github.com/fiorix/nitgen-bsp/tree/master/examples/>`_ subdirectory.
However, using NitgenBSP is pretty straightforward even for those with no experience with biometric devices.
Here is an example of simple usage::
#!/usr/bin/env python
# coding: utf-8
import NitgenBSP
if __name__ == "__main__":
nbio = NitgenBSP.Handler()
finger = nbio.capture()
image = finger.image()
image.save("out.png")
print "your fingerprint text-encoded FIR is:", finger.text()
Credits
=======
Thanks to (in no particular order):
- Nitgen Brazil
- For providing documentation and granting permission for this code to be published
|
fiorix/nitgen-bsp
|
75ec23beba27cc5cb67412ce1ea53e2006a06368
|
added search engine example
|
diff --git a/examples/search_engine.py b/examples/search_engine.py
new file mode 100755
index 0000000..779e51a
--- /dev/null
+++ b/examples/search_engine.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+# coding: utf-8
+
+import os
+import time
+import NitgenBSP
+
+if __name__ == "__main__":
+ assert os.getuid() == 0, "please run as root"
+
+ # get the bsp handler
+ nbio = NitgenBSP.Handler()
+
+ # get the search engine handler
+ search = NitgenBSP.SearchEngine(nbio)
+
+ # search.load("/tmp/nitgen.db")
+
+ # capture new fingerprint
+ raw_input("place your finger in the device and press enter: ")
+
+ # insert into the db
+ userID = int(time.time())
+ finger = nbio.capture()
+ print "adding user %d into the search engine" % userID
+ search.insert_user(userID, finger)
+
+ # identify user in the db
+ # other = nbio.capture()
+ # userID = search.identify(other)
+
+ # automatically capture new fingerprint and identify
+ raw_input("place your finger in the device and press enter: ")
+ userID = search.identify()
+ print "your userID is:", userID
+
+ # search.save("/tmp/nitgen.db")
+
+ # close nbio handler
+ nbio.close()
|
fiorix/nitgen-bsp
|
9f3c6ec578f7f741632d0ce5ffe1c0e2ec3a9e85
|
added search engine
|
diff --git a/NitgenBSP/__init__.py b/NitgenBSP/__init__.py
index 724266b..86d30c3 100644
--- a/NitgenBSP/__init__.py
+++ b/NitgenBSP/__init__.py
@@ -1,129 +1,206 @@
#!/usr/bin/env python
# coding: utf-8
+import types
from PIL import Image
from NitgenBSP import _bsp_core
+from NitgenBSP import _bsp_search
"""Nitgen fingerprint recognition API"""
PURPOSE_VERIFY = 0x01
PURPOSE_ENROLL = 0x03
-class FingerText(str):
+class FingerText:
"""The Text-Encoded version of a fingerprint's FIR.
+ FingerText objects are created automatically by instances of
+ the Finger class, when invoking the Finger.text() method.
"""
- pass
+ def __init__(self, text):
+ self.text = text
-class Finger(object):
+ def __str__(self):
+ return self.text
+
+class Finger:
"""The Finger class provides the FIR Handle, raw
image buffer provided by the device, as well as
image dimentions (width and height).
It may also convert the raw buffer to a PIL image,
as well as the Text-Encoded FIR.
"""
def __init__(self, handler, FIR, buffer, width, height):
+ """Finger objects are created automatically by instances of
+ the Handler class, when invoking the Handler.capture() method.
+ """
self.FIR = FIR
self.width = width
self.height = height
self.buffer = buffer
self.__handler = handler
self.payload = ""
def set_payload(self, text):
+ """Add text (user data) into this fingerprint record.
+ """
self.payload = text
self.FIR = _bsp_core.payload(self.__handler, self.FIR, text)
def text(self):
"""Return the Text-Encoded version of the FIR for this
fingerprint, which may be used to store the fingerprint
in a database as well as later verification.
"""
return FingerText(_bsp_core.text_fir(self.__handler, self.FIR))
def image(self):
"""Return the PIL image of this fingerprint, which may be
used to be saved on disk as JPG, PNG, etc.
"""
return Image.fromstring("L",
(self.width, self.height), self.buffer)
def __del__(self):
del(self.buffer)
_bsp_core.free_fir(self.__handler, self.FIR)
class Handler:
"""A Nitgen device handler
"""
def __init__(self):
"""Initialize the Nitgen API and open the first available device
using the auto-detection mode.
"""
- self.__handler, self.__image_width, self.__image_height = _bsp_core.open()
+ self._handler, self.__image_width, self.__image_height = _bsp_core.open()
def capture(self, payload=None, purpose=PURPOSE_VERIFY, timeout=5):
"""Capture a fingerprint from the device and return an instance
of the Finger class.
`payload` is an optional STRING which is encoded within the FIR,
and retrieved during the verify() process.
Default `purpose` of capture is VERIFY, but may also be ENROLL.
The optional `timeout` is defined in seconds.
"""
if purpose not in (PURPOSE_VERIFY, PURPOSE_ENROLL):
raise TypeError("unknown capture purpose")
- FIR, buffer = _bsp_core.capture(self.__handler,
+ FIR, buffer = _bsp_core.capture(self._handler,
self.__image_width, self.__image_height, purpose, timeout)
- finger = Finger(self.__handler, FIR, buffer,
+ finger = Finger(self._handler, FIR, buffer,
self.__image_width, self.__image_height)
if payload is not None:
finger.set_payload(payload)
return finger
- def verify(self, cap1, cap2=None, timeout=5):
+ def verify(self, finger1, finger2=None, timeout=5):
"""Perform verification of two fingerprints.
- `cap1` is mandatory and must be an instance of Finger or FingerText class.
- `cap2` is optional. When it is not available, a new capture() is done in
+ `finger1` is mandatory and must be an instance of Finger or FingerText class.
+ `finger2` is optional. When it is not available, a new capture() is done in
order to verify both fingerprints. However, if it is passed by the user,
- it must be the same type of `cap1`. It is not possible to verify an instance
+ it must be the same type of `finger1`. It is not possible to verify an instance
of Finger against FingerText and vice-versa.
- `timeout` is only used when `cap2` is not available. In this case, it will
+ `timeout` is only used when `finger2` is not available. In this case, it will
be passed in to the capture() method.
The return value is 0 when fingerprints doesn't match. When they match, the
- default return value is 1, unless `cap1` has an embedded payload. In this case,
- the payload of `cap1` is returned.
+ default return value is 1, unless `finger1` has an embedded payload. In this case,
+ the payload of `finger1` is returned.
"""
- if isinstance(cap1, Finger):
- if cap2 is None:
- cap1 = str(cap1.text())
- cap2 = self.capture(timeout=timeout).text()
- else:
- cap1 = cap1.FIR
- elif isinstance(cap1, FingerText):
- cap1 = str(cap1)
- if cap2 is None:
- cap2 = self.capture(timeout=timeout).text()
+ if isinstance(finger1, Finger):
+ finger1 = finger1.FIR
+ if finger2 is None:
+ finger2 = self.capture(timeout=timeout).text()
+ elif isinstance(finger1, FingerText):
+ finger1 = str(finger1)
+ if finger2 is None:
+ finger2 = self.capture(timeout=timeout).text()
else:
- raise TypeError("cap1 must be an instance of Finger or FingerText")
+ raise TypeError("finger1 must be an instance of Finger or FingerText")
- if isinstance(cap2, Finger):
- cap2 = cap2.FIR
- elif isinstance(cap2, FingerText):
- cap2 = str(cap2)
+ if isinstance(finger2, Finger):
+ finger2 = finger2.FIR
+ elif isinstance(finger2, FingerText):
+ finger2 = str(finger2)
else:
- raise TypeError("cap2 must be an instance of Finger or FingerText")
+ raise TypeError("finger2 must be an instance of Finger or FingerText")
- if type(cap1) != type(cap2):
+ if type(finger1) != type(finger2):
raise TypeError("cannot verify Finger against FingerText and vice-versa")
- match, payload = _bsp_core.verify(self.__handler, cap2, cap1)
+ match, payload = _bsp_core.verify(self._handler, finger2, finger1)
return match == 1 and (payload or match) or 0
def close(self):
"""Close the currently opened Nitgen device
"""
- _bsp_core.close(self.__handler)
+ _bsp_core.close(self._handler)
+
+
+class SearchEngine(object):
+ """The Nitgen's built-in in-memory Search Engine interface
+ """
+ def __init__(self, handler):
+ if not isinstance(handler, Handler):
+ raise TypeError("SearchEngine must be initialize with an instance of the Handler class")
+
+ self.__handler = handler._handler
+ self.__capture = handler.capture
+ _bsp_search.initialize(self.__handler)
+
+ def __del__(self):
+ _bsp_search.terminate(self.__handler)
+
+ def insert_user(self, userID, finger):
+ """Add new userID with its fingerprint into the DB
+ """
+ if isinstance(finger, Finger):
+ finger = finger.FIR
+ elif isinstance(finger, FingerText):
+ finger = str(finger)
+ else:
+ raise TypeError("finger must be an instance of either Finger or FingerText")
+
+ if not isinstance(userID, types.IntType):
+ raise TypeError("userID must be an integer")
+
+ _bsp_search.insert(self.__handler, userID, finger)
+
+ def remove_user(self, userID):
+ """Remove userID from the DB
+ """
+ if not isinstance(userID, types.IntType):
+ raise TypeError("userID must be an integer")
+
+ _bsp_search.remove(self.__handler, userID)
+
+ def identify(self, finger=None, security_level=5, timeout=5):
+ if finger is None:
+ finger = self.__capture(timeout=timeout).text()
+ elif isinstance(finger, Finger):
+ finger = finger.FIR
+ elif isinstance(finger, FingerText):
+ finger = str(finger)
+ else:
+ raise TypeError("finger must be an instance of Finger or FingerText")
+
+ if security_level not in range(1, 10):
+ raise TypeError("security_level must be an integer betweeen 1 (lowest) and 9 (highest)")
+
+ if not isinstance(timeout, types.IntType):
+ raise TypeError("timeout (seconds) must be an integer")
+
+ return _bsp_search.identify(self.__handler, finger, security_level)
+
+ def save(self, filename):
+ """Save DB into filename
+ """
+ _bsp_search.save(self.__handler, filename)
+
+ def load(self, filename):
+ """Load DB from filename
+ """
+ _bsp_search.load(self.__handler, filename)
diff --git a/NitgenBSP/bsp_search.c b/NitgenBSP/bsp_search.c
index 903f7b1..0db1c43 100644
--- a/NitgenBSP/bsp_search.c
+++ b/NitgenBSP/bsp_search.c
@@ -1,176 +1,177 @@
#include <string.h>
#include <Python.h>
#include <NBioAPI.h>
+#include <NBioAPI_IndexSearch.h>
static PyObject *search_initialize(PyObject *self, PyObject *args)
{
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
if(!PyArg_ParseTuple(args, "i", &m_hBSP))
return PyErr_Format(PyExc_TypeError, "invalid bsp handler");
err = NBioAPI_InitIndexSearchEngine(m_hBSP);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot initialize search engine");
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *search_terminate(PyObject *self, PyObject *args)
{
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
if(!PyArg_ParseTuple(args, "i", &m_hBSP))
return PyErr_Format(PyExc_TypeError, "invalid bsp handler");
err = NBioAPI_TerminateIndexSearchEngine(m_hBSP);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot terminate search engine");
Py_INCREF(Py_None);
return Py_None;
}
-static PyObject *search_add_fir(PyObject *self, PyObject *args)
+static PyObject *search_insert(PyObject *self, PyObject *args)
{
PyObject *rawFIR;
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
NBioAPI_UINT32 userID;
NBioAPI_INPUT_FIR inputFIR;
NBioAPI_FIR_HANDLE fir_handle;
NBioAPI_FIR_TEXTENCODE fir_text;
NBioAPI_INDEXSEARCH_SAMPLE_INFO sample;
- if(!PyArg_ParseTuple(args, "iOi", &m_hBSP, &rawFIR, &userID))
+ if(!PyArg_ParseTuple(args, "iiO", &m_hBSP, &userID, &rawFIR))
return PyErr_Format(PyExc_TypeError, "invalid arguments");
/* determine format of FIR: handler or text */
if(PyInt_Check(rawFIR)) {
PyArg_Parse(rawFIR, "i", &fir_handle);
inputFIR.Form = NBioAPI_FIR_FORM_HANDLE;
inputFIR.InputFIR.FIRinBSP = &fir_handle;
} else if(PyString_Check(rawFIR)) {
PyArg_Parse(rawFIR, "s", &fir_text.TextFIR);
fir_text.IsWideChar = NBioAPI_FALSE;
inputFIR.Form = NBioAPI_FIR_FORM_TEXTENCODE;
inputFIR.InputFIR.TextFIR = &fir_text;
} else
return PyErr_Format(PyExc_TypeError, "unknown format of FIR");
memset(&sample, 0, sizeof(sample));
err = NBioAPI_AddFIRToIndexSearchDB(m_hBSP, &inputFIR, userID, &sample);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot add FIR to search engine");
Py_INCREF(Py_None);
return Py_None;
}
-static PyObject *search_del_fir(PyObject *self, PyObject *args)
+static PyObject *search_remove(PyObject *self, PyObject *args)
{
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
NBioAPI_UINT32 userID;
if(!PyArg_ParseTuple(args, "ii", &m_hBSP, &userID))
return PyErr_Format(PyExc_TypeError, "invalid arguments");
err = NBioAPI_RemoveUserFromIndexSearchDB(m_hBSP, userID);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot remove FIR from search engine");
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *search_identify(PyObject *self, PyObject *args)
{
int seclevel;
PyObject *rawFIR;
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
NBioAPI_INPUT_FIR inputFIR;
NBioAPI_FIR_HANDLE fir_handle;
NBioAPI_FIR_TEXTENCODE fir_text;
- NBioAPI_INDEXSEARCH_CALLBACK_INFO_0 info;
+ NBioAPI_INDEXSEARCH_FP_INFO info;
if(!PyArg_ParseTuple(args, "iOi", &m_hBSP, &rawFIR, &seclevel))
return PyErr_Format(PyExc_TypeError, "invalid arguments");
/* determine format of FIR: handler or text */
if(PyInt_Check(rawFIR)) {
PyArg_Parse(rawFIR, "i", &fir_handle);
inputFIR.Form = NBioAPI_FIR_FORM_HANDLE;
inputFIR.InputFIR.FIRinBSP = &fir_handle;
} else if(PyString_Check(rawFIR)) {
PyArg_Parse(rawFIR, "s", &fir_text.TextFIR);
fir_text.IsWideChar = NBioAPI_FALSE;
inputFIR.Form = NBioAPI_FIR_FORM_TEXTENCODE;
inputFIR.InputFIR.TextFIR = &fir_text;
} else
return PyErr_Format(PyExc_TypeError, "unknown format of FIR");
memset(&info, 0, sizeof(info));
err = NBioAPI_IdentifyDataFromIndexSearchDB(m_hBSP, &inputFIR, seclevel, &info, NULL);
if(err == NBioAPIERROR_INDEXSEARCH_IDENTIFY_FAIL) {
Py_INCREF(Py_None);
return Py_None;
} else if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot perform identify within the search engine");
return Py_BuildValue("i", info.ID);
}
static PyObject *search_save(PyObject *self, PyObject *args)
{
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
NBioAPI_CHAR *fullpath;
if(!PyArg_ParseTuple(args, "is", &m_hBSP, &fullpath))
return PyErr_Format(PyExc_TypeError, "invalid arguments");
err = NBioAPI_SaveIndexSearchDBToFile(m_hBSP, fullpath);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot save search engine DB to file");
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *search_load(PyObject *self, PyObject *args)
{
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
NBioAPI_CHAR *fullpath;
if(!PyArg_ParseTuple(args, "is", &m_hBSP, &fullpath))
return PyErr_Format(PyExc_TypeError, "invalid arguments");
- err = NBioAPI_LoadIndexSearchDBFromFile(m_hBSP, fullpath)
+ err = NBioAPI_LoadIndexSearchDBFromFile(m_hBSP, fullpath);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot load search engine DB from file");
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef SearchMethods[] = {
{"initialize", search_initialize, METH_VARARGS, "initialize search engine"},
{"terminate", search_terminate, METH_VARARGS, "terminate search engine"},
- {"add_fir", search_add_fir, METH_VARARGS, "add FIR to search engine"},
- {"del_fir", search_del_fir, METH_VARARGS, "remove FIR from search engine (using uid)"},
+ {"insert", search_insert, METH_VARARGS, "insert userID with FIR into the search engine"},
+ {"remove", search_remove, METH_VARARGS, "remove userID from the search engine"},
{"identify", search_identify, METH_VARARGS, "identify FIR using search engine"},
{"save", search_save, METH_VARARGS, "save search engine db into file"},
{"load", search_load, METH_VARARGS, "load search engine db from file"},
{NULL, NULL, 0, NULL},
};
PyMODINIT_FUNC init_bsp_search(void)
{
Py_InitModule("_bsp_search", SearchMethods);
}
diff --git a/setup.py b/setup.py
index 35f3580..df5cbad 100644
--- a/setup.py
+++ b/setup.py
@@ -1,19 +1,22 @@
#!/usr/bin/env python
# coding: utf-8
from distutils.core import setup, Extension
+nitgen_include_dirs=["/usr/local/NITGEN/eNBSP/include"]
+nitgen_libraries=["pthread", "NBioBSP"]
+
setup(
name="NitgenBSP",
version="0.1",
author="Alexandre Fiori",
author_email="[email protected]",
url="http://github.com/fiorix/nitgen-bsp",
packages=["NitgenBSP"],
ext_modules=[
Extension("NitgenBSP/_bsp_core", ["NitgenBSP/bsp_core.c"],
+ include_dirs=nitgen_include_dirs, libraries=nitgen_libraries),
Extension("NitgenBSP/_bsp_search", ["NitgenBSP/bsp_search.c"],
- include_dirs=["/usr/local/NITGEN/eNBSP/include"],
- libraries=["pthread", "NBioBSP"], )
+ include_dirs=nitgen_include_dirs, libraries=nitgen_libraries),
]
)
|
fiorix/nitgen-bsp
|
f3f9ae3f94628a11bac4b00e03f1dd983d3b599b
|
nitgen search engine api
|
diff --git a/NitgenBSP/bsp_search.c b/NitgenBSP/bsp_search.c
new file mode 100644
index 0000000..903f7b1
--- /dev/null
+++ b/NitgenBSP/bsp_search.c
@@ -0,0 +1,176 @@
+#include <string.h>
+#include <Python.h>
+#include <NBioAPI.h>
+
+static PyObject *search_initialize(PyObject *self, PyObject *args)
+{
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+
+ if(!PyArg_ParseTuple(args, "i", &m_hBSP))
+ return PyErr_Format(PyExc_TypeError, "invalid bsp handler");
+
+ err = NBioAPI_InitIndexSearchEngine(m_hBSP);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot initialize search engine");
+
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+static PyObject *search_terminate(PyObject *self, PyObject *args)
+{
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+
+ if(!PyArg_ParseTuple(args, "i", &m_hBSP))
+ return PyErr_Format(PyExc_TypeError, "invalid bsp handler");
+
+ err = NBioAPI_TerminateIndexSearchEngine(m_hBSP);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot terminate search engine");
+
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+static PyObject *search_add_fir(PyObject *self, PyObject *args)
+{
+ PyObject *rawFIR;
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_UINT32 userID;
+ NBioAPI_INPUT_FIR inputFIR;
+ NBioAPI_FIR_HANDLE fir_handle;
+ NBioAPI_FIR_TEXTENCODE fir_text;
+ NBioAPI_INDEXSEARCH_SAMPLE_INFO sample;
+
+ if(!PyArg_ParseTuple(args, "iOi", &m_hBSP, &rawFIR, &userID))
+ return PyErr_Format(PyExc_TypeError, "invalid arguments");
+
+ /* determine format of FIR: handler or text */
+ if(PyInt_Check(rawFIR)) {
+ PyArg_Parse(rawFIR, "i", &fir_handle);
+ inputFIR.Form = NBioAPI_FIR_FORM_HANDLE;
+ inputFIR.InputFIR.FIRinBSP = &fir_handle;
+ } else if(PyString_Check(rawFIR)) {
+ PyArg_Parse(rawFIR, "s", &fir_text.TextFIR);
+ fir_text.IsWideChar = NBioAPI_FALSE;
+ inputFIR.Form = NBioAPI_FIR_FORM_TEXTENCODE;
+ inputFIR.InputFIR.TextFIR = &fir_text;
+ } else
+ return PyErr_Format(PyExc_TypeError, "unknown format of FIR");
+
+ memset(&sample, 0, sizeof(sample));
+ err = NBioAPI_AddFIRToIndexSearchDB(m_hBSP, &inputFIR, userID, &sample);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot add FIR to search engine");
+
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+static PyObject *search_del_fir(PyObject *self, PyObject *args)
+{
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_UINT32 userID;
+
+ if(!PyArg_ParseTuple(args, "ii", &m_hBSP, &userID))
+ return PyErr_Format(PyExc_TypeError, "invalid arguments");
+
+ err = NBioAPI_RemoveUserFromIndexSearchDB(m_hBSP, userID);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot remove FIR from search engine");
+
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+static PyObject *search_identify(PyObject *self, PyObject *args)
+{
+ int seclevel;
+ PyObject *rawFIR;
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_INPUT_FIR inputFIR;
+ NBioAPI_FIR_HANDLE fir_handle;
+ NBioAPI_FIR_TEXTENCODE fir_text;
+ NBioAPI_INDEXSEARCH_CALLBACK_INFO_0 info;
+
+ if(!PyArg_ParseTuple(args, "iOi", &m_hBSP, &rawFIR, &seclevel))
+ return PyErr_Format(PyExc_TypeError, "invalid arguments");
+
+ /* determine format of FIR: handler or text */
+ if(PyInt_Check(rawFIR)) {
+ PyArg_Parse(rawFIR, "i", &fir_handle);
+ inputFIR.Form = NBioAPI_FIR_FORM_HANDLE;
+ inputFIR.InputFIR.FIRinBSP = &fir_handle;
+ } else if(PyString_Check(rawFIR)) {
+ PyArg_Parse(rawFIR, "s", &fir_text.TextFIR);
+ fir_text.IsWideChar = NBioAPI_FALSE;
+ inputFIR.Form = NBioAPI_FIR_FORM_TEXTENCODE;
+ inputFIR.InputFIR.TextFIR = &fir_text;
+ } else
+ return PyErr_Format(PyExc_TypeError, "unknown format of FIR");
+
+ memset(&info, 0, sizeof(info));
+ err = NBioAPI_IdentifyDataFromIndexSearchDB(m_hBSP, &inputFIR, seclevel, &info, NULL);
+ if(err == NBioAPIERROR_INDEXSEARCH_IDENTIFY_FAIL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ } else if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot perform identify within the search engine");
+
+ return Py_BuildValue("i", info.ID);
+}
+
+static PyObject *search_save(PyObject *self, PyObject *args)
+{
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_CHAR *fullpath;
+
+ if(!PyArg_ParseTuple(args, "is", &m_hBSP, &fullpath))
+ return PyErr_Format(PyExc_TypeError, "invalid arguments");
+
+ err = NBioAPI_SaveIndexSearchDBToFile(m_hBSP, fullpath);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot save search engine DB to file");
+
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+static PyObject *search_load(PyObject *self, PyObject *args)
+{
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_CHAR *fullpath;
+
+ if(!PyArg_ParseTuple(args, "is", &m_hBSP, &fullpath))
+ return PyErr_Format(PyExc_TypeError, "invalid arguments");
+
+ err = NBioAPI_LoadIndexSearchDBFromFile(m_hBSP, fullpath)
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot load search engine DB from file");
+
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+static PyMethodDef SearchMethods[] = {
+ {"initialize", search_initialize, METH_VARARGS, "initialize search engine"},
+ {"terminate", search_terminate, METH_VARARGS, "terminate search engine"},
+ {"add_fir", search_add_fir, METH_VARARGS, "add FIR to search engine"},
+ {"del_fir", search_del_fir, METH_VARARGS, "remove FIR from search engine (using uid)"},
+ {"identify", search_identify, METH_VARARGS, "identify FIR using search engine"},
+ {"save", search_save, METH_VARARGS, "save search engine db into file"},
+ {"load", search_load, METH_VARARGS, "load search engine db from file"},
+ {NULL, NULL, 0, NULL},
+};
+
+PyMODINIT_FUNC init_bsp_search(void)
+{
+ Py_InitModule("_bsp_search", SearchMethods);
+}
diff --git a/setup.py b/setup.py
index c393474..35f3580 100644
--- a/setup.py
+++ b/setup.py
@@ -1,20 +1,19 @@
#!/usr/bin/env python
# coding: utf-8
from distutils.core import setup, Extension
setup(
name="NitgenBSP",
version="0.1",
author="Alexandre Fiori",
author_email="[email protected]",
url="http://github.com/fiorix/nitgen-bsp",
packages=["NitgenBSP"],
ext_modules=[
- Extension("NitgenBSP/_bsp_core", [
- "NitgenBSP/bsp_core.c",
- ],
+ Extension("NitgenBSP/_bsp_core", ["NitgenBSP/bsp_core.c"],
+ Extension("NitgenBSP/_bsp_search", ["NitgenBSP/bsp_search.c"],
include_dirs=["/usr/local/NITGEN/eNBSP/include"],
libraries=["pthread", "NBioBSP"], )
]
)
|
fiorix/nitgen-bsp
|
6193d532522ab0753a5250aa0bd01a3791bfa7da
|
added example
|
diff --git a/examples/auto_verify.py b/examples/auto_verify.py
new file mode 100755
index 0000000..d58430a
--- /dev/null
+++ b/examples/auto_verify.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python
+# coding: utf-8
+
+import os
+import NitgenBSP
+
+if __name__ == "__main__":
+ assert os.getuid() == 0, "please run as root"
+
+ # get the bsp handler
+ handler = NitgenBSP.Handler()
+
+ raw_input("place your finger in the device and press enter: ")
+ finger = handler.capture(payload="hello, world!", purpose=NitgenBSP.PURPOSE_ENROLL)
+
+ raw_input("ok. do it again... press enter when ready: ")
+ match = handler.verify(finger, timeout=5)
+
+ print "your fingerprints " + (match and "do match" or "do not match")
+ if match:
+ print "FIR payload is:", match
+
+ # that's it
+ handler.close()
|
fiorix/nitgen-bsp
|
0516777d0ad37215c74f27ca34ed2507288675b4
|
new features, organization...
|
diff --git a/NitgenBSP/__init__.py b/NitgenBSP/__init__.py
index 8b4a6b2..724266b 100644
--- a/NitgenBSP/__init__.py
+++ b/NitgenBSP/__init__.py
@@ -1,92 +1,129 @@
#!/usr/bin/env python
# coding: utf-8
from PIL import Image
-from NitgenBSP import _bsp_module
+from NitgenBSP import _bsp_core
"""Nitgen fingerprint recognition API"""
+PURPOSE_VERIFY = 0x01
+PURPOSE_ENROLL = 0x03
+
class FingerText(str):
"""The Text-Encoded version of a fingerprint's FIR.
"""
pass
class Finger(object):
"""The Finger class provides the FIR Handle, raw
image buffer provided by the device, as well as
image dimentions (width and height).
It may also convert the raw buffer to a PIL image,
as well as the Text-Encoded FIR.
"""
- def __init__(self, handler, data, width, height):
- self.__handler = handler
- self.buffer, self.FIR = data
+ def __init__(self, handler, FIR, buffer, width, height):
+ self.FIR = FIR
self.width = width
self.height = height
+ self.buffer = buffer
+ self.__handler = handler
+ self.payload = ""
+ def set_payload(self, text):
+ self.payload = text
+ self.FIR = _bsp_core.payload(self.__handler, self.FIR, text)
+
def text(self):
"""Return the Text-Encoded version of the FIR for this
fingerprint, which may be used to store the fingerprint
in a database as well as later verification.
"""
- return FingerText(_bsp_module.text_fir(self.__handler, self.FIR))
+ return FingerText(_bsp_core.text_fir(self.__handler, self.FIR))
def image(self):
"""Return the PIL image of this fingerprint, which may be
used to be saved on disk as JPG, PNG, etc.
"""
return Image.fromstring("L",
(self.width, self.height), self.buffer)
def __del__(self):
- _bsp_module.free_fir(self.__handler, self.FIR)
+ del(self.buffer)
+ _bsp_core.free_fir(self.__handler, self.FIR)
class Handler:
"""A Nitgen device handler
"""
def __init__(self):
"""Initialize the Nitgen API and open the first available device
using the auto-detection mode.
"""
- self.__bsp = _bsp_module.open()
- self.__handler = self.__bsp[0]
- self.__image_width = self.__bsp[1]
- self.__image_height = self.__bsp[2]
+ self.__handler, self.__image_width, self.__image_height = _bsp_core.open()
- def capture(self):
+ def capture(self, payload=None, purpose=PURPOSE_VERIFY, timeout=5):
"""Capture a fingerprint from the device and return an instance
of the Finger class.
+ `payload` is an optional STRING which is encoded within the FIR,
+ and retrieved during the verify() process.
+ Default `purpose` of capture is VERIFY, but may also be ENROLL.
+ The optional `timeout` is defined in seconds.
"""
- return Finger(self.__handler,
- _bsp_module.capture(*self.__bsp),
+ if purpose not in (PURPOSE_VERIFY, PURPOSE_ENROLL):
+ raise TypeError("unknown capture purpose")
+
+ FIR, buffer = _bsp_core.capture(self.__handler,
+ self.__image_width, self.__image_height, purpose, timeout)
+
+ finger = Finger(self.__handler, FIR, buffer,
self.__image_width, self.__image_height)
- def verify(self, cap1, cap2):
- """Perform verification of two fingerprints by receiving either
- a pair of Finger or FingerText instances.
- Returns 0 or 1, depending on finger verification.
+ if payload is not None:
+ finger.set_payload(payload)
+
+ return finger
+
+ def verify(self, cap1, cap2=None, timeout=5):
+ """Perform verification of two fingerprints.
+ `cap1` is mandatory and must be an instance of Finger or FingerText class.
+ `cap2` is optional. When it is not available, a new capture() is done in
+ order to verify both fingerprints. However, if it is passed by the user,
+ it must be the same type of `cap1`. It is not possible to verify an instance
+ of Finger against FingerText and vice-versa.
+ `timeout` is only used when `cap2` is not available. In this case, it will
+ be passed in to the capture() method.
+
+ The return value is 0 when fingerprints doesn't match. When they match, the
+ default return value is 1, unless `cap1` has an embedded payload. In this case,
+ the payload of `cap1` is returned.
"""
if isinstance(cap1, Finger):
- cap1 = cap1.FIR
+ if cap2 is None:
+ cap1 = str(cap1.text())
+ cap2 = self.capture(timeout=timeout).text()
+ else:
+ cap1 = cap1.FIR
elif isinstance(cap1, FingerText):
cap1 = str(cap1)
+ if cap2 is None:
+ cap2 = self.capture(timeout=timeout).text()
else:
raise TypeError("cap1 must be an instance of Finger or FingerText")
if isinstance(cap2, Finger):
cap2 = cap2.FIR
elif isinstance(cap2, FingerText):
cap2 = str(cap2)
else:
raise TypeError("cap2 must be an instance of Finger or FingerText")
if type(cap1) != type(cap2):
raise TypeError("cannot verify Finger against FingerText and vice-versa")
- return _bsp_module.verify(self.__handler, cap1, cap2)
+ match, payload = _bsp_core.verify(self.__handler, cap2, cap1)
+ return match == 1 and (payload or match) or 0
def close(self):
"""Close the currently opened Nitgen device
"""
- _bsp_module.close(self.__handler)
+ _bsp_core.close(self.__handler)
diff --git a/NitgenBSP/bsp_module.c b/NitgenBSP/bsp_core.c
similarity index 69%
rename from NitgenBSP/bsp_module.c
rename to NitgenBSP/bsp_core.c
index b5a6777..d937ba3 100644
--- a/NitgenBSP/bsp_module.c
+++ b/NitgenBSP/bsp_core.c
@@ -1,179 +1,220 @@
#include <string.h>
#include <Python.h>
#include <NBioAPI.h>
struct capture_data {
int image_width;
int image_height;
int buffer_size;
unsigned char *buffer;
};
static PyObject *bsp_open(PyObject *self, PyObject *args)
{
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
NBioAPI_VERSION m_Version;
NBioAPI_UINT32 dev_cnt;
NBioAPI_DEVICE_ID *dev_list;
NBioAPI_DEVICE_INFO_0 m_DeviceInfo0;
err = NBioAPI_Init(&m_hBSP);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot initialize NBioAPI");
NBioAPI_GetVersion(m_hBSP, &m_Version);
err = NBioAPI_EnumerateDevice(m_hBSP, &dev_cnt, &dev_list);
if(dev_cnt == 0)
return PyErr_Format(PyExc_RuntimeError, "device not found");
err = NBioAPI_OpenDevice(m_hBSP, NBioAPI_DEVICE_ID_AUTO);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot open device");
memset(&m_DeviceInfo0, 0, sizeof(NBioAPI_DEVICE_INFO_0));
NBioAPI_GetDeviceInfo(m_hBSP, NBioAPI_DEVICE_ID_AUTO, 0, &m_DeviceInfo0);
return Py_BuildValue("(iii)", m_hBSP,
m_DeviceInfo0.ImageWidth, m_DeviceInfo0.ImageHeight);
}
static PyObject *bsp_close(PyObject *self, PyObject *args)
{
NBioAPI_HANDLE m_hBSP;
if(!PyArg_ParseTuple(args, "i", &m_hBSP))
return PyErr_Format(PyExc_TypeError, "invalid bsp handler");
NBioAPI_CloseDevice(m_hBSP, NBioAPI_DEVICE_ID_AUTO);
Py_INCREF(Py_None);
return Py_None;
}
NBioAPI_RETURN MyCaptureCallback(NBioAPI_WINDOW_CALLBACK_PARAM_PTR_0 pCallbackParam, NBioAPI_VOID_PTR pUserParam)
{
struct capture_data *data = (struct capture_data *) pUserParam;
memcpy(data->buffer, pCallbackParam->lpImageBuf, data->buffer_size);
return NBioAPIERROR_NONE;
}
static PyObject *bsp_capture(PyObject *self, PyObject *args)
{
+ int purpose;
+ int timeout;
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
NBioAPI_FIR_HANDLE capFIR;
NBioAPI_WINDOW_OPTION winOption;
struct capture_data data;
memset(&data, 0, sizeof(data));
- if(!PyArg_ParseTuple(args, "iii", &m_hBSP, &data.image_width, &data.image_height))
+ if(!PyArg_ParseTuple(args, "iiiii", &m_hBSP,
+ &data.image_width, &data.image_height, &purpose, &timeout))
return PyErr_Format(PyExc_TypeError, "invalid arguments");
data.buffer_size = data.image_width * data.image_height;
data.buffer = PyMem_Malloc(data.buffer_size);
memset(&winOption, 0, sizeof(NBioAPI_WINDOW_OPTION));
winOption.Length = sizeof(NBioAPI_WINDOW_OPTION);
winOption.CaptureCallBackInfo.CallBackType = 0;
winOption.CaptureCallBackInfo.CallBackFunction = MyCaptureCallback;
winOption.CaptureCallBackInfo.UserCallBackParam = &data;
capFIR = NBioAPI_INVALID_HANDLE;
- err = NBioAPI_Capture(m_hBSP, NBioAPI_FIR_PURPOSE_VERIFY, &capFIR, -1, NULL, &winOption);
+ err = NBioAPI_Capture(m_hBSP, purpose, &capFIR, timeout*1000, NULL, &winOption);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot capture fingerprint");
- return Py_BuildValue("(s#i)", data.buffer, data.buffer_size, capFIR);
+ return Py_BuildValue("(is#)", capFIR, data.buffer, data.buffer_size);
}
static PyObject *bsp_verify(PyObject *self, PyObject *args)
{
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
+ NBioAPI_FIR_PAYLOAD payload;
NBioAPI_INPUT_FIR cap1, cap2;
NBioAPI_BOOL bResult = NBioAPI_FALSE;
NBioAPI_FIR_HANDLE fir1_handle, fir2_handle;
NBioAPI_FIR_TEXTENCODE fir1_text, fir2_text;
PyObject *rawF1, *rawF2;
if(!PyArg_ParseTuple(args, "iOO", &m_hBSP, &rawF1, &rawF2))
return PyErr_Format(PyExc_TypeError, "invalid arguments");
/* determine format of FIR 1: handler or text */
if(PyInt_Check(rawF1)) {
PyArg_Parse(rawF1, "i", &fir1_handle);
cap1.Form = NBioAPI_FIR_FORM_HANDLE;
cap1.InputFIR.FIRinBSP = &fir1_handle;
} else if(PyString_Check(rawF1)) {
PyArg_Parse(rawF1, "s", &fir1_text.TextFIR);
fir1_text.IsWideChar = NBioAPI_FALSE;
cap1.Form = NBioAPI_FIR_FORM_TEXTENCODE;
cap1.InputFIR.TextFIR = &fir1_text;
} else
return PyErr_Format(PyExc_TypeError, "unknown format of cap1");
/* determine format of FIR 2: handler or text */
if(PyInt_Check(rawF2)) {
PyArg_Parse(rawF2, "i", &fir2_handle);
cap2.Form = NBioAPI_FIR_FORM_HANDLE;
cap2.InputFIR.FIRinBSP = &fir2_handle;
} else if(PyString_Check(rawF2)) {
PyArg_Parse(rawF2, "s", &fir2_text.TextFIR);
fir2_text.IsWideChar = NBioAPI_FALSE;
cap2.Form = NBioAPI_FIR_FORM_TEXTENCODE;
cap2.InputFIR.TextFIR = &fir2_text;
} else
return PyErr_Format(PyExc_TypeError, "unknown format of cap2");
/* warning: cannot verify text VS handle and vice-versa */
- err = NBioAPI_VerifyMatch(m_hBSP, &cap1, &cap2, &bResult, NULL);
+ memset(&payload, 0, sizeof(payload));
+ err = NBioAPI_VerifyMatch(m_hBSP, &cap1, &cap2, &bResult, &payload);
if(err != NBioAPIERROR_NONE)
- return PyErr_Format(PyExc_RuntimeError, "cannot verify");
- return Py_BuildValue("i", bResult);
+ switch(err) {
+ case NBioAPIERROR_INVALID_HANDLE:
+ return PyErr_Format(PyExc_RuntimeError, "cannot verify: invalid handle");
+ case NBioAPIERROR_INVALID_POINTER:
+ return PyErr_Format(PyExc_RuntimeError, "cannot verify: invalid pointer");
+ case NBioAPIERROR_ENCRYPTED_DATA_ERROR:
+ return PyErr_Format(PyExc_RuntimeError, "cannot verify: encrypted data error");
+ case NBioAPIERROR_INTERNAL_CHECKSUM_FAIL:
+ return PyErr_Format(PyExc_RuntimeError, "cannot verify: checksum fail");
+ case NBioAPIERROR_MUST_BE_PROCESSED_DATA:
+ return PyErr_Format(PyExc_RuntimeError, "cannot verify: must be processed data");
+ default:
+ return PyErr_Format(PyExc_RuntimeError, "cannot verify: unknown reason");
+ }
+ return Py_BuildValue("is#", bResult, payload.Data, payload.Length);
+}
+
+static PyObject *bsp_payload(PyObject *self, PyObject *args)
+{
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_INPUT_FIR inputFIR;
+ NBioAPI_FIR_PAYLOAD payload;
+ NBioAPI_FIR_HANDLE fir_handle, fir_template;
+
+ memset(&payload, 0, sizeof(payload));
+ if(!PyArg_ParseTuple(args, "iis#", &m_hBSP, &fir_handle, &payload.Data, &payload.Length))
+ return PyErr_Format(PyExc_TypeError, "invalid arguments");
+
+ memset(&inputFIR, 0, sizeof(inputFIR));
+ inputFIR.Form = NBioAPI_FIR_FORM_HANDLE;
+ inputFIR.InputFIR.FIRinBSP = &fir_handle;
+
+ err = NBioAPI_CreateTemplate(m_hBSP, &inputFIR, NULL, &fir_template, &payload);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot create template from FIR handle");
+
+ NBioAPI_FreeFIRHandle(m_hBSP, fir_handle);
+ return Py_BuildValue("i", fir_template);
}
static PyObject *bsp_free_fir(PyObject *self, PyObject *args)
{
NBioAPI_HANDLE m_hBSP;
NBioAPI_FIR_HANDLE fir;
if(!PyArg_ParseTuple(args, "ii", &m_hBSP, &fir))
return PyErr_Format(PyExc_TypeError, "invalid arguments");
NBioAPI_FreeFIRHandle(m_hBSP, fir);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *bsp_text_fir(PyObject *self, PyObject *args)
{
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
NBioAPI_FIR_HANDLE fir;
NBioAPI_FIR_TEXTENCODE TextFIR;
if(!PyArg_ParseTuple(args, "ii", &m_hBSP, &fir))
return PyErr_Format(PyExc_TypeError, "invalid arguments");
err = NBioAPI_GetTextFIRFromHandle(m_hBSP, fir, &TextFIR, NBioAPI_FALSE);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot retrieve text-encoded FIR");
return Py_BuildValue("s", TextFIR.TextFIR);
}
static PyMethodDef BspMethods[] = {
{"open", bsp_open, 0, "open bsp device"},
{"close", bsp_close, METH_VARARGS, "close bsp device"},
{"capture", bsp_capture, METH_VARARGS, "capture fingerprint"},
{"verify", bsp_verify, METH_VARARGS, "verify fingerprints"},
+ {"payload", bsp_payload, METH_VARARGS, "set FIR payload"},
{"free_fir", bsp_free_fir, METH_VARARGS, "release FIR memory"},
{"text_fir", bsp_text_fir, METH_VARARGS, "return text-encoded FIR"},
{NULL, NULL, 0, NULL},
};
-PyMODINIT_FUNC init_bsp_module(void)
+PyMODINIT_FUNC init_bsp_core(void)
{
- PyObject *m;
-
- Py_InitModule("_bsp_module", BspMethods);
+ Py_InitModule("_bsp_core", BspMethods);
}
|
fiorix/nitgen-bsp
|
a372b3f0b692bb7becb59c9c937184fb1c06c7f9
|
added support for 'user data'
|
diff --git a/TODO b/TODO
index 075139d..af41d65 100644
--- a/TODO
+++ b/TODO
@@ -1,3 +1,2 @@
support multiple devices
-support for adding user data in FIR
add support for nitgen's search engine
|
fiorix/nitgen-bsp
|
d37d90550d48a718f449e99f3b8ae524ea1cf13c
|
added documentation
|
diff --git a/BUGS b/BUGS
new file mode 100644
index 0000000..23a2142
--- /dev/null
+++ b/BUGS
@@ -0,0 +1 @@
+allow non-root users to communicate (actually depends on /dev/ permissions)
diff --git a/NitgenBSP/__init__.py b/NitgenBSP/__init__.py
index 090f386..8b4a6b2 100644
--- a/NitgenBSP/__init__.py
+++ b/NitgenBSP/__init__.py
@@ -1,61 +1,92 @@
#!/usr/bin/env python
# coding: utf-8
from PIL import Image
from NitgenBSP import _bsp_module
+"""Nitgen fingerprint recognition API"""
+
class FingerText(str):
+ """The Text-Encoded version of a fingerprint's FIR.
+ """
pass
class Finger(object):
+ """The Finger class provides the FIR Handle, raw
+ image buffer provided by the device, as well as
+ image dimentions (width and height).
+ It may also convert the raw buffer to a PIL image,
+ as well as the Text-Encoded FIR.
+ """
def __init__(self, handler, data, width, height):
self.__handler = handler
self.buffer, self.FIR = data
self.width = width
self.height = height
def text(self):
+ """Return the Text-Encoded version of the FIR for this
+ fingerprint, which may be used to store the fingerprint
+ in a database as well as later verification.
+ """
return FingerText(_bsp_module.text_fir(self.__handler, self.FIR))
def image(self):
+ """Return the PIL image of this fingerprint, which may be
+ used to be saved on disk as JPG, PNG, etc.
+ """
return Image.fromstring("L",
(self.width, self.height), self.buffer)
def __del__(self):
_bsp_module.free_fir(self.__handler, self.FIR)
class Handler:
+ """A Nitgen device handler
+ """
def __init__(self):
+ """Initialize the Nitgen API and open the first available device
+ using the auto-detection mode.
+ """
self.__bsp = _bsp_module.open()
self.__handler = self.__bsp[0]
self.__image_width = self.__bsp[1]
self.__image_height = self.__bsp[2]
def capture(self):
+ """Capture a fingerprint from the device and return an instance
+ of the Finger class.
+ """
return Finger(self.__handler,
_bsp_module.capture(*self.__bsp),
self.__image_width, self.__image_height)
def verify(self, cap1, cap2):
+ """Perform verification of two fingerprints by receiving either
+ a pair of Finger or FingerText instances.
+ Returns 0 or 1, depending on finger verification.
+ """
if isinstance(cap1, Finger):
cap1 = cap1.FIR
elif isinstance(cap1, FingerText):
cap1 = str(cap1)
else:
raise TypeError("cap1 must be an instance of Finger or FingerText")
if isinstance(cap2, Finger):
cap2 = cap2.FIR
elif isinstance(cap2, FingerText):
cap2 = str(cap2)
else:
raise TypeError("cap2 must be an instance of Finger or FingerText")
if type(cap1) != type(cap2):
raise TypeError("cannot verify Finger against FingerText and vice-versa")
return _bsp_module.verify(self.__handler, cap1, cap2)
def close(self):
+ """Close the currently opened Nitgen device
+ """
_bsp_module.close(self.__handler)
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..6049c9e
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,53 @@
+=========
+NitgenBSP
+=========
+:Info: See `github <http://github.com/fiorix/nitgen-bsp>`_ for the latest source.
+:Author: Alexandre Fiori <[email protected]>
+
+About
+=====
+
+NitgenBSP is a Python extentension based on the `Nitgen SDK for Linux <http://www.nitgen.com/eng/product/enbsp_sdk.html>`_. It currently supports Nitgen fingerprint recognition devices such as `Fingkey Hamster <http://www.nitgen.com/eng/product/finkey.html>`_ and `Fingkey Hamster II <http://www.nitgen.com/eng/product/finkey2.html>`_.
+
+Implementation details
+----------------------
+
+- It has been tested under Ubuntu Linux 9.10
+- Require root access level (actually depends on file permission of /dev/nitgen0)
+- Only supports the auto-detection mode (I don't have 2 devices do try manual selection)
+- Supports verification with the FIR Handle and Text-Encoded FIR (not the FULL FIR)
+- Allows the Text-Encoded FIR to be saved on remote database for later verification
+- Text-Encoded FIR does not allow multi-byte encoding
+- Ships with `PIL <http://www.pythonware.com/products/pil/>`_ support and allows saving fingerprint images as JPG, PNG, etc
+
+Documentation and Examples
+==========================
+
+The source code ships with built-in Python Docstring documentation for class reference. It also ships with examples in the `examples/ <http://github.com/fiorix/nitgen-bsp/tree/master/examples/>`_ subdirectory.
+
+However, using NitgenBSP is pretty straightforward even for those with no experience with biometric devices.
+Here is an example of simple usage::
+
+ #!/usr/bin/env python
+ # coding: utf-8
+
+ import NitgenBSP
+
+ if __name__ == "__main__":
+ handler = NitgenBSP.Handler()
+
+ finger = handler.capture()
+ image = finger.image()
+ image.save("out.png")
+
+ print "your fingerprint text-encoded FIR is:", finger.text()
+
+In the near future I'll provide support for the SDK's Search Engine API, and probably other features such as manual device selection. See the `TODO <http://github.com/fiorix/nitgen-bsp/tree/master/TODO>`_ for details.
+
+Credits
+=======
+Thanks to (in no particular order):
+
+- Nitgen Brazil
+
+ - For providing documentation and allowing this code do be published
diff --git a/TODO b/TODO
new file mode 100644
index 0000000..075139d
--- /dev/null
+++ b/TODO
@@ -0,0 +1,3 @@
+support multiple devices
+support for adding user data in FIR
+add support for nitgen's search engine
|
fiorix/nitgen-bsp
|
fc93f59f5ea1d99fef76eb8c9f7a60a9164f6569
|
removed unused variable
|
diff --git a/NitgenBSP/bsp_module.c b/NitgenBSP/bsp_module.c
index b3fcfa9..b5a6777 100644
--- a/NitgenBSP/bsp_module.c
+++ b/NitgenBSP/bsp_module.c
@@ -1,185 +1,179 @@
#include <string.h>
#include <Python.h>
#include <NBioAPI.h>
struct capture_data {
int image_width;
int image_height;
int buffer_size;
unsigned char *buffer;
};
static PyObject *bsp_open(PyObject *self, PyObject *args)
{
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
NBioAPI_VERSION m_Version;
NBioAPI_UINT32 dev_cnt;
NBioAPI_DEVICE_ID *dev_list;
NBioAPI_DEVICE_INFO_0 m_DeviceInfo0;
err = NBioAPI_Init(&m_hBSP);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot initialize NBioAPI");
NBioAPI_GetVersion(m_hBSP, &m_Version);
err = NBioAPI_EnumerateDevice(m_hBSP, &dev_cnt, &dev_list);
if(dev_cnt == 0)
return PyErr_Format(PyExc_RuntimeError, "device not found");
err = NBioAPI_OpenDevice(m_hBSP, NBioAPI_DEVICE_ID_AUTO);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot open device");
memset(&m_DeviceInfo0, 0, sizeof(NBioAPI_DEVICE_INFO_0));
NBioAPI_GetDeviceInfo(m_hBSP, NBioAPI_DEVICE_ID_AUTO, 0, &m_DeviceInfo0);
return Py_BuildValue("(iii)", m_hBSP,
m_DeviceInfo0.ImageWidth, m_DeviceInfo0.ImageHeight);
}
static PyObject *bsp_close(PyObject *self, PyObject *args)
{
NBioAPI_HANDLE m_hBSP;
if(!PyArg_ParseTuple(args, "i", &m_hBSP))
return PyErr_Format(PyExc_TypeError, "invalid bsp handler");
NBioAPI_CloseDevice(m_hBSP, NBioAPI_DEVICE_ID_AUTO);
Py_INCREF(Py_None);
return Py_None;
}
NBioAPI_RETURN MyCaptureCallback(NBioAPI_WINDOW_CALLBACK_PARAM_PTR_0 pCallbackParam, NBioAPI_VOID_PTR pUserParam)
{
struct capture_data *data = (struct capture_data *) pUserParam;
memcpy(data->buffer, pCallbackParam->lpImageBuf, data->buffer_size);
return NBioAPIERROR_NONE;
}
static PyObject *bsp_capture(PyObject *self, PyObject *args)
{
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
NBioAPI_FIR_HANDLE capFIR;
NBioAPI_WINDOW_OPTION winOption;
struct capture_data data;
memset(&data, 0, sizeof(data));
if(!PyArg_ParseTuple(args, "iii", &m_hBSP, &data.image_width, &data.image_height))
return PyErr_Format(PyExc_TypeError, "invalid arguments");
data.buffer_size = data.image_width * data.image_height;
data.buffer = PyMem_Malloc(data.buffer_size);
memset(&winOption, 0, sizeof(NBioAPI_WINDOW_OPTION));
winOption.Length = sizeof(NBioAPI_WINDOW_OPTION);
winOption.CaptureCallBackInfo.CallBackType = 0;
winOption.CaptureCallBackInfo.CallBackFunction = MyCaptureCallback;
winOption.CaptureCallBackInfo.UserCallBackParam = &data;
capFIR = NBioAPI_INVALID_HANDLE;
err = NBioAPI_Capture(m_hBSP, NBioAPI_FIR_PURPOSE_VERIFY, &capFIR, -1, NULL, &winOption);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot capture fingerprint");
return Py_BuildValue("(s#i)", data.buffer, data.buffer_size, capFIR);
}
static PyObject *bsp_verify(PyObject *self, PyObject *args)
{
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
NBioAPI_INPUT_FIR cap1, cap2;
NBioAPI_BOOL bResult = NBioAPI_FALSE;
NBioAPI_FIR_HANDLE fir1_handle, fir2_handle;
NBioAPI_FIR_TEXTENCODE fir1_text, fir2_text;
PyObject *rawF1, *rawF2;
if(!PyArg_ParseTuple(args, "iOO", &m_hBSP, &rawF1, &rawF2))
return PyErr_Format(PyExc_TypeError, "invalid arguments");
/* determine format of FIR 1: handler or text */
if(PyInt_Check(rawF1)) {
PyArg_Parse(rawF1, "i", &fir1_handle);
cap1.Form = NBioAPI_FIR_FORM_HANDLE;
cap1.InputFIR.FIRinBSP = &fir1_handle;
} else if(PyString_Check(rawF1)) {
- char *text_stream;
- PyArg_Parse(rawF1, "s", &text_stream);
+ PyArg_Parse(rawF1, "s", &fir1_text.TextFIR);
fir1_text.IsWideChar = NBioAPI_FALSE;
- fir1_text.TextFIR = text_stream;
cap1.Form = NBioAPI_FIR_FORM_TEXTENCODE;
cap1.InputFIR.TextFIR = &fir1_text;
} else
return PyErr_Format(PyExc_TypeError, "unknown format of cap1");
/* determine format of FIR 2: handler or text */
if(PyInt_Check(rawF2)) {
PyArg_Parse(rawF2, "i", &fir2_handle);
cap2.Form = NBioAPI_FIR_FORM_HANDLE;
cap2.InputFIR.FIRinBSP = &fir2_handle;
} else if(PyString_Check(rawF2)) {
- char *text_stream;
- PyArg_Parse(rawF2, "s", &text_stream);
+ PyArg_Parse(rawF2, "s", &fir2_text.TextFIR);
fir2_text.IsWideChar = NBioAPI_FALSE;
- fir2_text.TextFIR = text_stream;
cap2.Form = NBioAPI_FIR_FORM_TEXTENCODE;
cap2.InputFIR.TextFIR = &fir2_text;
} else
return PyErr_Format(PyExc_TypeError, "unknown format of cap2");
/* warning: cannot verify text VS handle and vice-versa */
err = NBioAPI_VerifyMatch(m_hBSP, &cap1, &cap2, &bResult, NULL);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot verify");
return Py_BuildValue("i", bResult);
}
static PyObject *bsp_free_fir(PyObject *self, PyObject *args)
{
NBioAPI_HANDLE m_hBSP;
NBioAPI_FIR_HANDLE fir;
if(!PyArg_ParseTuple(args, "ii", &m_hBSP, &fir))
return PyErr_Format(PyExc_TypeError, "invalid arguments");
NBioAPI_FreeFIRHandle(m_hBSP, fir);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *bsp_text_fir(PyObject *self, PyObject *args)
{
NBioAPI_RETURN err;
NBioAPI_HANDLE m_hBSP;
NBioAPI_FIR_HANDLE fir;
NBioAPI_FIR_TEXTENCODE TextFIR;
if(!PyArg_ParseTuple(args, "ii", &m_hBSP, &fir))
return PyErr_Format(PyExc_TypeError, "invalid arguments");
err = NBioAPI_GetTextFIRFromHandle(m_hBSP, fir, &TextFIR, NBioAPI_FALSE);
if(err != NBioAPIERROR_NONE)
return PyErr_Format(PyExc_RuntimeError, "cannot retrieve text-encoded FIR");
return Py_BuildValue("s", TextFIR.TextFIR);
}
static PyMethodDef BspMethods[] = {
{"open", bsp_open, 0, "open bsp device"},
{"close", bsp_close, METH_VARARGS, "close bsp device"},
{"capture", bsp_capture, METH_VARARGS, "capture fingerprint"},
{"verify", bsp_verify, METH_VARARGS, "verify fingerprints"},
{"free_fir", bsp_free_fir, METH_VARARGS, "release FIR memory"},
{"text_fir", bsp_text_fir, METH_VARARGS, "return text-encoded FIR"},
{NULL, NULL, 0, NULL},
};
PyMODINIT_FUNC init_bsp_module(void)
{
PyObject *m;
- m = Py_InitModule("_bsp_module", BspMethods);
- if(m == NULL)
- return;
+ Py_InitModule("_bsp_module", BspMethods);
}
|
fiorix/nitgen-bsp
|
7f73c98caea08a77dee0e53b4c68d0108e423fad
|
added examples
|
diff --git a/examples/save_image.py b/examples/save_image.py
new file mode 100755
index 0000000..d12eae9
--- /dev/null
+++ b/examples/save_image.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python
+# coding: utf-8
+
+import os
+import NitgenBSP
+
+if __name__ == "__main__":
+ assert os.getuid() == 0, "please run as root"
+
+ # get the bsp handler
+ handler = NitgenBSP.Handler()
+
+ raw_input("place your finger in the reader and press enter: ")
+
+ # get the fingerprint
+ finger = handler.capture()
+
+ filename = raw_input("enter the filename to save your fingerprint [out.jpg, out.png, out.gif]: ")
+
+ # get the PIL image
+ image = finger.image()
+ image.save(filename)
+
+ # close the handler
+ handler.close()
diff --git a/examples/verify_fingers.py b/examples/verify_fingers.py
new file mode 100755
index 0000000..af6a571
--- /dev/null
+++ b/examples/verify_fingers.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python
+# coding: utf-8
+
+import os
+import NitgenBSP
+
+if __name__ == "__main__":
+ assert os.getuid() == 0, "please run as root"
+
+ # get the bsp handler
+ handler = NitgenBSP.Handler()
+
+ raw_input("place your finger in the device and press enter: ")
+ cap1 = handler.capture()
+
+ raw_input("ok. do it again... press enter when ready: ")
+ cap2 = handler.capture()
+
+ # default verification method is via FIR handler in the device
+ # but it may also be done by the text-encoded FIR, like this:
+ # handler.verify(cap1.text(), cap2.text())
+ match = handler.verify(cap1, cap2)
+ print "your fingerprints " + (match and "do match" or "do not match")
+
+ # that's it
+ handler.close()
|
fiorix/nitgen-bsp
|
b2e49dc485cc557b9e9ab0c8a13f9625c8a4eaa9
|
renamed to NitgenBSP
|
diff --git a/NitgenBSP/__init__.py b/NitgenBSP/__init__.py
new file mode 100644
index 0000000..090f386
--- /dev/null
+++ b/NitgenBSP/__init__.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+# coding: utf-8
+
+from PIL import Image
+from NitgenBSP import _bsp_module
+
+class FingerText(str):
+ pass
+
+class Finger(object):
+ def __init__(self, handler, data, width, height):
+ self.__handler = handler
+ self.buffer, self.FIR = data
+ self.width = width
+ self.height = height
+
+ def text(self):
+ return FingerText(_bsp_module.text_fir(self.__handler, self.FIR))
+
+ def image(self):
+ return Image.fromstring("L",
+ (self.width, self.height), self.buffer)
+
+ def __del__(self):
+ _bsp_module.free_fir(self.__handler, self.FIR)
+
+
+class Handler:
+ def __init__(self):
+ self.__bsp = _bsp_module.open()
+ self.__handler = self.__bsp[0]
+ self.__image_width = self.__bsp[1]
+ self.__image_height = self.__bsp[2]
+
+ def capture(self):
+ return Finger(self.__handler,
+ _bsp_module.capture(*self.__bsp),
+ self.__image_width, self.__image_height)
+
+ def verify(self, cap1, cap2):
+ if isinstance(cap1, Finger):
+ cap1 = cap1.FIR
+ elif isinstance(cap1, FingerText):
+ cap1 = str(cap1)
+ else:
+ raise TypeError("cap1 must be an instance of Finger or FingerText")
+
+ if isinstance(cap2, Finger):
+ cap2 = cap2.FIR
+ elif isinstance(cap2, FingerText):
+ cap2 = str(cap2)
+ else:
+ raise TypeError("cap2 must be an instance of Finger or FingerText")
+
+ if type(cap1) != type(cap2):
+ raise TypeError("cannot verify Finger against FingerText and vice-versa")
+
+ return _bsp_module.verify(self.__handler, cap1, cap2)
+
+ def close(self):
+ _bsp_module.close(self.__handler)
diff --git a/NitgenBSP/bsp_module.c b/NitgenBSP/bsp_module.c
new file mode 100644
index 0000000..b3fcfa9
--- /dev/null
+++ b/NitgenBSP/bsp_module.c
@@ -0,0 +1,185 @@
+#include <string.h>
+#include <Python.h>
+#include <NBioAPI.h>
+
+struct capture_data {
+ int image_width;
+ int image_height;
+ int buffer_size;
+ unsigned char *buffer;
+};
+
+static PyObject *bsp_open(PyObject *self, PyObject *args)
+{
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_VERSION m_Version;
+ NBioAPI_UINT32 dev_cnt;
+ NBioAPI_DEVICE_ID *dev_list;
+ NBioAPI_DEVICE_INFO_0 m_DeviceInfo0;
+
+ err = NBioAPI_Init(&m_hBSP);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot initialize NBioAPI");
+
+ NBioAPI_GetVersion(m_hBSP, &m_Version);
+ err = NBioAPI_EnumerateDevice(m_hBSP, &dev_cnt, &dev_list);
+ if(dev_cnt == 0)
+ return PyErr_Format(PyExc_RuntimeError, "device not found");
+
+ err = NBioAPI_OpenDevice(m_hBSP, NBioAPI_DEVICE_ID_AUTO);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot open device");
+
+ memset(&m_DeviceInfo0, 0, sizeof(NBioAPI_DEVICE_INFO_0));
+ NBioAPI_GetDeviceInfo(m_hBSP, NBioAPI_DEVICE_ID_AUTO, 0, &m_DeviceInfo0);
+
+ return Py_BuildValue("(iii)", m_hBSP,
+ m_DeviceInfo0.ImageWidth, m_DeviceInfo0.ImageHeight);
+}
+
+static PyObject *bsp_close(PyObject *self, PyObject *args)
+{
+ NBioAPI_HANDLE m_hBSP;
+ if(!PyArg_ParseTuple(args, "i", &m_hBSP))
+ return PyErr_Format(PyExc_TypeError, "invalid bsp handler");
+
+ NBioAPI_CloseDevice(m_hBSP, NBioAPI_DEVICE_ID_AUTO);
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+NBioAPI_RETURN MyCaptureCallback(NBioAPI_WINDOW_CALLBACK_PARAM_PTR_0 pCallbackParam, NBioAPI_VOID_PTR pUserParam)
+{
+ struct capture_data *data = (struct capture_data *) pUserParam;
+ memcpy(data->buffer, pCallbackParam->lpImageBuf, data->buffer_size);
+ return NBioAPIERROR_NONE;
+}
+
+static PyObject *bsp_capture(PyObject *self, PyObject *args)
+{
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_FIR_HANDLE capFIR;
+ NBioAPI_WINDOW_OPTION winOption;
+ struct capture_data data;
+
+ memset(&data, 0, sizeof(data));
+ if(!PyArg_ParseTuple(args, "iii", &m_hBSP, &data.image_width, &data.image_height))
+ return PyErr_Format(PyExc_TypeError, "invalid arguments");
+
+ data.buffer_size = data.image_width * data.image_height;
+ data.buffer = PyMem_Malloc(data.buffer_size);
+
+ memset(&winOption, 0, sizeof(NBioAPI_WINDOW_OPTION));
+ winOption.Length = sizeof(NBioAPI_WINDOW_OPTION);
+ winOption.CaptureCallBackInfo.CallBackType = 0;
+ winOption.CaptureCallBackInfo.CallBackFunction = MyCaptureCallback;
+ winOption.CaptureCallBackInfo.UserCallBackParam = &data;
+
+ capFIR = NBioAPI_INVALID_HANDLE;
+ err = NBioAPI_Capture(m_hBSP, NBioAPI_FIR_PURPOSE_VERIFY, &capFIR, -1, NULL, &winOption);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot capture fingerprint");
+
+ return Py_BuildValue("(s#i)", data.buffer, data.buffer_size, capFIR);
+}
+
+static PyObject *bsp_verify(PyObject *self, PyObject *args)
+{
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_INPUT_FIR cap1, cap2;
+ NBioAPI_BOOL bResult = NBioAPI_FALSE;
+ NBioAPI_FIR_HANDLE fir1_handle, fir2_handle;
+ NBioAPI_FIR_TEXTENCODE fir1_text, fir2_text;
+ PyObject *rawF1, *rawF2;
+
+ if(!PyArg_ParseTuple(args, "iOO", &m_hBSP, &rawF1, &rawF2))
+ return PyErr_Format(PyExc_TypeError, "invalid arguments");
+
+ /* determine format of FIR 1: handler or text */
+ if(PyInt_Check(rawF1)) {
+ PyArg_Parse(rawF1, "i", &fir1_handle);
+ cap1.Form = NBioAPI_FIR_FORM_HANDLE;
+ cap1.InputFIR.FIRinBSP = &fir1_handle;
+ } else if(PyString_Check(rawF1)) {
+ char *text_stream;
+ PyArg_Parse(rawF1, "s", &text_stream);
+ fir1_text.IsWideChar = NBioAPI_FALSE;
+ fir1_text.TextFIR = text_stream;
+ cap1.Form = NBioAPI_FIR_FORM_TEXTENCODE;
+ cap1.InputFIR.TextFIR = &fir1_text;
+ } else
+ return PyErr_Format(PyExc_TypeError, "unknown format of cap1");
+
+ /* determine format of FIR 2: handler or text */
+ if(PyInt_Check(rawF2)) {
+ PyArg_Parse(rawF2, "i", &fir2_handle);
+ cap2.Form = NBioAPI_FIR_FORM_HANDLE;
+ cap2.InputFIR.FIRinBSP = &fir2_handle;
+ } else if(PyString_Check(rawF2)) {
+ char *text_stream;
+ PyArg_Parse(rawF2, "s", &text_stream);
+ fir2_text.IsWideChar = NBioAPI_FALSE;
+ fir2_text.TextFIR = text_stream;
+ cap2.Form = NBioAPI_FIR_FORM_TEXTENCODE;
+ cap2.InputFIR.TextFIR = &fir2_text;
+ } else
+ return PyErr_Format(PyExc_TypeError, "unknown format of cap2");
+
+ /* warning: cannot verify text VS handle and vice-versa */
+ err = NBioAPI_VerifyMatch(m_hBSP, &cap1, &cap2, &bResult, NULL);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot verify");
+ return Py_BuildValue("i", bResult);
+}
+
+static PyObject *bsp_free_fir(PyObject *self, PyObject *args)
+{
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_FIR_HANDLE fir;
+
+ if(!PyArg_ParseTuple(args, "ii", &m_hBSP, &fir))
+ return PyErr_Format(PyExc_TypeError, "invalid arguments");
+
+ NBioAPI_FreeFIRHandle(m_hBSP, fir);
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+static PyObject *bsp_text_fir(PyObject *self, PyObject *args)
+{
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_FIR_HANDLE fir;
+ NBioAPI_FIR_TEXTENCODE TextFIR;
+
+ if(!PyArg_ParseTuple(args, "ii", &m_hBSP, &fir))
+ return PyErr_Format(PyExc_TypeError, "invalid arguments");
+
+ err = NBioAPI_GetTextFIRFromHandle(m_hBSP, fir, &TextFIR, NBioAPI_FALSE);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot retrieve text-encoded FIR");
+
+ return Py_BuildValue("s", TextFIR.TextFIR);
+}
+
+static PyMethodDef BspMethods[] = {
+ {"open", bsp_open, 0, "open bsp device"},
+ {"close", bsp_close, METH_VARARGS, "close bsp device"},
+ {"capture", bsp_capture, METH_VARARGS, "capture fingerprint"},
+ {"verify", bsp_verify, METH_VARARGS, "verify fingerprints"},
+ {"free_fir", bsp_free_fir, METH_VARARGS, "release FIR memory"},
+ {"text_fir", bsp_text_fir, METH_VARARGS, "return text-encoded FIR"},
+ {NULL, NULL, 0, NULL},
+};
+
+PyMODINIT_FUNC init_bsp_module(void)
+{
+ PyObject *m;
+
+ m = Py_InitModule("_bsp_module", BspMethods);
+ if(m == NULL)
+ return;
+}
|
fiorix/nitgen-bsp
|
91a038c8e579593c7a2a78ec158e25c3a63bff9f
|
initial import
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..903b180
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+*.pyc
+*.swp
+*.o
+build/
diff --git a/BSP/__init__.py b/BSP/__init__.py
new file mode 100644
index 0000000..f144dee
--- /dev/null
+++ b/BSP/__init__.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+# coding: utf-8
+
+from BSP import _bsp_module
+from PIL import Image
+
+class FingerText(str):
+ pass
+
+class Finger(object):
+ def __init__(self, handler, data, width, height):
+ self.__handler = handler
+ self.buffer, self.FIR = data
+ self.width = width
+ self.height = height
+
+ def text(self):
+ return FingerText(_bsp_module.text_fir(self.__handler, self.FIR))
+
+ def image(self):
+ return Image.fromstring("L",
+ (self.width, self.height), self.buffer)
+
+ def __del__(self):
+ _bsp_module.free_fir(self.__handler, self.FIR)
+
+
+class Handler:
+ def __init__(self):
+ self.__bsp = _bsp_module.open()
+ self.__handler = self.__bsp[0]
+ self.__image_width = self.__bsp[1]
+ self.__image_height = self.__bsp[2]
+
+ def capture(self):
+ return Finger(self.__handler,
+ _bsp_module.capture(*self.__bsp),
+ self.__image_width, self.__image_height)
+
+ def verify(self, cap1, cap2):
+ if isinstance(cap1, Finger):
+ cap1 = cap1.FIR
+ elif isinstance(cap1, FingerText):
+ cap1 = str(cap1)
+ else:
+ raise TypeError("cap1 must be an instance of Finger or FingerText")
+
+ if isinstance(cap2, Finger):
+ cap2 = cap2.FIR
+ elif isinstance(cap2, FingerText):
+ cap2 = str(cap2)
+ else:
+ raise TypeError("cap2 must be an instance of Finger or FingerText")
+
+ if type(cap1) != type(cap2):
+ raise TypeError("cannot verify Finger against FingerText and vice-versa")
+
+ return _bsp_module.verify(self.__handler, cap1, cap2)
+
+ def close(self):
+ _bsp_module.close(self.__handler)
diff --git a/BSP/bsp_module.c b/BSP/bsp_module.c
new file mode 100644
index 0000000..b3fcfa9
--- /dev/null
+++ b/BSP/bsp_module.c
@@ -0,0 +1,185 @@
+#include <string.h>
+#include <Python.h>
+#include <NBioAPI.h>
+
+struct capture_data {
+ int image_width;
+ int image_height;
+ int buffer_size;
+ unsigned char *buffer;
+};
+
+static PyObject *bsp_open(PyObject *self, PyObject *args)
+{
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_VERSION m_Version;
+ NBioAPI_UINT32 dev_cnt;
+ NBioAPI_DEVICE_ID *dev_list;
+ NBioAPI_DEVICE_INFO_0 m_DeviceInfo0;
+
+ err = NBioAPI_Init(&m_hBSP);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot initialize NBioAPI");
+
+ NBioAPI_GetVersion(m_hBSP, &m_Version);
+ err = NBioAPI_EnumerateDevice(m_hBSP, &dev_cnt, &dev_list);
+ if(dev_cnt == 0)
+ return PyErr_Format(PyExc_RuntimeError, "device not found");
+
+ err = NBioAPI_OpenDevice(m_hBSP, NBioAPI_DEVICE_ID_AUTO);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot open device");
+
+ memset(&m_DeviceInfo0, 0, sizeof(NBioAPI_DEVICE_INFO_0));
+ NBioAPI_GetDeviceInfo(m_hBSP, NBioAPI_DEVICE_ID_AUTO, 0, &m_DeviceInfo0);
+
+ return Py_BuildValue("(iii)", m_hBSP,
+ m_DeviceInfo0.ImageWidth, m_DeviceInfo0.ImageHeight);
+}
+
+static PyObject *bsp_close(PyObject *self, PyObject *args)
+{
+ NBioAPI_HANDLE m_hBSP;
+ if(!PyArg_ParseTuple(args, "i", &m_hBSP))
+ return PyErr_Format(PyExc_TypeError, "invalid bsp handler");
+
+ NBioAPI_CloseDevice(m_hBSP, NBioAPI_DEVICE_ID_AUTO);
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+NBioAPI_RETURN MyCaptureCallback(NBioAPI_WINDOW_CALLBACK_PARAM_PTR_0 pCallbackParam, NBioAPI_VOID_PTR pUserParam)
+{
+ struct capture_data *data = (struct capture_data *) pUserParam;
+ memcpy(data->buffer, pCallbackParam->lpImageBuf, data->buffer_size);
+ return NBioAPIERROR_NONE;
+}
+
+static PyObject *bsp_capture(PyObject *self, PyObject *args)
+{
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_FIR_HANDLE capFIR;
+ NBioAPI_WINDOW_OPTION winOption;
+ struct capture_data data;
+
+ memset(&data, 0, sizeof(data));
+ if(!PyArg_ParseTuple(args, "iii", &m_hBSP, &data.image_width, &data.image_height))
+ return PyErr_Format(PyExc_TypeError, "invalid arguments");
+
+ data.buffer_size = data.image_width * data.image_height;
+ data.buffer = PyMem_Malloc(data.buffer_size);
+
+ memset(&winOption, 0, sizeof(NBioAPI_WINDOW_OPTION));
+ winOption.Length = sizeof(NBioAPI_WINDOW_OPTION);
+ winOption.CaptureCallBackInfo.CallBackType = 0;
+ winOption.CaptureCallBackInfo.CallBackFunction = MyCaptureCallback;
+ winOption.CaptureCallBackInfo.UserCallBackParam = &data;
+
+ capFIR = NBioAPI_INVALID_HANDLE;
+ err = NBioAPI_Capture(m_hBSP, NBioAPI_FIR_PURPOSE_VERIFY, &capFIR, -1, NULL, &winOption);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot capture fingerprint");
+
+ return Py_BuildValue("(s#i)", data.buffer, data.buffer_size, capFIR);
+}
+
+static PyObject *bsp_verify(PyObject *self, PyObject *args)
+{
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_INPUT_FIR cap1, cap2;
+ NBioAPI_BOOL bResult = NBioAPI_FALSE;
+ NBioAPI_FIR_HANDLE fir1_handle, fir2_handle;
+ NBioAPI_FIR_TEXTENCODE fir1_text, fir2_text;
+ PyObject *rawF1, *rawF2;
+
+ if(!PyArg_ParseTuple(args, "iOO", &m_hBSP, &rawF1, &rawF2))
+ return PyErr_Format(PyExc_TypeError, "invalid arguments");
+
+ /* determine format of FIR 1: handler or text */
+ if(PyInt_Check(rawF1)) {
+ PyArg_Parse(rawF1, "i", &fir1_handle);
+ cap1.Form = NBioAPI_FIR_FORM_HANDLE;
+ cap1.InputFIR.FIRinBSP = &fir1_handle;
+ } else if(PyString_Check(rawF1)) {
+ char *text_stream;
+ PyArg_Parse(rawF1, "s", &text_stream);
+ fir1_text.IsWideChar = NBioAPI_FALSE;
+ fir1_text.TextFIR = text_stream;
+ cap1.Form = NBioAPI_FIR_FORM_TEXTENCODE;
+ cap1.InputFIR.TextFIR = &fir1_text;
+ } else
+ return PyErr_Format(PyExc_TypeError, "unknown format of cap1");
+
+ /* determine format of FIR 2: handler or text */
+ if(PyInt_Check(rawF2)) {
+ PyArg_Parse(rawF2, "i", &fir2_handle);
+ cap2.Form = NBioAPI_FIR_FORM_HANDLE;
+ cap2.InputFIR.FIRinBSP = &fir2_handle;
+ } else if(PyString_Check(rawF2)) {
+ char *text_stream;
+ PyArg_Parse(rawF2, "s", &text_stream);
+ fir2_text.IsWideChar = NBioAPI_FALSE;
+ fir2_text.TextFIR = text_stream;
+ cap2.Form = NBioAPI_FIR_FORM_TEXTENCODE;
+ cap2.InputFIR.TextFIR = &fir2_text;
+ } else
+ return PyErr_Format(PyExc_TypeError, "unknown format of cap2");
+
+ /* warning: cannot verify text VS handle and vice-versa */
+ err = NBioAPI_VerifyMatch(m_hBSP, &cap1, &cap2, &bResult, NULL);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot verify");
+ return Py_BuildValue("i", bResult);
+}
+
+static PyObject *bsp_free_fir(PyObject *self, PyObject *args)
+{
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_FIR_HANDLE fir;
+
+ if(!PyArg_ParseTuple(args, "ii", &m_hBSP, &fir))
+ return PyErr_Format(PyExc_TypeError, "invalid arguments");
+
+ NBioAPI_FreeFIRHandle(m_hBSP, fir);
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+static PyObject *bsp_text_fir(PyObject *self, PyObject *args)
+{
+ NBioAPI_RETURN err;
+ NBioAPI_HANDLE m_hBSP;
+ NBioAPI_FIR_HANDLE fir;
+ NBioAPI_FIR_TEXTENCODE TextFIR;
+
+ if(!PyArg_ParseTuple(args, "ii", &m_hBSP, &fir))
+ return PyErr_Format(PyExc_TypeError, "invalid arguments");
+
+ err = NBioAPI_GetTextFIRFromHandle(m_hBSP, fir, &TextFIR, NBioAPI_FALSE);
+ if(err != NBioAPIERROR_NONE)
+ return PyErr_Format(PyExc_RuntimeError, "cannot retrieve text-encoded FIR");
+
+ return Py_BuildValue("s", TextFIR.TextFIR);
+}
+
+static PyMethodDef BspMethods[] = {
+ {"open", bsp_open, 0, "open bsp device"},
+ {"close", bsp_close, METH_VARARGS, "close bsp device"},
+ {"capture", bsp_capture, METH_VARARGS, "capture fingerprint"},
+ {"verify", bsp_verify, METH_VARARGS, "verify fingerprints"},
+ {"free_fir", bsp_free_fir, METH_VARARGS, "release FIR memory"},
+ {"text_fir", bsp_text_fir, METH_VARARGS, "return text-encoded FIR"},
+ {NULL, NULL, 0, NULL},
+};
+
+PyMODINIT_FUNC init_bsp_module(void)
+{
+ PyObject *m;
+
+ m = Py_InitModule("_bsp_module", BspMethods);
+ if(m == NULL)
+ return;
+}
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..a954eea
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,20 @@
+#!/usr/bin/env python
+# coding: utf-8
+
+from distutils.core import setup, Extension
+
+setup(
+ name="bsp",
+ version="0.1",
+ author="Alexandre Fiori",
+ author_email="[email protected]",
+ url="http://github.com/fiorix/nitgen_bsp",
+ packages=["BSP"],
+ ext_modules=[
+ Extension("BSP/_bsp_module", [
+ "BSP/bsp_module.c",
+ ],
+ include_dirs=["/usr/local/NITGEN/eNBSP/include"],
+ libraries=["pthread", "NBioBSP"], )
+ ]
+)
|
vits/good_enough_form_builder
|
5b70ac67d41fe4c64f190ecac945ba55fdd44e96
|
Fixed: use class attribute as inner element class only for plain fields.
|
diff --git a/lib/good_enough_form_builder.rb b/lib/good_enough_form_builder.rb
index 9748052..66599ab 100644
--- a/lib/good_enough_form_builder.rb
+++ b/lib/good_enough_form_builder.rb
@@ -1,202 +1,205 @@
module GoodEnoughFormBuilder
class Builder < ActionView::Helpers::FormBuilder
@@templates_path = "forms/"
cattr_accessor :templates_path
def wrapper(locals)
type = locals[:type]
body = locals[:body]
begin
@template.render :partial => template_name(type), :locals => locals
rescue ActionView::MissingTemplate
if type == 'field'
body
else
begin
@template.render :partial => template_name('field'), :locals => locals
rescue ActionView::MissingTemplate
body
end
end
end
end
def buttons_wrapper(locals)
body = locals[:body]
begin
@template.render :partial => template_name('buttons'), :locals => locals
rescue ActionView::MissingTemplate
body
end
end
def field(*args, &block)
options = args.extract_options!
locals = template_locals(options)
locals.merge!({
:method => nil,
:type => 'field',
:body => @template.capture(&block)
})
wrapper(locals)
end
['text_field', 'file_field', 'password_field', 'text_area',
'select', 'collection_select'].each do |name|
define_method(name) do |method, *args|
options = args.extract_options!
plain = options.delete(:plain)
locals = template_locals(options)
- options[:class] = locals[:inner_class] || locals[:klass]
+ options[:class] = locals[:inner_class]
+ options[:class] ||= locals[:klass] if plain
body = super
return body if plain
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_text] ||= false if name == 'submit'
locals.merge!({
:method => method,
:type => name,
:body => body
})
wrapper(locals)
end
end
def fieldset(*args, &block)
options = args.extract_options!
body = ''
body += @template.content_tag(:legend, options[:legend]) unless options[:legend].blank?
body += @template.capture(&block)
@template.content_tag(:fieldset, body, :class => options[:class])
end
def radio_select(method, choices, *args)
options = args.extract_options!
value = @object.send(method)
separator = options.delete(:separator)
body = ''
for text,key in choices
body << radio_button(method, key.to_s, :selected => (value == key), :class => options[:inner_class]) + ' '
body << @template.content_tag("label" , text, :for => "#{object_name}_#{method}_#{key.to_s}")
body << separator unless separator.blank?
end
locals = template_locals(options)
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_for] ||= false
locals.merge!({
:method => method,
:type => 'radio_select',
:body => body
})
wrapper(locals)
end
def check_box_group(name, choices, *args)
options = args.extract_options!
values = args.pop
values = [] if values.nil?
values = [values] unless values.is_a?(Array)
separator = options.delete(:separator)
body = ''
for text,key in choices
id = "#{name}_#{key}".gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
input = @template.check_box_tag(name, key, (values.include?(key)), :id => id, :class => options[:inner_class])
body << @template.content_tag("label" , "#{input} #{text}", :for => id)
body << separator unless separator.blank?
end
locals = template_locals(options)
locals[:label_for] ||= false
locals.merge!({
:method => nil,
:type => 'check_box_group',
:body => body
})
wrapper(locals)
end
def check_box_field(method, text, *args)
options = args.extract_options!
locals = template_locals(options)
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_for] ||= false
body = @template.content_tag("label" , "#{check_box(method, :class => locals[:inner_class])} #{text}", :for => "#{object_name}_#{method}")
locals.merge!({
:method => method,
:type => 'check_box_field',
:body => body
})
wrapper(locals)
end
def buttons(*args, &block)
options = args.extract_options!
locals = template_locals(options)
locals[:body] = @template.capture(&block)
buttons_wrapper(locals)
end
def submit(method, *args)
options = args.extract_options!
plain = options.delete(:plain)
locals = template_locals(options)
- options[:class] = locals[:inner_class] || locals[:klass]
+ options[:class] = locals[:inner_class]
if plain
+ options[:class] ||= locals[:klass]
super
else
locals[:body] = super
buttons_wrapper(locals)
end
end
def button(value, *args)
options = args.extract_options!
plain = options.delete(:plain)
locals = template_locals(options)
options.merge!({
:type => 'button',
:value => value,
- :class => locals[:inner_class] || locals[:klass]
+ :class => locals[:inner_class]
})
+ options[:class] ||= locals[:klass] if plain
body = @template.content_tag(:input, '', options)
if plain
body
else
locals[:body] = body
buttons_wrapper(locals)
end
end
private
def template_name(name)
return "#{templates_path}#{name}"
end
def template_locals(options)
{
:builder => self,
:object => @object,
:object_name => @object_name,
:method => options.delete(:method),
:type => options.delete(:type),
:body => options.delete(:body),
:error => options.delete(:error),
:required => options.delete(:required),
:klass => options.delete(:class),
:inner_class => options.delete(:inner_class),
:label_text => options.delete(:label),
:label_for => options.delete(:label_for),
:note => options.delete(:note),
:help => options.delete(:help),
:options => options
}
end
end
end
|
vits/good_enough_form_builder
|
d53d85102bab589898ebe8511961e608dffaf042
|
Added inner_class attribute.
|
diff --git a/lib/good_enough_form_builder.rb b/lib/good_enough_form_builder.rb
index 13f487e..9748052 100644
--- a/lib/good_enough_form_builder.rb
+++ b/lib/good_enough_form_builder.rb
@@ -1,199 +1,202 @@
module GoodEnoughFormBuilder
class Builder < ActionView::Helpers::FormBuilder
@@templates_path = "forms/"
cattr_accessor :templates_path
def wrapper(locals)
type = locals[:type]
body = locals[:body]
begin
@template.render :partial => template_name(type), :locals => locals
rescue ActionView::MissingTemplate
if type == 'field'
body
else
begin
@template.render :partial => template_name('field'), :locals => locals
rescue ActionView::MissingTemplate
body
end
end
end
end
def buttons_wrapper(locals)
body = locals[:body]
begin
@template.render :partial => template_name('buttons'), :locals => locals
rescue ActionView::MissingTemplate
body
end
end
def field(*args, &block)
options = args.extract_options!
locals = template_locals(options)
locals.merge!({
:method => nil,
:type => 'field',
:body => @template.capture(&block)
})
wrapper(locals)
end
['text_field', 'file_field', 'password_field', 'text_area',
'select', 'collection_select'].each do |name|
define_method(name) do |method, *args|
options = args.extract_options!
plain = options.delete(:plain)
- return super if plain
-
locals = template_locals(options)
+ options[:class] = locals[:inner_class] || locals[:klass]
+ body = super
+ return body if plain
+
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_text] ||= false if name == 'submit'
locals.merge!({
:method => method,
:type => name,
- :body => super
+ :body => body
})
wrapper(locals)
end
end
def fieldset(*args, &block)
options = args.extract_options!
body = ''
body += @template.content_tag(:legend, options[:legend]) unless options[:legend].blank?
body += @template.capture(&block)
@template.content_tag(:fieldset, body, :class => options[:class])
end
def radio_select(method, choices, *args)
options = args.extract_options!
value = @object.send(method)
separator = options.delete(:separator)
body = ''
for text,key in choices
- body << radio_button(method, key.to_s, :selected => (value == key)) + ' '
+ body << radio_button(method, key.to_s, :selected => (value == key), :class => options[:inner_class]) + ' '
body << @template.content_tag("label" , text, :for => "#{object_name}_#{method}_#{key.to_s}")
body << separator unless separator.blank?
end
locals = template_locals(options)
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_for] ||= false
locals.merge!({
:method => method,
:type => 'radio_select',
:body => body
})
wrapper(locals)
end
def check_box_group(name, choices, *args)
options = args.extract_options!
values = args.pop
values = [] if values.nil?
values = [values] unless values.is_a?(Array)
separator = options.delete(:separator)
body = ''
for text,key in choices
id = "#{name}_#{key}".gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
- input = @template.check_box_tag name, key, (values.include?(key)), :id => id
+ input = @template.check_box_tag(name, key, (values.include?(key)), :id => id, :class => options[:inner_class])
body << @template.content_tag("label" , "#{input} #{text}", :for => id)
body << separator unless separator.blank?
end
locals = template_locals(options)
locals[:label_for] ||= false
locals.merge!({
:method => nil,
:type => 'check_box_group',
:body => body
})
wrapper(locals)
end
def check_box_field(method, text, *args)
options = args.extract_options!
locals = template_locals(options)
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_for] ||= false
- body = @template.content_tag("label" , "#{check_box(method)} #{text}", :for => "#{object_name}_#{method}")
+ body = @template.content_tag("label" , "#{check_box(method, :class => locals[:inner_class])} #{text}", :for => "#{object_name}_#{method}")
locals.merge!({
:method => method,
:type => 'check_box_field',
:body => body
})
wrapper(locals)
end
def buttons(*args, &block)
options = args.extract_options!
locals = template_locals(options)
locals[:body] = @template.capture(&block)
- # @template.content_tag(:div, , options)
buttons_wrapper(locals)
end
def submit(method, *args)
options = args.extract_options!
plain = options.delete(:plain)
locals = template_locals(options)
+ options[:class] = locals[:inner_class] || locals[:klass]
if plain
super
else
locals[:body] = super
buttons_wrapper(locals)
end
end
def button(value, *args)
options = args.extract_options!
plain = options.delete(:plain)
locals = template_locals(options)
options.merge!({
:type => 'button',
:value => value,
- :class => locals[:klass]
+ :class => locals[:inner_class] || locals[:klass]
})
body = @template.content_tag(:input, '', options)
if plain
body
else
locals[:body] = body
buttons_wrapper(locals)
end
end
private
def template_name(name)
return "#{templates_path}#{name}"
end
def template_locals(options)
{
:builder => self,
:object => @object,
:object_name => @object_name,
:method => options.delete(:method),
:type => options.delete(:type),
:body => options.delete(:body),
:error => options.delete(:error),
:required => options.delete(:required),
:klass => options.delete(:class),
+ :inner_class => options.delete(:inner_class),
:label_text => options.delete(:label),
:label_for => options.delete(:label_for),
:note => options.delete(:note),
:help => options.delete(:help),
:options => options
}
end
end
end
|
vits/good_enough_form_builder
|
a981e9232a2ad4ea0d2937cffea84bacf8ffba9f
|
Added button fields, changed submit button.
|
diff --git a/lib/good_enough_form_builder.rb b/lib/good_enough_form_builder.rb
index deedc5d..13f487e 100644
--- a/lib/good_enough_form_builder.rb
+++ b/lib/good_enough_form_builder.rb
@@ -1,150 +1,199 @@
module GoodEnoughFormBuilder
class Builder < ActionView::Helpers::FormBuilder
@@templates_path = "forms/"
cattr_accessor :templates_path
def wrapper(locals)
type = locals[:type]
body = locals[:body]
begin
@template.render :partial => template_name(type), :locals => locals
rescue ActionView::MissingTemplate
if type == 'field'
body
else
begin
@template.render :partial => template_name('field'), :locals => locals
rescue ActionView::MissingTemplate
body
end
end
end
end
+ def buttons_wrapper(locals)
+ body = locals[:body]
+ begin
+ @template.render :partial => template_name('buttons'), :locals => locals
+ rescue ActionView::MissingTemplate
+ body
+ end
+ end
+
def field(*args, &block)
options = args.extract_options!
locals = template_locals(options)
locals.merge!({
:method => nil,
:type => 'field',
:body => @template.capture(&block)
})
wrapper(locals)
end
['text_field', 'file_field', 'password_field', 'text_area',
- 'select', 'collection_select', 'submit'].each do |name|
+ 'select', 'collection_select'].each do |name|
define_method(name) do |method, *args|
options = args.extract_options!
plain = options.delete(:plain)
return super if plain
locals = template_locals(options)
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_text] ||= false if name == 'submit'
locals.merge!({
:method => method,
:type => name,
:body => super
})
wrapper(locals)
end
end
def fieldset(*args, &block)
options = args.extract_options!
body = ''
body += @template.content_tag(:legend, options[:legend]) unless options[:legend].blank?
body += @template.capture(&block)
@template.content_tag(:fieldset, body, :class => options[:class])
end
def radio_select(method, choices, *args)
options = args.extract_options!
value = @object.send(method)
separator = options.delete(:separator)
body = ''
for text,key in choices
body << radio_button(method, key.to_s, :selected => (value == key)) + ' '
body << @template.content_tag("label" , text, :for => "#{object_name}_#{method}_#{key.to_s}")
body << separator unless separator.blank?
end
locals = template_locals(options)
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_for] ||= false
locals.merge!({
:method => method,
:type => 'radio_select',
:body => body
})
wrapper(locals)
end
def check_box_group(name, choices, *args)
options = args.extract_options!
values = args.pop
values = [] if values.nil?
values = [values] unless values.is_a?(Array)
separator = options.delete(:separator)
body = ''
for text,key in choices
id = "#{name}_#{key}".gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
input = @template.check_box_tag name, key, (values.include?(key)), :id => id
body << @template.content_tag("label" , "#{input} #{text}", :for => id)
body << separator unless separator.blank?
end
locals = template_locals(options)
locals[:label_for] ||= false
locals.merge!({
:method => nil,
:type => 'check_box_group',
:body => body
})
wrapper(locals)
end
def check_box_field(method, text, *args)
options = args.extract_options!
locals = template_locals(options)
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_for] ||= false
body = @template.content_tag("label" , "#{check_box(method)} #{text}", :for => "#{object_name}_#{method}")
locals.merge!({
:method => method,
:type => 'check_box_field',
:body => body
})
wrapper(locals)
end
+ def buttons(*args, &block)
+ options = args.extract_options!
+ locals = template_locals(options)
+ locals[:body] = @template.capture(&block)
+ # @template.content_tag(:div, , options)
+ buttons_wrapper(locals)
+ end
+
+ def submit(method, *args)
+ options = args.extract_options!
+ plain = options.delete(:plain)
+ locals = template_locals(options)
+
+ if plain
+ super
+ else
+ locals[:body] = super
+ buttons_wrapper(locals)
+ end
+ end
+
+ def button(value, *args)
+ options = args.extract_options!
+ plain = options.delete(:plain)
+ locals = template_locals(options)
+
+ options.merge!({
+ :type => 'button',
+ :value => value,
+ :class => locals[:klass]
+ })
+ body = @template.content_tag(:input, '', options)
+ if plain
+ body
+ else
+ locals[:body] = body
+ buttons_wrapper(locals)
+ end
+ end
+
private
def template_name(name)
return "#{templates_path}#{name}"
end
def template_locals(options)
{
:builder => self,
:object => @object,
:object_name => @object_name,
:method => options.delete(:method),
:type => options.delete(:type),
:body => options.delete(:body),
:error => options.delete(:error),
:required => options.delete(:required),
:klass => options.delete(:class),
:label_text => options.delete(:label),
:label_for => options.delete(:label_for),
:note => options.delete(:note),
:help => options.delete(:help),
:options => options
}
end
end
end
|
vits/good_enough_form_builder
|
912452bee162b2c2faa196d2c9ccac14262521d3
|
Added check_box_group.
|
diff --git a/lib/good_enough_form_builder.rb b/lib/good_enough_form_builder.rb
index b31deb4..deedc5d 100644
--- a/lib/good_enough_form_builder.rb
+++ b/lib/good_enough_form_builder.rb
@@ -1,125 +1,150 @@
module GoodEnoughFormBuilder
class Builder < ActionView::Helpers::FormBuilder
@@templates_path = "forms/"
cattr_accessor :templates_path
def wrapper(locals)
type = locals[:type]
body = locals[:body]
begin
@template.render :partial => template_name(type), :locals => locals
rescue ActionView::MissingTemplate
if type == 'field'
body
else
begin
@template.render :partial => template_name('field'), :locals => locals
rescue ActionView::MissingTemplate
body
end
end
end
end
def field(*args, &block)
options = args.extract_options!
locals = template_locals(options)
locals.merge!({
:method => nil,
:type => 'field',
:body => @template.capture(&block)
})
wrapper(locals)
end
['text_field', 'file_field', 'password_field', 'text_area',
'select', 'collection_select', 'submit'].each do |name|
define_method(name) do |method, *args|
options = args.extract_options!
plain = options.delete(:plain)
return super if plain
locals = template_locals(options)
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_text] ||= false if name == 'submit'
locals.merge!({
:method => method,
:type => name,
:body => super
})
wrapper(locals)
end
end
def fieldset(*args, &block)
options = args.extract_options!
body = ''
body += @template.content_tag(:legend, options[:legend]) unless options[:legend].blank?
body += @template.capture(&block)
@template.content_tag(:fieldset, body, :class => options[:class])
end
def radio_select(method, choices, *args)
options = args.extract_options!
value = @object.send(method)
separator = options.delete(:separator)
body = ''
for text,key in choices
body << radio_button(method, key.to_s, :selected => (value == key)) + ' '
body << @template.content_tag("label" , text, :for => "#{object_name}_#{method}_#{key.to_s}")
body << separator unless separator.blank?
end
locals = template_locals(options)
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_for] ||= false
locals.merge!({
:method => method,
:type => 'radio_select',
:body => body
})
wrapper(locals)
end
+ def check_box_group(name, choices, *args)
+ options = args.extract_options!
+ values = args.pop
+ values = [] if values.nil?
+ values = [values] unless values.is_a?(Array)
+ separator = options.delete(:separator)
+
+ body = ''
+ for text,key in choices
+ id = "#{name}_#{key}".gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
+ input = @template.check_box_tag name, key, (values.include?(key)), :id => id
+ body << @template.content_tag("label" , "#{input} #{text}", :for => id)
+ body << separator unless separator.blank?
+ end
+
+ locals = template_locals(options)
+ locals[:label_for] ||= false
+ locals.merge!({
+ :method => nil,
+ :type => 'check_box_group',
+ :body => body
+ })
+ wrapper(locals)
+ end
+
def check_box_field(method, text, *args)
options = args.extract_options!
locals = template_locals(options)
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_for] ||= false
body = @template.content_tag("label" , "#{check_box(method)} #{text}", :for => "#{object_name}_#{method}")
locals.merge!({
:method => method,
:type => 'check_box_field',
:body => body
})
wrapper(locals)
end
private
def template_name(name)
return "#{templates_path}#{name}"
end
def template_locals(options)
{
:builder => self,
:object => @object,
:object_name => @object_name,
:method => options.delete(:method),
:type => options.delete(:type),
:body => options.delete(:body),
:error => options.delete(:error),
:required => options.delete(:required),
:klass => options.delete(:class),
:label_text => options.delete(:label),
:label_for => options.delete(:label_for),
:note => options.delete(:note),
:help => options.delete(:help),
:options => options
}
end
end
end
|
vits/good_enough_form_builder
|
2fa1c3477ca5828b70d5548fdb0647f339613966
|
Added check_box_field.
|
diff --git a/lib/good_enough_form_builder.rb b/lib/good_enough_form_builder.rb
index 1f47b47..b31deb4 100644
--- a/lib/good_enough_form_builder.rb
+++ b/lib/good_enough_form_builder.rb
@@ -1,110 +1,125 @@
module GoodEnoughFormBuilder
class Builder < ActionView::Helpers::FormBuilder
@@templates_path = "forms/"
cattr_accessor :templates_path
def wrapper(locals)
type = locals[:type]
body = locals[:body]
begin
@template.render :partial => template_name(type), :locals => locals
rescue ActionView::MissingTemplate
if type == 'field'
body
else
begin
@template.render :partial => template_name('field'), :locals => locals
rescue ActionView::MissingTemplate
body
end
end
end
end
def field(*args, &block)
options = args.extract_options!
locals = template_locals(options)
locals.merge!({
:method => nil,
:type => 'field',
:body => @template.capture(&block)
})
wrapper(locals)
end
['text_field', 'file_field', 'password_field', 'text_area',
'select', 'collection_select', 'submit'].each do |name|
define_method(name) do |method, *args|
options = args.extract_options!
plain = options.delete(:plain)
return super if plain
locals = template_locals(options)
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_text] ||= false if name == 'submit'
locals.merge!({
:method => method,
:type => name,
:body => super
})
wrapper(locals)
end
end
def fieldset(*args, &block)
options = args.extract_options!
body = ''
body += @template.content_tag(:legend, options[:legend]) unless options[:legend].blank?
body += @template.capture(&block)
@template.content_tag(:fieldset, body, :class => options[:class])
end
def radio_select(method, choices, *args)
options = args.extract_options!
value = @object.send(method)
separator = options.delete(:separator)
body = ''
for text,key in choices
body << radio_button(method, key.to_s, :selected => (value == key)) + ' '
body << @template.content_tag("label" , text, :for => "#{object_name}_#{method}_#{key.to_s}")
body << separator unless separator.blank?
end
locals = template_locals(options)
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_for] ||= false
locals.merge!({
:method => method,
:type => 'radio_select',
:body => body
})
wrapper(locals)
end
+ def check_box_field(method, text, *args)
+ options = args.extract_options!
+ locals = template_locals(options)
+ locals[:error] ||= @object.errors.on(method) if @object
+ locals[:label_for] ||= false
+
+ body = @template.content_tag("label" , "#{check_box(method)} #{text}", :for => "#{object_name}_#{method}")
+ locals.merge!({
+ :method => method,
+ :type => 'check_box_field',
+ :body => body
+ })
+ wrapper(locals)
+ end
+
private
def template_name(name)
return "#{templates_path}#{name}"
end
def template_locals(options)
{
:builder => self,
:object => @object,
:object_name => @object_name,
:method => options.delete(:method),
:type => options.delete(:type),
:body => options.delete(:body),
:error => options.delete(:error),
:required => options.delete(:required),
:klass => options.delete(:class),
:label_text => options.delete(:label),
:label_for => options.delete(:label_for),
:note => options.delete(:note),
:help => options.delete(:help),
:options => options
}
end
end
end
|
vits/good_enough_form_builder
|
d3d5d0b6957dbb12dd8da3fcc85d4c9547ccb28d
|
Added collection_select field type.
|
diff --git a/lib/good_enough_form_builder.rb b/lib/good_enough_form_builder.rb
index d744f90..1f47b47 100644
--- a/lib/good_enough_form_builder.rb
+++ b/lib/good_enough_form_builder.rb
@@ -1,109 +1,110 @@
module GoodEnoughFormBuilder
class Builder < ActionView::Helpers::FormBuilder
@@templates_path = "forms/"
cattr_accessor :templates_path
def wrapper(locals)
type = locals[:type]
body = locals[:body]
begin
@template.render :partial => template_name(type), :locals => locals
rescue ActionView::MissingTemplate
if type == 'field'
body
else
begin
@template.render :partial => template_name('field'), :locals => locals
rescue ActionView::MissingTemplate
body
end
end
end
end
def field(*args, &block)
options = args.extract_options!
locals = template_locals(options)
locals.merge!({
:method => nil,
:type => 'field',
:body => @template.capture(&block)
})
wrapper(locals)
end
- ['text_field', 'file_field', 'password_field', 'text_area', 'select', 'submit'].each do |name|
+ ['text_field', 'file_field', 'password_field', 'text_area',
+ 'select', 'collection_select', 'submit'].each do |name|
define_method(name) do |method, *args|
options = args.extract_options!
plain = options.delete(:plain)
return super if plain
locals = template_locals(options)
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_text] ||= false if name == 'submit'
locals.merge!({
:method => method,
:type => name,
:body => super
})
wrapper(locals)
end
end
def fieldset(*args, &block)
options = args.extract_options!
body = ''
body += @template.content_tag(:legend, options[:legend]) unless options[:legend].blank?
body += @template.capture(&block)
@template.content_tag(:fieldset, body, :class => options[:class])
end
def radio_select(method, choices, *args)
options = args.extract_options!
value = @object.send(method)
separator = options.delete(:separator)
body = ''
for text,key in choices
body << radio_button(method, key.to_s, :selected => (value == key)) + ' '
body << @template.content_tag("label" , text, :for => "#{object_name}_#{method}_#{key.to_s}")
body << separator unless separator.blank?
end
locals = template_locals(options)
locals[:error] ||= @object.errors.on(method) if @object
locals[:label_for] ||= false
locals.merge!({
:method => method,
:type => 'radio_select',
:body => body
})
wrapper(locals)
end
private
def template_name(name)
return "#{templates_path}#{name}"
end
def template_locals(options)
{
:builder => self,
:object => @object,
:object_name => @object_name,
:method => options.delete(:method),
:type => options.delete(:type),
:body => options.delete(:body),
:error => options.delete(:error),
:required => options.delete(:required),
:klass => options.delete(:class),
:label_text => options.delete(:label),
:label_for => options.delete(:label_for),
:note => options.delete(:note),
:help => options.delete(:help),
:options => options
}
end
end
end
|
vits/good_enough_form_builder
|
e22eab6bff2fc1ccc3a74b8a11f6a533e358b7ec
|
Code refactored to clean options hash before calling super field builder to prevent rendering field options as HTML tag attributes.
|
diff --git a/lib/good_enough_form_builder.rb b/lib/good_enough_form_builder.rb
index 8cb71d4..d744f90 100644
--- a/lib/good_enough_form_builder.rb
+++ b/lib/good_enough_form_builder.rb
@@ -1,120 +1,109 @@
module GoodEnoughFormBuilder
class Builder < ActionView::Helpers::FormBuilder
@@templates_path = "forms/"
cattr_accessor :templates_path
- def wrapper(*args)
- options = args.extract_options!
- type = options[:type]
- body = options[:body]
- locals = template_locals(options)
+ def wrapper(locals)
+ type = locals[:type]
+ body = locals[:body]
begin
- @template.render :partial => partial_name(type), :locals => locals
+ @template.render :partial => template_name(type), :locals => locals
rescue ActionView::MissingTemplate
if type == 'field'
body
else
begin
- @template.render :partial => partial_name('field'), :locals => locals
+ @template.render :partial => template_name('field'), :locals => locals
rescue ActionView::MissingTemplate
body
end
end
end
end
def field(*args, &block)
options = args.extract_options!
- options.merge!({
+ locals = template_locals(options)
+ locals.merge!({
:method => nil,
:type => 'field',
:body => @template.capture(&block)
})
- args << options
- wrapper(*args)
+ wrapper(locals)
end
['text_field', 'file_field', 'password_field', 'text_area', 'select', 'submit'].each do |name|
define_method(name) do |method, *args|
options = args.extract_options!
plain = options.delete(:plain)
return super if plain
-
- options[:method] = method
- options[:type] = name
- options[:error] ||= @object.errors.on(method) if @object
- options[:label] ||= false if name == 'submit'
- options[:body] = super
- args << options
- wrapper(*args)
- # full_options = options.dup
- # locals = template_locals(options)
- # locals[:body] = super
- #
- # begin
- # @template.render :partial => partial_name(name), :locals => locals
- # rescue ActionView::MissingTemplate
- # full_options[:body] = locals[:body]
- # args << full_options
- # wrapper(*args)
- # end
- end
- end
- def partial_name(name)
- return "#{templates_path}#{name}"
+ locals = template_locals(options)
+ locals[:error] ||= @object.errors.on(method) if @object
+ locals[:label_text] ||= false if name == 'submit'
+ locals.merge!({
+ :method => method,
+ :type => name,
+ :body => super
+ })
+ wrapper(locals)
+ end
end
def fieldset(*args, &block)
options = args.extract_options!
body = ''
body += @template.content_tag(:legend, options[:legend]) unless options[:legend].blank?
body += @template.capture(&block)
@template.content_tag(:fieldset, body, :class => options[:class])
end
def radio_select(method, choices, *args)
options = args.extract_options!
value = @object.send(method)
separator = options.delete(:separator)
body = ''
for text,key in choices
body << radio_button(method, key.to_s, :selected => (value == key)) + ' '
body << @template.content_tag("label" , text, :for => "#{object_name}_#{method}_#{key.to_s}")
body << separator unless separator.blank?
end
- options[:method] = method
- options[:type] = 'radio_select'
- options[:error] ||= @object.errors.on(method) if @object
- options[:label_for] ||= false
- full_options = options.dup
locals = template_locals(options)
- locals[:body] = body
-
-
+ locals[:error] ||= @object.errors.on(method) if @object
+ locals[:label_for] ||= false
+ locals.merge!({
+ :method => method,
+ :type => 'radio_select',
+ :body => body
+ })
+ wrapper(locals)
end
private
+ def template_name(name)
+ return "#{templates_path}#{name}"
+ end
+
def template_locals(options)
{
:builder => self,
:object => @object,
:object_name => @object_name,
:method => options.delete(:method),
:type => options.delete(:type),
:body => options.delete(:body),
:error => options.delete(:error),
:required => options.delete(:required),
:klass => options.delete(:class),
:label_text => options.delete(:label),
:label_for => options.delete(:label_for),
:note => options.delete(:note),
:help => options.delete(:help),
:options => options
}
end
end
end
|
vits/good_enough_form_builder
|
35468d01223c247e491956c5c1c9a4ff5fe1c146
|
Initial functionality
|
diff --git a/README b/README
index 139cb66..2cbae89 100644
--- a/README
+++ b/README
@@ -1,13 +1,13 @@
GoodEnoughFormBuilder
=====================
-Introduction goes here.
+Rails form builder plugin with form templating suppoprt.
Example
=======
-Example goes here.
+TODO
-Copyright (c) 2009 [name of plugin creator], released under the MIT license
+Copyright (c) 2009 Vitauts StoÄka, released under the MIT license
diff --git a/init.rb b/init.rb
index 3c19a74..6785225 100644
--- a/init.rb
+++ b/init.rb
@@ -1 +1,4 @@
-# Include hook code here
+require 'good_enough_form_builder'
+require 'good_enough_form_helpers'
+
+ActionView::Base.send :include, GoodEnoughFormBuilder::Helpers
diff --git a/lib/good_enough_form_builder.rb b/lib/good_enough_form_builder.rb
index 142d804..8cb71d4 100644
--- a/lib/good_enough_form_builder.rb
+++ b/lib/good_enough_form_builder.rb
@@ -1 +1,120 @@
-# GoodEnoughFormBuilder
+module GoodEnoughFormBuilder
+ class Builder < ActionView::Helpers::FormBuilder
+ @@templates_path = "forms/"
+ cattr_accessor :templates_path
+
+ def wrapper(*args)
+ options = args.extract_options!
+ type = options[:type]
+ body = options[:body]
+ locals = template_locals(options)
+
+ begin
+ @template.render :partial => partial_name(type), :locals => locals
+ rescue ActionView::MissingTemplate
+ if type == 'field'
+ body
+ else
+ begin
+ @template.render :partial => partial_name('field'), :locals => locals
+ rescue ActionView::MissingTemplate
+ body
+ end
+ end
+ end
+ end
+
+ def field(*args, &block)
+ options = args.extract_options!
+ options.merge!({
+ :method => nil,
+ :type => 'field',
+ :body => @template.capture(&block)
+ })
+ args << options
+ wrapper(*args)
+ end
+
+ ['text_field', 'file_field', 'password_field', 'text_area', 'select', 'submit'].each do |name|
+ define_method(name) do |method, *args|
+ options = args.extract_options!
+ plain = options.delete(:plain)
+ return super if plain
+
+ options[:method] = method
+ options[:type] = name
+ options[:error] ||= @object.errors.on(method) if @object
+ options[:label] ||= false if name == 'submit'
+ options[:body] = super
+ args << options
+ wrapper(*args)
+ # full_options = options.dup
+ # locals = template_locals(options)
+ # locals[:body] = super
+ #
+ # begin
+ # @template.render :partial => partial_name(name), :locals => locals
+ # rescue ActionView::MissingTemplate
+ # full_options[:body] = locals[:body]
+ # args << full_options
+ # wrapper(*args)
+ # end
+ end
+ end
+
+ def partial_name(name)
+ return "#{templates_path}#{name}"
+ end
+
+ def fieldset(*args, &block)
+ options = args.extract_options!
+ body = ''
+ body += @template.content_tag(:legend, options[:legend]) unless options[:legend].blank?
+ body += @template.capture(&block)
+ @template.content_tag(:fieldset, body, :class => options[:class])
+ end
+
+ def radio_select(method, choices, *args)
+ options = args.extract_options!
+ value = @object.send(method)
+ separator = options.delete(:separator)
+ body = ''
+ for text,key in choices
+ body << radio_button(method, key.to_s, :selected => (value == key)) + ' '
+ body << @template.content_tag("label" , text, :for => "#{object_name}_#{method}_#{key.to_s}")
+ body << separator unless separator.blank?
+ end
+
+ options[:method] = method
+ options[:type] = 'radio_select'
+ options[:error] ||= @object.errors.on(method) if @object
+ options[:label_for] ||= false
+ full_options = options.dup
+ locals = template_locals(options)
+ locals[:body] = body
+
+
+ end
+
+ private
+
+ def template_locals(options)
+ {
+ :builder => self,
+ :object => @object,
+ :object_name => @object_name,
+ :method => options.delete(:method),
+ :type => options.delete(:type),
+ :body => options.delete(:body),
+ :error => options.delete(:error),
+ :required => options.delete(:required),
+ :klass => options.delete(:class),
+ :label_text => options.delete(:label),
+ :label_for => options.delete(:label_for),
+ :note => options.delete(:note),
+ :help => options.delete(:help),
+ :options => options
+ }
+ end
+ end
+end
diff --git a/lib/good_enough_form_helpers.rb b/lib/good_enough_form_helpers.rb
new file mode 100644
index 0000000..836c854
--- /dev/null
+++ b/lib/good_enough_form_helpers.rb
@@ -0,0 +1,10 @@
+module GoodEnoughFormBuilder
+ module Helpers
+ def ge_form_for(record_or_name_or_array, *args, &block)
+ options = args.extract_options! || {}
+ options[:builder] = GoodEnoughFormBuilder::Builder
+ args << options
+ form_for(record_or_name_or_array, *args, &block)
+ end
+ end
+end
\ No newline at end of file
|
vits/good_enough_form_builder
|
f70a7c6dfa221d2a9a578f0d1145b347cc04b686
|
first import
|
diff --git a/MIT-LICENSE b/MIT-LICENSE
new file mode 100644
index 0000000..9376605
--- /dev/null
+++ b/MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2009 [name of plugin creator]
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README b/README
new file mode 100644
index 0000000..139cb66
--- /dev/null
+++ b/README
@@ -0,0 +1,13 @@
+GoodEnoughFormBuilder
+=====================
+
+Introduction goes here.
+
+
+Example
+=======
+
+Example goes here.
+
+
+Copyright (c) 2009 [name of plugin creator], released under the MIT license
diff --git a/Rakefile b/Rakefile
new file mode 100644
index 0000000..5c51bb6
--- /dev/null
+++ b/Rakefile
@@ -0,0 +1,23 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+desc 'Test the good_enough_form_builder plugin.'
+Rake::TestTask.new(:test) do |t|
+ t.libs << 'lib'
+ t.libs << 'test'
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = true
+end
+
+desc 'Generate documentation for the good_enough_form_builder plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'GoodEnoughFormBuilder'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.rdoc_files.include('README')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
diff --git a/init.rb b/init.rb
new file mode 100644
index 0000000..3c19a74
--- /dev/null
+++ b/init.rb
@@ -0,0 +1 @@
+# Include hook code here
diff --git a/install.rb b/install.rb
new file mode 100644
index 0000000..f7732d3
--- /dev/null
+++ b/install.rb
@@ -0,0 +1 @@
+# Install hook code here
diff --git a/lib/good_enough_form_builder.rb b/lib/good_enough_form_builder.rb
new file mode 100644
index 0000000..142d804
--- /dev/null
+++ b/lib/good_enough_form_builder.rb
@@ -0,0 +1 @@
+# GoodEnoughFormBuilder
diff --git a/tasks/good_enough_form_builder_tasks.rake b/tasks/good_enough_form_builder_tasks.rake
new file mode 100644
index 0000000..7ea606d
--- /dev/null
+++ b/tasks/good_enough_form_builder_tasks.rake
@@ -0,0 +1,4 @@
+# desc "Explaining what the task does"
+# task :good_enough_form_builder do
+# # Task goes here
+# end
diff --git a/test/good_enough_form_builder_test.rb b/test/good_enough_form_builder_test.rb
new file mode 100644
index 0000000..5e29ea2
--- /dev/null
+++ b/test/good_enough_form_builder_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class GoodEnoughFormBuilderTest < ActiveSupport::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
diff --git a/test/test_helper.rb b/test/test_helper.rb
new file mode 100644
index 0000000..cf148b8
--- /dev/null
+++ b/test/test_helper.rb
@@ -0,0 +1,3 @@
+require 'rubygems'
+require 'active_support'
+require 'active_support/test_case'
\ No newline at end of file
diff --git a/uninstall.rb b/uninstall.rb
new file mode 100644
index 0000000..9738333
--- /dev/null
+++ b/uninstall.rb
@@ -0,0 +1 @@
+# Uninstall hook code here
|
komagata/dnsbl_client
|
0eff1fcb0ef355758967c2adc15d604a2feeffb3
|
added has_rdoc
|
diff --git a/dnsbl_client.gemspec b/dnsbl_client.gemspec
index d26ad86..000c5dd 100644
--- a/dnsbl_client.gemspec
+++ b/dnsbl_client.gemspec
@@ -1,15 +1,16 @@
Gem::Specification.new do |s|
s.author = 'Masaki Komagata'
s.description = <<-EOF
DNSBL Client is simple solution for spam blocking.
(What is DNSBL? http://en.wikipedia.org/wiki/Dnsbl)
EOF
s.email = '[email protected]'
s.homepage = 'http://github.com/komagata/dnsbl_client/tree'
s.name = 'dnsbl_client'
s.required_ruby_version = '>= 1.8.5'
s.rubyforge_project = 'dnsbl_client'
s.summary = 'DNSBL Client is simple solution for spam blocking.'
s.version = '0.0.1'
s.files = %w[README lib/dnsbl.rb lib/dnsbl/client.rb lib/dnsbl/bbq.rb]
+ s.has_rdoc = true
end
|
techwizrd/GtkSidebar
|
8fd6eed016b032ed7890e9e9884ce9e7d2eea3f6
|
added text markup support
|
diff --git a/GtkSidebar.py b/GtkSidebar.py
index 488f79c..df2e390 100755
--- a/GtkSidebar.py
+++ b/GtkSidebar.py
@@ -1,85 +1,85 @@
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
class GtkSidebar(gtk.Frame):
__gtype_name = 'GtkSidebar'
def __init__(self):
gtk.Frame.__init__(self)
self.SBscrollbar = gtk.ScrolledWindow()
self.SBscrollbar.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.SBstore = gtk.TreeStore(str, str)
self.SBtreeview = gtk.TreeView(self.SBstore)
self.SBcolumn = gtk.TreeViewColumn('Pixbuf and Text')
self.SBtreeview.append_column(self.SBcolumn)
self.SBcell0 = gtk.CellRendererPixbuf()
self.SBcell1 = gtk.CellRendererText()
self.SBcolumn.pack_start(self.SBcell0, False)
self.SBcolumn.pack_start(self.SBcell1, True)
# set the cell attributes to the appropriate liststore column
# GTK+ 2.0 doesn't support the "stock_id" property
if gtk.gtk_version[1] < 2:
self.SBcolumn.set_cell_data_func(self.SBcell0, self.make_pb)
else:
self.SBcolumn.set_attributes(self.SBcell0, stock_id=1)
- self.SBcolumn.set_attributes(self.SBcell1, text=0)
+ self.SBcolumn.set_attributes(self.SBcell1, markup=0)
self.SBtreeview.set_search_column(0)
self.SBcolumn.set_sort_column_id(0)
self.SBtreeview.set_reorderable(True)
self.SBtreeview.set_headers_visible(False)
self.add(self.SBscrollbar)
self.SBscrollbar.add(self.SBtreeview)
def add_item(self, parent, stuff):
"""Add items to the model. If adding a large amount of items, decouple
first, add the items, and then recouple it."""
return self.SBstore.append(parent, stuff)
def decouple(self):
"""Used for decoupling the model. This is useful when adding large
amounts of rows, as you do not need to wait for each addition to
update the TreeView. Just remember to call recouple() afterwards."""
self.SBtreeview.set_model(None)
def recouple(self):
"""Used for recoupling the model. This is useful when adding large
amounts of rows, as you do not need to wait for each addition to
update the TreeView."""
self.SBtreeview.set_model(self.SBstore)
def make_pb(self, tvcolumn, cell, model, iter):
stock = model.get_value(iter, 1)
pb = self.SBtreeview.render_icon(stock, gtk.ICON_SIZE_MENU, None)
cell.set_property('pixbuf', pb)
return
def get_store(self):
return self.SBstore
if __name__ == "__main__":
a = gtk.Window()
a.connect('delete_event', gtk.main_quit)
a.set_size_request(200,400)
b = GtkSidebar()
a.add(b)
a.show_all()
- for item in range(1, 5):
- b.add_item(None, ['Parent %i' % item, gtk.STOCK_OPEN])
+ for item in range(1, 6):
+ b.add_item(None, ['Parent %i' % item, None])
for parent in range(6,11):
piter = b.add_item(None, ['Parent %i' % parent, gtk.STOCK_OPEN])
for child in range(1,6):
b.add_item(piter, ['Child %i of Parent %i' % (child, parent), gtk.STOCK_NEW])
gtk.main()
|
gklopper/Simple-Web-Reference
|
bbb9f27d2c9cd459ac5aff936a8a8887c476cdee
|
Added repository to pom file
|
diff --git a/pom.xml b/pom.xml
index 15474bc..c749452 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,48 +1,56 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>webtest</groupId>
<artifactId>webtest</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>webtest Maven Webapp</name>
<url>http://maven.apache.org</url>
+ <repositories>
+ <repository>
+ <id>mvn.github.com</id>
+ <name>Maven repository on Github</name>
+ <url>http://mvn.github.com/repository</url>
+ </repository>
+ </repositories>
+
<dependencies>
<dependency>
<groupId>simpleweb</groupId>
<artifactId>simpleweb</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
</dependencies>
<build>
<finalName>webtest</finalName>
-
+
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>7.0.1.v20091125</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
|
Abica/Packit
|
530379cd8d1237034a36d3f9279da1a94f4eff1b
|
noticed some typos
|
diff --git a/lib/packit.rb b/lib/packit.rb
index 0a93eda..892ea5f 100644
--- a/lib/packit.rb
+++ b/lib/packit.rb
@@ -1,100 +1,100 @@
module Packit
class Field
attr_accessor :name, :args
def initialize( name, args )
@name = Utils.cache_key_for name
@args = args
end
def size
0
end
def call
nil
end
end
class Record
def initialize
@fields = []
end
# TODO: test me
def call
yield self if block_given?
# I forgot what happens here
to_a.map { | field | field.call }
end
def add name, args = {}
@fields << Field.new( name.to_sym, args )
self
end
def bring record
@fields += Backend.find( record ).to_a
self
end
def size
- @fields.inject( 0 ) { | sum, f | sum + f }
+ @fields.inject( 0 ) { | sum, f | sum + f.size }
end
def to_a
@fields.to_a
end
end
class Backend
class << self
def new &block
block.call( Record.new )
end
def create name, &block
key = Utils.cache_key_for name
records[ key ] ||= new &block
end
def find record
return record if record.respond_to? :bring
records[ Utils.cache_key_for( record ) ]
end
def count
records.size
end
def clear
records.clear
end
private
def records
@@records ||= {}
end
end
end
class Utils
def self.cache_key_for name
return name.to_sym if name.respond_to? :to_sym
name
end
end
class << self
def [] name
Backend.find name
end
# TODO: test me
def call name, &block
record = Backend.find name
- name.call &block
+ record.call &block
end
end
end
|
Abica/Packit
|
e55827f146a9f5e9edc478e1c79cd1bca7fd8f0f
|
add call methods so I don't forget that I want them
|
diff --git a/lib/packit.rb b/lib/packit.rb
index 3fc5b89..0a93eda 100644
--- a/lib/packit.rb
+++ b/lib/packit.rb
@@ -1,82 +1,100 @@
module Packit
class Field
attr_accessor :name, :args
def initialize( name, args )
@name = Utils.cache_key_for name
@args = args
end
def size
0
end
+
+ def call
+ nil
+ end
end
class Record
def initialize
@fields = []
end
+ # TODO: test me
+ def call
+ yield self if block_given?
+
+ # I forgot what happens here
+ to_a.map { | field | field.call }
+ end
+
def add name, args = {}
@fields << Field.new( name.to_sym, args )
self
end
- def bring holder
- @fields += Backend.find( holder ).to_a
+ def bring record
+ @fields += Backend.find( record ).to_a
self
end
def size
@fields.inject( 0 ) { | sum, f | sum + f }
end
def to_a
@fields.to_a
end
end
class Backend
class << self
def new &block
block.call( Record.new )
end
def create name, &block
key = Utils.cache_key_for name
records[ key ] ||= new &block
end
def find record
return record if record.respond_to? :bring
records[ Utils.cache_key_for( record ) ]
end
def count
records.size
end
def clear
records.clear
end
private
def records
@@records ||= {}
end
end
end
class Utils
def self.cache_key_for name
return name.to_sym if name.respond_to? :to_sym
name
end
end
class << self
def [] name
Backend.find name
end
+
+ # TODO: test me
+ def call name, &block
+ record = Backend.find name
+ name.call &block
+ end
end
end
|
Abica/Packit
|
7f912f2ae762e276edcc82a1456f63299d32c169
|
- change tabs -> whitespace - flesh out tests
|
diff --git a/lib/packit.rb b/lib/packit.rb
index c6f6441..3fc5b89 100644
--- a/lib/packit.rb
+++ b/lib/packit.rb
@@ -1,74 +1,82 @@
module Packit
- class Field
- attr_accessor :name, :args
+ class Field
+ attr_accessor :name, :args
- def initialize( name, args )
- @name = Utils.cache_key_for name
- @args = args
- end
- end
+ def initialize( name, args )
+ @name = Utils.cache_key_for name
+ @args = args
+ end
- class Record
- def initialize
- @fields = []
- end
+ def size
+ 0
+ end
+ end
- def add name, args = {}
- @fields << Field.new( name.to_sym, args )
- self
- end
+ class Record
+ def initialize
+ @fields = []
+ end
- def bring holder
- @fields += Backend.find( holder ).to_a
- self
- end
+ def add name, args = {}
+ @fields << Field.new( name.to_sym, args )
+ self
+ end
- def size
- @fields.inject( 0 ) { | sum, f | sum + f }
- end
+ def bring holder
+ @fields += Backend.find( holder ).to_a
+ self
+ end
- def to_a
- @fields.to_a
- end
- end
+ def size
+ @fields.inject( 0 ) { | sum, f | sum + f }
+ end
- class Backend
- class << self
- def new &block
- block.call( Record.new )
- end
+ def to_a
+ @fields.to_a
+ end
+ end
- def create name, &block
- key = Utils.cache_key_for name
- records[ key ] ||= new &block
- end
+ class Backend
+ class << self
+ def new &block
+ block.call( Record.new )
+ end
- def find record
- return record if record.respond_to? :bring
- records[ Utils.cache_key_for( record ) ]
- end
+ def create name, &block
+ key = Utils.cache_key_for name
+ records[ key ] ||= new &block
+ end
- def count
- records.size
- end
+ def find record
+ return record if record.respond_to? :bring
+ records[ Utils.cache_key_for( record ) ]
+ end
- def clear
- records.clear
- end
+ def count
+ records.size
+ end
- private
- def records
- @@records ||= {}
- end
- end
- end
+ def clear
+ records.clear
+ end
- class Utils
- def self.cache_key_for name
- return name.to_sym if name.respond_to? :to_sym
- name
- end
- end
+ private
+ def records
+ @@records ||= {}
+ end
+ end
+ end
- extend Backend
+ class Utils
+ def self.cache_key_for name
+ return name.to_sym if name.respond_to? :to_sym
+ name
+ end
+ end
+
+ class << self
+ def [] name
+ Backend.find name
+ end
+ end
end
diff --git a/spec/packit_spec.rb b/spec/packit_spec.rb
index 7fdb025..ace1f37 100644
--- a/spec/packit_spec.rb
+++ b/spec/packit_spec.rb
@@ -1,96 +1,160 @@
require File.join( "spec", "spec_helper" )
require File.join( "lib", "packit" )
-def create_record( name = :temp )
- Packit::Backend.create name do | record |
- if block_given?
- yield record
- else
- record.add :field_1
- record.add :field_2
- record.add :field_3
- end
- end
-end
-
-describe "Packit::Field" do
- it "ssdsd"
-end
-
-describe "Packit::Record" do
- it "ssdsd"
-end
-
-describe "Packit::Backend" do
- before do
- @backend = Packit::Backend
- @backend.clear
- end
-
- describe "#new" do
- it "should create a record but not add to the backend" do
- old_count = @backend.count
-
- @backend.new do | record |
- record.add :a
- record.add :b
- record.add :c
- end
-
- old_count.should == @backend.count
-
- end
- end
-
- describe "#create" do
- it "ssdsd"
- end
-
- describe "#find" do
- before do
- @name = :new_record
- @record = create_record @name
-
- end
-
- describe "given an instance" do
- it "should return itself" do
- @backend.find( @record ).should == @record
- end
- end
-
- describe "given a symbol" do
- it "should return a record instance" do
- record = @backend.find( @name )
- record.should == @record
-
- record.should be_a_kind_of( Packit::Record )
- end
- end
- end
-
- describe "#count" do
- it "should change when a new record is added" do
- old_count = @backend.count
-
- create_record
-
- old_count.should_not == @backend.count
- end
- end
-
- describe "#clear" do
- it "should remove all records" do
- create_record
- @backend.count.should > 0
-
- @backend.clear
-
- @backend.count.should be_zero
- end
- end
-end
-
-describe "Packit::Utils" do
- it ""
+describe Packit do
+ describe "[]" do
+ it "should return a Record instance" do
+ record_name = :name
+ Packit[ record_name ].should be_nil
+
+ record = create_backend_record record_name
+
+ Packit[ record_name ].should == record
+ end
+ end
+
+ describe "Field" do
+ describe "#size"
+ end
+
+ describe "Record" do
+ before do
+ @record = Packit::Record.new
+ end
+
+ describe "#add" do
+ it "should add a Field to a record" do
+ old_size = @record.to_a.size
+
+ @record.add :a
+
+ old_size.should < @record.to_a.size
+ end
+ end
+
+ describe "#bring" do
+ it "should include the fields from a 'brought in' record" do
+ record_b_name = :b_name
+ record_b = create_backend_record record_b_name do | record |
+ record.add :b
+ record.add :c
+ end
+
+ @record.to_a.should_not include( *record_b.to_a )
+
+ @record.bring record_b_name
+
+ @record.to_a.should include( *record_b.to_a )
+ end
+ end
+
+ describe "#size" do
+ it "should be zero" do
+ @record.size.should be_zero
+ end
+ end
+
+ describe "to_a" do
+ it "should return an array" do
+ @record.to_a.should be_a_kind_of( Array )
+ end
+ end
+ end
+
+ describe "Backend" do
+ before do
+ @backend = Packit::Backend
+ @backend.clear
+ end
+
+ describe "#new" do
+ it "should create a record but not add to the backend" do
+ old_count = @backend.count
+
+ new_record = @backend.new do | record |
+ record.add :a
+ record.add :b
+ end
+
+ new_record.should be_a_kind_of( Packit::Record )
+ old_count.should == @backend.count
+ end
+ end
+
+ describe "#create" do
+ it "should create a record and add it to the backend" do
+ record_name = :name
+ old_count = @backend.count
+
+ new_record = @backend.create record_name do | record |
+ record.add :a
+ record.add :b
+ end
+
+ new_record.should be_a_kind_of( Packit::Record )
+ old_count.should < @backend.count
+
+ @backend.find( record_name ).should == new_record
+ end
+ end
+
+ describe "#find" do
+ before do
+ @name = :new_record
+ @record = create_backend_record @name
+ end
+
+ describe "given an instance" do
+ it "should return itself" do
+ @backend.find( @record ).should == @record
+ end
+ end
+
+ describe "given a symbol" do
+ it "should return a record instance" do
+ record = @backend.find( @name )
+ record.should == @record
+
+ record.should be_a_kind_of( Packit::Record )
+ end
+ end
+ end
+
+ describe "#count" do
+ it "should change when a new record is added" do
+ old_count = @backend.count
+
+ create_backend_record
+
+ old_count.should_not == @backend.count
+ end
+ end
+
+ describe "#clear" do
+ it "should remove all records" do
+ create_backend_record
+ @backend.count.should > 0
+
+ @backend.clear
+
+ @backend.count.should be_zero
+ end
+ end
+ end
+
+ describe "Utils" do
+ [ nil, {}, 0b0011, "word", 32903290329032, [], // ].each do | key |
+ klass = if key.respond_to? :to_sym
+ key.to_sym.class
+ else
+ key.class
+ end
+
+ describe "#cache_key_for(#{ key.inspect })" do
+ it "should return a #{ klass.to_s.downcase }" do
+ Packit::Utils.cache_key_for( key ).should be_a_kind_of( klass )
+ end
+ end
+ end
+ end
end
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index f9aa9ad..fcfae92 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,13 +1,24 @@
require File.join( File.dirname( __FILE__ ), "..", "lib", "packit" )
module Packit
module Test
- module Helper
- # MUWAHAHAHAHAHAH!@!!!!!@!
+ module Factory
+ # MUWAHAHAHAHAHAH!@!!!!!@!
+ def create_backend_record( name = :temp )
+ Packit::Backend.create name do | record |
+ if block_given?
+ yield record
+ else
+ record.add :field_1
+ record.add :field_2
+ record.add :field_3
+ end
+ end
+ end
end
end
end
Spec::Runner.configure do |config|
- config.include Packit::Test::Helper
+ config.include Packit::Test::Factory
end
|
Abica/Packit
|
950c521900a1a241b4f4303e5abd659e131912bd
|
initial progress
|
diff --git a/lib/packit.rb b/lib/packit.rb
new file mode 100644
index 0000000..c6f6441
--- /dev/null
+++ b/lib/packit.rb
@@ -0,0 +1,74 @@
+module Packit
+ class Field
+ attr_accessor :name, :args
+
+ def initialize( name, args )
+ @name = Utils.cache_key_for name
+ @args = args
+ end
+ end
+
+ class Record
+ def initialize
+ @fields = []
+ end
+
+ def add name, args = {}
+ @fields << Field.new( name.to_sym, args )
+ self
+ end
+
+ def bring holder
+ @fields += Backend.find( holder ).to_a
+ self
+ end
+
+ def size
+ @fields.inject( 0 ) { | sum, f | sum + f }
+ end
+
+ def to_a
+ @fields.to_a
+ end
+ end
+
+ class Backend
+ class << self
+ def new &block
+ block.call( Record.new )
+ end
+
+ def create name, &block
+ key = Utils.cache_key_for name
+ records[ key ] ||= new &block
+ end
+
+ def find record
+ return record if record.respond_to? :bring
+ records[ Utils.cache_key_for( record ) ]
+ end
+
+ def count
+ records.size
+ end
+
+ def clear
+ records.clear
+ end
+
+ private
+ def records
+ @@records ||= {}
+ end
+ end
+ end
+
+ class Utils
+ def self.cache_key_for name
+ return name.to_sym if name.respond_to? :to_sym
+ name
+ end
+ end
+
+ extend Backend
+end
diff --git a/spec/packit_spec.rb b/spec/packit_spec.rb
new file mode 100644
index 0000000..7fdb025
--- /dev/null
+++ b/spec/packit_spec.rb
@@ -0,0 +1,96 @@
+require File.join( "spec", "spec_helper" )
+require File.join( "lib", "packit" )
+
+def create_record( name = :temp )
+ Packit::Backend.create name do | record |
+ if block_given?
+ yield record
+ else
+ record.add :field_1
+ record.add :field_2
+ record.add :field_3
+ end
+ end
+end
+
+describe "Packit::Field" do
+ it "ssdsd"
+end
+
+describe "Packit::Record" do
+ it "ssdsd"
+end
+
+describe "Packit::Backend" do
+ before do
+ @backend = Packit::Backend
+ @backend.clear
+ end
+
+ describe "#new" do
+ it "should create a record but not add to the backend" do
+ old_count = @backend.count
+
+ @backend.new do | record |
+ record.add :a
+ record.add :b
+ record.add :c
+ end
+
+ old_count.should == @backend.count
+
+ end
+ end
+
+ describe "#create" do
+ it "ssdsd"
+ end
+
+ describe "#find" do
+ before do
+ @name = :new_record
+ @record = create_record @name
+
+ end
+
+ describe "given an instance" do
+ it "should return itself" do
+ @backend.find( @record ).should == @record
+ end
+ end
+
+ describe "given a symbol" do
+ it "should return a record instance" do
+ record = @backend.find( @name )
+ record.should == @record
+
+ record.should be_a_kind_of( Packit::Record )
+ end
+ end
+ end
+
+ describe "#count" do
+ it "should change when a new record is added" do
+ old_count = @backend.count
+
+ create_record
+
+ old_count.should_not == @backend.count
+ end
+ end
+
+ describe "#clear" do
+ it "should remove all records" do
+ create_record
+ @backend.count.should > 0
+
+ @backend.clear
+
+ @backend.count.should be_zero
+ end
+ end
+end
+
+describe "Packit::Utils" do
+ it ""
+end
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
new file mode 100644
index 0000000..f9aa9ad
--- /dev/null
+++ b/spec/spec_helper.rb
@@ -0,0 +1,13 @@
+require File.join( File.dirname( __FILE__ ), "..", "lib", "packit" )
+
+module Packit
+ module Test
+ module Helper
+ # MUWAHAHAHAHAHAH!@!!!!!@!
+ end
+ end
+end
+
+Spec::Runner.configure do |config|
+ config.include Packit::Test::Helper
+end
|
icehook/icehook_slinger_cdr_ftp_scripts
|
101112983786a066013145f1b50bceff5261fcab
|
added -f to cp
|
diff --git a/curl_ftp.sh b/curl_ftp.sh
index 3c269cb..7cf05da 100755
--- a/curl_ftp.sh
+++ b/curl_ftp.sh
@@ -1,162 +1,162 @@
#!/bin/bash
# change this to false (or anything but true) when not debugging
DEBUG=true
# dont modify this unless parameters change
USAGE="Usage: $0 -g(to gunzip) -k /absolute/path/preprocessor.awk -u user -p password -a /absolute/path/cdrs -d /absolute/path/processed/cdrs -e extension(ex: csv)"
FTPSERVER="ftp://ftp1.slinger.icehook.com"
CURL="/usr/bin/curl"
AWK="/usr/bin/awk"
GUNZIP="/bin/gunzip"
TMP_DIR="/tmp/curl_ftp"
PROCESSED_STRING="v2"
function debug() {
if [[ $DEBUG ]] ; then
echo $1
fi
}
# process the command line args
while getopts "k:u:p:a:e:d:g" options; do
case $options in
k ) preprocessor=$OPTARG;;
u ) user=$OPTARG;;
p ) pass=$OPTARG;;
a ) path=$OPTARG;;
d ) processed_path=$OPTARG;;
e ) ext=$OPTARG;;
g ) gunzip=true;;
h ) echo $USAGE;;
\? ) echo $USAGE
exit 1;;
* ) echo $USAGE
exit 1;;
esac
done
# ensure the required args - show errors and exit if not
if [ -z $user ] ; then
echo "ftp user is required"
quit=true
fi
if [ -z $pass ] ; then
echo "ftp password is required"
quit=true
fi
if [ -z $path ] ; then
echo "absolute cdr path is required"
quit=true
fi
if [ -z $processed_path ] ; then
echo "absolute processed cdr path is required"
quit=true
fi
if [ -z $ext ] ; then
echo "cdr extentions required ex: csv"
quit=true
fi
if [[ $quit ]] ; then
echo $USAGE
exit 1
fi
if [[ ! $ext =~ "^." ]] ; then
ext=".$ext"
fi
if [ ! -d "$TMP_DIR" ] ; then
debug "making directory for preprocessing files in $TMP_DIR"
mkdir -p "$TMP_DIR"
fi
if [ ! -d "$processed_path" ] ; then
debug "making directory for processed files in $processed_path"
mkdir -p "$processed_path"
fi
debug "looking for files ending in $ext in $path"
# push each cdrfile with the given extension - move it to a "backup" after we have pushed it
# connecting for each ftp session is not fast - but its the best way we can garauntee we
# dont move any unpushed cdrfiles
for cdr_file in `find "$path" -regextype grep -type f -regex "^.*$ext$"`
do
original_cdr_file="$cdr_file"
filename=$(basename "$cdr_file")
- cp "$cdr_file" "$TMP_DIR"
+ cp -f "$cdr_file" "$TMP_DIR"
cdr_file="$TMP_DIR/$filename"
if [[ $gunzip ]] ; then
output_file=${cdr_file%.gz}
debug "gunzipping $cdr_file with output going to $output_file"
- echo "$GUNZIP -c $cdr_file"
+ echo "$GUNZIP $cdr_file"
$GUNZIP "$cdr_file"
if [ $? = "0" ] ; then
debug "successful gunzipping of $cdr_file"
cdr_file=$output_file
ext=${ext%.gz}
else
echo "failed gunzipping of $cdr_file" >> slinger_ftp.err
echo "failed gunzipping of $cdr_file"
exit 1
fi
fi
if [ $preprocessor ] ; then
filename=$(basename "$cdr_file")
base_filename=${filename%ext}
output_file="$TMP_DIR/$base_filename-$PROCESSED_STRING$ext"
debug "preprocessing $cdr_file with output going to $output_file"
echo "$AWK -f $preprocessor $cdr_file > $output_file"
$AWK -f $preprocessor $cdr_file > $output_file
if [ $? = "0" ] ; then
debug "successful preprocessing of $cdr_file"
debug "deleting $cdr_file"
rm "$cdr_file"
cdr_file=$output_file
else
echo "failed preprocessing of $cdr_file" >> slinger_ftp.err
echo "failed preprocessing of $cdr_file"
exit 1
fi
fi
debug "pushing $cdr_file to $FTPSERVER"
$CURL -T $cdr_file $FTPSERVER --user $user:$pass >> slinger_ftp.out 2>> slinger_ftp.err
if [ $? = "0" ] ; then
debug "successful upload of $cdr_file"
debug "backing up $original_cdr_file"
mv "$original_cdr_file" "$processed_path"
debug "deleting $cdr_file"
rm "$cdr_file"
else
echo "failed uploading $cdr_file" >> slinger_ftp.err
debug "failed uploading $cdr_file"
fi
echo ""
done
|
icehook/icehook_slinger_cdr_ftp_scripts
|
2e6fe62a74737acb1162c57691afbe62a79f665d
|
added gunzip step
|
diff --git a/curl_ftp.sh b/curl_ftp.sh
index d11fa8b..3c269cb 100755
--- a/curl_ftp.sh
+++ b/curl_ftp.sh
@@ -1,133 +1,162 @@
#!/bin/bash
# change this to false (or anything but true) when not debugging
DEBUG=true
# dont modify this unless parameters change
-USAGE="Usage: $0 -k /absolute/path/preprocessor.awk -u user -p password -a /absolute/path/cdrs -d /absolute/path/processed/cdrs -e extension(ex: csv)"
+USAGE="Usage: $0 -g(to gunzip) -k /absolute/path/preprocessor.awk -u user -p password -a /absolute/path/cdrs -d /absolute/path/processed/cdrs -e extension(ex: csv)"
FTPSERVER="ftp://ftp1.slinger.icehook.com"
CURL="/usr/bin/curl"
AWK="/usr/bin/awk"
+GUNZIP="/bin/gunzip"
+
TMP_DIR="/tmp/curl_ftp"
PROCESSED_STRING="v2"
function debug() {
if [[ $DEBUG ]] ; then
echo $1
fi
}
# process the command line args
-while getopts "k:u:p:a:e:d:" options; do
+while getopts "k:u:p:a:e:d:g" options; do
case $options in
k ) preprocessor=$OPTARG;;
u ) user=$OPTARG;;
p ) pass=$OPTARG;;
a ) path=$OPTARG;;
d ) processed_path=$OPTARG;;
e ) ext=$OPTARG;;
+ g ) gunzip=true;;
h ) echo $USAGE;;
\? ) echo $USAGE
exit 1;;
* ) echo $USAGE
exit 1;;
esac
done
# ensure the required args - show errors and exit if not
if [ -z $user ] ; then
echo "ftp user is required"
quit=true
fi
if [ -z $pass ] ; then
echo "ftp password is required"
quit=true
fi
if [ -z $path ] ; then
echo "absolute cdr path is required"
quit=true
fi
if [ -z $processed_path ] ; then
echo "absolute processed cdr path is required"
quit=true
fi
if [ -z $ext ] ; then
echo "cdr extentions required ex: csv"
quit=true
fi
if [[ $quit ]] ; then
echo $USAGE
exit 1
fi
if [[ ! $ext =~ "^." ]] ; then
ext=".$ext"
fi
if [ ! -d "$TMP_DIR" ] ; then
debug "making directory for preprocessing files in $TMP_DIR"
mkdir -p "$TMP_DIR"
fi
if [ ! -d "$processed_path" ] ; then
debug "making directory for processed files in $processed_path"
mkdir -p "$processed_path"
fi
debug "looking for files ending in $ext in $path"
# push each cdrfile with the given extension - move it to a "backup" after we have pushed it
# connecting for each ftp session is not fast - but its the best way we can garauntee we
# dont move any unpushed cdrfiles
for cdr_file in `find "$path" -regextype grep -type f -regex "^.*$ext$"`
do
original_cdr_file="$cdr_file"
filename=$(basename "$cdr_file")
- base_filename="${filename%$ext}"
+ cp "$cdr_file" "$TMP_DIR"
+ cdr_file="$TMP_DIR/$filename"
+
+ if [[ $gunzip ]] ; then
+ output_file=${cdr_file%.gz}
+
+ debug "gunzipping $cdr_file with output going to $output_file"
+ echo "$GUNZIP -c $cdr_file"
+
+ $GUNZIP "$cdr_file"
+
+ if [ $? = "0" ] ; then
+ debug "successful gunzipping of $cdr_file"
+ cdr_file=$output_file
+ ext=${ext%.gz}
+ else
+ echo "failed gunzipping of $cdr_file" >> slinger_ftp.err
+ echo "failed gunzipping of $cdr_file"
+ exit 1
+ fi
+ fi
if [ $preprocessor ] ; then
+ filename=$(basename "$cdr_file")
+ base_filename=${filename%ext}
output_file="$TMP_DIR/$base_filename-$PROCESSED_STRING$ext"
debug "preprocessing $cdr_file with output going to $output_file"
echo "$AWK -f $preprocessor $cdr_file > $output_file"
$AWK -f $preprocessor $cdr_file > $output_file
if [ $? = "0" ] ; then
debug "successful preprocessing of $cdr_file"
+ debug "deleting $cdr_file"
+ rm "$cdr_file"
cdr_file=$output_file
else
echo "failed preprocessing of $cdr_file" >> slinger_ftp.err
echo "failed preprocessing of $cdr_file"
exit 1
fi
fi
debug "pushing $cdr_file to $FTPSERVER"
$CURL -T $cdr_file $FTPSERVER --user $user:$pass >> slinger_ftp.out 2>> slinger_ftp.err
if [ $? = "0" ] ; then
debug "successful upload of $cdr_file"
debug "backing up $original_cdr_file"
mv "$original_cdr_file" "$processed_path"
debug "deleting $cdr_file"
rm "$cdr_file"
else
echo "failed uploading $cdr_file" >> slinger_ftp.err
debug "failed uploading $cdr_file"
fi
+
+ echo ""
done
diff --git a/slinger_ftp.err b/slinger_ftp.err
new file mode 100644
index 0000000..640d14a
--- /dev/null
+++ b/slinger_ftp.err
@@ -0,0 +1,21 @@
+
################################ 44.8%
###################################################################### 97.3%
+
################################ 45.7%
####################################################################### 99.0%
+
################################ 44.8%
##################################################################### 96.4%
+
############################### 44.0%
################################################################## 93.0%
+
############################### 44.0%
###################################################################### 97.3%
+
###################### 31.3%
################################################ 67.7%
######################################################################## 100.0%
+
################################# 46.5%
####################################################################### 99.8%
+
############################### 43.1%
#################################################################### 95.6%
+failed gunzipping of /tmp/curl_ftp//home/klarrimore/Projects/scratchpad/slinger/ftp/cdrs/gzipped/bws2BW-CDR-20130416123000-2-845706a1-102319.csv.gz
+
############################### 43.1%
################################################################## 92.2%
+
################################# 46.5%
######################################################################## 100.0%
+
################################# 46.5%
#################################################################### 94.7%
+
################################# 46.5%
###################################################################### 98.1%
+
########################### 38.1%
############################################################### 88.8%
+
############################# 41.4%
################################################################## 92.2%
+
########################### 38.1%
################################################################ 89.6%
+
############################### 43.1%
#################################################################### 95.6%
+
############################# 41.4%
################################################################## 93.0%
+
######################### 35.5%
######################################################## 78.7%
+
################################ 45.7%
###################################################################### 98.1%
+
################################ 44.8%
####################################################################### 99.8%
diff --git a/slinger_ftp.out b/slinger_ftp.out
new file mode 100644
index 0000000..e69de29
|
icehook/icehook_slinger_cdr_ftp_scripts
|
fcf4b18764d0f0e52e822aa023925d71c61b325c
|
switch find ordering and regextype
|
diff --git a/curl_ftp.sh b/curl_ftp.sh
old mode 100644
new mode 100755
index d9d2e2b..d11fa8b
--- a/curl_ftp.sh
+++ b/curl_ftp.sh
@@ -1,133 +1,133 @@
#!/bin/bash
# change this to false (or anything but true) when not debugging
DEBUG=true
# dont modify this unless parameters change
USAGE="Usage: $0 -k /absolute/path/preprocessor.awk -u user -p password -a /absolute/path/cdrs -d /absolute/path/processed/cdrs -e extension(ex: csv)"
FTPSERVER="ftp://ftp1.slinger.icehook.com"
CURL="/usr/bin/curl"
AWK="/usr/bin/awk"
TMP_DIR="/tmp/curl_ftp"
PROCESSED_STRING="v2"
function debug() {
if [[ $DEBUG ]] ; then
echo $1
fi
}
# process the command line args
while getopts "k:u:p:a:e:d:" options; do
case $options in
k ) preprocessor=$OPTARG;;
u ) user=$OPTARG;;
p ) pass=$OPTARG;;
a ) path=$OPTARG;;
d ) processed_path=$OPTARG;;
e ) ext=$OPTARG;;
h ) echo $USAGE;;
\? ) echo $USAGE
exit 1;;
* ) echo $USAGE
exit 1;;
esac
done
# ensure the required args - show errors and exit if not
if [ -z $user ] ; then
echo "ftp user is required"
quit=true
fi
if [ -z $pass ] ; then
echo "ftp password is required"
quit=true
fi
if [ -z $path ] ; then
echo "absolute cdr path is required"
quit=true
fi
if [ -z $processed_path ] ; then
echo "absolute processed cdr path is required"
quit=true
fi
if [ -z $ext ] ; then
echo "cdr extentions required ex: csv"
quit=true
fi
if [[ $quit ]] ; then
echo $USAGE
exit 1
fi
if [[ ! $ext =~ "^." ]] ; then
ext=".$ext"
fi
if [ ! -d "$TMP_DIR" ] ; then
debug "making directory for preprocessing files in $TMP_DIR"
mkdir -p "$TMP_DIR"
fi
if [ ! -d "$processed_path" ] ; then
debug "making directory for processed files in $processed_path"
mkdir -p "$processed_path"
fi
debug "looking for files ending in $ext in $path"
# push each cdrfile with the given extension - move it to a "backup" after we have pushed it
# connecting for each ftp session is not fast - but its the best way we can garauntee we
# dont move any unpushed cdrfiles
-for cdr_file in `find "$path" -type f -regextype sed -regex "^.*$ext$"`
+for cdr_file in `find "$path" -regextype grep -type f -regex "^.*$ext$"`
do
original_cdr_file="$cdr_file"
filename=$(basename "$cdr_file")
base_filename="${filename%$ext}"
if [ $preprocessor ] ; then
output_file="$TMP_DIR/$base_filename-$PROCESSED_STRING$ext"
debug "preprocessing $cdr_file with output going to $output_file"
echo "$AWK -f $preprocessor $cdr_file > $output_file"
$AWK -f $preprocessor $cdr_file > $output_file
if [ $? = "0" ] ; then
debug "successful preprocessing of $cdr_file"
cdr_file=$output_file
else
echo "failed preprocessing of $cdr_file" >> slinger_ftp.err
echo "failed preprocessing of $cdr_file"
exit 1
fi
fi
debug "pushing $cdr_file to $FTPSERVER"
$CURL -T $cdr_file $FTPSERVER --user $user:$pass >> slinger_ftp.out 2>> slinger_ftp.err
if [ $? = "0" ] ; then
debug "successful upload of $cdr_file"
debug "backing up $original_cdr_file"
mv "$original_cdr_file" "$processed_path"
debug "deleting $cdr_file"
rm "$cdr_file"
else
echo "failed uploading $cdr_file" >> slinger_ftp.err
debug "failed uploading $cdr_file"
fi
done
|
icehook/icehook_slinger_cdr_ftp_scripts
|
7d10157f2d0a397de914aacbc6e41c9290db8b86
|
cleaned up curl_ftp a bit and added awk preprocessing
|
diff --git a/curl_ftp.sh b/curl_ftp.sh
index bc2b37b..d9d2e2b 100644
--- a/curl_ftp.sh
+++ b/curl_ftp.sh
@@ -1,83 +1,133 @@
#!/bin/bash
# change this to false (or anything but true) when not debugging
-DEBUG="true"
+DEBUG=true
# dont modify this unless parameters change
-USAGE="Usage: $0 -u user -p password -a /absolute/path/to/cdrs/ -d /absolute/path/to/processed/cdrs/ -e extension"
+USAGE="Usage: $0 -k /absolute/path/preprocessor.awk -u user -p password -a /absolute/path/cdrs -d /absolute/path/processed/cdrs -e extension(ex: csv)"
FTPSERVER="ftp://ftp1.slinger.icehook.com"
+CURL="/usr/bin/curl"
+
+AWK="/usr/bin/awk"
+
+TMP_DIR="/tmp/curl_ftp"
+
+PROCESSED_STRING="v2"
+
function debug() {
- if [ "$DEBUG" = "true" ] ; then
+ if [[ $DEBUG ]] ; then
echo $1
fi
}
# process the command line args
-while getopts "u:p:a:e:d:" options; do
+while getopts "k:u:p:a:e:d:" options; do
case $options in
+ k ) preprocessor=$OPTARG;;
u ) user=$OPTARG;;
p ) pass=$OPTARG;;
a ) path=$OPTARG;;
d ) processed_path=$OPTARG;;
e ) ext=$OPTARG;;
h ) echo $USAGE;;
\? ) echo $USAGE
exit 1;;
* ) echo $USAGE
exit 1;;
esac
done
# ensure the required args - show errors and exit if not
-if [ -z $user ] ; then
+if [ -z $user ] ; then
echo "ftp user is required"
- quit="true"
+ quit=true
fi
-if [ -z $pass ] ; then
+if [ -z $pass ] ; then
echo "ftp password is required"
- quit="true"
+ quit=true
fi
if [ -z $path ] ; then
echo "absolute cdr path is required"
- quit="true"
+ quit=true
fi
if [ -z $processed_path ] ; then
echo "absolute processed cdr path is required"
- quit="true"
+ quit=true
fi
-if [ "$quit" = "true" ] ; then
+if [ -z $ext ] ; then
+ echo "cdr extentions required ex: csv"
+ quit=true
+fi
+
+if [[ $quit ]] ; then
echo $USAGE
exit 1
fi
+if [[ ! $ext =~ "^." ]] ; then
+ ext=".$ext"
+fi
+
+if [ ! -d "$TMP_DIR" ] ; then
+ debug "making directory for preprocessing files in $TMP_DIR"
+ mkdir -p "$TMP_DIR"
+fi
+
if [ ! -d "$processed_path" ] ; then
debug "making directory for processed files in $processed_path"
- mkdir "$processed_path"
+ mkdir -p "$processed_path"
fi
+debug "looking for files ending in $ext in $path"
+
# push each cdrfile with the given extension - move it to a "backup" after we have pushed it
-# connecting for each ftp session is not fast - but its the best way we can garauntee we
+# connecting for each ftp session is not fast - but its the best way we can garauntee we
# dont move any unpushed cdrfiles
-for cdr_file in `find $path -type f -regextype sed -regex "$ext"`
+for cdr_file in `find "$path" -type f -regextype sed -regex "^.*$ext$"`
do
-debug "pushing $cdr_file to $FTPSERVER"
+ original_cdr_file="$cdr_file"
+ filename=$(basename "$cdr_file")
+ base_filename="${filename%$ext}"
+
+ if [ $preprocessor ] ; then
+ output_file="$TMP_DIR/$base_filename-$PROCESSED_STRING$ext"
+
+ debug "preprocessing $cdr_file with output going to $output_file"
+ echo "$AWK -f $preprocessor $cdr_file > $output_file"
+
+ $AWK -f $preprocessor $cdr_file > $output_file
+
+ if [ $? = "0" ] ; then
+ debug "successful preprocessing of $cdr_file"
+ cdr_file=$output_file
+ else
+ echo "failed preprocessing of $cdr_file" >> slinger_ftp.err
+ echo "failed preprocessing of $cdr_file"
+ exit 1
+ fi
+ fi
-curl -T $cdr_file $FTPSERVER --user $user:$pass >> slinger_ftp.out 2>> slinger_ftp.err
+ debug "pushing $cdr_file to $FTPSERVER"
-EXITSTATUS=$?
-if [ "$EXITSTATUS" = "0" ] ; then
- debug "successful upload of $cdr_file"
- debug "backing up $cdr_file"
- mv $cdr_file $processed_path
-else
- debug "failed uploading $cdr_file"
-fi
+ $CURL -T $cdr_file $FTPSERVER --user $user:$pass >> slinger_ftp.out 2>> slinger_ftp.err
+
+ if [ $? = "0" ] ; then
+ debug "successful upload of $cdr_file"
+ debug "backing up $original_cdr_file"
+ mv "$original_cdr_file" "$processed_path"
+ debug "deleting $cdr_file"
+ rm "$cdr_file"
+ else
+ echo "failed uploading $cdr_file" >> slinger_ftp.err
+ debug "failed uploading $cdr_file"
+ fi
done
+
|
icehook/icehook_slinger_cdr_ftp_scripts
|
db7683f32af521ab346505ec270e4e633d95d732
|
added curl based ftp script
|
diff --git a/curl_ftp.sh b/curl_ftp.sh
new file mode 100644
index 0000000..c757845
--- /dev/null
+++ b/curl_ftp.sh
@@ -0,0 +1,83 @@
+#!/bin/bash
+
+# change this to false (or anything but true) when not debugging
+DEBUG="true"
+
+# dont modify this unless parameters change
+USAGE="Usage: $0 -u user -p password -a /absolute/path/to/cdrs/ -d /absolute/path/to/processed/cdrs/ -e extension"
+
+FTPSERVER="ftp://ftp1.slinger.icehook.com"
+
+function debug() {
+ if [ "$DEBUG" = "true" ] ; then
+ echo $1
+ fi
+}
+
+# process the command line args
+while getopts "u:p:a:e:d:" options; do
+ case $options in
+ u ) user=$OPTARG;;
+ p ) pass=$OPTARG;;
+ a ) path=$OPTARG;;
+ d ) processed_path=$OPTARG;;
+ e ) ext=$OPTARG;;
+ h ) echo $USAGE;;
+ \? ) echo $USAGE
+ exit 1;;
+ * ) echo $USAGE
+ exit 1;;
+ esac
+done
+
+
+# ensure the required args - show errors and exit if not
+if [ -z $user ] ; then
+ echo "ftp user is required"
+ quit="true"
+fi
+
+if [ -z $pass ] ; then
+ echo "ftp password is required"
+ quit="true"
+fi
+
+if [ -z $path ] ; then
+ echo "absolute cdr path is required"
+ quit="true"
+fi
+
+if [ -z $processed_path ] ; then
+ echo "absolute processed cdr path is required"
+ quit="true"
+fi
+
+if [ "$quit" = "true" ] ; then
+ echo $USAGE
+ exit 1
+fi
+
+if [ ! -d "$processed_path" ] ; then
+ debug "making directory for processed files in $processed_path"
+ mkdir "$processed_path"
+fi
+
+# push each cdrfile with the given extension - move it to a "backup" after we have pushed it
+# connecting for each ftp session is not fast - but its the best way we can garauntee we
+# dont move any unpushed cdrfiles
+for cdr_file in `find $path -type f -name "*$ext"`
+do
+debug "pushing $cdr_file to $FTPSERVER"
+
+curl -T $cdr_file $FTPSERVER --user $user:$pass >> slinger_ftp.out 2>> slinger_ftp.err
+
+EXITSTATUS=$?
+if [ "$EXITSTATUS" = "0" ] ; then
+ debug "successful upload of $cdr_file"
+ debug "backing up $cdr_file"
+ mv $cdr_file $processed_path
+else
+ debug "failed uploading $cdr_file"
+fi
+done
+
|
vim-scripts/XQuery-syntax
|
6876e6e48be20d9a204a69a54536476ffce55557
|
Version 0.1: Initial upload
|
diff --git a/README b/README
new file mode 100644
index 0000000..62ad577
--- /dev/null
+++ b/README
@@ -0,0 +1,3 @@
+This is a mirror of http://www.vim.org/scripts/script.php?script_id=803
+
+see http://jmvanel.free.fr/vim/
diff --git a/syntax/xquery.vim b/syntax/xquery.vim
new file mode 100644
index 0000000..be6b74f
--- /dev/null
+++ b/syntax/xquery.vim
@@ -0,0 +1,53 @@
+" Vim syntax file
+" Language: XQuery
+" Author: Jean-Marc Vanel <http://jmvanel.free.fr/>
+" Last Change: sam oct 25 10:36:59 CEST 2003
+" Filenames: *.xq
+" URL: http://jmvanel.free.fr/vim/xquery.vim
+" $Id: xquery.vim,v 1.1 2003/10/26 21:00:12 jmv Exp jmv $
+
+" REFERENCES:
+" [1] http://www.w3.org/TR/xquery/
+
+" Quit when a syntax file was already loaded
+if exists("b:current_syntax")
+ finish
+endif
+
+runtime syntax/xml.vim
+
+syn case match
+syn keyword xqueryStatement for let where ascending descending empty greatest empty least collation some every in in satisfies typeswitch default return case as return if then else or and instance of treat as castable as cast as to div idiv mod union intersect except validate validate global validate context validate context global eq ne lt le gt ge is isnot child descendant attribute self following parent ancestor preceding document element element namespace attribute attribute pi pi comment text declare xmlspace preserve strip declare default collation declare declare namespace declare default element declare default function namespace declare function as external as empty item element nillable attribute comment text node declare validation import schema at namespace default element
+
+highlight link xqueryStatement Statement
+
+"floating point number, with dot, optional exponent
+syn match cFloat "\d\+\.\d*\(e[-+]\=\d\+\)\=[fl]\="
+"floating point number, starting with a dot, optional exponent
+syn match cFloat "\.\d\+\(e[-+]\=\d\+\)\=[fl]\=\>"
+"floating point number, without dot, with exponent
+syn match cFloat "\d\+e[-+]\=\d\+[fl]\=\>"
+syn match cNumber "0x\x\+\(u\=l\{0,2}\|ll\=u\)\>"
+syn match cNumber "\d\+"
+highlight link cNumber Number
+highlight link cFloat Number
+
+syn region xqComment start='(:' excludenl end=':)'
+highlight link xqComment Comment
+syntax match xqVariable "$\w\+"
+highlight link xqVariable Identifier
+" Redefine the default XML highlighting:
+hi link xmlTag Structure
+hi link xmlTagName Structure
+hi link xmlEndTag Structure
+
+syntax match xqSeparator ",\|;"
+highlight link xqSeparator Operator
+
+syn region xqCode transparent start='{' excludenl end='}' contains=xmlRegionBis,xqComment,xqueryStatement,xmlString,xqSeparator,cNumber,xqVariable keepend extend
+
+syn region xmlRegionBis start=+<\z([^ /!?<>"']\+\)+ skip=+<!--\_.\{-}-->+ end=+</\z1\_\s\{-}>+ end=+/>+ fold contains=xmlTag,xmlEndTag,xmlCdata,xmlRegionBis,xmlComment,xmlEntity,xmlProcessing,xqCode keepend extend
+
+syn region List transparent start='(' excludenl end=')' contains=xqCode,xmlRegion,xqComment,xqSeparator,xqueryStatement keepend extend
+
+
|
jeffkaufman/statmbx
|
8eaeeee66369754d36cfd9a01d693bd596a0ae5a
|
added license information
|
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..d159169
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,339 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/README b/README
index 43c262d..e7755fe 100644
--- a/README
+++ b/README
@@ -1,43 +1,47 @@
Summary:
statmbx allows you to see what unread messages you have in your
mailbox without opening an email client. It is written in C and
runs as quickly as is possible without indexing. Compatible with
mutt, pine, and any other mail program storing messages in the mbox
format: http://www.jwz.org/doc/content-length.html
+License:
+
+ GPL v2 or later. See the included file COPYING.
+
Usage:
$ cat ~/.statmbx
[events] mail/events
[main] .mail
[folder_with_no_new_messages] mail/somembox
#[folder_not_to_check_right_now] mail/someothermbox
$ statmbx
[events]
Jane Doe Re: [FOOLIST] Movies this evening?
Ignatz Miller [BARLIST] Gaming this Sunday!
[main]
Mike Smith long list, poorly organized
$ statmbx --only-names
[events] [main]
To get rid of the square brackets, don't include them in ~/.statmbx.
I just like the way they look.
If you don't want headers to show bold, perhaps because your terminal
doesn't do escape sequences, disable that by changing STATMBX_DO_BOLD
from 1 to 0 in statmbx.c and recompiling.
If this runs too slowly for you, you probably have too many messages
in the folders you want to check. You could either switch to
something that uses indexing and caching, or you could move old
messages to some archive folder that you can then not check for new
mail. I do the latter.
Installation:
$ gcc -o statmbx statmbx.c
$ cp statmbx somewhere-on-your-path
|
jeffkaufman/statmbx
|
58b9898cda3c1b8cab816751ddbf1242bccd29e7
|
explained some details
|
diff --git a/README b/README
index 9c1c9bc..43c262d 100644
--- a/README
+++ b/README
@@ -1,30 +1,43 @@
Summary:
statmbx allows you to see what unread messages you have in your
mailbox without opening an email client. It is written in C and
runs as quickly as is possible without indexing. Compatible with
mutt, pine, and any other mail program storing messages in the mbox
format: http://www.jwz.org/doc/content-length.html
Usage:
$ cat ~/.statmbx
[events] mail/events
[main] .mail
[folder_with_no_new_messages] mail/somembox
#[folder_not_to_check_right_now] mail/someothermbox
$ statmbx
[events]
Jane Doe Re: [FOOLIST] Movies this evening?
Ignatz Miller [BARLIST] Gaming this Sunday!
[main]
Mike Smith long list, poorly organized
$ statmbx --only-names
[events] [main]
+
+To get rid of the square brackets, don't include them in ~/.statmbx.
+I just like the way they look.
+
+If you don't want headers to show bold, perhaps because your terminal
+doesn't do escape sequences, disable that by changing STATMBX_DO_BOLD
+from 1 to 0 in statmbx.c and recompiling.
+
+If this runs too slowly for you, you probably have too many messages
+in the folders you want to check. You could either switch to
+something that uses indexing and caching, or you could move old
+messages to some archive folder that you can then not check for new
+mail. I do the latter.
Installation:
$ gcc -o statmbx statmbx.c
$ cp statmbx somewhere-on-your-path
|
jeffkaufman/statmbx
|
3634e00da7c33ff11f08abe8ceda6b10b4cecfd4
|
added readme text and existing code
|
diff --git a/README b/README
index e69de29..9c1c9bc 100644
--- a/README
+++ b/README
@@ -0,0 +1,30 @@
+Summary:
+
+ statmbx allows you to see what unread messages you have in your
+ mailbox without opening an email client. It is written in C and
+ runs as quickly as is possible without indexing. Compatible with
+ mutt, pine, and any other mail program storing messages in the mbox
+ format: http://www.jwz.org/doc/content-length.html
+
+Usage:
+
+ $ cat ~/.statmbx
+ [events] mail/events
+ [main] .mail
+ [folder_with_no_new_messages] mail/somembox
+ #[folder_not_to_check_right_now] mail/someothermbox
+ $ statmbx
+
+ [events]
+ Jane Doe Re: [FOOLIST] Movies this evening?
+ Ignatz Miller [BARLIST] Gaming this Sunday!
+
+ [main]
+ Mike Smith long list, poorly organized
+ $ statmbx --only-names
+ [events] [main]
+
+Installation:
+
+ $ gcc -o statmbx statmbx.c
+ $ cp statmbx somewhere-on-your-path
diff --git a/statmbx.c b/statmbx.c
new file mode 100644
index 0000000..3a41344
--- /dev/null
+++ b/statmbx.c
@@ -0,0 +1,276 @@
+
+/* statmbx 0.2
+ *
+ * Copyright 2007,2010, Jeff Kaufman. Distributed under the GPL.
+ *
+ * Reads mbx files and prints out information about unread messages.
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#define STATMBX_BUF_SIZE 256
+#define STATMBX_CONFIG_FILE_NAME ".statmbx"
+#define STATMBX_DO_BOLD 1
+
+#define SCREEN_WIDTH 80 /* assume we have 80 columns to work with */
+#define FROM_HALF 30 /* how many columns to allow from the from
+ line */
+
+/* If we're supporting bold text, print with escape characters.
+ * Otherwise don't bother*/
+void statmbx_printMaybeBold(char* str)
+{
+#if STATMBX_DO_BOLD
+ printf("%c%c%c%c%s%c%c%c%c", 033, '[', '1', 'm',
+ str ,033,'[','0','m');
+#else
+ printf("%s", str);
+#endif
+}
+
+
+void statmbx_getRelativeFname(char* base, char* relative, char* fname)
+{
+ int i, n;
+
+ for(n=0;n<strlen(base) && n<STATMBX_BUF_SIZE-strlen(relative);n++)
+ fname[n] = base[n];
+
+ fname[n++] = '/';
+
+ for(i=0;i<strlen(relative) && i< STATMBX_BUF_SIZE;i++)
+ fname[n++] = relative[i];
+
+ fname[n] = '\0';
+}
+
+FILE* statmbx_getFile(char* homedir, char* suffix)
+{
+ char fname[STATMBX_BUF_SIZE];
+ statmbx_getRelativeFname(homedir, suffix, fname);
+ return fopen(fname, "r");
+}
+
+void statmbx_printName(char* name, char* subj)
+{
+ int i, len, offset;
+
+ int seen_at = 0;
+
+ for(i = 0; i<strlen(name) && i<STATMBX_BUF_SIZE; i++)
+ if(name[i] == '\n')
+ name[i] = '\0';
+
+ for(i = 0; i<strlen(subj) && i<STATMBX_BUF_SIZE; i++)
+ if(subj[i] == '\n')
+ subj[i] = '\0';
+
+ /* prepare "from" */
+
+ offset = 6; /* length of "From: " */
+ for (i=offset;i<strlen(name)&&i<STATMBX_BUF_SIZE;i++)
+ {
+ if (name[i] == '<' || (name[i] == ' ' && seen_at))
+ break;
+ if (name[i] == '"')
+ offset++;
+ else
+ {
+ if (name[i] == '@')
+ seen_at = 1;
+ name[i-offset] = name[i];
+ }
+ }
+ if (i-offset > FROM_HALF-1)
+ {
+ name[FROM_HALF - 6] = '.';
+ name[FROM_HALF - 5] = '.';
+ name[FROM_HALF - 4] = '.';
+ name[FROM_HALF - 3] = ' ';
+ name[FROM_HALF - 2] = ' ';
+ name[FROM_HALF - 1] = '\0';
+ }
+ else
+ {
+ while (i - offset < FROM_HALF-1)
+ name[(i++) - offset] = ' ';
+ name[i-offset] = '\0';
+ }
+
+
+ /* prepare "subj" */
+
+ offset = 9; /* length of "Subject: " */
+ for (i=offset;i<strlen(subj)&&i<STATMBX_BUF_SIZE;i++)
+ subj[i-offset] = subj[i];
+
+ if (i-offset > SCREEN_WIDTH - FROM_HALF - 2)
+ {
+ subj[SCREEN_WIDTH - FROM_HALF - 2 + 0] = '.';
+ subj[SCREEN_WIDTH - FROM_HALF - 2 + 1] = '.';
+ subj[SCREEN_WIDTH - FROM_HALF - 2 + 2] = '.';
+ subj[SCREEN_WIDTH - FROM_HALF - 2 + 3] = '\0';
+ }
+ else
+ {
+ while (i - offset < SCREEN_WIDTH - FROM_HALF - 2 - 1)
+ subj[(i++) - offset] = ' ';
+ subj[i-offset] = '\0';
+ }
+
+
+ if (strlen(name) > 0)
+ printf(" %s%s\n", name,subj);
+}
+
+
+void statmbx_splitConfigLine(char* line,
+ char** mailbox_title,
+ char** mailbox_fname)
+{
+ int i;
+
+ for(i = 0 ; i < STATMBX_BUF_SIZE ; i++)
+ if (line[i] == ' ')
+ {
+ line[i] = '\0';
+ *mailbox_title = line;
+ *mailbox_fname = line+i+1;
+ for(;i<STATMBX_BUF_SIZE ; i++)
+ if(line[i] == '\n')
+ {
+ line[i] = '\0';
+ break;
+ }
+ return;
+ }
+
+ printf("statmbx: error, config line \"%s\" invalid\n",line);
+ exit(-1);
+}
+
+int main(int argc, char** argv)
+{
+ FILE *config_file;
+ FILE *mail_file;
+ char config_line [STATMBX_BUF_SIZE];
+ char mail_line [STATMBX_BUF_SIZE];
+
+ char cur_name [STATMBX_BUF_SIZE];
+ char cur_subj [STATMBX_BUF_SIZE];
+
+ int n,i;
+ char* homedir;
+ char* mailbox_title;
+ char* mailbox_fname;
+
+ int msgs, new_msgs;
+ int inhdr, seen_status_read, printed_title;
+
+ int just_print_names;
+
+
+ just_print_names = 0; /*don't print message, just a space separated
+ list of mailboxes */
+ if (argc == 2 && strncmp(argv[1], "--only-names", 13) == 0)
+ just_print_names = 1;
+ else if (argc != 1)
+ {
+ printf("Usage: statmbx or statmbx --only-names\n");
+ exit(-1);
+ }
+
+ if( (homedir = getenv("HOME")) == NULL)
+ {
+ printf("statmbx:: error, envrionment varible \"HOME\" not\
+ found.\n");
+ exit (-1);
+ }
+
+ config_file = statmbx_getFile(homedir,STATMBX_CONFIG_FILE_NAME);
+
+ n=0;
+ while(fgets(config_line,STATMBX_BUF_SIZE,config_file) != NULL)
+ {
+ config_line[STATMBX_BUF_SIZE-1] = '\0';
+ if (config_line[0] == '\0' || config_line[0] == '#')
+ continue;
+
+ statmbx_splitConfigLine(config_line, &mailbox_title, &mailbox_fname);
+ mail_file = statmbx_getFile(homedir, mailbox_fname);
+ if (mail_file == 0)
+ {
+ printf("statmbx: error, couldn't locate ");
+ printf("mailfile %s relative to %s.\n", mailbox_fname, homedir);
+ }
+ else
+ {
+ msgs = new_msgs = seen_status_read = inhdr = printed_title = 0;
+
+ while(fgets(mail_line, STATMBX_BUF_SIZE, mail_file) != NULL)
+ {
+ mail_line[STATMBX_BUF_SIZE-1] = '\0';
+ if (strncmp(mail_line, "From ", 5) == 0)
+ {
+ if (inhdr)
+ {
+ printf("statmbx: error, corrupt mail file \"%s\"",
+ mailbox_fname);
+ exit(-1);
+ }
+
+ seen_status_read = 0;
+ inhdr = 1;
+ cur_name[0] = '\0';
+ cur_subj[0] = '\0';
+ }
+ else if(inhdr)
+ {
+ if(mail_line[0] == '\n')
+ {
+ if (!seen_status_read)
+ {
+ if (just_print_names)
+ {
+ printf("%s ", mailbox_title);
+ break; /* next file */
+ }
+
+ new_msgs++;
+ if (!printed_title)
+ {
+ printed_title = 1;
+ printf("\n");
+ statmbx_printMaybeBold(mailbox_title);
+ printf("\n");
+ }
+
+ statmbx_printName(cur_name, cur_subj);
+
+ }
+ msgs++;
+ inhdr = 0;
+ }
+ else /*line in the header */
+ {
+ if (strncmp(mail_line, "Status: R", 9) == 0)
+ seen_status_read = 1;
+ else if(strncmp(mail_line, "From: ", 6) == 0)
+ strncpy(cur_name, mail_line, STATMBX_BUF_SIZE);
+ else if(strncasecmp(mail_line, "Subject: ", 9) == 0)
+ strncpy(cur_subj, mail_line, STATMBX_BUF_SIZE);
+ }
+ }
+ }
+ }
+ n++;
+ }
+
+ if (just_print_names)
+ printf("\n");
+
+
+ fclose(config_file);
+}
|
plouj/testHudsonSelect
|
dfc4a3174a7457ec0b70a6e9c6129f44a1d099e4
|
trying to write a unit test - does not work
|
diff --git a/pom.xml b/pom.xml
index f24fcda..13ed5f6 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,29 +1,29 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jvnet.hudson.plugins</groupId>
<artifactId>plugin</artifactId>
- <version>1.360</version><!-- which version of Hudson is this plugin built against? -->
+ <version>1.355</version><!-- which version of Hudson is this plugin built against? -->
<relativePath>../pom.xml</relativePath>
</parent>
<groupId>com.example</groupId>
<artifactId>testRecorder</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>hpi</packaging>
<!-- get every artifact through maven.glassfish.org, which proxies all the artifacts that we need -->
<repositories>
<repository>
<id>m.g.o-public</id>
<url>http://maven.glassfish.org/content/groups/public/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>m.g.o-public</id>
<url>http://maven.glassfish.org/content/groups/public/</url>
</pluginRepository>
</pluginRepositories>
</project>
diff --git a/src/test/java/com/example/HelloWorldTests.java b/src/test/java/com/example/HelloWorldTests.java
new file mode 100644
index 0000000..787ef71
--- /dev/null
+++ b/src/test/java/com/example/HelloWorldTests.java
@@ -0,0 +1,21 @@
+package com.example;
+
+import org.jvnet.hudson.test.HudsonTestCase;
+import org.apache.commons.io.FileUtils;
+import hudson.model.*;
+import hudson.tasks.Shell;
+
+public class HelloWorldTests extends HudsonTestCase
+{
+ public void test1() throws Exception {
+ FreeStyleProject project = createFreeStyleProject();
+ project.getBuildersList().add(new Shell("echo hello"));
+
+ FreeStyleBuild build = project.scheduleBuild2(0).get();
+ System.out.println(build.getDisplayName()+" completed");
+
+ // TODO: change this to use HtmlUnit
+ String s = FileUtils.readFileToString(build.getLogFile());
+ assertTrue(s.contains("+ echo hello"));
+ }
+}
\ No newline at end of file
|
plouj/testHudsonSelect
|
ca4e20bad7186821574cc39767d0456ea83456c1
|
example where f:select inside f:repeatable does not get properly set from saved-to-disk values
|
diff --git a/src/main/java/com/example/HelloWorldBuilder.java b/src/main/java/com/example/HelloWorldBuilder.java
index b074aaf..6536bda 100644
--- a/src/main/java/com/example/HelloWorldBuilder.java
+++ b/src/main/java/com/example/HelloWorldBuilder.java
@@ -1,91 +1,99 @@
package com.example;
import hudson.Launcher;
import hudson.Extension;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.AbstractProject;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Builder;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import hudson.tasks.Recorder;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.QueryParameter;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
public class HelloWorldBuilder extends Recorder {
- public final String selectedOption;
+ public final ArrayList<Configurable> configurables;
@DataBoundConstructor
- public HelloWorldBuilder(String selectedOption) {
- this.selectedOption = selectedOption;
+ public HelloWorldBuilder(ArrayList<Configurable> configurables) {
+ this.configurables = configurables;
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
- listener.getLogger().println("selected option=" + selectedOption);
return true;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
@Extension // this marker indicates Hudson that this is an implementation of an extension point.
public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public ArrayList<Option> globalOptions;
public ListBoxModel doFillSelectedOptionItems() {
ListBoxModel m = new ListBoxModel();
if (globalOptions != null) {
for (Option o : globalOptions) {
m.add(o.name, o.name);
}
}
return m;
}
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "Test selection";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
this.globalOptions = new ArrayList<Option>(req.bindJSONToList(
Option.class, formData.get("globalOptions")));
save();
return super.configure(req,formData);
}
public static final class Option {
public String name;
@DataBoundConstructor
public Option(String name) {
this.name = name;
}
}
}
+ public static final class Configurable {
+ public String selectedOption;
+
+ @DataBoundConstructor
+ public Configurable(String selectedOption) {
+ this.selectedOption = selectedOption;
+ }
+ }
+
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
}
diff --git a/src/main/resources/com/example/HelloWorldBuilder/config.jelly b/src/main/resources/com/example/HelloWorldBuilder/config.jelly
index 0708aa0..14ce470 100644
--- a/src/main/resources/com/example/HelloWorldBuilder/config.jelly
+++ b/src/main/resources/com/example/HelloWorldBuilder/config.jelly
@@ -1,7 +1,16 @@
<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define"
xmlns:l="/lib/layout" xmlns:t="/lib/hudson" xmlns:f="/lib/form">
- <f:entry title="Select an option:">
- <f:select field="selectedOption" />
- </f:entry>
+ <f:section title="Configurables">
+ <f:entry> <!-- this empty entry is necessary for proper HTML output -->
+ <f:repeatable var="configurable" items="${instance.configurables}"
+ name="configurables">
+ <table width="100%">
+ <f:entry title="Select an option:">
+ <f:select field="selectedOption" />
+ </f:entry>
+ </table>
+ </f:repeatable>
+ </f:entry>
+ </f:section>
</j:jelly>
\ No newline at end of file
|
plouj/testHudsonSelect
|
86cb5b9a0afd12168ee8940b81f0295e33189687
|
go to the minimum hudson version in which selection doFill actually works for f:select
|
diff --git a/pom.xml b/pom.xml
index 13ed5f6..27fbe9e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,29 +1,29 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jvnet.hudson.plugins</groupId>
<artifactId>plugin</artifactId>
- <version>1.355</version><!-- which version of Hudson is this plugin built against? -->
+ <version>1.357</version><!-- which version of Hudson is this plugin built against? -->
<relativePath>../pom.xml</relativePath>
</parent>
<groupId>com.example</groupId>
<artifactId>testRecorder</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>hpi</packaging>
<!-- get every artifact through maven.glassfish.org, which proxies all the artifacts that we need -->
<repositories>
<repository>
<id>m.g.o-public</id>
<url>http://maven.glassfish.org/content/groups/public/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>m.g.o-public</id>
<url>http://maven.glassfish.org/content/groups/public/</url>
</pluginRepository>
</pluginRepositories>
</project>
|
plouj/testHudsonSelect
|
6c549ce632a9b66ac239b71c13759915686a4738
|
initial version - selection dropdown menu does not show the options configured globally
|
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000..13ed5f6
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,29 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.jvnet.hudson.plugins</groupId>
+ <artifactId>plugin</artifactId>
+ <version>1.355</version><!-- which version of Hudson is this plugin built against? -->
+ <relativePath>../pom.xml</relativePath>
+ </parent>
+
+ <groupId>com.example</groupId>
+ <artifactId>testRecorder</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ <packaging>hpi</packaging>
+
+ <!-- get every artifact through maven.glassfish.org, which proxies all the artifacts that we need -->
+ <repositories>
+ <repository>
+ <id>m.g.o-public</id>
+ <url>http://maven.glassfish.org/content/groups/public/</url>
+ </repository>
+ </repositories>
+
+ <pluginRepositories>
+ <pluginRepository>
+ <id>m.g.o-public</id>
+ <url>http://maven.glassfish.org/content/groups/public/</url>
+ </pluginRepository>
+ </pluginRepositories>
+</project>
diff --git a/src/main/java/com/example/HelloWorldBuilder.java b/src/main/java/com/example/HelloWorldBuilder.java
new file mode 100644
index 0000000..b074aaf
--- /dev/null
+++ b/src/main/java/com/example/HelloWorldBuilder.java
@@ -0,0 +1,91 @@
+package com.example;
+import hudson.Launcher;
+import hudson.Extension;
+import hudson.util.FormValidation;
+import hudson.util.ListBoxModel;
+import hudson.model.AbstractBuild;
+import hudson.model.BuildListener;
+import hudson.model.AbstractProject;
+import hudson.tasks.BuildStepMonitor;
+import hudson.tasks.Builder;
+import hudson.tasks.BuildStepDescriptor;
+import hudson.tasks.Publisher;
+import hudson.tasks.Recorder;
+import net.sf.json.JSONObject;
+import org.kohsuke.stapler.DataBoundConstructor;
+import org.kohsuke.stapler.StaplerRequest;
+import org.kohsuke.stapler.QueryParameter;
+
+import javax.servlet.ServletException;
+import java.io.IOException;
+import java.util.ArrayList;
+
+public class HelloWorldBuilder extends Recorder {
+
+ public final String selectedOption;
+
+ @DataBoundConstructor
+ public HelloWorldBuilder(String selectedOption) {
+ this.selectedOption = selectedOption;
+ }
+
+ @Override
+ public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
+ listener.getLogger().println("selected option=" + selectedOption);
+ return true;
+ }
+
+ @Override
+ public DescriptorImpl getDescriptor() {
+ return (DescriptorImpl)super.getDescriptor();
+ }
+
+ @Extension // this marker indicates Hudson that this is an implementation of an extension point.
+ public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
+
+ public ArrayList<Option> globalOptions;
+
+ public ListBoxModel doFillSelectedOptionItems() {
+ ListBoxModel m = new ListBoxModel();
+ if (globalOptions != null) {
+ for (Option o : globalOptions) {
+ m.add(o.name, o.name);
+ }
+ }
+ return m;
+ }
+
+ public boolean isApplicable(Class<? extends AbstractProject> aClass) {
+ return true;
+ }
+
+ /**
+ * This human readable name is used in the configuration screen.
+ */
+ public String getDisplayName() {
+ return "Test selection";
+ }
+
+ @Override
+ public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
+ this.globalOptions = new ArrayList<Option>(req.bindJSONToList(
+ Option.class, formData.get("globalOptions")));
+ save();
+ return super.configure(req,formData);
+ }
+
+ public static final class Option {
+ public String name;
+
+ @DataBoundConstructor
+ public Option(String name) {
+ this.name = name;
+ }
+ }
+ }
+
+ public BuildStepMonitor getRequiredMonitorService() {
+ return BuildStepMonitor.NONE;
+ }
+}
+
diff --git a/src/main/resources/com/example/HelloWorldBuilder/config.jelly b/src/main/resources/com/example/HelloWorldBuilder/config.jelly
new file mode 100644
index 0000000..0708aa0
--- /dev/null
+++ b/src/main/resources/com/example/HelloWorldBuilder/config.jelly
@@ -0,0 +1,7 @@
+<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define"
+ xmlns:l="/lib/layout" xmlns:t="/lib/hudson" xmlns:f="/lib/form">
+
+ <f:entry title="Select an option:">
+ <f:select field="selectedOption" />
+ </f:entry>
+</j:jelly>
\ No newline at end of file
diff --git a/src/main/resources/com/example/HelloWorldBuilder/global.jelly b/src/main/resources/com/example/HelloWorldBuilder/global.jelly
new file mode 100644
index 0000000..0fb165b
--- /dev/null
+++ b/src/main/resources/com/example/HelloWorldBuilder/global.jelly
@@ -0,0 +1,20 @@
+<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define"
+ xmlns:l="/lib/layout" xmlns:t="/lib/hudson" xmlns:f="/lib/form">
+ <f:section title="Simple Select">
+ <f:entry> <!-- this empty entry is necessary for proper HTML output -->
+ <f:repeatable var="option" items="${descriptor.globalOptions}"
+ name="globalOptions">
+ <table width="100%">
+ <f:entry title="Option:">
+ <f:textbox field="name" value="${option.name}" />
+ </f:entry>
+ <f:entry title="">
+ <div align="right">
+ <f:repeatableDeleteButton />
+ </div>
+ </f:entry>
+ </table>
+ </f:repeatable>
+ </f:entry>
+ </f:section>
+</j:jelly>
diff --git a/src/main/resources/index.jelly b/src/main/resources/index.jelly
new file mode 100644
index 0000000..de6361c
--- /dev/null
+++ b/src/main/resources/index.jelly
@@ -0,0 +1,8 @@
+<!--
+ This view is used to render the plugin list page.
+
+ Since we don't really have anything dynamic here, let's just use static HTML.
+-->
+<div>
+ This plugin is a sample plugin to explain how to write a Hudson plugin.
+</div>
\ No newline at end of file
|
thedoct/vincitrentino
|
198170337eed779215f8905353116d7b4a4be283
|
primo commit della storia
|
diff --git a/README b/README
index ee85649..775ae19 100644
--- a/README
+++ b/README
@@ -1 +1 @@
-RUL3Z
\ No newline at end of file
+RUL3ZZ
\ No newline at end of file
|
thedoct/vincitrentino
|
46f488ee3745ba1ff3939efa1cb5b1b1c8a0c197
|
primo commit della storia
|
diff --git a/README b/README
new file mode 100644
index 0000000..e69de29
|
miki/Statistics-Associations
|
408de1e6448fdae6e831d79eb170ef6b2249b268
|
ã¢ã½ã·ã¨ã¼ã·ã§ã³
|
diff --git a/Changes b/Changes
new file mode 100644
index 0000000..e99f463
--- /dev/null
+++ b/Changes
@@ -0,0 +1,13 @@
+Revision history for Perl extension Statistics::Associations
+
+0.00003 2008/11/19
+ - fix a bug in case that is called without make_matrix()
+ - fix a typo in docs ( 'contingenvy -> 'contingency' )
+ - add some error cases
+ - add test codes
+
+0.00002 2008/11/18
+ - fix a typo in docs ( 'Normal Scale' -> 'Nominal Scale' )
+
+0.00001 2008/11/18
+ - original version
diff --git a/Makefile.PL b/Makefile.PL
new file mode 100644
index 0000000..b6a6296
--- /dev/null
+++ b/Makefile.PL
@@ -0,0 +1,8 @@
+use inc::Module::Install;
+name 'Statistics-Associations';
+all_from 'lib/Statistics/Associations.pm';
+requires 'Carp';
+build_requires 'Test::More';
+use_test_base;
+auto_include;
+WriteAll;
diff --git a/README b/README
new file mode 100644
index 0000000..c9019a9
--- /dev/null
+++ b/README
@@ -0,0 +1,27 @@
+This is Perl module Statistics::Associations.
+
+INSTALLATION
+
+Statistics::Associations installation is straightforward. If your CPAN shell is set up,
+you should just be able to do
+
+ % cpan Statistics::Associations
+
+Download it, unpack it, then build it as per the usual:
+
+ % perl Makefile.PL
+ % make && make test
+
+Then install it:
+
+ % make install
+
+DOCUMENTATION
+
+Statistics::Associations documentation is available as in POD. So you can do:
+
+ % perldoc Statistics::Associations
+
+to read the documentation online with your favorite pager.
+
+takeshi miki
diff --git a/lib/Statistics/Associations.pm b/lib/Statistics/Associations.pm
new file mode 100644
index 0000000..1c6e48b
--- /dev/null
+++ b/lib/Statistics/Associations.pm
@@ -0,0 +1,242 @@
+package Statistics::Associations;
+
+use strict;
+use Carp;
+our $VERSION = '0.00003';
+
+sub new {
+ my $class = shift;
+ my $self = bless {@_}, $class;
+ return $self;
+}
+
+sub phi {
+ my $self = shift;
+ my $matrix = shift;
+ unless ( ref $matrix eq 'ARRAY' && ref $matrix->[0] eq 'ARRAY' ) {
+ croak("ERROR: invalid matrix is posted");
+ }
+ my $phi = sqrt( $self->chisq($matrix) / $self->_sum($matrix) );
+ return $phi;
+}
+
+sub contingency {
+ my $self = shift;
+ my $matrix = shift;
+ unless ( ref $matrix eq 'ARRAY' && ref $matrix->[0] eq 'ARRAY' ) {
+ croak("ERROR: invalid matrix is posted");
+ }
+ my $x2 = $self->chisq($matrix);
+ my $contingency = sqrt( $x2 / ( $self->_sum($matrix) + $x2 ) );
+ return $contingency;
+}
+
+sub cramer {
+ my $self = shift;
+ my $matrix = shift;
+ unless ( ref $matrix eq 'ARRAY' && ref $matrix->[0] eq 'ARRAY' ) {
+ croak("ERROR: invalid matrix is posted");
+ }
+ my $row_num = @$matrix;
+ my $col_num = @{ $matrix->[0] };
+ my $n;
+ $n = $col_num if ( @$matrix >= @{ $matrix->[0] } );
+ $n = $row_num if ( @$matrix <= @{ $matrix->[0] } );
+ my $cramer = $self->phi($matrix) / sqrt( $n - 1 );
+ return $cramer;
+}
+
+sub chisq {
+ my $self = shift;
+ my $matrix = shift;
+ unless ( ref $matrix eq 'ARRAY' && ref $matrix->[0] eq 'ARRAY' ) {
+ croak("ERROR: invalid matrix is posted");
+ }
+ $self->{matrix} = $matrix;
+ $self->{row_count} = @$matrix;
+ $self->{col_count} = @{ $matrix->[0] };
+ my $x2;
+ for my $i ( 0 .. $self->{row_count} - 1 ) {
+ for my $j ( 0 .. $self->{col_count} - 1 ) {
+ my $row_sum = $self->_row_sum($i);
+ my $col_sum = $self->_col_sum($j);
+ my $sum = $self->_sum;
+ my $expect = $row_sum * $col_sum / $sum;
+ $expect ||= 0.00000000000001;
+ $x2 += ( $matrix->[$i]->[$j] - $expect )**2 / $expect;
+ }
+ }
+ return $x2;
+}
+
+sub _row_sum {
+ my $self = shift;
+ my $row_num = shift;
+ $self->{row_sum}->[$row_num] or sub {
+ my $sum;
+ for my $i ( 0 .. $self->{col_count} - 1 ) {
+ $sum += $self->{matrix}->[$row_num]->[$i];
+ }
+ $self->{row_sum}->[$row_num] = $sum;
+ }
+ ->();
+}
+
+sub _col_sum {
+ my $self = shift;
+ my $col_num = shift;
+ $self->{col_sum}->[$col_num] or sub {
+ my $sum;
+ for my $i ( 0 .. $self->{row_count} - 1 ) {
+ $sum += $self->{matrix}->[$i]->[$col_num];
+ }
+ $self->{col_sum}->[$col_num] = $sum;
+ }
+ ->();
+}
+
+sub _sum {
+ my $self = shift;
+ my $sum;
+ $self->{sum} or sub {
+ for my $i ( 0 .. $self->{row_count} - 1 ) {
+ for my $j ( 0 .. $self->{col_count} - 1 ) {
+ $sum += $self->{matrix}->[$i]->[$j];
+ }
+ }
+ $self->{sum} = $sum;
+ }
+ ->();
+}
+
+sub make_matrix {
+ my $self = shift;
+ my $row_label = shift;
+ my $col_label = shift;
+ my $value = shift;
+ unless ( defined $row_label ) {
+ croak("ERROR: undefined row_label is posted");
+ }
+ unless ( defined $col_label ) {
+ croak("ERROR: undefined col_label is posted");
+ }
+ unless ( defined $value ) { $value = 1; }
+ my $row_num = $self->_key2num( { row => $row_label } );
+ my $col_num = $self->_key2num( { col => $col_label } );
+ $self->{matrix}->[$row_num]->[$col_num] += $value;
+}
+
+sub _key2num {
+ my $self = shift;
+ my $ref = shift;
+ my ( $row_or_col, $label ) = each %$ref;
+ my $num = $self->{$row_or_col}->{$label} ||=
+ ++$self->{ $row_or_col . '_count' };
+ $num = $num - 1;
+ $self->{ $row_or_col . '_label' }->[$num] = $label;
+ return $num;
+}
+
+sub matrix {
+ my $self = shift;
+ for my $i ( 0 .. $self->{row_count} - 1 ) {
+ for my $j ( 0 .. $self->{col_count} - 1 ) {
+ $self->{matrix}->[$i]->[$j] ||= 0;
+ }
+ }
+ return $self->{matrix} || [];
+}
+
+sub convert_hashref {
+ my $self = shift;
+ my $hash = {};
+ for my $i ( 0 .. $self->{row_count} - 1 ) {
+ for my $j ( 0 .. $self->{col_count} - 1 ) {
+ my $row_label = $self->{row_label}->[$i];
+ my $col_label = $self->{col_label}->[$j];
+ $hash->{$row_label}->{$col_label} = $self->{matrix}->[$i]->[$j];
+ }
+ }
+ return $hash;
+}
+
+1;
+__END__
+
+=head1 NAME
+
+Statistics::Associations - Calculates Association Coefficients of Nominal Scale.
+
+=head1 SYNOPSIS
+
+ use Statistics::Associations;
+ my $asso = Statistics::Associations->new;
+
+ # Basic Methods
+ # calculates coefficients
+
+ my $matrix = [ [ 6, 4 ], [ 5, 5 ] ];
+ my $phi = $asso->phi($matrix);
+ my $contingency = $asso->contingency($matrix);
+ my $cramer = $asso->cramer($matrix);
+
+ # -------------------
+
+ # Helper Methods
+ # it helps you to making matrix
+
+ while(<STDIN>){
+ my $row_label = ...;
+ my $col_label = ...;
+ my $value = ...;
+ $asso->make_matrix( $row_label, $col_label, $value );
+ }
+ my $matrix = $asso->matrix;
+
+ # convert to hash_ref
+ my $hash_ref = $asso->convert_hashref;
+
+=head1 DESCRIPTION
+
+Statistics::Associations is a calculator of Association Coefficients that specialized in 'Nominal Scale'.
+
+It calculates next three coeffients.
+
+ * phi
+ * contingency
+ * cramer
+
+And it calculates chi-square, too.
+
+And then, it helps you to making matrix in a loop that looks like parsing logs.
+
+=head1 METHODS
+
+=head2 new
+
+=head2 phi( $matrix )
+
+=head2 contingency( $matrix )
+
+=head2 cramer( $matrix )
+
+=head2 chisq( $matrix )
+
+=head2 make_matrix( $row_label, $col_label, [$value] )
+
+=head2 matrix()
+
+=head2 convert_hashref()
+
+=head1 AUTHOR
+
+takeshi miki E<lt>[email protected]<gt>
+
+=head1 LICENSE
+
+This library is free software; you can redistribute it and/or modify
+it under the same terms as Perl itself.
+
+=head1 SEE ALSO
+
+=cut
diff --git a/t/00_compile.t b/t/00_compile.t
new file mode 100644
index 0000000..5ee50c8
--- /dev/null
+++ b/t/00_compile.t
@@ -0,0 +1,4 @@
+use strict;
+use Test::More tests => 1;
+
+BEGIN { use_ok 'Statistics::Associations' }
diff --git a/t/10_phi.t b/t/10_phi.t
new file mode 100644
index 0000000..8febe5e
--- /dev/null
+++ b/t/10_phi.t
@@ -0,0 +1,49 @@
+use strict;
+use Statistics::Associations;
+use Test::More tests => 2;
+
+
+# phi() test
+{
+ my $asso = Statistics::Associations->new;
+ while (<DATA>) {
+ chomp $_;
+ my ( $sex, $like_or_unlike ) = split( /\s/, $_ );
+ $asso->make_matrix( $sex, $like_or_unlike, 3 );
+ }
+ my $matrix = $asso->matrix;
+ my $phi = $asso->phi($matrix);
+ is($phi, '0.100503781525921','phi() returns correct data');
+}
+
+# phi() without make_matrix() test
+{
+ my $asso = Statistics::Associations->new;
+ my $matrix = [
+ [ 100, 98, 89, 3, 4, 14, 8],
+ [ 2, 11, 4, 86, 79, 99, 95],
+ ];
+ my $phi = $asso->phi($matrix);
+ is($phi, '0.869032948250183', 'phi() without make_matrix() returns correct data');
+}
+__DATA__
+man like
+man unlike
+woman like
+man unlike
+woman like
+man like
+woman unlike
+woman unlike
+man like
+man unlike
+woman unlike
+man like
+man like
+woman like
+woman like
+man like
+woman unlike
+woman like
+man unlike
+woman unlike
\ No newline at end of file
diff --git a/t/11_contingency.t b/t/11_contingency.t
new file mode 100644
index 0000000..fba50f8
--- /dev/null
+++ b/t/11_contingency.t
@@ -0,0 +1,49 @@
+use strict;
+use Statistics::Associations;
+use Test::More tests => 2;
+
+# contingency() test
+{
+ my $asso = Statistics::Associations->new;
+ while (<DATA>) {
+ chomp $_;
+ my ( $sex, $like_or_unlike ) = split( /\s/, $_ );
+ $asso->make_matrix( $sex, $like_or_unlike, 1 );
+ }
+ my $matrix = $asso->matrix;
+ my $contingency = $asso->contingency($matrix);
+ is( $contingency, '0.1', 'contingency() returns correct data' );
+}
+
+# contingency() without make_matrix() test
+{
+ my $asso = Statistics::Associations->new;
+ my $matrix = [
+ [ 100, 98, 89, 3, 4, 14, 8],
+ [ 2, 11, 4, 86, 79, 99, 95],
+ ];
+ my $contingency = $asso->contingency($matrix);
+ is( $contingency, '0.655949911287953', 'contingency() without make_matrix() returns correct data' );
+}
+
+__DATA__
+man like
+man unlike
+woman like
+man unlike
+woman like
+man like
+woman unlike
+woman unlike
+man like
+man unlike
+woman unlike
+man like
+man like
+woman like
+woman like
+man like
+woman unlike
+woman like
+man unlike
+woman unlike
\ No newline at end of file
diff --git a/t/12_cramer.t b/t/12_cramer.t
new file mode 100644
index 0000000..3edb196
--- /dev/null
+++ b/t/12_cramer.t
@@ -0,0 +1,48 @@
+use strict;
+use Statistics::Associations;
+use Test::More tests => 2;
+
+# cramer() test
+{
+ my $asso = Statistics::Associations->new;
+ while (<DATA>) {
+ chomp $_;
+ my ( $sex, $like_or_unlike ) = split( /\s/, $_ );
+ $asso->make_matrix( $sex, $like_or_unlike, 1 );
+ }
+ my $matrix = $asso->matrix;
+ my $cramer = $asso->cramer($matrix);
+ is( $cramer, '0.100503781525921', 'cramer() returns correct data' );
+}
+
+# cramer() without make_matrix() test
+{
+ my $asso = Statistics::Associations->new;
+ my $matrix = [
+ [ 100, 98, 89, 3, 4, 14, 8],
+ [ 2, 11, 4, 86, 79, 99, 95],
+ ];
+ my $cramer = $asso->cramer($matrix);
+ is( $cramer, '0.869032948250183', 'cramer() without make_matrix() returns correct data' );
+}
+__DATA__
+man like
+man unlike
+woman like
+man unlike
+woman like
+man like
+woman unlike
+woman unlike
+man like
+man unlike
+woman unlike
+man like
+man like
+woman like
+woman like
+man like
+woman unlike
+woman like
+man unlike
+woman unlike
\ No newline at end of file
diff --git a/t/13_chisq.t b/t/13_chisq.t
new file mode 100644
index 0000000..cd50ee9
--- /dev/null
+++ b/t/13_chisq.t
@@ -0,0 +1,39 @@
+use strict;
+use Statistics::Associations;
+use Test::More tests => 1;
+
+my $asso = Statistics::Associations->new;
+while (<DATA>) {
+ chomp $_;
+ my ( $sex, $like_or_unlike ) = split( /\s/, $_ );
+ $asso->make_matrix( $sex, $like_or_unlike, 1 );
+}
+
+# chisq() test
+{
+ my $matrix = $asso->matrix;
+ my $chisq = $asso->chisq($matrix);
+ is( $chisq, '0.202020202020202', 'chisq() returns correct data' );
+}
+
+__DATA__
+man like
+man unlike
+woman like
+man unlike
+woman like
+man like
+woman unlike
+woman unlike
+man like
+man unlike
+woman unlike
+man like
+man like
+woman like
+woman like
+man like
+woman unlike
+woman like
+man unlike
+woman unlike
\ No newline at end of file
diff --git a/t/20_make_matrix.t b/t/20_make_matrix.t
new file mode 100644
index 0000000..406a560
--- /dev/null
+++ b/t/20_make_matrix.t
@@ -0,0 +1,55 @@
+use strict;
+use Statistics::Associations;
+use Test::More tests => 1;
+
+my $asso = Statistics::Associations->new;
+while (<DATA>) {
+ chomp $_;
+ my ( $sex, $like_or_unlike ) = split( /\s/, $_ );
+ $asso->make_matrix( $sex, $like_or_unlike, 1 );
+}
+
+# object test
+{
+ my $correct = bless(
+ {
+ 'col_count' => 2,
+ 'col_label' => [ 'like', 'unlike' ],
+ 'col' => {
+ 'unlike' => 2,
+ 'like' => 1
+ },
+ 'row' => {
+ 'woman' => 2,
+ 'man' => 1
+ },
+ 'row_count' => 2,
+ 'matrix' => [ [ 6, 4 ], [ 5, 5 ] ],
+ 'row_label' => [ 'man', 'woman' ]
+ },
+ 'Statistics::Associations'
+ );
+ is_deeply( $asso, $correct, "make_matric() makes correct object" );
+}
+
+__DATA__
+man like
+man unlike
+woman like
+man unlike
+woman like
+man like
+woman unlike
+woman unlike
+man like
+man unlike
+woman unlike
+man like
+man like
+woman like
+woman like
+man like
+woman unlike
+woman like
+man unlike
+woman unlike
\ No newline at end of file
diff --git a/t/21_matrix.t b/t/21_matrix.t
new file mode 100644
index 0000000..d31d44d
--- /dev/null
+++ b/t/21_matrix.t
@@ -0,0 +1,39 @@
+use strict;
+use Statistics::Associations;
+use Test::More tests => 1;
+
+my $asso = Statistics::Associations->new;
+while (<DATA>) {
+ chomp $_;
+ my ( $sex, $like_or_unlike ) = split( /\s/, $_ );
+ $asso->make_matrix( $sex, $like_or_unlike, 1 );
+}
+
+# matrix() test
+{
+ my $matrix = $asso->matrix;
+ my $correct = [ [ 6, 4 ], [ 5, 5 ] ];
+ is_deeply( $matrix, $correct, "matrix() returns correct array_ref" );
+}
+
+__DATA__
+man like
+man unlike
+woman like
+man unlike
+woman like
+man like
+woman unlike
+woman unlike
+man like
+man unlike
+woman unlike
+man like
+man like
+woman like
+woman like
+man like
+woman unlike
+woman like
+man unlike
+woman unlike
\ No newline at end of file
diff --git a/t/22_convert_hashref.t b/t/22_convert_hashref.t
new file mode 100644
index 0000000..26be72f
--- /dev/null
+++ b/t/22_convert_hashref.t
@@ -0,0 +1,48 @@
+use strict;
+use Statistics::Associations;
+use Test::More tests => 1;
+
+my $asso = Statistics::Associations->new;
+while (<DATA>) {
+ chomp $_;
+ my ( $sex, $like_or_unlike ) = split( /\s/, $_ );
+ $asso->make_matrix( $sex, $like_or_unlike, 1 );
+}
+
+# convert_hash() test
+{
+ my $hash_ref = $asso->convert_hashref;
+ my $correct = {
+ 'woman' => {
+ 'unlike' => 5,
+ 'like' => 5
+ },
+ 'man' => {
+ 'unlike' => 4,
+ 'like' => 6
+ }
+ };
+ is_deeply( $hash_ref, $correct, "convert_hashref() returns correct hash_ref" );
+}
+
+__DATA__
+man like
+man unlike
+woman like
+man unlike
+woman like
+man like
+woman unlike
+woman unlike
+man like
+man unlike
+woman unlike
+man like
+man like
+woman like
+woman like
+man like
+woman unlike
+woman like
+man unlike
+woman unlike
\ No newline at end of file
diff --git a/t/30_error.t b/t/30_error.t
new file mode 100644
index 0000000..8ce86b3
--- /dev/null
+++ b/t/30_error.t
@@ -0,0 +1,81 @@
+use strict;
+use Statistics::Associations;
+use Test::More tests => 6;
+
+my $asso = Statistics::Associations->new;
+
+# argument of make_matrix() is not enough
+{
+
+ # no args
+ eval { $asso->make_matrix(); };
+ if ($@) {
+ like(
+ $@,
+ qr/ERROR: undefined row_label is posted/,
+ 'make_matrix() returns error message-1'
+ );
+ }
+
+ # one args
+ eval { $asso->make_matrix("row"); };
+ if ($@) {
+ like(
+ $@,
+ qr/ERROR: undefined col_label is posted/,
+ 'make_matrix() returns error message-2'
+ );
+ }
+}
+
+# phi() is called without matrix
+{
+ my $matrix = [ [ 0, 0, 0, 3 ], [ 1, 0, 3, 4 ], [ 3, 0, 2, 9 ], ];
+ eval { my $phi = $asso->phi(); };
+ if ($@) {
+ like(
+ $@,
+ qr/ERROR: invalid matrix is posted/,
+ 'phi() returns error message'
+ );
+ }
+}
+
+# contingency() is called without matrix
+{
+ my $matrix = [ [ 0, 0, 0, 3 ], [ 1, 0, 3, 4 ], [ 3, 0, 2, 9 ], ];
+ eval { my $contingency = $asso->contingency(); };
+ if ($@) {
+ like(
+ $@,
+ qr/ERROR: invalid matrix is posted/,
+ 'contingency() returns error message'
+ );
+ }
+}
+
+# cramer() is called without matrix
+{
+ my $matrix = [ [ 0, 0, 0, 3 ], [ 1, 0, 3, 4 ], [ 3, 0, 2, 9 ], ];
+ eval { my $cramer = $asso->cramer(); };
+ if ($@) {
+ like(
+ $@,
+ qr/ERROR: invalid matrix is posted/,
+ 'cramer() returns error message'
+ );
+ }
+}
+
+# chisq() is called without matrix
+{
+ my $matrix = [ [ 0, 0, 0, 3 ], [ 1, 0, 3, 4 ], [ 3, 0, 2, 9 ], ];
+ eval { my $chisq = $asso->chisq(); };
+ if ($@) {
+ like(
+ $@,
+ qr/ERROR: invalid matrix is posted/,
+ 'chisq() returns error message'
+ );
+ }
+}
diff --git a/t/97_kwalitee.t b/t/97_kwalitee.t
new file mode 100644
index 0000000..39591ac
--- /dev/null
+++ b/t/97_kwalitee.t
@@ -0,0 +1,3 @@
+use Test::More;
+eval { require Test::Kwalitee; Test::Kwalitee->import() };
+plan( skip_all => 'Test::Kwalitee not installed; skipping' ) if $@;
diff --git a/t/98_pod-coverage.t b/t/98_pod-coverage.t
new file mode 100644
index 0000000..bc7bd54
--- /dev/null
+++ b/t/98_pod-coverage.t
@@ -0,0 +1,15 @@
+use strict;
+use Test::More;
+BEGIN {
+ unless ( !$ENV{TEST_POD} ) {
+
+ plan skip_all => "Enable TEST_POD environment variable to test POD";
+ }
+ else {
+ eval "use Test::Pod::Coverage";
+ plan skip_all =>
+ "Test::Pod::Coverage required for testting pod coverage"
+ if $@;
+ Test::Pod::Coverage::all_pod_coverage_ok();
+ }
+}
diff --git a/t/99_pod.t b/t/99_pod.t
new file mode 100644
index 0000000..437887a
--- /dev/null
+++ b/t/99_pod.t
@@ -0,0 +1,4 @@
+use Test::More;
+eval "use Test::Pod 1.00";
+plan skip_all => "Test::Pod 1.00 required for testing POD" if $@;
+all_pod_files_ok();
|
AstraFIN/fields
|
954864ab3314d93753ce755ae1b14c15240ca08a
|
Generalized <=: and <=~ to do customizable effects.
|
diff --git a/Data/Record/Field/Combinators.hs b/Data/Record/Field/Combinators.hs
index 0773c8a..abc0833 100644
--- a/Data/Record/Field/Combinators.hs
+++ b/Data/Record/Field/Combinators.hs
@@ -1,133 +1,161 @@
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
-- | Field combinators.
module Data.Record.Field.Combinators
( -- * Basic combinators.
idL
, ( # )
, (#$ )
-- * Combinators for @'Functor'@s, @'Applicative'@s and
-- @'Monad'@s.
, (<.#>)
, (<#>)
, (<##>)
-- * Zippy assignment.
, (*#)
, (=*)
-- * Assignment and modification in a State monad.
+ , EffectAssignment(..)
+ , This(..)
, (<=:)
, (<=~)
-- * Utility combinator for comparisons etc.
, onField
) where
import Data.Record.Field.Basic
import Data.Record.Label hiding ((=:))
import qualified Control.Category as C
import Control.Applicative
import Control.Monad
import "monads-fd" Control.Monad.State.Class
cantSet :: String -> a
cantSet n = error $ n ++ ": cannot set values."
-- | Identity lens.
idL :: a :-> a
idL = C.id
-- | Field composition with arguments in OO-like order.
infixl 8 #
( # ) :: (Field a, Field b, Dst a ~ Src b) =>
a -> b -> Src a :-> Dst b
a # b = (field b) C.. (field a)
-- | Compose fields with ordinary functions. As functions are one-way,
-- the resulting field cannot be used to set values.
infixl 8 #$
(#$) :: (Field a) => a -> (Dst a -> b) -> Src a :-> b
ab #$ f = lens getter (cantSet "(#$)")
where getter a = f . getL (field ab) $ a
-- | Infix @'fmap'@ for fields.
--
-- Examples:
--
--
-- > persons <.#> firstName
--
-- > do (v1, v2) <- takeMVar mv <.#> (field1, field2)
-- > putStrLn . unlines $ [ "v1: " ++ show v1, "v2: " ++ show v2 ]
--
infixl 7 <.#>
(<.#>) :: (Functor f, Field a) => f (Src a) -> a -> f (Dst a)
f <.#> a = fmap (.# a) f
-- | @'Applicative'@ functor composition for fields.
--
-- > book .# characters <#> lastName
--
infixr 9 <#>
(<#>) :: (Applicative f, Field a, Field b, Dst a ~ f (Src b)) =>
a -> b -> Src a :-> f (Dst b)
ab <#> bc = lens getter setter
where getter = (fmap $ getL (field bc)) . getL (field ab)
-- the flip is so effects get performed for b first.
setter fc = modL (field ab) $
\fb -> flip (setL (field bc)) <$> fb <*> fc
-- | Flattening monadic composition for fields.
--
-- > person .# superior <##> superior <##> superior <##> superior
--
infixr 9 <##>
(<##>) :: (Monad m, Field a, Field b,
Dst a ~ m (Src b), Dst b ~ m c) =>
a -> b -> Src a :-> m c
ab <##> bc = lens getter setter
where getter = getL (field ab) >=> getL (field bc)
setter mc = modL (field ab) $
\mb -> do b <- mb
return $ setL (field bc) mc b
-- | Zippy field reference to be used with @('=*')@.
--
-- > [ rec1, rec2 ] *# field =* [ value1, value2 ]
--
infixl 7 *#
(*#) :: (Field b) => [Src b] -> [b] -> [Dst b]
rs *# as = zipWith (.#) rs as
-- | Zippy infix assignment to be used with @('*#')@.
infixl 8 =*
(=*) :: (Field a) => a -> [Dst a] -> [Src a :-> Src a]
a =* vs = [ a =: v | v <- vs ]
--- | Infix assignment for the State monad.
---
--- > (field1, field2) <=: (value1, value2)
---
-infix 3 <=:
-(<=:) :: (MonadState (Src a) m, Field a) =>
- a -> Dst a -> m ()
-a <=: v = modify (.# a =: v)
+-- | Class for customizing where you can do effectful assignment. @m@
+-- will probably usually be a @'Monad'@, but it can be any type
+-- constructor.
+--
+-- > a :: a
+-- > f :: b :-> v
+-- > v :: v
+-- > a .# f <=: v :: m (ReturnType a b m)
+--
+class EffectAssignment a b (m :: * -> *) where
+ type ReturnType a b m :: *
+ effectAssign :: (Field f, Src f ~ b, Dst f ~ v) =>
+ f -> v -> a -> m (ReturnType a b m)
+ effectModify :: (Field f, Src f ~ b, Dst f ~ v) =>
+ f -> (v -> v) -> a -> m (ReturnType a b m)
+ effectModify = error "effectModify not defined"
+
+infixl 8 <=:
+-- | Infix operator for effectful assignment.
+(<=:) :: (EffectAssignment a (Src f) m, Field f) =>
+ f -> Dst f -> a :-> m (ReturnType a (Src f) m)
+f <=: v = lens (effectAssign f v) (cantSet "effectAssign")
--- | Infix modification for the State monad.
+infixl 8 <=~
+-- | Infix operator for effectful modification.
+(<=~) :: (EffectAssignment a (Src f) m, Field f) =>
+ f -> (Dst f -> Dst f) -> a :-> m (ReturnType a (Src f) m)
+f <=~ g = lens (effectModify f g) (cantSet "effectModify")
+
+-- | Effectful assignment for the State monad.
--
--- > (field1, field2) <=~ (f, g)
+-- > f :: s :-> v
+-- > v :: v
+-- > This .# f <=: v :: (MonadState s m) => m ()
--
-infix 3 <=~
-(<=~) :: (MonadState (Src a) m, Field a) =>
- a -> (Dst a -> Dst a) -> m ()
-a <=~ f = modify (.# a =~ f)
+data This = This
+
+instance (MonadState s m) => EffectAssignment This s m where
+ type ReturnType This s m = ()
+ effectAssign f v This = modify $ \s -> s .# f =: v
+ effectModify f g This = modify $ \s -> s .# f =~ g
-- | Utility combinator in the manner of @'Data.Function.on'@.
--
-- > sortBy (compare `onField` (lastName,firstName)) persons
--
infixl 0 `onField`
onField :: (Field a) => (Dst a -> Dst a -> t) -> a -> Src a -> Src a -> t
onField f a r1 r2 = f (r1.#a) (r2.#a)
|
AstraFIN/fields
|
97f670c17569a1e5c2a96e004461109f69d19180
|
Fixed documentation regarding Indexable.
|
diff --git a/Data/Record/Field.hs b/Data/Record/Field.hs
index 24ea2be..3ef3db9 100644
--- a/Data/Record/Field.hs
+++ b/Data/Record/Field.hs
@@ -1,242 +1,241 @@
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeOperators #-}
-- | Using records, especially nested records, in Haskell can sometimes be
-- a bit of a chore. Fortunately, there are several libraries in hackage
-- to make working with records easier. This library is my attempt to
-- build on top of these libraries to make working with records even
-- more pleasant!
--
-- In most imperative languages, records are accessed using the infix
-- dot operator. Record fields can be read simply by suffixing a record
-- value with '.field' and they can be modified by simply assigning to
-- that location. Although this is not the only way to access records
-- (indeed, Haskell does not use it), many people (including myself)
-- like it. This library attempts to support this style for Haskell
-- records in the following manner:
--
-- > record.field.subfield becomes record .# field # subfield
-- > record.field = value becomes record .# field =: value
--
-- Of course, the infix assignment in Haskell is pure and doesn't
-- actually mutate anything. Rather, a modified version of the record is
-- returned.
--
-- Below, a detailed and commented usage example is presented.
--
-- > import Data.Record.Field
-- > import Data.Record.Label hiding ((=:))
--
-- Currently, @"fields"@ is built on top of @"fclabels"@, so we import
-- that package as well. We hide the @(=:)@ operator because that
-- operator is also used by @"fields"@ itself.
--
-- First, let's define some example data types and derive lenses for
-- them using @"fclabels"@.
--
-- > data Person = Person
-- > { _firstName :: String
-- > , _lastName :: String
-- > , _age :: Int
-- > , _superior :: Maybe Person
-- > } deriving Show
-- >
-- > data Book = Book
-- > { _title :: String
-- > , _author :: Person
-- > , _characters :: [Person]
-- > } deriving Show
-- >
-- > $(mkLabels [''Person, ''Book])
--
-- Now, let's define some example data.
--
-- > howard = Person "Howard" "Lovecraft" 46 Nothing
-- > charles = Person "Charles" "Ward" 26 Nothing
-- > marinus = Person "Marinus" "Willett" 56 Nothing
-- > william = Person "William" "Dyer" 53 Nothing
-- > frank = Person "Frank" "Pabodie" 49 Nothing
-- > herbert = Person "Herbert" "West" 32 Nothing
-- > abdul = Person "Abdul" "Alhazred" 71 Nothing
-- >
-- > mountains = Book "At the Mountains of Madness" undefined []
-- > caseOfCDW = Book "The Case of Charles Dexter Ward" undefined []
-- > reanimator = Book "Herbert West -- The Re-animator" undefined []
-- > necronomicon = Book "Necronomicon" undefined []
-- >
-- > persons = [howard, charles, marinus, herbert, william, frank, abdul]
-- > books = [mountains, caseOfCDW, reanimator, necronomicon]
--
-- Now, to look up a book's title, we can use the @('.#')@ operator,
-- which is the basis of all @"fields"@ functionality. @('.#')@ takes a
-- value of type @a@ and a @'Field'@ from @a@ to some other type (in
-- this case, 'String') and returns the value of that field. Since an
-- @"fclabels"@ lens is an instance of @'Field'@, we can just use the
-- lens directly.
--
-- > necronomicon .# title
-- > -- :: String
--
-- The @author@ field, however, was left undefined in the above
-- definition. We can set it using the @(=:)@ operator
--
-- > necronomicon .# author =: abdul
-- > -- :: Book
--
-- A notable detail is that the above expression parenthesizes as
-- @necronomicon .# (author =: abdul)@. The @(=:)@ operator takes a
-- @'Field'@ and a value for that @'Field'@ and returns a new @'Field'@
-- that, when read, returns a modified version of the record.
--
-- For the sake of the example, I will assume here that the subsequent
-- references to @necronomicon@ refer to this modified version (and
-- similarly for all other assignment examples below), even though
-- nothing is mutated in reality.
--
-- The @('=~')@ operator is similar, except that instead of a value, it
-- takes a function that modifies the previous value. For example
--
-- > howard .# age =~ succ
-- > -- :: Person
--
-- To access fields in nested records, @'Field'@s can be composed using
-- the @(#)@ combinator.
--
-- > necronomicon .# author # lastName
-- > -- :: String
--
-- If we wish to access a field of several records at once, we can use
-- the @('<.#>')@ operator, which can be used to access fields of
-- a record inside a @'Functor'@. For example
--
-- > persons <.#> age
-- > -- :: [Int]
--
-- This also works for assignment. For example, let's fix the @author@
-- fields of the rest of our books.
--
-- > [mountains, caseOfCDW, reanimator ] <.#> author =: howard
-- > -- :: [Book]
--
-- Because @('<.#>')@ works for any @'Functor'@, we could access values
-- of type @Maybe Book@, @a -> Book@ or @IO Book@ similarly.
--
-- We frequently wish to access several fields of a record
-- simultaneously. @"fields"@ supports this using tuples. A tuple of
-- primitive @'Field'@s (currently, \"primitive @'Field'@\" means an
-- @"fclabels"@ lens) is itself a @'Field'@, provided that all the
-- @'Field'@s in the tuple have the same source type (ie. you can
-- combine @Book :-> String@ and @Book :-> Int@ but not @Book :->
-- String@ and @Person :-> String@). For example, we could do
--
-- > howard .# (firstName, lastName, age)
-- > -- :: (String, String, Int)
--
-- @"fields"@ defines instances for tuples of up to 10 elements. In
-- addition, the 2-tuple instance is recursively defined so that a tuple
-- @(a, b)@ is a @'Field'@ if @a@ is a primitive @'Field'@ and @b@ is
-- /any/ valid field. This makes it possible to do
--
-- > howard .# (firstName, (lastName, age)) =~ (reverse *** reverse *** negate)
-- > -- :: Person
--
-- We can also compose a @'Field'@ with a pure function (for example, a
-- regular record field accessor function) using the @('#$')@
-- combinator. However, since a function is one-way, the resulting
-- @'Field'@ cannot be used to set values, and trying to do so will
-- result in an @'error'@.
--
-- > howard .# lastName #$ length
-- > -- :: Int
--
-- If we wish to set fields of several records at once, but so that
-- we can also specify the value individually for each record, we can
-- use the @('*#')@ and @('=*')@ operators, which can be thought of as
-- \"zippy\" assignment. They can be used like this
--
-- > [ mountains, caseOfCDW, reanimator ] *# characters =*
-- > [ [ william, frank ]
-- > , [ charles, marinus ]
-- > , [ herbert ] ]
-- > -- :: [Book]
--
-- For more complex queries, @"fields"@ also provides the @('<#>')@ and
-- @('<##>')@ combinators. @('<#>')@ combines a @'Field'@ of type @a :->
-- f b@ with a field of type @b :-> c@, producing a @'Field'@ of type @a
-- :-> f c@, where @f@ is any @'Applicative'@ functor.
--
-- > mountains .# characters <#> (lastName, age)
-- > -- :: [(String, Int)]
--
-- @('<##>')@ is similar, except that flattens two monadic @'Field'@s
-- together. I.e. the type signature is @a :-> m b -> b :-> m c -> a :->
-- m c@. For example
--
-- > frank .# superior <##> superior <##> superior
-- > -- :: Maybe Person
--
-- Both @('<#>')@ and @('<##>')@ also support assignment normally,
-- although the exact semantics vary depending on the @'Applicative'@ or
-- @'Monad'@ in question.
--
-- We might also like to sort or otherwise manipulate collections of
-- records easily. For this, @"fields"@ provides the @'onField'@
-- combinator in the manner of @'Data.Function.on'@. For example, to sort
-- a list of books by their authors' last names, we can use
--
-- > sortBy (compare `onField` author # lastName) books
-- > -- :: [Book]
--
-- Using tuples, we can also easily define sub-orderings. For example,
-- if we wish to break ties based on the authors' first names and then
-- by ages, we can use
--
-- > sortBy (compare `onField` author # (lastName, firstName, age)) books
-- > -- :: [Book]
--
-- Since @'onField'@ accepts any @'Field'@, we can easily specify more
-- complex criteria. To sort a list of books by the sum of their
-- characters' ages (which is a bit silly), we could use
--
-- > sortBy (compare `onField` (characters <#> age) #$ sum) books
-- > -- :: [Book]
--
-- @"fields"@ also attempts to support convenient pattern matching by
-- means of the @'match'@ function and GHC's @ViewPatterns@ extension.
-- To pattern match on records, you could do something like this
--
-- > case charles of
-- > (match lastName -> "Dexter") -> Left False
-- > (match lastName -> "Ward") -> Left True
-- > (match (age, superior) -> (a, Just s))
-- > | a > 18 -> Right a
-- > | otherwise -> Right (s .# age)
-- > -- :: Either Bool Int
--
-- Finally, a pair of combinators is provided to access record fields of
-- collection types. The @(#!)@ combinator has the type @a :-> c b ->
-- i -> a :-> Maybe b@, where @c@ is an instance of @'Indexable'@ and
-- @i@ is an index type suitable for @c@. For example, you can use an
-- @'Integral'@ value to index a @'String'@ and a value of type @k@ to
-- index a @Map k v@. The @(#!!)@ combinator is also provided. It
-- doesn't have @Maybe@ in the return type, so using a bad index will
-- usually result in an @'error'@.
--
-- Currently, instances are provided for @[a]@, @'Data.Map'@,
--- @'Data.IntMap'@, @'Data.Array.IArray'@, @'Data.Set'@ and
--- @'Data.IntSet'@.
+-- @'Data.IntMap'@, @'Data.Set'@ and @'Data.IntSet'@.
module Data.Record.Field
( module Data.Record.Field.Basic
, module Data.Record.Field.Tuple
, module Data.Record.Field.Indexable
, module Data.Record.Field.Combinators
) where
import Data.Record.Field.Basic
import Data.Record.Field.Tuple
import Data.Record.Field.Indexable
import Data.Record.Field.Combinators
|
AstraFIN/fields
|
4e0a3a99519785a1b97b4ee554b11f9b9b69c55d
|
Made Indexable a single-parameter type class.
|
diff --git a/Data/Record/Field/Indexable.hs b/Data/Record/Field/Indexable.hs
index f8ea585..1500fce 100644
--- a/Data/Record/Field/Indexable.hs
+++ b/Data/Record/Field/Indexable.hs
@@ -1,122 +1,110 @@
-- vim: encoding=latin1
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeOperators #-}
-- | Composition operators for collection fields.
module Data.Record.Field.Indexable
( Indexable(..)
, (#!)
, (#!!)
) where
import Data.Record.Field.Basic
import Data.Record.Label
import qualified Data.Map as Map
import qualified Data.IntMap as IntMap
import qualified Data.Array.IArray as IArray
import qualified Data.Set as Set
import qualified Data.IntSet as IntSet
-- | Class of collection types that can be indexed into.
---
--- TODO: This should probably be a single-parameter type class with two
--- associated types instead.
-class Indexable a i where
- type Element a :: *
- indexGet :: i -> a -> Maybe (Element a)
- indexSet :: i -> Maybe (Element a) -> a -> a
- unsafeIndexGet :: i -> a -> Element a
+class Indexable a where
+ type IndexOf a :: *
+ type ElementOf a :: *
+ indexGet :: IndexOf a -> a -> Maybe (ElementOf a)
+ indexSet :: IndexOf a -> Maybe (ElementOf a) -> a -> a
+ unsafeIndexGet :: IndexOf a -> a -> ElementOf a
unsafeIndexGet i a = maybe notFound id $ indexGet i a
where notFound = error "unsafeIndexGet: element not found"
-- | Compose a field with an @'Indexable'@ collection safely.
--
-- > r .# coll #! idx
--
-- returns @Nothing@ if @idx@ was not found from the collection, and
-- @Just v@ if @v@ was found.
--
-- > r .# coll #! idx =: Just v
--
-- sets the value at @idx@ in the collection to be @v@. If the value
-- wasn't in the collection, it's inserted. The exact semantics of
-- insertion depend on the actual collection in question.
--
-- > r .# coll #! idx =: Nothing
--
-- removes the value at @idx@ from the collection, if possible.
--
infixl 8 #!
-(#!) :: (Field a, Indexable (Dst a) i) =>
- a -> i -> Src a :-> Maybe (Element (Dst a))
+(#!) :: (Field a, Indexable (Dst a)) =>
+ a -> IndexOf (Dst a) -> Src a :-> Maybe (ElementOf (Dst a))
f #! i = lens getter setter
where getter a = indexGet i (getL (field f) a)
setter v = modL (field f) (indexSet i v)
-- | As @(#!)@, but reading a nonexistent value will likely result in a
-- bottom value being returned. Also, the resulting field cannot be used
-- to remove values.
infixl 8 #!!
-(#!!) :: (Field a, Indexable (Dst a) i) =>
- a -> i -> Src a :-> Element (Dst a)
+(#!!) :: (Field a, Indexable (Dst a)) =>
+ a -> IndexOf (Dst a) -> Src a :-> ElementOf (Dst a)
f #!! i = lens getter setter
where getter a = unsafeIndexGet i (getL (field f) a)
setter v = setL (field $ f #! i) (Just v)
-instance (Integral i) => Indexable [a] i where
- type Element [a] = a
- unsafeIndexGet i as = as !! fromIntegral i
- indexGet i as = case drop (fromIntegral i) as of
+instance Indexable [a] where
+ type IndexOf [a] = Int
+ type ElementOf [a] = a
+ unsafeIndexGet i as = as !! i
+ indexGet i as = case drop i as of
[] -> Nothing
(a:_) -> Just a
indexSet i Nothing as = before ++ drop 1 after
- where (before,after) = splitAt (fromIntegral i) as
+ where (before,after) = splitAt i as
indexSet i (Just v) as = before ++ (v : drop 1 after)
- where (before,after) = splitAt (fromIntegral i) as
+ where (before,after) = splitAt i as
-instance (Ord k1, k1 ~ k2) => Indexable (Map.Map k1 a) k2 where
- type Element (Map.Map k1 a) = a
+instance (Ord k) => Indexable (Map.Map k a) where
+ type IndexOf (Map.Map k a) = k
+ type ElementOf (Map.Map k a) = a
unsafeIndexGet = flip (Map.!)
indexGet = Map.lookup
indexSet k v = Map.alter (const v) k
-instance Indexable (IntMap.IntMap a) Int where
- type Element (IntMap.IntMap a) = a
+instance Indexable (IntMap.IntMap a) where
+ type IndexOf (IntMap.IntMap a) = Int
+ type ElementOf (IntMap.IntMap a) = a
unsafeIndexGet = flip (IntMap.!)
indexGet = IntMap.lookup
indexSet k v = IntMap.alter (const v) k
-instance (IArray.IArray a e, IArray.Ix i1, i1 ~ i2) =>
- Indexable (a i1 e) i2 where
- type Element (a i1 e) = e
- unsafeIndexGet = flip (IArray.!)
- indexGet i a
- | i >= min && i <= max = Just $ a IArray.! i
- | otherwise = Nothing
- where (min, max) = IArray.bounds a
-
- indexSet i Nothing a = a -- array elements can't be removed
- indexSet i (Just v) a
- | i >= min && i <= max = a IArray.// [(i,v)]
- | otherwise = a
- where (min, max) = IArray.bounds a
-
-instance (Ord a1, a1 ~ a2) => Indexable (Set.Set a1) a2 where
- type Element (Set.Set a1) = a1
+instance (Ord a) => Indexable (Set.Set a) where
+ type IndexOf (Set.Set a) = a
+ type ElementOf (Set.Set a) = a
-- unsafeIndexGet doesn't really make sense here.
indexGet a set | a `Set.member` set = Just a
| otherwise = Nothing
indexSet a Nothing set = Set.delete a set
indexSet a (Just _) set = Set.insert a set
-instance Indexable IntSet.IntSet Int where
- type Element IntSet.IntSet = Int
+instance Indexable IntSet.IntSet where
+ type IndexOf IntSet.IntSet = Int
+ type ElementOf IntSet.IntSet = Int
-- unsafeIndexGet doesn't really make sense here.
indexGet a set | a `IntSet.member` set = Just a
| otherwise = Nothing
indexSet a Nothing set = IntSet.delete a set
indexSet a (Just _) set = IntSet.insert a set
diff --git a/fields.cabal b/fields.cabal
index c9b453f..a88c398 100644
--- a/fields.cabal
+++ b/fields.cabal
@@ -1,161 +1,161 @@
-- fields.cabal auto-generated by cabal init. For additional options,
-- see
-- http://www.haskell.org/cabal/release/cabal-latest/doc/users-guide/authors.html#pkg-descr.
-- The name of the package.
Name: fields
-- The package version. See the Haskell package versioning policy
-- (http://www.haskell.org/haskellwiki/Package_versioning_policy) for
-- standards guiding when and how versions should be incremented.
-Version: 0.1.0
+Version: 0.1.1
-- A short (one-line) description of the package.
Synopsis: First-class record field combinators with infix
record field syntax.
-- A longer description of the package.
Description: Using records, especially nested records, in
Haskell can sometimes be a bit of a chore.
Fortunately, there are several libraries in hackage
that make working with records easier. This library
is my attempt to build on top of these libraries to
make working with records even more pleasant!
.
In most imperative languages, records are accessed
using the infix dot operator. Record fields can be
read simply by suffixing a record value with
'.field' and they can be modified by simply
assigning to that location. Although this is not
the only way to access records (indeed, Haskell
does not use it), many people (including myself)
like it. This library attempts to support this
style for Haskell records in the following manner:
.
> record.field.subfield becomes record .# field # subfield
> record.field = value becomes record .# field =: value
.
Of course, the infix assignment in Haskell is pure
and doesn't actually mutate anything. Rather, a
modified version of the record is returned.
.
In addition, the following features are supported:
.
* Accessing several fields simultaneously using
tuples.
Example: @record .# (field1, field2, field3)@
.
* Accessing records inside a @'Functor'@.
Example: @recordInFunctor \<.#\> field@
.
* Composing fields with @'Applicative'@ functors
and @'Monad'@s.
Example: @record .\# applicativeField \<\#\> subfield@
.
* Pattern matching using @ViewPatterns@.
Example: @case record of (match field -> 1) -> ...@
.
* Easy comparisons etc. using @'onField'@.
Example: @sortBy (compare \`onField\`
field#subfield) records@
.
For a detailed description of usage, see
"Data.Record.Field".
.
This library is a work-in-progress. Some
limitations, deficiencies, points of interest and
possible future improvements include:
.
* Currently, a @'Field'@ instance is only provided
for @"fclabels"@ lenses, since that is what I
have personally used. However, there should be
nothing in principle that would prevent adding
instances for @"data-accessor"@ and @"lenses"@.
However, doing this would make this package
depend on several record libraries at once,
which might not be the best approach. Perhaps
this package should be split into several
packages?
.
* Similarly, the @'field'@ method currently
returns an @"fclabels"@ lens. To fully decouple
this package from @"fclabels"@, the @'field'@
method probably has to be split into @getField@,
@setField@ and @modField@ or something similar.
.
* For monad transformers, @"transformers"@ and
@"monads-fd"@ are used, since those are what
@"fclabels"@ uses. This might be a problem for a
program that uses @"mtl"@ instead.
.
* To avoid lots of parentheses, @"fields"@ uses
high-precedence operators at three operator
precedence levels. The goal was to make field
accesses directly usable in arithmetic
expressions (e.g. @r1\.\#int + r2\.\#int@).
Unfortunately, since Haskell has a finite number
of precedence levels, this goal was not properly
met, since @('*')@ and all higher-precedence
arithmetic operators have conflicting precedence
levels.
.
* Performance has not been analyzed at all. To my
knowledge, GHC doesn't do type class
specialization or method inlining by default, so
needlessly generic code might be generated, even
if all types are statically known. I'm hoping
that this can be addressed using @SPECIALIZE@
and @INLINE@ pragmas if it turns out to be an
issue.
-- The license under which the package is released.
License: BSD3
-- The file containing the license text.
License-file: LICENSE
-- The package author(s).
Author: Jussi Knuuttila
-- An email address to which users can send suggestions, bug reports,
-- and patches.
Maintainer: [email protected]
Homepage: http://github.com/AstraFIN/fields
-- A copyright notice.
-- Copyright:
Category: Data
Build-type: Simple
-- Extra files to be distributed with the package, such as examples or
-- a README.
Extra-source-files: Example.hs
-- Constraint on the version of Cabal needed to build this package.
Cabal-version: >=1.8.0.2
Library
-- Modules exported by the library.
Exposed-modules: Data.Record.Field
, Data.Record.Field.Basic
, Data.Record.Field.Combinators
, Data.Record.Field.Tuple
, Data.Record.Field.Indexable
-- Packages needed in order to build this package.
Build-depends: base >= 4 && < 5
, fclabels >= 0.9.1
, containers >= 0.3.0.0
, array >= 0.3.0.0
, transformers >= 0.2.0.0
, monads-fd >= 0.1.0.1
-- Modules not exported by this package.
-- Other-modules:
-- Extra tools (e.g. alex, hsc2hs, ...) needed to build the source.
-- Build-tools:
|
AstraFIN/fields
|
4fa2fa237ba36bae113fe6f1ff43d96f4a063864
|
Uploaded to Hackage.
|
diff --git a/fields.cabal b/fields.cabal
index 06062e8..c9b453f 100644
--- a/fields.cabal
+++ b/fields.cabal
@@ -1,160 +1,161 @@
-- fields.cabal auto-generated by cabal init. For additional options,
-- see
-- http://www.haskell.org/cabal/release/cabal-latest/doc/users-guide/authors.html#pkg-descr.
-- The name of the package.
Name: fields
-- The package version. See the Haskell package versioning policy
-- (http://www.haskell.org/haskellwiki/Package_versioning_policy) for
-- standards guiding when and how versions should be incremented.
Version: 0.1.0
-- A short (one-line) description of the package.
Synopsis: First-class record field combinators with infix
record field syntax.
-- A longer description of the package.
Description: Using records, especially nested records, in
Haskell can sometimes be a bit of a chore.
Fortunately, there are several libraries in hackage
that make working with records easier. This library
is my attempt to build on top of these libraries to
make working with records even more pleasant!
.
In most imperative languages, records are accessed
using the infix dot operator. Record fields can be
read simply by suffixing a record value with
'.field' and they can be modified by simply
assigning to that location. Although this is not
the only way to access records (indeed, Haskell
does not use it), many people (including myself)
like it. This library attempts to support this
style for Haskell records in the following manner:
.
> record.field.subfield becomes record .# field # subfield
> record.field = value becomes record .# field =: value
.
Of course, the infix assignment in Haskell is pure
and doesn't actually mutate anything. Rather, a
modified version of the record is returned.
.
In addition, the following features are supported:
.
* Accessing several fields simultaneously using
tuples.
Example: @record .# (field1, field2, field3)@
.
* Accessing records inside a @'Functor'@.
Example: @recordInFunctor \<.#\> field@
.
* Composing fields with @'Applicative'@ functors
and @'Monad'@s.
Example: @record .\# applicativeField \<\#\> subfield@
.
* Pattern matching using @ViewPatterns@.
Example: @case record of (match field -> 1) -> ...@
.
* Easy comparisons etc. using @'onField'@.
Example: @sortBy (compare \`onField\`
field#subfield) records@
.
For a detailed description of usage, see
"Data.Record.Field".
.
This library is a work-in-progress. Some
limitations, deficiencies, points of interest and
possible future improvements include:
.
* Currently, a @'Field'@ instance is only provided
for @"fclabels"@ lenses, since that is what I
have personally used. However, there should be
nothing in principle that would prevent adding
instances for @"data-accessor"@ and @"lenses"@.
However, doing this would make this package
depend on several record libraries at once,
which might not be the best approach. Perhaps
this package should be split into several
packages?
.
* Similarly, the @'field'@ method currently
returns an @"fclabels"@ lens. To fully decouple
this package from @"fclabels"@, the @'field'@
method probably has to be split into @getField@,
@setField@ and @modField@ or something similar.
.
* For monad transformers, @"transformers"@ and
@"monads-fd"@ are used, since those are what
@"fclabels"@ uses. This might be a problem for a
program that uses @"mtl"@ instead.
.
* To avoid lots of parentheses, @"fields"@ uses
high-precedence operators at three operator
precedence levels. The goal was to make field
accesses directly usable in arithmetic
expressions (e.g. @r1\.\#int + r2\.\#int@).
Unfortunately, since Haskell has a finite number
of precedence levels, this goal was not properly
met, since @('*')@ and all higher-precedence
arithmetic operators have conflicting precedence
levels.
.
* Performance has not been analyzed at all. To my
knowledge, GHC doesn't do type class
specialization or method inlining by default, so
needlessly generic code might be generated, even
if all types are statically known. I'm hoping
that this can be addressed using @SPECIALIZE@
and @INLINE@ pragmas if it turns out to be an
issue.
-- The license under which the package is released.
License: BSD3
-- The file containing the license text.
License-file: LICENSE
-- The package author(s).
Author: Jussi Knuuttila
-- An email address to which users can send suggestions, bug reports,
-- and patches.
Maintainer: [email protected]
+
Homepage: http://github.com/AstraFIN/fields
-- A copyright notice.
-- Copyright:
Category: Data
Build-type: Simple
-- Extra files to be distributed with the package, such as examples or
-- a README.
Extra-source-files: Example.hs
-- Constraint on the version of Cabal needed to build this package.
Cabal-version: >=1.8.0.2
Library
-- Modules exported by the library.
Exposed-modules: Data.Record.Field
, Data.Record.Field.Basic
, Data.Record.Field.Combinators
, Data.Record.Field.Tuple
, Data.Record.Field.Indexable
-- Packages needed in order to build this package.
Build-depends: base >= 4 && < 5
, fclabels >= 0.9.1
, containers >= 0.3.0.0
, array >= 0.3.0.0
, transformers >= 0.2.0.0
, monads-fd >= 0.1.0.1
-- Modules not exported by this package.
-- Other-modules:
-- Extra tools (e.g. alex, hsc2hs, ...) needed to build the source.
-- Build-tools:
|
AstraFIN/fields
|
5c7a15e474d6b1a50dd409e211bcd56b2a68f2d9
|
Improved the Cabal description.
|
diff --git a/fields.cabal b/fields.cabal
index 4b5b648..06062e8 100644
--- a/fields.cabal
+++ b/fields.cabal
@@ -1,145 +1,160 @@
-- fields.cabal auto-generated by cabal init. For additional options,
-- see
-- http://www.haskell.org/cabal/release/cabal-latest/doc/users-guide/authors.html#pkg-descr.
-- The name of the package.
Name: fields
-- The package version. See the Haskell package versioning policy
-- (http://www.haskell.org/haskellwiki/Package_versioning_policy) for
-- standards guiding when and how versions should be incremented.
Version: 0.1.0
-- A short (one-line) description of the package.
Synopsis: First-class record field combinators with infix
record field syntax.
-- A longer description of the package.
Description: Using records, especially nested records, in
Haskell can sometimes be a bit of a chore.
Fortunately, there are several libraries in hackage
that make working with records easier. This library
is my attempt to build on top of these libraries to
make working with records even more pleasant!
.
In most imperative languages, records are accessed
using the infix dot operator. Record fields can be
read simply by suffixing a record value with
'.field' and they can be modified by simply
assigning to that location. Although this is not
the only way to access records (indeed, Haskell
does not use it), many people (including myself)
like it. This library attempts to support this
style for Haskell records in the following manner:
.
> record.field.subfield becomes record .# field # subfield
> record.field = value becomes record .# field =: value
.
Of course, the infix assignment in Haskell is pure
and doesn't actually mutate anything. Rather, a
modified version of the record is returned.
.
- In addition, several combinators for first-class
- record fields are provided, e.g. for easily
- handling @'Functor'@s, @'Applicative'@s and
- @'Monad'@s.
+ In addition, the following features are supported:
+ .
+ * Accessing several fields simultaneously using
+ tuples.
+ Example: @record .# (field1, field2, field3)@
+ .
+ * Accessing records inside a @'Functor'@.
+ Example: @recordInFunctor \<.#\> field@
+ .
+ * Composing fields with @'Applicative'@ functors
+ and @'Monad'@s.
+ Example: @record .\# applicativeField \<\#\> subfield@
+ .
+ * Pattern matching using @ViewPatterns@.
+ Example: @case record of (match field -> 1) -> ...@
+ .
+ * Easy comparisons etc. using @'onField'@.
+ Example: @sortBy (compare \`onField\`
+ field#subfield) records@
.
For a detailed description of usage, see
"Data.Record.Field".
.
This library is a work-in-progress. Some
limitations, deficiencies, points of interest and
possible future improvements include:
.
* Currently, a @'Field'@ instance is only provided
for @"fclabels"@ lenses, since that is what I
have personally used. However, there should be
nothing in principle that would prevent adding
instances for @"data-accessor"@ and @"lenses"@.
However, doing this would make this package
depend on several record libraries at once,
which might not be the best approach. Perhaps
this package should be split into several
packages?
.
* Similarly, the @'field'@ method currently
returns an @"fclabels"@ lens. To fully decouple
this package from @"fclabels"@, the @'field'@
method probably has to be split into @getField@,
@setField@ and @modField@ or something similar.
.
* For monad transformers, @"transformers"@ and
@"monads-fd"@ are used, since those are what
@"fclabels"@ uses. This might be a problem for a
program that uses @"mtl"@ instead.
.
* To avoid lots of parentheses, @"fields"@ uses
high-precedence operators at three operator
precedence levels. The goal was to make field
accesses directly usable in arithmetic
expressions (e.g. @r1\.\#int + r2\.\#int@).
Unfortunately, since Haskell has a finite number
of precedence levels, this goal was not properly
met, since @('*')@ and all higher-precedence
arithmetic operators have conflicting precedence
levels.
.
* Performance has not been analyzed at all. To my
knowledge, GHC doesn't do type class
specialization or method inlining by default, so
needlessly generic code might be generated, even
if all types are statically known. I'm hoping
that this can be addressed using @SPECIALIZE@
and @INLINE@ pragmas if it turns out to be an
issue.
-- The license under which the package is released.
License: BSD3
-- The file containing the license text.
License-file: LICENSE
-- The package author(s).
Author: Jussi Knuuttila
-- An email address to which users can send suggestions, bug reports,
-- and patches.
Maintainer: [email protected]
Homepage: http://github.com/AstraFIN/fields
-- A copyright notice.
-- Copyright:
Category: Data
Build-type: Simple
-- Extra files to be distributed with the package, such as examples or
-- a README.
Extra-source-files: Example.hs
-- Constraint on the version of Cabal needed to build this package.
Cabal-version: >=1.8.0.2
Library
-- Modules exported by the library.
Exposed-modules: Data.Record.Field
, Data.Record.Field.Basic
, Data.Record.Field.Combinators
, Data.Record.Field.Tuple
, Data.Record.Field.Indexable
-- Packages needed in order to build this package.
Build-depends: base >= 4 && < 5
, fclabels >= 0.9.1
, containers >= 0.3.0.0
, array >= 0.3.0.0
, transformers >= 0.2.0.0
, monads-fd >= 0.1.0.1
-- Modules not exported by this package.
-- Other-modules:
-- Extra tools (e.g. alex, hsc2hs, ...) needed to build the source.
-- Build-tools:
|
AstraFIN/fields
|
a445abcb73813b9bf4f93c881fd0b73ff1fba9da
|
Removed a hyperlink to (#), due to a Haddock bug.
|
diff --git a/Data/Record/Field.hs b/Data/Record/Field.hs
index 7ea2156..24ea2be 100644
--- a/Data/Record/Field.hs
+++ b/Data/Record/Field.hs
@@ -1,242 +1,242 @@
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeOperators #-}
-- | Using records, especially nested records, in Haskell can sometimes be
-- a bit of a chore. Fortunately, there are several libraries in hackage
-- to make working with records easier. This library is my attempt to
-- build on top of these libraries to make working with records even
-- more pleasant!
--
-- In most imperative languages, records are accessed using the infix
-- dot operator. Record fields can be read simply by suffixing a record
-- value with '.field' and they can be modified by simply assigning to
-- that location. Although this is not the only way to access records
-- (indeed, Haskell does not use it), many people (including myself)
-- like it. This library attempts to support this style for Haskell
-- records in the following manner:
--
-- > record.field.subfield becomes record .# field # subfield
-- > record.field = value becomes record .# field =: value
--
-- Of course, the infix assignment in Haskell is pure and doesn't
-- actually mutate anything. Rather, a modified version of the record is
-- returned.
--
-- Below, a detailed and commented usage example is presented.
--
-- > import Data.Record.Field
-- > import Data.Record.Label hiding ((=:))
--
-- Currently, @"fields"@ is built on top of @"fclabels"@, so we import
-- that package as well. We hide the @(=:)@ operator because that
-- operator is also used by @"fields"@ itself.
--
-- First, let's define some example data types and derive lenses for
-- them using @"fclabels"@.
--
-- > data Person = Person
-- > { _firstName :: String
-- > , _lastName :: String
-- > , _age :: Int
-- > , _superior :: Maybe Person
-- > } deriving Show
-- >
-- > data Book = Book
-- > { _title :: String
-- > , _author :: Person
-- > , _characters :: [Person]
-- > } deriving Show
-- >
-- > $(mkLabels [''Person, ''Book])
--
-- Now, let's define some example data.
--
-- > howard = Person "Howard" "Lovecraft" 46 Nothing
-- > charles = Person "Charles" "Ward" 26 Nothing
-- > marinus = Person "Marinus" "Willett" 56 Nothing
-- > william = Person "William" "Dyer" 53 Nothing
-- > frank = Person "Frank" "Pabodie" 49 Nothing
-- > herbert = Person "Herbert" "West" 32 Nothing
-- > abdul = Person "Abdul" "Alhazred" 71 Nothing
-- >
-- > mountains = Book "At the Mountains of Madness" undefined []
-- > caseOfCDW = Book "The Case of Charles Dexter Ward" undefined []
-- > reanimator = Book "Herbert West -- The Re-animator" undefined []
-- > necronomicon = Book "Necronomicon" undefined []
-- >
-- > persons = [howard, charles, marinus, herbert, william, frank, abdul]
-- > books = [mountains, caseOfCDW, reanimator, necronomicon]
--
-- Now, to look up a book's title, we can use the @('.#')@ operator,
-- which is the basis of all @"fields"@ functionality. @('.#')@ takes a
-- value of type @a@ and a @'Field'@ from @a@ to some other type (in
-- this case, 'String') and returns the value of that field. Since an
-- @"fclabels"@ lens is an instance of @'Field'@, we can just use the
-- lens directly.
--
-- > necronomicon .# title
-- > -- :: String
--
-- The @author@ field, however, was left undefined in the above
-- definition. We can set it using the @(=:)@ operator
--
-- > necronomicon .# author =: abdul
-- > -- :: Book
--
-- A notable detail is that the above expression parenthesizes as
-- @necronomicon .# (author =: abdul)@. The @(=:)@ operator takes a
-- @'Field'@ and a value for that @'Field'@ and returns a new @'Field'@
-- that, when read, returns a modified version of the record.
--
-- For the sake of the example, I will assume here that the subsequent
-- references to @necronomicon@ refer to this modified version (and
-- similarly for all other assignment examples below), even though
-- nothing is mutated in reality.
--
-- The @('=~')@ operator is similar, except that instead of a value, it
-- takes a function that modifies the previous value. For example
--
-- > howard .# age =~ succ
-- > -- :: Person
--
-- To access fields in nested records, @'Field'@s can be composed using
--- the @('#')@ combinator.
+-- the @(#)@ combinator.
--
-- > necronomicon .# author # lastName
-- > -- :: String
--
-- If we wish to access a field of several records at once, we can use
-- the @('<.#>')@ operator, which can be used to access fields of
-- a record inside a @'Functor'@. For example
--
-- > persons <.#> age
-- > -- :: [Int]
--
-- This also works for assignment. For example, let's fix the @author@
-- fields of the rest of our books.
--
-- > [mountains, caseOfCDW, reanimator ] <.#> author =: howard
-- > -- :: [Book]
--
-- Because @('<.#>')@ works for any @'Functor'@, we could access values
-- of type @Maybe Book@, @a -> Book@ or @IO Book@ similarly.
--
-- We frequently wish to access several fields of a record
-- simultaneously. @"fields"@ supports this using tuples. A tuple of
-- primitive @'Field'@s (currently, \"primitive @'Field'@\" means an
-- @"fclabels"@ lens) is itself a @'Field'@, provided that all the
-- @'Field'@s in the tuple have the same source type (ie. you can
-- combine @Book :-> String@ and @Book :-> Int@ but not @Book :->
-- String@ and @Person :-> String@). For example, we could do
--
-- > howard .# (firstName, lastName, age)
-- > -- :: (String, String, Int)
--
-- @"fields"@ defines instances for tuples of up to 10 elements. In
-- addition, the 2-tuple instance is recursively defined so that a tuple
-- @(a, b)@ is a @'Field'@ if @a@ is a primitive @'Field'@ and @b@ is
-- /any/ valid field. This makes it possible to do
--
-- > howard .# (firstName, (lastName, age)) =~ (reverse *** reverse *** negate)
-- > -- :: Person
--
-- We can also compose a @'Field'@ with a pure function (for example, a
-- regular record field accessor function) using the @('#$')@
-- combinator. However, since a function is one-way, the resulting
-- @'Field'@ cannot be used to set values, and trying to do so will
-- result in an @'error'@.
--
-- > howard .# lastName #$ length
-- > -- :: Int
--
-- If we wish to set fields of several records at once, but so that
-- we can also specify the value individually for each record, we can
-- use the @('*#')@ and @('=*')@ operators, which can be thought of as
-- \"zippy\" assignment. They can be used like this
--
-- > [ mountains, caseOfCDW, reanimator ] *# characters =*
-- > [ [ william, frank ]
-- > , [ charles, marinus ]
-- > , [ herbert ] ]
-- > -- :: [Book]
--
-- For more complex queries, @"fields"@ also provides the @('<#>')@ and
-- @('<##>')@ combinators. @('<#>')@ combines a @'Field'@ of type @a :->
-- f b@ with a field of type @b :-> c@, producing a @'Field'@ of type @a
-- :-> f c@, where @f@ is any @'Applicative'@ functor.
--
-- > mountains .# characters <#> (lastName, age)
-- > -- :: [(String, Int)]
--
-- @('<##>')@ is similar, except that flattens two monadic @'Field'@s
-- together. I.e. the type signature is @a :-> m b -> b :-> m c -> a :->
-- m c@. For example
--
-- > frank .# superior <##> superior <##> superior
-- > -- :: Maybe Person
--
-- Both @('<#>')@ and @('<##>')@ also support assignment normally,
-- although the exact semantics vary depending on the @'Applicative'@ or
-- @'Monad'@ in question.
--
-- We might also like to sort or otherwise manipulate collections of
-- records easily. For this, @"fields"@ provides the @'onField'@
-- combinator in the manner of @'Data.Function.on'@. For example, to sort
-- a list of books by their authors' last names, we can use
--
-- > sortBy (compare `onField` author # lastName) books
-- > -- :: [Book]
--
-- Using tuples, we can also easily define sub-orderings. For example,
-- if we wish to break ties based on the authors' first names and then
-- by ages, we can use
--
-- > sortBy (compare `onField` author # (lastName, firstName, age)) books
-- > -- :: [Book]
--
-- Since @'onField'@ accepts any @'Field'@, we can easily specify more
-- complex criteria. To sort a list of books by the sum of their
-- characters' ages (which is a bit silly), we could use
--
-- > sortBy (compare `onField` (characters <#> age) #$ sum) books
-- > -- :: [Book]
--
-- @"fields"@ also attempts to support convenient pattern matching by
-- means of the @'match'@ function and GHC's @ViewPatterns@ extension.
-- To pattern match on records, you could do something like this
--
-- > case charles of
-- > (match lastName -> "Dexter") -> Left False
-- > (match lastName -> "Ward") -> Left True
-- > (match (age, superior) -> (a, Just s))
-- > | a > 18 -> Right a
-- > | otherwise -> Right (s .# age)
-- > -- :: Either Bool Int
--
-- Finally, a pair of combinators is provided to access record fields of
-- collection types. The @(#!)@ combinator has the type @a :-> c b ->
-- i -> a :-> Maybe b@, where @c@ is an instance of @'Indexable'@ and
-- @i@ is an index type suitable for @c@. For example, you can use an
-- @'Integral'@ value to index a @'String'@ and a value of type @k@ to
-- index a @Map k v@. The @(#!!)@ combinator is also provided. It
-- doesn't have @Maybe@ in the return type, so using a bad index will
-- usually result in an @'error'@.
--
-- Currently, instances are provided for @[a]@, @'Data.Map'@,
-- @'Data.IntMap'@, @'Data.Array.IArray'@, @'Data.Set'@ and
-- @'Data.IntSet'@.
module Data.Record.Field
( module Data.Record.Field.Basic
, module Data.Record.Field.Tuple
, module Data.Record.Field.Indexable
, module Data.Record.Field.Combinators
) where
import Data.Record.Field.Basic
import Data.Record.Field.Tuple
import Data.Record.Field.Indexable
import Data.Record.Field.Combinators
|
AstraFIN/fields
|
fa12e44a019da9b70e7657596de850df2018030d
|
First public release.
|
diff --git a/Data/Record/Field.hs b/Data/Record/Field.hs
new file mode 100644
index 0000000..7ea2156
--- /dev/null
+++ b/Data/Record/Field.hs
@@ -0,0 +1,242 @@
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE TypeOperators #-}
+
+-- | Using records, especially nested records, in Haskell can sometimes be
+-- a bit of a chore. Fortunately, there are several libraries in hackage
+-- to make working with records easier. This library is my attempt to
+-- build on top of these libraries to make working with records even
+-- more pleasant!
+--
+-- In most imperative languages, records are accessed using the infix
+-- dot operator. Record fields can be read simply by suffixing a record
+-- value with '.field' and they can be modified by simply assigning to
+-- that location. Although this is not the only way to access records
+-- (indeed, Haskell does not use it), many people (including myself)
+-- like it. This library attempts to support this style for Haskell
+-- records in the following manner:
+--
+-- > record.field.subfield becomes record .# field # subfield
+-- > record.field = value becomes record .# field =: value
+--
+-- Of course, the infix assignment in Haskell is pure and doesn't
+-- actually mutate anything. Rather, a modified version of the record is
+-- returned.
+--
+-- Below, a detailed and commented usage example is presented.
+--
+-- > import Data.Record.Field
+-- > import Data.Record.Label hiding ((=:))
+--
+-- Currently, @"fields"@ is built on top of @"fclabels"@, so we import
+-- that package as well. We hide the @(=:)@ operator because that
+-- operator is also used by @"fields"@ itself.
+--
+-- First, let's define some example data types and derive lenses for
+-- them using @"fclabels"@.
+--
+-- > data Person = Person
+-- > { _firstName :: String
+-- > , _lastName :: String
+-- > , _age :: Int
+-- > , _superior :: Maybe Person
+-- > } deriving Show
+-- >
+-- > data Book = Book
+-- > { _title :: String
+-- > , _author :: Person
+-- > , _characters :: [Person]
+-- > } deriving Show
+-- >
+-- > $(mkLabels [''Person, ''Book])
+--
+-- Now, let's define some example data.
+--
+-- > howard = Person "Howard" "Lovecraft" 46 Nothing
+-- > charles = Person "Charles" "Ward" 26 Nothing
+-- > marinus = Person "Marinus" "Willett" 56 Nothing
+-- > william = Person "William" "Dyer" 53 Nothing
+-- > frank = Person "Frank" "Pabodie" 49 Nothing
+-- > herbert = Person "Herbert" "West" 32 Nothing
+-- > abdul = Person "Abdul" "Alhazred" 71 Nothing
+-- >
+-- > mountains = Book "At the Mountains of Madness" undefined []
+-- > caseOfCDW = Book "The Case of Charles Dexter Ward" undefined []
+-- > reanimator = Book "Herbert West -- The Re-animator" undefined []
+-- > necronomicon = Book "Necronomicon" undefined []
+-- >
+-- > persons = [howard, charles, marinus, herbert, william, frank, abdul]
+-- > books = [mountains, caseOfCDW, reanimator, necronomicon]
+--
+-- Now, to look up a book's title, we can use the @('.#')@ operator,
+-- which is the basis of all @"fields"@ functionality. @('.#')@ takes a
+-- value of type @a@ and a @'Field'@ from @a@ to some other type (in
+-- this case, 'String') and returns the value of that field. Since an
+-- @"fclabels"@ lens is an instance of @'Field'@, we can just use the
+-- lens directly.
+--
+-- > necronomicon .# title
+-- > -- :: String
+--
+-- The @author@ field, however, was left undefined in the above
+-- definition. We can set it using the @(=:)@ operator
+--
+-- > necronomicon .# author =: abdul
+-- > -- :: Book
+--
+-- A notable detail is that the above expression parenthesizes as
+-- @necronomicon .# (author =: abdul)@. The @(=:)@ operator takes a
+-- @'Field'@ and a value for that @'Field'@ and returns a new @'Field'@
+-- that, when read, returns a modified version of the record.
+--
+-- For the sake of the example, I will assume here that the subsequent
+-- references to @necronomicon@ refer to this modified version (and
+-- similarly for all other assignment examples below), even though
+-- nothing is mutated in reality.
+--
+-- The @('=~')@ operator is similar, except that instead of a value, it
+-- takes a function that modifies the previous value. For example
+--
+-- > howard .# age =~ succ
+-- > -- :: Person
+--
+-- To access fields in nested records, @'Field'@s can be composed using
+-- the @('#')@ combinator.
+--
+-- > necronomicon .# author # lastName
+-- > -- :: String
+--
+-- If we wish to access a field of several records at once, we can use
+-- the @('<.#>')@ operator, which can be used to access fields of
+-- a record inside a @'Functor'@. For example
+--
+-- > persons <.#> age
+-- > -- :: [Int]
+--
+-- This also works for assignment. For example, let's fix the @author@
+-- fields of the rest of our books.
+--
+-- > [mountains, caseOfCDW, reanimator ] <.#> author =: howard
+-- > -- :: [Book]
+--
+-- Because @('<.#>')@ works for any @'Functor'@, we could access values
+-- of type @Maybe Book@, @a -> Book@ or @IO Book@ similarly.
+--
+-- We frequently wish to access several fields of a record
+-- simultaneously. @"fields"@ supports this using tuples. A tuple of
+-- primitive @'Field'@s (currently, \"primitive @'Field'@\" means an
+-- @"fclabels"@ lens) is itself a @'Field'@, provided that all the
+-- @'Field'@s in the tuple have the same source type (ie. you can
+-- combine @Book :-> String@ and @Book :-> Int@ but not @Book :->
+-- String@ and @Person :-> String@). For example, we could do
+--
+-- > howard .# (firstName, lastName, age)
+-- > -- :: (String, String, Int)
+--
+-- @"fields"@ defines instances for tuples of up to 10 elements. In
+-- addition, the 2-tuple instance is recursively defined so that a tuple
+-- @(a, b)@ is a @'Field'@ if @a@ is a primitive @'Field'@ and @b@ is
+-- /any/ valid field. This makes it possible to do
+--
+-- > howard .# (firstName, (lastName, age)) =~ (reverse *** reverse *** negate)
+-- > -- :: Person
+--
+-- We can also compose a @'Field'@ with a pure function (for example, a
+-- regular record field accessor function) using the @('#$')@
+-- combinator. However, since a function is one-way, the resulting
+-- @'Field'@ cannot be used to set values, and trying to do so will
+-- result in an @'error'@.
+--
+-- > howard .# lastName #$ length
+-- > -- :: Int
+--
+-- If we wish to set fields of several records at once, but so that
+-- we can also specify the value individually for each record, we can
+-- use the @('*#')@ and @('=*')@ operators, which can be thought of as
+-- \"zippy\" assignment. They can be used like this
+--
+-- > [ mountains, caseOfCDW, reanimator ] *# characters =*
+-- > [ [ william, frank ]
+-- > , [ charles, marinus ]
+-- > , [ herbert ] ]
+-- > -- :: [Book]
+--
+-- For more complex queries, @"fields"@ also provides the @('<#>')@ and
+-- @('<##>')@ combinators. @('<#>')@ combines a @'Field'@ of type @a :->
+-- f b@ with a field of type @b :-> c@, producing a @'Field'@ of type @a
+-- :-> f c@, where @f@ is any @'Applicative'@ functor.
+--
+-- > mountains .# characters <#> (lastName, age)
+-- > -- :: [(String, Int)]
+--
+-- @('<##>')@ is similar, except that flattens two monadic @'Field'@s
+-- together. I.e. the type signature is @a :-> m b -> b :-> m c -> a :->
+-- m c@. For example
+--
+-- > frank .# superior <##> superior <##> superior
+-- > -- :: Maybe Person
+--
+-- Both @('<#>')@ and @('<##>')@ also support assignment normally,
+-- although the exact semantics vary depending on the @'Applicative'@ or
+-- @'Monad'@ in question.
+--
+-- We might also like to sort or otherwise manipulate collections of
+-- records easily. For this, @"fields"@ provides the @'onField'@
+-- combinator in the manner of @'Data.Function.on'@. For example, to sort
+-- a list of books by their authors' last names, we can use
+--
+-- > sortBy (compare `onField` author # lastName) books
+-- > -- :: [Book]
+--
+-- Using tuples, we can also easily define sub-orderings. For example,
+-- if we wish to break ties based on the authors' first names and then
+-- by ages, we can use
+--
+-- > sortBy (compare `onField` author # (lastName, firstName, age)) books
+-- > -- :: [Book]
+--
+-- Since @'onField'@ accepts any @'Field'@, we can easily specify more
+-- complex criteria. To sort a list of books by the sum of their
+-- characters' ages (which is a bit silly), we could use
+--
+-- > sortBy (compare `onField` (characters <#> age) #$ sum) books
+-- > -- :: [Book]
+--
+-- @"fields"@ also attempts to support convenient pattern matching by
+-- means of the @'match'@ function and GHC's @ViewPatterns@ extension.
+-- To pattern match on records, you could do something like this
+--
+-- > case charles of
+-- > (match lastName -> "Dexter") -> Left False
+-- > (match lastName -> "Ward") -> Left True
+-- > (match (age, superior) -> (a, Just s))
+-- > | a > 18 -> Right a
+-- > | otherwise -> Right (s .# age)
+-- > -- :: Either Bool Int
+--
+-- Finally, a pair of combinators is provided to access record fields of
+-- collection types. The @(#!)@ combinator has the type @a :-> c b ->
+-- i -> a :-> Maybe b@, where @c@ is an instance of @'Indexable'@ and
+-- @i@ is an index type suitable for @c@. For example, you can use an
+-- @'Integral'@ value to index a @'String'@ and a value of type @k@ to
+-- index a @Map k v@. The @(#!!)@ combinator is also provided. It
+-- doesn't have @Maybe@ in the return type, so using a bad index will
+-- usually result in an @'error'@.
+--
+-- Currently, instances are provided for @[a]@, @'Data.Map'@,
+-- @'Data.IntMap'@, @'Data.Array.IArray'@, @'Data.Set'@ and
+-- @'Data.IntSet'@.
+module Data.Record.Field
+ ( module Data.Record.Field.Basic
+ , module Data.Record.Field.Tuple
+ , module Data.Record.Field.Indexable
+ , module Data.Record.Field.Combinators
+ ) where
+
+import Data.Record.Field.Basic
+import Data.Record.Field.Tuple
+import Data.Record.Field.Indexable
+import Data.Record.Field.Combinators
+
diff --git a/Data/Record/Field/Basic.hs b/Data/Record/Field/Basic.hs
new file mode 100644
index 0000000..56b2ae3
--- /dev/null
+++ b/Data/Record/Field/Basic.hs
@@ -0,0 +1,72 @@
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE TypeOperators #-}
+
+-- | The @'Field'@ class and basic operations.
+
+module Data.Record.Field.Basic
+ ( -- * Record fields.
+ Field(..)
+ -- * Basic field operators.
+ , (.#)
+ , (=:)
+ , (=~)
+ -- * Pattern matching.
+ , match
+ ) where
+
+import Data.Record.Label hiding ((=:))
+
+-- | Instances of this class can be combined with the functions and
+-- operators in this package.
+class Field a where
+ -- | The source type of the field. I.e. the record type.
+ type Src a :: *
+ -- | The destination type of the field. I.e. the type of the field
+ -- in question.
+ type Dst a :: *
+ -- | Return an @"fclabels"@ lens corresponding to this field.
+ field :: a -> (Src a :-> Dst a)
+
+instance Field (a :-> b) where
+ type Src (a :-> b) = a
+ type Dst (a :-> b) = b
+ field = id
+
+infixl 7 .#
+-- | Return the value of the field in the given record.
+(.#) :: (Field a) => Src a -> a -> Dst a
+r .# f = getL (field f) r
+
+-- | Infix assignment lookalike.
+--
+-- > r.#f =: v
+--
+-- returns a modified version of @r@ so that the field corresponding to
+-- @f@ are set to @v@.
+infixl 8 =:
+(=:) :: (Field a) => a -> Dst a -> Src a :-> Src a
+a =: v = lens (setL (field a) v) const
+
+-- | Infix modification lookalike.
+--
+-- > r.#f =~ g
+--
+-- returns a modified version of @r@ so that the fields corresponding to
+-- @f@ are modified with the function @g@.
+infixl 8 =~
+(=~) :: (Field a) => a -> (Dst a -> Dst a) -> Src a :-> Src a
+a =~ f = lens (modL (field a) f) const
+
+-- | Convenience function for use with the @ViewPatterns@ extension.
+--
+-- > case r of
+-- > (match int -> 5) -> "It's 5!"
+-- > (match (int,str#$length) -> (i,l))
+-- > | i == l -> "They're equal!"
+-- > | otherwise -> "Not equal."
+-- > _ -> "Something else."
+--
+match :: (Field a) => a -> Src a -> Dst a
+match f = (.# f)
+
diff --git a/Data/Record/Field/Combinators.hs b/Data/Record/Field/Combinators.hs
new file mode 100644
index 0000000..0773c8a
--- /dev/null
+++ b/Data/Record/Field/Combinators.hs
@@ -0,0 +1,133 @@
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE PackageImports #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE TypeOperators #-}
+
+-- | Field combinators.
+module Data.Record.Field.Combinators
+ ( -- * Basic combinators.
+ idL
+ , ( # )
+ , (#$ )
+ -- * Combinators for @'Functor'@s, @'Applicative'@s and
+ -- @'Monad'@s.
+ , (<.#>)
+ , (<#>)
+ , (<##>)
+ -- * Zippy assignment.
+ , (*#)
+ , (=*)
+ -- * Assignment and modification in a State monad.
+ , (<=:)
+ , (<=~)
+ -- * Utility combinator for comparisons etc.
+ , onField
+ ) where
+
+import Data.Record.Field.Basic
+import Data.Record.Label hiding ((=:))
+import qualified Control.Category as C
+import Control.Applicative
+import Control.Monad
+import "monads-fd" Control.Monad.State.Class
+
+cantSet :: String -> a
+cantSet n = error $ n ++ ": cannot set values."
+
+-- | Identity lens.
+idL :: a :-> a
+idL = C.id
+
+-- | Field composition with arguments in OO-like order.
+infixl 8 #
+( # ) :: (Field a, Field b, Dst a ~ Src b) =>
+ a -> b -> Src a :-> Dst b
+a # b = (field b) C.. (field a)
+
+-- | Compose fields with ordinary functions. As functions are one-way,
+-- the resulting field cannot be used to set values.
+infixl 8 #$
+(#$) :: (Field a) => a -> (Dst a -> b) -> Src a :-> b
+ab #$ f = lens getter (cantSet "(#$)")
+ where getter a = f . getL (field ab) $ a
+
+-- | Infix @'fmap'@ for fields.
+--
+-- Examples:
+--
+--
+-- > persons <.#> firstName
+--
+-- > do (v1, v2) <- takeMVar mv <.#> (field1, field2)
+-- > putStrLn . unlines $ [ "v1: " ++ show v1, "v2: " ++ show v2 ]
+--
+infixl 7 <.#>
+(<.#>) :: (Functor f, Field a) => f (Src a) -> a -> f (Dst a)
+f <.#> a = fmap (.# a) f
+
+-- | @'Applicative'@ functor composition for fields.
+--
+-- > book .# characters <#> lastName
+--
+infixr 9 <#>
+(<#>) :: (Applicative f, Field a, Field b, Dst a ~ f (Src b)) =>
+ a -> b -> Src a :-> f (Dst b)
+ab <#> bc = lens getter setter
+ where getter = (fmap $ getL (field bc)) . getL (field ab)
+ -- the flip is so effects get performed for b first.
+ setter fc = modL (field ab) $
+ \fb -> flip (setL (field bc)) <$> fb <*> fc
+
+-- | Flattening monadic composition for fields.
+--
+-- > person .# superior <##> superior <##> superior <##> superior
+--
+infixr 9 <##>
+(<##>) :: (Monad m, Field a, Field b,
+ Dst a ~ m (Src b), Dst b ~ m c) =>
+ a -> b -> Src a :-> m c
+ab <##> bc = lens getter setter
+ where getter = getL (field ab) >=> getL (field bc)
+ setter mc = modL (field ab) $
+ \mb -> do b <- mb
+ return $ setL (field bc) mc b
+
+-- | Zippy field reference to be used with @('=*')@.
+--
+-- > [ rec1, rec2 ] *# field =* [ value1, value2 ]
+--
+infixl 7 *#
+(*#) :: (Field b) => [Src b] -> [b] -> [Dst b]
+rs *# as = zipWith (.#) rs as
+
+-- | Zippy infix assignment to be used with @('*#')@.
+infixl 8 =*
+(=*) :: (Field a) => a -> [Dst a] -> [Src a :-> Src a]
+a =* vs = [ a =: v | v <- vs ]
+
+-- | Infix assignment for the State monad.
+--
+-- > (field1, field2) <=: (value1, value2)
+--
+infix 3 <=:
+(<=:) :: (MonadState (Src a) m, Field a) =>
+ a -> Dst a -> m ()
+a <=: v = modify (.# a =: v)
+
+-- | Infix modification for the State monad.
+--
+-- > (field1, field2) <=~ (f, g)
+--
+infix 3 <=~
+(<=~) :: (MonadState (Src a) m, Field a) =>
+ a -> (Dst a -> Dst a) -> m ()
+a <=~ f = modify (.# a =~ f)
+
+-- | Utility combinator in the manner of @'Data.Function.on'@.
+--
+-- > sortBy (compare `onField` (lastName,firstName)) persons
+--
+infixl 0 `onField`
+onField :: (Field a) => (Dst a -> Dst a -> t) -> a -> Src a -> Src a -> t
+onField f a r1 r2 = f (r1.#a) (r2.#a)
+
diff --git a/Data/Record/Field/Indexable.hs b/Data/Record/Field/Indexable.hs
new file mode 100644
index 0000000..f8ea585
--- /dev/null
+++ b/Data/Record/Field/Indexable.hs
@@ -0,0 +1,122 @@
+-- vim: encoding=latin1
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE TypeOperators #-}
+
+-- | Composition operators for collection fields.
+module Data.Record.Field.Indexable
+ ( Indexable(..)
+ , (#!)
+ , (#!!)
+ ) where
+
+import Data.Record.Field.Basic
+import Data.Record.Label
+import qualified Data.Map as Map
+import qualified Data.IntMap as IntMap
+import qualified Data.Array.IArray as IArray
+import qualified Data.Set as Set
+import qualified Data.IntSet as IntSet
+
+-- | Class of collection types that can be indexed into.
+--
+-- TODO: This should probably be a single-parameter type class with two
+-- associated types instead.
+class Indexable a i where
+ type Element a :: *
+ indexGet :: i -> a -> Maybe (Element a)
+ indexSet :: i -> Maybe (Element a) -> a -> a
+ unsafeIndexGet :: i -> a -> Element a
+ unsafeIndexGet i a = maybe notFound id $ indexGet i a
+ where notFound = error "unsafeIndexGet: element not found"
+
+-- | Compose a field with an @'Indexable'@ collection safely.
+--
+-- > r .# coll #! idx
+--
+-- returns @Nothing@ if @idx@ was not found from the collection, and
+-- @Just v@ if @v@ was found.
+--
+-- > r .# coll #! idx =: Just v
+--
+-- sets the value at @idx@ in the collection to be @v@. If the value
+-- wasn't in the collection, it's inserted. The exact semantics of
+-- insertion depend on the actual collection in question.
+--
+-- > r .# coll #! idx =: Nothing
+--
+-- removes the value at @idx@ from the collection, if possible.
+--
+infixl 8 #!
+(#!) :: (Field a, Indexable (Dst a) i) =>
+ a -> i -> Src a :-> Maybe (Element (Dst a))
+f #! i = lens getter setter
+ where getter a = indexGet i (getL (field f) a)
+ setter v = modL (field f) (indexSet i v)
+
+-- | As @(#!)@, but reading a nonexistent value will likely result in a
+-- bottom value being returned. Also, the resulting field cannot be used
+-- to remove values.
+infixl 8 #!!
+(#!!) :: (Field a, Indexable (Dst a) i) =>
+ a -> i -> Src a :-> Element (Dst a)
+f #!! i = lens getter setter
+ where getter a = unsafeIndexGet i (getL (field f) a)
+ setter v = setL (field $ f #! i) (Just v)
+
+instance (Integral i) => Indexable [a] i where
+ type Element [a] = a
+ unsafeIndexGet i as = as !! fromIntegral i
+ indexGet i as = case drop (fromIntegral i) as of
+ [] -> Nothing
+ (a:_) -> Just a
+ indexSet i Nothing as = before ++ drop 1 after
+ where (before,after) = splitAt (fromIntegral i) as
+ indexSet i (Just v) as = before ++ (v : drop 1 after)
+ where (before,after) = splitAt (fromIntegral i) as
+
+instance (Ord k1, k1 ~ k2) => Indexable (Map.Map k1 a) k2 where
+ type Element (Map.Map k1 a) = a
+ unsafeIndexGet = flip (Map.!)
+ indexGet = Map.lookup
+ indexSet k v = Map.alter (const v) k
+
+instance Indexable (IntMap.IntMap a) Int where
+ type Element (IntMap.IntMap a) = a
+ unsafeIndexGet = flip (IntMap.!)
+ indexGet = IntMap.lookup
+ indexSet k v = IntMap.alter (const v) k
+
+instance (IArray.IArray a e, IArray.Ix i1, i1 ~ i2) =>
+ Indexable (a i1 e) i2 where
+ type Element (a i1 e) = e
+ unsafeIndexGet = flip (IArray.!)
+ indexGet i a
+ | i >= min && i <= max = Just $ a IArray.! i
+ | otherwise = Nothing
+ where (min, max) = IArray.bounds a
+
+ indexSet i Nothing a = a -- array elements can't be removed
+ indexSet i (Just v) a
+ | i >= min && i <= max = a IArray.// [(i,v)]
+ | otherwise = a
+ where (min, max) = IArray.bounds a
+
+instance (Ord a1, a1 ~ a2) => Indexable (Set.Set a1) a2 where
+ type Element (Set.Set a1) = a1
+ -- unsafeIndexGet doesn't really make sense here.
+ indexGet a set | a `Set.member` set = Just a
+ | otherwise = Nothing
+ indexSet a Nothing set = Set.delete a set
+ indexSet a (Just _) set = Set.insert a set
+
+instance Indexable IntSet.IntSet Int where
+ type Element IntSet.IntSet = Int
+ -- unsafeIndexGet doesn't really make sense here.
+ indexGet a set | a `IntSet.member` set = Just a
+ | otherwise = Nothing
+ indexSet a Nothing set = IntSet.delete a set
+ indexSet a (Just _) set = IntSet.insert a set
+
diff --git a/Data/Record/Field/Tuple.hs b/Data/Record/Field/Tuple.hs
new file mode 100644
index 0000000..f606a11
--- /dev/null
+++ b/Data/Record/Field/Tuple.hs
@@ -0,0 +1,302 @@
+-- vim: encoding=latin1
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE TypeOperators #-}
+
+-- | Instances for tuples of fields up to a 10-tuple. This allows
+-- accessing several fields simultaneously.
+--
+-- > r.#(field1, field2, field3#field4) =: (value1, value2, value3)
+--
+-- In addition, the pair instance is recursively defined, which allows
+-- stuff like
+--
+-- > import Control.Arrow ((***))
+-- > r.#(field1, (field2, field3)) =~ (f *** g *** h)
+--
+module Data.Record.Field.Tuple
+ (
+ ) where
+
+import Data.Record.Field.Basic
+import Data.Record.Field.Combinators
+import Data.Record.Label hiding ((=:))
+{- Commented out to remove the dependency to pretty.
+import Text.PrettyPrint hiding (int)
+import qualified Text.PrettyPrint as PP
+-}
+
+
+instance (Field f, r ~ Src f) => Field (r :-> a, f) where
+ type Src (r :-> a, f) = r
+ type Dst (r :-> a, f) = (a, Dst f)
+ field (l1, f) = lens get set
+ where get r = (getL l1 r, getL l2 r)
+ set (a, b) = setL l2 b . setL l1 a
+ l2 = field f
+
+{- Commented out to remove the dependency to pretty.
+mkTupleFieldInstance :: Int -> String
+mkTupleFieldInstance n = render inst
+ where inst = header $+$ nest 4 defs
+ header = text "instance Field" <+> typ <+> text "where"
+
+ typ = tupleOf [ text "r :->" <+> v | v <- vs ]
+ vals = tupleOf vs
+
+ defs = vcat [rec, val, field, accs]
+
+ tupleOf = parens . commaSep
+ commaSep = sep . punctuate (text ",")
+
+ rs = [ text "r" <> PP.int i | i <- [1..n] ]
+ vs = take n $ [ text [v] | v <- ['a'..'z'] ] ++
+ [ text [v1,v2] | v1 <- ['a'..'z']
+ , v2 <- ['a'..'z'] ]
+
+ rec = text "type Src" <+> typ <+> text "= r"
+ val = text "type Dst" <+> typ <+> text "=" <+> vals
+ field = text "field" <+> tupleOf rs <+> text "= lens get set"
+ accs = nest 4 $ text "where" <+> vcat [getter, setter]
+
+ getter = text "get r =" <+> tupleOf [ get r | r <- rs ]
+ setter = text "set" <+> vals <+> text "=" <+>
+ (sep . punctuate (text " .")) [ set r v | (r,v) <- zip rs vs ]
+
+ get r = text "getL" <+> r <+> text "r"
+ set r v = text "setL" <+> r <+> v
+-}
+
+instance Field (r :-> a, r :-> b, r :-> c) where
+ type Src (r :-> a, r :-> b, r :-> c) = r
+ type Dst (r :-> a, r :-> b, r :-> c) = (a, b, c)
+ field (r1, r2, r3) = lens get set
+ where get r = (getL r1 r, getL r2 r, getL r3 r)
+ set (a, b, c) = setL r1 a . setL r2 b . setL r3 c
+instance Field (r :-> a, r :-> b, r :-> c, r :-> d) where
+ type Src (r :-> a, r :-> b, r :-> c, r :-> d) = r
+ type Dst (r :-> a, r :-> b, r :-> c, r :-> d) = (a, b, c, d)
+ field (r1, r2, r3, r4) = lens get set
+ where get r = (getL r1 r, getL r2 r, getL r3 r, getL r4 r)
+ set (a, b, c, d) = setL r1 a . setL r2 b . setL r3 c . setL r4 d
+instance Field (r :-> a, r :-> b, r :-> c, r :-> d, r :-> e) where
+ type Src (r :-> a, r :-> b, r :-> c, r :-> d, r :-> e) = r
+ type Dst (r :-> a, r :-> b, r :-> c, r :-> d, r :-> e) = (a,
+ b,
+ c,
+ d,
+ e)
+ field (r1, r2, r3, r4, r5) = lens get set
+ where get r = (getL r1 r,
+ getL r2 r,
+ getL r3 r,
+ getL r4 r,
+ getL r5 r)
+ set (a, b, c, d, e) = setL r1 a .
+ setL r2 b .
+ setL r3 c .
+ setL r4 d .
+ setL r5 e
+instance Field (r :-> a,
+ r :-> b,
+ r :-> c,
+ r :-> d,
+ r :-> e,
+ r :-> f) where
+ type Src (r :-> a, r :-> b, r :-> c, r :-> d, r :-> e, r :-> f) = r
+ type Dst (r :-> a,
+ r :-> b,
+ r :-> c,
+ r :-> d,
+ r :-> e,
+ r :-> f) = (a, b, c, d, e, f)
+ field (r1, r2, r3, r4, r5, r6) = lens get set
+ where get r = (getL r1 r,
+ getL r2 r,
+ getL r3 r,
+ getL r4 r,
+ getL r5 r,
+ getL r6 r)
+ set (a, b, c, d, e, f) = setL r1 a .
+ setL r2 b .
+ setL r3 c .
+ setL r4 d .
+ setL r5 e .
+ setL r6 f
+instance Field (r :-> a,
+ r :-> b,
+ r :-> c,
+ r :-> d,
+ r :-> e,
+ r :-> f,
+ r :-> g) where
+ type Src (r :-> a,
+ r :-> b,
+ r :-> c,
+ r :-> d,
+ r :-> e,
+ r :-> f,
+ r :-> g) = r
+ type Dst (r :-> a,
+ r :-> b,
+ r :-> c,
+ r :-> d,
+ r :-> e,
+ r :-> f,
+ r :-> g) = (a, b, c, d, e, f, g)
+ field (r1, r2, r3, r4, r5, r6, r7) = lens get set
+ where get r = (getL r1 r,
+ getL r2 r,
+ getL r3 r,
+ getL r4 r,
+ getL r5 r,
+ getL r6 r,
+ getL r7 r)
+ set (a, b, c, d, e, f, g) = setL r1 a .
+ setL r2 b .
+ setL r3 c .
+ setL r4 d .
+ setL r5 e .
+ setL r6 f .
+ setL r7 g
+instance Field (r :-> a,
+ r :-> b,
+ r :-> c,
+ r :-> d,
+ r :-> e,
+ r :-> f,
+ r :-> g,
+ r :-> h) where
+ type Src (r :-> a,
+ r :-> b,
+ r :-> c,
+ r :-> d,
+ r :-> e,
+ r :-> f,
+ r :-> g,
+ r :-> h) = r
+ type Dst (r :-> a,
+ r :-> b,
+ r :-> c,
+ r :-> d,
+ r :-> e,
+ r :-> f,
+ r :-> g,
+ r :-> h) = (a, b, c, d, e, f, g, h)
+ field (r1, r2, r3, r4, r5, r6, r7, r8) = lens get set
+ where get r = (getL r1 r,
+ getL r2 r,
+ getL r3 r,
+ getL r4 r,
+ getL r5 r,
+ getL r6 r,
+ getL r7 r,
+ getL r8 r)
+ set (a, b, c, d, e, f, g, h) = setL r1 a .
+ setL r2 b .
+ setL r3 c .
+ setL r4 d .
+ setL r5 e .
+ setL r6 f .
+ setL r7 g .
+ setL r8 h
+instance Field (r :-> a,
+ r :-> b,
+ r :-> c,
+ r :-> d,
+ r :-> e,
+ r :-> f,
+ r :-> g,
+ r :-> h,
+ r :-> i) where
+ type Src (r :-> a,
+ r :-> b,
+ r :-> c,
+ r :-> d,
+ r :-> e,
+ r :-> f,
+ r :-> g,
+ r :-> h,
+ r :-> i) = r
+ type Dst (r :-> a,
+ r :-> b,
+ r :-> c,
+ r :-> d,
+ r :-> e,
+ r :-> f,
+ r :-> g,
+ r :-> h,
+ r :-> i) = (a, b, c, d, e, f, g, h, i)
+ field (r1, r2, r3, r4, r5, r6, r7, r8, r9) = lens get set
+ where get r = (getL r1 r,
+ getL r2 r,
+ getL r3 r,
+ getL r4 r,
+ getL r5 r,
+ getL r6 r,
+ getL r7 r,
+ getL r8 r,
+ getL r9 r)
+ set (a, b, c, d, e, f, g, h, i) = setL r1 a .
+ setL r2 b .
+ setL r3 c .
+ setL r4 d .
+ setL r5 e .
+ setL r6 f .
+ setL r7 g .
+ setL r8 h .
+ setL r9 i
+instance Field (r :-> a,
+ r :-> b,
+ r :-> c,
+ r :-> d,
+ r :-> e,
+ r :-> f,
+ r :-> g,
+ r :-> h,
+ r :-> i,
+ r :-> j) where
+ type Src (r :-> a,
+ r :-> b,
+ r :-> c,
+ r :-> d,
+ r :-> e,
+ r :-> f,
+ r :-> g,
+ r :-> h,
+ r :-> i,
+ r :-> j) = r
+ type Dst (r :-> a,
+ r :-> b,
+ r :-> c,
+ r :-> d,
+ r :-> e,
+ r :-> f,
+ r :-> g,
+ r :-> h,
+ r :-> i,
+ r :-> j) = (a, b, c, d, e, f, g, h, i, j)
+ field (r1, r2, r3, r4, r5, r6, r7, r8, r9, r10) = lens get set
+ where get r = (getL r1 r,
+ getL r2 r,
+ getL r3 r,
+ getL r4 r,
+ getL r5 r,
+ getL r6 r,
+ getL r7 r,
+ getL r8 r,
+ getL r9 r,
+ getL r10 r)
+ set (a, b, c, d, e, f, g, h, i, j) = setL r1 a .
+ setL r2 b .
+ setL r3 c .
+ setL r4 d .
+ setL r5 e .
+ setL r6 f .
+ setL r7 g .
+ setL r8 h .
+ setL r9 i .
+ setL r10 j
+
diff --git a/Example.hs b/Example.hs
new file mode 100644
index 0000000..8653e0a
--- /dev/null
+++ b/Example.hs
@@ -0,0 +1,125 @@
+{-# LANGUAGE TypeOperators #-}
+{-# LANGUAGE ViewPatterns #-}
+{-# LANGUAGE PackageImports #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+module Main where
+
+import Data.List
+import Control.Applicative
+import Control.Arrow ((***))
+import "monads-fd" Control.Monad.State
+
+import Data.Record.Field
+import Data.Record.Label hiding ((=:))
+
+data Person = Person
+ { _firstName :: String
+ , _lastName :: String
+ , _age :: Int
+ , _superior :: Maybe Person
+ }
+
+data Book = Book
+ { _title :: String
+ , _author :: Person
+ , _characters :: [Person]
+ }
+
+$(mkLabels [''Person, ''Book])
+
+parens s = concat ["(", s, ")"]
+
+-- We could just derive Show, but let's try to eat our own dog food
+-- here.
+instance Show Person where
+ -- Arguably, RecordWildCards would be nicer here, but nothing
+ -- prevents you from using it along with this package.
+ show (match (firstName, lastName, age, superior) ->
+ (f, l, a, s)) = parens . unwords $ [ "Person"
+ , show f
+ , show l
+ , show a
+ , show s ]
+
+instance Show Book where
+ show b = parens . unwords $ "Book" : [ b .# f
+ | f <- [ title #$ show
+ , author #$ show
+ , characters #$ show ] ]
+
+howard = Person "Howard" "Lovecraft" 46 Nothing
+charles = Person "Charles" "Ward" 26 Nothing
+marinus = Person "Marinus" "Willett" 56 Nothing
+william = Person "William" "Dyer" 53 Nothing
+frank = Person "Frank" "Pabodie" 49 Nothing
+herbert = Person "Herbert" "West" 32 Nothing
+abdul = Person "Abdul" "Alhazred" 71 Nothing
+
+mountains = Book "At the Mountains of Madness" undefined []
+caseOfCDW = Book "The Case of Charles Dexter Ward" undefined []
+reanimator = Book "Herbert West -- The Re-animator" undefined []
+necronomicon = Book "Necronomicon" undefined []
+
+persons = [howard, charles, marinus, herbert, william, frank, abdul]
+
+-- All the lets and primes are ugly, but it clearly shows that nothing
+-- is being mutated. With the State monad, we could use (<=:) instead.
+main = do print $ necronomicon .# title
+ let necronomicon' = necronomicon .# author =: abdul
+ print $ necronomicon' .# author # lastName
+
+ sep
+
+ let [mountains', caseOfCDW', reanimator' ] =
+ [mountains, caseOfCDW, reanimator ] <.#> author =: howard
+
+ [ mountains'', caseOfCDW'', reanimator'' ] =
+ [ mountains', caseOfCDW', reanimator' ] *# characters =*
+ [ [ william, frank ]
+ , [ charles, marinus ]
+ , [ herbert ] ]
+ let books = [ mountains'', caseOfCDW''
+ , reanimator'', necronomicon']
+ print books
+
+ sep
+
+ print $ howard .# (firstName, lastName, age)
+ print $ howard .# (firstName, (lastName, age )) =~
+ (reverse *** reverse *** negate)
+
+ sep
+
+ print $ books <.#> characters <#> (lastName, firstName )
+ print $ sortBy (compare `onField` author # lastName) books
+ print $ sortBy (compare `onField` (characters <#> age) #$ sum) books
+
+ sep
+
+ print $ case charles of
+ (match lastName -> "Dexter") -> Left False
+ (match lastName -> "Ward") -> Left True
+ (match (age, superior) -> (a, Just s))
+ | a > 18 -> Right a
+ | otherwise -> Right (s .# age)
+
+ sep
+
+ print $ howard .# lastName #! 0
+ print $ howard .# lastName #! 0 =: Nothing
+ print $ howard .# lastName #! 0 =: Just 'X'
+
+ sep
+
+ let frank' = frank .# superior =: Just william
+ -- :: Maybe Person
+ print $ frank' .# superior
+ -- :: Maybe (Maybe Person)
+ print $ frank' .# superior <#> superior
+ -- :: Maybe (Maybe (Maybe Person))
+ print $ frank' .# superior <#> superior <#> superior
+ -- :: Maybe Person
+ print $ frank' .# superior <##> superior <##> superior <##> superior
+ where sep = putStrLn ""
+
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..31cb2d9
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,30 @@
+Copyright (c)2010, Jussi Knuuttila
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+ * Neither the name of Jussi Knuuttila nor the names of other
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/Setup.hs b/Setup.hs
new file mode 100644
index 0000000..9a994af
--- /dev/null
+++ b/Setup.hs
@@ -0,0 +1,2 @@
+import Distribution.Simple
+main = defaultMain
diff --git a/fields.cabal b/fields.cabal
new file mode 100644
index 0000000..4b5b648
--- /dev/null
+++ b/fields.cabal
@@ -0,0 +1,145 @@
+-- fields.cabal auto-generated by cabal init. For additional options,
+-- see
+-- http://www.haskell.org/cabal/release/cabal-latest/doc/users-guide/authors.html#pkg-descr.
+-- The name of the package.
+Name: fields
+
+-- The package version. See the Haskell package versioning policy
+-- (http://www.haskell.org/haskellwiki/Package_versioning_policy) for
+-- standards guiding when and how versions should be incremented.
+Version: 0.1.0
+
+-- A short (one-line) description of the package.
+Synopsis: First-class record field combinators with infix
+ record field syntax.
+
+-- A longer description of the package.
+Description: Using records, especially nested records, in
+ Haskell can sometimes be a bit of a chore.
+ Fortunately, there are several libraries in hackage
+ that make working with records easier. This library
+ is my attempt to build on top of these libraries to
+ make working with records even more pleasant!
+ .
+ In most imperative languages, records are accessed
+ using the infix dot operator. Record fields can be
+ read simply by suffixing a record value with
+ '.field' and they can be modified by simply
+ assigning to that location. Although this is not
+ the only way to access records (indeed, Haskell
+ does not use it), many people (including myself)
+ like it. This library attempts to support this
+ style for Haskell records in the following manner:
+ .
+ > record.field.subfield becomes record .# field # subfield
+ > record.field = value becomes record .# field =: value
+ .
+ Of course, the infix assignment in Haskell is pure
+ and doesn't actually mutate anything. Rather, a
+ modified version of the record is returned.
+ .
+ In addition, several combinators for first-class
+ record fields are provided, e.g. for easily
+ handling @'Functor'@s, @'Applicative'@s and
+ @'Monad'@s.
+ .
+ For a detailed description of usage, see
+ "Data.Record.Field".
+ .
+ This library is a work-in-progress. Some
+ limitations, deficiencies, points of interest and
+ possible future improvements include:
+ .
+ * Currently, a @'Field'@ instance is only provided
+ for @"fclabels"@ lenses, since that is what I
+ have personally used. However, there should be
+ nothing in principle that would prevent adding
+ instances for @"data-accessor"@ and @"lenses"@.
+ However, doing this would make this package
+ depend on several record libraries at once,
+ which might not be the best approach. Perhaps
+ this package should be split into several
+ packages?
+ .
+ * Similarly, the @'field'@ method currently
+ returns an @"fclabels"@ lens. To fully decouple
+ this package from @"fclabels"@, the @'field'@
+ method probably has to be split into @getField@,
+ @setField@ and @modField@ or something similar.
+ .
+ * For monad transformers, @"transformers"@ and
+ @"monads-fd"@ are used, since those are what
+ @"fclabels"@ uses. This might be a problem for a
+ program that uses @"mtl"@ instead.
+ .
+ * To avoid lots of parentheses, @"fields"@ uses
+ high-precedence operators at three operator
+ precedence levels. The goal was to make field
+ accesses directly usable in arithmetic
+ expressions (e.g. @r1\.\#int + r2\.\#int@).
+ Unfortunately, since Haskell has a finite number
+ of precedence levels, this goal was not properly
+ met, since @('*')@ and all higher-precedence
+ arithmetic operators have conflicting precedence
+ levels.
+ .
+ * Performance has not been analyzed at all. To my
+ knowledge, GHC doesn't do type class
+ specialization or method inlining by default, so
+ needlessly generic code might be generated, even
+ if all types are statically known. I'm hoping
+ that this can be addressed using @SPECIALIZE@
+ and @INLINE@ pragmas if it turns out to be an
+ issue.
+
+-- The license under which the package is released.
+License: BSD3
+
+-- The file containing the license text.
+License-file: LICENSE
+
+-- The package author(s).
+Author: Jussi Knuuttila
+
+-- An email address to which users can send suggestions, bug reports,
+-- and patches.
+Maintainer: [email protected]
+Homepage: http://github.com/AstraFIN/fields
+
+-- A copyright notice.
+-- Copyright:
+
+Category: Data
+
+Build-type: Simple
+
+-- Extra files to be distributed with the package, such as examples or
+-- a README.
+Extra-source-files: Example.hs
+
+-- Constraint on the version of Cabal needed to build this package.
+Cabal-version: >=1.8.0.2
+
+
+Library
+ -- Modules exported by the library.
+ Exposed-modules: Data.Record.Field
+ , Data.Record.Field.Basic
+ , Data.Record.Field.Combinators
+ , Data.Record.Field.Tuple
+ , Data.Record.Field.Indexable
+
+ -- Packages needed in order to build this package.
+ Build-depends: base >= 4 && < 5
+ , fclabels >= 0.9.1
+ , containers >= 0.3.0.0
+ , array >= 0.3.0.0
+ , transformers >= 0.2.0.0
+ , monads-fd >= 0.1.0.1
+
+ -- Modules not exported by this package.
+ -- Other-modules:
+
+ -- Extra tools (e.g. alex, hsc2hs, ...) needed to build the source.
+ -- Build-tools:
+
|
lunatech/pimpmyblog
|
df524437f6d71046e6ee6b0c06b8bda926e261d1
|
- try t identify and parse both rss and atom feed - print to STDOUT if no output file specified other improvemets
|
diff --git a/pimpmyblog.pl b/pimpmyblog.pl
index cc5a92a..f9f8eba 100755
--- a/pimpmyblog.pl
+++ b/pimpmyblog.pl
@@ -1,97 +1,112 @@
#!/usr/bin/perl -w
use strict;
use warnings;
use LWP;
use Getopt::Long;
use XML::LibXML;
-use Data::Dumper;
+#use Data::Dumper;
sub print_usage {
my $usage = <<USAGE;
$0 : -f "url of the blog" [-t "template file"] [-o "output file"]
+if no -o is specified, it prints on STDOUT
USAGE
print $usage;
}
sub fetch_feed {
my $url = shift;
my $ua = LWP::UserAgent->new;
# Create a request
my $req = HTTP::Request->new( GET => $url );
my $res = $ua->request($req);
if ( $res->is_success ) {
return $res->content;
}
else {
$@ = "error status: ". $res->status_line."; server message: ". $res->message;
return undef;
}
}
sub parse_feed {
+ # to id a feed do - 'name(/*)'
my $xml_str = shift;
my $parser = XML::LibXML->new();
my $doc = $parser->parse_string($xml_str);
+ my $feed_type = $doc->findvalue("name(/*)");
+ my ($query_title,$query_link) ;
# we just need the first item and first link
- my $query ;
- my %res ;
- $query = "/rss/channel/item[1]/link";
- $res{"link"} = $doc->findvalue($query);
- $query = "/rss/channel/item[1]/title";
- $res{"title"} = $doc->findvalue($query);
+ if ($feed_type eq "feed") {
+ ($query_title,$query_link) = ("/feed/entry[1]/title","/feed/entry[1]/id")
+ }
+ elsif ($feed_type eq "rss") {
+ ($query_title,$query_link) = ("/rss/channel/item[1]/title","/rss/channel/item[1]/link")
+ }
+ else {
+ $@ = "unknown feed type";
+ return undef;
+ }
+ my %res;
+ $res{"title"} = $doc->findvalue($query_title);
+ $res{"link"} = $doc->findvalue($query_link);
unless (defined($res{"link"}) and defined ($res{"title"})) {
$@ = "error in parsing feed";
return undef;
}
return \%res;
}
my ($feed_url,$tpl_file,$out_file) =
- (undef, "/tmp/sig.tpl","/tmp/mysig.txt");
+ (undef, "/tmp/sig.tpl","-");
GetOptions(
"f|feed=s" => \$feed_url,
"t|template=s" => \$tpl_file,
"o|output=s" => \$out_file )
or die ("error processing options" . $@);
unless (defined($feed_url)) {print_usage ; exit 0;}
my $feed_xml = fetch_feed ($feed_url)
or die ("failed fetching $feed_url with error : " .$@);
my $ref_feed_item = parse_feed($feed_xml)
or die ("failed parsing feed from url $feed_url with error : ".$@);
open TPL,$tpl_file
or die ("error opening template file $tpl_file with error : " .$!);
my $sig_str;
while (<TPL>) {
s/(!title!)/$ref_feed_item->{title}/;
s/(!url!)/$ref_feed_item->{link}/;
$sig_str.= $_;
}
close TPL;
-open OUT,">",$out_file
- or die ("error opening signature file $out_file with error : " .$!);
-
+if ($out_file eq "-") {
+ print $sig_str;
+}
+else {
+ open OUT,">",$out_file
+ or die ("error opening signature file $out_file with error : " .$!);
+ print OUT $sig_str;
+ close OUT;
+}
-print OUT $sig_str;
-close OUT;
|
lunatech/pimpmyblog
|
455c8851f2b2155ddaf88a8afd9d442cc6fe921e
|
updating sig
|
diff --git a/mysig.tpl b/mysig.tpl
index 4e86e71..5628219 100644
--- a/mysig.tpl
+++ b/mysig.tpl
@@ -1,9 +1,6 @@
-raj shekhar
-
-Take my love, take my land
-Take me where I cannot stand
-I don't care, I'm still free
-You can't take the sky from me
-
-Read the latest at my blog:
-"!title!" <!url!>
\ No newline at end of file
+Raj Shekhar
+-
+Simon: I swear... when it's appropriate.
+Kaylee: Simon, the whole point of swearing is that it ain't appropriate.
+-
+Read the latest at my blog: "!title!" <!url!>
|
lunatech/pimpmyblog
|
ed132fccfb4ce9f1a79285715283d48f97e29d65
|
pl scrpt to fetch create the sig file
|
diff --git a/pimpmyblog.pl b/pimpmyblog.pl
new file mode 100755
index 0000000..cc5a92a
--- /dev/null
+++ b/pimpmyblog.pl
@@ -0,0 +1,97 @@
+#!/usr/bin/perl -w
+
+use strict;
+use warnings;
+
+use LWP;
+use Getopt::Long;
+use XML::LibXML;
+use Data::Dumper;
+
+sub print_usage {
+ my $usage = <<USAGE;
+$0 : -f "url of the blog" [-t "template file"] [-o "output file"]
+USAGE
+
+print $usage;
+
+}
+
+sub fetch_feed {
+ my $url = shift;
+
+ my $ua = LWP::UserAgent->new;
+
+ # Create a request
+ my $req = HTTP::Request->new( GET => $url );
+ my $res = $ua->request($req);
+ if ( $res->is_success ) {
+ return $res->content;
+ }
+ else {
+ $@ = "error status: ". $res->status_line."; server message: ". $res->message;
+ return undef;
+ }
+
+}
+
+
+sub parse_feed {
+ my $xml_str = shift;
+ my $parser = XML::LibXML->new();
+ my $doc = $parser->parse_string($xml_str);
+ # we just need the first item and first link
+ my $query ;
+ my %res ;
+ $query = "/rss/channel/item[1]/link";
+ $res{"link"} = $doc->findvalue($query);
+ $query = "/rss/channel/item[1]/title";
+ $res{"title"} = $doc->findvalue($query);
+ unless (defined($res{"link"}) and defined ($res{"title"})) {
+ $@ = "error in parsing feed";
+ return undef;
+ }
+ return \%res;
+}
+
+my ($feed_url,$tpl_file,$out_file) =
+ (undef, "/tmp/sig.tpl","/tmp/mysig.txt");
+
+GetOptions(
+ "f|feed=s" => \$feed_url,
+ "t|template=s" => \$tpl_file,
+ "o|output=s" => \$out_file )
+ or die ("error processing options" . $@);
+
+unless (defined($feed_url)) {print_usage ; exit 0;}
+
+my $feed_xml = fetch_feed ($feed_url)
+ or die ("failed fetching $feed_url with error : " .$@);
+
+my $ref_feed_item = parse_feed($feed_xml)
+ or die ("failed parsing feed from url $feed_url with error : ".$@);
+
+open TPL,$tpl_file
+ or die ("error opening template file $tpl_file with error : " .$!);
+my $sig_str;
+
+while (<TPL>) {
+ s/(!title!)/$ref_feed_item->{title}/;
+ s/(!url!)/$ref_feed_item->{link}/;
+ $sig_str.= $_;
+}
+close TPL;
+
+open OUT,">",$out_file
+ or die ("error opening signature file $out_file with error : " .$!);
+
+
+print OUT $sig_str;
+close OUT;
+
+
+
+
+
+
+
|
lunatech/pimpmyblog
|
5105a109e445d2e47c909d1f3ad63249474ccb52
|
added options
|
diff --git a/pimpmyblog.php b/pimpmyblog.php
index ce3a8ff..31c3443 100755
--- a/pimpmyblog.php
+++ b/pimpmyblog.php
@@ -1,45 +1,50 @@
#!/usr/bin/php -dopen_basedir=
<?php
function fetch_url($url)
{
$ch = curl_init ($url) ;
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1) ;
$res = curl_exec ($ch) ;
curl_close ($ch) ;
return $res;
}
function fetch_last_post($blog_xml)
{
$h_xml = simplexml_load_string($blog_xml);
$result['title'] = (string)$h_xml->channel->item[0]->title;
$result['link'] = (string)$h_xml->channel->item[0]->link;
$result['pubDate'] = (string)$h_xml->channel->item[0]->pubDate;
return $result;
}
function create_mail_sig($template,$title,$link)
{
$tmpl = file_get_contents($template);
$magic_url = "/\!url\!/";
$magic_title = "/\!title\!/";
$tmpl = preg_replace($magic_url,$link,$tmpl);
$tmpl = preg_replace($magic_title,$title,$tmpl);
//preg_replace($tmpl,"/$magic_title/",$title);
return $tmpl;
}
-$blog_rss_url = "http://rajshekhar.net/blog/feeds/index.rss2";
-$f_template = "/Users/rshekhar/personal/programming/pimpmyblog/mysig.tpl";
+$opts = getopt('u:t:');
+if (!( key_exists('u',$opts) && key_exists('t',$opts))) {
+ die("required args not passed\n");
+}
+
+$blog_rss_url = $opts['u'];
+$f_template = $opts['t'];
$blog_xml = fetch_url($blog_rss_url);
$last_blog = fetch_last_post($blog_xml);
$mail_sig_txt = create_mail_sig($f_template,$last_blog['title'],$last_blog['link']);
print $mail_sig_txt;
?>
\ No newline at end of file
|
lunatech/pimpmyblog
|
469a5592a2e71aa1e1e52656a164894ad646c873
|
template for the signature
|
diff --git a/mysig.tpl b/mysig.tpl
index 4454bb3..4e86e71 100644
--- a/mysig.tpl
+++ b/mysig.tpl
@@ -1,6 +1,9 @@
raj shekhar
-http://rajshekhar.net
-I've never made anyone's life easier and you know it!
+
+Take my love, take my land
+Take me where I cannot stand
+I don't care, I'm still free
+You can't take the sky from me
Read the latest at my blog:
-"!title!" <!url!>
+"!title!" <!url!>
\ No newline at end of file
|
lunatech/pimpmyblog
|
3a9450c18520f58527ce3497dd7b243f0eb76848
|
functional php script
|
diff --git a/mysig.tpl b/mysig.tpl
new file mode 100644
index 0000000..4454bb3
--- /dev/null
+++ b/mysig.tpl
@@ -0,0 +1,6 @@
+raj shekhar
+http://rajshekhar.net
+I've never made anyone's life easier and you know it!
+
+Read the latest at my blog:
+"!title!" <!url!>
diff --git a/pimpmyblog.php b/pimpmyblog.php
index 09ffb10..ce3a8ff 100755
--- a/pimpmyblog.php
+++ b/pimpmyblog.php
@@ -1,38 +1,45 @@
#!/usr/bin/php -dopen_basedir=
<?php
function fetch_url($url)
{
$ch = curl_init ($url) ;
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1) ;
$res = curl_exec ($ch) ;
curl_close ($ch) ;
return $res;
}
-function fetch_last_post_xpath($blog_xml)
-{
- $h_xml = simplexml_load_string($blog_xml);
- $t = $h_xml->xpath('/rss/channel/item[1]/title');
- $result['title'] = (string)$t[0];
- //var_dump($result);
- return $result;
-}
-
function fetch_last_post($blog_xml)
{
$h_xml = simplexml_load_string($blog_xml);
$result['title'] = (string)$h_xml->channel->item[0]->title;
- $result['title'] = (string)$h_xml->xpath('/rss/channel/item');
$result['link'] = (string)$h_xml->channel->item[0]->link;
$result['pubDate'] = (string)$h_xml->channel->item[0]->pubDate;
- $result = $h_xml->xpath('/rss/channel/item[1]/title');
return $result;
}
-$blog_rss_url = "http://joomladev.rajshekhar.net/index.php?format=feed&type=rss";
+function create_mail_sig($template,$title,$link)
+{
+ $tmpl = file_get_contents($template);
+ $magic_url = "/\!url\!/";
+ $magic_title = "/\!title\!/";
+
+
+ $tmpl = preg_replace($magic_url,$link,$tmpl);
+ $tmpl = preg_replace($magic_title,$title,$tmpl);
+ //preg_replace($tmpl,"/$magic_title/",$title);
+ return $tmpl;
+}
+
+$blog_rss_url = "http://rajshekhar.net/blog/feeds/index.rss2";
+$f_template = "/Users/rshekhar/personal/programming/pimpmyblog/mysig.tpl";
+
$blog_xml = fetch_url($blog_rss_url);
-$last_blog_xpath = fetch_last_post_xpath($blog_xml);
-//$last_blog = fetch_last_post($blog_xml);
+$last_blog = fetch_last_post($blog_xml);
+
+$mail_sig_txt = create_mail_sig($f_template,$last_blog['title'],$last_blog['link']);
+print $mail_sig_txt;
+
?>
\ No newline at end of file
|
lunatech/pimpmyblog
|
ffe1a60c51d47faad2761d9d09290cf5b151a363
|
experimented with xpath on this branch. However, did not see any difference in the speed in using xpath
|
diff --git a/pimpmyblog.php b/pimpmyblog.php
index 823c7c0..09ffb10 100755
--- a/pimpmyblog.php
+++ b/pimpmyblog.php
@@ -1,26 +1,38 @@
#!/usr/bin/php -dopen_basedir=
<?php
function fetch_url($url)
{
$ch = curl_init ($url) ;
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1) ;
$res = curl_exec ($ch) ;
curl_close ($ch) ;
return $res;
}
+
+function fetch_last_post_xpath($blog_xml)
+{
+ $h_xml = simplexml_load_string($blog_xml);
+ $t = $h_xml->xpath('/rss/channel/item[1]/title');
+ $result['title'] = (string)$t[0];
+ //var_dump($result);
+ return $result;
+}
+
function fetch_last_post($blog_xml)
{
$h_xml = simplexml_load_string($blog_xml);
$result['title'] = (string)$h_xml->channel->item[0]->title;
+ $result['title'] = (string)$h_xml->xpath('/rss/channel/item');
$result['link'] = (string)$h_xml->channel->item[0]->link;
$result['pubDate'] = (string)$h_xml->channel->item[0]->pubDate;
+ $result = $h_xml->xpath('/rss/channel/item[1]/title');
return $result;
}
-$blog_rss_url = "http://rajshekhar.net/blog/feeds/index.rss2";
+$blog_rss_url = "http://joomladev.rajshekhar.net/index.php?format=feed&type=rss";
$blog_xml = fetch_url($blog_rss_url);
-$last_blog = fetch_last_post($blog_xml);
-print_r($last_blog);
+$last_blog_xpath = fetch_last_post_xpath($blog_xml);
+//$last_blog = fetch_last_post($blog_xml);
?>
\ No newline at end of file
|
lunatech/pimpmyblog
|
8deb72d4c6ca186289d46753852cff1a4c64d70a
|
initial version
|
diff --git a/TODO b/TODO
new file mode 100644
index 0000000..f571c25
--- /dev/null
+++ b/TODO
@@ -0,0 +1,5 @@
+-*-outline-*-
+
+* Add a "decay" functionality
+This will not add the blog line to the signature if it is more than N
+days old
diff --git a/pimpmyblog.php b/pimpmyblog.php
new file mode 100755
index 0000000..823c7c0
--- /dev/null
+++ b/pimpmyblog.php
@@ -0,0 +1,26 @@
+#!/usr/bin/php -dopen_basedir=
+<?php
+
+function fetch_url($url)
+{
+ $ch = curl_init ($url) ;
+ curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1) ;
+ $res = curl_exec ($ch) ;
+ curl_close ($ch) ;
+ return $res;
+}
+
+function fetch_last_post($blog_xml)
+{
+ $h_xml = simplexml_load_string($blog_xml);
+ $result['title'] = (string)$h_xml->channel->item[0]->title;
+ $result['link'] = (string)$h_xml->channel->item[0]->link;
+ $result['pubDate'] = (string)$h_xml->channel->item[0]->pubDate;
+ return $result;
+}
+
+$blog_rss_url = "http://rajshekhar.net/blog/feeds/index.rss2";
+$blog_xml = fetch_url($blog_rss_url);
+$last_blog = fetch_last_post($blog_xml);
+print_r($last_blog);
+?>
\ No newline at end of file
|
cvan/secinv-client
|
46c4759656b9dd2233bef70088a5e4745c5a6cca
|
concatenate multiple ports
|
diff --git a/client/inventory.py b/client/inventory.py
index 1986203..f0cff66 100644
--- a/client/inventory.py
+++ b/client/inventory.py
@@ -1,513 +1,521 @@
from ConfigParser import RawConfigParser, ParsingError
import cStringIO
import os
import re
import subprocess
import string
from apacheparser import *
from common import *
# TODO: Use `logging`.
class Interfaces:
@classmethod
def get_interfaces(cls):
"""
Return dictionary of IP address, MAC address, and netmask for each
interface.
"""
i_dict = {}
open_files = subprocess.Popen(IFCONFIG, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = open_files.split('\n')
interface = ''
for line in lines:
if not line:
continue
ls = line.split(' ')
if ls[0].strip():
interface = ls[0].strip()
i_dict[interface] = {'i_ip': '', 'i_mac': '', 'i_mask': ''}
# Get MAC address.
if 'HWaddr' in ls:
i_dict[interface]['i_mac'] = ls[ls.index('HWaddr') + 1].lower()
# Get IP address and netmask.
if 'inet' in ls:
inet = ls[ls.index('inet') + 1]
if ':' in inet:
i_dict[interface]['i_ip'] = inet.split(':')[1]
else:
i_dict[interface]['i_ip'] = inet
if ':' in ls[-1]:
i_dict[interface]['i_mask'] = ls[-1].split(':')[1]
else:
i_dict[interface]['i_mask'] = ls[-1]
return i_dict
class System:
@classmethod
def _get_ip(self):
"""Get `hostname` and return local IP address from hostname."""
try:
import socket
sys_ip = socket.gethostbyaddr(socket.gethostname())[-1][0]
except (socket.error, socket.herror, socket.gaierror):
sys_ip = ''
return sys_ip
@classmethod
def _get_hostname(self):
"""Parse `hostname` and return local hostname."""
full_hn = subprocess.Popen(HOSTNAME, shell=True,
stdout=subprocess.PIPE).communicate()[0]
p = re.compile(r'([^\.]+)')
m = p.match(full_hn)
return m and m.group(0).strip() or ''
@classmethod
def _get_kernel_release(self):
"""
Call `uname -r` and return kernel release version number.
"""
kernel_rel = subprocess.Popen('%s -r' % UNAME, shell=True,
stdout=subprocess.PIPE).communicate()[0]
return kernel_rel.strip()
@classmethod
def _get_redhat_version(self, filename=RH_RELEASE):
"""
Parse `redhat-release` file and return release name and version number.
"""
rh_version = ''
try:
rh_file = open(filename, 'r')
release_line = rh_file.readline()
rh_file.close()
p = re.compile(r'Red Hat Enterprise Linux \S+ release ([^\n].+)\n')
m = p.match(release_line)
if m:
rh_version = m.group(1)
except IOError:
#raise Exception("Notice: Cannot open redhat-release file '%s'." % filename)
print "Notice: Cannot open redhat-release file '%s'" % filename
rh_version = ''
return rh_version.strip()
@classmethod
def _ip_fwd_status(self, filename=IP_FORWARD):
"""
Parse `ip_forward` file and return a boolean of IP forwarding status.
"""
ip_fwd = 0
try:
ip_file = open(filename, 'r')
status_line = ip_file.readline().strip()
ip_file.close()
if status_line == '1':
ip_fwd = 1
except IOError:
#raise Exception("Notice: Cannot open ip_forward file '%s'." % filename)
print "Notice: Cannot open ip_forward file '%s'" % filename
pass
return ip_fwd
@classmethod
def _nfs_status(self):
"""
Check and return an integer of whether a NFS is currently mounted.
"""
found_nfs = 0
mount_info = subprocess.Popen('%s -l' % MOUNT, shell=True,
stdout=subprocess.PIPE).communicate()[0]
mount_info = mount_info.strip('\n')
lines = mount_info.split('\n')
for line in lines:
if not line:
continue
p = re.compile(r'.+ type ([^\s].+) ')
m = p.match(line)
if m and m.group(1) == 'nfs':
found_nfs = 1
break
return found_nfs
@classmethod
def get_system_dict(cls):
"""Build and return dictionary of assets fields."""
i_dict = {'sys_ip': cls._get_ip(),
'hostname': cls._get_hostname(),
'kernel_rel': cls._get_kernel_release(),
'rh_rel': cls._get_redhat_version(),
'nfs': cls._nfs_status(),
'ip_fwd': cls._ip_fwd_status()}
return i_dict
class Services:
@classmethod
def get_services(cls):
"""
Parse `lsof -ni -P` and return a dictionary of all listening processes
and ports.
"""
ports_dict = {}
open_files = subprocess.Popen('%s -ni -P' % LSOF, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = open_files.split('\n')
for line in lines:
if not line:
continue
chunks = re.split('\s*', line)
if not '(LISTEN)' in chunks:
continue
proc_name = chunks[0]
full_name = chunks[-2]
- ports_dict[proc_name] = full_name.split(':')[1]
+ port = full_name.split(':')[1]
+
+ ports_dict.setdefault(proc_name, [])
+
+ if port not in ports_dict[proc_name]:
+ ports_dict[proc_name].append(port)
+
+ for k, v in ports_dict.iteritems():
+ ports_dict[k] = ', '.join(v)
return ports_dict
class RPMs:
@classmethod
def get_rpms(cls, filename=RPM_PKGS):
"""Get all RPMs installed."""
rpms_dict = {'list': ''}
try:
rpmpkgs_file = open(filename, 'r')
lines = rpmpkgs_file.readlines()
rpmpkgs_file.close()
lines_str = ''.join(lines)
lines_str = lines_str.strip('\n')
rpms_dict = {'list': lines_str}
except IOError:
# TODO: Logging Error.
#raise Exception("Notice: Cannot open rpmpkgs file '%s'." % filename)
print "Notice: Cannot open rpmpkgs file '%s'" % filename
return rpms_dict
class SSHConfig:
@classmethod
def parse(cls, filename=SSH_CONFIG_FILE):
"""
Parse SSH configuration file and a return a dictionary of
body, parameters/values, and filename.
"""
body = ''
items = {}
filename = path(filename)
try:
file_obj = open(filename, 'r')
lines = file_obj.readlines()
file_obj.close()
except IOError:
#raise Exception("Notice: Cannot open SSH config file '%s'." % filename)
print "Notice: Cannot open SSH config file '%s'" % filename
lines = ''
if lines:
body = ''
for index, line in enumerate(lines):
line = line.strip()
if not line or (not PARSE_CONF_COMMENTS and line[0] == '#'):
continue
# Concatenate multiline instructions delimited by backslash-newlines.
if line and line[-1] == '\\':
while line[-1] == '\\':
line = ' '.join([line[:-1].strip(),
lines[index + 1].strip()])
del lines[index + 1]
if line[0] != '#':
ls = re.split('\s*', line)
if ls[0] in items:
items[ls[0]] += [' %s' % ' '.join(ls[1:])]
else:
items[ls[0]] = [' '.join(ls[1:])]
body += '%s\n' % line
ssh_dict = {'body': body, 'items': items, 'filename': filename}
return ssh_dict
class IPTables:
@classmethod
def _status(self):
"""
Check and return an integer of whether iptables are running.
"""
ipt_status = 0
status_info = subprocess.Popen('%s status' % IPTABLES, shell=True,
stdout=subprocess.PIPE).communicate()[0]
status_info = status_info.strip('\n')
if status_info != 'Firewall is stopped.':
ipt_status = 1
return ipt_status
@classmethod
def _parse(self):
"""
Parse IP tables and a return a dictionary of policies for each table.
"""
ipt_dict = {}
lines = subprocess.Popen(IPTABLES_SAVE, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = lines.split('\n')
table_name = ''
body = ''
for index, line in enumerate(lines):
line = line.strip()
if not line or (not PARSE_CONF_COMMENTS and line[0] == '#') or \
(PARSE_CONF_COMMENTS and line.startswith('# Generated by') or \
line.startswith('# Completed on')):
continue
# Concatenate multiline instructions delimited by backslash-newlines.
if line and line[-1] == '\\':
while line[-1] == '\\':
line = ' '.join([line[:-1].strip(),
lines[index + 1].strip()])
del lines[index + 1]
if line[0] == ':':
# Chain specification.
# :<chain-name> <chain-policy> [<packet-counter>:<byte-counter>]
# Strip packet-counter and byte-counter.
ls = line.split()
if len(ls) > 2 and ls[0].strip():
chain_name = ls[0].strip()[1:]
chain_policy = ls[1].strip()
line = ':%s %s' % (chain_name, chain_policy)
body += '%s\n' % line
ipt_dict['body'] = body
return ipt_dict
@classmethod
def get_ipt_dict(cls):
"""Build and return dictionary of iptables fields."""
ipt_dict = {'status': cls._status(),
'rules': cls._parse()}
return ipt_dict
class ApacheConfigList:
def __init__(self):
self.apache_configs = []
def recurse_apache_includes(self, fn, includes_list):
for i_fn in includes_list:
i_ac = ApacheConfig()
i_ac.parse(i_fn)
i_apache = {'body': i_ac.get_body(),
'filename': i_fn,
'directives': i_ac.get_directives(),
'domains': i_ac.get_domains(),
'included': i_ac.get_includes()}
# Remove circular includes.
try:
del i_apache['included'][i_apache['included'].index(fn)]
except ValueError:
pass
self.apache_configs.append(i_apache)
self.recurse_apache_includes(i_fn, i_apache['included'])
def recurse(self):
ac = ApacheConfig()
ac.parse(APACHE_CONF)
apache = {'body': ac.get_body(),
'filename': APACHE_CONF,
'directives': ac.get_directives(),
'domains': ac.get_domains(),
'included': ac.get_includes()}
# Remove circular includes.
try:
del apache['included'][apache['included'].index(APACHE_CONF)]
except ValueError:
pass
self.apache_configs.append(apache)
self.recurse_apache_includes(APACHE_CONF, apache['included'])
def get_apache_configs(self):
if os.path.exists(APACHE_CONF):
self.recurse()
return self.apache_configs
class PHPConfig:
def get_items(self):
parameters = {}
php_config = RawConfigParser()
sections = []
try:
contents = file(path(MY_CNF))
lines = contents.readlines()
# Workaround for `allow_no_value` (which is available in only Python 2.7+).
body = ''
for line in lines:
stripped_line = line.strip()
if not stripped_line or stripped_line[0] in ('#', ';'):
pass
elif line[0] != '[' and line[-1] != ']' and \
'=' not in line:
line = '%s=\n' % line.rstrip('\n')
body += line
php_config.readfp(cStringIO.StringIO(body))
sections = php_config.sections()
except IOError:
#sys.exit("Notice: Cannot open PHP configuration file '%s'" % MY_CNF)
print "Notice: Cannot open PHP configuration file '%s'" % MY_CNF
except ParsingError, error:
print "Notice: Cannot parse PHP configuration file '%s'\n%s" % (PHP_INI, error)
for section in sections:
items = php_config.items(section)
for item in items:
if item[0] in parameters:
parameters[item[0]] += [item[1]]
else:
parameters[item[0]] = [item[1]]
return parameters
def parse(self):
try:
file_obj = open(path(MY_CNF), 'r')
lines = file_obj.readlines()
file_obj.close()
body = clean_body(lines, '#')
items = self.get_items()
my_dict = {'body': body, 'items': items, 'filename': MY_CNF}
except IOError:
#raise Exception("Notice: Cannot open PHP configuration file '%s'" % MY_CNF)'
print "Notice: Cannot open PHP configuration file '%s'" % MY_CNF
my_dict = {'body': '', 'items': [], 'filename': ''}
return my_dict
class MySQLConfig:
def get_items(self):
parameters = {}
mysql_config = RawConfigParser()
sections = []
try:
contents = file(path(MY_CNF))
lines = contents.readlines()
# Workaround for `allow_no_value` (which is available in only Python 2.7+).
body = ''
for line in lines:
stripped_line = line.strip()
if not stripped_line or stripped_line[0] in ('#', ';'):
pass
elif line[0] != '[' and line[-1] != ']' and \
'=' not in line:
line = '%s=\n' % line.rstrip('\n')
body += line
mysql_config.readfp(cStringIO.StringIO(body))
sections = mysql_config.sections()
except IOError:
#sys.exit("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)
print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF
except ParsingError, error:
print "Notice: Cannot parse PHP configuration file '%s'\n%s" % (PHP_INI, error)
for section in sections:
items = mysql_config.items(section)
for item in items:
if item[0] in parameters:
parameters[item[0]] += [item[1]]
else:
parameters[item[0]] = [item[1]]
return parameters
def parse(self):
try:
file_obj = open(path(MY_CNF), 'r')
lines = file_obj.readlines()
file_obj.close()
body = clean_body(lines, '#')
items = self.get_items()
my_dict = {'body': body, 'items': items, 'filename': MY_CNF}
except IOError:
#raise Exception("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)'
print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF
my_dict = {'body': '', 'items': [], 'filename': ''}
return my_dict
|
cvan/secinv-client
|
129bf51ea849de8aca35337f92da3b9854b09c53
|
split line by space
|
diff --git a/client/inventory.py b/client/inventory.py
index 7230139..1986203 100644
--- a/client/inventory.py
+++ b/client/inventory.py
@@ -1,513 +1,513 @@
from ConfigParser import RawConfigParser, ParsingError
import cStringIO
import os
import re
import subprocess
import string
from apacheparser import *
from common import *
# TODO: Use `logging`.
class Interfaces:
@classmethod
def get_interfaces(cls):
"""
Return dictionary of IP address, MAC address, and netmask for each
interface.
"""
i_dict = {}
open_files = subprocess.Popen(IFCONFIG, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = open_files.split('\n')
interface = ''
for line in lines:
if not line:
continue
- ls = line.split()
+ ls = line.split(' ')
if ls[0].strip():
interface = ls[0].strip()
i_dict[interface] = {'i_ip': '', 'i_mac': '', 'i_mask': ''}
# Get MAC address.
if 'HWaddr' in ls:
i_dict[interface]['i_mac'] = ls[ls.index('HWaddr') + 1].lower()
# Get IP address and netmask.
if 'inet' in ls:
inet = ls[ls.index('inet') + 1]
if ':' in inet:
i_dict[interface]['i_ip'] = inet.split(':')[1]
else:
i_dict[interface]['i_ip'] = inet
if ':' in ls[-1]:
i_dict[interface]['i_mask'] = ls[-1].split(':')[1]
else:
i_dict[interface]['i_mask'] = ls[-1]
return i_dict
class System:
@classmethod
def _get_ip(self):
"""Get `hostname` and return local IP address from hostname."""
try:
import socket
sys_ip = socket.gethostbyaddr(socket.gethostname())[-1][0]
except (socket.error, socket.herror, socket.gaierror):
sys_ip = ''
return sys_ip
@classmethod
def _get_hostname(self):
"""Parse `hostname` and return local hostname."""
full_hn = subprocess.Popen(HOSTNAME, shell=True,
stdout=subprocess.PIPE).communicate()[0]
p = re.compile(r'([^\.]+)')
m = p.match(full_hn)
return m and m.group(0).strip() or ''
@classmethod
def _get_kernel_release(self):
"""
Call `uname -r` and return kernel release version number.
"""
kernel_rel = subprocess.Popen('%s -r' % UNAME, shell=True,
stdout=subprocess.PIPE).communicate()[0]
return kernel_rel.strip()
@classmethod
def _get_redhat_version(self, filename=RH_RELEASE):
"""
Parse `redhat-release` file and return release name and version number.
"""
rh_version = ''
try:
rh_file = open(filename, 'r')
release_line = rh_file.readline()
rh_file.close()
p = re.compile(r'Red Hat Enterprise Linux \S+ release ([^\n].+)\n')
m = p.match(release_line)
if m:
rh_version = m.group(1)
except IOError:
#raise Exception("Notice: Cannot open redhat-release file '%s'." % filename)
print "Notice: Cannot open redhat-release file '%s'" % filename
rh_version = ''
return rh_version.strip()
@classmethod
def _ip_fwd_status(self, filename=IP_FORWARD):
"""
Parse `ip_forward` file and return a boolean of IP forwarding status.
"""
ip_fwd = 0
try:
ip_file = open(filename, 'r')
status_line = ip_file.readline().strip()
ip_file.close()
if status_line == '1':
ip_fwd = 1
except IOError:
#raise Exception("Notice: Cannot open ip_forward file '%s'." % filename)
print "Notice: Cannot open ip_forward file '%s'" % filename
pass
return ip_fwd
@classmethod
def _nfs_status(self):
"""
Check and return an integer of whether a NFS is currently mounted.
"""
found_nfs = 0
mount_info = subprocess.Popen('%s -l' % MOUNT, shell=True,
stdout=subprocess.PIPE).communicate()[0]
mount_info = mount_info.strip('\n')
lines = mount_info.split('\n')
for line in lines:
if not line:
continue
p = re.compile(r'.+ type ([^\s].+) ')
m = p.match(line)
if m and m.group(1) == 'nfs':
found_nfs = 1
break
return found_nfs
@classmethod
def get_system_dict(cls):
"""Build and return dictionary of assets fields."""
i_dict = {'sys_ip': cls._get_ip(),
'hostname': cls._get_hostname(),
'kernel_rel': cls._get_kernel_release(),
'rh_rel': cls._get_redhat_version(),
'nfs': cls._nfs_status(),
'ip_fwd': cls._ip_fwd_status()}
return i_dict
class Services:
@classmethod
def get_services(cls):
"""
Parse `lsof -ni -P` and return a dictionary of all listening processes
and ports.
"""
ports_dict = {}
open_files = subprocess.Popen('%s -ni -P' % LSOF, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = open_files.split('\n')
for line in lines:
if not line:
continue
chunks = re.split('\s*', line)
if not '(LISTEN)' in chunks:
continue
proc_name = chunks[0]
full_name = chunks[-2]
ports_dict[proc_name] = full_name.split(':')[1]
return ports_dict
class RPMs:
@classmethod
def get_rpms(cls, filename=RPM_PKGS):
"""Get all RPMs installed."""
rpms_dict = {'list': ''}
try:
rpmpkgs_file = open(filename, 'r')
lines = rpmpkgs_file.readlines()
rpmpkgs_file.close()
lines_str = ''.join(lines)
lines_str = lines_str.strip('\n')
rpms_dict = {'list': lines_str}
except IOError:
# TODO: Logging Error.
#raise Exception("Notice: Cannot open rpmpkgs file '%s'." % filename)
print "Notice: Cannot open rpmpkgs file '%s'" % filename
return rpms_dict
class SSHConfig:
@classmethod
def parse(cls, filename=SSH_CONFIG_FILE):
"""
Parse SSH configuration file and a return a dictionary of
body, parameters/values, and filename.
"""
body = ''
items = {}
filename = path(filename)
try:
file_obj = open(filename, 'r')
lines = file_obj.readlines()
file_obj.close()
except IOError:
#raise Exception("Notice: Cannot open SSH config file '%s'." % filename)
print "Notice: Cannot open SSH config file '%s'" % filename
lines = ''
if lines:
body = ''
for index, line in enumerate(lines):
line = line.strip()
if not line or (not PARSE_CONF_COMMENTS and line[0] == '#'):
continue
# Concatenate multiline instructions delimited by backslash-newlines.
if line and line[-1] == '\\':
while line[-1] == '\\':
line = ' '.join([line[:-1].strip(),
lines[index + 1].strip()])
del lines[index + 1]
if line[0] != '#':
ls = re.split('\s*', line)
if ls[0] in items:
items[ls[0]] += [' %s' % ' '.join(ls[1:])]
else:
items[ls[0]] = [' '.join(ls[1:])]
body += '%s\n' % line
ssh_dict = {'body': body, 'items': items, 'filename': filename}
return ssh_dict
class IPTables:
@classmethod
def _status(self):
"""
Check and return an integer of whether iptables are running.
"""
ipt_status = 0
status_info = subprocess.Popen('%s status' % IPTABLES, shell=True,
stdout=subprocess.PIPE).communicate()[0]
status_info = status_info.strip('\n')
if status_info != 'Firewall is stopped.':
ipt_status = 1
return ipt_status
@classmethod
def _parse(self):
"""
Parse IP tables and a return a dictionary of policies for each table.
"""
ipt_dict = {}
lines = subprocess.Popen(IPTABLES_SAVE, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = lines.split('\n')
table_name = ''
body = ''
for index, line in enumerate(lines):
line = line.strip()
if not line or (not PARSE_CONF_COMMENTS and line[0] == '#') or \
(PARSE_CONF_COMMENTS and line.startswith('# Generated by') or \
line.startswith('# Completed on')):
continue
# Concatenate multiline instructions delimited by backslash-newlines.
if line and line[-1] == '\\':
while line[-1] == '\\':
line = ' '.join([line[:-1].strip(),
lines[index + 1].strip()])
del lines[index + 1]
if line[0] == ':':
# Chain specification.
# :<chain-name> <chain-policy> [<packet-counter>:<byte-counter>]
# Strip packet-counter and byte-counter.
ls = line.split()
if len(ls) > 2 and ls[0].strip():
chain_name = ls[0].strip()[1:]
chain_policy = ls[1].strip()
line = ':%s %s' % (chain_name, chain_policy)
body += '%s\n' % line
ipt_dict['body'] = body
return ipt_dict
@classmethod
def get_ipt_dict(cls):
"""Build and return dictionary of iptables fields."""
ipt_dict = {'status': cls._status(),
'rules': cls._parse()}
return ipt_dict
class ApacheConfigList:
def __init__(self):
self.apache_configs = []
def recurse_apache_includes(self, fn, includes_list):
for i_fn in includes_list:
i_ac = ApacheConfig()
i_ac.parse(i_fn)
i_apache = {'body': i_ac.get_body(),
'filename': i_fn,
'directives': i_ac.get_directives(),
'domains': i_ac.get_domains(),
'included': i_ac.get_includes()}
# Remove circular includes.
try:
del i_apache['included'][i_apache['included'].index(fn)]
except ValueError:
pass
self.apache_configs.append(i_apache)
self.recurse_apache_includes(i_fn, i_apache['included'])
def recurse(self):
ac = ApacheConfig()
ac.parse(APACHE_CONF)
apache = {'body': ac.get_body(),
'filename': APACHE_CONF,
'directives': ac.get_directives(),
'domains': ac.get_domains(),
'included': ac.get_includes()}
# Remove circular includes.
try:
del apache['included'][apache['included'].index(APACHE_CONF)]
except ValueError:
pass
self.apache_configs.append(apache)
self.recurse_apache_includes(APACHE_CONF, apache['included'])
def get_apache_configs(self):
if os.path.exists(APACHE_CONF):
self.recurse()
return self.apache_configs
class PHPConfig:
def get_items(self):
parameters = {}
php_config = RawConfigParser()
sections = []
try:
contents = file(path(MY_CNF))
lines = contents.readlines()
# Workaround for `allow_no_value` (which is available in only Python 2.7+).
body = ''
for line in lines:
stripped_line = line.strip()
if not stripped_line or stripped_line[0] in ('#', ';'):
pass
elif line[0] != '[' and line[-1] != ']' and \
'=' not in line:
line = '%s=\n' % line.rstrip('\n')
body += line
php_config.readfp(cStringIO.StringIO(body))
sections = php_config.sections()
except IOError:
#sys.exit("Notice: Cannot open PHP configuration file '%s'" % MY_CNF)
print "Notice: Cannot open PHP configuration file '%s'" % MY_CNF
except ParsingError, error:
print "Notice: Cannot parse PHP configuration file '%s'\n%s" % (PHP_INI, error)
for section in sections:
items = php_config.items(section)
for item in items:
if item[0] in parameters:
parameters[item[0]] += [item[1]]
else:
parameters[item[0]] = [item[1]]
return parameters
def parse(self):
try:
file_obj = open(path(MY_CNF), 'r')
lines = file_obj.readlines()
file_obj.close()
body = clean_body(lines, '#')
items = self.get_items()
my_dict = {'body': body, 'items': items, 'filename': MY_CNF}
except IOError:
#raise Exception("Notice: Cannot open PHP configuration file '%s'" % MY_CNF)'
print "Notice: Cannot open PHP configuration file '%s'" % MY_CNF
my_dict = {'body': '', 'items': [], 'filename': ''}
return my_dict
class MySQLConfig:
def get_items(self):
parameters = {}
mysql_config = RawConfigParser()
sections = []
try:
contents = file(path(MY_CNF))
lines = contents.readlines()
# Workaround for `allow_no_value` (which is available in only Python 2.7+).
body = ''
for line in lines:
stripped_line = line.strip()
if not stripped_line or stripped_line[0] in ('#', ';'):
pass
elif line[0] != '[' and line[-1] != ']' and \
'=' not in line:
line = '%s=\n' % line.rstrip('\n')
body += line
mysql_config.readfp(cStringIO.StringIO(body))
sections = mysql_config.sections()
except IOError:
#sys.exit("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)
print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF
except ParsingError, error:
print "Notice: Cannot parse PHP configuration file '%s'\n%s" % (PHP_INI, error)
for section in sections:
items = mysql_config.items(section)
for item in items:
if item[0] in parameters:
parameters[item[0]] += [item[1]]
else:
parameters[item[0]] = [item[1]]
return parameters
def parse(self):
try:
file_obj = open(path(MY_CNF), 'r')
lines = file_obj.readlines()
file_obj.close()
body = clean_body(lines, '#')
items = self.get_items()
my_dict = {'body': body, 'items': items, 'filename': MY_CNF}
except IOError:
#raise Exception("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)'
print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF
my_dict = {'body': '', 'items': [], 'filename': ''}
return my_dict
|
cvan/secinv-client
|
6379d353a08e0de189610e6b8f831ff18741ba8b
|
add workaround for allow_no_value for ConfigParser (for python < 2.7)
|
diff --git a/client/inventory.py b/client/inventory.py
index b1aa7f3..7230139 100644
--- a/client/inventory.py
+++ b/client/inventory.py
@@ -1,484 +1,513 @@
-from ConfigParser import ConfigParser
+from ConfigParser import RawConfigParser, ParsingError
+import cStringIO
import os
import re
import subprocess
import string
from apacheparser import *
from common import *
# TODO: Use `logging`.
class Interfaces:
@classmethod
def get_interfaces(cls):
"""
Return dictionary of IP address, MAC address, and netmask for each
interface.
"""
i_dict = {}
open_files = subprocess.Popen(IFCONFIG, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = open_files.split('\n')
interface = ''
for line in lines:
if not line:
continue
ls = line.split()
if ls[0].strip():
interface = ls[0].strip()
i_dict[interface] = {'i_ip': '', 'i_mac': '', 'i_mask': ''}
# Get MAC address.
if 'HWaddr' in ls:
i_dict[interface]['i_mac'] = ls[ls.index('HWaddr') + 1].lower()
# Get IP address and netmask.
if 'inet' in ls:
inet = ls[ls.index('inet') + 1]
if ':' in inet:
i_dict[interface]['i_ip'] = inet.split(':')[1]
else:
i_dict[interface]['i_ip'] = inet
if ':' in ls[-1]:
i_dict[interface]['i_mask'] = ls[-1].split(':')[1]
else:
i_dict[interface]['i_mask'] = ls[-1]
return i_dict
class System:
@classmethod
def _get_ip(self):
"""Get `hostname` and return local IP address from hostname."""
try:
import socket
sys_ip = socket.gethostbyaddr(socket.gethostname())[-1][0]
except (socket.error, socket.herror, socket.gaierror):
sys_ip = ''
return sys_ip
@classmethod
def _get_hostname(self):
"""Parse `hostname` and return local hostname."""
full_hn = subprocess.Popen(HOSTNAME, shell=True,
stdout=subprocess.PIPE).communicate()[0]
p = re.compile(r'([^\.]+)')
m = p.match(full_hn)
return m and m.group(0).strip() or ''
@classmethod
def _get_kernel_release(self):
"""
Call `uname -r` and return kernel release version number.
"""
kernel_rel = subprocess.Popen('%s -r' % UNAME, shell=True,
stdout=subprocess.PIPE).communicate()[0]
return kernel_rel.strip()
@classmethod
def _get_redhat_version(self, filename=RH_RELEASE):
"""
Parse `redhat-release` file and return release name and version number.
"""
rh_version = ''
try:
rh_file = open(filename, 'r')
release_line = rh_file.readline()
rh_file.close()
p = re.compile(r'Red Hat Enterprise Linux \S+ release ([^\n].+)\n')
m = p.match(release_line)
if m:
rh_version = m.group(1)
except IOError:
#raise Exception("Notice: Cannot open redhat-release file '%s'." % filename)
print "Notice: Cannot open redhat-release file '%s'" % filename
rh_version = ''
return rh_version.strip()
@classmethod
def _ip_fwd_status(self, filename=IP_FORWARD):
"""
Parse `ip_forward` file and return a boolean of IP forwarding status.
"""
ip_fwd = 0
try:
ip_file = open(filename, 'r')
status_line = ip_file.readline().strip()
ip_file.close()
if status_line == '1':
ip_fwd = 1
except IOError:
#raise Exception("Notice: Cannot open ip_forward file '%s'." % filename)
print "Notice: Cannot open ip_forward file '%s'" % filename
+ pass
return ip_fwd
@classmethod
def _nfs_status(self):
"""
Check and return an integer of whether a NFS is currently mounted.
"""
found_nfs = 0
mount_info = subprocess.Popen('%s -l' % MOUNT, shell=True,
stdout=subprocess.PIPE).communicate()[0]
mount_info = mount_info.strip('\n')
lines = mount_info.split('\n')
for line in lines:
if not line:
continue
p = re.compile(r'.+ type ([^\s].+) ')
m = p.match(line)
if m and m.group(1) == 'nfs':
found_nfs = 1
break
return found_nfs
@classmethod
def get_system_dict(cls):
"""Build and return dictionary of assets fields."""
i_dict = {'sys_ip': cls._get_ip(),
- 'hostname': cls._get_hostname(),
- 'kernel_rel': cls._get_kernel_release(),
- 'rh_rel': cls._get_redhat_version(),
- 'nfs': cls._nfs_status(),
- 'ip_fwd': cls._ip_fwd_status()}
+ 'hostname': cls._get_hostname(),
+ 'kernel_rel': cls._get_kernel_release(),
+ 'rh_rel': cls._get_redhat_version(),
+ 'nfs': cls._nfs_status(),
+ 'ip_fwd': cls._ip_fwd_status()}
return i_dict
class Services:
@classmethod
def get_services(cls):
"""
Parse `lsof -ni -P` and return a dictionary of all listening processes
and ports.
"""
ports_dict = {}
open_files = subprocess.Popen('%s -ni -P' % LSOF, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = open_files.split('\n')
for line in lines:
if not line:
continue
chunks = re.split('\s*', line)
if not '(LISTEN)' in chunks:
continue
proc_name = chunks[0]
full_name = chunks[-2]
- port = full_name.split(':')[1]
-
- ports_dict.setdefault(proc_name, [])
-
- if proc_name in ports_dict and port not in ports_dict[proc_name]:
- ports_dict[proc_name].append(port)
- for k, v in ports_dict.iteritems():
- ports_dict[k] = ', '.join(v)
+ ports_dict[proc_name] = full_name.split(':')[1]
return ports_dict
class RPMs:
@classmethod
def get_rpms(cls, filename=RPM_PKGS):
"""Get all RPMs installed."""
rpms_dict = {'list': ''}
try:
rpmpkgs_file = open(filename, 'r')
lines = rpmpkgs_file.readlines()
rpmpkgs_file.close()
lines_str = ''.join(lines)
lines_str = lines_str.strip('\n')
rpms_dict = {'list': lines_str}
except IOError:
# TODO: Logging Error.
#raise Exception("Notice: Cannot open rpmpkgs file '%s'." % filename)
print "Notice: Cannot open rpmpkgs file '%s'" % filename
return rpms_dict
class SSHConfig:
@classmethod
def parse(cls, filename=SSH_CONFIG_FILE):
"""
Parse SSH configuration file and a return a dictionary of
body, parameters/values, and filename.
"""
body = ''
items = {}
filename = path(filename)
try:
file_obj = open(filename, 'r')
lines = file_obj.readlines()
file_obj.close()
except IOError:
#raise Exception("Notice: Cannot open SSH config file '%s'." % filename)
print "Notice: Cannot open SSH config file '%s'" % filename
lines = ''
if lines:
body = ''
for index, line in enumerate(lines):
line = line.strip()
if not line or (not PARSE_CONF_COMMENTS and line[0] == '#'):
continue
# Concatenate multiline instructions delimited by backslash-newlines.
if line and line[-1] == '\\':
while line[-1] == '\\':
line = ' '.join([line[:-1].strip(),
lines[index + 1].strip()])
del lines[index + 1]
if line[0] != '#':
ls = re.split('\s*', line)
if ls[0] in items:
items[ls[0]] += [' %s' % ' '.join(ls[1:])]
else:
items[ls[0]] = [' '.join(ls[1:])]
body += '%s\n' % line
ssh_dict = {'body': body, 'items': items, 'filename': filename}
return ssh_dict
class IPTables:
@classmethod
def _status(self):
"""
Check and return an integer of whether iptables are running.
"""
ipt_status = 0
status_info = subprocess.Popen('%s status' % IPTABLES, shell=True,
stdout=subprocess.PIPE).communicate()[0]
status_info = status_info.strip('\n')
if status_info != 'Firewall is stopped.':
ipt_status = 1
return ipt_status
@classmethod
def _parse(self):
"""
Parse IP tables and a return a dictionary of policies for each table.
"""
ipt_dict = {}
lines = subprocess.Popen(IPTABLES_SAVE, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = lines.split('\n')
table_name = ''
body = ''
for index, line in enumerate(lines):
line = line.strip()
if not line or (not PARSE_CONF_COMMENTS and line[0] == '#') or \
(PARSE_CONF_COMMENTS and line.startswith('# Generated by') or \
line.startswith('# Completed on')):
continue
# Concatenate multiline instructions delimited by backslash-newlines.
if line and line[-1] == '\\':
while line[-1] == '\\':
line = ' '.join([line[:-1].strip(),
lines[index + 1].strip()])
del lines[index + 1]
if line[0] == ':':
# Chain specification.
# :<chain-name> <chain-policy> [<packet-counter>:<byte-counter>]
# Strip packet-counter and byte-counter.
ls = line.split()
if len(ls) > 2 and ls[0].strip():
chain_name = ls[0].strip()[1:]
chain_policy = ls[1].strip()
line = ':%s %s' % (chain_name, chain_policy)
body += '%s\n' % line
ipt_dict['body'] = body
return ipt_dict
@classmethod
def get_ipt_dict(cls):
"""Build and return dictionary of iptables fields."""
ipt_dict = {'status': cls._status(),
'rules': cls._parse()}
return ipt_dict
class ApacheConfigList:
def __init__(self):
self.apache_configs = []
def recurse_apache_includes(self, fn, includes_list):
for i_fn in includes_list:
i_ac = ApacheConfig()
i_ac.parse(i_fn)
i_apache = {'body': i_ac.get_body(),
'filename': i_fn,
'directives': i_ac.get_directives(),
'domains': i_ac.get_domains(),
'included': i_ac.get_includes()}
# Remove circular includes.
try:
del i_apache['included'][i_apache['included'].index(fn)]
except ValueError:
pass
self.apache_configs.append(i_apache)
self.recurse_apache_includes(i_fn, i_apache['included'])
def recurse(self):
ac = ApacheConfig()
ac.parse(APACHE_CONF)
apache = {'body': ac.get_body(),
'filename': APACHE_CONF,
'directives': ac.get_directives(),
'domains': ac.get_domains(),
'included': ac.get_includes()}
# Remove circular includes.
try:
del apache['included'][apache['included'].index(APACHE_CONF)]
except ValueError:
pass
self.apache_configs.append(apache)
self.recurse_apache_includes(APACHE_CONF, apache['included'])
def get_apache_configs(self):
if os.path.exists(APACHE_CONF):
self.recurse()
return self.apache_configs
class PHPConfig:
def get_items(self):
parameters = {}
- php_config = ConfigParser()
+ php_config = RawConfigParser()
+
+ sections = []
try:
- php_config.readfp(file(path(PHP_INI)))
+ contents = file(path(MY_CNF))
+ lines = contents.readlines()
+
+ # Workaround for `allow_no_value` (which is available in only Python 2.7+).
+ body = ''
+ for line in lines:
+ stripped_line = line.strip()
+ if not stripped_line or stripped_line[0] in ('#', ';'):
+ pass
+
+ elif line[0] != '[' and line[-1] != ']' and \
+ '=' not in line:
+ line = '%s=\n' % line.rstrip('\n')
+
+ body += line
+
+ php_config.readfp(cStringIO.StringIO(body))
+
sections = php_config.sections()
except IOError:
- #sys.exit("Notice: Cannot open PHP configuration file '%s'" % PHP_INI)
- print "Notice: Cannot open PHP configuration file '%s'" % PHP_INI
- sections = []
+ #sys.exit("Notice: Cannot open PHP configuration file '%s'" % MY_CNF)
+ print "Notice: Cannot open PHP configuration file '%s'" % MY_CNF
+ except ParsingError, error:
+ print "Notice: Cannot parse PHP configuration file '%s'\n%s" % (PHP_INI, error)
for section in sections:
items = php_config.items(section)
- #parameters[section] = {}
for item in items:
- #parameters[section][item[0]] = [item[1]]
if item[0] in parameters:
parameters[item[0]] += [item[1]]
else:
parameters[item[0]] = [item[1]]
- #parameters.setdefault(item[0], []).append(item[1])
return parameters
def parse(self):
try:
- file_obj = open(path(PHP_INI), 'r')
+ file_obj = open(path(MY_CNF), 'r')
lines = file_obj.readlines()
file_obj.close()
-
- body = clean_body(lines, ';')
+
+ body = clean_body(lines, '#')
items = self.get_items()
- php_dict = {'body': body, 'items': items, 'filename': PHP_INI}
+ my_dict = {'body': body, 'items': items, 'filename': MY_CNF}
except IOError:
- #raise Exception("Notice: Cannot open PHP configuration file '%s'" % PHP_INI)'
- print "Notice: Cannot open PHP configuration file '%s'" % PHP_INI
- php_dict = {'body': '', 'items': [], 'filename': ''}
+ #raise Exception("Notice: Cannot open PHP configuration file '%s'" % MY_CNF)'
+ print "Notice: Cannot open PHP configuration file '%s'" % MY_CNF
+ my_dict = {'body': '', 'items': [], 'filename': ''}
- return php_dict
+ return my_dict
class MySQLConfig:
def get_items(self):
parameters = {}
- mysql_config = ConfigParser()
+ mysql_config = RawConfigParser()
+
+ sections = []
try:
- mysql_config.readfp(file(path(MY_CNF)))
+ contents = file(path(MY_CNF))
+ lines = contents.readlines()
+
+ # Workaround for `allow_no_value` (which is available in only Python 2.7+).
+ body = ''
+ for line in lines:
+ stripped_line = line.strip()
+ if not stripped_line or stripped_line[0] in ('#', ';'):
+ pass
+
+ elif line[0] != '[' and line[-1] != ']' and \
+ '=' not in line:
+ line = '%s=\n' % line.rstrip('\n')
+
+ body += line
+
+ mysql_config.readfp(cStringIO.StringIO(body))
+
sections = mysql_config.sections()
except IOError:
#sys.exit("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)
print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF
- sections = []
+ except ParsingError, error:
+ print "Notice: Cannot parse PHP configuration file '%s'\n%s" % (PHP_INI, error)
for section in sections:
items = mysql_config.items(section)
- #parameters[section] = {}
for item in items:
- #parameters[section][item[0]] = [item[1]]
if item[0] in parameters:
parameters[item[0]] += [item[1]]
else:
parameters[item[0]] = [item[1]]
- #parameters.setdefault(item[0], []).append(item[1])
return parameters
def parse(self):
try:
file_obj = open(path(MY_CNF), 'r')
lines = file_obj.readlines()
file_obj.close()
body = clean_body(lines, '#')
items = self.get_items()
my_dict = {'body': body, 'items': items, 'filename': MY_CNF}
except IOError:
#raise Exception("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)'
print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF
my_dict = {'body': '', 'items': [], 'filename': ''}
return my_dict
|
cvan/secinv-client
|
a75a58c680b2a968281f71672e2861ee7d04e70c
|
add list of ports for services, ws alignment
|
diff --git a/client/inventory.py b/client/inventory.py
index fe2d1d6..b1aa7f3 100644
--- a/client/inventory.py
+++ b/client/inventory.py
@@ -1,477 +1,484 @@
from ConfigParser import ConfigParser
import os
import re
import subprocess
import string
from apacheparser import *
from common import *
# TODO: Use `logging`.
class Interfaces:
@classmethod
def get_interfaces(cls):
"""
Return dictionary of IP address, MAC address, and netmask for each
interface.
"""
i_dict = {}
open_files = subprocess.Popen(IFCONFIG, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = open_files.split('\n')
interface = ''
for line in lines:
if not line:
continue
ls = line.split()
if ls[0].strip():
interface = ls[0].strip()
i_dict[interface] = {'i_ip': '', 'i_mac': '', 'i_mask': ''}
# Get MAC address.
if 'HWaddr' in ls:
i_dict[interface]['i_mac'] = ls[ls.index('HWaddr') + 1].lower()
# Get IP address and netmask.
if 'inet' in ls:
inet = ls[ls.index('inet') + 1]
if ':' in inet:
i_dict[interface]['i_ip'] = inet.split(':')[1]
else:
i_dict[interface]['i_ip'] = inet
if ':' in ls[-1]:
i_dict[interface]['i_mask'] = ls[-1].split(':')[1]
else:
i_dict[interface]['i_mask'] = ls[-1]
return i_dict
class System:
@classmethod
def _get_ip(self):
"""Get `hostname` and return local IP address from hostname."""
try:
import socket
sys_ip = socket.gethostbyaddr(socket.gethostname())[-1][0]
except (socket.error, socket.herror, socket.gaierror):
sys_ip = ''
return sys_ip
@classmethod
def _get_hostname(self):
"""Parse `hostname` and return local hostname."""
full_hn = subprocess.Popen(HOSTNAME, shell=True,
stdout=subprocess.PIPE).communicate()[0]
p = re.compile(r'([^\.]+)')
m = p.match(full_hn)
return m and m.group(0).strip() or ''
@classmethod
def _get_kernel_release(self):
"""
Call `uname -r` and return kernel release version number.
"""
kernel_rel = subprocess.Popen('%s -r' % UNAME, shell=True,
stdout=subprocess.PIPE).communicate()[0]
return kernel_rel.strip()
@classmethod
def _get_redhat_version(self, filename=RH_RELEASE):
"""
Parse `redhat-release` file and return release name and version number.
"""
rh_version = ''
try:
rh_file = open(filename, 'r')
release_line = rh_file.readline()
rh_file.close()
p = re.compile(r'Red Hat Enterprise Linux \S+ release ([^\n].+)\n')
m = p.match(release_line)
if m:
rh_version = m.group(1)
except IOError:
#raise Exception("Notice: Cannot open redhat-release file '%s'." % filename)
print "Notice: Cannot open redhat-release file '%s'" % filename
rh_version = ''
return rh_version.strip()
@classmethod
def _ip_fwd_status(self, filename=IP_FORWARD):
"""
Parse `ip_forward` file and return a boolean of IP forwarding status.
"""
ip_fwd = 0
try:
ip_file = open(filename, 'r')
status_line = ip_file.readline().strip()
ip_file.close()
if status_line == '1':
ip_fwd = 1
except IOError:
#raise Exception("Notice: Cannot open ip_forward file '%s'." % filename)
print "Notice: Cannot open ip_forward file '%s'" % filename
return ip_fwd
@classmethod
def _nfs_status(self):
"""
Check and return an integer of whether a NFS is currently mounted.
"""
found_nfs = 0
mount_info = subprocess.Popen('%s -l' % MOUNT, shell=True,
stdout=subprocess.PIPE).communicate()[0]
mount_info = mount_info.strip('\n')
lines = mount_info.split('\n')
for line in lines:
if not line:
continue
p = re.compile(r'.+ type ([^\s].+) ')
m = p.match(line)
if m and m.group(1) == 'nfs':
found_nfs = 1
break
return found_nfs
@classmethod
def get_system_dict(cls):
"""Build and return dictionary of assets fields."""
i_dict = {'sys_ip': cls._get_ip(),
- 'hostname': cls._get_hostname(),
- 'kernel_rel': cls._get_kernel_release(),
- 'rh_rel': cls._get_redhat_version(),
- 'nfs': cls._nfs_status(),
- 'ip_fwd': cls._ip_fwd_status()}
+ 'hostname': cls._get_hostname(),
+ 'kernel_rel': cls._get_kernel_release(),
+ 'rh_rel': cls._get_redhat_version(),
+ 'nfs': cls._nfs_status(),
+ 'ip_fwd': cls._ip_fwd_status()}
return i_dict
class Services:
@classmethod
def get_services(cls):
"""
Parse `lsof -ni -P` and return a dictionary of all listening processes
and ports.
"""
ports_dict = {}
open_files = subprocess.Popen('%s -ni -P' % LSOF, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = open_files.split('\n')
for line in lines:
if not line:
continue
chunks = re.split('\s*', line)
if not '(LISTEN)' in chunks:
continue
proc_name = chunks[0]
full_name = chunks[-2]
+ port = full_name.split(':')[1]
- ports_dict[proc_name] = full_name.split(':')[1]
+ ports_dict.setdefault(proc_name, [])
+
+ if proc_name in ports_dict and port not in ports_dict[proc_name]:
+ ports_dict[proc_name].append(port)
+
+ for k, v in ports_dict.iteritems():
+ ports_dict[k] = ', '.join(v)
return ports_dict
class RPMs:
@classmethod
def get_rpms(cls, filename=RPM_PKGS):
"""Get all RPMs installed."""
rpms_dict = {'list': ''}
try:
rpmpkgs_file = open(filename, 'r')
lines = rpmpkgs_file.readlines()
rpmpkgs_file.close()
lines_str = ''.join(lines)
lines_str = lines_str.strip('\n')
rpms_dict = {'list': lines_str}
except IOError:
# TODO: Logging Error.
#raise Exception("Notice: Cannot open rpmpkgs file '%s'." % filename)
print "Notice: Cannot open rpmpkgs file '%s'" % filename
return rpms_dict
class SSHConfig:
@classmethod
def parse(cls, filename=SSH_CONFIG_FILE):
"""
Parse SSH configuration file and a return a dictionary of
body, parameters/values, and filename.
"""
body = ''
items = {}
filename = path(filename)
try:
file_obj = open(filename, 'r')
lines = file_obj.readlines()
file_obj.close()
except IOError:
#raise Exception("Notice: Cannot open SSH config file '%s'." % filename)
print "Notice: Cannot open SSH config file '%s'" % filename
lines = ''
if lines:
body = ''
for index, line in enumerate(lines):
line = line.strip()
if not line or (not PARSE_CONF_COMMENTS and line[0] == '#'):
continue
# Concatenate multiline instructions delimited by backslash-newlines.
if line and line[-1] == '\\':
while line[-1] == '\\':
line = ' '.join([line[:-1].strip(),
lines[index + 1].strip()])
del lines[index + 1]
if line[0] != '#':
ls = re.split('\s*', line)
if ls[0] in items:
items[ls[0]] += [' %s' % ' '.join(ls[1:])]
else:
items[ls[0]] = [' '.join(ls[1:])]
body += '%s\n' % line
ssh_dict = {'body': body, 'items': items, 'filename': filename}
return ssh_dict
class IPTables:
@classmethod
def _status(self):
"""
Check and return an integer of whether iptables are running.
"""
ipt_status = 0
status_info = subprocess.Popen('%s status' % IPTABLES, shell=True,
stdout=subprocess.PIPE).communicate()[0]
status_info = status_info.strip('\n')
if status_info != 'Firewall is stopped.':
ipt_status = 1
return ipt_status
@classmethod
def _parse(self):
"""
Parse IP tables and a return a dictionary of policies for each table.
"""
ipt_dict = {}
lines = subprocess.Popen(IPTABLES_SAVE, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = lines.split('\n')
table_name = ''
body = ''
for index, line in enumerate(lines):
line = line.strip()
if not line or (not PARSE_CONF_COMMENTS and line[0] == '#') or \
(PARSE_CONF_COMMENTS and line.startswith('# Generated by') or \
line.startswith('# Completed on')):
continue
# Concatenate multiline instructions delimited by backslash-newlines.
if line and line[-1] == '\\':
while line[-1] == '\\':
line = ' '.join([line[:-1].strip(),
lines[index + 1].strip()])
del lines[index + 1]
if line[0] == ':':
# Chain specification.
# :<chain-name> <chain-policy> [<packet-counter>:<byte-counter>]
# Strip packet-counter and byte-counter.
ls = line.split()
if len(ls) > 2 and ls[0].strip():
chain_name = ls[0].strip()[1:]
chain_policy = ls[1].strip()
line = ':%s %s' % (chain_name, chain_policy)
body += '%s\n' % line
ipt_dict['body'] = body
return ipt_dict
@classmethod
def get_ipt_dict(cls):
"""Build and return dictionary of iptables fields."""
ipt_dict = {'status': cls._status(),
'rules': cls._parse()}
return ipt_dict
class ApacheConfigList:
def __init__(self):
self.apache_configs = []
def recurse_apache_includes(self, fn, includes_list):
for i_fn in includes_list:
i_ac = ApacheConfig()
i_ac.parse(i_fn)
i_apache = {'body': i_ac.get_body(),
'filename': i_fn,
'directives': i_ac.get_directives(),
'domains': i_ac.get_domains(),
'included': i_ac.get_includes()}
# Remove circular includes.
try:
del i_apache['included'][i_apache['included'].index(fn)]
except ValueError:
pass
self.apache_configs.append(i_apache)
self.recurse_apache_includes(i_fn, i_apache['included'])
def recurse(self):
ac = ApacheConfig()
ac.parse(APACHE_CONF)
apache = {'body': ac.get_body(),
'filename': APACHE_CONF,
'directives': ac.get_directives(),
'domains': ac.get_domains(),
'included': ac.get_includes()}
# Remove circular includes.
try:
del apache['included'][apache['included'].index(APACHE_CONF)]
except ValueError:
pass
self.apache_configs.append(apache)
self.recurse_apache_includes(APACHE_CONF, apache['included'])
def get_apache_configs(self):
if os.path.exists(APACHE_CONF):
self.recurse()
return self.apache_configs
class PHPConfig:
def get_items(self):
parameters = {}
php_config = ConfigParser()
try:
php_config.readfp(file(path(PHP_INI)))
sections = php_config.sections()
except IOError:
#sys.exit("Notice: Cannot open PHP configuration file '%s'" % PHP_INI)
print "Notice: Cannot open PHP configuration file '%s'" % PHP_INI
sections = []
for section in sections:
items = php_config.items(section)
#parameters[section] = {}
for item in items:
#parameters[section][item[0]] = [item[1]]
if item[0] in parameters:
parameters[item[0]] += [item[1]]
else:
parameters[item[0]] = [item[1]]
#parameters.setdefault(item[0], []).append(item[1])
return parameters
def parse(self):
try:
file_obj = open(path(PHP_INI), 'r')
lines = file_obj.readlines()
file_obj.close()
body = clean_body(lines, ';')
items = self.get_items()
php_dict = {'body': body, 'items': items, 'filename': PHP_INI}
except IOError:
#raise Exception("Notice: Cannot open PHP configuration file '%s'" % PHP_INI)'
print "Notice: Cannot open PHP configuration file '%s'" % PHP_INI
php_dict = {'body': '', 'items': [], 'filename': ''}
return php_dict
class MySQLConfig:
def get_items(self):
parameters = {}
mysql_config = ConfigParser()
try:
mysql_config.readfp(file(path(MY_CNF)))
sections = mysql_config.sections()
except IOError:
#sys.exit("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)
print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF
sections = []
for section in sections:
items = mysql_config.items(section)
#parameters[section] = {}
for item in items:
#parameters[section][item[0]] = [item[1]]
if item[0] in parameters:
parameters[item[0]] += [item[1]]
else:
parameters[item[0]] = [item[1]]
#parameters.setdefault(item[0], []).append(item[1])
return parameters
def parse(self):
try:
file_obj = open(path(MY_CNF), 'r')
lines = file_obj.readlines()
file_obj.close()
body = clean_body(lines, '#')
items = self.get_items()
my_dict = {'body': body, 'items': items, 'filename': MY_CNF}
except IOError:
#raise Exception("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)'
print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF
my_dict = {'body': '', 'items': [], 'filename': ''}
return my_dict
|
cvan/secinv-client
|
94795a8a17786578251c03dccf43a6ad499c7e02
|
check for colons in netmask and ip, clear ignore_directives
|
diff --git a/client/common.py b/client/common.py
index 50a8a4c..3cdcc72 100644
--- a/client/common.py
+++ b/client/common.py
@@ -1,103 +1,103 @@
from ConfigParser import ConfigParser
import os
import re
import sys
ROOT = os.path.dirname(os.path.abspath(__file__))
# Used to translate path in this directory to an absolute path.
path = lambda *a: os.path.join(ROOT, *a)
# Supress warnings.
import warnings
warnings.filterwarnings('ignore')
# Path to client configuration file.
AUTH_CONFIG_FN = path('auth.conf')
CLIENT_CONFIG_FN = path('settings.conf')
client_config = auth_config = ConfigParser()
try:
client_config.readfp(file(CLIENT_CONFIG_FN))
except IOError:
sys.exit("Error: Cannot open inventory configuration file '%s'"
% CLIENT_CONFIG_FN)
try:
auth_config.readfp(file(AUTH_CONFIG_FN))
except IOError:
sys.exit("Error: Cannot open inventory authorization token file '%s'"
% AUTH_CONFIG_FN)
## Server.
HOST = client_config.get('server', 'host')
PORT = client_config.get('server', 'port')
AUTH_TOKEN = auth_config.get('auth_token', 'auth_token')
DEBUG = client_config.get('server', 'debug').lower() == 'true' and True or False
## Paths.
RH_RELEASE = os.path.abspath(client_config.get('paths', 'rh_release'))
IP_FORWARD = os.path.abspath(client_config.get('paths', 'ip_forward'))
RPM_PKGS = os.path.abspath(client_config.get('paths', 'rpm_pkgs'))
SSH_CONFIG_FILE = os.path.abspath(client_config.get('paths', 'ssh_config_file'))
IPTABLES = client_config.get('paths', 'iptables')
PHP_INI = client_config.get('paths', 'php_ini')
MY_CNF = client_config.get('paths', 'my_cnf')
IFCONFIG = client_config.get('paths', 'ifconfig')
HOSTNAME = client_config.get('paths', 'hostname')
UNAME = client_config.get('paths', 'uname')
MOUNT = client_config.get('paths', 'mount')
LSOF = client_config.get('paths', 'lsof')
IPTABLES = client_config.get('paths', 'iptables')
IPTABLES_SAVE = client_config.get('paths', 'iptables_save')
## Apache.
APACHE_ROOT = os.path.abspath(client_config.get('apache', 'server_root'))
APACHE_CONF = os.path.abspath(client_config.get('apache', 'conf_file'))
APACHE_IGNORE_DIRECTIVES = [f.strip() for f in \
re.split(',', client_config.get('apache', 'ignore_directives'))]
## Miscellaneous.
PARSE_CONF_COMMENTS = client_config.get('miscellaneous',
'parse_conf_comments').lower() == 'true' and True or False
-def clean_body(body, comments_prefix=('#')):
+def clean_body(body, comments_prefix='#'):
"""
Clean up whitespace, multiline instructions, and comments (if applicable).
"""
if not type(comments_prefix) in (tuple, list, str):
raise TypeError
if type(body) is list:
lines = body
else:
lines = re.split('\n', body)
-
+
body = ''
for index, line in enumerate(lines):
line = line.strip()
if not line or (not PARSE_CONF_COMMENTS and line[0] in comments_prefix):
continue
# Concatenate multiline instructions delimited by backslash-newlines.
if line and line[-1] == '\\':
while line[-1] == '\\':
line = ' '.join([line[:-1].strip(),
lines[index + 1].strip()])
del lines[index + 1]
body += '%s\n' % line
return body
diff --git a/client/inventory.py b/client/inventory.py
index cbf3e9a..fe2d1d6 100644
--- a/client/inventory.py
+++ b/client/inventory.py
@@ -1,470 +1,477 @@
from ConfigParser import ConfigParser
import os
import re
import subprocess
import string
from apacheparser import *
from common import *
# TODO: Use `logging`.
class Interfaces:
@classmethod
def get_interfaces(cls):
"""
Return dictionary of IP address, MAC address, and netmask for each
interface.
"""
i_dict = {}
open_files = subprocess.Popen(IFCONFIG, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = open_files.split('\n')
+ interface = ''
for line in lines:
if not line:
continue
ls = line.split()
if ls[0].strip():
interface = ls[0].strip()
i_dict[interface] = {'i_ip': '', 'i_mac': '', 'i_mask': ''}
# Get MAC address.
if 'HWaddr' in ls:
i_dict[interface]['i_mac'] = ls[ls.index('HWaddr') + 1].lower()
# Get IP address and netmask.
if 'inet' in ls:
inet = ls[ls.index('inet') + 1]
- i_dict[interface]['i_ip'] = inet.split(':')[1]
- i_dict[interface]['i_mask'] = ls[-1].split(':')[1]
+ if ':' in inet:
+ i_dict[interface]['i_ip'] = inet.split(':')[1]
+ else:
+ i_dict[interface]['i_ip'] = inet
+
+ if ':' in ls[-1]:
+ i_dict[interface]['i_mask'] = ls[-1].split(':')[1]
+ else:
+ i_dict[interface]['i_mask'] = ls[-1]
return i_dict
class System:
@classmethod
def _get_ip(self):
"""Get `hostname` and return local IP address from hostname."""
try:
import socket
sys_ip = socket.gethostbyaddr(socket.gethostname())[-1][0]
except (socket.error, socket.herror, socket.gaierror):
sys_ip = ''
return sys_ip
@classmethod
def _get_hostname(self):
"""Parse `hostname` and return local hostname."""
full_hn = subprocess.Popen(HOSTNAME, shell=True,
stdout=subprocess.PIPE).communicate()[0]
p = re.compile(r'([^\.]+)')
m = p.match(full_hn)
return m and m.group(0).strip() or ''
@classmethod
def _get_kernel_release(self):
"""
Call `uname -r` and return kernel release version number.
"""
kernel_rel = subprocess.Popen('%s -r' % UNAME, shell=True,
stdout=subprocess.PIPE).communicate()[0]
return kernel_rel.strip()
@classmethod
def _get_redhat_version(self, filename=RH_RELEASE):
"""
Parse `redhat-release` file and return release name and version number.
"""
rh_version = ''
try:
rh_file = open(filename, 'r')
release_line = rh_file.readline()
rh_file.close()
p = re.compile(r'Red Hat Enterprise Linux \S+ release ([^\n].+)\n')
m = p.match(release_line)
if m:
rh_version = m.group(1)
except IOError:
#raise Exception("Notice: Cannot open redhat-release file '%s'." % filename)
print "Notice: Cannot open redhat-release file '%s'" % filename
rh_version = ''
return rh_version.strip()
@classmethod
def _ip_fwd_status(self, filename=IP_FORWARD):
"""
Parse `ip_forward` file and return a boolean of IP forwarding status.
"""
ip_fwd = 0
try:
ip_file = open(filename, 'r')
status_line = ip_file.readline().strip()
ip_file.close()
if status_line == '1':
ip_fwd = 1
except IOError:
#raise Exception("Notice: Cannot open ip_forward file '%s'." % filename)
print "Notice: Cannot open ip_forward file '%s'" % filename
- pass
return ip_fwd
@classmethod
def _nfs_status(self):
"""
Check and return an integer of whether a NFS is currently mounted.
"""
found_nfs = 0
mount_info = subprocess.Popen('%s -l' % MOUNT, shell=True,
stdout=subprocess.PIPE).communicate()[0]
mount_info = mount_info.strip('\n')
lines = mount_info.split('\n')
for line in lines:
if not line:
continue
p = re.compile(r'.+ type ([^\s].+) ')
m = p.match(line)
if m and m.group(1) == 'nfs':
found_nfs = 1
break
return found_nfs
@classmethod
def get_system_dict(cls):
"""Build and return dictionary of assets fields."""
i_dict = {'sys_ip': cls._get_ip(),
'hostname': cls._get_hostname(),
'kernel_rel': cls._get_kernel_release(),
'rh_rel': cls._get_redhat_version(),
'nfs': cls._nfs_status(),
'ip_fwd': cls._ip_fwd_status()}
return i_dict
class Services:
@classmethod
def get_services(cls):
"""
Parse `lsof -ni -P` and return a dictionary of all listening processes
and ports.
"""
ports_dict = {}
open_files = subprocess.Popen('%s -ni -P' % LSOF, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = open_files.split('\n')
for line in lines:
if not line:
continue
chunks = re.split('\s*', line)
if not '(LISTEN)' in chunks:
continue
proc_name = chunks[0]
full_name = chunks[-2]
ports_dict[proc_name] = full_name.split(':')[1]
return ports_dict
class RPMs:
@classmethod
def get_rpms(cls, filename=RPM_PKGS):
"""Get all RPMs installed."""
rpms_dict = {'list': ''}
try:
rpmpkgs_file = open(filename, 'r')
lines = rpmpkgs_file.readlines()
rpmpkgs_file.close()
lines_str = ''.join(lines)
lines_str = lines_str.strip('\n')
rpms_dict = {'list': lines_str}
except IOError:
# TODO: Logging Error.
#raise Exception("Notice: Cannot open rpmpkgs file '%s'." % filename)
print "Notice: Cannot open rpmpkgs file '%s'" % filename
return rpms_dict
class SSHConfig:
@classmethod
def parse(cls, filename=SSH_CONFIG_FILE):
"""
Parse SSH configuration file and a return a dictionary of
body, parameters/values, and filename.
"""
body = ''
items = {}
filename = path(filename)
try:
file_obj = open(filename, 'r')
lines = file_obj.readlines()
file_obj.close()
except IOError:
#raise Exception("Notice: Cannot open SSH config file '%s'." % filename)
print "Notice: Cannot open SSH config file '%s'" % filename
lines = ''
if lines:
body = ''
for index, line in enumerate(lines):
line = line.strip()
if not line or (not PARSE_CONF_COMMENTS and line[0] == '#'):
continue
# Concatenate multiline instructions delimited by backslash-newlines.
if line and line[-1] == '\\':
while line[-1] == '\\':
line = ' '.join([line[:-1].strip(),
lines[index + 1].strip()])
del lines[index + 1]
if line[0] != '#':
ls = re.split('\s*', line)
if ls[0] in items:
items[ls[0]] += [' %s' % ' '.join(ls[1:])]
else:
items[ls[0]] = [' '.join(ls[1:])]
body += '%s\n' % line
ssh_dict = {'body': body, 'items': items, 'filename': filename}
return ssh_dict
class IPTables:
@classmethod
def _status(self):
"""
Check and return an integer of whether iptables are running.
"""
ipt_status = 0
status_info = subprocess.Popen('%s status' % IPTABLES, shell=True,
stdout=subprocess.PIPE).communicate()[0]
status_info = status_info.strip('\n')
if status_info != 'Firewall is stopped.':
ipt_status = 1
return ipt_status
@classmethod
def _parse(self):
"""
Parse IP tables and a return a dictionary of policies for each table.
"""
ipt_dict = {}
lines = subprocess.Popen(IPTABLES_SAVE, shell=True,
stdout=subprocess.PIPE).communicate()[0]
lines = lines.split('\n')
table_name = ''
body = ''
for index, line in enumerate(lines):
line = line.strip()
if not line or (not PARSE_CONF_COMMENTS and line[0] == '#') or \
(PARSE_CONF_COMMENTS and line.startswith('# Generated by') or \
line.startswith('# Completed on')):
continue
# Concatenate multiline instructions delimited by backslash-newlines.
if line and line[-1] == '\\':
while line[-1] == '\\':
line = ' '.join([line[:-1].strip(),
lines[index + 1].strip()])
del lines[index + 1]
if line[0] == ':':
# Chain specification.
# :<chain-name> <chain-policy> [<packet-counter>:<byte-counter>]
# Strip packet-counter and byte-counter.
ls = line.split()
if len(ls) > 2 and ls[0].strip():
chain_name = ls[0].strip()[1:]
chain_policy = ls[1].strip()
line = ':%s %s' % (chain_name, chain_policy)
body += '%s\n' % line
ipt_dict['body'] = body
return ipt_dict
@classmethod
def get_ipt_dict(cls):
"""Build and return dictionary of iptables fields."""
ipt_dict = {'status': cls._status(),
'rules': cls._parse()}
return ipt_dict
class ApacheConfigList:
def __init__(self):
self.apache_configs = []
def recurse_apache_includes(self, fn, includes_list):
for i_fn in includes_list:
i_ac = ApacheConfig()
i_ac.parse(i_fn)
i_apache = {'body': i_ac.get_body(),
'filename': i_fn,
'directives': i_ac.get_directives(),
'domains': i_ac.get_domains(),
'included': i_ac.get_includes()}
# Remove circular includes.
try:
del i_apache['included'][i_apache['included'].index(fn)]
except ValueError:
pass
self.apache_configs.append(i_apache)
self.recurse_apache_includes(i_fn, i_apache['included'])
def recurse(self):
ac = ApacheConfig()
ac.parse(APACHE_CONF)
apache = {'body': ac.get_body(),
'filename': APACHE_CONF,
'directives': ac.get_directives(),
'domains': ac.get_domains(),
'included': ac.get_includes()}
# Remove circular includes.
try:
del apache['included'][apache['included'].index(APACHE_CONF)]
except ValueError:
pass
self.apache_configs.append(apache)
self.recurse_apache_includes(APACHE_CONF, apache['included'])
def get_apache_configs(self):
if os.path.exists(APACHE_CONF):
self.recurse()
return self.apache_configs
class PHPConfig:
def get_items(self):
parameters = {}
php_config = ConfigParser()
try:
php_config.readfp(file(path(PHP_INI)))
sections = php_config.sections()
except IOError:
#sys.exit("Notice: Cannot open PHP configuration file '%s'" % PHP_INI)
print "Notice: Cannot open PHP configuration file '%s'" % PHP_INI
sections = []
for section in sections:
items = php_config.items(section)
#parameters[section] = {}
for item in items:
#parameters[section][item[0]] = [item[1]]
if item[0] in parameters:
parameters[item[0]] += [item[1]]
else:
parameters[item[0]] = [item[1]]
#parameters.setdefault(item[0], []).append(item[1])
return parameters
def parse(self):
try:
file_obj = open(path(PHP_INI), 'r')
lines = file_obj.readlines()
file_obj.close()
body = clean_body(lines, ';')
items = self.get_items()
php_dict = {'body': body, 'items': items, 'filename': PHP_INI}
except IOError:
#raise Exception("Notice: Cannot open PHP configuration file '%s'" % PHP_INI)'
print "Notice: Cannot open PHP configuration file '%s'" % PHP_INI
php_dict = {'body': '', 'items': [], 'filename': ''}
return php_dict
class MySQLConfig:
def get_items(self):
parameters = {}
mysql_config = ConfigParser()
try:
mysql_config.readfp(file(path(MY_CNF)))
sections = mysql_config.sections()
except IOError:
#sys.exit("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)
print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF
sections = []
for section in sections:
items = mysql_config.items(section)
#parameters[section] = {}
for item in items:
#parameters[section][item[0]] = [item[1]]
if item[0] in parameters:
parameters[item[0]] += [item[1]]
else:
parameters[item[0]] = [item[1]]
#parameters.setdefault(item[0], []).append(item[1])
return parameters
def parse(self):
try:
file_obj = open(path(MY_CNF), 'r')
lines = file_obj.readlines()
file_obj.close()
body = clean_body(lines, '#')
items = self.get_items()
my_dict = {'body': body, 'items': items, 'filename': MY_CNF}
except IOError:
#raise Exception("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)'
print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF
my_dict = {'body': '', 'items': [], 'filename': ''}
return my_dict
diff --git a/client/settings.conf b/client/settings.conf
index 02e4c65..d788c43 100644
--- a/client/settings.conf
+++ b/client/settings.conf
@@ -1,33 +1,33 @@
[server]
-host=https://cm-sectest01
+host=https://localhost
port=8668
debug=false
[paths]
rh_release=/etc/redhat-release
ip_forward=/proc/sys/net/ipv4/ip_forward
rpm_pkgs=/var/log/rpmpkgs
ssh_config_file=/etc/ssh/sshd_config
iptables=/etc/init.d/iptables
php_ini=/etc/php.ini
my_cnf=/etc/my.cnf
ifconfig=/sbin/ifconfig
hostname=/bin/hostname
uname=/bin/uname
mount=/bin/mount
lsof=/usr/sbin/lsof
iptables=/etc/init.d/iptables
iptables_save=/sbin/iptables-save
[apache]
server_root=/etc/httpd/
conf_file=%(server_root)s/conf/httpd.conf
-ignore_directives=AddLanguage, LanguagePriority
+ignore_directives=
[miscellaneous]
parse_conf_comments=true
|
cvan/secinv-client
|
00670a1f29ac7989355659d719c74065a0e75559
|
add auth config
|
diff --git a/client/auth.conf b/client/auth.conf
new file mode 100644
index 0000000..95a3a46
--- /dev/null
+++ b/client/auth.conf
@@ -0,0 +1,2 @@
+[auth_token]
+auth_token=Jz_Cl1d0kF);}SwE
|
cvan/secinv-client
|
9b2fbf102a4189171d9bf1543b729e36c5df14df
|
add markdown readme
|
diff --git a/README b/README
deleted file mode 100644
index 48a71ee..0000000
--- a/README
+++ /dev/null
@@ -1 +0,0 @@
-README.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..f63ad1b
--- /dev/null
+++ b/README.md
@@ -0,0 +1,18 @@
+LittleSIS Client
+================
+LittleSIS scans the system for OS info, network interfaces, iptables rules,
+and configuration files (Apache, PHP, MySQL, OpenSSH sshd). This is the client
+agent used in cooperation with the XML-RPC-based LittleSIS server.
+
+# Requirements
+
+* Python 2.4 (or greater)
+
+# Instructions
+
+1. Edit `client/settings.conf` to update the server location, port, and
+ miscellaneous settings as you see fit (e.g., system file paths).
+
+2. Edit `client/auth.conf` with the machine's authorization token to compare
+ against the token stored on the server.
+
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.