/** * {@inheritdoc} */ public function run() { if (is_null($this->dst) || "" === $this->dst) { return Result::error($this, 'You must specify a destination file with to() method.'); } if (!$this->checkResources($this->files, 'file')) { return Result::error($this, 'Source files are missing!'); } if (file_exists($this->dst) && !is_writable($this->dst)) { return Result::error($this, 'Destination already exists and cannot be overwritten.'); } $dump = ''; foreach ($this->files as $path) { foreach (glob($path) as $file) { $dump .= file_get_contents($file) . "\n"; } } $this->printTaskInfo('Writing {destination}', ['destination' => $this->dst]); $dst = $this->dst . '.part'; $write_result = file_put_contents($dst, $dump); if (false === $write_result) { @unlink($dst); return Result::error($this, 'File write failed.'); } // Cannot be cross-volume; should always succeed. @rename($dst, $this->dst); return Result::success($this); }
public function testStopOnFail() { $exceptionClass = false; $task = new ResultDummyTask(); Result::$stopOnFail = true; $result = Result::success($task, "Something that worked"); try { $result = Result::error($task, "Something that did not work"); // stopOnFail will cause Result::error() to throw an exception, // so we will never get here. If we did, the assert below would fail. $this->assertTrue($result->wasSuccessful()); $this->assertTrue(false); } catch (\Exception $e) { $exceptionClass = get_class($e); } $this->assertEquals(TaskExitException::class, $exceptionClass); $this->assertTrue($result->wasSuccessful()); /* // This gives an error: // Exception of class Robo\Exception\TaskExitException expected to // be thrown, but PHPUnit_Framework_Exception caught // This happens whether or not the expected exception is thrown $this->guy->expectException(TaskExitException::class, function() { // $result = Result::error($task, "Something that did not work"); $result = Result::success($task, "Something that worked"); }); */ Result::$stopOnFail = false; }
public function run() { $this->printTaskInfo("Writing {$this->filename}"); $res = file_put_contents($this->filename, $this->body); if ($res === false) { return Result::error($this, "File {$this->filename} couldnt be created"); } return Result::success($this); }
/** * Check for availablilty of PHP extensions. */ protected function checkExtension($service, $extensionList) { foreach ((array) $extensionList as $ext) { if (!extension_loaded($ext)) { return Result::error($this, "You must use PHP with the {$ext} extension enabled to use {$service}"); } } return Result::success($this); }
/** * Execute one task method */ protected function callTaskMethod($command, $action) { try { $function_result = call_user_func_array($command, $action); return $this->processResult($function_result); } catch (IOExceptionInterface $e) { $this->printTaskInfo("<error>" . $e->getMessage() . "</error>"); return Result::error($this, $e->getMessage(), $e->getPath()); } }
public function run() { if (!$this->checkResources($this->dirs, 'dir')) { return Result::error($this, 'Source directories are missing!'); } foreach ($this->dirs as $src => $dst) { $this->copyDir($src, $dst); $this->printTaskInfo("Copied from <info>{$src}</info> to <info>{$dst}</info>"); } return Result::success($this); }
/** * {@inheritdoc} */ public function run() { if (!$this->checkResources($this->dirs, 'dir')) { return Result::error($this, 'Source directories are missing!'); } foreach ($this->dirs as $dir) { $this->fs->remove($dir); $this->printTaskInfo("Deleted {dir}...", ['dir' => $dir]); } return Result::success($this); }
public function run() { if (!$this->checkResources($this->dirs, 'dir')) { return Result::error($this, 'Source directories are missing!'); } foreach ($this->dirs as $dir) { $this->emptyDir($dir); $this->printTaskInfo("Cleaned <info>{$dir}</info>"); } return Result::success($this); }
/** * {@inheritdoc} */ public function run() { if (!$this->checkResources($this->dirs, 'dir')) { return Result::error($this, 'Source directories are missing!'); } foreach ($this->dirs as $src => $dst) { $this->copyDir($src, $dst); $this->printTaskInfo('Copied from {source} to {destination}', ['source' => $src, 'destination' => $dst]); } return Result::success($this); }
public function run() { $openCommand = $this->getOpenCommand(); if (empty($openCommand)) { return Result::error($this, 'no suitable browser opening command found'); } foreach ($this->urls as $url) { passthru(sprintf($openCommand, ProcessUtils::escapeArgument($url))); $this->printTaskInfo("Opened <info>{$url}</info>"); } return Result::success($this); }
public function run() { if ($this->check()) { return Result::success($this); } $message = 'One or more requirements failed'; if ($this->stopOnFail) { $requirements = array_keys($this->results); $message = array_pop($requirements); } return Result::error($this, $message); }
/** * Create our working directory. * * @return \Robo\Result */ public function run() { // Destination cannot be empty if (empty($this->finalDestination)) { return Result::error($this, "Destination directory not specified."); } // Before we do anything else, ensure that any directory in the // final destination is writable, so that we can at a minimum // move it out of the way before placing our results there. if (is_dir($this->finalDestination)) { if (!is_writable($this->finalDestination)) { return Result::error($this, "Destination directory {dir} exists and cannot be overwritten.", ['dir' => $this->finalDestination]); } } return parent::run(); }
function run() { if (!file_exists($this->filename)) { $this->printTaskError("File {$this->filename} does not exist"); return false; } $text = file_get_contents($this->filename); if ($this->regex) { $text = preg_replace($this->regex, $this->to, $text, -1, $count); } else { $text = str_replace($this->from, $this->to, $text, $count); } $res = file_put_contents($this->filename, $text); if ($res === false) { return Result::error($this, "Error writing to file {$this->filename}."); } $this->printTaskSuccess("<info>{$this->filename}</info> updated. {$count} items replaced"); return Result::success($this, '', ['replaced' => $count]); }
/** * {@inheritdoc} */ public function run() { if (is_null($this->dst) || "" === $this->dst) { return Result::error($this, 'You must specify a destination file with to() method.'); } if (!$this->checkResources($this->files, 'file')) { return Result::error($this, 'Source files are missing!'); } $dump = ''; foreach ($this->files as $path) { foreach (glob($path) as $file) { $dump .= file_get_contents($file) . "\n"; } } $this->printTaskInfo(sprintf('Writing <info>%s</info>', $this->dst)); $dst = $this->dst . '.part'; file_put_contents($dst, $dump); rename($dst, $this->dst); return Result::success($this); }
/** * {@inheritdoc} */ public function run() { if (is_null($this->dst) || "" === $this->dst) { return Result::error($this, 'You must specify a destination file with to() method.'); } $dump = ''; foreach ($this->files as $path) { foreach (glob($path) as $file) { if (!file_exists($file)) { return Result::error($this, sprintf('File %s not found', $file)); } $dump .= file_get_contents($file); } } $this->printTaskInfo(sprintf('Writing <info>%s</info>', $this->dst)); $dst = $this->dst . '.part'; file_put_contents($dst, $dump); rename($dst, $this->dst); return Result::success($this); }
/** * Run task */ function run() { if (!file_exists($this->filename)) { return Result::error($this, "File {$this->filename} does not exist"); } $text = file_get_contents($this->filename); $info = json_decode($text); if (!isset($info->version)) { return Result::error($this, "{$this->filename} does not contain a version property"); } if ($this->to) { if (!preg_match('/^v?(\\d+\\.\\d+\\.\\d+(?:-.+)?)$/', $this->to, $matches)) { return Result::error($this, "Invalid version {$version}"); } $version = $matches[1]; } elseif ($this->useGit) { $version = $info->version; while ($this->versionExists($version)) { $version = $this->bumpSemVer($version); if ($this->inc && $this->inc !== 'patch' && $this->versionExists($version)) { return Result::error($this, "Version {$version} already exists as Git tag"); } } } else { $version = $this->bumpSemVer($info->version); } $pattern = '/"version"\\s*:\\s*"' . preg_quote($info->version, '/') . '"/'; $replacement = '"version": "' . $version . '"'; $newText = preg_replace($pattern, $replacement, $text, 1, $count); if (!$count) { return Result::error($this, "Failed to update version in {$this->filename}."); } $res = file_put_contents($this->filename, $newText); if ($res === false) { return Result::error($this, "Error writing to file {$this->filename}."); } $this->printTaskSuccess("<info>{$this->filename}</info> updated. Bumped to {$version}"); return Result::success($this, '', ['version' => $version]); }
public function run() { if (!file_exists($this->filename)) { $this->printTaskError('File {filename} does not exist', ['filename' => $this->filename]); return false; } $text = file_get_contents($this->filename); if ($this->regex) { $text = preg_replace($this->regex, $this->to, $text, -1, $count); } else { $text = str_replace($this->from, $this->to, $text, $count); } if ($count > 0) { $res = file_put_contents($this->filename, $text); if ($res === false) { return Result::error($this, "Error writing to file {filename}.", ['filename' => $this->filename]); } $this->printTaskSuccess("{filename} updated. {count} items replaced", ['filename' => $this->filename, 'count' => $count]); } else { $this->printTaskInfo("{filename} unchanged. {count} items replaced", ['filename' => $this->filename, 'count' => $count]); } return Result::success($this, '', ['replaced' => $count]); }
protected function extractTar($extractLocation) { $tar_object = new \Archive_Tar($this->filename); if (!$tar_object->extract($extractLocation)) { return Result::error($this, "Could not extract tar archive {$this->filename}"); } return Result::success($this); }
protected function extractTar($extractLocation) { if (!class_exists('Archive_Tar')) { return Result::errorMissingPackage($this, 'Archive_Tar', 'pear/archive_tar'); } $tar_object = new \Archive_Tar($this->filename); if (!$tar_object->extract($extractLocation)) { return Result::error($this, "Could not extract tar archive {$this->filename}"); } return Result::success($this); }
/** * Writes the result to destination. * * @return Result */ public function run() { foreach ($this->files as $in => $out) { $css = $this->compile($in); if (false === $css) { return \Result::error($this, 'Less compilation failed for %s.', $in); } $dst = $out . '.part'; $write_result = file_put_contents($dst, $css); rename($dst, $out); if (false === $write_result) { return Result::error($this, 'File write failed: %s', $out); } $this->printTaskSuccess(sprintf('Wrote CSS to <info>%s</info>', $out)); } return Result::success($this, 'All less files compiled.'); }
/** * Executes the ImportSqlDump Task. * * @return Robo\Result */ public function run() { // Lets make sure we have a database if (!$this->taskCreateDb()->host($this->host)->user($this->user)->pass($this->pass)->name($this->name)->dropTables(true)->run()->wasSuccessful()) { throw new RuntimeException('We failed to create the db.'); } // Do we need to uncompress it first? if (strpos($this->dump, '.gz') !== false) { // Create a temp dump file $temp_dump = tempnam(sys_get_temp_dir(), 'dump'); // Decompress the dump file if ($fp_out = fopen($temp_dump, 'wb')) { if ($fp_in = gzopen($this->dump, 'rb')) { while (!gzeof($fp_in)) { fwrite($fp_out, gzread($fp_in, 1024 * 512)); } fclose($fp_in); } else { throw new RuntimeException('Failed to open source dump file for reading.'); } gzclose($fp_out); } else { throw new RuntimeException('Failed to open temp dump file for writing.'); } // Set the dump the deflated version $this->dump = $temp_dump; // Delete the temp later $delete_me = $this->dump; } // Construct the command to import the dump $cmd = 'mysql -h' . $this->host . ' -u' . $this->user; if (!empty($this->pass)) { $cmd .= ' -p' . $this->pass; } $cmd .= ' ' . $this->name . ' < ' . $this->dump; // Run the command if (!$this->taskExec($cmd)->run()->wasSuccessful()) { throw new RuntimeException('We failed to import your dump. ' . 'HINT: Is the `mysql` binary in your "PATH"?'); } // Delete the deflated temp dump file if (isset($delete_me)) { $this->printTaskInfo('Deleting temp dump file.'); if (!unlink($delete_me)) { return Result::error($this, 'Couldn`t delete temp file.'); } } // If we get to here assume everything worked return Result::success($this); }
/** * Executes the SearchReplaceDb Task. * * @return Robo\Result */ public function run() { // Build the command to run $cmd = 'php ./vendor/interconnectit/search-replace-db/srdb.cli.php '; // Add the the db details $cmd .= '--host "' . $this->dbHost . '" '; $cmd .= '--user "' . $this->dbUser . '" '; $cmd .= '--pass "' . $this->dbPass . '" '; $cmd .= '--name "' . $this->dbName . '" '; // Add the search term and replacement $cmd .= '--search "' . $this->searchFor . '" '; $cmd .= '--replace "' . $this->replaceWith . '" '; // Provide a custom set of tables to search and replace if (!empty($this->tables)) { if (is_array($this->tables)) { $this->tables = implode(',', $this->tables); } $cmd .= '--tables "' . $this->tables . '" '; } // Provide a custom set of columns to search and replace if (!empty($this->columns)) { if (is_array($this->columns)) { $this->columns = implode(',', $this->columns); } $cmd .= '--include-cols "' . $this->columns . '" '; } // Are we using regular expressions if ($this->useRegx) { $cmd .= '--regex '; } // Is it a dry run or not if ($this->dryRun) { $cmd .= '--dry-run '; } // Tell the world whats happening $this->printTaskInfo('running <info>' . $cmd . '</info>'); // Run the cmd $descriptorspec = [1 => ["pipe", "w"], 2 => ["pipe", "w"]]; $process = proc_open($cmd, $descriptorspec, $pipes); if (is_resource($process)) { $output = []; $output['stdout'] = stream_get_contents($pipes[1]); fclose($pipes[1]); $output['stderr'] = stream_get_contents($pipes[2]); fclose($pipes[2]); proc_close($process); } else { return Result::error($this, 'Failed to run the command!'); } // Remove the strict standard error $regx = '/(PHP\\s)?Strict Standards:\\s+Declaration of icit_srdb_cli::log.*?\\d+/'; $output['stdout'] = trim(s::create($output['stdout'])->regexReplace($regx, '')); $output['stderr'] = trim(s::create($output['stderr'])->regexReplace($regx, '')); // Check for errors if (!empty($output['stderr'])) { return Result::error($this, $output['stderr']); } // Split stdout to an array of lines $output = explode("\n", $output['stdout']); // Remove the last 2 lines from the output // While the search and replace might be done, other tasks may not be. // Thus we might give the wrong impression of being complete. $status = array_pop($output); array_pop($output); // Do we want to output all the results if ($this->verbose) { foreach ($output as $line) { $this->printTaskInfo($line); } } else { // We only need to output the last 4 lines foreach (array_slice($output, -4) as $line) { $this->printTaskInfo($line); } } // Return success of failure if ($status == 'And we\'re done!') { return Result::success($this); } else { return Result::error($this, $status); } }
protected function addItemsToZip($zip, $items) { foreach ($items as $placementLocation => $filesystemLocation) { if (is_dir($filesystemLocation)) { $finder = new Finder(); $finder->files()->in($filesystemLocation)->ignoreDotFiles(false); foreach ($finder as $file) { // Replace Windows slashes or resulting zip will have issues on *nixes. $relativePathname = str_replace('\\', '/', $file->getRelativePathname()); if (!$zip->addFile($file->getRealpath(), "{$placementLocation}/{$relativePathname}")) { return Result::error($this, "Could not add directory {$filesystemLocation} to the archive; error adding {$file->getRealpath()}."); } } } elseif (is_file($filesystemLocation)) { if (!$zip->addFile($filesystemLocation, $placementLocation)) { return Result::error($this, "Could not add file {$filesystemLocation} to the archive."); } } else { return Result::error($this, "Could not find {$filesystemLocation} for the archive."); } } return Result::success($this); }
/** * Writes minified result to destination. * * @return Result */ public function run() { if (empty($this->type)) { return Result::error($this, 'Unknown asset type.'); } if (empty($this->dst)) { return Result::error($this, 'Unknown file destination.'); } $size_before = strlen($this->text); $minified = $this->getMinifiedText(); if ($minified instanceof Result) { return $minified; } elseif (false === $minified) { return Result::error($this, 'Minification failed.'); } $size_after = strlen($minified); $dst = $this->dst . '.part'; $write_result = file_put_contents($dst, $minified); rename($dst, $this->dst); if (false === $write_result) { return Result::error($this, 'File write failed.'); } if ($size_before === 0) { $minified_percent = 0; } else { $minified_percent = number_format(100 - $size_after / $size_before * 100, 1); } $this->printTaskSuccess(sprintf('Wrote <info>%s</info>', $this->dst)); $this->printTaskSuccess(sprintf('Wrote <info>%s</info> (reduced by <info>%s</info> / <info>%s%%</info>)', $this->formatBytes($size_after), $this->formatBytes($size_before - $size_after), $minified_percent)); return Result::success($this, 'Asset minified.'); }
/** * Writes the result to destination. * * @return Result */ public function run() { if (!in_array($this->compiler, $this->compilers, true) && !is_callable($this->compiler)) { $message = sprintf('Invalid ' . static::FORMAT_NAME . ' compiler %s!', $this->compiler); return Result::error($this, $message); } foreach ($this->files as $in => $out) { if (!file_exists($in)) { $message = sprintf('File %s not found.', $in); return Result::error($this, $message); } $css = $this->compile($in); if ($css instanceof Result) { return $css; } elseif (false === $css) { $message = sprintf(ucfirst(static::FORMAT_NAME) . ' compilation failed for %s.', $in); return Result::error($this, $message); } $dst = $out . '.part'; $write_result = file_put_contents($dst, $css); rename($dst, $out); if (false === $write_result) { $message = sprintf('File write failed: %s', $out); return Result::error($this, $message); } $this->printTaskSuccess(sprintf('Wrote CSS to <info>%s</info>', $out)); } return Result::success($this, 'All ' . static::FORMAT_NAME . ' files compiled.'); }
/** * @param string $executable * * @return \Robo\Result */ protected function installFromImagemin($executable) { // check if there is an url defined for the executable if (!array_key_exists($executable, $this->imageminRepos)) { $message = sprintf('The executable %s cannot be found in the defined imagemin repositories', $executable); return Result::error($this, $message); } $this->printTaskInfo('Downloading the {executable} executable from the imagemin repository', ['executable' => $executable]); $os = $this->getOS(); $url = $this->imageminRepos[$executable] . '/blob/master/vendor/' . $os . '/' . $executable . '?raw=true'; if (substr($os, 0, 3) == 'win') { // if it is win, add a .exe extension $url = $this->imageminRepos[$executable] . '/blob/master/vendor/' . $os . '/' . $executable . '.exe?raw=true'; } $data = @file_get_contents($url, false, null); if ($data === false) { // there is something wrong with the url, try it without the version info $url = preg_replace('/x[68][64]\\//', '', $url); $data = @file_get_contents($url, false, null); if ($data === false) { // there is still something wrong with the url if it is win, try with win32 if (substr($os, 0, 3) == 'win') { $url = preg_replace('win/', 'win32/', $url); $data = @file_get_contents($url, false, null); if ($data === false) { // there is nothing more we can do $message = sprintf('Could not download the executable <info>%s</info>', $executable); return Result::error($this, $message); } } // if it is not windows there is nothing we can do $message = sprintf('Could not download the executable <info>%s</info>', $executable); return Result::error($this, $message); } } // check if target directory exists if (!is_dir($this->executableTargetDir)) { mkdir($this->executableTargetDir); } // save the executable into the target dir $path = $this->executableTargetDir . '/' . $executable; if (substr($os, 0, 3) == 'win') { // if it is win, add a .exe extension $path = $this->executableTargetDir . '/' . $executable . '.exe'; } $result = file_put_contents($path, $data); if ($result === false) { $message = sprintf('Could not copy the executable <info>%s</info> to %s', $executable, $target_dir); return Result::error($this, $message); } // set the binary to executable chmod($path, 0755); // if everything successful, store the executable path $this->executablePaths[$executable] = $this->executableTargetDir . '/' . $executable; // if it is win, add a .exe extension if (substr($os, 0, 3) == 'win') { $this->executablePaths[$executable] .= '.exe'; } $message = sprintf('Executable <info>%s</info> successfully downloaded', $executable); return Result::success($this, $message); }
/** * {@inheritdoc} */ public function run() { if (empty($this->type)) { return Result::error($this, 'Unknown asset type.'); } if (empty($this->dst)) { return Result::error($this, 'Unknown file destination.'); } if (file_exists($this->dst) && !is_writable($this->dst)) { return Result::error($this, 'Destination already exists and cannot be overwritten.'); } $size_before = strlen($this->text); $minified = $this->getMinifiedText(); if ($minified instanceof Result) { return $minified; } elseif (false === $minified) { return Result::error($this, 'Minification failed.'); } $size_after = strlen($minified); // Minification did not reduce file size, so use original file. if ($size_after > $size_before) { $minified = $this->text; $size_after = $size_before; } $dst = $this->dst . '.part'; $write_result = file_put_contents($dst, $minified); if (false === $write_result) { @unlink($dst); return Result::error($this, 'File write failed.'); } // Cannot be cross-volume; should always succeed. @rename($dst, $this->dst); if ($size_before === 0) { $minified_percent = 0; } else { $minified_percent = number_format(100 - $size_after / $size_before * 100, 1); } $this->printTaskSuccess('Wrote {filepath}', ['filepath' => $this->dst]); $context = ['bytes' => $this->formatBytes($size_after), 'reduction' => $this->formatBytes($size_before - $size_after), 'percentage' => $minified_percent]; $this->printTaskSuccess('Wrote {bytes} (reduced by {reduction} / {percentage})', $context); return Result::success($this, 'Asset minified.'); }
public function run() { $command = $this->getCommand(); $dir = $this->workingDirectory ? " in " . $this->workingDirectory : ""; $this->printTaskInfo("running <info>{$command}</info>{$dir}"); $this->process = new Process($command); $this->process->setTimeout($this->timeout); $this->process->setIdleTimeout($this->idleTimeout); $this->process->setWorkingDirectory($this->workingDirectory); if (!$this->background and !$this->isPrinted) { $this->process->run(); return new Result($this, $this->process->getExitCode(), $this->process->getOutput()); } if (!$this->background and $this->isPrinted) { $this->process->run(function ($type, $buffer) { Process::ERR === $type ? print 'ER» ' . $buffer : (print '» ' . $buffer); }); return new Result($this, $this->process->getExitCode(), $this->process->getOutput()); } try { $this->process->start(); } catch (\Exception $e) { return Result::error($this, $e->getMessage()); } return Result::success($this); }
/** * {@inheritdoc} */ public function run() { if (!in_array($this->compiler, $this->compilers, true) && !is_callable($this->compiler)) { $message = sprintf('Invalid ' . static::FORMAT_NAME . ' compiler %s!', $this->compiler); return Result::error($this, $message); } foreach ($this->files as $in => $out) { if (!file_exists($in)) { $message = sprintf('File %s not found.', $in); return Result::error($this, $message); } if (file_exists($out) && !is_writable($out)) { return Result::error($this, 'Destination already exists and cannot be overwritten.'); } } foreach ($this->files as $in => $out) { $css = $this->compile($in); if ($css instanceof Result) { return $css; } elseif (false === $css) { $message = sprintf(ucfirst(static::FORMAT_NAME) . ' compilation failed for %s.', $in); return Result::error($this, $message); } $dst = $out . '.part'; $write_result = file_put_contents($dst, $css); if (false === $write_result) { $message = sprintf('File write failed: %s', $out); @unlink($dst); return Result::error($this, $message); } // Cannot be cross-volume: should always succeed @rename($dst, $out); $this->printTaskSuccess('Wrote CSS to {filename}', ['filename' => $out]); } return Result::success($this, 'All ' . static::FORMAT_NAME . ' files compiled.'); }
/** * {@inheritdoc} */ public function run() { if (empty($this->log)) { return Result::error($this, "Changelog is empty"); } $text = implode("\n", array_map(function ($i) { return "* {$i} *" . date('Y-m-d') . "*"; }, $this->log)) . "\n"; $ver = "#### {$this->version}\n\n"; $text = $ver . $text; if (!file_exists($this->filename)) { $this->printTaskInfo('Creating {filename}', ['filename' => $this->filename]); $res = file_put_contents($this->filename, $this->anchor); if ($res === false) { return Result::error($this, "File {filename} cant be created", ['filename' => $this->filename]); } } /** @var \Robo\Result $result */ // trying to append to changelog for today $result = $this->collectionBuilder()->taskReplace($this->filename)->from($ver)->to($text)->run(); if (!isset($result['replaced']) || !$result['replaced']) { $result = $this->collectionBuilder()->taskReplace($this->filename)->from($this->anchor)->to($this->anchor . "\n\n" . $text)->run(); } return new Result($this, $result->getExitCode(), $result->getMessage(), $this->log); }