diff --git a/src/configuration/ArcanistSettings.php b/src/configuration/ArcanistSettings.php index b6ede180..cd5f8f01 100644 --- a/src/configuration/ArcanistSettings.php +++ b/src/configuration/ArcanistSettings.php @@ -1,347 +1,338 @@ array( 'type' => 'string', 'help' => pht( 'The URI of a Phabricator install to connect to by default, if '. '%s is run in a project without a Phabricator URI or run outside '. 'of a project.', 'arc'), 'example' => '"http://phabricator.example.com/"', ), 'base' => array( 'type' => 'string', 'help' => pht( 'Base commit ruleset to invoke when determining the start of a '. 'commit range. See "Arcanist User Guide: Commit Ranges" for '. 'details.'), 'example' => '"arc:amended, arc:prompt"', ), 'load' => array( 'type' => 'list', 'legacy' => 'phutil_libraries', 'help' => pht( 'A list of paths to phutil libraries that should be loaded at '. 'startup. This can be used to make classes available, like lint '. 'or unit test engines.'), 'default' => array(), 'example' => '["/var/arc/customlib/src"]', ), 'repository.callsign' => array( 'type' => 'string', 'example' => '"X"', 'help' => pht( 'Associate the working copy with a specific Phabricator repository. '. 'Normally, %s can figure this association out on its own, but if '. 'your setup is unusual you can use this option to tell it what the '. 'desired value is.', 'arc'), ), 'phabricator.uri' => array( 'type' => 'string', 'legacy' => 'conduit_uri', 'example' => '"https://phabricator.mycompany.com/"', 'help' => pht( 'Associates this working copy with a specific installation of '. 'Phabricator.'), ), - 'project.name' => array( - 'type' => 'string', - 'legacy' => 'project_id', - 'example' => '"arcanist"', - 'help' => pht( - 'Associates this working copy with a named Arcanist Project. '. - 'This is primarily useful if you use SVN and have several different '. - 'projects in the same repository.'), - ), 'lint.engine' => array( 'type' => 'string', 'legacy' => 'lint_engine', 'help' => pht( 'The name of a default lint engine to use, if no lint engine is '. 'specified by the current project.'), 'example' => '"ExampleLintEngine"', ), 'unit.engine' => array( 'type' => 'string', 'legacy' => 'unit_engine', 'help' => pht( 'The name of a default unit test engine to use, if no unit test '. 'engine is specified by the current project.'), 'example' => '"ExampleUnitTestEngine"', ), 'arc.feature.start.default' => array( 'type' => 'string', 'help' => pht( 'The name of the default branch to create the new feature branch '. 'off of.'), 'example' => '"develop"', ), 'arc.land.onto.default' => array( 'type' => 'string', 'help' => pht( 'The name of the default branch to land changes onto when '. '`%s` is run.', 'arc land'), 'example' => '"develop"', ), 'arc.land.update.default' => array( 'type' => 'string', 'help' => pht( 'The default strategy to use when arc land updates the feature '. 'branch. Supports "rebase" and "merge" strategies.'), 'example' => '"rebase"', ), 'arc.lint.cache' => array( 'type' => 'bool', 'help' => pht( 'Enable the lint cache by default. When enabled, `%s` attempts to '. 'use cached results if possible. Currently, the cache is not always '. 'invalidated correctly and may cause `%s` to report incorrect '. 'results, particularly while developing linters. This is probably '. 'worth enabling only if your linters are very slow.', 'arc lint', 'arc lint'), 'default' => false, 'example' => 'false', ), 'history.immutable' => array( 'type' => 'bool', 'legacy' => 'immutable_history', 'help' => pht( 'If true, %s will never change repository history (e.g., through '. 'amending or rebasing). Defaults to true in Mercurial and false in '. 'Git. This setting has no effect in Subversion.', 'arc'), 'example' => 'false', ), 'editor' => array( 'type' => 'string', 'help' => pht( 'Command to use to invoke an interactive editor, like `%s` or `%s`. '. 'This setting overrides the %s environmental variable.', 'nano', 'vim', 'EDITOR'), 'example' => '"nano"', ), 'https.cabundle' => array( 'type' => 'string', 'help' => pht( "Path to a custom CA bundle file to be used for arcanist's cURL ". "calls. This is used primarily when your conduit endpoint is ". "behind HTTPS signed by your organization's internal CA."), 'example' => 'support/yourca.pem', ), 'https.blindly-trust-domains' => array( 'type' => 'list', 'help' => pht( 'List of domains to blindly trust SSL certificates for. '. 'Disables peer verification.'), 'default' => array(), 'example' => '["secure.mycompany.com"]', ), 'browser' => array( 'type' => 'string', 'help' => pht('Command to use to invoke a web browser.'), 'example' => '"gnome-www-browser"', ), 'events.listeners' => array( 'type' => 'list', 'help' => pht('List of event listener classes to install at startup.'), 'default' => array(), 'example' => '["ExampleEventListener"]', ), 'http.basicauth.user' => array( 'type' => 'string', 'help' => pht('Username to use for basic auth over HTTP transports.'), 'example' => '"bob"', ), 'http.basicauth.pass' => array( 'type' => 'string', 'help' => pht('Password to use for basic auth over HTTP transports.'), 'example' => '"bobhasasecret"', ), 'arc.autostash' => array( 'type' => 'bool', 'help' => pht( 'Whether %s should permit the automatic stashing of changes in the '. 'working directory when requiring a clean working copy. This option '. 'should only be used when users understand how to restore their '. 'working directory from the local stash if an Arcanist operation '. 'causes an unrecoverable error.', 'arc'), 'default' => false, 'example' => 'false', ), ); } private function getOption($key) { return idx($this->getOptions(), $key, array()); } public function getAllKeys() { return array_keys($this->getOptions()); } public function getHelp($key) { return idx($this->getOption($key), 'help'); } public function getExample($key) { return idx($this->getOption($key), 'example'); } public function getType($key) { return idx($this->getOption($key), 'type', 'wild'); } public function getLegacyName($key) { return idx($this->getOption($key), 'legacy'); } public function getDefaultSettings() { $defaults = array(); foreach ($this->getOptions() as $key => $option) { if (array_key_exists('default', $option)) { $defaults[$key] = $option['default']; } } return $defaults; } public function willWriteValue($key, $value) { $type = $this->getType($key); switch ($type) { case 'bool': if (strtolower($value) === 'false' || strtolower($value) === 'no' || strtolower($value) === 'off' || $value === '' || $value === '0' || $value === 0 || $value === false) { $value = false; } else if (strtolower($value) === 'true' || strtolower($value) === 'yes' || strtolower($value) === 'on' || $value === '1' || $value === 1 || $value === true) { $value = true; } else { throw new ArcanistUsageException( pht( "Type of setting '%s' must be boolean, like 'true' or 'false'.", $key)); } break; case 'list': if (is_array($value)) { break; } if (is_string($value)) { $list = json_decode($value, true); if (is_array($list)) { $value = $list; break; } } throw new ArcanistUsageException( pht( "Type of setting '%s' must be list. You can specify a list ". "in JSON, like: %s", $key, '["apple", "banana", "cherry"]')); case 'string': if (!is_scalar($value)) { throw new ArcanistUsageException( pht( "Type of setting '%s' must be string.", $key)); } $value = (string)$value; break; case 'wild': break; } return $value; } public function willReadValue($key, $value) { $type = $this->getType($key); switch ($type) { case 'string': if (!is_string($value)) { throw new ArcanistUsageException( pht( "Type of setting '%s' must be string.", $key)); } break; case 'bool': if ($value !== true && $value !== false) { throw new ArcanistUsageException( pht( "Type of setting '%s' must be boolean.", $key)); } break; case 'list': if (!is_array($value)) { throw new ArcanistUsageException( pht( "Type of setting '%s' must be list.", $key)); } break; case 'wild': break; } return $value; } public function formatConfigValueForDisplay($key, $value) { if ($value === false) { return 'false'; } if ($value === true) { return 'true'; } if ($value === null) { return 'null'; } if (is_string($value)) { return '"'.$value.'"'; } if (is_array($value)) { // TODO: Both json_encode() and PhutilJSON do a bad job with one-liners. // PhutilJSON splits them across a bunch of lines, while json_encode() // escapes all kinds of stuff like "/". It would be nice if PhutilJSON // had a mode for pretty one-liners. $value = json_encode($value); // json_encode() unnecessarily escapes "/" to prevent "" stuff, // optimistically unescape it for display to improve readability. $value = preg_replace('@(?authorEmail = $author_email; return $this; } public function getAuthorEmail() { return $this->authorEmail; } public function setAuthorName($author_name) { $this->authorName = $author_name; return $this; } public function getAuthorName() { return $this->authorName; } public function getFullAuthor() { $author_name = $this->getAuthorName(); if ($author_name === null) { return null; } $author_email = $this->getAuthorEmail(); if ($author_email === null) { return null; } $full_author = sprintf('%s <%s>', $author_name, $author_email); // Because git is very picky about the author being in a valid format, // verify that we can parse it. $address = new PhutilEmailAddress($full_author); if (!$address->getDisplayName() || !$address->getAddress()) { return null; } return $full_author; } public function setConduit(ConduitClient $conduit) { $this->conduit = $conduit; return $this; } public function setBaseRevision($base_revision) { $this->baseRevision = $base_revision; return $this; } public function setEncoding($encoding) { $this->encoding = $encoding; return $this; } public function getEncoding() { return $this->encoding; } public function getBaseRevision() { return $this->baseRevision; } public function setRevisionID($revision_id) { $this->revisionID = $revision_id; return $this; } public function getRevisionID() { return $this->revisionID; } public static function newFromChanges(array $changes) { $obj = new ArcanistBundle(); $obj->changes = $changes; return $obj; } private function getEOL($patch_type) { // NOTE: Git always generates "\n" line endings, even under Windows, and // can not parse certain patches with "\r\n" line endings. SVN generates // patches with "\n" line endings on Mac or Linux and "\r\n" line endings // on Windows. (This EOL style is used only for patch metadata lines, not // for the actual patch content.) // (On Windows, Mercurial generates \n newlines for `--git` diffs, as it // must, but also \n newlines for unified diffs. We never need to deal with // these as we use Git format for Mercurial, so this case is currently // ignored.) switch ($patch_type) { case 'git': return "\n"; case 'unified': return phutil_is_windows() ? "\r\n" : "\n"; default: throw new Exception( pht("Unknown patch type '%s'!", $patch_type)); } } public static function newFromArcBundle($path) { $path = Filesystem::resolvePath($path); $future = new ExecFuture( 'tar tfO %s', $path); list($stdout, $file_list) = $future->resolvex(); $file_list = explode("\n", trim($file_list)); if (in_array('meta.json', $file_list)) { $future = new ExecFuture( 'tar xfO %s meta.json', $path); $meta_info = $future->resolveJSON(); $version = idx($meta_info, 'version', 0); - $project_name = idx($meta_info, 'projectName'); $base_revision = idx($meta_info, 'baseRevision'); $revision_id = idx($meta_info, 'revisionID'); $encoding = idx($meta_info, 'encoding'); $author_name = idx($meta_info, 'authorName'); $author_email = idx($meta_info, 'authorEmail'); } else { // this arc bundle was probably made before we started storing meta info $version = 0; - $project_name = null; $base_revision = null; $revision_id = null; $encoding = null; $author = null; } $future = new ExecFuture( 'tar xfO %s changes.json', $path); $changes = $future->resolveJSON(); foreach ($changes as $change_key => $change) { foreach ($change['hunks'] as $key => $hunk) { list($hunk_data) = execx('tar xfO %s hunks/%s', $path, $hunk['corpus']); $changes[$change_key]['hunks'][$key]['corpus'] = $hunk_data; } } foreach ($changes as $change_key => $change) { $changes[$change_key] = ArcanistDiffChange::newFromDictionary($change); } $obj = new ArcanistBundle(); $obj->changes = $changes; $obj->diskPath = $path; $obj->setBaseRevision($base_revision); $obj->setRevisionID($revision_id); $obj->setEncoding($encoding); return $obj; } public static function newFromDiff($data) { $obj = new ArcanistBundle(); $parser = new ArcanistDiffParser(); $obj->changes = $parser->parseDiff($data); return $obj; } private function __construct() {} public function writeToDisk($path) { $changes = $this->getChanges(); $change_list = array(); foreach ($changes as $change) { $change_list[] = $change->toDictionary(); } $hunks = array(); foreach ($change_list as $change_key => $change) { foreach ($change['hunks'] as $key => $hunk) { $hunks[] = $hunk['corpus']; $change_list[$change_key]['hunks'][$key]['corpus'] = count($hunks) - 1; } } $blobs = array(); foreach ($change_list as $change) { if (!empty($change['metadata']['old:binary-phid'])) { $blobs[$change['metadata']['old:binary-phid']] = null; } if (!empty($change['metadata']['new:binary-phid'])) { $blobs[$change['metadata']['new:binary-phid']] = null; } } foreach ($blobs as $phid => $null) { $blobs[$phid] = $this->getBlob($phid); } $meta_info = array( 'version' => 5, 'baseRevision' => $this->getBaseRevision(), 'revisionID' => $this->getRevisionID(), 'encoding' => $this->getEncoding(), 'authorName' => $this->getAuthorName(), 'authorEmail' => $this->getAuthorEmail(), ); $dir = Filesystem::createTemporaryDirectory(); Filesystem::createDirectory($dir.'/hunks'); Filesystem::createDirectory($dir.'/blobs'); Filesystem::writeFile($dir.'/changes.json', json_encode($change_list)); Filesystem::writeFile($dir.'/meta.json', json_encode($meta_info)); foreach ($hunks as $key => $hunk) { Filesystem::writeFile($dir.'/hunks/'.$key, $hunk); } foreach ($blobs as $key => $blob) { Filesystem::writeFile($dir.'/blobs/'.$key, $blob); } execx( '(cd %s; tar -czf %s *)', $dir, Filesystem::resolvePath($path)); Filesystem::remove($dir); } public function toUnifiedDiff() { $eol = $this->getEOL('unified'); $result = array(); $changes = $this->getChanges(); foreach ($changes as $change) { $hunk_changes = $this->buildHunkChanges($change->getHunks(), $eol); if (!$hunk_changes) { continue; } $old_path = $this->getOldPath($change); $cur_path = $this->getCurrentPath($change); $index_path = $cur_path; if ($index_path === null) { $index_path = $old_path; } $result[] = 'Index: '.$index_path; $result[] = $eol; $result[] = str_repeat('=', 67); $result[] = $eol; if ($old_path === null) { $old_path = '/dev/null'; } if ($cur_path === null) { $cur_path = '/dev/null'; } // When the diff is used by `patch`, `patch` ignores what is listed as the // current path and just makes changes to the file at the old path (unless // the current path is '/dev/null'. // If the old path and the current path aren't the same (and neither is // /dev/null), this indicates the file was moved or copied. By listing // both paths as the new file, `patch` will apply the diff to the new // file. if ($cur_path !== '/dev/null' && $old_path !== '/dev/null') { $old_path = $cur_path; } $result[] = '--- '.$old_path.$eol; $result[] = '+++ '.$cur_path.$eol; $result[] = $hunk_changes; } if (!$result) { return ''; } $diff = implode('', $result); return $this->convertNonUTF8Diff($diff); } public function toGitPatch() { $eol = $this->getEOL('git'); $result = array(); $changes = $this->getChanges(); $binary_sources = array(); foreach ($changes as $change) { if (!$this->isGitBinaryChange($change)) { continue; } $type = $change->getType(); if ($type == ArcanistDiffChangeType::TYPE_MOVE_AWAY || $type == ArcanistDiffChangeType::TYPE_COPY_AWAY || $type == ArcanistDiffChangeType::TYPE_MULTICOPY) { foreach ($change->getAwayPaths() as $path) { $binary_sources[$path] = $change; } } } foreach (array_keys($changes) as $multicopy_key) { $multicopy_change = $changes[$multicopy_key]; $type = $multicopy_change->getType(); if ($type != ArcanistDiffChangeType::TYPE_MULTICOPY) { continue; } // Decompose MULTICOPY into one MOVE_HERE and several COPY_HERE because // we need more information than we have in order to build a delete patch // and represent it as a bunch of COPY_HERE plus a delete. For details, // see T419. // Basically, MULTICOPY means there are 2 or more corresponding COPY_HERE // changes, so find one of them arbitrarily and turn it into a MOVE_HERE. // TODO: We might be able to do this more cleanly after T230 is resolved. $decompose_okay = false; foreach ($changes as $change_key => $change) { if ($change->getType() != ArcanistDiffChangeType::TYPE_COPY_HERE) { continue; } if ($change->getOldPath() != $multicopy_change->getCurrentPath()) { continue; } $decompose_okay = true; $change = clone $change; $change->setType(ArcanistDiffChangeType::TYPE_MOVE_HERE); $changes[$change_key] = $change; // The multicopy is now fully represented by MOVE_HERE plus one or more // COPY_HERE, so throw it away. unset($changes[$multicopy_key]); break; } if (!$decompose_okay) { throw new Exception( pht( 'Failed to decompose multicopy changeset in '. 'order to generate diff.')); } } foreach ($changes as $change) { $type = $change->getType(); $file_type = $change->getFileType(); if ($file_type == ArcanistDiffChangeType::FILE_DIRECTORY) { // TODO: We should raise a FYI about this, so the user is aware // that we omitted it, if the directory is empty or has permissions // which git can't represent. // Git doesn't support empty directories, so we simply ignore them. If // the directory is nonempty, 'git apply' will create it when processing // the changesets for files inside it. continue; } if ($type == ArcanistDiffChangeType::TYPE_MOVE_AWAY) { // Git will apply this in the corresponding MOVE_HERE. continue; } $old_mode = idx($change->getOldProperties(), 'unix:filemode', '100644'); $new_mode = idx($change->getNewProperties(), 'unix:filemode', '100644'); $is_binary = $this->isGitBinaryChange($change); if ($is_binary) { $old_binary = idx($binary_sources, $this->getCurrentPath($change)); $change_body = $this->buildBinaryChange($change, $old_binary); } else { $change_body = $this->buildHunkChanges($change->getHunks(), $eol); } if ($type == ArcanistDiffChangeType::TYPE_COPY_AWAY) { // TODO: This is only relevant when patching old Differential diffs // which were created prior to arc pruning TYPE_COPY_AWAY for files // with no modifications. if (!strlen($change_body) && ($old_mode == $new_mode)) { continue; } } $old_path = $this->getOldPath($change); $cur_path = $this->getCurrentPath($change); if ($old_path === null) { $old_index = 'a/'.$cur_path; $old_target = '/dev/null'; } else { $old_index = 'a/'.$old_path; $old_target = 'a/'.$old_path; } if ($cur_path === null) { $cur_index = 'b/'.$old_path; $cur_target = '/dev/null'; } else { $cur_index = 'b/'.$cur_path; $cur_target = 'b/'.$cur_path; } $result[] = "diff --git {$old_index} {$cur_index}".$eol; if ($type == ArcanistDiffChangeType::TYPE_ADD) { $result[] = "new file mode {$new_mode}".$eol; } if ($type == ArcanistDiffChangeType::TYPE_COPY_HERE || $type == ArcanistDiffChangeType::TYPE_MOVE_HERE || $type == ArcanistDiffChangeType::TYPE_COPY_AWAY || $type == ArcanistDiffChangeType::TYPE_CHANGE) { if ($old_mode !== $new_mode) { $result[] = "old mode {$old_mode}".$eol; $result[] = "new mode {$new_mode}".$eol; } } if ($type == ArcanistDiffChangeType::TYPE_COPY_HERE) { $result[] = "copy from {$old_path}".$eol; $result[] = "copy to {$cur_path}".$eol; } else if ($type == ArcanistDiffChangeType::TYPE_MOVE_HERE) { $result[] = "rename from {$old_path}".$eol; $result[] = "rename to {$cur_path}".$eol; } else if ($type == ArcanistDiffChangeType::TYPE_DELETE || $type == ArcanistDiffChangeType::TYPE_MULTICOPY) { $old_mode = idx($change->getOldProperties(), 'unix:filemode'); if ($old_mode) { $result[] = "deleted file mode {$old_mode}".$eol; } } if ($change_body) { if (!$is_binary) { $result[] = "--- {$old_target}".$eol; $result[] = "+++ {$cur_target}".$eol; } $result[] = $change_body; } } $diff = implode('', $result).$eol; return $this->convertNonUTF8Diff($diff); } private function isGitBinaryChange(ArcanistDiffChange $change) { $file_type = $change->getFileType(); return ($file_type == ArcanistDiffChangeType::FILE_BINARY || $file_type == ArcanistDiffChangeType::FILE_IMAGE); } private function convertNonUTF8Diff($diff) { if ($this->encoding) { $diff = phutil_utf8_convert($diff, $this->encoding, 'UTF-8'); } return $diff; } public function getChanges() { return $this->changes; } private function breakHunkIntoSmallHunks(ArcanistDiffHunk $base_hunk) { $context = 3; $results = array(); $lines = phutil_split_lines($base_hunk->getCorpus()); $n = count($lines); $old_offset = $base_hunk->getOldOffset(); $new_offset = $base_hunk->getNewOffset(); $ii = 0; $jj = 0; while ($ii < $n) { // Skip lines until we find the next line with changes. Note: this skips // both ' ' (no changes) and '\' (no newline at end of file) lines. If we // don't skip the latter, we may incorrectly generate a terminal hunk // that has no actual change information when a file doesn't have a // terminal newline and not changed near the end of the file. 'patch' will // fail to apply the diff if we generate a hunk that does not actually // contain changes. for ($jj = $ii; $jj < $n; ++$jj) { $char = $lines[$jj][0]; if ($char == '-' || $char == '+') { break; } } if ($jj >= $n) { break; } $hunk_start = max($jj - $context, 0); // NOTE: There are two tricky considerations here. // We can not generate a patch with overlapping hunks, or 'git apply' // rejects it after 1.7.3.4. // We can not generate a patch with too much trailing context, or // 'patch' rejects it. // So we need to ensure that we generate disjoint hunks, but don't // generate any hunks with too much context. $old_lines = 0; $new_lines = 0; $hunk_adjust = 0; $last_change = $jj; $break_here = null; for (; $jj < $n; ++$jj) { if ($lines[$jj][0] == ' ') { if ($jj - $last_change > $context) { if ($break_here === null) { // We haven't seen a change in $context lines, so this is a // potential place to break the hunk. However, we need to keep // looking in case there is another change fewer than $context // lines away, in which case we have to merge the hunks. $break_here = $jj; } } if ($jj - $last_change > (($context + 1) * 2)) { // We definitely aren't going to merge this with the next hunk, so // break out of the loop. We'll end the hunk at $break_here. break; } } else { $break_here = null; $last_change = $jj; if ($lines[$jj][0] == '\\') { // When we have a "\ No newline at end of file" line, it does not // contribute to either hunk length. ++$hunk_adjust; } else if ($lines[$jj][0] == '-') { ++$old_lines; } else if ($lines[$jj][0] == '+') { ++$new_lines; } } } if ($break_here !== null) { $jj = $break_here; } $hunk_length = min($jj, $n) - $hunk_start; $count_length = ($hunk_length - $hunk_adjust); $hunk = new ArcanistDiffHunk(); $hunk->setOldOffset($old_offset + $hunk_start - $ii); $hunk->setNewOffset($new_offset + $hunk_start - $ii); $hunk->setOldLength($count_length - $new_lines); $hunk->setNewLength($count_length - $old_lines); $corpus = array_slice($lines, $hunk_start, $hunk_length); $corpus = implode('', $corpus); $hunk->setCorpus($corpus); $results[] = $hunk; $old_offset += ($jj - $ii) - $new_lines; $new_offset += ($jj - $ii) - $old_lines; $ii = $jj; } return $results; } private function getOldPath(ArcanistDiffChange $change) { $old_path = $change->getOldPath(); $type = $change->getType(); if (!strlen($old_path) || $type == ArcanistDiffChangeType::TYPE_ADD) { $old_path = null; } return $old_path; } private function getCurrentPath(ArcanistDiffChange $change) { $cur_path = $change->getCurrentPath(); $type = $change->getType(); if (!strlen($cur_path) || $type == ArcanistDiffChangeType::TYPE_DELETE || $type == ArcanistDiffChangeType::TYPE_MULTICOPY) { $cur_path = null; } return $cur_path; } private function buildHunkChanges(array $hunks, $eol) { assert_instances_of($hunks, 'ArcanistDiffHunk'); $result = array(); foreach ($hunks as $hunk) { $small_hunks = $this->breakHunkIntoSmallHunks($hunk); foreach ($small_hunks as $small_hunk) { $o_off = $small_hunk->getOldOffset(); $o_len = $small_hunk->getOldLength(); $n_off = $small_hunk->getNewOffset(); $n_len = $small_hunk->getNewLength(); $corpus = $small_hunk->getCorpus(); // NOTE: If the length is 1 it can be omitted. Since git does this, // we also do it so that "arc export --git" diffs are as similar to // real git diffs as possible, which helps debug issues. if ($o_len == 1) { $o_head = "{$o_off}"; } else { $o_head = "{$o_off},{$o_len}"; } if ($n_len == 1) { $n_head = "{$n_off}"; } else { $n_head = "{$n_off},{$n_len}"; } $result[] = "@@ -{$o_head} +{$n_head} @@".$eol; $result[] = $corpus; $last = substr($corpus, -1); if ($last !== false && $last != "\r" && $last != "\n") { $result[] = $eol; } } } return implode('', $result); } public function setLoadFileDataCallback($callback) { $this->loadFileDataCallback = $callback; return $this; } private function getBlob($phid, $name = null) { if ($this->loadFileDataCallback) { return call_user_func($this->loadFileDataCallback, $phid); } if ($this->diskPath) { list($blob_data) = execx('tar xfO %s blobs/%s', $this->diskPath, $phid); return $blob_data; } $console = PhutilConsole::getConsole(); if ($this->conduit) { if ($name) { $console->writeErr( "%s\n", pht("Downloading binary data for '%s'...", $name)); } else { $console->writeErr("%s\n", pht('Downloading binary data...')); } $data_base64 = $this->conduit->callMethodSynchronous( 'file.download', array( 'phid' => $phid, )); return base64_decode($data_base64); } throw new Exception(pht("Nowhere to load blob '%s' from!", $phid)); } private function buildBinaryChange(ArcanistDiffChange $change, $old_binary) { $eol = $this->getEOL('git'); // In Git, when we write out a binary file move or copy, we need the // original binary for the source and the current binary for the // destination. if ($old_binary) { if ($old_binary->getOriginalFileData() !== null) { $old_data = $old_binary->getOriginalFileData(); $old_phid = null; } else { $old_data = null; $old_phid = $old_binary->getMetadata('old:binary-phid'); } } else { $old_data = $change->getOriginalFileData(); $old_phid = $change->getMetadata('old:binary-phid'); } if ($old_data === null && $old_phid) { $name = basename($change->getOldPath()); $old_data = $this->getBlob($old_phid, $name); } $old_length = strlen($old_data); if ($old_data === null) { $old_data = ''; $old_sha1 = str_repeat('0', 40); } else { $old_sha1 = sha1("blob {$old_length}\0{$old_data}"); } $new_phid = $change->getMetadata('new:binary-phid'); $new_data = null; if ($change->getCurrentFileData() !== null) { $new_data = $change->getCurrentFileData(); } else if ($new_phid) { $name = basename($change->getCurrentPath()); $new_data = $this->getBlob($new_phid, $name); } $new_length = strlen($new_data); if ($new_data === null) { $new_data = ''; $new_sha1 = str_repeat('0', 40); } else { $new_sha1 = sha1("blob {$new_length}\0{$new_data}"); } $content = array(); $content[] = "index {$old_sha1}..{$new_sha1}".$eol; $content[] = 'GIT binary patch'.$eol; $content[] = "literal {$new_length}".$eol; $content[] = $this->emitBinaryDiffBody($new_data).$eol; $content[] = "literal {$old_length}".$eol; $content[] = $this->emitBinaryDiffBody($old_data).$eol; return implode('', $content); } private function emitBinaryDiffBody($data) { $eol = $this->getEOL('git'); if (!function_exists('gzcompress')) { throw new Exception( pht( 'This patch has binary data. The PHP zlib extension is required to '. 'apply patches with binary data to git. Install the PHP zlib '. 'extension to continue.')); } // See emit_binary_diff_body() in diff.c for git's implementation. $buf = ''; $deflated = gzcompress($data); $lines = str_split($deflated, 52); foreach ($lines as $line) { $len = strlen($line); // The first character encodes the line length. if ($len <= 26) { $buf .= chr($len + ord('A') - 1); } else { $buf .= chr($len - 26 + ord('a') - 1); } $buf .= self::encodeBase85($line); $buf .= $eol; } return $buf; } public static function encodeBase85($data) { // This is implemented awkwardly in order to closely mirror git's // implementation in base85.c // It is also implemented awkwardly to work correctly on 32-bit machines. // Broadly, this algorithm converts the binary input to printable output // by transforming each 4 binary bytes of input to 5 printable bytes of // output, one piece at a time. // // To do this, we convert the 4 bytes into a 32-bit integer, then use // modulus and division by 85 to pick out printable bytes (85^5 is slightly // larger than 2^32). In C, this algorithm is fairly easy to implement // because the accumulator can be made unsigned. // // In PHP, there are no unsigned integers, so values larger than 2^31 break // on 32-bit systems under modulus: // // $ php -r 'print (1 << 31) % 13;' # On a 32-bit machine. // -11 // // However, PHP's float type is an IEEE 754 64-bit double precision float, // so we can safely store integers up to around 2^53 without loss of // precision. To work around the lack of an unsigned type, we just use a // double and perform the modulus with fmod(). // // (Since PHP overflows integer operations into floats, we don't need much // additional casting.) static $map = array( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '!', '#', '$', '%', '&', '(', ')', '*', '+', '-', ';', '<', '=', '>', '?', '@', '^', '_', '`', '{', '|', '}', '~', ); $buf = ''; $pos = 0; $bytes = strlen($data); while ($bytes) { $accum = 0; for ($count = 24; $count >= 0; $count -= 8) { $val = ord($data[$pos++]); $val = $val * (1 << $count); $accum = $accum + $val; if (--$bytes == 0) { break; } } $slice = ''; for ($count = 4; $count >= 0; $count--) { $val = (int)fmod($accum, 85.0); $accum = floor($accum / 85.0); $slice .= $map[$val]; } $buf .= strrev($slice); } return $buf; } } diff --git a/src/repository/api/ArcanistSubversionAPI.php b/src/repository/api/ArcanistSubversionAPI.php index 707d2d93..d8420a1b 100644 --- a/src/repository/api/ArcanistSubversionAPI.php +++ b/src/repository/api/ArcanistSubversionAPI.php @@ -1,703 +1,692 @@ getPath()) as $parent) { $possible_svn_dir = Filesystem::resolvePath('.svn', $parent); if (Filesystem::pathExists($possible_svn_dir)) { $svn_dir = $possible_svn_dir; break; } } } return $svn_dir; } protected function buildLocalFuture(array $argv) { $argv[0] = 'svn '.$argv[0]; $future = newv('ExecFuture', $argv); $future->setCWD($this->getPath()); return $future; } protected function buildCommitRangeStatus() { // In SVN, the commit range is always "uncommitted changes", so these // statuses are equivalent. return $this->getUncommittedStatus(); } protected function buildUncommittedStatus() { return $this->getSVNStatus(); } public function getSVNBaseRevisions() { if ($this->svnBaseRevisions === null) { $this->getSVNStatus(); } return $this->svnBaseRevisions; } public function limitStatusToPaths(array $paths) { $this->statusPaths = $paths; return $this; } public function getSVNStatus($with_externals = false) { if ($this->svnStatus === null) { if ($this->statusPaths) { list($status) = $this->execxLocal( '--xml status %Ls', $this->statusPaths); } else { list($status) = $this->execxLocal('--xml status'); } $xml = new SimpleXMLElement($status); $externals = array(); $files = array(); foreach ($xml->target as $target) { $this->svnBaseRevisions = array(); foreach ($target->entry as $entry) { $path = (string)$entry['path']; // On Windows, we get paths with backslash directory separators here. // Normalize them to the format everything else expects and generates. if (phutil_is_windows()) { $path = str_replace(DIRECTORY_SEPARATOR, '/', $path); } $mask = 0; $props = (string)($entry->{'wc-status'}[0]['props']); $item = (string)($entry->{'wc-status'}[0]['item']); $base = (string)($entry->{'wc-status'}[0]['revision']); $this->svnBaseRevisions[$path] = $base; switch ($props) { case 'none': case 'normal': break; case 'modified': $mask |= self::FLAG_MODIFIED; break; default: throw new Exception(pht( "Unrecognized property status '%s'.", $props)); } $mask |= $this->parseSVNStatus($item); if ($item == 'external') { $externals[] = $path; } // This is new in or around Subversion 1.6. $tree_conflicts = ($entry->{'wc-status'}[0]['tree-conflicted']); if ((string)$tree_conflicts) { $mask |= self::FLAG_CONFLICT; } $files[$path] = $mask; } } foreach ($files as $path => $mask) { foreach ($externals as $external) { if (!strncmp($path.'/', $external.'/', strlen($external) + 1)) { $files[$path] |= self::FLAG_EXTERNALS; } } } $this->svnStatus = $files; } $status = $this->svnStatus; if (!$with_externals) { foreach ($status as $path => $mask) { if ($mask & ArcanistRepositoryAPI::FLAG_EXTERNALS) { unset($status[$path]); } } } return $status; } private function parseSVNStatus($item) { switch ($item) { case 'none': // We can get 'none' for property changes on a directory. case 'normal': return 0; case 'external': return self::FLAG_EXTERNALS; case 'unversioned': return self::FLAG_UNTRACKED; case 'obstructed': return self::FLAG_OBSTRUCTED; case 'missing': return self::FLAG_MISSING; case 'added': return self::FLAG_ADDED; case 'replaced': // This is the result of "svn rm"-ing a file, putting another one // in place of it, and then "svn add"-ing the new file. Just treat // this as equivalent to "modified". return self::FLAG_MODIFIED; case 'modified': return self::FLAG_MODIFIED; case 'deleted': return self::FLAG_DELETED; case 'conflicted': return self::FLAG_CONFLICT; case 'incomplete': return self::FLAG_INCOMPLETE; default: throw new Exception(pht("Unrecognized item status '%s'.", $item)); } } public function addToCommit(array $paths) { $add = array_filter($paths, 'Filesystem::pathExists'); if ($add) { $this->execxLocal( 'add -- %Ls', $add); } if ($add != $paths) { $this->execxLocal( 'delete -- %Ls', array_diff($paths, $add)); } $this->svnStatus = null; } public function getSVNProperty($path, $property) { list($stdout) = execx( 'svn propget %s %s@', $property, $this->getPath($path)); return trim($stdout); } public function getSourceControlPath() { return idx($this->getSVNInfo('/'), 'URL'); } public function getSourceControlBaseRevision() { $info = $this->getSVNInfo('/'); return $info['URL'].'@'.$this->getSVNBaseRevisionNumber(); } public function getCanonicalRevisionName($string) { // TODO: This could be more accurate, but is only used by `arc browse` // for now. if (is_numeric($string)) { return $string; } return null; } public function getSVNBaseRevisionNumber() { if ($this->svnBaseRevisionNumber) { return $this->svnBaseRevisionNumber; } $info = $this->getSVNInfo('/'); return $info['Revision']; } public function overrideSVNBaseRevisionNumber($effective_base_revision) { $this->svnBaseRevisionNumber = $effective_base_revision; return $this; } public function getBranchName() { $info = $this->getSVNInfo('/'); $repo_root = idx($info, 'Repository Root'); $repo_root_length = strlen($repo_root); $url = idx($info, 'URL'); if (substr($url, 0, $repo_root_length) == $repo_root) { return substr($url, $repo_root_length); } return 'svn'; } public function getRemoteURI() { return idx($this->getSVNInfo('/'), 'Repository Root'); } public function buildInfoFuture($path) { if ($path == '/') { // When the root of a working copy is referenced by a symlink and you // execute 'svn info' on that symlink, svn fails. This is a longstanding // bug in svn: // // See http://subversion.tigris.org/issues/show_bug.cgi?id=2305 // // To reproduce, do: // // $ ln -s working_copy working_link // $ svn info working_copy # ok // $ svn info working_link # fails // // Work around this by cd-ing into the directory before executing // 'svn info'. return $this->buildLocalFuture(array('info .')); } else { // Note: here and elsewhere we need to append "@" to the path because if // a file has a literal "@" in it, everything after that will be // interpreted as a revision. By appending "@" with no argument, SVN // parses it properly. return $this->buildLocalFuture(array('info %s@', $this->getPath($path))); } } public function buildDiffFuture($path) { $root = phutil_get_library_root('arcanist'); // The "--depth empty" flag prevents us from picking up changes in // children when we run 'diff' against a directory. Specifically, when a // user has added or modified some directory "example/", we want to return // ONLY changes to that directory when given it as a path. If we run // without "--depth empty", svn will give us changes to the directory // itself (such as property changes) and also give us changes to any // files within the directory (basically, implicit recursion). We don't // want that, so prevent recursive diffing. This flag does not work if the // directory is newly added (see T5555) so we need to filter the results // out later as well. if (phutil_is_windows()) { // TODO: Provide a binary_safe_diff script for Windows. // TODO: Provide a diff command which can take lines of context somehow. return $this->buildLocalFuture( array( 'diff --depth empty %s', $path, )); } else { $diff_bin = $root.'/../scripts/repository/binary_safe_diff.sh'; $diff_cmd = Filesystem::resolvePath($diff_bin); return $this->buildLocalFuture( array( 'diff --depth empty --diff-cmd %s -x -U%d %s', $diff_cmd, $this->getDiffLinesOfContext(), $path, )); } } public function primeSVNInfoResult($path, $result) { $this->svnInfoRaw[$path] = $result; return $this; } public function primeSVNDiffResult($path, $result) { $this->svnDiffRaw[$path] = $result; return $this; } public function getSVNInfo($path) { if (empty($this->svnInfo[$path])) { if (empty($this->svnInfoRaw[$path])) { $this->svnInfoRaw[$path] = $this->buildInfoFuture($path)->resolve(); } list($err, $stdout) = $this->svnInfoRaw[$path]; if ($err) { throw new Exception( pht("Error #%d executing svn info against '%s'.", $err, $path)); } // TODO: Hack for Windows. $stdout = str_replace("\r\n", "\n", $stdout); $patterns = array( '/^(URL): (\S+)$/m', '/^(Revision): (\d+)$/m', '/^(Last Changed Author): (\S+)$/m', '/^(Last Changed Rev): (\d+)$/m', '/^(Last Changed Date): (.+) \(.+\)$/m', '/^(Copied From URL): (\S+)$/m', '/^(Copied From Rev): (\d+)$/m', '/^(Repository Root): (\S+)$/m', '/^(Repository UUID): (\S+)$/m', '/^(Node Kind): (\S+)$/m', ); $result = array(); foreach ($patterns as $pattern) { $matches = null; if (preg_match($pattern, $stdout, $matches)) { $result[$matches[1]] = $matches[2]; } } if (isset($result['Last Changed Date'])) { $result['Last Changed Date'] = strtotime($result['Last Changed Date']); } if (empty($result)) { throw new Exception(pht('Unable to parse SVN info.')); } $this->svnInfo[$path] = $result; } return $this->svnInfo[$path]; } public function getRawDiffText($path) { $status = $this->getSVNStatus(); if (!isset($status[$path])) { return null; } $status = $status[$path]; // Build meaningful diff text for "svn copy" operations. if ($status & ArcanistRepositoryAPI::FLAG_ADDED) { $info = $this->getSVNInfo($path); if (!empty($info['Copied From URL'])) { return $this->buildSyntheticAdditionDiff( $path, $info['Copied From URL'], $info['Copied From Rev']); } } // If we run "diff" on a binary file which doesn't have the "svn:mime-type" // of "application/octet-stream", `diff' will explode in a rain of // unhelpful hellfire as it tries to build a textual diff of the two // files. We just fix this inline since it's pretty unambiguous. // TODO: Move this to configuration? $matches = null; if (preg_match('/\.(gif|png|jpe?g|swf|pdf|ico)$/i', $path, $matches)) { // Check if the file is deleted first; SVN will complain if we try to // get properties of a deleted file. if ($status & ArcanistRepositoryAPI::FLAG_DELETED) { return <<getSVNProperty($path, 'svn:mime-type'); if ($mime != 'application/octet-stream') { execx( 'svn propset svn:mime-type application/octet-stream %s', self::escapeFileNameForSVN($this->getPath($path))); } } if (empty($this->svnDiffRaw[$path])) { $this->svnDiffRaw[$path] = $this->buildDiffFuture($path)->resolve(); } list($err, $stdout, $stderr) = $this->svnDiffRaw[$path]; // Note: GNU Diff returns 2 when SVN hands it binary files to diff and they // differ. This is not an error; it is documented behavior. But SVN isn't // happy about it. SVN will exit with code 1 and return the string below. if ($err != 0 && $stderr !== "svn: 'diff' returned 2\n") { throw new Exception( pht( "%s returned unexpected error code: %d\nstdout: %s\nstderr: %s", 'svn diff', $err, $stdout, $stderr)); } if ($err == 0 && empty($stdout)) { // If there are no changes, 'diff' exits with no output, but that means // we can not distinguish between empty and unmodified files. Build a // synthetic "diff" without any changes in it. return $this->buildSyntheticUnchangedDiff($path); } return $stdout; } protected function buildSyntheticAdditionDiff($path, $source, $rev) { $type = $this->getSVNProperty($path, 'svn:mime-type'); if ($type == 'application/octet-stream') { return <<getPath($path))) { return null; } $data = Filesystem::readFile($this->getPath($path)); list($orig) = execx('svn cat %s@%s', $source, $rev); $src = new TempFile(); $dst = new TempFile(); Filesystem::writeFile($src, $orig); Filesystem::writeFile($dst, $data); list($err, $diff) = exec_manual( 'diff -L a/%s -L b/%s -U%d %s %s', str_replace($this->getSourceControlPath().'/', '', $source), $path, $this->getDiffLinesOfContext(), $src, $dst); if ($err == 1) { // 1 means there are differences. return <<buildSyntheticUnchangedDiff($path); } } protected function buildSyntheticUnchangedDiff($path) { $full_path = $this->getPath($path); if (is_dir($full_path)) { return null; } if (!file_exists($full_path)) { return null; } $data = Filesystem::readFile($full_path); $lines = explode("\n", $data); $len = count($lines); foreach ($lines as $key => $line) { $lines[$key] = ' '.$line; } $lines = implode("\n", $lines); return <<buildLocalFuture(array('list -R')); return new PhutilCallbackFilterIterator( new LinesOfALargeExecFuture($future), array($this, 'filterFiles')); } public function getChangedFiles($since_commit) { $url = ''; $match = null; if (preg_match('/(.*)@(.*)/', $since_commit, $match)) { list(, $url, $since_commit) = $match; } // TODO: Handle paths with newlines. list($stdout) = $this->execxLocal( '--xml diff --revision %s:HEAD --summarize %s', $since_commit, $url); $xml = new SimpleXMLElement($stdout); $return = array(); foreach ($xml->paths[0]->path as $path) { $return[(string)$path] = $this->parseSVNStatus($path['item']); } return $return; } public function filterFiles($path) { // NOTE: SVN uses '/' also on Windows. if ($path == '' || substr($path, -1) == '/') { return null; } return $path; } public function getBlame($path) { $blame = array(); list($stdout) = $this->execxLocal('blame %s', $path); $stdout = trim($stdout); if (!strlen($stdout)) { // Empty file. return $blame; } foreach (explode("\n", $stdout) as $line) { $m = array(); if (!preg_match('/^\s*(\d+)\s+(\S+)/', $line, $m)) { throw new Exception(pht("Bad blame? `%s'", $line)); } $revision = $m[1]; $author = $m[2]; $blame[] = array($author, $revision); } return $blame; } public function getOriginalFileData($path) { // SVN issues warnings for nonexistent paths, directories, etc., but still // returns no error code. However, for new paths in the working copy it // fails. Assume that failure means the original file does not exist. list($err, $stdout) = $this->execManualLocal('cat %s@', $path); if ($err) { return null; } return $stdout; } public function getCurrentFileData($path) { $full_path = $this->getPath($path); if (Filesystem::pathExists($full_path)) { return Filesystem::readFile($full_path); } return null; } public function getRepositoryUUID() { $info = $this->getSVNInfo('/'); return $info['Repository UUID']; } public function getLocalCommitInformation() { return null; } public function isHistoryDefaultImmutable() { return true; } public function supportsAmend() { return false; } public function supportsCommitRanges() { return false; } public function supportsLocalCommits() { return false; } public function hasLocalCommit($commit) { return false; } public function getWorkingCopyRevision() { return $this->getSourceControlBaseRevision(); } public function supportsLocalBranchMerge() { return false; } public function getFinalizedRevisionMessage() { // In other VCSes we give push instructions here, but it never makes sense // in SVN. return 'Done.'; } public function loadWorkingCopyDifferentialRevisions( ConduitClient $conduit, array $query) { - // We don't have much to go on in SVN, look for revisions that came from - // this directory and belong to the same project. - - $project = $this->getWorkingCopyIdentity()->getProjectID(); - if (!$project) { - return array(); - } - - $results = $conduit->callMethodSynchronous( - 'differential.query', - $query); + $results = $conduit->callMethodSynchronous('differential.query', $query); foreach ($results as $key => $result) { if ($result['sourcePath'] != $this->getPath()) { unset($results[$key]); } } foreach ($results as $key => $result) { - $results[$key]['why'] = pht( - 'Matching arcanist project name and working copy directory path.'); + $results[$key]['why'] = pht('Matching working copy directory path.'); } return $results; } public function updateWorkingCopy() { $this->execxLocal('up'); } public static function escapeFileNamesForSVN(array $files) { foreach ($files as $k => $file) { $files[$k] = self::escapeFileNameForSVN($file); } return $files; } public static function escapeFileNameForSVN($file) { // SVN interprets "x@1" as meaning "file x at revision 1", which is not // intended for files named "sprite@2x.png" or similar. For files with an // "@" in their names, escape them by adding "@" at the end, which SVN // interprets as "at the working copy revision". There is a special case // where ".@" means "fail with an error" instead of ". at the working copy // revision", so avoid escaping "." into ".@". if (strpos($file, '@') !== false) { $file = $file.'@'; } return $file; } } diff --git a/src/workingcopyidentity/ArcanistWorkingCopyIdentity.php b/src/workingcopyidentity/ArcanistWorkingCopyIdentity.php index ba1985df..122997de 100644 --- a/src/workingcopyidentity/ArcanistWorkingCopyIdentity.php +++ b/src/workingcopyidentity/ArcanistWorkingCopyIdentity.php @@ -1,352 +1,342 @@ $parent_path) { $try = array( 'git' => $parent_path.'/.git', 'hg' => $parent_path.'/.hg', 'svn' => $parent_path.'/.svn', ); foreach ($try as $vcs => $try_dir) { if (!Filesystem::pathExists($try_dir)) { continue; } // NOTE: We're distinguishing between the `$project_root` and the // `$vcs_root` because they may not be the same in Subversion. Normally, // they are identical. However, in Subversion, the `$vcs_root` is the // base directory of the working copy (the directory which has the // `.svn/` directory, after SVN 1.7), while the `$project_root` might // be any subdirectory of the `$vcs_root`: it's the the directory // closest to the current directory which contains a `.arcconfig`. $project_root = $parent_path; $vcs_root = $parent_path; $vcs_type = $vcs; if ($vcs == 'svn') { // For Subversion, we'll look for a ".arcconfig" file here or in // any subdirectory, starting at the deepest subdirectory. $config_paths = array_slice($paths, $path_key); $config_paths = array_reverse($config_paths); } else { // For Git and Mercurial, we'll only look for ".arcconfig" right here. $config_paths = array($parent_path); } break; } } $console = PhutilConsole::getConsole(); $looked_in = array(); foreach ($config_paths as $config_path) { $config_file = $config_path.'/.arcconfig'; $looked_in[] = $config_file; if (Filesystem::pathExists($config_file)) { // We always need to examine the filesystem to look for `.arcconfig` // so we can set the project root correctly. We might or might not // actually read the file: if the caller passed in configuration data, // we'll ignore the actual file contents. $project_root = $config_path; if ($config === null) { $console->writeLog( "%s\n", pht( 'Working Copy: Reading %s from "%s".', '.arcconfig', $config_file)); $config_data = Filesystem::readFile($config_file); $config = self::parseRawConfigFile($config_data, $config_file); } break; } } if ($config === null) { if ($looked_in) { $console->writeLog( "%s\n", pht( 'Working Copy: Unable to find %s in any of these locations: %s.', '.arcconfig', implode(', ', $looked_in))); } else { $console->writeLog( "%s\n", pht( 'Working Copy: No candidate locations for %s from '. 'this working directory.', '.arcconfig')); } $config = array(); } if ($project_root === null) { // We aren't in a working directory at all. This is fine if we're // running a command like "arc help". If we're running something that // requires a working directory, an exception will be raised a little // later on. $console->writeLog( "%s\n", pht('Working Copy: Path "%s" is not in any working copy.', $path)); return new ArcanistWorkingCopyIdentity($path, $config); } $console->writeLog( "%s\n", pht( 'Working Copy: Path "%s" is part of `%s` working copy "%s".', $path, $vcs_type, $vcs_root)); $console->writeLog( "%s\n", pht( 'Working Copy: Project root is at "%s".', $project_root)); $identity = new ArcanistWorkingCopyIdentity($project_root, $config); $identity->localMetaDir = $vcs_root.'/.'.$vcs_type; $identity->localConfig = $identity->readLocalArcConfig(); $identity->vcsType = $vcs_type; $identity->vcsRoot = $vcs_root; return $identity; } public static function newFromRootAndConfigFile( $root, $config_raw, $from_where) { if ($config_raw === null) { $config = array(); } else { $config = self::parseRawConfigFile($config_raw, $from_where); } return self::newFromPathWithConfig($root, $config); } private static function parseRawConfigFile($raw_config, $from_where) { try { return phutil_json_decode($raw_config); } catch (PhutilJSONParserException $ex) { throw new PhutilProxyException( pht("Unable to parse '%s' file '%s'.", '.arcconfig', $from_where), $ex); } } private function __construct($root, array $config) { $this->projectRoot = $root; $this->projectConfig = $config; } - public function getProjectID() { - $project_id = $this->getProjectConfig('project.name'); - if ($project_id) { - return $project_id; - } - - // This is an older name for the setting. - return $this->getProjectConfig('project_id'); - } - public function getProjectRoot() { return $this->projectRoot; } public function getProjectPath($to_file) { return $this->projectRoot.'/'.$to_file; } public function getVCSType() { return $this->vcsType; } public function getVCSRoot() { return $this->vcsRoot; } /* -( Config )------------------------------------------------------------- */ public function readProjectConfig() { return $this->projectConfig; } /** * Read a configuration directive from project configuration. This reads ONLY * permanent project configuration (i.e., ".arcconfig"), not other * configuration sources. See @{method:getConfigFromAnySource} to read from * user configuration. * * @param key Key to read. * @param wild Default value if key is not found. * @return wild Value, or default value if not found. * * @task config */ public function getProjectConfig($key, $default = null) { $settings = new ArcanistSettings(); $pval = idx($this->projectConfig, $key); // Test for older names in the per-project config only, since // they've only been used there. if ($pval === null) { $legacy = $settings->getLegacyName($key); if ($legacy) { $pval = $this->getProjectConfig($legacy); } } if ($pval === null) { $pval = $default; } else { $pval = $settings->willReadValue($key, $pval); } return $pval; } /** * Read a configuration directive from local configuration. This * reads ONLY the per-working copy configuration, * i.e. .(git|hg|svn)/arc/config, and not other configuration * sources. See @{method:getConfigFromAnySource} to read from any * config source or @{method:getProjectConfig} to read permanent * project-level config. * * @task config */ public function getLocalConfig($key, $default = null) { return idx($this->localConfig, $key, $default); } public function readLocalArcConfig() { if (strlen($this->localMetaDir)) { $local_path = Filesystem::resolvePath('arc/config', $this->localMetaDir); $console = PhutilConsole::getConsole(); if (Filesystem::pathExists($local_path)) { $console->writeLog( "%s\n", pht( 'Config: Reading local configuration file "%s"...', $local_path)); try { $json = Filesystem::readFile($local_path); return phutil_json_decode($json); } catch (PhutilJSONParserException $ex) { throw new PhutilProxyException( pht("Failed to parse '%s' as JSON.", $local_path), $ex); } } else { $console->writeLog( "%s\n", pht( 'Config: Did not find local configuration at "%s".', $local_path)); } } return array(); } public function writeLocalArcConfig(array $config) { $json_encoder = new PhutilJSON(); $json = $json_encoder->encodeFormatted($config); $dir = $this->localMetaDir; if (!strlen($dir)) { throw new Exception(pht('No working copy to write config into!')); } $local_dir = $dir.DIRECTORY_SEPARATOR.'arc'; if (!Filesystem::pathExists($local_dir)) { Filesystem::createDirectory($local_dir, 0755); } $config_file = $local_dir.DIRECTORY_SEPARATOR.'config'; Filesystem::writeFile($config_file, $json); } }