IndentShell.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. */
  38. class IndentShell extends AppShell {
  39. public $settings = array(
  40. 'files' => array('php', 'ctp', 'inc', 'tpl'),
  41. 'againWithHalf' => false, # if 4, go again with 2 afterwards
  42. 'outputToTmp' => false, # write to filename_.ext
  43. 'debug' => false # add debug info after each line
  44. );
  45. protected $changes = null;
  46. protected $_paths = array();
  47. protected $_files = array();
  48. /**
  49. * Main execution function to indent a folder recursivly
  50. *
  51. * @return void
  52. */
  53. public function folder() {
  54. if (!empty($this->params['extensions'])) {
  55. $this->settings['files'] = String::tokenize($this->params['extensions']);
  56. }
  57. if (!empty($this->params['again'])) {
  58. $this->settings['againWithHalf'] = true;
  59. }
  60. if (!empty($this->args)) {
  61. if (!empty($this->args[0]) && $this->args[0] !== 'app') {
  62. $folder = $this->args[0];
  63. if ($folder === '/') {
  64. $folder = APP;
  65. }
  66. $folder = realpath($folder);
  67. if (!file_exists($folder)) {
  68. return $this->error('folder not exists: ' . $folder . '');
  69. }
  70. $this->_paths[] = $folder;
  71. } elseif ($this->args[0] === 'app') {
  72. $this->_paths[] = APP;
  73. }
  74. if (!empty($this->params['files'])) {
  75. $this->settings['files'] = explode(',', $this->params['files']);
  76. }
  77. $this->out($folder);
  78. $this->out('searching...');
  79. $this->_searchFiles();
  80. $this->out('found: ' . count($this->_files));
  81. if (!empty($this->params['dry-run'])) {
  82. $this->out('TEST DONE');
  83. } else {
  84. $continue = $this->in(__('Modifying files! Continue?'), array('y', 'n'), 'n');
  85. if (strtolower($continue) !== 'y' && strtolower($continue) !== 'yes') {
  86. return $this->error('...aborted');
  87. }
  88. $this->_correctFiles();
  89. $this->out('DONE');
  90. }
  91. } else {
  92. $this->out('Usage: cake intend folder');
  93. $this->out('"folder" is then intended recursivly');
  94. $this->out('default file types are');
  95. $this->out('['.implode(', ', $this->settings['files']).']');
  96. $this->out('');
  97. $this->out('Specify file types manually:');
  98. $this->out('-files php,js,css');
  99. }
  100. }
  101. protected function _write($file, $text) {
  102. $text = implode(PHP_EOL, $text);
  103. if ($this->settings['outputToTmp']) {
  104. $filename = extractPathInfo('file', $file);
  105. if (mb_substr($filename, -1, 1) === '_') {
  106. return;
  107. }
  108. $file = extractPathInfo('dir', $file).DS.$filename.'_.'.extractPathInfo('ext', $file);
  109. }
  110. return file_put_contents($file, $text);
  111. }
  112. protected function _read($file) {
  113. $text = file_get_contents($file);
  114. if (empty($text)) {
  115. return array();
  116. }
  117. $pieces = explode(NL, $text);
  118. return $pieces;
  119. }
  120. /**
  121. * NEW TRY!
  122. * idea: just count spaces and replace those
  123. *
  124. */
  125. protected function _correctFiles() {
  126. foreach ($this->_files as $file) {
  127. $this->changes = false;
  128. $textCorrect = array();
  129. $pieces = $this->_read($file);
  130. $spacesPerTab = $this->params['spaces'];
  131. foreach ($pieces as $piece) {
  132. $tmp = $this->_process($piece, $spacesPerTab);
  133. if ($this->settings['againWithHalf'] && $spacesPerTab % 2 === 0 && $spacesPerTab > 3) {
  134. $tmp = $this->_process($tmp, $spacesPerTab/2);
  135. }
  136. $tmp = $this->_processSpaceErrors($tmp, 1);
  137. $textCorrect[] = $tmp;
  138. }
  139. if ($this->changes) {
  140. $this->_write($file, $textCorrect);
  141. }
  142. }
  143. }
  144. /**
  145. * @return string
  146. */
  147. protected function _process($piece, $spacesPerTab) {
  148. $pos = -1;
  149. $spaces = $mod = $tabs = 0;
  150. $debug = '';
  151. $newPiece = $piece;
  152. if ($spacesPerTab) {
  153. //TODO
  154. while (mb_substr($piece, $pos+1, 1) === ' ' || mb_substr($piece, $pos + 1, 1) === TB) {
  155. $pos++;
  156. }
  157. $piece1 = mb_substr($piece, 0, $pos + 1);
  158. $piece1 = str_replace(str_repeat(' ', $spacesPerTab), TB, $piece1, $count);
  159. if ($count > 0) {
  160. $this->changes = true;
  161. }
  162. $piece2 = mb_substr($piece, $pos+1);
  163. $newPiece = $piece1 . $piece2;
  164. }
  165. $newPiece = rtrim($newPiece) . $debug;
  166. if ($newPiece != $piece || strlen($newPiece) !== strlen($piece)) {
  167. $this->changes = true;
  168. }
  169. return $newPiece;
  170. }
  171. /**
  172. * NEW TRY!
  173. * idea: hardcore replaceing
  174. *
  175. * @deprecated
  176. */
  177. protected function _processSpaceErrors($piece) {
  178. $space = 1;
  179. $newPiece = $piece;
  180. if (mb_substr($piece, 0, $space) === ' ' && mb_substr($piece, $space, 1) === TB) {
  181. $newPiece = mb_substr($piece, $space);
  182. }
  183. if ($newPiece != $piece || strlen($newPiece) !== strlen($piece)) {
  184. $this->changes = true;
  185. }
  186. return $newPiece;
  187. }
  188. /**
  189. * Old try - sometimes TABS at the beginning are not recogized...
  190. * idea: strip tabs and spaces, remember their amount and add tabs again!
  191. *
  192. * @deprecated
  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. return $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. }