Debian Codegraph @

lib/Dancer2/CLI/Gen.pm

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 package Dancer2::CLI::Gen;
2 # ABSTRACT: Create new Dancer2 application
3 $Dancer2::CLI::Gen::VERSION = '2.2.2';
4 use Moo;
5 use URI;
6 use HTTP::Tiny;
7 use Path::Tiny;
8 use JSON::MaybeXS;
9 use Dancer2::Template::Tiny;
10 use Module::Runtime qw( use_module is_module_name );
11 use CLI::Osprey
12 desc => 'Helper script to create new Dancer2 applications';
13
14 # For git integration
15 use Symbol;
16 use IPC::Open3 qw();
17 use Try::Tiny;
18 use File::Which;
19
20 option application => (
21 is => 'ro',
22 short => 'a',
23 doc => 'application name',
24 format => 's',
25 format_doc => 'appname',
26 required => 1,
27 spacer_before => 1,
28 );
29
30 option directory => (
31 is => 'ro',
32 short => 'd',
33 doc => 'application directory (default: dashed application name)',
34 format => 's',
35 format_doc => 'directory',
36 required => 0,
37 );
38
39 # This was causing conflict with Path::Tiny's path(), so renaming to avoid
40 # the overhead of making Path::Tiny an object.
41 option app_path => (
42 is => 'ro',
43 short => 'p',
44 option => 'path',
45 doc => 'application path (default: current directory)',
46 format => 's',
47 format_doc => 'directory',
48 required => 0,
49 default => '.',
50 );
51
52 option overwrite => (
53 is => 'ro',
54 short => 'o',
55 doc => 'overwrite existing files',
56 required => 0,
57 default => 0,
58 );
59
60 option no_check => (
61 is => 'ro',
62 short => 'x',
63 doc => "don't check latest Dancer2 version (default: check - requires internet)",
64 required => 0,
65 default => 0,
66 );
67
68 option skel => (
69 is => 'ro',
70 short => 's',
71 doc => 'skeleton directory',
72 format => 's',
73 format_doc => 'directory',
74 required => 0,
75 default => sub{
76 my $self = shift;
77 path( $self->parent_command->_dist_dir, 'skel' );
78 },
79 );
80
81 option skel_name => (
82 is => 'ro',
83 short => 'n',
84 doc => 'skeleton name',
85 format => 's',
86 format_doc => 'skelname',
87 required => 0,
88 default => 'default',
89 );
90
91 option docker => (
92 is => 'ro',
93 short => 'c',
94 doc => 'create a dockerfile (container definition)',
95 required => 0,
96 default => 0,
97 );
98
99 option git => (
100 is => 'ro',
101 short => 'g',
102 doc => 'init git repository',
103 required => 0,
104 default => 0,
105 );
106
107 option remote => (
108 is => 'ro',
109 short => 'r',
110 doc => 'URI for git repository (implies -g)',
111 format => 's',
112 format_doc => 'URI',
113 required => 0,
114 );
115
116 option no_package_files => (
117 is => 'ro',
118 doc => "don't create files needed for CPAN packaging",
119 required => 0,
120 default => 0,
121 );
122
123 has _engine => (
124 is => 'ro',
125 default => sub {
126 return Dancer2::Template::Tiny->new( config => { start_tag => '[d2%', end_tag => '%2d]' } );
127 },
128 );
129
130 # Last chance to validate args before we attempt to do something with them
131 sub BUILD {
132 my ( $self, $args ) = @_;
133
134 $self->osprey_usage( 1, qq{
135 Invalid application name. Application names must not contain single colons,
136 dots, hyphens or start with a number.
137 }) unless is_module_name( $self->application );
138
139 if ( my $remote = $self->remote ) {
140 my $scheme = URI->new( $remote )->scheme // $self->remote; # This feels dirty
141 $self->osprey_usage( 1, "'$remote' must be a valid URI to git repository")
142 unless $scheme =~ / ^ git \@ .+ : .+ \.git $ | ^ http /x;
143 }
144
145 my $path = $self->app_path;
146 -d $path or $self->osprey_usage( 1, "path: directory '$path' does not exist" );
147 -w $path or $self->osprey_usage( 1, "path: directory '$path' is not writeable" );
148
149 if ( my $skel = $self->skel ) {
150 -d $skel or $self->osprey_usage( 1, "skel: directory '$skel' not found" );
151 }
152 }
153
154 sub run {
155 my $self = shift;
156 $self->_version_check unless $self->no_check;
157
158 my $app_name = $self->application;
159 my $app_file = $self->parent_command->_get_app_file( $app_name );
160 my $app_path = $self->parent_command->_get_app_path( $self->app_path, $app_name );
161
162 if( my $dir = $self->directory ) {
163 $app_path = path( $self->app_path, $dir );
164 }
165
166 my $files_to_copy = $self->_build_file_list( $self->skel . '/' . $self->skel_name, $app_path );
167 foreach my $pair( @$files_to_copy ) {
168 if( $pair->[0] =~ m/lib\/AppFile.pm$/ ) {
169 $pair->[1] = path( $app_path, $app_file );
170 last;
171 }
172 }
173
174 if( $self->docker ) {
175 push @$files_to_copy, [ path( $self->parent_command->_dist_dir, 'docker/Dockerfile' ), "$app_name/Dockerfile" ];
176 }
177
178 my $vars = {
179 appname => $app_name,
180 appfile => $app_file->stringify,
181 apppath => $app_path->stringify,
182 appdir => $app_path->absolute->stringify,
183 perl_interpreter => $self->parent_command->_get_perl_interpreter,
184 cleanfiles => $self->parent_command->_get_dashed_name( $app_name ),
185 dancer_version => $self->parent_command->_dancer2_version,
186 docker => $self->docker,
187 };
188
189 $self->_copy_templates( $files_to_copy, $vars, $self->overwrite );
190 unless( $self->no_package_files ) {
191 $self->_create_manifest( $files_to_copy, $app_path );
192 $self->_add_to_manifest_skip( $app_path, $vars->{cleanfiles} );
193 }
194
195 $self->_check_git( $vars );
196 $self->_check_yaml;
197 $self->_how_to_run( $vars );
198 }
199
200 sub _check_git {
201 my( $self, $vars ) = @_;
202
203 if( my $remote = $self->remote or $self->git ) {
204 my $app_name = $vars->{ appname };
205 my $git_error = qq{
206 *****
207
208 WARNING: Couldn't initialize a git repo despite being asked to do so.
209
210 To resolve this, cd to your application directory and run the following
211 commands:
212
213 git init
214 git add .
215 git commit -m"Initial commit of $app_name by Dancer2"
216 };
217
218 my $git = which 'git';
219 -x $git or die "Can't execute git: $!";
220
221 #my $dist_dir = $self->parent_command->_dist_dir;
222 my $app_path = $vars->{ apppath };
223
224 # The shipped template lives at share/gitignore, not share/.gitignore --
225 # a leading dot there would make git itself honour it against this
226 # distribution's own share/ tree, which kept the skeleton's environment
227 # configs out of the shipped dist entirely. The generated application
228 # still needs a file literally named .gitignore, so the destination
229 # name is given explicitly rather than left to whatever copy() does
230 # with a directory target.
231 my $gitignore = path( $self->parent_command->_dist_dir, 'gitignore' );
232 path( $gitignore )->copy( path( $app_path, '.gitignore' ) );
233
234 # $vars->{apppath} is a plain string (see the die message below, which
235 # wants it as one); the absolute path was already computed once into
236 # $vars->{appdir} at the point of $app_path->absolute->stringify in
237 # run(), so re-derive it from there instead of calling ->absolute on
238 # a string -- which is what used to make 'dancer2 gen -g' die with
239 # "Can't locate object method \"absolute\" via package ...".
240 chdir $vars->{ appdir }
241 or die "Can't cd to $app_path: $!";
242 if( _run_shell_cmd( 'git', 'init') != 0 or
243 _run_shell_cmd( 'git', 'add', '.') != 0 or
244 _run_shell_cmd( 'git', 'commit', "-m 'Initial commit of $app_name by Dancer2'" ) != 0 ) {
245 print $git_error;
246 }
247 else {
248 if( $self->remote &&
249 _run_shell_cmd( 'git', 'remote', 'add', 'origin', $self->remote ) != 0 ) {
250 print $git_error;
251 print " git remote add origin " . $self->remote . "\n";
252 }
253 }
254 print "\n*****\n";
255 }
256 }
257
258 sub _check_yaml {
259 if ( ! eval { use_module( 'YAML' ); 1; } ) {
260 print qq{
261 *****
262
263 WARNING: YAML.pm is not installed. This is not a full dependency, but is highly
264 recommended; in particular, the scaffolded Dancer app being created will not be
265 able to read settings from the config file without YAML.pm being installed.
266
267 To resolve this, simply install YAML from CPAN, for instance using one of the
268 following commands:
269
270 cpan YAML
271 perl -MCPAN -e 'install YAML'
272 curl -L https://cpanmin.us | perl - --sudo YAML
273
274 *****
275 };
276 }
277 }
278
279 sub _how_to_run {
280 my( $self, $vars ) = @_;
281
282 my $app_path = $vars->{ apppath };
283 my $app_name = $vars->{ appname };
284
285 print "\nYour new application is ready! To run it:\n";
286
287 if( $vars->{ docker } ) {
288 my $image = lc $app_name;
289 print qq{
290
291 cd $app_path
292 docker build -t ${image} .
293 docker run -d -p 5000:4000 --name $app_name ${image}
294
295 where 5000 is the external port, and 4000 is the port your application
296 runs on inside of the container.
297
298 (note: you may need to run the docker commands with sudo)
299
300 You may also run your app without Docker:
301 };
302 }
303
304 my $install_deps = '';
305 $install_deps = "\n cpanm --installdeps ."
306 if $self->skel_name ne 'default';
307
308 print qq{
309 cd $app_path$install_deps
310 plackup bin/app.psgi
311
312 To access your application, point your browser to http://localhost:5000/
313
314 If you need community assistance, the following resources are available:
315 - Dancer website: https://perldancer.org
316 - GitHub: https://github.com/PerlDancer/Dancer2/
317 - Mailing list: https://lists.perldancer.org/mailman/listinfo/dancer-users
318 - IRC: irc.perl.org#dancer
319
320 Happy Dancing!
321
322 };
323 }
324
325 # skel creation routines
326 sub _build_file_list {
327 my ( $self, $from, $to ) = @_;
328 $from =~ s{/+$}{};
329
330 my @result;
331 my $iter = path( $from )->iterator({ recurse => 1 });
332 while( my $file = $iter->() ) {
333 warn "File not found: $file" unless $file->exists; # Paranoia
334 next if $file->basename =~ m{^\.git(/|$)};
335 next if $file->is_dir;
336
337 my $filename = $file->relative( $from );
338 push @result, [ $file, path( $to, $filename )];
339 }
340 return \@result;
341 }
342
343 sub _copy_templates {
344 my ( $self, $files, $vars, $overwrite ) = @_;
345 my $app_name = $vars->{ appname };
346
347 foreach my $pair (@$files) {
348 my ( $from, $to ) = @{$pair};
349 next if $self->no_package_files && $from =~ /MANIFEST\.SKIP$/;
350 next if $self->no_package_files && $from =~ /Makefile.PL$/;
351
352 if ( -f $to && !$overwrite ) {
353 print "! $to exists, overwrite? (or rerun this command with -o) [N/y/a]: ";
354 my $res = <STDIN>; chomp($res);
355 $overwrite = 1 if $res eq 'a';
356 next unless ( $res eq 'y' ) or ( $res eq 'a' );
357 }
358
359 $to =~ s/AppFile/$app_name/;
360 my $to_dir = path( $to )->parent;
361 if ( ! $to_dir->is_dir ) {
362 print "+ $to_dir\n";
363 $to_dir->mkpath;
364 }
365
366 # Skeleton files whose names are prefixed with + need to be executable, but we must strip
367 # that from the name when copying them
368 my $to_file = path( $to )->basename;
369 my $ex = ( $to_file =~ s/^\+// );
370 $to = path( $to_dir, $to_file ) if $ex;
371
372 print "+ $to\n";
373 my $content;
374 {
375 local $/;
376 open( my $fh, '<:raw', $from ) or die "unable to open file `$from' for reading: $!";
377 $content = <$fh>;
378 close $fh;
379 }
380
381 if( $from !~ m/\.(db|ico|jpg|png|css|eot|map|swp|ttf|svg|woff|woff2|js)$/ ) {
382 $content = $self->_process_template($content, $vars);
383 }
384
385 path( $to )->spew_raw( $content );
386 if( $ex ) {
387 $to->chmod( 0755 ) or warn "unable to change permissions for $to: $!";
388 }
389 }
390 }
391
392 sub _create_manifest {
393 my ( $self, $files, $dir ) = @_;
394
395 my $manifest_name = path( $dir, 'MANIFEST' );
396 open( my $manifest, '>', $manifest_name ) or die $!;
397 print $manifest "MANIFEST\n";
398
399 foreach my $file( @{ $files } ) {
400 my $filename = path( $file->[1] )->relative( $dir );
401 my $basename = $filename->basename;
402 my $clean_basename = $basename;
403 $clean_basename =~ s/^\+//;
404 $filename =~ s/\Q$basename\E/$clean_basename/;
405 print {$manifest} "$filename\n";
406 }
407
408 close $manifest;
409 }
410
411 sub _add_to_manifest_skip {
412 my ( $self, $dir, $dist_name ) = @_;
413
414 my $filename = path( $dir, 'MANIFEST.SKIP' );
415 open my $fh, '>>', $filename or die $!;
416 print {$fh} "^$dist_name-\n";
417 close $fh;
418 }
419
420 sub _process_template {
421 my ( $self, $template, $tokens ) = @_;
422
423 return $self->_engine->render( \$template, $tokens );
424 }
425
426 sub _version_check {
427 my $self = shift;
428 my $version = $self->parent_command->_dancer2_version;
429 return if $version =~ m/_/;
430
431 my $latest_version = 0;
432 my $resp = HTTP::Tiny->new( timeout => 5 )->get( 'https://fastapi.metacpan.org/release/Dancer2' );
433 if( $resp->{ success } && decode_json( $resp->{ content } )->{ version } =~ /(\d\.\d+)/ ) {
434 $latest_version = $1;
435 if ($latest_version gt $version) {
436 print qq{
437 The latest stable Dancer2 release is $latest_version. You are currently using $version.
438 Please check https://metacpan.org/pod/Dancer2/ for updates.
439
440 };
441 }
442 } else {
443 warn "\nCouldn't determine latest version of Dancer2. Please check your internet
444 connection, or pass -x to gen to bypass this check in the future.\n\n";
445
446 }
447 }
448
449 # Shell out to run git
450 sub _run_shell_cmd {
451 my @cmds = @_;
452
453 my $exit_status = try {
454 my $pid = IPC::Open3::open3(
455 my $stdin,
456 my $stdout,
457 my $stderr = Symbol::gensym,
458 @cmds,
459 );
460
461 waitpid( $pid, 0 );
462 return $? >> 8;
463 } catch {
464 print STDERR "$_\n";
465 return 1;
466 };
467
468 return $exit_status;
469 }
470
471 1;
472
473 __END__
474
475 =pod
476
477 =encoding UTF-8
478
479 =head1 NAME
480
481 Dancer2::CLI::Gen - Create new Dancer2 application
482
483 =head1 VERSION
484
485 version 2.2.2
486
487 =head1 AUTHOR
488
489 Dancer Core Developers
490
491 =head1 COPYRIGHT AND LICENSE
492
493 This software is copyright (c) 2026 by Alexis Sukrieh.
494
495 This is free software; you can redistribute it and/or modify it under
496 the same terms as the Perl 5 programming language system itself.
497
498 =cut