Skip to content

Instantly share code, notes, and snippets.

@neilb
Created March 17, 2014 23:55
Show Gist options
  • Save neilb/9610895 to your computer and use it in GitHub Desktop.
Save neilb/9610895 to your computer and use it in GitHub Desktop.
Script which gets the pod source for a module from MetaCPAN then tries to extract the abstract for it, following the spec for an abstract
#!/usr/bin/env perl
#
# module-abstract - get the abstract for a module, using MetaCPAN
#
# Usage: module-abstract <module-name>
#
use strict;
use warnings;
use HTTP::Tiny;
use JSON;
die "usage: $0 <module>\n" unless @ARGV == 1;
my $module_name = $ARGV[0];
my $pod_source = get_module_pod_source($module_name);
open(my $fh, '>', 'module.pod');
print $fh $pod_source;
close($fh);
my $abstract = parse_abstract($pod_source);
print "$module_name abstract = '$abstract'\n";
sub get_module_pod_source
{
my $module_name = shift;
my $ua = HTTP::Tiny->new();
my $url = "https://api.metacpan.org/module/$module_name";
my $response = $ua->get($url);
if (not $response->{success}) {
die "failed to get module details for $module_name from MetaCPAN ($url): ",
"$response->{status} $response->{reason}\n";
}
my $metadata = decode_json($response->{content});
my $pod_path = $metadata->{module}->[0]->{associated_pod};
if (not defined($pod_path)) {
die "couldn't get path to module pod from MetaCPAN";
}
my $source_url = "http://api.metacpan.org/source/$pod_path";
$response = $ua->get($source_url);
if (not $response->{success}) {
die "failed to get pod source from MetaCPAN: ",
"$response->{status} $response->{reason}\n";
}
return $response->{content};
}
sub parse_abstract
{
my $pod_source = shift;
my ($abstract) = $pod_source =~ m!
(?:\A|\R\R)
=head1[ ]NAME\R
\s*\R
\Q$module_name\E[ ]-[ ](.*?)\R
\R
!msx;
die "couldn't find abstract\n" if not defined($abstract);
return $abstract;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment