init 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. #!/usr/bin/env php
  2. <?php
  3. /**
  4. * Yii Application Initialization Tool
  5. *
  6. * In order to run in non-interactive mode:
  7. *
  8. * init --env=Development --overwrite=All
  9. *
  10. * @author Alexander Makarov <sam@rmcreative.ru>
  11. *
  12. * @link http://www.yiiframework.com/
  13. * @copyright Copyright (c) 2008 Yii Software LLC
  14. * @license http://www.yiiframework.com/license/
  15. */
  16. if (!extension_loaded('openssl')) {
  17. die('The OpenSSL PHP extension is required by Yii2.');
  18. }
  19. $params = getParams();
  20. $root = str_replace('\\', '/', __DIR__);
  21. $envs = require "$root/environments/index.php";
  22. $envNames = array_keys($envs);
  23. echo "Yii Application Initialization Tool v1.0\n\n";
  24. $envName = null;
  25. if (empty($params['env']) || $params['env'] === '1') {
  26. echo "Which environment do you want the application to be initialized in?\n\n";
  27. foreach ($envNames as $i => $name) {
  28. echo " [$i] $name\n";
  29. }
  30. echo "\n Your choice [0-" . (count($envs) - 1) . ', or "q" to quit] ';
  31. $answer = trim(fgets(STDIN));
  32. if (!ctype_digit($answer) || !in_array($answer, range(0, count($envs) - 1))) {
  33. echo "\n Quit initialization.\n";
  34. exit(0);
  35. }
  36. if (isset($envNames[$answer])) {
  37. $envName = $envNames[$answer];
  38. }
  39. } else {
  40. $envName = $params['env'];
  41. }
  42. if (!in_array($envName, $envNames)) {
  43. $envsList = implode(', ', $envNames);
  44. echo "\n $envName is not a valid environment. Try one of the following: $envsList. \n";
  45. exit(2);
  46. }
  47. $env = $envs[$envName];
  48. if (empty($params['env'])) {
  49. echo "\n Initialize the application under '{$envNames[$answer]}' environment? [yes|no] ";
  50. $answer = trim(fgets(STDIN));
  51. if (strncasecmp($answer, 'y', 1)) {
  52. echo "\n Quit initialization.\n";
  53. exit(0);
  54. }
  55. }
  56. echo "\n Start initialization ...\n\n";
  57. $files = getFileList("$root/environments/{$env['path']}");
  58. if (isset($env['skipFiles'])) {
  59. $skipFiles = $env['skipFiles'];
  60. array_walk($skipFiles, function(&$value) use($env, $root) { $value = "$root/$value"; });
  61. $files = array_diff($files, array_intersect_key($env['skipFiles'], array_filter($skipFiles, 'file_exists')));
  62. }
  63. $all = false;
  64. if( isset($params['overwrite']) && strtolower($params['overwrite'])==="all" ){
  65. $all = true;
  66. }
  67. foreach ($files as $file) {
  68. if (!copyFile($root, "environments/{$env['path']}/$file", $file, $all, $params)) {
  69. break;
  70. }
  71. }
  72. $callbacks = ['setCookieValidationKey', 'setWritable', 'setExecutable', 'createSymlink'];
  73. foreach ($callbacks as $callback) {
  74. if (!empty($env[$callback])) {
  75. $callback($root, $env[$callback]);
  76. }
  77. }
  78. $installLockFile = $root . DIRECTORY_SEPARATOR . 'install' . DIRECTORY_SEPARATOR . 'install.lock';
  79. if( !file_exists($installLockFile) ) {
  80. if( !touch($installLockFile) ){
  81. printError("create install lock file " . $installLockFile . " failed, please handled create it");
  82. }
  83. }
  84. echo "\n ... initialization completed.\n\n";
  85. function getFileList($root, $basePath = '')
  86. {
  87. $files = [];
  88. $handle = opendir($root);
  89. while (($path = readdir($handle)) !== false) {
  90. if ($path === '.git' || $path === '.svn' || $path === '.' || $path === '..') {
  91. continue;
  92. }
  93. $fullPath = "$root/$path";
  94. $relativePath = $basePath === '' ? $path : "$basePath/$path";
  95. if (is_dir($fullPath)) {
  96. $files = array_merge($files, getFileList($fullPath, $relativePath));
  97. } else {
  98. $files[] = $relativePath;
  99. }
  100. }
  101. closedir($handle);
  102. return $files;
  103. }
  104. function copyFile($root, $source, $target, &$all, $params)
  105. {
  106. if (!is_file($root . '/' . $source)) {
  107. echo " skip $target ($source not exist)\n";
  108. return true;
  109. }
  110. if (is_file($root . '/' . $target)) {
  111. if (file_get_contents($root . '/' . $source) === file_get_contents($root . '/' . $target)) {
  112. echo " unchanged $target\n";
  113. return true;
  114. }
  115. if ($all) {
  116. echo " overwrite $target\n";
  117. } else {
  118. echo " exist $target\n";
  119. echo " ...overwrite? [Yes|No|All|Quit] ";
  120. $answer = !empty($params['overwrite']) ? $params['overwrite'] : trim(fgets(STDIN));
  121. if (!strncasecmp($answer, 'q', 1)) {
  122. return false;
  123. } else {
  124. if (!strncasecmp($answer, 'y', 1)) {
  125. echo " overwrite $target\n";
  126. } else {
  127. if (!strncasecmp($answer, 'a', 1)) {
  128. echo " overwrite $target\n";
  129. $all = true;
  130. } else {
  131. echo " skip $target\n";
  132. return true;
  133. }
  134. }
  135. }
  136. }
  137. file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source));
  138. return true;
  139. }
  140. echo " generate $target\n";
  141. @mkdir(dirname($root . '/' . $target), 0777, true);
  142. file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source));
  143. return true;
  144. }
  145. function getParams()
  146. {
  147. $rawParams = [];
  148. if (isset($_SERVER['argv'])) {
  149. $rawParams = $_SERVER['argv'];
  150. array_shift($rawParams);
  151. }
  152. $params = [];
  153. foreach ($rawParams as $param) {
  154. if (preg_match('/^--(\w+)(=(.*))?$/', $param, $matches)) {
  155. $name = $matches[1];
  156. $params[$name] = isset($matches[3]) ? $matches[3] : true;
  157. } else {
  158. $params[] = $param;
  159. }
  160. }
  161. return $params;
  162. }
  163. function setWritable($root, $paths)
  164. {
  165. foreach ($paths as $writable) {
  166. if (is_dir("$root/$writable")) {
  167. if (@chmod("$root/$writable", 0777)) {
  168. echo " chmod 0777 $writable\n";
  169. } else {
  170. printError("Operation chmod not permitted for directory $writable.");
  171. }
  172. } else {
  173. printError("Directory $writable does not exist.");
  174. }
  175. }
  176. }
  177. function setExecutable($root, $paths)
  178. {
  179. foreach ($paths as $executable) {
  180. if (file_exists("$root/$executable")) {
  181. if (@chmod("$root/$executable", 0755)) {
  182. echo " chmod 0755 $executable\n";
  183. } else {
  184. printError("Operation chmod not permitted for $executable.");
  185. }
  186. } else {
  187. printError("$executable does not exist.");
  188. }
  189. }
  190. }
  191. function setCookieValidationKey($root, $paths)
  192. {
  193. foreach ($paths as $file) {
  194. echo " generate cookie validation key in $file\n";
  195. $file = $root . '/' . $file;
  196. $length = 32;
  197. $bytes = openssl_random_pseudo_bytes($length);
  198. $key = strtr(substr(base64_encode($bytes), 0, $length), '+/=', '_-.');
  199. $content = preg_replace('/(("|\')cookieValidationKey("|\')\s*=>\s*)(""|\'\')/', "\\1'$key'", file_get_contents($file));
  200. file_put_contents($file, $content);
  201. }
  202. }
  203. function createSymlink($root, $links)
  204. {
  205. foreach ($links as $link => $target) {
  206. //first removing folders to avoid errors if the folder already exists
  207. @rmdir($root . "/" . $link);
  208. //next removing existing symlink in order to update the target
  209. if (is_link($root . "/" . $link)) {
  210. @unlink($root . "/" . $link);
  211. }
  212. if (@symlink($root . "/" . $target, $root . "/" . $link)) {
  213. echo " symlink $root/$target $root/$link\n";
  214. } else {
  215. printError("Cannot create symlink $root/$target $root/$link.");
  216. }
  217. }
  218. }
  219. /**
  220. * Prints error message.
  221. * @param string $message message
  222. */
  223. function printError($message)
  224. {
  225. echo "\n " . formatMessage("Error. $message", ['fg-red']) . " \n";
  226. }
  227. /**
  228. * Returns true if the stream supports colorization. ANSI colors are disabled if not supported by the stream.
  229. *
  230. * - windows without ansicon
  231. * - not tty consoles
  232. *
  233. * @return boolean true if the stream supports ANSI colors, otherwise false.
  234. */
  235. function ansiColorsSupported()
  236. {
  237. return DIRECTORY_SEPARATOR === '\\'
  238. ? getenv('ANSICON') !== false || getenv('ConEmuANSI') === 'ON'
  239. : function_exists('posix_isatty') && @posix_isatty(STDOUT);
  240. }
  241. /**
  242. * Get ANSI code of style.
  243. * @param string $name style name
  244. * @return integer ANSI code of style.
  245. */
  246. function getStyleCode($name)
  247. {
  248. $styles = [
  249. 'bold' => 1,
  250. 'fg-black' => 30,
  251. 'fg-red' => 31,
  252. 'fg-green' => 32,
  253. 'fg-yellow' => 33,
  254. 'fg-blue' => 34,
  255. 'fg-magenta' => 35,
  256. 'fg-cyan' => 36,
  257. 'fg-white' => 37,
  258. 'bg-black' => 40,
  259. 'bg-red' => 41,
  260. 'bg-green' => 42,
  261. 'bg-yellow' => 43,
  262. 'bg-blue' => 44,
  263. 'bg-magenta' => 45,
  264. 'bg-cyan' => 46,
  265. 'bg-white' => 47,
  266. ];
  267. return $styles[$name];
  268. }
  269. /**
  270. * Formats message using styles if STDOUT supports it.
  271. * @param string $message message
  272. * @param string[] $styles styles
  273. * @return string formatted message.
  274. */
  275. function formatMessage($message, $styles)
  276. {
  277. if (empty($styles) || !ansiColorsSupported()) {
  278. return $message;
  279. }
  280. return sprintf("\x1b[%sm", implode(';', array_map('getStyleCode', $styles))) . $message . "\x1b[0m";
  281. }