summaryrefslogtreecommitdiff
path: root/lib/Carton/Tree.pm
blob: 6ce22a1aa2b30637ae35896b81aa94529fa087b0 (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
package Carton::Tree;
use strict;
use Carton::Dependency;

use Class::Tiny qw( cpanfile snapshot );

use constant STOP => -1;

sub walk_down {
    my($self, $cb) = @_;

    my $dumper; $dumper = sub {
        my($dependency, $reqs, $level, $parent) = @_;

        my $ret = $cb->($dependency, $reqs, $level);
        return if $ret && $ret == STOP;

        local $parent->{$dependency->distname} = 1 if $dependency;

        for my $module (sort $reqs->required_modules) {
            my $dependency = $self->dependency_for($module, $reqs);
            if ($dependency->dist) {
                next if $parent->{$dependency->distname};
                $dumper->($dependency, $dependency->requirements, $level + 1, $parent);
            } else {
                # no dist found in lock
            }
        }
    };

    $dumper->(undef, $self->cpanfile->requirements, 0, {});
    undef $dumper;
}

sub dependency_for {
    my($self, $module, $reqs) = @_;

    my $requirement = $reqs->requirements_for_module($module);

    my $dep = Carton::Dependency->new;
    $dep->module($module);
    $dep->requirement($requirement);

    if (my $dist = $self->snapshot->find_or_core($module)) {
        $dep->dist($dist);
    }

    return $dep;
}

sub merged_requirements {
    my $self = shift;

    my $merged_reqs = CPAN::Meta::Requirements->new;

    my %seen;
    $self->walk_down(sub {
        my($dependency, $reqs, $level) = @_;
        return Carton::Tree::STOP if $dependency && $seen{$dependency->distname}++;
        $merged_reqs->add_requirements($reqs);
    });

    $merged_reqs->clear_requirement('perl');
    $merged_reqs->finalize;

    $merged_reqs;
}

1;