<commit_before><?php

namespace Gerrit\GerritTools\Cli\Command;

use GuzzleHttp\Message;
use GuzzleHttp\Client;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Yaml\Parser;
use Symfony\Component\Yaml\Dumper;
use Symfony\Component\Process\Process;
use Symfony\Component\Console\Question\ChoiceQuestion;

class GerritCommand extends Command
{
  protected $config;
  protected $client;

  /**
   * Load configuration from the user's .platform file.
   *
   * Configuration is loaded only if $this->config hasn't been populated
   * already. This allows LoginCommand to avoid writing the config file
   * before using the client for the first time.
   *
   * @return array The populated configuration array.
   */
  protected function loadConfig()
  {
    if (!$this->config) {
        $configPath = $this->getHomeDirectory() . '/.gerrittools';
        $yaml = new Parser();
        $this->config = $yaml->parse(file_get_contents($configPath));
    }

    return $this->config;
  }

  /**
   * Return an instance of the Guzzle client for the gerrit endpoint.
   *
   * @return Client
   */
  protected function getClient()
  {

    $config = $this->loadConfig();
    $user = $config['user'];
    $pass = $config['pass'];
    $gerrit_uri = $config['gerrit_uri'];
      if (!$this->client) {
          $this->client = new Client(['base_url' => $gerrit_uri . '/a']);
          $this->client->setDefaultOption('auth', array(
              $user,
              $pass,
              'Digest'));
          $this->client->setDefaultOption('verify', FALSE);
      }

      return $this->client;
  }

  /**
   * Run a shell command in the current directory.
   *
   * @param string $cmd    The command.
   *
   * @throws \Exception
   *
   * @return string The command output.
   */
  protected function ShellDo($cmd) {

    $process = new Process($cmd);
    $process->run();

    // executes after the command finishes
    if (!$process->isSuccessful()) {
      throw new \RuntimeException($process->getErrorOutput());
    }

    echo $process->getOutput();
  }

  /**
   * Destructor: Write the configuration to disk.
   */
  public function __destruct()
  {
      if (is_array($this->config)) {

          $configPath = $this->getHomeDirectory() . '/.gerrittools';
          $dumper = new Dumper();
          file_put_contents($configPath, $dumper->dump($this->config));
      }
  }

  /**
   * @return string The absolute path to the user's home directory.
   */
  public function getHomeDirectory()
  {
      $home = getenv('HOME');
      if (empty($home)) {
          // Windows compatibility.
          if (!empty($_SERVER['HOMEDRIVE']) && !empty($_SERVER['HOMEPATH'])) {
              $home = $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH'];
          }
      }

      return $home;
  }

  /**
   * To prevent against Cross Site Script Inclusion (XSSI) attacks, the JSON
   * response body starts with a magic prefix line that must be stripped before
   * feeding the rest of the response body to a JSON parser
   *
   * @param $malformattedJson
   *
   * @return string
   */
  public function fixGerritJson($malformattedJson) {
    if (substr($malformattedJson, 0, 4) === ")]}'") {
      return substr((string) $malformattedJson, 4);
    }
    return $malformattedJson;
  }


  public function getOpenChangeId($input, $output) {<commit_msg>Implements the logic that handle a project level config file and a "master" config file store in the users home.<commit_after><?php

namespace Gerrit\GerritTools\Cli\Command;

use GuzzleHttp\Message;
use GuzzleHttp\Client;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Yaml\Parser;
use Symfony\Component\Yaml\Dumper;
use Symfony\Component\Process\Process;
use Symfony\Component\Console\Question\ChoiceQuestion;

class GerritCommand extends Command
{
  protected $config;
  protected $client;

  /**
   * Load configuration from the user's .gerrittools file.
   *
   * @return array The populated configuration array.
   */
  protected function loadConfig()
  {
    if (!$this->config) {
        // Try to find a project config.
        if ($projectRoot = $this->getProjectRoot()) {
          $configPath = $projectRoot . '/.gerrittools';
        }
        else {
          $configPath = $this->getHomeDirectory() . '/.gerrittools';
        }
        $yaml = new Parser();
        $this->config = $yaml->parse(file_get_contents($configPath));
    }

    return $this->config;
  }

  /**
   * Return an instance of the Guzzle client for the gerrit endpoint.
   *
   * @return Client
   */
  protected function getClient()
  {

    $config = $this->loadConfig();
    $user = $config['user'];
    $pass = $config['pass'];
    $gerrit_uri = $config['gerrit_uri'];
      if (!$this->client) {
          $this->client = new Client(['base_url' => $gerrit_uri . '/a']);
          $this->client->setDefaultOption('auth', array(
              $user,
              $pass,
              'Digest'));
          $this->client->setDefaultOption('verify', FALSE);
      }

      return $this->client;
  }

  /**
   * Run a shell command in the current directory.
   *
   * @param string $cmd    The command.
   *
   * @throws \Exception
   *
   * @return string The command output.
   */
  protected function ShellDo($cmd) {

    $process = new Process($cmd);
    $process->run();

    // executes after the command finishes
    if (!$process->isSuccessful()) {
      throw new \RuntimeException($process->getErrorOutput());
    }

    echo $process->getOutput();
  }

  /**
   * Destructor: Write the configuration to disk.
   */
  public function __destruct()
  {
      if (is_array($this->config)) {

          $configPath = $this->getHomeDirectory() . '/.gerrittools';
          $dumper = new Dumper();
          file_put_contents($configPath, $dumper->dump($this->config));
      }
  }

  /**
   * @return string The absolute path to the user's home directory.
   */
  public function getHomeDirectory()
  {
      $home = getenv('HOME');
      if (empty($home)) {
          // Windows compatibility.
          if (!empty($_SERVER['HOMEDRIVE']) && !empty($_SERVER['HOMEPATH'])) {
              $home = $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH'];
          }
      }

      return $home;
  }


  /**
   * Find the root of the current project.
   *
   * The project root might contains a .gerrittools file.
   * The current directory tree is traversed until the file is found, or
   * the home directory is reached.
   */
  protected function getProjectRoot() {
    $homeDir = $this->getHomeDirectory();
    $currentDir = getcwd();
    $projectRoot = NULL;
    while (!$projectRoot) {
      if (file_exists($currentDir . '/.gerrittools')) {
        $projectRoot = $currentDir;
        break;
      }

      // The file was not found, go one directory up.
      $dirParts = explode('/', $currentDir);
      array_pop($dirParts);
      if (count($dirParts) == 0) {
        // We've reached the end, stop.
        break;
      }
      $currentDir = implode('/', $dirParts);
      if ($currentDir == $homeDir) {
        // We've reached the home directory, stop.
        break;
      }
    }

    return $projectRoot;
  }

  /**
   * To prevent against Cross Site Script Inclusion (XSSI) attacks, the JSON
   * response body starts with a magic prefix line that must be stripped before
   * feeding the rest of the response body to a JSON parser
   *
   * @param $malformattedJson
   *
   * @return string
   */
  public function fixGerritJson($malformattedJson) {
    if (substr($malformattedJson, 0, 4) === ")]}'") {
      return substr((string) $malformattedJson, 4);
    }
    return $malformattedJson;
  }


  public function getOpenChangeId($input, $output) {
{'fraction_non_alphanumeric': 0.13555152770585188, 'fraction_numerical': 0.0009062661833247022, 'mean_word_length': 2.591352859135286, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 50, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4600221', 'n_tokens_mistral': 2334, 'n_tokens_neox': 2275, 'n_words': 613}