Libgit2/Error.pm untested

filter: Statementstmt 0.0% 0 / 42 Branchbran 0.0% 0 / 8 Conditioncond 0.0% 0 / 9 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 81 CC 5 SCAR 24.3
CC
5
Cov
0%
_decode
30.0
last
2.0
code
2.0
CRAP 11.3
1 # ABSTRACT: Wraps git_error_last() into a Perl structure
2  
3 package Git::Libgit2::Error;
4 our $VERSION = '0.008';
5 use strict;
6 use warnings;
7 use FFI::Platypus 2.00;
8 use Git::Libgit2::FFI ();
9  
10 # struct git_error { char *message; int klass; }
11 # We read the two fields by hand using cast() — keeps us free of
12 # FFI::Platypus::Record's compile-time layout requirements.
13 my $_decode_ffi;
14 sub _decode {
15 my ($err_ptr) = @_;
16 return ( '<no error>', 0 ) unless $err_ptr;
17 $_decode_ffi ||= do {
18 my $f = FFI::Platypus->new( api => 2 );
19 $f->attach_cast( '_msg_ptr', 'opaque', 'opaque' ); # *(void**)p
20 $f->attach_cast( '_msg_to_str','opaque', 'string' ); # null-terminated C string
21 $f;
22 };
23 # The struct starts with `char *message`. Cast the struct-pointer to
24 # opaque*: FFI::Platypus reads the pointer at offset 0 for us.
25 my $msg_ref = $_decode_ffi->cast( 'opaque', 'opaque*', $err_ptr );
26 my $msg_ptr = ref $msg_ref ? $$msg_ref : $msg_ref;
27 my $msg = $msg_ptr ? $_decode_ffi->cast( 'opaque', 'string', $msg_ptr ) : '';
28 # `int klass` follows the pointer at offset sizeof(void*) = 8 on the LP64
29 # platforms this distribution targets (the rest of the bindings assume 8
30 # too). Read the int living at that address.
31 my $klass_ref = $_decode_ffi->cast( 'opaque', 'int*', $err_ptr + 8 );
32 my $klass = ref $klass_ref ? $$klass_ref : $klass_ref;
33 return ( $msg, $klass // 0 );
34 }
35  
36  
37 sub last {
38 my ( $class, $rc ) = @_;
39 $rc //= -1;
40 Git::Libgit2::FFI::ffi(); # ensure FFI is initialised
41 my $err_ptr = Git::Libgit2::FFI::git_error_last();
42 my ( $msg, $klass ) = _decode($err_ptr);
43 return bless {
44 code => $rc,
45 klass => $klass,
46 message => $msg || '<no error>',
47 }, $class;
48 }
49  
50  
51 sub code { $_[0]->{code} }
52  
53  
54 sub klass { $_[0]->{klass} }
55  
56  
57 sub message { $_[0]->{message} }
58  
59  
60 sub stringify {
61 my $self = shift;
62 sprintf 'libgit2 error %d (klass %d): %s',
63 $self->{code}, $self->{klass}, $self->{message};
64 }
65  
66 use overload
67 '""' => \&stringify,
68 fallback => 1;
69  
70 1;
71  
72 __END__