Skip to content
Er Galvão Abbott edited this page Sep 29, 2024 · 4 revisions

Data Sample

The following sample was created from my bash history, and examples from a couple of man pages:

exit 0
rm -rf ~/foo/test/
cd bin/
ping www.google.com
zypper se traceroute
sudo zypper in traceroute
sudo vi /etc/routes
ls -lAR
ls -lAR /home/zaphod/
ls -lA --recursive /home/zaphod/
composer require laminas/laminas-mezzio
nvim --version
git merge --allow-unrelated-histories master
composer require laminas/laminas-log
chown -R zaphod:wwwrun /srw/www/htdocs
git push --set-upstream origin master
ls --classify=always
exit

shelly-api's parser treats the each of the above sample correctly.

Differences from bash

  • Only verbose flags may contain a value (e.g.: --classify=always) and in that case must use the equal sign as an operator and must not contain spaces between operands and operator.

PoC

#!/usr/bin/php
<?php
$samples = [
    'exit 0',
    'rm -rf ~/foo/test/',
    'cd bin/',
    'ping www.google.com',
    'zypper se traceroute',
    'sudo zypper in traceroute',
    'sudo vi /etc/routes',
    'ls -lAR',
    'ls -lAR /home/zaphod/',
    'ls -lA --recursive /home/zaphod/',
    'composer require laminas/laminas-mezzio',
    'nvim --version',
    'git merge --allow-unrelated-histories master',
    'composer require laminas/laminas-log',
    'chown -R zaphod:wwwrun /srw/www/htdocs/',
    'git push --set-upstream origin master',
    'ls --classify=always',
    'exit',
];

foreach($samples as $input) {
    $segments = explode(' ', trim($input));
    $command = array_shift($segments);

    echo PHP_EOL . '-----------------------------------------------------------------------------' . PHP_EOL;
    echo PHP_EOL . 'Input: ' . $input . PHP_EOL;
    echo PHP_EOL . 'Command: ' . $command;

    foreach ($segments as $segment) {
        $output = '';
        $trimmedSegment = trim($segment, ' -');

        if ($segment[0] === '-') {
            $output .= 'Flag';

            if ($segment[1] === '-') {
                list($name, $value) = explode('=', $trimmedSegment);

                $output = 'Verbose ' . $output . ': ' . $name . ($value === null ? '' : ' with value: ' . $value);
            } else {
                if (strlen($trimmedSegment) > 1) {
                    $output .= 's: ' . implode(', ', str_split($trimmedSegment));
                } else {
                    $output .= ': ' . $trimmedSegment;
                }
            }
        } else {
            $output .= 'Subcommand / Argument: ' . $trimmedSegment;
        }

        echo PHP_EOL . $output;
    }

    echo PHP_EOL;
}
Clone this wiki locally