<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#
# Parse::DebianChangelog
#
# Copyright 1996 Ian Jackson
# Copyright 2005,2011 Frank Lichtenheld &lt;frank@lichtenheld.de&gt;
#
#    This program is free software; you can redistribute it and/or modify
#    it 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, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
#

=head1 NAME

Parse::DebianChangelog - parse Debian changelogs and output them in other formats

=head1 SYNOPSIS

    use Parse::DebianChangelog;

    my $chglog = Parse::DebianChangelog-&gt;init( { infile =&gt; 'debian/changelog',
                                                 HTML =&gt; { outfile =&gt; 'changelog.html' } );
    $chglog-&gt;html;

    # the following is semantically equivalent
    my $chglog = Parse::DebianChangelog-&gt;init();
    $chglog-&gt;parse( { infile =&gt; 'debian/changelog' } );
    $chglog-&gt;html( { outfile =&gt; 'changelog.html' } );

    my $changes = $chglog-&gt;dpkg_str( { since =&gt; '1.0-1' } );
    print $changes;

=head1 DESCRIPTION

Parse::DebianChangelog parses Debian changelogs as described in the Debian
policy (version 3.6.2.1 at the time of this writing). See section
L&lt;"SEE ALSO"&gt; for locations where to find this definition.

The parser tries to ignore most cruft like # or /* */ style comments,
CVS comments, vim variables, emacs local variables and stuff from
older changelogs with other formats at the end of the file.
NOTE: most of these are ignored silently currently, there is no
parser error issued for them. This should become configurable in the
future.

Beside giving access to the details of the parsed file via the
L&lt;"data"&gt; method, Parse::DebianChangelog also supports converting these
changelogs to various other formats. These are currently:

=over 4

=item dpkg

Format as known from L&lt;dpkg-parsechangelog(1)&gt;. All requested entries
(see L&lt;"METHODS"&gt; for an explanation what this means) are returned in
the usual Debian control format, merged in one stanza, ready to be used
in a F&lt;.changes&gt; file.

=item rfc822

Similar to the C&lt;dpkg&gt; format, but the requested entries are returned
as one stanza each, i.e. they are not merged. This is probably the format
to use if you want a machine-usable representation of the changelog.

=item xml

Just a simple XML dump of the changelog data. Without any schema or
DTD currently, just some made up XML. The actual format might still
change. Comments and Improvements welcome.

=item html

The changelog is converted to a somewhat nice looking HTML file with
some nice features as a quick-link bar with direct links to every entry.
NOTE: This is not very configurable yet and was specifically designed
to be used on L&lt;http://packages.debian.org/&gt;. This is planned to be
changed until version 1.0.

=back

=head2 METHODS

=cut

package Parse::DebianChangelog;

use 5.010;
use strict;
use warnings;

use Fcntl qw( :flock );
use Locale::gettext;
use Date::Parse;
use Parse::DebianChangelog::Util qw( :all );
use Parse::DebianChangelog::Entry;

our $VERSION = '1.2.0';

=pod

=head3 init

Creates a new object instance. Takes a reference to a hash as
optional argument, which is interpreted as configuration options.
There are currently no supported general configuration options, but
see the other methods for more specific configuration options which
can also specified to C&lt;init&gt;.

If C&lt;infile&gt; or C&lt;instring&gt; are specified (see L&lt;parse&gt;), C&lt;parse()&gt;
is called from C&lt;init&gt;. If a fatal error is encountered during parsing
(e.g. the file can't be opened), C&lt;init&gt; will not return a
valid object but C&lt;undef&gt;!

=cut

sub init {
    my $classname = shift;
    my $config = shift || {};
    my $self = {};
    bless( $self, $classname );

    $config-&gt;{verbose} = 1 if $config-&gt;{debug};
    $self-&gt;{config} = $config;

    $self-&gt;init_filters;
    $self-&gt;reset_parse_errors;

    if ($self-&gt;{config}{infile} || $self-&gt;{config}{instring}) {
	defined($self-&gt;parse) or return undef;
    }

    return $self;
}

=pod

=head3 reset_parse_errors

Can be used to delete all information about errors ocurred during
previous L&lt;parse&gt; runs. Note that C&lt;parse()&gt; also calls this method.

=cut

sub reset_parse_errors {
    my ($self) = @_;

    $self-&gt;{errors}{parser} = [];
}

sub _do_parse_error {
    my ($self, $file, $line_nr, $error, $line) = @_;
    shift;

    push @{$self-&gt;{errors}{parser}}, [ @_ ];

    $file = substr $file, 0, 20;
    unless ($self-&gt;{config}{quiet}) {
	if ($line) {
	    warn "WARN: $file(l$.): $error\nLINE: $line\n";
	} else {
	    warn "WARN: $file(l$.): $error\n";
	}
    }
}

=pod

=head3 get_parse_errors

Returns all error messages from the last L&lt;parse&gt; run.
If called in scalar context returns a human readable
string representation. If called in list context returns
an array of arrays. Each of these arrays contains

=over 4

=item 1.

the filename of the parsed file or C&lt;String&gt; if a string was
parsed directly

=item 2.

the line number where the error occurred

=item 3.

an error description

=item 4.

the original line

=back

NOTE: This format isn't stable yet and may change in later versions
of this module.

=cut

sub get_parse_errors {
    my ($self) = @_;

    if (wantarray) {
	return @{$self-&gt;{errors}{parser}};
    } else {
	my $res = "";
	foreach my $e (@{$self-&gt;{errors}{parser}}) {
	    if ($e-&gt;[3]) {
		$res .= __g( "WARN: %s(l%s): %s\nLINE: %s\n", @$e );
	    } else {
		$res .= __g( "WARN: %s(l%s): %s\n", @$e );
	    }
	}
	return $res;
    }
}

sub _do_fatal_error {
    my ($self, @msg) = @_;

    $self-&gt;{errors}{fatal} = "@msg";
    warn __g( "FATAL: %s", "@msg")."\n" unless $self-&gt;{config}{quiet};
}

=pod

=head3 get_error

Get the last non-parser error (e.g. the file to parse couldn't be opened).

=cut

sub get_error {
    my ($self) = @_;

    return $self-&gt;{errors}{fatal};
}

=pod

=head3 parse

Parses either the file named in configuration item C&lt;infile&gt; or the string
saved in configuration item C&lt;instring&gt;.
Accepts a hash ref as optional argument which can contain configuration
items.

Returns C&lt;undef&gt; in case of error (e.g. "file not found", B&lt;not&gt; parse
errors) and the object if successful. If C&lt;undef&gt; was returned, you
can get the reason for the failure by calling the L&lt;get_error&gt; method.

=cut

sub __g {
    my $string = shift;
    return sprintf( dgettext( 'Parse-DebianChangelog', $string ), @_ );
}

sub parse {
    my ($self, $config) = @_;

    foreach my $c (keys %$config) {
	$self-&gt;{config}{$c} = $config-&gt;{$c};
    }

    my ($fh, $file);
    if ($file = $self-&gt;{config}{infile}) {
	open $fh, '&lt;', $file or do {
	    $self-&gt;_do_fatal_error( __g( "can't open file %s: %s",
					 $file, $! ));
	    return undef;
	};
	flock $fh, LOCK_SH or do {
	    $self-&gt;_do_fatal_error( __g( "can't lock file %s: %s",
					 $file, $! ));
	    return undef;
	};
    } elsif (my $string = $self-&gt;{config}{instring}) {
	eval { require IO::String };
	if ($@) {
	    $self-&gt;_do_fatal_error( __g( "can't load IO::String: %s",
					 $@ ));
	    return undef;
	}
	$fh = IO::String-&gt;new( $string );
	$file = 'String';
    } else {
	$self-&gt;_do_fatal_error( __g( 'no changelog file specified' ));
	return undef;
    }

    $self-&gt;reset_parse_errors;

    $self-&gt;{data} = [];

# based on /usr/lib/dpkg/parsechangelog/debian
    my $expect='first heading';
    my $entry = Parse::DebianChangelog::Entry-&gt;init();
    my $blanklines = 0;
    my $unknowncounter = 1; # to make version unique, e.g. for using as id

    local $_;
    while (&lt;$fh&gt;) {
	s/\s*\n$//;
#	printf(STDERR "%-39.39s %-39.39s\n",$expect,$_);
	if (m/^(?&lt;Source&gt;\w[-+0-9a-z.]*) \((?&lt;Version&gt;[^\(\) \t]+)\)(?&lt;Distribution&gt;(?:\s+[-+0-9a-z.]+)+)\;\s*(?&lt;kv&gt;.*)$/i) {
	    unless ($expect eq 'first heading'
		    || $expect eq 'next heading or eof') {
		$entry-&gt;{ERROR} = [ $file, $.,
				  __g( "found start of entry where expected %s",
				       $expect ), "$_" ];
		$self-&gt;_do_parse_error(@{$entry-&gt;{ERROR}});
	    }
	    unless ($entry-&gt;is_empty) {
		$entry-&gt;{'Closes'} = find_closes( $entry-&gt;{Changes} );
#		    print STDERR, Dumper($entry);
		push @{$self-&gt;{data}}, $entry;
		$entry = Parse::DebianChangelog::Entry-&gt;init();
	    }
	    {
		$entry-&gt;{'Source'} = $+{Source};
		$entry-&gt;{'Version'} = $+{Version};
		$entry-&gt;{'Header'} = "$_";
		($entry-&gt;{'Distribution'} = $+{Distribution}) =~ s/^\s+//;
		$entry-&gt;{'Changes'} = $entry-&gt;{'Urgency_Comment'} = '';
		$entry-&gt;{'Urgency'} = $entry-&gt;{'Urgency_LC'} = 'unknown';
	    }
	    my %kvdone;
	    for my $kv (split(/\s*,\s*/,$+{kv})) {
		$kv =~ m/^([-0-9a-z]+)\=\s*(.*\S)$/i ||
		    $self-&gt;_do_parse_error($file, $.,
					   __g( "bad key-value after \`;': \`%s'", $kv ));
		my $k = ucfirst $1;
		my $v = $2;
		$kvdone{$k}++ &amp;&amp; $self-&gt;_do_parse_error($file, $.,
						       __g( "repeated key-value %s", $k ));
		if ($k eq 'Urgency') {
		    $v =~ m/^([-0-9a-z]+)((\s+.*)?)$/i ||
			$self-&gt;_do_parse_error($file, $.,
					      __g( "badly formatted urgency value" ),
					      $v);
		    $entry-&gt;{'Urgency'} = "$1";
		    $entry-&gt;{'Urgency_LC'} = lc("$1");
		    $entry-&gt;{'Urgency_Comment'} = "$2";
		} elsif ($k =~ m/^X[BCS]+-/i) {
		    # Extensions - XB for putting in Binary,
		    # XC for putting in Control, XS for putting in Source
		    $entry-&gt;{$k}= $v;
		} else {
		    $self-&gt;_do_parse_error($file, $.,
					  __g( "unknown key-value key %s - copying to XS-%s", $k, $k ));
		    $entry-&gt;{ExtraFields}{"XS-$k"} = $v;
		}
	    }
	    $expect= 'start of change data';
	    $blanklines = 0;
	} elsif (m/^(;;\s*)?Local variables:/io) {
	    last; # skip Emacs variables at end of file
	} elsif (m/^vim:/io) {
	    last; # skip vim variables at end of file
	} elsif (m/^\$\w+:.*\$/o) {
	    next; # skip stuff that look like a CVS keyword
	} elsif (m/^\# /o) {
	    next; # skip comments, even that's not supported
	} elsif (m,^/\*.*\*/,o) {
	    next; # more comments
	} elsif (m/^(\w+\s+\w+\s+\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}\s+[\w\s]*\d{4})\s+(.*)\s+(&lt;|\()(.*)(\)|&gt;)/o
		 || m/^(\w+\s+\w+\s+\d{1,2},?\s*\d{4})\s+(.*)\s+(&lt;|\()(.*)(\)|&gt;)/o
		 || m/^(\w[-+0-9a-z.]*) \(([^\(\) \t]+)\)\;?/io
		 || m/^([\w.+-]+)(-| )(\S+) Debian (\S+)/io
		 || m/^Changes from version (.*) to (.*):/io
		 || m/^Changes for [\w.+-]+-[\w.+-]+:?$/io
		 || m/^Old Changelog:$/io
		 || m/^(?:\d+:)?\w[\w.+~-]*:?$/o) {
	    # save entries on old changelog format verbatim
	    # we assume the rest of the file will be in old format once we
	    # hit it for the first time
	    $self-&gt;{oldformat} = "$_\n";
	    $self-&gt;{oldformat} .= join "", &lt;$fh&gt;;
	} elsif (m/^\S/) {
	    $self-&gt;_do_parse_error($file, $.,
				  __g( "badly formatted heading line" ), "$_");
	} elsif (m/^ \-\- (?&lt;name&gt;.*) &lt;(?&lt;email&gt;.*)&gt;(?&lt;sep&gt;  ?)(?&lt;date&gt;(?:\w+\,\s*)?\d{1,2}\s+\w+\s+\d{4}\s+\d{1,2}:\d\d:\d\d\s+[-+]\d{4}(\s+\([^\\\(\)]\))?)$/o) {
	    $expect eq 'more change data or trailer' ||
		$self-&gt;_do_parse_error($file, $.,
				       __g( "found trailer where expected %s",
					    $expect ), "$_");
	    if ($+{sep} ne '  ') {
		$self-&gt;_do_parse_error($file, $.,
				       __g( "badly formatted trailer line" ),
				       "$_");
	    }
	    $entry-&gt;{'Trailer'} = $_;
	    $entry-&gt;{'Maintainer'} = "$+{name} &lt;$+{email}&gt;" unless $entry-&gt;{'Maintainer'};
	    unless($entry-&gt;{'Date'} &amp;&amp; defined $entry-&gt;{'Timestamp'}) {
		$entry-&gt;{'Date'} = "$+{date}";
		$entry-&gt;{'Timestamp'} = str2time($+{date});
		unless (defined $entry-&gt;{'Timestamp'}) {
		    $self-&gt;_do_parse_error( $file, $.,
					    __g( "couldn't parse date %s",
						 "$+{date}" ) );
		}
	    }
	    $expect = 'next heading or eof';
	} elsif (m/^ \-\-/) {
	    $entry-&gt;{ERROR} = [ $file, $.,
			      __g( "badly formatted trailer line" ), "$_" ];
	    $self-&gt;_do_parse_error(@{$entry-&gt;{ERROR}});
#	    $expect = 'next heading or eof'
#		if $expect eq 'more change data or trailer';
	} elsif (m/^\s{2,}(\S)/) {
	    $expect eq 'start of change data'
		|| $expect eq 'more change data or trailer'
		|| do {
		    $self-&gt;_do_parse_error($file, $.,
			    __g( "found change data where expected %s",
				 $expect ), "$_");
		    if (($expect eq 'next heading or eof')
			&amp;&amp; !$entry-&gt;is_empty) {
			# lets assume we have missed the actual header line
			$entry-&gt;{'Closes'} = find_closes( $entry-&gt;{Changes} );
#		    print STDERR, Dumper($entry);
			push @{$self-&gt;{data}}, $entry;
			$entry = Parse::DebianChangelog::Entry-&gt;init();
			$entry-&gt;{Source} =
			    $entry-&gt;{Distribution} = $entry-&gt;{Urgency} =
			    $entry-&gt;{Urgency_LC} = 'unknown';
			$entry-&gt;{Version} = 'unknown'.($unknowncounter++);
			$entry-&gt;{Urgency_Comment} = '';
			$entry-&gt;{ERROR} = [ $file, $.,
					    __g( "found change data where expected %s",
						 $expect ), "$_" ];
		    }
		};
	    $entry-&gt;{'Changes'} .= (" \n" x $blanklines)." $_\n";
	    if (!$entry-&gt;{'Items'} || ($1 eq '*')) {
		$entry-&gt;{'Items'} ||= [];
		push @{$entry-&gt;{'Items'}}, "$_\n";
	    } else {
		$entry-&gt;{'Items'}[-1] .= (" \n" x $blanklines)." $_\n";
	    }
	    $blanklines = 0;
	    $expect = 'more change data or trailer';
	} elsif (!m/\S/) {
	    next if $expect eq 'start of change data'
		|| $expect eq 'next heading or eof';
	    $expect eq 'more change data or trailer'
		|| $self-&gt;_do_parse_error($file, $.,
					 __g( "found blank line where expected %s",
					      $expect ));
	    $blanklines++;
	} else {
	    $self-&gt;_do_parse_error($file, $., __g( "unrecognised line" ),
				   "$_");
	    ($expect eq 'start of change data'
		|| $expect eq 'more change data or trailer')
		&amp;&amp; do {
		    # lets assume change data if we expected it
		    $entry-&gt;{'Changes'} .= (" \n" x $blanklines)." $_\n";
		    if (!$entry-&gt;{'Items'}) {
			$entry-&gt;{'Items'} ||= [];
			push @{$entry-&gt;{'Items'}}, "$_\n";
		    } else {
			$entry-&gt;{'Items'}[-1] .= (" \n" x $blanklines)." $_\n";
		    }
		    $blanklines = 0;
		    $expect = 'more change data or trailer';
		    $entry-&gt;{ERROR} = [ $file, $., __g( "unrecognised line" ),
					"$_" ];
		};
	}
    }

    $expect eq 'next heading or eof'
	|| do {
	    $entry-&gt;{ERROR} = [ $file, $.,
				__g( "found eof where expected %s",
				     $expect ) ];
	    $self-&gt;_do_parse_error( @{$entry-&gt;{ERROR}} );
	};
    unless ($entry-&gt;is_empty) {
	$entry-&gt;{'Closes'} = find_closes( $entry-&gt;{Changes} );
	push @{$self-&gt;{data}}, $entry;
    }

    if ($self-&gt;{config}{infile}) {
	close $fh or do {
	    $self-&gt;_do_fatal_error( __g( "can't close file %s: %s",
					 $file, $! ));
	    return undef;
	};
    }

#    use Data::Dumper;
#    print Dumper( $self );

    return $self;
}

=pod

=head3 data

C&lt;data&gt; returns an array (if called in list context) or a reference
to an array of Parse::DebianChangelog::Entry objects which each
represent one entry of the changelog.

This is currently merely a placeholder to enable users to get to the
raw data, expect changes to this API in the near future.

This method supports the common output options described in
section L&lt;"COMMON OUTPUT OPTIONS"&gt;.

=cut

sub data {
    my ($self, $config) = @_;

    my $data = $self-&gt;{data};
    if ($config) {
	$self-&gt;{config}{DATA} = $config if $config;
	$data = $self-&gt;_data_range( $config ) or return undef;
    }
    return @$data if wantarray;
    return $data;
}

sub __sanity_check_range {
    my ( $data, $from, $to, $since, $until, $start, $end ) = @_;

    if (($$start || $$end) &amp;&amp; ($$from || $$since || $$to || $$until)) {
	warn( __g( "you can't combine 'count' or 'offset' with any other range option" ) ."\n");
	$$from = $$since = $$to = $$until = '';
    }
    if ($$from &amp;&amp; $$since) {
	warn( __g( "you can only specify one of 'from' and 'since'" ) ."\n");
	$$from = '';
    }
    if ($$to &amp;&amp; $$until) {
	warn( __g( "you can only specify one of 'to' and 'until'" ) ."\n");
	$$to = '';
    }
    if ($$since &amp;&amp; ($data-&gt;[0]{Version} eq $$since)) {
	warn( __g( "'since' option specifies most recent version" ) ."\n");
	$$since = '';
    }
    if ($$until &amp;&amp; ($data-&gt;[$#{$data}]{Version} eq $$until)) {
	warn( __g( "'until' option specifies oldest version" ) ."\n");
	$$until = '';
    }
    $$start = 0 if $$start &lt; 0;
    return if $$start &gt; $#$data;
    $$end = $#$data if $$end &gt; $#$data;
    return if $$end &lt; 0;
    $$end = $$start if $$end &lt; $$start;
    #TODO: compare versions
    return 1;
}

sub _data_range {
    my ($self, $config) = @_;

    my $data = $self-&gt;data or return undef;

    return [ @$data ] if $config-&gt;{all};

    my $since = $config-&gt;{since} || '';
    my $until = $config-&gt;{until} || '';
    my $from = $config-&gt;{from} || '';
    my $to = $config-&gt;{to} || '';
    my $count = $config-&gt;{count} || 0;
    my $offset = $config-&gt;{offset} || 0;

    return if $offset and not $count;
    if ($offset &gt; 0) {
	$offset -= ($count &lt; 0);
    } elsif ($offset &lt; 0) {
	$offset = $#$data + ($count &gt; 0) + $offset;
    } else {
	$offset = $#$data if $count &lt; 0;
    }
    my $start = my $end = $offset;
    $start += $count+1 if $count &lt; 0;
    $end += $count-1 if $count &gt; 0;

    return unless __sanity_check_range( $data, \$from, \$to,
					\$since, \$until,
					\$start, \$end );


    unless ($from or $to or $since or $until or $start or $end) {
	return [ @$data ] if $config-&gt;{default_all} and not $count;
	return [ $data-&gt;[0] ];
    }

    return [ @{$data}[$start .. $end] ] if $start or $end;

    my @result;

    my $include = 1;
    $include = 0 if $to or $until;
    foreach (@$data) {
	my $v = $_-&gt;{Version};
	$include = 1 if $v eq $to;
	last if $v eq $since;

	push @result, $_ if $include;

	$include = 1 if $v eq $until;
	last if $v eq $from;
    }

    return \@result;
}

=pod

=head3 dpkg

(and B&lt;dpkg_str&gt;)

C&lt;dpkg&gt; returns a hash (in list context) or a hash reference
(in scalar context) where the keys are field names and the values are
field values. The following fields are given:

=over 4

=item Source

package name (in the first entry)

=item Version

packages' version (from first entry)

=item Distribution

target distribution (from first entry)

=item Urgency

urgency (highest of all printed entries)

=item Maintainer

person that created the (first) entry

=item Date

date of the (first) entry

=item Closes

bugs closed by the entry/entries, sorted by bug number

=item Changes

content of the the entry/entries

=back

C&lt;dpkg_str&gt; returns a stringified version of this hash which should look
exactly like the output of L&lt;dpkg-parsechangelog(1)&gt;. The fields are
ordered like in the list above.

Both methods only support the common output options described in
section L&lt;"COMMON OUTPUT OPTIONS"&gt;.

=head3 dpkg_str

See L&lt;dpkg&gt;.

=cut

our ( %FIELDIMPS, %URGENCIES );
BEGIN {
    my $i=100;
    grep($FIELDIMPS{$_}=$i--,
	 qw(Source Version Distribution Urgency Maintainer Date Closes
	    Changes));
    $i=1;
    grep($URGENCIES{$_}=$i++,
	 qw(low medium high critical emergency));
}

sub dpkg {
    my ($self, $config) = @_;

    $self-&gt;{config}{DPKG} = $config if $config;

    $config = $self-&gt;{config}{DPKG} || {};
    my $data = $self-&gt;_data_range( $config ) or return undef;

    my %f;
    foreach my $field (qw( Urgency Source Version
			   Distribution Maintainer Date )) {
	$f{$field} = $data-&gt;[0]{$field};
    }

    $f{Changes} = get_dpkg_changes( $data-&gt;[0] );
    my %closes = map { $_ =&gt; 1 } @{$data-&gt;[0]{Closes}};

    my $first = 1; my $urg_comment = '';
    foreach my $entry (@$data) {
	$first = 0, next if $first;

	my $oldurg = $f{Urgency} || '';
	my $oldurgn = $URGENCIES{$f{Urgency}} || -1;
	my $newurg = $entry-&gt;{Urgency_LC} || '';
	my $newurgn = $URGENCIES{$entry-&gt;{Urgency_LC}} || -1;
	$f{Urgency} = ($newurgn &gt; $oldurgn) ? $newurg : $oldurg;
	$urg_comment .= $entry-&gt;{Urgency_Comment};

	$f{Changes} .= "\n .".get_dpkg_changes( $entry );
	$closes{ $_ } = 1 for @{$entry-&gt;{Closes}};
    }

    $f{Closes} = join " ", sort { $a &lt;=&gt; $b } keys %closes;
    $f{Urgency} .= $urg_comment;

    return %f if wantarray;
    return \%f;
}

sub dpkg_str {
    return data2rfc822( scalar dpkg(@_), \%FIELDIMPS );
}

=pod

=head3 rfc822

(and B&lt;rfc822_str&gt;)

C&lt;rfc822&gt; returns an array of hashes (in list context) or a reference
to this array (in scalar context) where each hash represents one entry
in the changelog. For the format of such a hash see the description
of the L&lt;"dpkg"&gt; method (while ignoring the remarks about which
values are taken from the first entry).

C&lt;rfc822_str&gt; returns a stringified version of this hash which looks
similar to the output of dpkg-parsechangelog but instead of one
stanza the output contains one stanza for each entry.

Both methods only support the common output options described in
section L&lt;"COMMON OUTPUT OPTIONS"&gt;.

=head3 rfc822_str

See L&lt;rfc822&gt;.

=cut

sub rfc822 {
    my ($self, $config) = @_;

    $self-&gt;{config}{RFC822} = $config if $config;

    $config = $self-&gt;{config}{RFC822} || {};
    my $data = $self-&gt;_data_range( $config ) or return undef;
    my @out_data;

    foreach my $entry (@$data) {
	my %f;
	foreach my $field (qw( Urgency Source Version
			   Distribution Maintainer Date )) {
	    $f{$field} = $entry-&gt;{$field};
	}

	$f{Urgency} .= $entry-&gt;{Urgency_Comment};
	$f{Changes} = get_dpkg_changes( $entry );
	$f{Closes} = join " ", sort { $a &lt;=&gt; $b } @{$entry-&gt;{Closes}};
	push @out_data, \%f;
    }

    return @out_data if wantarray;
    return \@out_data;
}

sub rfc822_str {
    return data2rfc822_mult( scalar rfc822(@_), \%FIELDIMPS );
}

sub __version2id {
    my $version = shift;
    $version =~ s/[^\w.:-]/_/go;
    return "version$version";
}

=pod

=head3 xml

(and B&lt;xml_str&gt;)

C&lt;xml&gt; converts the changelog to some free-form (i.e. there is neither
a DTD or a schema for it) XML.

The method C&lt;xml_str&gt; is an alias for C&lt;xml&gt;.

Both methods support the common output options described in
section L&lt;"COMMON OUTPUT OPTIONS"&gt; and additionally the following
configuration options (as usual to give
in a hash reference as parameter to the method call):

=over 4

=item outfile

directly write the output to the file specified

=back

=head3 xml_str

See L&lt;xml&gt;.

=cut

sub xml {
    my ($self, $config) = @_;

    $self-&gt;{config}{XML} = $config if $config;
    $config = $self-&gt;{config}{XML} || {};
    $config-&gt;{default_all} = 1 unless exists $config-&gt;{all};
    my $data = $self-&gt;_data_range( $config ) or return undef;
    my %out_data;
    $out_data{Entry} = [];

    require XML::Simple;
    import XML::Simple qw( :strict );

    foreach my $entry (@$data) {
	my %f;
	foreach my $field (qw( Urgency Source Version
			       Distribution Closes )) {
	    $f{$field} = $entry-&gt;{$field};
	}
	foreach my $field (qw( Maintainer Changes )) {
	    $f{$field} = [ $entry-&gt;{$field} ];
	}

	$f{Urgency} .= $entry-&gt;{Urgency_Comment};
	$f{Date} = { timestamp =&gt; $entry-&gt;{Timestamp},
		     content =&gt; $entry-&gt;{Date} };
	push @{$out_data{Entry}}, \%f;
    }

    my $xml_str;
    my %xml_opts = ( SuppressEmpty =&gt; 1, KeyAttr =&gt; {},
		     RootName =&gt; 'Changelog' );
    $xml_str = XMLout( \%out_data, %xml_opts );
    if ($config-&gt;{outfile}) {
	open my $fh, '&gt;', $config-&gt;{outfile} or return undef;
	flock $fh, LOCK_EX or return undef;

	print $fh $xml_str;

	close $fh or return undef;
    }

    return $xml_str;
}

sub xml_str {
    return xml(@_);
}

=pod

=head3 html

(and B&lt;html_str&gt;)

C&lt;html&gt; converts the changelog to a HTML file with some nice features
such as a quick-link bar with direct links to every entry. The HTML
is generated with the help of HTML::Template. If you want to change
the output you should use the default template provided with this module
as a base and read the documentation of HTML::Template to understand
how to edit it.

The method C&lt;html_str&gt; is an alias for C&lt;html&gt;.

Both methods support the common output options described in
section L&lt;"COMMON OUTPUT OPTIONS"&gt; and additionally the following
configuration options (as usual to give
in a hash reference as parameter to the method call):

=over 4

=item outfile

directly write the output to the file specified

=item template

template file to use, defaults to tmpl/default.tmpl, so you
most likely want to override that.
NOTE: The plan is to provide a configuration file for the module
later to be able to use sane defaults here.

=item style

path to the CSS stylesheet to use (a default might be specified
in the template and will be honoured, see the default template
for an example)

=item print_style

path to the CSS stylesheet to use for printing (see the notes for
C&lt;style&gt; about default values)

=back

=head3 html_str

See L&lt;html&gt;.

=cut

sub html {
    my ($self, $config) = @_;

    $self-&gt;{config}{HTML} = $config if $config;
    $config = $self-&gt;{config}{HTML} || {};
    $config-&gt;{default_all} = 1 unless exists $config-&gt;{all};
    my $data = $self-&gt;_data_range( $config ) or return undef;

    require CGI;
    import CGI qw( -no_xhtml -no_debug );
    require HTML::Template;

    my $template = HTML::Template-&gt;new(filename =&gt; $config-&gt;{template}
				       || 'tmpl/default.tmpl',
				       die_on_bad_params =&gt; 0);
    $template-&gt;param( MODULE_NAME =&gt; ref($self),
		      MODULE_VERSION =&gt; $VERSION,
		      GENERATED_DATE =&gt; gmtime()." UTC",
		      SOURCE_NEWEST =&gt; $data-&gt;[0]{Source},
		      VERSION_NEWEST =&gt; $data-&gt;[0]{Version},
		      MAINTAINER_NEWEST =&gt; $data-&gt;[0]{Maintainer},
		      );

    $template-&gt;param( CSS_FILE_SCREEN =&gt; $config-&gt;{style} )
	if $config-&gt;{style};
    $template-&gt;param( CSS_FILE_PRINT =&gt; $config-&gt;{print_style} )
	if $config-&gt;{print_style};

    my $cgi = new CGI;
    $cgi-&gt;autoEscape(0);

    my %navigation;
    my $last_year;
    foreach my $entry (@$data) {
	my $year = $last_year; # try to deal gracefully with unparsable dates
	if (defined $entry-&gt;{Timestamp}) {
	    $year = (gmtime($entry-&gt;{Timestamp}))[5] + 1900;
	    $last_year = $year;
	}

	$year ||= (($entry-&gt;{Date} =~ /\s(\d{4})\s/) ? $1 : (gmtime)[5] + 1900);

	$navigation{$year}{NAV_VERSIONS} ||= [];
	$navigation{$year}{NAV_YEAR} ||= $year;

	$entry-&gt;{Maintainer} ||= 'unknown';
	$entry-&gt;{Date} ||= 'unknown';
	push @{$navigation{$year}{NAV_VERSIONS}},
	       { NAV_VERSION_ID =&gt; __version2id($entry-&gt;{Version}),
		 NAV_VERSION =&gt; $entry-&gt;{Version},
		 NAV_MAINTAINER =&gt; $entry-&gt;{Maintainer},
		 NAV_DATE =&gt; $entry-&gt;{Date} };
    }
    my @nav_years;
    foreach my $y (reverse sort keys %navigation) {
	push @nav_years, $navigation{$y};
    }
    $template-&gt;param( OLDFORMAT =&gt; (($self-&gt;{oldformat}||'') ne ''),
		      NAV_YEARS =&gt; \@nav_years );


    my %years;
    $last_year = undef;
    foreach my $entry (@$data) {
	my $year = $last_year; # try to deal gracefully with unparsable dates
	if (defined $entry-&gt;{Timestamp}) {
	    $year = (gmtime($entry-&gt;{Timestamp}))[5] + 1900;
	}
	$year ||= (($entry-&gt;{Date} =~ /\s(\d{4})\s/) ? $1 : (gmtime)[5] + 1900);

	if (!$last_year || ($year &lt; $last_year)) {
	    $last_year = $year;
	}

	$years{$last_year}{CONTENT_VERSIONS} ||= [];
	$years{$last_year}{CONTENT_YEAR} ||= $last_year;

	my $text = $self-&gt;apply_filters( 'html::changes',
					 $entry-&gt;{Changes}, $cgi );

	(my $maint_name = $entry-&gt;{Maintainer} ) =~ s|&lt;([a-zA-Z0-9_\+\-\.]+\@([a-zA-Z0-9][\w\.+\-]+\.[a-zA-Z]{2,}))&gt;||o;
	my $maint_mail = $1;

	my $parse_error;
	$parse_error = $cgi-&gt;p( { -class=&gt;'parse_error' },
				"(There has been a parse error in the entry above, if some values don't make sense please check the original changelog)" )
	    if $entry-&gt;{ERROR};

	push @{$years{$last_year}{CONTENT_VERSIONS}}, {
	    CONTENT_VERSION =&gt; $entry-&gt;{Version},
	    CONTENT_VERSION_ID =&gt; __version2id($entry-&gt;{Version}),
	    CONTENT_URGENCY =&gt; $entry-&gt;{Urgency}.$entry-&gt;{Urgency_Comment},
	    CONTENT_URGENCY_NORM =&gt; $entry-&gt;{Urgency_LC},
	    CONTENT_DISTRIBUTION =&gt; $entry-&gt;{Distribution},
	    CONTENT_DISTRIBUTION_NORM =&gt; lc($entry-&gt;{Distribution}),
	    CONTENT_SOURCE =&gt; $entry-&gt;{Source},
	    CONTENT_CHANGES =&gt; $text,
	    CONTENT_CHANGES_UNFILTERED =&gt; $entry-&gt;{Changes},
	    CONTENT_DATE =&gt; $entry-&gt;{Date},
	    CONTENT_MAINTAINER_NAME =&gt; $maint_name,
	    CONTENT_MAINTAINER_EMAIL =&gt; $maint_mail,
	    CONTENT_PARSE_ERROR =&gt; $parse_error,
	};
    }
    my @content_years;
    foreach my $y (reverse sort keys %years) {
	push @content_years, $years{$y};
    }
    $template-&gt;param( OLDFORMAT_CHANGES =&gt; $self-&gt;{oldformat},
		      CONTENT_YEARS =&gt; \@content_years );

    my $html_str = $template-&gt;output;

    if ($config-&gt;{outfile}) {
	open my $fh, '&gt;', $config-&gt;{outfile} or return undef;
	flock $fh, LOCK_EX or return undef;

	print $fh $html_str;

	close $fh or return undef;
    }

    return $html_str;
}

sub html_str {
    return html(@_);
}


=pod

=head3 init_filters

not yet documented

=cut

sub init_filters {
    my ($self) = @_;

    require Parse::DebianChangelog::ChangesFilters;

    $self-&gt;{filters} = {};

    $self-&gt;{filters}{'html::changes'} =
	[ @Parse::DebianChangelog::ChangesFilters::all_filters ];
}

=pod

=head3 apply_filters

not yet documented

=cut

sub apply_filters {
    my ($self, $filter_class, $text, $data) = @_;

    foreach my $f (@{$self-&gt;{filters}{$filter_class}}) {
	$text = &amp;$f( $text, $data );
    }
    return $text;
}

=pod

=head3 add_filter, delete_filter, replace_filter

not yet documented

=cut

sub add_filter {
    my ($self, $filter_class, $filter, $pos) = @_;

    $self-&gt;{filters}{$filter_class} ||= [];
    unless ($pos) {
	push @{$self-&gt;{filters}{$filter_class}}, $filter;
    } elsif ($pos == 1) {
	unshift @{$self-&gt;{filters}{$filter_class}}, $filter;
    } elsif ($pos &gt; 1) {
	my $length = @{$self-&gt;{filters}{$filter_class}};
	$self-&gt;{filters}{$filter_class} =
	    [ @{$self-&gt;{filters}{$filter_class}[0 .. ($pos-2)]}, $filter,
	      @{$self-&gt;{filters}{$filter_class}[($pos-1) .. ($length-1)]} ];
    }

    return $self;
}

sub delete_filter {
    my ($self, $filter_class, $filter) = @_;

    my $pos;
    unless (ref $filter) {
	$pos = $filter;

	return delete $self-&gt;{filters}{$filter_class}[$pos];
    }

    $self-&gt;{filters}{$filter_class} ||= [];
    my @deleted;
    for my $i (0 .. $#{$self-&gt;{filters}{$filter_class}}) {
	push @deleted, delete $self-&gt;{filters}{$filter_class}[$i]
	    if $self-&gt;{filters}{$filter_class}[$i] == $filter;
    }

    return @deleted;
}

sub replace_filter {
    my ($self, $filter_class, $filter, @new_filters) = @_;

    my @pos;
    unless (ref $filter) {
	$pos[0] = $filter;
    } else {
	$self-&gt;{filters}{$filter_class} ||= [];
	for my $i (0 .. $#{$self-&gt;{filters}{$filter_class}}) {
	    push @pos, $i
		if $self-&gt;{filters}{$filter_class}[$i] == $filter;
	}
    }

    foreach my $p (@pos) {
	$self-&gt;delete_filter( $filter_class, $p );

	foreach my $f (@new_filters) {
	    $self-&gt;add_filter( $filter_class, $f, $p++);
	}
    }

    return $self;
}

1;
__END__

=head1 COMMON OUTPUT OPTIONS

The following options are supported by all output methods,
all take a version number as value:

=over 4

=item since

Causes changelog information from all versions strictly
later than B&lt;version&gt; to be used.

(works exactly like the C&lt;-v&gt; option of dpkg-parsechangelog).

=item until

Causes changelog information from all versions strictly
earlier than B&lt;version&gt; to be used.

=item from

Similar to C&lt;since&gt; but also includes the information for the
specified B&lt;version&gt; itself.

=item to

Similar to C&lt;until&gt; but also includes the information for the
specified B&lt;version&gt; itself.

=back

The following options also supported by all output methods but
don't take version numbers as values:

=over 4

=item all

If set to a true value, all entries of the changelog are returned,
this overrides all other options. While the XML and HTML formats
default to all == true, this does of course not overwrite other
options unless it is set explicitly with the call.

=item count

Expects a signed integer as value. Returns C&lt;value&gt; entries from the
top of the changelog if set to a positive integer, and C&lt;abs(value)&gt;
entries from the tail if set to a negative integer.

=item offset

Expects a signed integer as value. Changes the starting point for
C&lt;count&gt;, either counted from the top (positive integer) or from
the tail (negative integer). C&lt;offset&gt; has no effect if C&lt;count&gt;
wasn't given as well.

=back

Some examples for the above options. Imagine an example changelog with
entries for the versions 1.2, 1.3, 2.0, 2.1, 2.2, 3.0 and 3.1.

            Call                               Included entries
 C&lt;E&lt;lt&gt;formatE&lt;gt&gt;({ since =E&lt;gt&gt; '2.0' })&gt;  3.1, 3.0, 2.2
 C&lt;E&lt;lt&gt;formatE&lt;gt&gt;({ until =E&lt;gt&gt; '2.0' })&gt;  1.3, 1.2
 C&lt;E&lt;lt&gt;formatE&lt;gt&gt;({ from =E&lt;gt&gt; '2.0' })&gt;   3.1, 3.0, 2.2, 2.1, 2.0
 C&lt;E&lt;lt&gt;formatE&lt;gt&gt;({ to =E&lt;gt&gt; '2.0' })&gt;     2.0, 1.3, 1.2
 C&lt;E&lt;lt&gt;formatE&lt;gt&gt;({ count =E&lt;gt&gt; 2 }&gt;&gt;      3.1, 3.0
 C&lt;E&lt;lt&gt;formatE&lt;gt&gt;({ count =E&lt;gt&gt; -2 }&gt;&gt;     1.3, 1.2
 C&lt;E&lt;lt&gt;formatE&lt;gt&gt;({ count =E&lt;gt&gt; 3,
		      offset=E&lt;gt&gt; 2 }&gt;&gt;      2.2, 2.1, 2.0
 C&lt;E&lt;lt&gt;formatE&lt;gt&gt;({ count =E&lt;gt&gt; 2,
		      offset=E&lt;gt&gt; -3 }&gt;&gt;     2.0, 1.3
 C&lt;E&lt;lt&gt;formatE&lt;gt&gt;({ count =E&lt;gt&gt; -2,
		      offset=E&lt;gt&gt; 3 }&gt;&gt;      3.0, 2.2
 C&lt;E&lt;lt&gt;formatE&lt;gt&gt;({ count =E&lt;gt&gt; -2,
		      offset=E&lt;gt&gt; -3 }&gt;&gt;     2.2, 2.1

Any combination of one option of C&lt;since&gt; and C&lt;from&gt; and one of
C&lt;until&gt; and C&lt;to&gt; returns the intersection of the two results
with only one of the options specified.

=head1 SEE ALSO

Parse::DebianChangelog::Entry, Parse::DebianChangelog::ChangesFilters

Description of the Debian changelog format in the Debian policy:
L&lt;http://www.debian.org/doc/debian-policy/ch-source.html#s-dpkgchangelog&gt;.

=head1 AUTHOR

Frank Lichtenheld, E&lt;lt&gt;frank@lichtenheld.deE&lt;gt&gt;

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2005 by Frank Lichtenheld

This program is free software; you can redistribute it and/or modify
it 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, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

=cut
</pre></body></html>