#!/usr/bin/perl

# Builds a dependency tree of all the modules passed on the command
# line.  Caches the fetched tarballs so you don't have to keep
# refetching over and over.  I just run it against my minicpan mirror,
# but you can make $mirror be any CPAN mirror.

use strict;
use warnings;

use Module::Depends::Tree;

$Module::Depends::Tree::workdir = '/tmp/deptree';
$Module::Depends::Tree::mirror  = 'file://Users/andy/minicpan';


MAIN: {
    my @topdeps;

    print 'Dependency tree created ', scalar localtime, "\n";
    print "Created with Module::Depends::Tree $Module::Depends::Tree::VERSION\n";

    print join( " ", '$', $0, @ARGV ), "\n\n";

    for my $arg ( @ARGV ) {
        if ( $arg =~ /\.yaml$/ ) { # Load the deps in the yaml file
            require YAML;
            my $stats = YAML::LoadFile( $arg );
            push @topdeps, sort keys %$stats;
        }
        elsif ( $arg =~ /-(.+)/ ) { # Remove the module from the deps list
            my $module = $1;
            @topdeps = grep { $_ ne $module } @topdeps;
        }
        else { # Add it to the deps
            $arg =~ s/^\+//; # Allow a plus sign for orthagonality
            push @topdeps, $arg;
        }
    }
    @topdeps = sort grep { !$Module::Depends::Tree::skippers{$_} } @topdeps;
    if ( !@topdeps ) {
        die "Must specify a list of modules\n";
    }

    Module::Depends::Tree::process_queue( @topdeps );

    # Now dump the table
    for my $module ( @topdeps ) {
        Module::Depends::Tree::print_deps( 0, $module, () );
        print "\n";
    }

    print "\nNumber of times each module is used\n";
    # Show table in reverse numeric, forward alpha order
    my $used = \%Module::Depends::Tree::used;
    for my $key ( sort { ($used->{$b} <=> $used->{$a}) || ($a cmp $b) } keys %$used ) {
        printf( "%3d %s\n", $used->{$key}, $key );
    }

    print "\n", scalar keys %Module::Depends::Tree::stats, " total modules\n\n";
} # MAIN


