Page MenuHomePhorge

No OneTemporary

diff --git a/src/console/PhutilConsoleFormatter.php b/src/console/PhutilConsoleFormatter.php
index d380c961..43f1fadc 100644
--- a/src/console/PhutilConsoleFormatter.php
+++ b/src/console/PhutilConsoleFormatter.php
@@ -1,98 +1,113 @@
<?php
final class PhutilConsoleFormatter extends Phobject {
private static $colorCodes = array(
'black' => 0,
'red' => 1,
'green' => 2,
'yellow' => 3,
'blue' => 4,
'magenta' => 5,
'cyan' => 6,
'white' => 7,
'default' => 9,
);
private static $disableANSI;
public static function disableANSI($disable) {
self::$disableANSI = $disable;
}
public static function getDisableANSI() {
if (self::$disableANSI === null) {
- $term = phutil_utf8_strtolower(getenv('TERM'));
- // ansicon enables ANSI support on Windows
- if (!$term && getenv('ANSICON')) {
- $term = 'ansi';
+ self::$disableANSI = self::newShouldDisableAnsi();
+ }
+ return self::$disableANSI;
+ }
+
+ private static function newShouldDisableANSI() {
+ $term = phutil_utf8_strtolower(getenv('TERM'));
+
+ // ansicon enables ANSI support on Windows
+ if (!$term && getenv('ANSICON')) {
+ $term = 'ansi';
+ }
+
+
+ if (phutil_is_windows()) {
+ if ($term !== 'cygwin' && $term !== 'ansi') {
+ return true;
}
+ }
+
+ $stdout = PhutilSystem::getStdoutHandle();
+ if ($stdout === null) {
+ return true;
+ }
- if (phutil_is_windows() && $term !== 'cygwin' && $term !== 'ansi') {
- self::$disableANSI = true;
- } else if (!defined('STDOUT')) {
- self::$disableANSI = true;
- } else if (function_exists('posix_isatty') && !posix_isatty(STDOUT)) {
- self::$disableANSI = true;
- } else {
- self::$disableANSI = false;
+ if (function_exists('posix_isatty')) {
+ if (!posix_isatty($stdout)) {
+ return true;
}
}
- return self::$disableANSI;
+
+ return false;
}
public static function formatString($format /* ... */) {
$args = func_get_args();
$args[0] = self::interpretFormat($args[0]);
return call_user_func_array('sprintf', $args);
}
public static function replaceColorCode($matches) {
$codes = self::$colorCodes;
$offset = 30 + $codes[$matches[2]];
$default = 39;
if ($matches[1] == 'bg') {
$offset += 10;
$default += 10;
}
return chr(27).'['.$offset.'m'.$matches[3].chr(27).'['.$default.'m';
}
public static function interpretFormat($format) {
$colors = implode('|', array_keys(self::$colorCodes));
// Sequence should be preceded by start-of-string or non-backslash
// escaping.
$bold_re = '/(?<![\\\\])\*\*(.*)\*\*/sU';
$underline_re = '/(?<![\\\\])__(.*)__/sU';
$invert_re = '/(?<![\\\\])##(.*)##/sU';
if (self::getDisableANSI()) {
$format = preg_replace($bold_re, '\1', $format);
$format = preg_replace($underline_re, '\1', $format);
$format = preg_replace($invert_re, '\1', $format);
$format = preg_replace(
'@<(fg|bg):('.$colors.')>(.*)</\1>@sU',
'\3',
$format);
} else {
$esc = chr(27);
$bold = $esc.'[1m'.'\\1'.$esc.'[m';
$underline = $esc.'[4m'.'\\1'.$esc.'[m';
$invert = $esc.'[7m'.'\\1'.$esc.'[m';
$format = preg_replace($bold_re, $bold, $format);
$format = preg_replace($underline_re, $underline, $format);
$format = preg_replace($invert_re, $invert, $format);
$format = preg_replace_callback(
'@<(fg|bg):('.$colors.')>(.*)</\1>@sU',
array(__CLASS__, 'replaceColorCode'),
$format);
}
// Remove backslash escaping
return preg_replace('/\\\\(\*\*.*\*\*|__.*__|##.*##)/sU', '\1', $format);
}
}
diff --git a/src/filesystem/PhutilErrorLog.php b/src/filesystem/PhutilErrorLog.php
index bc316c9e..d652d854 100644
--- a/src/filesystem/PhutilErrorLog.php
+++ b/src/filesystem/PhutilErrorLog.php
@@ -1,101 +1,101 @@
<?php
final class PhutilErrorLog
extends Phobject {
private $logName;
private $logPath;
public function setLogName($log_name) {
$this->logName = $log_name;
return $this;
}
public function getLogName() {
return $this->logName;
}
public function setLogPath($log_path) {
$this->logPath = $log_path;
return $this;
}
public function getLogPath() {
return $this->logPath;
}
public function activateLog() {
$log_path = $this->getLogPath();
if ($log_path !== null && false) {
// Test that the path is writable.
$write_exception = null;
try {
Filesystem::assertWritableFile($log_path);
} catch (FilesystemException $ex) {
$write_exception = $ex;
}
// If we hit an exception, try to create the containing directory.
if ($write_exception) {
$log_dir = dirname($log_path);
if (!Filesystem::pathExists($log_dir)) {
try {
Filesystem::createDirectory($log_dir, 0755, true);
} catch (FilesystemException $ex) {
throw new PhutilProxyException(
pht(
'Unable to write log "%s" to path "%s". The containing '.
'directory ("%s") does not exist or is not readable, and '.
'could not be created.',
$this->getLogName(),
$log_path,
$log_dir),
$ex);
}
}
// If we created the parent directory, test if the path is writable
// again.
try {
Filesystem::assertWritableFile($log_path);
$write_exception = null;
} catch (FilesystemException $ex) {
$write_exception = $ex;
}
}
// If we ran into a write exception and couldn't resolve it, fail.
if ($write_exception) {
throw new PhutilProxyException(
pht(
'Unable to write log "%s" to path "%s" because the path is not '.
'writable.',
$this->getLogName(),
$log_path),
$write_exception);
}
}
ini_set('error_log', $log_path);
PhutilErrorHandler::setErrorListener(array($this, 'onError'));
}
public function onError($event, $value, array $metadata) {
// If we've set "error_log" to a real file, so messages won't be output to
// stderr by default. Copy them to stderr.
if ($this->logPath === null) {
return;
}
$message = idx($metadata, 'default_message');
if (strlen($message)) {
$message = tsprintf("%B\n", $message);
- @fwrite(STDERR, $message);
+ PhutilSystem::writeStderr($message);
}
}
}
diff --git a/src/future/exec/PhutilExecPassthru.php b/src/future/exec/PhutilExecPassthru.php
index fc61dc21..63921cf0 100644
--- a/src/future/exec/PhutilExecPassthru.php
+++ b/src/future/exec/PhutilExecPassthru.php
@@ -1,156 +1,160 @@
<?php
/**
* Execute a command which takes over stdin, stdout and stderr, similar to
* `passthru()`, but which preserves TTY semantics, escapes arguments, and is
* traceable.
*
* Passthru commands use the `STDIN`, `STDOUT` and `STDERR` of the parent
* process, so input can be read from the console and output is printed to it.
* This is primarily useful for executing things like `$EDITOR` from command
* line scripts.
*
* $exec = new PhutilExecPassthru('nano -- %s', $filename);
* $err = $exec->resolve();
*
* You can set the current working directory for the command with
* @{method:setCWD}, and set the environment with @{method:setEnv}.
*
* @task command Executing Passthru Commands
*/
final class PhutilExecPassthru extends PhutilExecutableFuture {
private $stdinData;
public function write($data) {
$this->stdinData = $data;
return $this;
}
/* -( Executing Passthru Commands )---------------------------------------- */
public function execute() {
phlog(
pht(
'The "execute()" method of "PhutilExecPassthru" is deprecated and '.
'calls should be replaced with "resolve()". See T13660.'));
return $this->resolve();
}
/**
* Execute this command.
*
* @return int Error code returned by the subprocess.
*
* @task command
*/
private function executeCommand() {
$command = $this->getCommand();
$is_write = ($this->stdinData !== null);
if ($is_write) {
$stdin_spec = array('pipe', 'r');
} else {
- $stdin_spec = STDIN;
+ $stdin_spec = PhutilSystem::getStdinHandle();
}
- $spec = array($stdin_spec, STDOUT, STDERR);
+ $spec = array(
+ $stdin_spec,
+ PhutilSystem::getStdoutHandle(),
+ PhutilSystem::getStderrHandle(),
+ );
$pipes = array();
$unmasked_command = $command->getUnmaskedString();
if ($this->hasEnv()) {
$env = $this->getEnv();
} else {
$env = null;
}
$cwd = $this->getCWD();
$options = array();
if (phutil_is_windows()) {
// Without 'bypass_shell', things like launching vim don't work properly,
// and we can't execute commands with spaces in them, and all commands
// invoked from git bash fail horridly, and everything is a mess in
// general.
$options['bypass_shell'] = true;
}
$trap = new PhutilErrorTrap();
$proc = @proc_open(
$unmasked_command,
$spec,
$pipes,
$cwd,
$env,
$options);
$errors = $trap->getErrorsAsString();
$trap->destroy();
if (!is_resource($proc)) {
// See T13504. When "proc_open()" is given a command with a binary
// that isn't available on Windows with "bypass_shell", the function
// fails entirely.
if (phutil_is_windows()) {
$err = 1;
} else {
throw new Exception(
pht(
'Failed to passthru %s: %s',
'proc_open()',
$errors));
}
} else {
if ($is_write) {
fwrite($pipes[0], $this->stdinData);
fclose($pipes[0]);
}
$err = proc_close($proc);
}
return $err;
}
/* -( Future )------------------------------------------------------------- */
public function isReady() {
// This isn't really a future because it executes synchronously and has
// full control of the console. We're just implementing the interfaces to
// make it easier to share code with ExecFuture.
if (!$this->hasResult()) {
$result = $this->executeCommand();
$this->setResult($result);
}
return true;
}
protected function getServiceProfilerStartParameters() {
return array(
'type' => 'exec',
'subtype' => 'passthru',
'command' => phutil_string_cast($this->getCommand()),
);
}
protected function getServiceProfilerResultParameters() {
if ($this->hasResult()) {
$err = $this->getResult();
} else {
$err = null;
}
return array(
'err' => $err,
);
}
}
diff --git a/src/log/ArcanistLogEngine.php b/src/log/ArcanistLogEngine.php
index 11f6918b..c2d19c13 100644
--- a/src/log/ArcanistLogEngine.php
+++ b/src/log/ArcanistLogEngine.php
@@ -1,105 +1,105 @@
<?php
final class ArcanistLogEngine
extends Phobject {
private $showTraceMessages;
public function setShowTraceMessages($show_trace_messages) {
$this->showTraceMessages = $show_trace_messages;
return $this;
}
public function getShowTraceMessages() {
return $this->showTraceMessages;
}
public function newMessage() {
return new ArcanistLogMessage();
}
private function writeBytes($bytes) {
- fprintf(STDERR, '%s', $bytes);
+ PhutilSystem::writeStderr($bytes);
return $this;
}
public function writeNewline() {
return $this->writeBytes("\n");
}
public function writeMessage(ArcanistLogMessage $message) {
$color = $message->getColor();
$this->writeBytes(
tsprintf(
"**<bg:".$color."> %s </bg>** %s\n",
$message->getLabel(),
$message->getMessage()));
return $message;
}
public function writeWarning($label, $message) {
return $this->writeMessage(
$this->newMessage()
->setColor('yellow')
->setLabel($label)
->setMessage($message));
}
public function writeError($label, $message) {
return $this->writeMessage(
$this->newMessage()
->setColor('red')
->setLabel($label)
->setMessage($message));
}
public function writeSuccess($label, $message) {
return $this->writeMessage(
$this->newMessage()
->setColor('green')
->setLabel($label)
->setMessage($message));
}
public function writeStatus($label, $message) {
return $this->writeMessage(
$this->newMessage()
->setColor('blue')
->setLabel($label)
->setMessage($message));
}
public function writeTrace($label, $message) {
$trace = $this->newMessage()
->setColor('magenta')
->setLabel($label)
->setMessage($message);
if ($this->getShowTraceMessages()) {
$this->writeMessage($trace);
}
return $trace;
}
public function writeHint($label, $message) {
return $this->writeMessage(
$this->newMessage()
->setColor('cyan')
->setLabel($label)
->setMessage($message));
}
public function writeWaitingForInput() {
if (!phutil_is_interactive()) {
return;
}
$this->writeStatus(
pht('INPUT'),
pht('Waiting for input on stdin...'));
}
}
diff --git a/src/parser/ArcanistBaseCommitParser.php b/src/parser/ArcanistBaseCommitParser.php
index 5ed6ce4a..2c886bd6 100644
--- a/src/parser/ArcanistBaseCommitParser.php
+++ b/src/parser/ArcanistBaseCommitParser.php
@@ -1,208 +1,208 @@
<?php
final class ArcanistBaseCommitParser extends Phobject {
private $api;
private $try;
private $verbose = false;
public function __construct(ArcanistRepositoryAPI $api) {
$this->api = $api;
}
private function tokenizeBaseCommitSpecification($raw_spec) {
if (!$raw_spec) {
return array();
}
$spec = preg_split('/\s*,\s*/', $raw_spec);
$spec = array_filter($spec);
foreach ($spec as $rule) {
if (strpos($rule, ':') === false) {
throw new ArcanistUsageException(
pht(
"Rule '%s' is invalid, it must have a type and name like '%s'.",
$rule,
'arc:upstream'));
}
}
return $spec;
}
private function log($message) {
if ($this->verbose) {
- fwrite(STDERR, $message."\n");
+ PhutilSystem::writeStderr($message."\n");
}
}
public function resolveBaseCommit(array $specs) {
$specs += array(
'runtime' => '',
'local' => '',
'project' => '',
'user' => '',
'system' => '',
);
foreach ($specs as $source => $spec) {
$specs[$source] = self::tokenizeBaseCommitSpecification($spec);
}
$this->try = array(
'runtime',
'local',
'project',
'user',
'system',
);
while ($this->try) {
$source = head($this->try);
if (!idx($specs, $source)) {
$this->log(pht("No rules left from source '%s'.", $source));
array_shift($this->try);
continue;
}
$this->log(pht("Trying rules from source '%s'.", $source));
$rules = &$specs[$source];
while ($rule = array_shift($rules)) {
$this->log(pht("Trying rule '%s'.", $rule));
$commit = $this->resolveRule($rule, $source);
if ($commit === false) {
// If a rule returns false, it means to go to the next ruleset.
break;
} else if ($commit !== null) {
$this->log(pht(
"Resolved commit '%s' from rule '%s'.",
$commit,
$rule));
return $commit;
}
}
}
return null;
}
/**
* Handle resolving individual rules.
*/
private function resolveRule($rule, $source) {
// NOTE: Returning `null` from this method means "no match".
// Returning `false` from this method means "stop current ruleset".
list($type, $name) = explode(':', $rule, 2);
switch ($type) {
case 'literal':
return $name;
case 'git':
case 'hg':
return $this->api->resolveBaseCommitRule($rule, $source);
case 'arc':
return $this->resolveArcRule($rule, $name, $source);
default:
throw new ArcanistUsageException(
pht(
"Base commit rule '%s' (from source '%s') ".
"is not a recognized rule.",
$rule,
$source));
}
}
/**
* Handle resolving "arc:*" rules.
*/
private function resolveArcRule($rule, $name, $source) {
$name = $this->updateLegacyRuleName($name);
switch ($name) {
case 'verbose':
$this->verbose = true;
$this->log(pht('Enabled verbose mode.'));
break;
case 'prompt':
$reason = pht('it is what you typed when prompted.');
$this->api->setBaseCommitExplanation($reason);
$result = phutil_console_prompt(pht('Against which commit?'));
if (!strlen($result)) {
// Allow the user to continue to the next rule by entering no
// text.
return null;
}
return $result;
case 'local':
case 'user':
case 'project':
case 'runtime':
case 'system':
// Push the other source on top of the list.
array_unshift($this->try, $name);
$this->log(pht("Switching to source '%s'.", $name));
return false;
case 'yield':
// Cycle this source to the end of the list.
$this->try[] = array_shift($this->try);
$this->log(pht("Yielding processing of rules from '%s'.", $source));
return false;
case 'halt':
// Dump the whole stack.
$this->try = array();
$this->log(pht('Halting all rule processing.'));
return false;
case 'skip':
return null;
case 'empty':
case 'upstream':
case 'outgoing':
case 'bookmark':
case 'amended':
case 'this':
return $this->api->resolveBaseCommitRule($rule, $source);
default:
$matches = null;
if (preg_match('/^exec\((.*)\)$/', $name, $matches)) {
$root = $this->api->getWorkingCopyIdentity()->getProjectRoot();
$future = new ExecFuture('%C', $matches[1]);
$future->setCWD($root);
list($err, $stdout) = $future->resolve();
if (!$err) {
return trim($stdout);
} else {
return null;
}
} else if (preg_match('/^nodiff\((.*)\)$/', $name, $matches)) {
return $this->api->resolveBaseCommitRule($rule, $source);
}
throw new ArcanistUsageException(
pht(
"Base commit rule '%s' (from source '%s') ".
"is not a recognized rule.",
$rule,
$source));
}
}
private function updateLegacyRuleName($name) {
$updated = array(
'global' => 'user',
'args' => 'runtime',
);
$new_name = idx($updated, $name);
if ($new_name) {
$this->log(pht("Translating legacy name '%s' to '%s'", $name, $new_name));
return $new_name;
}
return $name;
}
}
diff --git a/src/parser/argument/PhutilArgumentParser.php b/src/parser/argument/PhutilArgumentParser.php
index 1bf31a23..04b04666 100644
--- a/src/parser/argument/PhutilArgumentParser.php
+++ b/src/parser/argument/PhutilArgumentParser.php
@@ -1,1017 +1,1017 @@
<?php
/**
* Parser for command-line arguments for scripts. Like similar parsers, this
* class allows you to specify, validate, and render help for command-line
* arguments. For example:
*
* name=create_dog.php
* $args = new PhutilArgumentParser($argv);
* $args->setTagline('make an new dog')
* $args->setSynopsis(<<<EOHELP
* **dog** [--big] [--name __name__]
* Create a new dog. How does it work? Who knows.
* EOHELP
* );
* $args->parse(
* array(
* array(
* 'name' => 'name',
* 'param' => 'dogname',
* 'default' => 'Rover',
* 'help' => 'Set the dog\'s name. By default, the dog will be '.
* 'named "Rover".',
* ),
* array(
* 'name' => 'big',
* 'short' => 'b',
* 'help' => 'If set, create a large dog.',
* ),
* ));
*
* $dog_name = $args->getArg('name');
* $dog_size = $args->getArg('big') ? 'big' : 'small';
*
* // ... etc ...
*
* (For detailed documentation on supported keys in argument specifications,
* see @{class:PhutilArgumentSpecification}.)
*
* This will handle argument parsing, and generate appropriate usage help if
* the user provides an unsupported flag. @{class:PhutilArgumentParser} also
* supports some builtin "standard" arguments:
*
* $args->parseStandardArguments();
*
* See @{method:parseStandardArguments} for details. Notably, this includes
* a "--help" flag, and an "--xprofile" flag for profiling command-line scripts.
*
* Normally, when the parser encounters an unknown flag, it will exit with
* an error. However, you can use @{method:parsePartial} to consume only a
* set of flags:
*
* $args->parsePartial($spec_list);
*
* This allows you to parse some flags before making decisions about other
* parsing, or share some flags across scripts. The builtin standard arguments
* are implemented in this way.
*
* There is also builtin support for "workflows", which allow you to build a
* script that operates in several modes (e.g., by accepting commands like
* `install`, `upgrade`, etc), like `arc` does. For detailed documentation on
* workflows, see @{class:PhutilArgumentWorkflow}.
*
* @task parse Parsing Arguments
* @task read Reading Arguments
* @task help Command Help
* @task internal Internals
*/
final class PhutilArgumentParser extends Phobject {
private $bin;
private $argv;
private $specs = array();
private $results = array();
private $parsed;
private $tagline;
private $synopsis;
private $workflows;
private $helpWorkflows;
private $showHelp;
private $requireArgumentTerminator = false;
private $sawTerminator = false;
const PARSE_ERROR_CODE = 77;
private static $traceModeEnabled = false;
/* -( Parsing Arguments )-------------------------------------------------- */
/**
* Build a new parser. Generally, you start a script with:
*
* $args = new PhutilArgumentParser($argv);
*
* @param list Argument vector to parse, generally the $argv global.
* @task parse
*/
public function __construct(array $argv) {
$this->bin = $argv[0];
$this->argv = array_slice($argv, 1);
}
/**
* Parse and consume a list of arguments, removing them from the argument
* vector but leaving unparsed arguments for later consumption. You can
* retrieve unconsumed arguments directly with
* @{method:getUnconsumedArgumentVector}. Doing a partial parse can make it
* easier to share common flags across scripts or workflows.
*
* @param list List of argument specs, see
* @{class:PhutilArgumentSpecification}.
* @param bool Require flags appear before any non-flag arguments.
* @return this
* @task parse
*/
public function parsePartial(array $specs, $initial_only = false) {
return $this->parseInternal($specs, false, $initial_only);
}
/**
* @return this
*/
private function parseInternal(
array $specs,
$correct_spelling,
$initial_only) {
$specs = PhutilArgumentSpecification::newSpecsFromList($specs);
$this->mergeSpecs($specs);
// Wildcard arguments have a name like "argv", but we don't want to
// parse a corresponding flag like "--argv". Filter them out before
// building a list of available flags.
$non_wildcard = array();
foreach ($specs as $spec_key => $spec) {
if ($spec->getWildcard()) {
continue;
}
$non_wildcard[$spec_key] = $spec;
}
$specs_by_name = mpull($non_wildcard, null, 'getName');
$specs_by_short = mpull($non_wildcard, null, 'getShortAlias');
unset($specs_by_short[null]);
$argv = $this->argv;
$len = count($argv);
$is_initial = true;
for ($ii = 0; $ii < $len; $ii++) {
$arg = $argv[$ii];
$map = null;
$options = null;
if (!is_string($arg)) {
// Non-string argument; pass it through as-is.
} else if ($arg == '--') {
// This indicates "end of flags".
$this->sawTerminator = true;
break;
} else if ($arg == '-') {
// This is a normal argument (e.g., stdin).
continue;
} else if (!strncmp('--', $arg, 2)) {
$pre = '--';
$arg = substr($arg, 2);
$map = $specs_by_name;
$options = array_keys($specs_by_name);
} else if (!strncmp('-', $arg, 1) && strlen($arg) > 1) {
$pre = '-';
$arg = substr($arg, 1);
$map = $specs_by_short;
} else {
$is_initial = false;
}
if ($map) {
$val = null;
$parts = explode('=', $arg, 2);
if (count($parts) == 2) {
list($arg, $val) = $parts;
}
// Try to correct flag spelling for full flags, to allow users to make
// minor mistakes.
if ($correct_spelling && $options && !isset($map[$arg])) {
$corrections = PhutilArgumentSpellingCorrector::newFlagCorrector()
->correctSpelling($arg, $options);
$should_autocorrect = $this->shouldAutocorrect();
if (count($corrections) == 1 && $should_autocorrect) {
$corrected = head($corrections);
$this->logMessage(
tsprintf(
"%s\n",
pht(
'(Assuming "%s" is the British spelling of "%s".)',
$pre.$arg,
$pre.$corrected)));
$arg = $corrected;
}
}
if (isset($map[$arg])) {
if ($initial_only && !$is_initial) {
throw new PhutilArgumentUsageException(
pht(
'Argument "%s" appears after the first non-flag argument. '.
'This special argument must appear before other arguments.',
"{$pre}{$arg}"));
}
$spec = $map[$arg];
unset($argv[$ii]);
$param_name = $spec->getParamName();
if ($val !== null) {
if ($param_name === null) {
throw new PhutilArgumentUsageException(
pht(
'Argument "%s" does not take a parameter.',
"{$pre}{$arg}"));
}
} else {
if ($param_name !== null) {
if ($ii + 1 < $len) {
$val = $argv[$ii + 1];
unset($argv[$ii + 1]);
$ii++;
} else {
throw new PhutilArgumentUsageException(
pht(
'Argument "%s" requires a parameter.',
"{$pre}{$arg}"));
}
} else {
$val = true;
}
}
if (!$spec->getRepeatable()) {
if (array_key_exists($spec->getName(), $this->results)) {
throw new PhutilArgumentUsageException(
pht(
'Argument "%s" was provided twice.',
"{$pre}{$arg}"));
}
}
$conflicts = $spec->getConflicts();
foreach ($conflicts as $conflict => $reason) {
if (array_key_exists($conflict, $this->results)) {
if (!is_string($reason) || !strlen($reason)) {
$reason = '.';
} else {
$reason = ': '.$reason.'.';
}
throw new PhutilArgumentUsageException(
pht(
'Argument "%s" conflicts with argument "%s"%s',
"{$pre}{$arg}",
"--{$conflict}",
$reason));
}
}
if ($spec->getRepeatable()) {
if ($spec->getParamName() === null) {
if (empty($this->results[$spec->getName()])) {
$this->results[$spec->getName()] = 0;
}
$this->results[$spec->getName()]++;
} else {
$this->results[$spec->getName()][] = $val;
}
} else {
$this->results[$spec->getName()] = $val;
}
}
}
}
foreach ($specs as $spec) {
if ($spec->getWildcard()) {
$this->results[$spec->getName()] = $this->filterWildcardArgv($argv);
$argv = array();
break;
}
}
$this->argv = array_values($argv);
return $this;
}
/**
* Parse and consume a list of arguments, throwing an exception if there is
* anything left unconsumed. This is like @{method:parsePartial}, but raises
* a {class:PhutilArgumentUsageException} if there are leftovers.
*
* Normally, you would call @{method:parse} instead, which emits a
* user-friendly error. You can also use @{method:printUsageException} to
* render the exception in a user-friendly way.
*
* @param list List of argument specs, see
* @{class:PhutilArgumentSpecification}.
* @return this
* @task parse
*/
public function parseFull(array $specs) {
$this->parseInternal($specs, true, false);
// If we have remaining unconsumed arguments other than a single "--",
// fail.
$argv = $this->filterWildcardArgv($this->argv);
if ($argv) {
throw new PhutilArgumentUsageException(
pht(
'Unrecognized argument "%s".',
head($argv)));
}
if ($this->getRequireArgumentTerminator()) {
if (!$this->sawTerminator) {
throw new ArcanistMissingArgumentTerminatorException();
}
}
if ($this->showHelp) {
$this->printHelpAndExit();
}
return $this;
}
/**
* Parse and consume a list of arguments, raising a user-friendly error if
* anything remains. See also @{method:parseFull} and @{method:parsePartial}.
*
* @param list List of argument specs, see
* @{class:PhutilArgumentSpecification}.
* @return this
* @task parse
*/
public function parse(array $specs) {
try {
return $this->parseFull($specs);
} catch (PhutilArgumentUsageException $ex) {
$this->printUsageException($ex);
exit(self::PARSE_ERROR_CODE);
}
}
/**
* Parse and execute workflows, raising a user-friendly error if anything
* remains. See also @{method:parseWorkflowsFull}.
*
* See @{class:PhutilArgumentWorkflow} for details on using workflows.
*
* @param list List of argument specs, see
* @{class:PhutilArgumentSpecification}.
* @return this
* @task parse
*/
public function parseWorkflows(array $workflows) {
try {
return $this->parseWorkflowsFull($workflows);
} catch (PhutilArgumentUsageException $ex) {
$this->printUsageException($ex);
exit(self::PARSE_ERROR_CODE);
}
}
/**
* Select a workflow. For commands that may operate in several modes, like
* `arc`, the modes can be split into "workflows". Each workflow specifies
* the arguments it accepts. This method takes a list of workflows, selects
* the chosen workflow, parses its arguments, and either executes it (if it
* is executable) or returns it for handling.
*
* See @{class:PhutilArgumentWorkflow} for details on using workflows.
*
* @param list List of @{class:PhutilArgumentWorkflow}s.
* @return PhutilArgumentWorkflow|no Returns the chosen workflow if it is
* not executable, or executes it and
* exits with a return code if it is.
* @task parse
*/
public function parseWorkflowsFull(array $workflows) {
assert_instances_of($workflows, 'PhutilArgumentWorkflow');
// Clear out existing workflows. We need to do this to permit the
// construction of sub-workflows.
$this->workflows = array();
foreach ($workflows as $workflow) {
$name = $workflow->getName();
if ($name === null) {
throw new PhutilArgumentSpecificationException(
pht('Workflow has no name!'));
}
if (isset($this->workflows[$name])) {
throw new PhutilArgumentSpecificationException(
pht("Two workflows with name '%s!", $name));
}
$this->workflows[$name] = $workflow;
}
$argv = $this->argv;
if (empty($argv)) {
// TODO: this is kind of hacky / magical.
if (isset($this->workflows['help'])) {
$argv = array('help');
} else {
throw new PhutilArgumentUsageException(pht('No workflow selected.'));
}
}
$flow = array_shift($argv);
if (empty($this->workflows[$flow])) {
$corrected = PhutilArgumentSpellingCorrector::newCommandCorrector()
->correctSpelling($flow, array_keys($this->workflows));
$should_autocorrect = $this->shouldAutocorrect();
if (count($corrected) == 1 && $should_autocorrect) {
$corrected = head($corrected);
$this->logMessage(
tsprintf(
"%s\n",
pht(
'(Assuming "%s" is the British spelling of "%s".)',
$flow,
$corrected)));
$flow = $corrected;
} else {
if (!$this->showHelp) {
$this->raiseUnknownWorkflow($flow, $corrected);
}
}
}
$workflow = idx($this->workflows, $flow);
if ($this->showHelp) {
// Make "cmd flow --help" behave like "cmd help flow", not "cmd help".
$help_flow = idx($this->workflows, 'help');
if ($help_flow) {
if ($help_flow !== $workflow) {
$workflow = $help_flow;
$argv = array($flow);
// Prevent parse() from dumping us back out to standard help.
$this->showHelp = false;
}
} else {
$this->printHelpAndExit();
}
}
if (!$workflow) {
$this->raiseUnknownWorkflow($flow, $corrected);
}
$this->argv = array_values($argv);
if ($workflow->shouldParsePartial()) {
$this->parsePartial($workflow->getArguments());
} else {
$this->parse($workflow->getArguments());
}
if ($workflow->isExecutable()) {
$workflow->setArgv($this);
$err = $workflow->execute($this);
exit($err);
} else {
return $workflow;
}
}
/**
* Parse "standard" arguments and apply their effects:
*
* --trace Enable service call tracing.
* --no-ansi Disable ANSI color/style sequences.
* --xprofile <file> Write out an XHProf profile.
* --help Show help.
*
* @return this
*
* @phutil-external-symbol function xhprof_enable
*/
public function parseStandardArguments() {
try {
$this->parsePartial(
array(
array(
'name' => 'trace',
'help' => pht('Trace command execution and show service calls.'),
'standard' => true,
),
array(
'name' => 'no-ansi',
'help' => pht(
'Disable ANSI terminal codes, printing plain text with '.
'no color or style.'),
'conflicts' => array(
'ansi' => null,
),
'standard' => true,
),
array(
'name' => 'ansi',
'help' => pht(
"Use formatting even in environments which probably ".
"don't support it."),
'standard' => true,
),
array(
'name' => 'xprofile',
'param' => 'profile',
'help' => pht(
'Profile script execution and write results to a file.'),
'standard' => true,
),
array(
'name' => 'help',
'short' => 'h',
'help' => pht('Show this help.'),
'standard' => true,
),
array(
'name' => 'show-standard-options',
'help' => pht(
'Show every option, including standard options like this one.'),
'standard' => true,
),
array(
'name' => 'recon',
'help' => pht('Start in remote console mode.'),
'standard' => true,
),
));
} catch (PhutilArgumentUsageException $ex) {
$this->printUsageException($ex);
exit(self::PARSE_ERROR_CODE);
}
if ($this->getArg('trace')) {
PhutilServiceProfiler::installEchoListener();
self::$traceModeEnabled = true;
}
if ($this->getArg('no-ansi')) {
PhutilConsoleFormatter::disableANSI(true);
}
if ($this->getArg('ansi')) {
PhutilConsoleFormatter::disableANSI(false);
}
if ($this->getArg('help')) {
$this->showHelp = true;
}
$xprofile = $this->getArg('xprofile');
if ($xprofile) {
if (!function_exists('xhprof_enable')) {
throw new Exception(
pht('To use "--xprofile", you must install XHProf.'));
}
xhprof_enable(0);
register_shutdown_function(array($this, 'shutdownProfiler'));
}
$recon = $this->getArg('recon');
if ($recon) {
$remote_console = PhutilConsole::newRemoteConsole();
$remote_console->beginRedirectOut();
PhutilConsole::setConsole($remote_console);
} else if ($this->getArg('trace')) {
$server = new PhutilConsoleServer();
$server->setEnableLog(true);
$console = PhutilConsole::newConsoleForServer($server);
PhutilConsole::setConsole($console);
}
return $this;
}
/* -( Reading Arguments )-------------------------------------------------- */
public function getArg($name) {
if (empty($this->specs[$name])) {
throw new PhutilArgumentSpecificationException(
pht('No specification exists for argument "%s"!', $name));
}
if (idx($this->results, $name) !== null) {
return $this->results[$name];
}
return $this->specs[$name]->getDefault();
}
public function getUnconsumedArgumentVector() {
return $this->argv;
}
public function setUnconsumedArgumentVector(array $argv) {
$this->argv = $argv;
return $this;
}
public function setWorkflows($workflows) {
$workflows = mpull($workflows, null, 'getName');
$this->workflows = $workflows;
return $this;
}
public function setHelpWorkflows(array $help_workflows) {
$help_workflows = mpull($help_workflows, null, 'getName');
$this->helpWorkflows = $help_workflows;
return $this;
}
public function getWorkflows() {
return $this->workflows;
}
/* -( Command Help )------------------------------------------------------- */
public function setRequireArgumentTerminator($require) {
$this->requireArgumentTerminator = $require;
return $this;
}
public function getRequireArgumentTerminator() {
return $this->requireArgumentTerminator;
}
public function setSynopsis($synopsis) {
$this->synopsis = $synopsis;
return $this;
}
public function setTagline($tagline) {
$this->tagline = $tagline;
return $this;
}
public function printHelpAndExit() {
echo $this->renderHelp();
exit(self::PARSE_ERROR_CODE);
}
public function renderHelp() {
$out = array();
$more = array();
if ($this->bin) {
$out[] = $this->format('**%s**', pht('NAME'));
$name = $this->indent(6, '**%s**', basename($this->bin));
if ($this->tagline) {
$name .= $this->format(' - '.$this->tagline);
}
$out[] = $name;
$out[] = null;
}
if ($this->synopsis) {
$out[] = $this->format('**%s**', pht('SYNOPSIS'));
$out[] = $this->indent(6, $this->synopsis);
$out[] = null;
}
$workflows = $this->helpWorkflows;
if ($workflows === null) {
$workflows = $this->workflows;
}
if ($workflows) {
$has_help = false;
$out[] = $this->format('**%s**', pht('WORKFLOWS'));
$out[] = null;
$flows = $workflows;
ksort($flows);
foreach ($flows as $workflow) {
if ($workflow->getName() == 'help') {
$has_help = true;
}
$out[] = $this->renderWorkflowHelp(
$workflow->getName(),
$show_details = false);
}
if ($has_help) {
$more[] = pht(
'Use **%s** __command__ for a detailed command reference.', 'help');
}
}
$specs = $this->renderArgumentSpecs($this->specs);
if ($specs) {
$out[] = $this->format('**%s**', pht('OPTION REFERENCE'));
$out[] = null;
$out[] = $specs;
}
// If we have standard options but no --show-standard-options, print out
// a quick hint about it.
if (!empty($this->specs['show-standard-options']) &&
!$this->getArg('show-standard-options')) {
$more[] = pht(
'Use __%s__ to show additional options.', '--show-standard-options');
}
$out[] = null;
if ($more) {
foreach ($more as $hint) {
$out[] = $this->indent(0, $hint);
}
$out[] = null;
}
return implode("\n", $out);
}
public function renderWorkflowHelp(
$workflow_name,
$show_details = false) {
$out = array();
$indent = ($show_details ? 0 : 6);
$workflows = $this->helpWorkflows;
if ($workflows === null) {
$workflows = $this->workflows;
}
$workflow = idx($workflows, strtolower($workflow_name));
if (!$workflow) {
$out[] = $this->indent(
$indent,
pht('There is no **%s** workflow.', $workflow_name));
} else {
$out[] = $this->indent($indent, $workflow->getExamples());
$synopsis = $workflow->getSynopsis();
if ($synopsis !== null) {
$out[] = $this->indent($indent, $workflow->getSynopsis());
}
if ($show_details) {
$full_help = $workflow->getHelp();
if ($full_help) {
$out[] = null;
$out[] = $this->indent($indent, $full_help);
}
$specs = $this->renderArgumentSpecs($workflow->getArguments());
if ($specs) {
$out[] = null;
$out[] = $specs;
}
}
}
$out[] = null;
return implode("\n", $out);
}
public function printUsageException(PhutilArgumentUsageException $ex) {
$message = tsprintf(
"**%s** %B\n",
pht('Usage Exception:'),
$ex->getMessage());
$this->logMessage($message);
}
private function logMessage($message) {
- fwrite(STDERR, $message);
+ PhutilSystem::writeStderr($message);
}
/* -( Internals )---------------------------------------------------------- */
private function filterWildcardArgv(array $argv) {
foreach ($argv as $key => $value) {
if ($value == '--') {
unset($argv[$key]);
break;
} else if (
is_string($value) &&
!strncmp($value, '-', 1) &&
strlen($value) > 1) {
throw new PhutilArgumentUsageException(
pht(
'Argument "%s" is unrecognized. Use "%s" to indicate '.
'the end of flags.',
$value,
'--'));
}
}
return array_values($argv);
}
private function mergeSpecs(array $specs) {
$short_map = mpull($this->specs, null, 'getShortAlias');
unset($short_map[null]);
$wildcard = null;
foreach ($this->specs as $spec) {
if ($spec->getWildcard()) {
$wildcard = $spec;
break;
}
}
foreach ($specs as $spec) {
$spec->validate();
$name = $spec->getName();
if (isset($this->specs[$name])) {
throw new PhutilArgumentSpecificationException(
pht(
'Two argument specifications have the same name ("%s").',
$name));
}
$short = $spec->getShortAlias();
if ($short) {
if (isset($short_map[$short])) {
throw new PhutilArgumentSpecificationException(
pht(
'Two argument specifications have the same short alias ("%s").',
$short));
}
$short_map[$short] = $spec;
}
if ($spec->getWildcard()) {
if ($wildcard) {
throw new PhutilArgumentSpecificationException(
pht(
'Two argument specifications are marked as wildcard arguments. '.
'You can have a maximum of one wildcard argument.'));
} else {
$wildcard = $spec;
}
}
$this->specs[$name] = $spec;
}
foreach ($this->specs as $name => $spec) {
foreach ($spec->getConflicts() as $conflict => $reason) {
if (empty($this->specs[$conflict])) {
throw new PhutilArgumentSpecificationException(
pht(
'Argument "%s" conflicts with unspecified argument "%s".',
$name,
$conflict));
}
if ($conflict == $name) {
throw new PhutilArgumentSpecificationException(
pht(
'Argument "%s" conflicts with itself!',
$name));
}
}
}
}
private function renderArgumentSpecs(array $specs) {
foreach ($specs as $key => $spec) {
if ($spec->getWildcard()) {
unset($specs[$key]);
}
}
$out = array();
$no_standard_options =
!empty($this->specs['show-standard-options']) &&
!$this->getArg('show-standard-options');
$specs = msort($specs, 'getName');
foreach ($specs as $spec) {
if ($spec->getStandard() && $no_standard_options) {
// If this is a standard argument and the user didn't pass
// --show-standard-options, skip it.
continue;
}
$name = $this->indent(6, '__--%s__', $spec->getName());
$short = null;
if ($spec->getShortAlias()) {
$short = $this->format(', __-%s__', $spec->getShortAlias());
}
if ($spec->getParamName()) {
$param = $this->format(' __%s__', $spec->getParamName());
$name .= $param;
if ($short) {
$short .= $param;
}
}
$out[] = $name.$short;
$out[] = $this->indent(10, $spec->getHelp());
$out[] = null;
}
return implode("\n", $out);
}
private function format($str /* , ... */) {
$args = func_get_args();
return call_user_func_array(
'phutil_console_format',
$args);
}
private function indent($level, $str /* , ... */) {
$args = func_get_args();
$args = array_slice($args, 1);
$text = call_user_func_array(array($this, 'format'), $args);
return phutil_console_wrap($text, $level);
}
/**
* @phutil-external-symbol function xhprof_disable
*/
public function shutdownProfiler() {
$data = xhprof_disable();
$data = json_encode($data);
Filesystem::writeFile($this->getArg('xprofile'), $data);
}
public static function isTraceModeEnabled() {
return self::$traceModeEnabled;
}
private function raiseUnknownWorkflow($flow, array $maybe) {
if ($maybe) {
sort($maybe);
$maybe_list = id(new PhutilConsoleList())
->setWrap(false)
->setBullet(null)
->addItems($maybe)
->drawConsoleString();
$message = tsprintf(
"%B\n%B",
pht(
'Invalid command "%s". Did you mean:',
$flow),
$maybe_list);
} else {
$names = mpull($this->workflows, 'getName');
sort($names);
$message = tsprintf(
'%B',
pht(
'Invalid command "%s". Valid commands are: %s.',
$flow,
implode(', ', $names)));
}
if (isset($this->workflows['help'])) {
$binary = basename($this->bin);
$message = tsprintf(
"%B\n%s",
$message,
pht(
'For details on available commands, run "%s".',
"{$binary} help"));
}
throw new PhutilArgumentUsageException($message);
}
private function shouldAutocorrect() {
return !phutil_is_noninteractive();
}
}
diff --git a/src/progress/PhutilConsoleProgressSink.php b/src/progress/PhutilConsoleProgressSink.php
index 11a61895..ca5dff88 100644
--- a/src/progress/PhutilConsoleProgressSink.php
+++ b/src/progress/PhutilConsoleProgressSink.php
@@ -1,115 +1,115 @@
<?php
final class PhutilConsoleProgressSink
extends PhutilProgressSink {
private $lastUpdate;
private $isTTY;
private $width;
private $lineWidth;
protected function publishProgress() {
if (!$this->shouldPublishToConsole()) {
return;
}
$completed = $this->getCompletedWork();
$total = $this->getTotalWork();
if ($total !== null) {
$percent = ($completed / $total);
$percent = min(1, $percent);
$percent = max(0, $percent);
} else {
$percent = null;
}
// TODO: In TTY mode, draw a nice ASCII progress bar.
if ($percent !== null) {
$marker = sprintf('% 3.1f%%', 100 * $percent);
} else {
$marker = sprintf('% 16d', $completed);
}
$message = pht('[%s] Working...', $marker);
if ($this->isTTY()) {
$this->overwriteLine($message);
} else {
$this->printLine($message."\n");
}
$this->didPublishToConsole();
}
protected function publishCompletion() {
$this->printLine("\n");
}
protected function publishFailure() {
$this->printLine("\n");
}
private function shouldPublishToConsole() {
if (!$this->lastUpdate) {
return true;
}
// Limit the number of times per second we actually write to the console.
if ($this->isTTY()) {
$writes_per_second = 5;
} else {
$writes_per_second = 0.5;
}
$now = microtime(true);
if (($now - $this->lastUpdate) < (1.0 / $writes_per_second)) {
return false;
}
return true;
}
private function didPublishToConsole() {
$this->lastUpdate = microtime(true);
}
private function isTTY() {
if ($this->isTTY === null) {
$this->isTTY = (function_exists('posix_isatty') && posix_isatty(STDERR));
}
return $this->isTTY;
}
private function getWidth() {
if ($this->width === null) {
$width = phutil_console_get_terminal_width();
$width = min(nonempty($width, 78), 78);
$this->width = $width;
}
return $this->width;
}
private function overwriteLine($line) {
$head = "\r";
$tail = '';
if ($this->lineWidth) {
$line_len = strlen($line);
if ($line_len < $this->lineWidth) {
$tail = str_repeat(' ', $this->lineWidth - $line_len);
}
$this->lineWidth = strlen($line);
}
$this->printLine($head.$line.$tail);
}
private function printLine($line) {
- fprintf(STDERR, '%s', $line);
+ PhutilSystem::writeStderr($line);
}
}
diff --git a/src/symbols/PhutilSymbolLoader.php b/src/symbols/PhutilSymbolLoader.php
index 32c7a042..a5851a5e 100644
--- a/src/symbols/PhutilSymbolLoader.php
+++ b/src/symbols/PhutilSymbolLoader.php
@@ -1,455 +1,456 @@
<?php
/**
* Query and load Phutil classes, interfaces and functions.
*
* `PhutilSymbolLoader` is a query object which selects symbols which satisfy
* certain criteria, and optionally loads them. For instance, to load all
* classes in a library:
*
* ```lang=php
* $symbols = id(new PhutilSymbolLoader())
* ->setType('class')
* ->setLibrary('example')
* ->selectAndLoadSymbols();
* ```
*
* When you execute the loading query, it returns a dictionary of matching
* symbols:
*
* ```lang=php
* array(
* 'class$Example' => array(
* 'type' => 'class',
* 'name' => 'Example',
* 'library' => 'libexample',
* 'where' => 'examples/example.php',
* ),
* // ... more ...
* );
* ```
*
* The **library** and **where** keys show where the symbol is defined. The
* **type** and **name** keys identify the symbol itself.
*
* NOTE: This class must not use libphutil functions, including @{function:id}
* and @{function:idx}.
*
* @task config Configuring the Query
* @task load Loading Symbols
* @task internal Internals
*/
final class PhutilSymbolLoader {
private $type;
private $library;
private $base;
private $name;
private $concrete;
private $pathPrefix;
private $suppressLoad;
private $continueOnFailure;
/**
* Select the type of symbol to load, either `class`, `function` or
* `interface`.
*
* @param string Type of symbol to load.
* @return this
*
* @task config
*/
public function setType($type) {
$this->type = $type;
return $this;
}
/**
* Restrict the symbol query to a specific library; only symbols from this
* library will be loaded.
*
* @param string Library name.
* @return this
*
* @task config
*/
public function setLibrary($library) {
// Validate the library name; this throws if the library in not loaded.
$bootloader = PhutilBootloader::getInstance();
$bootloader->getLibraryRoot($library);
$this->library = $library;
return $this;
}
/**
* Restrict the symbol query to a specific path prefix; only symbols defined
* in files below that path will be selected.
*
* @param string Path relative to library root, like "apps/cheese/".
* @return this
*
* @task config
*/
public function setPathPrefix($path) {
$this->pathPrefix = str_replace(DIRECTORY_SEPARATOR, '/', $path);
return $this;
}
/**
* Restrict the symbol query to a single symbol name, e.g. a specific class
* or function name.
*
* @param string Symbol name.
* @return this
*
* @task config
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Restrict the symbol query to only descendants of some class. This will
* strictly select descendants, the base class will not be selected. This
* implies loading only classes.
*
* @param string Base class name.
* @return this
*
* @task config
*/
public function setAncestorClass($base) {
$this->base = $base;
return $this;
}
/**
* Restrict the symbol query to only concrete symbols; this will filter out
* abstract classes.
*
* NOTE: This currently causes class symbols to load, even if you run
* @{method:selectSymbolsWithoutLoading}.
*
* @param bool True if the query should load only concrete symbols.
* @return this
*
* @task config
*/
public function setConcreteOnly($concrete) {
$this->concrete = $concrete;
return $this;
}
public function setContinueOnFailure($continue) {
$this->continueOnFailure = $continue;
return $this;
}
/* -( Load )--------------------------------------------------------------- */
/**
* Execute the query and select matching symbols, then load them so they can
* be used.
*
* @return dict A dictionary of matching symbols. See top-level class
* documentation for details. These symbols will be loaded
* and available.
*
* @task load
*/
public function selectAndLoadSymbols() {
$map = array();
$bootloader = PhutilBootloader::getInstance();
if ($this->library) {
$libraries = array($this->library);
} else {
$libraries = $bootloader->getAllLibraries();
}
if ($this->type) {
$types = array($this->type);
} else {
$types = array(
'class',
'function',
);
}
$names = null;
if ($this->base) {
$names = $this->selectDescendantsOf(
$bootloader->getClassTree(),
$this->base);
}
$symbols = array();
foreach ($libraries as $library) {
$map = $bootloader->getLibraryMap($library);
foreach ($types as $type) {
if ($type == 'interface') {
$lookup_map = $map['class'];
} else {
$lookup_map = $map[$type];
}
// As an optimization, we filter the list of candidate symbols in
// several passes, applying a name-based filter first if possible since
// it is highly selective and guaranteed to match at most one symbol.
// This is the common case and we land here through `__autoload()` so
// it's worthwhile to micro-optimize a bit because this code path is
// very hot and we save 5-10ms per page for a very moderate increase in
// complexity.
if ($this->name) {
// If we have a name filter, just pick the matching name out if it
// exists.
if (isset($lookup_map[$this->name])) {
$filtered_map = array(
$this->name => $lookup_map[$this->name],
);
} else {
$filtered_map = array();
}
} else if ($names !== null) {
$filtered_map = array();
foreach ($names as $name => $ignored) {
if (isset($lookup_map[$name])) {
$filtered_map[$name] = $lookup_map[$name];
}
}
} else {
// Otherwise, start with everything.
$filtered_map = $lookup_map;
}
if ($this->pathPrefix) {
$len = strlen($this->pathPrefix);
foreach ($filtered_map as $name => $where) {
if (strncmp($where, $this->pathPrefix, $len) !== 0) {
unset($filtered_map[$name]);
}
}
}
foreach ($filtered_map as $name => $where) {
$symbols[$type.'$'.$name] = array(
'type' => $type,
'name' => $name,
'library' => $library,
'where' => $where,
);
}
}
}
if (!$this->suppressLoad) {
// Loading a class may trigger the autoloader to load more classes
// (usually, the parent class), so we need to keep track of whether we
// are currently loading in "continue on failure" mode. Otherwise, we'll
// fail anyway if we fail to load a parent class.
// The driving use case for the "continue on failure" mode is to let
// "arc liberate" run so it can rebuild the library map, even if you have
// made changes to Workflow or Config classes which it must load before
// it can operate. If we don't let it continue on failure, it is very
// difficult to remove or move Workflows.
static $continue_depth = 0;
if ($this->continueOnFailure) {
$continue_depth++;
}
$caught = null;
foreach ($symbols as $key => $symbol) {
try {
$this->loadSymbol($symbol);
} catch (Exception $ex) {
// If we failed to load this symbol, remove it from the results.
// Otherwise, we may fatal below when trying to reflect it.
unset($symbols[$key]);
$caught = $ex;
}
}
$should_continue = ($continue_depth > 0);
if ($this->continueOnFailure) {
$continue_depth--;
}
if ($caught) {
// NOTE: We try to load everything even if we fail to load something,
// primarily to make it possible to remove functions from a libphutil
// library without breaking library startup.
if ($should_continue) {
// We may not have `pht()` yet.
- fprintf(
- STDERR,
+ $message = sprintf(
"%s: %s\n",
'IGNORING CLASS LOAD FAILURE',
$caught->getMessage());
+
+ @file_put_contents('php://stderr', $message);
} else {
throw $caught;
}
}
}
if ($this->concrete) {
// Remove 'abstract' classes.
foreach ($symbols as $key => $symbol) {
if ($symbol['type'] == 'class') {
$reflection = new ReflectionClass($symbol['name']);
if ($reflection->isAbstract()) {
unset($symbols[$key]);
}
}
}
}
return $symbols;
}
/**
* Execute the query and select matching symbols, but do not load them. This
* will perform slightly better if you are only interested in the existence
* of the symbols and don't plan to use them; otherwise, use
* @{method:selectAndLoadSymbols}.
*
* @return dict A dictionary of matching symbols. See top-level class
* documentation for details.
*
* @task load
*/
public function selectSymbolsWithoutLoading() {
$this->suppressLoad = true;
$result = $this->selectAndLoadSymbols();
$this->suppressLoad = false;
return $result;
}
/**
* Select symbols matching the query and then instantiate them, returning
* concrete objects. This is a convenience method which simplifies symbol
* handling if you are only interested in building objects.
*
* If you want to do more than build objects, or want to build objects with
* varying constructor arguments, use @{method:selectAndLoadSymbols} for
* fine-grained control over results.
*
* This method implicitly restricts the query to match only concrete
* classes.
*
* @param list<wild> List of constructor arguments.
* @return map<string, object> Map of class names to constructed objects.
*/
public function loadObjects(array $argv = array()) {
$symbols = $this
->setConcreteOnly(true)
->setType('class')
->selectAndLoadSymbols();
$objects = array();
foreach ($symbols as $symbol) {
$objects[$symbol['name']] = newv($symbol['name'], $argv);
}
return $objects;
}
/* -( Internals )---------------------------------------------------------- */
/**
* @task internal
*/
private function selectDescendantsOf(array $tree, $root) {
$result = array();
if (empty($tree[$root])) {
// No known descendants.
return array();
}
foreach ($tree[$root] as $child) {
$result[$child] = true;
if (!empty($tree[$child])) {
$result += $this->selectDescendantsOf($tree, $child);
}
}
return $result;
}
/**
* @task internal
*/
private function loadSymbol(array $symbol_spec) {
// Check if we've already loaded the symbol; bail if we have.
$name = $symbol_spec['name'];
$is_function = ($symbol_spec['type'] == 'function');
if ($is_function) {
if (function_exists($name)) {
return;
}
} else {
if (class_exists($name, false) || interface_exists($name, false)) {
return;
}
}
$lib_name = $symbol_spec['library'];
$where = $symbol_spec['where'];
$bootloader = PhutilBootloader::getInstance();
$bootloader->loadLibrarySource($lib_name, $where);
// Check that we successfully loaded the symbol from wherever it was
// supposed to be defined.
$load_failed = null;
if ($is_function) {
if (!function_exists($name)) {
$load_failed = pht('function');
}
} else {
if (!class_exists($name, false) && !interface_exists($name, false)) {
$load_failed = pht('class or interface');
}
}
if ($load_failed !== null) {
$lib_path = phutil_get_library_root($lib_name);
throw new PhutilMissingSymbolException(
$name,
$load_failed,
pht(
"The symbol map for library '%s' (at '%s') claims this %s is ".
"defined in '%s', but loading that source file did not cause the ".
"%s to become defined.",
$lib_name,
$lib_path,
$load_failed,
$where,
$load_failed));
}
}
}
diff --git a/src/upload/ArcanistFileUploader.php b/src/upload/ArcanistFileUploader.php
index cde462e7..2af3ae25 100644
--- a/src/upload/ArcanistFileUploader.php
+++ b/src/upload/ArcanistFileUploader.php
@@ -1,319 +1,319 @@
<?php
/**
* Upload a list of @{class:ArcanistFileDataRef} objects over Conduit.
*
* // Create a new uploader.
* $uploader = id(new ArcanistFileUploader())
* ->setConduitEngine($conduit);
*
* // Queue one or more files to be uploaded.
* $file = id(new ArcanistFileDataRef())
* ->setName('example.jpg')
* ->setPath('/path/to/example.jpg');
* $uploader->addFile($file);
*
* // Upload the files.
* $files = $uploader->uploadFiles();
*
* For details about building file references, see @{class:ArcanistFileDataRef}.
*
* @task config Configuring the Uploader
* @task add Adding Files
* @task upload Uploading Files
* @task internal Internals
*/
final class ArcanistFileUploader extends Phobject {
private $conduitEngine;
private $files = array();
/* -( Configuring the Uploader )------------------------------------------- */
public function setConduitEngine(ArcanistConduitEngine $engine) {
$this->conduitEngine = $engine;
return $this;
}
/* -( Adding Files )------------------------------------------------------- */
/**
* Add a file to the list of files to be uploaded.
*
* You can optionally provide an explicit key which will be used to identify
* the file. After adding files, upload them with @{method:uploadFiles}.
*
* @param ArcanistFileDataRef File data to upload.
* @param null|string Optional key to use to identify this file.
* @return this
* @task add
*/
public function addFile(ArcanistFileDataRef $file, $key = null) {
if ($key === null) {
$this->files[] = $file;
} else {
if (isset($this->files[$key])) {
throw new Exception(
pht(
'Two files were added with identical explicit keys ("%s"); each '.
'explicit key must be unique.',
$key));
}
$this->files[$key] = $file;
}
return $this;
}
/* -( Uploading Files )---------------------------------------------------- */
/**
* Upload files to the server.
*
* This transfers all files which have been queued with @{method:addFiles}
* over the Conduit link configured with @{method:setConduitEngine}.
*
* This method returns a map of all file data references. If references were
* added with an explicit key when @{method:addFile} was called, the key is
* retained in the result map.
*
* On return, files are either populated with a PHID (indicating a successful
* upload) or a list of errors. See @{class:ArcanistFileDataRef} for
* details.
*
* @return map<string, ArcanistFileDataRef> Files with results populated.
* @task upload
*/
public function uploadFiles() {
if (!$this->conduitEngine) {
throw new PhutilInvalidStateException('setConduitEngine');
}
$files = $this->files;
foreach ($files as $key => $file) {
try {
$file->willUpload();
} catch (Exception $ex) {
$file->didFail($ex->getMessage());
unset($files[$key]);
}
}
$conduit = $this->conduitEngine;
$futures = array();
foreach ($files as $key => $file) {
$params = $this->getUploadParameters($file) + array(
'contentLength' => $file->getByteSize(),
'contentHash' => $file->getContentHash(),
);
$delete_after = $file->getDeleteAfterEpoch();
if ($delete_after !== null) {
$params['deleteAfterEpoch'] = $delete_after;
}
$futures[$key] = $conduit->newFuture('file.allocate', $params);
}
$iterator = id(new FutureIterator($futures))->limit(4);
$chunks = array();
foreach ($iterator as $key => $future) {
try {
$result = $future->resolve();
} catch (Exception $ex) {
// The most likely cause for a failure here is that the server does
// not support `file.allocate`. In this case, we'll try the older
// upload method below.
continue;
}
$phid = $result['filePHID'];
$file = $files[$key];
// We don't need to upload any data. Figure out why not: this can either
// be because of an error (server can't accept the data) or because the
// server already has the data.
if (!$result['upload']) {
if (!$phid) {
$file->didFail(
pht(
'Unable to upload file: the server refused to accept file '.
'"%s". This usually means it is too large.',
$file->getName()));
} else {
// These server completed the upload by creating a reference to known
// file data. We don't need to transfer the actual data, and are all
// set.
$file->setPHID($phid);
}
unset($files[$key]);
continue;
}
// The server wants us to do an upload.
if ($phid) {
$chunks[$key] = array(
'file' => $file,
'phid' => $phid,
);
}
}
foreach ($chunks as $key => $chunk) {
$file = $chunk['file'];
$phid = $chunk['phid'];
try {
$this->uploadChunks($file, $phid);
$file->setPHID($phid);
} catch (Exception $ex) {
$file->didFail(
pht(
'Unable to upload file chunks: %s',
$ex->getMessage()));
}
unset($files[$key]);
}
foreach ($files as $key => $file) {
try {
$phid = $this->uploadData($file);
$file->setPHID($phid);
} catch (Exception $ex) {
$file->didFail(
pht(
'Unable to upload file data: %s',
$ex->getMessage()));
}
unset($files[$key]);
}
foreach ($this->files as $file) {
$file->didUpload();
}
return $this->files;
}
/* -( Internals )---------------------------------------------------------- */
/**
* Upload missing chunks of a large file by calling `file.uploadchunk` over
* Conduit.
*
* @task internal
*/
private function uploadChunks(ArcanistFileDataRef $file, $file_phid) {
$conduit = $this->conduitEngine;
$future = $conduit->newFuture(
'file.querychunks',
array(
'filePHID' => $file_phid,
));
$chunks = $future->resolve();
$remaining = array();
foreach ($chunks as $chunk) {
if (!$chunk['complete']) {
$remaining[] = $chunk;
}
}
$done = (count($chunks) - count($remaining));
if ($done) {
$this->writeStatus(
pht(
'Resuming upload (%s of %s chunks remain).',
phutil_count($remaining),
phutil_count($chunks)));
} else {
$this->writeStatus(
pht(
'Uploading chunks (%s chunks to upload).',
phutil_count($remaining)));
}
$progress = new PhutilConsoleProgressBar();
$progress->setTotal(count($chunks));
for ($ii = 0; $ii < $done; $ii++) {
$progress->update(1);
}
$progress->draw();
// TODO: We could do these in parallel to improve upload performance.
foreach ($remaining as $chunk) {
$data = $file->readBytes($chunk['byteStart'], $chunk['byteEnd']);
$future = $conduit->newFuture(
'file.uploadchunk',
array(
'filePHID' => $file_phid,
'byteStart' => $chunk['byteStart'],
'dataEncoding' => 'base64',
'data' => base64_encode($data),
));
$future->resolve();
$progress->update(1);
}
}
/**
* Upload an entire file by calling `file.upload` over Conduit.
*
* @task internal
*/
private function uploadData(ArcanistFileDataRef $file) {
$conduit = $this->conduitEngine;
$data = $file->readBytes(0, $file->getByteSize());
$future = $conduit->newFuture(
'file.upload',
$this->getUploadParameters($file) + array(
'data_base64' => base64_encode($data),
));
return $future->resolve();
}
/**
* Get common parameters for file uploads.
*/
private function getUploadParameters(ArcanistFileDataRef $file) {
$params = array(
'name' => $file->getName(),
);
$view_policy = $file->getViewPolicy();
if ($view_policy !== null) {
$params['viewPolicy'] = $view_policy;
}
return $params;
}
/**
* Write a status message.
*
* @task internal
*/
private function writeStatus($message) {
- fwrite(STDERR, $message."\n");
+ PhutilSystem::writeStderr($message."\n");
}
}
diff --git a/src/utils/PhutilSystem.php b/src/utils/PhutilSystem.php
index 6c6d5dcd..3657d8b0 100644
--- a/src/utils/PhutilSystem.php
+++ b/src/utils/PhutilSystem.php
@@ -1,164 +1,230 @@
<?php
/**
* Interact with the operating system.
*
+ * @task stdio Interacting with Standard I/O
* @task memory Interacting with System Memory
*/
final class PhutilSystem extends Phobject {
+ private static $stdin = false;
+ private static $stderr = false;
+ private static $stdout = false;
+
+ /**
+ * @task stdio
+ */
+ public static function getStdinHandle() {
+ if (self::$stdin === false) {
+ self::$stdin = self::newStdioHandle('php://stdin');
+ }
+
+ return self::$stdin;
+ }
+
+ /**
+ * @task stdio
+ */
+ public static function getStdoutHandle() {
+ if (self::$stdout === false) {
+ self::$stdout = self::newStdioHandle('php://stdout');
+ }
+
+ return self::$stdout;
+ }
+
+ /**
+ * @task stdio
+ */
+ public static function getStderrHandle() {
+ if (self::$stderr === false) {
+ self::$stderr = self::newStdioHandle('php://stderr');
+ }
+
+ return self::$stderr;
+ }
+
+ /**
+ * @task stdio
+ */
+ public static function writeStderr($message) {
+ $stderr = self::getStderrHandle();
+
+ if ($stderr === null) {
+ return;
+ }
+
+ $message = phutil_string_cast($message);
+ @fwrite($stderr, $message);
+ }
+
+
+ /**
+ * @task stdio
+ */
+ private static function newStdioHandle($ref) {
+ $ignored_mode = '';
+
+ $handle = @fopen($ref, $ignored_mode);
+ if ($handle === false) {
+ return null;
+ }
+
+ return $handle;
+ }
/**
* Get information about total and free memory on the system.
*
* Because "free memory" is a murky concept, the interpretation of the values
* returned from this method will vary from system to system and the numbers
* themselves may be only roughly accurate.
*
* @return map<string, wild> Dictionary of memory information.
* @task memory
*/
public static function getSystemMemoryInformation() {
$meminfo_path = '/proc/meminfo';
if (Filesystem::pathExists($meminfo_path)) {
$meminfo_data = Filesystem::readFile($meminfo_path);
return self::parseMemInfo($meminfo_data);
} else if (Filesystem::binaryExists('vm_stat')) {
list($vm_stat_stdout) = execx('vm_stat');
return self::parseVMStat($vm_stat_stdout);
} else {
throw new Exception(
pht(
'Unable to access %s or `%s` on this system to '.
'get system memory information.',
'/proc/meminfo',
'vm_stat'));
}
}
/**
* Parse the output of `/proc/meminfo`.
*
* See @{method:getSystemMemoryInformation}. This method is used to get memory
* information on Linux.
*
* @param string Raw `/proc/meminfo`.
* @return map<string, wild> Parsed memory information.
* @task memory
*/
public static function parseMemInfo($data) {
$data = phutil_split_lines($data);
$map = array();
foreach ($data as $line) {
list($key, $value) = explode(':', $line, 2);
$key = trim($key);
$value = trim($value);
$matches = null;
if (preg_match('/^(\d+) kB\z/', $value, $matches)) {
$value = (int)$matches[1] * 1024;
}
$map[$key] = $value;
}
$expect = array(
'MemTotal',
'MemFree',
'Buffers',
'Cached',
);
foreach ($expect as $key) {
if (!array_key_exists($key, $map)) {
throw new Exception(
pht(
'Expected to find "%s" in "%s" output, but did not.',
$key,
'/proc/meminfo'));
}
}
$total = $map['MemTotal'];
$free = $map['MemFree'] + $map['Buffers'] + $map['Cached'];
return array(
'total' => $total,
'free' => $free,
);
}
/**
* Parse the output of `vm_stat`.
*
* See @{method:getSystemMemoryInformation}. This method is used to get memory
* information on Mac OS X.
*
* @param string Raw `vm_stat` output.
* @return map<string, wild> Parsed memory information.
* @task memory
*/
public static function parseVMStat($data) {
$data = phutil_split_lines($data);
$page_size = null;
$map = array();
foreach ($data as $line) {
list($key, $value) = explode(':', $line, 2);
$key = trim($key);
$value = trim($value);
$matches = null;
if (preg_match('/page size of (\d+) bytes/', $value, $matches)) {
$page_size = (int)$matches[1];
continue;
}
$value = trim($value, '.');
$map[$key] = $value;
}
if (!$page_size) {
throw new Exception(
pht(
'Expected to find "%s" in `%s` output, but did not.',
'page size',
'vm_stat'));
}
$expect = array(
'Pages free',
'Pages active',
'Pages inactive',
'Pages wired down',
);
foreach ($expect as $key) {
if (!array_key_exists($key, $map)) {
throw new Exception(
pht(
'Expected to find "%s" in `%s` output, but did not.',
$key,
'vm_stat'));
}
}
// NOTE: This calculation probably isn't quite right. In particular,
// the numbers don't exactly add up, and "Pages inactive" includes a
// bunch of disk cache. So these numbers aren't totally reliable and they
// aren't directly comparable to the /proc/meminfo numbers.
$free = $map['Pages free'];
$active = $map['Pages active'];
$inactive = $map['Pages inactive'];
$wired = $map['Pages wired down'];
return array(
'total' => ($free + $active + $inactive + $wired) * $page_size,
'free' => ($free) * $page_size,
);
}
}
diff --git a/src/workflow/ArcanistDiffWorkflow.php b/src/workflow/ArcanistDiffWorkflow.php
index 36117994..5b8ff40c 100644
--- a/src/workflow/ArcanistDiffWorkflow.php
+++ b/src/workflow/ArcanistDiffWorkflow.php
@@ -1,2897 +1,2900 @@
<?php
/**
* Sends changes from your working copy to Differential for code review.
*
* @task lintunit Lint and Unit Tests
* @task message Commit and Update Messages
* @task diffspec Diff Specification
* @task diffprop Diff Properties
*/
final class ArcanistDiffWorkflow extends ArcanistWorkflow {
private $console;
private $hasWarnedExternals = false;
private $unresolvedLint;
private $testResults;
private $diffID;
private $revisionID;
private $diffPropertyFutures = array();
private $commitMessageFromRevision;
private $hitAutotargets;
private $revisionTransactions;
private $revisionIsDraft;
const STAGING_PUSHED = 'pushed';
const STAGING_USER_SKIP = 'user.skip';
const STAGING_DIFF_RAW = 'diff.raw';
const STAGING_REPOSITORY_UNKNOWN = 'repository.unknown';
const STAGING_REPOSITORY_UNAVAILABLE = 'repository.unavailable';
const STAGING_REPOSITORY_UNSUPPORTED = 'repository.unsupported';
const STAGING_REPOSITORY_UNCONFIGURED = 'repository.unconfigured';
const STAGING_CLIENT_UNSUPPORTED = 'client.unsupported';
public function getWorkflowName() {
return 'diff';
}
public function getCommandSynopses() {
return phutil_console_format(<<<EOTEXT
**diff** [__paths__] (svn)
**diff** [__commit__] (git, hg)
EOTEXT
);
}
public function getCommandHelp() {
return phutil_console_format(<<<EOTEXT
Supports: git, svn, hg
Generate a Differential diff or revision from local changes.
Under git and mercurial, you can specify a commit (like __HEAD^^^__
or __master__) and Differential will generate a diff against the
merge base of that commit and your current working directory parent.
Under svn, you can choose to include only some of the modified files
in the working copy in the diff by specifying their paths. If you
omit paths, all changes are included in the diff.
EOTEXT
);
}
public function requiresWorkingCopy() {
return !$this->isRawDiffSource();
}
public function requiresConduit() {
return true;
}
public function requiresAuthentication() {
return true;
}
public function requiresRepositoryAPI() {
if (!$this->isRawDiffSource()) {
return true;
}
return false;
}
public function getDiffID() {
return $this->diffID;
}
public function getArguments() {
$arguments = array(
'message' => array(
'short' => 'm',
'param' => 'message',
'help' => pht(
'When updating a revision, use the specified message instead of '.
'prompting.'),
),
'message-file' => array(
'short' => 'F',
'param' => 'file',
'paramtype' => 'file',
'help' => pht(
'When creating a revision, read revision information '.
'from this file.'),
),
'edit' => array(
'supports' => array(
'git',
'hg',
),
'nosupport' => array(
'svn' => pht('Edit revisions via the web interface when using SVN.'),
),
'help' => pht(
'When updating a revision under git, edit revision information '.
'before updating.'),
),
'raw' => array(
'help' => pht(
'Read diff from stdin, not from the working copy. This disables '.
'many features which depend on having access to the working copy.'),
'conflicts' => array(
'apply-patches' => pht('%s disables lint.', '--raw'),
'never-apply-patches' => pht('%s disables lint.', '--raw'),
'create' => pht(
'%s and %s both need stdin. Use %s.',
'--raw',
'--create',
'--raw-command'),
'edit' => pht(
'%s and %s both need stdin. Use %s.',
'--raw',
'--edit',
'--raw-command'),
'raw-command' => null,
),
),
'raw-command' => array(
'param' => 'command',
'help' => pht(
'Generate diff by executing a specified command, not from the '.
'working copy. This disables many features which depend on having '.
'access to the working copy.'),
'conflicts' => array(
'apply-patches' => pht('%s disables lint.', '--raw-command'),
'never-apply-patches' => pht('%s disables lint.', '--raw-command'),
),
),
'create' => array(
'help' => pht('Always create a new revision.'),
'conflicts' => array(
'edit' => pht(
'%s can not be used with %s.',
'--create',
'--edit'),
'only' => pht(
'%s can not be used with %s.',
'--create',
'--only'),
'update' => pht(
'%s can not be used with %s.',
'--create',
'--update'),
),
),
'update' => array(
'param' => 'revision_id',
'help' => pht('Always update a specific revision.'),
),
'draft' => array(
'help' => pht(
'Create a draft revision so you can look over your changes before '.
'involving anyone else. Other users will not be notified about the '.
'revision until you later use "Request Review" to publish it. You '.
'can still share the draft by giving someone the link.'),
'conflicts' => array(
'edit' => null,
'only' => null,
'update' => null,
),
),
'nounit' => array(
'help' => pht('Do not run unit tests.'),
),
'nolint' => array(
'help' => pht('Do not run lint.'),
'conflicts' => array(
'apply-patches' => pht('%s suppresses lint.', '--nolint'),
'never-apply-patches' => pht('%s suppresses lint.', '--nolint'),
),
),
'only' => array(
'help' => pht(
'Instead of creating or updating a revision, only create a diff, '.
'which you may later attach to a revision.'),
'conflicts' => array(
'edit' => pht('%s does affect revisions.', '--only'),
'message' => pht('%s does not update any revision.', '--only'),
),
),
'allow-untracked' => array(
'help' => pht('Skip checks for untracked files in the working copy.'),
),
'apply-patches' => array(
'help' => pht(
'Apply patches suggested by lint to the working copy without '.
'prompting.'),
'conflicts' => array(
'never-apply-patches' => true,
),
'passthru' => array(
'lint' => true,
),
),
'never-apply-patches' => array(
'help' => pht('Never apply patches suggested by lint.'),
'conflicts' => array(
'apply-patches' => true,
),
'passthru' => array(
'lint' => true,
),
),
'amend-all' => array(
'help' => pht(
'When linting git repositories, amend HEAD with all patches '.
'suggested by lint without prompting.'),
'passthru' => array(
'lint' => true,
),
),
'amend-autofixes' => array(
'help' => pht(
'When linting git repositories, amend HEAD with autofix '.
'patches suggested by lint without prompting.'),
'passthru' => array(
'lint' => true,
),
),
'add-all' => array(
'short' => 'a',
'help' => pht(
'Automatically add all unstaged and uncommitted '.
'files to the commit.'),
),
'json' => array(
'help' => pht(
'Emit machine-readable JSON. EXPERIMENTAL! Probably does not work!'),
),
'no-amend' => array(
'help' => pht(
'Never amend commits in the working copy with lint patches.'),
),
'uncommitted' => array(
'help' => pht('Suppress warning about uncommitted changes.'),
'supports' => array(
'hg',
),
),
'verbatim' => array(
'help' => pht(
'When creating a revision, try to use the working copy commit '.
'message verbatim, without prompting to edit it. When updating a '.
'revision, update some fields from the local commit message.'),
'supports' => array(
'hg',
'git',
),
'conflicts' => array(
'update' => true,
'only' => true,
'raw' => true,
'raw-command' => true,
'message-file' => true,
),
),
'reviewers' => array(
'param' => 'usernames',
'help' => pht('When creating a revision, add reviewers.'),
'conflicts' => array(
'only' => true,
'update' => true,
),
),
'cc' => array(
'param' => 'usernames',
'help' => pht('When creating a revision, add CCs.'),
'conflicts' => array(
'only' => true,
'update' => true,
),
),
'skip-binaries' => array(
'help' => pht('Do not upload binaries (like images).'),
),
'skip-staging' => array(
'help' => pht('Do not copy changes to the staging area.'),
),
'base' => array(
'param' => 'rules',
'help' => pht('Additional rules for determining base revision.'),
'nosupport' => array(
'svn' => pht('Subversion does not use base commits.'),
),
'supports' => array('git', 'hg'),
),
'coverage' => array(
'help' => pht('Always enable coverage information.'),
'conflicts' => array(
'no-coverage' => null,
),
'passthru' => array(
'unit' => true,
),
),
'no-coverage' => array(
'help' => pht('Always disable coverage information.'),
'passthru' => array(
'unit' => true,
),
),
'browse' => array(
'help' => pht(
'After creating a diff or revision, open it in a web browser.'),
),
'*' => 'paths',
'head' => array(
'param' => 'commit',
'help' => pht(
'Specify the end of the commit range. This disables many features '.
'which depend on having access to the working copy.'),
'supports' => array('git'),
'nosupport' => array(
'svn' => pht('Subversion does not support commit ranges.'),
'hg' => pht('Mercurial does not support %s yet.', '--head'),
),
),
);
return $arguments;
}
public function isRawDiffSource() {
return $this->getArgument('raw') || $this->getArgument('raw-command');
}
public function run() {
$this->console = PhutilConsole::getConsole();
$this->runRepositoryAPISetup();
$this->runDiffSetupBasics();
$commit_message = $this->buildCommitMessage();
$this->dispatchEvent(
ArcanistEventType::TYPE_DIFF_DIDBUILDMESSAGE,
array(
'message' => $commit_message,
));
if (!$this->shouldOnlyCreateDiff()) {
$revision = $this->buildRevisionFromCommitMessage($commit_message);
}
$data = $this->runLintUnit();
$lint_result = $data['lintResult'];
$this->unresolvedLint = $data['unresolvedLint'];
$unit_result = $data['unitResult'];
$this->testResults = $data['testResults'];
$changes = $this->generateChanges();
if (!$changes) {
throw new ArcanistUsageException(
pht('There are no changes to generate a diff from!'));
}
$diff_spec = array(
'changes' => mpull($changes, 'toDictionary'),
'lintStatus' => $this->getLintStatus($lint_result),
'unitStatus' => $this->getUnitStatus($unit_result),
) + $this->buildDiffSpecification();
$conduit = $this->getConduit();
$diff_info = $conduit->callMethodSynchronous(
'differential.creatediff',
$diff_spec);
$this->diffID = $diff_info['diffid'];
$event = $this->dispatchEvent(
ArcanistEventType::TYPE_DIFF_WASCREATED,
array(
'diffID' => $diff_info['diffid'],
'lintResult' => $lint_result,
'unitResult' => $unit_result,
));
$this->submitChangesToStagingArea($this->diffID);
$phid = idx($diff_info, 'phid');
if ($phid) {
$this->hitAutotargets = $this->updateAutotargets(
$phid,
$unit_result);
}
$this->updateLintDiffProperty();
$this->updateUnitDiffProperty();
$this->updateLocalDiffProperty();
$this->updateOntoDiffProperty();
$this->resolveDiffPropertyUpdates();
$output_json = $this->getArgument('json');
if ($this->shouldOnlyCreateDiff()) {
if (!$output_json) {
echo phutil_console_format(
"%s\n **%s** __%s__\n\n",
pht('Created a new Differential diff:'),
pht('Diff URI:'),
$diff_info['uri']);
} else {
$human = ob_get_clean();
echo json_encode(array(
'diffURI' => $diff_info['uri'],
'diffID' => $this->getDiffID(),
'human' => $human,
))."\n";
ob_start();
}
if ($this->shouldOpenCreatedObjectsInBrowser()) {
$this->openURIsInBrowser(array($diff_info['uri']));
}
} else {
$is_draft = $this->getArgument('draft');
$revision['diffid'] = $this->getDiffID();
if ($commit_message->getRevisionID()) {
if ($is_draft) {
// TODO: In at least some cases, we could raise this earlier in the
// workflow to save users some time before the workflow aborts.
if ($this->revisionIsDraft) {
$this->writeWarn(
pht('ALREADY A DRAFT'),
pht(
'You are updating a revision ("%s") with the "--draft" flag, '.
'but this revision is already a draft. You only need to '.
'provide the "--draft" flag when creating a revision. Draft '.
'revisions are not published until you explicitly request '.
'review from the web UI.',
$commit_message->getRevisionMonogram()));
} else {
throw new ArcanistUsageException(
pht(
'You are updating a revision ("%s") with the "--draft" flag, '.
'but this revision has already been published for review. '.
'You can not turn a revision back into a draft once it has '.
'been published.',
$commit_message->getRevisionMonogram()));
}
}
$result = $conduit->callMethodSynchronous(
'differential.updaterevision',
$revision);
foreach (array('edit-messages.json', 'update-messages.json') as $file) {
$messages = $this->readScratchJSONFile($file);
unset($messages[$revision['id']]);
$this->writeScratchJSONFile($file, $messages);
}
$result_uri = $result['uri'];
$result_id = $result['revisionid'];
echo pht('Updated an existing Differential revision:')."\n";
} else {
// NOTE: We're either using "differential.revision.edit" (preferred)
// if we can, or falling back to "differential.createrevision"
// (the older way) if not.
$xactions = $this->revisionTransactions;
if ($xactions) {
$xactions[] = array(
'type' => 'update',
'value' => $diff_info['phid'],
);
if ($is_draft) {
$xactions[] = array(
'type' => 'draft',
'value' => true,
);
}
$result = $conduit->callMethodSynchronous(
'differential.revision.edit',
array(
'transactions' => $xactions,
));
$result_id = idxv($result, array('object', 'id'));
if (!$result_id) {
throw new Exception(
pht(
'Expected a revision ID to be returned by '.
'"differential.revision.edit".'));
}
// TODO: This is hacky, but we don't currently receive a URI back
// from "differential.revision.edit".
$result_uri = id(new PhutilURI($this->getConduitURI()))
->setPath('/D'.$result_id);
} else {
if ($is_draft) {
throw new ArcanistUsageException(
pht(
'You have specified "--draft", but the software version '.
'on the server is too old to support draft revisions. Omit '.
'the flag or upgrade the server software.'));
}
$revision = $this->dispatchWillCreateRevisionEvent($revision);
$result = $conduit->callMethodSynchronous(
'differential.createrevision',
$revision);
$result_uri = $result['uri'];
$result_id = $result['revisionid'];
}
$revised_message = $conduit->callMethodSynchronous(
'differential.getcommitmessage',
array(
'revision_id' => $result_id,
));
if ($this->shouldAmend()) {
$repository_api = $this->getRepositoryAPI();
if ($repository_api->supportsAmend()) {
echo pht('Updating commit message...')."\n";
$repository_api->amendCommit($revised_message);
} else {
echo pht(
'Commit message was not amended. Amending commit message is '.
'only supported in git and hg (version 2.2 or newer)');
}
}
echo pht('Created a new Differential revision:')."\n";
}
$uri = $result_uri;
echo phutil_console_format(
" **%s** __%s__\n\n",
pht('Revision URI:'),
$uri);
if ($this->shouldOpenCreatedObjectsInBrowser()) {
$this->openURIsInBrowser(array($uri));
}
}
echo pht('Included changes:')."\n";
foreach ($changes as $change) {
echo ' '.$change->renderTextSummary()."\n";
}
if ($output_json) {
ob_get_clean();
}
$this->removeScratchFile('create-message');
return 0;
}
private function runRepositoryAPISetup() {
if (!$this->requiresRepositoryAPI()) {
return;
}
$repository_api = $this->getRepositoryAPI();
$repository_api->setBaseCommitArgumentRules(
$this->getArgument('base', ''));
if ($repository_api->supportsCommitRanges()) {
$this->parseBaseCommitArgument($this->getArgument('paths'));
}
$head_commit = $this->getArgument('head');
if ($head_commit !== null) {
$repository_api->setHeadCommit($head_commit);
}
}
private function runDiffSetupBasics() {
$output_json = $this->getArgument('json');
if ($output_json) {
// TODO: We should move this to a higher-level and put an indirection
// layer between echoing stuff and stdout.
ob_start();
}
if ($this->requiresWorkingCopy()) {
$repository_api = $this->getRepositoryAPI();
if ($this->getArgument('add-all')) {
$this->setCommitMode(self::COMMIT_ENABLE);
} else if ($this->getArgument('uncommitted')) {
$this->setCommitMode(self::COMMIT_DISABLE);
} else {
$this->setCommitMode(self::COMMIT_ALLOW);
}
if ($repository_api instanceof ArcanistSubversionAPI) {
$repository_api->limitStatusToPaths($this->getArgument('paths'));
}
if (!$this->getArgument('head')) {
$this->requireCleanWorkingCopy();
}
}
$this->dispatchEvent(
ArcanistEventType::TYPE_DIFF_DIDCOLLECTCHANGES,
array());
}
private function buildRevisionFromCommitMessage(
ArcanistDifferentialCommitMessage $message) {
$conduit = $this->getConduit();
$revision_id = $message->getRevisionID();
$revision = array(
'fields' => $message->getFields(),
);
$xactions = $message->getTransactions();
if ($revision_id) {
// With '--verbatim', pass the (possibly modified) local fields. This
// allows the user to edit some fields (like "title" and "summary")
// locally without '--edit' and have changes automatically synchronized.
// Without '--verbatim', we do not update the revision to reflect local
// commit message changes.
if ($this->getArgument('verbatim')) {
$use_fields = $message->getFields();
} else {
$use_fields = array();
}
$should_edit = $this->getArgument('edit');
$edit_messages = $this->readScratchJSONFile('edit-messages.json');
$remote_corpus = idx($edit_messages, $revision_id);
if (!$should_edit || !$remote_corpus || $use_fields) {
if ($this->commitMessageFromRevision) {
$remote_corpus = $this->commitMessageFromRevision;
} else {
$remote_corpus = $conduit->callMethodSynchronous(
'differential.getcommitmessage',
array(
'revision_id' => $revision_id,
'edit' => 'edit',
'fields' => $use_fields,
));
}
}
if ($should_edit) {
$edited = $this->newInteractiveEditor($remote_corpus)
->setName('differential-edit-revision-info')
->setTaskMessage(pht(
'Update the details for a revision, then save and exit.'))
->editInteractively();
if ($edited != $remote_corpus) {
$remote_corpus = $edited;
$edit_messages[$revision_id] = $remote_corpus;
$this->writeScratchJSONFile('edit-messages.json', $edit_messages);
}
}
if ($this->commitMessageFromRevision == $remote_corpus) {
$new_message = $message;
} else {
$remote_corpus = ArcanistCommentRemover::removeComments(
$remote_corpus);
$new_message = ArcanistDifferentialCommitMessage::newFromRawCorpus(
$remote_corpus);
$new_message->pullDataFromConduit($conduit);
}
$revision['fields'] = $new_message->getFields();
$xactions = $new_message->getTransactions();
$revision['id'] = $revision_id;
$this->revisionID = $revision_id;
$revision['message'] = $this->getArgument('message');
if ($revision['message'] === null) {
$update_messages = $this->readScratchJSONFile('update-messages.json');
$update_messages[$revision_id] = $this->getUpdateMessage(
$revision['fields'],
idx($update_messages, $revision_id));
$revision['message'] = ArcanistCommentRemover::removeComments(
$update_messages[$revision_id]);
if (!strlen(trim($revision['message']))) {
throw new ArcanistUserAbortException();
}
$this->writeScratchJSONFile('update-messages.json', $update_messages);
}
}
$this->revisionTransactions = $xactions;
return $revision;
}
protected function shouldOnlyCreateDiff() {
if ($this->getArgument('create')) {
return false;
}
if ($this->getArgument('update')) {
return false;
}
if ($this->isRawDiffSource()) {
return true;
}
return $this->getArgument('only');
}
private function generateAffectedPaths() {
if ($this->isRawDiffSource()) {
return array();
}
$repository_api = $this->getRepositoryAPI();
if ($repository_api instanceof ArcanistSubversionAPI) {
$file_list = new FileList($this->getArgument('paths', array()));
$paths = $repository_api->getSVNStatus($externals = true);
foreach ($paths as $path => $mask) {
if (!$file_list->contains($repository_api->getPath($path), true)) {
unset($paths[$path]);
}
}
$warn_externals = array();
foreach ($paths as $path => $mask) {
$any_mod = ($mask & ArcanistRepositoryAPI::FLAG_ADDED) ||
($mask & ArcanistRepositoryAPI::FLAG_MODIFIED) ||
($mask & ArcanistRepositoryAPI::FLAG_DELETED);
if ($mask & ArcanistRepositoryAPI::FLAG_EXTERNALS) {
unset($paths[$path]);
if ($any_mod) {
$warn_externals[] = $path;
}
}
}
if ($warn_externals && !$this->hasWarnedExternals) {
echo phutil_console_format(
"%s\n\n%s\n\n",
pht(
"The working copy includes changes to '%s' paths. These ".
"changes will not be included in the diff because SVN can not ".
"commit 'svn:externals' changes alongside normal changes.",
'svn:externals'),
pht(
"Modified '%s' files:",
'svn:externals'),
phutil_console_wrap(implode("\n", $warn_externals), 8));
$prompt = pht('Generate a diff (with just local changes) anyway?');
if (!phutil_console_confirm($prompt)) {
throw new ArcanistUserAbortException();
} else {
$this->hasWarnedExternals = true;
}
}
} else {
$paths = $repository_api->getWorkingCopyStatus();
}
foreach ($paths as $path => $mask) {
if ($mask & ArcanistRepositoryAPI::FLAG_UNTRACKED) {
unset($paths[$path]);
}
}
return $paths;
}
protected function generateChanges() {
$parser = $this->newDiffParser();
$is_raw = $this->isRawDiffSource();
if ($is_raw) {
if ($this->getArgument('raw')) {
- fwrite(STDERR, pht('Reading diff from stdin...')."\n");
+ PhutilSystem::writeStderr(
+ tsprintf(
+ "%s\n",
+ pht('Reading diff from stdin...')));
$raw_diff = file_get_contents('php://stdin');
} else if ($this->getArgument('raw-command')) {
list($raw_diff) = execx('%C', $this->getArgument('raw-command'));
} else {
throw new Exception(pht('Unknown raw diff source.'));
}
$changes = $parser->parseDiff($raw_diff);
foreach ($changes as $key => $change) {
// Remove "message" changes, e.g. from "git show".
if ($change->getType() == ArcanistDiffChangeType::TYPE_MESSAGE) {
unset($changes[$key]);
}
}
return $changes;
}
$repository_api = $this->getRepositoryAPI();
if ($repository_api instanceof ArcanistSubversionAPI) {
$paths = $this->generateAffectedPaths();
$this->primeSubversionWorkingCopyData($paths);
// Check to make sure the user is diffing from a consistent base revision.
// This is mostly just an abuse sanity check because it's silly to do this
// and makes the code more difficult to effectively review, but it also
// affects patches and makes them nonportable.
$bases = $repository_api->getSVNBaseRevisions();
// Remove all files with baserev "0"; these files are new.
foreach ($bases as $path => $baserev) {
if ($bases[$path] <= 0) {
unset($bases[$path]);
}
}
if ($bases) {
$rev = reset($bases);
$revlist = array();
foreach ($bases as $path => $baserev) {
$revlist[] = ' '.pht('Revision %s, %s', $baserev, $path);
}
$revlist = implode("\n", $revlist);
foreach ($bases as $path => $baserev) {
if ($baserev !== $rev) {
throw new ArcanistUsageException(
pht(
"Base revisions of changed paths are mismatched. Update all ".
"paths to the same base revision before creating a diff: ".
"\n\n%s",
$revlist));
}
}
// If you have a change which affects several files, all of which are
// at a consistent base revision, treat that revision as the effective
// base revision. The use case here is that you made a change to some
// file, which updates it to HEAD, but want to be able to change it
// again without updating the entire working copy. This is a little
// sketchy but it arises in Facebook Ops workflows with config files and
// doesn't have any real material tradeoffs (e.g., these patches are
// perfectly applyable).
$repository_api->overrideSVNBaseRevisionNumber($rev);
}
$changes = $parser->parseSubversionDiff(
$repository_api,
$paths);
} else if ($repository_api instanceof ArcanistGitAPI) {
$diff = $repository_api->getFullGitDiff(
$repository_api->getBaseCommit(),
$repository_api->getHeadCommit());
if (!strlen($diff)) {
throw new ArcanistUsageException(
pht('No changes found. (Did you specify the wrong commit range?)'));
}
$changes = $parser->parseDiff($diff);
} else if ($repository_api instanceof ArcanistMercurialAPI) {
$diff = $repository_api->getFullMercurialDiff();
if (!strlen($diff)) {
throw new ArcanistUsageException(
pht('No changes found. (Did you specify the wrong commit range?)'));
}
$changes = $parser->parseDiff($diff);
} else {
throw new Exception(pht('Repository API is not supported.'));
}
$limit = 1024 * 1024 * 4;
foreach ($changes as $change) {
$size = 0;
foreach ($change->getHunks() as $hunk) {
$size += strlen($hunk->getCorpus());
}
if ($size > $limit) {
$byte_warning = pht(
"Diff for '%s' with context is %s bytes in length. ".
"Generally, source changes should not be this large.",
$change->getCurrentPath(),
new PhutilNumber($size));
if ($repository_api instanceof ArcanistSubversionAPI) {
throw new ArcanistUsageException(
$byte_warning.' '.
pht(
"If the file is not a text file, mark it as binary with:".
"\n\n $ %s\n",
'svn propset svn:mime-type application/octet-stream <filename>'));
} else {
$confirm = $byte_warning.' '.pht(
"If the file is not a text file, you can mark it 'binary'. ".
"Mark this file as 'binary' and continue?");
if (phutil_console_confirm($confirm)) {
$change->convertToBinaryChange($repository_api);
} else {
throw new ArcanistUsageException(
pht('Aborted generation of gigantic diff.'));
}
}
}
}
$utf8_problems = array();
foreach ($changes as $change) {
foreach ($change->getHunks() as $hunk) {
$corpus = $hunk->getCorpus();
if (!phutil_is_utf8($corpus)) {
// If this corpus is heuristically binary, don't try to convert it.
// mb_check_encoding() and mb_convert_encoding() are both very very
// liberal about what they're willing to process.
$is_binary = ArcanistDiffUtils::isHeuristicBinaryFile($corpus);
if (!$is_binary) {
try {
$try_encoding = $this->getRepositoryEncoding();
} catch (ConduitClientException $e) {
if ($e->getErrorCode() == 'ERR-BAD-ARCANIST-PROJECT') {
echo phutil_console_wrap(
pht('Lookup of encoding in project failed: %s',
$e->getMessage())."\n");
} else {
throw $e;
}
}
if ($try_encoding) {
$corpus = phutil_utf8_convert($corpus, 'UTF-8', $try_encoding);
$name = $change->getCurrentPath();
if (phutil_is_utf8($corpus)) {
$this->writeStatusMessage(
pht(
"Converted a '%s' hunk from '%s' to UTF-8.\n",
$name,
$try_encoding));
$hunk->setCorpus($corpus);
continue;
}
}
}
$utf8_problems[] = $change;
break;
}
}
}
// If there are non-binary files which aren't valid UTF-8, warn the user
// and treat them as binary changes. See D327 for discussion of why Arcanist
// has this behavior.
if ($utf8_problems) {
$utf8_warning =
sprintf(
"%s\n\n%s\n\n %s\n",
pht(
'This diff includes %s file(s) which are not valid UTF-8 (they '.
'contain invalid byte sequences). You can either stop this '.
'workflow and fix these files, or continue. If you continue, '.
'these files will be marked as binary.',
phutil_count($utf8_problems)),
pht(
"You can learn more about how this software handles character ".
"encodings (and how to configure encoding settings and detect and ".
"correct encoding problems) by reading 'User Guide: UTF-8 and ".
"Character Encoding' in the documentation."),
pht(
'%s AFFECTED FILE(S)',
phutil_count($utf8_problems)));
$confirm = pht(
'Do you want to mark these %s file(s) as binary and continue?',
phutil_count($utf8_problems));
echo phutil_console_format(
"**%s**\n",
pht('Invalid Content Encoding (Non-UTF8)'));
echo phutil_console_wrap($utf8_warning);
$file_list = mpull($utf8_problems, 'getCurrentPath');
$file_list = ' '.implode("\n ", $file_list);
echo $file_list;
if (!phutil_console_confirm($confirm, $default_no = false)) {
throw new ArcanistUsageException(pht('Aborted workflow to fix UTF-8.'));
} else {
foreach ($utf8_problems as $change) {
$change->convertToBinaryChange($repository_api);
}
}
}
$this->uploadFilesForChanges($changes);
return $changes;
}
private function getGitParentLogInfo() {
$info = array(
'parent' => null,
'base_revision' => null,
'base_path' => null,
'uuid' => null,
);
$repository_api = $this->getRepositoryAPI();
$parser = $this->newDiffParser();
$history_messages = $repository_api->getGitHistoryLog();
if (!$history_messages) {
// This can occur on the initial commit.
return $info;
}
$history_messages = $parser->parseDiff($history_messages);
foreach ($history_messages as $key => $change) {
try {
$message = ArcanistDifferentialCommitMessage::newFromRawCorpus(
$change->getMetadata('message'));
if ($message->getRevisionID() && $info['parent'] === null) {
$info['parent'] = $message->getRevisionID();
}
if ($message->getGitSVNBaseRevision() &&
$info['base_revision'] === null) {
$info['base_revision'] = $message->getGitSVNBaseRevision();
$info['base_path'] = $message->getGitSVNBasePath();
}
if ($message->getGitSVNUUID()) {
$info['uuid'] = $message->getGitSVNUUID();
}
if ($info['parent'] && $info['base_revision']) {
break;
}
} catch (ArcanistDifferentialCommitMessageParserException $ex) {
// Ignore.
} catch (ArcanistUsageException $ex) {
// Ignore an invalid Differential Revision field in the parent commit
}
}
return $info;
}
protected function primeSubversionWorkingCopyData($paths) {
$repository_api = $this->getRepositoryAPI();
$futures = array();
$targets = array();
foreach ($paths as $path => $mask) {
$futures[] = $repository_api->buildDiffFuture($path);
$targets[] = array('command' => 'diff', 'path' => $path);
$futures[] = $repository_api->buildInfoFuture($path);
$targets[] = array('command' => 'info', 'path' => $path);
}
$futures = id(new FutureIterator($futures))
->limit(8);
foreach ($futures as $key => $future) {
$target = $targets[$key];
if ($target['command'] == 'diff') {
$repository_api->primeSVNDiffResult(
$target['path'],
$future->resolve());
} else {
$repository_api->primeSVNInfoResult(
$target['path'],
$future->resolve());
}
}
}
private function shouldAmend() {
if ($this->isRawDiffSource()) {
return false;
}
if ($this->getArgument('no-amend')) {
return false;
}
if ($this->getArgument('head') !== null) {
return false;
}
// Run this last: with --raw or --raw-command, we won't have a repository
// API.
if ($this->isHistoryImmutable()) {
return false;
}
return true;
}
/* -( Lint and Unit Tests )------------------------------------------------ */
/**
* @task lintunit
*/
private function runLintUnit() {
$lint_result = $this->runLint();
$unit_result = $this->runUnit();
return array(
'lintResult' => $lint_result,
'unresolvedLint' => $this->unresolvedLint,
'unitResult' => $unit_result,
'testResults' => $this->testResults,
);
}
/**
* @task lintunit
*/
private function runLint() {
if ($this->getArgument('nolint') ||
$this->isRawDiffSource() ||
$this->getArgument('head')) {
return ArcanistLintWorkflow::RESULT_SKIP;
}
$repository_api = $this->getRepositoryAPI();
$this->console->writeOut("%s\n", pht('Linting...'));
try {
$argv = $this->getPassthruArgumentsAsArgv('lint');
if ($repository_api->supportsCommitRanges()) {
$argv[] = '--rev';
$argv[] = $repository_api->getBaseCommit();
}
$lint_workflow = $this->buildChildWorkflow('lint', $argv);
if ($this->shouldAmend()) {
// TODO: We should offer to create a checkpoint commit.
$lint_workflow->setShouldAmendChanges(true);
}
$lint_result = $lint_workflow->run();
switch ($lint_result) {
case ArcanistLintWorkflow::RESULT_OKAY:
$this->console->writeOut(
"<bg:green>** %s **</bg> %s\n",
pht('LINT OKAY'),
pht('No lint problems.'));
break;
case ArcanistLintWorkflow::RESULT_WARNINGS:
$this->console->writeOut(
"<bg:yellow>** %s **</bg> %s\n",
pht('LINT MESSAGES'),
pht('Lint issued unresolved warnings.'));
break;
case ArcanistLintWorkflow::RESULT_ERRORS:
$this->console->writeOut(
"<bg:red>** %s **</bg> %s\n",
pht('LINT ERRORS'),
pht('Lint raised errors!'));
break;
}
$this->unresolvedLint = array();
foreach ($lint_workflow->getUnresolvedMessages() as $message) {
$this->unresolvedLint[] = $message->toDictionary();
}
return $lint_result;
} catch (ArcanistNoEngineException $ex) {
$this->console->writeOut(
"%s\n",
pht('No lint engine configured for this project.'));
} catch (ArcanistNoEffectException $ex) {
$this->console->writeOut("%s\n", $ex->getMessage());
}
return null;
}
/**
* @task lintunit
*/
private function runUnit() {
if ($this->getArgument('nounit') ||
$this->isRawDiffSource() ||
$this->getArgument('head')) {
return ArcanistUnitWorkflow::RESULT_SKIP;
}
$repository_api = $this->getRepositoryAPI();
$this->console->writeOut("%s\n", pht('Running unit tests...'));
try {
$argv = $this->getPassthruArgumentsAsArgv('unit');
if ($repository_api->supportsCommitRanges()) {
$argv[] = '--rev';
$argv[] = $repository_api->getBaseCommit();
}
$unit_workflow = $this->buildChildWorkflow('unit', $argv);
$unit_result = $unit_workflow->run();
switch ($unit_result) {
case ArcanistUnitWorkflow::RESULT_OKAY:
$this->console->writeOut(
"<bg:green>** %s **</bg> %s\n",
pht('UNIT OKAY'),
pht('No unit test failures.'));
break;
case ArcanistUnitWorkflow::RESULT_UNSOUND:
$continue = phutil_console_confirm(
pht(
'Unit test results included failures, but all failing tests '.
'are known to be unsound. Ignore unsound test failures?'));
if (!$continue) {
throw new ArcanistUserAbortException();
}
echo phutil_console_format(
"<bg:yellow>** %s **</bg> %s\n",
pht('UNIT UNSOUND'),
pht(
'Unit testing raised errors, but all '.
'failing tests are unsound.'));
break;
case ArcanistUnitWorkflow::RESULT_FAIL:
$this->console->writeOut(
"<bg:red>** %s **</bg> %s\n",
pht('UNIT ERRORS'),
pht('Unit testing raised errors!'));
break;
}
$this->testResults = array();
foreach ($unit_workflow->getTestResults() as $test) {
$this->testResults[] = $test->toDictionary();
}
return $unit_result;
} catch (ArcanistNoEngineException $ex) {
$this->console->writeOut(
"%s\n",
pht('No unit test engine is configured for this project.'));
} catch (ArcanistNoEffectException $ex) {
$this->console->writeOut("%s\n", $ex->getMessage());
}
return null;
}
public function getTestResults() {
return $this->testResults;
}
/* -( Commit and Update Messages )----------------------------------------- */
/**
* @task message
*/
private function buildCommitMessage() {
if ($this->getArgument('only')) {
return null;
}
$is_create = $this->getArgument('create');
$is_update = $this->getArgument('update');
$is_raw = $this->isRawDiffSource();
$is_verbatim = $this->getArgument('verbatim');
if ($is_verbatim) {
return $this->getCommitMessageFromUser();
}
if (!$is_raw && !$is_create && !$is_update) {
$repository_api = $this->getRepositoryAPI();
$revisions = $repository_api->loadWorkingCopyDifferentialRevisions(
$this->getConduit(),
array(
'authors' => array($this->getUserPHID()),
'status' => 'status-open',
));
if (!$revisions) {
$is_create = true;
} else if (count($revisions) == 1) {
$revision = head($revisions);
$is_update = $revision['id'];
} else {
throw new ArcanistUsageException(
pht(
"There are several revisions which match the working copy:\n\n%s\n".
"Use '%s' to choose one, or '%s' to create a new revision.",
$this->renderRevisionList($revisions),
'--update',
'--create'));
}
}
$message = null;
if ($is_create) {
$message_file = $this->getArgument('message-file');
if ($message_file) {
return $this->getCommitMessageFromFile($message_file);
} else {
return $this->getCommitMessageFromUser();
}
} else if ($is_update) {
$revision_id = $this->normalizeRevisionID($is_update);
if (!is_numeric($revision_id)) {
throw new ArcanistUsageException(
pht(
'Parameter to %s must be a Differential Revision number.',
'--update'));
}
return $this->getCommitMessageFromRevision($revision_id);
} else {
// This is --raw without enough info to create a revision, so force just
// a diff.
return null;
}
}
/**
* @task message
*/
private function getCommitMessageFromUser() {
$conduit = $this->getConduit();
$template = null;
if (!$this->getArgument('verbatim')) {
$saved = $this->readScratchFile('create-message');
if ($saved) {
$where = $this->getReadableScratchFilePath('create-message');
$preview = explode("\n", $saved);
$preview = array_shift($preview);
$preview = trim($preview);
$preview = id(new PhutilUTF8StringTruncator())
->setMaximumGlyphs(64)
->truncateString($preview);
if ($preview) {
$preview = pht('Message begins:')."\n\n {$preview}\n\n";
} else {
$preview = null;
}
echo pht(
"You have a saved revision message in '%s'.\n%s".
"You can use this message, or discard it.",
$where,
$preview);
$use = phutil_console_confirm(
pht('Do you want to use this message?'),
$default_no = false);
if ($use) {
$template = $saved;
} else {
$this->removeScratchFile('create-message');
}
}
}
$template_is_default = false;
$notes = array();
$included = array();
list($fields, $notes, $included_commits) = $this->getDefaultCreateFields();
if ($template) {
$fields = array();
$notes = array();
} else {
if (!$fields) {
$template_is_default = true;
}
if ($notes) {
$commit = head($this->getRepositoryAPI()->getLocalCommitInformation());
$template = $commit['message'];
} else {
$template = $conduit->callMethodSynchronous(
'differential.getcommitmessage',
array(
'revision_id' => null,
'edit' => 'create',
'fields' => $fields,
));
}
}
$old_message = $template;
$included = array();
if ($included_commits) {
foreach ($included_commits as $commit) {
$included[] = ' '.$commit;
}
if (!$this->isRawDiffSource()) {
$message = pht(
'Included commits in branch %s:',
$this->getRepositoryAPI()->getBranchName());
} else {
$message = pht('Included commits:');
}
$included = array_merge(
array(
'',
$message,
'',
),
$included);
}
$issues = array_merge(
array(
pht('NEW DIFFERENTIAL REVISION'),
pht('Describe the changes in this new revision.'),
),
$included,
array(
'',
pht(
'arc could not identify any existing revision in your working copy.'),
pht('If you intended to update an existing revision, use:'),
'',
' $ arc diff --update <revision>',
));
if ($notes) {
$issues = array_merge($issues, array(''), $notes);
}
$done = false;
$first = true;
while (!$done) {
$template = rtrim($template, "\r\n")."\n\n";
foreach ($issues as $issue) {
$template .= rtrim('# '.$issue)."\n";
}
$template .= "\n";
if ($first && $this->getArgument('verbatim') && !$template_is_default) {
$new_template = $template;
} else {
$new_template = $this->newInteractiveEditor($template)
->setName('new-commit')
->setTaskMessage(pht(
'Provide the details for a new revision, then save and exit.'))
->editInteractively();
}
$first = false;
if ($template_is_default && ($new_template == $template)) {
throw new ArcanistUsageException(pht('Template not edited.'));
}
$template = ArcanistCommentRemover::removeComments($new_template);
// With --raw-command, we may not have a repository API.
if ($this->hasRepositoryAPI()) {
$repository_api = $this->getRepositoryAPI();
// special check for whether to amend here. optimizes a common git
// workflow. we can't do this for mercurial because the mq extension
// is popular and incompatible with hg commit --amend ; see T2011.
$should_amend = (count($included_commits) == 1 &&
$repository_api instanceof ArcanistGitAPI &&
$this->shouldAmend());
} else {
$should_amend = false;
}
if ($should_amend) {
$wrote = (rtrim($old_message) != rtrim($template));
if ($wrote) {
$repository_api->amendCommit($template);
$where = pht('commit message');
}
} else {
$wrote = $this->writeScratchFile('create-message', $template);
$where = "'".$this->getReadableScratchFilePath('create-message')."'";
}
try {
$message = ArcanistDifferentialCommitMessage::newFromRawCorpus(
$template);
$message->pullDataFromConduit($conduit);
$this->validateCommitMessage($message);
$done = true;
} catch (ArcanistDifferentialCommitMessageParserException $ex) {
echo pht('Commit message has errors:')."\n\n";
$issues = array(pht('Resolve these errors:'));
foreach ($ex->getParserErrors() as $error) {
echo phutil_console_wrap("- ".$error."\n", 6);
$issues[] = ' - '.$error;
}
echo "\n";
echo pht('You must resolve these errors to continue.');
$again = phutil_console_confirm(
pht('Do you want to edit the message?'),
$default_no = false);
if ($again) {
// Keep going.
} else {
$saved = null;
if ($wrote) {
$saved = pht('A copy was saved to %s.', $where);
}
throw new ArcanistUsageException(
pht('Message has unresolved errors.')." {$saved}");
}
} catch (Exception $ex) {
if ($wrote) {
echo phutil_console_wrap(pht('(Message saved to %s.)', $where)."\n");
}
throw $ex;
}
}
return $message;
}
/**
* @task message
*/
private function getCommitMessageFromFile($file) {
$conduit = $this->getConduit();
$data = Filesystem::readFile($file);
$message = ArcanistDifferentialCommitMessage::newFromRawCorpus($data);
$message->pullDataFromConduit($conduit);
$this->validateCommitMessage($message);
return $message;
}
/**
* @task message
*/
private function getCommitMessageFromRevision($revision_id) {
$id = $revision_id;
$revision = $this->getConduit()->callMethodSynchronous(
'differential.query',
array(
'ids' => array($id),
));
$revision = head($revision);
if (!$revision) {
throw new ArcanistUsageException(
pht(
"Revision '%s' does not exist!",
$revision_id));
}
$this->checkRevisionOwnership($revision);
// TODO: Save this status to improve a prompt later. See PHI458. This is
// extra awful until we move to "differential.revision.search" because
// the "differential.query" method doesn't return a real draft status for
// compatibility.
$this->revisionIsDraft = (idx($revision, 'statusName') === 'Draft');
$message = $this->getConduit()->callMethodSynchronous(
'differential.getcommitmessage',
array(
'revision_id' => $id,
'edit' => false,
));
$this->commitMessageFromRevision = $message;
$obj = ArcanistDifferentialCommitMessage::newFromRawCorpus($message);
$obj->pullDataFromConduit($this->getConduit());
return $obj;
}
/**
* @task message
*/
private function validateCommitMessage(
ArcanistDifferentialCommitMessage $message) {
$futures = array();
$revision_id = $message->getRevisionID();
if ($revision_id) {
$futures['revision'] = $this->getConduit()->callMethod(
'differential.query',
array(
'ids' => array($revision_id),
));
}
$reviewers = $message->getFieldValue('reviewerPHIDs');
if ($reviewers) {
$futures['reviewers'] = $this->getConduit()->callMethod(
'user.query',
array(
'phids' => $reviewers,
));
}
foreach (new FutureIterator($futures) as $key => $future) {
$result = $future->resolve();
switch ($key) {
case 'revision':
if (empty($result)) {
throw new ArcanistUsageException(
pht(
'There is no revision %s.',
"D{$revision_id}"));
}
$this->checkRevisionOwnership(head($result));
break;
case 'reviewers':
$away = array();
foreach ($result as $user) {
if (idx($user, 'currentStatus') != 'away') {
continue;
}
$username = $user['userName'];
$real_name = $user['realName'];
if (strlen($real_name)) {
$name = pht('%s (%s)', $username, $real_name);
} else {
$name = pht('%s', $username);
}
$away[] = array(
'name' => $name,
'until' => $user['currentStatusUntil'],
);
}
if ($away) {
if (count($away) == count($reviewers)) {
$earliest_return = min(ipull($away, 'until'));
$message = pht(
'All reviewers are away until %s:',
date('l, M j Y', $earliest_return));
} else {
$message = pht('Some reviewers are currently away:');
}
echo tsprintf(
"%s\n\n",
$message);
$list = id(new PhutilConsoleList());
foreach ($away as $spec) {
$list->addItem(
pht(
'%s (until %s)',
$spec['name'],
date('l, M j Y', $spec['until'])));
}
echo tsprintf(
'%B',
$list->drawConsoleString());
$confirm = pht('Continue even though reviewers are unavailable?');
if (!phutil_console_confirm($confirm)) {
throw new ArcanistUsageException(
pht('Specify available reviewers and retry.'));
}
}
break;
}
}
}
/**
* @task message
*/
private function getUpdateMessage(array $fields, $template = '') {
if ($this->getArgument('raw')) {
throw new ArcanistUsageException(
pht(
"When using '%s' to update a revision, specify an update message ".
"with '%s'. (Normally, we'd launch an editor to ask you for a ".
"message, but can not do that because stdin is the diff source.)",
'--raw',
'--message'));
}
// When updating a revision using git without specifying '--message', try
// to prefill with the message in HEAD if it isn't a template message. The
// idea is that if you do:
//
// $ git commit -a -m 'fix some junk'
// $ arc diff
//
// ...you shouldn't have to retype the update message. Similar things apply
// to Mercurial.
if ($template == '') {
$comments = $this->getDefaultUpdateMessage();
$comments = phutil_string_cast($comments);
$comments = rtrim($comments);
$template = sprintf(
"%s\n\n# %s\n#\n# %s\n# %s\n#\n# %s\n# $ %s\n\n",
$comments,
pht(
'Updating %s: %s',
"D{$fields['revisionID']}",
$fields['title']),
pht(
'Enter a brief description of the changes included in this update.'),
pht('The first line is used as subject, next lines as comment.'),
pht('If you intended to create a new revision, use:'),
'arc diff --create');
}
$comments = $this->newInteractiveEditor($template)
->setName('differential-update-comments')
->setTaskMessage(pht(
'Update the revision comments, then save and exit.'))
->editInteractively();
return $comments;
}
private function getDefaultCreateFields() {
$result = array(array(), array(), array());
if ($this->isRawDiffSource()) {
return $result;
}
$repository_api = $this->getRepositoryAPI();
$local = $repository_api->getLocalCommitInformation();
if ($local) {
$result = $this->parseCommitMessagesIntoFields($local);
if ($this->getArgument('create')) {
unset($result[0]['revisionID']);
}
}
$result[0] = $this->dispatchWillBuildEvent($result[0]);
return $result;
}
/**
* Convert a list of commits from `getLocalCommitInformation()` into
* a format usable by arc to create a new diff. Specifically, we emit:
*
* - A dictionary of commit message fields.
* - A list of errors encountered while parsing the messages.
* - A human-readable list of the commits themselves.
*
* For example, if the user runs "arc diff HEAD^^^" and selects a diff range
* which includes several diffs, we attempt to merge them somewhat
* intelligently into a single message, because we can only send one
* "Summary:", "Reviewers:", etc., field to Differential. We also return
* errors (e.g., if the user typed a reviewer name incorrectly) and a
* summary of the commits themselves.
*
* @param dict Local commit information.
* @return list Complex output, see summary.
* @task message
*/
private function parseCommitMessagesIntoFields(array $local) {
$conduit = $this->getConduit();
$local = ipull($local, null, 'commit');
// If the user provided "--reviewers" or "--ccs", add a faux message to
// the list with the implied fields.
$faux_message = array();
if ($this->getArgument('reviewers')) {
$faux_message[] = pht('Reviewers: %s', $this->getArgument('reviewers'));
}
if ($this->getArgument('cc')) {
$faux_message[] = pht('CC: %s', $this->getArgument('cc'));
}
// NOTE: For now, this isn't a real field, so it just ends up as the first
// part of the summary.
$depends_ref = $this->getDependsOnRevisionRef();
if ($depends_ref) {
$faux_message[] = pht(
'Depends on %s. ',
$depends_ref->getMonogram());
}
// See T12069. After T10312, the first line of a message is always parsed
// as a title. Add a placeholder so "Reviewers" and "CC" are never the
// first line.
$placeholder_title = pht('<placeholder>');
if ($faux_message) {
array_unshift($faux_message, $placeholder_title);
$faux_message = implode("\n\n", $faux_message);
$local = array(
'(Flags) ' => array(
'message' => $faux_message,
'summary' => pht('Command-Line Flags'),
),
) + $local;
}
// Build a human-readable list of the commits, so we can show the user which
// commits are included in the diff.
$included = array();
foreach ($local as $hash => $info) {
$included[] = substr($hash, 0, 12).' '.$info['summary'];
}
// Parse all of the messages into fields.
$messages = array();
foreach ($local as $hash => $info) {
$text = $info['message'];
$obj = ArcanistDifferentialCommitMessage::newFromRawCorpus($text);
$messages[$hash] = $obj;
}
$notes = array();
$fields = array();
foreach ($messages as $hash => $message) {
try {
$message->pullDataFromConduit($conduit, $partial = true);
$fields[$hash] = $message->getFields();
} catch (ArcanistDifferentialCommitMessageParserException $ex) {
if ($this->getArgument('verbatim')) {
// In verbatim mode, just bail when we hit an error. The user can
// rerun without --verbatim if they want to fix it manually. Most
// users will probably `git commit --amend` instead.
throw $ex;
}
$fields[$hash] = $message->getFields();
$frev = substr($hash, 0, 12);
$notes[] = pht(
'NOTE: commit %s could not be completely parsed:',
$frev);
foreach ($ex->getParserErrors() as $error) {
$notes[] = " - {$error}";
}
}
}
// Merge commit message fields. We do this somewhat-intelligently so that
// multiple "Reviewers" or "CC" fields will merge into the concatenation
// of all values.
// We have special parsing rules for 'title' because we can't merge
// multiple titles, and one-line commit messages like "fix stuff" will
// parse as titles. Instead, pick the first title we encounter. When we
// encounter subsequent titles, treat them as part of the summary. Then
// we merge all the summaries together below.
$result = array();
// Process fields in oldest-first order, so earlier commits get to set the
// title of record and reviewers/ccs are listed in chronological order.
$fields = array_reverse($fields);
foreach ($fields as $hash => $dict) {
$title = idx($dict, 'title');
if (!strlen($title)) {
continue;
}
if ($title === $placeholder_title) {
continue;
}
if (!isset($result['title'])) {
// We don't have a title yet, so use this one.
$result['title'] = $title;
} else {
// We already have a title, so merge this new title into the summary.
$summary = idx($dict, 'summary');
if ($summary) {
$summary = $title."\n\n".$summary;
} else {
$summary = $title;
}
$fields[$hash]['summary'] = $summary;
}
}
// Now, merge all the other fields in a general sort of way.
foreach ($fields as $hash => $dict) {
foreach ($dict as $key => $value) {
if ($key == 'title') {
// This has been handled above, and either assigned directly or
// merged into the summary.
continue;
}
if (is_array($value)) {
// For array values, merge the arrays, appending the new values.
// Examples are "Reviewers" and "Cc", where this produces a list of
// all users specified as reviewers.
$cur = idx($result, $key, array());
$new = array_merge($cur, $value);
$result[$key] = $new;
continue;
} else {
if (!strlen(trim($value))) {
// Ignore empty fields.
continue;
}
// For string values, append the new field to the old field with
// a blank line separating them. Examples are "Test Plan" and
// "Summary".
$cur = idx($result, $key, '');
if (strlen($cur)) {
$new = $cur."\n\n".$value;
} else {
$new = $value;
}
$result[$key] = $new;
}
}
}
return array($result, $notes, $included);
}
private function getDefaultUpdateMessage() {
if ($this->isRawDiffSource()) {
return null;
}
$repository_api = $this->getRepositoryAPI();
if ($repository_api instanceof ArcanistGitAPI) {
return $this->getGitUpdateMessage();
}
if ($repository_api instanceof ArcanistMercurialAPI) {
return $this->getMercurialUpdateMessage();
}
return null;
}
/**
* Retrieve the git messages between HEAD and the last update.
*
* @task message
*/
private function getGitUpdateMessage() {
$repository_api = $this->getRepositoryAPI();
$parser = $this->newDiffParser();
$commit_messages = $repository_api->getGitCommitLog();
$commit_messages = $parser->parseDiff($commit_messages);
if (count($commit_messages) == 1) {
// If there's only one message, assume this is an amend-based workflow and
// that using it to prefill doesn't make sense.
return null;
}
// We have more than one message, so figure out which ones are new. We
// do this by pulling the current diff and comparing commit hashes in the
// working copy with attached commit hashes. It's not super important that
// we always get this 100% right, we're just trying to do something
// reasonable.
$hashes = $this->loadActiveDiffLocalCommitHashes();
$hashes = array_fuse($hashes);
$usable = array();
foreach ($commit_messages as $message) {
$text = $message->getMetadata('message');
$parsed = ArcanistDifferentialCommitMessage::newFromRawCorpus($text);
if ($parsed->getRevisionID()) {
// If this is an amended commit message with a revision ID, it's
// certainly not new. Stop marking commits as usable and break out.
break;
}
if (isset($hashes[$message->getCommitHash()])) {
// If this commit is currently part of the diff, stop using commit
// messages, since anything older than this isn't new.
break;
}
// Otherwise, this looks new, so it's a usable commit message.
$usable[] = $text;
}
if (!$usable) {
// No new commit messages, so we don't have anywhere to start from.
return null;
}
return $this->formatUsableLogs($usable);
}
/**
* Retrieve the hg messages between tip and the last update.
*
* @task message
*/
private function getMercurialUpdateMessage() {
$repository_api = $this->getRepositoryAPI();
$messages = $repository_api->getCommitMessageLog();
if (count($messages) == 1) {
// If there's only one message, assume this is an amend-based workflow and
// that using it to prefill doesn't make sense.
return null;
}
$hashes = $this->loadActiveDiffLocalCommitHashes();
$hashes = array_fuse($hashes);
$usable = array();
foreach ($messages as $rev => $message) {
if (isset($hashes[$rev])) {
// If this commit is currently part of the active diff on the revision,
// stop using commit messages, since anything older than this isn't new.
break;
}
// Otherwise, this looks new, so it's a usable commit message.
$usable[] = $message;
}
if (!$usable) {
// No new commit messages, so we don't have anywhere to start from.
return null;
}
return $this->formatUsableLogs($usable);
}
/**
* Format log messages to prefill a diff update.
*
* @task message
*/
private function formatUsableLogs(array $usable) {
// Flip messages so they'll read chronologically (oldest-first) in the
// template, e.g.:
//
// - Added foobar.
// - Fixed foobar bug.
// - Documented foobar.
$usable = array_reverse($usable);
$default = array();
foreach ($usable as $message) {
// Pick the first line out of each message.
$text = trim($message);
$text = head(explode("\n", $text));
$default[] = ' - '.$text."\n";
}
return implode('', $default);
}
private function loadActiveDiffLocalCommitHashes() {
// The older "differential.querydiffs" method includes the full diff text,
// which can be very slow for large diffs. If we can, try to use
// "differential.diff.search" instead.
// We expect this to fail if the Phabricator version on the server is
// older than April 2018 (D19386), which introduced the "commits"
// attachment for "differential.revision.search".
// TODO: This can be optimized if we're able to learn the "revisionPHID"
// before we get here. See PHI1104.
try {
$revisions_raw = $this->getConduit()->callMethodSynchronous(
'differential.revision.search',
array(
'constraints' => array(
'ids' => array(
$this->revisionID,
),
),
));
$revisions = $revisions_raw['data'];
$revision = head($revisions);
if ($revision) {
$revision_phid = $revision['phid'];
$diffs_raw = $this->getConduit()->callMethodSynchronous(
'differential.diff.search',
array(
'constraints' => array(
'revisionPHIDs' => array(
$revision_phid,
),
),
'attachments' => array(
'commits' => true,
),
'limit' => 1,
));
$diffs = $diffs_raw['data'];
$diff = head($diffs);
if ($diff) {
$commits = idxv($diff, array('attachments', 'commits', 'commits'));
if ($commits !== null) {
$hashes = ipull($commits, 'identifier');
return array_values($hashes);
}
}
}
} catch (Exception $ex) {
// If any of this fails, fall back to the older method below.
}
$current_diff = $this->getConduit()->callMethodSynchronous(
'differential.querydiffs',
array(
'revisionIDs' => array($this->revisionID),
));
$current_diff = head($current_diff);
$properties = idx($current_diff, 'properties', array());
$local = idx($properties, 'local:commits', array());
$hashes = ipull($local, 'commit');
return array_values($hashes);
}
/* -( Diff Specification )------------------------------------------------- */
/**
* @task diffspec
*/
private function getLintStatus($lint_result) {
$map = array(
ArcanistLintWorkflow::RESULT_OKAY => 'okay',
ArcanistLintWorkflow::RESULT_ERRORS => 'fail',
ArcanistLintWorkflow::RESULT_WARNINGS => 'warn',
ArcanistLintWorkflow::RESULT_SKIP => 'skip',
);
return idx($map, $lint_result, 'none');
}
/**
* @task diffspec
*/
private function getUnitStatus($unit_result) {
$map = array(
ArcanistUnitWorkflow::RESULT_OKAY => 'okay',
ArcanistUnitWorkflow::RESULT_FAIL => 'fail',
ArcanistUnitWorkflow::RESULT_UNSOUND => 'warn',
ArcanistUnitWorkflow::RESULT_SKIP => 'skip',
);
return idx($map, $unit_result, 'none');
}
/**
* @task diffspec
*/
private function buildDiffSpecification() {
$base_revision = null;
$base_path = null;
$vcs = null;
$repo_uuid = null;
$parent = null;
$source_path = null;
$branch = null;
$bookmark = null;
if (!$this->isRawDiffSource()) {
$repository_api = $this->getRepositoryAPI();
$base_revision = $repository_api->getSourceControlBaseRevision();
$base_path = $repository_api->getSourceControlPath();
$vcs = $repository_api->getSourceControlSystemName();
$source_path = $repository_api->getPath();
$branch = $repository_api->getBranchName();
$repo_uuid = $repository_api->getRepositoryUUID();
if ($repository_api instanceof ArcanistGitAPI) {
$info = $this->getGitParentLogInfo();
if ($info['parent']) {
$parent = $info['parent'];
}
if ($info['base_revision']) {
$base_revision = $info['base_revision'];
}
if ($info['base_path']) {
$base_path = $info['base_path'];
}
if ($info['uuid']) {
$repo_uuid = $info['uuid'];
}
} else if ($repository_api instanceof ArcanistMercurialAPI) {
$bookmark = $repository_api->getActiveBookmark();
$svn_info = $repository_api->getSubversionInfo();
$repo_uuid = idx($svn_info, 'uuid');
$base_path = idx($svn_info, 'base_path', $base_path);
$base_revision = idx($svn_info, 'base_revision', $base_revision);
// TODO: provide parent info
}
}
$data = array(
'sourceMachine' => php_uname('n'),
'sourcePath' => $source_path,
'branch' => $branch,
'bookmark' => $bookmark,
'sourceControlSystem' => $vcs,
'sourceControlPath' => $base_path,
'sourceControlBaseRevision' => $base_revision,
'creationMethod' => 'arc',
);
if (!$this->isRawDiffSource()) {
$repository_phid = $this->getRepositoryPHID();
if ($repository_phid) {
$data['repositoryPHID'] = $repository_phid;
}
}
return $data;
}
/* -( Diff Properties )---------------------------------------------------- */
/**
* Update lint information for the diff.
*
* @return void
*
* @task diffprop
*/
private function updateLintDiffProperty() {
if (!$this->hitAutotargets) {
if ($this->unresolvedLint) {
$this->updateDiffProperty(
'arc:lint',
json_encode($this->unresolvedLint));
}
}
}
/**
* Update unit test information for the diff.
*
* @return void
*
* @task diffprop
*/
private function updateUnitDiffProperty() {
if (!$this->hitAutotargets) {
if ($this->testResults) {
$this->updateDiffProperty('arc:unit', json_encode($this->testResults));
}
}
}
/**
* Update local commit information for the diff.
*
* @task diffprop
*/
private function updateLocalDiffProperty() {
if ($this->isRawDiffSource()) {
return;
}
$local_info = $this->getRepositoryAPI()->getLocalCommitInformation();
if (!$local_info) {
return;
}
$this->updateDiffProperty('local:commits', json_encode($local_info));
}
private function updateOntoDiffProperty() {
$onto = $this->getDiffOntoTargets();
if (!$onto) {
return;
}
$this->updateDiffProperty('arc:onto', json_encode($onto));
}
private function getDiffOntoTargets() {
if ($this->isRawDiffSource()) {
return null;
}
$api = $this->getRepositoryAPI();
if (!($api instanceof ArcanistGitAPI)) {
return null;
}
// If we track an upstream branch either directly or indirectly, use that.
$branch = $api->getBranchName();
if (strlen($branch)) {
$upstream_path = $api->getPathToUpstream($branch);
$remote_branch = $upstream_path->getRemoteBranchName();
if ($remote_branch !== null) {
return array(
array(
'type' => 'branch',
'name' => $remote_branch,
'kind' => 'upstream',
),
);
}
}
// If "arc.land.onto.default" is configured, use that.
$config_key = 'arc.land.onto.default';
$onto = $this->getConfigFromAnySource($config_key);
if ($onto !== null) {
return array(
array(
'type' => 'branch',
'name' => $onto,
'kind' => 'arc.land.onto.default',
),
);
}
return null;
}
/**
* Update an arbitrary diff property.
*
* @param string Diff property name.
* @param string Diff property value.
* @return void
*
* @task diffprop
*/
private function updateDiffProperty($name, $data) {
$this->diffPropertyFutures[] = $this->getConduit()->callMethod(
'differential.setdiffproperty',
array(
'diff_id' => $this->getDiffID(),
'name' => $name,
'data' => $data,
));
}
/**
* Wait for finishing all diff property updates.
*
* @return void
*
* @task diffprop
*/
private function resolveDiffPropertyUpdates() {
id(new FutureIterator($this->diffPropertyFutures))
->resolveAll();
$this->diffPropertyFutures = array();
}
private function dispatchWillCreateRevisionEvent(array $fields) {
$event = $this->dispatchEvent(
ArcanistEventType::TYPE_REVISION_WILLCREATEREVISION,
array(
'specification' => $fields,
));
return $event->getValue('specification');
}
private function dispatchWillBuildEvent(array $fields) {
$event = $this->dispatchEvent(
ArcanistEventType::TYPE_DIFF_WILLBUILDMESSAGE,
array(
'fields' => $fields,
));
return $event->getValue('fields');
}
private function checkRevisionOwnership(array $revision) {
if ($revision['authorPHID'] == $this->getUserPHID()) {
return;
}
$id = $revision['id'];
$title = $revision['title'];
$prompt = pht(
"You don't own revision %s: \"%s\". Normally, you should ".
"only update revisions you own. You can \"Commandeer\" this revision ".
"from the web interface if you want to become the owner.\n\n".
"Update this revision anyway?",
"D{$id}",
$title);
$ok = phutil_console_confirm($prompt, $default_no = true);
if (!$ok) {
throw new ArcanistUsageException(
pht('Aborted update of revision: You are not the owner.'));
}
}
/* -( File Uploads )------------------------------------------------------- */
private function uploadFilesForChanges(array $changes) {
assert_instances_of($changes, 'ArcanistDiffChange');
// Collect all the files we need to upload.
$need_upload = array();
foreach ($changes as $key => $change) {
if ($change->getFileType() != ArcanistDiffChangeType::FILE_BINARY) {
continue;
}
if ($this->getArgument('skip-binaries')) {
continue;
}
$name = basename($change->getCurrentPath());
$need_upload[] = array(
'type' => 'old',
'name' => $name,
'data' => $change->getOriginalFileData(),
'change' => $change,
);
$need_upload[] = array(
'type' => 'new',
'name' => $name,
'data' => $change->getCurrentFileData(),
'change' => $change,
);
}
if (!$need_upload) {
return;
}
// Determine mime types and file sizes. Update changes from "binary" to
// "image" if the file is an image. Set image metadata.
$type_image = ArcanistDiffChangeType::FILE_IMAGE;
foreach ($need_upload as $key => $spec) {
$change = $need_upload[$key]['change'];
if ($spec['data'] === null) {
// This covers the case where a file was added or removed; we don't
// need to upload the other half of it (e.g., the old file data for
// a file which was just added). This is distinct from an empty
// file, which we do upload.
unset($need_upload[$key]);
continue;
}
$type = $spec['type'];
$size = strlen($spec['data']);
$change->setMetadata("{$type}:file:size", $size);
$mime = $this->getFileMimeType($spec['data']);
if (preg_match('@^image/@', $mime)) {
$change->setFileType($type_image);
}
$change->setMetadata("{$type}:file:mime-type", $mime);
}
$uploader = id(new ArcanistFileUploader())
->setConduitEngine($this->getConduitEngine());
foreach ($need_upload as $key => $spec) {
$ref = id(new ArcanistFileDataRef())
->setName($spec['name'])
->setData($spec['data']);
$uploader->addFile($ref, $key);
}
$files = $uploader->uploadFiles();
$errors = false;
foreach ($files as $key => $file) {
if ($file->getErrors()) {
unset($files[$key]);
$errors = true;
echo pht(
'Failed to upload binary "%s".',
$file->getName());
}
}
if ($errors) {
$prompt = pht('Continue?');
$ok = phutil_console_confirm($prompt, $default_no = false);
if (!$ok) {
throw new ArcanistUsageException(
pht(
'Aborted due to file upload failure. You can use %s '.
'to skip binary uploads.',
'--skip-binaries'));
}
}
foreach ($files as $key => $file) {
$spec = $need_upload[$key];
$phid = $file->getPHID();
$change = $spec['change'];
$type = $spec['type'];
$change->setMetadata("{$type}:binary-phid", $phid);
echo pht('Uploaded binary data for "%s".', $file->getName())."\n";
}
echo pht('Upload complete.')."\n";
}
private function getFileMimeType($data) {
$tmp = new TempFile();
Filesystem::writeFile($tmp, $data);
return Filesystem::getMimeType($tmp);
}
private function shouldOpenCreatedObjectsInBrowser() {
return $this->getArgument('browse');
}
private function submitChangesToStagingArea($id) {
$result = $this->pushChangesToStagingArea($id);
// We'll either get a failure constant on error, or a list of pushed
// refs on success.
$ok = is_array($result);
if ($ok) {
$staging = array(
'status' => self::STAGING_PUSHED,
'refs' => $result,
);
} else {
$staging = array(
'status' => $result,
'refs' => array(),
);
}
$this->updateDiffProperty(
'arc.staging',
phutil_json_encode($staging));
}
private function pushChangesToStagingArea($id) {
if ($this->getArgument('skip-staging')) {
$this->writeInfo(
pht('SKIP STAGING'),
pht('Flag --skip-staging was specified.'));
return self::STAGING_USER_SKIP;
}
if ($this->isRawDiffSource()) {
$this->writeInfo(
pht('SKIP STAGING'),
pht('Raw changes can not be pushed to a staging area.'));
return self::STAGING_DIFF_RAW;
}
if (!$this->getRepositoryPHID()) {
$this->writeInfo(
pht('SKIP STAGING'),
pht('Unable to determine repository for this change.'));
return self::STAGING_REPOSITORY_UNKNOWN;
}
$staging = $this->getRepositoryStagingConfiguration();
if ($staging === null) {
$this->writeInfo(
pht('SKIP STAGING'),
pht('The server does not support staging areas.'));
return self::STAGING_REPOSITORY_UNAVAILABLE;
}
$supported = idx($staging, 'supported');
if (!$supported) {
$this->writeInfo(
pht('SKIP STAGING'),
pht('The server does not support staging areas for this repository.'));
return self::STAGING_REPOSITORY_UNSUPPORTED;
}
$staging_uri = idx($staging, 'uri');
if (!$staging_uri) {
$this->writeInfo(
pht('SKIP STAGING'),
pht('No staging area is configured for this repository.'));
return self::STAGING_REPOSITORY_UNCONFIGURED;
}
$api = $this->getRepositoryAPI();
if (!($api instanceof ArcanistGitAPI)) {
$this->writeInfo(
pht('SKIP STAGING'),
pht('This client version does not support staging this repository.'));
return self::STAGING_CLIENT_UNSUPPORTED;
}
$commit = $api->getHeadCommit();
$prefix = idx($staging, 'prefix', 'phabricator');
$base_tag = "refs/tags/{$prefix}/base/{$id}";
$diff_tag = "refs/tags/{$prefix}/diff/{$id}";
$this->writeOkay(
pht('PUSH STAGING'),
pht('Pushing changes to staging area...'));
$push_flags = array();
if (version_compare($api->getGitVersion(), '1.8.2', '>=')) {
$push_flags[] = '--no-verify';
}
$refs = array();
$remote = array(
'uri' => $staging_uri,
);
$is_lfs = $api->isGitLFSWorkingCopy();
// If the base commit is a real commit, we're going to push it. We don't
// use this, but pushing it to a ref reduces the amount of redundant work
// that Git does on later pushes by helping it figure out that the remote
// already has most of the history. See T10509.
// In the future, we could avoid this push if the staging area is the same
// as the main repository, or if the staging area is a virtual repository.
// In these cases, the staging area should automatically have up-to-date
// refs.
$base_commit = $api->getSourceControlBaseRevision();
if ($base_commit !== ArcanistGitAPI::GIT_MAGIC_ROOT_COMMIT) {
$refs[] = array(
'ref' => $base_tag,
'type' => 'base',
'commit' => $base_commit,
'remote' => $remote,
);
}
// We're always going to push the change itself.
$refs[] = array(
'ref' => $diff_tag,
'type' => 'diff',
'commit' => $is_lfs ? $base_commit : $commit,
'remote' => $remote,
);
$ref_list = array();
foreach ($refs as $ref) {
$ref_list[] = $ref['commit'].':'.$ref['ref'];
}
$err = phutil_passthru(
'git push %Ls -- %s %Ls',
$push_flags,
$staging_uri,
$ref_list);
if ($err) {
$this->writeWarn(
pht('STAGING FAILED'),
pht('Unable to push changes to the staging area.'));
throw new ArcanistUsageException(
pht(
'Failed to push changes to staging area. Correct the issue, or '.
'use --skip-staging to skip this step.'));
}
if ($is_lfs) {
$ref = '+'.$commit.':'.$diff_tag;
$err = phutil_passthru(
'git push -- %s %s',
$staging_uri,
$ref);
if ($err) {
$this->writeWarn(
pht('STAGING FAILED'),
pht('Unable to push lfs changes to the staging area.'));
throw new ArcanistUsageException(
pht(
'Failed to push lfs changes to staging area. Correct the issue, '.
'or use --skip-staging to skip this step.'));
}
}
return $refs;
}
/**
* Try to upload lint and unit test results into modern Harbormaster build
* targets.
*
* @return bool True if everything was uploaded to build targets.
*/
private function updateAutotargets($diff_phid, $unit_result) {
$lint_key = 'arcanist.lint';
$unit_key = 'arcanist.unit';
try {
$result = $this->getConduit()->callMethodSynchronous(
'harbormaster.queryautotargets',
array(
'objectPHID' => $diff_phid,
'targetKeys' => array(
$lint_key,
$unit_key,
),
));
$targets = idx($result, 'targetMap', array());
} catch (Exception $ex) {
return false;
}
$futures = array();
$lint_target = idx($targets, $lint_key);
if ($lint_target) {
$lint = nonempty($this->unresolvedLint, array());
foreach ($lint as $key => $message) {
$lint[$key] = $this->getModernLintDictionary($message);
}
// Consider this target to have failed if there are any unresolved
// errors or warnings.
$type = 'pass';
foreach ($lint as $message) {
switch (idx($message, 'severity')) {
case ArcanistLintSeverity::SEVERITY_WARNING:
case ArcanistLintSeverity::SEVERITY_ERROR:
$type = 'fail';
break;
}
}
$futures[] = $this->getConduit()->callMethod(
'harbormaster.sendmessage',
array(
'buildTargetPHID' => $lint_target,
'lint' => array_values($lint),
'type' => $type,
));
}
$unit_target = idx($targets, $unit_key);
if ($unit_target) {
$unit = nonempty($this->testResults, array());
foreach ($unit as $key => $message) {
$unit[$key] = $this->getModernUnitDictionary($message);
}
$type = ArcanistUnitWorkflow::getHarbormasterTypeFromResult($unit_result);
$futures[] = $this->getConduit()->callMethod(
'harbormaster.sendmessage',
array(
'buildTargetPHID' => $unit_target,
'unit' => array_values($unit),
'type' => $type,
));
}
try {
foreach (new FutureIterator($futures) as $future) {
$future->resolve();
}
return true;
} catch (Exception $ex) {
// TODO: Eventually, we should expect these to succeed if we get this
// far, but just log errors for now.
phlog($ex);
return false;
}
}
private function getDependsOnRevisionRef() {
// TODO: Restore this behavior after updating for toolsets. Loading the
// required hardpoints currently depends on a "WorkingCopy" existing.
return null;
$api = $this->getRepositoryAPI();
$base_ref = $api->getBaseCommitRef();
$state_ref = id(new ArcanistWorkingCopyStateRef())
->setCommitRef($base_ref);
$this->loadHardpoints(
$state_ref,
ArcanistWorkingCopyStateRef::HARDPOINT_REVISIONREFS);
$revision_refs = $state_ref->getRevisionRefs();
$viewer_phid = $this->getUserPHID();
foreach ($revision_refs as $key => $revision_ref) {
// Don't automatically depend on closed revisions.
if ($revision_ref->isClosed()) {
unset($revision_refs[$key]);
continue;
}
// Don't automatically depend on revisions authored by other users.
if ($revision_ref->getAuthorPHID() != $viewer_phid) {
unset($revision_refs[$key]);
continue;
}
}
if (!$revision_refs) {
return null;
}
if (count($revision_refs) > 1) {
return null;
}
return head($revision_refs);
}
}
diff --git a/src/workflow/ArcanistWorkflow.php b/src/workflow/ArcanistWorkflow.php
index 3630bdb8..a93238d7 100644
--- a/src/workflow/ArcanistWorkflow.php
+++ b/src/workflow/ArcanistWorkflow.php
@@ -1,2468 +1,2468 @@
<?php
/**
* Implements a runnable command, like "arc diff" or "arc help".
*
* = Managing Conduit =
*
* Workflows have the builtin ability to open a Conduit connection to a
* Phabricator installation, so methods can be invoked over the API. Workflows
* may either not need this (e.g., "help"), or may need a Conduit but not
* authentication (e.g., calling only public APIs), or may need a Conduit and
* authentication (e.g., "arc diff").
*
* To specify that you need an //unauthenticated// conduit, override
* @{method:requiresConduit} to return ##true##. To specify that you need an
* //authenticated// conduit, override @{method:requiresAuthentication} to
* return ##true##. You can also manually invoke @{method:establishConduit}
* and/or @{method:authenticateConduit} later in a workflow to upgrade it.
* Once a conduit is open, you can access the client by calling
* @{method:getConduit}, which allows you to invoke methods. You can get
* verified information about the user identity by calling @{method:getUserPHID}
* or @{method:getUserName} after authentication occurs.
*
* = Scratch Files =
*
* Arcanist workflows can read and write 'scratch files', which are temporary
* files stored in the project that persist across commands. They can be useful
* if you want to save some state, or keep a copy of a long message the user
* entered if something goes wrong.
*
*
* @task conduit Conduit
* @task scratch Scratch Files
* @task phabrep Phabricator Repositories
*/
abstract class ArcanistWorkflow extends Phobject {
const COMMIT_DISABLE = 0;
const COMMIT_ALLOW = 1;
const COMMIT_ENABLE = 2;
private $commitMode = self::COMMIT_DISABLE;
private $conduit;
private $conduitURI;
private $conduitCredentials;
private $conduitAuthenticated;
private $conduitTimeout;
private $userPHID;
private $userName;
private $repositoryAPI;
private $configurationManager;
private $arguments = array();
private $command;
private $stashed;
private $shouldAmend;
private $projectInfo;
private $repositoryInfo;
private $repositoryReasons;
private $repositoryRef;
private $arcanistConfiguration;
private $parentWorkflow;
private $workingDirectory;
private $repositoryVersion;
private $changeCache = array();
private $conduitEngine;
private $toolset;
private $runtime;
private $configurationEngine;
private $configurationSourceList;
private $promptMap;
final public function setToolset(ArcanistToolset $toolset) {
$this->toolset = $toolset;
return $this;
}
final public function getToolset() {
return $this->toolset;
}
final public function setRuntime(ArcanistRuntime $runtime) {
$this->runtime = $runtime;
return $this;
}
final public function getRuntime() {
return $this->runtime;
}
final public function setConfigurationEngine(
ArcanistConfigurationEngine $engine) {
$this->configurationEngine = $engine;
return $this;
}
final public function getConfigurationEngine() {
return $this->configurationEngine;
}
final public function setConfigurationSourceList(
ArcanistConfigurationSourceList $list) {
$this->configurationSourceList = $list;
return $this;
}
final public function getConfigurationSourceList() {
return $this->configurationSourceList;
}
public function newPhutilWorkflow() {
$arguments = $this->getWorkflowArguments();
assert_instances_of($arguments, 'ArcanistWorkflowArgument');
$specs = mpull($arguments, 'getPhutilSpecification');
$phutil_workflow = id(new ArcanistPhutilWorkflow())
->setName($this->getWorkflowName())
->setWorkflow($this)
->setArguments($specs);
$information = $this->getWorkflowInformation();
if ($information !== null) {
if (!($information instanceof ArcanistWorkflowInformation)) {
throw new Exception(
pht(
'Expected workflow ("%s", of class "%s") to return an '.
'"ArcanistWorkflowInformation" object from call to '.
'"getWorkflowInformation()", got %s.',
$this->getWorkflowName(),
get_class($this),
phutil_describe_type($information)));
}
}
if ($information) {
$synopsis = $information->getSynopsis();
if ($synopsis !== null) {
$phutil_workflow->setSynopsis($synopsis);
}
$examples = $information->getExamples();
if ($examples) {
$examples = implode("\n", $examples);
$phutil_workflow->setExamples($examples);
}
$help = $information->getHelp();
if ($help !== null) {
// Unwrap linebreaks in the help text so we don't get weird formatting.
$help = preg_replace("/(?<=\S)\n(?=\S)/", ' ', $help);
$phutil_workflow->setHelp($help);
}
}
return $phutil_workflow;
}
final public function newLegacyPhutilWorkflow() {
$phutil_workflow = id(new ArcanistPhutilWorkflow())
->setName($this->getWorkflowName());
$arguments = $this->getArguments();
$specs = array();
foreach ($arguments as $key => $argument) {
if ($key == '*') {
$key = $argument;
$argument = array(
'wildcard' => true,
);
}
unset($argument['paramtype']);
unset($argument['supports']);
unset($argument['nosupport']);
unset($argument['passthru']);
unset($argument['conflict']);
$spec = array(
'name' => $key,
) + $argument;
$specs[] = $spec;
}
$phutil_workflow->setArguments($specs);
$synopses = $this->getCommandSynopses();
$phutil_workflow->setSynopsis($synopses);
$help = $this->getCommandHelp();
if (strlen($help)) {
$phutil_workflow->setHelp($help);
}
return $phutil_workflow;
}
final protected function newWorkflowArgument($key) {
return id(new ArcanistWorkflowArgument())
->setKey($key);
}
final protected function newWorkflowInformation() {
return new ArcanistWorkflowInformation();
}
final public function executeWorkflow(PhutilArgumentParser $args) {
$runtime = $this->getRuntime();
$this->arguments = $args;
$caught = null;
$runtime->pushWorkflow($this);
try {
$err = $this->runWorkflow($args);
} catch (Exception $ex) {
$caught = $ex;
}
try {
$this->runWorkflowCleanup();
} catch (Exception $ex) {
phlog($ex);
}
$runtime->popWorkflow();
if ($caught) {
throw $caught;
}
return $err;
}
final public function getLogEngine() {
return $this->getRuntime()->getLogEngine();
}
protected function runWorkflowCleanup() {
// TOOLSETS: Do we need this?
return;
}
public function __construct() {}
public function run() {
throw new PhutilMethodNotImplementedException();
}
/**
* Finalizes any cleanup operations that need to occur regardless of
* whether the command succeeded or failed.
*/
public function finalize() {
$this->finalizeWorkingCopy();
}
/**
* Return the command used to invoke this workflow from the command like,
* e.g. "help" for @{class:ArcanistHelpWorkflow}.
*
* @return string The command a user types to invoke this workflow.
*/
abstract public function getWorkflowName();
/**
* Return console formatted string with all command synopses.
*
* @return string 6-space indented list of available command synopses.
*/
public function getCommandSynopses() {
return array();
}
/**
* Return console formatted string with command help printed in `arc help`.
*
* @return string 10-space indented help to use the command.
*/
public function getCommandHelp() {
return null;
}
public function supportsToolset(ArcanistToolset $toolset) {
return false;
}
/* -( Conduit )------------------------------------------------------------ */
/**
* Set the URI which the workflow will open a conduit connection to when
* @{method:establishConduit} is called. Arcanist makes an effort to set
* this by default for all workflows (by reading ##.arcconfig## and/or the
* value of ##--conduit-uri##) even if they don't need Conduit, so a workflow
* can generally upgrade into a conduit workflow later by just calling
* @{method:establishConduit}.
*
* You generally should not need to call this method unless you are
* specifically overriding the default URI. It is normally sufficient to
* just invoke @{method:establishConduit}.
*
* NOTE: You can not call this after a conduit has been established.
*
* @param string The URI to open a conduit to when @{method:establishConduit}
* is called.
* @return this
* @task conduit
*/
final public function setConduitURI($conduit_uri) {
if ($this->conduit) {
throw new Exception(
pht(
'You can not change the Conduit URI after a '.
'conduit is already open.'));
}
$this->conduitURI = $conduit_uri;
return $this;
}
/**
* Returns the URI the conduit connection within the workflow uses.
*
* @return string
* @task conduit
*/
final public function getConduitURI() {
return $this->conduitURI;
}
/**
* Open a conduit channel to the server which was previously configured by
* calling @{method:setConduitURI}. Arcanist will do this automatically if
* the workflow returns ##true## from @{method:requiresConduit}, or you can
* later upgrade a workflow and build a conduit by invoking it manually.
*
* You must establish a conduit before you can make conduit calls.
*
* NOTE: You must call @{method:setConduitURI} before you can call this
* method.
*
* @return this
* @task conduit
*/
final public function establishConduit() {
if ($this->conduit) {
return $this;
}
if (!$this->conduitURI) {
throw new Exception(
pht(
'You must specify a Conduit URI with %s before you can '.
'establish a conduit.',
'setConduitURI()'));
}
$this->conduit = new ConduitClient($this->conduitURI);
if ($this->conduitTimeout) {
$this->conduit->setTimeout($this->conduitTimeout);
}
return $this;
}
final public function getConfigFromAnySource($key) {
$source_list = $this->getConfigurationSourceList();
if ($source_list) {
$value_list = $source_list->getStorageValueList($key);
if ($value_list) {
return last($value_list)->getValue();
}
return null;
}
return $this->configurationManager->getConfigFromAnySource($key);
}
/**
* Set credentials which will be used to authenticate against Conduit. These
* credentials can then be used to establish an authenticated connection to
* conduit by calling @{method:authenticateConduit}. Arcanist sets some
* defaults for all workflows regardless of whether or not they return true
* from @{method:requireAuthentication}, based on the ##~/.arcrc## and
* ##.arcconf## files if they are present. Thus, you can generally upgrade a
* workflow which does not require authentication into an authenticated
* workflow by later invoking @{method:requireAuthentication}. You should not
* normally need to call this method unless you are specifically overriding
* the defaults.
*
* NOTE: You can not call this method after calling
* @{method:authenticateConduit}.
*
* @param dict A credential dictionary, see @{method:authenticateConduit}.
* @return this
* @task conduit
*/
final public function setConduitCredentials(array $credentials) {
if ($this->isConduitAuthenticated()) {
throw new Exception(
pht('You may not set new credentials after authenticating conduit.'));
}
$this->conduitCredentials = $credentials;
return $this;
}
/**
* Get the protocol version the client should identify with.
*
* @return int Version the client should claim to be.
* @task conduit
*/
final public function getConduitVersion() {
return 6;
}
/**
* Open and authenticate a conduit connection to a Phabricator server using
* provided credentials. Normally, Arcanist does this for you automatically
* when you return true from @{method:requiresAuthentication}, but you can
* also upgrade an existing workflow to one with an authenticated conduit
* by invoking this method manually.
*
* You must authenticate the conduit before you can make authenticated conduit
* calls (almost all calls require authentication).
*
* This method uses credentials provided via @{method:setConduitCredentials}
* to authenticate to the server:
*
* - ##user## (required) The username to authenticate with.
* - ##certificate## (required) The Conduit certificate to use.
* - ##description## (optional) Description of the invoking command.
*
* Successful authentication allows you to call @{method:getUserPHID} and
* @{method:getUserName}, as well as use the client you access with
* @{method:getConduit} to make authenticated calls.
*
* NOTE: You must call @{method:setConduitURI} and
* @{method:setConduitCredentials} before you invoke this method.
*
* @return this
* @task conduit
*/
final public function authenticateConduit() {
if ($this->isConduitAuthenticated()) {
return $this;
}
$this->establishConduit();
$credentials = $this->conduitCredentials;
try {
if (!$credentials) {
throw new Exception(
pht(
'Set conduit credentials with %s before authenticating conduit!',
'setConduitCredentials()'));
}
// If we have `token`, this server supports the simpler, new-style
// token-based authentication. Use that instead of all the certificate
// stuff.
$token = idx($credentials, 'token');
if (strlen($token)) {
$conduit = $this->getConduit();
$conduit->setConduitToken($token);
try {
$result = $this->getConduit()->callMethodSynchronous(
'user.whoami',
array());
$this->userName = $result['userName'];
$this->userPHID = $result['phid'];
$this->conduitAuthenticated = true;
return $this;
} catch (Exception $ex) {
$conduit->setConduitToken(null);
throw $ex;
}
}
if (empty($credentials['user'])) {
throw new ConduitClientException(
'ERR-INVALID-USER',
pht('Empty user in credentials.'));
}
if (empty($credentials['certificate'])) {
throw new ConduitClientException(
'ERR-NO-CERTIFICATE',
pht('Empty certificate in credentials.'));
}
$description = idx($credentials, 'description', '');
$user = $credentials['user'];
$certificate = $credentials['certificate'];
$connection = $this->getConduit()->callMethodSynchronous(
'conduit.connect',
array(
'client' => 'arc',
'clientVersion' => $this->getConduitVersion(),
'clientDescription' => php_uname('n').':'.$description,
'user' => $user,
'certificate' => $certificate,
'host' => $this->conduitURI,
));
} catch (ConduitClientException $ex) {
if ($ex->getErrorCode() == 'ERR-NO-CERTIFICATE' ||
$ex->getErrorCode() == 'ERR-INVALID-USER' ||
$ex->getErrorCode() == 'ERR-INVALID-AUTH') {
$conduit_uri = $this->conduitURI;
$message = phutil_console_format(
"\n%s\n\n %s\n\n%s\n%s",
pht('YOU NEED TO __INSTALL A CERTIFICATE__ TO LOG IN'),
pht('To do this, run: **%s**', 'arc install-certificate'),
pht("The server '%s' rejected your request:", $conduit_uri),
$ex->getMessage());
throw new ArcanistUsageException($message);
} else if ($ex->getErrorCode() == 'NEW-ARC-VERSION') {
// Cleverly disguise this as being AWESOME!!!
echo phutil_console_format("**%s**\n\n", pht('New Version Available!'));
echo phutil_console_wrap($ex->getMessage());
echo "\n\n";
echo pht('In most cases, arc can be upgraded automatically.')."\n";
$ok = phutil_console_confirm(
pht('Upgrade arc now?'),
$default_no = false);
if (!$ok) {
throw $ex;
}
$root = dirname(phutil_get_library_root('arcanist'));
chdir($root);
$err = phutil_passthru('%s upgrade', $root.'/bin/arc');
if (!$err) {
echo "\n".pht('Try running your arc command again.')."\n";
}
exit(1);
} else {
throw $ex;
}
}
$this->userName = $user;
$this->userPHID = $connection['userPHID'];
$this->conduitAuthenticated = true;
return $this;
}
/**
* @return bool True if conduit is authenticated, false otherwise.
* @task conduit
*/
final protected function isConduitAuthenticated() {
return (bool)$this->conduitAuthenticated;
}
/**
* Override this to return true if your workflow requires a conduit channel.
* Arc will build the channel for you before your workflow executes. This
* implies that you only need an unauthenticated channel; if you need
* authentication, override @{method:requiresAuthentication}.
*
* @return bool True if arc should build a conduit channel before running
* the workflow.
* @task conduit
*/
public function requiresConduit() {
return false;
}
/**
* Override this to return true if your workflow requires an authenticated
* conduit channel. This implies that it requires a conduit. Arc will build
* and authenticate the channel for you before the workflow executes.
*
* @return bool True if arc should build an authenticated conduit channel
* before running the workflow.
* @task conduit
*/
public function requiresAuthentication() {
return false;
}
/**
* Returns the PHID for the user once they've authenticated via Conduit.
*
* @return phid Authenticated user PHID.
* @task conduit
*/
final public function getUserPHID() {
if (!$this->userPHID) {
$workflow = get_class($this);
throw new Exception(
pht(
"This workflow ('%s') requires authentication, override ".
"%s to return true.",
$workflow,
'requiresAuthentication()'));
}
return $this->userPHID;
}
/**
* Return the username for the user once they've authenticated via Conduit.
*
* @return string Authenticated username.
* @task conduit
*/
final public function getUserName() {
return $this->userName;
}
/**
* Get the established @{class@libphutil:ConduitClient} in order to make
* Conduit method calls. Before the client is available it must be connected,
* either implicitly by making @{method:requireConduit} or
* @{method:requireAuthentication} return true, or explicitly by calling
* @{method:establishConduit} or @{method:authenticateConduit}.
*
* @return @{class@libphutil:ConduitClient} Live conduit client.
* @task conduit
*/
final public function getConduit() {
if (!$this->conduit) {
$workflow = get_class($this);
throw new Exception(
pht(
"This workflow ('%s') requires a Conduit, override ".
"%s to return true.",
$workflow,
'requiresConduit()'));
}
return $this->conduit;
}
final public function setArcanistConfiguration(
ArcanistConfiguration $arcanist_configuration) {
$this->arcanistConfiguration = $arcanist_configuration;
return $this;
}
final public function getArcanistConfiguration() {
return $this->arcanistConfiguration;
}
final public function setConfigurationManager(
ArcanistConfigurationManager $arcanist_configuration_manager) {
$this->configurationManager = $arcanist_configuration_manager;
return $this;
}
final public function getConfigurationManager() {
return $this->configurationManager;
}
public function requiresWorkingCopy() {
return false;
}
public function desiresWorkingCopy() {
return false;
}
public function requiresRepositoryAPI() {
return false;
}
public function desiresRepositoryAPI() {
return false;
}
final public function setCommand($command) {
$this->command = $command;
return $this;
}
final public function getCommand() {
return $this->command;
}
public function getArguments() {
return array();
}
final public function setWorkingDirectory($working_directory) {
$this->workingDirectory = $working_directory;
return $this;
}
final public function getWorkingDirectory() {
return $this->workingDirectory;
}
private function setParentWorkflow($parent_workflow) {
$this->parentWorkflow = $parent_workflow;
return $this;
}
final protected function getParentWorkflow() {
return $this->parentWorkflow;
}
final public function buildChildWorkflow($command, array $argv) {
$arc_config = $this->getArcanistConfiguration();
$workflow = $arc_config->buildWorkflow($command);
$workflow->setParentWorkflow($this);
$workflow->setConduitEngine($this->getConduitEngine());
$workflow->setCommand($command);
$workflow->setConfigurationManager($this->getConfigurationManager());
if ($this->repositoryAPI) {
$workflow->setRepositoryAPI($this->repositoryAPI);
}
if ($this->userPHID) {
$workflow->userPHID = $this->getUserPHID();
$workflow->userName = $this->getUserName();
}
if ($this->conduit) {
$workflow->conduit = $this->conduit;
$workflow->setConduitCredentials($this->conduitCredentials);
$workflow->conduitAuthenticated = $this->conduitAuthenticated;
}
$workflow->setArcanistConfiguration($arc_config);
$workflow->parseArguments(array_values($argv));
return $workflow;
}
final public function getArgument($key, $default = null) {
// TOOLSETS: Remove this legacy code.
if (is_array($this->arguments)) {
return idx($this->arguments, $key, $default);
}
return $this->arguments->getArg($key);
}
final public function getCompleteArgumentSpecification() {
$spec = $this->getArguments();
$arc_config = $this->getArcanistConfiguration();
$command = $this->getCommand();
$spec += $arc_config->getCustomArgumentsForCommand($command);
return $spec;
}
final public function parseArguments(array $args) {
$spec = $this->getCompleteArgumentSpecification();
$dict = array();
$more_key = null;
if (!empty($spec['*'])) {
$more_key = $spec['*'];
unset($spec['*']);
$dict[$more_key] = array();
}
$short_to_long_map = array();
foreach ($spec as $long => $options) {
if (!empty($options['short'])) {
$short_to_long_map[$options['short']] = $long;
}
}
foreach ($spec as $long => $options) {
if (!empty($options['repeat'])) {
$dict[$long] = array();
}
}
$more = array();
$size = count($args);
for ($ii = 0; $ii < $size; $ii++) {
$arg = $args[$ii];
$arg_name = null;
$arg_key = null;
if ($arg == '--') {
$more = array_merge(
$more,
array_slice($args, $ii + 1));
break;
} else if (!strncmp($arg, '--', 2)) {
$arg_key = substr($arg, 2);
$parts = explode('=', $arg_key, 2);
if (count($parts) == 2) {
list($arg_key, $val) = $parts;
array_splice($args, $ii, 1, array('--'.$arg_key, $val));
$size++;
}
if (!array_key_exists($arg_key, $spec)) {
$corrected = PhutilArgumentSpellingCorrector::newFlagCorrector()
->correctSpelling($arg_key, array_keys($spec));
if (count($corrected) == 1) {
PhutilConsole::getConsole()->writeErr(
pht(
"(Assuming '%s' is the British spelling of '%s'.)",
'--'.$arg_key,
'--'.head($corrected))."\n");
$arg_key = head($corrected);
} else {
throw new ArcanistUsageException(
pht(
"Unknown argument '%s'. Try '%s'.",
$arg_key,
'arc help'));
}
}
} else if (!strncmp($arg, '-', 1)) {
$arg_key = substr($arg, 1);
if (empty($short_to_long_map[$arg_key])) {
throw new ArcanistUsageException(
pht(
"Unknown argument '%s'. Try '%s'.",
$arg_key,
'arc help'));
}
$arg_key = $short_to_long_map[$arg_key];
} else {
$more[] = $arg;
continue;
}
$options = $spec[$arg_key];
if (empty($options['param'])) {
$dict[$arg_key] = true;
} else {
if ($ii == $size - 1) {
throw new ArcanistUsageException(
pht(
"Option '%s' requires a parameter.",
$arg));
}
if (!empty($options['repeat'])) {
$dict[$arg_key][] = $args[$ii + 1];
} else {
$dict[$arg_key] = $args[$ii + 1];
}
$ii++;
}
}
if ($more) {
if ($more_key) {
$dict[$more_key] = $more;
} else {
$example = reset($more);
throw new ArcanistUsageException(
pht(
"Unrecognized argument '%s'. Try '%s'.",
$example,
'arc help'));
}
}
foreach ($dict as $key => $value) {
if (empty($spec[$key]['conflicts'])) {
continue;
}
foreach ($spec[$key]['conflicts'] as $conflict => $more) {
if (isset($dict[$conflict])) {
if ($more) {
$more = ': '.$more;
} else {
$more = '.';
}
// TODO: We'll always display these as long-form, when the user might
// have typed them as short form.
throw new ArcanistUsageException(
pht(
"Arguments '%s' and '%s' are mutually exclusive",
"--{$key}",
"--{$conflict}").$more);
}
}
}
$this->arguments = $dict;
$this->didParseArguments();
return $this;
}
protected function didParseArguments() {
// Override this to customize workflow argument behavior.
}
final public function getWorkingCopy() {
$configuration_engine = $this->getConfigurationEngine();
// TOOLSETS: Remove this once all workflows are toolset workflows.
if (!$configuration_engine) {
throw new Exception(
pht(
'This workflow has not yet been updated to Toolsets and can '.
'not retrieve a modern WorkingCopy object. Use '.
'"getWorkingCopyIdentity()" to retrieve a previous-generation '.
'object.'));
}
return $configuration_engine->getWorkingCopy();
}
final public function getWorkingCopyIdentity() {
$configuration_engine = $this->getConfigurationEngine();
if ($configuration_engine) {
$working_copy = $configuration_engine->getWorkingCopy();
$working_path = $working_copy->getWorkingDirectory();
return ArcanistWorkingCopyIdentity::newFromPath($working_path);
}
$working_copy = $this->getConfigurationManager()->getWorkingCopyIdentity();
if (!$working_copy) {
$workflow = get_class($this);
throw new Exception(
pht(
"This workflow ('%s') requires a working copy, override ".
"%s to return true.",
$workflow,
'requiresWorkingCopy()'));
}
return $working_copy;
}
final public function setRepositoryAPI($api) {
$this->repositoryAPI = $api;
return $this;
}
final public function hasRepositoryAPI() {
try {
return (bool)$this->getRepositoryAPI();
} catch (Exception $ex) {
return false;
}
}
final public function getRepositoryAPI() {
$configuration_engine = $this->getConfigurationEngine();
if ($configuration_engine) {
$working_copy = $configuration_engine->getWorkingCopy();
return $working_copy->getRepositoryAPI();
}
if (!$this->repositoryAPI) {
$workflow = get_class($this);
throw new Exception(
pht(
"This workflow ('%s') requires a Repository API, override ".
"%s to return true.",
$workflow,
'requiresRepositoryAPI()'));
}
return $this->repositoryAPI;
}
final protected function shouldRequireCleanUntrackedFiles() {
return empty($this->arguments['allow-untracked']);
}
final public function setCommitMode($mode) {
$this->commitMode = $mode;
return $this;
}
final public function finalizeWorkingCopy() {
if ($this->stashed) {
$api = $this->getRepositoryAPI();
$api->unstashChanges();
echo pht('Restored stashed changes to the working directory.')."\n";
}
}
final public function requireCleanWorkingCopy() {
$api = $this->getRepositoryAPI();
$must_commit = array();
$working_copy_desc = phutil_console_format(
" %s: __%s__\n\n",
pht('Working copy'),
$api->getPath());
// NOTE: this is a subversion-only concept.
$incomplete = $api->getIncompleteChanges();
if ($incomplete) {
throw new ArcanistUsageException(
sprintf(
"%s\n\n%s %s\n %s\n\n%s",
pht(
"You have incompletely checked out directories in this working ".
"copy. Fix them before proceeding.'"),
$working_copy_desc,
pht('Incomplete directories in working copy:'),
implode("\n ", $incomplete),
pht(
"You can fix these paths by running '%s' on them.",
'svn update')));
}
$conflicts = $api->getMergeConflicts();
if ($conflicts) {
throw new ArcanistUsageException(
sprintf(
"%s\n\n%s %s\n %s",
pht(
'You have merge conflicts in this working copy. Resolve merge '.
'conflicts before proceeding.'),
$working_copy_desc,
pht('Conflicts in working copy:'),
implode("\n ", $conflicts)));
}
$missing = $api->getMissingChanges();
if ($missing) {
throw new ArcanistUsageException(
sprintf(
"%s\n\n%s %s\n %s\n",
pht(
'You have missing files in this working copy. Revert or formally '.
'remove them (with `%s`) before proceeding.',
'svn rm'),
$working_copy_desc,
pht('Missing files in working copy:'),
implode("\n ", $missing)));
}
$externals = $api->getDirtyExternalChanges();
// TODO: This state can exist in Subversion, but it is currently handled
// elsewhere. It should probably be handled here, eventually.
if ($api instanceof ArcanistSubversionAPI) {
$externals = array();
}
if ($externals) {
$message = pht(
'%s submodule(s) have uncommitted or untracked changes:',
new PhutilNumber(count($externals)));
$prompt = pht(
'Ignore the changes to these %s submodule(s) and continue?',
new PhutilNumber(count($externals)));
$list = id(new PhutilConsoleList())
->setWrap(false)
->addItems($externals);
id(new PhutilConsoleBlock())
->addParagraph($message)
->addList($list)
->draw();
$ok = phutil_console_confirm($prompt, $default_no = false);
if (!$ok) {
throw new ArcanistUserAbortException();
}
}
$uncommitted = $api->getUncommittedChanges();
$unstaged = $api->getUnstagedChanges();
// We already dealt with externals.
$unstaged = array_diff($unstaged, $externals);
// We only want files which are purely uncommitted.
$uncommitted = array_diff($uncommitted, $unstaged);
$uncommitted = array_diff($uncommitted, $externals);
$untracked = $api->getUntrackedChanges();
if (!$this->shouldRequireCleanUntrackedFiles()) {
$untracked = array();
}
if ($untracked) {
echo sprintf(
"%s\n\n%s",
pht('You have untracked files in this working copy.'),
$working_copy_desc);
if ($api instanceof ArcanistGitAPI) {
$hint = pht(
'(To ignore these %s change(s), add them to "%s".)',
phutil_count($untracked),
'.git/info/exclude');
} else if ($api instanceof ArcanistSubversionAPI) {
$hint = pht(
'(To ignore these %s change(s), add them to "%s".)',
phutil_count($untracked),
'svn:ignore');
} else if ($api instanceof ArcanistMercurialAPI) {
$hint = pht(
'(To ignore these %s change(s), add them to "%s".)',
phutil_count($untracked),
'.hgignore');
}
$untracked_list = " ".implode("\n ", $untracked);
echo sprintf(
" %s\n %s\n%s",
pht('Untracked changes in working copy:'),
$hint,
$untracked_list);
$prompt = pht(
'Ignore these %s untracked file(s) and continue?',
phutil_count($untracked));
if (!phutil_console_confirm($prompt)) {
throw new ArcanistUserAbortException();
}
}
$should_commit = false;
if ($unstaged || $uncommitted) {
// NOTE: We're running this because it builds a cache and can take a
// perceptible amount of time to arrive at an answer, but we don't want
// to pause in the middle of printing the output below.
$this->getShouldAmend();
echo sprintf(
"%s\n\n%s",
pht('You have uncommitted changes in this working copy.'),
$working_copy_desc);
$lists = array();
if ($unstaged) {
$unstaged_list = " ".implode("\n ", $unstaged);
$lists[] = sprintf(
" %s\n%s",
pht('Unstaged changes in working copy:'),
$unstaged_list);
}
if ($uncommitted) {
$uncommitted_list = " ".implode("\n ", $uncommitted);
$lists[] = sprintf(
"%s\n%s",
pht('Uncommitted changes in working copy:'),
$uncommitted_list);
}
echo implode("\n\n", $lists)."\n";
$all_uncommitted = array_merge($unstaged, $uncommitted);
if ($this->askForAdd($all_uncommitted)) {
if ($unstaged) {
$api->addToCommit($unstaged);
}
$should_commit = true;
} else {
$permit_autostash = $this->getConfigFromAnySource('arc.autostash');
if ($permit_autostash && $api->canStashChanges()) {
echo pht(
'Stashing uncommitted changes. (You can restore them with `%s`).',
'git stash pop')."\n";
$api->stashChanges();
$this->stashed = true;
} else {
throw new ArcanistUsageException(
pht(
'You can not continue with uncommitted changes. '.
'Commit or discard them before proceeding.'));
}
}
}
if ($should_commit) {
if ($this->getShouldAmend()) {
$commit = head($api->getLocalCommitInformation());
$api->amendCommit($commit['message']);
} else if ($api->supportsLocalCommits()) {
$template = sprintf(
"\n\n# %s\n#\n# %s\n#\n",
pht('Enter a commit message.'),
pht('Changes:'));
$paths = array_merge($uncommitted, $unstaged);
$paths = array_unique($paths);
sort($paths);
foreach ($paths as $path) {
$template .= "# ".$path."\n";
}
$commit_message = $this->newInteractiveEditor($template)
->setName(pht('commit-message'))
->setTaskMessage(pht(
'Supply commit message for uncommitted changes, then save and '.
'exit.'))
->editInteractively();
if ($commit_message === $template) {
throw new ArcanistUsageException(
pht('You must provide a commit message.'));
}
$commit_message = ArcanistCommentRemover::removeComments(
$commit_message);
if (!strlen($commit_message)) {
throw new ArcanistUsageException(
pht('You must provide a nonempty commit message.'));
}
$api->doCommit($commit_message);
}
}
}
private function getShouldAmend() {
if ($this->shouldAmend === null) {
$this->shouldAmend = $this->calculateShouldAmend();
}
return $this->shouldAmend;
}
private function calculateShouldAmend() {
$api = $this->getRepositoryAPI();
if ($this->isHistoryImmutable() || !$api->supportsAmend()) {
return false;
}
$commits = $api->getLocalCommitInformation();
if (!$commits) {
return false;
}
$commit = reset($commits);
$message = ArcanistDifferentialCommitMessage::newFromRawCorpus(
$commit['message']);
if ($message->getGitSVNBaseRevision()) {
return false;
}
if ($api->getAuthor() != $commit['author']) {
return false;
}
if ($message->getRevisionID() && $this->getArgument('create')) {
return false;
}
// TODO: Check commits since tracking branch. If empty then return false.
// Don't amend the current commit if it has already been published.
$repository = $this->loadProjectRepository();
if ($repository) {
$repo_id = $repository['id'];
$commit_hash = $commit['commit'];
$callsign = idx($repository, 'callsign');
if ($callsign) {
// The server might be too old to support the new style commit names,
// so prefer the old way
$commit_name = "r{$callsign}{$commit_hash}";
} else {
$commit_name = "R{$repo_id}:{$commit_hash}";
}
$result = $this->getConduit()->callMethodSynchronous(
'diffusion.querycommits',
array('names' => array($commit_name)));
$known_commit = idx($result['identifierMap'], $commit_name);
if ($known_commit) {
return false;
}
}
if (!$message->getRevisionID()) {
return true;
}
$in_working_copy = $api->loadWorkingCopyDifferentialRevisions(
$this->getConduit(),
array(
'authors' => array($this->getUserPHID()),
'status' => 'status-open',
));
if ($in_working_copy) {
return true;
}
return false;
}
private function askForAdd(array $files) {
if ($this->commitMode == self::COMMIT_DISABLE) {
return false;
}
if ($this->commitMode == self::COMMIT_ENABLE) {
return true;
}
$prompt = $this->getAskForAddPrompt($files);
return phutil_console_confirm($prompt);
}
private function getAskForAddPrompt(array $files) {
if ($this->getShouldAmend()) {
$prompt = pht(
'Do you want to amend these %s change(s) to the current commit?',
phutil_count($files));
} else {
$prompt = pht(
'Do you want to create a new commit with these %s change(s)?',
phutil_count($files));
}
return $prompt;
}
final protected function loadDiffBundleFromConduit(
ConduitClient $conduit,
$diff_id) {
return $this->loadBundleFromConduit(
$conduit,
array(
'ids' => array($diff_id),
));
}
final protected function loadRevisionBundleFromConduit(
ConduitClient $conduit,
$revision_id) {
return $this->loadBundleFromConduit(
$conduit,
array(
'revisionIDs' => array($revision_id),
));
}
private function loadBundleFromConduit(
ConduitClient $conduit,
$params) {
$future = $conduit->callMethod('differential.querydiffs', $params);
$diff = head($future->resolve());
if ($diff == null) {
throw new Exception(
phutil_console_wrap(
pht("The diff or revision you specified is either invalid or you ".
"don't have permission to view it."))
);
}
$changes = array();
foreach ($diff['changes'] as $changedict) {
$changes[] = ArcanistDiffChange::newFromDictionary($changedict);
}
$bundle = ArcanistBundle::newFromChanges($changes);
$bundle->setConduit($conduit);
// since the conduit method has changes, assume that these fields
// could be unset
$bundle->setBaseRevision(idx($diff, 'sourceControlBaseRevision'));
$bundle->setRevisionID(idx($diff, 'revisionID'));
$bundle->setAuthorName(idx($diff, 'authorName'));
$bundle->setAuthorEmail(idx($diff, 'authorEmail'));
return $bundle;
}
/**
* Return a list of lines changed by the current diff, or ##null## if the
* change list is meaningless (for example, because the path is a directory
* or binary file).
*
* @param string Path within the repository.
* @param string Change selection mode (see ArcanistDiffHunk).
* @return list|null List of changed line numbers, or null to indicate that
* the path is not a line-oriented text file.
*/
final protected function getChangedLines($path, $mode) {
$repository_api = $this->getRepositoryAPI();
$full_path = $repository_api->getPath($path);
if (is_dir($full_path)) {
return null;
}
if (!file_exists($full_path)) {
return null;
}
$change = $this->getChange($path);
if ($change->getFileType() !== ArcanistDiffChangeType::FILE_TEXT) {
return null;
}
$lines = $change->getChangedLines($mode);
return array_keys($lines);
}
final protected function getChange($path) {
$repository_api = $this->getRepositoryAPI();
// TODO: Very gross
$is_git = ($repository_api instanceof ArcanistGitAPI);
$is_hg = ($repository_api instanceof ArcanistMercurialAPI);
$is_svn = ($repository_api instanceof ArcanistSubversionAPI);
if ($is_svn) {
// NOTE: In SVN, we don't currently support a "get all local changes"
// operation, so special case it.
if (empty($this->changeCache[$path])) {
$diff = $repository_api->getRawDiffText($path);
$parser = $this->newDiffParser();
$changes = $parser->parseDiff($diff);
if (count($changes) != 1) {
throw new Exception(pht('Expected exactly one change.'));
}
$this->changeCache[$path] = reset($changes);
}
} else if ($is_git || $is_hg) {
if (empty($this->changeCache)) {
$changes = $repository_api->getAllLocalChanges();
foreach ($changes as $change) {
$this->changeCache[$change->getCurrentPath()] = $change;
}
}
} else {
throw new Exception(pht('Missing VCS support.'));
}
if (empty($this->changeCache[$path])) {
if ($is_git || $is_hg) {
// This can legitimately occur under git/hg if you make a change,
// "git/hg commit" it, and then revert the change in the working copy
// and run "arc lint".
$change = new ArcanistDiffChange();
$change->setCurrentPath($path);
return $change;
} else {
throw new Exception(
pht(
"Trying to get change for unchanged path '%s'!",
$path));
}
}
return $this->changeCache[$path];
}
final public function willRunWorkflow() {
$spec = $this->getCompleteArgumentSpecification();
foreach ($this->arguments as $arg => $value) {
if (empty($spec[$arg])) {
continue;
}
$options = $spec[$arg];
if (!empty($options['supports'])) {
$system_name = $this->getRepositoryAPI()->getSourceControlSystemName();
if (!in_array($system_name, $options['supports'])) {
$extended_info = null;
if (!empty($options['nosupport'][$system_name])) {
$extended_info = ' '.$options['nosupport'][$system_name];
}
throw new ArcanistUsageException(
pht(
"Option '%s' is not supported under %s.",
"--{$arg}",
$system_name).
$extended_info);
}
}
}
}
final protected function normalizeRevisionID($revision_id) {
return preg_replace('/^D/i', '', $revision_id);
}
protected function shouldShellComplete() {
return true;
}
protected function getShellCompletions(array $argv) {
return array();
}
public function getSupportedRevisionControlSystems() {
return array('git', 'hg', 'svn');
}
final protected function getPassthruArgumentsAsMap($command) {
$map = array();
foreach ($this->getCompleteArgumentSpecification() as $key => $spec) {
if (!empty($spec['passthru'][$command])) {
if (isset($this->arguments[$key])) {
$map[$key] = $this->arguments[$key];
}
}
}
return $map;
}
final protected function getPassthruArgumentsAsArgv($command) {
$spec = $this->getCompleteArgumentSpecification();
$map = $this->getPassthruArgumentsAsMap($command);
$argv = array();
foreach ($map as $key => $value) {
$argv[] = '--'.$key;
if (!empty($spec[$key]['param'])) {
$argv[] = $value;
}
}
return $argv;
}
/**
* Write a message to stderr so that '--json' flags or stdout which is meant
* to be piped somewhere aren't disrupted.
*
* @param string Message to write to stderr.
* @return void
*/
final protected function writeStatusMessage($msg) {
- fwrite(STDERR, $msg);
+ PhutilSystem::writeStderr($msg);
}
final public function writeInfo($title, $message) {
$this->writeStatusMessage(
phutil_console_format(
"<bg:blue>** %s **</bg> %s\n",
$title,
$message));
}
final public function writeWarn($title, $message) {
$this->writeStatusMessage(
phutil_console_format(
"<bg:yellow>** %s **</bg> %s\n",
$title,
$message));
}
final public function writeOkay($title, $message) {
$this->writeStatusMessage(
phutil_console_format(
"<bg:green>** %s **</bg> %s\n",
$title,
$message));
}
final protected function isHistoryImmutable() {
$repository_api = $this->getRepositoryAPI();
$config = $this->getConfigFromAnySource('history.immutable');
if ($config !== null) {
return $config;
}
return $repository_api->isHistoryDefaultImmutable();
}
/**
* Workflows like 'lint' and 'unit' operate on a list of working copy paths.
* The user can either specify the paths explicitly ("a.js b.php"), or by
* specifying a revision ("--rev a3f10f1f") to select all paths modified
* since that revision, or by omitting both and letting arc choose the
* default relative revision.
*
* This method takes the user's selections and returns the paths that the
* workflow should act upon.
*
* @param list List of explicitly provided paths.
* @param string|null Revision name, if provided.
* @param mask Mask of ArcanistRepositoryAPI flags to exclude.
* Defaults to ArcanistRepositoryAPI::FLAG_UNTRACKED.
* @return list List of paths the workflow should act on.
*/
final protected function selectPathsForWorkflow(
array $paths,
$rev,
$omit_mask = null) {
if ($omit_mask === null) {
$omit_mask = ArcanistRepositoryAPI::FLAG_UNTRACKED;
}
if ($paths) {
$working_copy = $this->getWorkingCopyIdentity();
foreach ($paths as $key => $path) {
$full_path = Filesystem::resolvePath($path);
if (!Filesystem::pathExists($full_path)) {
throw new ArcanistUsageException(
pht(
"Path '%s' does not exist!",
$path));
}
$relative_path = Filesystem::readablePath(
$full_path,
$working_copy->getProjectRoot());
$paths[$key] = $relative_path;
}
} else {
$repository_api = $this->getRepositoryAPI();
if ($rev) {
$this->parseBaseCommitArgument(array($rev));
}
$paths = $repository_api->getWorkingCopyStatus();
foreach ($paths as $path => $flags) {
if ($flags & $omit_mask) {
unset($paths[$path]);
}
}
$paths = array_keys($paths);
}
return array_values($paths);
}
final protected function renderRevisionList(array $revisions) {
$list = array();
foreach ($revisions as $revision) {
$list[] = ' - D'.$revision['id'].': '.$revision['title']."\n";
}
return implode('', $list);
}
/* -( Scratch Files )------------------------------------------------------ */
/**
* Try to read a scratch file, if it exists and is readable.
*
* @param string Scratch file name.
* @return mixed String for file contents, or false for failure.
* @task scratch
*/
final protected function readScratchFile($path) {
if (!$this->repositoryAPI) {
return false;
}
return $this->getRepositoryAPI()->readScratchFile($path);
}
/**
* Try to read a scratch JSON file, if it exists and is readable.
*
* @param string Scratch file name.
* @return array Empty array for failure.
* @task scratch
*/
final protected function readScratchJSONFile($path) {
$file = $this->readScratchFile($path);
if (!$file) {
return array();
}
return phutil_json_decode($file);
}
/**
* Try to write a scratch file, if there's somewhere to put it and we can
* write there.
*
* @param string Scratch file name to write.
* @param string Data to write.
* @return bool True on success, false on failure.
* @task scratch
*/
final protected function writeScratchFile($path, $data) {
if (!$this->repositoryAPI) {
return false;
}
return $this->getRepositoryAPI()->writeScratchFile($path, $data);
}
/**
* Try to write a scratch JSON file, if there's somewhere to put it and we can
* write there.
*
* @param string Scratch file name to write.
* @param array Data to write.
* @return bool True on success, false on failure.
* @task scratch
*/
final protected function writeScratchJSONFile($path, array $data) {
return $this->writeScratchFile($path, json_encode($data));
}
/**
* Try to remove a scratch file.
*
* @param string Scratch file name to remove.
* @return bool True if the file was removed successfully.
* @task scratch
*/
final protected function removeScratchFile($path) {
if (!$this->repositoryAPI) {
return false;
}
return $this->getRepositoryAPI()->removeScratchFile($path);
}
/**
* Get a human-readable description of the scratch file location.
*
* @param string Scratch file name.
* @return mixed String, or false on failure.
* @task scratch
*/
final protected function getReadableScratchFilePath($path) {
if (!$this->repositoryAPI) {
return false;
}
return $this->getRepositoryAPI()->getReadableScratchFilePath($path);
}
/**
* Get the path to a scratch file, if possible.
*
* @param string Scratch file name.
* @return mixed File path, or false on failure.
* @task scratch
*/
final protected function getScratchFilePath($path) {
if (!$this->repositoryAPI) {
return false;
}
return $this->getRepositoryAPI()->getScratchFilePath($path);
}
final protected function getRepositoryEncoding() {
return nonempty(
idx($this->loadProjectRepository(), 'encoding'),
'UTF-8');
}
final protected function loadProjectRepository() {
list($info, $reasons) = $this->loadRepositoryInformation();
return coalesce($info, array());
}
final protected function newInteractiveEditor($text) {
$editor = new PhutilInteractiveEditor($text);
$preferred = $this->getConfigFromAnySource('editor');
if ($preferred) {
$editor->setPreferredEditor($preferred);
}
return $editor;
}
final protected function newDiffParser() {
$parser = new ArcanistDiffParser();
if ($this->repositoryAPI) {
$parser->setRepositoryAPI($this->getRepositoryAPI());
}
$parser->setWriteDiffOnFailure(true);
return $parser;
}
final protected function dispatchEvent($type, array $data) {
$data += array(
'workflow' => $this,
);
$event = new PhutilEvent($type, $data);
PhutilEventEngine::dispatchEvent($event);
return $event;
}
final public function parseBaseCommitArgument(array $argv) {
if (!count($argv)) {
return;
}
$api = $this->getRepositoryAPI();
if (!$api->supportsCommitRanges()) {
throw new ArcanistUsageException(
pht('This version control system does not support commit ranges.'));
}
if (count($argv) > 1) {
throw new ArcanistUsageException(
pht(
'Specify exactly one base commit. The end of the commit range is '.
'always the working copy state.'));
}
$api->setBaseCommit(head($argv));
return $this;
}
final protected function getRepositoryVersion() {
if (!$this->repositoryVersion) {
$api = $this->getRepositoryAPI();
$commit = $api->getSourceControlBaseRevision();
$versions = array('' => $commit);
foreach ($api->getChangedFiles($commit) as $path => $mask) {
$versions[$path] = (Filesystem::pathExists($path)
? md5_file($path)
: '');
}
$this->repositoryVersion = md5(json_encode($versions));
}
return $this->repositoryVersion;
}
/* -( Phabricator Repositories )------------------------------------------- */
/**
* Get the PHID of the Phabricator repository this working copy corresponds
* to. Returns `null` if no repository can be identified.
*
* @return phid|null Repository PHID, or null if no repository can be
* identified.
*
* @task phabrep
*/
final protected function getRepositoryPHID() {
return idx($this->getRepositoryInformation(), 'phid');
}
/**
* Get the name of the Phabricator repository this working copy
* corresponds to. Returns `null` if no repository can be identified.
*
* @return string|null Repository name, or null if no repository can be
* identified.
*
* @task phabrep
*/
final protected function getRepositoryName() {
return idx($this->getRepositoryInformation(), 'name');
}
/**
* Get the URI of the Phabricator repository this working copy
* corresponds to. Returns `null` if no repository can be identified.
*
* @return string|null Repository URI, or null if no repository can be
* identified.
*
* @task phabrep
*/
final protected function getRepositoryURI() {
return idx($this->getRepositoryInformation(), 'uri');
}
final protected function getRepositoryStagingConfiguration() {
return idx($this->getRepositoryInformation(), 'staging');
}
/**
* Get human-readable reasoning explaining how `arc` evaluated which
* Phabricator repository corresponds to this working copy. Used by
* `arc which` to explain the process to users.
*
* @return list<string> Human-readable explanation of the repository
* association process.
*
* @task phabrep
*/
final protected function getRepositoryReasons() {
$this->getRepositoryInformation();
return $this->repositoryReasons;
}
/**
* @task phabrep
*/
private function getRepositoryInformation() {
if ($this->repositoryInfo === null) {
list($info, $reasons) = $this->loadRepositoryInformation();
$this->repositoryInfo = nonempty($info, array());
$this->repositoryReasons = $reasons;
}
return $this->repositoryInfo;
}
/**
* @task phabrep
*/
private function loadRepositoryInformation() {
list($query, $reasons) = $this->getRepositoryQuery();
if (!$query) {
return array(null, $reasons);
}
try {
$method = 'repository.query';
$results = $this->getConduitEngine()
->newFuture($method, $query)
->resolve();
} catch (ConduitClientException $ex) {
if ($ex->getErrorCode() == 'ERR-CONDUIT-CALL') {
$reasons[] = pht(
'This software version on the server you are connecting to is out '.
'of date and does not have support for identifying repositories '.
'by callsign or URI. Update the server sofwware to enable these '.
'features.');
return array(null, $reasons);
}
throw $ex;
}
$result = null;
if (!$results) {
$reasons[] = pht(
'No repositories matched the query. Check that your configuration '.
'is correct, or use "%s" to select a repository explicitly.',
'repository.callsign');
} else if (count($results) > 1) {
$reasons[] = pht(
'Multiple repostories (%s) matched the query. You can use the '.
'"%s" configuration to select the one you want.',
implode(', ', ipull($results, 'callsign')),
'repository.callsign');
} else {
$result = head($results);
$reasons[] = pht('Found a unique matching repository.');
}
return array($result, $reasons);
}
/**
* @task phabrep
*/
private function getRepositoryQuery() {
$reasons = array();
$callsign = $this->getConfigFromAnySource('repository.callsign');
if ($callsign) {
$query = array(
'callsigns' => array($callsign),
);
$reasons[] = pht(
'Configuration value "%s" is set to "%s".',
'repository.callsign',
$callsign);
return array($query, $reasons);
} else {
$reasons[] = pht(
'Configuration value "%s" is empty.',
'repository.callsign');
}
$uuid = $this->getRepositoryAPI()->getRepositoryUUID();
if ($uuid !== null) {
$query = array(
'uuids' => array($uuid),
);
$reasons[] = pht(
'The UUID for this working copy is "%s".',
$uuid);
return array($query, $reasons);
} else {
$reasons[] = pht(
'This repository has no VCS UUID (this is normal for git/hg).');
}
// TODO: Swap this for a RemoteRefQuery.
$remote_uri = $this->getRepositoryAPI()->getRemoteURI();
if ($remote_uri !== null) {
$query = array(
'remoteURIs' => array($remote_uri),
);
$reasons[] = pht(
'The remote URI for this working copy is "%s".',
$remote_uri);
return array($query, $reasons);
} else {
$reasons[] = pht(
'Unable to determine the remote URI for this repository.');
}
return array(null, $reasons);
}
/**
* Build a new lint engine for the current working copy.
*
* Optionally, you can pass an explicit engine class name to build an engine
* of a particular class. Normally this is used to implement an `--engine`
* flag from the CLI.
*
* @param string Optional explicit engine class name.
* @return ArcanistLintEngine Constructed engine.
*/
protected function newLintEngine($engine_class = null) {
$working_copy = $this->getWorkingCopyIdentity();
$config = $this->getConfigurationManager();
if (!$engine_class) {
$engine_class = $config->getConfigFromAnySource('lint.engine');
}
if (!$engine_class) {
if (Filesystem::pathExists($working_copy->getProjectPath('.arclint'))) {
$engine_class = 'ArcanistConfigurationDrivenLintEngine';
}
}
if (!$engine_class) {
throw new ArcanistNoEngineException(
pht(
"No lint engine is configured for this project. Create an '%s' ".
"file, or configure an advanced engine with '%s' in '%s'.",
'.arclint',
'lint.engine',
'.arcconfig'));
}
$base_class = 'ArcanistLintEngine';
if (!class_exists($engine_class) ||
!is_subclass_of($engine_class, $base_class)) {
throw new ArcanistUsageException(
pht(
'Configured lint engine "%s" is not a subclass of "%s", but must be.',
$engine_class,
$base_class));
}
$engine = newv($engine_class, array())
->setWorkingCopy($working_copy)
->setConfigurationManager($config);
return $engine;
}
/**
* Build a new unit test engine for the current working copy.
*
* Optionally, you can pass an explicit engine class name to build an engine
* of a particular class. Normally this is used to implement an `--engine`
* flag from the CLI.
*
* @param string Optional explicit engine class name.
* @return ArcanistUnitTestEngine Constructed engine.
*/
protected function newUnitTestEngine($engine_class = null) {
$working_copy = $this->getWorkingCopyIdentity();
$config = $this->getConfigurationManager();
if (!$engine_class) {
$engine_class = $config->getConfigFromAnySource('unit.engine');
}
if (!$engine_class) {
if (Filesystem::pathExists($working_copy->getProjectPath('.arcunit'))) {
$engine_class = 'ArcanistConfigurationDrivenUnitTestEngine';
}
}
if (!$engine_class) {
throw new ArcanistNoEngineException(
pht(
"No unit test engine is configured for this project. Create an ".
"'%s' file, or configure an advanced engine with '%s' in '%s'.",
'.arcunit',
'unit.engine',
'.arcconfig'));
}
$base_class = 'ArcanistUnitTestEngine';
if (!class_exists($engine_class) ||
!is_subclass_of($engine_class, $base_class)) {
throw new ArcanistUsageException(
pht(
'Configured unit test engine "%s" is not a subclass of "%s", '.
'but must be.',
$engine_class,
$base_class));
}
$engine = newv($engine_class, array())
->setWorkingCopy($working_copy)
->setConfigurationManager($config);
return $engine;
}
protected function openURIsInBrowser(array $uris) {
$browser = $this->getBrowserCommand();
// The "browser" may actually be a list of arguments.
if (!is_array($browser)) {
$browser = array($browser);
}
foreach ($uris as $uri) {
$err = phutil_passthru('%LR %R', $browser, $uri);
if ($err) {
throw new ArcanistUsageException(
pht(
'Failed to open URI "%s" in browser ("%s"). '.
'Check your "browser" config option.',
$uri,
implode(' ', $browser)));
}
}
}
private function getBrowserCommand() {
$config = $this->getConfigFromAnySource('browser');
if ($config) {
return $config;
}
if (phutil_is_windows()) {
// See T13504. We now use "bypass_shell", so "start" alone is no longer
// a valid binary to invoke directly.
return array(
'cmd',
'/c',
'start',
);
}
$candidates = array(
'sensible-browser' => array('sensible-browser'),
'xdg-open' => array('xdg-open'),
'open' => array('open', '--'),
);
// NOTE: The "open" command works well on OS X, but on many Linuxes "open"
// exists and is not a browser. For now, we're just looking for other
// commands first, but we might want to be smarter about selecting "open"
// only on OS X.
foreach ($candidates as $cmd => $argv) {
if (Filesystem::binaryExists($cmd)) {
return $argv;
}
}
throw new ArcanistUsageException(
pht(
'Unable to find a browser command to run. Set "browser" in your '.
'configuration to specify a command to use.'));
}
/**
* Ask Phabricator to update the current repository as soon as possible.
*
* Calling this method after pushing commits allows Phabricator to discover
* the commits more quickly, so the system overall is more responsive.
*
* @return void
*/
protected function askForRepositoryUpdate() {
// If we know which repository we're in, try to tell Phabricator that we
// pushed commits to it so it can update. This hint can help pull updates
// more quickly, especially in rarely-used repositories.
if ($this->getRepositoryPHID()) {
try {
$this->getConduit()->callMethodSynchronous(
'diffusion.looksoon',
array(
'repositories' => array($this->getRepositoryPHID()),
));
} catch (ConduitClientException $ex) {
// If we hit an exception, just ignore it. Likely, we are running
// against a Phabricator which is too old to support this method.
// Since this hint is purely advisory, it doesn't matter if it has
// no effect.
}
}
}
protected function getModernLintDictionary(array $map) {
$map = $this->getModernCommonDictionary($map);
return $map;
}
protected function getModernUnitDictionary(array $map) {
$map = $this->getModernCommonDictionary($map);
$details = idx($map, 'userData');
if (strlen($details)) {
$map['details'] = (string)$details;
}
unset($map['userData']);
return $map;
}
private function getModernCommonDictionary(array $map) {
foreach ($map as $key => $value) {
if ($value === null) {
unset($map[$key]);
}
}
return $map;
}
final public function setConduitEngine(
ArcanistConduitEngine $conduit_engine) {
$this->conduitEngine = $conduit_engine;
return $this;
}
final public function getConduitEngine() {
return $this->conduitEngine;
}
final public function getRepositoryRef() {
$configuration_engine = $this->getConfigurationEngine();
if ($configuration_engine) {
// This is a toolset workflow and can always build a repository ref.
} else {
if (!$this->getConfigurationManager()->getWorkingCopyIdentity()) {
return null;
}
if (!$this->repositoryAPI) {
return null;
}
}
if (!$this->repositoryRef) {
$ref = id(new ArcanistRepositoryRef())
->setPHID($this->getRepositoryPHID())
->setBrowseURI($this->getRepositoryURI());
$this->repositoryRef = $ref;
}
return $this->repositoryRef;
}
final public function getToolsetKey() {
return $this->getToolset()->getToolsetKey();
}
final public function getConfig($key) {
return $this->getConfigurationSourceList()->getConfig($key);
}
public function canHandleSignal($signo) {
return false;
}
public function handleSignal($signo) {
return;
}
final public function newCommand(PhutilExecutableFuture $future) {
return id(new ArcanistCommand())
->setLogEngine($this->getLogEngine())
->setExecutableFuture($future);
}
final public function loadHardpoints(
$objects,
$requests) {
return $this->getRuntime()->loadHardpoints($objects, $requests);
}
protected function newPrompts() {
return array();
}
protected function newPrompt($key) {
return id(new ArcanistPrompt())
->setWorkflow($this)
->setKey($key);
}
public function hasPrompt($key) {
$map = $this->getPromptMap();
return isset($map[$key]);
}
public function getPromptMap() {
if ($this->promptMap === null) {
$prompts = $this->newPrompts();
assert_instances_of($prompts, 'ArcanistPrompt');
// TODO: Move this somewhere modular.
$prompts[] = $this->newPrompt('arc.state.stash')
->setDescription(
pht(
'Prompts the user to stash changes and continue when the '.
'working copy has untracked, uncommitted, or unstaged '.
'changes.'));
// TODO: Swap to ArrayCheck?
$map = array();
foreach ($prompts as $prompt) {
$key = $prompt->getKey();
if (isset($map[$key])) {
throw new Exception(
pht(
'Workflow ("%s") generates two prompts with the same '.
'key ("%s"). Each prompt a workflow generates must have a '.
'unique key.',
get_class($this),
$key));
}
$map[$key] = $prompt;
}
$this->promptMap = $map;
}
return $this->promptMap;
}
final public function getPrompt($key) {
$map = $this->getPromptMap();
$prompt = idx($map, $key);
if (!$prompt) {
throw new Exception(
pht(
'Workflow ("%s") is requesting a prompt ("%s") but it did not '.
'generate any prompt with that name in "newPrompts()".',
get_class($this),
$key));
}
return clone $prompt;
}
final protected function getSymbolEngine() {
return $this->getRuntime()->getSymbolEngine();
}
final protected function getViewer() {
return $this->getRuntime()->getViewer();
}
final protected function readStdin() {
$log = $this->getLogEngine();
$log->writeWaitingForInput();
// NOTE: We can't just "file_get_contents()" here because signals don't
// interrupt it. If the user types "^C", we want to interrupt the read.
$raw_handle = fopen('php://stdin', 'rb');
$stdin = new PhutilSocketChannel($raw_handle);
while ($stdin->update()) {
PhutilChannel::waitForAny(array($stdin));
}
return $stdin->read();
}
final public function getAbsoluteURI($raw_uri) {
// TODO: "ArcanistRevisionRef", at least, may return a relative URI.
// If we get a relative URI, guess the correct absolute URI based on
// the Conduit URI. This might not be correct for Conduit over SSH.
$raw_uri = new PhutilURI($raw_uri);
if (!strlen($raw_uri->getDomain())) {
$base_uri = $this->getConduitEngine()
->getConduitURI();
$raw_uri = id(new PhutilURI($base_uri))
->setPath($raw_uri->getPath());
}
$raw_uri = phutil_string_cast($raw_uri);
return $raw_uri;
}
final public function writeToPager($corpus) {
$is_tty = (function_exists('posix_isatty') && posix_isatty(STDOUT));
if (!$is_tty) {
echo $corpus;
} else {
$pager = $this->getConfig('pager');
if (!$pager) {
$pager = array('less', '-R', '--');
}
// Try to show the content through a pager.
$err = id(new PhutilExecPassthru('%Ls', $pager))
->write($corpus)
->resolve();
// If the pager exits with an error, print the content normally.
if ($err) {
echo $corpus;
}
}
return $this;
}
}

File Metadata

Mime Type
text/x-diff
Expires
Sun, Jan 19, 14:42 (3 w, 2 d ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1125614
Default Alt Text
(239 KB)

Event Timeline