IndentShell.php 9.2 KB

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