The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

App::bif - A base class for App::bif::* commands

VERSION

0.1.5_4 (2015-08-04)

SYNOPSIS

    # In App/bif/command/name.pm
    use strict;
    use warnings;
    use parent 'App::bif';

    sub run {
        my $self = shift;
        my $db   = $self->db;
        my $data = $db->xarrayref(...);

        return $self->err( 'SomeFailure', 'something failed' )
          if ( $self->{command_option} );

        $self->start_pager;

        print $self->render_table( ' r  l  l ',
            [qw/ ID Title Status /], $data, );



        return $self->ok('CommandName');
    }

DESCRIPTION

App::bif provides a context/configuration class for bif commands to inherit from. The above synopsis is the basic template for any bif command. At run time the run method is called.

App::bif sets the encoding of STDOUT and STDIN to utf-8 when it is loaded.

CONSTRUCTOR

new( opts => $opts )

Initializes the common elements of all bif scripts. Requires the options hashref as provided by OptArgs but also returns it.

  • Sets the package variable $App::bif::STDOUT_TERMINAL to true if STDOUT is connected to a terminal.

  • Sets the environment variable ANSI_COLORS_DISABLED to 1 if STDOUT is not connected to a terminal, in order to disable Term::ANSIColor functions.

  • Starts a pager if --debug is true, unless --no-pager is also set to true or STDOUT is not connected to a terminal.

  • Adds unfiltered logging via Log::Any::Adapter::Stdout.

ATTRIBUTES

To be documented.

METHODS

colours( @colours ) -> @codes

Calls color() from Term::ANSIColor on every string from @colours and returns the results. Returns empty strings if the environment variable $ANSI_COLORS_DISABLED is true (set by the --no-color option).

header( $key, $val, $val2 ) -> ArrayRef

Returns a two or three element arrayref formatted as so:

    ["$key:", $val, "<$val2>"]

Colours are used to make the $val2 variable darker. The result is generally used when rendering tables by log and show commands.

ago( $epoch, $offset ) -> $string, $timestamp

Uses Time::Duration to generate a human readable $string indicating how long ago UTC $epoch was (with $offset in +/- seconds) plus a regular timestamp string.

err( $err, $message, [ @args ])

Throws an exception that stringifies to $message prefixed with "fatal: ". The exception is an object from the Bif::Error::$err class which is used by test scripts to reliably detect the type of error. If @args exists then $message is assumed to be a format string to be converted with sprintf.

ok( $type, [ $arg ])

Returns a Bif::OK::$type object, either as a reference to $arg or as a reference to the class name. Every App::bif::* command should return such an object, which can be tested for by tests.

start_pager([ $rows ])

Start a pager (less, more, etc) on STDOUT using IO::Pager, provided that --no-pager has not been used. The pager handle encoding is set to utf-8. If the optional $rows has been given then the pager will only be started if Term::Size reports the height of the terminal as being less than $rows.

end_pager

Stops the pager on STDOUT if it was previously started.

user_repo -> Path::Tiny

Returns the location of the user repository directory. Raises a 'UserRepoNotFound' error on failure.

user_db -> Bif::DB::db

Returns a read-only handle for the SQLite database containing user-specific data.

user_dbw -> Bif::DBW::db

Returns a read-write handle for the SQLite database containing user-specific data.

repo -> Path::Tiny

Return the path to the first '.bif' directory found starting from the current working directory and searching upwards. Raises a 'RepoNotFound' error on failure.

db -> Bif::DB::db

Returns a handle for the SQLite database in the current respository (as found by bif_repo). The handle is only good for read operations - use $self-dbw> when inserting,updating or deleting from the database.

You should manually import any DBIx::ThinSQL functions you need only after calling bif_db, in order to keep startup time short for cases such as when the repository is not found.

dbw -> Bif::DBW::db

Returns a handle for the SQLite database in the current respository (as found by bif_repo). The handle is good for INSERT, UPDATE and DELETE operations.

You should manually import any DBIx::ThinSQL functions you need only after calling $self-dbw>, in order to keep startup time short for cases such as when the repository is not found.

new_cmd($class, %attrs)

Loads $class and creates a new object from that class populated with the attributes from $self plus the attributes in the %attrs HASH.

dispatch($class, $attrs)

Loads the bif class $class, creates a new object populated with the attributes from $self plus the attributes in the HASHref $attrs and runs the run() method.

run

App::bif is responsible for expanding user aliases and redispatching to the actual command. Needs to be documented .... sorry.

user_id -> Int

Returns the topic ID for the user (self) identity.

uuid2id( $try ) -> Int

Returns $try unless a $self->{uuid} option has been set. Returns Bif::DB->uuid2id($try) if the lookup succeeds or else raises an error.

get_project( $path ) -> HashRef

Calls get_project from Bif::DB and returns a single hashref. Raises an error if no project is found. $path is interpreted as a string of the form PROJECT[@HUB].

get_hub( $name ) -> HashRef

Looks up the hub where $name is either the topic ID, the hub name, or a hub location and returns the equivalent of get_topic($ID) plus the hub name.

render_table( $format, \@header, \@data, [ $indent ] ) -> Str

Uses Text::FormatTable to construct a table of <@data>, aligned and spaced according to $format, preceded by a @header. If $indent is greater than zero then the entire table is indented by that number of spaces.

prompt_edit( %options ) -> Str

If the environment is interactive this function will invoke an editor and return the result. All comment lines (beginning with '#') are removed. TODO: describe %options.

lprint( $msg ) -> Int

If a pager is not active this method prints $msg to STDOUT and returns the cursor to the beginning of the line. The next call over-writes the previously printed text before printing the new $msg. In this way a continually updating status can be displayed.

get_change( $CID, [$first_change_id] ) -> HashRef

Looks up the change identified by $CID (of the form "c23") and returns a hash reference containg the following keys:

  • id - the change ID

  • uuid - the universally unique identifier of the change

An ChangeNotFound error will be raised if the change does not exist. If $first_change_id is provided then a check will be made to ensure that that $CID is a child of <$first_change_id> with a FirstChangeMismatch error thrown if that is not the case.

get_topic( $TOKEN ) -> HashRef

Looks up the topic identified by $TOKEN and returns undef or a hash reference containg the following keys:

  • id - the topic ID

  • first_change_id - the change_id that created the topic

  • kind - the type of the topic

  • uuid - the universally unique identifier of the topic

current_work -> HashRef

Returns a hashref representing the currently open work buffer:

  • topic_id

  • kind

  • path

  • start

  • billable

start_work(%opts)

Creates a new entry in the work_buffers table.

  • topic_id

  • start

  • start_comment

  • stop

  • stop_comment

  • billable

  • save

stop_work(%opts)

Ensures nothing is worked, finalizing an open entry in the work_buffers table if one exists.

  • stop

  • stop_comment

  • restore

  • save

new_change( %args ) -> Int

Creates a new row in the changes table according to the content of %args (must include at least a message value) and the current context (identity). Returns the integer ID of the change.

check( $id ) -> (Bool,Str)

Computes the uuid of the change $id and compares it against the stored uuid value. Returns two variables: the first is a true/false scalar indicating validity, and the second is a human-readable status string.

A valid uuid example:

    [u.a83372c(.11)] some action string

An invalid uuid example:

    [u.328ea8b(.12)] another action string INVALID
s2hms($seconds) -> '+hh:mm:ss'

Converts the integer $seconds into a string representing the hours, minutes and seconds that make up the delta.

s2hm($seconds) -> '+hh:mm'

Converts the integer $seconds into a string representing the hours and minutes that make up the delta.

datetime2s($str) -> $epoch

Converts a partial date/time string into a UNIX epoch, with certain assumptions as to the date. Accepts the following variations:

  • [h]h:mm

  • [h]h:mm:ss

  • yesterday [h]h:mm

  • yesterday [h]h:mm:ss

  • yyyy-mm-dd

  • yyyy-mm-dd [h]h:mm

  • yyyy-mm-dd [h]h:mm:ss

SEE ALSO

Bif::DB, Bif::DBW

AUTHOR

Mark Lawrence <nomad@null.net>

COPYRIGHT AND LICENSE

Copyright 2013-2015 Mark Lawrence <nomad@null.net>

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.