4 * This file is part of Psy Shell.
6 * (c) 2012-2018 Justin Hileman
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Psy\Command;
14 use Psy\Input\FilterOptions;
15 use Psy\Output\ShellOutput;
16 use Psy\Readline\Readline;
17 use Symfony\Component\Console\Formatter\OutputFormatter;
18 use Symfony\Component\Console\Input\InputInterface;
19 use Symfony\Component\Console\Input\InputOption;
20 use Symfony\Component\Console\Output\OutputInterface;
23 * Psy Shell history command.
25 * Shows, searches and replays readline history. Not too shabby.
27 class HistoryCommand extends Command
35 public function __construct($name = null)
37 $this->filter = new FilterOptions();
39 parent::__construct($name);
43 * Set the Shell's Readline service.
45 * @param Readline $readline
47 public function setReadline(Readline $readline)
49 $this->readline = $readline;
55 protected function configure()
57 list($grep, $insensitive, $invert) = FilterOptions::getOptions();
61 ->setAliases(['hist'])
63 new InputOption('show', 's', InputOption::VALUE_REQUIRED, 'Show the given range of lines.'),
64 new InputOption('head', 'H', InputOption::VALUE_REQUIRED, 'Display the first N items.'),
65 new InputOption('tail', 'T', InputOption::VALUE_REQUIRED, 'Display the last N items.'),
71 new InputOption('no-numbers', 'N', InputOption::VALUE_NONE, 'Omit line numbers.'),
73 new InputOption('save', '', InputOption::VALUE_REQUIRED, 'Save history to a file.'),
74 new InputOption('replay', '', InputOption::VALUE_NONE, 'Replay.'),
75 new InputOption('clear', '', InputOption::VALUE_NONE, 'Clear the history.'),
77 ->setDescription('Show the Psy Shell history.')
80 Show, search, save or replay the Psy Shell history.
83 <return>>>> history --grep /[bB]acon/</return>
84 <return>>>> history --show 0..10 --replay</return>
85 <return>>>> history --clear</return>
86 <return>>>> history --tail 1000 --save somefile.txt</return>
94 protected function execute(InputInterface $input, OutputInterface $output)
96 $this->validateOnlyOne($input, ['show', 'head', 'tail']);
97 $this->validateOnlyOne($input, ['save', 'replay', 'clear']);
99 $history = $this->getHistorySlice(
100 $input->getOption('show'),
101 $input->getOption('head'),
102 $input->getOption('tail')
104 $highlighted = false;
106 $this->filter->bind($input);
107 if ($this->filter->hasFilter()) {
110 foreach ($history as $i => $line) {
111 if ($this->filter->match($line, $matches)) {
112 if (isset($matches[0])) {
113 $chunks = explode($matches[0], $history[$i]);
114 $chunks = array_map([__CLASS__, 'escape'], $chunks);
115 $glue = sprintf('<urgent>%s</urgent>', self::escape($matches[0]));
117 $highlighted[$i] = implode($glue, $chunks);
125 if ($save = $input->getOption('save')) {
126 $output->writeln(sprintf('Saving history in %s...', $save));
127 file_put_contents($save, implode(PHP_EOL, $history) . PHP_EOL);
128 $output->writeln('<info>History saved.</info>');
129 } elseif ($input->getOption('replay')) {
130 if (!($input->getOption('show') || $input->getOption('head') || $input->getOption('tail'))) {
131 throw new \InvalidArgumentException('You must limit history via --head, --tail or --show before replaying');
134 $count = count($history);
135 $output->writeln(sprintf('Replaying %d line%s of history', $count, ($count !== 1) ? 's' : ''));
136 $this->getApplication()->addInput($history);
137 } elseif ($input->getOption('clear')) {
138 $this->clearHistory();
139 $output->writeln('<info>History cleared.</info>');
141 $type = $input->getOption('no-numbers') ? 0 : ShellOutput::NUMBER_LINES;
143 $type = $type | ShellOutput::OUTPUT_RAW;
146 $output->page($highlighted ?: $history, $type);
151 * Extract a range from a string.
153 * @param string $range
155 * @return array [ start, end ]
157 private function extractRange($range)
159 if (preg_match('/^\d+$/', $range)) {
160 return [$range, $range + 1];
164 if ($range !== '..' && preg_match('/^(\d*)\.\.(\d*)$/', $range, $matches)) {
165 $start = $matches[1] ? intval($matches[1]) : 0;
166 $end = $matches[2] ? intval($matches[2]) + 1 : PHP_INT_MAX;
168 return [$start, $end];
171 throw new \InvalidArgumentException('Unexpected range: ' . $range);
175 * Retrieve a slice of the readline history.
177 * @param string $show
178 * @param string $head
179 * @param string $tail
181 * @return array A slilce of history
183 private function getHistorySlice($show, $head, $tail)
185 $history = $this->readline->listHistory();
187 // don't show the current `history` invocation
191 list($start, $end) = $this->extractRange($show);
192 $length = $end - $start;
194 if (!preg_match('/^\d+$/', $head)) {
195 throw new \InvalidArgumentException('Please specify an integer argument for --head');
199 $length = intval($head);
201 if (!preg_match('/^\d+$/', $tail)) {
202 throw new \InvalidArgumentException('Please specify an integer argument for --tail');
205 $start = count($history) - $tail;
206 $length = intval($tail) + 1;
211 return array_slice($history, $start, $length, true);
215 * Validate that only one of the given $options is set.
217 * @param InputInterface $input
218 * @param array $options
220 private function validateOnlyOne(InputInterface $input, array $options)
223 foreach ($options as $opt) {
224 if ($input->getOption($opt)) {
230 throw new \InvalidArgumentException('Please specify only one of --' . implode(', --', $options));
235 * Clear the readline history.
237 private function clearHistory()
239 $this->readline->clearHistory();
242 public static function escape($string)
244 return OutputFormatter::escape($string);