IndentShell.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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 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: hardcore replaceing
  187. *
  188. * @deprecated
  189. */
  190. protected function _processSpaceErrors($piece) {
  191. $space = 1;
  192. $newPiece = $piece;
  193. if (mb_substr($piece, 0, $space) === ' ' && mb_substr($piece, $space, 1) === TB) {
  194. $newPiece = mb_substr($piece, $space);
  195. }
  196. if ($newPiece != $piece || strlen($newPiece) !== strlen($piece)) {
  197. $this->_changes = true;
  198. }
  199. return $newPiece;
  200. }
  201. /**
  202. * Old try - sometimes TABS at the beginning are not recogized...
  203. * idea: strip tabs and spaces, remember their amount and add tabs again!
  204. *
  205. * @deprecated
  206. */
  207. protected function _correctFilesTry() {
  208. foreach ($this->_files as $file) {
  209. $changes = false;
  210. $textCorrect = array();
  211. $pieces = $this->_read($file);
  212. foreach ($pieces as $piece) {
  213. $pos = -1;
  214. $spaces = $mod = $tabs = 0;
  215. $debug = '';
  216. $newPiece = trim($piece, CR);
  217. $newPiece = trim($newPiece, NL);
  218. //$debug .= ''.stripos($newPiece, TB);
  219. // detect tabs and whitespaces at the beginning
  220. //while (($pieceOfString = mb_substr($newPiece, 0, 1)) === ' ' || ($pieceOfString = mb_substr($newPiece, 0, 1)) == TB) {
  221. while ((stripos($newPiece, ' ')) === 0 || (stripos($newPiece, TB)) === 0) {
  222. $pieceOfString = mb_substr($newPiece, 0, 1);
  223. if ($pieceOfString === ' ') {
  224. $pos++;
  225. $spaces++;
  226. } elseif ($pieceOfString === TB) {
  227. $pos++;
  228. $spaces += $this->settings['spacesPerTab'];
  229. } else {
  230. return $this->error('???');
  231. }
  232. $newPiece = mb_substr($newPiece, 1);
  233. }
  234. if ($pos >= 1) {
  235. $changes = true;
  236. // if only spaces and tabs, we might as well trim the line
  237. //should be done
  238. // now correct
  239. //$newPiece = mb_substr($piece, $pos + 1);
  240. // clear single spaces
  241. /*
  242. if (mb_substr($newPiece, 0, 1) === ' ' && mb_substr($newPiece, 1, 1) !== '*') {
  243. $newPiece = mb_substr($newPiece, 1);
  244. }
  245. */
  246. $mod = $spaces % $this->settings['spacesPerTab'];
  247. $tabs = ($spaces - $mod) / $this->settings['spacesPerTab'];
  248. //$beginning = str_replace(' ', TB, $piece);
  249. $beginning = str_repeat(TB, $tabs);
  250. $beginning .= str_repeat(' ', $mod);
  251. $newPiece = $beginning . trim($newPiece);
  252. } else {
  253. $newPiece = rtrim($newPiece);
  254. }
  255. if ($this->settings['debug']) {
  256. $debug .= ' ' . ($changes ? '[MOD]' : '[]') . ' (SPACES ' . $tabs . ', POS ' . $pos . ', TABS ' . $tabs . ', MOD ' . $mod . ')';
  257. }
  258. $textCorrect[] = $newPiece . $debug;
  259. }
  260. if ($changes) {
  261. $this->_write($file, $textCorrect);
  262. }
  263. //die();
  264. }
  265. }
  266. /**
  267. * Search files that may contain translateable strings
  268. *
  269. * @return void
  270. */
  271. protected function _searchFiles() {
  272. foreach ($this->_paths as $path) {
  273. $Folder = new Folder($path);
  274. $files = $Folder->findRecursive('.*\.(' . implode('|', $this->settings['files']) . ')', true);
  275. foreach ($files as $file) {
  276. if (strpos($file, DS . 'Vendor' . DS) !== false) {
  277. continue;
  278. }
  279. $this->_files[] = $file;
  280. }
  281. }
  282. }
  283. public function getOptionParser() {
  284. $subcommandParser = array(
  285. 'options' => array(
  286. 'dry-run' => array(
  287. 'short' => 'd',
  288. 'help' => 'Dry run the update, no files will actually be modified.',
  289. 'boolean' => true
  290. ),
  291. 'log' => array(
  292. 'short' => 'l',
  293. 'help' => 'Log all ouput to file log.txt in TMP dir',
  294. 'boolean' => true
  295. ),
  296. 'interactive' => array(
  297. 'short' => 'i',
  298. 'help' => 'Interactive',
  299. 'boolean' => true
  300. ),
  301. 'spaces' => array(
  302. 'short' => 's',
  303. 'help' => 'Spaces per Tab',
  304. 'default' => '4',
  305. ),
  306. 'extensions' => array(
  307. 'short' => 'e',
  308. 'help' => 'Extensions (comma-separated)',
  309. 'default' => '',
  310. ),
  311. 'again' => array(
  312. 'short' => 'a',
  313. 'help' => 'Again (with half) afterwards',
  314. 'boolean' => true
  315. ),
  316. )
  317. );
  318. return parent::getOptionParser()
  319. ->description("Correct indentation of files")
  320. ->addSubcommand('folder', array(
  321. 'help' => 'Indent all files in a folder',
  322. 'parser' => $subcommandParser
  323. ));
  324. }
  325. }