Takes a build and puts it into the queue to be run (if using a queue)
@param Build $build
766779
public function addBuildToQueue(Build $build)
    {
        $buildId = $build->getId();

        if (empty($buildId)) {
            return;
        }

        $config = Config::getInstance();
        $settings = $config->get('phpci.worker', []);

        if (!empty($settings['host']) && !empty($settings['queue'])) {
            try {
                $jobData = array(
                    'type' => 'phpci.build',
                    'build_id' => $build->getId(),
                );

                if ($config->get('using_custom_file')) {
                    $jobData['config'] = $config->getArray();
                }

                $pheanstalk = new Pheanstalk($settings['host']);
                $pheanstalk->useTube($settings['queue']);
                $pheanstalk->put(
                    json_encode($jobData),
                    PheanstalkInterface::DEFAULT_PRIORITY,
                    PheanstalkInterface::DEFAULT_DELAY,
                    $config->get('phpci.worker.job_timeout', 600)
                );
            } catch (\Exception $ex) {
                $this->queueError = true;
            }
        }
    }
1055201
public function addBuilds(BuildIterator $builds)
    {
        foreach ($builds as $build) {
            $this->builds->add($build);
        }
    }
496368
public function main() {
    $this->validate();

    // Remove existing destination first.
    if ($this->dest->exists()) {
      $this->log("Replacing existing resource '" . $this->dest->getPath() . "'");

      if ($this->dest->delete(TRUE) === FALSE) {
        throw new BuildException("Failed to delete existing destination '$this->dest'");
      }
    }

    // Link or copy the source artifact.
    $this->dest->getParentFile()->mkdirs();
    if ($this->mode == 'copy') {
      $this->log(sprintf("Copying '%s' to '%s'", $this->source->getPath(), $this->dest->getPath()));
      $this->source->copyTo($this->dest);
    }
    else {
      $this->log(sprintf("Linking '%s' to '%s'", $this->source->getPath(), $this->dest->getPath()));
      FileSystem::getFileSystem()->symlink($this->source->getPath(), $this->dest->getPath());
    }
  }
933425
public function main()
    {
        $exc = null;

        if (empty($this->tryContainer)) {
            throw new BuildException('A nested <try> element is required');
        }

        try {
            $this->tryContainer->perform();
        } catch (BuildException $e) {
            if (!empty($this->propertyName)) {
                $this->project->setProperty($this->propertyName, $e->getMessage());
            }

            if (!empty($this->referenceName)) {
                $this->project->addReference($this->referenceName, $e);
            }

            if (!empty($this->catchContainer)) {
                $this->catchContainer->perform();
            } else {
                $exc = $e;
            }
        }

        if (!empty($this->finallyContainer)) {
            $this->finallyContainer->perform();
        }

        if (!empty($exc)) {
            throw $exc;
        }
    }
222123
public function build()
    {
        $this->clean();
        $this->prepare();
        $this->runCs();
        $this->runCpd();
        $this->runMd();
        $this->runTests();
    }
645278
public function queuePush(Job $job)
    {
        if ($this->isSingle()) {
            $queue_config = $this->getQueueConfig();
            if (isset($queue_config['driver'])) {
                /** @var BaseQueue $driver */
                $driver = $queue_config['driver'];
                $driver::component()->push($job);
            }
        }
    }
640142
public function main()
    {
        if (null === $this->getRepository()) {
            throw new BuildException('"repository" is required parameter');
        }

        $client = $this->getGitClient(false, $this->getRepository());
        $command = $client->getCommand('tag');
        $command
            ->setOption('a', $this->isAnnotate())
            ->setOption('s', $this->isSign())
            ->setOption('f', $this->isReplace())
            ->setOption('d', $this->isDelete())
            ->setOption('v', $this->isVerify())
            ->setOption('l', $this->isList());

        if (null !== $this->getKeySign()) {
            $command->setOption('u', $this->getKeySign());
        }

        if (null !== $this->getMessage()) {
            $command->setOption('m', $this->getMessage());
        }

        if (null !== $this->getFile()) {
            $command->setOption('F', $this->getFile());
        }

        // Use 'name' arg, if relevant
        if (null != $this->getName() && false == $this->isList()) {
            $command->addArgument($this->getName());
        }

        if (null !== $this->getKeySign() || $this->isAnnotate() || $this->isSign()) {
            // Require a tag message or file
            if (null === $this->getMessage() && null === $this->getFile()) {
                throw new BuildException('"message" or "file" required to make a tag');
            }
        }

        // Use 'commit' or 'object' args, if relevant
        if (null !== $this->getCommit()) {
            $command->addArgument($this->getCommit());
        } else {
            if (null !== $this->getObject()) {
                $command->addArgument($this->getObject());
            }
        }

        // Customize list (-l) options
        if ($this->isList()) {
            if (null !== $this->getContains()) {
                $command->setOption('contains', $this->getContains());
            }
            if (null !== $this->getPattern()) {
                $command->addArgument($this->getPattern());
            }
            if (null != $this->getNum()) {
                $command->setOption('n', $this->getNum());
            }
        }

        $this->log('git-tag command: ' . $command->createCommandString(), Project::MSG_INFO);

        try {
            $output = $command->execute();
        } catch (Exception $e) {
            $this->log($e->getMessage(), Project::MSG_ERR);
            throw new BuildException('Task execution failed. ' . $e->getMessage());
        }

        if (null !== $this->outputProperty) {
            $this->project->setProperty($this->outputProperty, $output);
        }

        $this->log(
            sprintf('git-tag: tags for "%s" repository', $this->getRepository()),
            Project::MSG_INFO
        );
        $this->log('git-tag output: ' . trim($output), Project::MSG_INFO);
    }
275364
public function main()
    {
        if (null === $this->getRepository()) {
            throw new BuildException('"repository" is required parameter');
        }
        $remotes = trim($this->getRemote());
        if (null === $remotes || '' === $remotes) {
            throw new BuildException('"remote" is required parameter');
        }

        $client = $this->getGitClient(false, $this->getRepository());
        $command = $client->getCommand('merge');
        $command
            ->setOption('commit', $this->isCommit())
            ->setOption('q', $this->isQuiet());

        if ($this->getMessage()) {
            $command->setOption('message', $this->getMessage());
        }

        if (!$this->isCommit()) {
            $command->setOption('no-commit', $this->isNoCommit());
        }

        if ($this->isFastForwardCommit()) {
            $command->setOption('no-ff', true);
        }

        $strategy = $this->getStrategy();
        if ($strategy) {
            // check if strategy is valid
            if (false === in_array($strategy, $this->validStrategies)) {
                throw new BuildException(
                    "Could not find merge strategy '" . $strategy . "'\n" .
                    "Available strategies are: " . implode(', ', $this->validStrategies)
                );
            }
            $command->setOption('strategy', $strategy);
            if ($this->getStrategyOption()) {
                $command->setOption(
                    'strategy-option',
                    $this->getStrategyOption()
                );
            }
        }

        $remotes = explode(' ', $this->getRemote());
        foreach ($remotes as $remote) {
            $command->addArgument($remote);
        }

        $this->log('git-merge command: ' . $command->createCommandString(), Project::MSG_INFO);

        try {
            $output = $command->execute();
        } catch (Exception $e) {
            throw new BuildException('Task execution failed.', $e);
        }

        $this->log(
            sprintf('git-merge: replaying "%s" commits', $this->getRemote()),
            Project::MSG_INFO
        );
        $this->log('git-merge output: ' . trim($output), Project::MSG_INFO);
    }
642154
protected function _buildTarget(AssetTarget $build)
    {
        $writer = $this->factory->writer();
        $compiler = $this->factory->compiler();

        $name = $writer->buildFileName($build);
        if ($writer->isFresh($build) && empty($this->params['force'])) {
            $this->out('<info>Skip building</info> ' . $name . ' existing file is still fresh.');

            return;
        }

        $writer->invalidate($build);
        $name = $writer->buildFileName($build);
        try {
            $this->out('<success>Saving file</success> for ' . $name);
            $contents = $compiler->generate($build);
            $writer->write($build, $contents);
        } catch (Exception $e) {
            $this->err('Error: ' . $e->getMessage());
        }
    }
913107
function() {
    if (!builds.length) { return; } // this shouldn't happen

    var build = builds.shift();
    var buildCallback = function(stats) {
      cb(build.buildName, stats);
      if (builds.length) {
        runNextBuild();
      }
    };
    console.log(colors.cyan('[Starting build]'), build.buildName);
    executeBuild(build, buildCallback);
  }
282749
public function build()
    {
        $this->debug->groupCollapsed(__METHOD__);
        $this->debug->groupUncollapse();
        $str = '';
        $cfg = $this->form->cfg;
        $status = $this->form->status;
        // $printOpts   = $cfg['output'];
        // $this->debug->log('cfg', $cfg);
        $this->debug->log('status', $status);
        $strAlerts = \is_callable($cfg['buildAlerts'])
            ? \call_user_func_array($cfg['buildAlerts'], array($this->form))
            : '';
        if ($status['error']) {
            $str = $strAlerts
                .$cfg['messages']['error'];
        } elseif ($status['completed']) {
            $str = $strAlerts
                .$cfg['messages']['completed'];
        } elseif ($cfg['buildOutput']) {
            // $this->debug->warn('have buildOutput');
            $this->outputSetup();
            if (\is_callable($cfg['buildOutput'])) {
                $str = \call_user_func_array($cfg['buildOutput'], array($this->form));
            }
            if (empty($str)) {
                $this->debug->info('buildOutput callback didn\'t generate anything');
                $str = $this->buildOutput($this->form);
            }
            $str = $strAlerts
                .$this->buildHiddenFields()
                .$str;
            $str = $this->form->eventManager->publish(
                'form.buildOutput',
                $this->form,
                array('output'=>$str)
            )->getValue('output');
            if ($cfg['output']['formWrap']) {
                $attribs = $cfg['attribs'];
                if (empty($attribs['action'])) {
                    $attribs['action'] = Html::getSelfUrl();
                }
                if ($status['multipart']) {
                    $attribs['enctype'] = 'multipart/form-data';
                }
                if (\strtolower($attribs['method']) == 'get') {
                    $urlParts = \parse_url(\html_entity_decode($attribs['action']));
                    $attribs['action'] = $urlParts['path'];
                }
                #$this->debug->log('form attribs', $attribs);
                $str = '<form'.Html::buildAttribString($attribs).'>'."\n"
                    .$str
                    .'</form>'."\n";
            }
            if ($cfg['output']['filepathScript'] && \file_exists($cfg['output']['filepathScript'])) {
                $str .= '<script type="text/javascript">'
                    .\file_get_contents($cfg['output']['filepathScript'])
                    .'</script>';
            }
            if ($cfg['output']['reqDepJs']) {
                $outputScript = new OutputScript($this->form);
                $str .= $outputScript->build()."\n";
            }
        }
        $this->debug->groupEnd();
        return $str;
    }
952209
public function main()
    {
        if (empty($this->lockFile)) {
            throw new \BuildException('Lockfile needs to be set!');
        }

        if (!file_exists($this->lockFile) || !is_readable($this->lockFile)) {
            throw new \BuildException('Given Lockfile does not exist or is not readable!');
        }

        $checker = $this->getSecurityChecker();
        try {
            if (!empty($this->timeout)) {
                $checker->getCrawler()->setTimeout($this->timeout);
            }
            if (!empty($this->endPoint)) {
                $checker->getCrawler()->setEndPoint($this->endPoint);
            }

            $vulnerabilities = $checker->check($this->lockFile, 'json');
            if ($vulnerabilities->count() === 0) {
                $this->log('No vulnerabilities found!');
                return;
            }

            if ($vulnerabilities->getFormat() !== 'json') {
                throw new \BuildException('Was expecting JSON response, but got "' . $vulnerabilities->getFormat().'"');
            }

            $dependencies = json_decode($vulnerabilities->__toString(), true);
            if (!is_array($dependencies)) {
                throw new \BuildException('The web service response could not be parsed!');
            }

            foreach ($dependencies as $dependency => $issues) {
                $dependencyFullName = $dependency . ' (' . $issues['version'] . ')';
                $this->log($dependencyFullName);
                $this->log(str_repeat('-', strlen($dependencyFullName)));

                foreach ($issues['advisories'] as $issue => $details) {
                    $title = ' * ' . $details['title'];
                    if ($details['cve']) {
                        $title .= ' (CVE: ' . $details['cve'] . ')';
                    }
                    $this->log($title);

                    if ('' !== $details['link']) {
                        $this->log('   ' . $details['link']);
                    }

                    $this->log('');
                }
            }
        } catch (\Exception $e) {
            throw new \BuildException($e);
        }

        throw new \BuildException('Vulnerabilities found!');
    }
961588
public function build()
    {
        if ($this->cacheProvider->fetch($this->getCacheKey())) {
            return;
        }

        $this->doBuild();
        $this->cacheProvider->save($this->getCacheKey(), true);
    }
877941
public function getNextBuild()
    {
        //if (count($this->_queue)<1) {
        //    $this->getNextBuildTime();
        //}
        usort($this->queue, array($this, 'sortQueue'));
        if (isset($this->queue[0])) {
            if ($this->queue[0]->getNextBuildTime() <= time()) {
                $build = array_shift($this->queue);
                $build->dequeue();

                return $build;
            }
        }

        return;
    }
611556
private void addNewBuilds(List<BambooJob> enabledJobs,
                              Map<BambooJob, Set<Build>> buildsByJob) {
        long start = System.currentTimeMillis();
        int count = 0;

        for (BambooJob job : enabledJobs) {
            if (job.isPushed()) {
                LOG.info("Job Pushed already: " + job.getJobName());
                continue;
            }
            // process new builds in the order of their build numbers - this has implication to handling of commits in BuildEventListener
            ArrayList<Build> builds = Lists.newArrayList(nullSafe(buildsByJob.get(job)));
            builds.sort((Build b1, Build b2) -> Integer.valueOf(b1.getNumber()) - Integer.valueOf(b2.getNumber()));
            for (Build buildSummary : builds) {
                if (isNewBuild(job, buildSummary)) {
                    Build build = bambooClient.getBuildDetails(buildSummary
                            .getBuildUrl(), job.getInstanceUrl());
                    if (build != null) {
                        build.setCollectorItemId(job.getId());
                        buildRepository.save(build);
                        count++;
                    }
                }
            }
        }
        log("New builds", start, count);
    }
718927
private function runAsParent(Job $job): void
    {
        $status = sprintf('Forked %s for ID: %s', $this->child, $job->getId());
        $this->updateProcLine($status);

        $this->log->debug(
            $status,
            [
                'type' => 'fork',
                'worker' => $this->worker_name,
                'job_id' => $job->getId(),
            ]
        );

        pcntl_wait($wait_status);
        $exit_status = pcntl_wexitstatus($wait_status);

        if ($exit_status !== 0) {
            $this->job_manager->failJob(
                $job,
                new DirtyExitException(
                    sprintf('Job Exited with exit code %d', $exit_status)
                )
            );
        }
    }
520120
private function buildPluginFactory(Build $build)
    {
        $pluginFactory = new PluginFactory();

        $self = $this;
        $pluginFactory->registerResource(
            function () use ($self) {
                return $self;
            },
            null,
            'PHPCI\Builder'
        );

        $pluginFactory->registerResource(
            function () use ($build) {
                return $build;
            },
            null,
            'PHPCI\Model\Build'
        );

        $logger = $this->logger;
        $pluginFactory->registerResource(
            function () use ($logger) {
                return $logger;
            },
            null,
            'Psr\Log\LoggerInterface'
        );

        $pluginFactory->registerResource(
            function () use ($self) {
                $factory = new MailerFactory($self->getSystemConfig('phpci'));
                return $factory->getSwiftMailerFromConfig();
            },
            null,
            'Swift_Mailer'
        );

        return $pluginFactory;
    }