summarylogtreecommitdiffstats
path: root/fu.pl
blob: afcccfafbb7f4d6399647ce4fad1b49d8974efda (plain)
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
#!/usr/bin/env perl
package App::commandlinefu;
use Mouse;
use LWP::UserAgent;

our $VERSION = '0.01';

has ua => (
    accessor => 'ua',
    isa => "LWP::UserAgent",
    lazy_build => 1,
);

sub _build_ua {
    LWP::UserAgent->new(
        agent => __PACKAGE__ . $VERSION,
        timeout => 10,
    );
}

__PACKAGE__->meta->make_immutable;

no Mouse;

use Carp;
use Encode;
use JSON::XS;
use MIME::Base64;
use Term::ANSIColor qw(:constants);

sub run {
    my ($self, $query) = @_;
    _validate($query);

    my $url = $self->_api_url($query);

    my $res = $self->ua->get($url);
    unless ($res->is_success) {
        Carp::croak("Can't download $url ", $res->status_line);
    }

    my $content = decode_utf8($res->content);

    my $command_infos_ref = $self->_parse_response(\$content);
    for my $command_info (@{$command_infos_ref}) {
        print BRIGHT_GREEN "# ";
        print encode_utf8($command_info->{summary});
        print encode_utf8(" [votes=" . encode_utf8($command_info->{votes}) . "]\n");
        print RESET;

        my $colored_query = YELLOW . $query . RESET;
        $command_info->{command} =~ s/$query/$colored_query/;
        print encode_utf8($command_info->{command}), "\n\n";
    }
}

sub _validate {
    my $query = shift;

    unless (defined $query) {
        Carp::croak("Usage $0 search_command\n");
    }
}

sub _parse_response {
    my ($self, $content_ref) = @_;
    return decode_json(${$content_ref});
}

sub _api_url {
    my ($self, $query) = @_;
    my $base = 'http://www.commandlinefu.com/commands/matching';
    my $base64 = encode_base64($query, '');

    return "${base}/${query}/${base64}/json";
}

package main;
use strict;
use warnings;

unless (caller) {
    my $app = App::commandlinefu->new();
    $app->run( @ARGV );
}