diff --git a/src/internationalization/ArcanistUSEnglishTranslation.php b/src/internationalization/ArcanistUSEnglishTranslation.php index e83e099e..f8d01ee9 100644 --- a/src/internationalization/ArcanistUSEnglishTranslation.php +++ b/src/internationalization/ArcanistUSEnglishTranslation.php @@ -1,89 +1,87 @@ array( 'A locally modified path is not included in this revision:', 'Locally modified paths are not included in this revision:', ), 'These %s path(s) will NOT be committed. Commit this revision '. 'anyway?' => array( 'This path will NOT be committed. Commit this revision anyway?', 'These paths will NOT be committed. Commit this revision anyway?', ), 'Revision includes changes to %s path(s) that do not exist:' => array( 'Revision includes changes to a path that does not exist:', 'Revision includes changes to paths that do not exist:', ), '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.' => array( 'This diff includes a file which is not valid UTF-8 (it has invalid '. 'byte sequences). You can either stop this workflow and fix it, or '. 'continue. If you continue, this file will be marked as binary.', 'This diff includes files 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.', ), - '%d AFFECTED FILE(S)' => array('AFFECTED FILE', 'AFFECTED FILES'), + '%s AFFECTED FILE(S)' => array('AFFECTED FILE', 'AFFECTED FILES'), 'Do you want to mark these %s file(s) as binary and continue?' => array( 'Do you want to mark this file as binary and continue?', 'Do you want to mark these files as binary and continue?', ), 'Do you want to amend these %s change(s) to the current commit?' => array( 'Do you want to amend this change to the current commit?', 'Do you want to amend these changes to the current commit?', ), 'Do you want to create a new commit with these %s change(s)?' => array( 'Do you want to create a new commit with this change?', 'Do you want to create a new commit with these changes?', ), '(To ignore these %s change(s), add them to "%s".)' => array( '(To ignore this change, add it to "%2$s".)', '(To ignore these changes, add them to "%2$s".)', ), '%s line(s)' => array('line', 'lines'), - '%d test(s)' => array('%d test', '%d tests'), - - '%d assertion(s) passed.' => array( - '%d assertion passed.', - '%d assertions passed.', + '%s assertion(s) passed.' => array( + '%s assertion passed.', + '%s assertions passed.', ), 'Ignore these %s untracked file(s) and continue?' => array( 'Ignore this untracked file and continue?', 'Ignore these untracked files and continue?', ), '%s submodule(s) have uncommitted or untracked changes:' => array( 'A submodule has uncommitted or untracked changes:', 'Submodules have uncommitted or untracked changes:', ), 'Ignore the changes to these %s submodule(s) and continue?' => array( 'Ignore the changes to this submodule and continue?', 'Ignore the changes to these submodules and continue?', ), 'These %s commit(s) will be landed:' => array( 'This commit will be landed:', 'These commits will be landed:', ), ); } } diff --git a/src/unit/engine/phutil/PhutilTestCase.php b/src/unit/engine/phutil/PhutilTestCase.php index 911ebbc8..f16d9f2b 100644 --- a/src/unit/engine/phutil/PhutilTestCase.php +++ b/src/unit/engine/phutil/PhutilTestCase.php @@ -1,748 +1,751 @@ assertions++; return; } $this->failAssertionWithExpectedValue('false', $result, $message); } /** * Assert that a value is `true`, strictly. The test fails if it is not. * * @param wild The empirically derived value, generated by executing the * test. * @param string A human-readable description of what these values represent, * and particularly of what a discrepancy means. * * @return void * @task assert */ final protected function assertTrue($result, $message = null) { if ($result === true) { $this->assertions++; return; } $this->failAssertionWithExpectedValue('true', $result, $message); } /** * Assert that two values are equal, strictly. The test fails if they are not. * * NOTE: This method uses PHP's strict equality test operator (`===`) to * compare values. This means values and types must be equal, key order must * be identical in arrays, and objects must be referentially identical. * * @param wild The theoretically expected value, generated by careful * reasoning about the properties of the system. * @param wild The empirically derived value, generated by executing the * test. * @param string A human-readable description of what these values represent, * and particularly of what a discrepancy means. * * @return void * @task assert */ final protected function assertEqual($expect, $result, $message = null) { if ($expect === $result) { $this->assertions++; return; } $expect = PhutilReadableSerializer::printableValue($expect); $result = PhutilReadableSerializer::printableValue($result); $caller = self::getCallerInfo(); $file = $caller['file']; $line = $caller['line']; if ($message !== null) { $output = pht( 'Assertion failed, expected values to be equal (at %s:%d): %s', $file, $line, $message); } else { $output = pht( 'Assertion failed, expected values to be equal (at %s:%d).', $file, $line); } $output .= "\n"; if (strpos($expect, "\n") === false && strpos($result, "\n") === false) { $output .= pht("Expected: %s\n Actual: %s", $expect, $result); } else { $output .= pht( "Expected vs Actual Output Diff\n%s", ArcanistDiffUtils::renderDifferences( $expect, $result, $lines = 0xFFFF)); } $this->failTest($output); throw new PhutilTestTerminatedException($output); } /** * Assert an unconditional failure. This is just a convenience method that * better indicates intent than using dummy values with assertEqual(). This * causes test failure. * * @param string Human-readable description of the reason for test failure. * @return void * @task assert */ final protected function assertFailure($message) { $this->failTest($message); throw new PhutilTestTerminatedException($message); } /** * End this test by asserting that the test should be skipped for some * reason. * * @param string Reason for skipping this test. * @return void * @task assert */ final protected function assertSkipped($message) { $this->skipTest($message); throw new PhutilTestSkippedException($message); } /* -( Exception Handling )------------------------------------------------- */ /** * This simplest way to assert exceptions are thrown. * * @param exception The expected exception. * @param callable The thing which throws the exception. * * @return void * @task exceptions */ final protected function assertException( $expected_exception_class, $callable) { $this->tryTestCases( array('assertException' => array()), array(false), $callable, $expected_exception_class); } /** * Straightforward method for writing unit tests which check if some block of * code throws an exception. For example, this allows you to test the * exception behavior of ##is_a_fruit()## on various inputs: * * public function testFruit() { * $this->tryTestCases( * array( * 'apple is a fruit' => new Apple(), * 'rock is not a fruit' => new Rock(), * ), * array( * true, * false, * ), * array($this, 'tryIsAFruit'), * 'NotAFruitException'); * } * * protected function tryIsAFruit($input) { * is_a_fruit($input); * } * * @param map Map of test case labels to test case inputs. * @param list List of expected results, true to indicate that the case * is expected to succeed and false to indicate that the case * is expected to throw. * @param callable Callback to invoke for each test case. * @param string Optional exception class to catch, defaults to * 'Exception'. * @return void * @task exceptions */ final protected function tryTestCases( array $inputs, array $expect, $callable, $exception_class = 'Exception') { if (count($inputs) !== count($expect)) { $this->assertFailure( pht('Input and expectations must have the same number of values.')); } $labels = array_keys($inputs); $inputs = array_values($inputs); $expecting = array_values($expect); foreach ($inputs as $idx => $input) { $expect = $expecting[$idx]; $label = $labels[$idx]; $caught = null; try { call_user_func($callable, $input); } catch (Exception $ex) { if ($ex instanceof PhutilTestTerminatedException) { throw $ex; } if (!($ex instanceof $exception_class)) { throw $ex; } $caught = $ex; } $actual = !($caught instanceof Exception); if ($expect === $actual) { if ($expect) { $message = pht("Test case '%s' did not throw, as expected.", $label); } else { $message = pht("Test case '%s' threw, as expected.", $label); } } else { if ($expect) { $message = pht( "Test case '%s' was expected to succeed, but it ". "raised an exception of class %s with message: %s", $label, get_class($ex), $ex->getMessage()); } else { $message = pht( "Test case '%s' was expected to raise an ". "exception, but it did not throw anything.", $label); } } $this->assertEqual($expect, $actual, $message); } } /** * Convenience wrapper around @{method:tryTestCases} for cases where your * inputs are scalar. For example: * * public function testFruit() { * $this->tryTestCaseMap( * array( * 'apple' => true, * 'rock' => false, * ), * array($this, 'tryIsAFruit'), * 'NotAFruitException'); * } * * protected function tryIsAFruit($input) { * is_a_fruit($input); * } * * For cases where your inputs are not scalar, use @{method:tryTestCases}. * * @param map Map of scalar test inputs to expected success (true * expects success, false expects an exception). * @param callable Callback to invoke for each test case. * @param string Optional exception class to catch, defaults to * 'Exception'. * @return void * @task exceptions */ final protected function tryTestCaseMap( array $map, $callable, $exception_class = 'Exception') { return $this->tryTestCases( array_fuse(array_keys($map)), array_values($map), $callable, $exception_class); } /* -( Hooks for Setup and Teardown )--------------------------------------- */ /** * This hook is invoked once, before any tests in this class are run. It * gives you an opportunity to perform setup steps for the entire class. * * @return void * @task hook */ protected function willRunTests() { return; } /** * This hook is invoked once, after any tests in this class are run. It gives * you an opportunity to perform teardown steps for the entire class. * * @return void * @task hook */ protected function didRunTests() { return; } /** * This hook is invoked once per test, before the test method is invoked. * * @param string Method name of the test which will be invoked. * @return void * @task hook */ protected function willRunOneTest($test_method_name) { return; } /** * This hook is invoked once per test, after the test method is invoked. * * @param string Method name of the test which was invoked. * @return void * @task hook */ protected function didRunOneTest($test_method_name) { return; } /** * This hook is invoked once, before any test cases execute. It gives you * an opportunity to perform setup steps for the entire suite of test cases. * * @param list List of test cases to be run. * @return void * @task hook */ public function willRunTestCases(array $test_cases) { return; } /** * This hook is invoked once, after all test cases execute. * * @param list List of test cases that ran. * @return void * @task hook */ public function didRunTestCases(array $test_cases) { return; } /* -( Internals )---------------------------------------------------------- */ /** * Construct a new test case. This method is ##final##, use willRunTests() to * provide test-wide setup logic. * * @task internal */ final public function __construct() {} /** * Mark the currently-running test as a failure. * * @param string Human-readable description of problems. * @return void * * @task internal */ final private function failTest($reason) { $this->resultTest(ArcanistUnitTestResult::RESULT_FAIL, $reason); } /** * This was a triumph. I'm making a note here: HUGE SUCCESS. * * @param string Human-readable overstatement of satisfaction. * @return void * * @task internal */ final private function passTest($reason) { $this->resultTest(ArcanistUnitTestResult::RESULT_PASS, $reason); } /** * Mark the current running test as skipped. * * @param string Description for why this test was skipped. * @return void * @task internal */ final private function skipTest($reason) { $this->resultTest(ArcanistUnitTestResult::RESULT_SKIP, $reason); } final private function resultTest($test_result, $reason) { $coverage = $this->endCoverage(); $result = new ArcanistUnitTestResult(); $result->setCoverage($coverage); $result->setNamespace(get_class($this)); $result->setName($this->runningTest); $result->setLink($this->getLink($this->runningTest)); $result->setResult($test_result); $result->setDuration(microtime(true) - $this->testStartTime); $result->setUserData($reason); $this->results[] = $result; if ($this->renderer) { echo $this->renderer->renderUnitResult($result); } } /** * Execute the tests in this test case. You should not call this directly; * use @{class:PhutilUnitTestEngine} to orchestrate test execution. * * @return void * @task internal */ final public function run() { $this->results = array(); $reflection = new ReflectionClass($this); $methods = $reflection->getMethods(); // Try to ensure that poorly-written tests which depend on execution order // (and are thus not properly isolated) will fail. shuffle($methods); $this->willRunTests(); foreach ($methods as $method) { $name = $method->getName(); if (preg_match('/^test/', $name)) { $this->runningTest = $name; $this->assertions = 0; $this->testStartTime = microtime(true); try { $this->willRunOneTest($name); $this->beginCoverage(); $exceptions = array(); try { call_user_func_array( array($this, $name), array()); - $this->passTest(pht('%d assertion(s) passed.', $this->assertions)); + $this->passTest( + pht( + '%s assertion(s) passed.', + new PhutilNumber($this->assertions))); } catch (Exception $ex) { $exceptions['Execution'] = $ex; } try { $this->didRunOneTest($name); } catch (Exception $ex) { $exceptions['Shutdown'] = $ex; } if ($exceptions) { if (count($exceptions) == 1) { throw head($exceptions); } else { throw new PhutilAggregateException( pht('Multiple exceptions were raised during test execution.'), $exceptions); } } if (!$this->assertions) { $this->failTest( pht( 'This test case made no assertions. Test cases must make at '. 'least one assertion.')); } } catch (PhutilTestTerminatedException $ex) { // Continue with the next test. } catch (PhutilTestSkippedException $ex) { // Continue with the next test. } catch (Exception $ex) { $ex_class = get_class($ex); $ex_message = $ex->getMessage(); $ex_trace = $ex->getTraceAsString(); $message = sprintf( "%s (%s): %s\n%s", pht('EXCEPTION'), $ex_class, $ex_message, $ex_trace); $this->failTest($message); } } } $this->didRunTests(); return $this->results; } final public function setEnableCoverage($enable_coverage) { $this->enableCoverage = $enable_coverage; return $this; } /** * @phutil-external-symbol function xdebug_start_code_coverage */ final private function beginCoverage() { if (!$this->enableCoverage) { return; } $this->assertCoverageAvailable(); xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE); } /** * @phutil-external-symbol function xdebug_get_code_coverage * @phutil-external-symbol function xdebug_stop_code_coverage */ final private function endCoverage() { if (!$this->enableCoverage) { return; } $result = xdebug_get_code_coverage(); xdebug_stop_code_coverage($cleanup = false); $coverage = array(); foreach ($result as $file => $report) { $project_root = $this->getProjectRoot(); if (strncmp($file, $project_root, strlen($project_root))) { continue; } $max = max(array_keys($report)); $str = ''; for ($ii = 1; $ii <= $max; $ii++) { $c = null; if (isset($report[$ii])) { $c = $report[$ii]; } if ($c === -1) { $str .= 'U'; // Un-covered. } else if ($c === -2) { // TODO: This indicates "unreachable", but it flags the closing braces // of functions which end in "return", which is super ridiculous. Just // ignore it for now. // // See http://bugs.xdebug.org/view.php?id=1041 $str .= 'N'; // Not executable. } else if ($c === 1) { $str .= 'C'; // Covered. } else { $str .= 'N'; // Not executable. } } $coverage[substr($file, strlen($project_root) + 1)] = $str; } // Only keep coverage information for files modified by the change. In // the case of --everything, we won't have paths, so just return all the // coverage data. if ($this->paths) { $coverage = array_select_keys($coverage, $this->paths); } return $coverage; } final private function assertCoverageAvailable() { if (!function_exists('xdebug_start_code_coverage')) { throw new Exception( pht("You've enabled code coverage but XDebug is not installed.")); } } final public function getWorkingCopy() { return $this->workingCopy; } final public function setWorkingCopy( ArcanistWorkingCopyIdentity $working_copy) { $this->workingCopy = $working_copy; return $this; } final public function getProjectRoot() { $working_copy = $this->getWorkingCopy(); if (!$working_copy) { throw new PhutilInvalidStateException('setWorkingCopy'); } return $working_copy->getProjectRoot(); } final public function setPaths(array $paths) { $this->paths = $paths; return $this; } final protected function getLink($method) { $base_uri = $this ->getWorkingCopy() ->getProjectConfig('phabricator.uri'); $uri = id(new PhutilURI($base_uri)) ->setPath("/diffusion/symbol/{$method}/") ->setQueryParam('context', get_class($this)) ->setQueryParam('jump', 'true') ->setQueryParam('lang', 'php'); return (string)$uri; } final public function setRenderer(ArcanistUnitRenderer $renderer) { $this->renderer = $renderer; return $this; } /** * Returns info about the caller function. * * @return map */ final private static function getCallerInfo() { $callee = array(); $caller = array(); $seen = false; foreach (array_slice(debug_backtrace(), 1) as $location) { $function = idx($location, 'function'); if (!$seen && preg_match('/^assert[A-Z]/', $function)) { $seen = true; $caller = $location; } else if ($seen && !preg_match('/^assert[A-Z]/', $function)) { $callee = $location; break; } } return array( 'file' => basename(idx($caller, 'file')), 'line' => idx($caller, 'line'), 'function' => idx($callee, 'function'), 'class' => idx($callee, 'class'), 'object' => idx($caller, 'object'), 'type' => idx($callee, 'type'), 'args' => idx($caller, 'args'), ); } /** * Fail an assertion which checks that some result is equal to a specific * value, like 'true' or 'false'. This prints a readable error message and * fails the current test. * * This method throws and does not return. * * @param string Human readable description of the expected value. * @param string The actual value. * @param string|null Optional assertion message. * @return void * @task internal */ private function failAssertionWithExpectedValue( $expect_description, $actual_result, $message) { $caller = self::getCallerInfo(); $file = $caller['file']; $line = $caller['line']; if ($message !== null) { $description = pht( "Assertion failed, expected '%s' (at %s:%d): %s", $expect_description, $file, $line, $message); } else { $description = pht( "Assertion failed, expected '%s' (at %s:%d).", $expect_description, $file, $line); } $actual_result = PhutilReadableSerializer::printableValue($actual_result); $header = pht('ACTUAL VALUE'); $output = $description."\n\n".$header."\n".$actual_result; $this->failTest($output); throw new PhutilTestTerminatedException($output); } } diff --git a/src/upload/ArcanistFileUploader.php b/src/upload/ArcanistFileUploader.php index 27ec8d34..d8c65a43 100644 --- a/src/upload/ArcanistFileUploader.php +++ b/src/upload/ArcanistFileUploader.php @@ -1,313 +1,313 @@ setConduitClient($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 $conduit; private $files; /* -( Configuring the Uploader )------------------------------------------- */ /** * Provide a Conduit client to choose which server to upload files to. * * @param ConduitClient Configured client. * @return this * @task config */ public function setConduitClient(ConduitClient $conduit) { $this->conduit = $conduit; 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:setConduitClient}. * * 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 Files with results populated. * @task upload */ public function uploadFiles() { if (!$this->conduit) { throw new PhutilInvalidStateException('setConduitClient'); } $files = $this->files; foreach ($files as $key => $file) { try { $file->willUpload(); } catch (Exception $ex) { $file->didFail($ex->getMessage()); unset($files[$key]); } } $conduit = $this->conduit; $futures = array(); foreach ($files as $key => $file) { $params = array( 'name' => $file->getName(), 'contentLength' => $file->getByteSize(), 'contentHash' => $file->getContentHash(), ); $delete_after = $file->getDeleteAfterEpoch(); if ($delete_after !== null) { $params['deleteAfterEpoch'] = $delete_after; } $view_policy = $file->getViewPolicy(); if ($view_policy !== null) { $params['viewPolicy'] = $view_policy; } $futures[$key] = $conduit->callMethod('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->conduit; $chunks = $conduit->callMethodSynchronous( 'file.querychunks', array( 'filePHID' => $file_phid, )); $remaining = array(); foreach ($chunks as $chunk) { if (!$chunk['complete']) { $remaining[] = $chunk; } } $done = (count($chunks) - count($remaining)); if ($done) { $this->writeStatus( pht( - 'Resuming upload (%d of %d chunks remain).', - new PhutilNumber(count($remaining)), - new PhutilNumber(count($chunks)))); + 'Resuming upload (%s of %s chunks remain).', + phutil_count($remaining), + phutil_count($chunks))); } else { $this->writeStatus( pht( - 'Uploading chunks (%d chunks to upload).', - new PhutilNumber(count($remaining)))); + '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']); $conduit->callMethodSynchronous( 'file.uploadchunk', array( 'filePHID' => $file_phid, 'byteStart' => $chunk['byteStart'], 'dataEncoding' => 'base64', 'data' => base64_encode($data), )); $progress->update(1); } } /** * Upload an entire file by calling `file.upload` over Conduit. * * @task internal */ private function uploadData(ArcanistFileDataRef $file) { $conduit = $this->conduit; $data = $file->readBytes(0, $file->getByteSize()); return $conduit->callMethodSynchronous( 'file.upload', array( 'name' => $file->getName(), 'data_base64' => base64_encode($data), )); } /** * Write a status message. * * @task internal */ private function writeStatus($message) { fwrite(STDERR, $message."\n"); } } diff --git a/src/workflow/ArcanistCommitWorkflow.php b/src/workflow/ArcanistCommitWorkflow.php index e1c5a917..c0e91db3 100644 --- a/src/workflow/ArcanistCommitWorkflow.php +++ b/src/workflow/ArcanistCommitWorkflow.php @@ -1,352 +1,352 @@ revisionID; } public function getArguments() { return array( 'show' => array( 'help' => pht( 'Show the command which would be issued, but do not actually '. 'commit anything.'), ), 'revision' => array( 'param' => 'revision_id', 'help' => pht( 'Commit a specific revision. If you do not specify a revision, '. 'arc will look for committable revisions.'), ), ); } public function run() { $repository_api = $this->getRepositoryAPI(); $revision_id = $this->normalizeRevisionID($this->getArgument('revision')); if (!$revision_id) { $revisions = $repository_api->loadWorkingCopyDifferentialRevisions( $this->getConduit(), array( 'authors' => array($this->getUserPHID()), 'status' => 'status-accepted', )); if (count($revisions) == 0) { throw new ArcanistUsageException( pht( "Unable to identify the revision in the working copy. Use ". "'%s' to select a revision.", '--revision ')); } else if (count($revisions) > 1) { throw new ArcanistUsageException( pht( "More than one revision exists in the working copy:\n\n%s\n". "Use '%s' to select a revision.", $this->renderRevisionList($revisions), '--revision ')); } } else { $revisions = $this->getConduit()->callMethodSynchronous( 'differential.query', array( 'ids' => array($revision_id), )); if (count($revisions) == 0) { throw new ArcanistUsageException( pht( "Revision '%s' does not exist.", "D{$revision_id}")); } } $revision = head($revisions); $this->revisionID = $revision['id']; $revision_id = $revision['id']; $is_show = $this->getArgument('show'); if (!$is_show) { $this->runSanityChecks($revision); } $message = $this->getConduit()->callMethodSynchronous( 'differential.getcommitmessage', array( 'revision_id' => $revision_id, 'edit' => false, )); $event = $this->dispatchEvent( ArcanistEventType::TYPE_COMMIT_WILLCOMMITSVN, array( 'message' => $message, )); $message = $event->getValue('message'); if ($is_show) { echo $message."\n"; return 0; } $revision_title = $revision['title']; echo pht( "Committing '%s: %s'...\n", "D{$revision_id}", $revision_title); $files = $this->getCommitFileList($revision); $tmp_file = new TempFile(); Filesystem::writeFile($tmp_file, $message); $command = csprintf( 'svn commit %Ls --encoding utf-8 -F %s', $files, $tmp_file); // make sure to specify LANG on non-windows systems to suppress any fancy // warnings; see @{method:getSVNLangEnvVar}. if (!phutil_is_windows()) { $command = csprintf('LANG=%C %C', $this->getSVNLangEnvVar(), $command); } chdir($repository_api->getPath()); $err = phutil_passthru('%C', $command); if ($err) { throw new Exception(pht("Executing '%s' failed!", 'svn commit')); } $this->askForRepositoryUpdate(); $mark_workflow = $this->buildChildWorkflow( 'close-revision', array( '--finalize', $revision_id, )); $mark_workflow->run(); return $err; } protected function getCommitFileList(array $revision) { $repository_api = $this->getRepositoryAPI(); $revision_id = $revision['id']; $commit_paths = $this->getConduit()->callMethodSynchronous( 'differential.getcommitpaths', array( 'revision_id' => $revision_id, )); $dir_paths = array(); foreach ($commit_paths as $path) { $path = dirname($path); while ($path != '.') { $dir_paths[$path] = true; $path = dirname($path); } } $commit_paths = array_fill_keys($commit_paths, true); $status = $repository_api->getSVNStatus(); $modified_but_not_included = array(); foreach ($status as $path => $mask) { if (!empty($dir_paths[$path])) { $commit_paths[$path] = true; } if (!empty($commit_paths[$path])) { continue; } foreach ($commit_paths as $will_commit => $ignored) { if (Filesystem::isDescendant($path, $will_commit)) { throw new ArcanistUsageException( pht( "This commit includes the directory '%s', but it contains a ". "modified path ('%s') which is NOT included in the commit. ". "Subversion can not handle this operation and will commit the ". "path anyway. You need to sort out the working copy changes to ". "'%s' before you may proceed with the commit.", $will_commit, $path, $path)); } } $modified_but_not_included[] = $path; } if ($modified_but_not_included) { $prefix = pht( '%s locally modified path(s) are not included in this revision:', - new PhutilNumber(count($modified_but_not_included))); + phutil_count($modified_but_not_included)); $prompt = pht( 'These %s path(s) will NOT be committed. Commit this revision anyway?', - new PhutilNumber(count($modified_but_not_included))); + phutil_count($modified_but_not_included)); $this->promptFileWarning($prefix, $prompt, $modified_but_not_included); } $do_not_exist = array(); foreach ($commit_paths as $path => $ignored) { $disk_path = $repository_api->getPath($path); if (file_exists($disk_path)) { continue; } if (is_link($disk_path)) { continue; } if (idx($status, $path) & ArcanistRepositoryAPI::FLAG_DELETED) { continue; } $do_not_exist[] = $path; unset($commit_paths[$path]); } if ($do_not_exist) { $prefix = pht( 'Revision includes changes to %s path(s) that do not exist:', - new PhutilNumber(count($do_not_exist))); + phutil_count($do_not_exist)); $prompt = pht('Commit this revision anyway?'); $this->promptFileWarning($prefix, $prompt, $do_not_exist); } $files = array_keys($commit_paths); $files = ArcanistSubversionAPI::escapeFileNamesForSVN($files); if (empty($files)) { throw new ArcanistUsageException( pht( 'There is nothing left to commit. '. 'None of the modified paths exist.')); } return $files; } protected function promptFileWarning($prefix, $prompt, array $paths) { echo $prefix."\n\n"; foreach ($paths as $path) { echo " ".$path."\n"; } if (!phutil_console_confirm($prompt)) { throw new ArcanistUserAbortException(); } } public function getSupportedRevisionControlSystems() { return array('svn'); } /** * On some systems, we need to specify "en_US.UTF-8" instead of "en_US.utf8", * and SVN spews some bewildering warnings if we don't: * * svn: warning: cannot set LC_CTYPE locale * svn: warning: environment variable LANG is en_US.utf8 * svn: warning: please check that your locale name is correct * * For example, it happens on epriestley's Mac (10.6.7) with * Subversion 1.6.15. */ private function getSVNLangEnvVar() { $locale = 'en_US.utf8'; try { list($locales) = execx('locale -a'); $locales = explode("\n", trim($locales)); $locales = array_fill_keys($locales, true); if (isset($locales['en_US.UTF-8'])) { $locale = 'en_US.UTF-8'; } } catch (Exception $ex) { // Ignore. } return $locale; } private function runSanityChecks(array $revision) { $repository_api = $this->getRepositoryAPI(); $revision_id = $revision['id']; $revision_title = $revision['title']; $confirm = array(); if ($revision['status'] != ArcanistDifferentialRevisionStatus::ACCEPTED) { $confirm[] = pht( "Revision '%s: %s' has not been accepted. Commit this revision anyway?", "D{$revision_id}", $revision_title); } if ($revision['authorPHID'] != $this->getUserPHID()) { $confirm[] = pht( "You are not the author of '%s: %s'. Commit this revision anyway?", "D{$revision_id}", $revision_title); } $revision_source = idx($revision, 'branch'); $current_source = $repository_api->getBranchName(); if ($revision_source != $current_source) { $confirm[] = pht( "Revision '%s: %s' was generated from '%s', but current working ". "copy root is '%s'. Commit this revision anyway?", "D{$revision_id}", $revision_title, $revision_source, $current_source); } foreach ($confirm as $thing) { if (!phutil_console_confirm($thing)) { throw new ArcanistUserAbortException(); } } } } diff --git a/src/workflow/ArcanistCoverWorkflow.php b/src/workflow/ArcanistCoverWorkflow.php index 35c3c891..a9b188cf 100644 --- a/src/workflow/ArcanistCoverWorkflow.php +++ b/src/workflow/ArcanistCoverWorkflow.php @@ -1,172 +1,172 @@ array( 'param' => 'revision', 'help' => pht('Cover changes since a specific revision.'), 'supports' => array( 'git', 'hg', ), 'nosupport' => array( 'svn' => pht('cover does not currently support %s in svn.', '--rev'), ), ), '*' => 'paths', ); } public function requiresWorkingCopy() { return true; } public function requiresConduit() { return false; } public function requiresAuthentication() { return false; } public function requiresRepositoryAPI() { return true; } public function run() { $repository_api = $this->getRepositoryAPI(); $in_paths = $this->getArgument('paths'); $in_rev = $this->getArgument('rev'); if ($in_rev) { $this->parseBaseCommitArgument(array($in_rev)); } $paths = $this->selectPathsForWorkflow( $in_paths, $in_rev, ArcanistRepositoryAPI::FLAG_UNTRACKED | ArcanistRepositoryAPI::FLAG_ADDED); if (!$paths) { throw new ArcanistNoEffectException( pht("You're covered, you didn't change anything.")); } $covers = array(); foreach ($paths as $path) { if (is_dir($repository_api->getPath($path))) { continue; } $lines = $this->getChangedLines($path, 'cover'); if (!$lines) { continue; } $blame = $repository_api->getBlame($path); foreach ($lines as $line) { list($author, $revision) = idx($blame, $line, array(null, null)); if (!$author) { continue; } if (!isset($covers[$author])) { $covers[$author] = array(); } if (!isset($covers[$author][$path])) { $covers[$author][$path] = array( 'lines' => array(), 'revisions' => array(), ); } $covers[$author][$path]['lines'][] = $line; $covers[$author][$path]['revisions'][] = $revision; } } if (count($covers)) { foreach ($covers as $author => $files) { echo phutil_console_format( "**%s**\n", $author); foreach ($files as $file => $info) { $line_noun = pht( '%s line(s)', - new PhutilNumber(count($info['lines']))); + phutil_count($info['lines'])); $lines = $this->readableSequenceFromLineNumbers($info['lines']); echo " {$file}: {$line_noun} {$lines}\n"; } } } else { echo pht( "You're covered, your changes didn't touch anyone else's code.\n"); } return 0; } private function readableSequenceFromLineNumbers(array $array) { $sequence = array(); $last = null; $seq = null; $array = array_unique(array_map('intval', $array)); sort($array); foreach ($array as $element) { if ($seq !== null && $element == ($seq + 1)) { $seq++; continue; } if ($seq === null) { $last = $element; $seq = $element; continue; } if ($seq > $last) { $sequence[] = $last.'-'.$seq; } else { $sequence[] = $last; } $last = $element; $seq = $element; } if ($last !== null && $seq > $last) { $sequence[] = $last.'-'.$seq; } else if ($last !== null) { $sequence[] = $element; } return implode(', ', $sequence); } } diff --git a/src/workflow/ArcanistDiffWorkflow.php b/src/workflow/ArcanistDiffWorkflow.php index eeabfdfb..aeae0526 100644 --- a/src/workflow/ArcanistDiffWorkflow.php +++ b/src/workflow/ArcanistDiffWorkflow.php @@ -1,2780 +1,2780 @@ null, 'unit' => null); private $testResults; private $diffID; private $revisionID; private $haveUncommittedChanges = false; private $diffPropertyFutures = array(); private $commitMessageFromRevision; private $hitAutotargets; public function getWorkflowName() { return 'diff'; } public function getCommandSynopses() { return phutil_console_format(<<isRawDiffSource(); } public function requiresConduit() { return true; } public function requiresAuthentication() { return true; } public function requiresRepositoryAPI() { if (!$this->isRawDiffSource()) { return true; } if ($this->getArgument('use-commit-message')) { 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.'), ), 'use-commit-message' => array( 'supports' => array( 'git', // TODO: Support mercurial. ), 'short' => 'C', 'param' => 'commit', 'help' => pht('Read revision information from a specific commit.'), 'conflicts' => array( 'only' => null, 'preview' => null, 'update' => null, ), ), '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 Arcanist/Phabricator features which depend on having access '. 'to the working copy.'), 'conflicts' => array( 'less-context' => null, 'apply-patches' => pht('%s disables lint.', '--raw'), 'never-apply-patches' => pht('%s disables lint.', '--raw'), 'advice' => pht('%s disables lint.', '--raw'), 'lintall' => 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 Arcanist/Phabricator features '. 'which depend on having access to the working copy.'), 'conflicts' => array( 'less-context' => null, 'apply-patches' => pht('%s disables lint.', '--raw-command'), 'never-apply-patches' => pht('%s disables lint.', '--raw-command'), 'advice' => pht('%s disables lint.', '--raw-command'), 'lintall' => 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'), 'preview' => pht( '%s can not be used with %s.', '--create', '--preview'), 'update' => pht( '%s can not be used with %s.', '--create', '--update'), ), ), 'update' => array( 'param' => 'revision_id', 'help' => pht('Always update a specific revision.'), ), 'nounit' => array( 'help' => pht('Do not run unit tests.'), ), 'nolint' => array( 'help' => pht('Do not run lint.'), 'conflicts' => array( 'lintall' => pht('%s suppresses lint.', '--nolint'), 'advice' => pht('%s suppresses lint.', '--nolint'), 'apply-patches' => pht('%s suppresses lint.', '--nolint'), 'never-apply-patches' => pht('%s suppresses lint.', '--nolint'), ), ), 'only' => array( 'help' => pht( 'Only generate a diff, without running lint, unit tests, or other '. 'auxiliary steps. See also %s.', '--preview'), 'conflicts' => array( 'preview' => null, 'message' => pht('%s does not affect revisions.', '--only'), 'edit' => pht('%s does not affect revisions.', '--only'), 'lintall' => pht('%s suppresses lint.', '--only'), 'advice' => pht('%s suppresses lint.', '--only'), 'apply-patches' => pht('%s suppresses lint.', '--only'), 'never-apply-patches' => pht('%s suppresses lint.', '--only'), ), ), 'preview' => array( 'help' => pht( 'Instead of creating or updating a revision, only create a diff, '. 'which you may later attach to a revision. This still runs lint '. 'unit tests. See also %s.', '--only'), 'conflicts' => array( 'only' => null, 'edit' => pht('%s does affect revisions.', '--preview'), 'message' => pht('%s does not update any revision.', '--preview'), ), ), 'plan-changes' => array( 'help' => pht( 'Create or update a revision without requesting a code review.'), 'conflicts' => array( 'only' => pht('%s does not affect revisions.', '--only'), 'preview' => pht('%s does not affect revisions.', '--preview'), ), ), 'encoding' => array( 'param' => 'encoding', 'help' => pht( 'Attempt to convert non UTF-8 hunks into specified encoding.'), ), 'allow-untracked' => array( 'help' => pht('Skip checks for untracked files in the working copy.'), ), 'excuse' => array( 'param' => 'excuse', 'help' => pht( 'Provide a prepared in advance excuse for any lints/tests '. 'shall they fail.'), ), 'less-context' => array( 'help' => pht( "Normally, files are diffed with full context: the entire file is ". "sent to Differential so reviewers can 'show more' and see it. If ". "you are making changes to very large files with tens of thousands ". "of lines, this may not work well. With this flag, a diff will ". "be created that has only a few lines of context."), ), 'lintall' => array( 'help' => pht( 'Raise all lint warnings, not just those on lines you changed.'), 'passthru' => array( 'lint' => true, ), ), 'advice' => array( 'help' => pht( 'Require excuse for lint advice in addition to lint warnings and '. 'errors.'), ), 'only-new' => array( 'param' => 'bool', 'help' => pht( 'Display only lint messages not present in the original code.'), 'passthru' => array( 'lint' => true, ), ), '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( 'use-commit-message' => true, 'update' => true, 'only' => true, 'preview' => 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, 'preview' => true, 'update' => true, ), ), 'cc' => array( 'param' => 'usernames', 'help' => pht('When creating a revision, add CCs.'), 'conflicts' => array( 'only' => true, 'preview' => 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.'), ), 'ignore-unsound-tests' => array( 'help' => pht('Ignore unsound test failures without prompting.'), ), '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'), ), 'no-diff' => array( 'help' => pht( 'Only run lint and unit tests. Intended for internal use.'), ), 'cache' => array( 'param' => 'bool', 'help' => pht( '%d to disable lint cache, %d to enable (default).', 0, 1), 'passthru' => array( 'lint' => true, ), ), '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 '. 'Arcanist/Phabricator 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'), ), 'conflicts' => array( 'lintall' => pht('%s suppresses lint.', '--head'), 'advice' => pht('%s suppresses lint.', '--head'), ), ), ); return $arguments; } public function isRawDiffSource() { return $this->getArgument('raw') || $this->getArgument('raw-command'); } public function run() { $this->console = PhutilConsole::getConsole(); $this->runRepositoryAPISetup(); if ($this->getArgument('no-diff')) { $this->removeScratchFile('diff-result.json'); $data = $this->runLintUnit(); $this->writeScratchJSONFile('diff-result.json', $data); return 0; } $this->runDiffSetupBasics(); $commit_message = $this->buildCommitMessage(); $this->dispatchEvent( ArcanistEventType::TYPE_DIFF_DIDBUILDMESSAGE, array( 'message' => $commit_message, )); if (!$this->shouldOnlyCreateDiff()) { $revision = $this->buildRevisionFromCommitMessage($commit_message); } $server = $this->console->getServer(); $server->setHandler(array($this, 'handleServerMessage')); $data = $this->runLintUnit(); $lint_result = $data['lintResult']; $this->unresolvedLint = $data['unresolvedLint']; $unit_result = $data['unitResult']; $this->testResults = $data['testResults']; if ($this->getArgument('nolint')) { $this->excuses['lint'] = $this->getSkipExcuse( pht('Provide explanation for skipping lint or press Enter to abort:'), 'lint-excuses'); } if ($this->getArgument('nounit')) { $this->excuses['unit'] = $this->getSkipExcuse( pht( 'Provide explanation for skipping unit tests '. 'or press Enter to abort:'), 'unit-excuses'); } $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->pushChangesToStagingArea($this->diffID); $phid = idx($diff_info, 'phid'); if ($phid) { $this->hitAutotargets = $this->updateAutotargets( $phid, $unit_result); } $this->updateLintDiffProperty(); $this->updateUnitDiffProperty(); $this->updateLocalDiffProperty(); $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 { $revision['diffid'] = $this->getDiffID(); if ($commit_message->getRevisionID()) { $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); } echo pht('Updated an existing Differential revision:')."\n"; } else { $revision = $this->dispatchWillCreateRevisionEvent($revision); $result = $conduit->callMethodSynchronous( 'differential.createrevision', $revision); $revised_message = $conduit->callMethodSynchronous( 'differential.getcommitmessage', array( 'revision_id' => $result['revisionid'], )); 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->getArgument('plan-changes')) { $conduit->callMethodSynchronous( 'differential.createcomment', array( 'revision_id' => $result['revisionid'], 'action' => 'rethink', )); echo pht('Planned changes to the revision.')."\n"; } 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(); if ($this->getArgument('less-context')) { $repository_api->setDiffLinesOfContext(3); } $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(), ); 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') ->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(); $revision['id'] = $revision_id; $this->revisionID = $revision_id; $revision['message'] = $this->getArgument('message'); if (!strlen($revision['message'])) { $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); } } return $revision; } protected function shouldOnlyCreateDiff() { if ($this->getArgument('create')) { return false; } if ($this->getArgument('update')) { return false; } if ($this->getArgument('use-commit-message')) { return false; } if ($this->isRawDiffSource()) { return true; } return $this->getArgument('preview') || $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"); $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.')); } if (count($changes) > 250) { $message = pht( 'This diff has a very large number of changes (%s). Differential '. 'works best for changes which will receive detailed human review, '. 'and not as well for large automated changes or bulk checkins. '. 'See %s for information about reviewing big checkins. Continue anyway?', - new PhutilNumber(count($changes)), + phutil_count($changes), 'https://secure.phabricator.com/book/phabricator/article/'. 'differential_large_changes/'); if (!phutil_console_confirm($message)) { throw new ArcanistUsageException( pht('Aborted generation of gigantic diff.')); } } $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 (!$this->getArgument('less-context')) { $byte_warning .= ' '.pht( "If this file is a huge text file, try using the '%s' flag.", '--less-context'); } 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 ')); } 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.')); } } } } $try_encoding = nonempty($this->getArgument('encoding'), null); $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) { if (!$try_encoding) { try { $try_encoding = $this->getRepositoryEncoding(); } catch (ConduitClientException $e) { if ($e->getErrorCode() == 'ERR-BAD-ARCANIST-PROJECT') { echo phutil_console_wrap( pht('Lookup of encoding in arcanist 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.', - new PhutilNumber(count($utf8_problems))), + phutil_count($utf8_problems)), pht( "You can learn more about how Phabricator 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 Phabricator documentation."), pht( - '%d AFFECTED FILE(S)', - count($utf8_problems))); + '%s AFFECTED FILE(S)', + phutil_count($utf8_problems))); $confirm = pht( 'Do you want to mark these %s file(s) as binary and continue?', - new PhutilNumber(count($utf8_problems))); + 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->haveUncommittedChanges) { 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->getArgument('only') || $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: if ($this->getArgument('advice') && $lint_workflow->getUnresolvedMessages()) { $this->getErrorExcuse( 'lint', pht('Lint issued unresolved advice.'), 'lint-excuses'); } else { $this->console->writeOut( "** %s ** %s\n", pht('LINT OKAY'), pht('No lint problems.')); } break; case ArcanistLintWorkflow::RESULT_WARNINGS: $this->getErrorExcuse( 'lint', pht('Lint issued unresolved warnings.'), 'lint-excuses'); break; case ArcanistLintWorkflow::RESULT_ERRORS: $this->console->writeOut( "** %s ** %s\n", pht('LINT ERRORS'), pht('Lint raised errors!')); $this->getErrorExcuse( 'lint', pht('Lint issued unresolved errors!'), 'lint-excuses'); 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->getArgument('only') || $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( "** %s ** %s\n", pht('UNIT OKAY'), pht('No unit test failures.')); break; case ArcanistUnitWorkflow::RESULT_UNSOUND: if ($this->getArgument('ignore-unsound-tests')) { echo phutil_console_format( "** %s ** %s\n", pht('UNIT UNSOUND'), pht( 'Unit testing raised errors, but all '. 'failing tests are unsound.')); } else { $continue = $this->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(); } } break; case ArcanistUnitWorkflow::RESULT_FAIL: $this->console->writeOut( "** %s ** %s\n", pht('UNIT ERRORS'), pht('Unit testing raised errors!')); $this->getErrorExcuse( 'unit', pht('Unit test results include failures!'), 'unit-excuses'); 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; } private function getSkipExcuse($prompt, $history) { $excuse = $this->getArgument('excuse'); if ($excuse === null) { $history = $this->getRepositoryAPI()->getScratchFilePath($history); $excuse = phutil_console_prompt($prompt, $history); if ($excuse == '') { throw new ArcanistUserAbortException(); } } return $excuse; } private function getErrorExcuse($type, $prompt, $history) { if ($this->getArgument('excuse')) { $this->console->sendMessage(array( 'type' => $type, 'confirm' => $prompt.' '.pht('Ignore them?'), )); return; } $history = $this->getRepositoryAPI()->getScratchFilePath($history); $prompt .= ' '. pht('Provide explanation to continue or press Enter to abort.'); $this->console->writeOut("\n\n%s", phutil_console_wrap($prompt)); $this->console->sendMessage(array( 'type' => $type, 'prompt' => pht('Explanation:'), 'history' => $history, )); } public function handleServerMessage(PhutilConsoleMessage $message) { $data = $message->getData(); if ($this->getArgument('excuse')) { try { phutil_console_require_tty(); } catch (PhutilConsoleStdinNotInteractiveException $ex) { $this->excuses[$data['type']] = $this->getArgument('excuse'); return null; } } $response = ''; if (isset($data['prompt'])) { $response = phutil_console_prompt($data['prompt'], idx($data, 'history')); } else if (phutil_console_confirm($data['confirm'])) { $response = $this->getArgument('excuse'); } if ($response == '') { throw new ArcanistUserAbortException(); } $this->excuses[$data['type']] = $response; return null; } /* -( Commit and Update Messages )----------------------------------------- */ /** * @task message */ private function buildCommitMessage() { if ($this->getArgument('preview') || $this->getArgument('only')) { return null; } $is_create = $this->getArgument('create'); $is_update = $this->getArgument('update'); $is_raw = $this->isRawDiffSource(); $is_message = $this->getArgument('use-commit-message'); $is_verbatim = $this->getArgument('verbatim'); if ($is_message) { return $this->getCommitMessageFromCommit($is_message); } 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 getCommitMessageFromCommit($commit) { $text = $this->getRepositoryAPI()->getCommitMessage($commit); $message = ArcanistDifferentialCommitMessage::newFromRawCorpus($text); $message->pullDataFromConduit($this->getConduit()); $this->validateCommitMessage($message); return $message; } /** * @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 ', )); 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') ->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); $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) { $confirm = pht('You have not specified any reviewers. Continue anyway?'); if (!phutil_console_confirm($confirm)) { throw new ArcanistUsageException(pht('Specify reviewers and retry.')); } } else { $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': $untils = array(); foreach ($result as $user) { if (idx($user, 'currentStatus') == 'away') { $untils[] = $user['currentStatusUntil']; } } if (count($untils) == count($reviewers)) { $until = date('l, M j Y', min($untils)); $confirm = pht( 'All reviewers are away until %s. Continue anyway?', $until); 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(); $template = sprintf( "%s\n\n# %s\n#\n# %s\n# %s\n#\n# %s\n# $ %s\n\n", rtrim($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') ->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')); } if ($faux_message) { $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 (!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. $local = $this->loadActiveLocalCommitInfo(); $hashes = ipull($local, null, 'commit'); $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; } $local = $this->loadActiveLocalCommitInfo(); $hashes = ipull($local, null, 'commit'); $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 loadActiveLocalCommitInfo() { $current_diff = $this->getConduit()->callMethodSynchronous( 'differential.querydiffs', array( 'revisionIDs' => array($this->revisionID), )); $current_diff = head($current_diff); $properties = idx($current_diff, 'properties', array()); return idx($properties, 'local:commits', array()); } /* -( 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 (strlen($this->excuses['lint'])) { $this->updateDiffProperty( 'arc:lint-excuse', json_encode($this->excuses['lint'])); } 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 (strlen($this->excuses['unit'])) { $this->updateDiffProperty('arc:unit-excuse', json_encode($this->excuses['unit'])); } 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)); } /** * 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']; throw new ArcanistUsageException( pht( "You don't own revision %s '%s'. You can only update revisions ". "you own. You can 'Commandeer' this revision from the web ". "interface if you want to become the owner.", "D{$id}", $title)); } /* -( 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']; $type = $spec['type']; $size = strlen($spec['data']); $change->setMetadata("{$type}:file:size", $size); 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; } $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()) ->setConduitClient($this->getConduit()); 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 pushChangesToStagingArea($id) { if ($this->getArgument('skip-staging')) { $this->writeInfo( pht('SKIP STAGING'), pht('Flag --skip-staging was specified.')); return; } if ($this->isRawDiffSource()) { $this->writeInfo( pht('SKIP STAGING'), pht('Raw changes can not be pushed to a staging area.')); return; } if (!$this->getRepositoryPHID()) { $this->writeInfo( pht('SKIP STAGING'), pht('Unable to determine repository for this change.')); return; } $staging = $this->getRepositoryStagingConfiguration(); if ($staging === null) { $this->writeInfo( pht('SKIP STAGING'), pht('The server does not support staging areas.')); return; } $supported = idx($staging, 'supported'); if (!$supported) { $this->writeInfo( pht('SKIP STAGING'), pht('Phabricator does not support staging areas for this repository.')); return; } $staging_uri = idx($staging, 'uri'); if (!$staging_uri) { $this->writeInfo( pht('SKIP STAGING'), pht('No staging area is configured for this repository.')); return; } $api = $this->getRepositoryAPI(); if (!($api instanceof ArcanistGitAPI)) { $this->writeInfo( pht('SKIP STAGING'), pht('This client version does not support staging this repository.')); return; } $commit = $api->getHeadCommit(); $prefix = idx($staging, 'prefix', 'phabricator'); $tag = $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'; } $err = phutil_passthru( 'git push %Ls -- %s %s:refs/tags/%s', $push_flags, $staging_uri, $commit, $tag); if ($err) { $this->writeWarn( pht('STAGING FAILED'), pht('Unable to push changes to the staging area.')); } else { $this->writeOkay( pht('STAGING PUSHED'), pht( 'Pushed a copy of the changes to tag "%s" in the staging area.', $tag)); } } /** * 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; } } } diff --git a/src/workflow/ArcanistUploadWorkflow.php b/src/workflow/ArcanistUploadWorkflow.php index a31ce0f0..a0582a69 100644 --- a/src/workflow/ArcanistUploadWorkflow.php +++ b/src/workflow/ArcanistUploadWorkflow.php @@ -1,198 +1,198 @@ array( 'help' => pht('Output upload information in JSON format.'), ), 'temporary' => array( 'help' => pht( 'Mark the file as temporary. Temporary files will be deleted '. 'automatically after 24 hours.'), ), '*' => 'paths', ); } protected function didParseArguments() { if (!$this->getArgument('paths')) { throw new ArcanistUsageException( pht('Specify one or more files to upload.')); } $this->paths = $this->getArgument('paths'); $this->json = $this->getArgument('json'); } public function requiresAuthentication() { return true; } public function run() { $is_temporary = $this->getArgument('temporary'); $conduit = $this->getConduit(); $results = array(); $uploader = id(new ArcanistFileUploader()) ->setConduitClient($conduit); foreach ($this->paths as $key => $path) { $file = id(new ArcanistFileDataRef()) ->setName(basename($path)) ->setPath($path); if ($is_temporary) { $expires_at = time() + phutil_units('24 hours in seconds'); $file->setDeleteAfterEpoch($expires_at); } $uploader->addFile($file); } $files = $uploader->uploadFiles(); $results = array(); foreach ($files as $file) { // TODO: This could be handled more gracefully; just preserving behavior // until we introduce `file.query` and modernize this. if ($file->getErrors()) { throw new Exception(implode("\n", $file->getErrors())); } $phid = $file->getPHID(); $name = $file->getName(); $info = $conduit->callMethodSynchronous( 'file.info', array( 'phid' => $phid, )); $results[$path] = $info; if (!$this->json) { $id = $info['id']; echo " F{$id} {$name}: ".$info['uri']."\n\n"; } } if ($this->json) { echo json_encode($results)."\n"; } else { $this->writeStatus(pht('Done.')); } return 0; } private function writeStatus($line) { $this->writeStatusMessage($line."\n"); } private function uploadChunks($file_phid, $path) { $conduit = $this->getConduit(); $f = @fopen($path, 'rb'); if (!$f) { throw new Exception(pht('Unable to open file "%s"', $path)); } $this->writeStatus(pht('Beginning chunked upload of large file...')); $chunks = $conduit->callMethodSynchronous( 'file.querychunks', array( 'filePHID' => $file_phid, )); $remaining = array(); foreach ($chunks as $chunk) { if (!$chunk['complete']) { $remaining[] = $chunk; } } $done = (count($chunks) - count($remaining)); if ($done) { $this->writeStatus( pht( - 'Resuming upload (%d of %d chunks remain).', - new PhutilNumber(count($remaining)), - new PhutilNumber(count($chunks)))); + 'Resuming upload (%s of %s chunks remain).', + phutil_count($remaining), + phutil_count($chunks))); } else { $this->writeStatus( pht( - 'Uploading chunks (%d chunks to upload).', - new PhutilNumber(count($remaining)))); + '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) { $offset = $chunk['byteStart']; $ok = fseek($f, $offset); if ($ok !== 0) { throw new Exception( pht( 'Failed to %s!', 'fseek()')); } $data = fread($f, $chunk['byteEnd'] - $chunk['byteStart']); if ($data === false) { throw new Exception( pht( 'Failed to %s!', 'fread()')); } $conduit->callMethodSynchronous( 'file.uploadchunk', array( 'filePHID' => $file_phid, 'byteStart' => $offset, 'dataEncoding' => 'base64', 'data' => base64_encode($data), )); $progress->update(1); } } } diff --git a/src/workflow/ArcanistWorkflow.php b/src/workflow/ArcanistWorkflow.php index e222914c..ad57c843 100644 --- a/src/workflow/ArcanistWorkflow.php +++ b/src/workflow/ArcanistWorkflow.php @@ -1,2052 +1,2052 @@ 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. */ abstract public function getCommandSynopses(); /** * Return console formatted string with command help printed in `arc help`. * * @return string 10-space indented help to use the command. */ abstract public function getCommandHelp(); /* -( 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); } $user = $this->getConfigFromAnySource('http.basicauth.user'); $pass = $this->getConfigFromAnySource('http.basicauth.pass'); if ($user !== null && $pass !== null) { $this->conduit->setBasicAuthCredentials($user, $pass); } return $this; } final public function getConfigFromAnySource($key) { 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; } /** * Force arc to identify with a specific Conduit version during the * protocol handshake. This is primarily useful for development (especially * for sending diffs which bump the client Conduit version), since the client * still actually speaks the builtin version of the protocol. * * Controlled by the --conduit-version flag. * * @param int Version the client should pretend to be. * @return this * @task conduit */ final public function forceConduitVersion($version) { $this->forcedConduitVersion = $version; 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 nonempty($this->forcedConduitVersion, 6); } /** * Override the default timeout for Conduit. * * Controlled by the --conduit-timeout flag. * * @param float Timeout, in seconds. * @return this * @task conduit */ final public function setConduitTimeout($timeout) { $this->conduitTimeout = $timeout; if ($this->conduit) { $this->conduit->setConduitTimeout($timeout); } return $this; } /** * 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; } 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 LOGIN TO PHABRICATOR'), 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; } final 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->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) { return idx($this->arguments, $key, $default); } final public function getPassedArguments() { return $this->passedArguments; } 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) { $this->passedArguments = $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 = ArcanistConfiguration::correctArgumentSpelling( $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() { $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() { 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".)', - new PhutilNumber(count($untracked)), + phutil_count($untracked), '.git/info/exclude'); } else if ($api instanceof ArcanistSubversionAPI) { $hint = pht( '(To ignore these %s change(s), add them to "%s".)', - new PhutilNumber(count($untracked)), + phutil_count($untracked), 'svn:ignore'); } else if ($api instanceof ArcanistMercurialAPI) { $hint = pht( '(To ignore these %s change(s), add them to "%s".)', - new PhutilNumber(count($untracked)), + 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?', - new PhutilNumber(count($untracked))); + 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', false); 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')) ->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) { $callsign = $repository['callsign']; $commit_name = 'r'.$callsign.$commit['commit']; $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?', - new PhutilNumber(count($files))); + phutil_count($files)); } else { $prompt = pht( 'Do you want to create a new commit with these %s change(s)?', - new PhutilNumber(count($files))); + 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), )); } final private function loadBundleFromConduit( ConduitClient $conduit, $params) { $future = $conduit->callMethod('differential.querydiffs', $params); $diff = head($future->resolve()); $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); } final public function writeInfo($title, $message) { $this->writeStatusMessage( phutil_console_format( "** %s ** %s\n", $title, $message)); } final public function writeWarn($title, $message) { $this->writeStatusMessage( phutil_console_format( "** %s ** %s\n", $title, $message)); } final public function writeOkay($title, $message) { $this->writeStatusMessage( phutil_console_format( "** %s ** %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->getWorkingCopy(); 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 resolveCall(ConduitFuture $method, $timeout = null) { try { return $method->resolve($timeout); } catch (ConduitClientException $ex) { if ($ex->getErrorCode() == 'ERR-CONDUIT-CALL') { echo phutil_console_wrap( pht( 'This feature requires a newer version of Phabricator. Please '. 'update it using these instructions: %s', 'https://secure.phabricator.com/book/phabricator/article/'. 'upgrading/')."\n\n"); } throw $ex; } } 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 callsign of the Phabricator repository this working copy * corresponds to. Returns `null` if no repository can be identified. * * @return string|null Repository callsign, or null if no repository can be * identified. * * @task phabrep */ final protected function getRepositoryCallsign() { return idx($this->getRepositoryInformation(), 'callsign'); } /** * 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 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 { $results = $this->getConduit()->callMethodSynchronous( 'repository.query', $query); } catch (ConduitClientException $ex) { if ($ex->getErrorCode() == 'ERR-CONDUIT-CALL') { $reasons[] = pht( 'This version of Arcanist is more recent than the version of '. 'Phabricator you are connecting to: the Phabricator install is '. 'out of date and does not have support for identifying '. 'repositories by callsign or URI. Update Phabricator 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).'); } $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->getWorkingCopy(); $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->getWorkingCopy(); $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(); foreach ($uris as $uri) { $err = phutil_passthru('%s %s', $browser, $uri); if ($err) { throw new ArcanistUsageException( pht( "Failed to open '%s' in browser ('%s'). ". "Check your 'browser' config option.", $uri, $browser)); } } } private function getBrowserCommand() { $config = $this->getConfigFromAnySource('browser'); if ($config) { return $config; } if (phutil_is_windows()) { return 'start'; } $candidates = array('sensible-browser', 'xdg-open', '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) { if (Filesystem::binaryExists($cmd)) { return $cmd; } } throw new ArcanistUsageException( pht( "Unable to find a browser command to run. Set '%s' in your ". "Arcanist config to specify a command to use.", 'browser')); } /** * 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->getRepositoryCallsign()) { try { $this->getConduit()->callMethodSynchronous( 'diffusion.looksoon', array( 'callsigns' => array($this->getRepositoryCallsign()), )); } 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); return $map; } private function getModernCommonDictionary(array $map) { foreach ($map as $key => $value) { if ($value === null) { unset($map[$key]); } } return $map; } }