IndentShell.php 9.6 KB

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