Acrux

 view release on metacpan or  search on metacpan

eg/acrux_std.pl  view on Meta::CPAN


sub startup {
    my $self = shift;

    print color(green => "Start application"), "\n" ;

    return $self;
}

DESTROY {
    my $el = sprintf("%+.*f sec", 4, shift->elapsed);
    print color(green => "Finish application ($el)"), "\n" ;
}

__PACKAGE__->register_handler; # default

__PACKAGE__->register_handler( handler => "noop" );

__PACKAGE__->register_handler(
    handler     => "version",
    aliases     => "ver",

eg/acrux_test.pl  view on Meta::CPAN

    my $self = shift;
    print sprintf(color(green => "Start application %s"), $self->project), "\n" ;

    # Set plugin 'Test'
    $self->plugin(Test => 'MyTestPlugin'); # $self->test;

    return $self;
}

DESTROY {
    my $el = sprintf("%+.*f sec", 4, $_[0]->elapsed);
    print sprintf(color(green => "Finish application %s ($el)"), $_[0]->project), "\n" ;
}

__PACKAGE__->register_handler; # default

__PACKAGE__->register_handler(
    handler     => "test",
    description => "Test handler",
    code => sub {
### CODE:

lib/Acme/Crux.pm  view on Meta::CPAN

    my $elapsed = $app->elapsed( $timing_begin );

=head2 elapsed

    my $elapsed = $app->elapsed;

    my $timing_begin = [gettimeofday];
    # ... long operations ...
    my $elapsed = $app->elapsed( $timing_begin );

Return fractional amount of time in seconds since unnamed timstamp has been created while start application

    my $elapsed = $app->elapsed;
    $app->log->debug("Database stuff took $elapsed seconds");

For formatted output:

    $app->log->debug(sprintf("%+.*f sec", 4, $app->elapsed));

=head2 error

    my $error = $app->error;

Returns error string if occurred any errors while working with application

    $app = $app->error( "error text" );

Sets new error message and returns object

lib/Acme/Crux/Plugin/Config.pm  view on Meta::CPAN

    my $config = $app->plugin('Config');
    my $config = $app->plugin('Config', undef, {file => '/etc/myapp.conf'});

    # In application
    my $val = $app->config->get("/foo/bar/baz");
    my $all = $app->config->conf;

    my $array = $app->config->array('/foo'); # 'value'
        # ['value']

    my $hash = $app->config->hash('/foo'); # { foo => 'first', bar => 'second' }
        # { foo => 'first', bar => 'second' }

    my $first = $app->config->first('/foo'); # ['first', 'second', 'third']
        # first

    my $latest = $app->config->latest('/foo'); # ['first', 'second', 'third']
        # third

=head1 DESCRIPTION

The Acme::Crux plugin for configuration your application

=head1 OPTIONS

This plugin supports the following options

lib/Acrux/Config.pm  view on Meta::CPAN

    root => '/etc/myapp'

Sets the root directory to configuration files and directories location

=head1 METHODS

This plugin implements the following methods

=head2 array, list

    dumper $config->array('/foo'); # ['first', 'second', 'third']
        # ['first', 'second', 'third']
    dumper $config->array('/foo'); # 'value'
        # ['value']

Returns an array of found values from configuration

=head2 config, conf

    my $config_hash = $config->config; # { ... }

This method returns config structure directly as hash ref

=head2 error

    my $error = $config->error;

Returns error string if occurred any errors while creating the object or reading the configuration file

=head2 first

    say $config->first('/foo'); # ['first', 'second', 'third']
        # first

Returns an first value of found values from configuration

=head2 get

    say $config->get('/datadir');

Returns configuration value by path

=head2 hash, object

    dumper $config->hash('/foo'); # { foo => 'first', bar => 'second' }
        # { foo => 'first', bar => 'second' }

Returns an hash of found values from configuration

=head2 latest

    say $config->latest('/foo'); # ['first', 'second', 'third']
        # third

Returns an latest value of found values from configuration

=head2 load

    my $config = $config->load;

Loading config files

lib/Acrux/FileLock.pm  view on Meta::CPAN

=item debug

    debug => 0

Print debugging messages to STDERR (0=Off (default), 1=On)

=item delay

    delay => 60

Number of seconds to wait between retries to getting a lockfile

Default: 60

=item file

    file => '/tmp/test.lock'

The name of the lock file to work on. If not specified, a lock
file located in current directory will be created that matches F<./basename($0).lock>.

lib/Acrux/FileLock.pm  view on Meta::CPAN

        # Rename temp file to lock file
        for my $try (0 .. $self->{retries}) {
            unless ($self->check()) { # not exists, ok
                if (rename($tmp_file, $self->file)) {
                    $self->{_is_locked} = 1;
                    $self->_debug("Got lock file");
                    return $self;
                }
            }
            if ($self->{retries} && ($try != $self->{retries})) {
                $self->_debug(sprintf("Retrying in %d seconds", $self->{delay}));
                sleep $self->{delay} unless ($try == $self->{retries});
            }
        }

    } else {
        $self->error(sprintf("Could not write to %s: $!", $tmp_file))->_debug($self->error);
    }

    # Remove temp file in silent mode
    unlink $tmp_file if -f $tmp_file;

lib/Acrux/Util.pm  view on Meta::CPAN

With no arguments, returns the OS type for the current value of $^O.
If the operating system is not recognized, the function will return the empty string.

Original this function see in L<Perl::OSType/os_type>

=head2 parse_expire

    print parse_expire("+1d"); # 86400
    print parse_expire("-1d"); # -86400

Returns offset of expires time (in secs).

Original this function is the part of CGI::Util::expire_calc!

This internal routine creates an expires time exactly some number of hours from the current time.
It incorporates modifications from  Mark Fisher.

format for time can be in any of the forms:

    now   -- expire immediately
    +180s -- in 180 seconds
    +2m   -- in 2 minutes
    +12h  -- in 12 hours
    +1d   -- in 1 day
    +3M   -- in 3 months
    +2y   -- in 2 years
    -3m   -- 3 minutes ago(!)

If you don't supply one of these forms, we assume you are specifying the date yourself

=head2 parse_time_offset

    my $off = parse_time_offset("1h2m24s"); # 4344
    my $off = parse_time_offset("1h 2m 24s"); # 4344

Returns offset of time (in secs)

=head2 prompt

    my $value = prompt($message);
    my $value = prompt($message, $default);

The C<prompt()> is an extremely simple function, based on the extremely simple prompt
offered by L<ExtUtils::MakeMaker>. In many cases this function just to prompt for input

This function displays the message as a prompt for input and returns the (chomped)

lib/Acrux/Util.pm  view on Meta::CPAN


    print strf( $format, %data );
    print strf( $format, \%data );

The C<strf> function returns a string representing hash-data as string in specified C<$format>.
This function is somewhat similar to the C function strftime(), except that the data source
is not the date and time, but the set of data passed to the function.

The format string may be containing any combination of regular characters and special format
specifiers (patterns). These patterns are replaced to the corresponding values to represent
the data passed as  second function argument. They all begin with a percentage (%) sign,
and are: '%c' or '%{word}'. The "c" is single character specifier like %d, the "word" is
regular word like "month" or "filename"

If you give a pattern that doesn't exist, then it is simply treated as text.
If you give a pattern that doesn't defined but is exist in data set, then it will be
replaced to empty text string ('')

B<Please note!> All patterns C<'%%'> will be replaced to literal C<'%'> character if you not
redefinet this pattern in Your data set manually

lib/Acrux/Util.pm  view on Meta::CPAN

}
sub human2bytes {
    my $h = shift || 0;
    return 0 unless $h;
    my ($bts, $sfx) = $h =~ /([0-9.]+)\s*([a-zA-Z]*)/;
    return 0 unless $bts;
    my $exp = HUMAN_SUFFIXES->{($sfx ? uc($sfx) : "B")} || 0;
    return ceil($bts * (2 ** $exp));
}
sub humanize_duration {
    my $msecs = shift || 0;
    my $secs = int($msecs);
    my $years = int($secs / (60*60*24*365));
       $secs -= $years * 60*60*24*365;
    my $days = int($secs / (60*60*24));
       $secs -= $days * 60*60*24;
    my $hours = int($secs / (60*60));
       $secs -= $hours * 60*60;
    my $mins = int($secs / 60);
       $secs %= 60;
    if ($years) { return sprintf("%d years %d days %s hours", $years, $days, $hours) }
    elsif ($days) { return sprintf("%d days %s hours %d minutes", $days, $hours, $mins) }
    elsif ($hours) { return sprintf("%d hours %d minutes %d seconds", $hours, $mins, $secs) }
    elsif ($mins >= 2) { return sprintf("%d minutes %d seconds", $mins, $secs) }
    elsif ($secs > 5) { return sprintf("%d seconds", $secs + $mins * 60) }
    elsif ($msecs - $secs) { return sprintf("%.4f seconds", $msecs) }
    return sprintf("%d seconds", $secs);
}
sub fduration {
    my $msecs = shift || 0;
    my $secs = int($msecs);
    my $hours = int($secs / (60*60));
       $secs -= $hours * 60*60;
    my $mins = int($secs / 60);
       $secs %= 60;
    if ($hours) {
        return sprintf("%d hours %d minutes", $hours, $mins);
    } elsif ($mins >= 2) {
        return sprintf("%d minutes", $mins);
    } elsif ($secs < 2*60) {
        return sprintf("%.4f seconds", $msecs);
    } else {
        $secs += $mins * 60;
        return sprintf("%d seconds", $secs);
    }
}
sub humanize_number {
    my $var = shift || 0;
    my $sep = shift || "`";
    1 while $var=~s/(\d)(\d\d\d)(?!\d)/$1$sep$2/;
    return $var;
}

# Date and Time utils

lib/Acrux/Util.pm  view on Meta::CPAN

            'm' => 60,
            'h' => 60*60,
            'd' => 60*60*24,
            'w' => 60*60*24*7,
            'M' => 60*60*24*30,
            'y' => 60*60*24*365
        );
    if (!$t || (lc($t) eq 'now')) {
        return 0;
    } elsif ($t =~ /^\d+$/) {
        return $t; # secs
    } elsif ($t=~/^([+-]?(?:\d+|\d*\.\d*))([smhdwMy])/) {
        return ($mult{$2} || 1) * $1;
    }
    return $t;
}
sub parse_time_offset {
    my $s = trim(shift(@_) // 0);
    return $s if $s =~ /^\d+$/;
    my $r = 0;
    my $c = 0;

t/11-strf.t  view on Meta::CPAN

# M   Minute as a zero-padded decimal number                  00, 01, ..., 59
# p   AM or PM designation                                    AM, PM
# S   Second as a zero-padded decimal number                  00, 01, ..., 59
# U   Week number of the year (Sunday as the first day)       00, 01, ..., 53
# w   Weekday as a decimal number with Sunday as 0 (0-6)      0, 1, ..., 6
# W   Week number of the year (Monday as the first day)       00, 01, ..., 53
# y   Year without century as a zero-padded decimal number    00, 01, ..., 99
# Y   Year                                                    2001, 2024 etc.

use POSIX qw/strftime/;
my $now = time; # The number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC)
my %t = ('s' => $now);
my @fmt = qw/%a %A %b %B %d %e %H %I %j %m %M %p %S %U %w %W %y %Y/;
my @adt = split /#+/, strftime(join('#', @fmt), localtime($now));
#diag explain \@adt;
for (@fmt) { s/%//; $t{$_} = shift @adt };
#diag explain \%t;

# RFC 3339/ISO 8601
my $rfc = '%Y-%m-%dT%H:%M:%S';
is( strf($rfc, %t), strftime($rfc, localtime($now)), "RFC 3339/ISO 8601" ); # 2024-06-05T10:37:47



( run in 1.379 second using v1.01-cache-2.11-cpan-39bf76dae61 )