Tag Archives: Moo

Using MooX::Options to run a Perl script.

In my last post about using Moo I added some more functionality to my File::Info package. I added some more attributes and some Moo roles. I also updated and ran my test script to ensure that it worked well.

Now I want to put my File::Info class to use.  Normally when I write scripts I like to use configuration files with Config::General and command line options (CLI) with Getopt::Long. These have served me very well in the past. Having seen a post recently on the excellent Perl Maven site about Command Line Scripts With Moo I decided to give MooX::Options a try.

This script accepts one input option,  ‘in_file’. The MooX option attribute takes care of  most of the validation and error handling of the input. It also takes care of displaying ‘–help’ and ‘–man’  documentation based on what is entered into the ‘doc’ and ‘long_doc’ option parameters respectively.

You can even do coercion on the option input just as you would with any Moo attribute. Here I could have coerced the input file into a ‘Path::Tiny’ object if I wished. However this is already taken care of in the File::Info module already.

Even though this is a script, because it uses Moo, you could also create Moo attributes. It really is a neat way to write Perl scripts with input options.

 

use Moo;
use MooX::Options;
use v5.16;
use FindBin qw/$Bin/;
use lib qq{$Bin/../lib};

use File::Info;

#-------------------------------------------------------------------------------
#  Options
#-------------------------------------------------------------------------------

option 'in_file' => (
    is       => 'ro',
    format   => 's',
    required => 1,
    short => q{file|i_f},
    doc      => q{The file you wish to examine.},
    long_doc => q{
    The full file path of the file that you would like to get size and age information about.},
);

#-------------------------------------------------------------------------------
#  Functions
#-------------------------------------------------------------------------------
sub run_like_the_wind {
    my ($self) = @_;
    say qq{\n};
    say q{Your File: } . $self->in_file;
    say q{=} x (length($self->in_file) + 11);

    my $file_info_obj = File::Info->new( file => $self->in_file );

    say qq{Not so pretty...\n}
      . $file_info_obj->file->stringify . q{ size is }
      . $file_info_obj->size_bytes
      . q{ and it's been }
      . $file_info_obj->seconds_since_mod
      . qq{ seconds since its last modification.};

    say qq{\nA little prettier...\n}
      . $file_info_obj->file->stringify . q{ size is }
      . $file_info_obj->make_file_size_pretty
      . q{ and was last modified on }
      . $file_info_obj->mod_time_moment->strftime(qq{%a %b %e at %I:%M:%S %p})  . q{ local time.};

     say q{That's } .$file_info_obj->time_since_mod_pretty  . qq{ ago!\n};
}

#--- Run the script
main->new_with_options->run_like_the_wind;

On the first run I forget to enter the ‘in_file’.

Moo > perl bin/file_info.pl 
in_file is missing
USAGE: file_info.pl [-h] [long options...]

    --in_file: String
        The file you wish to examine.

    
    --usage:
        show a short help message

    
    -h --help:
        show a help message

    
    --man:
        show the manual

    
[14:44 - 0.62]
Moo > 

It prints a nice error message with some instructions.  Next time I will get it right.

Moo > perl bin/file_info.pl --in_file IMAG0029.jpg 


Your File: IMAG0029.jpg
=======================
Not so pretty...
IMAG0029.jpg size is 592023 and it's been 78620118 seconds since its last modification.

A little prettier...
IMAG0029.jpg size is 578.15 KB and was last modified on Sat Apr  6 at 04:02:28 PM local time.
That's 129.99 Weeks ago!

[14:57 - 0.04]
[austin@the-general-II 83] Moo > 

There is a lot more that could be added to our File::Info module. It could be subclassed and or given some more Roles to provide some extra functionality.

Here is some more useful links on this topic.

MooX::Options on CPAN

Now I Have Better Options, by Mark Fowler in the Perl Advent Calendar

App::Math::Tutor, by Jens Rehsack , has lots of Moo and Moox::Options examples.

Using Moo (continued)

Continuing from my last post  Using Moo,  I will add a little more functionality to my File::Info class.  At first I was going to subclass it, but then I decided to use  Moo::Role instead. Moo::Role which is based on Role::Tiny. Roles are a really convenient way of adding extra functionality to your class.

package File::Info;
use Scalar::Util qw/blessed looks_like_number/;
use Moo;
use v5.16;
#-------------------------------------------------------------------------------
#  Base class to provide some useful information about a given file.
#-------------------------------------------------------------------------------
use Path::Tiny;
use Carp;
use File::stat;
use namespace::clean;    # clean imported functions from your namespace.
#-------------------------------------------------------------------------------
#  Attributes
#-------------------------------------------------------------------------------
has file => (
    is  => 'ro',
    isa => sub {
        #--- Because I like Path::Tiny
        Carp::croak(
            qq{'in_file' needs to be an existing file and a Path::Tiny Object!})
          unless ( ref $_[0] eq 'Path::Tiny' and $_[0]->exists );
    },
    coerce => sub {
        return $_[0]
          if ( ref $_[0] eq 'Path::Tiny' );
        return path( $_[0] );
    },
    required => 1
);

has file_stat => (
    is  => 'rwp',
    isa => sub {
        Carp::croak(qq{$_[0] is not a File::stat::stat!})
          unless ( $_[0] and ( ref $_[0] ) );
    },
);

has size_bytes => (
    is  => 'rwp',
    isa => sub {
        Carp::croak(qq{'bytes' value $_[0] is not numeric!})
          unless ( looks_like_number( $_[0] ) );
    },
    lazy    => 1,
    builder => sub {
        $_[0]->file_stat->size;
    },
);

has mod_time_seconds => (
    is  => 'ro',
    isa => sub {
        Carp::croak(qq{$_[0] is not a number!})
          unless ( looks_like_number( $_[0] ) );
    },
    lazy    => 1,
    builder => sub {
        $_[0]->file_stat->mtime;
    },
);

#--- Moo roles to print bytes/seconds in a more readable form
with qw{MakeBytesPretty MakeSecondsPretty};

#-------------------------------------------------------------------------------
#  Builders and Triggers
#-------------------------------------------------------------------------------
sub BUILD {
    my ($self) = @_;
    $self->_set_file_stat( File::stat::stat( $self->file ) )
      or Carp::croak( qq{File stat failed to get the file stat for, }
          . $self->file
          . qq{!: $!} );
}
1;

And the Roles…

package MakeBytesPretty;
use Moo::Role; #--- Makes this a role, and not a class. 
use v5.16;
use namespace::clean;

requires 'size_bytes'; #-- Make sure that this attribute exists somewhare. 
#-------------------------------------------------------------------------------
#  Moo role to prints bytes a little more pretty.
#-------------------------------------------------------------------------------
sub make_file_size_pretty {
    my ($self) = @_;
    my $bytes = $self->size_bytes;

    return ( not $bytes )
      ? 0
      : ( $bytes <= 1024 ) ? sprintf( "%0.02f", $bytes )
      . " Bytes"

      : ( $bytes <= 1048576 ) ? sprintf( "%0.02f", ( $bytes / 1024 ) ) . " KB"

      : ( $bytes <= 1073741824 )
      ? sprintf( "%0.02f", ( $bytes / 1048576 ) ) . " MB"

      : ( $bytes <= 1099511627776 )
      ? sprintf( "%0.02f", ( $bytes / 1073741824 ) ) . " GB"

      : ( $bytes <= 1125899906842624 )
      ? sprintf( "%0.02f", ( $bytes / 1099511627776 ) ) . " TB"

      : ( $bytes <= 1152921504606846976 )

      ? sprintf( "%0.02f", ( $bytes / 1125899906842624 ) ) . " PB"    # Petabyte

      : sprintf( "%0.02f", ( $bytes / 1152921504606846976 ) ) . " EB" # Exabyte
}
#-------------------------------------------------------------------------------
#  End
#-------------------------------------------------------------------------------
1;
package MakeSecondsPretty;
use Moo::Role;
use v5.16;
use namespace::clean;

requires 'mod_time_seconds';
#-------------------------------------------------------------------------------
#  Moo role to print time 'Seconds' in a more pretty way.
#-------------------------------------------------------------------------------
sub make_mod_time_pretty {
    my ( $self ) = @_;
    my $seconds = $self->mod_time_seconds;
    return ( not $seconds )
      ? 0
      : ( $seconds <= 60 ) ? sprintf( "%0.02f", $seconds )
      . " Seconds"

      : ( $seconds <= 3600 )
      ? sprintf( "%0.02f", ( $seconds / 60 ) ) . " Minutes"

      : ( $seconds <= 3600 )
      ? sprintf( "%0.02f", ( $seconds / 3600 ) ) . " Hours"

      : ( $seconds <= 86400 )
      ? sprintf( "%0.02f", ( $seconds / 86400 ) ) . " Days"

      : sprintf( "%0.02f", ( $seconds / 604800 ) ) . " Weeks";
}
#-------------------------------------------------------------------------------
#  End
#-------------------------------------------------------------------------------
1;

As before, it’s a good idea to write a test script to make sure all is ok. This test script isn’t overly thorough, but it’s good enough for this demonstration.

use Test::Modern;    #-- I wonder will it be modern in 10 years time??
use FindBin qw($Bin);
use lib qq{$Bin/../lib};    #-- Where File::Info is located.
use File::Info;
use Scalar::Util qw/blessed looks_like_number/;

my $fi = object_ok(
    sub { File::Info->new( file => qq{IMAG0029.jpg} ) },
    '$fi',
    isa => [qw(Moo::Object )],
    can => [
        qw(  file file_stat size_bytes mod_time_seconds make_file_size_pretty
          make_mod_time_pretty )
    ],
    clean => 1,
    more  => sub {
        my $file_info_obj = shift;
        isa_ok( $file_info_obj->file, 'Path::Tiny',
            q{File::Info 'file' is a Path::Tiny object.} );
        is( $file_info_obj->file->basename,
            qq{IMAG0029.jpg},
            q{File::Info 'file' has the correct file basename.} );
        isa_ok( $file_info_obj->file_stat, q{File::stat},
            qq{File::Info 'file_stat' is a 'File::stat'.} );
        like( $file_info_obj->file_stat->size,
            qr/^[0-9]+$/,
            q{File::Info 'file_stat->size' returns a numeric file size.} );
        like( $file_info_obj->size_bytes,
            qr/^[0-9]+$/, qq{File::Info 'size_bytes' is numeric.} );
        like(
            $file_info_obj->make_file_size_pretty,
            qr/^d+?.d+ (bytes|KB|MB|GB|TB|PB|EB)$/, qq{
            File::Info bytes 'make_file_size_pretty' 
            prints a file size followed by the size Unit.}
        );
        like( $file_info_obj->mod_time_seconds, qr/^d+$/,
            qq{File::Info 'mod_time_seconds' prints the file modification time.}
        );
        like(
            $file_info_obj->make_mod_time_pretty,
            qr/^d+?.d+ (Seconds|Minutes|Hours|Days|Weeks)$/, qq{
            File::Info bytes 'make_mod_timepretty' 
            prints the file mod time followed by the time Unit.}
        );
    },
);

done_testing();

Run the test script …

Moo > prove -v t/test_file.t 
t/test_file.t .. 
    # Subtest: $fi ok
    ok 1 - instantiate $fi
    ok 2 - $fi is blessed
    ok 3 - '$fi' isa 'Moo::Object'
    ok 4 - File::Info->can(...)
    ok 5 - File::Info contains no imported functions
        # Subtest: more tests for $fi
        ok 1 - 'File::Info 'file' is a Path::Tiny object.' isa 'Path::Tiny'
        ok 2 - File::Info 'file' has the correct file basename.
        ok 3 - 'File::Info 'file_stat' is a 'File::stat'.' isa 'File::stat'
        ok 4 - File::Info 'file_stat->size' returns a numeric file size.
        ok 5 - File::Info 'size_bytes' is numeric.
        ok 6 - 
        #             File::Info bytes 'make_file_size_pretty' 
        #             prints a file size followed by the size Unit.
        ok 7 - File::Info 'mod_time_seconds' prints the file modification time.
        ok 8 - 
        #             File::Info bytes 'make_mod_timepretty' 
        #             prints the file mod time followed by the time Unit.
        ok 9 - no exception thrown by additional tests
        1..9
    ok 6 - more tests for $fi
    1..6
ok 1 - $fi ok
ok 2 - no (unexpected) warnings (via done_testing)
1..2
ok
All tests successful.
Files=1, Tests=2,  1 wallclock secs ( 0.03 usr  0.00 sys +  0.08 cusr  0.02 csys =  0.13 CPU)
Result: PASS
[17:10 - 1.06]

Ok. Looks fine for now.

However, I would like to change the module around a little. I want to be able to print the size and age of a given file in a somewhat readable fashion.

I removed the ‘mod_time_seconds’ attribute and replaced it with ‘mod_time_moment’ . This attribute will store the file’s modification time as a Time::Moment object. This will add a little more versatility to the module. Time::Moment is a handy and fast time manipulation module that’s relatively new on the block. Other modules that I could have used would be, Time::Piece which I use a lot also, and  the venerable DateTime module, which is excellent for serious date calculations involving time zones, durations etc.

I also added two new methods to get the time since the last file modification. One will return the elapsed time in seconds and the other will return the elapsed time in a more readable form.

Here is the updated File::Info module…

package File::Info;
use Scalar::Util qw/blessed looks_like_number/;
use Moo;
use v5.16;

#-------------------------------------------------------------------------------
#  Base class to provide some useful information about a given file.
#-------------------------------------------------------------------------------
use Path::Tiny;
use Carp;
use File::stat;
use Time::Moment;
use Time::Piece;
use namespace::clean;    # clean imported functions from your namespace.

#-------------------------------------------------------------------------------
#  Attributes
#-------------------------------------------------------------------------------
has file => (
    is  => 'ro',
    isa => sub {

        #--- Because I like Path::Tiny
        Carp::croak(
            qq{'in_file' needs to be an existing file and a Path::Tiny Object!})
          unless ( ref $_[0] eq 'Path::Tiny' and $_[0]->exists );
    },
    coerce => sub {
        return $_[0]
          if ( ref $_[0] eq 'Path::Tiny' );
        return path( $_[1] );
    },
    required => 1
);

has file_stat => (
    is  => 'rwp',
    isa => sub {
        Carp::croak(qq{$_[0] is not a File::stat::stat!})
          unless ( $_[0] and ( ref $_[0] ) );
    },
);

has size_bytes => (
    is  => 'rwp',
    isa => sub {
        Carp::croak(qq{'bytes' value $_[0] is not numeric!})
          unless ( looks_like_number( $_[0] ) );
    },
    lazy    => 1,
    builder => sub {
        $_[0]->file_stat->size;
    },
);

#--- The file's last modification time
#    as a Time::Moment Object
has mod_time_moment => (
    is  => 'ro',
    isa => sub {
        Carp::croak(
            qq{Bad 'mod_time_moment' because $_[0] is not a Time::Moment!})
          unless ( ref $_[0] eq q{Time::Moment} );
    },
    lazy    => 1,
    builder => sub {
        #--- Time::Piece To keep it in the local time zone
   Time::Moment->from_object( scalar Time::Piece::localtime($_[0]->file_stat->mtime ) 
        );
    },
);

#--- Moo roles to print bytes/seconds in a more readable form
with qw{MakeBytesPretty MakeSecondsPretty};

#-------------------------------------------------------------------------------
#  Builders and Triggers
#-------------------------------------------------------------------------------
sub BUILD {
    my ($self) = @_;
    $self->_set_file_stat( File::stat::stat( $self->file ) )
      or Carp::croak( qq{File stat failed to get the file stat for, }
          . $self->file
          . qq{!: $!} );
}

#-------------------------------------------------------------------------------
#  Methods
#-------------------------------------------------------------------------------
#--- The file age since its last modification expressed in seconds.
sub seconds_since_mod {
    my ($self) = @_;
    return ( Time::Moment->now()->epoch - $self->mod_time_moment->epoch );
}

sub time_since_mod_pretty {
    my ($self) = @_;
    return $self->make_seconds_pretty( $self->seconds_since_mod );
}

#-------------------------------------------------------------------------------
1;

I also made some changes to the role MakeSecondsPretty.pm. I removed the ‘requires’  statement and renamed the only method to ‘make_seconds_pretty’ . I also changed this method slightly.

sub make_seconds_pretty {
    my ( $self , $seconds ) = @_;
    return ( not $seconds )
      ? 0
      : ( $seconds <= 60 ) ? sprintf( "%0.02f", $seconds )
      . " Seconds"

      : ( $seconds <= 3600 )
      ? sprintf( "%0.02f", ( $seconds / 60 ) ) . " Minutes"

      : ( $seconds <= 86400 )
      ? sprintf( "%0.02f", ( $seconds / 3600 ) ) . " Hours"

      : ( $seconds <= 604800 )
      ? sprintf( "%0.02f", ( $seconds / 86400 ) ) . " Days"

      : sprintf( "%0.02f", ( $seconds / 604800 ) ) . " Weeks";
}

The testing script also has to be changed to reflect changes in the module.

my $fi = object_ok(
    sub { File::Info->new( file => qq{IMAG0029.jpg} ) },
    '$fi',
    isa => [qw(Moo::Object )],
    can => [
        qw(  file file_stat size_bytes mod_time_moment make_seconds_pretty
          seconds_since_mod time_since_mod_pretty )
    ],
    clean => 1,
    more  => sub {
        my $file_info_obj = shift;
        isa_ok( $file_info_obj->file, 'Path::Tiny',
            q{File::Info 'file' is a Path::Tiny object.} );
        is( $file_info_obj->file->basename,
            qq{IMAG0029.jpg},
            q{File::Info 'file' has the correct file basename.} );
        isa_ok( $file_info_obj->file_stat, q{File::stat},
            qq{File::Info 'file_stat' is a 'File::stat'.} );
        like( $file_info_obj->file_stat->size,
            qr/^[0-9]+$/,
            q{File::Info 'file_stat->size' returns a numeric file size.} );
        like( $file_info_obj->size_bytes,
            qr/^[0-9]+$/, qq{File::Info 'size_bytes' is numeric.} );
        like(
            $file_info_obj->make_file_size_pretty,
            qr/^d+?.d+ (bytes|KB|MB|GB|TB|PB|EB)$/, qq{
            File::Info bytes 'make_file_size_pretty' 
            prints a file size followed by the size Unit.}
        );
        isa_ok( $file_info_obj->mod_time_moment, q{Time::Moment},
            qq{File::Info 'mod_time_moment' returns a Time::Moment object.}
        );
        like( $file_info_obj->seconds_since_mod, qr/^d+$/,
            qq{File::Info 'seconds_since_mod' returns a numeric.}
        );
        like(
           $file_info_obj->time_since_mod_pretty(),
            qr/^d+?.d+ (Seconds|Minutes|Hours|Days|Weeks)$/, qq{
            File::Info 'time_since_mod_pretty' uses 'make_seconds_pretty' 
            to print the 'seconds_since_mod' as time followed by the time Unit.}
        );
    },
);

Run the test again…

Moo > prove -v t/test_file.t 
t/test_file.t .. 
    # Subtest: $fi ok
    ok 1 - instantiate $fi
    ok 2 - $fi is blessed
    ok 3 - '$fi' isa 'Moo::Object'
    ok 4 - File::Info->can(...)
    ok 5 - File::Info contains no imported functions
        # Subtest: more tests for $fi
        ok 1 - 'File::Info 'file' is a Path::Tiny object.' isa 'Path::Tiny'
        ok 2 - File::Info 'file' has the correct file basename.
        ok 3 - 'File::Info 'file_stat' is a 'File::stat'.' isa 'File::stat'
        ok 4 - File::Info 'file_stat->size' returns a numeric file size.
        ok 5 - File::Info 'size_bytes' is numeric.
        ok 6 - 
        #             File::Info bytes 'make_file_size_pretty' 
        #             prints a file size followed by the size Unit.
        ok 7 - 'File::Info 'mod_time_moment' returns a Time::Moment object.' isa 'Time::Moment'
        ok 8 - File::Info 'seconds_since_mod' returns a numeric.
        ok 9 - 
        #             File::Info 'time_since_mod_pretty' uses 'make_seconds_pretty' 
        #             to print the 'seconds_since_mod' as time followed by the time Unit.
        ok 10 - no exception thrown by additional tests
        1..10
    ok 6 - more tests for $fi
    1..6
ok 1 - $fi ok
ok 2 - no (unexpected) warnings (via done_testing)
1..2
ok
All tests successful.
Files=1, Tests=2,  1 wallclock secs ( 0.03 usr  0.01 sys +  0.10 cusr  0.02 csys =  0.16 CPU)
Result: PASS
[22:28 - 0.34]

Ok!

For my next post. I will use my module in a script with the help of  MooX::Options.

 

Using Moo

Moo simplifies OO in Perl.
Here is a Moo class that will provide some information about a file. I will use D.A Golden’s Path::Tiny, because I use this module in almost every script that I write.

package File::Info;
use Moo;
use v5.16;
#-------------------------------------------------------------------------------
#  Base class to provide information about a given file.
#-------------------------------------------------------------------------------
use Path::Tiny;
use File::stat;
use Carp;
use namespace::clean; #--- Dont export unintentionally
#-------------------------------------------------------------------------------
#  Attributes
#-------------------------------------------------------------------------------
has file => (
    is  => 'ro',
    isa => sub {
        Carp::croak(qq{'in_file' needs to be an existing file and a Path::Tiny Object!})
          unless (ref $_[0] eq 'Path::Tiny' and $_[0]->exists);
    },
    coerce => sub {
        return $_[0]
          if ( ref $_[0] eq 'Path::Tiny' );
        return path( $_[0] );
    },
    required => 1
);

has file_stat => (
    is  => 'rwp',
    isa => sub {
        Carp::croak(qq{$_[0] is not a File::stat::stat!})
          unless ( $_[0] and ( ref $_[0] ) );
    },
);

#-------------------------------------------------------------------------------
#  Builders and Triggers
#-------------------------------------------------------------------------------
sub BUILD {
    my ($self) = @_;
    $self->_set_file_stat( File::stat::stat( $self->file ) )
      or Carp::croak( qq{File stat failed to get the file stat for, }
          . $self->file
          . qq{!: $!} );
}
1;

It would be a good idea to test this module before we proceed further.
I found a this Test::Modern  module by Toby Inkster(who always does good stuff). It’s a testing module that includes many other testing modules(Also see Test::Most).

Here’s a test to make sure that all’s ok with my File::Info module.

use Test::Modern;    #-- I wonder will it be modern in 10 years time??
use FindBin qw($Bin);
use lib qq{$Bin/../lib};    #-- Where File::Info is located.
use File::Info;

my $fi = object_ok(
    sub { File::Info->new( file => qq{IMAG0029.jpg} ) },
    '$fi',
    isa   => [qw(Moo::Object )],
    can   => [qw(  file file_stat )],
    clean => 1,
    more  => sub {
        my $file_info_obj = shift;

        isa_ok( $file_info_obj->file, 'Path::Tiny',
            q{File::Info 'file' is a Path::Tiny object.} );

        is( $file_info_obj->file->basename,
            qq{IMAG0029.jpg},
            q{File::Info 'file' has the correct file basename.} );

        isa_ok( $file_info_obj->file_stat, q{File::stat},
            qq{File::Info 'file_stat' is a 'File::stat'.} );

        like( $file_info_obj->file_stat->size,
            qr/^[0-9]+$/,
            q{File::Info 'file_stat->size' returns a numeric file size.} );
    },
);

done_testing();

I ran this test script and got the following results ( on the first attempt of course :)).

Moo > prove -v t/test_file.t 
t/test_file.t .. 
    # Subtest: $fi ok
    ok 1 - instantiate $fi
    ok 2 - $fi is blessed
    ok 3 - '$fi' isa 'Moo::Object'
    ok 4 - File::Info->can(...)
    ok 5 - File::Info contains no imported functions
        # Subtest: more tests for $fi
        ok 1 - 'File::Info 'file' is a Path::Tiny object.' isa 'Path::Tiny'
        ok 2 - File::Info 'file' has the correct file basename.
        ok 3 - 'File::Info 'file_stat' is a 'File::stat'.' isa 'File::stat'
        ok 4 - File::Info 'file_stat->size' returns a numeric file size.
        ok 5 - no exception thrown by additional tests
        1..5
    ok 6 - more tests for $fi
    1..6
ok 1 - $fi ok
ok 2 - no (unexpected) warnings (via done_testing)
1..2
ok
All tests successful.
Files=1, Tests=2,  0 wallclock secs ( 0.03 usr  0.01 sys +  0.09 cusr  0.00 csys =  0.13 CPU)
Result: PASS
[21:42 - 0.37]
[austin@the-general-II 64] Moo >

 

Test::Modern seems pretty cool.  My File::Info module seems to be ok so far.  Now to add some more useful functionality.