Page MenuHomeSealhub

No OneTemporary

diff --git a/.divinerconfig b/.divinerconfig
index 6b02d18b..17f75d88 100644
--- a/.divinerconfig
+++ b/.divinerconfig
@@ -1,23 +1,22 @@
{
"name" : "Arcanist",
"src_link" :
"https://secure.phabricator.com/diffusion/ARC/browse/master/%f$%l",
"groups" : {
"notuser" : "HEY! THIS IS NOT USER DOCUMENTATION!",
"config" : "Setup & Configuration",
"workflow" : "Workflows",
"lint" : "Lint Integration",
"linter" : "Linters",
"unit" : "Unit Test Integration",
"unitrun" : "Unit Test Runners",
"diff" : "Diff and Changeset APIs",
"differential" : "Differential Integration",
"workingcopy" : "Working Copy APIs",
"testcase" : "Test Cases"
},
"engines" : [
["DivinerArticleEngine", {}],
["DivinerXHPEngine", {}]
]
}
-
diff --git a/bin/arc.bat b/bin/arc.bat
index a1fd8f6c..5ce474bf 100644
--- a/bin/arc.bat
+++ b/bin/arc.bat
@@ -1,3 +1,2 @@
@echo off
php -f "%~dp0..\scripts\arcanist.php" -- %*
-
diff --git a/scripts/arcanist.php b/scripts/arcanist.php
index 3c4936b8..62a67e50 100755
--- a/scripts/arcanist.php
+++ b/scripts/arcanist.php
@@ -1,627 +1,626 @@
#!/usr/bin/env php
<?php
sanity_check_environment();
require_once dirname(__FILE__).'/__init_script__.php';
ini_set('memory_limit', -1);
$original_argv = $argv;
$args = new PhutilArgumentParser($argv);
$args->parseStandardArguments();
$args->parsePartial(
array(
array(
'name' => 'load-phutil-library',
'param' => 'path',
'help' => 'Load a libphutil library.',
'repeat' => true,
),
array(
'name' => 'skip-arcconfig',
),
array(
'name' => 'arcrc-file',
'param' => 'filename',
),
array(
'name' => 'conduit-uri',
'param' => 'uri',
'help' => 'Connect to Phabricator install specified by __uri__.',
),
array(
'name' => 'conduit-version',
'param' => 'version',
'help' => '(Developers) Mock client version in protocol handshake.',
),
array(
'name' => 'conduit-timeout',
'param' => 'timeout',
'help' => 'Set Conduit timeout (in seconds).',
),
));
$config_trace_mode = $args->getArg('trace');
$force_conduit = $args->getArg('conduit-uri');
$force_conduit_version = $args->getArg('conduit-version');
$conduit_timeout = $args->getArg('conduit-timeout');
$skip_arcconfig = $args->getArg('skip-arcconfig');
$custom_arcrc = $args->getArg('arcrc-file');
$load = $args->getArg('load-phutil-library');
$help = $args->getArg('help');
$argv = $args->getUnconsumedArgumentVector();
$args = array_values($argv);
$working_directory = getcwd();
$console = PhutilConsole::getConsole();
$config = null;
$workflow = null;
try {
$console->writeLog(
"libphutil loaded from '%s'.\n",
phutil_get_library_root('phutil'));
$console->writeLog(
"arcanist loaded from '%s'.\n",
phutil_get_library_root('arcanist'));
if (!$args) {
if ($help) {
$args = array('help');
} else {
throw new ArcanistUsageException("No command provided. Try 'arc help'.");
}
} else if ($help) {
array_unshift($args, 'help');
}
$configuration_manager = new ArcanistConfigurationManager();
$global_config = $configuration_manager->readUserArcConfig();
$system_config = $configuration_manager->readSystemArcConfig();
if ($skip_arcconfig) {
$working_copy = ArcanistWorkingCopyIdentity::newDummyWorkingCopy();
} else {
$working_copy =
ArcanistWorkingCopyIdentity::newFromPath($working_directory);
}
$configuration_manager->setWorkingCopyIdentity($working_copy);
reenter_if_this_is_arcanist_or_libphutil(
$console,
$working_copy,
$original_argv);
// Load additional libraries, which can provide new classes like configuration
// overrides, linters and lint engines, unit test engines, etc.
// If the user specified "--load-phutil-library" one or more times from
// the command line, we load those libraries **instead** of whatever else
// is configured. This is basically a debugging feature to let you force
// specific libraries to load regardless of the state of the world.
if ($load) {
$console->writeLog(
"Using '--load-phutil-library' flag, configuration will be ignored ".
"and configured libraries will not be loaded."."\n");
// Load the flag libraries. These must load, since the user specified them
// explicitly.
arcanist_load_libraries(
$load,
$must_load = true,
$lib_source = 'a "--load-phutil-library" flag',
$working_copy);
} else {
// Load libraries in system 'load' config. In contrast to global config, we
// fail hard here because this file is edited manually, so if 'arc' breaks
// that doesn't make it any more difficult to correct.
arcanist_load_libraries(
idx($system_config, 'load', array()),
$must_load = true,
$lib_source = 'the "load" setting in system config',
$working_copy);
// Load libraries in global 'load' config, as per "arc set-config load". We
// need to fail softly if these break because errors would prevent the user
// from running "arc set-config" to correct them.
arcanist_load_libraries(
idx($global_config, 'load', array()),
$must_load = false,
$lib_source = 'the "load" setting in global config',
$working_copy);
// Load libraries in ".arcconfig". Libraries here must load.
arcanist_load_libraries(
$working_copy->getProjectConfig('load'),
$must_load = true,
$lib_source = 'the "load" setting in ".arcconfig"',
$working_copy);
}
if ($custom_arcrc) {
$configuration_manager->setUserConfigurationFileLocation($custom_arcrc);
}
$user_config = $configuration_manager->readUserConfigurationFile();
$config_class = $working_copy->getProjectConfig('arcanist_configuration');
if ($config_class) {
$config = new $config_class();
} else {
$config = new ArcanistConfiguration();
}
$command = strtolower($args[0]);
$args = array_slice($args, 1);
$workflow = $config->selectWorkflow(
$command,
$args,
$configuration_manager,
$console);
$workflow->setConfigurationManager($configuration_manager);
$workflow->setArcanistConfiguration($config);
$workflow->setCommand($command);
$workflow->setWorkingDirectory($working_directory);
$workflow->parseArguments($args);
// Write the command into the environment so that scripts (for example, local
// Git commit hooks) can detect that they're being run via `arc` and change
// their behaviors.
putenv('ARCANIST='.$command);
if ($force_conduit_version) {
$workflow->forceConduitVersion($force_conduit_version);
}
if ($conduit_timeout) {
$workflow->setConduitTimeout($conduit_timeout);
}
$need_working_copy = $workflow->requiresWorkingCopy();
$need_conduit = $workflow->requiresConduit();
$need_auth = $workflow->requiresAuthentication();
$need_repository_api = $workflow->requiresRepositoryAPI();
$want_repository_api = $workflow->desiresRepositoryAPI();
$want_working_copy = $workflow->desiresWorkingCopy() ||
$want_repository_api;
$need_conduit = $need_conduit ||
$need_auth;
$need_working_copy = $need_working_copy ||
$need_repository_api;
if ($need_working_copy || $want_working_copy) {
if ($need_working_copy && !$working_copy->getProjectRoot()) {
throw new ArcanistUsageException(
"This command must be run in a Git, Mercurial or Subversion working ".
"copy.");
}
$configuration_manager->setWorkingCopyIdentity($working_copy);
}
if ($force_conduit) {
$conduit_uri = $force_conduit;
} else {
$project_conduit_uri =
$configuration_manager->getProjectConfig('conduit_uri');
if ($project_conduit_uri) {
$conduit_uri = $project_conduit_uri;
} else {
$conduit_uri = idx($global_config, 'default');
}
}
if ($conduit_uri) {
// Set the URI path to '/api/'. TODO: Originally, I contemplated letting
// you deploy Phabricator somewhere other than the domain root, but ended
// up never pursuing that. We should get rid of all "/api/" silliness
// in things users are expected to configure. This is already happening
// to some degree, e.g. "arc install-certificate" does it for you.
$conduit_uri = new PhutilURI($conduit_uri);
$conduit_uri->setPath('/api/');
$conduit_uri = (string)$conduit_uri;
}
$workflow->setConduitURI($conduit_uri);
// Apply global CA bundle from configs.
$ca_bundle = $configuration_manager->getConfigFromAnySource('https.cabundle');
if ($ca_bundle) {
$ca_bundle = Filesystem::resolvePath(
$ca_bundle, $working_copy->getProjectRoot());
HTTPSFuture::setGlobalCABundleFromPath($ca_bundle);
}
$blind_key = 'https.blindly-trust-domains';
$blind_trust = $configuration_manager->getConfigFromAnySource($blind_key);
if ($blind_trust) {
HTTPSFuture::setBlindlyTrustDomains($blind_trust);
}
if ($need_conduit) {
if (!$conduit_uri) {
$message = phutil_console_format(
"This command requires arc to connect to a Phabricator install, but ".
"no Phabricator installation is configured. To configure a ".
"Phabricator URI:\n\n".
" - set a default location with `arc set-config default <uri>`; or\n".
" - specify '--conduit-uri=uri' explicitly; or\n".
" - run 'arc' in a working copy with an '.arcconfig'.\n");
$message = phutil_console_wrap($message);
throw new ArcanistUsageException($message);
}
$workflow->establishConduit();
}
$hosts_config = idx($user_config, 'hosts', array());
$host_config = idx($hosts_config, $conduit_uri, array());
$user_name = idx($host_config, 'user');
$certificate = idx($host_config, 'cert');
$description = implode(' ', $original_argv);
$credentials = array(
'user' => $user_name,
'certificate' => $certificate,
'description' => $description,
);
$workflow->setConduitCredentials($credentials);
if ($need_auth) {
if (!$user_name || !$certificate) {
$arc = 'arc';
if ($force_conduit) {
$arc .= csprintf(' --conduit-uri=%s', $conduit_uri);
}
throw new ArcanistUsageException(
phutil_console_format(
"YOU NEED TO __INSTALL A CERTIFICATE__ TO LOGIN TO PHABRICATOR\n\n".
"You are trying to connect to '{$conduit_uri}' but do not have ".
"a certificate installed for this host. Run:\n\n".
" $ **{$arc} install-certificate**\n\n".
"...to install one."));
}
$workflow->authenticateConduit();
}
if ($need_repository_api || ($want_repository_api && $working_copy)) {
$repository_api = ArcanistRepositoryAPI::newAPIFromConfigurationManager(
$configuration_manager);
$workflow->setRepositoryAPI($repository_api);
}
$listeners = $configuration_manager->getConfigFromAnySource(
'events.listeners');
if ($listeners) {
foreach ($listeners as $listener) {
$console->writeLog(
"Registering event listener '%s'.\n",
$listener);
try {
id(new $listener())->register();
} catch (PhutilMissingSymbolException $ex) {
// Continue anwyay, since you may otherwise be unable to run commands
// like `arc set-config events.listeners` in order to repair the damage
// you've caused. We're writing out the entire exception here because
// it might not have been triggered by the listener itself (for example,
// the listener might use a bad class in its register() method).
$console->writeErr(
"ERROR: Failed to load event listener '%s': %s\n",
$listener,
$ex->getMessage());
}
}
}
$config->willRunWorkflow($command, $workflow);
$workflow->willRunWorkflow();
try {
$err = $workflow->run();
$config->didRunWorkflow($command, $workflow, $err);
} catch (Exception $e) {
$workflow->finalize();
throw $e;
}
$workflow->finalize();
exit((int)$err);
} catch (ArcanistNoEffectException $ex) {
echo $ex->getMessage()."\n";
} catch (Exception $ex) {
$is_usage = ($ex instanceof ArcanistUsageException);
if ($is_usage) {
echo phutil_console_format(
"**Usage Exception:** %s\n",
$ex->getMessage());
}
if ($config) {
$config->didAbortWorkflow($command, $workflow, $ex);
}
if ($config_trace_mode) {
echo "\n";
throw $ex;
}
if (!$is_usage) {
echo phutil_console_format(
"**Exception**\n%s\n%s\n",
$ex->getMessage(),
"(Run with --trace for a full exception trace.)");
}
exit(1);
}
/**
* Perform some sanity checks against the possible diversity of PHP builds in
* the wild, like very old versions and builds that were compiled with flags
* that exclude core functionality.
*/
function sanity_check_environment() {
// NOTE: We don't have phutil_is_windows() yet here.
$is_windows = (DIRECTORY_SEPARATOR != '/');
// We use stream_socket_pair() which is not available on Windows earlier.
$min_version = ($is_windows ? '5.3.0' : '5.2.3');
$cur_version = phpversion();
if (version_compare($cur_version, $min_version, '<')) {
die_with_bad_php(
"You are running PHP version '{$cur_version}', which is older than ".
"the minimum version, '{$min_version}'. Update to at least ".
"'{$min_version}'.");
}
if ($is_windows) {
$need_functions = array(
'curl_init' => array('builtin-dll', 'php_curl.dll'),
);
} else {
$need_functions = array(
'curl_init' => array(
'text',
"You need to install the cURL PHP extension, maybe with ".
"'apt-get install php5-curl' or 'yum install php53-curl' or ".
"something similar."),
'json_decode' => array('flag', '--without-json'),
);
}
$problems = array();
$config = null;
$show_config = false;
foreach ($need_functions as $fname => $resolution) {
if (function_exists($fname)) {
continue;
}
static $info;
if ($info === null) {
ob_start();
phpinfo(INFO_GENERAL);
$info = ob_get_clean();
$matches = null;
if (preg_match('/^Configure Command =>\s*(.*?)$/m', $info, $matches)) {
$config = $matches[1];
}
}
$generic = true;
list($what, $which) = $resolution;
if ($what == 'flag' && strpos($config, $which) !== false) {
$show_config = true;
$generic = false;
$problems[] =
"This build of PHP was compiled with the configure flag '{$which}', ".
"which means it does not have the function '{$fname}()'. This ".
"function is required for arc to run. Rebuild PHP without this flag. ".
"You may also be able to build or install the relevant extension ".
"separately.";
}
if ($what == 'builtin-dll') {
$generic = false;
$problems[] =
"Your install of PHP does not have the '{$which}' extension enabled. ".
"Edit your php.ini file and uncomment the line which reads ".
"'extension={$which}'.";
}
if ($what == 'text') {
$generic = false;
$problems[] = $which;
}
if ($generic) {
$problems[] =
"This build of PHP is missing the required function '{$fname}()'. ".
"Rebuild PHP or install the extension which provides '{$fname}()'.";
}
}
if ($problems) {
if ($show_config) {
$problems[] = "PHP was built with this configure command:\n\n{$config}";
}
die_with_bad_php(implode("\n\n", $problems));
}
}
function die_with_bad_php($message) {
echo "\nPHP CONFIGURATION ERRORS\n\n";
echo $message;
echo "\n\n";
exit(1);
}
function arcanist_load_libraries(
$load,
$must_load,
$lib_source,
ArcanistWorkingCopyIdentity $working_copy) {
if (!$load) {
return;
}
if (!is_array($load)) {
$error = "Libraries specified by {$lib_source} are invalid; expected ".
"a list. Check your configuration.";
$console = PhutilConsole::getConsole();
$console->writeErr("WARNING: %s\n", $error);
return;
}
foreach ($load as $location) {
// Try to resolve the library location. We look in several places, in
// order:
//
// 1. Inside the working copy. This is for phutil libraries within the
// project. For instance "library/src" will resolve to
// "./library/src" if it exists.
// 2. In the same directory as the working copy. This allows you to
// check out a library alongside a working copy and reference it.
// If we haven't resolved yet, "library/src" will try to resolve to
// "../library/src" if it exists.
// 3. Using normal libphutil resolution rules. Generally, this means
// that it checks for libraries next to libphutil, then libraries
// in the PHP include_path.
//
// Note that absolute paths will just resolve absolutely through rule (1).
$resolved = false;
// Check inside the working copy. This also checks absolute paths, since
// they'll resolve absolute and just ignore the project root.
$resolved_location = Filesystem::resolvePath(
$location,
$working_copy->getProjectRoot());
if (Filesystem::pathExists($resolved_location)) {
$location = $resolved_location;
$resolved = true;
}
// If we didn't find anything, check alongside the working copy.
if (!$resolved) {
$resolved_location = Filesystem::resolvePath(
$location,
dirname($working_copy->getProjectRoot()));
if (Filesystem::pathExists($resolved_location)) {
$location = $resolved_location;
$resolved = true;
}
}
$console = PhutilConsole::getConsole();
$console->writeLog(
"Loading phutil library from '%s'...\n",
$location);
$error = null;
try {
phutil_load_library($location);
} catch (PhutilBootloaderException $ex) {
$error = "Failed to load phutil library at location '{$location}'. ".
"This library is specified by {$lib_source}. Check that the ".
"setting is correct and the library is located in the right ".
"place.";
if ($must_load) {
throw new ArcanistUsageException($error);
} else {
fwrite(STDERR, phutil_console_wrap('WARNING: '.$error."\n\n"));
}
} catch (PhutilLibraryConflictException $ex) {
if ($ex->getLibrary() != 'arcanist') {
throw $ex;
}
$arc_dir = dirname(dirname(__FILE__));
$error =
"You are trying to run one copy of Arcanist on another copy of ".
"Arcanist. This operation is not supported. To execute Arcanist ".
"operations against this working copy, run './bin/arc' (from the ".
"current working copy) not some other copy of 'arc' (you ran one ".
"from '{$arc_dir}').";
throw new ArcanistUsageException($error);
}
}
}
/**
* NOTE: SPOOKY BLACK MAGIC
*
* When arc is run in a copy of arcanist other than itself, or a copy of
* libphutil other than the one we loaded, reenter the script and force it
* to use the current working directory instead of the default.
*
* In the case of execution inside arcanist/, we force execution of the local
* arc binary.
*
* In the case of execution inside libphutil/, we force the local copy to load
* instead of the one selected by default rules.
*
* @param PhutilConsole Console.
* @param ArcanistWorkingCopyIdentity The current working copy.
* @param array Original arc arguments.
* @return void
*/
function reenter_if_this_is_arcanist_or_libphutil(
PhutilConsole $console,
ArcanistWorkingCopyIdentity $working_copy,
array $original_argv) {
$project_id = $working_copy->getProjectID();
if ($project_id != 'arcanist' && $project_id != 'libphutil') {
// We're not in a copy of arcanist or libphutil.
return;
}
$library_names = array(
'arcanist' => 'arcanist',
'libphutil' => 'phutil',
);
$library_root = phutil_get_library_root($library_names[$project_id]);
$project_root = $working_copy->getProjectRoot();
if (Filesystem::isDescendant($library_root, $project_root)) {
// We're in a copy of arcanist or libphutil, but already loaded the correct
// copy. Continue execution normally.
return;
}
if ($project_id == 'libphutil') {
$console->writeLog(
"This is libphutil! Forcing this copy to load...\n");
$original_argv[0] = dirname(phutil_get_library_root('arcanist')).'/bin/arc';
$libphutil_path = $project_root;
} else {
$console->writeLog(
"This is arcanist! Forcing this copy to run...\n");
$original_argv[0] = $project_root.'/bin/arc';
$libphutil_path = dirname(phutil_get_library_root('phutil'));
}
if (phutil_is_windows()) {
$err = phutil_passthru(
'set ARC_PHUTIL_PATH=%s & %Ls',
$libphutil_path,
$original_argv);
} else {
$err = phutil_passthru(
'ARC_PHUTIL_PATH=%s %Ls',
$libphutil_path,
$original_argv);
}
exit($err);
}
-
diff --git a/src/lint/linter/ArcanistLicenseLinter.php b/src/lint/linter/ArcanistLicenseLinter.php
index 1f071ddf..815e178a 100644
--- a/src/lint/linter/ArcanistLicenseLinter.php
+++ b/src/lint/linter/ArcanistLicenseLinter.php
@@ -1,61 +1,59 @@
<?php
/**
* @deprecated
*/
abstract class ArcanistLicenseLinter extends ArcanistLinter {
const LINT_NO_LICENSE_HEADER = 1;
public function willLintPaths(array $paths) {
return;
}
public function getLintSeverityMap() {
return array();
}
public function getLintNameMap() {
return array(
self::LINT_NO_LICENSE_HEADER => 'No License Header',
);
}
abstract protected function getLicenseText($copyright_holder);
abstract protected function getLicensePatterns();
public function lintPath($path) {
$copyright_holder = $this->getConfig('copyright_holder');
if ($copyright_holder === null) {
$config = $this->getEngine()->getConfigurationManager();
$copyright_holder = $config->getConfigFromAnySource('copyright_holder');
}
if (!$copyright_holder) {
return;
}
$patterns = $this->getLicensePatterns();
$license = $this->getLicenseText($copyright_holder);
$data = $this->getData($path);
$matches = 0;
foreach ($patterns as $pattern) {
if (preg_match($pattern, $data, $matches)) {
$expect = rtrim(implode('', array_slice($matches, 1)))."\n".$license;
if (trim($matches[0]) != trim($expect)) {
$this->raiseLintAtOffset(
0,
self::LINT_NO_LICENSE_HEADER,
'This file has a missing or out of date license header.',
$matches[0],
ltrim($expect));
}
break;
}
}
}
}
-
-
diff --git a/src/lint/linter/ArcanistTextLinter.php b/src/lint/linter/ArcanistTextLinter.php
index 4fdbef48..9042207e 100644
--- a/src/lint/linter/ArcanistTextLinter.php
+++ b/src/lint/linter/ArcanistTextLinter.php
@@ -1,214 +1,270 @@
<?php
/**
* Enforces basic text file rules.
*
* @group linter
*/
final class ArcanistTextLinter extends ArcanistLinter {
const LINT_DOS_NEWLINE = 1;
const LINT_TAB_LITERAL = 2;
const LINT_LINE_WRAP = 3;
const LINT_EOF_NEWLINE = 4;
const LINT_BAD_CHARSET = 5;
const LINT_TRAILING_WHITESPACE = 6;
const LINT_NO_COMMIT = 7;
+ const LINT_BOF_WHITESPACE = 8;
+ const LINT_EOF_WHITESPACE = 9;
private $maxLineLength = 80;
public function getLinterPriority() {
return 0.5;
}
public function setMaxLineLength($new_length) {
$this->maxLineLength = $new_length;
return $this;
}
public function getLinterName() {
return 'TXT';
}
public function getLinterConfigurationName() {
return 'text';
}
public function getLintSeverityMap() {
return array(
self::LINT_LINE_WRAP => ArcanistLintSeverity::SEVERITY_WARNING,
self::LINT_TRAILING_WHITESPACE => ArcanistLintSeverity::SEVERITY_AUTOFIX,
+ self::LINT_BOF_WHITESPACE => ArcanistLintSeverity::SEVERITY_AUTOFIX,
+ self::LINT_EOF_WHITESPACE => ArcanistLintSeverity::SEVERITY_AUTOFIX,
);
}
public function getLintNameMap() {
return array(
self::LINT_DOS_NEWLINE => pht('DOS Newlines'),
self::LINT_TAB_LITERAL => pht('Tab Literal'),
self::LINT_LINE_WRAP => pht('Line Too Long'),
self::LINT_EOF_NEWLINE => pht('File Does Not End in Newline'),
self::LINT_BAD_CHARSET => pht('Bad Charset'),
self::LINT_TRAILING_WHITESPACE => pht('Trailing Whitespace'),
self::LINT_NO_COMMIT => pht('Explicit %s', '@no'.'commit'),
+ self::LINT_BOF_WHITESPACE => pht('Leading Whitespace at BOF'),
+ self::LINT_EOF_WHITESPACE => pht('Trailing Whitespace at EOF'),
);
}
public function lintPath($path) {
if (!strlen($this->getData($path))) {
// If the file is empty, don't bother; particularly, don't require
// the user to add a newline.
return;
}
$this->lintNewlines($path);
$this->lintTabs($path);
if ($this->didStopAllLinters()) {
return;
}
$this->lintCharset($path);
if ($this->didStopAllLinters()) {
return;
}
$this->lintLineLength($path);
$this->lintEOFNewline($path);
$this->lintTrailingWhitespace($path);
+ $this->lintBOFWhitespace($path);
+ $this->lintEOFWhitespace($path);
+
if ($this->getEngine()->getCommitHookMode()) {
$this->lintNoCommit($path);
}
}
protected function lintNewlines($path) {
$pos = strpos($this->getData($path), "\r");
if ($pos !== false) {
$this->raiseLintAtOffset(
$pos,
self::LINT_DOS_NEWLINE,
'You must use ONLY Unix linebreaks ("\n") in source code.',
"\r");
if ($this->isMessageEnabled(self::LINT_DOS_NEWLINE)) {
$this->stopAllLinters();
}
}
}
protected function lintTabs($path) {
$pos = strpos($this->getData($path), "\t");
if ($pos !== false) {
$this->raiseLintAtOffset(
$pos,
self::LINT_TAB_LITERAL,
'Configure your editor to use spaces for indentation.',
"\t");
}
}
protected function lintLineLength($path) {
$lines = explode("\n", $this->getData($path));
$width = $this->maxLineLength;
foreach ($lines as $line_idx => $line) {
if (strlen($line) > $width) {
$this->raiseLintAtLine(
$line_idx + 1,
1,
self::LINT_LINE_WRAP,
'This line is '.number_format(strlen($line)).' characters long, '.
'but the convention is '.$width.' characters.',
$line);
}
}
}
protected function lintEOFNewline($path) {
$data = $this->getData($path);
if (!strlen($data) || $data[strlen($data) - 1] != "\n") {
$this->raiseLintAtOffset(
strlen($data),
self::LINT_EOF_NEWLINE,
"Files must end in a newline.",
'',
"\n");
}
}
protected function lintCharset($path) {
$data = $this->getData($path);
$matches = null;
$bad = '[^\x09\x0A\x20-\x7E]';
$preg = preg_match_all(
"/{$bad}(.*{$bad})?/",
$data,
$matches,
PREG_OFFSET_CAPTURE);
if (!$preg) {
return;
}
foreach ($matches[0] as $match) {
list($string, $offset) = $match;
$this->raiseLintAtOffset(
$offset,
self::LINT_BAD_CHARSET,
'Source code should contain only ASCII bytes with ordinal decimal '.
'values between 32 and 126 inclusive, plus linefeed. Do not use UTF-8 '.
'or other multibyte charsets.',
$string);
}
if ($this->isMessageEnabled(self::LINT_BAD_CHARSET)) {
$this->stopAllLinters();
}
}
protected function lintTrailingWhitespace($path) {
$data = $this->getData($path);
$matches = null;
$preg = preg_match_all(
'/ +$/m',
$data,
$matches,
PREG_OFFSET_CAPTURE);
if (!$preg) {
return;
}
foreach ($matches[0] as $match) {
list($string, $offset) = $match;
$this->raiseLintAtOffset(
$offset,
self::LINT_TRAILING_WHITESPACE,
'This line contains trailing whitespace. Consider setting up your '.
'editor to automatically remove trailing whitespace, you will save '.
'time.',
$string,
'');
}
}
+ protected function lintBOFWhitespace($path) {
+ $data = $this->getData($path);
+
+ $matches = null;
+ $preg = preg_match(
+ '/^\s*\n/',
+ $data,
+ $matches,
+ PREG_OFFSET_CAPTURE);
+
+ if (!$preg) {
+ return;
+ }
+
+ list($string, $offset) = $matches[0];
+ $this->raiseLintAtOffset(
+ $offset,
+ self::LINT_BOF_WHITESPACE,
+ 'This file contains leading whitespace at the beginning of the file. ' .
+ 'This is unnecessary and should be avoided when possible.',
+ $string,
+ '');
+ }
+
+ protected function lintEOFWhitespace($path) {
+ $data = $this->getData($path);
+
+ $matches = null;
+ $preg = preg_match(
+ '/(?<=\n)\s+$/',
+ $data,
+ $matches,
+ PREG_OFFSET_CAPTURE);
+
+ if (!$preg) {
+ return;
+ }
+
+ list($string, $offset) = $matches[0];
+ $this->raiseLintAtOffset(
+ $offset,
+ self::LINT_EOF_WHITESPACE,
+ 'This file contains trailing whitespace at the end of the file. This ' .
+ 'is unnecessary and should be avoided when possible.',
+ $string,
+ '');
+ }
+
private function lintNoCommit($path) {
$data = $this->getData($path);
$deadly = '@no'.'commit';
$offset = strpos($data, $deadly);
if ($offset !== false) {
$this->raiseLintAtOffset(
$offset,
self::LINT_NO_COMMIT,
'This file is explicitly marked as "'.$deadly.'", which blocks '.
'commits.',
$deadly);
}
}
-
}
diff --git a/src/lint/linter/__tests__/text/bof-whitespace-1.lint-test b/src/lint/linter/__tests__/text/bof-whitespace-1.lint-test
new file mode 100644
index 00000000..995aad6b
--- /dev/null
+++ b/src/lint/linter/__tests__/text/bof-whitespace-1.lint-test
@@ -0,0 +1,9 @@
+
+
+
+
+The quick brown fox jumps over the lazy dog.
+~~~~~~~~~~
+autofix:1:1
+~~~~~~~~~~
+The quick brown fox jumps over the lazy dog.
diff --git a/src/lint/linter/__tests__/text/bof-whitespace-2.lint-test b/src/lint/linter/__tests__/text/bof-whitespace-2.lint-test
new file mode 100644
index 00000000..87ae7e67
--- /dev/null
+++ b/src/lint/linter/__tests__/text/bof-whitespace-2.lint-test
@@ -0,0 +1,2 @@
+ The quick brown fox jumps over the lazy dog.
+~~~~~~~~~~
diff --git a/src/lint/linter/__tests__/text/eof-whitespace.lint-test b/src/lint/linter/__tests__/text/eof-whitespace.lint-test
new file mode 100644
index 00000000..b3b778c7
--- /dev/null
+++ b/src/lint/linter/__tests__/text/eof-whitespace.lint-test
@@ -0,0 +1,9 @@
+The quick brown fox jumps over the lazy dog.
+
+
+
+
+~~~~~~~~~~
+autofix:2:1
+~~~~~~~~~~
+The quick brown fox jumps over the lazy dog.
diff --git a/src/unit/engine/CSharpToolsTestEngine.php b/src/unit/engine/CSharpToolsTestEngine.php
index 9b85257a..d2557894 100644
--- a/src/unit/engine/CSharpToolsTestEngine.php
+++ b/src/unit/engine/CSharpToolsTestEngine.php
@@ -1,288 +1,286 @@
<?php
/**
* Uses cscover (http://github.com/hach-que/cstools) to report code coverage.
*
* This engine inherits from `XUnitTestEngine`, where xUnit is used to actually
* run the unit tests and this class provides a thin layer on top to collect
* code coverage data with a third-party tool.
*
* @group unitrun
*/
final class CSharpToolsTestEngine extends XUnitTestEngine {
private $cscoverHintPath;
private $coverEngine;
private $cachedResults;
private $matchRegex;
private $excludedFiles;
/**
* Overridden version of `loadEnvironment` to support a different set
* of configuration values and to pull in the cstools config for
* code coverage.
*/
protected function loadEnvironment() {
$config = $this->getConfigurationManager();
$this->cscoverHintPath =
$config->getConfigFromAnySource('unit.csharp.cscover.binary');
$this->matchRegex =
$config->getConfigFromAnySource('unit.csharp.coverage.match');
$this->excludedFiles =
$config->getConfigFromAnySource('unit.csharp.coverage.excluded');
parent::loadEnvironment();
if ($this->getEnableCoverage() === false) {
return;
}
// Determine coverage path.
if ($this->cscoverHintPath === null) {
throw new Exception(
"Unable to locate cscover. Configure it with ".
"the `unit.csharp.coverage.binary' option in .arcconfig");
}
$cscover = $this->projectRoot.DIRECTORY_SEPARATOR.$this->cscoverHintPath;
if (file_exists($cscover)) {
$this->coverEngine = Filesystem::resolvePath($cscover);
} else {
throw new Exception(
"Unable to locate cscover coverage runner ".
"(have you built yet?)");
}
}
/**
* Returns whether the specified assembly should be instrumented for
* code coverage reporting. Checks the excluded file list and the
* matching regex if they are configured.
*
* @return boolean Whether the assembly should be instrumented.
*/
private function assemblyShouldBeInstrumented($file) {
if ($this->excludedFiles !== null) {
if (array_key_exists((string)$file, $this->excludedFiles)) {
return false;
}
}
if ($this->matchRegex !== null) {
if (preg_match($this->matchRegex, $file) === 1) {
return true;
} else {
return false;
}
}
return true;
}
/**
* Overridden version of `buildTestFuture` so that the unit test can be run
* via `cscover`, which instruments assemblies and reports on code coverage.
*
* @param string Name of the test assembly.
* @return array The future, output filename and coverage filename
* stored in an array.
*/
protected function buildTestFuture($test_assembly) {
if ($this->getEnableCoverage() === false) {
return parent::buildTestFuture($test_assembly);
}
// FIXME: Can't use TempFile here as xUnit doesn't like
// UNIX-style full paths. It sees the leading / as the
// start of an option flag, even when quoted.
$xunit_temp = Filesystem::readRandomCharacters(10).".results.xml";
if (file_exists($xunit_temp)) {
unlink($xunit_temp);
}
$cover_temp = new TempFile();
$cover_temp->setPreserveFile(true);
$xunit_cmd = $this->runtimeEngine;
$xunit_args = null;
if ($xunit_cmd === "") {
$xunit_cmd = $this->testEngine;
$xunit_args = csprintf(
"%s /xml %s",
$test_assembly,
$xunit_temp);
} else {
$xunit_args = csprintf(
"%s %s /xml %s",
$this->testEngine,
$test_assembly,
$xunit_temp);
}
$assembly_dir = dirname($test_assembly);
$assemblies_to_instrument = array();
foreach (Filesystem::listDirectory($assembly_dir) as $file) {
if (substr($file, -4) == ".dll" || substr($file, -4) == ".exe") {
if ($this->assemblyShouldBeInstrumented($file)) {
$assemblies_to_instrument[] = $assembly_dir.DIRECTORY_SEPARATOR.$file;
}
}
}
if (count($assemblies_to_instrument) === 0) {
return parent::buildTestFuture($test_assembly);
}
$future = new ExecFuture(
"%C -o %s -c %s -a %s -w %s %Ls",
trim($this->runtimeEngine." ".$this->coverEngine),
$cover_temp,
$xunit_cmd,
$xunit_args,
$assembly_dir,
$assemblies_to_instrument);
$future->setCWD(Filesystem::resolvePath($this->projectRoot));
return array(
$future,
$assembly_dir.DIRECTORY_SEPARATOR.$xunit_temp,
$cover_temp);
}
/**
* Returns coverage results for the unit tests.
*
* @param string The name of the coverage file if one was provided by
* `buildTestFuture`.
* @return array Code coverage results, or null.
*/
protected function parseCoverageResult($cover_file) {
if ($this->getEnableCoverage() === false) {
return parent::parseCoverageResult($cover_file);
}
return $this->readCoverage($cover_file);
}
/**
* Retrieves the cached results for a coverage result file. The coverage
* result file is XML and can be large depending on what has been instrumented
* so we cache it in case it's requested again.
*
* @param string The name of the coverage file.
* @return array Code coverage results, or null if not cached.
*/
private function getCachedResultsIfPossible($cover_file) {
if ($this->cachedResults == null) {
$this->cachedResults = array();
}
if (array_key_exists((string)$cover_file, $this->cachedResults)) {
return $this->cachedResults[(string)$cover_file];
}
return null;
}
/**
* Stores the code coverage results in the cache.
*
* @param string The name of the coverage file.
* @param array The results to cache.
*/
private function addCachedResults($cover_file, array $results) {
if ($this->cachedResults == null) {
$this->cachedResults = array();
}
$this->cachedResults[(string)$cover_file] = $results;
}
/**
* Processes a set of XML tags as code coverage results. We parse
* the `instrumented` and `executed` tags with this method so that
* we can access the data multiple times without a performance hit.
*
* @param array The array of XML tags to parse.
* @return array A PHP array containing the data.
*/
private function processTags($tags) {
$results = array();
foreach ($tags as $tag) {
$results[] = array(
"file" => $tag->getAttribute("file"),
"start" => $tag->getAttribute("start"),
"end" => $tag->getAttribute("end"));
}
return $results;
}
/**
* Reads the code coverage results from the cscover results file.
*
* @param string The path to the code coverage file.
* @return array The code coverage results.
*/
public function readCoverage($cover_file) {
$cached = $this->getCachedResultsIfPossible($cover_file);
if ($cached !== null) {
return $cached;
}
$coverage_dom = new DOMDocument();
$coverage_dom->loadXML(Filesystem::readFile($cover_file));
$modified = $this->getPaths();
$files = array();
$reports = array();
$instrumented = array();
$executed = array();
$instrumented = $this->processTags(
$coverage_dom->getElementsByTagName("instrumented"));
$executed = $this->processTags(
$coverage_dom->getElementsByTagName("executed"));
foreach ($instrumented as $instrument) {
$absolute_file = $instrument["file"];
$relative_file = substr($absolute_file, strlen($this->projectRoot) + 1);
if (!in_array($relative_file, $files)) {
$files[] = $relative_file;
}
}
foreach ($files as $file) {
$absolute_file = Filesystem::resolvePath(
$this->projectRoot.DIRECTORY_SEPARATOR.$file);
// get total line count in file
$line_count = count(file($absolute_file));
$coverage = array();
for ($i = 0; $i < $line_count; $i++) {
$coverage[$i] = 'N';
}
foreach ($instrumented as $instrument) {
if ($instrument["file"] !== $absolute_file) {
continue;
}
for (
$i = $instrument["start"];
$i <= $instrument["end"];
$i++) {
$coverage[$i - 1] = 'U';
}
}
foreach ($executed as $execute) {
if ($execute["file"] !== $absolute_file) {
continue;
}
for (
$i = $execute["start"];
$i <= $execute["end"];
$i++) {
$coverage[$i - 1] = 'C';
}
}
$reports[$file] = implode($coverage);
}
$this->addCachedResults($cover_file, $reports);
return $reports;
}
}
-
-
diff --git a/src/workflow/ArcanistBackoutWorkflow.php b/src/workflow/ArcanistBackoutWorkflow.php
index ac7c73d2..b7e0486d 100644
--- a/src/workflow/ArcanistBackoutWorkflow.php
+++ b/src/workflow/ArcanistBackoutWorkflow.php
@@ -1,184 +1,183 @@
<?php
/**
* Runs git revert and assigns hi pri task to original author
* @group workflow
*/
final class ArcanistBackoutWorkflow extends ArcanistBaseWorkflow {
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
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(
'The revision you provided does not exist!');
}
$revision = $revisions[0];
$commits = $revision["commits"];
if (!$commits) {
throw new ArcanistUsageException(
'This revision has not been committed yet!');
}
elseif (count($commits) > 1) {
throw new ArcanistUsageException(
'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.getcommits',
array(
'commits' => array($commit_id),
));
$commit = $result[$commit_id];
// This commit was not found in Diffusion
if (array_key_exists("error", $commit)) {
return null;
}
return $commit;
}
// Retrieves default template from differential and prefills 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;
}
// Performs the backout/revert of a revision and creates a commit
public function run() {
$console = PhutilConsole::getConsole();
$conduit = $this->getConduit();
$repository_api = $this->getRepositoryAPI();
$repository = $this->loadProjectRepository();
$callsign = $repository["callsign"];
$is_git_svn = $repository_api instanceof ArcanistGitAPI &&
$repository_api->isGitSubversionRepo();
$is_hg_svn = $repository_api instanceof ArcanistMercurialAPI &&
$repository_api->isHgSubversionRepo();
$revision_id = null;
if (!($repository_api instanceof ArcanistGitAPI) &&
!($repository_api instanceof ArcanistMercurialAPI)) {
throw new ArcanistUsageException(
'Backout currently only supports Git and Mercurial'
);
}
$console->writeOut("Starting backout\n");
$input = $this->getArgument('input');
if (!$input || count($input) != 1) {
throw new ArcanistUsageException(
'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['commitIdentifier'];
// 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!');
}
// Run 'backout'.
$subject = $repository_api->getCommitSummary($commit_hash);
$console->writeOut("Backing out commit {$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("Double-check the commit and push when ready\n");
}
}
-
diff --git a/src/workflow/ArcanistRevertWorkflow.php b/src/workflow/ArcanistRevertWorkflow.php
index ee7bc743..4b1b9491 100644
--- a/src/workflow/ArcanistRevertWorkflow.php
+++ b/src/workflow/ArcanistRevertWorkflow.php
@@ -1,38 +1,37 @@
<?php
/**
* Redirects to arc backout workflow
* @group workflow
*/
final class ArcanistRevertWorkflow extends ArcanistBaseWorkflow {
public function getWorkflowName() {
return 'revert';
}
public function getCommandSynopses() {
return phutil_console_format(<<<EOTEXT
**revert**
EOTEXT
);
}
public function getCommandHelp() {
return phutil_console_format(<<<EOTEXT
Please use arc backout instead
EOTEXT
);
}
public function getArguments() {
return array(
'*' => 'input',
);
}
public function run() {
$console = PhutilConsole::getConsole();
$console->writeOut("Please use arc backout instead.\n");
}
}
-

File Metadata

Mime Type
text/x-diff
Expires
Sat, Nov 23, 22:13 (1 d, 15 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
548030
Default Alt Text
(47 KB)

Event Timeline