summaryrefslogtreecommitdiffstats
path: root/lib/Devscripts/PackageDeps.pm
blob: 8bad0d77255c6bc6008a2dab527b2c466e0b7f23 (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# Based vaguely on the deprecated dpkg-perl package modules
# Dpkg::Package::List and Dpkg::Package::Package.
# This module creates an object which holds package names and dependencies
# (just Depends and Pre-Depends).
# It can also calculate the total set of subdependencies using the
# fulldepends method.
#
# Copyright 2002 Julian Gilbey <jdg@debian.org>
#
# 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 <https://www.gnu.org/licenses/>.

package Devscripts::PackageDeps;
use strict;
use Carp;
use Dpkg::Control;
use Dpkg::IPC;
use FileHandle;
require 5.006_000;

# This reads in a package file list, such as /var/lib/dpkg/status,
# and parses it.  Using /var/lib/dpkg/status is deprecated in favor of
# fromStatus().

# Syntax: Devscripts::PackageDeps->new($filename)

sub new ($$) {
    my $this     = shift;
    my $class    = ref($this) || $this;
    my $filename = shift;

    my $self = {};

    if (!defined $filename) {
        croak("requires filename as parameter");
    }

    bless($self, $class);

    my $fh = FileHandle->new($filename, 'r');
    unless (defined $fh) {
        croak("Unable to load $filename: $!");
    }
    $self->parse($fh, $filename);
    $fh->close or croak("Problems encountered reading $filename: $!");

    return $self;
}

# This reads in dpkg's status information and parses it.

# Syntax: Devscripts::PackageDeps->fromStatus()

sub fromStatus ($) {
    my $this  = shift;
    my $class = ref($this) || $this;

    my $self = {};

    bless($self, $class);

    my $fh  = FileHandle->new;
    my $pid = spawn(
        exec    => ['dpkg', '--status'],
        to_pipe => $fh
    );
    unless (defined $pid) {
        croak("Unable to run 'dpkg --status': $!");
    }

    $self->parse($fh, 'dpkg --status');

    wait_child($pid, cmdline => 'dpkg --status', nocheck => 1);

    return $self;
}

# Internal functions

my $multiarch;

sub multiarch () {
    if (!defined $multiarch) {
        $multiarch
          = (system('dpkg --assert-multi-arch >/dev/null 2>&1') >> 8) == 0;
    }
    return $multiarch;
}

sub parse ($$$) {
    my $self     = shift;
    my $fh       = shift;
    my $filename = shift;

    my $ctrl;
  PACKAGE_ENTRY:
    while (defined($ctrl = Dpkg::Control->new(type => CTRL_FILE_STATUS))
        && $ctrl->parse($fh, $filename)) {

        # So we've got a package
        my $pkg  = $ctrl->{Package};
        my @deps = ();

        if ($ctrl->{Status} =~ /^\S+\s+\S+\s+(\S+)$/) {
            my $status = $1;
            unless ($status eq 'installed' or $status eq 'unpacked') {
                undef $ctrl;
                next PACKAGE_ENTRY;
            }
        }

        for my $dep (qw(Depends Pre-Depends)) {
            if (exists $ctrl->{$dep}) {
                my $value = $ctrl->{$dep};
                $value =~ s/\([^)]+\)//g;    # ignore versioning information
                $value =~ tr/ \t//d;         # remove spaces
                my @dep_pkgs = split /,/, $value;
                foreach my $dep_pkg (@dep_pkgs) {
                    my @dep_pkg_alts = split /\|/, $dep_pkg;
                    if   (@dep_pkg_alts == 1) { push @deps, $dep_pkg_alts[0]; }
                    else                      { push @deps, \@dep_pkg_alts; }
                }
            }
        }

        $self->{$pkg} = \@deps;
        if ($ctrl->{Architecture} ne 'all' && multiarch) {
            my $arch = $ctrl->{Architecture};
            @deps = map { "$_:$arch" } @deps;
            $self->{"$pkg:$arch"} = \@deps;
        }
        undef $ctrl;
    }
}

# Get direct dependency information for a specified package
# Returns an array or array ref depending on context

# Syntax: $obj->dependencies($package)

sub dependencies ($$) {
    my $self = shift;
    my $pkg  = shift;

    if (!defined $pkg) {
        croak("requires package as parameter");
    }

    if (!exists $self->{$pkg}) {
        return undef;
    }

    return wantarray ? @{ $self->{$pkg} } : $self->{$pkg};
}

# Get full dependency information for a specified package or packages,
# including the packages themselves.
#
# This only follows the first of sets of alternatives, and ignores
# dependencies on packages which do not appear to exist.
# Returns an array or array ref

# Syntax: $obj->full_dependencies(@packages)

sub full_dependencies ($@) {
    my $self      = shift;
    my @toprocess = @_;
    my %deps;

    return wantarray ? () : [] unless @toprocess;

    while (@toprocess) {
        my $next = shift @toprocess;
        $next = $$next[0] if ref $next;
        # Already seen?
        next if exists $deps{$next};
        # Known package?
        next unless exists $self->{$next};
        # Mark it as a dependency
        $deps{$next} = 1;
        push @toprocess, @{ $self->{$next} };
    }

    return wantarray ? keys %deps : [keys %deps];
}

# Given a set of packages, find a minimal set with respect to the
# pre-partial order of dependency.
#
# This is vaguely based on the dpkg-mindep script by
# Bill Allombert <ballombe@debian.org>.  It only follows direct
# dependencies, and does not attempt to follow indirect dependencies.
#
# This respects the all packages in sets of alternatives.
# Returns: (\@minimal_set, \%dependencies)
# where the %dependencies hash is of the form
#   non-minimal package => depending package

# Syntax: $obj->min_dependencies(@packages)

sub min_dependencies ($@) {
    my $self     = shift;
    my @pkgs     = @_;
    my @min_pkgs = ();
    my %dep_pkgs = ();

    return (\@min_pkgs, \%dep_pkgs) unless @pkgs;

    # We create a directed graph: the %forward_deps hash records arrows
    # pkg A depends on pkg B; the %reverse_deps hash records the
    # reverse arrows
    my %forward_deps;
    my %reverse_deps;

    # Initialise
    foreach my $pkg (@pkgs) {
        $forward_deps{$pkg} = {};
        $reverse_deps{$pkg} = {};
    }

    foreach my $pkg (@pkgs) {
        next unless exists $self->{$pkg};
        my @pkg_deps = @{ $self->{$pkg} };
        while (@pkg_deps) {
            my $dep = shift @pkg_deps;
            if (ref $dep) {
                unshift @pkg_deps, @$dep;
                next;
            }
            if (exists $forward_deps{$dep}) {
                $forward_deps{$pkg}{$dep} = 1;
                $reverse_deps{$dep}{$pkg} = 1;
            }
        }
    }

    # We start removing packages from the tree if they have no dependencies.
    # Once we have no such packages left, we must have mutual or cyclic
    # dependencies, so we pick a random one to remove and then start again.
    # We continue this until there are no packages left in the graph.
  PACKAGE:
    while (scalar keys %forward_deps) {
        foreach my $pkg (keys %forward_deps) {
            if (scalar keys %{ $forward_deps{$pkg} } == 0) {
                # Great, no dependencies!
                if (scalar keys %{ $reverse_deps{$pkg} }) {
                    # This package is depended upon, so we can remove it
                    # with care
                    foreach my $dep_pkg (keys %{ $reverse_deps{$pkg} }) {
                        # take the first mentioned package for the
                        # recorded list of depended-upon packages
                        $dep_pkgs{$pkg} ||= $dep_pkg;
                        delete $forward_deps{$dep_pkg}{$pkg};
                    }
                } else {
                    # This package is not depended upon, so it must
                    # go into our mindep list
                    push @min_pkgs, $pkg;
                }
                # Now remove this node
                delete $forward_deps{$pkg};
                delete $reverse_deps{$pkg};
                next PACKAGE;
            }
        }

        # Oh, we didn't find any package which didn't depend on any other.
        # We'll pick a random one, then.  At least *some* package must
        # be depended upon in this situation; let's pick one of these.
        foreach my $pkg (keys %forward_deps) {
            next unless scalar keys %{ $reverse_deps{$pkg} } > 0;

            foreach my $dep_pkg (keys %{ $forward_deps{$pkg} }) {
                delete $reverse_deps{$dep_pkg}{$pkg};
            }
            foreach my $dep_pkg (keys %{ $reverse_deps{$pkg} }) {
                # take the first mentioned package for the
                # recorded list of depended-upon packages
                $dep_pkgs{$pkg} ||= $dep_pkg;
                delete $forward_deps{$dep_pkg}{$pkg};
            }

            # Now remove this node
            delete $forward_deps{$pkg};
            delete $reverse_deps{$pkg};
            # And onto the next package
            goto PACKAGE;
        }

        # Ouch!  We shouldn't ever get here
        croak("Couldn't determine mindeps; this can't happen!");
    }

    return (\@min_pkgs, \%dep_pkgs);
}

1;