Page Menu
Home
Sealhub
Search
Configure Global Search
Log In
Files
F10360397
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
485 KB
Referenced Files
None
Subscribers
None
View Options
This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/scripts/__init_script__.php b/scripts/__init_script__.php
index 8bbdf0fd..377b1b4c 100644
--- a/scripts/__init_script__.php
+++ b/scripts/__init_script__.php
@@ -1,58 +1,58 @@
<?php
/**
* Adjust 'include_path' to add locations where we'll search for libphutil.
* We look in these places:
*
* - Next to 'arcanist/'.
* - Anywhere in the normal PHP 'include_path'.
* - Inside 'arcanist/externals/includes/'.
*
* When looking in these places, we expect to find a 'libphutil/' directory.
*/
function arcanist_adjust_php_include_path() {
// The 'arcanist/' directory.
$arcanist_dir = dirname(dirname(__FILE__));
// The parent directory of 'arcanist/'.
$parent_dir = dirname($arcanist_dir);
// The 'arcanist/externals/includes/' directory.
$include_dir = implode(
DIRECTORY_SEPARATOR,
array(
$arcanist_dir,
'externals',
'includes',
));
$php_include_path = ini_get('include_path');
$php_include_path = implode(
PATH_SEPARATOR,
array(
$parent_dir,
$php_include_path,
$include_dir,
));
ini_set('include_path', $php_include_path);
}
arcanist_adjust_php_include_path();
if (getenv('ARC_PHUTIL_PATH')) {
@include_once getenv('ARC_PHUTIL_PATH').'/scripts/__init_script__.php';
} else {
@include_once 'libphutil/scripts/__init_script__.php';
}
if (!@constant('__LIBPHUTIL__')) {
echo "ERROR: Unable to load libphutil. Put libphutil/ next to arcanist/, or ".
- "update your PHP 'include_path' to include the parent directory of ".
- "libphutil/, or symlink libphutil/ into arcanist/externals/includes/.\n";
+ "update your PHP 'include_path' to include the parent directory of ".
+ "libphutil/, or symlink libphutil/ into arcanist/externals/includes/.\n";
exit(1);
}
phutil_load_library(dirname(dirname(__FILE__)).'/src/');
PhutilTranslator::getInstance()
->setLocale(PhutilLocale::loadLocale('en_US'))
->setTranslations(PhutilTranslation::getTranslationMapForLocale('en_US'));
diff --git a/src/difference/__tests__/ArcanistDiffUtilsTestCase.php b/src/difference/__tests__/ArcanistDiffUtilsTestCase.php
index 81c326d2..26fa9e47 100644
--- a/src/difference/__tests__/ArcanistDiffUtilsTestCase.php
+++ b/src/difference/__tests__/ArcanistDiffUtilsTestCase.php
@@ -1,242 +1,242 @@
<?php
/**
* Test cases for @{class:ArcanistDiffUtils}.
*/
final class ArcanistDiffUtilsTestCase extends PhutilTestCase {
public function testLevenshtein() {
$tests = array(
array(
'a',
'b',
'x',
),
array(
'kalrmr(array($b))',
'array($b)',
'dddddddssssssssds',
),
array(
'array($b)',
'kalrmr(array($b))',
'iiiiiiissssssssis',
),
array(
'zkalrmr(array($b))z',
'xarray($b)x',
'dddddddxsssssssssdx',
),
array(
'xarray($b)x',
'zkalrmr(array($b))z',
'iiiiiiixsssssssssix',
),
array(
'abcdefghi',
'abcdefghi',
'sssssssss',
),
array(
'abcdefghi',
'abcdefghijkl',
'sssssssssiii',
),
array(
'abcdefghijkl',
'abcdefghi',
'sssssssssddd',
),
array(
'xyzabcdefghi',
'abcdefghi',
'dddsssssssss',
),
array(
'abcdefghi',
'xyzabcdefghi',
'iiisssssssss',
),
array(
'abcdefg',
'abxdxfg',
'ssxsxss',
),
array(
'private function a($a, $b) {',
'public function and($b, $c) {',
'siixsdddxsssssssssssiissxsssxsss',
),
array(
// This is a test that we correctly detect shared prefixes and suffixes
// and don't trigger "give up, too long" mode if there's a small text
// change in an ocean of similar text.
' if ('.
'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.
'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.
'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx) {',
' if('.
'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.
'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.
'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx) {',
'ssssssssssds'.
'ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss'.
'ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss'.
'sssssssssssssssssssssssssssssssssssssss',
),
);
foreach ($tests as $test) {
$this->assertEqual(
$test[2],
ArcanistDiffUtils::generateEditString(
str_split($test[0]),
str_split($test[1])),
- "'{$test[0]}' vs '{$test[1]}'");
+ pht("'%s' vs '%s'", $test[0], $test[1]));
}
$utf8_tests = array(
array(
'GrumpyCat',
"Grumpy\xE2\x98\x83at",
'ssssssxss',
),
);
foreach ($tests as $test) {
$this->assertEqual(
$test[2],
ArcanistDiffUtils::generateEditString(
phutil_utf8v_combined($test[0]),
phutil_utf8v_combined($test[1])),
- "'{$test[0]}' vs '{$test[1]}' (utf8)");
+ pht("'%s' vs '%s' (utf8)", $test[0], $test[1]));
}
}
public function testGenerateUTF8IntralineDiff() {
// Both Strings Empty.
$left = '';
$right = '';
$result = array(
array(array(0, 0)),
array(array(0, 0)),
);
$this->assertEqual(
$result,
ArcanistDiffUtils::generateIntralineDiff($left, $right));
// Left String Empty.
$left = '';
$right = "Grumpy\xE2\x98\x83at";
$result = array(
array(array(0, 0)),
array(array(0, 11)),
);
$this->assertEqual(
$result,
ArcanistDiffUtils::generateIntralineDiff($left, $right));
// Right String Empty.
$left = "Grumpy\xE2\x98\x83at";
$right = '';
$result = array(
array(array(0, 11)),
array(array(0, 0)),
);
$this->assertEqual(
$result,
ArcanistDiffUtils::generateIntralineDiff($left, $right));
// Both Strings Same
$left = "Grumpy\xE2\x98\x83at";
$right = "Grumpy\xE2\x98\x83at";
$result = array(
array(array(0, 11)),
array(array(0, 11)),
);
$this->assertEqual(
$result,
ArcanistDiffUtils::generateIntralineDiff($left, $right));
// Both Strings are different.
$left = "Grumpy\xE2\x98\x83at";
$right = 'Smiling Dog';
$result = array(
array(array(1, 11)),
array(array(1, 11)),
);
$this->assertEqual(
$result,
ArcanistDiffUtils::generateIntralineDiff($left, $right));
// String with one difference in the middle.
$left = 'GrumpyCat';
$right = "Grumpy\xE2\x98\x83at";
$result = array(
array(array(0, 6), array(1, 1), array(0, 2)),
array(array(0, 6), array(1, 3), array(0, 2)),
);
$this->assertEqual(
$result,
ArcanistDiffUtils::generateIntralineDiff($left, $right));
// Differences in middle, not connected to each other.
$left = 'GrumpyCat';
$right = "Grumpy\xE2\x98\x83a\xE2\x98\x83t";
$result = array(
array(array(0, 6), array(1, 2), array(0, 1)),
array(array(0, 6), array(1, 7), array(0, 1)),
);
$this->assertEqual(
$result,
ArcanistDiffUtils::generateIntralineDiff($left, $right));
// String with difference at the beginning.
$left = "GrumpyC\xE2\x98\x83t";
$right = "DrumpyC\xE2\x98\x83t";
$result = array(
array(array(1, 1), array(0, 10)),
array(array(1, 1), array(0, 10)),
);
$this->assertEqual(
$result,
ArcanistDiffUtils::generateIntralineDiff($left, $right));
// String with difference at the end.
$left = "GrumpyC\xE2\x98\x83t";
$right = "GrumpyC\xE2\x98\x83P";
$result = array(
array(array(0, 10), array(1, 1)),
array(array(0, 10), array(1, 1)),
);
$this->assertEqual(
$result,
ArcanistDiffUtils::generateIntralineDiff($left, $right));
// String with differences at the beginning and end.
$left = "GrumpyC\xE2\x98\x83t";
$right = "DrumpyC\xE2\x98\x83P";
$result = array(
array(array(1, 1), array(0, 9), array(1, 1)),
array(array(1, 1), array(0, 9), array(1, 1)),
);
$this->assertEqual(
$result,
ArcanistDiffUtils::generateIntralineDiff($left, $right));
// This is a unicode combining character, "COMBINING DOUBLE TILDE".
$cc = "\xCD\xA0";
$left = 'Senor';
$right = "Sen{$cc}or";
$result = array(
array(array(0, 2), array(1, 1), array(0, 2)),
array(array(0, 2), array(1, 3), array(0, 2)),
);
$this->assertEqual(
$result,
ArcanistDiffUtils::generateIntralineDiff($left, $right));
}
}
diff --git a/src/internationalization/ArcanistUSEnglishTranslation.php b/src/internationalization/ArcanistUSEnglishTranslation.php
index 4356d37c..b468aaaf 100644
--- a/src/internationalization/ArcanistUSEnglishTranslation.php
+++ b/src/internationalization/ArcanistUSEnglishTranslation.php
@@ -1,85 +1,74 @@
<?php
final class ArcanistUSEnglishTranslation extends PhutilTranslation {
public function getLocaleCode() {
return 'en_US';
}
protected function getTranslations() {
return array(
'%s locally modified path(s) are not included in this revision:' => 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'),
'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 ".git/info/exclude".)' =>
- array(
- '(To ignore this change, add it to ".git/info/exclude".)',
- '(To ignore these changes, add them to ".git/info/exclude".)',
- ),
-
- '(To ignore these %s change(s), add them to "svn:ignore".)' => array(
- '(To ignore this change, add it to "svn:ignore".)',
- '(To ignore these changes, add them to "svn:ignore".)',
- ),
-
- '(To ignore these %s change(s), add them to ".hgignore".)' => array(
- '(To ignore this change, add it to ".hgignore".)',
- '(To ignore these changes, add them to ".hgignore".)',
+ '(To ignore these %s change(s), add them to "%s".)' => array(
+ '(To ignore this change, add it to "%s".)',
+ '(To ignore these changes, add them to "%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.',
),
'Ignore these %s untracked file(s) and continue?' => array(
'Ignore this untracked file and continue?',
'Ignore these untracked files and continue?',
),
);
}
}
diff --git a/src/lint/linter/ArcanistClosureLinter.php b/src/lint/linter/ArcanistClosureLinter.php
index 78d4d428..5cdf6259 100644
--- a/src/lint/linter/ArcanistClosureLinter.php
+++ b/src/lint/linter/ArcanistClosureLinter.php
@@ -1,62 +1,62 @@
<?php
/**
* Uses `gjslint` to detect errors and potential problems in JavaScript code.
*/
final class ArcanistClosureLinter extends ArcanistExternalLinter {
public function getInfoName() {
- return 'Closure Linter';
+ return pht('Closure Linter');
}
public function getInfoURI() {
return 'https://developers.google.com/closure/utilities/';
}
public function getInfoDescription() {
return pht("Uses Google's Closure Linter to check JavaScript code.");
}
public function getLinterName() {
return 'GJSLINT';
}
public function getLinterConfigurationName() {
return 'gjslint';
}
public function getDefaultBinary() {
return 'gjslint';
}
public function getInstallInstructions() {
return pht(
'Install %s using `%s`.',
'gjslint',
'sudo easy_install http://closure-linter.googlecode.com/'.
'files/closure_linter-latest.tar.gz');
}
protected function parseLinterOutput($path, $err, $stdout, $stderr) {
$lines = phutil_split_lines($stdout, false);
$messages = array();
foreach ($lines as $line) {
$matches = null;
if (!preg_match('/^Line (\d+), E:(\d+): (.*)/', $line, $matches)) {
continue;
}
$message = id(new ArcanistLintMessage())
->setPath($path)
->setLine($matches[1])
->setSeverity(ArcanistLintSeverity::SEVERITY_ERROR)
->setCode($this->getLinterName().$matches[2])
->setDescription($matches[3]);
$messages[] = $message;
}
return $messages;
}
}
diff --git a/src/lint/linter/ArcanistJSONLintLinter.php b/src/lint/linter/ArcanistJSONLintLinter.php
index d6b13103..7fd00254 100644
--- a/src/lint/linter/ArcanistJSONLintLinter.php
+++ b/src/lint/linter/ArcanistJSONLintLinter.php
@@ -1,85 +1,85 @@
<?php
/**
* A linter for JSON files.
*/
final class ArcanistJSONLintLinter extends ArcanistExternalLinter {
public function getInfoName() {
- return 'JSON Lint';
+ return pht('JSON Lint');
}
public function getInfoURI() {
return 'https://github.com/zaach/jsonlint';
}
public function getInfoDescription() {
return pht('Use `%s` to detect syntax errors in JSON files.', 'jsonlint');
}
public function getLinterName() {
return 'JSON';
}
public function getLinterConfigurationName() {
return 'jsonlint';
}
public function getDefaultBinary() {
return 'jsonlint';
}
public function getVersion() {
// NOTE: `jsonlint --version` returns a non-zero exit status.
list($err, $stdout) = exec_manual(
'%C --version',
$this->getExecutableCommand());
$matches = array();
if (preg_match('/^(?P<version>\d+\.\d+\.\d+)$/', $stdout, $matches)) {
return $matches['version'];
} else {
return false;
}
}
public function getInstallInstructions() {
return pht('Install jsonlint using `%s`.', 'npm install -g jsonlint');
}
protected function getMandatoryFlags() {
return array(
'--compact',
);
}
protected function parseLinterOutput($path, $err, $stdout, $stderr) {
$lines = phutil_split_lines($stderr, false);
$messages = array();
foreach ($lines as $line) {
$matches = null;
$match = preg_match(
'/^(?:(?<path>.+): )?'.
'line (?<line>\d+), col (?<column>\d+), '.
'(?<description>.*)$/',
$line,
$matches);
if ($match) {
$message = new ArcanistLintMessage();
$message->setPath($path);
$message->setLine($matches['line']);
$message->setChar($matches['column']);
$message->setCode($this->getLinterName());
$message->setDescription(ucfirst($matches['description']));
$message->setSeverity(ArcanistLintSeverity::SEVERITY_ERROR);
$messages[] = $message;
}
}
return $messages;
}
}
diff --git a/src/lint/linter/ArcanistJSONLinter.php b/src/lint/linter/ArcanistJSONLinter.php
index f6727032..773b21ad 100644
--- a/src/lint/linter/ArcanistJSONLinter.php
+++ b/src/lint/linter/ArcanistJSONLinter.php
@@ -1,50 +1,50 @@
<?php
/**
* A linter for JSON files.
*/
final class ArcanistJSONLinter extends ArcanistLinter {
const LINT_PARSE_ERROR = 1;
public function getInfoName() {
- return 'JSON Lint';
+ return pht('JSON Lint');
}
public function getInfoDescription() {
return pht('Detect syntax errors in JSON files.');
}
public function getLinterName() {
return 'JSON';
}
public function getLinterConfigurationName() {
return 'json';
}
public function getLintNameMap() {
return array(
self::LINT_PARSE_ERROR => pht('Parse Error'),
);
}
protected function canCustomizeLintSeverities() {
return false;
}
public function lintPath($path) {
$data = $this->getData($path);
try {
id(new PhutilJSONParser())->parse($data);
} catch (PhutilJSONParserException $ex) {
$this->raiseLintAtLine(
$ex->getSourceLine(),
$ex->getSourceChar(),
self::LINT_PARSE_ERROR,
$ex->getMessage());
}
}
}
diff --git a/src/lint/linter/ArcanistPhutilLibraryLinter.php b/src/lint/linter/ArcanistPhutilLibraryLinter.php
index baee3ba3..917c7938 100644
--- a/src/lint/linter/ArcanistPhutilLibraryLinter.php
+++ b/src/lint/linter/ArcanistPhutilLibraryLinter.php
@@ -1,229 +1,229 @@
<?php
/**
* Applies lint rules for Phutil libraries. We enforce three rules:
*
* # If you use a symbol, it must be defined somewhere.
* # If you define a symbol, it must not duplicate another definition.
* # If you define a class or interface in a file, it MUST be the only symbol
* defined in that file.
*/
final class ArcanistPhutilLibraryLinter extends ArcanistLinter {
const LINT_UNKNOWN_SYMBOL = 1;
const LINT_DUPLICATE_SYMBOL = 2;
const LINT_ONE_CLASS_PER_FILE = 3;
public function getInfoName() {
- return 'Phutil Library Linter';
+ return pht('Phutil Library Linter');
}
public function getInfoDescription() {
return pht(
'Make sure all the symbols used in a %s library are defined and known. '.
'This linter is specific to PHP source in %s libraries.',
'libphutil',
'libphutil');
}
public function getLinterName() {
return 'PHL';
}
public function getLinterConfigurationName() {
return 'phutil-library';
}
public function getCacheGranularity() {
return self::GRANULARITY_GLOBAL;
}
public function getLintNameMap() {
return array(
self::LINT_UNKNOWN_SYMBOL => pht('Unknown Symbol'),
self::LINT_DUPLICATE_SYMBOL => pht('Duplicate Symbol'),
self::LINT_ONE_CLASS_PER_FILE => pht('One Class Per File'),
);
}
public function getLinterPriority() {
return 2.0;
}
public function willLintPaths(array $paths) {
// NOTE: For now, we completely ignore paths and just lint every library in
// its entirety. This is simpler and relatively fast because we don't do any
// detailed checks and all the data we need for this comes out of module
// caches.
$bootloader = PhutilBootloader::getInstance();
$libraries = $bootloader->getAllLibraries();
// Load the up-to-date map for each library, without loading the library
// itself. This means lint results will accurately reflect the state of
// the working copy.
$symbols = array();
foreach ($libraries as $library) {
$root = phutil_get_library_root($library);
try {
$symbols[$library] = id(new PhutilLibraryMapBuilder($root))
->buildFileSymbolMap();
} catch (XHPASTSyntaxErrorException $ex) {
// If the library contains a syntax error then there isn't much that we
// can do.
continue;
}
}
$all_symbols = array();
foreach ($symbols as $library => $map) {
// Check for files which declare more than one class/interface in the same
// file, or mix function definitions with class/interface definitions. We
// must isolate autoloadable symbols to one per file so the autoloader
// can't end up in an unresolvable cycle.
foreach ($map as $file => $spec) {
$have = idx($spec, 'have', array());
$have_classes =
idx($have, 'class', array()) +
idx($have, 'interface', array());
$have_functions = idx($have, 'function');
if ($have_functions && $have_classes) {
$function_list = implode(', ', array_keys($have_functions));
$class_list = implode(', ', array_keys($have_classes));
$this->raiseLintInLibrary(
$library,
$file,
end($have_functions),
self::LINT_ONE_CLASS_PER_FILE,
pht(
"File '%s' mixes function (%s) and class/interface (%s) ".
"definitions in the same file. A file which declares a class ".
"or an interface MUST declare nothing else.",
$file,
$function_list,
$class_list));
} else if (count($have_classes) > 1) {
$class_list = implode(', ', array_keys($have_classes));
$this->raiseLintInLibrary(
$library,
$file,
end($have_classes),
self::LINT_ONE_CLASS_PER_FILE,
pht(
"File '%s' declares more than one class or interface (%s). ".
"A file which declares a class or interface MUST declare ".
"nothing else.",
$file,
$class_list));
}
}
// Check for duplicate symbols: two files providing the same class or
// function.
foreach ($map as $file => $spec) {
$have = idx($spec, 'have', array());
foreach (array('class', 'function', 'interface') as $type) {
$libtype = ($type == 'interface') ? 'class' : $type;
foreach (idx($have, $type, array()) as $symbol => $offset) {
if (empty($all_symbols[$libtype][$symbol])) {
$all_symbols[$libtype][$symbol] = array(
'library' => $library,
'file' => $file,
'offset' => $offset,
);
continue;
}
$osrc = $all_symbols[$libtype][$symbol]['file'];
$olib = $all_symbols[$libtype][$symbol]['library'];
$this->raiseLintInLibrary(
$library,
$file,
$offset,
self::LINT_DUPLICATE_SYMBOL,
pht(
"Definition of %s '%s' in '%s' in library '%s' duplicates ".
"prior definition in '%s' in library '%s'.",
$type,
$symbol,
$file,
$library,
$osrc,
$olib));
}
}
}
}
$types = array('class', 'function', 'interface', 'class/interface');
foreach ($symbols as $library => $map) {
// Check for unknown symbols: uses of classes, functions or interfaces
// which are not defined anywhere. We reference the list of all symbols
// we built up earlier.
foreach ($map as $file => $spec) {
$need = idx($spec, 'need', array());
foreach ($types as $type) {
$libtype = $type;
if ($type == 'interface' || $type == 'class/interface') {
$libtype = 'class';
}
foreach (idx($need, $type, array()) as $symbol => $offset) {
if (!empty($all_symbols[$libtype][$symbol])) {
// Symbol is defined somewhere.
continue;
}
$libphutil_root = dirname(phutil_get_library_root('phutil'));
$this->raiseLintInLibrary(
$library,
$file,
$offset,
self::LINT_UNKNOWN_SYMBOL,
pht(
"Use of unknown %s '%s'. Common causes are:\n\n".
" - Your %s is out of date.\n".
" This is the most common cause.\n".
" Update this copy of libphutil: %s\n\n".
" - Some other library is out of date.\n".
" Update the library this symbol appears in.\n\n".
" - This symbol is misspelled.\n".
" Spell the symbol name correctly.\n".
" Symbol name spelling is case-sensitive.\n\n".
" - This symbol was added recently.\n".
" Run `%s` on the library it was added to.\n\n".
" - This symbol is external. Use `%s`.\n".
" Use `%s` to find usage examples of this directive.\n\n".
"*** ALTHOUGH USUALLY EASY TO FIX, THIS IS A SERIOUS ERROR.\n".
"*** THIS ERROR IS YOUR FAULT. YOU MUST RESOLVE IT.",
$type,
$symbol,
'libphutil/',
$libphutil_root,
'arc liberate',
'@phutil-external-symbol',
'grep'));
}
}
}
}
}
private function raiseLintInLibrary($library, $path, $offset, $code, $desc) {
$root = phutil_get_library_root($library);
$this->activePath = $root.'/'.$path;
$this->raiseLintAtOffset($offset, $code, $desc);
}
public function lintPath($path) {
return;
}
}
diff --git a/src/lint/linter/ArcanistXHPASTLinter.php b/src/lint/linter/ArcanistXHPASTLinter.php
index 29939e9e..4bce3bde 100644
--- a/src/lint/linter/ArcanistXHPASTLinter.php
+++ b/src/lint/linter/ArcanistXHPASTLinter.php
@@ -1,4475 +1,4476 @@
<?php
/**
* Uses XHPAST to apply lint rules to PHP.
*/
final class ArcanistXHPASTLinter extends ArcanistBaseXHPASTLinter {
const LINT_PHP_SYNTAX_ERROR = 1;
const LINT_UNABLE_TO_PARSE = 2;
const LINT_VARIABLE_VARIABLE = 3;
const LINT_EXTRACT_USE = 4;
const LINT_UNDECLARED_VARIABLE = 5;
const LINT_PHP_SHORT_TAG = 6;
const LINT_PHP_ECHO_TAG = 7;
const LINT_PHP_CLOSE_TAG = 8;
const LINT_NAMING_CONVENTIONS = 9;
const LINT_IMPLICIT_CONSTRUCTOR = 10;
const LINT_DYNAMIC_DEFINE = 12;
const LINT_STATIC_THIS = 13;
const LINT_PREG_QUOTE_MISUSE = 14;
const LINT_PHP_OPEN_TAG = 15;
const LINT_TODO_COMMENT = 16;
const LINT_EXIT_EXPRESSION = 17;
const LINT_COMMENT_STYLE = 18;
const LINT_CLASS_FILENAME_MISMATCH = 19;
const LINT_TAUTOLOGICAL_EXPRESSION = 20;
const LINT_PLUS_OPERATOR_ON_STRINGS = 21;
const LINT_DUPLICATE_KEYS_IN_ARRAY = 22;
const LINT_REUSED_ITERATORS = 23;
const LINT_BRACE_FORMATTING = 24;
const LINT_PARENTHESES_SPACING = 25;
const LINT_CONTROL_STATEMENT_SPACING = 26;
const LINT_BINARY_EXPRESSION_SPACING = 27;
const LINT_ARRAY_INDEX_SPACING = 28;
const LINT_IMPLICIT_FALLTHROUGH = 30;
const LINT_REUSED_AS_ITERATOR = 32;
const LINT_COMMENT_SPACING = 34;
const LINT_SLOWNESS = 36;
const LINT_CLOSING_CALL_PAREN = 37;
const LINT_CLOSING_DECL_PAREN = 38;
const LINT_REUSED_ITERATOR_REFERENCE = 39;
const LINT_KEYWORD_CASING = 40;
const LINT_DOUBLE_QUOTE = 41;
const LINT_ELSEIF_USAGE = 42;
const LINT_SEMICOLON_SPACING = 43;
const LINT_CONCATENATION_OPERATOR = 44;
const LINT_PHP_COMPATIBILITY = 45;
const LINT_LANGUAGE_CONSTRUCT_PAREN = 46;
const LINT_EMPTY_STATEMENT = 47;
const LINT_ARRAY_SEPARATOR = 48;
const LINT_CONSTRUCTOR_PARENTHESES = 49;
const LINT_DUPLICATE_SWITCH_CASE = 50;
const LINT_BLACKLISTED_FUNCTION = 51;
const LINT_IMPLICIT_VISIBILITY = 52;
const LINT_CALL_TIME_PASS_BY_REF = 53;
const LINT_FORMATTED_STRING = 54;
const LINT_UNNECESSARY_FINAL_MODIFIER = 55;
const LINT_UNNECESSARY_SEMICOLON = 56;
const LINT_SELF_MEMBER_REFERENCE = 57;
const LINT_LOGICAL_OPERATORS = 58;
const LINT_INNER_FUNCTION = 59;
const LINT_DEFAULT_PARAMETERS = 60;
const LINT_LOWERCASE_FUNCTIONS = 61;
const LINT_CLASS_NAME_LITERAL = 62;
const LINT_USELESS_OVERRIDING_METHOD = 63;
const LINT_NO_PARENT_SCOPE = 64;
const LINT_ALIAS_FUNCTION = 65;
const LINT_CAST_SPACING = 66;
const LINT_TOSTRING_EXCEPTION = 67;
const LINT_LAMBDA_FUNC_FUNCTION = 68;
const LINT_INSTANCEOF_OPERATOR = 69;
const LINT_INVALID_DEFAULT_PARAMETER = 70;
const LINT_MODIFIER_ORDERING = 71;
const LINT_INVALID_MODIFIERS = 72;
private $blacklistedFunctions = array();
private $naminghook;
private $printfFunctions = array();
private $switchhook;
private $version;
private $windowsVersion;
public function getInfoName() {
- return 'XHPAST Lint';
+ return pht('XHPAST Lint');
}
public function getInfoDescription() {
return pht('Use XHPAST to enforce coding conventions on PHP source files.');
}
public function getLintNameMap() {
return array(
self::LINT_PHP_SYNTAX_ERROR
=> pht('PHP Syntax Error!'),
self::LINT_UNABLE_TO_PARSE
=> pht('Unable to Parse'),
self::LINT_VARIABLE_VARIABLE
=> pht('Use of Variable Variable'),
self::LINT_EXTRACT_USE
=> pht('Use of %s', 'extract()'),
self::LINT_UNDECLARED_VARIABLE
=> pht('Use of Undeclared Variable'),
self::LINT_PHP_SHORT_TAG
=> pht('Use of Short Tag "%s"', '<?'),
self::LINT_PHP_ECHO_TAG
=> pht('Use of Echo Tag "%s"', '<?='),
self::LINT_PHP_CLOSE_TAG
=> pht('Use of Close Tag "%s"', '?>'),
self::LINT_NAMING_CONVENTIONS
=> pht('Naming Conventions'),
self::LINT_IMPLICIT_CONSTRUCTOR
=> pht('Implicit Constructor'),
self::LINT_DYNAMIC_DEFINE
=> pht('Dynamic %s', 'define()'),
self::LINT_STATIC_THIS
=> pht('Use of %s in Static Context', '$this'),
self::LINT_PREG_QUOTE_MISUSE
=> pht('Misuse of %s', 'preg_quote()'),
self::LINT_PHP_OPEN_TAG
=> pht('Expected Open Tag'),
self::LINT_TODO_COMMENT
=> pht('TODO Comment'),
self::LINT_EXIT_EXPRESSION
=> pht('Exit Used as Expression'),
self::LINT_COMMENT_STYLE
=> pht('Comment Style'),
self::LINT_CLASS_FILENAME_MISMATCH
=> pht('Class-Filename Mismatch'),
self::LINT_TAUTOLOGICAL_EXPRESSION
=> pht('Tautological Expression'),
self::LINT_PLUS_OPERATOR_ON_STRINGS
=> pht('Not String Concatenation'),
self::LINT_DUPLICATE_KEYS_IN_ARRAY
=> pht('Duplicate Keys in Array'),
self::LINT_REUSED_ITERATORS
=> pht('Reuse of Iterator Variable'),
self::LINT_BRACE_FORMATTING
=> pht('Brace Placement'),
self::LINT_PARENTHESES_SPACING
=> pht('Spaces Inside Parentheses'),
self::LINT_CONTROL_STATEMENT_SPACING
=> pht('Space After Control Statement'),
self::LINT_BINARY_EXPRESSION_SPACING
=> pht('Space Around Binary Operator'),
self::LINT_ARRAY_INDEX_SPACING
=> pht('Spacing Before Array Index'),
self::LINT_IMPLICIT_FALLTHROUGH
=> pht('Implicit Fallthrough'),
self::LINT_REUSED_AS_ITERATOR
=> pht('Variable Reused As Iterator'),
self::LINT_COMMENT_SPACING
=> pht('Comment Spaces'),
self::LINT_SLOWNESS
=> pht('Slow Construct'),
self::LINT_CLOSING_CALL_PAREN
=> pht('Call Formatting'),
self::LINT_CLOSING_DECL_PAREN
=> pht('Declaration Formatting'),
self::LINT_REUSED_ITERATOR_REFERENCE
=> pht('Reuse of Iterator References'),
self::LINT_KEYWORD_CASING
=> pht('Keyword Conventions'),
self::LINT_DOUBLE_QUOTE
=> pht('Unnecessary Double Quotes'),
self::LINT_ELSEIF_USAGE
=> pht('ElseIf Usage'),
self::LINT_SEMICOLON_SPACING
=> pht('Semicolon Spacing'),
self::LINT_CONCATENATION_OPERATOR
=> pht('Concatenation Spacing'),
self::LINT_PHP_COMPATIBILITY
=> pht('PHP Compatibility'),
self::LINT_LANGUAGE_CONSTRUCT_PAREN
=> pht('Language Construct Parentheses'),
self::LINT_EMPTY_STATEMENT
=> pht('Empty Block Statement'),
self::LINT_ARRAY_SEPARATOR
=> pht('Array Separator'),
self::LINT_CONSTRUCTOR_PARENTHESES
=> pht('Constructor Parentheses'),
self::LINT_DUPLICATE_SWITCH_CASE
=> pht('Duplicate Case Statements'),
self::LINT_BLACKLISTED_FUNCTION
=> pht('Use of Blacklisted Function'),
self::LINT_IMPLICIT_VISIBILITY
=> pht('Implicit Method Visibility'),
self::LINT_CALL_TIME_PASS_BY_REF
=> pht('Call-Time Pass-By-Reference'),
self::LINT_FORMATTED_STRING
=> pht('Formatted String'),
self::LINT_UNNECESSARY_FINAL_MODIFIER
=> pht('Unnecessary Final Modifier'),
self::LINT_UNNECESSARY_SEMICOLON
=> pht('Unnecessary Semicolon'),
self::LINT_SELF_MEMBER_REFERENCE
=> pht('Self Member Reference'),
self::LINT_LOGICAL_OPERATORS
=> pht('Logical Operators'),
self::LINT_INNER_FUNCTION
=> pht('Inner Functions'),
self::LINT_DEFAULT_PARAMETERS
=> pht('Default Parameters'),
self::LINT_LOWERCASE_FUNCTIONS
=> pht('Lowercase Functions'),
self::LINT_CLASS_NAME_LITERAL
=> pht('Class Name Literal'),
self::LINT_USELESS_OVERRIDING_METHOD
=> pht('Useless Overriding Method'),
self::LINT_NO_PARENT_SCOPE
=> pht('No Parent Scope'),
self::LINT_ALIAS_FUNCTION
=> pht('Alias Functions'),
self::LINT_CAST_SPACING
=> pht('Cast Spacing'),
self::LINT_TOSTRING_EXCEPTION
=> pht('Throwing Exception in %s Method', '__toString'),
self::LINT_LAMBDA_FUNC_FUNCTION
=> pht('%s Function', '__lambda_func'),
self::LINT_INSTANCEOF_OPERATOR
=> pht('%s Operator', 'instanceof'),
self::LINT_INVALID_DEFAULT_PARAMETER
=> pht('Invalid Default Parameter'),
self::LINT_MODIFIER_ORDERING
=> pht('Modifier Ordering'),
self::LINT_INVALID_MODIFIERS
=> pht('Invalid Modifiers'),
);
}
public function getLinterName() {
return 'XHP';
}
public function getLinterConfigurationName() {
return 'xhpast';
}
public function getLintSeverityMap() {
$disabled = ArcanistLintSeverity::SEVERITY_DISABLED;
$advice = ArcanistLintSeverity::SEVERITY_ADVICE;
$warning = ArcanistLintSeverity::SEVERITY_WARNING;
return array(
self::LINT_TODO_COMMENT => $disabled,
self::LINT_UNABLE_TO_PARSE => $warning,
self::LINT_NAMING_CONVENTIONS => $warning,
self::LINT_PREG_QUOTE_MISUSE => $advice,
self::LINT_BRACE_FORMATTING => $warning,
self::LINT_PARENTHESES_SPACING => $warning,
self::LINT_CONTROL_STATEMENT_SPACING => $warning,
self::LINT_BINARY_EXPRESSION_SPACING => $warning,
self::LINT_ARRAY_INDEX_SPACING => $warning,
self::LINT_IMPLICIT_FALLTHROUGH => $warning,
self::LINT_SLOWNESS => $warning,
self::LINT_COMMENT_SPACING => $advice,
self::LINT_CLOSING_CALL_PAREN => $warning,
self::LINT_CLOSING_DECL_PAREN => $warning,
self::LINT_REUSED_ITERATOR_REFERENCE => $warning,
self::LINT_KEYWORD_CASING => $warning,
self::LINT_DOUBLE_QUOTE => $advice,
self::LINT_ELSEIF_USAGE => $advice,
self::LINT_SEMICOLON_SPACING => $advice,
self::LINT_CONCATENATION_OPERATOR => $warning,
self::LINT_LANGUAGE_CONSTRUCT_PAREN => $warning,
self::LINT_EMPTY_STATEMENT => $advice,
self::LINT_ARRAY_SEPARATOR => $advice,
self::LINT_CONSTRUCTOR_PARENTHESES => $advice,
self::LINT_IMPLICIT_VISIBILITY => $advice,
self::LINT_UNNECESSARY_FINAL_MODIFIER => $advice,
self::LINT_UNNECESSARY_SEMICOLON => $advice,
self::LINT_SELF_MEMBER_REFERENCE => $advice,
self::LINT_LOGICAL_OPERATORS => $advice,
self::LINT_INNER_FUNCTION => $warning,
self::LINT_DEFAULT_PARAMETERS => $warning,
self::LINT_LOWERCASE_FUNCTIONS => $advice,
self::LINT_CLASS_NAME_LITERAL => $advice,
self::LINT_USELESS_OVERRIDING_METHOD => $advice,
self::LINT_ALIAS_FUNCTION => $advice,
self::LINT_CAST_SPACING => $advice,
self::LINT_MODIFIER_ORDERING => $advice,
);
}
public function getLinterConfigurationOptions() {
return parent::getLinterConfigurationOptions() + array(
'xhpast.blacklisted.function' => array(
'type' => 'optional map<string, string>',
'help' => pht('Blacklisted functions which should not be used.'),
),
'xhpast.naminghook' => array(
'type' => 'optional string',
'help' => pht(
'Name of a concrete subclass of ArcanistXHPASTLintNamingHook which '.
'enforces more granular naming convention rules for symbols.'),
),
'xhpast.printf-functions' => array(
'type' => 'optional map<string, int>',
'help' => pht(
'%s-style functions which take a format string and list of values '.
'as arguments. The value for the mapping is the start index of the '.
'function parameters (the index of the format string parameter).',
'printf()'),
),
'xhpast.switchhook' => array(
'type' => 'optional string',
'help' => pht(
'Name of a concrete subclass of ArcanistXHPASTLintSwitchHook which '.
'tunes the analysis of switch() statements for this linter.'),
),
'xhpast.php-version' => array(
'type' => 'optional string',
'help' => pht('PHP version to target.'),
),
'xhpast.php-version.windows' => array(
'type' => 'optional string',
'help' => pht('PHP version to target on Windows.'),
),
);
}
public function setLinterConfigurationValue($key, $value) {
switch ($key) {
case 'xhpast.blacklisted.function':
$this->blacklistedFunctions = $value;
return;
case 'xhpast.naminghook':
$this->naminghook = $value;
return;
case 'xhpast.printf-functions':
$this->printfFunctions = $value;
return;
case 'xhpast.switchhook':
$this->switchhook = $value;
return;
case 'xhpast.php-version':
$this->version = $value;
return;
case 'xhpast.php-version.windows':
$this->windowsVersion = $value;
return;
}
return parent::setLinterConfigurationValue($key, $value);
}
public function getVersion() {
// The version number should be incremented whenever a new rule is added.
return '34';
}
protected function resolveFuture($path, Future $future) {
$tree = $this->getXHPASTTreeForPath($path);
if (!$tree) {
$ex = $this->getXHPASTExceptionForPath($path);
if ($ex instanceof XHPASTSyntaxErrorException) {
$this->raiseLintAtLine(
$ex->getErrorLine(),
1,
self::LINT_PHP_SYNTAX_ERROR,
pht(
'This file contains a syntax error: %s',
$ex->getMessage()));
} else if ($ex instanceof Exception) {
$this->raiseLintAtPath(self::LINT_UNABLE_TO_PARSE, $ex->getMessage());
}
return;
}
$root = $tree->getRootNode();
$method_codes = array(
'lintStrstrUsedForCheck' => self::LINT_SLOWNESS,
'lintStrposUsedForStart' => self::LINT_SLOWNESS,
'lintImplicitFallthrough' => self::LINT_IMPLICIT_FALLTHROUGH,
'lintBraceFormatting' => self::LINT_BRACE_FORMATTING,
'lintTautologicalExpressions' => self::LINT_TAUTOLOGICAL_EXPRESSION,
'lintCommentSpaces' => self::LINT_COMMENT_SPACING,
'lintHashComments' => self::LINT_COMMENT_STYLE,
'lintReusedIterators' => self::LINT_REUSED_ITERATORS,
'lintReusedIteratorReferences' => self::LINT_REUSED_ITERATOR_REFERENCE,
'lintVariableVariables' => self::LINT_VARIABLE_VARIABLE,
'lintUndeclaredVariables' => array(
self::LINT_EXTRACT_USE,
self::LINT_REUSED_AS_ITERATOR,
self::LINT_UNDECLARED_VARIABLE,
),
'lintPHPTagUse' => array(
self::LINT_PHP_SHORT_TAG,
self::LINT_PHP_ECHO_TAG,
self::LINT_PHP_OPEN_TAG,
self::LINT_PHP_CLOSE_TAG,
),
'lintNamingConventions' => self::LINT_NAMING_CONVENTIONS,
'lintSurpriseConstructors' => self::LINT_IMPLICIT_CONSTRUCTOR,
'lintParenthesesShouldHugExpressions' => self::LINT_PARENTHESES_SPACING,
'lintSpaceAfterControlStatementKeywords' =>
self::LINT_CONTROL_STATEMENT_SPACING,
'lintSpaceAroundBinaryOperators' => self::LINT_BINARY_EXPRESSION_SPACING,
'lintDynamicDefines' => self::LINT_DYNAMIC_DEFINE,
'lintUseOfThisInStaticMethods' => self::LINT_STATIC_THIS,
'lintPregQuote' => self::LINT_PREG_QUOTE_MISUSE,
'lintExitExpressions' => self::LINT_EXIT_EXPRESSION,
'lintArrayIndexWhitespace' => self::LINT_ARRAY_INDEX_SPACING,
'lintTodoComments' => self::LINT_TODO_COMMENT,
'lintPrimaryDeclarationFilenameMatch' =>
self::LINT_CLASS_FILENAME_MISMATCH,
'lintPlusOperatorOnStrings' => self::LINT_PLUS_OPERATOR_ON_STRINGS,
'lintDuplicateKeysInArray' => self::LINT_DUPLICATE_KEYS_IN_ARRAY,
'lintClosingCallParen' => self::LINT_CLOSING_CALL_PAREN,
'lintClosingDeclarationParen' => self::LINT_CLOSING_DECL_PAREN,
'lintKeywordCasing' => self::LINT_KEYWORD_CASING,
'lintStrings' => self::LINT_DOUBLE_QUOTE,
'lintElseIfStatements' => self::LINT_ELSEIF_USAGE,
'lintSemicolons' => self::LINT_SEMICOLON_SPACING,
'lintSpaceAroundConcatenationOperators' =>
self::LINT_CONCATENATION_OPERATOR,
'lintPHPCompatibility' => self::LINT_PHP_COMPATIBILITY,
'lintLanguageConstructParentheses' => self::LINT_LANGUAGE_CONSTRUCT_PAREN,
'lintEmptyBlockStatements' => self::LINT_EMPTY_STATEMENT,
'lintArraySeparator' => self::LINT_ARRAY_SEPARATOR,
'lintConstructorParentheses' => self::LINT_CONSTRUCTOR_PARENTHESES,
'lintSwitchStatements' => self::LINT_DUPLICATE_SWITCH_CASE,
'lintBlacklistedFunction' => self::LINT_BLACKLISTED_FUNCTION,
'lintMethodVisibility' => self::LINT_IMPLICIT_VISIBILITY,
'lintPropertyVisibility' => self::LINT_IMPLICIT_VISIBILITY,
'lintCallTimePassByReference' => self::LINT_CALL_TIME_PASS_BY_REF,
'lintFormattedString' => self::LINT_FORMATTED_STRING,
'lintUnnecessaryFinalModifier' => self::LINT_UNNECESSARY_FINAL_MODIFIER,
'lintUnnecessarySemicolons' => self::LINT_UNNECESSARY_SEMICOLON,
'lintConstantDefinitions' => self::LINT_NAMING_CONVENTIONS,
'lintSelfMemberReference' => self::LINT_SELF_MEMBER_REFERENCE,
'lintLogicalOperators' => self::LINT_LOGICAL_OPERATORS,
'lintInnerFunctions' => self::LINT_INNER_FUNCTION,
'lintDefaultParameters' => self::LINT_DEFAULT_PARAMETERS,
'lintLowercaseFunctions' => self::LINT_LOWERCASE_FUNCTIONS,
'lintClassNameLiteral' => self::LINT_CLASS_NAME_LITERAL,
'lintUselessOverridingMethods' => self::LINT_USELESS_OVERRIDING_METHOD,
'lintNoParentScope' => self::LINT_NO_PARENT_SCOPE,
'lintAliasFunctions' => self::LINT_ALIAS_FUNCTION,
'lintCastSpacing' => self::LINT_CAST_SPACING,
'lintThrowExceptionInToStringMethod' => self::LINT_TOSTRING_EXCEPTION,
'lintLambdaFuncFunction' => self::LINT_LAMBDA_FUNC_FUNCTION,
'lintInstanceOfOperator' => self::LINT_INSTANCEOF_OPERATOR,
'lintInvalidDefaultParameters' => self::LINT_INVALID_DEFAULT_PARAMETER,
'lintMethodModifierOrdering' => self::LINT_MODIFIER_ORDERING,
'lintPropertyModifierOrdering' => self::LINT_MODIFIER_ORDERING,
'lintInvalidModifiers' => self::LINT_INVALID_MODIFIERS,
);
foreach ($method_codes as $method => $codes) {
foreach ((array)$codes as $code) {
if ($this->isCodeEnabled($code)) {
call_user_func(array($this, $method), $root);
break;
}
}
}
}
private function lintStrstrUsedForCheck(XHPASTNode $root) {
$expressions = $root->selectDescendantsOfType('n_BINARY_EXPRESSION');
foreach ($expressions as $expression) {
$operator = $expression->getChildOfType(1, 'n_OPERATOR');
$operator = $operator->getConcreteString();
if ($operator !== '===' && $operator !== '!==') {
continue;
}
$false = $expression->getChildByIndex(0);
if ($false->getTypeName() === 'n_SYMBOL_NAME' &&
$false->getConcreteString() === 'false') {
$strstr = $expression->getChildByIndex(2);
} else {
$strstr = $false;
$false = $expression->getChildByIndex(2);
if ($false->getTypeName() !== 'n_SYMBOL_NAME' ||
$false->getConcreteString() !== 'false') {
continue;
}
}
if ($strstr->getTypeName() !== 'n_FUNCTION_CALL') {
continue;
}
$name = strtolower($strstr->getChildByIndex(0)->getConcreteString());
if ($name === 'strstr' || $name === 'strchr') {
$this->raiseLintAtNode(
$strstr,
self::LINT_SLOWNESS,
pht(
'Use %s for checking if the string contains something.',
'strpos()'));
} else if ($name === 'stristr') {
$this->raiseLintAtNode(
$strstr,
self::LINT_SLOWNESS,
pht(
'Use %s for checking if the string contains something.',
'stripos()'));
}
}
}
private function lintStrposUsedForStart(XHPASTNode $root) {
$expressions = $root->selectDescendantsOfType('n_BINARY_EXPRESSION');
foreach ($expressions as $expression) {
$operator = $expression->getChildOfType(1, 'n_OPERATOR');
$operator = $operator->getConcreteString();
if ($operator !== '===' && $operator !== '!==') {
continue;
}
$zero = $expression->getChildByIndex(0);
if ($zero->getTypeName() === 'n_NUMERIC_SCALAR' &&
$zero->getConcreteString() === '0') {
$strpos = $expression->getChildByIndex(2);
} else {
$strpos = $zero;
$zero = $expression->getChildByIndex(2);
if ($zero->getTypeName() !== 'n_NUMERIC_SCALAR' ||
$zero->getConcreteString() !== '0') {
continue;
}
}
if ($strpos->getTypeName() !== 'n_FUNCTION_CALL') {
continue;
}
$name = strtolower($strpos->getChildByIndex(0)->getConcreteString());
if ($name === 'strpos') {
$this->raiseLintAtNode(
$strpos,
self::LINT_SLOWNESS,
pht(
'Use %s for checking if the string starts with something.',
'strncmp()'));
} else if ($name === 'stripos') {
$this->raiseLintAtNode(
$strpos,
self::LINT_SLOWNESS,
pht(
'Use %s for checking if the string starts with something.',
'strncasecmp()'));
}
}
}
private function lintPHPCompatibility(XHPASTNode $root) {
static $compat_info;
if (!$this->version) {
return;
}
if ($compat_info === null) {
$target = phutil_get_library_root('phutil').
'/../resources/php_compat_info.json';
$compat_info = phutil_json_decode(Filesystem::readFile($target));
}
// Create a whitelist for symbols which are being used conditionally.
$whitelist = array(
'class' => array(),
'function' => array(),
);
$conditionals = $root->selectDescendantsOfType('n_IF');
foreach ($conditionals as $conditional) {
$condition = $conditional->getChildOfType(0, 'n_CONTROL_CONDITION');
$function = $condition->getChildByIndex(0);
if ($function->getTypeName() != 'n_FUNCTION_CALL') {
continue;
}
$function_token = $function
->getChildByIndex(0);
if ($function_token->getTypeName() != 'n_SYMBOL_NAME') {
// This may be `Class::method(...)` or `$var(...)`.
continue;
}
$function_name = $function_token->getConcreteString();
switch ($function_name) {
case 'class_exists':
case 'function_exists':
case 'interface_exists':
$type = null;
switch ($function_name) {
case 'class_exists':
$type = 'class';
break;
case 'function_exists':
$type = 'function';
break;
case 'interface_exists':
$type = 'interface';
break;
}
$params = $function->getChildOfType(1, 'n_CALL_PARAMETER_LIST');
$symbol = $params->getChildByIndex(0);
if (!$symbol->isStaticScalar()) {
continue;
}
$symbol_name = $symbol->evalStatic();
if (!idx($whitelist[$type], $symbol_name)) {
$whitelist[$type][$symbol_name] = array();
}
$span = $conditional
->getChildByIndex(1)
->getTokens();
$whitelist[$type][$symbol_name][] = range(
head_key($span),
last_key($span));
break;
}
}
$calls = $root->selectDescendantsOfType('n_FUNCTION_CALL');
foreach ($calls as $call) {
$node = $call->getChildByIndex(0);
$name = $node->getConcreteString();
$version = idx($compat_info['functions'], $name, array());
$min = idx($version, 'php.min');
$max = idx($version, 'php.max');
// Check if whitelisted.
$whitelisted = false;
foreach (idx($whitelist['function'], $name, array()) as $range) {
if (array_intersect($range, array_keys($node->getTokens()))) {
$whitelisted = true;
break;
}
}
if ($whitelisted) {
continue;
}
if ($min && version_compare($min, $this->version, '>')) {
$this->raiseLintAtNode(
$node,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s, but `%s()` was not '.
'introduced until PHP %s.',
$this->version,
$name,
$min));
} else if ($max && version_compare($max, $this->version, '<')) {
$this->raiseLintAtNode(
$node,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s, but `%s()` was '.
'removed in PHP %s.',
$this->version,
$name,
$max));
} else if (array_key_exists($name, $compat_info['params'])) {
$params = $call->getChildOfType(1, 'n_CALL_PARAMETER_LIST');
foreach (array_values($params->getChildren()) as $i => $param) {
$version = idx($compat_info['params'][$name], $i);
if ($version && version_compare($version, $this->version, '>')) {
$this->raiseLintAtNode(
$param,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s, but parameter %d '.
'of `%s()` was not introduced until PHP %s.',
$this->version,
$i + 1,
$name,
$version));
}
}
}
if ($this->windowsVersion) {
$windows = idx($compat_info['functions_windows'], $name);
if ($windows === false) {
$this->raiseLintAtNode(
$node,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s on Windows, '.
'but `%s()` is not available there.',
$this->windowsVersion,
$name));
} else if (version_compare($windows, $this->windowsVersion, '>')) {
$this->raiseLintAtNode(
$node,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s on Windows, '.
'but `%s()` is not available there until PHP %s.',
$this->windowsVersion,
$name,
$windows));
}
}
}
$classes = $root->selectDescendantsOfType('n_CLASS_NAME');
foreach ($classes as $node) {
$name = $node->getConcreteString();
$version = idx($compat_info['interfaces'], $name, array());
$version = idx($compat_info['classes'], $name, $version);
$min = idx($version, 'php.min');
$max = idx($version, 'php.max');
// Check if whitelisted.
$whitelisted = false;
foreach (idx($whitelist['class'], $name, array()) as $range) {
if (array_intersect($range, array_keys($node->getTokens()))) {
$whitelisted = true;
break;
}
}
if ($whitelisted) {
continue;
}
if ($min && version_compare($min, $this->version, '>')) {
$this->raiseLintAtNode(
$node,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s, but `%s` was not '.
'introduced until PHP %s.',
$this->version,
$name,
$min));
} else if ($max && version_compare($max, $this->version, '<')) {
$this->raiseLintAtNode(
$node,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s, but `%s` was '.
'removed in PHP %s.',
$this->version,
$name,
$max));
}
}
// TODO: Technically, this will include function names. This is unlikely to
// cause any issues (unless, of course, there existed a function that had
// the same name as some constant).
$constants = $root->selectDescendantsOfTypes(array(
'n_SYMBOL_NAME',
'n_MAGIC_SCALAR',
));
foreach ($constants as $node) {
$name = $node->getConcreteString();
$version = idx($compat_info['constants'], $name, array());
$min = idx($version, 'php.min');
$max = idx($version, 'php.max');
if ($min && version_compare($min, $this->version, '>')) {
$this->raiseLintAtNode(
$node,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s, but `%s` was not '.
'introduced until PHP %s.',
$this->version,
$name,
$min));
} else if ($max && version_compare($max, $this->version, '<')) {
$this->raiseLintAtNode(
$node,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s, but `%s` was '.
'removed in PHP %s.',
$this->version,
$name,
$max));
}
}
if (version_compare($this->version, '5.3.0') < 0) {
$this->lintPHP53Features($root);
} else {
$this->lintPHP53Incompatibilities($root);
}
if (version_compare($this->version, '5.4.0') < 0) {
$this->lintPHP54Features($root);
} else {
$this->lintPHP54Incompatibilities($root);
}
}
private function lintPHP53Features(XHPASTNode $root) {
$functions = $root->selectTokensOfType('T_FUNCTION');
foreach ($functions as $function) {
$next = $function->getNextToken();
while ($next) {
if ($next->isSemantic()) {
break;
}
$next = $next->getNextToken();
}
if ($next) {
if ($next->getTypeName() === '(') {
$this->raiseLintAtToken(
$function,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s, but anonymous '.
'functions were not introduced until PHP 5.3.',
$this->version));
}
}
}
$namespaces = $root->selectTokensOfType('T_NAMESPACE');
foreach ($namespaces as $namespace) {
$this->raiseLintAtToken(
$namespace,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s, but namespaces were not '.
'introduced until PHP 5.3.',
$this->version));
}
// NOTE: This is only "use x;", in anonymous functions the node type is
// n_LEXICAL_VARIABLE_LIST even though both tokens are T_USE.
// TODO: We parse n_USE in a slightly crazy way right now; that would be
// a better selector once it's fixed.
$uses = $root->selectDescendantsOfType('n_USE_LIST');
foreach ($uses as $use) {
$this->raiseLintAtNode(
$use,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s, but namespaces were not '.
'introduced until PHP 5.3.',
$this->version));
}
$statics = $root->selectDescendantsOfType('n_CLASS_STATIC_ACCESS');
foreach ($statics as $static) {
$name = $static->getChildByIndex(0);
if ($name->getTypeName() != 'n_CLASS_NAME') {
continue;
}
if ($name->getConcreteString() === 'static') {
$this->raiseLintAtNode(
$name,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s, but `static::` was not '.
'introduced until PHP 5.3.',
$this->version));
}
}
$ternaries = $root->selectDescendantsOfType('n_TERNARY_EXPRESSION');
foreach ($ternaries as $ternary) {
$yes = $ternary->getChildByIndex(1);
if ($yes->getTypeName() === 'n_EMPTY') {
$this->raiseLintAtNode(
$ternary,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s, but short ternary was '.
'not introduced until PHP 5.3.',
$this->version));
}
}
$heredocs = $root->selectDescendantsOfType('n_HEREDOC');
foreach ($heredocs as $heredoc) {
if (preg_match('/^<<<[\'"]/', $heredoc->getConcreteString())) {
$this->raiseLintAtNode(
$heredoc,
self::LINT_PHP_COMPATIBILITY,
pht(
'This codebase targets PHP %s, but nowdoc was not '.
'introduced until PHP 5.3.',
$this->version));
}
}
}
private function lintPHP53Incompatibilities(XHPASTNode $root) {}
private function lintPHP54Features(XHPASTNode $root) {
$indexes = $root->selectDescendantsOfType('n_INDEX_ACCESS');
foreach ($indexes as $index) {
switch ($index->getChildByIndex(0)->getTypeName()) {
case 'n_FUNCTION_CALL':
case 'n_METHOD_CALL':
$this->raiseLintAtNode(
$index->getChildByIndex(1),
self::LINT_PHP_COMPATIBILITY,
pht(
'The `%s` syntax was not introduced until PHP 5.4, but this '.
'codebase targets an earlier version of PHP. You can rewrite '.
'this expression using `%s`.',
'f()[...]',
'idx()'));
break;
}
}
}
private function lintPHP54Incompatibilities(XHPASTNode $root) {
$breaks = $root->selectDescendantsOfTypes(array('n_BREAK', 'n_CONTINUE'));
foreach ($breaks as $break) {
$arg = $break->getChildByIndex(0);
switch ($arg->getTypeName()) {
case 'n_EMPTY':
break;
case 'n_NUMERIC_SCALAR':
if ($arg->getConcreteString() != '0') {
break;
}
default:
$this->raiseLintAtNode(
$break->getChildByIndex(0),
self::LINT_PHP_COMPATIBILITY,
pht(
'The `%s` and `%s` statements no longer accept '.
'variable arguments.',
'break',
'continue'));
break;
}
}
}
private function lintImplicitFallthrough(XHPASTNode $root) {
$hook_obj = null;
$hook_class = $this->switchhook;
if ($hook_class) {
$hook_obj = newv($hook_class, array());
assert_instances_of(array($hook_obj), 'ArcanistXHPASTLintSwitchHook');
}
$switches = $root->selectDescendantsOfType('n_SWITCH');
foreach ($switches as $switch) {
$blocks = array();
$cases = $switch->selectDescendantsOfType('n_CASE');
foreach ($cases as $case) {
$blocks[] = $case;
}
$defaults = $switch->selectDescendantsOfType('n_DEFAULT');
foreach ($defaults as $default) {
$blocks[] = $default;
}
foreach ($blocks as $key => $block) {
// Collect all the tokens in this block which aren't at top level.
// We want to ignore "break", and "continue" in these blocks.
$lower_level = $block->selectDescendantsOfTypes(array(
'n_WHILE',
'n_DO_WHILE',
'n_FOR',
'n_FOREACH',
'n_SWITCH',
));
$lower_level_tokens = array();
foreach ($lower_level as $lower_level_block) {
$lower_level_tokens += $lower_level_block->getTokens();
}
// Collect all the tokens in this block which aren't in this scope
// (because they're inside class, function or interface declarations).
// We want to ignore all of these tokens.
$decls = $block->selectDescendantsOfTypes(array(
'n_FUNCTION_DECLARATION',
'n_CLASS_DECLARATION',
// For completeness; these can't actually have anything.
'n_INTERFACE_DECLARATION',
));
$different_scope_tokens = array();
foreach ($decls as $decl) {
$different_scope_tokens += $decl->getTokens();
}
$lower_level_tokens += $different_scope_tokens;
// Get all the trailing nonsemantic tokens, since we need to look for
// "fallthrough" comments past the end of the semantic block.
$tokens = $block->getTokens();
$last = end($tokens);
while ($last && $last = $last->getNextToken()) {
if ($last->isSemantic()) {
break;
}
$tokens[$last->getTokenID()] = $last;
}
$blocks[$key] = array(
$tokens,
$lower_level_tokens,
$different_scope_tokens,
);
}
foreach ($blocks as $token_lists) {
list(
$tokens,
$lower_level_tokens,
$different_scope_tokens) = $token_lists;
// Test each block (case or default statement) to see if it's OK. It's
// OK if:
//
// - it is empty; or
// - it ends in break, return, throw, continue or exit at top level; or
// - it has a comment with "fallthrough" in its text.
// Empty blocks are OK, so we start this at `true` and only set it to
// false if we find a statement.
$block_ok = true;
// Keeps track of whether the current statement is one that validates
// the block (break, return, throw, continue) or something else.
$statement_ok = false;
foreach ($tokens as $token_id => $token) {
if (!$token->isSemantic()) {
// Liberally match "fall" in the comment text so that comments like
// "fallthru", "fall through", "fallthrough", etc., are accepted.
if (preg_match('/fall/i', $token->getValue())) {
$block_ok = true;
break;
}
continue;
}
$tok_type = $token->getTypeName();
if ($tok_type === 'T_FUNCTION' ||
$tok_type === 'T_CLASS' ||
$tok_type === 'T_INTERFACE') {
// These aren't statements, but mark the block as nonempty anyway.
$block_ok = false;
continue;
}
if ($tok_type === ';') {
if ($statement_ok) {
$statment_ok = false;
} else {
$block_ok = false;
}
continue;
}
if ($tok_type === 'T_BREAK' || $tok_type === 'T_CONTINUE') {
if (empty($lower_level_tokens[$token_id])) {
$statement_ok = true;
$block_ok = true;
}
continue;
}
if ($tok_type === 'T_RETURN' ||
$tok_type === 'T_THROW' ||
$tok_type === 'T_EXIT' ||
($hook_obj && $hook_obj->checkSwitchToken($token))) {
if (empty($different_scope_tokens[$token_id])) {
$statement_ok = true;
$block_ok = true;
}
continue;
}
}
if (!$block_ok) {
$this->raiseLintAtToken(
head($tokens),
self::LINT_IMPLICIT_FALLTHROUGH,
pht(
"This '%s' or '%s' has a nonempty block which does not end ".
"with '%s', '%s', '%s', '%s' or '%s'. Did you forget to add ".
"one of those? If you intend to fall through, add a '%s' ".
"comment to silence this warning.",
'case',
'default',
'break',
'continue',
'return',
'throw',
'exit',
'// fallthrough'));
}
}
}
}
private function lintBraceFormatting(XHPASTNode $root) {
foreach ($root->selectDescendantsOfType('n_STATEMENT_LIST') as $list) {
$tokens = $list->getTokens();
if (!$tokens || head($tokens)->getValue() != '{') {
continue;
}
list($before, $after) = $list->getSurroundingNonsemanticTokens();
if (!$before) {
$first = head($tokens);
// Only insert the space if we're after a closing parenthesis. If
// we're in a construct like "else{}", other rules will insert space
// after the 'else' correctly.
$prev = $first->getPrevToken();
if (!$prev || $prev->getValue() !== ')') {
continue;
}
$this->raiseLintAtToken(
$first,
self::LINT_BRACE_FORMATTING,
pht(
'Put opening braces on the same line as control statements and '.
'declarations, with a single space before them.'),
' '.$first->getValue());
} else if (count($before) === 1) {
$before = reset($before);
if ($before->getValue() !== ' ') {
$this->raiseLintAtToken(
$before,
self::LINT_BRACE_FORMATTING,
pht(
'Put opening braces on the same line as control statements and '.
'declarations, with a single space before them.'),
' ');
}
}
}
$nodes = $root->selectDescendantsOfType('n_STATEMENT');
foreach ($nodes as $node) {
$parent = $node->getParentNode();
if (!$parent) {
continue;
}
$type = $parent->getTypeName();
if ($type != 'n_STATEMENT_LIST' && $type != 'n_DECLARE') {
$this->raiseLintAtNode(
$node,
self::LINT_BRACE_FORMATTING,
pht('Use braces to surround a statement block.'));
}
}
$nodes = $root->selectDescendantsOfTypes(array(
'n_DO_WHILE',
'n_ELSE',
'n_ELSEIF',
));
foreach ($nodes as $list) {
$tokens = $list->getTokens();
if (!$tokens || last($tokens)->getValue() != '}') {
continue;
}
list($before, $after) = $list->getSurroundingNonsemanticTokens();
if (!$before) {
$first = last($tokens);
$this->raiseLintAtToken(
$first,
self::LINT_BRACE_FORMATTING,
pht(
'Put opening braces on the same line as control statements and '.
'declarations, with a single space before them.'),
' '.$first->getValue());
} else if (count($before) === 1) {
$before = reset($before);
if ($before->getValue() !== ' ') {
$this->raiseLintAtToken(
$before,
self::LINT_BRACE_FORMATTING,
pht(
'Put opening braces on the same line as control statements and '.
'declarations, with a single space before them.'),
' ');
}
}
}
}
private function lintTautologicalExpressions(XHPASTNode $root) {
$expressions = $root->selectDescendantsOfType('n_BINARY_EXPRESSION');
static $operators = array(
'-' => true,
'/' => true,
'-=' => true,
'/=' => true,
'<=' => true,
'<' => true,
'==' => true,
'===' => true,
'!=' => true,
'!==' => true,
'>=' => true,
'>' => true,
);
static $logical = array(
'||' => true,
'&&' => true,
);
foreach ($expressions as $expr) {
$operator = $expr->getChildByIndex(1)->getConcreteString();
if (!empty($operators[$operator])) {
$left = $expr->getChildByIndex(0)->getSemanticString();
$right = $expr->getChildByIndex(2)->getSemanticString();
if ($left === $right) {
$this->raiseLintAtNode(
$expr,
self::LINT_TAUTOLOGICAL_EXPRESSION,
pht(
'Both sides of this expression are identical, so it always '.
'evaluates to a constant.'));
}
}
if (!empty($logical[$operator])) {
$left = $expr->getChildByIndex(0)->getSemanticString();
$right = $expr->getChildByIndex(2)->getSemanticString();
// NOTE: These will be null to indicate "could not evaluate".
$left = $this->evaluateStaticBoolean($left);
$right = $this->evaluateStaticBoolean($right);
if (($operator === '||' && ($left === true || $right === true)) ||
($operator === '&&' && ($left === false || $right === false))) {
$this->raiseLintAtNode(
$expr,
self::LINT_TAUTOLOGICAL_EXPRESSION,
pht(
'The logical value of this expression is static. '.
'Did you forget to remove some debugging code?'));
}
}
}
}
/**
* Statically evaluate a boolean value from an XHP tree.
*
* TODO: Improve this and move it to XHPAST proper?
*
* @param string The "semantic string" of a single value.
* @return mixed ##true## or ##false## if the value could be evaluated
* statically; ##null## if static evaluation was not possible.
*/
private function evaluateStaticBoolean($string) {
switch (strtolower($string)) {
case '0':
case 'null':
case 'false':
return false;
case '1':
case 'true':
return true;
}
return null;
}
protected function lintCommentSpaces(XHPASTNode $root) {
foreach ($root->selectTokensOfType('T_COMMENT') as $comment) {
$value = $comment->getValue();
if ($value[0] !== '#') {
$match = null;
if (preg_match('@^(/[/*]+)[^/*\s]@', $value, $match)) {
$this->raiseLintAtOffset(
$comment->getOffset(),
self::LINT_COMMENT_SPACING,
pht('Put space after comment start.'),
$match[1],
$match[1].' ');
}
}
}
}
protected function lintHashComments(XHPASTNode $root) {
foreach ($root->selectTokensOfType('T_COMMENT') as $comment) {
$value = $comment->getValue();
if ($value[0] !== '#') {
continue;
}
$this->raiseLintAtOffset(
$comment->getOffset(),
self::LINT_COMMENT_STYLE,
pht('Use "%s" single-line comments, not "%s".', '//', '#'),
'#',
(preg_match('/^#\S/', $value) ? '// ' : '//'));
}
}
/**
* Find cases where loops get nested inside each other but use the same
* iterator variable. For example:
*
* COUNTEREXAMPLE
* foreach ($list as $thing) {
* foreach ($stuff as $thing) { // <-- Raises an error for reuse of $thing
* // ...
* }
* }
*
*/
private function lintReusedIterators(XHPASTNode $root) {
$used_vars = array();
$for_loops = $root->selectDescendantsOfType('n_FOR');
foreach ($for_loops as $for_loop) {
$var_map = array();
// Find all the variables that are assigned to in the for() expression.
$for_expr = $for_loop->getChildOfType(0, 'n_FOR_EXPRESSION');
$bin_exprs = $for_expr->selectDescendantsOfType('n_BINARY_EXPRESSION');
foreach ($bin_exprs as $bin_expr) {
if ($bin_expr->getChildByIndex(1)->getConcreteString() === '=') {
$var = $bin_expr->getChildByIndex(0);
$var_map[$var->getConcreteString()] = $var;
}
}
$used_vars[$for_loop->getID()] = $var_map;
}
$foreach_loops = $root->selectDescendantsOfType('n_FOREACH');
foreach ($foreach_loops as $foreach_loop) {
$var_map = array();
$foreach_expr = $foreach_loop->getChildOfType(0, 'n_FOREACH_EXPRESSION');
// We might use one or two vars, i.e. "foreach ($x as $y => $z)" or
// "foreach ($x as $y)".
$possible_used_vars = array(
$foreach_expr->getChildByIndex(1),
$foreach_expr->getChildByIndex(2),
);
foreach ($possible_used_vars as $var) {
if ($var->getTypeName() === 'n_EMPTY') {
continue;
}
$name = $var->getConcreteString();
$name = trim($name, '&'); // Get rid of ref silliness.
$var_map[$name] = $var;
}
$used_vars[$foreach_loop->getID()] = $var_map;
}
$all_loops = $for_loops->add($foreach_loops);
foreach ($all_loops as $loop) {
$child_loops = $loop->selectDescendantsOfTypes(array(
'n_FOR',
'n_FOREACH',
));
$outer_vars = $used_vars[$loop->getID()];
foreach ($child_loops as $inner_loop) {
$inner_vars = $used_vars[$inner_loop->getID()];
$shared = array_intersect_key($outer_vars, $inner_vars);
if ($shared) {
$shared_desc = implode(', ', array_keys($shared));
$message = $this->raiseLintAtNode(
$inner_loop->getChildByIndex(0),
self::LINT_REUSED_ITERATORS,
pht(
'This loop reuses iterator variables (%s) from an '.
'outer loop. You might be clobbering the outer iterator. '.
'Change the inner loop to use a different iterator name.',
$shared_desc));
$locations = array();
foreach ($shared as $var) {
$locations[] = $this->getOtherLocation($var->getOffset());
}
$message->setOtherLocations($locations);
}
}
}
}
/**
* Find cases where a foreach loop is being iterated using a variable
* reference and the same variable is used outside of the loop without
* calling unset() or reassigning the variable to another variable
* reference.
*
* COUNTEREXAMPLE
* foreach ($ar as &$a) {
* // ...
* }
* $a = 1; // <-- Raises an error for using $a
*
*/
protected function lintReusedIteratorReferences(XHPASTNode $root) {
$defs = $root->selectDescendantsOfTypes(array(
'n_FUNCTION_DECLARATION',
'n_METHOD_DECLARATION',
));
foreach ($defs as $def) {
$body = $def->getChildByIndex(5);
if ($body->getTypeName() === 'n_EMPTY') {
// Abstract method declaration.
continue;
}
$exclude = array();
// Exclude uses of variables, unsets, and foreach loops
// within closures - they are checked on their own
$func_defs = $body->selectDescendantsOfType('n_FUNCTION_DECLARATION');
foreach ($func_defs as $func_def) {
$vars = $func_def->selectDescendantsOfType('n_VARIABLE');
foreach ($vars as $var) {
$exclude[$var->getID()] = true;
}
$unset_lists = $func_def->selectDescendantsOfType('n_UNSET_LIST');
foreach ($unset_lists as $unset_list) {
$exclude[$unset_list->getID()] = true;
}
$foreaches = $func_def->selectDescendantsOfType('n_FOREACH');
foreach ($foreaches as $foreach) {
$exclude[$foreach->getID()] = true;
}
}
// Find all variables that are unset within the scope
$unset_vars = array();
$unset_lists = $body->selectDescendantsOfType('n_UNSET_LIST');
foreach ($unset_lists as $unset_list) {
if (isset($exclude[$unset_list->getID()])) {
continue;
}
$unset_list_vars = $unset_list->selectDescendantsOfType('n_VARIABLE');
foreach ($unset_list_vars as $var) {
$concrete = $this->getConcreteVariableString($var);
$unset_vars[$concrete][] = $var->getOffset();
$exclude[$var->getID()] = true;
}
}
// Find all reference variables in foreach expressions
$reference_vars = array();
$foreaches = $body->selectDescendantsOfType('n_FOREACH');
foreach ($foreaches as $foreach) {
if (isset($exclude[$foreach->getID()])) {
continue;
}
$foreach_expr = $foreach->getChildOfType(0, 'n_FOREACH_EXPRESSION');
$var = $foreach_expr->getChildByIndex(2);
if ($var->getTypeName() !== 'n_VARIABLE_REFERENCE') {
continue;
}
$reference = $var->getChildByIndex(0);
if ($reference->getTypeName() !== 'n_VARIABLE') {
continue;
}
$reference_name = $this->getConcreteVariableString($reference);
$reference_vars[$reference_name][] = $reference->getOffset();
$exclude[$reference->getID()] = true;
// Exclude uses of the reference variable within the foreach loop
$foreach_vars = $foreach->selectDescendantsOfType('n_VARIABLE');
foreach ($foreach_vars as $var) {
$name = $this->getConcreteVariableString($var);
if ($name === $reference_name) {
$exclude[$var->getID()] = true;
}
}
}
// Allow usage if the reference variable is assigned to another
// reference variable
$binary = $body->selectDescendantsOfType('n_BINARY_EXPRESSION');
foreach ($binary as $expr) {
if ($expr->getChildByIndex(1)->getConcreteString() !== '=') {
continue;
}
$lval = $expr->getChildByIndex(0);
if ($lval->getTypeName() !== 'n_VARIABLE') {
continue;
}
$rval = $expr->getChildByIndex(2);
if ($rval->getTypeName() !== 'n_VARIABLE_REFERENCE') {
continue;
}
// Counts as unsetting a variable
$concrete = $this->getConcreteVariableString($lval);
$unset_vars[$concrete][] = $lval->getOffset();
$exclude[$lval->getID()] = true;
}
$all_vars = array();
$all = $body->selectDescendantsOfType('n_VARIABLE');
foreach ($all as $var) {
if (isset($exclude[$var->getID()])) {
continue;
}
$name = $this->getConcreteVariableString($var);
if (!isset($reference_vars[$name])) {
continue;
}
// Find the closest reference offset to this variable
$reference_offset = null;
foreach ($reference_vars[$name] as $offset) {
if ($offset < $var->getOffset()) {
$reference_offset = $offset;
} else {
break;
}
}
if (!$reference_offset) {
continue;
}
// Check if an unset exists between reference and usage of this
// variable
$warn = true;
if (isset($unset_vars[$name])) {
foreach ($unset_vars[$name] as $unset_offset) {
if ($unset_offset > $reference_offset &&
$unset_offset < $var->getOffset()) {
$warn = false;
break;
}
}
}
if ($warn) {
$this->raiseLintAtNode(
$var,
self::LINT_REUSED_ITERATOR_REFERENCE,
pht(
'This variable was used already as a by-reference iterator '.
'variable. Such variables survive outside the foreach loop, '.
'do not reuse.'));
}
}
}
}
protected function lintVariableVariables(XHPASTNode $root) {
$vvars = $root->selectDescendantsOfType('n_VARIABLE_VARIABLE');
foreach ($vvars as $vvar) {
$this->raiseLintAtNode(
$vvar,
self::LINT_VARIABLE_VARIABLE,
pht(
'Rewrite this code to use an array. Variable variables are unclear '.
'and hinder static analysis.'));
}
}
private function lintUndeclaredVariables(XHPASTNode $root) {
// These things declare variables in a function:
// Explicit parameters
// Assignment
// Assignment via list()
// Static
// Global
// Lexical vars
// Builtins ($this)
// foreach()
// catch
//
// These things make lexical scope unknowable:
// Use of extract()
// Assignment to variable variables ($$x)
// Global with variable variables
//
// These things don't count as "using" a variable:
// isset()
// empty()
// Static class variables
//
// The general approach here is to find each function/method declaration,
// then:
//
// 1. Identify all the variable declarations, and where they first occur
// in the function/method declaration.
// 2. Identify all the uses that don't really count (as above).
// 3. Everything else must be a use of a variable.
// 4. For each variable, check if any uses occur before the declaration
// and warn about them.
//
// We also keep track of where lexical scope becomes unknowable (e.g.,
// because the function calls extract() or uses dynamic variables,
// preventing us from keeping track of which variables are defined) so we
// can stop issuing warnings after that.
//
// TODO: Support functions defined inside other functions which is commonly
// used with anonymous functions.
$defs = $root->selectDescendantsOfTypes(array(
'n_FUNCTION_DECLARATION',
'n_METHOD_DECLARATION',
));
foreach ($defs as $def) {
// We keep track of the first offset where scope becomes unknowable, and
// silence any warnings after that. Default it to INT_MAX so we can min()
// it later to keep track of the first problem we encounter.
$scope_destroyed_at = PHP_INT_MAX;
$declarations = array(
'$this' => 0,
) + array_fill_keys($this->getSuperGlobalNames(), 0);
$declaration_tokens = array();
$exclude_tokens = array();
$vars = array();
// First up, find all the different kinds of declarations, as explained
// above. Put the tokens into the $vars array.
$param_list = $def->getChildOfType(3, 'n_DECLARATION_PARAMETER_LIST');
$param_vars = $param_list->selectDescendantsOfType('n_VARIABLE');
foreach ($param_vars as $var) {
$vars[] = $var;
}
// This is PHP5.3 closure syntax: function () use ($x) {};
$lexical_vars = $def
->getChildByIndex(4)
->selectDescendantsOfType('n_VARIABLE');
foreach ($lexical_vars as $var) {
$vars[] = $var;
}
$body = $def->getChildByIndex(5);
if ($body->getTypeName() === 'n_EMPTY') {
// Abstract method declaration.
continue;
}
$static_vars = $body
->selectDescendantsOfType('n_STATIC_DECLARATION')
->selectDescendantsOfType('n_VARIABLE');
foreach ($static_vars as $var) {
$vars[] = $var;
}
$global_vars = $body
->selectDescendantsOfType('n_GLOBAL_DECLARATION_LIST');
foreach ($global_vars as $var_list) {
foreach ($var_list->getChildren() as $var) {
if ($var->getTypeName() === 'n_VARIABLE') {
$vars[] = $var;
} else {
// Dynamic global variable, i.e. "global $$x;".
$scope_destroyed_at = min($scope_destroyed_at, $var->getOffset());
// An error is raised elsewhere, no need to raise here.
}
}
}
// Include "catch (Exception $ex)", but not variables in the body of the
// catch block.
$catches = $body->selectDescendantsOfType('n_CATCH');
foreach ($catches as $catch) {
$vars[] = $catch->getChildOfType(1, 'n_VARIABLE');
}
$binary = $body->selectDescendantsOfType('n_BINARY_EXPRESSION');
foreach ($binary as $expr) {
if ($expr->getChildByIndex(1)->getConcreteString() !== '=') {
continue;
}
$lval = $expr->getChildByIndex(0);
if ($lval->getTypeName() === 'n_VARIABLE') {
$vars[] = $lval;
} else if ($lval->getTypeName() === 'n_LIST') {
// Recursivey grab everything out of list(), since the grammar
// permits list() to be nested. Also note that list() is ONLY valid
// as an lval assignments, so we could safely lift this out of the
// n_BINARY_EXPRESSION branch.
$assign_vars = $lval->selectDescendantsOfType('n_VARIABLE');
foreach ($assign_vars as $var) {
$vars[] = $var;
}
}
if ($lval->getTypeName() === 'n_VARIABLE_VARIABLE') {
$scope_destroyed_at = min($scope_destroyed_at, $lval->getOffset());
// No need to raise here since we raise an error elsewhere.
}
}
$calls = $body->selectDescendantsOfType('n_FUNCTION_CALL');
foreach ($calls as $call) {
$name = strtolower($call->getChildByIndex(0)->getConcreteString());
if ($name === 'empty' || $name === 'isset') {
$params = $call
->getChildOfType(1, 'n_CALL_PARAMETER_LIST')
->selectDescendantsOfType('n_VARIABLE');
foreach ($params as $var) {
$exclude_tokens[$var->getID()] = true;
}
continue;
}
if ($name !== 'extract') {
continue;
}
$scope_destroyed_at = min($scope_destroyed_at, $call->getOffset());
$this->raiseLintAtNode(
$call,
self::LINT_EXTRACT_USE,
pht(
'Avoid %s. It is confusing and hinders static analysis.',
'extract()'));
}
// Now we have every declaration except foreach(), handled below. Build
// two maps, one which just keeps track of which tokens are part of
// declarations ($declaration_tokens) and one which has the first offset
// where a variable is declared ($declarations).
foreach ($vars as $var) {
$concrete = $this->getConcreteVariableString($var);
$declarations[$concrete] = min(
idx($declarations, $concrete, PHP_INT_MAX),
$var->getOffset());
$declaration_tokens[$var->getID()] = true;
}
// Excluded tokens are ones we don't "count" as being used, described
// above. Put them into $exclude_tokens.
$class_statics = $body
->selectDescendantsOfType('n_CLASS_STATIC_ACCESS');
$class_static_vars = $class_statics
->selectDescendantsOfType('n_VARIABLE');
foreach ($class_static_vars as $var) {
$exclude_tokens[$var->getID()] = true;
}
// Find all the variables in scope, and figure out where they are used.
// We want to find foreach() iterators which are both declared before and
// used after the foreach() loop.
$uses = array();
$all_vars = $body->selectDescendantsOfType('n_VARIABLE');
$all = array();
// NOTE: $all_vars is not a real array so we can't unset() it.
foreach ($all_vars as $var) {
// Be strict since it's easier; we don't let you reuse an iterator you
// declared before a loop after the loop, even if you're just assigning
// to it.
$concrete = $this->getConcreteVariableString($var);
$uses[$concrete][$var->getID()] = $var->getOffset();
if (isset($declaration_tokens[$var->getID()])) {
// We know this is part of a declaration, so it's fine.
continue;
}
if (isset($exclude_tokens[$var->getID()])) {
// We know this is part of isset() or similar, so it's fine.
continue;
}
$all[$var->getOffset()] = $concrete;
}
// Do foreach() last, we want to handle implicit redeclaration of a
// variable already in scope since this probably means we're ovewriting a
// local.
// NOTE: Processing foreach expressions in order allows programs which
// reuse iterator variables in other foreach() loops -- this is fine. We
// have a separate warning to prevent nested loops from reusing the same
// iterators.
$foreaches = $body->selectDescendantsOfType('n_FOREACH');
$all_foreach_vars = array();
foreach ($foreaches as $foreach) {
$foreach_expr = $foreach->getChildOfType(0, 'n_FOREACH_EXPRESSION');
$foreach_vars = array();
// Determine the end of the foreach() loop.
$foreach_tokens = $foreach->getTokens();
$last_token = end($foreach_tokens);
$foreach_end = $last_token->getOffset();
$key_var = $foreach_expr->getChildByIndex(1);
if ($key_var->getTypeName() === 'n_VARIABLE') {
$foreach_vars[] = $key_var;
}
$value_var = $foreach_expr->getChildByIndex(2);
if ($value_var->getTypeName() === 'n_VARIABLE') {
$foreach_vars[] = $value_var;
} else {
// The root-level token may be a reference, as in:
// foreach ($a as $b => &$c) { ... }
// Reach into the n_VARIABLE_REFERENCE node to grab the n_VARIABLE
// node.
$var = $value_var->getChildByIndex(0);
if ($var->getTypeName() === 'n_VARIABLE_VARIABLE') {
$var = $var->getChildByIndex(0);
}
$foreach_vars[] = $var;
}
// Remove all uses of the iterators inside of the foreach() loop from
// the $uses map.
foreach ($foreach_vars as $var) {
$concrete = $this->getConcreteVariableString($var);
$offset = $var->getOffset();
foreach ($uses[$concrete] as $id => $use_offset) {
if (($use_offset >= $offset) && ($use_offset < $foreach_end)) {
unset($uses[$concrete][$id]);
}
}
$all_foreach_vars[] = $var;
}
}
foreach ($all_foreach_vars as $var) {
$concrete = $this->getConcreteVariableString($var);
$offset = $var->getOffset();
// If a variable was declared before a foreach() and is used after
// it, raise a message.
if (isset($declarations[$concrete])) {
if ($declarations[$concrete] < $offset) {
if (!empty($uses[$concrete]) &&
max($uses[$concrete]) > $offset) {
$message = $this->raiseLintAtNode(
$var,
self::LINT_REUSED_AS_ITERATOR,
- 'This iterator variable is a previously declared local '.
- 'variable. To avoid overwriting locals, do not reuse them '.
- 'as iterator variables.');
+ pht(
+ 'This iterator variable is a previously declared local '.
+ 'variable. To avoid overwriting locals, do not reuse them '.
+ 'as iterator variables.'));
$message->setOtherLocations(array(
$this->getOtherLocation($declarations[$concrete]),
$this->getOtherLocation(max($uses[$concrete])),
));
}
}
}
// This is a declaration, exclude it from the "declare variables prior
// to use" check below.
unset($all[$var->getOffset()]);
$vars[] = $var;
}
// Now rebuild declarations to include foreach().
foreach ($vars as $var) {
$concrete = $this->getConcreteVariableString($var);
$declarations[$concrete] = min(
idx($declarations, $concrete, PHP_INT_MAX),
$var->getOffset());
$declaration_tokens[$var->getID()] = true;
}
foreach (array('n_STRING_SCALAR', 'n_HEREDOC') as $type) {
foreach ($body->selectDescendantsOfType($type) as $string) {
foreach ($string->getStringVariables() as $offset => $var) {
$all[$string->getOffset() + $offset - 1] = '$'.$var;
}
}
}
// Issue a warning for every variable token, unless it appears in a
// declaration, we know about a prior declaration, we have explicitly
// exlcuded it, or scope has been made unknowable before it appears.
$issued_warnings = array();
foreach ($all as $offset => $concrete) {
if ($offset >= $scope_destroyed_at) {
// This appears after an extract() or $$var so we have no idea
// whether it's legitimate or not. We raised a harshly-worded warning
// when scope was made unknowable, so just ignore anything we can't
// figure out.
continue;
}
if ($offset >= idx($declarations, $concrete, PHP_INT_MAX)) {
// The use appears after the variable is declared, so it's fine.
continue;
}
if (!empty($issued_warnings[$concrete])) {
// We've already issued a warning for this variable so we don't need
// to issue another one.
continue;
}
$this->raiseLintAtOffset(
$offset,
self::LINT_UNDECLARED_VARIABLE,
pht(
'Declare variables prior to use (even if you are passing them '.
'as reference parameters). You may have misspelled this '.
'variable name.'),
$concrete);
$issued_warnings[$concrete] = true;
}
}
}
private function getConcreteVariableString(XHPASTNode $var) {
$concrete = $var->getConcreteString();
// Strip off curly braces as in $obj->{$property}.
$concrete = trim($concrete, '{}');
return $concrete;
}
private function lintPHPTagUse(XHPASTNode $root) {
$tokens = $root->getTokens();
foreach ($tokens as $token) {
if ($token->getTypeName() === 'T_OPEN_TAG') {
if (trim($token->getValue()) === '<?') {
$this->raiseLintAtToken(
$token,
self::LINT_PHP_SHORT_TAG,
pht(
'Use the full form of the PHP open tag, "%s".',
'<?php'),
"<?php\n");
}
break;
} else if ($token->getTypeName() === 'T_OPEN_TAG_WITH_ECHO') {
$this->raiseLintAtToken(
$token,
self::LINT_PHP_ECHO_TAG,
pht('Avoid the PHP echo short form, "%s".', '<?='));
break;
} else {
if (!preg_match('/^#!/', $token->getValue())) {
$this->raiseLintAtToken(
$token,
self::LINT_PHP_OPEN_TAG,
pht(
'PHP files should start with "%s", which may be preceded by '.
'a "%s" line for scripts.',
'<?php',
'#!'));
}
break;
}
}
foreach ($root->selectTokensOfType('T_CLOSE_TAG') as $token) {
$this->raiseLintAtToken(
$token,
self::LINT_PHP_CLOSE_TAG,
pht('Do not use the PHP closing tag, "%s".', '?>'));
}
}
private function lintNamingConventions(XHPASTNode $root) {
// We're going to build up a list of <type, name, token, error> tuples
// and then try to instantiate a hook class which has the opportunity to
// override us.
$names = array();
$classes = $root->selectDescendantsOfType('n_CLASS_DECLARATION');
foreach ($classes as $class) {
$name_token = $class->getChildByIndex(1);
$name_string = $name_token->getConcreteString();
$names[] = array(
'class',
$name_string,
$name_token,
ArcanistXHPASTLintNamingHook::isUpperCamelCase($name_string)
? null
: pht(
'Follow naming conventions: classes should be named using '.
'UpperCamelCase.'),
);
}
$ifaces = $root->selectDescendantsOfType('n_INTERFACE_DECLARATION');
foreach ($ifaces as $iface) {
$name_token = $iface->getChildByIndex(1);
$name_string = $name_token->getConcreteString();
$names[] = array(
'interface',
$name_string,
$name_token,
ArcanistXHPASTLintNamingHook::isUpperCamelCase($name_string)
? null
: pht(
'Follow naming conventions: interfaces should be named using '.
'UpperCamelCase.'),
);
}
$functions = $root->selectDescendantsOfType('n_FUNCTION_DECLARATION');
foreach ($functions as $function) {
$name_token = $function->getChildByIndex(2);
if ($name_token->getTypeName() === 'n_EMPTY') {
// Unnamed closure.
continue;
}
$name_string = $name_token->getConcreteString();
$names[] = array(
'function',
$name_string,
$name_token,
ArcanistXHPASTLintNamingHook::isLowercaseWithUnderscores(
ArcanistXHPASTLintNamingHook::stripPHPFunction($name_string))
? null
: pht(
'Follow naming conventions: functions should be named using '.
'lowercase_with_underscores.'),
);
}
$methods = $root->selectDescendantsOfType('n_METHOD_DECLARATION');
foreach ($methods as $method) {
$name_token = $method->getChildByIndex(2);
$name_string = $name_token->getConcreteString();
$names[] = array(
'method',
$name_string,
$name_token,
ArcanistXHPASTLintNamingHook::isLowerCamelCase(
ArcanistXHPASTLintNamingHook::stripPHPFunction($name_string))
? null
: pht(
'Follow naming conventions: methods should be named using '.
'lowerCamelCase.'),
);
}
$param_tokens = array();
$params = $root->selectDescendantsOfType('n_DECLARATION_PARAMETER_LIST');
foreach ($params as $param_list) {
foreach ($param_list->getChildren() as $param) {
$name_token = $param->getChildByIndex(1);
if ($name_token->getTypeName() === 'n_VARIABLE_REFERENCE') {
$name_token = $name_token->getChildOfType(0, 'n_VARIABLE');
}
$param_tokens[$name_token->getID()] = true;
$name_string = $name_token->getConcreteString();
$names[] = array(
'parameter',
$name_string,
$name_token,
ArcanistXHPASTLintNamingHook::isLowercaseWithUnderscores(
ArcanistXHPASTLintNamingHook::stripPHPVariable($name_string))
? null
: pht(
'Follow naming conventions: parameters should be named using '.
'lowercase_with_underscores.'),
);
}
}
$constants = $root->selectDescendantsOfType(
'n_CLASS_CONSTANT_DECLARATION_LIST');
foreach ($constants as $constant_list) {
foreach ($constant_list->getChildren() as $constant) {
$name_token = $constant->getChildByIndex(0);
$name_string = $name_token->getConcreteString();
$names[] = array(
'constant',
$name_string,
$name_token,
ArcanistXHPASTLintNamingHook::isUppercaseWithUnderscores($name_string)
? null
: pht(
'Follow naming conventions: class constants should be named '.
'using UPPERCASE_WITH_UNDERSCORES.'),
);
}
}
$member_tokens = array();
$props = $root->selectDescendantsOfType('n_CLASS_MEMBER_DECLARATION_LIST');
foreach ($props as $prop_list) {
foreach ($prop_list->getChildren() as $token_id => $prop) {
if ($prop->getTypeName() === 'n_CLASS_MEMBER_MODIFIER_LIST') {
continue;
}
$name_token = $prop->getChildByIndex(0);
$member_tokens[$name_token->getID()] = true;
$name_string = $name_token->getConcreteString();
$names[] = array(
'member',
$name_string,
$name_token,
ArcanistXHPASTLintNamingHook::isLowerCamelCase(
ArcanistXHPASTLintNamingHook::stripPHPVariable($name_string))
? null
: pht(
'Follow naming conventions: class properties should be named '.
'using lowerCamelCase.'),
);
}
}
$superglobal_map = array_fill_keys(
$this->getSuperGlobalNames(),
true);
$defs = $root->selectDescendantsOfTypes(array(
'n_FUNCTION_DECLARATION',
'n_METHOD_DECLARATION',
));
foreach ($defs as $def) {
$globals = $def->selectDescendantsOfType('n_GLOBAL_DECLARATION_LIST');
$globals = $globals->selectDescendantsOfType('n_VARIABLE');
$globals_map = array();
foreach ($globals as $global) {
$global_string = $global->getConcreteString();
$globals_map[$global_string] = true;
$names[] = array(
'user',
$global_string,
$global,
// No advice for globals, but hooks have an option to provide some.
null,
);
}
// Exclude access of static properties, since lint will be raised at
// their declaration if they're invalid and they may not conform to
// variable rules. This is slightly overbroad (includes the entire
// RHS of a "Class::..." token) to cover cases like "Class:$x[0]". These
// variables are simply made exempt from naming conventions.
$exclude_tokens = array();
$statics = $def->selectDescendantsOfType('n_CLASS_STATIC_ACCESS');
foreach ($statics as $static) {
$rhs = $static->getChildByIndex(1);
if ($rhs->getTypeName() == 'n_VARIABLE') {
$exclude_tokens[$rhs->getID()] = true;
} else {
$rhs_vars = $rhs->selectDescendantsOfType('n_VARIABLE');
foreach ($rhs_vars as $var) {
$exclude_tokens[$var->getID()] = true;
}
}
}
$vars = $def->selectDescendantsOfType('n_VARIABLE');
foreach ($vars as $token_id => $var) {
if (isset($member_tokens[$token_id])) {
continue;
}
if (isset($param_tokens[$token_id])) {
continue;
}
if (isset($exclude_tokens[$token_id])) {
continue;
}
$var_string = $var->getConcreteString();
// Awkward artifact of "$o->{$x}".
$var_string = trim($var_string, '{}');
if (isset($superglobal_map[$var_string])) {
continue;
}
if (isset($globals_map[$var_string])) {
continue;
}
$names[] = array(
'variable',
$var_string,
$var,
ArcanistXHPASTLintNamingHook::isLowercaseWithUnderscores(
ArcanistXHPASTLintNamingHook::stripPHPVariable($var_string))
? null
: pht(
'Follow naming conventions: variables should be named using '.
'lowercase_with_underscores.'),
);
}
}
// If a naming hook is configured, give it a chance to override the
// default results for all the symbol names.
$hook_class = $this->naminghook;
if ($hook_class) {
$hook_obj = newv($hook_class, array());
foreach ($names as $k => $name_attrs) {
list($type, $name, $token, $default) = $name_attrs;
$result = $hook_obj->lintSymbolName($type, $name, $default);
$names[$k][3] = $result;
}
}
// Raise anything we're left with.
foreach ($names as $k => $name_attrs) {
list($type, $name, $token, $result) = $name_attrs;
if ($result) {
$this->raiseLintAtNode(
$token,
self::LINT_NAMING_CONVENTIONS,
$result);
}
}
}
private function lintSurpriseConstructors(XHPASTNode $root) {
$classes = $root->selectDescendantsOfType('n_CLASS_DECLARATION');
foreach ($classes as $class) {
$class_name = $class->getChildByIndex(1)->getConcreteString();
$methods = $class->selectDescendantsOfType('n_METHOD_DECLARATION');
foreach ($methods as $method) {
$method_name_token = $method->getChildByIndex(2);
$method_name = $method_name_token->getConcreteString();
if (strtolower($class_name) === strtolower($method_name)) {
$this->raiseLintAtNode(
$method_name_token,
self::LINT_IMPLICIT_CONSTRUCTOR,
pht(
'Name constructors %s explicitly. This method is a constructor '.
' because it has the same name as the class it is defined in.',
'__construct()'));
}
}
}
}
private function lintParenthesesShouldHugExpressions(XHPASTNode $root) {
$all_paren_groups = $root->selectDescendantsOfTypes(array(
'n_CALL_PARAMETER_LIST',
'n_CONTROL_CONDITION',
'n_FOR_EXPRESSION',
'n_FOREACH_EXPRESSION',
'n_DECLARATION_PARAMETER_LIST',
));
foreach ($all_paren_groups as $group) {
$tokens = $group->getTokens();
$token_o = array_shift($tokens);
$token_c = array_pop($tokens);
if ($token_o->getTypeName() !== '(') {
throw new Exception(pht('Expected open parentheses.'));
}
if ($token_c->getTypeName() !== ')') {
throw new Exception(pht('Expected close parentheses.'));
}
$nonsem_o = $token_o->getNonsemanticTokensAfter();
$nonsem_c = $token_c->getNonsemanticTokensBefore();
if (!$nonsem_o) {
continue;
}
$raise = array();
$string_o = implode('', mpull($nonsem_o, 'getValue'));
if (preg_match('/^[ ]+$/', $string_o)) {
$raise[] = array($nonsem_o, $string_o);
}
if ($nonsem_o !== $nonsem_c) {
$string_c = implode('', mpull($nonsem_c, 'getValue'));
if (preg_match('/^[ ]+$/', $string_c)) {
$raise[] = array($nonsem_c, $string_c);
}
}
foreach ($raise as $warning) {
list($tokens, $string) = $warning;
$this->raiseLintAtOffset(
reset($tokens)->getOffset(),
self::LINT_PARENTHESES_SPACING,
pht('Parentheses should hug their contents.'),
$string,
'');
}
}
}
private function lintSpaceAfterControlStatementKeywords(XHPASTNode $root) {
foreach ($root->getTokens() as $id => $token) {
switch ($token->getTypeName()) {
case 'T_IF':
case 'T_ELSE':
case 'T_FOR':
case 'T_FOREACH':
case 'T_WHILE':
case 'T_DO':
case 'T_SWITCH':
$after = $token->getNonsemanticTokensAfter();
if (empty($after)) {
$this->raiseLintAtToken(
$token,
self::LINT_CONTROL_STATEMENT_SPACING,
pht('Convention: put a space after control statements.'),
$token->getValue().' ');
} else if (count($after) === 1) {
$space = head($after);
// If we have an else clause with braces, $space may not be
// a single white space. e.g.,
//
// if ($x)
// echo 'foo'
// else // <- $space is not " " but "\n ".
// echo 'bar'
//
// We just require it starts with either a whitespace or a newline.
if ($token->getTypeName() === 'T_ELSE' ||
$token->getTypeName() === 'T_DO') {
break;
}
if ($space->isAnyWhitespace() && $space->getValue() !== ' ') {
$this->raiseLintAtToken(
$space,
self::LINT_CONTROL_STATEMENT_SPACING,
pht('Convention: put a single space after control statements.'),
' ');
}
}
break;
}
}
}
private function lintSpaceAroundBinaryOperators(XHPASTNode $root) {
$expressions = $root->selectDescendantsOfType('n_BINARY_EXPRESSION');
foreach ($expressions as $expression) {
$operator = $expression->getChildByIndex(1);
$operator_value = $operator->getConcreteString();
list($before, $after) = $operator->getSurroundingNonsemanticTokens();
$replace = null;
if (empty($before) && empty($after)) {
$replace = " {$operator_value} ";
} else if (empty($before)) {
$replace = " {$operator_value}";
} else if (empty($after)) {
$replace = "{$operator_value} ";
}
if ($replace !== null) {
$this->raiseLintAtNode(
$operator,
self::LINT_BINARY_EXPRESSION_SPACING,
pht(
'Convention: logical and arithmetic operators should be '.
'surrounded by whitespace.'),
$replace);
}
}
$tokens = $root->selectTokensOfType(',');
foreach ($tokens as $token) {
$next = $token->getNextToken();
switch ($next->getTypeName()) {
case ')':
case 'T_WHITESPACE':
break;
default:
$this->raiseLintAtToken(
$token,
self::LINT_BINARY_EXPRESSION_SPACING,
pht('Convention: comma should be followed by space.'),
', ');
break;
}
}
$tokens = $root->selectTokensOfType('T_DOUBLE_ARROW');
foreach ($tokens as $token) {
$prev = $token->getPrevToken();
$next = $token->getNextToken();
$prev_type = $prev->getTypeName();
$next_type = $next->getTypeName();
$prev_space = ($prev_type === 'T_WHITESPACE');
$next_space = ($next_type === 'T_WHITESPACE');
$replace = null;
if (!$prev_space && !$next_space) {
$replace = ' => ';
} else if ($prev_space && !$next_space) {
$replace = '=> ';
} else if (!$prev_space && $next_space) {
$replace = ' =>';
}
if ($replace !== null) {
$this->raiseLintAtToken(
$token,
self::LINT_BINARY_EXPRESSION_SPACING,
pht('Convention: double arrow should be surrounded by whitespace.'),
$replace);
}
}
$parameters = $root->selectDescendantsOfType('n_DECLARATION_PARAMETER');
foreach ($parameters as $parameter) {
if ($parameter->getChildByIndex(2)->getTypeName() == 'n_EMPTY') {
continue;
}
$operator = head($parameter->selectTokensOfType('='));
$before = $operator->getNonsemanticTokensBefore();
$after = $operator->getNonsemanticTokensAfter();
$replace = null;
if (empty($before) && empty($after)) {
$replace = ' = ';
} else if (empty($before)) {
$replace = ' =';
} else if (empty($after)) {
$replace = '= ';
}
if ($replace !== null) {
$this->raiseLintAtToken(
$operator,
self::LINT_BINARY_EXPRESSION_SPACING,
pht(
'Convention: logical and arithmetic operators should be '.
'surrounded by whitespace.'),
$replace);
}
}
}
private function lintSpaceAroundConcatenationOperators(XHPASTNode $root) {
$tokens = $root->selectTokensOfType('.');
foreach ($tokens as $token) {
$prev = $token->getPrevToken();
$next = $token->getNextToken();
foreach (array('prev' => $prev, 'next' => $next) as $wtoken) {
if ($wtoken->getTypeName() !== 'T_WHITESPACE') {
continue;
}
$value = $wtoken->getValue();
if (strpos($value, "\n") !== false) {
// If the whitespace has a newline, it's conventional.
continue;
}
$next = $wtoken->getNextToken();
if ($next && $next->getTypeName() === 'T_COMMENT') {
continue;
}
$this->raiseLintAtToken(
$wtoken,
self::LINT_CONCATENATION_OPERATOR,
pht(
'Convention: no spaces around "%s" '.
'(string concatenation) operator.',
'.'),
'');
}
}
}
private function lintDynamicDefines(XHPASTNode $root) {
$calls = $this->getFunctionCalls($root, array('define'));
foreach ($calls as $call) {
$parameter_list = $call->getChildOfType(1, 'n_CALL_PARAMETER_LIST');
$defined = $parameter_list->getChildByIndex(0);
if (!$defined->isStaticScalar()) {
$this->raiseLintAtNode(
$defined,
self::LINT_DYNAMIC_DEFINE,
pht(
'First argument to %s must be a string literal.',
'define()'));
}
}
}
private function lintUseOfThisInStaticMethods(XHPASTNode $root) {
$classes = $root->selectDescendantsOfType('n_CLASS_DECLARATION');
foreach ($classes as $class) {
$methods = $class->selectDescendantsOfType('n_METHOD_DECLARATION');
foreach ($methods as $method) {
$attributes = $method
->getChildByIndex(0, 'n_METHOD_MODIFIER_LIST')
->selectDescendantsOfType('n_STRING');
$method_is_static = false;
$method_is_abstract = false;
foreach ($attributes as $attribute) {
if (strtolower($attribute->getConcreteString()) === 'static') {
$method_is_static = true;
}
if (strtolower($attribute->getConcreteString()) === 'abstract') {
$method_is_abstract = true;
}
}
if ($method_is_abstract) {
continue;
}
if (!$method_is_static) {
continue;
}
$body = $method->getChildOfType(5, 'n_STATEMENT_LIST');
$variables = $body->selectDescendantsOfType('n_VARIABLE');
foreach ($variables as $variable) {
if ($method_is_static &&
strtolower($variable->getConcreteString()) === '$this') {
$this->raiseLintAtNode(
$variable,
self::LINT_STATIC_THIS,
pht(
'You can not reference `%s` inside a static method.',
'$this'));
}
}
}
}
}
/**
* preg_quote() takes two arguments, but the second one is optional because
* it is possible to use (), [] or {} as regular expression delimiters. If
* you don't pass a second argument, you're probably going to get something
* wrong.
*/
private function lintPregQuote(XHPASTNode $root) {
$function_calls = $this->getFunctionCalls($root, array('preg_quote'));
foreach ($function_calls as $call) {
$parameter_list = $call->getChildOfType(1, 'n_CALL_PARAMETER_LIST');
if (count($parameter_list->getChildren()) !== 2) {
$this->raiseLintAtNode(
$call,
self::LINT_PREG_QUOTE_MISUSE,
pht(
'If you use pattern delimiters that require escaping '.
'(such as `%s`, but not `%s`) then you should pass two '.
'arguments to %s, so that %s knows which delimiter to escape.',
'//',
'()',
'preg_quote()',
'preg_quote()'));
}
}
}
/**
* Exit is parsed as an expression, but using it as such is almost always
* wrong. That is, this is valid:
*
* strtoupper(33 * exit - 6);
*
* When exit is used as an expression, it causes the program to terminate with
* exit code 0. This is likely not what is intended; these statements have
* different effects:
*
* exit(-1);
* exit -1;
*
* The former exits with a failure code, the latter with a success code!
*/
private function lintExitExpressions(XHPASTNode $root) {
$unaries = $root->selectDescendantsOfType('n_UNARY_PREFIX_EXPRESSION');
foreach ($unaries as $unary) {
$operator = $unary->getChildByIndex(0)->getConcreteString();
if (strtolower($operator) === 'exit') {
if ($unary->getParentNode()->getTypeName() !== 'n_STATEMENT') {
$this->raiseLintAtNode(
$unary,
self::LINT_EXIT_EXPRESSION,
pht('Use `%s` as a statement, not an expression.', 'exit'));
}
}
}
}
private function lintArrayIndexWhitespace(XHPASTNode $root) {
$indexes = $root->selectDescendantsOfType('n_INDEX_ACCESS');
foreach ($indexes as $index) {
$tokens = $index->getChildByIndex(0)->getTokens();
$last = array_pop($tokens);
$trailing = $last->getNonsemanticTokensAfter();
$trailing_text = implode('', mpull($trailing, 'getValue'));
if (preg_match('/^ +$/', $trailing_text)) {
$this->raiseLintAtOffset(
$last->getOffset() + strlen($last->getValue()),
self::LINT_ARRAY_INDEX_SPACING,
pht('Convention: no spaces before index access.'),
$trailing_text,
'');
}
}
}
private function lintTodoComments(XHPASTNode $root) {
$comments = $root->selectTokensOfTypes(array(
'T_COMMENT',
'T_DOC_COMMENT',
));
foreach ($comments as $token) {
$value = $token->getValue();
if ($token->getTypeName() === 'T_DOC_COMMENT') {
$regex = '/(TODO|@todo)/';
} else {
$regex = '/TODO/';
}
$matches = null;
$preg = preg_match_all(
$regex,
$value,
$matches,
PREG_OFFSET_CAPTURE);
foreach ($matches[0] as $match) {
list($string, $offset) = $match;
$this->raiseLintAtOffset(
$token->getOffset() + $offset,
self::LINT_TODO_COMMENT,
pht('This comment has a TODO.'),
$string);
}
}
}
/**
* Lint that if the file declares exactly one interface or class,
* the name of the file matches the name of the class,
* unless the classname is funky like an XHP element.
*/
private function lintPrimaryDeclarationFilenameMatch(XHPASTNode $root) {
$classes = $root->selectDescendantsOfType('n_CLASS_DECLARATION');
$interfaces = $root->selectDescendantsOfType('n_INTERFACE_DECLARATION');
if (count($classes) + count($interfaces) !== 1) {
return;
}
$declarations = count($classes) ? $classes : $interfaces;
$declarations->rewind();
$declaration = $declarations->current();
$decl_name = $declaration->getChildByIndex(1);
$decl_string = $decl_name->getConcreteString();
// Exclude strangely named classes, e.g. XHP tags.
if (!preg_match('/^\w+$/', $decl_string)) {
return;
}
$rename = $decl_string.'.php';
$path = $this->getActivePath();
$filename = basename($path);
if ($rename === $filename) {
return;
}
$this->raiseLintAtNode(
$decl_name,
self::LINT_CLASS_FILENAME_MISMATCH,
pht(
"The name of this file differs from the name of the ".
"class or interface it declares. Rename the file to '%s'.",
$rename));
}
private function lintPlusOperatorOnStrings(XHPASTNode $root) {
$binops = $root->selectDescendantsOfType('n_BINARY_EXPRESSION');
foreach ($binops as $binop) {
$op = $binop->getChildByIndex(1);
if ($op->getConcreteString() !== '+') {
continue;
}
$left = $binop->getChildByIndex(0);
$right = $binop->getChildByIndex(2);
if (($left->getTypeName() === 'n_STRING_SCALAR') ||
($right->getTypeName() === 'n_STRING_SCALAR')) {
$this->raiseLintAtNode(
$binop,
self::LINT_PLUS_OPERATOR_ON_STRINGS,
pht(
"In PHP, '%s' is the string concatenation operator, not '%s'. ".
"This expression uses '+' with a string literal as an operand.",
'.',
'+'));
}
}
}
/**
* Finds duplicate keys in array initializers, as in
* array(1 => 'anything', 1 => 'foo'). Since the first entry is ignored,
* this is almost certainly an error.
*/
private function lintDuplicateKeysInArray(XHPASTNode $root) {
$array_literals = $root->selectDescendantsOfType('n_ARRAY_LITERAL');
foreach ($array_literals as $array_literal) {
$nodes_by_key = array();
$keys_warn = array();
$list_node = $array_literal->getChildByIndex(0);
foreach ($list_node->getChildren() as $array_entry) {
$key_node = $array_entry->getChildByIndex(0);
switch ($key_node->getTypeName()) {
case 'n_STRING_SCALAR':
case 'n_NUMERIC_SCALAR':
// Scalars: array(1 => 'v1', '1' => 'v2');
$key = 'scalar:'.(string)$key_node->evalStatic();
break;
case 'n_SYMBOL_NAME':
case 'n_VARIABLE':
case 'n_CLASS_STATIC_ACCESS':
// Constants: array(CONST => 'v1', CONST => 'v2');
// Variables: array($a => 'v1', $a => 'v2');
// Class constants and vars: array(C::A => 'v1', C::A => 'v2');
$key = $key_node->getTypeName().':'.$key_node->getConcreteString();
break;
default:
$key = null;
break;
}
if ($key !== null) {
if (isset($nodes_by_key[$key])) {
$keys_warn[$key] = true;
}
$nodes_by_key[$key][] = $key_node;
}
}
foreach ($keys_warn as $key => $_) {
$node = array_pop($nodes_by_key[$key]);
$message = $this->raiseLintAtNode(
$node,
self::LINT_DUPLICATE_KEYS_IN_ARRAY,
pht(
'Duplicate key in array initializer. PHP will ignore all '.
'but the last entry.'));
$locations = array();
foreach ($nodes_by_key[$key] as $node) {
$locations[] = $this->getOtherLocation($node->getOffset());
}
$message->setOtherLocations($locations);
}
}
}
private function lintClosingCallParen(XHPASTNode $root) {
$calls = $root->selectDescendantsOfTypes(array(
'n_FUNCTION_CALL',
'n_METHOD_CALL',
));
foreach ($calls as $call) {
// If the last parameter of a call is a HEREDOC, don't apply this rule.
$params = $call
->getChildOfType(1, 'n_CALL_PARAMETER_LIST')
->getChildren();
if ($params) {
$last_param = last($params);
if ($last_param->getTypeName() === 'n_HEREDOC') {
continue;
}
}
$tokens = $call->getTokens();
$last = array_pop($tokens);
$trailing = $last->getNonsemanticTokensBefore();
$trailing_text = implode('', mpull($trailing, 'getValue'));
if (preg_match('/^\s+$/', $trailing_text)) {
$this->raiseLintAtOffset(
$last->getOffset() - strlen($trailing_text),
self::LINT_CLOSING_CALL_PAREN,
pht('Convention: no spaces before closing parenthesis in calls.'),
$trailing_text,
'');
}
}
}
private function lintClosingDeclarationParen(XHPASTNode $root) {
$decs = $root->selectDescendantsOfTypes(array(
'n_FUNCTION_DECLARATION',
'n_METHOD_DECLARATION',
));
foreach ($decs as $dec) {
$params = $dec->getChildOfType(3, 'n_DECLARATION_PARAMETER_LIST');
$tokens = $params->getTokens();
$last = array_pop($tokens);
$trailing = $last->getNonsemanticTokensBefore();
$trailing_text = implode('', mpull($trailing, 'getValue'));
if (preg_match('/^\s+$/', $trailing_text)) {
$this->raiseLintAtOffset(
$last->getOffset() - strlen($trailing_text),
self::LINT_CLOSING_DECL_PAREN,
pht(
'Convention: no spaces before closing parenthesis in '.
'function and method declarations.'),
$trailing_text,
'');
}
}
}
private function lintKeywordCasing(XHPASTNode $root) {
$keywords = $root->selectTokensOfTypes(array(
'T_REQUIRE_ONCE',
'T_REQUIRE',
'T_EVAL',
'T_INCLUDE_ONCE',
'T_INCLUDE',
'T_LOGICAL_OR',
'T_LOGICAL_XOR',
'T_LOGICAL_AND',
'T_PRINT',
'T_INSTANCEOF',
'T_CLONE',
'T_NEW',
'T_EXIT',
'T_IF',
'T_ELSEIF',
'T_ELSE',
'T_ENDIF',
'T_ECHO',
'T_DO',
'T_WHILE',
'T_ENDWHILE',
'T_FOR',
'T_ENDFOR',
'T_FOREACH',
'T_ENDFOREACH',
'T_DECLARE',
'T_ENDDECLARE',
'T_AS',
'T_SWITCH',
'T_ENDSWITCH',
'T_CASE',
'T_DEFAULT',
'T_BREAK',
'T_CONTINUE',
'T_GOTO',
'T_FUNCTION',
'T_CONST',
'T_RETURN',
'T_TRY',
'T_CATCH',
'T_THROW',
'T_USE',
'T_GLOBAL',
'T_PUBLIC',
'T_PROTECTED',
'T_PRIVATE',
'T_FINAL',
'T_ABSTRACT',
'T_STATIC',
'T_VAR',
'T_UNSET',
'T_ISSET',
'T_EMPTY',
'T_HALT_COMPILER',
'T_CLASS',
'T_INTERFACE',
'T_EXTENDS',
'T_IMPLEMENTS',
'T_LIST',
'T_ARRAY',
'T_NAMESPACE',
'T_INSTEADOF',
'T_CALLABLE',
'T_TRAIT',
'T_YIELD',
'T_FINALLY',
));
foreach ($keywords as $keyword) {
$value = $keyword->getValue();
if ($value != strtolower($value)) {
$this->raiseLintAtToken(
$keyword,
self::LINT_KEYWORD_CASING,
pht(
"Convention: spell keyword '%s' as '%s'.",
$value,
strtolower($value)),
strtolower($value));
}
}
$symbols = $root->selectDescendantsOfType('n_SYMBOL_NAME');
foreach ($symbols as $symbol) {
static $interesting_symbols = array(
'false' => true,
'null' => true,
'true' => true,
);
$symbol_name = $symbol->getConcreteString();
if ($symbol->getParentNode()->getTypeName() == 'n_FUNCTION_CALL') {
continue;
}
if (idx($interesting_symbols, strtolower($symbol_name))) {
if ($symbol_name != strtolower($symbol_name)) {
$this->raiseLintAtNode(
$symbol,
self::LINT_KEYWORD_CASING,
pht(
"Convention: spell keyword '%s' as '%s'.",
$symbol_name,
strtolower($symbol_name)),
strtolower($symbol_name));
}
}
}
$magic_constants = $root->selectTokensOfTypes(array(
'T_CLASS_C',
'T_METHOD_C',
'T_FUNC_C',
'T_LINE',
'T_FILE',
'T_NS_C',
'T_DIR',
'T_TRAIT_C',
));
foreach ($magic_constants as $magic_constant) {
$value = $magic_constant->getValue();
if ($value != strtoupper($value)) {
$this->raiseLintAtToken(
$magic_constant,
self::LINT_KEYWORD_CASING,
pht('Magic constants should be uppercase.'),
strtoupper($value));
}
}
}
private function lintStrings(XHPASTNode $root) {
$nodes = $root->selectDescendantsOfTypes(array(
'n_CONCATENATION_LIST',
'n_STRING_SCALAR',
));
foreach ($nodes as $node) {
$strings = array();
if ($node->getTypeName() === 'n_CONCATENATION_LIST') {
$strings = $node->selectDescendantsOfType('n_STRING_SCALAR');
} else if ($node->getTypeName() === 'n_STRING_SCALAR') {
$strings = array($node);
if ($node->getParentNode()->getTypeName() === 'n_CONCATENATION_LIST') {
continue;
}
}
$valid = false;
$invalid_nodes = array();
$fixes = array();
foreach ($strings as $string) {
$concrete_string = $string->getConcreteString();
$single_quoted = ($concrete_string[0] === "'");
$contents = substr($concrete_string, 1, -1);
// Double quoted strings are allowed when the string contains the
// following characters.
static $allowed_chars = array(
'\n',
'\r',
'\t',
'\v',
'\e',
'\f',
'\'',
'\0',
'\1',
'\2',
'\3',
'\4',
'\5',
'\6',
'\7',
'\x',
);
$contains_special_chars = false;
foreach ($allowed_chars as $allowed_char) {
if (strpos($contents, $allowed_char) !== false) {
$contains_special_chars = true;
}
}
if (!$string->isConstantString()) {
$valid = true;
} else if ($contains_special_chars && !$single_quoted) {
$valid = true;
} else if (!$contains_special_chars && !$single_quoted) {
$invalid_nodes[] = $string;
$fixes[$string->getID()] = "'".str_replace('\"', '"', $contents)."'";
}
}
if (!$valid) {
foreach ($invalid_nodes as $invalid_node) {
$this->raiseLintAtNode(
$invalid_node,
self::LINT_DOUBLE_QUOTE,
pht(
'String does not require double quotes. For consistency, '.
'prefer single quotes.'),
$fixes[$invalid_node->getID()]);
}
}
}
}
protected function lintElseIfStatements(XHPASTNode $root) {
$tokens = $root->selectTokensOfType('T_ELSEIF');
foreach ($tokens as $token) {
$this->raiseLintAtToken(
$token,
self::LINT_ELSEIF_USAGE,
pht('Usage of `%s` is preferred over `%s`.', 'else if', 'elseif'),
'else if');
}
}
protected function lintSemicolons(XHPASTNode $root) {
$tokens = $root->selectTokensOfType(';');
foreach ($tokens as $token) {
$prev = $token->getPrevToken();
if ($prev->isAnyWhitespace()) {
$this->raiseLintAtToken(
$prev,
self::LINT_SEMICOLON_SPACING,
pht('Space found before semicolon.'),
'');
}
}
}
protected function lintLanguageConstructParentheses(XHPASTNode $root) {
$nodes = $root->selectDescendantsOfTypes(array(
'n_INCLUDE_FILE',
'n_ECHO_LIST',
));
foreach ($nodes as $node) {
$child = head($node->getChildren());
if ($child->getTypeName() === 'n_PARENTHETICAL_EXPRESSION') {
list($before, $after) = $child->getSurroundingNonsemanticTokens();
$replace = preg_replace(
'/^\((.*)\)$/',
'$1',
$child->getConcreteString());
if (!$before) {
$replace = ' '.$replace;
}
$this->raiseLintAtNode(
$child,
self::LINT_LANGUAGE_CONSTRUCT_PAREN,
pht('Language constructs do not require parentheses.'),
$replace);
}
}
}
protected function lintEmptyBlockStatements(XHPASTNode $root) {
$nodes = $root->selectDescendantsOfType('n_STATEMENT_LIST');
foreach ($nodes as $node) {
$tokens = $node->getTokens();
$token = head($tokens);
if (count($tokens) <= 2) {
continue;
}
// Safety check... if the first token isn't an opening brace then
// there's nothing to do here.
if ($token->getTypeName() != '{') {
continue;
}
$only_whitespace = true;
for ($token = $token->getNextToken();
$token && $token->getTypeName() != '}';
$token = $token->getNextToken()) {
$only_whitespace = $only_whitespace && $token->isAnyWhitespace();
}
if (count($tokens) > 2 && $only_whitespace) {
$this->raiseLintAtNode(
$node,
self::LINT_EMPTY_STATEMENT,
pht(
"Braces for an empty block statement shouldn't ".
"contain only whitespace."),
'{}');
}
}
}
protected function lintArraySeparator(XHPASTNode $root) {
$arrays = $root->selectDescendantsOfType('n_ARRAY_LITERAL');
foreach ($arrays as $array) {
$value_list = $array->getChildOfType(0, 'n_ARRAY_VALUE_LIST');
$values = $value_list->getChildrenOfType('n_ARRAY_VALUE');
if (!$values) {
// There is no need to check an empty array.
continue;
}
$multiline = $array->getLineNumber() != $array->getEndLineNumber();
$value = last($values);
$after = last($value->getTokens())->getNextToken();
if ($multiline) {
if (!$after || $after->getValue() != ',') {
if ($value->getChildByIndex(1)->getTypeName() == 'n_HEREDOC') {
continue;
}
list($before, $after) = $value->getSurroundingNonsemanticTokens();
$after = implode('', mpull($after, 'getValue'));
$original = $value->getConcreteString();
$replacement = $value->getConcreteString().',';
if (strpos($after, "\n") === false) {
$original .= $after;
$replacement .= $after."\n".$array->getIndentation();
}
$this->raiseLintAtOffset(
$value->getOffset(),
self::LINT_ARRAY_SEPARATOR,
pht('Multi-lined arrays should have trailing commas.'),
$original,
$replacement);
} else if ($value->getLineNumber() == $array->getEndLineNumber()) {
$close = last($array->getTokens());
$this->raiseLintAtToken(
$close,
self::LINT_ARRAY_SEPARATOR,
pht('Closing parenthesis should be on a new line.'),
"\n".$array->getIndentation().$close->getValue());
}
} else if ($after && $after->getValue() == ',') {
$this->raiseLintAtToken(
$after,
self::LINT_ARRAY_SEPARATOR,
pht('Single lined arrays should not have a trailing comma.'),
'');
}
}
}
private function lintConstructorParentheses(XHPASTNode $root) {
$nodes = $root->selectDescendantsOfType('n_NEW');
foreach ($nodes as $node) {
$class = $node->getChildByIndex(0);
$params = $node->getChildByIndex(1);
if ($params->getTypeName() == 'n_EMPTY') {
$this->raiseLintAtNode(
$class,
self::LINT_CONSTRUCTOR_PARENTHESES,
pht('Use parentheses when invoking a constructor.'),
$class->getConcreteString().'()');
}
}
}
private function lintSwitchStatements(XHPASTNode $root) {
$switch_statements = $root->selectDescendantsOfType('n_SWITCH');
foreach ($switch_statements as $switch_statement) {
$case_statements = $switch_statement
->getChildOfType(1, 'n_STATEMENT_LIST')
->getChildrenOfType('n_CASE');
$nodes_by_case = array();
foreach ($case_statements as $case_statement) {
$case = $case_statement
->getChildByIndex(0)
->getSemanticString();
$nodes_by_case[$case][] = $case_statement;
}
foreach ($nodes_by_case as $case => $nodes) {
if (count($nodes) <= 1) {
continue;
}
$node = array_pop($nodes_by_case[$case]);
$message = $this->raiseLintAtNode(
$node,
self::LINT_DUPLICATE_SWITCH_CASE,
pht(
'Duplicate case in switch statement. PHP will ignore all '.
'but the first case.'));
$locations = array();
foreach ($nodes_by_case[$case] as $node) {
$locations[] = $this->getOtherLocation($node->getOffset());
}
$message->setOtherLocations($locations);
}
}
}
private function lintBlacklistedFunction(XHPASTNode $root) {
$calls = $root->selectDescendantsOfType('n_FUNCTION_CALL');
foreach ($calls as $call) {
$node = $call->getChildByIndex(0);
$name = $node->getConcreteString();
$reason = idx($this->blacklistedFunctions, $name);
if ($reason) {
$this->raiseLintAtNode(
$node,
self::LINT_BLACKLISTED_FUNCTION,
$reason);
}
}
}
private function lintMethodVisibility(XHPASTNode $root) {
static $visibilities = array(
'public',
'protected',
'private',
);
$methods = $root->selectDescendantsOfType('n_METHOD_DECLARATION');
foreach ($methods as $method) {
$modifiers_list = $method->getChildOfType(
0,
'n_METHOD_MODIFIER_LIST');
foreach ($modifiers_list->getChildren() as $modifier) {
if (in_array($modifier->getConcreteString(), $visibilities)) {
continue 2;
}
}
if ($modifiers_list->getChildren()) {
$node = $modifiers_list;
} else {
$node = $method;
}
$this->raiseLintAtNode(
$node,
self::LINT_IMPLICIT_VISIBILITY,
pht('Methods should have their visibility declared explicitly.'),
'public '.$node->getConcreteString());
}
}
private function lintPropertyVisibility(XHPASTNode $root) {
static $visibilities = array(
'public',
'protected',
'private',
);
$nodes = $root->selectDescendantsOfType('n_CLASS_MEMBER_MODIFIER_LIST');
foreach ($nodes as $node) {
$modifiers = $node->getChildren();
foreach ($modifiers as $modifier) {
if ($modifier->getConcreteString() == 'var') {
$this->raiseLintAtNode(
$modifier,
self::LINT_IMPLICIT_VISIBILITY,
pht(
'Use `%s` instead of `%s` to indicate public visibility.',
'public',
'var'),
'public');
continue 2;
}
if (in_array($modifier->getConcreteString(), $visibilities)) {
continue 2;
}
}
$this->raiseLintAtNode(
$node,
self::LINT_IMPLICIT_VISIBILITY,
pht('Properties should have their visibility declared explicitly.'),
'public '.$node->getConcreteString());
}
}
private function lintCallTimePassByReference(XHPASTNode $root) {
$nodes = $root->selectDescendantsOfType('n_CALL_PARAMETER_LIST');
foreach ($nodes as $node) {
$parameters = $node->getChildrenOfType('n_VARIABLE_REFERENCE');
foreach ($parameters as $parameter) {
$this->raiseLintAtNode(
$parameter,
self::LINT_CALL_TIME_PASS_BY_REF,
pht('Call-time pass-by-reference calls are prohibited.'));
}
}
}
private function lintFormattedString(XHPASTNode $root) {
static $functions = array(
// Core PHP
'fprintf' => 1,
'printf' => 0,
'sprintf' => 0,
'vfprintf' => 1,
// libphutil
'csprintf' => 0,
'execx' => 0,
'exec_manual' => 0,
'hgsprintf' => 0,
'hsprintf' => 0,
'jsprintf' => 0,
'pht' => 0,
'phutil_passthru' => 0,
'qsprintf' => 1,
'queryfx' => 1,
'queryfx_all' => 1,
'queryfx_one' => 1,
'vcsprintf' => 0,
'vqsprintf' => 1,
);
$function_calls = $root->selectDescendantsOfType('n_FUNCTION_CALL');
foreach ($function_calls as $call) {
$name = $call->getChildByIndex(0)->getConcreteString();
$name = strtolower($name);
$start = idx($functions + $this->printfFunctions, $name);
if ($start === null) {
continue;
}
$parameters = $call->getChildOfType(1, 'n_CALL_PARAMETER_LIST');
$argc = count($parameters->getChildren()) - $start;
if ($argc < 1) {
$this->raiseLintAtNode(
$call,
self::LINT_FORMATTED_STRING,
pht('This function is expected to have a format string.'));
continue;
}
$format = $parameters->getChildByIndex($start);
if ($format->getTypeName() != 'n_STRING_SCALAR') {
continue;
}
$argv = array($format->evalStatic()) + array_fill(0, $argc, null);
try {
xsprintf(null, null, $argv);
} catch (BadFunctionCallException $ex) {
$this->raiseLintAtNode(
$call,
self::LINT_FORMATTED_STRING,
str_replace('xsprintf', $name, $ex->getMessage()));
} catch (InvalidArgumentException $ex) {
// Ignore.
}
}
}
private function lintUnnecessaryFinalModifier(XHPASTNode $root) {
$classes = $root->selectDescendantsOfType('n_CLASS_DECLARATION');
foreach ($classes as $class) {
$attributes = $class->getChildOfType(0, 'n_CLASS_ATTRIBUTES');
$is_final = false;
foreach ($attributes->getChildren() as $attribute) {
if ($attribute->getConcreteString() == 'final') {
$is_final = true;
break;
}
}
if (!$is_final) {
continue;
}
$methods = $class->selectDescendantsOfType('n_METHOD_DECLARATION');
foreach ($methods as $method) {
$attributes = $method->getChildOfType(0, 'n_METHOD_MODIFIER_LIST');
foreach ($attributes->getChildren() as $attribute) {
if ($attribute->getConcreteString() == 'final') {
$this->raiseLintAtNode(
$attribute,
self::LINT_UNNECESSARY_FINAL_MODIFIER,
pht(
'Unnecessary %s modifier in %s class.',
'final',
'final'));
}
}
}
}
}
private function lintUnnecessarySemicolons(XHPASTNode $root) {
$statements = $root->selectDescendantsOfType('n_STATEMENT');
foreach ($statements as $statement) {
if ($statement->getParentNode()->getTypeName() == 'n_DECLARE') {
continue;
}
if (count($statement->getChildren()) > 1) {
continue;
} else if ($statement->getChildByIndex(0)->getTypeName() != 'n_EMPTY') {
continue;
}
if ($statement->getConcreteString() == ';') {
$this->raiseLintAtNode(
$statement,
self::LINT_UNNECESSARY_SEMICOLON,
pht('Unnecessary semicolons after statement.'),
'');
}
}
}
private function lintConstantDefinitions(XHPASTNode $root) {
$defines = $this
->getFunctionCalls($root, array('define'))
->add($root->selectDescendantsOfTypes(array(
'n_CLASS_CONSTANT_DECLARATION',
'n_CONSTANT_DECLARATION',
)));
foreach ($defines as $define) {
switch ($define->getTypeName()) {
case 'n_CLASS_CONSTANT_DECLARATION':
case 'n_CONSTANT_DECLARATION':
$constant = $define->getChildByIndex(0);
if ($constant->getTypeName() !== 'n_STRING') {
$constant = null;
}
break;
case 'n_FUNCTION_CALL':
$constant = $define
->getChildOfType(1, 'n_CALL_PARAMETER_LIST')
->getChildByIndex(0);
if ($constant->getTypeName() !== 'n_STRING_SCALAR') {
$constant = null;
}
break;
default:
$constant = null;
break;
}
if (!$constant) {
continue;
}
$constant_name = $constant->getConcreteString();
if ($constant_name !== strtoupper($constant_name)) {
$this->raiseLintAtNode(
$constant,
self::LINT_NAMING_CONVENTIONS,
pht('Constants should be uppercase.'));
}
}
}
private function lintSelfMemberReference(XHPASTNode $root) {
$class_declarations = $root->selectDescendantsOfType('n_CLASS_DECLARATION');
foreach ($class_declarations as $class_declaration) {
$class_name = $class_declaration
->getChildOfType(1, 'n_CLASS_NAME')
->getConcreteString();
$class_static_accesses = $class_declaration
->selectDescendantsOfType('n_CLASS_STATIC_ACCESS');
foreach ($class_static_accesses as $class_static_access) {
$double_colons = $class_static_access
->selectTokensOfType('T_PAAMAYIM_NEKUDOTAYIM');
$class_ref = $class_static_access->getChildByIndex(0);
if ($class_ref->getTypeName() != 'n_CLASS_NAME') {
continue;
}
$class_ref_name = $class_ref->getConcreteString();
if (strtolower($class_name) == strtolower($class_ref_name)) {
$this->raiseLintAtNode(
$class_ref,
self::LINT_SELF_MEMBER_REFERENCE,
pht('Use `%s` for local static member references.', 'self::'),
'self');
}
static $self_refs = array(
'parent',
'self',
'static',
);
if (!in_array(strtolower($class_ref_name), $self_refs)) {
continue;
}
if ($class_ref_name != strtolower($class_ref_name)) {
$this->raiseLintAtNode(
$class_ref,
self::LINT_SELF_MEMBER_REFERENCE,
pht('PHP keywords should be lowercase.'),
strtolower($class_ref_name));
}
}
}
$double_colons = $root
->selectTokensOfType('T_PAAMAYIM_NEKUDOTAYIM');
foreach ($double_colons as $double_colon) {
$tokens = $double_colon->getNonsemanticTokensBefore() +
$double_colon->getNonsemanticTokensAfter();
foreach ($tokens as $token) {
if ($token->isAnyWhitespace()) {
if (strpos($token->getValue(), "\n") !== false) {
continue;
}
$this->raiseLintAtToken(
$token,
self::LINT_SELF_MEMBER_REFERENCE,
pht('Unnecessary whitespace around double colon operator.'),
'');
}
}
}
}
private function lintLogicalOperators(XHPASTNode $root) {
$logical_ands = $root->selectTokensOfType('T_LOGICAL_AND');
$logical_ors = $root->selectTokensOfType('T_LOGICAL_OR');
foreach ($logical_ands as $logical_and) {
$this->raiseLintAtToken(
$logical_and,
self::LINT_LOGICAL_OPERATORS,
pht('Use `%s` instead of `%s`.', '&&', 'and'),
'&&');
}
foreach ($logical_ors as $logical_or) {
$this->raiseLintAtToken(
$logical_or,
self::LINT_LOGICAL_OPERATORS,
pht('Use `%s` instead of `%s`.', '||', 'or'),
'||');
}
}
private function lintInnerFunctions(XHPASTNode $root) {
$function_decls = $root->selectDescendantsOfType('n_FUNCTION_DECLARATION');
foreach ($function_decls as $function_declaration) {
$inner_functions = $function_declaration
->selectDescendantsOfType('n_FUNCTION_DECLARATION');
foreach ($inner_functions as $inner_function) {
if ($inner_function->getChildByIndex(2)->getTypeName() == 'n_EMPTY') {
// Anonymous closure.
continue;
}
$this->raiseLintAtNode(
$inner_function,
self::LINT_INNER_FUNCTION,
pht('Avoid the use of inner functions.'));
}
}
}
private function lintDefaultParameters(XHPASTNode $root) {
$parameter_lists = $root->selectDescendantsOfType(
'n_DECLARATION_PARAMETER_LIST');
foreach ($parameter_lists as $parameter_list) {
$default_found = false;
$parameters = $parameter_list->selectDescendantsOfType(
'n_DECLARATION_PARAMETER');
foreach ($parameters as $parameter) {
$default_value = $parameter->getChildByIndex(2);
if ($default_value->getTypeName() != 'n_EMPTY') {
$default_found = true;
} else if ($default_found) {
$this->raiseLintAtNode(
$parameter_list,
self::LINT_DEFAULT_PARAMETERS,
pht(
'Arguments with default values must be at the end '.
'of the argument list.'));
}
}
}
}
private function lintLowercaseFunctions(XHPASTNode $root) {
static $builtin_functions = null;
if ($builtin_functions === null) {
$builtin_functions = array_fuse(
idx(get_defined_functions(), 'internal', array()));
}
$function_calls = $root->selectDescendantsOfType('n_FUNCTION_CALL');
foreach ($function_calls as $function_call) {
$function = $function_call->getChildByIndex(0);
if ($function->getTypeName() != 'n_SYMBOL_NAME') {
continue;
}
$function_name = $function->getConcreteString();
if (!idx($builtin_functions, strtolower($function_name))) {
continue;
}
if ($function_name != strtolower($function_name)) {
$this->raiseLintAtNode(
$function,
self::LINT_LOWERCASE_FUNCTIONS,
pht('Calls to built-in PHP functions should be lowercase.'),
strtolower($function_name));
}
}
}
private function lintClassNameLiteral(XHPASTNode $root) {
$class_declarations = $root->selectDescendantsOfType('n_CLASS_DECLARATION');
foreach ($class_declarations as $class_declaration) {
$class_name = $class_declaration
->getChildOfType(1, 'n_CLASS_NAME')
->getConcreteString();
$strings = $class_declaration->selectDescendantsOfType('n_STRING_SCALAR');
foreach ($strings as $string) {
$contents = substr($string->getSemanticString(), 1, -1);
$replacement = null;
if ($contents == $class_name) {
$replacement = '__CLASS__';
}
$regex = '/\b'.preg_quote($class_name, '/').'\b/';
if (!preg_match($regex, $contents)) {
continue;
}
$this->raiseLintAtNode(
$string,
self::LINT_CLASS_NAME_LITERAL,
pht(
"Don't hard-code class names, use %s instead.",
'__CLASS__'),
$replacement);
}
}
}
private function lintUselessOverridingMethods(XHPASTNode $root) {
$methods = $root->selectDescendantsOfType('n_METHOD_DECLARATION');
foreach ($methods as $method) {
$method_name = $method
->getChildOfType(2, 'n_STRING')
->getConcreteString();
$parameter_list = $method
->getChildOfType(3, 'n_DECLARATION_PARAMETER_LIST');
$parameters = array();
foreach ($parameter_list->getChildren() as $parameter) {
$parameter = $parameter->getChildByIndex(1);
if ($parameter->getTypeName() == 'n_VARIABLE_REFERENCE') {
$parameter = $parameter->getChildOfType(0, 'n_VARIABLE');
}
$parameters[] = $parameter->getConcreteString();
}
$statements = $method->getChildByIndex(5);
if ($statements->getTypeName() != 'n_STATEMENT_LIST') {
continue;
}
if (count($statements->getChildren()) != 1) {
continue;
}
$statement = $statements
->getChildOfType(0, 'n_STATEMENT')
->getChildByIndex(0);
if ($statement->getTypeName() == 'n_RETURN') {
$statement = $statement->getChildByIndex(0);
}
if ($statement->getTypeName() != 'n_FUNCTION_CALL') {
continue;
}
$function = $statement->getChildByIndex(0);
if ($function->getTypeName() != 'n_CLASS_STATIC_ACCESS') {
continue;
}
$called_class = $function->getChildOfType(0, 'n_CLASS_NAME');
$called_method = $function->getChildOfType(1, 'n_STRING');
if ($called_class->getConcreteString() != 'parent') {
continue;
} else if ($called_method->getConcreteString() != $method_name) {
continue;
}
$params = $statement
->getChildOfType(1, 'n_CALL_PARAMETER_LIST')
->getChildren();
foreach ($params as $param) {
if ($param->getTypeName() != 'n_VARIABLE') {
continue 2;
}
$expected = array_shift($parameters);
if ($param->getConcreteString() != $expected) {
continue 2;
}
}
$this->raiseLintAtNode(
$method,
self::LINT_USELESS_OVERRIDING_METHOD,
pht('Useless overriding method.'));
}
}
private function lintNoParentScope(XHPASTNode $root) {
$classes = $root->selectDescendantsOfType('n_CLASS_DECLARATION');
foreach ($classes as $class) {
$methods = $class->selectDescendantsOfType('n_METHOD_DECLARATION');
if ($class->getChildByIndex(2)->getTypeName() == 'n_EXTENDS_LIST') {
continue;
}
foreach ($methods as $method) {
$static_accesses = $method
->selectDescendantsOfType('n_CLASS_STATIC_ACCESS');
foreach ($static_accesses as $static_access) {
$called_class = $static_access->getChildByIndex(0);
if ($called_class->getTypeName() != 'n_CLASS_NAME') {
continue;
}
if ($called_class->getConcreteString() == 'parent') {
$this->raiseLintAtNode(
$static_access,
self::LINT_NO_PARENT_SCOPE,
pht(
'Cannot access %s when current class scope has no parent.',
'parent::'));
}
}
}
}
}
private function lintAliasFunctions(XHPASTNode $root) {
static $aliases = array(
'_' => 'gettext',
'chop' => 'rtrim',
'close' => 'closedir',
'com_get' => 'com_propget',
'com_propset' => 'com_propput',
'com_set' => 'com_propput',
'die' => 'exit',
'diskfreespace' => 'disk_free_space',
'doubleval' => 'floatval',
'drawarc' => 'swfshape_drawarc',
'drawcircle' => 'swfshape_drawcircle',
'drawcubic' => 'swfshape_drawcubic',
'drawcubicto' => 'swfshape_drawcubicto',
'drawcurve' => 'swfshape_drawcurve',
'drawcurveto' => 'swfshape_drawcurveto',
'drawglyph' => 'swfshape_drawglyph',
'drawline' => 'swfshape_drawline',
'drawlineto' => 'swfshape_drawlineto',
'fbsql' => 'fbsql_db_query',
'fputs' => 'fwrite',
'gzputs' => 'gzwrite',
'i18n_convert' => 'mb_convert_encoding',
'i18n_discover_encoding' => 'mb_detect_encoding',
'i18n_http_input' => 'mb_http_input',
'i18n_http_output' => 'mb_http_output',
'i18n_internal_encoding' => 'mb_internal_encoding',
'i18n_ja_jp_hantozen' => 'mb_convert_kana',
'i18n_mime_header_decode' => 'mb_decode_mimeheader',
'i18n_mime_header_encode' => 'mb_encode_mimeheader',
'imap_create' => 'imap_createmailbox',
'imap_fetchtext' => 'imap_body',
'imap_getmailboxes' => 'imap_list_full',
'imap_getsubscribed' => 'imap_lsub_full',
'imap_header' => 'imap_headerinfo',
'imap_listmailbox' => 'imap_list',
'imap_listsubscribed' => 'imap_lsub',
'imap_rename' => 'imap_renamemailbox',
'imap_scan' => 'imap_listscan',
'imap_scanmailbox' => 'imap_listscan',
'ini_alter' => 'ini_set',
'is_double' => 'is_float',
'is_integer' => 'is_int',
'is_long' => 'is_int',
'is_real' => 'is_float',
'is_writeable' => 'is_writable',
'join' => 'implode',
'key_exists' => 'array_key_exists',
'ldap_close' => 'ldap_unbind',
'magic_quotes_runtime' => 'set_magic_quotes_runtime',
'mbstrcut' => 'mb_strcut',
'mbstrlen' => 'mb_strlen',
'mbstrpos' => 'mb_strpos',
'mbstrrpos' => 'mb_strrpos',
'mbsubstr' => 'mb_substr',
'ming_setcubicthreshold' => 'ming_setCubicThreshold',
'ming_setscale' => 'ming_setScale',
'msql' => 'msql_db_query',
'msql_createdb' => 'msql_create_db',
'msql_dbname' => 'msql_result',
'msql_dropdb' => 'msql_drop_db',
'msql_fieldflags' => 'msql_field_flags',
'msql_fieldlen' => 'msql_field_len',
'msql_fieldname' => 'msql_field_name',
'msql_fieldtable' => 'msql_field_table',
'msql_fieldtype' => 'msql_field_type',
'msql_freeresult' => 'msql_free_result',
'msql_listdbs' => 'msql_list_dbs',
'msql_listfields' => 'msql_list_fields',
'msql_listtables' => 'msql_list_tables',
'msql_numfields' => 'msql_num_fields',
'msql_numrows' => 'msql_num_rows',
'msql_regcase' => 'sql_regcase',
'msql_selectdb' => 'msql_select_db',
'msql_tablename' => 'msql_result',
'mssql_affected_rows' => 'sybase_affected_rows',
'mssql_close' => 'sybase_close',
'mssql_connect' => 'sybase_connect',
'mssql_data_seek' => 'sybase_data_seek',
'mssql_fetch_array' => 'sybase_fetch_array',
'mssql_fetch_field' => 'sybase_fetch_field',
'mssql_fetch_object' => 'sybase_fetch_object',
'mssql_fetch_row' => 'sybase_fetch_row',
'mssql_field_seek' => 'sybase_field_seek',
'mssql_free_result' => 'sybase_free_result',
'mssql_get_last_message' => 'sybase_get_last_message',
'mssql_min_client_severity' => 'sybase_min_client_severity',
'mssql_min_error_severity' => 'sybase_min_error_severity',
'mssql_min_message_severity' => 'sybase_min_message_severity',
'mssql_min_server_severity' => 'sybase_min_server_severity',
'mssql_num_fields' => 'sybase_num_fields',
'mssql_num_rows' => 'sybase_num_rows',
'mssql_pconnect' => 'sybase_pconnect',
'mssql_query' => 'sybase_query',
'mssql_result' => 'sybase_result',
'mssql_select_db' => 'sybase_select_db',
'multcolor' => 'swfdisplayitem_multColor',
'mysql' => 'mysql_db_query',
'mysql_createdb' => 'mysql_create_db',
'mysql_db_name' => 'mysql_result',
'mysql_dbname' => 'mysql_result',
'mysql_dropdb' => 'mysql_drop_db',
'mysql_fieldflags' => 'mysql_field_flags',
'mysql_fieldlen' => 'mysql_field_len',
'mysql_fieldname' => 'mysql_field_name',
'mysql_fieldtable' => 'mysql_field_table',
'mysql_fieldtype' => 'mysql_field_type',
'mysql_freeresult' => 'mysql_free_result',
'mysql_listdbs' => 'mysql_list_dbs',
'mysql_listfields' => 'mysql_list_fields',
'mysql_listtables' => 'mysql_list_tables',
'mysql_numfields' => 'mysql_num_fields',
'mysql_numrows' => 'mysql_num_rows',
'mysql_selectdb' => 'mysql_select_db',
'mysql_tablename' => 'mysql_result',
'ociassignelem' => 'OCI-Collection::assignElem',
'ocibindbyname' => 'oci_bind_by_name',
'ocicancel' => 'oci_cancel',
'ocicloselob' => 'OCI-Lob::close',
'ocicollappend' => 'OCI-Collection::append',
'ocicollassign' => 'OCI-Collection::assign',
'ocicollmax' => 'OCI-Collection::max',
'ocicollsize' => 'OCI-Collection::size',
'ocicolltrim' => 'OCI-Collection::trim',
'ocicolumnisnull' => 'oci_field_is_null',
'ocicolumnname' => 'oci_field_name',
'ocicolumnprecision' => 'oci_field_precision',
'ocicolumnscale' => 'oci_field_scale',
'ocicolumnsize' => 'oci_field_size',
'ocicolumntype' => 'oci_field_type',
'ocicolumntyperaw' => 'oci_field_type_raw',
'ocicommit' => 'oci_commit',
'ocidefinebyname' => 'oci_define_by_name',
'ocierror' => 'oci_error',
'ociexecute' => 'oci_execute',
'ocifetch' => 'oci_fetch',
'ocifetchinto' => 'oci_fetch_array(),',
'ocifetchstatement' => 'oci_fetch_all',
'ocifreecollection' => 'OCI-Collection::free',
'ocifreecursor' => 'oci_free_statement',
'ocifreedesc' => 'oci_free_descriptor',
'ocifreestatement' => 'oci_free_statement',
'ocigetelem' => 'OCI-Collection::getElem',
'ociinternaldebug' => 'oci_internal_debug',
'ociloadlob' => 'OCI-Lob::load',
'ocilogon' => 'oci_connect',
'ocinewcollection' => 'oci_new_collection',
'ocinewcursor' => 'oci_new_cursor',
'ocinewdescriptor' => 'oci_new_descriptor',
'ocinlogon' => 'oci_new_connect',
'ocinumcols' => 'oci_num_fields',
'ociparse' => 'oci_parse',
'ocipasswordchange' => 'oci_password_change',
'ociplogon' => 'oci_pconnect',
'ociresult' => 'oci_result',
'ocirollback' => 'oci_rollback',
'ocisavelob' => 'OCI-Lob::save',
'ocisavelobfile' => 'OCI-Lob::import',
'ociserverversion' => 'oci_server_version',
'ocisetprefetch' => 'oci_set_prefetch',
'ocistatementtype' => 'oci_statement_type',
'ociwritelobtofile' => 'OCI-Lob::export',
'ociwritetemporarylob' => 'OCI-Lob::writeTemporary',
'odbc_do' => 'odbc_exec',
'odbc_field_precision' => 'odbc_field_len',
'pdf_add_outline' => 'pdf_add_bookmark',
'pg_clientencoding' => 'pg_client_encoding',
'pg_setclientencoding' => 'pg_set_client_encoding',
'pos' => 'current',
'recode' => 'recode_string',
'show_source' => 'highlight_file',
'sizeof' => 'count',
'snmpwalkoid' => 'snmprealwalk',
'strchr' => 'strstr',
'streammp3' => 'swfmovie_streamMp3',
'swfaction' => 'swfaction_init',
'swfbitmap' => 'swfbitmap_init',
'swfbutton' => 'swfbutton_init',
'swffill' => 'swffill_init',
'swffont' => 'swffont_init',
'swfgradient' => 'swfgradient_init',
'swfmorph' => 'swfmorph_init',
'swfmovie' => 'swfmovie_init',
'swfshape' => 'swfshape_init',
'swfsprite' => 'swfsprite_init',
'swftext' => 'swftext_init',
'swftextfield' => 'swftextfield_init',
'xptr_new_context' => 'xpath_new_context',
);
$functions = $this->getFunctionCalls($root, array_keys($aliases));
foreach ($functions as $function) {
$function_name = $function->getChildByIndex(0);
$this->raiseLintAtNode(
$function_name,
self::LINT_ALIAS_FUNCTION,
pht('Alias functions should be avoided.'),
$aliases[phutil_utf8_strtolower($function_name->getConcreteString())]);
}
}
private function lintCastSpacing(XHPASTNode $root) {
$cast_expressions = $root->selectDescendantsOfType('n_CAST_EXPRESSION');
foreach ($cast_expressions as $cast_expression) {
$cast = $cast_expression->getChildOfType(0, 'n_CAST');
list($before, $after) = $cast->getSurroundingNonsemanticTokens();
$after = head($after);
if ($after) {
$this->raiseLintAtToken(
$after,
self::LINT_CAST_SPACING,
pht('A cast statement must not be followed by a space.'),
'');
}
}
}
private function lintThrowExceptionInToStringMethod(XHPASTNode $root) {
$methods = $root->selectDescendantsOfType('n_METHOD_DECLARATION');
foreach ($methods as $method) {
$name = $method
->getChildOfType(2, 'n_STRING')
->getConcreteString();
if ($name != '__toString') {
continue;
}
$statements = $method->getChildByIndex(5);
if ($statements->getTypeName() != 'n_STATEMENT_LIST') {
continue;
}
$throws = $statements->selectDescendantsOfType('n_THROW');
foreach ($throws as $throw) {
$this->raiseLintAtNode(
$throw,
self::LINT_TOSTRING_EXCEPTION,
pht(
'It is not possible to throw an %s from within the %s method.',
'Exception',
'__toString'));
}
}
}
private function lintLambdaFuncFunction(XHPASTNode $root) {
$function_declarations = $root
->selectDescendantsOfType('n_FUNCTION_DECLARATION');
foreach ($function_declarations as $function_declaration) {
$function_name = $function_declaration->getChildByIndex(2);
if ($function_name->getTypeName() == 'n_EMPTY') {
// Anonymous closure.
continue;
}
if ($function_name->getConcreteString() != '__lambda_func') {
continue;
}
$this->raiseLintAtNode(
$function_declaration,
self::LINT_LAMBDA_FUNC_FUNCTION,
pht(
'Declaring a function named %s causes any call to %s to fail. '.
'This is because %s eval-declares the function %s, then '.
'modifies the symbol table so that the function is instead '.
'named %s, and returns that name.',
'__lambda_func',
'create_function',
'create_function',
'__lambda_func',
'"\0lambda_".(++$i)'));
}
}
private function lintInstanceOfOperator(XHPASTNode $root) {
$expressions = $root->selectDescendantsOfType('n_BINARY_EXPRESSION');
foreach ($expressions as $expression) {
$operator = $expression->getChildOfType(1, 'n_OPERATOR');
if (strtolower($operator->getConcreteString()) != 'instanceof') {
continue;
}
$object = $expression->getChildByIndex(0);
if ($object->isStaticScalar() ||
$object->getTypeName() == 'n_SYMBOL_NAME') {
$this->raiseLintAtNode(
$object,
self::LINT_INSTANCEOF_OPERATOR,
pht(
'%s expects an object instance, constant given.',
'instanceof'));
}
}
}
private function lintInvalidDefaultParameters(XHPASTNode $root) {
$parameters = $root->selectDescendantsOfType('n_DECLARATION_PARAMETER');
foreach ($parameters as $parameter) {
$type = $parameter->getChildByIndex(0);
$default = $parameter->getChildByIndex(2);
if ($type->getTypeName() == 'n_EMPTY') {
continue;
}
if ($default->getTypeName() == 'n_EMPTY') {
continue;
}
$default_is_null = $default->getTypeName() == 'n_SYMBOL_NAME' &&
strtolower($default->getConcreteString()) == 'null';
switch (strtolower($type->getConcreteString())) {
case 'array':
if ($default->getTypeName() == 'n_ARRAY_LITERAL') {
break;
}
if ($default_is_null) {
break;
}
$this->raiseLintAtNode(
$default,
self::LINT_INVALID_DEFAULT_PARAMETER,
pht(
'Default value for parameters with %s type hint '.
'can only be an %s or %s.',
'array',
'array',
'null'));
break;
case 'callable':
if ($default_is_null) {
break;
}
$this->raiseLintAtNode(
$default,
self::LINT_INVALID_DEFAULT_PARAMETER,
pht(
'Default value for parameters with %s type hint can only be %s.',
'callable',
'null'));
break;
default:
// Class/interface parameter.
if ($default_is_null) {
break;
}
$this->raiseLintAtNode(
$default,
self::LINT_INVALID_DEFAULT_PARAMETER,
pht(
'Default value for parameters with a class type hint '.
'can only be %s.',
'null'));
break;
}
}
}
private function lintMethodModifierOrdering(XHPASTNode $root) {
static $modifiers = array(
'abstract',
'final',
'public',
'protected',
'private',
'static',
);
$methods = $root->selectDescendantsOfType('n_METHOD_MODIFIER_LIST');
foreach ($methods as $method) {
$modifier_ordering = array_values(
mpull($method->getChildren(), 'getConcreteString'));
$expected_modifier_ordering = array_values(
array_intersect(
$modifiers,
$modifier_ordering));
if (count($modifier_ordering) != count($expected_modifier_ordering)) {
continue;
}
if ($modifier_ordering != $expected_modifier_ordering) {
$this->raiseLintAtNode(
$method,
self::LINT_MODIFIER_ORDERING,
pht('Non-conventional modifier ordering.'),
implode(' ', $expected_modifier_ordering));
}
}
}
private function lintPropertyModifierOrdering(XHPASTNode $root) {
static $modifiers = array(
'public',
'protected',
'private',
'static',
);
$properties = $root->selectDescendantsOfType(
'n_CLASS_MEMBER_MODIFIER_LIST');
foreach ($properties as $property) {
$modifier_ordering = array_values(
mpull($property->getChildren(), 'getConcreteString'));
$expected_modifier_ordering = array_values(
array_intersect(
$modifiers,
$modifier_ordering));
if (count($modifier_ordering) != count($expected_modifier_ordering)) {
continue;
}
if ($modifier_ordering != $expected_modifier_ordering) {
$this->raiseLintAtNode(
$property,
self::LINT_MODIFIER_ORDERING,
pht('Non-conventional modifier ordering.'),
implode(' ', $expected_modifier_ordering));
}
}
}
private function lintInvalidModifiers(XHPASTNode $root) {
$methods = $root->selectDescendantsOfTypes(array(
'n_CLASS_MEMBER_MODIFIER_LIST',
'n_METHOD_MODIFIER_LIST',
));
foreach ($methods as $method) {
$modifiers = $method->getChildren();
$is_abstract = false;
$is_final = false;
$is_static = false;
$visibility = null;
foreach ($modifiers as $modifier) {
switch ($modifier->getConcreteString()) {
case 'abstract':
if ($method->getTypeName() == 'n_CLASS_MEMBER_MODIFIER_LIST') {
$this->raiseLintAtNode(
$modifier,
self::LINT_INVALID_MODIFIERS,
pht(
'Properties cannot be declared %s.',
'abstract'));
}
if ($is_abstract) {
$this->raiseLintAtNode(
$modifier,
self::LINT_INVALID_MODIFIERS,
pht(
'Multiple %s modifiers are not allowed.',
'abstract'));
}
if ($is_final) {
$this->raiseLintAtNode(
$modifier,
self::LINT_INVALID_MODIFIERS,
pht(
'Cannot use the %s modifier on an %s class member',
'final',
'abstract'));
}
$is_abstract = true;
break;
case 'final':
if ($is_abstract) {
$this->raiseLintAtNode(
$modifier,
self::LINT_INVALID_MODIFIERS,
pht(
'Cannot use the %s modifier on an %s class member',
'final',
'abstract'));
}
if ($is_final) {
$this->raiseLintAtNode(
$modifier,
self::LINT_INVALID_MODIFIERS,
pht(
'Multiple %s modifiers are not allowed.',
'final'));
}
$is_final = true;
break;
case 'public':
case 'protected':
case 'private':
if ($visibility) {
$this->raiseLintAtNode(
$modifier,
self::LINT_INVALID_MODIFIERS,
pht('Multiple access type modifiers are not allowed.'));
}
$visibility = $modifier->getConcreteString();
break;
case 'static':
if ($is_static) {
$this->raiseLintAtNode(
$modifier,
self::LINT_INVALID_MODIFIERS,
pht(
'Multiple %s modifiers are not allowed.',
'static'));
}
break;
}
}
}
}
}
diff --git a/src/lint/linter/__tests__/ArcanistLinterTestCase.php b/src/lint/linter/__tests__/ArcanistLinterTestCase.php
index 66c71f16..564f57bc 100644
--- a/src/lint/linter/__tests__/ArcanistLinterTestCase.php
+++ b/src/lint/linter/__tests__/ArcanistLinterTestCase.php
@@ -1,266 +1,266 @@
<?php
/**
* Facilitates implementation of test cases for @{class:ArcanistLinter}s.
*/
abstract class ArcanistLinterTestCase extends PhutilTestCase {
/**
* Returns an instance of the linter being tested.
*
* @return ArcanistLinter
*/
protected final function getLinter() {
$matches = null;
if (!preg_match('/^(\w+Linter)TestCase$/', get_class($this), $matches) ||
!is_subclass_of($matches[1], 'ArcanistLinter')) {
throw new Exception(pht('Unable to infer linter class name.'));
}
return newv($matches[1], array());
}
public abstract function testLinter();
/**
* Executes all tests from the specified subdirectory. If a linter is not
* explicitly specified, it will be inferred from the name of the test class.
*/
public function executeTestsInDirectory(
$root,
ArcanistLinter $linter = null) {
if (!$linter) {
$linter = $this->getLinter();
}
$files = id(new FileFinder($root))
->withType('f')
->withSuffix('lint-test')
->find();
$test_count = 0;
foreach ($files as $file) {
$this->lintFile($root.$file, $linter);
$test_count++;
}
$this->assertTrue(
($test_count > 0),
pht(
'Expected to find some %s tests in directory %s!',
'.lint-test',
$root));
}
private function lintFile($file, ArcanistLinter $linter) {
$linter = clone $linter;
$contents = Filesystem::readFile($file);
$contents = preg_split('/^~{4,}\n/m', $contents);
if (count($contents) < 2) {
throw new Exception(
pht(
"Expected '%s' separating test case and results.",
'~~~~~~~~~~'));
}
list ($data, $expect, $xform, $config) = array_merge(
$contents,
array(null, null));
$basename = basename($file);
if ($config) {
$config = phutil_json_decode($config);
} else {
$config = array();
}
PhutilTypeSpec::checkMap(
$config,
array(
'config' => 'optional map<string, wild>',
'path' => 'optional string',
'mode' => 'optional string',
'stopped' => 'optional bool',
));
$exception = null;
$after_lint = null;
$messages = null;
$exception_message = false;
$caught_exception = false;
try {
$tmp = new TempFile($basename);
Filesystem::writeFile($tmp, $data);
$full_path = (string)$tmp;
$mode = idx($config, 'mode');
if ($mode) {
Filesystem::changePermissions($tmp, octdec($mode));
}
$dir = dirname($full_path);
$path = basename($full_path);
$working_copy = ArcanistWorkingCopyIdentity::newFromRootAndConfigFile(
$dir,
null,
- 'Unit Test');
+ pht('Unit Test'));
$configuration_manager = new ArcanistConfigurationManager();
$configuration_manager->setWorkingCopyIdentity($working_copy);
$engine = new ArcanistUnitTestableLintEngine();
$engine->setWorkingCopy($working_copy);
$engine->setConfigurationManager($configuration_manager);
$path_name = idx($config, 'path', $path);
$engine->setPaths(array($path_name));
$linter->addPath($path_name);
$linter->addData($path_name, $data);
foreach (idx($config, 'config', array()) as $key => $value) {
$linter->setLinterConfigurationValue($key, $value);
}
$engine->addLinter($linter);
$engine->addFileData($path_name, $data);
$results = $engine->run();
$this->assertEqual(
1,
count($results),
pht('Expect one result returned by linter.'));
$assert_stopped = idx($config, 'stopped');
if ($assert_stopped !== null) {
$this->assertEqual(
$assert_stopped,
$linter->didStopAllLinters(),
$assert_stopped
? pht('Expect linter to be stopped.')
: pht('Expect linter to not be stopped.'));
}
$result = reset($results);
$patcher = ArcanistLintPatcher::newFromArcanistLintResult($result);
$after_lint = $patcher->getModifiedFileContent();
} catch (PhutilTestTerminatedException $ex) {
throw $ex;
} catch (Exception $exception) {
$caught_exception = true;
if ($exception instanceof PhutilAggregateException) {
$caught_exception = false;
foreach ($exception->getExceptions() as $ex) {
if ($ex instanceof ArcanistUsageException ||
$ex instanceof ArcanistMissingLinterException) {
$this->assertSkipped($ex->getMessage());
} else {
$caught_exception = true;
}
}
} else if ($exception instanceof ArcanistUsageException ||
$exception instanceof ArcanistMissingLinterException) {
$this->assertSkipped($exception->getMessage());
}
$exception_message = $exception->getMessage()."\n\n".
$exception->getTraceAsString();
}
$this->assertEqual(false, $caught_exception, $exception_message);
$this->compareLint($basename, $expect, $result);
$this->compareTransform($xform, $after_lint);
}
private function compareLint($file, $expect, ArcanistLintResult $result) {
$seen = array();
$raised = array();
$message_map = array();
foreach ($result->getMessages() as $message) {
$sev = $message->getSeverity();
$line = $message->getLine();
$char = $message->getChar();
$code = $message->getCode();
$name = $message->getName();
$message_key = $sev.':'.$line.':'.$char;
$message_map[$message_key] = $message;
$seen[] = $message_key;
$raised[] = sprintf(
' %s: %s %s',
pht('%s at line %d, char %d', $sev, $line, $char),
$code,
$name);
}
$expect = trim($expect);
if ($expect) {
$expect = explode("\n", $expect);
} else {
$expect = array();
}
foreach ($expect as $key => $expected) {
$expect[$key] = head(explode(' ', $expected));
}
$expect = array_fill_keys($expect, true);
$seen = array_fill_keys($seen, true);
if (!$raised) {
$raised = array(pht('No messages.'));
}
$raised = sprintf(
"%s:\n%s",
pht('Actually raised'),
implode("\n", $raised));
foreach (array_diff_key($expect, $seen) as $missing => $ignored) {
$missing = explode(':', $missing);
$sev = array_shift($missing);
$pos = $missing;
$this->assertFailure(
pht(
"In '%s', expected lint to raise %s on line %d at char %d, ".
"but no %s was raised. %s",
$file,
$sev,
idx($pos, 0),
idx($pos, 1),
$sev,
$raised));
}
foreach (array_diff_key($seen, $expect) as $surprising => $ignored) {
$message = $message_map[$surprising];
$message_info = $message->getDescription();
list($sev, $line, $char) = explode(':', $surprising);
$this->assertFailure(
sprintf(
"%s:\n\n%s\n\n%s",
pht(
"In '%s', lint raised %s on line %d at char %d, ".
"but nothing was expected",
$file,
$sev,
$line,
$char),
$message_info,
$raised));
}
}
private function compareTransform($expected, $actual) {
if (!strlen($expected)) {
return;
}
$this->assertEqual(
$expected,
$actual,
pht('File as patched by lint did not match the expected patched file.'));
}
}
diff --git a/src/lint/linter/xhpast/__tests__/ArcanistXHPASTLintNamingHookTestCase.php b/src/lint/linter/xhpast/__tests__/ArcanistXHPASTLintNamingHookTestCase.php
index baec7dbc..16bc8051 100644
--- a/src/lint/linter/xhpast/__tests__/ArcanistXHPASTLintNamingHookTestCase.php
+++ b/src/lint/linter/xhpast/__tests__/ArcanistXHPASTLintNamingHookTestCase.php
@@ -1,66 +1,66 @@
<?php
/**
* Test cases for @{class:ArcanistXHPASTLintNamingHook}.
*/
final class ArcanistXHPASTLintNamingHookTestCase
extends PhutilTestCase {
public function testCaseUtilities() {
$tests = array(
'UpperCamelCase' => array(1, 0, 0, 0),
'UpperCamelCaseROFL' => array(1, 0, 0, 0),
'lowerCamelCase' => array(0, 1, 0, 0),
'lowerCamelCaseROFL' => array(0, 1, 0, 0),
'UPPERCASE_WITH_UNDERSCORES' => array(0, 0, 1, 0),
'_UPPERCASE_WITH_UNDERSCORES_' => array(0, 0, 1, 0),
'__UPPERCASE__WITH__UNDERSCORES__' => array(0, 0, 1, 0),
'lowercase_with_underscores' => array(0, 0, 0, 1),
'_lowercase_with_underscores_' => array(0, 0, 0, 1),
'__lowercase__with__underscores__' => array(0, 0, 0, 1),
'mixedCASE_NoNsEnSe' => array(0, 0, 0, 0),
);
foreach ($tests as $test => $expect) {
$this->assertEqual(
$expect[0],
ArcanistXHPASTLintNamingHook::isUpperCamelCase($test),
- "UpperCamelCase: '{$test}'");
+ pht("UpperCamelCase: '%s'", $test));
$this->assertEqual(
$expect[1],
ArcanistXHPASTLintNamingHook::isLowerCamelCase($test),
- "lowerCamelCase: '{$test}'");
+ pht("lowerCamelCase: '%s'", $test));
$this->assertEqual(
$expect[2],
ArcanistXHPASTLintNamingHook::isUppercaseWithUnderscores($test),
- "UPPERCASE_WITH_UNDERSCORES: '{$test}'");
+ pht("UPPERCASE_WITH_UNDERSCORES: '%s'", $test));
$this->assertEqual(
$expect[3],
ArcanistXHPASTLintNamingHook::isLowercaseWithUnderscores($test),
- "lowercase_with_underscores: '{$test}'");
+ pht("lowercase_with_underscores: '%s'", $test));
}
}
public function testStripUtilities() {
// Variable stripping.
$this->assertEqual(
'stuff',
ArcanistXHPASTLintNamingHook::stripPHPVariable('stuff'));
$this->assertEqual(
'stuff',
ArcanistXHPASTLintNamingHook::stripPHPVariable('$stuff'));
// Function/method stripping.
$this->assertEqual(
'construct',
ArcanistXHPASTLintNamingHook::stripPHPFunction('construct'));
$this->assertEqual(
'construct',
ArcanistXHPASTLintNamingHook::stripPHPFunction('__construct'));
}
}
diff --git a/src/parser/ArcanistDiffParser.php b/src/parser/ArcanistDiffParser.php
index 0e9627b7..7966461f 100644
--- a/src/parser/ArcanistDiffParser.php
+++ b/src/parser/ArcanistDiffParser.php
@@ -1,1443 +1,1443 @@
<?php
/**
* Parses diffs from a working copy.
*/
final class ArcanistDiffParser {
protected $repositoryAPI;
protected $text;
protected $line;
protected $lineSaved;
protected $isGit;
protected $isMercurial;
protected $isRCS;
protected $detectBinaryFiles = false;
protected $tryEncoding;
protected $rawDiff;
protected $writeDiffOnFailure;
protected $changes = array();
private $forcePath;
public function setRepositoryAPI(ArcanistRepositoryAPI $repository_api) {
$this->repositoryAPI = $repository_api;
return $this;
}
public function setDetectBinaryFiles($detect) {
$this->detectBinaryFiles = $detect;
return $this;
}
public function setTryEncoding($encoding) {
$this->tryEncoding = $encoding;
return $this;
}
public function forcePath($path) {
$this->forcePath = $path;
return $this;
}
public function setChanges(array $changes) {
assert_instances_of($changes, 'ArcanistDiffChange');
$this->changes = mpull($changes, null, 'getCurrentPath');
return $this;
}
public function parseSubversionDiff(ArcanistSubversionAPI $api, $paths) {
$this->setRepositoryAPI($api);
$diffs = array();
foreach ($paths as $path => $status) {
if ($status & ArcanistRepositoryAPI::FLAG_UNTRACKED ||
$status & ArcanistRepositoryAPI::FLAG_CONFLICT ||
$status & ArcanistRepositoryAPI::FLAG_MISSING) {
unset($paths[$path]);
}
}
$root = null;
$from = array();
foreach ($paths as $path => $status) {
$change = $this->buildChange($path);
if ($status & ArcanistRepositoryAPI::FLAG_ADDED) {
$change->setType(ArcanistDiffChangeType::TYPE_ADD);
} else if ($status & ArcanistRepositoryAPI::FLAG_DELETED) {
$change->setType(ArcanistDiffChangeType::TYPE_DELETE);
} else {
$change->setType(ArcanistDiffChangeType::TYPE_CHANGE);
}
$is_dir = is_dir($api->getPath($path));
if ($is_dir) {
$change->setFileType(ArcanistDiffChangeType::FILE_DIRECTORY);
// We have to go hit the diff even for directories because they may
// have property changes or moves, etc.
}
$is_link = is_link($api->getPath($path));
if ($is_link) {
$change->setFileType(ArcanistDiffChangeType::FILE_SYMLINK);
}
$diff = $api->getRawDiffText($path);
if ($diff) {
$this->parseDiff($diff);
}
$info = $api->getSVNInfo($path);
if (idx($info, 'Copied From URL')) {
if (!$root) {
$rinfo = $api->getSVNInfo('.');
$root = $rinfo['URL'].'/';
}
$cpath = $info['Copied From URL'];
$root_len = strlen($root);
if (!strncmp($cpath, $root, $root_len)) {
$cpath = substr($cpath, $root_len);
// The user can "svn cp /path/to/file@12345 x", which pulls a file out
// of version history at a specific revision. If we just use the path,
// we'll collide with possible changes to that path in the working
// copy below. In particular, "svn cp"-ing a path which no longer
// exists somewhere in the working copy and then adding that path
// gets us to the "origin change type" branches below with a
// TYPE_ADD state on the path. To avoid this, append the origin
// revision to the path so we'll necessarily generate a new change.
// TODO: In theory, you could have an '@' in your path and this could
// cause a collision, e.g. two files named 'f' and 'f@12345'. This is
// at least somewhat the user's fault, though.
if ($info['Copied From Rev']) {
if ($info['Copied From Rev'] != $info['Revision']) {
$cpath .= '@'.$info['Copied From Rev'];
}
}
$change->setOldPath($cpath);
$from[$path] = $cpath;
}
}
$type = $change->getType();
if (($type === ArcanistDiffChangeType::TYPE_MOVE_AWAY ||
$type === ArcanistDiffChangeType::TYPE_DELETE) &&
idx($info, 'Node Kind') === 'directory') {
$change->setFileType(ArcanistDiffChangeType::FILE_DIRECTORY);
}
}
foreach ($paths as $path => $status) {
$change = $this->buildChange($path);
if (empty($from[$path])) {
continue;
}
if (empty($this->changes[$from[$path]])) {
if ($change->getType() == ArcanistDiffChangeType::TYPE_COPY_HERE) {
// If the origin path wasn't changed (or isn't included in this diff)
// and we only copied it, don't generate a changeset for it. This
// keeps us out of trouble when we go to 'arc commit' and need to
// figure out which files should be included in the commit list.
continue;
}
}
$origin = $this->buildChange($from[$path]);
$origin->addAwayPath($change->getCurrentPath());
$type = $origin->getType();
switch ($type) {
case ArcanistDiffChangeType::TYPE_MULTICOPY:
case ArcanistDiffChangeType::TYPE_COPY_AWAY:
// "Add" is possible if you do some bizarre tricks with svn:ignore and
// "svn copy"'ing URLs straight from the repository; you can end up with
// a file that is a copy of itself. See T271.
case ArcanistDiffChangeType::TYPE_ADD:
break;
case ArcanistDiffChangeType::TYPE_DELETE:
$origin->setType(ArcanistDiffChangeType::TYPE_MOVE_AWAY);
break;
case ArcanistDiffChangeType::TYPE_MOVE_AWAY:
$origin->setType(ArcanistDiffChangeType::TYPE_MULTICOPY);
break;
case ArcanistDiffChangeType::TYPE_CHANGE:
$origin->setType(ArcanistDiffChangeType::TYPE_COPY_AWAY);
break;
default:
throw new Exception(pht('Bad origin state %s.', $type));
}
$type = $origin->getType();
switch ($type) {
case ArcanistDiffChangeType::TYPE_MULTICOPY:
case ArcanistDiffChangeType::TYPE_MOVE_AWAY:
$change->setType(ArcanistDiffChangeType::TYPE_MOVE_HERE);
break;
case ArcanistDiffChangeType::TYPE_ADD:
case ArcanistDiffChangeType::TYPE_COPY_AWAY:
$change->setType(ArcanistDiffChangeType::TYPE_COPY_HERE);
break;
default:
throw new Exception(pht('Bad origin state %s.', $type));
}
}
return $this->changes;
}
public function parseDiff($diff) {
if (!strlen(trim($diff))) {
throw new Exception(pht("Can't parse an empty diff!"));
}
// Detect `git-format-patch`, by looking for a "---" line somewhere in
// the file and then a footer with Git version number, which looks like
// this:
//
// --
// 1.8.4.2
//
// Note that `git-format-patch` adds a space after the "--", but we don't
// require it when detecting patches, as trailing whitespace can easily be
// lost in transit.
$detect_patch = '/^---$.*^-- ?[\s\d.]+\z/ms';
$message = null;
if (preg_match($detect_patch, $diff)) {
list($message, $diff) = $this->stripGitFormatPatch($diff);
}
$this->didStartParse($diff);
// Strip off header comments. While `patch` allows comments anywhere in the
// file, `git apply` is more strict. We get these comments in `hg export`
// diffs, and Eclipse can also produce them.
$line = $this->getLineTrimmed();
while (preg_match('/^#/', $line)) {
$line = $this->nextLine();
}
if (strlen($message)) {
// If we found a message during pre-parse steps, add it to the resulting
// changes here.
$change = $this->buildChange(null)
->setType(ArcanistDiffChangeType::TYPE_MESSAGE)
->setMetadata('message', $message);
}
do {
$patterns = array(
// This is a normal SVN text change, probably from "svn diff".
'(?P<type>Index): (?P<cur>.+)',
// This is an SVN text change, probably from "svnlook diff".
'(?P<type>Modified|Added|Deleted|Copied): (?P<cur>.+)',
// This is an SVN property change, probably from "svn diff".
'(?P<type>Property changes on): (?P<cur>.+)',
// This is a git commit message, probably from "git show".
'(?P<type>commit) (?P<hash>[a-f0-9]+)(?: \(.*\))?',
// This is a git diff, probably from "git show" or "git diff".
// Note that the filenames may appear quoted.
'(?P<type>diff --git) (?P<oldnew>.*)',
// RCS Diff
'(?P<type>rcsdiff -u) (?P<oldnew>.*)',
// This is a unified diff, probably from "diff -u" or synthetic diffing.
'(?P<type>---) (?P<old>.+)\s+\d{4}-\d{2}-\d{2}.*',
'(?P<binary>Binary files|Files) '.
'(?P<old>.+)\s+\d{4}-\d{2}-\d{2} and '.
'(?P<new>.+)\s+\d{4}-\d{2}-\d{2} differ.*',
// This is a normal Mercurial text change, probably from "hg diff". It
// may have two "-r" blocks if it came from "hg diff -r x:y".
'(?P<type>diff -r) (?P<hgrev>[a-f0-9]+) (?:-r [a-f0-9]+ )?(?P<cur>.+)',
);
$line = $this->getLineTrimmed();
$match = null;
$ok = $this->tryMatchHeader($patterns, $line, $match);
$failed_parse = false;
if (!$ok && $this->isFirstNonEmptyLine()) {
// 'hg export' command creates so called "extended diff" that
// contains some meta information and comment at the beginning
// (isFirstNonEmptyLine() to check for beginning). Actual mercurial
// code detects where comment ends and unified diff starts by
// searching for "diff -r" or "diff --git" in the text.
$this->saveLine();
$line = $this->nextLineThatLooksLikeDiffStart();
if (!$this->tryMatchHeader($patterns, $line, $match)) {
// Restore line before guessing to display correct error.
$this->restoreLine();
$failed_parse = true;
}
} else if (!$ok) {
$failed_parse = true;
}
if ($failed_parse) {
$this->didFailParse(
pht(
"Expected a hunk header, like '%s' (svn), '%s' (svn properties), ".
"'%s' (git show), '%s' (git diff), '%s' (unified diff), or ".
"'%s' (hg diff or patch).",
'Index: /path/to/file.ext',
'Property changes on: /path/to/file.ext',
'commit 59bcc3ad6775562f845953cf01624225',
'diff --git',
'--- filename',
'diff -r'));
}
if (isset($match['type'])) {
if ($match['type'] == 'diff --git') {
list($old, $new) = self::splitGitDiffPaths($match['oldnew']);
$match['old'] = $old;
$match['cur'] = $new;
}
}
$change = $this->buildChange(idx($match, 'cur'));
if (isset($match['old'])) {
$change->setOldPath($match['old']);
}
if (isset($match['hash'])) {
$change->setCommitHash($match['hash']);
}
if (isset($match['binary'])) {
$change->setFileType(ArcanistDiffChangeType::FILE_BINARY);
$line = $this->nextNonemptyLine();
continue;
}
$line = $this->nextLine();
switch ($match['type']) {
case 'Index':
case 'Modified':
case 'Added':
case 'Deleted':
case 'Copied':
$this->parseIndexHunk($change);
break;
case 'Property changes on':
$this->parsePropertyHunk($change);
break;
case 'diff --git':
$this->setIsGit(true);
$this->parseIndexHunk($change);
break;
case 'commit':
$this->setIsGit(true);
$this->parseCommitMessage($change);
break;
case '---':
$ok = preg_match(
'@^(?:\+\+\+) (.*)\s+\d{4}-\d{2}-\d{2}.*$@',
$line,
$match);
if (!$ok) {
$this->didFailParse(pht(
"Expected '%s' in unified diff.",
'+++ filename'));
}
$change->setCurrentPath($match[1]);
$line = $this->nextLine();
$this->parseChangeset($change);
break;
case 'diff -r':
$this->setIsMercurial(true);
$this->parseIndexHunk($change);
break;
case 'rcsdiff -u':
$this->isRCS = true;
$this->parseIndexHunk($change);
break;
default:
$this->didFailParse(pht('Unknown diff type.'));
break;
}
} while ($this->getLine() !== null);
$this->didFinishParse();
$this->loadSyntheticData();
return $this->changes;
}
protected function tryMatchHeader($patterns, $line, &$match) {
foreach ($patterns as $pattern) {
if (preg_match('@^'.$pattern.'$@', $line, $match)) {
return true;
}
}
return false;
}
protected function parseCommitMessage(ArcanistDiffChange $change) {
$change->setType(ArcanistDiffChangeType::TYPE_MESSAGE);
$message = array();
$line = $this->getLine();
if (preg_match('/^Merge: /', $line)) {
$this->nextLine();
}
$line = $this->getLine();
if (!preg_match('/^Author: /', $line)) {
$this->didFailParse(pht("Expected 'Author:'."));
}
$line = $this->nextLine();
if (!preg_match('/^Date: /', $line)) {
$this->didFailParse(pht("Expected 'Date:'."));
}
while (($line = $this->nextLineTrimmed()) !== null) {
if (strlen($line) && $line[0] != ' ') {
break;
}
// Strip leading spaces from Git commit messages. Note that empty lines
// are represented as just "\n"; don't touch those.
$message[] = preg_replace('/^ /', '', $this->getLine());
}
$message = rtrim(implode('', $message), "\r\n");
$change->setMetadata('message', $message);
}
/**
* Parse an SVN property change hunk. These hunks are ambiguous so just sort
* of try to get it mostly right. It's entirely possible to foil this parser
* (or any other parser) with a carefully constructed property change.
*/
protected function parsePropertyHunk(ArcanistDiffChange $change) {
$line = $this->getLineTrimmed();
if (!preg_match('/^_+$/', $line)) {
$this->didFailParse(pht("Expected '%s'.", '______________________'));
}
$line = $this->nextLine();
while ($line !== null) {
$done = preg_match('/^(Index|Property changes on):/', $line);
if ($done) {
break;
}
// NOTE: Before 1.5, SVN uses "Name". At 1.5 and later, SVN uses
// "Modified", "Added" and "Deleted".
$matches = null;
$ok = preg_match(
'/^(Name|Modified|Added|Deleted): (.*)$/',
$line,
$matches);
if (!$ok) {
$this->didFailParse(
pht("Expected 'Name', 'Added', 'Deleted', or 'Modified'."));
}
$op = $matches[1];
$prop = $matches[2];
list($old, $new) = $this->parseSVNPropertyChange($op, $prop);
if ($old !== null) {
$change->setOldProperty($prop, $old);
}
if ($new !== null) {
$change->setNewProperty($prop, $new);
}
$line = $this->getLine();
}
}
private function parseSVNPropertyChange($op, $prop) {
$old = array();
$new = array();
$target = null;
$line = $this->nextLine();
$prop_index = 2;
while ($line !== null) {
$done = preg_match(
'/^(Modified|Added|Deleted|Index|Property changes on):/',
$line);
if ($done) {
break;
}
$trimline = ltrim($line);
if ($trimline && $trimline[0] == '#') {
// in svn1.7, a line like ## -0,0 +1 ## is put between the Added: line
// and the line with the property change. If we have such a line, we'll
// just ignore it (:
$line = $this->nextLine();
$prop_index = 1;
$trimline = ltrim($line);
}
if ($trimline && $trimline[0] == '+') {
if ($op == 'Deleted') {
$this->didFailParse(pht(
'Unexpected "%s" section in property deletion.',
'+'));
}
$target = 'new';
$line = substr($trimline, $prop_index);
} else if ($trimline && $trimline[0] == '-') {
if ($op == 'Added') {
$this->didFailParse(pht(
'Unexpected "%s" section in property addition.',
'-'));
}
$target = 'old';
$line = substr($trimline, $prop_index);
} else if (!strncmp($trimline, 'Merged', 6)) {
if ($op == 'Added') {
$target = 'new';
} else {
// These can appear on merges. No idea how to interpret this (unclear
// what the old / new values are) and it's of dubious usefulness so
// just throw it away until someone complains.
$target = null;
}
$line = $trimline;
}
if ($target == 'new') {
$new[] = $line;
} else if ($target == 'old') {
$old[] = $line;
}
$line = $this->nextLine();
}
$old = rtrim(implode('', $old));
$new = rtrim(implode('', $new));
if (!strlen($old)) {
$old = null;
}
if (!strlen($new)) {
$new = null;
}
return array($old, $new);
}
protected function setIsGit($git) {
if ($this->isGit !== null && $this->isGit != $git) {
throw new Exception(pht('Git status has changed!'));
}
$this->isGit = $git;
return $this;
}
protected function getIsGit() {
return $this->isGit;
}
public function setIsMercurial($is_mercurial) {
$this->isMercurial = $is_mercurial;
return $this;
}
public function getIsMercurial() {
return $this->isMercurial;
}
protected function parseIndexHunk(ArcanistDiffChange $change) {
$is_git = $this->getIsGit();
$is_mercurial = $this->getIsMercurial();
$is_svn = (!$is_git && !$is_mercurial);
$move_source = null;
$line = $this->getLine();
if ($is_git) {
do {
$patterns = array(
'(?P<new>new) file mode (?P<newmode>\d+)',
'(?P<deleted>deleted) file mode (?P<oldmode>\d+)',
// These occur when someone uses `chmod` on a file.
'old mode (?P<oldmode>\d+)',
'new mode (?P<newmode>\d+)',
// These occur when you `mv` a file and git figures it out.
'similarity index ',
'rename from (?P<old>.*)',
'(?P<move>rename) to (?P<cur>.*)',
'copy from (?P<old>.*)',
'(?P<copy>copy) to (?P<cur>.*)',
);
$ok = false;
$match = null;
foreach ($patterns as $pattern) {
$ok = preg_match('@^'.$pattern.'@', $line, $match);
if ($ok) {
break;
}
}
if (!$ok) {
if ($line === null ||
preg_match('/^(diff --git|commit) /', $line)) {
// In this case, there are ONLY file mode changes, or this is a
// pure move. If it's a move, flag these changesets so we can build
// synthetic changes later, enabling us to show file contents in
// Differential -- git only gives us a block like this:
//
// diff --git a/README b/READYOU
// similarity index 100%
// rename from README
// rename to READYOU
//
// ...i.e., there is no associated diff.
// This allows us to distinguish between property changes only
// and actual moves. For property changes only, we can't currently
// build a synthetic diff correctly, so just skip it.
// TODO: Build synthetic diffs for property changes, too.
if ($change->getType() != ArcanistDiffChangeType::TYPE_CHANGE) {
$change->setNeedsSyntheticGitHunks(true);
if ($move_source) {
$move_source->setNeedsSyntheticGitHunks(true);
}
}
return;
}
break;
}
if (!empty($match['oldmode'])) {
$change->setOldProperty('unix:filemode', $match['oldmode']);
}
if (!empty($match['newmode'])) {
$change->setNewProperty('unix:filemode', $match['newmode']);
}
if (!empty($match['deleted'])) {
$change->setType(ArcanistDiffChangeType::TYPE_DELETE);
}
if (!empty($match['new'])) {
// If you replace a symlink with a normal file, git renders the change
// as a "delete" of the symlink plus an "add" of the new file. We
// prefer to represent this as a change.
if ($change->getType() == ArcanistDiffChangeType::TYPE_DELETE) {
$change->setType(ArcanistDiffChangeType::TYPE_CHANGE);
} else {
$change->setType(ArcanistDiffChangeType::TYPE_ADD);
}
}
if (!empty($match['old'])) {
$match['old'] = self::unescapeFilename($match['old']);
$change->setOldPath($match['old']);
}
if (!empty($match['cur'])) {
$match['cur'] = self::unescapeFilename($match['cur']);
$change->setCurrentPath($match['cur']);
}
if (!empty($match['copy'])) {
$change->setType(ArcanistDiffChangeType::TYPE_COPY_HERE);
$old = $this->buildChange($change->getOldPath());
$type = $old->getType();
if ($type == ArcanistDiffChangeType::TYPE_MOVE_AWAY) {
$old->setType(ArcanistDiffChangeType::TYPE_MULTICOPY);
} else {
$old->setType(ArcanistDiffChangeType::TYPE_COPY_AWAY);
}
$old->addAwayPath($change->getCurrentPath());
}
if (!empty($match['move'])) {
$change->setType(ArcanistDiffChangeType::TYPE_MOVE_HERE);
$old = $this->buildChange($change->getOldPath());
$type = $old->getType();
if ($type == ArcanistDiffChangeType::TYPE_MULTICOPY) {
// Great, no change.
} else if ($type == ArcanistDiffChangeType::TYPE_MOVE_AWAY) {
$old->setType(ArcanistDiffChangeType::TYPE_MULTICOPY);
} else if ($type == ArcanistDiffChangeType::TYPE_COPY_AWAY) {
$old->setType(ArcanistDiffChangeType::TYPE_MULTICOPY);
} else {
$old->setType(ArcanistDiffChangeType::TYPE_MOVE_AWAY);
}
// We'll reference this above.
$move_source = $old;
$old->addAwayPath($change->getCurrentPath());
}
$line = $this->nextNonemptyLine();
} while (true);
}
$line = $this->getLine();
if ($is_svn) {
$ok = preg_match('/^=+\s*$/', $line);
if (!$ok) {
$this->didFailParse(pht(
"Expected '%s' divider line.",
'======================='));
} else {
// Adding an empty file in SVN can produce an empty line here.
$line = $this->nextNonemptyLine();
}
} else if ($is_git) {
$ok = preg_match('/^index .*$/', $line);
if (!$ok) {
// TODO: "hg diff -g" diffs ("mercurial git-style diffs") do not include
// this line, so we can't parse them if we fail on it. Maybe introduce
// a flag saying "parse this diff using relaxed git-style diff rules"?
// $this->didFailParse("Expected 'index af23f...a98bc' header line.");
} else {
// NOTE: In the git case, where this patch is the last change in the
// file, we may have a final terminal newline. Skip over it so that
// we'll hit the '$line === null' block below. This is covered by the
// 'git-empty-file.gitdiff' test case.
$line = $this->nextNonemptyLine();
}
}
// If there are files with only whitespace changes and -b or -w are
// supplied as command-line flags to `diff', svn and git both produce
// changes without any body.
if ($line === null ||
preg_match(
'/^(Index:|Property changes on:|diff --git|commit) /',
$line)) {
return;
}
$is_binary_add = preg_match(
'/^Cannot display: file marked as a binary type\.$/',
rtrim($line));
if ($is_binary_add) {
$this->nextLine(); // Cannot display: file marked as a binary type.
$this->nextNonemptyLine(); // svn:mime-type = application/octet-stream
$this->markBinary($change);
return;
}
// We can get this in git, or in SVN when a file exists in the repository
// WITHOUT a binary mime-type and is changed and given a binary mime-type.
$is_binary_diff = preg_match(
'/^(Binary files|Files) .* and .* differ$/',
rtrim($line));
if ($is_binary_diff) {
$this->nextNonemptyLine(); // Binary files x and y differ
$this->markBinary($change);
return;
}
// This occurs under "hg diff --git" when a binary file is removed. See
// test case "hg-binary-delete.hgdiff". (I believe it never occurs under
// git, which reports the "files X and /dev/null differ" string above. Git
// can not apply these patches.)
$is_hg_binary_delete = preg_match(
'/^Binary file .* has changed$/',
rtrim($line));
if ($is_hg_binary_delete) {
$this->nextNonemptyLine();
$this->markBinary($change);
return;
}
// With "git diff --binary" (not a normal mode, but one users may explicitly
// invoke and then, e.g., copy-paste into the web console) or "hg diff
// --git" (normal under hg workflows), we may encounter a literal binary
// patch.
$is_git_binary_patch = preg_match(
'/^GIT binary patch$/',
rtrim($line));
if ($is_git_binary_patch) {
$this->nextLine();
$this->parseGitBinaryPatch();
$line = $this->getLine();
if (preg_match('/^literal/', $line)) {
// We may have old/new binaries (change) or just a new binary (hg add).
// If there are two blocks, parse both.
$this->parseGitBinaryPatch();
}
$this->markBinary($change);
return;
}
if ($is_git) {
// "git diff -b" ignores whitespace, but has an empty hunk target
if (preg_match('@^diff --git .*$@', $line)) {
$this->nextLine();
return null;
}
}
if ($this->isRCS) {
// Skip the RCS headers.
$this->nextLine();
$this->nextLine();
$this->nextLine();
}
$old_file = $this->parseHunkTarget();
$new_file = $this->parseHunkTarget();
if ($this->isRCS) {
$change->setCurrentPath($new_file);
}
$change->setOldPath($old_file);
$this->parseChangeset($change);
}
private function parseGitBinaryPatch() {
// TODO: We could decode the patches, but it's a giant mess so don't bother
// for now. We'll pick up the data from the working copy in the common
// case ("arc diff").
$line = $this->getLine();
if (!preg_match('/^literal /', $line)) {
$this->didFailParse(
pht("Expected '%s' to start git binary patch.", 'literal NNNN'));
}
do {
$line = $this->nextLineTrimmed();
if ($line === '' || $line === null) {
// Some versions of Mercurial apparently omit the terminal newline,
// although it's unclear if Git will ever do this. In either case,
// rely on the base85 check for sanity.
$this->nextNonemptyLine();
return;
} else if (!preg_match('/^[a-zA-Z]/', $line)) {
$this->didFailParse(
pht('Expected base85 line length character (a-zA-Z).'));
}
} while (true);
}
protected function parseHunkTarget() {
$line = $this->getLine();
$matches = null;
$remainder = '(?:\s*\(.*\))?';
if ($this->getIsMercurial()) {
// Something like "Fri Aug 26 01:20:50 2005 -0700", don't bother trying
// to parse it.
$remainder = '\t.*';
} else if ($this->isRCS) {
$remainder = '\s.*';
} else if ($this->getIsGit()) {
// When filenames contain spaces, Git terminates this line with a tab.
// Normally, the tab is not present. If there's a tab, ignore it.
$remainder = '(?:\t.*)?';
}
$ok = preg_match(
'@^[-+]{3} (?:[ab]/)?(?P<path>.*?)'.$remainder.'$@',
$line,
$matches);
if (!$ok) {
$this->didFailParse(
pht(
"Expected hunk target '%s'.",
'+++ path/to/file.ext (revision N)'));
}
$this->nextLine();
return $matches['path'];
}
protected function markBinary(ArcanistDiffChange $change) {
$change->setFileType(ArcanistDiffChangeType::FILE_BINARY);
return $this;
}
protected function parseChangeset(ArcanistDiffChange $change) {
// If a diff includes two sets of changes to the same file, let the
// second one win. In particular, this occurs when adding subdirectories
// in Subversion that contain files: the file text will be present in
// both the directory diff and the file diff. See T5555. Dropping the
// hunks lets whichever one shows up later win instead of showing changes
// twice.
$change->dropHunks();
$all_changes = array();
do {
$hunk = new ArcanistDiffHunk();
$line = $this->getLineTrimmed();
$real = array();
// In the case where only one line is changed, the length is omitted.
// The final group is for git, which appends a guess at the function
// context to the diff.
$matches = null;
$ok = preg_match(
'/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?: .*?)?$/U',
$line,
$matches);
if (!$ok) {
// It's possible we hit the style of an svn1.7 property change.
// This is a 4-line Index block, followed by an empty line, followed
// by a "Property changes on:" section similar to svn1.6.
if ($line == '') {
$line = $this->nextNonemptyLine();
$ok = preg_match('/^Property changes on:/', $line);
if (!$ok) {
$this->didFailParse(pht('Confused by empty line'));
}
$line = $this->nextLine();
return $this->parsePropertyHunk($change);
}
$this->didFailParse(pht(
"Expected hunk header '%s'.",
'@@ -NN,NN +NN,NN @@'));
}
$hunk->setOldOffset($matches[1]);
$hunk->setNewOffset($matches[3]);
// Cover for the cases where length wasn't present (implying one line).
$old_len = idx($matches, 2);
if (!strlen($old_len)) {
$old_len = 1;
}
$new_len = idx($matches, 4);
if (!strlen($new_len)) {
$new_len = 1;
}
$hunk->setOldLength($old_len);
$hunk->setNewLength($new_len);
$add = 0;
$del = 0;
$hit_next_hunk = false;
while ((($line = $this->nextLine()) !== null)) {
if (strlen(rtrim($line, "\r\n"))) {
$char = $line[0];
} else {
// Normally, we do not encouter empty lines in diffs, because
// unchanged lines have an initial space. However, in Git, with
// the option `diff.suppress-blank-empty` set, unchanged blank lines
// emit as completely empty. If we encounter a completely empty line,
// treat it as a ' ' (i.e., unchanged empty line) line.
$char = ' ';
}
switch ($char) {
case '\\':
if (!preg_match('@\\ No newline at end of file@', $line)) {
$this->didFailParse(
pht("Expected '\ No newline at end of file'."));
}
if ($new_len) {
$real[] = $line;
$hunk->setIsMissingOldNewline(true);
} else {
$real[] = $line;
$hunk->setIsMissingNewNewline(true);
}
if (!$new_len) {
break 2;
}
break;
case '+':
++$add;
--$new_len;
$real[] = $line;
break;
case '-':
if (!$old_len) {
// In this case, we've hit "---" from a new file. So don't
// advance the line cursor.
$hit_next_hunk = true;
break 2;
}
++$del;
--$old_len;
$real[] = $line;
break;
case ' ':
if (!$old_len && !$new_len) {
break 2;
}
--$old_len;
--$new_len;
$real[] = $line;
break;
default:
// We hit something, likely another hunk.
$hit_next_hunk = true;
break 2;
}
}
if ($old_len || $new_len) {
$this->didFailParse(pht('Found the wrong number of hunk lines.'));
}
$corpus = implode('', $real);
$is_binary = false;
if ($this->detectBinaryFiles) {
$is_binary = !phutil_is_utf8($corpus);
$try_encoding = $this->tryEncoding;
if ($is_binary && $try_encoding) {
$is_binary = ArcanistDiffUtils::isHeuristicBinaryFile($corpus);
if (!$is_binary) {
$corpus = phutil_utf8_convert($corpus, 'UTF-8', $try_encoding);
if (!phutil_is_utf8($corpus)) {
throw new Exception(
pht(
"Failed to convert a hunk from '%s' to UTF-8. ".
"Check that the specified encoding is correct.",
$try_encoding));
}
}
}
}
if ($is_binary) {
// SVN happily treats binary files which aren't marked with the right
// mime type as text files. Detect that junk here and mark the file
// binary. We'll catch stuff with unicode too, but that's verboten
// anyway. If there are too many false positives with this we might
// need to make it threshold-triggered instead of triggering on any
// unprintable byte.
$change->setFileType(ArcanistDiffChangeType::FILE_BINARY);
} else {
$hunk->setCorpus($corpus);
$hunk->setAddLines($add);
$hunk->setDelLines($del);
$change->addHunk($hunk);
}
if (!$hit_next_hunk) {
$line = $this->nextNonemptyLine();
}
} while (preg_match('/^@@ /', $line));
}
protected function buildChange($path = null) {
$change = null;
if ($path !== null) {
if (!empty($this->changes[$path])) {
return $this->changes[$path];
}
}
if ($this->forcePath) {
return $this->changes[$this->forcePath];
}
$change = new ArcanistDiffChange();
if ($path !== null) {
$change->setCurrentPath($path);
$this->changes[$path] = $change;
} else {
$this->changes[] = $change;
}
return $change;
}
protected function didStartParse($text) {
$this->rawDiff = $text;
// Eat leading whitespace. This may happen if the first change in the diff
// is an SVN property change.
$text = ltrim($text);
// Try to strip ANSI color codes from colorized diffs. ANSI color codes
// might be present in two cases:
//
// - You piped a colorized diff into 'arc --raw' or similar (normally
// we're able to disable colorization on diffs we control the generation
// of).
// - You're diffing a file which actually contains ANSI color codes.
//
// The former is vastly more likely, but we try to distinguish between the
// two cases by testing for a color code at the beginning of a line. If
// we find one, we know it's a colorized diff (since the beginning of the
// line should be "+", "-" or " " if the code is in the diff text).
//
// While it's possible a diff might be colorized and fail this test, it's
// unlikely, and it covers hg's color extension which seems to be the most
// stubborn about colorizing text despite stdout not being a TTY.
//
// We might incorrectly strip color codes from a colorized diff of a text
// file with color codes inside it, but this case is stupid and pathological
// and you've dug your own grave.
$ansi_color_pattern = '\x1B\[[\d;]*m';
if (preg_match('/^'.$ansi_color_pattern.'/m', $text)) {
$text = preg_replace('/'.$ansi_color_pattern.'/', '', $text);
}
$this->text = phutil_split_lines($text);
$this->line = 0;
}
protected function getLine() {
if ($this->text === null) {
- throw new Exception('Not parsing!');
+ throw new Exception(pht('Not parsing!'));
}
if (isset($this->text[$this->line])) {
return $this->text[$this->line];
}
return null;
}
protected function getLineTrimmed() {
$line = $this->getLine();
if ($line !== null) {
$line = trim($line, "\r\n");
}
return $line;
}
protected function nextLine() {
$this->line++;
return $this->getLine();
}
protected function nextLineTrimmed() {
$line = $this->nextLine();
if ($line !== null) {
$line = trim($line, "\r\n");
}
return $line;
}
protected function nextNonemptyLine() {
while (($line = $this->nextLine()) !== null) {
if (strlen(trim($line)) !== 0) {
break;
}
}
return $this->getLine();
}
protected function nextLineThatLooksLikeDiffStart() {
while (($line = $this->nextLine()) !== null) {
if (preg_match('/^\s*diff\s+-(?:r|-git)/', $line)) {
break;
}
}
return $this->getLine();
}
protected function saveLine() {
$this->lineSaved = $this->line;
}
protected function restoreLine() {
$this->line = $this->lineSaved;
}
protected function isFirstNonEmptyLine() {
$len = count($this->text);
for ($ii = 0; $ii < $len; $ii++) {
$line = $this->text[$ii];
if (!strlen(trim($line))) {
// This line is empty, skip it.
continue;
}
if (preg_match('/^#/', $line)) {
// This line is a comment, skip it.
continue;
}
return ($ii == $this->line);
}
// Entire file is empty.
return false;
}
protected function didFinishParse() {
$this->text = null;
}
public function setWriteDiffOnFailure($write) {
$this->writeDiffOnFailure = $write;
return $this;
}
protected function didFailParse($message) {
$context = 5;
$min = max(0, $this->line - $context);
$max = min($this->line + $context, count($this->text) - 1);
$context = '';
for ($ii = $min; $ii <= $max; $ii++) {
$context .= sprintf(
'%8.8s %6.6s %s',
($ii == $this->line) ? '>>> ' : '',
$ii + 1,
$this->text[$ii]);
}
$out = array();
- $out[] = "Diff Parse Exception: {$message}";
+ $out[] = pht('Diff Parse Exception: %s', $message);
if ($this->writeDiffOnFailure) {
$temp = new TempFile();
$temp->setPreserveFile(true);
Filesystem::writeFile($temp, $this->rawDiff);
- $out[] = 'Raw input file was written to: '.(string)$temp;
+ $out[] = pht('Raw input file was written to: %s', $temp);
}
$out[] = $context;
$out = implode("\n\n", $out);
throw new Exception($out);
}
/**
* Unescape escaped filenames, e.g. from "git diff".
*/
private static function unescapeFilename($name) {
if (preg_match('/^".+"$/', $name)) {
return stripcslashes(substr($name, 1, -1));
} else {
return $name;
}
}
private function loadSyntheticData() {
if (!$this->changes) {
return;
}
$repository_api = $this->repositoryAPI;
if (!$repository_api) {
return;
}
$imagechanges = array();
$changes = $this->changes;
foreach ($changes as $change) {
$path = $change->getCurrentPath();
// Certain types of changes (moves and copies) don't contain change data
// when expressed in raw "git diff" form. Augment any such diffs with
// textual data.
if ($change->getNeedsSyntheticGitHunks() &&
($repository_api instanceof ArcanistGitAPI)) {
$diff = $repository_api->getRawDiffText($path, $moves = false);
// NOTE: We're reusing the parser and it doesn't reset change state
// between parses because there's an oddball SVN workflow in Phabricator
// which relies on being able to inject changes.
// TODO: Fix this.
$parser = clone $this;
$parser->setChanges(array());
$raw_changes = $parser->parseDiff($diff);
foreach ($raw_changes as $raw_change) {
if ($raw_change->getCurrentPath() == $path) {
$change->setFileType($raw_change->getFileType());
foreach ($raw_change->getHunks() as $hunk) {
// Git thinks that this file has been added. But we know that it
// has been moved or copied without a change.
$hunk->setCorpus(
preg_replace('/^\+/m', ' ', $hunk->getCorpus()));
$change->addHunk($hunk);
}
break;
}
}
$change->setNeedsSyntheticGitHunks(false);
}
if ($change->getFileType() != ArcanistDiffChangeType::FILE_BINARY &&
$change->getFileType() != ArcanistDiffChangeType::FILE_IMAGE) {
continue;
}
$imagechanges[$path] = $change;
}
// Fetch the actual file contents in batches so repositories
// that have slow random file accesses (i.e. mercurial) can
// optimize the retrieval.
$paths = array_keys($imagechanges);
$filedata = $repository_api->getBulkOriginalFileData($paths);
foreach ($filedata as $path => $data) {
$imagechanges[$path]->setOriginalFileData($data);
}
$filedata = $repository_api->getBulkCurrentFileData($paths);
foreach ($filedata as $path => $data) {
$imagechanges[$path]->setCurrentFileData($data);
}
$this->changes = $changes;
}
/**
* Strip prefixes off paths from `git diff`. By default git uses a/ and b/,
* but you can set `diff.mnemonicprefix` to get a different set of prefixes,
* or use `--no-prefix`, `--src-prefix` or `--dst-prefix` to set these to
* other arbitrary values.
*
* We strip the default and mnemonic prefixes, and trust the user knows what
* they're doing in the other cases.
*
* @param string Path to strip.
* @return string Stripped path.
*/
public static function stripGitPathPrefix($path) {
static $regex;
if ($regex === null) {
$prefixes = array(
// These are the defaults.
'a/',
'b/',
// These show up when you set "diff.mnemonicprefix".
'i/',
'c/',
'w/',
'o/',
'1/',
'2/',
);
foreach ($prefixes as $key => $prefix) {
$prefixes[$key] = preg_quote($prefix, '@');
}
$regex = '@^('.implode('|', $prefixes).')@S';
}
return preg_replace($regex, '', $path);
}
/**
* Split the paths on a "diff --git" line into old and new paths. This
* is difficult because they may be ambiguous if the files contain spaces.
*
* @param string Text from a diff line after "diff --git ".
* @return pair<string, string> Old and new paths.
*/
public static function splitGitDiffPaths($paths) {
$matches = null;
$paths = rtrim($paths, "\r\n");
$patterns = array(
// Try quoted paths, used for unicode filenames or filenames with quotes.
'@^(?P<old>"(?:\\\\.|[^"\\\\]+)+") (?P<new>"(?:\\\\.|[^"\\\\]+)+")$@',
// Try paths without spaces.
'@^(?P<old>[^ ]+) (?P<new>[^ ]+)$@',
// Try paths with well-known prefixes.
'@^(?P<old>[abicwo12]/.*) (?P<new>[abicwo12]/.*)$@',
// Try the exact same string twice in a row separated by a space.
// This can hit a false positive for moves from files like "old file old"
// to "file", but such a case combined with custom diff prefixes is
// incredibly obscure.
'@^(?P<old>.*) (?P<new>\\1)$@',
);
foreach ($patterns as $pattern) {
if (preg_match($pattern, $paths, $matches)) {
break;
}
}
if (!$matches) {
throw new Exception(
pht(
"Input diff contains ambiguous line '%s'. This line is ambiguous ".
"because there are spaces in the file names, so the parser can not ".
"determine where the file names begin and end. To resolve this ".
"ambiguity, use standard prefixes ('a/' and 'b/') when ".
"generating diffs.",
"diff --git {$paths}"));
}
$old = $matches['old'];
$old = self::unescapeFilename($old);
$old = self::stripGitPathPrefix($old);
$new = $matches['new'];
$new = self::unescapeFilename($new);
$new = self::stripGitPathPrefix($new);
return array($old, $new);
}
/**
* Strip the header and footer off a `git-format-patch` diff.
*
* Returns a parseable normal diff and a textual commit message.
*/
private function stripGitFormatPatch($diff) {
// We can parse this by splitting it into two pieces over and over again
// along different section dividers:
//
// 1. Mail headers.
// 2. ("\n\n")
// 3. Mail body.
// 4. ("---")
// 5. Diff stat section.
// 6. ("\n\n")
// 7. Actual diff body.
// 8. ("--")
// 9. Patch footer.
list($head, $tail) = preg_split('/^---$/m', $diff, 2);
list($mail_headers, $mail_body) = explode("\n\n", $head, 2);
list($body, $foot) = preg_split('/^-- ?$/m', $tail, 2);
list($stat, $diff) = explode("\n\n", $body, 2);
// Rebuild the commit message by putting the subject line back on top of it,
// if we can find one.
$matches = null;
$pattern = '/^Subject: (?:\[PATCH\] )?(.*)$/mi';
if (preg_match($pattern, $mail_headers, $matches)) {
$mail_body = $matches[1]."\n\n".$mail_body;
$mail_body = rtrim($mail_body);
}
return array($mail_body, $diff);
}
}
diff --git a/src/parser/__tests__/ArcanistBaseCommitParserTestCase.php b/src/parser/__tests__/ArcanistBaseCommitParserTestCase.php
index 5580676b..5d6b11d2 100644
--- a/src/parser/__tests__/ArcanistBaseCommitParserTestCase.php
+++ b/src/parser/__tests__/ArcanistBaseCommitParserTestCase.php
@@ -1,162 +1,162 @@
<?php
final class ArcanistBaseCommitParserTestCase extends PhutilTestCase {
public function testBasics() {
// Verify that the very basics of base commit resolution work.
$this->assertCommit(
- 'Empty Rules',
+ pht('Empty Rules'),
null,
array(
));
$this->assertCommit(
'Literal',
'xyz',
array(
'runtime' => 'literal:xyz',
));
}
public function testResolutionOrder() {
// Rules should be resolved in order: args, local, project, global. These
// test cases intentionally scramble argument order to test that resolution
// order is independent of argument order.
$this->assertCommit(
- 'Order: Args',
+ pht('Order: Args'),
'y',
array(
'local' => 'literal:n',
'project' => 'literal:n',
'runtime' => 'literal:y',
'user' => 'literal:n',
));
$this->assertCommit(
- 'Order: Local',
+ pht('Order: Local'),
'y',
array(
'project' => 'literal:n',
'local' => 'literal:y',
'user' => 'literal:n',
));
$this->assertCommit(
- 'Order: Project',
+ pht('Order: Project'),
'y',
array(
'project' => 'literal:y',
'user' => 'literal:n',
));
$this->assertCommit(
- 'Order: Global',
+ pht('Order: Global'),
'y',
array(
'user' => 'literal:y',
));
}
public function testLegacyRule() {
// 'global' should translate to 'user'
$this->assertCommit(
- '"global" name',
+ pht('"%s" name', 'global'),
'y',
array(
'runtime' => 'arc:global, arc:halt',
'local' => 'arc:halt',
'project' => 'arc:halt',
'user' => 'literal:y',
));
// 'args' should translate to 'runtime'
$this->assertCommit(
- '"args" name',
+ pht('"%s" name', 'args'),
'y',
array(
'runtime' => 'arc:project, literal:y',
'local' => 'arc:halt',
'project' => 'arc:args',
'user' => 'arc:halt',
));
}
public function testHalt() {
// 'arc:halt' should halt all processing.
$this->assertCommit(
- 'Halt',
+ pht('Halt'),
null,
array(
'runtime' => 'arc:halt',
'local' => 'literal:xyz',
));
}
public function testYield() {
// 'arc:yield' should yield to other rulesets.
$this->assertCommit(
- 'Yield',
+ pht('Yield'),
'xyz',
array(
'runtime' => 'arc:yield, literal:abc',
'local' => 'literal:xyz',
));
// This one should return to 'runtime' after exhausting 'local'.
$this->assertCommit(
- 'Yield + Return',
+ pht('Yield + Return'),
'abc',
array(
'runtime' => 'arc:yield, literal:abc',
'local' => 'arc:skip',
));
}
public function testJump() {
// This should resolve to 'abc' without hitting any of the halts.
$this->assertCommit(
- 'Jump',
+ pht('Jump'),
'abc',
array(
'runtime' => 'arc:project, arc:halt',
'local' => 'literal:abc',
'project' => 'arc:user, arc:halt',
'user' => 'arc:local, arc:halt',
));
}
public function testJumpReturn() {
// After jumping to project, we should return to 'runtime'.
$this->assertCommit(
- 'Jump Return',
+ pht('Jump Return'),
'xyz',
array(
'runtime' => 'arc:project, literal:xyz',
'local' => 'arc:halt',
'project' => '',
'user' => 'arc:halt',
));
}
private function assertCommit($desc, $commit, $rules) {
$parser = $this->buildParser();
$result = $parser->resolveBaseCommit($rules);
$this->assertEqual($commit, $result, $desc);
}
private function buildParser() {
// TODO: This is a little hacky because we're using the Arcanist repository
// itself to execute tests with, but it should be OK until we get proper
// isolation for repository-oriented test cases.
$root = dirname(phutil_get_library_root('arcanist'));
$working_copy = ArcanistWorkingCopyIdentity::newFromPath($root);
$configuration_manager = new ArcanistConfigurationManager();
$configuration_manager->setWorkingCopyIdentity($working_copy);
$repo = ArcanistRepositoryAPI::newAPIFromConfigurationManager(
$configuration_manager);
return new ArcanistBaseCommitParser($repo);
}
}
diff --git a/src/repository/api/ArcanistGitAPI.php b/src/repository/api/ArcanistGitAPI.php
index 7b0bd64b..b9c6185f 100644
--- a/src/repository/api/ArcanistGitAPI.php
+++ b/src/repository/api/ArcanistGitAPI.php
@@ -1,1254 +1,1255 @@
<?php
/**
* Interfaces with Git working copies.
*/
final class ArcanistGitAPI extends ArcanistRepositoryAPI {
private $repositoryHasNoCommits = false;
const SEARCH_LENGTH_FOR_PARENT_REVISIONS = 16;
/**
* For the repository's initial commit, 'git diff HEAD^' and similar do
* not work. Using this instead does work; it is the hash of the empty tree.
*/
const GIT_MAGIC_ROOT_COMMIT = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
private $symbolicHeadCommit;
private $resolvedHeadCommit;
protected function buildLocalFuture(array $argv) {
$argv[0] = 'git '.$argv[0];
$future = newv('ExecFuture', $argv);
$future->setCWD($this->getPath());
return $future;
}
public function execPassthru($pattern /* , ... */) {
$args = func_get_args();
static $git = null;
if ($git === null) {
if (phutil_is_windows()) {
// NOTE: On Windows, phutil_passthru() uses 'bypass_shell' because
// everything goes to hell if we don't. We must provide an absolute
// path to Git for this to work properly.
$git = Filesystem::resolveBinary('git');
$git = csprintf('%s', $git);
} else {
$git = 'git';
}
}
$args[0] = $git.' '.$args[0];
return call_user_func_array('phutil_passthru', $args);
}
public function getSourceControlSystemName() {
return 'git';
}
public function getMetadataPath() {
static $path = null;
if ($path === null) {
list($stdout) = $this->execxLocal('rev-parse --git-dir');
$path = rtrim($stdout, "\n");
// the output of git rev-parse --git-dir is an absolute path, unless
// the cwd is the root of the repository, in which case it uses the
// relative path of .git. If we get this relative path, turn it into
// an absolute path.
if ($path === '.git') {
$path = $this->getPath('.git');
}
}
return $path;
}
public function getHasCommits() {
return !$this->repositoryHasNoCommits;
}
/**
* Tests if a child commit is descendant of a parent commit.
* If child and parent are the same, it returns false.
* @param Child commit SHA.
* @param Parent commit SHA.
* @return bool True if the child is a descendant of the parent.
*/
private function isDescendant($child, $parent) {
list($common_ancestor) = $this->execxLocal(
'merge-base %s %s',
$child,
$parent);
$common_ancestor = trim($common_ancestor);
return ($common_ancestor == $parent) && ($common_ancestor != $child);
}
public function getLocalCommitInformation() {
if ($this->repositoryHasNoCommits) {
// Zero commits.
throw new Exception(
pht(
"You can't get local commit information for a repository with no ".
"commits."));
} else if ($this->getBaseCommit() == self::GIT_MAGIC_ROOT_COMMIT) {
// One commit.
$against = 'HEAD';
} else {
// 2..N commits. We include commits reachable from HEAD which are
// not reachable from the base commit; this is consistent with user
// expectations even though it is not actually the diff range.
// Particularly:
//
// |
// D <----- master branch
// |
// C Y <- feature branch
// | /|
// B X
// | /
// A
// |
//
// If "A, B, C, D" are master, and the user is at Y, when they run
// "arc diff B" they want (and get) a diff of B vs Y, but they think about
// this as being the commits X and Y. If we log "B..Y", we only show
// Y. With "Y --not B", we show X and Y.
if ($this->symbolicHeadCommit !== null) {
$base_commit = $this->getBaseCommit();
$resolved_base = $this->resolveCommit($base_commit);
$head_commit = $this->symbolicHeadCommit;
$resolved_head = $this->getHeadCommit();
if (!$this->isDescendant($resolved_head, $resolved_base)) {
// NOTE: Since the base commit will have been resolved as the
// merge-base of the specified base and the specified HEAD, we can't
// easily tell exactly what's wrong with the range.
// For example, `arc diff HEAD --head HEAD^^^` is invalid because it
// is reversed, but resolving the commit "HEAD" will compute its
// merge-base with "HEAD^^^", which is "HEAD^^^", so the range will
// appear empty.
throw new ArcanistUsageException(
pht(
'The specified commit range is empty, backward or invalid: the '.
'base (%s) is not an ancestor of the head (%s). You can not '.
'diff an empty or reversed commit range.',
$base_commit,
$head_commit));
}
}
$against = csprintf(
'%s --not %s',
$this->getHeadCommit(),
$this->getBaseCommit());
}
// NOTE: Windows escaping of "%" symbols apparently is inherently broken;
// when passed through escapeshellarg() they are replaced with spaces.
// TODO: Learn how cmd.exe works and find some clever workaround?
// NOTE: If we use "%x00", output is truncated in Windows.
list($info) = $this->execxLocal(
phutil_is_windows()
? 'log %C --format=%C --'
: 'log %C --format=%s --',
$against,
// NOTE: "%B" is somewhat new, use "%s%n%n%b" instead.
'%H%x01%T%x01%P%x01%at%x01%an%x01%aE%x01%s%x01%s%n%n%b%x02');
$commits = array();
$info = trim($info, " \n\2");
if (!strlen($info)) {
return array();
}
$info = explode("\2", $info);
foreach ($info as $line) {
list($commit, $tree, $parents, $time, $author, $author_email,
$title, $message) = explode("\1", trim($line), 8);
$message = rtrim($message);
$commits[$commit] = array(
'commit' => $commit,
'tree' => $tree,
'parents' => array_filter(explode(' ', $parents)),
'time' => $time,
'author' => $author,
'summary' => $title,
'message' => $message,
'authorEmail' => $author_email,
);
}
return $commits;
}
protected function buildBaseCommit($symbolic_commit) {
if ($symbolic_commit !== null) {
if ($symbolic_commit == self::GIT_MAGIC_ROOT_COMMIT) {
$this->setBaseCommitExplanation(
pht('you explicitly specified the empty tree.'));
return $symbolic_commit;
}
list($err, $merge_base) = $this->execManualLocal(
'merge-base %s %s',
$symbolic_commit,
$this->getHeadCommit());
if ($err) {
throw new ArcanistUsageException(
pht(
"Unable to find any git commit named '%s' in this repository.",
$symbolic_commit));
}
if ($this->symbolicHeadCommit === null) {
$this->setBaseCommitExplanation(
pht(
"it is the merge-base of the explicitly specified base commit ".
"'%s' and HEAD.",
$symbolic_commit));
} else {
$this->setBaseCommitExplanation(
pht(
"it is the merge-base of the explicitly specified base commit ".
"'%s' and the explicitly specified head commit '%s'.",
$symbolic_commit,
$this->symbolicHeadCommit));
}
return trim($merge_base);
}
// Detect zero-commit or one-commit repositories. There is only one
// relative-commit value that makes any sense in these repositories: the
// empty tree.
list($err) = $this->execManualLocal('rev-parse --verify HEAD^');
if ($err) {
list($err) = $this->execManualLocal('rev-parse --verify HEAD');
if ($err) {
$this->repositoryHasNoCommits = true;
}
if ($this->repositoryHasNoCommits) {
$this->setBaseCommitExplanation(pht('the repository has no commits.'));
} else {
$this->setBaseCommitExplanation(
pht('the repository has only one commit.'));
}
return self::GIT_MAGIC_ROOT_COMMIT;
}
if ($this->getBaseCommitArgumentRules() ||
$this->getConfigurationManager()->getConfigFromAnySource('base')) {
$base = $this->resolveBaseCommit();
if (!$base) {
throw new ArcanistUsageException(
pht(
"None of the rules in your 'base' configuration matched a valid ".
"commit. Adjust rules or specify which commit you want to use ".
"explicitly."));
}
return $base;
}
$do_write = false;
$default_relative = null;
$working_copy = $this->getWorkingCopyIdentity();
if ($working_copy) {
$default_relative = $working_copy->getProjectConfig(
'git.default-relative-commit');
$this->setBaseCommitExplanation(
pht(
"it is the merge-base of '%s' and HEAD, as specified in '%s' in ".
"'%s'. This setting overrides other settings.",
$default_relative,
'git.default-relative-commit',
'.arcconfig'));
}
if (!$default_relative) {
list($err, $upstream) = $this->execManualLocal(
'rev-parse --abbrev-ref --symbolic-full-name %s',
'@{upstream}');
if (!$err) {
$default_relative = trim($upstream);
$this->setBaseCommitExplanation(
pht(
"it is the merge-base of '%s' (the Git upstream ".
"of the current branch) HEAD.",
$default_relative));
}
}
if (!$default_relative) {
$default_relative = $this->readScratchFile('default-relative-commit');
$default_relative = trim($default_relative);
if ($default_relative) {
$this->setBaseCommitExplanation(
pht(
"it is the merge-base of '%s' and HEAD, as specified in '%s'.",
$default_relative,
'.git/arc/default-relative-commit'));
}
}
if (!$default_relative) {
// TODO: Remove the history lesson soon.
echo phutil_console_format(
- "<bg:green>** Select a Default Commit Range **</bg>\n\n");
+ "<bg:green>** %s **</bg>\n\n",
+ pht('Select a Default Commit Range'));
echo phutil_console_wrap(
pht(
"You're running a command which operates on a range of revisions ".
"(usually, from some revision to HEAD) but have not specified the ".
"revision that should determine the start of the range.\n\n".
"Previously, arc assumed you meant '%s' when you did not specify ".
"a start revision, but this behavior does not make much sense in ".
"most workflows outside of Facebook's historic %s workflow.\n\n".
"arc no longer assumes '%s'. You must specify a relative commit ".
"explicitly when you invoke a command (e.g., `%s`, not just `%s`) ".
"or select a default for this working copy.\n\nIn most cases, the ".
"best default is '%s'. You can also select '%s' to preserve the ".
"old behavior, or some other remote or branch. But you almost ".
"certainly want to select 'origin/master'.\n\n".
"(Technically: the merge-base of the selected revision and HEAD is ".
"used to determine the start of the commit range.)",
'HEAD^',
'git-svn',
'HEAD^',
'arc diff HEAD^',
'arc diff',
'origin/master',
'HEAD^'));
$prompt = pht('What default do you want to use? [origin/master]');
$default = phutil_console_prompt($prompt);
if (!strlen(trim($default))) {
$default = 'origin/master';
}
$default_relative = $default;
$do_write = true;
}
list($object_type) = $this->execxLocal(
'cat-file -t %s',
$default_relative);
if (trim($object_type) !== 'commit') {
throw new Exception(
pht(
"Relative commit '%s' is not the name of a commit!",
$default_relative));
}
if ($do_write) {
// Don't perform this write until we've verified that the object is a
// valid commit name.
$this->writeScratchFile('default-relative-commit', $default_relative);
$this->setBaseCommitExplanation(
pht(
"it is the merge-base of '%s' and HEAD, as you just specified.",
$default_relative));
}
list($merge_base) = $this->execxLocal(
'merge-base %s HEAD',
$default_relative);
return trim($merge_base);
}
public function getHeadCommit() {
if ($this->resolvedHeadCommit === null) {
$this->resolvedHeadCommit = $this->resolveCommit(
coalesce($this->symbolicHeadCommit, 'HEAD'));
}
return $this->resolvedHeadCommit;
}
public function setHeadCommit($symbolic_commit) {
$this->symbolicHeadCommit = $symbolic_commit;
$this->reloadCommitRange();
return $this;
}
/**
* Translates a symbolic commit (like "HEAD^") to a commit identifier.
* @param string_symbol commit.
* @return string the commit SHA.
*/
private function resolveCommit($symbolic_commit) {
list($err, $commit_hash) = $this->execManualLocal(
'rev-parse %s',
$symbolic_commit);
if ($err) {
throw new ArcanistUsageException(
pht(
"Unable to find any git commit named '%s' in this repository.",
$symbolic_commit));
}
return trim($commit_hash);
}
private function getDiffFullOptions($detect_moves_and_renames = true) {
$options = array(
self::getDiffBaseOptions(),
'--no-color',
'--src-prefix=a/',
'--dst-prefix=b/',
'-U'.$this->getDiffLinesOfContext(),
);
if ($detect_moves_and_renames) {
$options[] = '-M';
$options[] = '-C';
}
return implode(' ', $options);
}
private function getDiffBaseOptions() {
$options = array(
// Disable external diff drivers, like graphical differs, since Arcanist
// needs to capture the diff text.
'--no-ext-diff',
// Disable textconv so we treat binary files as binary, even if they have
// an alternative textual representation. TODO: Ideally, Differential
// would ship up the binaries for 'arc patch' but display the textconv
// output in the visual diff.
'--no-textconv',
);
return implode(' ', $options);
}
/**
* @param the base revision
* @param head revision. If this is null, the generated diff will include the
* working copy
*/
public function getFullGitDiff($base, $head = null) {
$options = $this->getDiffFullOptions();
if ($head !== null) {
list($stdout) = $this->execxLocal(
"diff {$options} %s %s --",
$base,
$head);
} else {
list($stdout) = $this->execxLocal(
"diff {$options} %s --",
$base);
}
return $stdout;
}
/**
* @param string Path to generate a diff for.
* @param bool If true, detect moves and renames. Otherwise, ignore
* moves/renames; this is useful because it prompts git to
* generate real diff text.
*/
public function getRawDiffText($path, $detect_moves_and_renames = true) {
$options = $this->getDiffFullOptions($detect_moves_and_renames);
list($stdout) = $this->execxLocal(
"diff {$options} %s -- %s",
$this->getBaseCommit(),
$path);
return $stdout;
}
public function getBranchName() {
// TODO: consider:
//
// $ git rev-parse --abbrev-ref `git symbolic-ref HEAD`
//
// But that may fail if you're not on a branch.
list($stdout) = $this->execxLocal('branch --no-color');
// Assume that any branch beginning with '(' means 'no branch', or whatever
// 'no branch' is in the current locale.
$matches = null;
if (preg_match('/^\* ([^\(].*)$/m', $stdout, $matches)) {
return $matches[1];
}
return null;
}
public function getRemoteURI() {
list($stdout) = $this->execxLocal('remote show -n origin');
$matches = null;
if (preg_match('/^\s*Fetch URL: (.*)$/m', $stdout, $matches)) {
return trim($matches[1]);
}
return null;
}
public function getSourceControlPath() {
// TODO: Try to get something useful here.
return null;
}
public function getGitCommitLog() {
$relative = $this->getBaseCommit();
if ($this->repositoryHasNoCommits) {
// No commits yet.
return '';
} else if ($relative == self::GIT_MAGIC_ROOT_COMMIT) {
// First commit.
list($stdout) = $this->execxLocal(
'log --format=medium HEAD');
} else {
// 2..N commits.
list($stdout) = $this->execxLocal(
'log --first-parent --format=medium %s..%s',
$this->getBaseCommit(),
$this->getHeadCommit());
}
return $stdout;
}
public function getGitHistoryLog() {
list($stdout) = $this->execxLocal(
'log --format=medium -n%d %s',
self::SEARCH_LENGTH_FOR_PARENT_REVISIONS,
$this->getBaseCommit());
return $stdout;
}
public function getSourceControlBaseRevision() {
list($stdout) = $this->execxLocal(
'rev-parse %s',
$this->getBaseCommit());
return rtrim($stdout, "\n");
}
public function getCanonicalRevisionName($string) {
$match = null;
if (preg_match('/@([0-9]+)$/', $string, $match)) {
$stdout = $this->getHashFromFromSVNRevisionNumber($match[1]);
} else {
list($stdout) = $this->execxLocal(
phutil_is_windows()
? 'show -s --format=%C %s --'
: 'show -s --format=%s %s --',
'%H',
$string);
}
return rtrim($stdout);
}
private function executeSVNFindRev($input, $vcs) {
$match = array();
list($stdout) = $this->execxLocal(
'svn find-rev %s',
$input);
if (!$stdout) {
throw new ArcanistUsageException(
pht(
'Cannot find the %s equivalent of %s.',
$vcs,
$input));
}
// When git performs a partial-rebuild during svn
// look-up, we need to parse the final line
$lines = explode("\n", $stdout);
$stdout = $lines[count($lines) - 2];
return rtrim($stdout);
}
// Convert svn revision number to git hash
public function getHashFromFromSVNRevisionNumber($revision_id) {
return $this->executeSVNFindRev('r'.$revision_id, 'Git');
}
// Convert a git hash to svn revision number
public function getSVNRevisionNumberFromHash($hash) {
return $this->executeSVNFindRev($hash, 'SVN');
}
protected function buildUncommittedStatus() {
$diff_options = $this->getDiffBaseOptions();
if ($this->repositoryHasNoCommits) {
$diff_base = self::GIT_MAGIC_ROOT_COMMIT;
} else {
$diff_base = 'HEAD';
}
// Find uncommitted changes.
$uncommitted_future = $this->buildLocalFuture(
array(
'diff %C --raw %s --',
$diff_options,
$diff_base,
));
$untracked_future = $this->buildLocalFuture(
array(
'ls-files --others --exclude-standard',
));
// Unstaged changes
$unstaged_future = $this->buildLocalFuture(
array(
'diff-files --name-only',
));
$futures = array(
$uncommitted_future,
$untracked_future,
// NOTE: `git diff-files` races with each of these other commands
// internally, and resolves with inconsistent results if executed
// in parallel. To work around this, DO NOT run it at the same time.
// After the other commands exit, we can start the `diff-files` command.
);
id(new FutureIterator($futures))->resolveAll();
// We're clear to start the `git diff-files` now.
$unstaged_future->start();
$result = new PhutilArrayWithDefaultValue();
list($stdout) = $uncommitted_future->resolvex();
$uncommitted_files = $this->parseGitStatus($stdout);
foreach ($uncommitted_files as $path => $mask) {
$result[$path] |= ($mask | self::FLAG_UNCOMMITTED);
}
list($stdout) = $untracked_future->resolvex();
$stdout = rtrim($stdout, "\n");
if (strlen($stdout)) {
$stdout = explode("\n", $stdout);
foreach ($stdout as $path) {
$result[$path] |= self::FLAG_UNTRACKED;
}
}
list($stdout, $stderr) = $unstaged_future->resolvex();
$stdout = rtrim($stdout, "\n");
if (strlen($stdout)) {
$stdout = explode("\n", $stdout);
foreach ($stdout as $path) {
$result[$path] |= self::FLAG_UNSTAGED;
}
}
return $result->toArray();
}
protected function buildCommitRangeStatus() {
list($stdout, $stderr) = $this->execxLocal(
'diff %C --raw %s --',
$this->getDiffBaseOptions(),
$this->getBaseCommit());
return $this->parseGitStatus($stdout);
}
public function getGitConfig($key, $default = null) {
list($err, $stdout) = $this->execManualLocal('config %s', $key);
if ($err) {
return $default;
}
return rtrim($stdout);
}
public function getAuthor() {
list($stdout) = $this->execxLocal('var GIT_AUTHOR_IDENT');
return preg_replace('/\s+<.*/', '', rtrim($stdout, "\n"));
}
public function addToCommit(array $paths) {
$this->execxLocal(
'add -A -- %Ls',
$paths);
$this->reloadWorkingCopy();
return $this;
}
public function doCommit($message) {
$tmp_file = new TempFile();
Filesystem::writeFile($tmp_file, $message);
// NOTE: "--allow-empty-message" was introduced some time after 1.7.0.4,
// so we do not provide it and thus require a message.
$this->execxLocal(
'commit -F %s',
$tmp_file);
$this->reloadWorkingCopy();
return $this;
}
public function amendCommit($message = null) {
if ($message === null) {
$this->execxLocal('commit --amend --allow-empty -C HEAD');
} else {
$tmp_file = new TempFile();
Filesystem::writeFile($tmp_file, $message);
$this->execxLocal(
'commit --amend --allow-empty -F %s',
$tmp_file);
}
$this->reloadWorkingCopy();
return $this;
}
private function parseGitStatus($status, $full = false) {
static $flags = array(
'A' => self::FLAG_ADDED,
'M' => self::FLAG_MODIFIED,
'D' => self::FLAG_DELETED,
);
$status = trim($status);
$lines = array();
foreach (explode("\n", $status) as $line) {
if ($line) {
$lines[] = preg_split("/[ \t]/", $line, 6);
}
}
$files = array();
foreach ($lines as $line) {
$mask = 0;
$flag = $line[4];
$file = $line[5];
foreach ($flags as $key => $bits) {
if ($flag == $key) {
$mask |= $bits;
}
}
if ($full) {
$files[$file] = array(
'mask' => $mask,
'ref' => rtrim($line[3], '.'),
);
} else {
$files[$file] = $mask;
}
}
return $files;
}
public function getAllFiles() {
$future = $this->buildLocalFuture(array('ls-files -z'));
return id(new LinesOfALargeExecFuture($future))
->setDelimiter("\0");
}
public function getChangedFiles($since_commit) {
list($stdout) = $this->execxLocal(
'diff --raw %s',
$since_commit);
return $this->parseGitStatus($stdout);
}
public function getBlame($path) {
// TODO: 'git blame' supports --porcelain and we should probably use it.
list($stdout) = $this->execxLocal(
'blame --date=iso -w -M %s -- %s',
$this->getBaseCommit(),
$path);
$blame = array();
foreach (explode("\n", trim($stdout)) as $line) {
if (!strlen($line)) {
continue;
}
// lines predating a git repo's history are blamed to the oldest revision,
// with the commit hash prepended by a ^. we shouldn't count these lines
// as blaming to the oldest diff's unfortunate author
if ($line[0] == '^') {
continue;
}
$matches = null;
$ok = preg_match(
'/^([0-9a-f]+)[^(]+?[(](.*?) +\d\d\d\d-\d\d-\d\d/',
$line,
$matches);
if (!$ok) {
throw new Exception(pht("Bad blame? `%s'", $line));
}
$revision = $matches[1];
$author = $matches[2];
$blame[] = array($author, $revision);
}
return $blame;
}
public function getOriginalFileData($path) {
return $this->getFileDataAtRevision($path, $this->getBaseCommit());
}
public function getCurrentFileData($path) {
return $this->getFileDataAtRevision($path, 'HEAD');
}
private function parseGitTree($stdout) {
$result = array();
$stdout = trim($stdout);
if (!strlen($stdout)) {
return $result;
}
$lines = explode("\n", $stdout);
foreach ($lines as $line) {
$matches = array();
$ok = preg_match(
'/^(\d{6}) (blob|tree|commit) ([a-z0-9]{40})[\t](.*)$/',
$line,
$matches);
if (!$ok) {
throw new Exception(pht('Failed to parse %s output!', 'git ls-tree'));
}
$result[$matches[4]] = array(
'mode' => $matches[1],
'type' => $matches[2],
'ref' => $matches[3],
);
}
return $result;
}
private function getFileDataAtRevision($path, $revision) {
// NOTE: We don't want to just "git show {$revision}:{$path}" since if the
// path was a directory at the given revision we'll get a list of its files
// and treat it as though it as a file containing a list of other files,
// which is silly.
list($stdout) = $this->execxLocal(
'ls-tree %s -- %s',
$revision,
$path);
$info = $this->parseGitTree($stdout);
if (empty($info[$path])) {
// No such path, or the path is a directory and we executed 'ls-tree dir/'
// and got a list of its contents back.
return null;
}
if ($info[$path]['type'] != 'blob') {
// Path is or was a directory, not a file.
return null;
}
list($stdout) = $this->execxLocal(
'cat-file blob %s',
$info[$path]['ref']);
return $stdout;
}
/**
* Returns names of all the branches in the current repository.
*
* @return list<dict<string, string>> Dictionary of branch information.
*/
public function getAllBranches() {
list($branch_info) = $this->execxLocal(
'branch --no-color');
$lines = explode("\n", rtrim($branch_info));
$result = array();
foreach ($lines as $line) {
if (preg_match('@^[* ]+\(no branch|detached from \w+/\w+\)@', $line)) {
// This is indicating that the working copy is in a detached state;
// just ignore it.
continue;
}
list($current, $name) = preg_split('/\s+/', $line, 2);
$result[] = array(
'current' => !empty($current),
'name' => $name,
);
}
return $result;
}
public function getWorkingCopyRevision() {
list($stdout) = $this->execxLocal('rev-parse HEAD');
return rtrim($stdout, "\n");
}
public function getUnderlyingWorkingCopyRevision() {
list($err, $stdout) = $this->execManualLocal('svn find-rev HEAD');
if (!$err && $stdout) {
return rtrim($stdout, "\n");
}
return $this->getWorkingCopyRevision();
}
public function isHistoryDefaultImmutable() {
return false;
}
public function supportsAmend() {
return true;
}
public function supportsCommitRanges() {
return true;
}
public function supportsLocalCommits() {
return true;
}
public function hasLocalCommit($commit) {
try {
if (!$this->getCanonicalRevisionName($commit)) {
return false;
}
} catch (CommandException $exception) {
return false;
}
return true;
}
public function getAllLocalChanges() {
$diff = $this->getFullGitDiff($this->getBaseCommit());
if (!strlen(trim($diff))) {
return array();
}
$parser = new ArcanistDiffParser();
return $parser->parseDiff($diff);
}
public function supportsLocalBranchMerge() {
return true;
}
public function performLocalBranchMerge($branch, $message) {
if (!$branch) {
throw new ArcanistUsageException(
pht('Under git, you must specify the branch you want to merge.'));
}
$err = phutil_passthru(
'(cd %s && git merge --no-ff -m %s %s)',
$this->getPath(),
$message,
$branch);
if ($err) {
- throw new ArcanistUsageException('Merge failed!');
+ throw new ArcanistUsageException(pht('Merge failed!'));
}
}
public function getFinalizedRevisionMessage() {
return pht(
"You may now push this commit upstream, as appropriate (e.g. with ".
"'%s', or '%s', or by printing and faxing it).",
'git push',
'git svn dcommit');
}
public function getCommitMessage($commit) {
list($message) = $this->execxLocal(
'log -n1 --format=%C %s --',
'%s%n%n%b',
$commit);
return $message;
}
public function loadWorkingCopyDifferentialRevisions(
ConduitClient $conduit,
array $query) {
$messages = $this->getGitCommitLog();
if (!strlen($messages)) {
return array();
}
$parser = new ArcanistDiffParser();
$messages = $parser->parseDiff($messages);
// First, try to find revisions by explicit revision IDs in commit messages.
$reason_map = array();
$revision_ids = array();
foreach ($messages as $message) {
$object = ArcanistDifferentialCommitMessage::newFromRawCorpus(
$message->getMetadata('message'));
if ($object->getRevisionID()) {
$revision_ids[] = $object->getRevisionID();
$reason_map[$object->getRevisionID()] = $message->getCommitHash();
}
}
if ($revision_ids) {
$results = $conduit->callMethodSynchronous(
'differential.query',
$query + array(
'ids' => $revision_ids,
));
foreach ($results as $key => $result) {
$hash = substr($reason_map[$result['id']], 0, 16);
$results[$key]['why'] = pht(
"Commit message for '%s' has explicit 'Differential Revision'.",
$hash);
}
return $results;
}
// If we didn't succeed, try to find revisions by hash.
$hashes = array();
foreach ($this->getLocalCommitInformation() as $commit) {
$hashes[] = array('gtcm', $commit['commit']);
$hashes[] = array('gttr', $commit['tree']);
}
$results = $conduit->callMethodSynchronous(
'differential.query',
$query + array(
'commitHashes' => $hashes,
));
foreach ($results as $key => $result) {
$results[$key]['why'] = pht(
'A git commit or tree hash in the commit range is already attached '.
'to the Differential revision.');
}
return $results;
}
public function updateWorkingCopy() {
$this->execxLocal('pull');
$this->reloadWorkingCopy();
}
public function getCommitSummary($commit) {
if ($commit == self::GIT_MAGIC_ROOT_COMMIT) {
return pht('(The Empty Tree)');
}
list($summary) = $this->execxLocal(
'log -n 1 --format=%C %s',
'%s',
$commit);
return trim($summary);
}
public function backoutCommit($commit_hash) {
$this->execxLocal('revert %s -n --no-edit', $commit_hash);
$this->reloadWorkingCopy();
if (!$this->getUncommittedStatus()) {
throw new ArcanistUsageException(
pht('%s has already been reverted.', $commit_hash));
}
}
public function getBackoutMessage($commit_hash) {
return pht('This reverts commit %s.', $commit_hash);
}
public function isGitSubversionRepo() {
return Filesystem::pathExists($this->getPath('.git/svn'));
}
public function resolveBaseCommitRule($rule, $source) {
list($type, $name) = explode(':', $rule, 2);
switch ($type) {
case 'git':
$matches = null;
if (preg_match('/^merge-base\((.+)\)$/', $name, $matches)) {
list($err, $merge_base) = $this->execManualLocal(
'merge-base %s HEAD',
$matches[1]);
if (!$err) {
$this->setBaseCommitExplanation(
pht(
"it is the merge-base of '%s' and HEAD, as specified by ".
"'%s' in your %s 'base' configuration.",
$matches[1],
$rule,
$source));
return trim($merge_base);
}
} else if (preg_match('/^branch-unique\((.+)\)$/', $name, $matches)) {
list($err, $merge_base) = $this->execManualLocal(
'merge-base %s HEAD',
$matches[1]);
if ($err) {
return null;
}
$merge_base = trim($merge_base);
list($commits) = $this->execxLocal(
'log --format=%C %s..HEAD --',
'%H',
$merge_base);
$commits = array_filter(explode("\n", $commits));
if (!$commits) {
return null;
}
$commits[] = $merge_base;
$head_branch_count = null;
foreach ($commits as $commit) {
list($branches) = $this->execxLocal(
'branch --contains %s',
$commit);
$branches = array_filter(explode("\n", $branches));
if ($head_branch_count === null) {
// If this is the first commit, it's HEAD. Count how many
// branches it is on; we want to include commits on the same
// number of branches. This covers a case where this branch
// has sub-branches and we're running "arc diff" here again
// for whatever reason.
$head_branch_count = count($branches);
} else if (count($branches) > $head_branch_count) {
foreach ($branches as $key => $branch) {
$branches[$key] = trim($branch, ' *');
}
$branches = implode(', ', $branches);
$this->setBaseCommitExplanation(
pht(
"it is the first commit between '%s' (the merge-base of ".
"'%s' and HEAD) which is also contained by another branch ".
"(%s).",
$merge_base,
$matches[1],
$branches));
return $commit;
}
}
} else {
list($err) = $this->execManualLocal(
'cat-file -t %s',
$name);
if (!$err) {
$this->setBaseCommitExplanation(
pht(
"it is specified by '%s' in your %s 'base' configuration.",
$rule,
$source));
return $name;
}
}
break;
case 'arc':
switch ($name) {
case 'empty':
$this->setBaseCommitExplanation(
pht(
"you specified '%s' in your %s 'base' configuration.",
$rule,
$source));
return self::GIT_MAGIC_ROOT_COMMIT;
case 'amended':
$text = $this->getCommitMessage('HEAD');
$message = ArcanistDifferentialCommitMessage::newFromRawCorpus(
$text);
if ($message->getRevisionID()) {
$this->setBaseCommitExplanation(
pht(
"HEAD has been amended with 'Differential Revision:', ".
"as specified by '%s' in your %s 'base' configuration.",
$rule,
$source));
return 'HEAD^';
}
break;
case 'upstream':
list($err, $upstream) = $this->execManualLocal(
'rev-parse --abbrev-ref --symbolic-full-name %s',
'@{upstream}');
if (!$err) {
$upstream = rtrim($upstream);
list($upstream_merge_base) = $this->execxLocal(
'merge-base %s HEAD',
$upstream);
$upstream_merge_base = rtrim($upstream_merge_base);
$this->setBaseCommitExplanation(
pht(
"it is the merge-base of the upstream of the current branch ".
"and HEAD, and matched the rule '%s' in your %s ".
"'base' configuration.",
$rule,
$source));
return $upstream_merge_base;
}
break;
case 'this':
$this->setBaseCommitExplanation(
pht(
"you specified '%s' in your %s 'base' configuration.",
$rule,
$source));
return 'HEAD^';
}
default:
return null;
}
return null;
}
public function canStashChanges() {
return true;
}
public function stashChanges() {
$this->execxLocal('stash');
$this->reloadWorkingCopy();
}
public function unstashChanges() {
$this->execxLocal('stash pop');
}
protected function didReloadCommitRange() {
// After an amend, the symbolic head may resolve to a different commit.
$this->resolvedHeadCommit = null;
}
}
diff --git a/src/unit/engine/PhutilUnitTestEngine.php b/src/unit/engine/PhutilUnitTestEngine.php
index 3879396c..1abf1e74 100644
--- a/src/unit/engine/PhutilUnitTestEngine.php
+++ b/src/unit/engine/PhutilUnitTestEngine.php
@@ -1,201 +1,201 @@
<?php
/**
* Very basic unit test engine which runs libphutil tests.
*/
final class PhutilUnitTestEngine extends ArcanistUnitTestEngine {
protected function supportsRunAllTests() {
return true;
}
public function run() {
if ($this->getRunAllTests()) {
$run_tests = $this->getAllTests();
} else {
$run_tests = $this->getTestsForPaths();
}
if (!$run_tests) {
- throw new ArcanistNoEffectException('No tests to run.');
+ throw new ArcanistNoEffectException(pht('No tests to run.'));
}
$enable_coverage = $this->getEnableCoverage();
if ($enable_coverage !== false) {
if (!function_exists('xdebug_start_code_coverage')) {
if ($enable_coverage === true) {
throw new ArcanistUsageException(
pht(
'You specified %s but xdebug is not available, so '.
'coverage can not be enabled for %s.',
'--coverage',
__CLASS__));
}
} else {
$enable_coverage = true;
}
}
$project_root = $this->getWorkingCopy()->getProjectRoot();
$test_cases = array();
foreach ($run_tests as $test_class) {
$test_case = newv($test_class, array());
$test_case->setEnableCoverage($enable_coverage);
$test_case->setWorkingCopy($this->getWorkingCopy());
if ($this->getPaths()) {
$test_case->setPaths($this->getPaths());
}
if ($this->renderer) {
$test_case->setRenderer($this->renderer);
}
$test_cases[] = $test_case;
}
foreach ($test_cases as $test_case) {
$test_case->willRunTestCases($test_cases);
}
$results = array();
foreach ($test_cases as $test_case) {
$results[] = $test_case->run();
}
$results = array_mergev($results);
foreach ($test_cases as $test_case) {
$test_case->didRunTestCases($test_cases);
}
return $results;
}
private function getAllTests() {
$project_root = $this->getWorkingCopy()->getProjectRoot();
$symbols = id(new PhutilSymbolLoader())
->setType('class')
->setAncestorClass('PhutilTestCase')
->setConcreteOnly(true)
->selectSymbolsWithoutLoading();
$in_working_copy = array();
$run_tests = array();
foreach ($symbols as $symbol) {
if (!preg_match('@(?:^|/)__tests__/@', $symbol['where'])) {
continue;
}
$library = $symbol['library'];
if (!isset($in_working_copy[$library])) {
$library_root = phutil_get_library_root($library);
$in_working_copy[$library] = Filesystem::isDescendant(
$library_root,
$project_root);
}
if ($in_working_copy[$library]) {
$run_tests[] = $symbol['name'];
}
}
return $run_tests;
}
private function getTestsForPaths() {
$project_root = $this->getWorkingCopy()->getProjectRoot();
$look_here = array();
foreach ($this->getPaths() as $path) {
$library_root = phutil_get_library_root_for_path($path);
if (!$library_root) {
continue;
}
$library_name = phutil_get_library_name_for_root($library_root);
if (!$library_name) {
throw new Exception(
sprintf(
"%s\n\n %s\n\n%s\n\n - %s\n - %s\n",
pht(
'Attempting to run unit tests on a libphutil library '.
'which has not been loaded, at:'),
$library_root,
pht('This probably means one of two things:'),
pht(
'You may need to add this library to %s.',
'.arcconfig.'),
pht(
'You may be running tests on a copy of libphutil or '.
'arcanist using a different copy of libphutil or arcanist. '.
'This operation is not supported.')));
}
$path = Filesystem::resolvePath($path, $project_root);
if (!is_dir($path)) {
$path = dirname($path);
}
if ($path == $library_root) {
$look_here[$library_name.':.'] = array(
'library' => $library_name,
'path' => '',
);
} else if (!Filesystem::isDescendant($path, $library_root)) {
// We have encountered some kind of symlink maze -- for instance, $path
// is some symlink living outside the library that links into some file
// inside the library. Just ignore these cases, since the affected file
// does not actually lie within the library.
continue;
} else {
$library_path = Filesystem::readablePath($path, $library_root);
do {
$look_here[$library_name.':'.$library_path] = array(
'library' => $library_name,
'path' => $library_path,
);
$library_path = dirname($library_path);
} while ($library_path != '.');
}
}
// Look for any class that extends PhutilTestCase inside a `__tests__`
// directory in any parent directory of every affected file.
//
// The idea is that "infrastructure/__tests__/" tests defines general tests
// for all of "infrastructure/", and those tests run for any change in
// "infrastructure/". However, "infrastructure/concrete/rebar/__tests__/"
// defines more specific tests that run only when rebar/ (or some
// subdirectory) changes.
$run_tests = array();
foreach ($look_here as $path_info) {
$library = $path_info['library'];
$path = $path_info['path'];
$symbols = id(new PhutilSymbolLoader())
->setType('class')
->setLibrary($library)
->setPathPrefix(($path ? $path.'/' : '').'__tests__/')
->setAncestorClass('PhutilTestCase')
->setConcreteOnly(true)
->selectAndLoadSymbols();
foreach ($symbols as $symbol) {
$run_tests[$symbol['name']] = true;
}
}
$run_tests = array_keys($run_tests);
return $run_tests;
}
public function shouldEchoTestResults() {
return !$this->renderer;
}
}
diff --git a/src/unit/parser/ArcanistPhpunitTestResultParser.php b/src/unit/parser/ArcanistPhpunitTestResultParser.php
index 314c8265..8eaeb1ab 100644
--- a/src/unit/parser/ArcanistPhpunitTestResultParser.php
+++ b/src/unit/parser/ArcanistPhpunitTestResultParser.php
@@ -1,187 +1,187 @@
<?php
/**
* PHPUnit Result Parsing utility
*
* For an example on how to integrate with your test engine, see
* @{class:PhpunitTestEngine}.
*/
final class ArcanistPhpunitTestResultParser extends ArcanistTestResultParser {
/**
* Parse test results from phpunit json report
*
* @param string $path Path to test
* @param string $test_results String containing phpunit json report
*
* @return array
*/
public function parseTestResults($path, $test_results) {
if (!$test_results) {
$result = id(new ArcanistUnitTestResult())
->setName($path)
->setUserData($this->stderr)
->setResult(ArcanistUnitTestResult::RESULT_BROKEN);
return array($result);
}
$report = $this->getJsonReport($test_results);
// coverage is for all testcases in the executed $path
$coverage = array();
if ($this->enableCoverage !== false) {
$coverage = $this->readCoverage();
}
$results = array();
foreach ($report as $event) {
switch (idx($event, 'event')) {
case 'test':
break;
case 'testStart':
$last_test_finished = false;
// fall through
default:
continue 2; // switch + loop
}
$status = ArcanistUnitTestResult::RESULT_PASS;
$user_data = '';
if ('fail' == idx($event, 'status')) {
$status = ArcanistUnitTestResult::RESULT_FAIL;
$user_data .= idx($event, 'message')."\n";
foreach (idx($event, 'trace') as $trace) {
$user_data .= sprintf(
- "\n%s:%s",
- idx($trace, 'file'),
- idx($trace, 'line'));
+ "\n%s:%s",
+ idx($trace, 'file'),
+ idx($trace, 'line'));
}
} else if ('error' == idx($event, 'status')) {
if (strpos(idx($event, 'message'), 'Skipped Test') !== false) {
$status = ArcanistUnitTestResult::RESULT_SKIP;
$user_data .= idx($event, 'message');
} else if (strpos(
- idx($event, 'message'),
- 'Incomplete Test') !== false) {
+ idx($event, 'message'),
+ 'Incomplete Test') !== false) {
$status = ArcanistUnitTestResult::RESULT_SKIP;
$user_data .= idx($event, 'message');
} else {
$status = ArcanistUnitTestResult::RESULT_BROKEN;
$user_data .= idx($event, 'message');
foreach (idx($event, 'trace') as $trace) {
$user_data .= sprintf(
- "\n%s:%s",
- idx($trace, 'file'),
- idx($trace, 'line'));
+ "\n%s:%s",
+ idx($trace, 'file'),
+ idx($trace, 'line'));
}
}
}
$name = preg_replace('/ \(.*\)/s', '', idx($event, 'test'));
$result = new ArcanistUnitTestResult();
$result->setName($name);
$result->setResult($status);
$result->setDuration(idx($event, 'time'));
$result->setCoverage($coverage);
$result->setUserData($user_data);
$results[] = $result;
$last_test_finished = true;
}
if (!$last_test_finished) {
$results[] = id(new ArcanistUnitTestResult())
->setName(idx($event, 'test')) // use last event
->setUserData($this->stderr)
->setResult(ArcanistUnitTestResult::RESULT_BROKEN);
}
return $results;
}
/**
* Read the coverage from phpunit generated clover report
*
* @return array
*/
private function readCoverage() {
$test_results = Filesystem::readFile($this->coverageFile);
if (empty($test_results)) {
return array();
}
$coverage_dom = new DOMDocument();
$coverage_dom->loadXML($test_results);
$reports = array();
$files = $coverage_dom->getElementsByTagName('file');
foreach ($files as $file) {
$class_path = $file->getAttribute('name');
if (empty($this->affectedTests[$class_path])) {
continue;
}
$test_path = $this->affectedTests[$file->getAttribute('name')];
// get total line count in file
$line_count = count(file($class_path));
$coverage = '';
$start_line = 1;
$lines = $file->getElementsByTagName('line');
for ($ii = 0; $ii < $lines->length; $ii++) {
$line = $lines->item($ii);
for (; $start_line < $line->getAttribute('num'); $start_line++) {
$coverage .= 'N';
}
if ($line->getAttribute('type') != 'stmt') {
$coverage .= 'N';
} else {
if ((int) $line->getAttribute('count') == 0) {
$coverage .= 'U';
} else if ((int) $line->getAttribute('count') > 0) {
$coverage .= 'C';
}
}
$start_line++;
}
for (; $start_line <= $line_count; $start_line++) {
$coverage .= 'N';
}
$len = strlen($this->projectRoot.DIRECTORY_SEPARATOR);
$class_path = substr($class_path, $len);
$reports[$class_path] = $coverage;
}
return $reports;
}
/**
* We need this non-sense to make json generated by phpunit
* valid.
*
* @param string $json String containing JSON report
* @return array JSON decoded array
*/
private function getJsonReport($json) {
if (empty($json)) {
throw new Exception(
pht(
'JSON report file is empty, it probably means that phpunit '.
'failed to run tests. Try running %s with %s option and then run '.
'generated phpunit command yourself, you might get the answer.',
'arc unit',
'--trace'));
}
$json = preg_replace('/}{\s*"/', '},{"', $json);
$json = '['.$json.']';
return phutil_json_decode($json);
}
}
diff --git a/src/unit/renderer/ArcanistUnitConsoleRenderer.php b/src/unit/renderer/ArcanistUnitConsoleRenderer.php
index c2e95c01..16441f3c 100644
--- a/src/unit/renderer/ArcanistUnitConsoleRenderer.php
+++ b/src/unit/renderer/ArcanistUnitConsoleRenderer.php
@@ -1,110 +1,110 @@
<?php
final class ArcanistUnitConsoleRenderer extends ArcanistUnitRenderer {
public function renderUnitResult(ArcanistUnitTestResult $result) {
$result_code = $result->getResult();
$duration = '';
if ($result_code == ArcanistUnitTestResult::RESULT_PASS) {
$duration = ' '.$this->formatTestDuration($result->getDuration());
}
$test_name = $result->getName();
$test_namespace = $result->getNamespace();
if (strlen($test_namespace)) {
$test_name = $test_namespace.'::'.$test_name;
}
$return = sprintf(
" %s %s\n",
$this->getFormattedResult($result->getResult()).$duration,
$test_name);
if ($result_code != ArcanistUnitTestResult::RESULT_PASS) {
$return .= $result->getUserData()."\n";
}
return $return;
}
public function renderPostponedResult($count) {
return sprintf(
"%s %s\n",
$this->getFormattedResult(ArcanistUnitTestResult::RESULT_POSTPONED),
pht('%d test(s)', $count));
}
private function getFormattedResult($result) {
switch ($result) {
case ArcanistUnitTestResult::RESULT_PASS:
return phutil_console_format('<bg:green>** %s **</bg>', pht('PASS'));
case ArcanistUnitTestResult::RESULT_FAIL:
return phutil_console_format('<bg:red>** %s **</bg>', pht('FAIL'));
case ArcanistUnitTestResult::RESULT_SKIP:
return phutil_console_format('<bg:yellow>** %s **</bg>', pht('SKIP'));
case ArcanistUnitTestResult::RESULT_BROKEN:
return phutil_console_format('<bg:red>** %s **</bg>', pht('BROKEN'));
case ArcanistUnitTestResult::RESULT_UNSOUND:
return phutil_console_format(
'<bg:yellow>** %s **</bg>',
pht('UNSOUND'));
case ArcanistUnitTestResult::RESULT_POSTPONED:
return phutil_console_format(
'<bg:yellow>** %s **</bg>',
pht('POSTPONED'));
default:
return null;
}
}
private function formatTestDuration($seconds) {
// Very carefully define inclusive upper bounds on acceptable unit test
// durations. Times are in milliseconds and are in increasing order.
$star = "\xE2\x98\x85";
if (phutil_is_windows()) {
// Fall-back to normal asterisk for Windows consoles.
$star = '*';
}
$acceptableness = array(
50 => "<fg:green>%s</fg><fg:yellow>{$star}</fg> ",
200 => '<fg:green>%s</fg> ',
500 => '<fg:yellow>%s</fg> ',
INF => '<fg:red>%s</fg> ',
);
$milliseconds = $seconds * 1000;
$duration = $this->formatTime($seconds);
foreach ($acceptableness as $upper_bound => $formatting) {
if ($milliseconds <= $upper_bound) {
return phutil_console_format($formatting, $duration);
}
}
return phutil_console_format(end($acceptableness), $duration);
}
private function formatTime($seconds) {
if ($seconds >= 60) {
$minutes = floor($seconds / 60);
- return sprintf('%dm%02ds', $minutes, round($seconds % 60));
+ return pht('%dm%02ds', $minutes, round($seconds % 60));
}
if ($seconds >= 1) {
- return sprintf('%4.1fs', $seconds);
+ return pht('%4.1fs', $seconds);
}
$milliseconds = $seconds * 1000;
if ($milliseconds >= 1) {
- return sprintf('%3dms', round($milliseconds));
+ return pht('%3dms', round($milliseconds));
}
- return ' <1ms';
+ return pht(' <%dms', 1);
}
}
diff --git a/src/workflow/ArcanistBackoutWorkflow.php b/src/workflow/ArcanistBackoutWorkflow.php
index cdd26119..49ff007e 100644
--- a/src/workflow/ArcanistBackoutWorkflow.php
+++ b/src/workflow/ArcanistBackoutWorkflow.php
@@ -1,190 +1,190 @@
<?php
/**
* Runs git revert and assigns a high priority task to original author.
*/
final class ArcanistBackoutWorkflow extends ArcanistWorkflow {
private $console;
private $conduit;
private $revision;
public function getWorkflowName() {
return 'backout';
}
public function getCommandSynopses() {
return phutil_console_format(<<<EOTEXT
**backout**
EOTEXT
);
}
public function getCommandHelp() {
return phutil_console_format(<<<EOTEXT
Reverts/backouts on a previous commit. Supports: git, hg
Command is used like this: arc backout <commithash> | <diff revision>
Entering a differential revision will only work if there is only one commit
associated with the revision. This requires your working copy is up to date
and that the commit exists in the working copy.
EOTEXT
);
}
public function getArguments() {
return array(
'*' => 'input',
);
}
public function requiresWorkingCopy() {
return true;
}
public function requiresRepositoryAPI() {
return true;
}
public function requiresAuthentication() {
return true;
}
/**
* Given a differential revision ID, fetches the commit ID.
*/
private function getCommitIDFromRevisionID($revision_id) {
$conduit = $this->getConduit();
$revisions = $conduit->callMethodSynchronous(
'differential.query',
array(
'ids' => array($revision_id),
));
if (!$revisions) {
throw new ArcanistUsageException(
pht('The revision you provided does not exist!'));
}
$revision = $revisions[0];
$commits = $revision['commits'];
if (!$commits) {
throw new ArcanistUsageException(
pht('This revision has not been committed yet!'));
} else if (count($commits) > 1) {
throw new ArcanistUsageException(
pht('The revision you provided has multiple commits!'));
}
$commit_phid = $commits[0];
$commit = $conduit->callMethodSynchronous(
'phid.query',
array(
'phids' => array($commit_phid),
));
$commit_id = $commit[$commit_phid]['name'];
return $commit_id;
}
/**
* Fetches an array of commit info provided a Commit_id in the form of
* rE123456 (not local commit hash).
*/
private function getDiffusionCommit($commit_id) {
$result = $this->getConduit()->callMethodSynchronous(
'diffusion.querycommits',
array(
'names' => array($commit_id),
));
$phid = idx($result['identifierMap'], $commit_id);
// This commit was not found in Diffusion
if (!$phid) {
return null;
}
$commit = $result['data'][$phid];
return $commit;
}
/**
* Retrieves default template from differential and pre-fills info.
*/
private function buildCommitMessage($commit_hash) {
$conduit = $this->getConduit();
$repository_api = $this->getRepositoryAPI();
$summary = $repository_api->getBackoutMessage($commit_hash);
$fields = array(
'summary' => $summary,
'testPlan' => 'revert-hammer',
);
$template = $conduit->callMethodSynchronous(
'differential.getcommitmessage',
array(
'revision_id' => null,
'edit' => 'create',
'fields' => $fields,
));
$template = $this->newInteractiveEditor($template)
->setName('new-commit')
->editInteractively();
return $template;
}
public function getSupportedRevisionControlSystems() {
return array('git', 'hg');
}
/**
* Performs the backout/revert of a revision and creates a commit.
*/
public function run() {
$console = PhutilConsole::getConsole();
$conduit = $this->getConduit();
$repository_api = $this->getRepositoryAPI();
$is_git_svn = $repository_api instanceof ArcanistGitAPI &&
$repository_api->isGitSubversionRepo();
$is_hg_svn = $repository_api instanceof ArcanistMercurialAPI &&
$repository_api->isHgSubversionRepo();
$revision_id = null;
$console->writeOut(pht('Starting backout.')."\n");
$input = $this->getArgument('input');
if (!$input || count($input) != 1) {
throw new ArcanistUsageException(
pht('You must specify one commit to backout!'));
}
// Input looks like a Differential revision, so
// we try to find the commit attached to it
$matches = array();
if (preg_match('/^D(\d+)$/i', $input[0], $matches)) {
$revision_id = $matches[1];
$commit_id = $this->getCommitIDFromRevisionID($revision_id);
$commit = $this->getDiffusionCommit($commit_id);
$commit_hash = $commit['identifier'];
// Convert commit hash from SVN to Git/HG (for FB case)
if ($is_git_svn || $is_hg_svn) {
$commit_hash = $repository_api->
getHashFromFromSVNRevisionNumber($commit_hash);
}
} else {
// Assume input is a commit hash
$commit_hash = $input[0];
}
if (!$repository_api->hasLocalCommit($commit_hash)) {
throw new ArcanistUsageException(
- 'Invalid commit provided or does not exist in the working copy!');
+ pht('Invalid commit provided or does not exist in the working copy!'));
}
// Run 'backout'.
$subject = $repository_api->getCommitSummary($commit_hash);
$console->writeOut(
pht('Backing out commit %s %s', $commit_hash, $subject)."\n");
$repository_api->backoutCommit($commit_hash);
// Create commit message and execute the commit
$message = $this->buildCommitMessage($commit_hash);
$repository_api->doCommit($message);
$console->writeOut("%s\n",
pht('Double-check the commit and push when ready.'));
}
}
diff --git a/src/workflow/ArcanistCommitWorkflow.php b/src/workflow/ArcanistCommitWorkflow.php
index 72dae0ff..e1c5a917 100644
--- a/src/workflow/ArcanistCommitWorkflow.php
+++ b/src/workflow/ArcanistCommitWorkflow.php
@@ -1,352 +1,352 @@
<?php
/**
* Executes "svn commit" once a revision has been "Accepted".
*/
final class ArcanistCommitWorkflow extends ArcanistWorkflow {
private $revisionID;
public function getWorkflowName() {
return 'commit';
}
public function getCommandSynopses() {
return phutil_console_format(<<<EOTEXT
**commit** [--revision __revision_id__] [--show]
EOTEXT
);
}
public function getCommandHelp() {
return phutil_console_format(<<<EOTEXT
Supports: svn
Commit a revision which has been accepted by a reviewer.
EOTEXT
);
}
public function requiresWorkingCopy() {
return true;
}
public function requiresConduit() {
return true;
}
public function requiresAuthentication() {
return true;
}
public function requiresRepositoryAPI() {
return true;
}
public function getRevisionID() {
return $this->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 <revision_id>'));
} 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 <revision_id>'));
}
} 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)));
$prompt = pht(
'These %s path(s) will NOT be committed. Commit this revision anyway?',
new PhutilNumber(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)));
- $prompt = 'Commit this revision anyway?';
+ $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/ArcanistDiffWorkflow.php b/src/workflow/ArcanistDiffWorkflow.php
index 7f844de1..db1ad23d 100644
--- a/src/workflow/ArcanistDiffWorkflow.php
+++ b/src/workflow/ArcanistDiffWorkflow.php
@@ -1,2549 +1,2636 @@
<?php
/**
* Sends changes from your working copy to Differential for code review.
*
* @task lintunit Lint and Unit Tests
* @task message Commit and Update Messages
* @task diffspec Diff Specification
* @task diffprop Diff Properties
*/
final class ArcanistDiffWorkflow extends ArcanistWorkflow {
private $console;
private $hasWarnedExternals = false;
private $unresolvedLint;
private $excuses = array('lint' => null, 'unit' => null);
private $testResults;
private $diffID;
private $revisionID;
private $postponedLinters;
private $haveUncommittedChanges = false;
private $diffPropertyFutures = array();
private $commitMessageFromRevision;
public function getWorkflowName() {
return 'diff';
}
public function getCommandSynopses() {
return phutil_console_format(<<<EOTEXT
**diff** [__paths__] (svn)
**diff** [__commit__] (git, hg)
EOTEXT
);
}
public function getCommandHelp() {
return phutil_console_format(<<<EOTEXT
Supports: git, svn, hg
Generate a Differential diff or revision from local changes.
Under git and mercurial, you can specify a commit (like __HEAD^^^__
or __master__) and Differential will generate a diff against the
merge base of that commit and your current working directory parent.
Under svn, you can choose to include only some of the modified files
in the working copy in the diff by specifying their paths. If you
omit paths, all changes are included in the diff.
EOTEXT
);
}
public function requiresWorkingCopy() {
return !$this->isRawDiffSource();
}
public function requiresConduit() {
return true;
}
public function requiresAuthentication() {
return true;
}
public function requiresRepositoryAPI() {
if (!$this->isRawDiffSource()) {
return true;
}
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' =>
+ 'help' => pht(
'When updating a revision, use the specified message instead of '.
- 'prompting.',
+ 'prompting.'),
),
'message-file' => array(
'short' => 'F',
'param' => 'file',
'paramtype' => 'file',
- 'help' => 'When creating a revision, read revision information '.
- 'from this 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' => 'Read revision information from a specific 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' => 'Edit revisions via the web interface when using SVN.',
+ 'svn' => pht('Edit revisions via the web interface when using SVN.'),
),
- 'help' =>
+ 'help' => pht(
'When updating a revision under git, edit revision information '.
- 'before updating.',
+ 'before updating.'),
),
'raw' => array(
- 'help' =>
+ '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.',
+ 'to the working copy.'),
'conflicts' => array(
'less-context' => null,
- 'apply-patches' => '--raw disables lint.',
- 'never-apply-patches' => '--raw disables lint.',
- 'advice' => '--raw disables lint.',
- 'lintall' => '--raw disables lint.',
-
- 'create' => '--raw and --create both need stdin. '.
- 'Use --raw-command.',
- 'edit' => '--raw and --edit both need stdin. '.
- 'Use --raw-command.',
+ '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' =>
+ '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.',
+ 'which depend on having access to the working copy.'),
'conflicts' => array(
'less-context' => null,
- 'apply-patches' => '--raw-command disables lint.',
- 'never-apply-patches' => '--raw-command disables lint.',
- 'advice' => '--raw-command disables lint.',
- 'lintall' => '--raw-command disables lint.',
+ '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' => 'Always create a new revision.',
+ 'help' => pht('Always create a new revision.'),
'conflicts' => array(
- 'edit' => '--create can not be used with --edit.',
- 'only' => '--create can not be used with --only.',
- 'preview' => '--create can not be used with --preview.',
- 'update' => '--create can not be used with --update.',
+ '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' => 'Always update a specific revision.',
+ 'help' => pht('Always update a specific revision.'),
),
'nounit' => array(
- 'help' =>
- 'Do not run unit tests.',
+ 'help' => pht('Do not run unit tests.'),
),
'nolint' => array(
- 'help' =>
- 'Do not run lint.',
+ 'help' => pht('Do not run lint.'),
'conflicts' => array(
- 'lintall' => '--nolint suppresses lint.',
- 'advice' => '--nolint suppresses lint.',
- 'apply-patches' => '--nolint suppresses lint.',
- 'never-apply-patches' => '--nolint suppresses lint.',
+ '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' =>
+ 'help' => pht(
'Only generate a diff, without running lint, unit tests, or other '.
- 'auxiliary steps. See also --preview.',
+ 'auxiliary steps. See also %s.',
+ '--preview'),
'conflicts' => array(
'preview' => null,
- 'message' => '--only does not affect revisions.',
- 'edit' => '--only does not affect revisions.',
- 'lintall' => '--only suppresses lint.',
- 'advice' => '--only suppresses lint.',
- 'apply-patches' => '--only suppresses lint.',
- 'never-apply-patches' => '--only suppresses lint.',
+ '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' =>
+ '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 --only.',
+ 'unit tests. See also %s.',
+ '--only'),
'conflicts' => array(
'only' => null,
- 'edit' => '--preview does affect revisions.',
- 'message' => '--preview does not update any revision.',
+ 'edit' => pht('%s does affect revisions.', '--preview'),
+ 'message' => pht('%s does not update any revision.', '--preview'),
),
),
'plan-changes' => array(
- 'help' =>
- 'Create or update a revision without requesting a code review.',
+ 'help' => pht(
+ 'Create or update a revision without requesting a code review.'),
'conflicts' => array(
- 'only' => '--only does not affect revisions.',
- 'preview' => '--preview does not affect revisions.',
+ 'only' => pht('%s does not affect revisions.', '--only'),
+ 'preview' => pht('%s does not affect revisions.', '--preview'),
),
),
'encoding' => array(
'param' => 'encoding',
- 'help' =>
- 'Attempt to convert non UTF-8 hunks into specified encoding.',
+ 'help' => pht(
+ 'Attempt to convert non UTF-8 hunks into specified encoding.'),
),
'allow-untracked' => array(
- 'help' =>
- 'Skip checks for untracked files in the working copy.',
+ 'help' => pht('Skip checks for untracked files in the working copy.'),
),
'excuse' => array(
'param' => 'excuse',
- 'help' => 'Provide a prepared in advance excuse for any lints/tests'.
- ' shall they fail.',
+ 'help' => pht(
+ 'Provide a prepared in advance excuse for any lints/tests '.
+ 'shall they fail.'),
),
'less-context' => array(
- 'help' =>
+ '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.",
+ "be created that has only a few lines of context."),
),
'lintall' => array(
- 'help' =>
- 'Raise all lint warnings, not just those on lines you changed.',
+ 'help' => pht(
+ 'Raise all lint warnings, not just those on lines you changed.'),
'passthru' => array(
'lint' => true,
),
),
'advice' => array(
- 'help' =>
+ 'help' => pht(
'Require excuse for lint advice in addition to lint warnings and '.
- 'errors.',
+ 'errors.'),
),
'only-new' => array(
'param' => 'bool',
- 'help' =>
- 'Display only lint messages not present in the original code.',
+ 'help' => pht(
+ 'Display only lint messages not present in the original code.'),
'passthru' => array(
'lint' => true,
),
),
'apply-patches' => array(
- 'help' =>
+ 'help' => pht(
'Apply patches suggested by lint to the working copy without '.
- 'prompting.',
+ 'prompting.'),
'conflicts' => array(
'never-apply-patches' => true,
),
'passthru' => array(
'lint' => true,
),
),
'never-apply-patches' => array(
- 'help' => 'Never apply patches suggested by lint.',
+ 'help' => pht('Never apply patches suggested by lint.'),
'conflicts' => array(
'apply-patches' => true,
),
'passthru' => array(
'lint' => true,
),
),
'amend-all' => array(
- 'help' =>
+ 'help' => pht(
'When linting git repositories, amend HEAD with all patches '.
- 'suggested by lint without prompting.',
+ 'suggested by lint without prompting.'),
'passthru' => array(
'lint' => true,
),
),
'amend-autofixes' => array(
- 'help' =>
+ 'help' => pht(
'When linting git repositories, amend HEAD with autofix '.
- 'patches suggested by lint without prompting.',
+ 'patches suggested by lint without prompting.'),
'passthru' => array(
'lint' => true,
),
),
'add-all' => array(
'short' => 'a',
- 'help' =>
- 'Automatically add all unstaged and uncommitted files to the commit.',
+ 'help' => pht(
+ 'Automatically add all unstaged and uncommitted '.
+ 'files to the commit.'),
),
'json' => array(
- 'help' =>
- 'Emit machine-readable JSON. EXPERIMENTAL! Probably does not work!',
+ 'help' => pht(
+ 'Emit machine-readable JSON. EXPERIMENTAL! Probably does not work!'),
),
'no-amend' => array(
- 'help' => 'Never amend commits in the working copy with lint patches.',
+ 'help' => pht(
+ 'Never amend commits in the working copy with lint patches.'),
),
'uncommitted' => array(
- 'help' => 'Suppress warning about uncommitted changes.',
+ 'help' => pht('Suppress warning about uncommitted changes.'),
'supports' => array(
'hg',
),
),
'verbatim' => array(
- 'help' => '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.',
+ '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' => 'When creating a revision, add reviewers.',
+ 'help' => pht('When creating a revision, add reviewers.'),
'conflicts' => array(
'only' => true,
'preview' => true,
'update' => true,
),
),
'cc' => array(
'param' => 'usernames',
- 'help' => 'When creating a revision, add CCs.',
+ 'help' => pht('When creating a revision, add CCs.'),
'conflicts' => array(
'only' => true,
'preview' => true,
'update' => true,
),
),
'skip-binaries' => array(
- 'help' => 'Do not upload binaries (like images).',
+ 'help' => pht('Do not upload binaries (like images).'),
),
'ignore-unsound-tests' => array(
- 'help' => 'Ignore unsound test failures without prompting.',
+ 'help' => pht('Ignore unsound test failures without prompting.'),
),
'base' => array(
'param' => 'rules',
- 'help' => 'Additional rules for determining base revision.',
+ 'help' => pht('Additional rules for determining base revision.'),
'nosupport' => array(
- 'svn' => 'Subversion does not use base commits.',
+ 'svn' => pht('Subversion does not use base commits.'),
),
'supports' => array('git', 'hg'),
),
'no-diff' => array(
- 'help' => 'Only run lint and unit tests. Intended for internal use.',
+ 'help' => pht(
+ 'Only run lint and unit tests. Intended for internal use.'),
),
'cache' => array(
'param' => 'bool',
- 'help' => '0 to disable lint cache, 1 to enable (default).',
+ 'help' => pht(
+ '%d to disable lint cache, %d to enable (default).',
+ 0,
+ 1),
'passthru' => array(
'lint' => true,
),
),
'coverage' => array(
- 'help' => 'Always enable coverage information.',
+ 'help' => pht('Always enable coverage information.'),
'conflicts' => array(
'no-coverage' => null,
),
'passthru' => array(
'unit' => true,
),
),
'no-coverage' => array(
- 'help' => 'Always disable coverage information.',
+ '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 --head yet.'),
+ 'hg' => pht('Mercurial does not support %s yet.', '--head'),
),
'conflicts' => array(
- 'lintall' => '--head suppresses lint.',
- 'advice' => '--head suppresses lint.',
+ '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'];
$this->postponedLinters = $data['postponedLinters'];
$unit_result = $data['unitResult'];
$this->testResults = $data['testResults'];
if ($this->getArgument('nolint')) {
$this->excuses['lint'] = $this->getSkipExcuse(
- 'Provide explanation for skipping lint or press Enter to abort:',
+ pht('Provide explanation for skipping lint or press Enter to abort:'),
'lint-excuses');
}
if ($this->getArgument('nounit')) {
$this->excuses['unit'] = $this->getSkipExcuse(
- 'Provide explanation for skipping unit tests or press Enter to abort:',
+ pht(
+ 'Provide explanation for skipping unit tests '.
+ 'or press Enter to abort:'),
'unit-excuses');
}
$changes = $this->generateChanges();
if (!$changes) {
throw new ArcanistUsageException(
- 'There are no changes to generate a diff from!');
+ 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->updateLintDiffProperty();
$this->updateUnitDiffProperty();
$this->updateLocalDiffProperty();
$this->resolveDiffPropertyUpdates();
$output_json = $this->getArgument('json');
if ($this->shouldOnlyCreateDiff()) {
if (!$output_json) {
echo phutil_console_format(
- "Created a new Differential diff:\n".
- " **Diff URI:** __%s__\n\n",
+ "%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 "Updated an existing Differential revision:\n";
+ 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 "Updating commit message...\n";
+ echo pht('Updating commit message...')."\n";
$repository_api->amendCommit($revised_message);
} else {
- echo 'Commit message was not amended. Amending commit message is '.
- 'only supported in git and hg (version 2.2 or newer)';
+ echo pht(
+ 'Commit message was not amended. Amending commit message is '.
+ 'only supported in git and hg (version 2.2 or newer)');
}
}
- echo "Created a new Differential revision:\n";
+ echo pht('Created a new Differential revision:')."\n";
}
$uri = $result['uri'];
echo phutil_console_format(
- " **Revision URI:** __%s__\n\n",
+ " **%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 "Planned changes to the revision.\n";
+ echo pht('Planned changes to the revision.')."\n";
}
if ($this->shouldOpenCreatedObjectsInBrowser()) {
$this->openURIsInBrowser(array($uri));
}
}
- echo "Included changes:\n";
+ 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(
- "The working copy includes changes to 'svn:externals' paths. These ".
- "changes will not be included in the diff because SVN can not ".
- "commit 'svn:externals' changes alongside normal changes.".
- "\n\n".
- "Modified 'svn:externals' files:".
- "\n\n".
+ "%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 = 'Generate a diff (with just local changes) anyway?';
+ $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, "Reading diff from stdin...\n");
+ 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('Unknown raw diff source.');
+ 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[] = " Revision {$baserev}, {$path}";
+ $revlist[] = ' '.pht('Revision %s, %s', $baserev, $path);
}
$revlist = implode("\n", $revlist);
foreach ($bases as $path => $baserev) {
if ($baserev !== $rev) {
throw new ArcanistUsageException(
- "Base revisions of changed paths are mismatched. Update all ".
- "paths to the same base revision before creating a diff: ".
- "\n\n".
- $revlist);
+ 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(
- 'No changes found. (Did you specify the wrong commit range?)');
+ 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(
- 'No changes found. (Did you specify the wrong commit range?)');
+ pht('No changes found. (Did you specify the wrong commit range?)'));
}
$changes = $parser->parseDiff($diff);
} else {
- throw new Exception('Repository API is not supported.');
+ throw new Exception(pht('Repository API is not supported.'));
}
if (count($changes) > 250) {
$count = number_format(count($changes));
$link =
'http://www.phabricator.com/docs/phabricator/article/'.
'Differential_User_Guide_Large_Changes.html';
- $message =
- "This diff has a very large number of changes ({$count}). ".
- "Differential works best for changes which will receive detailed ".
- "human review, and not as well for large automated changes or ".
- "bulk checkins. See {$link} for information about reviewing big ".
- "checkins. Continue anyway?";
+ $message = pht(
+ 'This diff has a very large number of changes (%d). 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?',
+ $count,
+ $link);
if (!phutil_console_confirm($message)) {
throw new ArcanistUsageException(
- 'Aborted generation of gigantic diff.');
+ 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) {
$file_name = $change->getCurrentPath();
$change_size = number_format($size);
- $byte_warning =
- "Diff for '{$file_name}' with context is {$change_size} bytes in ".
- "length. Generally, source changes should not be this large.";
+ $byte_warning = pht(
+ "Diff for '%s' with context is %d bytes in length. ".
+ "Generally, source changes should not be this large.",
+ $file_name,
+ $change_size);
if (!$this->getArgument('less-context')) {
- $byte_warning .=
- " If this file is a huge text file, try using the ".
- "'--less-context' flag.";
+ $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} If the file is not a text file, mark it as ".
- "binary with:".
- "\n\n".
- " $ svn propset svn:mime-type application/octet-stream <filename>".
- "\n");
+ $byte_warning.' '.
+ pht(
+ "If the file is not a text file, mark it as binary with:".
+ "\n\n $ %s\n",
+ 'svn propset svn:mime-type application/octet-stream <filename>'));
} else {
- $confirm =
- "{$byte_warning} If the file is not a text file, you can ".
- "mark it 'binary'. Mark this file as 'binary' and continue?";
+ $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(
- 'Aborted generation of gigantic diff.');
+ 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(
- "Lookup of encoding in arcanist project failed\n".
+ "%s\n",
+ pht('Lookup of encoding in arcanist project failed'),
$e->getMessage());
} 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(
- "Converted a '{$name}' hunk from '{$try_encoding}' ".
- "to UTF-8.\n");
+ 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 =
- 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))).
- "\n\n".
- "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.\n\n".
- " ".pht('%d AFFECTED FILE(S)', count($utf8_problems))."\n";
+ 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))),
+ 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)));
$confirm = pht(
'Do you want to mark these %s file(s) as binary and continue?',
new PhutilNumber(count($utf8_problems)));
- echo phutil_console_format("**Invalid Content Encoding (Non-UTF8)**\n");
+ 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('Aborted workflow to fix UTF-8.');
+ 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,
'postponedLinters' => $this->postponedLinters,
'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("Linting...\n");
+ $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',
- 'Lint issued unresolved advice.',
+ pht('Lint issued unresolved advice.'),
'lint-excuses');
} else {
$this->console->writeOut(
- "<bg:green>** LINT OKAY **</bg> No lint problems.\n");
+ "<bg:green>** %s **</bg> %s\n",
+ pht('LINT OKAY'),
+ pht('No lint problems.'));
}
break;
case ArcanistLintWorkflow::RESULT_WARNINGS:
$this->getErrorExcuse(
'lint',
- 'Lint issued unresolved warnings.',
+ pht('Lint issued unresolved warnings.'),
'lint-excuses');
break;
case ArcanistLintWorkflow::RESULT_ERRORS:
$this->console->writeOut(
- "<bg:red>** LINT ERRORS **</bg> Lint raised errors!\n");
+ "<bg:red>** %s **</bg> %s\n",
+ pht('LINT ERRORS'),
+ pht('Lint raised errors!'));
$this->getErrorExcuse(
'lint',
- 'Lint issued unresolved errors!',
+ pht('Lint issued unresolved errors!'),
'lint-excuses');
break;
case ArcanistLintWorkflow::RESULT_POSTPONED:
$this->console->writeOut(
- "<bg:yellow>** LINT POSTPONED **</bg> ".
- "Lint results are postponed.\n");
+ "<bg:yellow>** %s **</bg> %s\n",
+ pht('LINT POSTPONED'),
+ pht('Lint results are postponed.'));
break;
}
$this->unresolvedLint = array();
foreach ($lint_workflow->getUnresolvedMessages() as $message) {
$this->unresolvedLint[] = $message->toDictionary();
}
$this->postponedLinters = $lint_workflow->getPostponedLinters();
return $lint_result;
} catch (ArcanistNoEngineException $ex) {
- $this->console->writeOut("No lint engine configured for this project.\n");
+ $this->console->writeOut(
+ "%s\n",
+ pht('No lint engine configured for this project.'));
} catch (ArcanistNoEffectException $ex) {
- $this->console->writeOut($ex->getMessage()."\n");
+ $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("Running unit tests...\n");
+ $this->console->writeOut("%s\n", pht('Running unit tests...'));
try {
$argv = $this->getPassthruArgumentsAsArgv('unit');
if ($repository_api->supportsCommitRanges()) {
$argv[] = '--rev';
$argv[] = $repository_api->getBaseCommit();
}
$unit_workflow = $this->buildChildWorkflow('unit', $argv);
$unit_result = $unit_workflow->run();
switch ($unit_result) {
case ArcanistUnitWorkflow::RESULT_OKAY:
$this->console->writeOut(
- "<bg:green>** UNIT OKAY **</bg> No unit test failures.\n");
+ "<bg:green>** %s **</bg> %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(
- "<bg:yellow>** UNIT UNSOUND **</bg> Unit testing raised errors, ".
- "but all failing tests are unsound.\n");
+ "<bg:yellow>** %s **</bg> %s\n",
+ pht('UNIT UNSOUND'),
+ pht(
+ 'Unit testing raised errors, but all '.
+ 'failing tests are unsound.'));
} else {
$continue = $this->console->confirm(
- 'Unit test results included failures, but all failing tests '.
- 'are known to be unsound. Ignore unsound test failures?');
+ 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(
- "<bg:red>** UNIT ERRORS **</bg> Unit testing raised errors!\n");
+ "<bg:red>** %s **</bg> %s\n",
+ pht('UNIT ERRORS'),
+ pht('Unit testing raised errors!'));
$this->getErrorExcuse(
'unit',
- 'Unit test results include failures!',
+ 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(
- "No unit test engine is configured for this project.\n");
+ "%s\n",
+ pht('No unit test engine is configured for this project.'));
} catch (ArcanistNoEffectException $ex) {
- $this->console->writeOut($ex->getMessage()."\n");
+ $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.' Ignore them?',
+ 'confirm' => $prompt.' '.pht('Ignore them?'),
));
return;
}
$history = $this->getRepositoryAPI()->getScratchFilePath($history);
- $prompt .= ' Provide explanation to continue or press Enter to abort.';
+ $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' => 'Explanation:',
+ '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(
- "There are several revisions which match the working copy:\n\n".
- $this->renderRevisionList($revisions)."\n".
- "Use '--update' to choose one, or '--create' to create a new ".
- "revision.");
+ 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(
- 'Parameter to --update must be a Differential Revision number');
+ 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 = "Message begins:\n\n {$preview}\n\n";
+ $preview = pht('Message begins:')."\n\n {$preview}\n\n";
} else {
$preview = null;
}
- echo
- "You have a saved revision message in '{$where}'.\n".
- "{$preview}".
- "You can use this message, or discard it.";
+ 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(
- 'Do you want to use this message?',
+ 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;
}
- $in_branch = '';
+
if (!$this->isRawDiffSource()) {
- $in_branch = ' in branch '.$this->getRepositoryAPI()->getBranchName();
+ $message = pht(
+ 'Included commits in branch %s:',
+ $this->getRepositoryAPI()->getBranchName());
+ } else {
+ $message = pht('Included commits:');
}
$included = array_merge(
array(
'',
- "Included commits{$in_branch}:",
+ $message,
'',
),
$included);
}
$issues = array_merge(
array(
- 'NEW DIFFERENTIAL REVISION',
- 'Describe the changes in this new revision.',
+ pht('NEW DIFFERENTIAL REVISION'),
+ pht('Describe the changes in this new revision.'),
),
$included,
array(
'',
- 'arc could not identify any existing revision in your working copy.',
- 'If you intended to update an existing revision, use:',
+ pht(
+ 'arc could not identify any existing revision in your working copy.'),
+ pht('If you intended to update an existing revision, use:'),
'',
' $ arc diff --update <revision>',
));
if ($notes) {
$issues = array_merge($issues, array(''), $notes);
}
$done = false;
$first = true;
while (!$done) {
$template = rtrim($template, "\r\n")."\n\n";
foreach ($issues as $issue) {
$template .= rtrim('# '.$issue)."\n";
}
$template .= "\n";
if ($first && $this->getArgument('verbatim') && !$template_is_default) {
$new_template = $template;
} else {
$new_template = $this->newInteractiveEditor($template)
->setName('new-commit')
->editInteractively();
}
$first = false;
if ($template_is_default && ($new_template == $template)) {
- throw new ArcanistUsageException('Template not edited.');
+ 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 = 'commit message';
+ $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 "Commit message has errors:\n\n";
- $issues = array('Resolve these errors:');
+ 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 'You must resolve these errors to continue.';
+ echo pht('You must resolve these errors to continue.');
$again = phutil_console_confirm(
- 'Do you want to edit the message?',
+ pht('Do you want to edit the message?'),
$default_no = false);
if ($again) {
// Keep going.
} else {
$saved = null;
if ($wrote) {
- $saved = "A copy was saved to {$where}.";
+ $saved = pht('A copy was saved to %s.', $where);
}
throw new ArcanistUsageException(
- "Message has unresolved errrors. {$saved}");
+ pht('Message has unresolved errors.')." {$saved}");
}
} catch (Exception $ex) {
if ($wrote) {
- echo phutil_console_wrap("(Message saved to {$where}.)\n");
+ echo phutil_console_wrap(
+ "%s\n",
+ pht(
+ '(Message saved to %s.)',
+ $where));
}
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(
- "Revision '{$revision_id}' does not exist!");
+ 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 = 'You have not specified any reviewers. Continue anyway?';
+ $confirm = pht('You have not specified any reviewers. Continue anyway?');
if (!phutil_console_confirm($confirm)) {
- throw new ArcanistUsageException('Specify reviewers and retry.');
+ 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(
- "There is no revision D{$revision_id}.");
+ 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 = "All reviewers are away until {$until}. ".
- "Continue anyway?";
+ $confirm = pht(
+ 'All reviewers are away until %s. Continue anyway?',
+ $until);
if (!phutil_console_confirm($confirm)) {
throw new ArcanistUsageException(
- 'Specify available reviewers and retry.');
+ pht('Specify available reviewers and retry.'));
}
}
break;
}
}
}
/**
* @task message
*/
private function getUpdateMessage(array $fields, $template = '') {
if ($this->getArgument('raw')) {
throw new ArcanistUsageException(
- "When using '--raw' to update a revision, specify an update message ".
- "with '--message'. (Normally, we'd launch an editor to ask you for a ".
- "message, but can not do that because stdin is the diff source.)");
+ 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 =
- rtrim($comments).
- "\n\n".
- "# Updating D{$fields['revisionID']}: {$fields['title']}\n".
- "#\n".
- "# Enter a brief description of the changes included in this update.\n".
- "# The first line is used as subject, next lines as comment.\n".
- "#\n".
- "# If you intended to create a new revision, use:\n".
- "# $ arc diff --create\n".
- "\n";
+ $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[] = 'Reviewers: '.$this->getArgument('reviewers');
+ $faux_message[] = pht('Reviewers: %s', $this->getArgument('reviewers'));
}
if ($this->getArgument('cc')) {
- $faux_message[] = 'CC: '.$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' => 'Command-Line Flags',
+ '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[] = "NOTE: commit {$frev} could not be completely parsed:";
+ $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',
ArcanistLintWorkflow::RESULT_POSTPONED => 'postponed',
);
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',
ArcanistUnitWorkflow::RESULT_POSTPONED => 'postponed',
);
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->unresolvedLint) {
$this->updateDiffProperty('arc:lint', json_encode($this->unresolvedLint));
}
$postponed = $this->postponedLinters;
if ($postponed) {
$this->updateDiffProperty('arc:lint-postponed', json_encode($postponed));
}
}
/**
* 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->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);
}
echo pht('Uploading %d files...', count($need_upload))."\n";
$hash_futures = array();
foreach ($need_upload as $key => $spec) {
$hash_futures[$key] = $this->getConduit()->callMethod(
'file.uploadhash',
array(
'name' => $spec['name'],
'hash' => sha1($spec['data']),
));
}
$futures = id(new FutureIterator($hash_futures))
->limit(8);
foreach ($futures as $key => $future) {
$type = $need_upload[$key]['type'];
$change = $need_upload[$key]['change'];
$name = $need_upload[$key]['name'];
$phid = null;
try {
$phid = $future->resolve();
} catch (Exception $e) {
// Just try uploading normally if the hash upload failed.
continue;
}
if ($phid) {
$change->setMetadata("{$type}:binary-phid", $phid);
unset($need_upload[$key]);
echo pht("Uploaded '%s' (%s).", $name, $type)."\n";
}
}
$upload_futures = array();
foreach ($need_upload as $key => $spec) {
$upload_futures[$key] = $this->getConduit()->callMethod(
'file.upload',
array(
'name' => $spec['name'],
'data_base64' => base64_encode($spec['data']),
));
}
$futures = id(new FutureIterator($upload_futures))
->limit(4);
foreach ($futures as $key => $future) {
$type = $need_upload[$key]['type'];
$change = $need_upload[$key]['change'];
$name = $need_upload[$key]['name'];
try {
$phid = $future->resolve();
$change->setMetadata("{$type}:binary-phid", $phid);
echo pht("Uploaded '%s' (%s).", $name, $type)."\n";
} catch (Exception $e) {
echo pht("Failed to upload %s binary '%s'.", $type, $name)."\n\n";
echo $e->getMessage()."\n";
if (!phutil_console_confirm(pht('Continue?'), $default_no = false)) {
throw new ArcanistUsageException(
pht(
'Aborted due to file upload failure. You can use %s '.
'to skip binary uploads.',
'--skip-binaries'));
}
}
}
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');
}
}
diff --git a/src/workflow/ArcanistDownloadWorkflow.php b/src/workflow/ArcanistDownloadWorkflow.php
index 49cb8117..56ea3a22 100644
--- a/src/workflow/ArcanistDownloadWorkflow.php
+++ b/src/workflow/ArcanistDownloadWorkflow.php
@@ -1,116 +1,116 @@
<?php
/**
* Download a file from Phabricator.
*/
final class ArcanistDownloadWorkflow extends ArcanistWorkflow {
private $id;
private $saveAs;
private $show;
public function getWorkflowName() {
return 'download';
}
public function getCommandSynopses() {
return phutil_console_format(<<<EOTEXT
**download** __file__ [--as __name__] [--show]
EOTEXT
);
}
public function getCommandHelp() {
return phutil_console_format(<<<EOTEXT
Supports: filesystems
Download a file to local disk, e.g.:
$ arc download F33 # Download file 'F33'
EOTEXT
);
}
public function getArguments() {
return array(
'show' => array(
'conflicts' => array(
'as' => pht(
'Use %s to direct the file to stdout, or %s to direct '.
'it to a named location.',
'--show',
'--as'),
),
'help' => pht('Write file to stdout instead of to disk.'),
),
'as' => array(
'param' => 'name',
'help' => pht(
'Save the file with a specific name rather than the default.'),
),
'*' => 'argv',
);
}
protected function didParseArguments() {
$argv = $this->getArgument('argv');
if (!$argv) {
throw new ArcanistUsageException(pht('Specify a file to download.'));
}
if (count($argv) > 1) {
throw new ArcanistUsageException(
pht('Specify exactly one file to download.'));
}
$file = reset($argv);
if (!preg_match('/^F?\d+$/', $file)) {
throw new ArcanistUsageException(
pht('Specify file by ID, e.g. %s.', 'F123'));
}
$this->id = (int)ltrim($file, 'F');
$this->saveAs = $this->getArgument('as');
$this->show = $this->getArgument('show');
}
public function requiresAuthentication() {
return true;
}
public function run() {
$conduit = $this->getConduit();
$this->writeStatusMessage(pht('Getting file information...')."\n");
$info = $conduit->callMethodSynchronous(
'file.info',
array(
'id' => $this->id,
));
$bytes = number_format($info['byteSize']);
- $desc = '('.$bytes.' bytes)';
+ $desc = pht('(%d bytes)', $bytes);
if ($info['name']) {
$desc = "'".$info['name']."' ".$desc;
}
$this->writeStatusMessage(pht('Downloading file %s...', $desc)."\n");
$data = $conduit->callMethodSynchronous(
'file.download',
array(
'phid' => $info['phid'],
));
$data = base64_decode($data);
if ($this->show) {
echo $data;
} else {
$path = Filesystem::writeUniqueFile(
nonempty($this->saveAs, $info['name'], 'file'),
$data);
$this->writeStatusMessage(pht("Saved file as '%s'.", $path)."\n");
}
return 0;
}
}
diff --git a/src/workflow/ArcanistHelpWorkflow.php b/src/workflow/ArcanistHelpWorkflow.php
index 2792afde..82233616 100644
--- a/src/workflow/ArcanistHelpWorkflow.php
+++ b/src/workflow/ArcanistHelpWorkflow.php
@@ -1,221 +1,221 @@
<?php
/**
* Seduces the reader with majestic prose.
*/
final class ArcanistHelpWorkflow extends ArcanistWorkflow {
public function getWorkflowName() {
return 'help';
}
public function getCommandSynopses() {
return phutil_console_format(<<<EOTEXT
**help** [__command__]
**help** --full
EOTEXT
);
}
public function getCommandHelp() {
return phutil_console_format(<<<EOTEXT
Supports: english
Shows this help. With __command__, shows help about a specific
command.
EOTEXT
);
}
public function getArguments() {
return array(
'full' => array(
- 'help' => 'Print detailed information about each command.',
+ 'help' => pht('Print detailed information about each command.'),
),
'*' => 'command',
);
}
public function run() {
$arc_config = $this->getArcanistConfiguration();
$workflows = $arc_config->buildAllWorkflows();
ksort($workflows);
$target = null;
if ($this->getArgument('command')) {
$target = head($this->getArgument('command'));
if (empty($workflows[$target])) {
throw new ArcanistUsageException(
pht(
"Unrecognized command '%s'. Try '%s'.",
$target,
'arc help'));
}
}
$cmdref = array();
foreach ($workflows as $command => $workflow) {
if ($target && $target != $command) {
continue;
}
if (!$target && !$this->getArgument('full')) {
$cmdref[] = $workflow->getCommandSynopses();
continue;
}
$optref = array();
$arguments = $workflow->getArguments();
$config_arguments = $arc_config->getCustomArgumentsForCommand($command);
// This juggling is to put the extension arguments after the normal
// arguments, and make sure the normal arguments aren't overwritten.
ksort($arguments);
ksort($config_arguments);
foreach ($config_arguments as $argument => $spec) {
if (empty($arguments[$argument])) {
$arguments[$argument] = $spec;
}
}
foreach ($arguments as $argument => $spec) {
if ($argument == '*') {
continue;
}
if (!empty($spec['hide'])) {
continue;
}
if (isset($spec['param'])) {
if (isset($spec['short'])) {
$optref[] = phutil_console_format(
' __--%s__ __%s__, __-%s__ __%s__',
$argument,
$spec['param'],
$spec['short'],
$spec['param']);
} else {
$optref[] = phutil_console_format(
' __--%s__ __%s__',
$argument,
$spec['param']);
}
} else {
if (isset($spec['short'])) {
$optref[] = phutil_console_format(
' __--%s__, __-%s__',
$argument,
$spec['short']);
} else {
$optref[] = phutil_console_format(
' __--%s__',
$argument);
}
}
if (isset($config_arguments[$argument])) {
$optref[] = ' '.
pht('(This is a custom option for this project.)');
}
if (isset($spec['supports'])) {
$optref[] = ' '.
pht('Supports: %s', implode(', ', $spec['supports']));
}
if (isset($spec['help'])) {
$docs = $spec['help'];
} else {
$docs = pht('This option is not documented.');
}
$docs = phutil_console_wrap($docs, 14);
$optref[] = "{$docs}\n";
}
if ($optref) {
$optref = implode("\n", $optref);
$optref = "\n\n".$optref;
} else {
$optref = "\n";
}
$cmdref[] =
$workflow->getCommandSynopses()."\n".
$workflow->getCommandHelp().
$optref;
}
$cmdref = implode("\n\n", $cmdref);
if ($target) {
echo "\n".$cmdref."\n";
return;
}
$self = 'arc';
echo phutil_console_format(<<<EOTEXT
**NAME**
**{$self}** - arcanist, a code review and revision management utility
**SYNOPSIS**
**{$self}** __command__ [__options__] [__args__]
This help file provides a detailed command reference.
**COMMAND REFERENCE**
{$cmdref}
EOTEXT
);
if (!$this->getArgument('full')) {
echo pht(
"Run '%s' to get commands and options descriptions.\n",
'arc help --full');
return;
}
echo phutil_console_format(<<<EOTEXT
**OPTION REFERENCE**
__--trace__
Debugging command. Shows underlying commands as they are executed,
and full stack traces when exceptions are thrown.
__--no-ansi__
Output in plain ASCII text only, without color or style.
__--ansi__
Use formatting even in environments which probably don't support it.
Example: arc --ansi unit | less -r
__--load-phutil-library=/path/to/library__
Ignore libraries listed in .arcconfig and explicitly load specified
libraries instead. Mostly useful for Arcanist development.
__--conduit-uri__ __uri__
Ignore configured Conduit URI and use an explicit one instead. Mostly
useful for Arcanist development.
__--conduit-token__ __token__
Ignore configured credentials and use an explicit API token instead.
__--conduit-version__ __version__
Ignore software version and claim to be running some other version
instead. Mostly useful for Arcanist development. May cause bad things
to happen.
__--conduit-timeout__ __timeout__
Override the default Conduit timeout. Specified in seconds.
__--config__ __key=value__
Specify a runtime configuration value. This will take precedence
over static values, and only affect the current arcanist invocation.
__--skip-arcconfig__
Skip the working copy configuration file
__--arcrc-file__ __filename__
Use provided file instead of ~/.arcrc.
EOTEXT
);
}
}
diff --git a/src/workflow/ArcanistShellCompleteWorkflow.php b/src/workflow/ArcanistShellCompleteWorkflow.php
index 90551f2a..0a933506 100644
--- a/src/workflow/ArcanistShellCompleteWorkflow.php
+++ b/src/workflow/ArcanistShellCompleteWorkflow.php
@@ -1,198 +1,198 @@
<?php
/**
* Powers shell-completion scripts.
*/
final class ArcanistShellCompleteWorkflow extends ArcanistWorkflow {
public function getWorkflowName() {
return 'shell-complete';
}
public function getCommandSynopses() {
return phutil_console_format(<<<EOTEXT
**shell-complete** __--current__ __N__ -- [__argv__]
EOTEXT
);
}
public function getCommandHelp() {
return phutil_console_format(<<<EOTEXT
Supports: bash, etc.
Implements shell completion. To use shell completion, source the
appropriate script from 'resources/shell/' in your .shellrc.
EOTEXT
);
}
public function getArguments() {
return array(
'current' => array(
'param' => 'cursor_position',
'paramtype' => 'int',
- 'help' => 'Current term in the argument list being completed.',
+ 'help' => pht('Current term in the argument list being completed.'),
),
'*' => 'argv',
);
}
protected function shouldShellComplete() {
return false;
}
public function run() {
$pos = $this->getArgument('current');
$argv = $this->getArgument('argv', array());
$argc = count($argv);
if ($pos === null) {
$pos = $argc - 1;
}
if ($pos > $argc) {
throw new ArcanistUsageException(
pht(
'Specified position is greater than the number of '.
'arguments provided.'));
}
// Determine which revision control system the working copy uses, so we
// can filter out commands and flags which aren't supported. If we can't
// figure it out, just return all flags/commands.
$vcs = null;
// We have to build our own because if we requiresWorkingCopy() we'll throw
// if we aren't in a .arcconfig directory. We probably still can't do much,
// but commands can raise more detailed errors.
$configuration_manager = $this->getConfigurationManager();
$working_copy = ArcanistWorkingCopyIdentity::newFromPath(getcwd());
if ($working_copy->getVCSType()) {
$configuration_manager->setWorkingCopyIdentity($working_copy);
$repository_api = ArcanistRepositoryAPI::newAPIFromConfigurationManager(
$configuration_manager);
$vcs = $repository_api->getSourceControlSystemName();
}
$arc_config = $this->getArcanistConfiguration();
if ($pos <= 1) {
$workflows = $arc_config->buildAllWorkflows();
$complete = array();
foreach ($workflows as $name => $workflow) {
if (!$workflow->shouldShellComplete()) {
continue;
}
if ($vcs || $workflow->requiresWorkingCopy()) {
$supported_vcs = $workflow->getSupportedRevisionControlSystems();
if (!in_array($vcs, $supported_vcs)) {
continue;
}
}
$complete[] = $name;
}
// Also permit autocompletion of "arc alias" commands.
$aliases = ArcanistAliasWorkflow::getAliases($configuration_manager);
foreach ($aliases as $key => $value) {
$complete[] = $key;
}
echo implode(' ', $complete)."\n";
return 0;
} else {
$workflow = $arc_config->buildWorkflow($argv[1]);
if (!$workflow) {
list($new_command, $new_args) = ArcanistAliasWorkflow::resolveAliases(
$argv[1],
$arc_config,
array_slice($argv, 2),
$configuration_manager);
if ($new_command) {
$workflow = $arc_config->buildWorkflow($new_command);
}
if (!$workflow) {
return 1;
} else {
$argv = array_merge(
array($argv[0]),
array($new_command),
$new_args);
}
}
$arguments = $workflow->getArguments();
$prev = idx($argv, $pos - 1, null);
if (!strncmp($prev, '--', 2)) {
$prev = substr($prev, 2);
} else {
$prev = null;
}
if ($prev !== null &&
isset($arguments[$prev]) &&
isset($arguments[$prev]['param'])) {
$type = idx($arguments[$prev], 'paramtype');
switch ($type) {
case 'file':
echo "FILE\n";
break;
case 'complete':
echo implode(' ', $workflow->getShellCompletions($argv))."\n";
break;
default:
echo "ARGUMENT\n";
break;
}
return 0;
} else {
$output = array();
foreach ($arguments as $argument => $spec) {
if ($argument == '*') {
continue;
}
if ($vcs &&
isset($spec['supports']) &&
!in_array($vcs, $spec['supports'])) {
continue;
}
$output[] = '--'.$argument;
}
$cur = idx($argv, $pos, '');
$any_match = false;
if (strlen($cur)) {
foreach ($output as $possible) {
if (!strncmp($possible, $cur, strlen($cur))) {
$any_match = true;
}
}
}
if (!$any_match && isset($arguments['*'])) {
// TODO: This is mega hacktown but something else probably breaks
// if we use a rich argument specification; fix it when we move to
// PhutilArgumentParser since everything will need to be tested then
// anyway.
if ($arguments['*'] == 'branch' && isset($repository_api)) {
$branches = $repository_api->getAllBranches();
$branches = ipull($branches, 'name');
$output = $branches;
} else {
$output = array('FILE');
}
}
echo implode(' ', $output)."\n";
return 0;
}
}
}
}
diff --git a/src/workflow/ArcanistWhichWorkflow.php b/src/workflow/ArcanistWhichWorkflow.php
index fdae9c7a..17d43447 100644
--- a/src/workflow/ArcanistWhichWorkflow.php
+++ b/src/workflow/ArcanistWhichWorkflow.php
@@ -1,287 +1,287 @@
<?php
/**
* Show which revision or revisions are in the working copy.
*/
final class ArcanistWhichWorkflow extends ArcanistWorkflow {
public function getWorkflowName() {
return 'which';
}
public function getCommandSynopses() {
return phutil_console_format(<<<EOTEXT
**which** [options] (svn)
**which** [options] [__commit__] (hg, git)
EOTEXT
);
}
public function getCommandHelp() {
return phutil_console_format(<<<EOTEXT
Supports: svn, git, hg
Shows which repository the current working copy corresponds to,
which commits 'arc diff' will select, and which revision is in
the working copy (or which revisions, if more than one matches).
EOTEXT
);
}
public function requiresConduit() {
return true;
}
public function requiresRepositoryAPI() {
return true;
}
public function requiresAuthentication() {
return true;
}
public function getArguments() {
return array(
'any-status' => array(
'help' => pht('Show committed and abandoned revisions.'),
),
'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'),
),
'show-base' => array(
'help' => pht('Print base commit only and exit.'),
'nosupport' => array(
'svn' => pht('Subversion does not use base commits.'),
),
'supports' => array('git', 'hg'),
),
'head' => array(
'param' => 'commit',
'help' => pht('Specify the end of the commit range to select.'),
'nosupport' => array(
'svn' => pht('Subversion does not support commit ranges.'),
'hg' => pht('Mercurial does not support %s yet.', '--head'),
),
'supports' => array('git'),
),
'*' => 'commit',
);
}
public function run() {
$console = PhutilConsole::getConsole();
if (!$this->getArgument('show-base')) {
$this->printRepositorySection();
$console->writeOut("\n");
}
$repository_api = $this->getRepositoryAPI();
$arg_commit = $this->getArgument('commit');
if (count($arg_commit)) {
$this->parseBaseCommitArgument($arg_commit);
}
$arg = $arg_commit ? ' '.head($arg_commit) : '';
$repository_api->setBaseCommitArgumentRules(
$this->getArgument('base', ''));
$supports_ranges = $repository_api->supportsCommitRanges();
$head_commit = $this->getArgument('head');
if ($head_commit !== null) {
$arg .= csprintf(' --head %R', $head_commit);
$repository_api->setHeadCommit($head_commit);
}
if ($supports_ranges) {
$relative = $repository_api->getBaseCommit();
if ($this->getArgument('show-base')) {
echo $relative."\n";
return 0;
}
$info = $repository_api->getLocalCommitInformation();
if ($info) {
$commits = array();
foreach ($info as $commit) {
$hash = substr($commit['commit'], 0, 16);
$summary = $commit['summary'];
$commits[] = " {$hash} {$summary}";
}
$commits = implode("\n", $commits);
} else {
$commits = ' '.pht('(No commits.)');
}
$explanation = $repository_api->getBaseCommitExplanation();
$relative_summary = $repository_api->getCommitSummary($relative);
$relative = substr($relative, 0, 16);
if ($repository_api instanceof ArcanistGitAPI) {
$head = $this->getArgument('head', 'HEAD');
$command = csprintf('git diff %R', "{$relative}..{$head}");
} else if ($repository_api instanceof ArcanistMercurialAPI) {
$command = csprintf(
'hg diff --rev %R',
hgsprintf('%s', $relative));
} else {
- throw new Exception('Unknown VCS!');
+ throw new Exception(pht('Unknown VCS!'));
}
echo phutil_console_wrap(
phutil_console_format(
"**%s**\n%s\n\n %s %s\n\n",
pht('COMMIT RANGE'),
pht(
"If you run '%s', changes between the commit:",
"arc diff{$arg}"),
$relative,
$relative_summary));
if ($head_commit === null) {
$will_be_sent = pht(
'...and the current working copy state will be sent to '.
'Differential, because %s',
$explanation);
} else {
$will_be_sent = pht(
'...and "%s" will be sent to Differential, because %s',
$head_commit,
$explanation);
}
echo phutil_console_wrap(
phutil_console_format(
"%s\n\n%s\n\n $ %s\n\n%s\n\n",
$will_be_sent,
pht(
'You can see the exact changes that will be sent by running '.
'this command:'),
$command,
pht('These commits will be included in the diff:')));
echo $commits."\n\n\n";
}
$any_status = $this->getArgument('any-status');
$query = array(
'status' => $any_status
? 'status-any'
: 'status-open',
);
$revisions = $repository_api->loadWorkingCopyDifferentialRevisions(
$this->getConduit(),
$query);
echo phutil_console_wrap(
phutil_console_format(
"**%s**\n%s\n\n",
pht('MATCHING REVISIONS'),
pht(
'These Differential revisions match the changes in this working '.
'copy:')));
if (empty($revisions)) {
- echo " (No revisions match.)\n";
+ echo " ".pht('(No revisions match.)')."\n";
echo "\n";
echo phutil_console_wrap(
phutil_console_format(
pht(
"Since there are no revisions in Differential which match this ".
"working copy, a new revision will be **created** if you run ".
"'%s'.\n\n",
"arc diff{$arg}")));
} else {
$other_author_phids = array();
foreach ($revisions as $revision) {
if ($revision['authorPHID'] != $this->getUserPHID()) {
$other_author_phids[] = $revision['authorPHID'];
}
}
$other_authors = array();
if ($other_author_phids) {
$other_authors = $this->getConduit()->callMethodSynchronous(
'user.query',
array(
'phids' => $other_author_phids,
));
$other_authors = ipull($other_authors, 'userName', 'phid');
}
foreach ($revisions as $revision) {
$title = $revision['title'];
$monogram = 'D'.$revision['id'];
if ($revision['authorPHID'] != $this->getUserPHID()) {
$author = $other_authors[$revision['authorPHID']];
echo pht(" %s (%s) %s\n", $monogram, $author, $title);
} else {
echo pht(" %s %s\n", $monogram, $title);
}
echo ' '.pht('Reason').': '.$revision['why']."\n";
echo "\n";
}
if (count($revisions) == 1) {
echo phutil_console_wrap(
phutil_console_format(
pht(
"Since exactly one revision in Differential matches this ".
"working copy, it will be **updated** if you run '%s'.",
"arc diff{$arg}")));
} else {
echo phutil_console_wrap(
pht(
"Since more than one revision in Differential matches this ".
"working copy, you will be asked which revision you want to ".
"update if you run '%s'.",
"arc diff {$arg}"));
}
echo "\n\n";
}
return 0;
}
private function printRepositorySection() {
$console = PhutilConsole::getConsole();
$console->writeOut("**%s**\n", pht('REPOSITORY'));
$callsign = $this->getRepositoryCallsign();
$console->writeOut(
"%s\n\n",
pht(
'To identify the repository associated with this working copy, '.
'arc followed this process:'));
foreach ($this->getRepositoryReasons() as $reason) {
$reason = phutil_console_wrap($reason, 4);
$console->writeOut("%s\n\n", $reason);
}
if ($callsign) {
$console->writeOut(
"%s\n",
pht('This working copy is associated with the %s repository.',
phutil_console_format('**%s**', $callsign)));
} else {
$console->writeOut(
"%s\n",
pht('This working copy is not associated with any repository.'));
}
}
}
diff --git a/src/workflow/ArcanistWorkflow.php b/src/workflow/ArcanistWorkflow.php
index 006d75c1..117bbe94 100644
--- a/src/workflow/ArcanistWorkflow.php
+++ b/src/workflow/ArcanistWorkflow.php
@@ -1,1997 +1,2008 @@
<?php
/**
* Implements a runnable command, like "arc diff" or "arc help".
*
* = Managing Conduit =
*
* Workflows have the builtin ability to open a Conduit connection to a
* Phabricator installation, so methods can be invoked over the API. Workflows
* may either not need this (e.g., "help"), or may need a Conduit but not
* authentication (e.g., calling only public APIs), or may need a Conduit and
* authentication (e.g., "arc diff").
*
* To specify that you need an //unauthenticated// conduit, override
* @{method:requiresConduit} to return ##true##. To specify that you need an
* //authenticated// conduit, override @{method:requiresAuthentication} to
* return ##true##. You can also manually invoke @{method:establishConduit}
* and/or @{method:authenticateConduit} later in a workflow to upgrade it.
* Once a conduit is open, you can access the client by calling
* @{method:getConduit}, which allows you to invoke methods. You can get
* verified information about the user identity by calling @{method:getUserPHID}
* or @{method:getUserName} after authentication occurs.
*
* = Scratch Files =
*
* Arcanist workflows can read and write 'scratch files', which are temporary
* files stored in the project that persist across commands. They can be useful
* if you want to save some state, or keep a copy of a long message the user
* entered if something goes wrong.
*
*
* @task conduit Conduit
* @task scratch Scratch Files
* @task phabrep Phabricator Repositories
*
* @stable
*/
abstract class ArcanistWorkflow extends Phobject {
const COMMIT_DISABLE = 0;
const COMMIT_ALLOW = 1;
const COMMIT_ENABLE = 2;
private $commitMode = self::COMMIT_DISABLE;
private $conduit;
private $conduitURI;
private $conduitCredentials;
private $conduitAuthenticated;
private $forcedConduitVersion;
private $conduitTimeout;
private $userPHID;
private $userName;
private $repositoryAPI;
private $configurationManager;
private $workingCopy;
private $arguments;
private $passedArguments;
private $command;
private $stashed;
private $shouldAmend;
private $projectInfo;
private $repositoryInfo;
private $repositoryReasons;
private $arcanistConfiguration;
private $parentWorkflow;
private $workingDirectory;
private $repositoryVersion;
private $changeCache = array();
public function __construct() {}
abstract public function run();
/**
* Finalizes any cleanup operations that need to occur regardless of
* whether the command succeeded or failed.
*/
public function finalize() {
$this->finalizeWorkingCopy();
}
/**
* Return the command used to invoke this workflow from the command like,
* e.g. "help" for @{class:ArcanistHelpWorkflow}.
*
* @return string The command a user types to invoke this workflow.
*/
abstract public function getWorkflowName();
/**
* Return console formatted string with all command synopses.
*
* @return string 6-space indented list of available command synopses.
*/
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;
}
if ($this->workingCopy) {
$workflow->setWorkingCopy($this->workingCopy);
}
$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 setWorkingCopy(
ArcanistWorkingCopyIdentity $working_copy) {
$this->workingCopy = $working_copy;
return $this;
}
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)));
}
$uncommitted = $api->getUncommittedChanges();
$unstaged = $api->getUnstagedChanges();
// We only want files which are purely uncommitted.
$uncommitted = array_diff($uncommitted, $unstaged);
$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)),
'.git/info/exclude');
} else if ($api instanceof ArcanistSubversionAPI) {
$hint = pht(
'(To ignore these %s change(s), add them to "%s".)',
new PhutilNumber(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)),
'.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)));
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)));
} else {
$prompt = pht(
'Do you want to create a new commit with these %s change(s)?',
new PhutilNumber(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->setProjectID(idx($diff, 'projectName'));
$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('Expected exactly one change.');
+ 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('Missing VCS support.');
+ 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(
- "Trying to get change for unchanged path '{$path}'!");
+ 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(
- "Option '--{$arg}' is not supported under {$system_name}.".
+ 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 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("Path '{$path}' does not exist!");
+ 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() {
$default = 'UTF-8';
return nonempty(idx($this->getProjectInfo(), 'encoding'), $default);
}
final protected function getProjectInfo() {
if ($this->projectInfo === null) {
$project_id = $this->getWorkingCopy()->getProjectID();
if (!$project_id) {
$this->projectInfo = array();
} else {
try {
$this->projectInfo = $this->getConduit()->callMethodSynchronous(
'arcanist.projectinfo',
array(
'name' => $project_id,
));
} catch (ConduitClientException $ex) {
if ($ex->getErrorCode() != 'ERR-BAD-ARCANIST-PROJECT') {
throw $ex;
}
// TODO: Implement a proper query method that doesn't throw on
// project not found. We just swallow this because some pathways,
// like Git with uncommitted changes in a repository with a new
// project ID, may attempt to access project information before
// the project is created. See T2153.
return array();
}
}
}
return $this->projectInfo;
}
final protected function loadProjectRepository() {
$project = $this->getProjectInfo();
if (isset($project['repository'])) {
return $project['repository'];
}
// NOTE: The rest of the code is here for backwards compatibility.
$repository_phid = idx($project, 'repositoryPHID');
if (!$repository_phid) {
return array();
}
$repositories = $this->getConduit()->callMethodSynchronous(
'repository.query',
array());
$repositories = ipull($repositories, null, 'phid');
return idx($repositories, $repository_phid, 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(
- "This feature requires a newer version of Phabricator. Please ".
- "update it using these instructions: ".
- "http://www.phabricator.com/docs/phabricator/article/".
- "Installation_Guide.html#updating-phabricator\n\n");
+ "%s\n\n",
+ pht(
+ 'This feature requires a newer version of Phabricator. Please '.
+ 'update it using these instructions: %s',
+ 'http://www.phabricator.com/docs/phabricator/article/'.
+ 'Installation_Guide.html#updating-phabricator'));
}
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(
- 'This version control system does not support commit ranges.');
+ pht('This version control system does not support commit ranges.'));
}
if (count($argv) > 1) {
throw new ArcanistUsageException(
- 'Specify exactly one base commit. The end of the commit range is '.
- 'always the working copy state.');
+ 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');
}
/**
* Get human-readable reasoning explaining how `arc` evaluated which
* Phabricator repository corresponds to this working copy. Used by
* `arc which` to explain the process to users.
*
* @return list<string> Human-readable explanation of the repository
* association process.
*
* @task phabrep
*/
final protected function getRepositoryReasons() {
$this->getRepositoryInformation();
return $this->repositoryReasons;
}
/**
* @task phabrep
*/
private function getRepositoryInformation() {
if ($this->repositoryInfo === null) {
list($info, $reasons) = $this->loadRepositoryInformation();
$this->repositoryInfo = nonempty($info, array());
$this->repositoryReasons = $reasons;
}
return $this->repositoryInfo;
}
/**
* @task phabrep
*/
private function loadRepositoryInformation() {
list($query, $reasons) = $this->getRepositoryQuery();
if (!$query) {
return array(null, $reasons);
}
try {
$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');
}
$project_info = $this->getProjectInfo();
$project_name = $this->getWorkingCopy()->getProjectID();
if ($this->getProjectInfo()) {
if (!empty($project_info['repository']['callsign'])) {
$callsign = $project_info['repository']['callsign'];
$query = array(
'callsigns' => array($callsign),
);
$reasons[] = pht(
'Configuration value "%s" is set to "%s"; this project '.
'is associated with the "%s" repository.',
'project.name',
$project_name,
$callsign);
return array($query, $reasons);
} else {
$reasons[] = pht(
'Configuration value "%s" is set to "%s", but this '.
'project is not associated with a repository.',
'project.name',
$project_name);
}
} else if (strlen($project_name)) {
$reasons[] = pht(
'Configuration value "%s" is set to "%s", but that '.
'project does not exist.',
'project.name',
$project_name);
} else {
$reasons[] = pht(
'Configuration value "%s" is empty.',
'project.name');
}
$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;
}
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.
}
}
}
}
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Sat, Nov 8, 06:33 (1 d, 11 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1034173
Default Alt Text
(485 KB)
Attached To
Mode
R118 Arcanist - fork
Attached
Detach File
Event Timeline
Log In to Comment