Skip to content

Commit

Permalink
use do rather than require to load a mojo application
Browse files Browse the repository at this point in the history
The return value of require is usually not a reasonable thing to rely
on, aside from it being true. The first time requiring a file, it will
return the value of the last statement in the file. The second time
requiring a file, it will return a simple true value.

Mojo was bypassing this problem by deleting the %INC entry for the file,
forcing it to always be loaded again. But the new module_true core
feature will cause require to always return a simple true value rather
than the last statement in the file. This does not apply to do though.

Switch to using do to be compatible with code using the new feature.
  • Loading branch information
haarg committed Aug 24, 2023
1 parent 058216d commit 693fc6c
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/Mojo/Server.pm
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ sub load_app {
local @ARGS_OVERRIDE = @args;

# Try to load application from script into sandbox
delete $INC{$path};
my $app = eval "package Mojo::Server::Sandbox::@{[md5_sum $path]}; require \$path";
die qq{Can't load application from file "$path": $@} if $@;
my $app = eval "package Mojo::Server::Sandbox::@{[md5_sum $path]}; do \$path";
my $err = $app ? undef : $@ || $! || "$path did not return a true value";
die qq{Can't load application from file "$path": $err} if $err;
die qq{File "$path" did not return an application object.\n} unless blessed $app && $app->can('handler');
$self->app($app);
};
Expand Down
9 changes: 9 additions & 0 deletions t/mojo/daemon.t
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,15 @@ subtest 'Load broken app' => sub {
like $@, qr/^Can't load application/, 'right error';
};

subtest 'Load app using module_true' => sub {
plan skip_all => 'module_true feature requires perl 5.38' if $] < 5.038;
my $daemon = Mojo::Server::Daemon->new;
my $path = curfile->sibling('lib', '..', 'lib', 'myapp-module-true.pl');
my $app = eval { $daemon->load_app($path) };
is $@, '', 'no error loading app';
is ref $app, 'Mojolicious::Lite', 'right reference';
};

subtest 'Load missing application class' => sub {
eval { Mojo::Server::Daemon->new->build_app('Mojo::DoesNotExist') };
like $@, qr/^Can't find application class "Mojo::DoesNotExist" in \@INC/, 'right error';
Expand Down
15 changes: 15 additions & 0 deletions t/mojo/lib/myapp-module-true.pl
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use v5.38;
use Mojolicious::Lite;

app->config(script => $0);

app->start;

=head1 SYNOPSIS
USAGE: myapp.pl daemon
test
123
=cut

0 comments on commit 693fc6c

Please sign in to comment.