<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;"># Copyright Â© 2005, 2007 Frank Lichtenheld &lt;frank@lichtenheld.de&gt;
# Copyright Â© 2009       RaphaÃ«l Hertzog &lt;hertzog@debian.org&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, see &lt;https://www.gnu.org/licenses/&gt;.

=encoding utf8

=head1 NAME

Dpkg::Changelog - base class to implement a changelog parser

=head1 DESCRIPTION

Dpkg::Changelog is a class representing a changelog file
as an array of changelog entries (L&lt;Dpkg::Changelog::Entry&gt;).
By deriving this class and implementing its parse() method, you
add the ability to fill this object with changelog entries.

=cut

package Dpkg::Changelog 2.00;

use strict;
use warnings;

use Carp;

use Dpkg::Gettext;
use Dpkg::ErrorHandling qw(:DEFAULT report REPORT_WARN);
use Dpkg::Control;
use Dpkg::Control::Changelog;
use Dpkg::Control::Fields;
use Dpkg::Index;
use Dpkg::Version;
use Dpkg::Vendor qw(run_vendor_hook);

use parent qw(Dpkg::Interface::Storable);

use overload
    '@{}' =&gt; sub { return $_[0]-&gt;{data} };

=head1 METHODS

=over 4

=item $c = Dpkg::Changelog-&gt;new(%options)

Creates a new changelog object.

=cut

sub new {
    my ($this, %opts) = @_;
    my $class = ref($this) || $this;
    my $self = {
	verbose =&gt; 1,
	parse_errors =&gt; []
    };
    bless $self, $class;
    $self-&gt;set_options(%opts);
    return $self;
}

=item $c-&gt;set_options(%opts)

Change the value of some options. "verbose" (defaults to 1) defines
whether parse errors are displayed as warnings by default. "reportfile"
is a string to use instead of the name of the file parsed, in particular
in error messages. "range" defines the range of entries that we want to
parse, the parser will stop as soon as it has parsed enough data to
satisfy $c-&gt;get_range($opts{range}).

=cut

sub set_options {
    my ($self, %opts) = @_;
    $self-&gt;{$_} = $opts{$_} foreach keys %opts;
}

=item $count = $c-&gt;parse($fh, $description)

Read the filehandle and parse a changelog in it. The data in the object is
reset before parsing new data.

Returns the number of changelog entries that have been parsed with success.

This method needs to be implemented by one of the specialized changelog
format subclasses.

=item $count = $c-&gt;load($filename)

Parse $filename contents for a changelog.

Returns the number of changelog entries that have been parsed with success.

=item $c-&gt;reset_parse_errors()

Can be used to delete all information about errors occurred during
previous parse() runs.

=cut

sub reset_parse_errors {
    my $self = shift;
    $self-&gt;{parse_errors} = [];
}

=item $c-&gt;parse_error($file, $line_nr, $error, [$line])

Record a new parse error in $file at line $line_nr. The error message is
specified with $error and a copy of the line can be recorded in $line.

=cut

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

    push @{$self-&gt;{parse_errors}}, [ $file, $line_nr, $error, $line ];

    if ($self-&gt;{verbose}) {
	if ($line) {
	    warning("%20s(l$line_nr): $error\nLINE: $line", $file);
	} else {
	    warning("%20s(l$line_nr): $error", $file);
	}
    }
}

=item $c-&gt;get_parse_errors()

Returns all error messages from the last parse() 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.

a string describing the origin of the data (a filename usually). If the
reportfile configuration option was given, its value will be used instead.

=item 2.

the line number where the error occurred

=item 3.

an error description

=item 4.

the original line

=back

=cut

sub get_parse_errors {
    my $self = shift;

    if (wantarray) {
	return @{$self-&gt;{parse_errors}};
    } else {
	my $res = '';
	foreach my $e (@{$self-&gt;{parse_errors}}) {
	    if ($e-&gt;[3]) {
		$res .= report(REPORT_WARN, g_("%s(l%s): %s\nLINE: %s"), @$e);
	    } else {
		$res .= report(REPORT_WARN, g_('%s(l%s): %s'), @$e);
	    }
	}
	return $res;
    }
}

=item $c-&gt;set_unparsed_tail($tail)

Add a string representing unparsed lines after the changelog entries.
Use undef as $tail to remove the unparsed lines currently set.

=item $c-&gt;get_unparsed_tail()

Return a string representing the unparsed lines after the changelog
entries. Returns undef if there's no such thing.

=cut

sub set_unparsed_tail {
    my ($self, $tail) = @_;
    $self-&gt;{unparsed_tail} = $tail;
}

sub get_unparsed_tail {
    my $self = shift;
    return $self-&gt;{unparsed_tail};
}

=item @{$c}

Returns all the L&lt;Dpkg::Changelog::Entry&gt; objects contained in this changelog
in the order in which they have been parsed.

=item $c-&gt;get_range($range)

Returns an array (if called in list context) or a reference to an array of
L&lt;Dpkg::Changelog::Entry&gt; objects which each represent one entry of the
changelog. $range is a hash reference describing the range of entries
to return. See section L&lt;/RANGE SELECTION&gt;.

=cut

sub _sanitize_range {
    my ($self, $r) = @_;
    my $data = $self-&gt;{data};

    if (defined($r-&gt;{offset}) and not defined($r-&gt;{count})) {
	warning(g_("'offset' without 'count' has no effect")) if $self-&gt;{verbose};
	delete $r-&gt;{offset};
    }

    ## no critic (ControlStructures::ProhibitUntilBlocks)
    if ((defined($r-&gt;{count}) || defined($r-&gt;{offset})) &amp;&amp;
        (defined($r-&gt;{from}) || defined($r-&gt;{since}) ||
	 defined($r-&gt;{to}) || defined($r-&gt;{until})))
    {
	warning(g_("you can't combine 'count' or 'offset' with any other " .
		   'range option')) if $self-&gt;{verbose};
	delete $r-&gt;{from};
	delete $r-&gt;{since};
	delete $r-&gt;{to};
	delete $r-&gt;{until};
    }
    if (defined($r-&gt;{from}) &amp;&amp; defined($r-&gt;{since})) {
	warning(g_("you can only specify one of 'from' and 'since', using " .
		   "'since'")) if $self-&gt;{verbose};
	delete $r-&gt;{from};
    }
    if (defined($r-&gt;{to}) &amp;&amp; defined($r-&gt;{until})) {
	warning(g_("you can only specify one of 'to' and 'until', using " .
		   "'until'")) if $self-&gt;{verbose};
	delete $r-&gt;{to};
    }

    # Handle non-existing versions
    my (%versions, @versions);
    foreach my $entry (@{$data}) {
        my $version = $entry-&gt;get_version();
        next unless defined $version;
        $versions{$version-&gt;as_string()} = 1;
        push @versions, $version-&gt;as_string();
    }
    if ((defined($r-&gt;{since}) and not exists $versions{$r-&gt;{since}})) {
        warning(g_("'%s' option specifies non-existing version '%s'"), 'since', $r-&gt;{since});
        warning(g_('use newest entry that is earlier than the one specified'));
        foreach my $v (@versions) {
            if (version_compare_relation($v, REL_LT, $r-&gt;{since})) {
                $r-&gt;{since} = $v;
                last;
            }
        }
        if (not exists $versions{$r-&gt;{since}}) {
            # No version was earlier, include all
            warning(g_('none found, starting from the oldest entry'));
            delete $r-&gt;{since};
            $r-&gt;{from} = $versions[-1];
        }
    }
    if ((defined($r-&gt;{from}) and not exists $versions{$r-&gt;{from}})) {
        warning(g_("'%s' option specifies non-existing version '%s'"), 'from', $r-&gt;{from});
        warning(g_('use oldest entry that is later than the one specified'));
        my $oldest;
        foreach my $v (@versions) {
            if (version_compare_relation($v, REL_GT, $r-&gt;{from})) {
                $oldest = $v;
            }
        }
        if (defined($oldest)) {
            $r-&gt;{from} = $oldest;
        } else {
            warning(g_("no such entry found, ignoring '%s' parameter '%s'"), 'from', $r-&gt;{from});
            delete $r-&gt;{from}; # No version was oldest
        }
    }
    if (defined($r-&gt;{until}) and not exists $versions{$r-&gt;{until}}) {
        warning(g_("'%s' option specifies non-existing version '%s'"), 'until', $r-&gt;{until});
        warning(g_('use oldest entry that is later than the one specified'));
        my $oldest;
        foreach my $v (@versions) {
            if (version_compare_relation($v, REL_GT, $r-&gt;{until})) {
                $oldest = $v;
            }
        }
        if (defined($oldest)) {
            $r-&gt;{until} = $oldest;
        } else {
            warning(g_("no such entry found, ignoring '%s' parameter '%s'"), 'until', $r-&gt;{until});
            delete $r-&gt;{until}; # No version was oldest
        }
    }
    if (defined($r-&gt;{to}) and not exists $versions{$r-&gt;{to}}) {
        warning(g_("'%s' option specifies non-existing version '%s'"), 'to', $r-&gt;{to});
        warning(g_('use newest entry that is earlier than the one specified'));
        foreach my $v (@versions) {
            if (version_compare_relation($v, REL_LT, $r-&gt;{to})) {
                $r-&gt;{to} = $v;
                last;
            }
        }
        if (not exists $versions{$r-&gt;{to}}) {
            # No version was earlier
            warning(g_("no such entry found, ignoring '%s' parameter '%s'"), 'to', $r-&gt;{to});
            delete $r-&gt;{to};
        }
    }

    if (defined($r-&gt;{since}) and $data-&gt;[0]-&gt;get_version() eq $r-&gt;{since}) {
	warning(g_("'since' option specifies most recent version '%s', ignoring"), $r-&gt;{since});
	delete $r-&gt;{since};
    }
    if (defined($r-&gt;{until}) and $data-&gt;[-1]-&gt;get_version() eq $r-&gt;{until}) {
	warning(g_("'until' option specifies oldest version '%s', ignoring"), $r-&gt;{until});
	delete $r-&gt;{until};
    }
    ## use critic
}

sub get_range {
    my ($self, $range) = @_;
    $range //= {};
    my $res = $self-&gt;_data_range($range);
    return unless defined $res;
    if (wantarray) {
        return reverse @{$res} if $range-&gt;{reverse};
        return @{$res};
    } else {
	return $res;
    }
}

sub _is_full_range {
    my ($self, $range) = @_;

    return 1 if $range-&gt;{all};

    # If no range delimiter is specified, we want everything.
    foreach my $delim (qw(since until from to count offset)) {
        return 0 if exists $range-&gt;{$delim};
    }

    return 1;
}

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

    my $data = $self-&gt;{data} or return;

    return [ @$data ] if $self-&gt;_is_full_range($range);

    $self-&gt;_sanitize_range($range);

    my ($start, $end);
    if (defined($range-&gt;{count})) {
	my $offset = $range-&gt;{offset} // 0;
	my $count = $range-&gt;{count};
	# Convert count/offset in start/end
	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;
	}
	$start = $end = $offset;
	$start += $count+1 if $count &lt; 0;
	$end += $count-1 if $count &gt; 0;
	# Check limits
	$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;
	return [ @{$data}[$start .. $end] ];
    }

    ## no critic (ControlStructures::ProhibitUntilBlocks)
    my @result;
    my $include = 1;
    $include = 0 if defined($range-&gt;{to}) or defined($range-&gt;{until});
    foreach my $entry (@{$data}) {
	my $v = $entry-&gt;get_version();
	$include = 1 if defined($range-&gt;{to}) and $v eq $range-&gt;{to};
	last if defined($range-&gt;{since}) and $v eq $range-&gt;{since};

	push @result, $entry if $include;

	$include = 1 if defined($range-&gt;{until}) and $v eq $range-&gt;{until};
	last if defined($range-&gt;{from}) and $v eq $range-&gt;{from};
    }
    ## use critic

    return \@result if scalar(@result);
    return;
}

=item $c-&gt;abort_early()

Returns true if enough data have been parsed to be able to return all
entries selected by the range set at creation (or with set_options).

=cut

sub abort_early {
    my $self = shift;

    my $data = $self-&gt;{data} or return;
    my $r = $self-&gt;{range} or return;
    my $count = $r-&gt;{count} // 0;
    my $offset = $r-&gt;{offset} // 0;

    return if $self-&gt;_is_full_range($r);
    return if $offset &lt; 0 or $count &lt; 0;
    if (defined($r-&gt;{count})) {
	if ($offset &gt; 0) {
	    $offset -= ($count &lt; 0);
	}
	my $start = my $end = $offset;
	$end += $count-1 if $count &gt; 0;
        return $start &lt; @{$data} &gt; $end;
    }

    return unless defined($r-&gt;{since}) or defined($r-&gt;{from});
    foreach my $entry (@{$data}) {
	my $v = $entry-&gt;get_version();
	return 1 if defined($r-&gt;{since}) and $v eq $r-&gt;{since};
	return 1 if defined($r-&gt;{from}) and $v eq $r-&gt;{from};
    }

    return;
}

=item $str = $c-&gt;output()

=item "$c"

Returns a string representation of the changelog (it's a concatenation of
the string representation of the individual changelog entries).

=item $c-&gt;output($fh)

Output the changelog to the given filehandle.

=cut

sub output {
    my ($self, $fh) = @_;
    my $str = '';
    foreach my $entry (@{$self}) {
	my $text = $entry-&gt;output();
	print { $fh } $text if defined $fh;
	$str .= $text if defined wantarray;
    }
    my $text = $self-&gt;get_unparsed_tail();
    if (defined $text) {
	print { $fh } $text if defined $fh;
	$str .= $text if defined wantarray;
    }
    return $str;
}

=item $c-&gt;save($filename)

Save the changelog in the given file.

=cut

our ( @URGENCIES, %URGENCIES );
BEGIN {
    @URGENCIES = qw(
        low
        medium
        high
        critical
        emergency
    );
    my $i = 1;
    %URGENCIES = map { $_ =&gt; $i++ } @URGENCIES;
}

sub _format_dpkg {
    my ($self, $range) = @_;

    my @data = $self-&gt;get_range($range) or return;
    my $src = shift @data;

    my $c = Dpkg::Control::Changelog-&gt;new();
    $c-&gt;{Urgency} = $src-&gt;get_urgency() || 'unknown';
    $c-&gt;{Source} = $src-&gt;get_source() || 'unknown';
    $c-&gt;{Version} = $src-&gt;get_version() // 'unknown';
    $c-&gt;{Distribution} = join ' ', $src-&gt;get_distributions();
    $c-&gt;{Maintainer} = $src-&gt;get_maintainer() // '';
    $c-&gt;{Date} = $src-&gt;get_timestamp() // '';
    $c-&gt;{Timestamp} = $src-&gt;get_timepiece &amp;&amp; $src-&gt;get_timepiece-&gt;epoch // '';
    $c-&gt;{Changes} = $src-&gt;get_dpkg_changes();

    # handle optional fields
    my $opts = $src-&gt;get_optional_fields();
    my %closes;
    foreach my $f (keys %{$opts}) {
        if ($f eq 'Urgency') {
            # Already handled.
        } elsif ($f eq 'Closes') {
	    $closes{$_} = 1 foreach (split(/\s+/, $opts-&gt;{Closes}));
	} else {
            field_transfer_single($opts, $c, $f);
	}
    }

    foreach my $bin (@data) {
        my $oldurg = $c-&gt;{Urgency} // '';
        my $oldurgn = $URGENCIES{$c-&gt;{Urgency}} // -1;
	my $newurg = $bin-&gt;get_urgency() // '';
	my $newurgn = $URGENCIES{$newurg} // -1;
        $c-&gt;{Urgency} = ($newurgn &gt; $oldurgn) ? $newurg : $oldurg;
        $c-&gt;{Changes} .= "\n" . $bin-&gt;get_dpkg_changes();

	# handle optional fields
	$opts = $bin-&gt;get_optional_fields();
        foreach my $f (keys %{$opts}) {
            if ($f eq 'Closes') {
		$closes{$_} = 1 foreach (split(/\s+/, $opts-&gt;{Closes}));
            } elsif (not exists $c-&gt;{$f}) {
                # Don't overwrite an existing field
                field_transfer_single($opts, $c, $f);
	    }
	}
    }

    if (scalar keys %closes) {
        $c-&gt;{Closes} = join ' ', sort { $a &lt;=&gt; $b } keys %closes;
    }
    run_vendor_hook('post-process-changelog-entry', $c);

    return $c;
}

sub _format_rfc822 {
    my ($self, $range) = @_;

    my @data = $self-&gt;get_range($range) or return;
    my @ctrl;

    foreach my $entry (@data) {
        my $c = Dpkg::Control::Changelog-&gt;new();
        $c-&gt;{Urgency} = $entry-&gt;get_urgency() || 'unknown';
        $c-&gt;{Source} = $entry-&gt;get_source() || 'unknown';
        $c-&gt;{Version} = $entry-&gt;get_version() // 'unknown';
        $c-&gt;{Distribution} = join ' ', $entry-&gt;get_distributions();
        $c-&gt;{Maintainer} = $entry-&gt;get_maintainer() // '';
        $c-&gt;{Date} = $entry-&gt;get_timestamp() // '';
        $c-&gt;{Timestamp} = $entry-&gt;get_timepiece &amp;&amp; $entry-&gt;get_timepiece-&gt;epoch // '';
        $c-&gt;{Changes} = $entry-&gt;get_dpkg_changes();

	# handle optional fields
	my $opts = $entry-&gt;get_optional_fields();
        foreach my $f (keys %{$opts}) {
            field_transfer_single($opts, $c, $f) unless exists $c-&gt;{$f};
	}

        run_vendor_hook('post-process-changelog-entry', $c);

        push @ctrl, $c;
    }

    return @ctrl;
}

=item $control = $c-&gt;format_range($format, $range)

Formats the changelog into L&lt;Dpkg::Control::Changelog&gt; objects representing
the entries selected by the optional range specifier (see L&lt;/RANGE SELECTION&gt;
for details). In scalar context returns a L&lt;Dpkg::Index&gt; object containing
the selected entries, in list context returns an array of
L&lt;Dpkg::Control::Changelog&gt; objects.

With format B&lt;dpkg&gt; the returned L&lt;Dpkg::Control::Changelog&gt; object is
coalesced from the entries in the changelog that are part of the range
requested, with the fields described below, but considering that
"selected entry" means the first entry of the selected range.

With format B&lt;rfc822&gt; each returned L&lt;Dpkg::Control::Changelog&gt; objects
represents one entry in the changelog that is part of the range requested,
with the fields described below, but considering that "selected entry"
means for each entry.

The different formats return undef if no entries are matched. The following
fields are contained in the object(s) returned:

=over 4

=item Source

package name (selected entry)

=item Version

packages' version (selected entry)

=item Distribution

target distribution (selected entry)

=item Urgency

urgency (highest of all entries in range)

=item Maintainer

person that created the (selected) entry

=item Date

date of the (selected) entry

=item Timestamp

date of the (selected) entry as a timestamp in seconds since the epoch

=item Closes

bugs closed by the (selected) entry/entries, sorted by bug number

=item Changes

content of the (selected) entry/entries

=back

=cut

sub format_range {
    my ($self, $format, $range) = @_;

    my @ctrl;

    if ($format eq 'dpkg') {
        @ctrl = $self-&gt;_format_dpkg($range);
    } elsif ($format eq 'rfc822') {
        @ctrl = $self-&gt;_format_rfc822($range);
    } else {
        croak "unknown changelog output format $format";
    }

    if (wantarray) {
        return @ctrl;
    } else {
        my $index = Dpkg::Index-&gt;new(type =&gt; CTRL_CHANGELOG);

        foreach my $c (@ctrl) {
            $index-&gt;add($c);
        }

        return $index;
    }
}

=back

=head1 RANGE SELECTION

A range selection is described by a hash reference where
the allowed keys and values are described below.

The following options 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.

=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 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.

=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.

  Range                        Included entries
  -----                        ----------------
  since =&gt; '2.0'               3.1, 3.0, 2.2
  until =&gt; '2.0'               1.3, 1.2
  from  =&gt; '2.0'               3.1, 3.0, 2.2, 2.1, 2.0
  to    =&gt; '2.0'               2.0, 1.3, 1.2
  count =&gt;  2                  3.1, 3.0
  count =&gt; -2                  1.3, 1.2
  count =&gt;  3, offset =&gt; 2     2.2, 2.1, 2.0
  count =&gt;  2, offset =&gt; -3    2.0, 1.3
  count =&gt; -2, offset =&gt; 3     3.0, 2.2
  count =&gt; -2, offset =&gt; -3    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 CHANGES

=head2 Version 2.00 (dpkg 1.20.0)

Remove methods: $c-&gt;dpkg(), $c-&gt;rfc822().

=head2 Version 1.01 (dpkg 1.18.8)

New method: $c-&gt;format_range().

Deprecated methods: $c-&gt;dpkg(), $c-&gt;rfc822().

New field Timestamp in output formats.

=head2 Version 1.00 (dpkg 1.15.6)

Mark the module as public.

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