Skip to content

Instantly share code, notes, and snippets.

@relipse
Created October 18, 2013 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save relipse/7034698 to your computer and use it in GitHub Desktop.
Save relipse/7034698 to your computer and use it in GitHub Desktop.
The goal of this script [right now] is to tell you how to "undo" a command. for example undo cd path/to/somewhere would result in "cd -" which will go back to the previous directory, and for example if you do mv path/to/a path/to/b this would produce "mv path/to/b path/to/a"
#!/usr/bin/php
<?php
if (!isset($argv[1])){
die('Usage: undo <command-to-try-and-undo>'."\n");
}
$OLDPWD = `echo "\$OLDPWD"`;
$allargs = $argv;
array_shift($allargs);
$undo = new Undo($allargs);
$reverse_cmd = $undo->getReverseCommand();
if ($reverse_cmd){
echo $reverse_cmd;
}else{
echo "'".$allargs[0].'\' not yet supported. Supported reversable commands are: '.Undo::GetSupportedCommands();
}
die("\n");
class Undo{
public static $quick_reverse = array('cd'=>'cd -');
public static $twolevel_reverse = array('git checkout'=>'git checkout -');
public static $special_reverse = array('mv'=>'mv {2} {1}');
public static function GetSupportedCommands(){ return implode(array_keys(self::$quick_reverse),','); }
//------------------------------------------------------------------------------------------
private $cmd_str = '';
private $cmd_ary = array();
public function __construct($cmd_ary){
$this->cmd_str = implode($cmd_ary, ' ');
$this->cmd_ary = $cmd_ary;
}
public function getReverseCommand($cmd = null, $ary = null){
if ($cmd === null){ $cmd = $this->cmd_str; }
if ($ary === null){ $ary = $this->cmd_ary; }
$cmd = strtolower($cmd);
if (isset(self::$quick_reverse[$ary[0]])){
return self::$quick_reverse[$ary[0]];
}
if (isset($ary[1])){
if (isset(self::$twolevel_reverse[$ary[0].' '.$ary[1]])){
return self::$twolevel_reverse[$ary[0].' '.$ary[1]];
}
}
foreach(self::$special_reverse as $scmd => $reversal_cmd){
if ($scmd === $ary[0]){
$newcmd = '';
$newcmd = $reversal_cmd;
foreach($ary as $i => $arg){
$newcmd = str_replace('{'.$i.'}', $ary[$i], $newcmd);
}
return $newcmd;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment