Burgomaster.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. <?php
  2. /**
  3. * Packages the zip and phar file using a staging directory.
  4. *
  5. * @license MIT, Michael Dowling https://github.com/mtdowling
  6. * @license https://github.com/mtdowling/Burgomaster/LICENSE
  7. */
  8. class Burgomaster
  9. {
  10. /** @var string Base staging directory of the project */
  11. public $stageDir;
  12. /** @var string Root directory of the project */
  13. public $projectRoot;
  14. /** @var array stack of sections */
  15. private $sections = array();
  16. /**
  17. * @param string $stageDir Staging base directory where your packaging
  18. * takes place. This folder will be created for
  19. * you if it does not exist. If it exists, it
  20. * will be deleted and recreated to start fresh.
  21. * @param string $projectRoot Root directory of the project.
  22. *
  23. * @throws \InvalidArgumentException
  24. * @throws \RuntimeException
  25. */
  26. public function __construct($stageDir, $projectRoot = null)
  27. {
  28. $this->startSection('setting_up');
  29. $this->stageDir = $stageDir;
  30. $this->projectRoot = $projectRoot;
  31. if (!$this->stageDir || $this->stageDir == '/') {
  32. throw new \InvalidArgumentException('Invalid base directory');
  33. }
  34. if (is_dir($this->stageDir)) {
  35. $this->debug("Removing existing directory: $this->stageDir");
  36. echo $this->exec("rm -rf $this->stageDir");
  37. }
  38. $this->debug("Creating staging directory: $this->stageDir");
  39. if (!mkdir($this->stageDir, 0777, true)) {
  40. throw new \RuntimeException("Could not create {$this->stageDir}");
  41. }
  42. $this->stageDir = realpath($this->stageDir);
  43. $this->debug("Creating staging directory at: {$this->stageDir}");
  44. if (!is_dir($this->projectRoot)) {
  45. throw new \InvalidArgumentException(
  46. "Project root not found: $this->projectRoot"
  47. );
  48. }
  49. $this->endSection();
  50. $this->startSection('staging');
  51. chdir($this->projectRoot);
  52. }
  53. /**
  54. * Cleanup if the last section was not already closed.
  55. */
  56. public function __destruct()
  57. {
  58. if ($this->sections) {
  59. $this->endSection();
  60. }
  61. }
  62. /**
  63. * Call this method when starting a specific section of the packager.
  64. *
  65. * This makes the debug messages used in your script more meaningful and
  66. * adds context when things go wrong. Be sure to call endSection() when
  67. * you have finished a section of your packaging script.
  68. *
  69. * @param string $section Part of the packager that is running
  70. */
  71. public function startSection($section)
  72. {
  73. $this->sections[] = $section;
  74. $this->debug('Starting');
  75. }
  76. /**
  77. * Call this method when leaving the last pushed section of the packager.
  78. */
  79. public function endSection()
  80. {
  81. if ($this->sections) {
  82. $this->debug('Completed');
  83. array_pop($this->sections);
  84. }
  85. }
  86. /**
  87. * Prints a debug message to STDERR bound to the current section.
  88. *
  89. * @param string $message Message to echo to STDERR
  90. */
  91. public function debug($message)
  92. {
  93. $prefix = date('c') . ': ';
  94. if ($this->sections) {
  95. $prefix .= '[' . end($this->sections) . '] ';
  96. }
  97. fwrite(STDERR, $prefix . $message . "\n");
  98. }
  99. /**
  100. * Copies a file and creates the destination directory if needed.
  101. *
  102. * @param string $from File to copy
  103. * @param string $to Destination to copy the file to, relative to the
  104. * base staging directory.
  105. * @throws \InvalidArgumentException if the file cannot be found
  106. * @throws \RuntimeException if the directory cannot be created.
  107. * @throws \RuntimeException if the file cannot be copied.
  108. */
  109. public function deepCopy($from, $to)
  110. {
  111. if (!is_file($from)) {
  112. throw new \InvalidArgumentException("File not found: {$from}");
  113. }
  114. $to = str_replace('//', '/', $this->stageDir . '/' . $to);
  115. $dir = dirname($to);
  116. if (!is_dir($dir)) {
  117. if (!mkdir($dir, 0777, true)) {
  118. throw new \RuntimeException("Unable to create directory: $dir");
  119. }
  120. }
  121. if (!copy($from, $to)) {
  122. throw new \RuntimeException("Unable to copy $from to $to");
  123. }
  124. }
  125. /**
  126. * Recursively copy one folder to another.
  127. *
  128. * Any LICENSE file is automatically copied.
  129. *
  130. * @param string $sourceDir Source directory to copy from
  131. * @param string $destDir Directory to copy the files to that is relative
  132. * to the the stage base directory.
  133. * @param array $extensions File extensions to copy from the $sourceDir.
  134. * Defaults to "php" files only (e.g., ['php']).
  135. * @throws \InvalidArgumentException if the source directory is invalid.
  136. */
  137. public function recursiveCopy(
  138. $sourceDir,
  139. $destDir,
  140. $extensions = array('php')
  141. ) {
  142. if (!realpath($sourceDir)) {
  143. throw new \InvalidArgumentException("$sourceDir not found");
  144. }
  145. if (!$extensions) {
  146. throw new \InvalidArgumentException('$extensions is empty!');
  147. }
  148. $sourceDir = realpath($sourceDir);
  149. $exts = array_fill_keys($extensions, true);
  150. $iter = new \RecursiveDirectoryIterator($sourceDir);
  151. $iter = new \RecursiveIteratorIterator($iter);
  152. $total = 0;
  153. $this->startSection('copy');
  154. $this->debug("Starting to copy files from $sourceDir");
  155. foreach ($iter as $file) {
  156. if (isset($exts[$file->getExtension()])
  157. || $file->getBaseName() == 'LICENSE'
  158. ) {
  159. // Remove the source directory from the destination path
  160. $toPath = str_replace($sourceDir, '', (string) $file);
  161. $toPath = $destDir . '/' . $toPath;
  162. $toPath = str_replace('//', '/', $toPath);
  163. $this->deepCopy((string) $file, $toPath);
  164. $total++;
  165. }
  166. }
  167. $this->debug("Copied $total files from $sourceDir");
  168. $this->endSection();
  169. }
  170. /**
  171. * Execute a command and throw an exception if the return code is not 0.
  172. *
  173. * @param string $command Command to execute
  174. *
  175. * @return string Returns the output of the command as a string
  176. * @throws \RuntimeException on error.
  177. */
  178. public function exec($command)
  179. {
  180. $this->debug("Executing: $command");
  181. $output = $returnValue = null;
  182. exec($command, $output, $returnValue);
  183. if ($returnValue != 0) {
  184. throw new \RuntimeException('Error executing command: '
  185. . $command . ' : ' . implode("\n", $output));
  186. }
  187. return implode("\n", $output);
  188. }
  189. /**
  190. * Creates a class-map autoloader to the staging directory in a file
  191. * named autoloader.php
  192. *
  193. * @param array $files Files to explicitly require in the autoloader. This
  194. * is similar to Composer's "files" "autoload" section.
  195. * @param string $filename Name of the autoloader file.
  196. * @throws \RuntimeException if the file cannot be written
  197. */
  198. public function createAutoloader($files = array(), $filename = 'autoloader.php')
  199. {
  200. $sourceDir = realpath($this->stageDir);
  201. $iter = new \RecursiveDirectoryIterator($sourceDir);
  202. $iter = new \RecursiveIteratorIterator($iter);
  203. $this->startSection('autoloader');
  204. $this->debug('Creating classmap autoloader');
  205. $this->debug("Collecting valid PHP files from {$this->stageDir}");
  206. $classMap = array();
  207. foreach ($iter as $file) {
  208. if ($file->getExtension() == 'php') {
  209. $location = str_replace($this->stageDir . '/', '', (string) $file);
  210. $className = str_replace('/', '\\', $location);
  211. $className = substr($className, 0, -4);
  212. // Remove "src\" or "lib\"
  213. if (strpos($className, 'src\\') === 0
  214. || strpos($className, 'lib\\') === 0
  215. ) {
  216. $className = substr($className, 4);
  217. }
  218. $classMap[$className] = "__DIR__ . '/$location'";
  219. $this->debug("Found $className");
  220. }
  221. }
  222. $destFile = $this->stageDir . '/' . $filename;
  223. $this->debug("Writing autoloader to {$destFile}");
  224. if (!($h = fopen($destFile, 'w'))) {
  225. throw new \RuntimeException('Unable to open file for writing');
  226. }
  227. $this->debug('Writing classmap files');
  228. fwrite($h, "<?php\n\n");
  229. fwrite($h, "\$mapping = array(\n");
  230. foreach ($classMap as $c => $f) {
  231. fwrite($h, " '$c' => $f,\n");
  232. }
  233. fwrite($h, ");\n\n");
  234. fwrite($h, <<<EOT
  235. spl_autoload_register(function (\$class) use (\$mapping) {
  236. if (isset(\$mapping[\$class])) {
  237. require \$mapping[\$class];
  238. }
  239. }, true);
  240. EOT
  241. );
  242. fwrite($h, "\n");
  243. $this->debug('Writing automatically included files');
  244. foreach ($files as $file) {
  245. fwrite($h, "require __DIR__ . '/$file';\n");
  246. }
  247. fclose($h);
  248. $this->endSection();
  249. }
  250. /**
  251. * Creates a default stub for the phar that includeds the generated
  252. * autoloader.
  253. *
  254. * This phar also registers a constant that can be used to check if you
  255. * are running the phar. The constant is the basename of the $dest variable
  256. * without the extension, with "_PHAR" appended, then converted to all
  257. * caps (e.g., "/foo/guzzle.phar" gets a contant defined as GUZZLE_PHAR.
  258. *
  259. * @param $dest
  260. * @param string $autoloaderFilename Name of the autoloader file.
  261. *
  262. * @return string
  263. */
  264. private function createStub($dest, $autoloaderFilename = 'autoloader.php')
  265. {
  266. $this->startSection('stub');
  267. $this->debug("Creating phar stub at $dest");
  268. $alias = basename($dest);
  269. $constName = str_replace('.phar', '', strtoupper($alias)) . '_PHAR';
  270. $stub = "<?php\n";
  271. $stub .= "define('$constName', true);\n";
  272. $stub .= "require 'phar://$alias/{$autoloaderFilename}';\n";
  273. $stub .= "__HALT_COMPILER();\n";
  274. $this->endSection();
  275. return $stub;
  276. }
  277. /**
  278. * Creates a phar that automatically registers an autoloader.
  279. *
  280. * Call this only after your staging directory is built.
  281. *
  282. * @param string $dest Where to save the file. The basename of the file
  283. * is also used as the alias name in the phar
  284. * (e.g., /path/to/guzzle.phar => guzzle.phar).
  285. * @param string|bool|null $stub The path to the phar stub file. Pass or
  286. * leave null to automatically have one created for you. Pass false
  287. * to no use a stub in the generated phar.
  288. * @param string $autoloaderFilename Name of the autolaoder filename.
  289. */
  290. public function createPhar(
  291. $dest,
  292. $stub = null,
  293. $autoloaderFilename = 'autoloader.php'
  294. ) {
  295. $this->startSection('phar');
  296. $this->debug("Creating phar file at $dest");
  297. $this->createDirIfNeeded(dirname($dest));
  298. $phar = new \Phar($dest, 0, basename($dest));
  299. $phar->buildFromDirectory($this->stageDir);
  300. if ($stub !== false) {
  301. if (!$stub) {
  302. $stub = $this->createStub($dest, $autoloaderFilename);
  303. }
  304. $phar->setStub($stub);
  305. }
  306. $this->debug("Created phar at $dest");
  307. $this->endSection();
  308. }
  309. /**
  310. * Creates a zip file containing the staged files of your project.
  311. *
  312. * Call this only after your staging directory is built.
  313. *
  314. * @param string $dest Where to save the zip file
  315. */
  316. public function createZip($dest)
  317. {
  318. $this->startSection('zip');
  319. $this->debug("Creating a zip file at $dest");
  320. $this->createDirIfNeeded(dirname($dest));
  321. chdir($this->stageDir);
  322. $this->exec("zip -r $dest ./");
  323. $this->debug(" > Created at $dest");
  324. chdir(__DIR__);
  325. $this->endSection();
  326. }
  327. private function createDirIfNeeded($dir)
  328. {
  329. if (!is_dir($dir) && !mkdir($dir, 0755, true)) {
  330. throw new \RuntimeException("Could not create dir: $dir");
  331. }
  332. }
  333. }