summaryrefslogtreecommitdiff
path: root/lib/Carton/CLI.pm
blob: b990ad297676feae5710d3e8ccf62a57c6b36816 (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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
package Carton::CLI;
use strict;
use warnings;
use Config;
use Getopt::Long;
use Path::Tiny;
use Try::Tiny;
use Module::CoreList;
use Scalar::Util qw(blessed);

use Carton;
use Carton::Builder;
use Carton::Mirror;
use Carton::Snapshot;
use Carton::Util;
use Carton::Environment;
use Carton::Error;

use constant { SUCCESS => 0, INFO => 1, WARN => 2, ERROR => 3 };

our $UseSystem = 0; # 1 for unit testing

use Class::Tiny {
    verbose => undef,
    carton => sub { $_[0]->_build_carton },
    mirror => sub { $_[0]->_build_mirror },
};

sub _build_mirror {
    my $self = shift;
    Carton::Mirror->new($ENV{PERL_CARTON_MIRROR} || $Carton::Mirror::DefaultMirror);
}

sub run {
    my($self, @args) = @_;

    my @commands;
    my $p = Getopt::Long::Parser->new(
        config => [ "no_ignore_case", "pass_through" ],
    );
    $p->getoptionsfromarray(
        \@args,
        "h|help"    => sub { unshift @commands, 'help' },
        "v|version" => sub { unshift @commands, 'version' },
        "verbose!"  => sub { $self->verbose($_[1]) },
    );

    push @commands, @args;

    my $cmd = shift @commands || 'install';

    my $code = try {
        my $call = $self->can("cmd_$cmd")
            or Carton::Error::CommandNotFound->throw(error => "Could not find command '$cmd'");
        $self->$call(@commands);
        return 0;
    } catch {
        die $_ unless blessed $_ && $_->can('rethrow');

        if ($_->isa('Carton::Error::CommandExit')) {
            return $_->code || 255;
        } elsif ($_->isa('Carton::Error::CommandNotFound')) {
            warn $_->error, "\n\n";
            $self->cmd_usage;
            return 255;
        } elsif ($_->isa('Carton::Error')) {
            warn $_->error, "\n";
            return 255;
        }
    };

    return $code;
}

sub commands {
    my $self = shift;

    no strict 'refs';
    map { s/^cmd_//; $_ }
        grep { /^cmd_.*/ && $self->can($_) } sort keys %{__PACKAGE__."::"};
}

sub cmd_usage {
    my $self = shift;
    $self->print(<<HELP);
Usage: carton <command>

where <command> is one of:
  @{[ join ", ", $self->commands ]}

Run carton -h <command> for help.
HELP
}

sub parse_options {
    my($self, $args, @spec) = @_;
    my $p = Getopt::Long::Parser->new(
        config => [ "no_auto_abbrev", "no_ignore_case" ],
    );
    $p->getoptionsfromarray($args, @spec);
}

sub parse_options_pass_through {
    my($self, $args, @spec) = @_;

    my $p = Getopt::Long::Parser->new(
        config => [ "no_auto_abbrev", "no_ignore_case", "pass_through" ],
    );
    $p->getoptionsfromarray($args, @spec);

    # with pass_through keeps -- in args
    shift @$args if $args->[0] && $args->[0] eq '--';
}

sub printf {
    my $self = shift;
    my $type = pop;
    my($temp, @args) = @_;
    $self->print(sprintf($temp, @args), $type);
}

sub print {
    my($self, $msg, $type) = @_;
    my $fh = $type && $type >= WARN ? *STDERR : *STDOUT;
    print {$fh} $msg;
}

sub error {
    my($self, $msg) = @_;
    $self->print($msg, ERROR);
    Carton::Error::CommandExit->throw;
}

sub cmd_help {
    my $self = shift;
    my $module = $_[0] ? ("Carton::Doc::" . ucfirst $_[0]) : "Carton.pm";
    system "perldoc", $module;
}

sub cmd_version {
    my $self = shift;
    $self->print("carton $Carton::VERSION\n");
}

sub cmd_bundle {
    my($self, @args) = @_;

    my $env = Carton::Environment->build;
    $env->snapshot->load;

    $self->print("Bundling modules using @{[$env->cpanfile]}\n");

    my $builder = Carton::Builder->new(
        mirror => $self->mirror,
        cpanfile => $env->cpanfile,
    );
    $builder->bundle($env->install_path, $env->vendor_cache, $env->snapshot);

    $self->printf("Complete! Modules were bundled into %s\n", $env->vendor_cache, SUCCESS);
}

sub cmd_fatpack {
    my($self, @args) = @_;

    my $env = Carton::Environment->build;
    require Carton::Packer;
    Carton::Packer->new->fatpack_carton($env->vendor_bin);
}

sub cmd_install {
    my($self, @args) = @_;

    my($install_path, $cpanfile_path, @without);

    $self->parse_options(
        \@args,
        "p|path=s"    => \$install_path,
        "cpanfile=s"  => \$cpanfile_path,
        "without=s"   => sub { push @without, split /,/, $_[1] },
        "deployment!" => \my $deployment,
        "cached!"     => \my $cached,
    );

    my $env = Carton::Environment->build($cpanfile_path, $install_path);
    $env->snapshot->load_if_exists;

    if ($deployment && !$env->snapshot->loaded) {
        $self->error("--deployment requires cpanfile.snapshot: Run `carton install` and make sure cpanfile.snapshot is checked into your version control.\n");
    }

    my $builder = Carton::Builder->new(
        cascade => 1,
        mirror  => $self->mirror,
        without => \@without,
        cpanfile => $env->cpanfile,
    );

    # TODO: --without with no .lock won't fetch the groups, resulting in insufficient requirements

    if ($deployment) {
        $self->print("Installing modules using @{[$env->cpanfile]} (deployment mode)\n");
        $builder->cascade(0);
    } else {
        $self->print("Installing modules using @{[$env->cpanfile]}\n");
    }

    # TODO merge CPANfile git to mirror even if lock doesn't exist
    if ($env->snapshot->loaded) {
        my $index_file = $env->install_path->child("cache/modules/02packages.details.txt");
           $index_file->parent->mkpath;

        $env->snapshot->write_index($index_file);
        $builder->index($index_file);
    }

    if ($cached) {
        $builder->mirror(Carton::Mirror->new($env->vendor_cache));
    }

    $builder->install($env->install_path);

    unless ($deployment) {
        $env->cpanfile->load;
        $env->snapshot->find_installs($env->install_path, $env->cpanfile->requirements);
        $env->snapshot->save;
    }

    $self->print("Complete! Modules were installed into @{[$env->install_path]}\n", SUCCESS);
}

sub cmd_show {
    my($self, @args) = @_;

    my $env = Carton::Environment->build;
    $env->snapshot->load;

    for my $module (@args) {
        my $dist = $env->snapshot->find($module)
            or $self->error("Couldn't locate $module in cpanfile.snapshot\n");
        $self->print( $dist->name . "\n" );
    }
}

sub cmd_list {
    my($self, @args) = @_;

    my $format = 'name';

    $self->parse_options(
        \@args,
        "distfile" => sub { $format = 'distfile' },
    );

    my $env = Carton::Environment->build;
    $env->snapshot->load;

    for my $dist ($env->snapshot->distributions) {
        $self->print($dist->$format . "\n");
    }
}

sub cmd_tree {
    my($self, @args) = @_;

    my $env = Carton::Environment->build;
    $env->snapshot->load;
    $env->cpanfile->load;

    my %seen;
    my $dumper = sub {
        my($dependency, $reqs, $level) = @_;
        return if $level == 0;
        return Carton::Tree::STOP if $dependency->dist->is_core;
        return Carton::Tree::STOP if $seen{$dependency->distname}++;
        $self->printf( "%s%s (%s)\n", " " x ($level - 1), $dependency->module, $dependency->distname, INFO );
    };

    $env->tree->walk_down($dumper);
}

sub cmd_check {
    my($self, @args) = @_;

    my $cpanfile_path;
    $self->parse_options(
        \@args,
        "cpanfile=s"  => \$cpanfile_path,
    );

    my $env = Carton::Environment->build($cpanfile_path);
    $env->snapshot->load;
    $env->cpanfile->load;

    # TODO remove snapshot
    # TODO pass git spec to Requirements?
    my $merged_reqs = $env->tree->merged_requirements;

    my @missing;
    for my $module ($merged_reqs->required_modules) {
        my $install = $env->snapshot->find_or_core($module);
        if ($install) {
            unless ($merged_reqs->accepts_module($module => $install->version_for($module))) {
                push @missing, [ $module, 1, $install->version_for($module) ];
            }
        } else {
            push @missing, [ $module, 0 ];
        }
    }

    if (@missing) {
        $self->print("Following dependencies are not satisfied.\n", INFO);
        for my $missing (@missing) {
            my($module, $unsatisfied, $version) = @$missing;
            if ($unsatisfied) {
                $self->printf("  %s has version %s. Needs %s\n",
                              $module, $version, $merged_reqs->requirements_for_module($module), INFO);
            } else {
                $self->printf("  %s is not installed. Needs %s\n",
                              $module, $merged_reqs->requirements_for_module($module), INFO);
            }
        }
        $self->printf("Run `carton install` to install them.\n", INFO);
        Carton::Error::CommandExit->throw;
    } else {
        $self->print("cpanfile's dependencies are satisfied.\n", INFO);
    }
}

sub cmd_update {
    my($self, @args) = @_;

    my $env = Carton::Environment->build;
    $env->cpanfile->load;


    my $cpanfile = Module::CPANfile->load($env->cpanfile);
    @args = grep { $_ ne 'perl' } $env->cpanfile->required_modules unless @args;

    $env->snapshot->load;

    my @modules;
    for my $module (@args) {
        my $dist = $env->snapshot->find_or_core($module)
            or $self->error("Could not find module $module.\n");
        next if $dist->is_core;
        push @modules, "$module~" . $env->cpanfile->requirements_for_module($module);
    }

    my $builder = Carton::Builder->new(
        mirror => $self->mirror,
        cpanfile => $env->cpanfile,
    );
    $builder->update($env->install_path, @modules);

    $env->snapshot->find_installs($env->install_path, $env->cpanfile->requirements);
    $env->snapshot->save;
}

sub cmd_exec {
    my($self, @args) = @_;

    my $env = Carton::Environment->build;
    $env->snapshot->load;

    # allows -Ilib
    @args = map { /^(-[I])(.+)/ ? ($1,$2) : $_ } @args;

    while (@args) {
        if ($args[0] eq '-I') {
            warn "exec -Ilib is deprecated. You might want to run: carton exec perl -Ilib ...\n";
            splice(@args, 0, 2);
        } else {
            last;
        }
    }

    $self->parse_options_pass_through(\@args); # to handle --

    unless (@args) {
        $self->error("carton exec needs a command to run.\n");
    }

    # PERL5LIB takes care of arch
    my $path = $env->install_path;
    local $ENV{PERL5LIB} = "$path/lib/perl5";
    local $ENV{PATH} = "$path/bin:$ENV{PATH}";

    if ($UseSystem) {
        system @args;
    } else {
        exec @args;
        exit 127; # command not found
    }
}

1;