<?php
namespace nur\tools\compctl;

use Exception;
use nur\A;
use nur\shell;
use nur\SL;

class git {
  static function setup(): void {
    putenv("GIT_DIR");
    putenv("GIT_WORK_TREE");
  }

  protected static function _rcmd(array &$cmd, ?int &$retcode, ?array &$output): void {
    $cmd = SL::merge(["git"], $cmd);
    shell::exec($cmd, $output, $retcode, "noerr");
  }

  static function rcmd(?int &$retcode, ...$cmd): ?array {
    self::_rcmd($cmd, $retcode, $output);
    return $output;
  }

  static function rcmd1(?int &$retcode, ...$args): ?string {
    return A::first(git::rcmd($retcode, ...$args));
  }

  static function cmd(...$cmd): array {
    self::_rcmd($cmd, $retcode, $output);
    if ($retcode != 0) {
      throw new Exception("error running command ".shell::join($cmd));
    }
    return $output;
  }

  static function cmd1(...$args): ?string {
    return A::first(git::cmd(...$args));
  }
}