]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GitCredential.pm
update copyrights for 2021
[public-inbox.git] / lib / PublicInbox / GitCredential.pm
1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 package PublicInbox::GitCredential;
4 use strict;
5 use PublicInbox::Spawn qw(popen_rd);
6
7 sub run ($$) {
8         my ($self, $op) = @_;
9         my ($in_r, $in_w);
10         pipe($in_r, $in_w) or die "pipe: $!";
11         my $out_r = popen_rd([qw(git credential), $op], undef, { 0 => $in_r });
12         close $in_r or die "close in_r: $!";
13
14         my $out = '';
15         for my $k (qw(url protocol host username password)) {
16                 defined(my $v = $self->{$k}) or next;
17                 die "`$k' contains `\\n' or `\\0'\n" if $v =~ /[\n\0]/;
18                 $out .= "$k=$v\n";
19         }
20         $out .= "\n";
21         print $in_w $out or die "print (git credential $op): $!";
22         close $in_w or die "close (git credential $op): $!";
23         return $out_r if $op eq 'fill';
24         <$out_r> and die "unexpected output from `git credential $op'\n";
25         close $out_r or die "`git credential $op' failed: \$!=$! \$?=$?\n";
26 }
27
28 sub check_netrc ($) {
29         my ($self) = @_;
30
31         # part of the standard library, but distributions may split it out
32         eval { require Net::Netrc };
33         if ($@) {
34                 warn "W: Net::Netrc missing: $@\n";
35                 return;
36         }
37         if (my $x = Net::Netrc->lookup($self->{host}, $self->{username})) {
38                 $self->{username} //= $x->login;
39                 $self->{password} = $x->password;
40         }
41 }
42
43 sub fill {
44         my ($self) = @_;
45         my $out_r = run($self, 'fill');
46         while (<$out_r>) {
47                 chomp;
48                 return if $_ eq '';
49                 /\A([^=]+)=(.*)\z/ or die "bad line: $_\n";
50                 $self->{$1} = $2;
51         }
52         close $out_r or die "git credential fill failed: \$!=$! \$?=$?\n";
53 }
54
55 1;