#!/usr/bin/perl
# update-exception-names -- update Lintian data about Python exception names
#
# Copyright © 2012, 2013 Jakub Wilk
#
# This program is free software.  It is distributed under the terms of the GNU
# General Public License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# this program.  If not, you can find it on the World Wide Web at
# http://www.gnu.org/copyleft/gpl.html, or write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

use strict;
use warnings;

use v5.10; # for the // operator

use File::Basename qw(dirname);
use POSIX qw(strftime);

chdir(dirname($0) . '/..') or die $!;

sub extract_exceptions
{
    my ($version) = @_;
    my $uri = "http://docs.python.org/$version/library/exceptions.html";
    if ($version =~ m/^2\.[0-5]/) {
        $uri = "http://docs.python.org/$version/lib/module-exceptions.html"
    }
    open(my $fh, "wget -q -O - $uri |") or die $!;
    {
        local $/ = undef;
        $_ = <$fh>;
    }
    close($fh) or die $!;
    m,<pre>(?:<span class="ne">)?(BaseException.*?)</pre>,s or die "cannot extract exception names for Python $version";
    $_ = $1;
    s,</?span[^<]*>,,g;
    s,\s+\(.*$,,gm;
    s,^[ \t|+-]++,,gm;
    @_ = split;
    for (@_) {
        m/^\w+$/ or die "invalid Python $version exception name: $_";
    }
    return @_;
}

my @versions = qw(2.5 2.6 2.7 3.0 3.1 3.2 3.3 3.4);
my %exceptions = ();
for my $v (@versions) {
    $exceptions{$_} = 1 for extract_exceptions($v);
}
my @exceptions = sort keys %exceptions;
my $date = strftime('%Y-%m-%d', gmtime);
open(my $fh, '>', 'data/python-exceptions') or die $!;
$" = ", ";
print $fh <<EOF ;
# This file contains names of built-in exceptions that exist in the following
# Python versions: @versions

# Last update: $date

EOF
$" = "\n";
print $fh "@exceptions\n";
close($fh) or die $!;

# Local Variables:
# indent-tabs-mode: nil
# End:
# vim: syntax=perl sw=4 sts=4 sr et
