Skip to content
This repository
tree: 316122c4e0
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

executable file 532 lines (456 sloc) 16.974 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
#!/usr/bin/env php
<?php

/*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

sanity_check_environment();

require_once dirname(__FILE__).'/__init_script__.php';

ini_set('memory_limit', -1);

$original_argv = $argv;
$args = new PhutilArgumentParser($argv);
$args->parseStandardArguments();
$args->parsePartial(
  array(
    array(
      'name' => 'load-phutil-library',
      'param' => 'path',
      'help' => 'Load a libphutil library.',
      'repeat' => true,
    ),
    array(
      'name' => 'conduit-uri',
      'param' => 'uri',
      'help' => 'Connect to Phabricator install specified by __uri__.',
    ),
    array(
      'name' => 'conduit-version',
      'param' => 'version',
      'help' => '(Developers) Mock client version in protocol handshake.',
    ),
    array(
      'name' => 'conduit-timeout',
      'param' => 'timeout',
      'help' => 'Set Conduit timeout (in seconds).',
    ),
  ));

$config_trace_mode = $args->getArg('trace');

$force_conduit = $args->getArg('conduit-uri');
$force_conduit_version = $args->getArg('conduit-version');
$conduit_timeout = $args->getArg('conduit-timeout');
$load = $args->getArg('load-phutil-library');

$argv = $args->getUnconsumedArgumentVector();
$args = array_values($argv);

$working_directory = getcwd();
$console = PhutilConsole::getConsole();

try {

  if ($config_trace_mode) {
    $phutil_location = phutil_get_library_root('phutil');
    $arcanist_location = phutil_get_library_root('arcanist');
    $console->writeErr("libphutil loaded from '{$phutil_location}'.\n");
    $console->writeErr("arcanist loaded from '{$arcanist_location}'.\n");
  }

  if (!$args) {
    throw new ArcanistUsageException("No command provided. Try 'arc help'.");
  }

  $global_config = ArcanistBaseWorkflow::readGlobalArcConfig();
  $system_config = ArcanistBaseWorkflow::readSystemArcConfig();
  $working_copy = ArcanistWorkingCopyIdentity::newFromPath($working_directory);

  // Load additional libraries, which can provide new classes like configuration
  // overrides, linters and lint engines, unit test engines, etc.

  // If the user specified "--load-phutil-library" one or more times from
  // the command line, we load those libraries **instead** of whatever else
  // is configured. This is basically a debugging feature to let you force
  // specific libraries to load regardless of the state of the world.
  if ($load) {
    // Load the flag libraries. These must load, since the user specified them
    // explicitly.
    arcanist_load_libraries(
      $load,
      $must_load = true,
      $lib_source = 'a "--load-phutil-library" flag',
      $working_copy,
      $config_trace_mode);
  } else {
    // Load libraries in system 'load' config. In contrast to global config, we
    // fail hard here because this file is edited manually, so if 'arc' breaks
    // that doesn't make it any more difficult to correct.
    arcanist_load_libraries(
      idx($system_config, 'load', array()),
      $must_load = true,
      $lib_source = 'the "load" setting in system config',
      $working_copy,
      $config_trace_mode);

    // Load libraries in global 'load' config, as per "arc set-config load". We
    // need to fail softly if these break because errors would prevent the user
    // from running "arc set-config" to correct them.
    arcanist_load_libraries(
      idx($global_config, 'load', array()),
      $must_load = false,
      $lib_source = 'the "load" setting in global config',
      $working_copy,
      $config_trace_mode);

    // Load libraries in ".arcconfig". Libraries here must load.
    arcanist_load_libraries(
      $working_copy->getConfig('phutil_libraries'),
      $must_load = true,
      $lib_source = 'the "phutil_libraries" setting in ".arcconfig"',
      $working_copy,
      $config_trace_mode);
  }

  $user_config = ArcanistBaseWorkflow::readUserConfigurationFile();

  $config = $working_copy->getConfig('arcanist_configuration');
  if ($config) {
    $config = new $config();
  } else {
    $config = new ArcanistConfiguration();
  }

  $command = strtolower($args[0]);
  $args = array_slice($args, 1);
  $workflow = $config->buildWorkflow($command);
  if (!$workflow) {

    // If the user has an alias, like 'arc alias dhelp diff help', look it up
    // and substitute it. We do this only after trying to resolve the workflow
    // normally to prevent you from doing silly things like aliasing 'alias'
    // to something else.

    $aliases = ArcanistAliasWorkflow::getAliases($working_copy);
    list($new_command, $args) = ArcanistAliasWorkflow::resolveAliases(
      $command,
      $config,
      $args,
      $working_copy);

    $full_alias = idx($aliases, $command, array());
    $full_alias = implode(' ', $full_alias);

    // Run shell command aliases.

    if (ArcanistAliasWorkflow::isShellCommandAlias($new_command)) {
      $shell_cmd = substr($full_alias, 1);

      if ($config_trace_mode) {
        echo "[alias: 'arc {$command}' -> \$ {$full_alias}]\n";
      }

      if ($args) {
        $err = phutil_passthru('%C %Ls', $shell_cmd, $args);
      } else {
        $err = phutil_passthru('%C', $shell_cmd);
      }
      exit($err);
    }

    // Run arc command aliases.

    if ($new_command) {
      $workflow = $config->buildWorkflow($new_command);
      if ($workflow) {
        if ($config_trace_mode) {
          echo "[alias: 'arc {$command}' -> 'arc {$full_alias}']\n";
        }
        $command = $new_command;
      }
    }

    if (!$workflow) {
      throw new ArcanistUsageException(
        "Unknown command '{$command}'. Try 'arc help'.");
    }
  }

  $workflow->setArcanistConfiguration($config);
  $workflow->setCommand($command);
  $workflow->setWorkingDirectory($working_directory);
  $workflow->parseArguments($args);

  if ($force_conduit_version) {
    $workflow->forceConduitVersion($force_conduit_version);
  }
  if ($conduit_timeout) {
    $workflow->setConduitTimeout($conduit_timeout);
  }

  $need_working_copy = $workflow->requiresWorkingCopy();
  $need_conduit = $workflow->requiresConduit();
  $need_auth = $workflow->requiresAuthentication();
  $need_repository_api = $workflow->requiresRepositoryAPI();

  $want_repository_api = $workflow->desiresRepositoryAPI();
  $want_working_copy = $workflow->desiresWorkingCopy() ||
                       $want_repository_api;

  $need_conduit = $need_conduit ||
                        $need_auth;
  $need_working_copy = $need_working_copy ||
                        $need_repository_api;

  if ($need_working_copy || $want_working_copy) {
    if ($need_working_copy && !$working_copy->getProjectRoot()) {
      throw new ArcanistUsageException(
        "This command must be run in a Git, Mercurial or Subversion working ".
        "copy.");
    }
    $workflow->setWorkingCopy($working_copy);
  }

  if ($force_conduit) {
    $conduit_uri = $force_conduit;
  } else {
    if ($working_copy->getConduitURI()) {
      $conduit_uri = $working_copy->getConduitURI();
    } else {
      $conduit_uri = idx($global_config, 'default');
    }
  }
  if ($conduit_uri) {
    // Set the URI path to '/api/'. TODO: Originally, I contemplated letting
    // you deploy Phabricator somewhere other than the domain root, but ended
    // up never pursuing that. We should get rid of all "/api/" silliness
    // in things users are expected to configure. This is already happening
    // to some degree, e.g. "arc install-certificate" does it for you.
    $conduit_uri = new PhutilURI($conduit_uri);
    $conduit_uri->setPath('/api/');
    $conduit_uri = (string)$conduit_uri;
  }
  $workflow->setConduitURI($conduit_uri);

  if ($need_conduit) {
    if (!$conduit_uri) {

      $message = phutil_console_format(
        "This command requires arc to connect to a Phabricator install, but ".
        "no Phabricator installation is configured. To configure a ".
        "Phabricator URI:\n\n".
        " - set a default location with `arc set-config default <uri>`; or\n".
        " - specify '--conduit-uri=uri' explicitly; or\n".
        " - run 'arc' in a working copy with an '.arcconfig'.\n");

      $message = phutil_console_wrap($message);
      throw new ArcanistUsageException($message);
    }
    $workflow->establishConduit();
  }

  $hosts_config = idx($user_config, 'hosts', array());
  $host_config = idx($hosts_config, $conduit_uri, array());
  $user_name = idx($host_config, 'user');
  $certificate = idx($host_config, 'cert');

  $description = implode(' ', $original_argv);
  $credentials = array(
    'user' => $user_name,
    'certificate' => $certificate,
    'description' => $description,
  );
  $workflow->setConduitCredentials($credentials);

  if ($need_auth) {
    if (!$user_name || !$certificate) {
      throw new ArcanistUsageException(
        phutil_console_format(
          "YOU NEED TO __INSTALL A CERTIFICATE__ TO LOGIN TO PHABRICATOR\n\n".
          "You are trying to connect to '{$conduit_uri}' but do not have ".
          "a certificate installed for this host. Run:\n\n".
          " $ **arc install-certificate**\n\n".
          "...to install one."));
    }
    $workflow->authenticateConduit();
  }

  if ($need_repository_api || ($want_repository_api && $working_copy)) {
    $repository_api = ArcanistRepositoryAPI::newAPIFromWorkingCopyIdentity(
      $working_copy);
    $workflow->setRepositoryAPI($repository_api);
  }

  $listeners = $working_copy->getConfig('events.listeners');
  if ($listeners) {
    foreach ($listeners as $listener) {
      id(new $listener())->register();
    }
  }

  $config->willRunWorkflow($command, $workflow);
  $workflow->willRunWorkflow();
  $err = $workflow->run();
  $config->didRunWorkflow($command, $workflow, $err);
  exit((int)$err);

} catch (ArcanistUsageException $ex) {
  echo phutil_console_format(
    "**Usage Exception:** %s\n",
    $ex->getMessage());
  if ($config_trace_mode) {
    echo "\n";
    throw $ex;
  }

  exit(1);
} catch (Exception $ex) {
  if ($config_trace_mode) {
    throw $ex;
  }

  echo phutil_console_format(
    "**Exception**\n%s\n%s\n",
    $ex->getMessage(),
    "(Run with --trace for a full exception trace.)");

  exit(1);
}


/**
* Perform some sanity checks against the possible diversity of PHP builds in
* the wild, like very old versions and builds that were compiled with flags
* that exclude core functionality.
*/
function sanity_check_environment() {
  $min_version = '5.2.3';
  $cur_version = phpversion();
  if (version_compare($cur_version, $min_version, '<')) {
    die_with_bad_php(
      "You are running PHP version '{$cur_version}', which is older than ".
      "the minimum version, '{$min_version}'. Update to at least ".
      "'{$min_version}'.");
  }

  // NOTE: We don't have phutil_is_windows() yet here.

  if (DIRECTORY_SEPARATOR != '/') {
    $need_functions = array(
      'curl_init' => array('builtin-dll', 'php_curl.dll'),
    );
  } else {
    $need_functions = array(
      'curl_init' => array(
        'text',
        "You need to install the cURL PHP extension, maybe with ".
        "'apt-get install php5-curl' or 'yum install php53-curl' or ".
        "something similar."),
      'json_decode' => array('flag', '--without-json'),
    );
  }

  $problems = array();

  $config = null;
  $show_config = false;
  foreach ($need_functions as $fname => $resolution) {
    if (function_exists($fname)) {
      continue;
    }

    static $info;
    if ($info === null) {
      ob_start();
      phpinfo(INFO_GENERAL);
      $info = ob_get_clean();
      $matches = null;
      if (preg_match('/^Configure Command =>\s*(.*?)$/m', $info, $matches)) {
        $config = $matches[1];
      }
    }

    $generic = true;
    list($what, $which) = $resolution;

    if ($what == 'flag' && strpos($config, $which) !== false) {
      $show_config = true;
      $generic = false;
      $problems[] =
        "This build of PHP was compiled with the configure flag '{$which}', ".
        "which means it does not have the function '{$fname}()'. This ".
        "function is required for arc to run. Rebuild PHP without this flag. ".
        "You may also be able to build or install the relevant extension ".
        "separately.";
    }

    if ($what == 'builtin-dll') {
      $generic = false;
      $problems[] =
        "Your install of PHP does not have the '{$which}' extension enabled. ".
        "Edit your php.ini file and uncomment the line which reads ".
        "'extension={$which}'.";
    }

    if ($what == 'text') {
      $generic = false;
      $problems[] = $which;
    }

    if ($generic) {
      $problems[] =
        "This build of PHP is missing the required function '{$fname}()'. ".
        "Rebuild PHP or install the extension which provides '{$fname}()'.";
    }
  }

  if ($problems) {
    if ($show_config) {
      $problems[] = "PHP was built with this configure command:\n\n{$config}";
    }
    die_with_bad_php(implode("\n\n", $problems));
  }
}

function die_with_bad_php($message) {
  echo "\nPHP CONFIGURATION ERRORS\n\n";
  echo $message;
  echo "\n\n";
  exit(1);
}


function arcanist_load_libraries(
  $load,
  $must_load,
  $lib_source,
  ArcanistWorkingCopyIdentity $working_copy,
  $config_trace_mode) {

  if (!$load) {
    return;
  }

  if (!is_array($load)) {
    $error = "Libraries specified by {$lib_source} are invalid; expected ".
             "a list. Check your configuration.";
    $console = PhutilConsole::getConsole();
    $console->writeErr("WARNING: %s\n", $error);
    return;
  }

  foreach ($load as $location) {

    // Try to resolve the library location. We look in several places, in
    // order:
    //
    // 1. Inside the working copy. This is for phutil libraries within the
    // project. For instance "library/src" will resolve to
    // "./library/src" if it exists.
    // 2. In the same directory as the working copy. This allows you to
    // check out a library alongside a working copy and reference it.
    // If we haven't resolved yet, "library/src" will try to resolve to
    // "../library/src" if it exists.
    // 3. Using normal libphutil resolution rules. Generally, this means
    // that it checks for libraries next to libphutil, then libraries
    // in the PHP include_path.
    //
    // Note that absolute paths will just resolve absolutely through rule (1).

    $resolved = false;

    // Check inside the working copy. This also checks absolute paths, since
    // they'll resolve absolute and just ignore the project root.
    $resolved_location = Filesystem::resolvePath(
      $location,
      $working_copy->getProjectRoot());
    if (Filesystem::pathExists($resolved_location)) {
      $location = $resolved_location;
      $resolved = true;
    }

    // If we didn't find anything, check alongside the working copy.
    if (!$resolved) {
      $resolved_location = Filesystem::resolvePath(
        $location,
        dirname($working_copy->getProjectRoot()));
      if (Filesystem::pathExists($resolved_location)) {
        $location = $resolved_location;
        $resolved = true;
      }
    }

    if ($config_trace_mode) {
      echo "Loading phutil library from '{$location}'...\n";
    }

    $error = null;
    try {
      phutil_load_library($location);
    } catch (PhutilBootloaderException $ex) {
      $error = "Failed to load phutil library at location '{$location}'. ".
               "This library is specified by {$lib_source}. Check that the ".
               "setting is correct and the library is located in the right ".
               "place.";
      if ($must_load) {
        throw new ArcanistUsageException($error);
      } else {
        file_put_contents(
          'php://stderr',
          phutil_console_wrap('WARNING: '.$error."\n\n"));
      }
    } catch (PhutilLibraryConflictException $ex) {
      if ($ex->getLibrary() != 'arcanist') {
        throw $ex;
      }
      $arc_dir = dirname(dirname(__FILE__));
      $error =
        "You are trying to run one copy of Arcanist on another copy of ".
        "Arcanist. This operation is not supported. To execute Arcanist ".
        "operations against this working copy, run './bin/arc' (from the ".
        "current working copy) not some other copy of 'arc' (you ran one ".
        "from '{$arc_dir}').";
      throw new ArcanistUsageException($error);
    }
  }
}
Something went wrong with that request. Please try again.