taeluf/cli

v0.1.x-dev 2024-02-03 13:23 UTC

This package is auto-updated.

Last update: 2024-03-03 20:59:02 UTC


README

A (hopefully) simple framework for running cli apps. It is not very feature rich. (no automatic help menus and not really any built-in cli functions)

Install

composer require taeluf/cli v0.1.x-dev   

or in your composer.json

{"require":{ "taeluf/cli": "v0.1.x-dev"}}  

Get Started

Use the built-in cli to generate a cli starter script for you, then edit it to fit your needs.

vendor/bin/tlf-cli setup  

Usage

Generally, you'll make an executable file with the #!/usr/bin/env php shebang at the top, then a <?php on the next line, then your script to follow.

Here is a sample we use for testing

#!/usr/bin/env php  
<?php  
/**  
 * This file is to be a sample cli setup, like somebody would write if they were implementing this library.  
 *  
 * So let's try to implement 3 cli functions  
 *  
 * proto & proto main  ## print some useless information  
 * proto rand -chars abc -len 20 ## generate a random number  
 * proto evens -from 1 -to 113   
 *        ## get all even numbers in the range  
 *        ## defaults to -from 0 -to 50  
 *  
 */  
  
require(__DIR__.'/../code/Msgs.php');  
require(__DIR__.'/../code/Cli.php');  
  
  
$cli = new \Tlf\Cli();  
// load_json_file fails silently if the file does not exist  
$cli->load_json_file(__DIR__.'/defaults.json');   
$cli->load_inputs(json_decode(file_get_contents(__DIR__.'/user_configs.json'),true));  
$cli->load_stdin();  
  
$cli->load_command('main',  
    function($cli, $args){  
        echo "pointless output";  
    }  
);  
  
$cli->load_command('rand',   
    function($cli, $args){  
  
        $chars = $args['chars'];  
        $len = $args['len'];  
        $random = '';  
        $i = 0;  
        while(++$i<=$len){  
            $random .=   
                $chars[random_int(0,strlen($chars)-1)];  
        }  
  
        echo $random;  
    }, "generate a random number from --chars string of --length int"  
);  
  
$cli->load_command('evens',  
    function($cli, $args){  
        extract($args);  
        $i = $from;  
        do {  
            if ($i%2==0)echo $i."\n";  
        } while ($i++<$to);  
    }, "list even numbers. --from int --to int"  
);  
  
  
  
  
$cli->execute();  

Testing this lib

I don't use my testing framework, since my testing framework uses this & a circular dependency like that is just a headache.

To test this lib during development run php test/test.php

The tests are simple & should stay that way.

TODO

  • Write better documentation???