【SWIG】DxLibのラッパーファイルを一から作り直してみる

久しぶりの更新。

DxLibのラッパー関数を作成しなおして
Swigでウハウハしようという試み。

手順は以下のようになる。
1.DxLibのWebサイト情報取得
2.関数郡の抜き出し
3.Swigで読み取れるよう関数の変換

というわけで、1のコードを書いてみた。

use 5.12.0;
use warnings;
use utf8;
use autodie;
use FindBin;
use lib "$FindBin::Bin/lib";

sub _IO::new {
    use IO::File;
    my $obj = {}; $obj->{class} = shift;

    $obj->{write_all} = sub {
        my ($file, $data) = @_;
        open my $fh, '>', "$file";
        $fh->autoflush(1);
        $fh->print($data);
        $fh->close;
    };
    $obj;
}

sub _HTML::new {
    use LWP::UserAgent;
    my $obj = {}; $obj->{class} = shift;
    my $ua = LWP::UserAgent->new;
    $ua->timeout(40);

    $obj->{steal_html} = sub {
        my ($url) = @_;
        my $response = $ua->get($url);
        if ($response->is_success) {
            return $response->content;
        }
        else {
            return $response->status_line;
        }
    };
    $obj;
}

sub _Parse::new {
    use HTML::TreeBuilder;
    my $obj = {}; $obj->{class} = shift;
    my $tree_builder = HTML::TreeBuilder->new;

    $obj->{steal_url} = sub {
        my ($content) = @_;
        my @url_list;
        $tree_builder->parse($content);
        my @items = $tree_builder->find('a');
        for (@items) {
            push @url_list, $_->attr('href');
        }
        return @url_list;
    };
    $obj;
}

my $my_content_path = "$FindBin::Bin"."/content/";
my $dxlib_url = 'http://homepage2.nifty.com/natupaji/DxLib/';
my $dxlib_sub_url = 'http://homepage2.nifty.com/natupaji/DxLib/function/';
my $dxlib_top_html = 'dxfunc.html';

my $io = _IO->new;
my $html = _HTML->new;
my $top_content = $html->{steal_html}->("$dxlib_url"."$dxlib_top_html");
$io->{write_all}->("$my_content_path"."$dxlib_top_html", "$top_content");

my $parse = _Parse->new;
my @url_list_org = $parse->{steal_url}->($top_content);
my @url_list  = grep { !/(^#.+)|(^index\.html$)/ if defined($_) } @url_list_org;
@url_list = map { $_ =~ s/#.*$//;$_ } @url_list;
@url_list = do { my %h; grep { !$h{$_}++ } @url_list };
@url_list = map { File::Basename::basename($_) } @url_list;

for (my $i = 0; $i < @url_list; $i++) {
    my $sub_content = $html->{steal_html}->("$dxlib_sub_url"."$url_list[$i]");
    $io->{write_all}->("$my_content_path"."$url_list[$i]", $sub_content);
}

__END__
実行すると
contentというフォルダの中に
Webサイト情報を保存してくれる。

次は保存した情報を元に関数群を抜き出すコードを書くよ。