IndentShell.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. <?php
  2. //Configure::write('debug', 1);
  3. if (!defined('TB')) {
  4. define('TB', "\t");
  5. }
  6. if (!defined('NL')) {
  7. define('NL', "\n");
  8. }
  9. if (!defined('CR')) {
  10. define('CR', "\r");
  11. }
  12. App::uses('Folder', 'Utility');
  13. App::uses('AppShell', 'Console/Command');
  14. /**
  15. * Indent Shell
  16. *
  17. * Correct indentation of files in a folder recursivly.
  18. * Useful if files contain either only spaces or even a mixture of spaces and tabs.
  19. * It can be a bitch to get this straightened out. Mix in a mixture of different space
  20. * lengths and it is a nightmare.
  21. * Using IDE specific beautifier is not always an option, either. They usually reformat
  22. * arrays and other things in a way you don't want. No matter how hard you try to set it
  23. * up correctly.
  24. *
  25. * This addresses the issue in a clean way and only modifies whitespace at the beginning
  26. * of a line.
  27. * Single "accidental" spaces will be filtered out automatically.
  28. *
  29. * Tip: For different space lenghts use multiple times from largest to smallest length.
  30. * E.g "-s 8", then "-s 4" and maybe even "-s 2".
  31. *
  32. * Oh, and: Use TABS for indentation of code - ALWAYS.
  33. *
  34. * @author Mark Scherer
  35. * @license http://opensource.org/licenses/mit-license.php MIT
  36. */
  37. class IndentShell extends AppShell {
  38. public $settings = array(
  39. 'files' => array('php', 'ctp', 'inc', 'tpl'),
  40. 'againWithHalf' => false, # if 4, go again with 2 afterwards
  41. 'outputToTmp' => false, # write to filename_.ext
  42. 'debug' => false # add debug info after each line
  43. );
  44. protected $_changes = null;
  45. protected $_paths = array();
  46. protected $_files = array();
  47. /**
  48. * Main execution function to indent a folder recursivly
  49. *
  50. * @return void
  51. */
  52. public function folder() {
  53. if (!empty($this->params['extensions'])) {
  54. $this->settings['files'] = String::tokenize($this->params['extensions']);
  55. }
  56. if (!empty($this->params['again'])) {
  57. $this->settings['againWithHalf'] = true;
  58. }
  59. if (!empty($this->args)) {
  60. if (!empty($this->args[0]) && $this->args[0] !== 'app') {
  61. $folder = $this->args[0];
  62. if ($folder === '/') {
  63. $folder = APP;
  64. }
  65. $folder = realpath($folder);
  66. if (!file_exists($folder)) {
  67. return $this->error('folder not exists: ' . $folder . '');
  68. }
  69. $this->_paths[] = $folder;
  70. } elseif ($this->args[0] === 'app') {
  71. $this->_paths[] = APP;
  72. }
  73. if (!empty($this->params['files'])) {
  74. $this->settings['files'] = explode(',', $this->params['files']);
  75. }
  76. $this->out($folder);
  77. $this->out('searching...');
  78. $this->_searchFiles();
  79. $this->out('found: ' . count($this->_files));
  80. if (!empty($this->params['dry-run'])) {
  81. $this->out('TEST DONE');
  82. } else {
  83. $continue = $this->in('Modifying files! Continue?', array('y', 'n'), 'n');
  84. if (strtolower($continue) !== 'y' && strtolower($continue) !== 'yes') {
  85. return $this->error('...aborted');
  86. }
  87. $this->_correctFiles();
  88. $this->out('DONE');
  89. }
  90. } else {
  91. $this->out('Usage: cake intend folder');
  92. $this->out('"folder" is then intended recursivly');
  93. $this->out('default file types are');
  94. $this->out('[' . implode(', ', $this->settings['files']) . ']');
  95. $this->out('');
  96. $this->out('Specify file types manually:');
  97. $this->out('-files php,js,css');
  98. }
  99. }
  100. /**
  101. * IndentShell::_write()
  102. *
  103. * @param mixed $file
  104. * @param mixed $text
  105. * @return bool Success
  106. */
  107. protected function _write($file, $text) {
  108. $text = implode(PHP_EOL, $text);
  109. if ($this->settings['outputToTmp']) {
  110. $filename = extractPathInfo('file', $file);
  111. if (mb_substr($filename, -1, 1) === '_') {
  112. return;
  113. }
  114. $file = extractPathInfo('dir', $file) . DS . $filename . '_.' . extractPathInfo('ext', $file);
  115. }
  116. return (bool)file_put_contents($file, $text);
  117. }
  118. /**
  119. * IndentShell::_read()
  120. *
  121. * @param mixed $file
  122. * @return array
  123. */
  124. protected function _read($file) {
  125. $text = file_get_contents($file);
  126. if (empty($text)) {
  127. return array();
  128. }
  129. $pieces = explode(NL, $text);
  130. return $pieces;
  131. }
  132. /**
  133. * NEW TRY!
  134. * idea: just count spaces and replace those
  135. *
  136. * @return void
  137. */
  138. protected function _correctFiles() {
  139. foreach ($this->_files as $file) {
  140. $this->_changes = false;
  141. $textCorrect = array();
  142. $pieces = $this->_read($file);
  143. $spacesPerTab = $this->params['spaces'];
  144. foreach ($pieces as $piece) {
  145. $tmp = $this->_process($piece, $spacesPerTab);
  146. if ($this->settings['againWithHalf'] && $spacesPerTab % 2 === 0 && $spacesPerTab > 3) {
  147. $tmp = $this->_process($tmp, $spacesPerTab / 2);
  148. }
  149. $tmp = $this->_processSpaceErrors($tmp, 1);
  150. $textCorrect[] = $tmp;
  151. }
  152. if ($this->_changes) {
  153. $this->_write($file, $textCorrect);
  154. }
  155. }
  156. }
  157. /**
  158. * @return string
  159. */
  160. protected function _process($piece, $spacesPerTab) {
  161. $pos = -1;
  162. $spaces = $mod = $tabs = 0;
  163. $debug = '';
  164. $newPiece = $piece;
  165. if ($spacesPerTab) {
  166. //TODO
  167. while (mb_substr($piece, $pos + 1, 1) === ' ' || mb_substr($piece, $pos + 1, 1) === TB) {
  168. $pos++;
  169. }
  170. $piece1 = mb_substr($piece, 0, $pos + 1);
  171. $piece1 = str_replace(str_repeat(' ', $spacesPerTab), TB, $piece1, $count);
  172. if ($count > 0) {
  173. $this->_changes = true;
  174. }
  175. $piece2 = mb_substr($piece, $pos + 1);
  176. $newPiece = $piece1 . $piece2;
  177. }
  178. $newPiece = rtrim($newPiece) . $debug;
  179. if ($newPiece != $piece || strlen($newPiece) !== strlen($piece)) {
  180. $this->_changes = true;
  181. }
  182. return $newPiece;
  183. }
  184. /**
  185. * NEW TRY!
  186. * idea: hardcoded replaceing
  187. *
  188. * @deprecated
  189. */
  190. protected function _processSpaceErrors($piece, $space = 1) {
  191. $newPiece = $piece;
  192. $spaceChar = str_repeat(' ', $space);
  193. if (mb_substr($newPiece, 0, $space) === $spaceChar && mb_substr($newPiece, $space, 1) === TB) {
  194. $newPiece = mb_substr($newPiece, $space);
  195. }
  196. if (($pos = mb_strpos($newPiece, $space)) > 0 && mb_substr($newPiece, $pos - 1, 1) === TB) {
  197. $newPiece = mb_substr($newPiece, $pos) . mb_substr($newPiece, $pos + 2);
  198. }
  199. $newPiece = str_replace($spaceChar . TB, TB, $newPiece);
  200. if ($newPiece !== $piece) {
  201. $this->_changes = true;
  202. }
  203. return $newPiece;
  204. }
  205. /**
  206. * Old try - sometimes TABS at the beginning are not recogized...
  207. * idea: strip tabs and spaces, remember their amount and add tabs again!
  208. *
  209. * @deprecated
  210. */
  211. protected function _correctFilesTry() {
  212. foreach ($this->_files as $file) {
  213. $changes = false;
  214. $textCorrect = array();
  215. $pieces = $this->_read($file);
  216. foreach ($pieces as $piece) {
  217. $pos = -1;
  218. $spaces = $mod = $tabs = 0;
  219. $debug = '';
  220. $newPiece = trim($piece, CR);
  221. $newPiece = trim($newPiece, NL);
  222. //$debug .= ''.stripos($newPiece, TB);
  223. // detect tabs and whitespaces at the beginning
  224. //while (($pieceOfString = mb_substr($newPiece, 0, 1)) === ' ' || ($pieceOfString = mb_substr($newPiece, 0, 1)) == TB) {
  225. while ((stripos($newPiece, ' ')) === 0 || (stripos($newPiece, TB)) === 0) {
  226. $pieceOfString = mb_substr($newPiece, 0, 1);
  227. if ($pieceOfString === ' ') {
  228. $pos++;
  229. $spaces++;
  230. } elseif ($pieceOfString === TB) {
  231. $pos++;
  232. $spaces += $this->settings['spacesPerTab'];
  233. } else {
  234. return $this->error('???');
  235. }
  236. $newPiece = mb_substr($newPiece, 1);
  237. }
  238. if ($pos >= 1) {
  239. $changes = true;
  240. // if only spaces and tabs, we might as well trim the line
  241. //should be done
  242. // now correct
  243. //$newPiece = mb_substr($piece, $pos + 1);
  244. // clear single spaces
  245. /*
  246. if (mb_substr($newPiece, 0, 1) === ' ' && mb_substr($newPiece, 1, 1) !== '*') {
  247. $newPiece = mb_substr($newPiece, 1);
  248. }
  249. */
  250. $mod = $spaces % $this->settings['spacesPerTab'];
  251. $tabs = ($spaces - $mod) / $this->settings['spacesPerTab'];
  252. //$beginning = str_replace(' ', TB, $piece);
  253. $beginning = str_repeat(TB, $tabs);
  254. $beginning .= str_repeat(' ', $mod);
  255. $newPiece = $beginning . trim($newPiece);
  256. } else {
  257. $newPiece = rtrim($newPiece);
  258. }
  259. if ($this->settings['debug']) {
  260. $debug .= ' ' . ($changes ? '[MOD]' : '[]') . ' (SPACES ' . $tabs . ', POS ' . $pos . ', TABS ' . $tabs . ', MOD ' . $mod . ')';
  261. }
  262. $textCorrect[] = $newPiece . $debug;
  263. }
  264. if ($changes) {
  265. $this->_write($file, $textCorrect);
  266. }
  267. //die();
  268. }
  269. }
  270. /**
  271. * Search files that may contain translateable strings
  272. *
  273. * @return void
  274. */
  275. protected function _searchFiles() {
  276. foreach ($this->_paths as $path) {
  277. $Folder = new Folder($path);
  278. $files = $Folder->findRecursive('.*\.(' . implode('|', $this->settings['files']) . ')', true);
  279. foreach ($files as $file) {
  280. if (strpos($file, DS . 'Vendor' . DS) !== false) {
  281. continue;
  282. }
  283. $this->_files[] = $file;
  284. }
  285. }
  286. }
  287. public function getOptionParser() {
  288. $subcommandParser = array(
  289. 'options' => array(
  290. 'dry-run' => array(
  291. 'short' => 'd',
  292. 'help' => 'Dry run the update, no files will actually be modified.',
  293. 'boolean' => true
  294. ),
  295. 'log' => array(
  296. 'short' => 'l',
  297. 'help' => 'Log all ouput to file log.txt in TMP dir',
  298. 'boolean' => true
  299. ),
  300. 'interactive' => array(
  301. 'short' => 'i',
  302. 'help' => 'Interactive',
  303. 'boolean' => true
  304. ),
  305. 'spaces' => array(
  306. 'short' => 's',
  307. 'help' => 'Spaces per Tab',
  308. 'default' => '4',
  309. ),
  310. 'extensions' => array(
  311. 'short' => 'e',
  312. 'help' => 'Extensions (comma-separated)',
  313. 'default' => '',
  314. ),
  315. 'again' => array(
  316. 'short' => 'a',
  317. 'help' => 'Again (with half) afterwards',
  318. 'boolean' => true
  319. ),
  320. )
  321. );
  322. return parent::getOptionParser()
  323. ->description("Correct indentation of files")
  324. ->addSubcommand('folder', array(
  325. 'help' => 'Indent all files in a folder',
  326. 'parser' => $subcommandParser
  327. ));
  328. }
  329. }