dit-php/dit.php

86 lines
1.9 KiB
PHP
Executable File

#!/usr/bin/php
<?php
$argv[1] = $argv[1] ?? 'now';
$options = getopt('f:t:z:', ['from:', 'to:', 'timezone:'], $rest_index);
$args = array_slice($argv, $rest_index);
foreach ($options as $opt)
if (is_array($opt)) {
fwrite(STDERR, 'You can\'t set multiple time the same option' . PHP_EOL);
exit(1);
}
$tz = $options['timezone'] ?? $options['z'] ?? 'UTC';
if (date_default_timezone_set($tz) !== true) {
fwrite(STDERR, 'Unknown timezone' . PHP_EOL);
exit(1);
}
$from = NULL;
if (isset($options['from']) OR isset($options['f'])) {
$from = $options['from'] ?? $options['f'];
if (!in_array($from, ['local', 'unix', 'dit'])) {
fwrite(STDERR, 'Unknown --from value' . PHP_EOL);
exit(1);
}
}
$to = NULL;
if (isset($options['to']) OR isset($options['t'])) {
$to = $options['to'] ?? $options['t'];
if (!in_array($to, ['local', 'unix', 'dit'])) {
fwrite(STDERR, 'Unknown --to value' . PHP_EOL);
exit(1);
}
}
require 'libdit.php';
if (isset($args[0]) AND $args[0] === '-')
foreach (stream_stdin() as $line)
display($line, $from, $to, $tz);
else
foreach ($args as $arg)
display($arg, $from, $to, $tz);
function display($arg, $from, $to, $tz) {
if (rtrim($arg) === 'exit' OR rtrim($arg) === 'quit')
exit(0);
if ($from === NULL) {
if (($unix = stardit_to_unix($arg)) !== false)
$from = 'dit';
else {
if (!($unix = strtotime($arg, time()))) {
fwrite(STDERR, 'String argument "' . $arg . '" can\'t be translated to time' . PHP_EOL);
exit(1);
} else {
$from = 'local';
}
}
}
$unix = match ($from) {
'dit' => stardit_to_unix($arg),
'unix' => $arg,
'local' => strtotime($arg, time()),
};
if ($to === NULL) {
$to = match ($from) {
'dit' => 'local',
'local','unix' => 'dit',
};
}
echo match ($to) {
'dit' => unix_to_stardit($unix),
'unix' => $unix,
'local' => date("Y/m/d H:i:s e", $unix),
} . PHP_EOL;
}
function stream_stdin() {
while ($line = fgets(STDIN))
yield $line;
}