IndentShell.php 9.0 KB

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