| 1 | # ABSTRACT: A Git author/committer signature | ||
| 2 | |||
| 3 | package Git::Native::Signature; | ||
| 4 | our $VERSION = '0.006'; | ||
| 5 | use Moo; | ||
| 6 | use Carp (); | ||
| 7 | use Git::Libgit2::FFI (); | ||
| 8 | use Git::Native::Error qw( check_rc ); | ||
| 9 | |||
| 10 | has name => ( is => 'ro', required => 1 ); | ||
| 11 | has email => ( is => 'ro', required => 1 ); | ||
| 12 | has when => ( is => 'ro' ); # epoch seconds; default = now | ||
| 13 | has offset => ( is => 'ro', default => 0 ); # minutes | ||
| 14 | |||
| 15 | # git_signature layout on a 64-bit host: | ||
| 16 | # typedef struct { char *name; char *email; git_time when; } git_signature; | ||
| 17 | # typedef struct { git_time_t time; int offset; char sign; } git_time; | ||
| 18 | # giving 0 = char *name, 8 = char *email, 16 = int64 time, 24 = int offset. | ||
| 19 | # Stable since libgit2 1.0; re-verified empirically against 1.5.1. | ||
| 20 | use constant SIG_HEADER_SIZE => 28; # through git_time.offset; .sign unused | ||
| 21 | |||
| 22 | # Underlying git_signature*; allocated lazily, freed in DESTROY. | ||
| 23 | has _handle => ( | ||
| 24 | is => 'lazy', | ||
| 25 | builder => '_build_handle', | ||
| 26 | clearer => '_clear_handle', | ||
| 27 | ); | ||
| 28 | |||
| 29 | sub _build_handle { | ||
| 30 | my $self = shift; | ||
| 31 | my $sig; | ||
| 32 | if ( defined $self->when ) { | ||
| 33 | check_rc Git::Libgit2::FFI::git_signature_new( | ||
| 34 | \$sig, $self->name, $self->email, $self->when, $self->offset, | ||
| 35 | ); | ||
| 36 | } | ||
| 37 | else { | ||
| 38 | check_rc Git::Libgit2::FFI::git_signature_now( | ||
| 39 | \$sig, $self->name, $self->email, | ||
| 40 | ); | ||
| 41 | } | ||
| 42 | return $sig; | ||
| 43 | } | ||
| 44 | |||
| 45 | # Wrap a git_signature* libgit2 allocated for us (e.g. git_signature_default). | ||
| 46 | # Takes ownership of the handle - DEMOLISH frees it. name/email are COPIED out | ||
| 47 | # of the struct into Perl scalars, so they don't dangle once the C handle is | ||
| 48 | # freed (same contract as Git::Native::Oid::from_ptr). | ||
| 49 | sub from_handle { | ||
| 50 | my ( $class, $ptr ) = @_; | ||
| 51 | Carp::croak 'from_handle: null pointer' unless $ptr; | ||
| 52 | my $ffi = Git::Libgit2::FFI::ffi(); | ||
| 53 | my ( $name_ptr, $email_ptr, $when, $offset ) | ||
| 54 | = unpack 'Q Q q l', $ffi->cast( 'opaque', 'string(' . SIG_HEADER_SIZE . ')', $ptr ); | ||
| 55 | return $class->new( | ||
| 56 | name => $ffi->cast( 'opaque', 'string', $name_ptr ), | ||
| 57 | email => $ffi->cast( 'opaque', 'string', $email_ptr ), | ||
| 58 | when => $when, | ||
| 59 | offset => $offset, | ||
| 60 | _handle => $ptr, | ||
| 61 | ); | ||
| 62 | } | ||
| 63 | |||
| 64 | sub DEMOLISH { | ||
| 65 | my $self = shift; | ||
| 66 | Git::Libgit2::FFI::git_signature_free( $self->{_handle} ) | ||
| 67 | if $self->{_handle}; | ||
| 68 | } | ||
| 69 | |||
| 70 | 1; | ||
| 71 | |||
| 72 | __END__ |