Mojolicious

 view release on metacpan or  search on metacpan

lib/Mojolicious/Command.pm  view on Meta::CPAN

package Mojolicious::Command;
use Mojo::Base -base;

use Carp         qw(croak);
use Mojo::File   qw(path);
use Mojo::Loader qw(data_section);
use Mojo::Server;
use Mojo::Template;

has app => sub { $_[0]{app_ref} = Mojo::Server->new->build_app('Mojo::HelloWorld') }, weak => 1;
has description => 'No description';
has 'quiet';
has template => sub { {vars => 1} };
has usage    => "Usage: APPLICATION\n";

sub chmod_file {
  my ($self, $path, $mode) = @_;
  path($path)->chmod($mode);
  return $self->_loud("  [chmod] $path " . sprintf('%lo', $mode));
}

sub chmod_rel_file { $_[0]->chmod_file($_[0]->rel_file($_[1]), $_[2]) }

sub create_dir {
  my ($self, $path) = @_;
  return $self->_loud("  [exist] $path") if -d $path;
  path($path)->make_path;
  return $self->_loud("  [mkdir] $path");
}

sub create_rel_dir { $_[0]->create_dir($_[0]->rel_file($_[1])) }

sub extract_usage { Mojo::Util::extract_usage((caller)[1]) }

sub help { print shift->usage }

sub rel_file { path->child(split(/\//, pop)) }

sub render_data {
  my ($self, $name) = (shift, shift);
  my $template = Mojo::Template->new($self->template)->name("template $name from DATA section");
  my $output   = $template->render(data_section(ref $self, $name), @_);
  return ref $output ? die $output : $output;
}

sub render_to_file {
  my ($self, $data, $path) = (shift, shift, shift);
  return $self->write_file($path, $self->render_data($data, @_));
}

sub render_to_rel_file {
  my $self = shift;
  $self->render_to_file(shift, $self->rel_file(shift), @_);
}

sub run { croak 'Method "run" not implemented by subclass' }

sub write_file {
  my ($self, $path, $data) = @_;
  return $self->_loud("  [exist] $path") if -f $path;
  $self->create_dir(path($path)->dirname);
  path($path)->spew($data);
  return $self->_loud("  [write] $path");
}

sub write_rel_file { $_[0]->write_file($_[0]->rel_file($_[1]), $_[2]) }

sub _loud {
  my ($self, $msg) = @_;
  say $msg unless $self->quiet;
  return $self;
}

1;

=encoding utf8

=head1 NAME

Mojolicious::Command - Command base class

=head1 SYNOPSIS

  # Lowercase command name
  package Mojolicious::Command::mycommand;
  use Mojo::Base 'Mojolicious::Command', -signatures;

  # Short description
  has description => 'My first Mojo command';

  # Usage message from SYNOPSIS
  has usage => sub ($self) { $self->extract_usage };



( run in 1.801 second using v1.01-cache-2.11-cpan-364913b4093 )