Bash-Completion-Plugins-cpanm

 view release on metacpan or  search on metacpan

README.pod  view on Meta::CPAN

package Bash::Completion::Plugins::cpanm;

# ABSTRACT: Bash completion for cpanm and cpanf
use strict;
use warnings;
use base 'Bash::Completion::Plugin';

use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
use JSON;

use Bash::Completion::Utils qw( command_in_path );

sub should_activate {
    my @commands = qw( cpanm cpanf cpan );
    return [ grep { command_in_path($_) } @commands ];
}

sub generate_bash_setup { return [qw( nospace default )] }

sub complete {
    my ( $class, $req ) = @_;
    my $ua = LWP::UserAgent->new;
    ( my $key = $req->word ) =~ s/::?/-/g;

    #$key =~ s/-$//g;
    my $res = $ua->request(
        POST 'http://api.metacpan.org/release/_search',
        Content => encode_json(
            {   size   => 1000,
                fields => ['distribution'],
                sort   => ['distribution'],
                query  => {
                    filtered => {
                        query  => { match_all => {} },
                        filter => {
                            and => [
                                { prefix => { 'release.distribution' => $key } },
                                { term   => { status        => 'latest' } }
                            ]
                        }
                    }
                }
            }
        )
    );
    eval {
        my $json = decode_json( $res->content );
        $req->candidates('') unless ( $json->{hits} );
        my @candidates;
        my $exact_match = 0;
        for ( @{ $json->{hits}->{hits} } ) {
            my $dist = $_->{fields}->{distribution};
            $exact_match = 1 if ( $key eq $dist );
            $key  =~ s/^(.*)\-.*?$/$1-/;
            $dist =~ s/^\Q$key\E// if ( $key =~ /-/ );
            $dist =~ s/-.*?$/::/g;
            push( @candidates, $dist );
        }
        $req->candidates(@candidates)
            unless ( $exact_match && @candidates == 1 );
    };
}

1;

__END__



( run in 1.349 second using v1.01-cache-2.11-cpan-75ffa21a3d4 )