Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 963 lines (771 sloc) 24.564 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
package MetaCPAN::Document::File;

use strict;
use warnings;
use utf8;

use Moose;
use ElasticSearchX::Model::Document;

use Encode;
use List::MoreUtils qw(uniq);
use MetaCPAN::Document::Module;
use MetaCPAN::Pod::XHTML;
use MetaCPAN::Types qw(:all);
use MetaCPAN::Util;
use MooseX::Types::Moose qw(ArrayRef);
use Plack::MIME;
use Pod::Text;
use URI::Escape ();

Plack::MIME->add_type( ".t" => "text/x-script.perl" );
Plack::MIME->add_type( ".pod" => "text/x-pod" );
Plack::MIME->add_type( ".xs" => "text/x-c" );

my @NOT_PERL_FILES = qw(SIGNATURE);

=head1 PROPERTIES

=head2 abstract

Abstract of the documentation (if any). This is built by parsing the
C<NAME> section. It also sets L</documentation> if it succeeds.

=cut

has abstract => (
    is => 'ro',
    required => 1,
    lazy_build => 1,
    index => 'analyzed',
);

sub _build_abstract {
    my $self = shift;
    return undef unless ( $self->is_perl_file );
    my $text = ${ $self->content };
    my ( $documentation, $abstract );
    my $section = MetaCPAN::Util::extract_section( $text, 'NAME' );

    # if it's a POD file without a name section, let's try to generate
    # an abstract and name based on filename
    if( !$section && $self->path =~ /\.pod$/ ) {
        $section = $self->path;
        $section =~ s{^(lib|pod|docs)/}{};
        $section =~ s{\.pod$}{};
        $section =~ s{/}{::}g;
    }

    return undef unless ($section);
    $section =~ s/^=\w+.*$//mg;
    $section =~ s/X<.*?>//mg;

    if ( $section =~ /^\s*(\S+)((\h+-+\h+(.+))|(\r?\n\h*\r?\n\h*(.+)))?/ms ) {
        chomp( $abstract = $4 || $6 ) if ( $4 || $6 );
        my $name = MetaCPAN::Util::strip_pod($1);
        $documentation = $name if ( $name =~ /^[\w\.:\-_']+$/ );
    }
    if ($abstract) {
        $abstract =~ s/^=\w+.*$//xms;
        $abstract =~ s{\r?\n\h*\r?\n\h*.*$}{}xms;
        $abstract =~ s{\n}{ }gxms;
        $abstract =~ s{\s+$}{}gxms;
        $abstract =~ s{(\s)+}{$1}gxms;
        $abstract = MetaCPAN::Util::strip_pod($abstract);
    }
    if ($documentation) {
        $self->documentation( MetaCPAN::Util::strip_pod($documentation) );
    }
    return $abstract;
}

=head2 id

Unique identifier of the release. Consists of the L</author>'s pauseid and
the release L</name>. See L<ElasticSearchX::Model::Util/digest>.

=cut

has id => (
    is => 'ro',
    id => [qw(author release path)],
);

=head2 module

An ArrayRef of L<MetaCPAN::Document::Module> objects, that represent
modules defined in that class (i.e. package declarations).

=cut

has module => (
    required => 0,
    is => 'rw',
    isa => Module,
    type => 'nested',
    include_in_root => 1,
    coerce => 1,
    clearer => 'clear_module',
    lazy => 1,
    default => sub { [] },
);

=head2 date

B<Required>

Release date (i.e. C<mtime> of the tarball).

=cut

has date => (
    is => 'ro',
    required => 1,
    isa => 'DateTime',
);

=head2 description

Contains the C<DESCRIPTION> section of the POD if any. Will be stripped from
whitespaces and POD commands.

=cut

has description => (
    is => 'ro',
    required => 1,
    lazy_build => 1,
    index => 'analyzed',
);

sub _build_description {
    my $self = shift;
    return undef unless ( $self->is_perl_file );
    my $section = MetaCPAN::Util::extract_section( ${ $self->content },
        'DESCRIPTION' );
    return undef unless ($section);
    my $parser = Pod::Text->new;
    my $text = "";
    $parser->output_string( \$text );
    $parser->parse_string_document("=pod\n\n$section");
    $text =~ s/\s+/ /g;
    $text =~ s/^\s+//;
    $text =~ s/\s+$//;
    return $text;
}

=head2 distribution

=head2 distribution.analyzed

=head2 distribution.camelcase

Name of the distribution (e.g. C<Some-Module>).

=head2 author

PAUSE ID of the author.

=head2 status

Valid values are C<latest>, C<cpan>, and C<backpan>. The most recent upload
of a distribution is tagged as C<latest> as long as it's not a developer
release, unless there are only developer releases. Everything else is
tagged C<cpan>. Once a release is deleted from PAUSE it is tagged as
C<backpan>.

=cut

has status => ( is => 'ro', required => 1, default => 'cpan' );

=head2 binary

File is binary or not.

=cut

has binary => (
    is => 'ro',
    isa => 'Bool',
    required => 1,
    default => 0,
);

=head2 authorized

See L</set_authorized>.

=cut

has authorized => (
    required => 1,
    is => 'rw',
    isa => 'Bool',
    default => 1,
);

=head2 maturity

Maturity of the release. This can either be C<released> or C<developer>.
See L<CPAN::DistnameInfo>.

=cut

has maturity => (
    is => 'ro',
    required => 1,
    default => 'released',
);

=head2 directory

Return true if this object represents a directory.

=cut

has directory => (
    is => 'ro',
    required => 1,
    isa => 'Bool',
    default => 0,
);

=head2 documentation

Holds the name for the documentation in this file.

If the file L</is_pod_file|is a pod file>, the name is derived from the
C<NAME> section. If the file L</is_perl_file|is a perl file> and the
name from the C<NAME> section matches one of the modules in L</module>,
it returns the name. Otherwise it returns the name of the first module
in L</module>. If there are no modules in the file the documentation is
set to C<undef>.

=cut

has documentation => (
    required => 1,
    is => 'rw',
    lazy_build => 1,
    index => 'analyzed',
    predicate => 'has_documentation',
    analyzer => [qw(standard camelcase lowercase)],
    clearer => 'clear_documentation',
);

sub _build_documentation {
    my $self = shift;
    $self->_build_abstract;
    my $documentation = $self->documentation if ( $self->has_documentation );
    return undef unless ( ${ $self->pod } );
    my @indexed = grep { $_->indexed } @{ $self->module || [] };
    if ( $documentation && $self->is_pod_file ) {
        return $documentation;
    }
    elsif ( $documentation && grep { $_->name eq $documentation } @indexed ) {
        return $documentation;
    }
    elsif (@indexed) {
        return $indexed[0]->name;
    }
    elsif ( !@{ $self->module || [] } ) {
        return $documentation;
    }
    else {
        return undef;
    }
}

=head2 indexed

B<Default 0>

Indicates whether the file should be included in the search index or
not. See L</set_indexed> for a more verbose explanation.

=cut

has indexed => (
    required => 1,
    is => 'rw',
    isa => 'Bool',
    default => 1,
);

=head2 level

Level of this file in the directory tree of the release (i.e. C<META.yml>
has a level of C<0>).

=cut

has level => (
    is => 'ro',
    required => 1,
    isa => 'Int',
    lazy_build => 1,
);

sub _build_level {
    my $self = shift;
    my @level = split( /\//, $self->path );
    return @level - 1;
}

=head2 pod

Pure text format of the pod (see L</Pod::Text>). Consecutive whitespaces
are removed to save space and for better snippet previews.

=cut

has pod => (
    is => 'ro',
    required => 1,
    isa => 'ScalarRef',
    lazy_build => 1,
    index => 'analyzed',
    not_analyzed => 0,
    store => 'no',
    term_vector => 'with_positions_offsets',
);

sub _build_pod {
    my $self = shift;
    return \'' unless ( $self->is_perl_file );
    my $parser = Pod::Text->new( sentence => 0, width => 78 );

    my $text = "";
    $parser->output_string( \$text );
    $parser->parse_string_document( ${ $self->content } );
    $text =~ s/\s+/ /g;
    return \$text;
}

=head2 pod_lines

ArrayRef of ArrayRefs of offset and length of pod blocks. Example:

# Two blocks of pod, starting at line 1 and line 15 with length
# of 10 lines each
[[1,10], [15,10]]

=cut

has pod_lines => (
    is => 'ro',
    required => 1,
    isa => 'ArrayRef',
    type => 'integer',
    lazy_build => 1,
    index => 'no',
);

sub _build_pod_lines {
    my $self = shift;
    return [] unless ( $self->is_perl_file );
    my ( $lines, $slop ) = MetaCPAN::Util::pod_lines( ${ $self->content } );
    $self->slop( $slop || 0 );
    return $lines;
}

=head2 sloc

Source Lines of Code. Strips empty lines, pod and C<END> section from
L</content> and returns the number of lines.

=cut

has sloc => (
    is => 'ro',
    required => 1,
    isa => 'Int',
    lazy_build => 1,
);

# Copied from Perl::Metrics2::Plugin::Core
sub _build_sloc {
    my $self = shift;
    return 0 unless ( $self->is_perl_file );
    my @content = split( "\n", ${ $self->content } );
    my $pods = 0;
    map {
        splice( @content, $_->[0], $_->[1], map {''} 1 .. $_->[1] )
    } @{ $self->pod_lines };
    my $sloc = 0;
    while (@content) {
        my $line = shift @content;
        last if ( $line =~ /^\s*__END__/s );
        $sloc++ if ( $line !~ /^\s*#/ && $line =~ /\S/ );
    }
    return $sloc;
}

=head2 slop

Source Lines of Pod. Returns the number of pod lines using L</pod_lines>.

=cut

has slop => (
    is => 'ro',
    required => 1,
    isa => 'Int',
    is => 'rw',
    lazy_build => 1,
);

sub _build_slop {
    my $self = shift;
    return 0 unless ( $self->is_perl_file );
    $self->_build_pod_lines;
    return $self->slop;
}

=head2 stat

L<File::stat> info of the tarball. Contains C<mode>, C<uid>, C<gid>, C<size>
and C<mtime>.

=cut

has stat => (
    is => 'ro',
    isa => Stat,
    required => 0,
    dynamic => 1,
);

=head2 version

Contains the raw version string.

=cut

has version => (
    is => 'ro',
    required => 0,
);

=head2 version_numified

B<Required>, B<Lazy Build>

Numeric representation of L</version>. Contains 0 if there is no version or the
version could not be parsed.

=cut

has version_numified => (
    is => 'ro',
    isa => 'Num',
    lazy_build => 1,
    required => 1,
);

sub _build_version_numified {
    my $self = shift;
    return 0 unless ( $self->version );
    return MetaCPAN::Util::numify_version( $self->version );
}

=head2 mime

MIME type of file. Derived using L<Plack::MIME> (for speed).

=cut

has mime => (
    is => 'ro',
    required => 1,
    lazy_build => 1,
);

sub _build_mime {
    my $self = shift;
    if ( !$self->directory
        && $self->name !~ /\./
        && grep { $self->name ne $_ } @NOT_PERL_FILES )
    {
        my $content = ${ $self->content };
        return "text/x-script.perl" if ( $content =~ /^#!.*?perl/ );
    }
    else {
        return Plack::MIME->mime_type( $self->name ) || 'text/plain';
    }
}

has [qw(path author name)] => ( is => 'ro', required => 1 );

sub _build_path {
    my $self = shift;
    return join( '/', $self->release->name, $self->name );
}

has [qw(release distribution)] => (
    is => 'ro',
    required => 1,
    analyzer => [qw(standard camelcase lowercase)],
);

=head1 ATTRIBUTES

These attributes are not stored.

=head2 content

The content of the file. It is built by calling L</content_cb> and
stripping the C<DATA> section for performance reasons.

=cut

has content => (
    is => 'ro',
    isa => 'ScalarRef',
    lazy_build => 1,
    property => 0,
    required => 0,
);

sub _build_content {
    my $self = shift;
    my @content = split( "\n", ${ $self->content_cb->() } || '' );
    my $content = "";
    my $in_data = 0; # skip DATA section
    while (@content) {
        my $line = shift @content;
        if ( $line =~ /^\s*__END__\s*$/ ) {
            $in_data = 0;
        }
        elsif ( $line =~ /^\s*__DATA__\s*$/ ) {
            $in_data++;
        }
        elsif ( $in_data && $line =~ /^=head1/ ) {
            $in_data = 0;
        }
        next if ($in_data);
        $content .= $line . "\n";
    }
    return \$content;
}

=head2 content_cb

Callback that returns the content of the file as a ScalarRef.

=cut

has content_cb => (
    is => 'ro',
    property => 0,
    required => 0,
    default => sub {
        sub { \'' }
    },
);

=head2 local_path

This attribute holds the path to the file on the local filesystem.

=cut

has local_path => (
    is => 'ro',
    property => 0,
);

=head2 metadata

Reference to the L<CPAN::Meta> object of the release.

=cut

has metadata => (
    is => "ro",
    lazy => 1,
    default => sub { die "meta attribute missing" },
    isa => "CPAN::Meta",
    property => 0,
);

=head1 METHODS

=head2 is_perl_file

Return true if the file extension is one of C<pl>, C<pm>, C<pod>, C<t>
or if the file has no extension, is not a binary file and its size is less
than 131072 bytes. This is an arbitrary limit but it keeps the pod parser
happy and the indexer fast.

=cut

sub is_perl_file {
    my $self = shift;
    return 0 if ( $self->directory );
    return 1 if ( $self->name =~ /\.(pl|pm|pod|t)$/i );
    return 1 if ( $self->mime eq "text/x-script.perl" );
    return 1
        if ( $self->name !~ /\./
        && !( grep { $self->name eq $_ } @NOT_PERL_FILES )
        && !$self->binary
        && $self->stat->{size} < 2**17 );
    return 0;
}

=head2 is_pod_file

Returns true if the file extension is C<pod>.

=cut

sub is_pod_file {
    shift->name =~ /\.pod$/i;
}

=head2 add_module

Requires at least one parameter which can be either a HashRef or
an instance of L<MetaCPAN::Document::Module>.

=cut

sub add_module {
    my ( $self, @modules ) = @_;
    $_ = MetaCPAN::Document::Module->new($_)
        for ( grep { ref $_ eq 'HASH' } @modules );
    $self->module( [ @{ $self->module }, @modules ] );
}

=head2 set_indexed

Expects a C<$meta> parameter which is an instance of L<CPAN::Meta>.

For each package (L</module>) in the file and based on L<CPAN::Meta/should_index_package>
it is decided, whether the module should have a true L</indexed> attribute.
If L<CPAN::Meta/should_index_package> returns true but the package declaration
uses the I<hide from PAUSE> hack, the L</indexed> property is set to false.

package # hide from PAUSE
MyTest::Module;
# will result in indexed => 0

Once that is done, the L</indexed> property of the file is determined by searching
the list of L<modules|/module> for a module that matches the value of L</documentation>.
If there is no such module, the L</indexed> property is set to false. If the file
does not include any modules, the L</indexed> property is true.

=cut

sub set_indexed {
    my ( $self, $meta ) = @_;
    foreach my $mod ( @{ $self->module } ) {
        $mod->indexed(
              $meta->should_index_package( $mod->name )
            ? $mod->hide_from_pause( ${ $self->content }, $self->name )
                    ? 0
                    : 1
            : 0
        ) unless ( $mod->indexed );
    }
    $self->indexed(

        # .pm file with no package declaration but pod should be indexed
        !@{ $self->module } ||

           # don't index if the documentation doesn't match any of its modules
            !!grep { $self->documentation eq $_->name } @{ $self->module }
    ) if ( $self->documentation );
}

=head2 set_authorized

Expects a C<$perms> parameter which is a HashRef. The key is the module name
and the value an ArrayRef of author names who are allowed to release
that module.

The method returns a list of unauthorized, but indexed modules.

Unauthorized modules are modules that were uploaded in the name of a
different author than stated in the C<06perms.txt.gz> file. One problem
with this file is, that it doesn't record historical data. It may very
well be that an author was authorized to upload a module at the time.
But then his co-maintainer rights might have been revoked, making consecutive
uploads of that release unauthorized. However, since this script runs
with the latest version of C<06perms.txt.gz>, the former upload will
be flagged as unauthorized as well. Same holds the other way round,
a previously unauthorized release would be flagged authorized if the
co-maintainership was added later on.

If a release contains unauthorized modules, the whole release is marked
as unauthorized as well.

=cut

sub set_authorized {
    my ( $self, $perms ) = @_;

    # only authorized perl distributions make it into the CPAN
    return () if ( $self->distribution eq 'perl' );
    foreach my $module ( @{ $self->module } ) {
        $module->authorized(0)
            if ( $perms->{ $module->name } && !grep { $_ eq $self->author }
            @{ $perms->{ $module->name } } );
    }
    $self->authorized(0)
        if ( $self->authorized
        && $self->documentation
        && $perms->{ $self->documentation }
        && !grep { $_ eq $self->author }
        @{ $perms->{ $self->documentation } } );
    return grep { !$_->authorized && $_->indexed } @{ $self->module };
}

=head2 full_path

Concatenate L</author>, L</release> and L</path>.

=cut

sub full_path {
    my $self = shift;
    return join( "/", $self->author, $self->release, $self->path );
}

__PACKAGE__->meta->make_immutable;

package MetaCPAN::Document::File::Set;
use Moose;
extends 'ElasticSearchX::Model::Document::Set';

my @ROGUE_DISTRIBUTIONS
    = qw(kurila perl_debug perl-5.005_02+apache1.3.3+modperl pod2texi perlbench spodcxx Bundle-Everything);

sub find {
    my ( $self, $module ) = @_;
    my @candidates = $self->index->type("file")->filter(
        { and => [
                { or => [
                        { term => { 'file.module.name' => $module } },
                        { term => { 'file.documentation' => $module } },
                    ]
                },
                { term => { 'file.indexed' => \1, } },
                { term => { status => 'latest', } },
                { not =>
                        { filter => { term => { 'file.authorized' => \0 } } }
                },
            ]
        }
        )->sort(
        [ { 'date' => { order => "desc" } },
            'mime',
            { 'stat.mtime' => { order => 'desc' } }
        ]
        )->size(100)->all;

    my ($file) = grep {
        grep { $_->indexed && $_->authorized && $_->name eq $module }
            @{ $_->module || [] }
        } grep { !$_->documentation || $_->documentation eq $module }
        @candidates;

    $file ||= shift @candidates;
    return $file ? $self->get( $file->id ) : undef;
}

sub find_pod {
    my ( $self, $name ) = @_;
    my $file = $self->find($name);
    return $file unless ($file);
    my ($module)
        = grep { $_->indexed && $_->authorized && $_->name eq $name }
        @{ $file->module || [] };
    if ( $module && ( my $pod = $module->associated_pod ) ) {
        my ( $author, $release, @path ) = split( /\//, $pod );
        return $self->get(
            { author => $author,
                release => $release,
                path => join( "/", @path ),
            }
        );
    }
    else {
        return $file;
    }
}

# return files that contain modules that match the given dist
# NOTE: these still need to be filtered by authorized/indexed
# TODO: test that we are getting the correct version (latest)
sub find_provided_by {
    my ( $self, $release ) = @_;
    return $self->filter(
        { and => [
                { term => { 'release' => $release->{name} } },
                { term => { 'author' => $release->{author} } },
                { term => { 'file.module.authorized' => 1 } },
                { term => { 'file.module.indexed' => 1 } },
            ]
        }
    )->size(999)->all;
}

# filter find_provided_by results for indexed/authorized modules
# and return a list of package names
sub find_module_names_provided_by {
    my ( $self, $release ) = @_;
    my $mods = $self->inflate(0)->find_provided_by($release);
    return (
        map { $_->{name} }
        grep { $_->{indexed} && $_->{authorized} }
        map { @{ $_->{_source}->{module} } } @{ $mods->{hits}->{hits} }
    );
}

# TODO: figure out what uses this and write tests for it
sub prefix {
    my ( $self, $prefix ) = @_;
    my @query = split( /\s+/, $prefix );
    my $should = [
        map {
            { field => { 'documentation.analyzed' => "$_*" } },
                { field => { 'documentation.camelcase' => "$_*" } }
        } grep {$_} @query
    ];
    return $self->query(
        { filtered => {
                query => {
                    custom_score => {
                        query => { bool => { should => $should } },

                        #metacpan_script => 'prefer_shorter_module_names_100',
                        script =>
                            "_score - doc['documentation'].value.length()/100"
                    },
                },
                filter => {
                    and => [
                        { not => {
                                filter => {
                                    or => [
                                        map {
                                            +{ term => {
                                                    'file.distribution' => $_
                                                }
                                                }
                                            } @ROGUE_DISTRIBUTIONS

                                    ]
                                }
                            }
                        },
                        { exists => { field => 'documentation' } },
                        { term => { 'file.indexed' => \1 } },
                        { term => { 'file.status' => 'latest' } },
                        { not => {
                                filter =>
                                    { term => { 'file.authorized' => \0 } }
                            }
                        }
                    ]
                }
            }
        }
    );
}

=head2 history

Find the history of a given module/documentation.

=cut

sub history {
    my ( $self, $type, $module, @path ) = @_;
    my $search
        = $type eq "module" ? $self->filter(
        { nested => {
                path => "module",
                query => {
                    constant_score => {
                        filter => {
                            and => [
                                { term => { "module.authorized" => \1 } },
                                { term => { "module.indexed" => \1 } },
                                { term => { "module.name" => $module } },
                            ]
                        }
                    }
                }
            }
        }
        )
        : $type eq "file" ? $self->filter(
        { and => [
                { term => { "file.path" => join( "/", @path ) } },
                { term => { "file.distribution" => $module } },
            ]
        }
        )
        : $self->filter(
        { and => [
                { term => { "file.documentation" => $module } },
                { term => { "file.indexed" => \1 } },
                { term => { "file.authorized" => \1 } },
            ]
        }
        );
    return $search->sort( [ { "file.date" => "desc" } ] );
}

sub _not_rogue {
    my @rogue_dists = map { { term => { 'file.distribution' => $_ } } }
        @ROGUE_DISTRIBUTIONS;
    return { not => { filter => { or => \@rogue_dists } } };
}

sub autocomplete {
    my ( $self, @terms ) = @_;
    my $query = join( " ", @terms );
    return $self unless $query;
    $query =~ s/::/ /g;
    my @query = split( /\s+/, $query );
    my $should = [
        map {
            { field => { 'documentation.analyzed' => "$_*" } },
                { field => { 'documentation.camelcase' => "$_*" } }
        } grep {$_} @query
    ];

    # TODO: custom_score is deprecated in 0.90.4 in favor of function_score.
    # As of 2013-10-27 we are still using 0.20.2 in production.
    return $self->query(
        { custom_score => {
                query => { bool => { should => $should } },
                script => "_score - doc['documentation'].value.length()/100",
            }
        }
        )->filter(
        { and => [
                $self->_not_rogue,
                { exists => { field => 'documentation' } },
                { term => { 'file.indexed' => \1 } },
                { term => { 'file.authorized' => \1 } },
                { term => { 'file.status' => 'latest' } },
            ]
        }
        )->sort( [ '_score', 'documentation' ] );
}

__PACKAGE__->meta->make_immutable;
1;
Something went wrong with that request. Please try again.