#! /usr/bin/env perl
# PODNAME: cpangit-add
our $VERSION = '0.011'; # VERSION
# ABSTRACT: import CPAN packages to local CPAN trees

use v5.36;
use FindBin;
BEGIN { push @INC, "$FindBin::RealBin/../lib" if -f "$FindBin::RealBin/../dist.ini" }
use CPAN::InGit;
use CPAN::InGit::TerminalEscape;
use Getopt::Long;
use Pod::Usage;
use Log::Any::Adapter 'Stdout', log_level => 'info';
use CPAN::Meta::Requirements;


my $log_level= Log::Any::Adapter::Util::numeric_level('info');
GetOptions(
   'git-dir=s'  => \(my $git_dir= $ENV{GIT_DIR} // '.'),
   'branch=s'   => \my $branch_name,
   'local'      => \my $local,
   'allowed-upstreams:s' => sub { CPAN::InGit->update_allowed_upstreams($_[1]) },
   'max-files=i'      => \$CPAN::InGit::MutableTree::archive_limits{max_files},
   'max-total-size=s' => sub { $CPAN::InGit::MutableTree::archive_limits{max_total_size}= CPAN::InGit::_parse_size($_[1]) },
   'max-file-size=s'  => sub { $CPAN::InGit::MutableTree::archive_limits{max_file_size}= CPAN::InGit::_parse_size($_[1]) },
   'verbose|v'  => sub { ++$log_level },
   'quiet|q'    => sub { --$log_level if $log_level },
   'help'       => sub { pod2usage(1) },
) && @ARGV or pod2usage(2);
# Names and contents from distributions could contain terminal control sequences
CPAN::InGit::TerminalEscape->apply(\*STDOUT, \*STDERR);
pod2usage(2) if $local && @ARGV != 1;

Log::Any::Adapter->set('Stdout', log_level => $log_level);

my $prereq_phases= [qw( configure build runtime test )];
my $prereq_types=  [qw( requires )];
my $requirements;
my $cpan_snapshot;

sub slurp {
   my $name= shift;
   open my $fh, '<:raw', $name or die "open($name): $!";
   local $/;
   my $bytes= <$fh> // die "read($name): $!";
   close $fh or die "close($name): $!";
   $bytes;
}

while (!$local && @ARGV) {
   if ($ARGV[0] =~ m,/, or $ARGV[0] eq 'cpanfile' or $ARGV[0] eq 'cpanfile.snapshot') {
      my $path= shift;
      # load content
      my $content= slurp($path);
      # detect format
      if ($path =~ /cpanfile\.snapshot\z/ or $content =~ /^# carton snapshot/) {
         my $snap= CPAN::InGit->_parse_cpanfile_snapshot($content);
         if ($cpan_snapshot) {
            %$cpan_snapshot= ( %$cpan_snapshot, %$snap );
         } else {
            $cpan_snapshot= $snap;
         }
      } elsif ($path =~ /cpanfile\z/ or $content =~ /^ *requires +\S/m) {
         require Module::CPANfile;
         my $pre= Module::CPANfile->load(\$content)->prereqs;
         my $req= $pre->merged_requirements($prereq_phases, $prereq_types);
         if ($requirements) {
            $requirements->add_requirements($req);
         } else {
            $requirements= $req
         }
      } else {
         die "Unrecognized format in file '$path'";
      }
   }
   elsif ($ARGV[0] =~ /^\w+(::\w+)*\z/) {
      my $mod_name= shift;
      my $ver_spec= 0;
      if (@ARGV && $ARGV[0] =~ /^[><=0-9]/) {
         $ver_spec= shift;
         ($ver_spec =~ /^(>|>=|=|<|<=|)([0-9]+(?:\.[0-9]+(?:_[0-9]+)*))\z/)
            or die "Unexpected version syntax '$ver_spec'";
      }
      $requirements ||= CPAN::Meta::Requirements->new;
      $requirements->add_string_requirement($mod_name, $ver_spec);
   }
}

{ # scope to help run destructors in the right order
   my $git_repo= Git::Raw::Repository->discover($git_dir);
   my $cpan_repo= CPAN::InGit->new(git_repo => $git_repo);
   # If branch name is not provided, use HEAD.  But there must be a working copy.
   # If the branch name is the same as the one checked out, we need to modify the working
   # copy instead of the branch itself, but the ArchiveTree object handles that.
   my $cur_branch= $cpan_repo->workdir_branch_name;
   die "Must specify --branch=X for bare git repo"
      unless length $branch_name || length $cur_branch;
   $branch_name //= $cur_branch;

   my $atree= $cpan_repo->get_archive_tree($branch_name);
   unless ($atree) {
      my $tree= $cpan_repo->lookup_tree($branch_name)
         or die "No tree named '$branch_name'";
      my $ent= $tree->entry_bypath('cpan_ingit.json');
      die "Tree '$branch_name' does not appear to be a 'PAN"
         .($ent? '' : ' (no /cpan_ingit.json file)');
   }

   if ($local) {
      my ($name)= @ARGV;
      my $is_module= $name =~ /\A\w+(?:::\w+)*\z/ && !-f $name;
      my $bytes= $is_module? undef : slurp($name);
      my $path;
      eval {
         $path= $is_module? $atree->localize_module($name) : $atree->add_local_dist($name, \$bytes);
         1;
      } or die "$@"
         ."Unreferenced intermediate data can be purged with 'git gc --prune=now'\n";
      $atree->commit("Import $path for local changes") unless $atree->use_workdir;
   } else {
      my %imported_dists;
      %imported_dists= %{ $atree->import_cpanfile_snapshot($cpan_snapshot) }
         if $cpan_snapshot;
      %imported_dists= ( %imported_dists, %{ $atree->import_modules($requirements) } )
         if $requirements;
      # If this is not the working branch, also need to commit it
      unless ($atree->use_workdir) {
         # TODO: smarter choice of commit title
         my $title= "Imported modules";
         $atree->commit("$title\n\nImported modules:\n".join('', map "  - $_\n", sort keys %imported_dists))
      }
   }
}
exit 0;

__END__

=pod

=encoding UTF-8

=head1 NAME

cpangit-add - import CPAN packages to local CPAN trees

=head1 NAME

cpangit-add - import CPAN distributions into local archive branches

=head1 USAGE

  cpangit-add [OPTIONS] [MODULE::NAME [VERSION]] ...
  cpangit-add [OPTIONS] PATH/TO/CPANFILE
  cpangit-add [OPTIONS] --local PATH_OR_MODULE_NAME

The first two forms add one or more modules, and their dependencies, to a
mirror branch.  If the branch is the working branch, this will add the files
to the index for you to review and commit.  Otherwise the files are added in
an automatic commit on that branch.

When '--local' is used, locate a distribution archive, unpack it under
author L/LO/LOCAL, and update the package index to use this dist.

=head1 OPTIONS

=over

=item --git-dir=PATH

Path to the Git repository of L<CPAN::InGit>.  The default is GIT_DIR from
the environment, or any git repo above "."

=item --branch=BRANCH_NAME

Branch name to commit the changes to.  If this is the checked-out branch, the
index will be updated but no commit will be generated.

=item --local

Unpack one distribution into C<authors/id/L/LO/LOCAL/> for local patching.
Only one argument is permitted, and in addition to a module name, it may be
a file path of a distribution archive.  For module names, the distribution
will be resolved by the usual means, possibly using a distribution that was
already indexed in this branch under a different author.  The action fails
if the local-author distribution directory already exists.

The archive is streamed into the repository's object storage before anything is added to the
branch, so if it fails (for instance by exceeding one of the limits below) the objects already
stored are unreferenced.  C<git gc> eventually removes them, or C<git gc --prune=now> right
away.

=item --allowed-upstreams=URL1,URL2,...

=item --allowed-upstreams=+URL1,URL2,...

The upstream URLs which mirror branches may download from.  The default is the public CPAN by
https (www.cpan.org, cpan.org, cpan.metacpan.org and backpan.perl.org).  The list replaces the
default, unless it begins with C<+>, in which case the URLs are added to it.  An empty list
prevents downloading from any upstream.  The C<upstream_url> of a mirror is configured in its
branch, which might have come from someone else's repository, so this lets you decide which
hosts may be contacted.  (see L<CPAN::InGit/allowed_upstreams>)

=item --max-files=COUNT

=item --max-total-size=SIZE

=item --max-file-size=SIZE

Limits for unpacking a distribution archive: the number of files, the total uncompressed size,
and the size of the largest file.  SIZE is a number of bytes with an optional suffix of C<K>,
C<M> or C<G>.  C<0> means no limit.  The defaults are 40000 files, 200M total, and 30M per
file.  (see L<CPAN::InGit::MutableTree/import_from_archive>)

=back

=head1 VERSION

version 0.011

=head1 AUTHOR

Michael Conrad <mike@nrdvana.net>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2026 by Michael Conrad, and IntelliTree Solutions.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
