<commit_before><?php
namespace Kunstmaan\Skylab\Command;

use CL\Slack\Model\Attachment;
use CL\Slack\Model\AttachmentField;
use CL\Slack\Payload\ChatDeletePayload;
use CL\Slack\Payload\ChatPostMessagePayload;
use CL\Slack\Payload\ChatPostMessagePayloadResponse;
use CL\Slack\Transport\ApiClient;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Process;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Parser;

/**
 * ExecuteCommand
 */
class ExecuteCommand extends AbstractCommand
{

    private $ts = null;
    private $channel = null;
    /** @var ApiClient */
    private $slackApiClient = null;

    /**
     * Configures the current command.
     */
    protected function configure()
    {
        $this
            ->addDefaults()
            ->setName('execute')
            ->setDescription('Executes a Skylab YAML file')
            ->addArgument('file', InputArgument::REQUIRED, 'The full path to the YAML file')
            ->addArgument('deploy-environment', InputArgument::OPTIONAL, 'The environment to deploy to')
            ->addOption("--skip-tests", null, InputOption::VALUE_NONE, 'If set, the test steps will be skipped')
            ->addOption("--skip-deploy", null, InputOption::VALUE_NONE, 'If set, the deploy steps will be skipped')
            ->addOption("--debug-yml", null, InputOption::VALUE_NONE, 'If set, the resulting yml will be shown without executing it')
            ->setHelp(<<<EOT
The <info>execute</info> command will execute a Skylab YAML file, used for testing and deploying via Jenkins

<info>php skylab.phar execute /opt/skylab/templates/execute/deploy.yml</info>
EOT
            );
    }

    protected function runStep($step, $yaml, $deployEnv, $successStep = null)
    {
        if (isset($yaml[$step])) {
            $this->dialogProvider->logStep($step);

            foreach ($yaml[$step] as $list) {
                foreach ($list as $source) {
                    foreach ($source as $command) {
                        try {
                            $result = $this->processProvider->executeCommand($command, false, function ($type, $buffer) {
                                if (Process::ERR === $type) {
                                    $this->dialogProvider->logOutput($buffer, true);
                                } else {
                                    if ($this->output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) {
                                        $this->dialogProvider->logOutput($buffer, false);
                                    }
                                }
                            }, $yaml["env"]);
                            if ($result === false) {
                                $this->notifySlack("Error while running the " . $step . " phase, check the console log in Jenkins", $yaml["deploy_matrix"][$deployEnv]["project"], $deployEnv, getenv("slack_user"), array(), "#CC0000", true);
                                $this->dialogProvider->logError($step . " failed!", false);
                            }
                        } catch (\Exception $ex) {
                            $this->notifySlack("Error while running the " . $step . " phase with error: " . $ex->getMessage(), $yaml["deploy_matrix"][$deployEnv]["project"], $deployEnv, getenv("slack_user"), array(), "#CC0000", true);
                            $extra = array();
                            $tags = array();
                            $this->dialogProvider->logException($ex, $tags, $extra);
                        }
                    }
                }
            }
            if (!is_null($successStep)) {
                $this->runStep($successStep, $yaml, $deployEnv);
            }
        } else {
            return;
        }
    }

    protected function notifySlack($message, $project, $env, $user, $resolverArray, $color = "#FFCC00", $update = false)
    {
        if ($update) {
            $payload = new ChatDeletePayload();
            $payload->setSlackTimestamp($this->ts);
            $payload->setChannelId($this->channel);
            $response = $this->slackApiClient->send($payload);

            if ($response->isOk()) {
                if ($response instanceof ChatPostMessagePayloadResponse) {
                    /** @var ChatPostMessagePayloadResponse $response */
                    $this->ts = $response->getSlackTimestamp();
                }
            } else {
                // something went wrong, but what?
                // simple error (Slack's error message)
                echo $response->getError();
                // explained error (Slack's explanation of the error, according to the documentation)
                echo $response->getErrorExplanation();
                exit(1);
            }
        }

        $payload = new ChatPostMessagePayload();
        $payload->setChannel("#" . getenv("slack_channel"));
        $payload->setIconUrl("https://www.dropbox.com/s/ivrj3wcze7cwh54/masterjenkins.png?dl=1");
        $payload->setUsername("Master Jenkins");

        $attachment = new Attachment();
        $attachment->setColor($color);
        $attachment->setFallback("[".$project."#" . getenv("BUILD_NUMBER"). " - " . $this->getBranch() . " to ". $env . "] " . $message);
        $attachment->setText("[".$project."#" . getenv("BUILD_NUMBER"). " - " . $this->getBranch() . " to ". $env . "] " . $message . "\n<" . getenv("BUILD_URL") . "console|Jenkins Console> - <".getenv("BUILD_URL")."changes|Changes>" . (isset($resolverArray["shared_package_target"]) && file_exists($resolverArray["shared_package_target"])?" - <" . $resolverArray["shared_package_url"] . "|Download>":""));
        $payload->addAttachment($attachment);

        $response = $this->slackApiClient->send($payload);

        if ($response->isOk()) {
            if ($response instanceof ChatPostMessagePayloadResponse) {
                /** @var ChatPostMessagePayloadResponse $response */
                $this->ts = $response->getSlackTimestamp();
                $this->channel = $response->getChannelId();
            }
        } else {
            // something went wrong, but what?
            // simple error (Slack's error message)
            echo $response->getError();
            // explained error (Slack's explanation of the error, according to the documentation)
            echo $response->getErrorExplanation();
            exit(1);
        }
    }

    protected function doExecute()
    {
        if (isset($this->app["config"]["slack_api_key"])) {
            $this->slackApiClient = new ApiClient($this->app["config"]["slack_api_key"]);
        } else {<commit_msg>change branch retrieval when execute is launched<commit_after><?php
namespace Kunstmaan\Skylab\Command;

use CL\Slack\Model\Attachment;
use CL\Slack\Model\AttachmentField;
use CL\Slack\Payload\ChatDeletePayload;
use CL\Slack\Payload\ChatPostMessagePayload;
use CL\Slack\Payload\ChatPostMessagePayloadResponse;
use CL\Slack\Transport\ApiClient;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Process;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Parser;

/**
 * ExecuteCommand
 */
class ExecuteCommand extends AbstractCommand
{

    private $ts = null;
    private $channel = null;
    /** @var ApiClient */
    private $slackApiClient = null;

    /**
     * Configures the current command.
     */
    protected function configure()
    {
        $this
            ->addDefaults()
            ->setName('execute')
            ->setDescription('Executes a Skylab YAML file')
            ->addArgument('file', InputArgument::REQUIRED, 'The full path to the YAML file')
            ->addArgument('deploy-environment', InputArgument::OPTIONAL, 'The environment to deploy to')
            ->addOption("--skip-tests", null, InputOption::VALUE_NONE, 'If set, the test steps will be skipped')
            ->addOption("--skip-deploy", null, InputOption::VALUE_NONE, 'If set, the deploy steps will be skipped')
            ->addOption("--debug-yml", null, InputOption::VALUE_NONE, 'If set, the resulting yml will be shown without executing it')
            ->setHelp(<<<EOT
The <info>execute</info> command will execute a Skylab YAML file, used for testing and deploying via Jenkins

<info>php skylab.phar execute /opt/skylab/templates/execute/deploy.yml</info>
EOT
            );
    }

    protected function runStep($step, $yaml, $deployEnv, $successStep = null)
    {
        if (isset($yaml[$step])) {
            $this->dialogProvider->logStep($step);

            foreach ($yaml[$step] as $list) {
                foreach ($list as $source) {
                    foreach ($source as $command) {
                        try {
                            $result = $this->processProvider->executeCommand($command, false, function ($type, $buffer) {
                                if (Process::ERR === $type) {
                                    $this->dialogProvider->logOutput($buffer, true);
                                } else {
                                    if ($this->output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) {
                                        $this->dialogProvider->logOutput($buffer, false);
                                    }
                                }
                            }, $yaml["env"]);
                            if ($result === false) {
                                $this->notifySlack("Error while running the " . $step . " phase, check the console log in Jenkins", $yaml["deploy_matrix"][$deployEnv]["project"], $deployEnv, getenv("slack_user"), array(), "#CC0000", true);
                                $this->dialogProvider->logError($step . " failed!", false);
                            }
                        } catch (\Exception $ex) {
                            $this->notifySlack("Error while running the " . $step . " phase with error: " . $ex->getMessage(), $yaml["deploy_matrix"][$deployEnv]["project"], $deployEnv, getenv("slack_user"), array(), "#CC0000", true);
                            $extra = array();
                            $tags = array();
                            $this->dialogProvider->logException($ex, $tags, $extra);
                        }
                    }
                }
            }
            if (!is_null($successStep)) {
                $this->runStep($successStep, $yaml, $deployEnv);
            }
        } else {
            return;
        }
    }

    protected function notifySlack($message, $project, $env, $user, $resolverArray, $color = "#FFCC00", $update = false)
    {
        if ($update) {
            $payload = new ChatDeletePayload();
            $payload->setSlackTimestamp($this->ts);
            $payload->setChannelId($this->channel);
            $response = $this->slackApiClient->send($payload);

            if ($response->isOk()) {
                if ($response instanceof ChatPostMessagePayloadResponse) {
                    /** @var ChatPostMessagePayloadResponse $response */
                    $this->ts = $response->getSlackTimestamp();
                }
            } else {
                // something went wrong, but what?
                // simple error (Slack's error message)
                echo $response->getError();
                // explained error (Slack's explanation of the error, according to the documentation)
                echo $response->getErrorExplanation();
                exit(1);
            }
        }

        $payload = new ChatPostMessagePayload();
        $payload->setChannel("#" . getenv("slack_channel"));
        $payload->setIconUrl("https://www.dropbox.com/s/ivrj3wcze7cwh54/masterjenkins.png?dl=1");
        $payload->setUsername("Master Jenkins");

        $attachment = new Attachment();
        $attachment->setColor($color);
        $attachment->setFallback("[".$project."#" . getenv("BUILD_NUMBER"). " - " . getenv("GIT_BRANCH") . " to ". $env . "] " . $message);
        $attachment->setText("[".$project."#" . getenv("BUILD_NUMBER"). " - " . getenv("GIT_BRANCH") . " to ". $env . "] " . $message . "\n<" . getenv("BUILD_URL") . "console|Jenkins Console> - <".getenv("BUILD_URL")."changes|Changes>" . (isset($resolverArray["shared_package_target"]) && file_exists($resolverArray["shared_package_target"])?" - <" . $resolverArray["shared_package_url"] . "|Download>":""));
        $payload->addAttachment($attachment);

        $response = $this->slackApiClient->send($payload);

        if ($response->isOk()) {
            if ($response instanceof ChatPostMessagePayloadResponse) {
                /** @var ChatPostMessagePayloadResponse $response */
                $this->ts = $response->getSlackTimestamp();
                $this->channel = $response->getChannelId();
            }
        } else {
            // something went wrong, but what?
            // simple error (Slack's error message)
            echo $response->getError();
            // explained error (Slack's explanation of the error, according to the documentation)
            echo $response->getErrorExplanation();
            exit(1);
        }
    }

    protected function doExecute()
    {
        if (isset($this->app["config"]["slack_api_key"])) {
            $this->slackApiClient = new ApiClient($this->app["config"]["slack_api_key"]);
        } else {
{'fraction_non_alphanumeric': 0.14110203781358052, 'fraction_numerical': 0.0025012874273523137, 'mean_word_length': 2.018876304685765, 'pattern_counts': {'":': 2, '<': 25, '<?xml version=': 0, '>': 135, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3947009', 'n_tokens_mistral': 3646, 'n_tokens_neox': 3524, 'n_words': 750}