Check repository and indices existence.

@param InputInterface  $input
@param OutputInterface $output

@return array

@throws Exception
767543
protected function getRepositoryAndIndices(
        InputInterface $input,
        OutputInterface $output
    ): array {
        $appName = $input->getArgument('app-name');
        $configuration = $this->repositoryBucket->getConfiguration();

        if (!isset($configuration[$appName])) {
            throw new Exception(sprintf('App %s not found under apisearch configuration', $appName));
        }

        $appId = $configuration[$appName]['app_id'];
        self::printInfoMessage(
            $output,
            $this->getHeader(),
            "App: <strong>{$appName} / {$appId}</strong>"
        );

        if (!$input->hasOption('index-name')) {
            return [$configuration[$appName]['app_id'], []];
        }

        $indexNamesAsArray = $configuration[$appName]['indices'] ?? [];

        $indices = array_map(function (string $indexName) use ($indexNamesAsArray, $appName, $output) {
            if (!isset($indexNamesAsArray[$indexName])) {
                throw new Exception(sprintf(
                    'Index %s not found under %s repository. Indices availables: %s',
                    $indexName,
                    $appName,
                    implode(', ', array_keys($indexNamesAsArray))
                ));
            }

            $indexId = $indexNamesAsArray[$indexName];
            self::printInfoMessage(
                $output,
                $this->getHeader(),
                "Index: <strong>{$indexName} / {$indexId}</strong>"
            );

            return IndexUUID::createById($indexId);
        }, $input->getOption('index-name'));

        return [
            AppUUID::createById($appId),
            $indices,
        ];
    }
647715
protected function execute(InputInterface $input, OutputInterface $output)
  {
    $name = $input->getArgument('name');
    $class = implode('', array_map('ucfirst', explode('_', str_replace(':', '_', $name))));

    if ($this->add($name, $class)) {
      return $output->writeln('<info>Command "' . $class . '" has been successfully created.</info>');
    }

    return $output->writeln('Command "' . $class . '" already exists.');
  }
889700
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $uuids = array();

        $count = filter_var(
            $input->getOption('count'),
            FILTER_VALIDATE_INT,
            array(
                'default' => 1,
                'min_range' => 1,
            )
        );

        if (((bool) $input->getOption('guid')) == true) {
            $features = new FeatureSet(true);

            Uuid::setFactory(new UuidFactory($features));
        }

        if (((bool) $input->getOption('comb')) === true) {
            Uuid::getFactory()->setRandomGenerator(
                new CombGenerator(
                    Uuid::getFactory()->getRandomGenerator(),
                    Uuid::getFactory()->getNumberConverter()
                )
            );
        }

        for ($i = 0; $i < $count; $i++) {
            $uuids[] = $this->createUuid(
                $input->getArgument('version'),
                $input->getArgument('namespace'),
                $input->getArgument('name')
            );
        }

        foreach ($uuids as $uuid) {
            $output->writeln((string) $uuid);
        }
    }
159458
protected function execute(InputInterface $input, OutputInterface $output)
    {
        if ($input->getOption('list-info-collectors')) {
            $output->writeln('Available info collectors:', true);
            foreach ($this->systemInfoCollectorRegistry->getIdentifiers() as $identifier) {
                $output->writeln("  $identifier", true);
            }

            return;
        }

        $outputFormatter = $this->outputFormatRegistry->getItem(
            $input->getOption('format')
         );

        if ($input->getArgument('info-collectors')) {
            $identifiers = $input->getArgument('info-collectors');
        } else {
            $identifiers = $this->systemInfoCollectorRegistry->getIdentifiers();
        }

        // Collect info for the given identifiers.
        $collectedInfoArray = [];
        foreach ($identifiers as $identifier) {
            $collectedInfoArray[$identifier] = $this->systemInfoCollectorRegistry->getItem($identifier)->collect();
        }

        $output->writeln(
             $outputFormatter->format($collectedInfoArray)
         );
    }
265022
protected function execute(InputInterface $input, OutputInterface $output)
    {
        foreach ($this->familyRegistry->getFamilies() as $family) {
            $this->updateFamilyData($family, $output);
        }
    }
141558
protected function execute(InputInterface $input, OutputInterface $output): ?int
    {
        $username = $this->getUsername($input, $output);
        if ($input->getOption('if-not-exists')) {
            try {
                $user = $this->userManager->loadUserByUsername($username);
            } catch (\Exception $e) {
                $user = null;
            }
            if ($user) {
                $message = $this->translator->trans(
                    'user.already_exists',
                    [
                        '%username%' => $username,
                    ],
                    'security'
                );
                $output->writeln("<comment>{$message}</comment>");

                return 0;
            }
        }

        try {
            $user = $this->userManager->createUser($username);
        } catch (BadUsernameException $e) {
            $output->writeln("<error>{$e->getMessage()}</error>");

            return 1;
        }

        $user->setSuperAdmin($input->getOption('admin'));
        $password = $this->getPassword($input, $output);
        if ($password) {
            $this->userManager->setPlainTextPassword($user, $password);
        }
        $this->userManager->save($user);

        $message = $this->translator->trans('user.created_success', ['%username%' => $username], 'security');
        $output->writeln("<info>{$message}</info>");

        return 0;
    }
347975
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->setInputAndOutput($input, $output);

        return $this->doExecute();
    }
834911
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('Checking DB connection');
        $loopCount = 0;
        $connection = $this->manager->getConnection();

        $isConnected = false;
        while (!$isConnected) {
            try {
                $connection->connect();

                if (!$connection->isConnected()) {
                    throw new \Exception('Could not connect');
                }

                $isConnected = true;
            } catch (\Exception $e) {
                $output->writeln('DB is not yet connected, sleep 1 second.');
                sleep(1);
            } finally {
                $loopCount++;
            }

            if ($loopCount > 100) {
                throw new ConnectionTimeoutException('DB connection failed.');
            }
        }

        $output->writeln('DB connected.');
    }
1177449
protected function execute(InputInterface $input, OutputInterface $output)
  {
    $this->_input = $input;
    $this->_output = $output;

    $params = array_values($input->getArguments());
    //Strip off the command name
    array_shift($params);

    //Call the execute command with $input and $output as the first args
    if(method_exists($this, 'executeCommand'))
    {
      array_unshift($params, $input, $output);
      return $this->executeCommand(...$params);
    }

    //Call the process method, without $input and $output
    if(method_exists($this, 'process'))
    {
      return $this->process(...$params);
    }

    throw new \RuntimeException(
      "Your command must contain one of the following methods:\n" .
      "process()\n" .
      'executeCommand(InputInterface $input, OutputInterface $output)' . "\n",
      500
    );
  }
591850
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $directory = (string) $input->getArgument('directory');

        if ($directory !== WORKING_DIRECTORY) {
            try {
                $this->analyser->setDirectory($directory);
            } catch (\RuntimeException $e) {
                $warning = "Warning: The provided directory "
                    . "'$directory' does not exist or is not a directory.";
                $outputContent = '<error>' . $warning . '</error>';
                $output->writeln($outputContent);

                return 1;
            }
        }

        $createGitattributesFile = $input->getOption('create');
        $overwriteGitattributesFile = $input->getOption('overwrite');
        $validateArchive = $input->getOption('validate-git-archive');
        $globPattern = $input->getOption('glob-pattern');
        $globPatternFile = (string) $input->getOption('glob-pattern-file');

        $enforceStrictOrderComparison = $input->getOption('enforce-strict-order');

        if ($enforceStrictOrderComparison) {
            $this->analyser->enableStrictOrderCamparison();
        }

        $enforceExportIgnoresAlignment = $input->getOption('enforce-alignment');

        if ($enforceExportIgnoresAlignment) {
            $this->analyser->enableStrictAlignmentCamparison();
        }

        $keepLicense = (boolean) $input->getOption('keep-license');

        if ($keepLicense) {
            $this->analyser->keepLicense();
        }

        $alignExportIgnores = $input->getOption('align-export-ignores');

        if ($alignExportIgnores) {
            $this->analyser->alignExportIgnores();
        }

        if ($globPattern) {
            try {
                $this->analyser->setGlobPattern((string) $globPattern);
            } catch (InvalidGlobPattern $e) {
                $warning = "Warning: The provided glob pattern "
                    . "'$globPattern' is considered invalid.";
                $outputContent = '<error>' . $warning . '</error>';
                $output->writeln($outputContent);

                return 1;
            }
        } elseif ($this->isGlobPatternFileSetable($globPatternFile)) {
            try {
                $this->analyser->setGlobPatternFromFile($globPatternFile);
            } catch (NonExistentGlobPatternFile $e) {
                $warning = "Warning: The provided glob pattern file "
                    . "'$globPatternFile' doesn't exist.";
                $outputContent = '<error>' . $warning . '</error>';
                $output->writeln($outputContent);

                return 1;
            } catch (InvalidGlobPatternFile $e) {
                $warning = "Warning: The provided glob pattern file "
                    . "'$globPatternFile' is considered invalid.";
                $outputContent = '<error>' . $warning . '</error>';
                $output->writeln($outputContent);

                return 1;
            }
        }

        if (!$this->analyser->hasGitattributesFile()) {
            $warning = 'Warning: There is no .gitattributes file present in '
                . $this->analyser->getDirectory() . '.';
            $outputContent = '<error>' . $warning . '</error>';

            $expectedGitattributesFileContent = $this->analyser
                ->getExpectedGitattributesContent();

            if ($expectedGitattributesFileContent !== '') {
                if ($createGitattributesFile || $overwriteGitattributesFile) {
                    try {
                        $outputContent .= $this->createGitattributesFile(
                            $expectedGitattributesFileContent
                        );

                        $output->writeln($outputContent);

                        return 0;
                    } catch (GitattributesCreationFailed $e) {
                        $outputContent .= PHP_EOL . PHP_EOL . $e->getMessage();
                        $output->writeln($outputContent);
                        return 1;
                    }
                } else {
                    $outputContent .= $this->getSuggestGitattributesFileCreationOptionOutput(
                        $expectedGitattributesFileContent
                    );

                    $output->writeln($outputContent);

                    return 1;
                }
            }

            $outputContent .= PHP_EOL . PHP_EOL . '<info>Unable to resolve expected .gitattributes '
                . 'content.</info>';
            $output->writeln($outputContent);

            return 1;
        } elseif ($validateArchive) {
            try {
                if ($this->isValidArchive($keepLicense)) {
                    $info = '<info>The archive file of the current HEAD is considered lean.</info>';
                    $output->writeln($info);

                    return 0;
                }
                $foundUnexpectedArchiveArtifacts = $this->archiveValidator
                    ->getFoundUnexpectedArchiveArtifacts();

                $info = '<error>The archive file of the current HEAD is not considered lean.</error>'
                    . PHP_EOL . PHP_EOL . 'Seems like the following artifacts slipped in:<info>' . PHP_EOL
                    . implode(PHP_EOL, $foundUnexpectedArchiveArtifacts) . '</info>' . PHP_EOL;

                if (count($this->archiveValidator->getFoundUnexpectedArchiveArtifacts()) === 1) {
                    $info = '<error>The archive file of the current HEAD is not considered lean.</error>'
                        . PHP_EOL . PHP_EOL . 'Seems like the following artifact slipped in:<info>' . PHP_EOL
                        . implode(PHP_EOL, $foundUnexpectedArchiveArtifacts) . '</info>' . PHP_EOL;
                }
            } catch (NoLicenseFilePresent $e) {
                $errorMessage = 'The archive file of the current HEAD '
                    . 'is considered invalid due to a missing license file.';
                $info = '<error>' . $errorMessage . '</error>' . PHP_EOL;
                $this->archiveValidator->getArchive()->removeArchive();
            }

            $output->writeln($info);

            return 1;
        } else {
            if ($this->analyser->hasCompleteExportIgnores() === false) {
                $outputContent = '<error>The present .gitattributes file is considered invalid.</error>';

                if ($this->analyser->hasCompleteExportIgnores() === false) {
                    $expectedGitattributesFileContent = $this->analyser
                        ->getExpectedGitattributesContent();

                    if ($createGitattributesFile || $overwriteGitattributesFile) {
                        try {
                            $outputContent .= $this->overwriteGitattributesFile(
                                $expectedGitattributesFileContent
                            );

                            $output->writeln($outputContent);

                            return 0;
                        } catch (GitattributesCreationFailed $e) {
                            $outputContent .= PHP_EOL . PHP_EOL . $e->getMessage();
                            $output->writeln($outputContent);

                            return 1;
                        }
                    }

                    $outputContent .= $this->getExpectedGitattributesFileContentOutput(
                        $expectedGitattributesFileContent
                    );

                    $output->writeln($outputContent);

                    return 1;
                }
            }

            $info = '<info>The present .gitattributes file is considered valid.</info>';
            $output->writeln($info);

            if ($this->analyser->hasPrecedingSlashesInExportIgnorePattern()) {
                $warning = "Warning: At least one export-ignore pattern has a leading '/', "
                    . $warning = 'which is considered as a smell.';
                $outputContent = '<error>' . $warning . '</error>';
                $output->writeln($outputContent);
            }

            if ($this->analyser->hasTextAutoConfiguration() === false) {
                $warning = 'Warning: Missing a text auto configuration. '
                    . 'Consider adding one.';
                $outputContent = '<error>' . $warning . '</error>';
                $output->writeln($outputContent);
            }

            return 0;
        }
    }
72996
protected function runCommand(InputInterface $input, OutputInterface $output)
    {
        $repository = $this->getRepository($input, $output);
        $file = $input->getArgument('file');

        self::importFromFile(
            $file,
            $output,
            function (array $items, bool $lastIteration) use ($repository) {
                foreach ($items as $item) {
                    $repository->addItem($item);
                }

                $repository->flush(500, !$lastIteration);
            }
        );
    }
185178
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $targetArg = rtrim($input->getArgument('target'), '/');

        if (!is_dir($targetArg)) {
            throw new \InvalidArgumentException(sprintf('The target directory "%s" does not exist.', $input->getArgument('target')));
        }

        $wantedVersion = $input->getOption('zeroclipboard-version');

        try {
            $versionConstraint = Constraint::parse($wantedVersion);
        } catch (UnexpectedValueException $e) {
            $output->writeln(
                '<error>Error:</error> <info>' .
                $wantedVersion . '</info> is not a valid version constraint.'
            );
            return;
        }

        $minimalConstraint =
            new SimpleConstraint(
                new Operator('>='),
                Version::parse($this->minimalSupportedVersion)
            );

        if(!$minimalConstraint->matches($versionConstraint)) {
            $output->writeln(
                '<error>Error:</error> <info>' .
                $wantedVersion . '</info> is not supported. Minimal version is: ' .
                $this->minimalSupportedVersion
            );
            return;
        }

        $curl = new Curl();
        $curl->get(
            'https://api.github.com' .
            '/repos/zeroclipboard/zeroclipboard/tags?per_page=100'
        );

        $versionToInstall = null;
        $versionToInstallObj = new Version(1, 0, 6);

        foreach(json_decode($curl->response) as $release) {
            try {
                $tag = Version::parse($release->name);
                if ($tag->getStability()->isStable()) {
                    $constraint = new SimpleConstraint(new Operator('='), $tag);
                    if ($constraint->isSubsetOf($versionConstraint)) {
                        if ($tag->compare($versionToInstallObj) > 0) {
                            $versionToInstall = $release->name;
                            $versionToInstallObj = $tag;
                        }
                    } else {
                    }
                }
            } catch(\Exception $e) {

            }
        }

        if(!$versionToInstall) {
            $output->writeln(
                '<error>Error:</error> <info>' .
                $wantedVersion . '</info> is greator than the last release. '
            );
            return;
        }

        /** @var Filesystem $filesystem */
        $filesystem = $this->getContainer()->get('filesystem');

        // Create the bundles directory otherwise symlink will fail.
        $bundlesDir = $targetArg . '/bundles/';
        $filesystem->mkdir($bundlesDir, 0777);

        $output->writeln(
            'Installing ZeroClipboard assets.'
        );

        $targetDir  = $bundlesDir . 'zeroclipboard-assets';

        $namespaceParts = explode('\\', __NAMESPACE__);
        array_pop($namespaceParts);

        $output->writeln(
            sprintf(
                'Installing assets for <comment>%s</comment> into <comment>%s</comment>',
                implode('\\', $namespaceParts),
                $targetDir
            )
        );

        $filesystem->remove($targetDir);

        $filesystem->mkdir($targetDir, 0777);

        $filesystem->mkdir($targetDir . '/tmp');

        $zip = file_get_contents(
            'https://github.com/zeroclipboard/zeroclipboard/archive/' . $versionToInstall . '.zip'
        );

        file_put_contents($targetDir . '/tmp/zeroclipboard.zip', $zip);

        $zip = new \ZipArchive;

        if ($zip->open($targetDir . '/tmp/zeroclipboard.zip') === TRUE) {
            $zip->extractTo($targetDir . '/tmp');
            $zip->close();

            if(file_exists($targetDir . '/tmp/zeroclipboard-' . $versionToInstall . '/dist')) {
                $filesystem->mirror(
                    $targetDir . '/tmp/zeroclipboard-' . $versionToInstall . '/dist',
                    $targetDir
                );
            } else {
                $versionToInstall = $versionToInstallObj->getMajor() .'.' .
                    $versionToInstallObj->getMinor() .'.' .
                    $versionToInstallObj->getRevision();
                if(file_exists($targetDir . '/tmp/zeroclipboard-' . $versionToInstall . '/dist')) {
                    $filesystem->mirror(
                        $targetDir . '/tmp/zeroclipboard-' . $versionToInstall . '/dist',
                        $targetDir
                    );
                } else {
                    foreach( array(
                                 'ZeroClipboard.js',
                                 'ZeroClipboard.min.js',
                                 'ZeroClipboard.min.map',
                                 'ZeroClipboard.Core.js',
                                 'ZeroClipboard.Core.min.js',
                                 'ZeroClipboard.Core.min.map',
                                 'ZeroClipboard.swf',
                             ) as $file) {
                        if(
                        file_exists(
                            $targetDir .
                            '/tmp/zeroclipboard-' .
                            $versionToInstall .
                            '/' . $file)) {
                            $filesystem->copy(
                                $targetDir . '/tmp/zeroclipboard-' . $versionToInstall . '/' . $file,
                                $targetDir . '/' . $file
                            );
                        }
                    }
                }
            }
            $filesystem->remove($targetDir . '/tmp');
        } else {
            throw new FileException('File Error');
        }
    }
867054
protected function execute( InputInterface $input, OutputInterface $output ) {
		Log::instance()->setOutput( $output );

		$repository = RepositoryManager::instance()->setup( $input->getOption( 'repository' ) );

		if ( ! $repository ) {
			Log::instance()->write( 'Could not setup repository.', 0, 'error' );
			return 1;
		}

		$instances = $repository->getDB()->search( $input->getArgument( 'search_text' ) );

		if ( ! $instances ) {
			Log::instance()->write( 'An error occured while searching.', 0, 'success' );
		}

		if ( empty( $instances ) ) {
			Log::instance()->write( 'No snapshots found.', 0, 'warning' );
			return;
		}

		$table = new Table( $output );
		$table->setHeaders( [ 'ID', 'Project', 'Description', 'Author', 'Size', 'Multisite', 'Created' ] );

		$rows = [];

		foreach ( $instances as $instance ) {
			if ( empty( $instance['time'] ) ) {
				$instance['time'] = time();
			}

			$rows[ $instance['time'] ] = [
				'id'          => ( ! empty( $instance['id'] ) ) ? $instance['id'] : '',
				'project'     => ( ! empty( $instance['project'] ) ) ? $instance['project'] : '',
				'description' => ( ! empty( $instance['description'] ) ) ? $instance['description'] : '',
				'author'      => ( ! empty( $instance['author']['name'] ) ) ? $instance['author']['name'] : '',
				'size'        => ( ! empty( $instance['size'] ) ) ? Utils\format_bytes( (int) $instance['size'] ) : '',
				'multisite'   => ( ! empty( $instance['multisite'] ) ) ? 'Yes' : 'No',
				'created'     => ( ! empty( $instance['time'] ) ) ? date( 'F j, Y, g:i a', $instance['time'] ) : '',
			];
		}

		ksort( $rows );

		$table->setRows( $rows );

		$table->render();
	}
660989
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $iterationCount = (int)$input->getOption('iteration-count');

        $locationsCount = $this->repository->sudo(
            function (Repository $repository) {
                return $repository->getLocationService()->getAllLocationsCount();
            }
        );

        $helper = $this->getHelper('question');
        $question = new ConfirmationQuestion(
            sprintf(
                "<info>Found %d Locations.</info>\n%s\n<info>Do you want to proceed? [y/N] </info>",
                $locationsCount,
                self::BEFORE_RUNNING_HINTS
            ),
            false
        );
        if (!$helper->ask($input, $output, $question)) {
            return;
        }

        $output->writeln('Regenerating System URL aliases...');

        $progressBar = $this->getProgressBar($locationsCount, $output);
        $progressBar->start();

        for ($offset = 0; $offset <= $locationsCount; $offset += $iterationCount) {
            gc_disable();
            $locations = $this->repository->sudo(
                function (Repository $repository) use ($offset, $iterationCount) {
                    return $repository->getLocationService()->loadAllLocations($offset, $iterationCount);
                }
            );
            $this->processLocations($locations, $progressBar);
            gc_enable();
        }
        $progressBar->finish();
        $output->writeln('');
        $output->writeln('<info>Done.</info>');

        $output->writeln('<info>Cleaning up corrupted URL aliases...</info>');
        $corruptedAliasesCount = $this->repository->sudo(
            function (Repository $repository) {
                return $repository->getURLAliasService()->deleteCorruptedUrlAliases();
            }
        );
        $output->writeln("<info>Done. Deleted {$corruptedAliasesCount} entries.</info>");
        $output->writeln('<comment>Make sure to clear HTTP cache afterwards.</comment>');
    }
491177
protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (!Uuid::isValid($input->getArgument('uuid'))) {
            throw new Exception('Invalid UUID (' . $input->getArgument('uuid') . ')');
        }

        $uuid = Uuid::fromString($input->getArgument('uuid'));

        $table = $this->getHelperSet()->get('table');
        $table->setLayout(TableHelper::LAYOUT_BORDERLESS);

        $table->addRows(array(
            array('encode:', 'STR:', (string) $uuid),
            array('',        'INT:', (string) $uuid->getInteger()),
        ));

        if ($uuid->getVariant() != Uuid::RFC_4122) {
            $table->addRows(array(
                array('decode:', 'variant:', 'Not an RFC 4122 UUID'),
            ));

            $table->render($output);

            return;
        }

        switch ($uuid->getVersion()) {
            case 1:
                $version = '1 (time and node based)';
                break;
            case 2:
                $version = '2 (DCE security based)';
                break;
            case 3:
                $version = '3 (name based, MD5)';
                break;
            case 4:
                $version = '4 (random data based)';
                break;
            case 5:
                $version = '5 (name based, SHA-1)';
                break;
        }

        $table->addRows(array(
            array('decode:', 'variant:', 'RFC 4122'),
            array('',        'version:', $version),
        ));

        if ($uuid->getVersion() == 1) {
            $table->addRows(array(
                array('', 'content:', 'time:  ' . $uuid->getDateTime()->format('c')),
                array('', '', 'clock: ' . $uuid->getClockSequence() . ' (usually random)'),
                array('', '', 'node:  ' . substr(chunk_split($uuid->getNodeHex(), 2, ':'), 0, -1)),
            ));
        }

        if ($uuid->getVersion() == 4) {
            $table->addRows(array(
                array('', 'content:', substr(chunk_split($uuid->getHex(), 2, ':'), 0, -1)),
                array('', '', '(no semantics: random data only)'),
            ));
        }

        if ($uuid->getVersion() == 3 || $uuid->getVersion() == 5) {
            $table->addRows(array(
                array('', 'content:', substr(chunk_split($uuid->getHex(), 2, ':'), 0, -1)),
                array('', '', '(not decipherable: MD5 message digest only)'),
            ));
        }

        $table->render($output);
    }
312235
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $parser = new Parser();
        $yaml = file_get_contents(APPLICATION_PATH . 'PHPCI/config.yml');
        $this->settings = $parser->parse($yaml);

        $token = $this->settings['phpci']['github']['token'];

        if (!$token) {
            $this->logger->error(Lang::get('no_token'));
            return;
        }

        $buildStore = Factory::getStore('Build');

        $this->logger->addInfo(Lang::get('finding_projects'));
        $projectStore = Factory::getStore('Project');
        $result = $projectStore->getWhere();
        $this->logger->addInfo(Lang::get('found_n_projects', count($result['items'])));

        foreach ($result['items'] as $project) {
            $http = new HttpClient('https://api.github.com');
            $commits = $http->get('/repos/' . $project->getReference() . '/commits', array('access_token' => $token));

            $last_commit = $commits['body'][0]['sha'];
            $last_committer = $commits['body'][0]['commit']['committer']['email'];
            $message = $commits['body'][0]['commit']['message'];

            $this->logger->info(Lang::get('last_commit_is', $project->getTitle(), $last_commit));

            if ($project->getLastCommit() != $last_commit && $last_commit != "") {
                $this->logger->info(
                    Lang::get('adding_new_build')
                );

                $build = new Build();
                $build->setProjectId($project->getId());
                $build->setCommitId($last_commit);
                $build->setStatus(Build::STATUS_NEW);
                $build->setBranch($project->getBranch());
                $build->setCreated(new \DateTime());
		$build->setCommitMessage($message);
                if (!empty($last_committer)) {
                    $build->setCommitterEmail($last_committer);
                }
                $buildStore->save($build);

                $project->setLastCommit($last_commit);
                $projectStore->save($project);
            }
        }

        $this->logger->addInfo(Lang::get('finished_processing_builds'));
    }
394192
protected function execute( InputInterface $input, OutputInterface $output ) {
		Log::instance()->setOutput( $output );

		$repository = RepositoryManager::instance()->setup( $input->getOption( 'repository' ) );

		if ( ! $repository ) {
			Log::instance()->write( 'Could not setup repository.', 0, 'error' );
			return 1;
		}

		$id = $input->getArgument( 'snapshot_id' );

		$snapshot = $repository->getDB()->getSnapshot( $id );

		if ( ! $snapshot ) {
			Log::instance()->write( 'Could not get snapshot from database.', 0, 'error' );

			return 1;
		}

		$files_result = $repository->getS3()->deleteSnapshot( $id, $snapshot['project'] );

		if ( ! $files_result ) {
			Log::instance()->write( 'Could not delete snapshot.', 0, 'error' );

			return 1;
		}

		$db_result = $repository->getDB()->deleteSnapshot( $id );

		if ( ! $db_result ) {
			Log::instance()->write( 'Could not delete snapshot.', 0, 'error' );

			return 1;
		}

		Log::instance()->write( 'Snapshot deleted.', 0, 'success' );
	}