| 1 | # ABSTRACT: A libgit2 configuration handle | ||
| 2 | |||
| 3 | package Git::Native::Config; | ||
| 4 | our $VERSION = '0.006'; | ||
| 5 | use Moo; | ||
| 6 | use Git::Libgit2::FFI (); | ||
| 7 | use Git::Libgit2 qw( GIT_ENOTFOUND ); | ||
| 8 | use Git::Native::Error qw( check_rc ); | ||
| 9 | |||
| 10 | has _handle => ( is => 'ro', required => 1 ); | ||
| 11 | has _owner => ( is => 'ro' ); # Repository (when repo-derived) - keeps it alive | ||
| 12 | |||
| 13 | # get_string($key): the value, or undef when the key is unset. Only | ||
| 14 | # GIT_ENOTFOUND maps to undef; any other libgit2 failure throws via check_rc | ||
| 15 | # (matching get_bool) - we don't silently swallow real errors as "unset". | ||
| 16 | # libgit2 only guarantees git_config_get_string on a *snapshot* config; | ||
| 17 | # use Repository->config_snapshot / config_string for reads. | ||
| 18 | sub get_string { | ||
| 19 | my ( $self, $key ) = @_; | ||
| 20 | my $rc = Git::Libgit2::FFI::git_config_get_string( \my $out, $self->_handle, $key ); | ||
| 21 | return undef if $rc == GIT_ENOTFOUND; # unset | ||
| 22 | check_rc $rc; | ||
| 23 | return $out; | ||
| 24 | } | ||
| 25 | |||
| 26 | # get_bool($key): 1 / 0 for a git-style boolean, or undef when the key is | ||
| 27 | # unset. libgit2 does the parsing via git_config_get_bool (true/yes/on/1, | ||
| 28 | # false/no/off/0, integers by non-zero) - we don't reimplement git's bool | ||
| 29 | # rules in Perl. A present-but-non-boolean value (e.g. "banana") makes | ||
| 30 | # libgit2 return an error, which check_rc turns into a Git::Native::Error; | ||
| 31 | # only GIT_ENOTFOUND maps to undef. | ||
| 32 | sub get_bool { | ||
| 33 | my ( $self, $key ) = @_; | ||
| 34 | my $rc = Git::Libgit2::FFI::git_config_get_bool( \my $out, $self->_handle, $key ); | ||
| 35 | return undef if $rc == GIT_ENOTFOUND; # unset | ||
| 36 | check_rc $rc; # other negatives (e.g. non-boolean) throw | ||
| 37 | return $out ? 1 : 0; | ||
| 38 | } | ||
| 39 | |||
| 40 | # set_string($key, $value): only valid on a live (non-snapshot) config. | ||
| 41 | sub set_string { | ||
| 42 | my ( $self, $key, $value ) = @_; | ||
| 43 | check_rc Git::Libgit2::FFI::git_config_set_string( $self->_handle, $key, $value ); | ||
| 44 | return $self; | ||
| 45 | } | ||
| 46 | |||
| 47 | # snapshot(): a read-only point-in-time copy. Returns a fresh Config. | ||
| 48 | sub snapshot { | ||
| 49 | my $self = shift; | ||
| 50 | check_rc Git::Libgit2::FFI::git_config_snapshot( \my $snap, $self->_handle ); | ||
| 51 | return Git::Native::Config->new( _handle => $snap, _owner => $self->_owner ); | ||
| 52 | } | ||
| 53 | |||
| 54 | sub DEMOLISH { | ||
| 55 | my $self = shift; | ||
| 56 | Git::Libgit2::FFI::git_config_free( $self->{_handle} ) if $self->{_handle}; | ||
| 57 | } | ||
| 58 | |||
| 59 | 1; | ||
| 60 | |||
| 61 | __END__ |