repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/conduit/DiffusionSearchQueryConduitAPIMethod.php | src/applications/diffusion/conduit/DiffusionSearchQueryConduitAPIMethod.php | <?php
final class DiffusionSearchQueryConduitAPIMethod
extends DiffusionQueryConduitAPIMethod {
public function getAPIMethodName() {
return 'diffusion.searchquery';
}
public function getMethodDescription() {
return pht('Search (grep) a repository at a specific path and commit.');
}
protected function defineReturnType() {
return 'array';
}
protected function defineCustomParamTypes() {
return array(
'path' => 'required string',
'commit' => 'optional string',
'grep' => 'required string',
'limit' => 'optional int',
'offset' => 'optional int',
);
}
protected function getResult(ConduitAPIRequest $request) {
try {
$results = parent::getResult($request);
} catch (CommandException $ex) {
$err = $ex->getError();
if ($err === 1) {
// `git grep` and `hg grep` exit with 1 if there are no matches;
// assume we just didn't get any hits.
return array();
}
throw $ex;
}
$offset = $request->getValue('offset');
$results = array_slice($results, $offset);
return $results;
}
protected function getGitResult(ConduitAPIRequest $request) {
$drequest = $this->getDiffusionRequest();
$path = $drequest->getPath();
$grep = $request->getValue('grep');
$repository = $drequest->getRepository();
$limit = $request->getValue('limit');
$offset = $request->getValue('offset');
// Starting with Git 2.16.0, Git assumes passing an empty argument is
// an error and recommends you pass "." instead.
if (!strlen($path)) {
$path = '.';
}
$results = array();
$future = $repository->getLocalCommandFuture(
// NOTE: --perl-regexp is available only with libpcre compiled in.
'grep --extended-regexp --null -n --no-color -f - %s -- %s',
gitsprintf('%s', $drequest->getStableCommit()),
$path);
// NOTE: We're writing the pattern on stdin to avoid issues with UTF8
// being mangled by the shell. See T12807.
$future->write($grep);
$binary_pattern = '/Binary file [^:]*:(.+) matches/';
$lines = new LinesOfALargeExecFuture($future);
foreach ($lines as $line) {
$result = null;
if (preg_match('/[^:]*:(.+)\0(.+)\0(.*)/', $line, $result)) {
$results[] = array_slice($result, 1);
} else if (preg_match($binary_pattern, $line, $result)) {
list(, $path) = $result;
$results[] = array($path, null, pht('Binary file'));
} else {
$results[] = array(null, null, $line);
}
if (count($results) >= $offset + $limit) {
break;
}
}
unset($lines);
return $results;
}
protected function getMercurialResult(ConduitAPIRequest $request) {
$drequest = $this->getDiffusionRequest();
$path = $drequest->getPath();
$grep = $request->getValue('grep');
$repository = $drequest->getRepository();
$limit = $request->getValue('limit');
$offset = $request->getValue('offset');
$results = array();
$future = $repository->getLocalCommandFuture(
'grep --rev %s --print0 --line-number -- %s %s',
hgsprintf('ancestors(%s)', $drequest->getStableCommit()),
$grep,
$path);
$lines = id(new LinesOfALargeExecFuture($future))->setDelimiter("\0");
$parts = array();
foreach ($lines as $line) {
$parts[] = $line;
if (count($parts) == 4) {
list($path, $char_offset, $line, $string) = $parts;
$results[] = array($path, $line, $string);
if (count($results) >= $offset + $limit) {
break;
}
$parts = array();
}
}
unset($lines);
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/conduit/DiffusionCommitEditConduitAPIMethod.php | src/applications/diffusion/conduit/DiffusionCommitEditConduitAPIMethod.php | <?php
final class DiffusionCommitEditConduitAPIMethod
extends PhabricatorEditEngineAPIMethod {
public function getAPIMethodName() {
return 'diffusion.commit.edit';
}
public function newEditEngine() {
return new DiffusionCommitEditEngine();
}
public function getMethodSummary() {
return pht(
'Apply transactions to edit an existing commit. This method can not '.
'create new commits.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/conduit/DiffusionBranchQueryConduitAPIMethod.php | src/applications/diffusion/conduit/DiffusionBranchQueryConduitAPIMethod.php | <?php
final class DiffusionBranchQueryConduitAPIMethod
extends DiffusionQueryConduitAPIMethod {
public function getAPIMethodName() {
return 'diffusion.branchquery';
}
public function getMethodDescription() {
return pht('Determine what branches exist for a repository.');
}
protected function defineReturnType() {
return 'list<dict>';
}
protected function defineCustomParamTypes() {
return array(
'closed' => 'optional bool',
'limit' => 'optional int',
'offset' => 'optional int',
'contains' => 'optional string',
'patterns' => 'optional list<string>',
);
}
protected function getGitResult(ConduitAPIRequest $request) {
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
$contains = $request->getValue('contains');
if ($contains !== null && strlen($contains)) {
// See PHI958 (and, earlier, PHI720). If "patterns" are provided, pass
// them to "git branch ..." to let callers test for reachability from
// particular branch heads.
$patterns_argv = $request->getValue('patterns', array());
PhutilTypeSpec::checkMap(
array(
'patterns' => $patterns_argv,
),
array(
'patterns' => 'list<string>',
));
// NOTE: We can't use DiffusionLowLevelGitRefQuery here because
// `git for-each-ref` does not support `--contains`.
list($stdout) = $repository->execxLocalCommand(
'branch --verbose --no-abbrev --contains %s -- %Ls',
$contains,
$patterns_argv);
$ref_map = DiffusionGitBranch::parseLocalBranchOutput(
$stdout);
$refs = array();
foreach ($ref_map as $ref => $commit) {
$refs[] = id(new DiffusionRepositoryRef())
->setShortName($ref)
->setCommitIdentifier($commit);
}
} else {
$refs = id(new DiffusionLowLevelGitRefQuery())
->setRepository($repository)
->withRefTypes(
array(
PhabricatorRepositoryRefCursor::TYPE_BRANCH,
))
->execute();
}
return $this->processBranchRefs($request, $refs);
}
protected function getMercurialResult(ConduitAPIRequest $request) {
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
$query = id(new DiffusionLowLevelMercurialBranchesQuery())
->setRepository($repository);
$contains = $request->getValue('contains');
if ($contains !== null && strlen($contains)) {
$query->withContainsCommit($contains);
}
$refs = $query->execute();
return $this->processBranchRefs($request, $refs);
}
protected function getSVNResult(ConduitAPIRequest $request) {
// Since SVN doesn't have meaningful branches, just return nothing for all
// queries.
return array();
}
private function processBranchRefs(ConduitAPIRequest $request, array $refs) {
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
$offset = $request->getValue('offset');
$limit = $request->getValue('limit');
foreach ($refs as $key => $ref) {
if (!$repository->shouldTrackBranch($ref->getShortName())) {
unset($refs[$key]);
}
}
$with_closed = $request->getValue('closed');
if ($with_closed !== null) {
foreach ($refs as $key => $ref) {
$fields = $ref->getRawFields();
if (idx($fields, 'closed') != $with_closed) {
unset($refs[$key]);
}
}
}
// NOTE: We can't apply the offset or limit until here, because we may have
// filtered untrackable branches out of the result set.
if ($offset) {
$refs = array_slice($refs, $offset);
}
if ($limit) {
$refs = array_slice($refs, 0, $limit);
}
$refs = array_values($refs);
return mpull($refs, 'toDictionary');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/conduit/DiffusionMergedCommitsQueryConduitAPIMethod.php | src/applications/diffusion/conduit/DiffusionMergedCommitsQueryConduitAPIMethod.php | <?php
final class DiffusionMergedCommitsQueryConduitAPIMethod
extends DiffusionQueryConduitAPIMethod {
public function getAPIMethodName() {
return 'diffusion.mergedcommitsquery';
}
public function getMethodDescription() {
return pht(
'Merged commit information for a specific commit in a repository.');
}
protected function defineReturnType() {
return 'array';
}
protected function defineCustomParamTypes() {
return array(
'commit' => 'required string',
'limit' => 'optional int',
);
}
private function getLimit(ConduitAPIRequest $request) {
// TODO: Paginate this sensibly at some point.
return $request->getValue('limit', 4096);
}
protected function getGitResult(ConduitAPIRequest $request) {
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
$commit = $request->getValue('commit');
$limit = $this->getLimit($request);
list($parents) = $repository->execxLocalCommand(
'log -n 1 %s %s --',
'--format=%P',
gitsprintf('%s', $commit));
$parents = preg_split('/\s+/', trim($parents));
if (count($parents) < 2) {
// This is not a merge commit, so it doesn't merge anything.
return array();
}
// Get all of the commits which are not reachable from the first parent.
// These are the commits this change merges.
$first_parent = head($parents);
list($logs) = $repository->execxLocalCommand(
'log -n %d %s %s %s --',
// NOTE: "+ 1" accounts for the merge commit itself.
$limit + 1,
'--format=%H',
gitsprintf('%s', $commit),
gitsprintf('%s', '^'.$first_parent));
$hashes = explode("\n", trim($logs));
// Remove the merge commit.
$hashes = array_diff($hashes, array($commit));
$history = DiffusionQuery::loadHistoryForCommitIdentifiers(
$hashes,
$drequest);
return mpull($history, 'toDictionary');
}
protected function getMercurialResult(ConduitAPIRequest $request) {
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
$commit = $request->getValue('commit');
$limit = $this->getLimit($request);
list($parents) = $repository->execxLocalCommand(
'parents --template=%s --rev %s',
'{node}\\n',
hgsprintf('%s', $commit));
$parents = explode("\n", trim($parents));
if (count($parents) < 2) {
// Not a merge commit.
return array();
}
// NOTE: In Git, the first parent is the "mainline". In Mercurial, the
// second parent is the "mainline" (the way 'git merge' and 'hg merge'
// work is also reversed).
$last_parent = last($parents);
list($logs) = $repository->execxLocalCommand(
'log --template=%s --follow --limit %d --rev %s:0 --prune %s --',
'{node}\\n',
$limit + 1,
$commit,
$last_parent);
$hashes = explode("\n", trim($logs));
// Remove the merge commit.
$hashes = array_diff($hashes, array($commit));
$history = DiffusionQuery::loadHistoryForCommitIdentifiers(
$hashes,
$drequest);
return mpull($history, 'toDictionary');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/conduit/DiffusionDiffQueryConduitAPIMethod.php | src/applications/diffusion/conduit/DiffusionDiffQueryConduitAPIMethod.php | <?php
final class DiffusionDiffQueryConduitAPIMethod
extends DiffusionQueryConduitAPIMethod {
private $effectiveCommit;
public function getAPIMethodName() {
return 'diffusion.diffquery';
}
public function getMethodDescription() {
return pht(
'Get diff information from a repository for a specific path at an '.
'(optional) commit.');
}
protected function defineReturnType() {
return 'array';
}
protected function defineCustomParamTypes() {
return array(
'path' => 'required string',
'commit' => 'optional string',
);
}
protected function getResult(ConduitAPIRequest $request) {
$result = parent::getResult($request);
return array(
'changes' => mpull($result, 'toDictionary'),
'effectiveCommit' => $this->getEffectiveCommit($request),
);
}
protected function getGitResult(ConduitAPIRequest $request) {
return $this->getGitOrMercurialResult($request);
}
protected function getMercurialResult(ConduitAPIRequest $request) {
return $this->getGitOrMercurialResult($request);
}
/**
* NOTE: We have to work particularly hard for SVN as compared to other VCS.
* That's okay but means this shares little code with the other VCS.
*/
protected function getSVNResult(ConduitAPIRequest $request) {
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
$effective_commit = $this->getEffectiveCommit($request);
if (!$effective_commit) {
return $this->getEmptyResult();
}
$drequest = clone $drequest;
$drequest->updateSymbolicCommit($effective_commit);
$path_change_query = DiffusionPathChangeQuery::newFromDiffusionRequest(
$drequest);
$path_changes = $path_change_query->loadChanges();
$path = null;
foreach ($path_changes as $change) {
if ($change->getPath() == $drequest->getPath()) {
$path = $change;
}
}
if (!$path) {
return $this->getEmptyResult();
}
$change_type = $path->getChangeType();
switch ($change_type) {
case DifferentialChangeType::TYPE_MULTICOPY:
case DifferentialChangeType::TYPE_DELETE:
if ($path->getTargetPath()) {
$old = array(
$path->getTargetPath(),
$path->getTargetCommitIdentifier(),
);
} else {
$old = array($path->getPath(), $path->getCommitIdentifier() - 1);
}
$old_name = $path->getPath();
$new_name = '';
$new = null;
break;
case DifferentialChangeType::TYPE_ADD:
$old = null;
$new = array($path->getPath(), $path->getCommitIdentifier());
$old_name = '';
$new_name = $path->getPath();
break;
case DifferentialChangeType::TYPE_MOVE_HERE:
case DifferentialChangeType::TYPE_COPY_HERE:
$old = array(
$path->getTargetPath(),
$path->getTargetCommitIdentifier(),
);
$new = array($path->getPath(), $path->getCommitIdentifier());
$old_name = $path->getTargetPath();
$new_name = $path->getPath();
break;
case DifferentialChangeType::TYPE_MOVE_AWAY:
$old = array(
$path->getPath(),
$path->getCommitIdentifier() - 1,
);
$old_name = $path->getPath();
$new_name = null;
$new = null;
break;
default:
$old = array($path->getPath(), $path->getCommitIdentifier() - 1);
$new = array($path->getPath(), $path->getCommitIdentifier());
$old_name = $path->getPath();
$new_name = $path->getPath();
break;
}
$futures = array(
'old' => $this->buildSVNContentFuture($old),
'new' => $this->buildSVNContentFuture($new),
);
$futures = array_filter($futures);
foreach (new FutureIterator($futures) as $key => $future) {
$stdout = '';
try {
list($stdout) = $future->resolvex();
} catch (CommandException $e) {
if ($path->getFileType() != DifferentialChangeType::FILE_DIRECTORY) {
throw $e;
}
}
$futures[$key] = $stdout;
}
$old_data = idx($futures, 'old', '');
$new_data = idx($futures, 'new', '');
$engine = new PhabricatorDifferenceEngine();
$engine->setOldName($old_name);
$engine->setNewName($new_name);
$raw_diff = $engine->generateRawDiffFromFileContent($old_data, $new_data);
$arcanist_changes = DiffusionPathChange::convertToArcanistChanges(
$path_changes);
$parser = $this->getDefaultParser();
$parser->setChanges($arcanist_changes);
$parser->forcePath($path->getPath());
$changes = $parser->parseDiff($raw_diff);
$change = $changes[$path->getPath()];
return array($change);
}
private function getEffectiveCommit(ConduitAPIRequest $request) {
if ($this->effectiveCommit === null) {
$drequest = $this->getDiffusionRequest();
$path = $drequest->getPath();
$result = DiffusionQuery::callConduitWithDiffusionRequest(
$request->getUser(),
$drequest,
'diffusion.lastmodifiedquery',
array(
'paths' => array($path => $drequest->getStableCommit()),
));
$this->effectiveCommit = idx($result, $path);
}
return $this->effectiveCommit;
}
private function buildSVNContentFuture($spec) {
if (!$spec) {
return null;
}
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
list($ref, $rev) = $spec;
return $repository->getRemoteCommandFuture(
'cat %s',
$repository->getSubversionPathURI($ref, $rev));
}
private function getGitOrMercurialResult(ConduitAPIRequest $request) {
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
$effective_commit = $this->getEffectiveCommit($request);
if (!$effective_commit) {
return $this->getEmptyResult();
}
$raw_query = DiffusionRawDiffQuery::newFromDiffusionRequest($drequest)
->setAnchorCommit($effective_commit);
$raw_diff = $raw_query->executeInline();
if (!$raw_diff) {
return $this->getEmptyResult();
}
$parser = $this->getDefaultParser();
$changes = $parser->parseDiff($raw_diff);
return $changes;
}
private function getDefaultParser() {
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
$parser = new ArcanistDiffParser();
$try_encoding = $repository->getDetail('encoding');
if ($try_encoding) {
$parser->setTryEncoding($try_encoding);
}
$parser->setDetectBinaryFiles(true);
return $parser;
}
private function getEmptyResult() {
return array();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/conduit/DiffusionURIEditConduitAPIMethod.php | src/applications/diffusion/conduit/DiffusionURIEditConduitAPIMethod.php | <?php
final class DiffusionURIEditConduitAPIMethod
extends PhabricatorEditEngineAPIMethod {
public function getAPIMethodName() {
return 'diffusion.uri.edit';
}
public function newEditEngine() {
return new DiffusionURIEditEngine();
}
public function getMethodSummary() {
return pht(
'Apply transactions to create a new repository URI or edit an existing '.
'one.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/conduit/DiffusionLastModifiedQueryConduitAPIMethod.php | src/applications/diffusion/conduit/DiffusionLastModifiedQueryConduitAPIMethod.php | <?php
final class DiffusionLastModifiedQueryConduitAPIMethod
extends DiffusionQueryConduitAPIMethod {
public function getAPIMethodName() {
return 'diffusion.lastmodifiedquery';
}
public function getMethodDescription() {
return pht('Get the commits at which paths were last modified.');
}
protected function defineReturnType() {
return 'map<string, string>';
}
protected function defineCustomParamTypes() {
return array(
'paths' => 'required map<string, string>',
);
}
protected function getGitResult(ConduitAPIRequest $request) {
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
$paths = $request->getValue('paths');
$results = $this->loadCommitsFromCache($paths);
foreach ($paths as $path => $commit) {
if (array_key_exists($path, $results)) {
continue;
}
list($hash) = $repository->execxLocalCommand(
'log -n1 %s %s -- %s',
'--format=%H',
gitsprintf('%s', $commit),
$path);
$results[$path] = trim($hash);
}
return $results;
}
protected function getSVNResult(ConduitAPIRequest $request) {
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
$results = array();
foreach ($request->getValue('paths') as $path => $commit) {
$history_result = DiffusionQuery::callConduitWithDiffusionRequest(
$request->getUser(),
$drequest,
'diffusion.historyquery',
array(
'commit' => $commit,
'path' => $path,
'limit' => 1,
'offset' => 0,
'needDirectChanges' => true,
'needChildChanges' => true,
));
$history_array = DiffusionPathChange::newFromConduit(
$history_result['pathChanges']);
if ($history_array) {
$results[$path] = head($history_array)
->getCommit()
->getCommitIdentifier();
}
}
return $results;
}
protected function getMercurialResult(ConduitAPIRequest $request) {
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
$paths = $request->getValue('paths');
$results = $this->loadCommitsFromCache($paths);
foreach ($paths as $path => $commit) {
if (array_key_exists($path, $results)) {
continue;
}
list($hash) = $repository->execxLocalCommand(
'log --template %s --limit 1 --removed --rev %s -- %s',
'{node}',
hgsprintf('reverse(ancestors(%s))', $commit),
nonempty(ltrim($path, '/'), '.'));
$results[$path] = trim($hash);
}
return $results;
}
private function loadCommitsFromCache(array $map) {
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
$path_map = id(new DiffusionPathIDQuery(array_keys($map)))
->loadPathIDs();
$commit_query = id(new DiffusionCommitQuery())
->setViewer($drequest->getUser())
->withRepository($repository)
->withIdentifiers(array_values($map));
$commit_query->execute();
$commit_map = $commit_query->getIdentifierMap();
$commit_map = mpull($commit_map, 'getID');
$graph_cache = new PhabricatorRepositoryGraphCache();
$results = array();
// Spend no more than this many total seconds trying to satisfy queries
// via the graph cache.
$remaining_time = 10.0;
foreach ($map as $path => $commit) {
$path_id = idx($path_map, $path);
if (!$path_id) {
continue;
}
$commit_id = idx($commit_map, $commit);
if (!$commit_id) {
continue;
}
$t_start = microtime(true);
$cache_result = $graph_cache->loadLastModifiedCommitID(
$commit_id,
$path_id,
$remaining_time);
$t_end = microtime(true);
if ($cache_result !== false) {
$results[$path] = $cache_result;
}
$remaining_time -= ($t_end - $t_start);
if ($remaining_time <= 0) {
break;
}
}
if ($results) {
$commits = id(new DiffusionCommitQuery())
->setViewer($drequest->getUser())
->withRepository($repository)
->withIDs($results)
->execute();
foreach ($results as $path => $id) {
$commit = idx($commits, $id);
if ($commit) {
$results[$path] = $commit->getCommitIdentifier();
} else {
unset($results[$path]);
}
}
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/conduit/DiffusionUpdateCoverageConduitAPIMethod.php | src/applications/diffusion/conduit/DiffusionUpdateCoverageConduitAPIMethod.php | <?php
final class DiffusionUpdateCoverageConduitAPIMethod
extends DiffusionConduitAPIMethod {
public function getAPIMethodName() {
return 'diffusion.updatecoverage';
}
public function getMethodStatus() {
return self::METHOD_STATUS_UNSTABLE;
}
public function getMethodDescription() {
return pht('Publish coverage information for a repository.');
}
protected function defineReturnType() {
return 'void';
}
protected function defineParamTypes() {
$modes = array(
'overwrite',
'update',
);
return array(
'repositoryPHID' => 'required phid',
'branch' => 'required string',
'commit' => 'required string',
'coverage' => 'required map<string, string>',
'mode' => 'optional '.$this->formatStringConstants($modes),
);
}
protected function execute(ConduitAPIRequest $request) {
$viewer = $request->getUser();
$repository_phid = $request->getValue('repositoryPHID');
$repository = id(new PhabricatorRepositoryQuery())
->setViewer($viewer)
->withPHIDs(array($repository_phid))
->executeOne();
if (!$repository) {
throw new Exception(
pht('No repository exists with PHID "%s".', $repository_phid));
}
$commit_name = $request->getValue('commit');
$commit = id(new DiffusionCommitQuery())
->setViewer($viewer)
->withRepository($repository)
->withIdentifiers(array($commit_name))
->executeOne();
if (!$commit) {
throw new Exception(
pht('No commit exists with identifier "%s".', $commit_name));
}
$branch = PhabricatorRepositoryBranch::loadOrCreateBranch(
$repository->getID(),
$request->getValue('branch'));
$coverage = $request->getValue('coverage');
$path_map = id(new DiffusionPathIDQuery(array_keys($coverage)))
->loadPathIDs();
$conn = $repository->establishConnection('w');
$sql = array();
foreach ($coverage as $path => $coverage_info) {
$sql[] = qsprintf(
$conn,
'(%d, %d, %d, %s)',
$branch->getID(),
$path_map[$path],
$commit->getID(),
$coverage_info);
}
$table_name = 'repository_coverage';
$conn->openTransaction();
$mode = $request->getValue('mode');
switch ($mode) {
case '':
case 'overwrite':
// sets the coverage for the whole branch, deleting all previous
// coverage information
queryfx(
$conn,
'DELETE FROM %T WHERE branchID = %d',
$table_name,
$branch->getID());
break;
case 'update':
// sets the coverage for the provided files on the specified commit
break;
default:
$conn->killTransaction();
throw new Exception(pht('Invalid mode "%s".', $mode));
}
foreach (PhabricatorLiskDAO::chunkSQL($sql) as $chunk) {
queryfx(
$conn,
'INSERT INTO %T (branchID, pathID, commitID, coverage) VALUES %LQ'.
' ON DUPLICATE KEY UPDATE coverage = VALUES(coverage)',
$table_name,
$chunk);
}
$conn->saveTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/data/DiffusionCommitRef.php | src/applications/diffusion/data/DiffusionCommitRef.php | <?php
final class DiffusionCommitRef extends Phobject {
private $message;
private $authorEpoch;
private $authorName;
private $authorEmail;
private $committerName;
private $committerEmail;
private $hashes = array();
public function newDictionary() {
$hashes = $this->getHashes();
$hashes = mpull($hashes, 'newDictionary');
$hashes = array_values($hashes);
return array(
'authorEpoch' => $this->authorEpoch,
'authorName' => $this->authorName,
'authorEmail' => $this->authorEmail,
'committerName' => $this->committerName,
'committerEmail' => $this->committerEmail,
'message' => $this->message,
'hashes' => $hashes,
);
}
public static function newFromDictionary(array $map) {
$hashes = idx($map, 'hashes', array());
foreach ($hashes as $key => $hash_map) {
$hashes[$key] = DiffusionCommitHash::newFromDictionary($hash_map);
}
$hashes = array_values($hashes);
$author_epoch = idx($map, 'authorEpoch');
$author_name = idx($map, 'authorName');
$author_email = idx($map, 'authorEmail');
$committer_name = idx($map, 'committerName');
$committer_email = idx($map, 'committerEmail');
$message = idx($map, 'message');
return id(new self())
->setAuthorEpoch($author_epoch)
->setAuthorName($author_name)
->setAuthorEmail($author_email)
->setCommitterName($committer_name)
->setCommitterEmail($committer_email)
->setMessage($message)
->setHashes($hashes);
}
public function setHashes(array $hashes) {
assert_instances_of($hashes, 'DiffusionCommitHash');
$this->hashes = $hashes;
return $this;
}
public function getHashes() {
return $this->hashes;
}
public function setAuthorEpoch($author_epoch) {
$this->authorEpoch = $author_epoch;
return $this;
}
public function getAuthorEpoch() {
return $this->authorEpoch;
}
public function setCommitterEmail($committer_email) {
$this->committerEmail = $committer_email;
return $this;
}
public function getCommitterEmail() {
return $this->committerEmail;
}
public function setCommitterName($committer_name) {
$this->committerName = $committer_name;
return $this;
}
public function getCommitterName() {
return $this->committerName;
}
public function setAuthorEmail($author_email) {
$this->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 setMessage($message) {
$this->message = $message;
return $this;
}
public function getMessage() {
return $this->message;
}
public function getAuthor() {
return $this->formatUser($this->authorName, $this->authorEmail);
}
public function getCommitter() {
return $this->formatUser($this->committerName, $this->committerEmail);
}
public function getSummary() {
return PhabricatorRepositoryCommitData::summarizeCommitMessage(
$this->getMessage());
}
private function formatUser($name, $email) {
if ($name === null) {
$name = '';
}
if ($email === null) {
$email = '';
}
if (strlen($name) && strlen($email)) {
return "{$name} <{$email}>";
} else if (strlen($email)) {
return $email;
} else if (strlen($name)) {
return $name;
} else {
return null;
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/data/DiffusionRepositoryRef.php | src/applications/diffusion/data/DiffusionRepositoryRef.php | <?php
/**
* @task serialization Serializing Repository Refs
*/
final class DiffusionRepositoryRef extends Phobject {
private $shortName;
private $commitIdentifier;
private $refType;
private $rawFields = array();
public function setRawFields(array $raw_fields) {
$this->rawFields = $raw_fields;
return $this;
}
public function getRawFields() {
return $this->rawFields;
}
public function setCommitIdentifier($commit_identifier) {
$this->commitIdentifier = $commit_identifier;
return $this;
}
public function getCommitIdentifier() {
return $this->commitIdentifier;
}
public function setShortName($short_name) {
$this->shortName = $short_name;
return $this;
}
public function getShortName() {
return $this->shortName;
}
public function setRefType($ref_type) {
$this->refType = $ref_type;
return $this;
}
public function getRefType() {
return $this->refType;
}
public function isBranch() {
$type_branch = PhabricatorRepositoryRefCursor::TYPE_BRANCH;
return ($this->getRefType() === $type_branch);
}
public function isTag() {
$type_tag = PhabricatorRepositoryRefCursor::TYPE_TAG;
return ($this->getRefType() === $type_tag);
}
/* -( Serialization )------------------------------------------------------ */
public function toDictionary() {
return array(
'shortName' => $this->shortName,
'commitIdentifier' => $this->commitIdentifier,
'refType' => $this->refType,
'rawFields' => $this->rawFields,
);
}
public static function newFromDictionary(array $dict) {
return id(new DiffusionRepositoryRef())
->setShortName($dict['shortName'])
->setCommitIdentifier($dict['commitIdentifier'])
->setRefType($dict['refType'])
->setRawFields($dict['rawFields']);
}
public static function loadAllFromDictionaries(array $dictionaries) {
$refs = array();
foreach ($dictionaries as $dictionary) {
$refs[] = self::newFromDictionary($dictionary);
}
return $refs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/data/DiffusionRepositoryPath.php | src/applications/diffusion/data/DiffusionRepositoryPath.php | <?php
final class DiffusionRepositoryPath extends Phobject {
private $fullPath;
private $path;
private $hash;
private $fileType;
private $fileSize;
private $externalURI;
private $lastModifiedCommit;
private $lastCommitData;
public function setFullPath($full_path) {
$this->fullPath = $full_path;
return $this;
}
public function getFullPath() {
return $this->fullPath;
}
public function setPath($path) {
$this->path = $path;
return $this;
}
public function getPath() {
return $this->path;
}
public function setHash($hash) {
$this->hash = $hash;
return $this;
}
public function getHash() {
return $this->hash;
}
public function setLastModifiedCommit(
PhabricatorRepositoryCommit $commit) {
$this->lastModifiedCommit = $commit;
return $this;
}
public function getLastModifiedCommit() {
return $this->lastModifiedCommit;
}
public function setLastCommitData(
PhabricatorRepositoryCommitData $last_commit_data) {
$this->lastCommitData = $last_commit_data;
return $this;
}
public function getLastCommitData() {
return $this->lastCommitData;
}
public function setFileType($file_type) {
$this->fileType = $file_type;
return $this;
}
public function getFileType() {
return $this->fileType;
}
public function setFileSize($file_size) {
$this->fileSize = $file_size;
return $this;
}
public function getFileSize() {
return $this->fileSize;
}
public function setExternalURI($external_uri) {
$this->externalURI = $external_uri;
return $this;
}
public function getExternalURI() {
return $this->externalURI;
}
public function toDictionary() {
$last_modified_commit = $this->getLastModifiedCommit();
if ($last_modified_commit) {
$last_modified_commit = $last_modified_commit->toDictionary();
}
$last_commit_data = $this->getLastCommitData();
if ($last_commit_data) {
$last_commit_data = $last_commit_data->toDictionary();
}
return array(
'fullPath' => $this->getFullPath(),
'path' => $this->getPath(),
'hash' => $this->getHash(),
'fileType' => $this->getFileType(),
'fileSize' => $this->getFileSize(),
'externalURI' => $this->getExternalURI(),
'lastModifiedCommit' => $last_modified_commit,
'lastCommitData' => $last_commit_data,
);
}
public static function newFromDictionary(array $dict) {
$path = id(new DiffusionRepositoryPath())
->setFullPath($dict['fullPath'])
->setPath($dict['path'])
->setHash($dict['hash'])
->setFileType($dict['fileType'])
->setFileSize($dict['fileSize'])
->setExternalURI($dict['externalURI']);
if ($dict['lastModifiedCommit']) {
$last_modified_commit = PhabricatorRepositoryCommit::newFromDictionary(
$dict['lastModifiedCommit']);
$path->setLastModifiedCommit($last_modified_commit);
}
if ($dict['lastCommitData']) {
$last_commit_data = PhabricatorRepositoryCommitData::newFromDictionary(
$dict['lastCommitData']);
$path->setLastCommitData($last_commit_data);
}
return $path;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/data/DiffusionCommitHash.php | src/applications/diffusion/data/DiffusionCommitHash.php | <?php
final class DiffusionCommitHash extends Phobject {
private $hashType;
private $hashValue;
public function setHashValue($hash_value) {
$this->hashValue = $hash_value;
return $this;
}
public function getHashValue() {
return $this->hashValue;
}
public function setHashType($hash_type) {
$this->hashType = $hash_type;
return $this;
}
public function getHashType() {
return $this->hashType;
}
public static function convertArrayToObjects(array $hashes) {
$hash_objects = array();
foreach ($hashes as $hash) {
$type = $hash[0];
$hash = $hash[1];
$hash_objects[] = id(new DiffusionCommitHash())
->setHashType($type)
->setHashValue($hash);
}
return $hash_objects;
}
public static function newFromDictionary(array $map) {
$hash_type = idx($map, 'type');
$hash_value = idx($map, 'value');
return id(new self())
->setHashType($hash_type)
->setHashValue($hash_value);
}
public function newDictionary() {
return array(
'type' => $this->hashType,
'value' => $this->hashValue,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/data/DiffusionRepositoryTag.php | src/applications/diffusion/data/DiffusionRepositoryTag.php | <?php
final class DiffusionRepositoryTag extends Phobject {
private $author;
private $epoch;
private $commitIdentifier;
private $name;
private $description;
private $type;
private $message = false;
public function setType($type) {
$this->type = $type;
return $this;
}
public function getType() {
return $this->type;
}
public function setDescription($description) {
$this->description = $description;
return $this;
}
public function getDescription() {
return $this->description;
}
public function setName($name) {
$this->name = $name;
return $this;
}
public function getName() {
return $this->name;
}
public function setCommitIdentifier($commit_identifier) {
$this->commitIdentifier = $commit_identifier;
return $this;
}
public function getCommitIdentifier() {
return $this->commitIdentifier;
}
public function setEpoch($epoch) {
$this->epoch = $epoch;
return $this;
}
public function getEpoch() {
return $this->epoch;
}
public function setAuthor($author) {
$this->author = $author;
return $this;
}
public function getAuthor() {
return $this->author;
}
public function attachMessage($message) {
$this->message = $message;
return $this;
}
public function getMessage() {
if ($this->message === false) {
throw new Exception(pht('Message is not attached!'));
}
return $this->message;
}
public function toDictionary() {
$dict = array(
'author' => $this->getAuthor(),
'epoch' => $this->getEpoch(),
'commitIdentifier' => $this->getCommitIdentifier(),
'name' => $this->getName(),
'description' => $this->getDescription(),
'type' => $this->getType(),
);
if ($this->message !== false) {
$dict['message'] = $this->message;
}
return $dict;
}
public static function newFromConduit(array $dicts) {
$tags = array();
foreach ($dicts as $dict) {
$tag = id(new DiffusionRepositoryTag())
->setAuthor($dict['author'])
->setEpoch($dict['epoch'])
->setCommitIdentifier($dict['commitIdentifier'])
->setName($dict['name'])
->setDescription($dict['description'])
->setType($dict['type']);
if (array_key_exists('message', $dict)) {
$tag->attachMessage($dict['message']);
}
$tags[] = $tag;
}
return $tags;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/data/DiffusionBrowseResultSet.php | src/applications/diffusion/data/DiffusionBrowseResultSet.php | <?php
final class DiffusionBrowseResultSet extends Phobject {
const REASON_IS_FILE = 'is-file';
const REASON_IS_SUBMODULE = 'is-submodule';
const REASON_IS_DELETED = 'is-deleted';
const REASON_IS_NONEXISTENT = 'nonexistent';
const REASON_BAD_COMMIT = 'bad-commit';
const REASON_IS_EMPTY = 'empty';
const REASON_IS_UNTRACKED_PARENT = 'untracked-parent';
private $paths;
private $isValidResults;
private $reasonForEmptyResultSet;
private $existedAtCommit;
private $deletedAtCommit;
public function setPaths(array $paths) {
assert_instances_of($paths, 'DiffusionRepositoryPath');
$this->paths = $paths;
return $this;
}
public function getPaths() {
return $this->paths;
}
public function setIsValidResults($is_valid) {
$this->isValidResults = $is_valid;
return $this;
}
public function isValidResults() {
return $this->isValidResults;
}
public function setReasonForEmptyResultSet($reason) {
$this->reasonForEmptyResultSet = $reason;
return $this;
}
public function getReasonForEmptyResultSet() {
return $this->reasonForEmptyResultSet;
}
public function setExistedAtCommit($existed_at_commit) {
$this->existedAtCommit = $existed_at_commit;
return $this;
}
public function getExistedAtCommit() {
return $this->existedAtCommit;
}
public function setDeletedAtCommit($deleted_at_commit) {
$this->deletedAtCommit = $deleted_at_commit;
return $this;
}
public function getDeletedAtCommit() {
return $this->deletedAtCommit;
}
public function toDictionary() {
$paths = $this->getPathDicts();
return array(
'paths' => $paths,
'isValidResults' => $this->isValidResults(),
'reasonForEmptyResultSet' => $this->getReasonForEmptyResultSet(),
'existedAtCommit' => $this->getExistedAtCommit(),
'deletedAtCommit' => $this->getDeletedAtCommit(),
);
}
public function getPathDicts() {
$paths = $this->getPaths();
if ($paths) {
return mpull($paths, 'toDictionary');
}
return array();
}
/**
* Get the best README file in this result set, if one exists.
*
* Callers should normally use `diffusion.filecontentquery` to pull README
* content.
*
* @return string|null Full path to best README, or null if one does not
* exist.
*/
public function getReadmePath() {
$allowed_types = array(
ArcanistDiffChangeType::FILE_NORMAL => true,
ArcanistDiffChangeType::FILE_TEXT => true,
);
$candidates = array();
foreach ($this->getPaths() as $path_object) {
if (empty($allowed_types[$path_object->getFileType()])) {
// Skip directories, images, etc.
continue;
}
$local_path = $path_object->getPath();
if (!preg_match('/^readme(\.|$)/i', $local_path)) {
// Skip files not named "README".
continue;
}
$full_path = $path_object->getFullPath();
$candidates[$full_path] = self::getReadmePriority($local_path);
}
if (!$candidates) {
return null;
}
arsort($candidates);
return head_key($candidates);
}
/**
* Get the priority of a README file.
*
* When a directory contains several README files, this function scores them
* so the caller can select a preferred file. See @{method:getReadmePath}.
*
* @param string Local README path, like "README.txt".
* @return int Priority score, with higher being more preferred.
*/
public static function getReadmePriority($path) {
$path = phutil_utf8_strtolower($path);
if ($path == 'readme') {
return 90;
}
$ext = last(explode('.', $path));
switch ($ext) {
case 'remarkup':
return 100;
case 'rainbow':
return 80;
case 'md':
return 70;
case 'txt':
return 60;
default:
return 50;
}
}
public static function newFromConduit(array $data) {
$paths = array();
$path_dicts = $data['paths'];
foreach ($path_dicts as $dict) {
$paths[] = DiffusionRepositoryPath::newFromDictionary($dict);
}
return id(new DiffusionBrowseResultSet())
->setPaths($paths)
->setIsValidResults($data['isValidResults'])
->setReasonForEmptyResultSet($data['reasonForEmptyResultSet'])
->setExistedAtCommit($data['existedAtCommit'])
->setDeletedAtCommit($data['deletedAtCommit']);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/data/DiffusionGitBranch.php | src/applications/diffusion/data/DiffusionGitBranch.php | <?php
final class DiffusionGitBranch extends Phobject {
const DEFAULT_GIT_REMOTE = 'origin';
/**
* Parse the output of 'git branch -r --verbose --no-abbrev' or similar into
* a map. For instance:
*
* array(
* 'origin/master' => '99a9c082f9a1b68c7264e26b9e552484a5ae5f25',
* );
*
* If you specify $only_this_remote, branches will be filtered to only those
* on the given remote, **and the remote name will be stripped**. For example:
*
* array(
* 'master' => '99a9c082f9a1b68c7264e26b9e552484a5ae5f25',
* );
*
* @param string stdout of git branch command.
* @param string Filter branches to those on a specific remote.
* @return map Map of 'branch' or 'remote/branch' to hash at HEAD.
*/
public static function parseRemoteBranchOutput(
$stdout,
$only_this_remote = null) {
$map = array();
$lines = array_filter(explode("\n", $stdout));
foreach ($lines as $line) {
$matches = null;
if (preg_match('/^ (\S+)\s+-> (\S+)$/', $line, $matches)) {
// This is a line like:
//
// origin/HEAD -> origin/master
//
// ...which we don't currently do anything interesting with, although
// in theory we could use it to automatically choose the default
// branch.
continue;
}
if (!preg_match('/^ *(\S+)\s+([a-z0-9]{40})/', $line, $matches)) {
throw new Exception(
pht(
'Failed to parse %s!',
$line));
}
$remote_branch = $matches[1];
$branch_head = $matches[2];
if (strpos($remote_branch, 'HEAD') !== false) {
// let's assume that no one will call their remote or branch HEAD
continue;
}
if ($only_this_remote) {
$matches = null;
if (!preg_match('#^([^/]+)/(.*)$#', $remote_branch, $matches)) {
throw new Exception(
pht(
"Failed to parse remote branch '%s'!",
$remote_branch));
}
$remote_name = $matches[1];
$branch_name = $matches[2];
if ($remote_name != $only_this_remote) {
continue;
}
$map[$branch_name] = $branch_head;
} else {
$map[$remote_branch] = $branch_head;
}
}
return $map;
}
/**
* As above, but with no `-r`. Used for bare repositories.
*/
public static function parseLocalBranchOutput($stdout) {
$map = array();
$lines = array_filter(explode("\n", $stdout));
$regex = '/^[* ]*(\(no branch\)|\S+)\s+([a-z0-9]{40})/';
foreach ($lines as $line) {
$matches = null;
if (!preg_match($regex, $line, $matches)) {
throw new Exception(
pht(
'Failed to parse %s!',
$line));
}
$branch = $matches[1];
$branch_head = $matches[2];
if ($branch == '(no branch)') {
continue;
}
$map[$branch] = $branch_head;
}
return $map;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/data/DiffusionLocalRepositoryFilter.php | src/applications/diffusion/data/DiffusionLocalRepositoryFilter.php | <?php
/**
* Filter a list of repositories, removing repositories not local to the
* current device.
*/
final class DiffusionLocalRepositoryFilter extends Phobject {
private $viewer;
private $device;
private $repositories;
private $rejectionReasons;
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setDevice(AlmanacDevice $device = null) {
$this->device = $device;
return $this;
}
public function getDevice() {
return $this->device;
}
public function setRepositories(array $repositories) {
$this->repositories = $repositories;
return $this;
}
public function getRepositories() {
return $this->repositories;
}
public function setRejectionReasons($rejection_reasons) {
$this->rejectionReasons = $rejection_reasons;
return $this;
}
public function getRejectionReasons() {
return $this->rejectionReasons;
}
public function execute() {
$repositories = $this->getRepositories();
$device = $this->getDevice();
$viewer = $this->getViewer();
$reasons = array();
$service_phids = array();
foreach ($repositories as $key => $repository) {
$service_phid = $repository->getAlmanacServicePHID();
// If the repository is bound to a service but this host is not a
// recognized device, or vice versa, don't pull the repository unless
// we're sure it's safe because the repository has no local working copy
// or the working copy already exists on disk.
$is_cluster_repo = (bool)$service_phid;
$is_cluster_device = (bool)$device;
if ($is_cluster_repo != $is_cluster_device) {
$has_working_copy = $repository->hasLocalWorkingCopy();
if ($is_cluster_device) {
if (!$has_working_copy) {
$reasons[$key] = pht(
'Repository "%s" is not a cluster repository, but the current '.
'host is a cluster device ("%s") and updating this repository '.
'would create a new local working copy. This is dangerous, so '.
'the repository will not be updated on this host.',
$repository->getDisplayName(),
$device->getName());
unset($repositories[$key]);
continue;
}
} else {
$reasons[$key] = pht(
'Repository "%s" is a cluster repository, but the current host '.
'is not a cluster device (it has no device ID), so the '.
'repository will not be updated on this host.',
$repository->getDisplayName());
unset($repositories[$key]);
continue;
}
}
if ($service_phid) {
$service_phids[] = $service_phid;
}
}
if (!$device) {
$this->rejectionReasons = $reasons;
return $repositories;
}
$device_phid = $device->getPHID();
if ($service_phids) {
// We could include `withDevicePHIDs()` here to pull a smaller result
// set, but we can provide more helpful diagnostic messages below if
// we fetch a little more data.
$services = id(new AlmanacServiceQuery())
->setViewer($viewer)
->withPHIDs($service_phids)
->withServiceTypes(
array(
AlmanacClusterRepositoryServiceType::SERVICETYPE,
))
->needBindings(true)
->execute();
$services = mpull($services, null, 'getPHID');
} else {
$services = array();
}
foreach ($repositories as $key => $repository) {
$service_phid = $repository->getAlmanacServicePHID();
if (!$service_phid) {
continue;
}
$service = idx($services, $service_phid);
if (!$service) {
$reasons[$key] = pht(
'Repository "%s" is on cluster service "%s", but that service '.
'could not be loaded, so the repository will not be updated on '.
'this host.',
$repository->getDisplayName(),
$service_phid);
unset($repositories[$key]);
continue;
}
$bindings = $service->getBindings();
$bindings = mgroup($bindings, 'getDevicePHID');
$bindings = idx($bindings, $device_phid);
if (!$bindings) {
$reasons[$key] = pht(
'Repository "%s" is on cluster service "%s", but that service is '.
'not bound to this device ("%s"), so the repository will not be '.
'updated on this host.',
$repository->getDisplayName(),
$service->getName(),
$device->getName());
unset($repositories[$key]);
continue;
}
$all_disabled = true;
foreach ($bindings as $binding) {
if (!$binding->getIsDisabled()) {
$all_disabled = false;
break;
}
}
if ($all_disabled) {
$reasons[$key] = pht(
'Repository "%s" is on cluster service "%s", but the binding '.
'between that service and this device ("%s") is disabled, so it '.
'can not be updated on this host.',
$repository->getDisplayName(),
$service->getName(),
$device->getName());
unset($repositories[$key]);
continue;
}
// We have a valid service that is actively bound to the current host
// device, so we're good to go.
}
$this->rejectionReasons = $reasons;
return $repositories;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/data/DiffusionPathChange.php | src/applications/diffusion/data/DiffusionPathChange.php | <?php
final class DiffusionPathChange extends Phobject {
private $path;
private $commitIdentifier;
private $commit;
private $commitData;
private $changeType;
private $fileType;
private $targetPath;
private $targetCommitIdentifier;
private $awayPaths = array();
public function setPath($path) {
$this->path = $path;
return $this;
}
public function getPath() {
return $this->path;
}
public function setChangeType($change_type) {
$this->changeType = $change_type;
return $this;
}
public function getChangeType() {
return $this->changeType;
}
public function setFileType($file_type) {
$this->fileType = $file_type;
return $this;
}
public function getFileType() {
return $this->fileType;
}
public function setTargetPath($target_path) {
$this->targetPath = $target_path;
return $this;
}
public function getTargetPath() {
return $this->targetPath;
}
public function setAwayPaths(array $away_paths) {
$this->awayPaths = $away_paths;
return $this;
}
public function getAwayPaths() {
return $this->awayPaths;
}
public function setCommitIdentifier($commit) {
$this->commitIdentifier = $commit;
return $this;
}
public function getCommitIdentifier() {
return $this->commitIdentifier;
}
public function setTargetCommitIdentifier($target_commit_identifier) {
$this->targetCommitIdentifier = $target_commit_identifier;
return $this;
}
public function getTargetCommitIdentifier() {
return $this->targetCommitIdentifier;
}
public function setCommit($commit) {
$this->commit = $commit;
return $this;
}
public function getCommit() {
return $this->commit;
}
public function setCommitData($commit_data) {
$this->commitData = $commit_data;
return $this;
}
public function getCommitData() {
return $this->commitData;
}
public function getEpoch() {
if ($this->getCommit()) {
return $this->getCommit()->getEpoch();
}
return null;
}
public function getAuthorName() {
if ($this->getCommitData()) {
return $this->getCommitData()->getAuthorString();
}
return null;
}
public function getSummary() {
if (!$this->getCommitData()) {
return null;
}
return $this->getCommitData()->getSummary();
}
public static function convertToArcanistChanges(array $changes) {
assert_instances_of($changes, __CLASS__);
$direct = array();
$result = array();
foreach ($changes as $path) {
$change = new ArcanistDiffChange();
$change->setCurrentPath($path->getPath());
$direct[] = $path->getPath();
$change->setType($path->getChangeType());
$file_type = $path->getFileType();
if ($file_type == DifferentialChangeType::FILE_NORMAL) {
$file_type = DifferentialChangeType::FILE_TEXT;
}
$change->setFileType($file_type);
$change->setOldPath($path->getTargetPath());
foreach ($path->getAwayPaths() as $away_path) {
$change->addAwayPath($away_path);
}
$result[$path->getPath()] = $change;
}
return array_select_keys($result, $direct);
}
public static function convertToDifferentialChangesets(
PhabricatorUser $user,
array $changes) {
assert_instances_of($changes, __CLASS__);
$arcanist_changes = self::convertToArcanistChanges($changes);
$diff = DifferentialDiff::newEphemeralFromRawChanges(
$arcanist_changes);
return $diff->getChangesets();
}
public function toDictionary() {
$commit = $this->getCommit();
if ($commit) {
$commit_dict = $commit->toDictionary();
} else {
$commit_dict = array();
}
$commit_data = $this->getCommitData();
if ($commit_data) {
$commit_data_dict = $commit_data->toDictionary();
} else {
$commit_data_dict = array();
}
return array(
'path' => $this->getPath(),
'commitIdentifier' => $this->getCommitIdentifier(),
'commit' => $commit_dict,
'commitData' => $commit_data_dict,
'fileType' => $this->getFileType(),
'changeType' => $this->getChangeType(),
'targetPath' => $this->getTargetPath(),
'targetCommitIdentifier' => $this->getTargetCommitIdentifier(),
'awayPaths' => $this->getAwayPaths(),
);
}
public static function newFromConduit(array $dicts) {
$results = array();
foreach ($dicts as $dict) {
$commit = PhabricatorRepositoryCommit::newFromDictionary($dict['commit']);
$commit_data =
PhabricatorRepositoryCommitData::newFromDictionary(
$dict['commitData']);
$results[] = id(new DiffusionPathChange())
->setPath($dict['path'])
->setCommitIdentifier($dict['commitIdentifier'])
->setCommit($commit)
->setCommitData($commit_data)
->setFileType($dict['fileType'])
->setChangeType($dict['changeType'])
->setTargetPath($dict['targetPath'])
->setTargetCommitIdentifier($dict['targetCommitIdentifier'])
->setAwayPaths($dict['awayPaths']);
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/data/__tests__/DiffusionGitBranchTestCase.php | src/applications/diffusion/data/__tests__/DiffusionGitBranchTestCase.php | <?php
final class DiffusionGitBranchTestCase
extends PhabricatorTestCase {
public function testRemoteBranchParser() {
$output = <<<EOTXT
origin/HEAD -> origin/master
origin/accent-folding bfaea2e72197506e028c604cd1a294b6e37aa17d Add...
origin/eventordering 185a90a3c1b0556015e5f318fb86ccf8f7a6f3e3 RFC: Order...
origin/master 713f1fc54f9cfc830acbf6bbdb46a2883f772896 Automat...
alternate/stuff 4444444444444444444444444444444444444444 Hmm...
origin/HEAD 713f1fc54f9cfc830acbf6bbdb46a2883f772896
origin/refactoring 6e947ab0498b82075ca6195ac168385a11326c4b
alternate/release-1.0.0 9ddd5d67962dd89fa167f9989954468b6c517b87
EOTXT;
$this->assertEqual(
array(
'origin/accent-folding' => 'bfaea2e72197506e028c604cd1a294b6e37aa17d',
'origin/eventordering' => '185a90a3c1b0556015e5f318fb86ccf8f7a6f3e3',
'origin/master' => '713f1fc54f9cfc830acbf6bbdb46a2883f772896',
'alternate/stuff' => '4444444444444444444444444444444444444444',
'origin/refactoring' => '6e947ab0498b82075ca6195ac168385a11326c4b',
'alternate/release-1.0.0' => '9ddd5d67962dd89fa167f9989954468b6c517b87',
),
DiffusionGitBranch::parseRemoteBranchOutput($output));
$this->assertEqual(
array(
'accent-folding' => 'bfaea2e72197506e028c604cd1a294b6e37aa17d',
'eventordering' => '185a90a3c1b0556015e5f318fb86ccf8f7a6f3e3',
'master' => '713f1fc54f9cfc830acbf6bbdb46a2883f772896',
'refactoring' => '6e947ab0498b82075ca6195ac168385a11326c4b',
),
DiffusionGitBranch::parseRemoteBranchOutput($output, 'origin'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/document/DiffusionDocumentRenderingEngine.php | src/applications/diffusion/document/DiffusionDocumentRenderingEngine.php | <?php
final class DiffusionDocumentRenderingEngine
extends PhabricatorDocumentRenderingEngine {
private $diffusionRequest;
public function setDiffusionRequest(DiffusionRequest $drequest) {
$this->diffusionRequest = $drequest;
return $this;
}
public function getDiffusionRequest() {
return $this->diffusionRequest;
}
protected function newRefViewURI(
PhabricatorDocumentRef $ref,
PhabricatorDocumentEngine $engine) {
$file = $ref->getFile();
$engine_key = $engine->getDocumentEngineKey();
$drequest = $this->getDiffusionRequest();
return (string)$drequest->generateURI(
array(
'action' => 'browse',
'stable' => true,
'params' => array(
'as' => $engine_key,
),
));
}
protected function newRefRenderURI(
PhabricatorDocumentRef $ref,
PhabricatorDocumentEngine $engine) {
$engine_key = $engine->getDocumentEngineKey();
$file = $ref->getFile();
$file_phid = $file->getPHID();
$drequest = $this->getDiffusionRequest();
return (string)$drequest->generateURI(
array(
'action' => 'document',
'stable' => true,
'params' => array(
'as' => $engine_key,
'filePHID' => $file_phid,
),
));
}
protected function getSelectedDocumentEngineKey() {
return $this->getRequest()->getStr('as');
}
protected function getSelectedLineRange() {
$range = $this->getDiffusionRequest()->getLine();
return AphrontRequest::parseURILineRange($range, 1000);
}
protected function addApplicationCrumbs(
PHUICrumbsView $crumbs,
PhabricatorDocumentRef $ref = null) {
return;
}
protected function willStageRef(PhabricatorDocumentRef $ref) {
$drequest = $this->getDiffusionRequest();
$blame_uri = (string)$drequest->generateURI(
array(
'action' => 'blame',
'stable' => true,
));
$ref->setBlameURI($blame_uri);
}
protected function willRenderRef(PhabricatorDocumentRef $ref) {
$drequest = $this->getDiffusionRequest();
$ref->setSymbolMetadata($this->getSymbolMetadata());
$coverage = $drequest->loadCoverage();
if ($coverage !== null && strlen($coverage)) {
$ref->addCoverage($coverage);
}
}
private function getSymbolMetadata() {
$drequest = $this->getDiffusionRequest();
$repo = $drequest->getRepository();
$symbol_repos = nonempty($repo->getSymbolSources(), array());
$symbol_repos[] = $repo->getPHID();
$lang = last(explode('.', $drequest->getPath()));
return array(
'repositories' => $symbol_repos,
'lang' => $lang,
'path' => $drequest->getPath(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/engine/DiffusionCommitDraftEngine.php | src/applications/diffusion/engine/DiffusionCommitDraftEngine.php | <?php
final class DiffusionCommitDraftEngine
extends PhabricatorDraftEngine {
protected function hasCustomDraftContent() {
$viewer = $this->getViewer();
$commit = $this->getObject();
$inlines = id(new DiffusionDiffInlineCommentQuery())
->setViewer($viewer)
->withCommitPHIDs(array($commit->getPHID()))
->withPublishableComments(true)
->setReturnPartialResultsOnOverheat(true)
->setLimit(1)
->execute();
return (bool)$inlines;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/engine/DiffusionCommitTimelineEngine.php | src/applications/diffusion/engine/DiffusionCommitTimelineEngine.php | <?php
final class DiffusionCommitTimelineEngine
extends PhabricatorTimelineEngine {
protected function newTimelineView() {
$xactions = $this->getTransactions();
$path_ids = array();
foreach ($xactions as $xaction) {
if ($xaction->hasComment()) {
$path_id = $xaction->getComment()->getPathID();
if ($path_id) {
$path_ids[] = $path_id;
}
}
}
$path_map = array();
if ($path_ids) {
$path_map = id(new DiffusionPathQuery())
->withPathIDs($path_ids)
->execute();
$path_map = ipull($path_map, 'path', 'id');
}
return id(new PhabricatorAuditTransactionView())
->setPathMap($path_map);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/engine/DiffusionCommitHookEngine.php | src/applications/diffusion/engine/DiffusionCommitHookEngine.php | <?php
/**
* @task config Configuring the Hook Engine
* @task hook Hook Execution
* @task git Git Hooks
* @task hg Mercurial Hooks
* @task svn Subversion Hooks
* @task internal Internals
*/
final class DiffusionCommitHookEngine extends Phobject {
const ENV_REPOSITORY = 'PHABRICATOR_REPOSITORY';
const ENV_USER = 'PHABRICATOR_USER';
const ENV_REQUEST = 'PHABRICATOR_REQUEST';
const ENV_REMOTE_ADDRESS = 'PHABRICATOR_REMOTE_ADDRESS';
const ENV_REMOTE_PROTOCOL = 'PHABRICATOR_REMOTE_PROTOCOL';
const EMPTY_HASH = '0000000000000000000000000000000000000000';
private $viewer;
private $repository;
private $stdin;
private $originalArgv;
private $subversionTransaction;
private $subversionRepository;
private $remoteAddress;
private $remoteProtocol;
private $requestIdentifier;
private $transactionKey;
private $mercurialHook;
private $mercurialCommits = array();
private $gitCommits = array();
private $startTime;
private $heraldViewerProjects;
private $rejectCode = PhabricatorRepositoryPushLog::REJECT_BROKEN;
private $rejectDetails;
private $emailPHIDs = array();
private $changesets = array();
private $changesetsSize = 0;
private $filesizeCache = array();
/* -( Config )------------------------------------------------------------- */
public function setRemoteProtocol($remote_protocol) {
$this->remoteProtocol = $remote_protocol;
return $this;
}
public function getRemoteProtocol() {
return $this->remoteProtocol;
}
public function setRemoteAddress($remote_address) {
$this->remoteAddress = $remote_address;
return $this;
}
public function getRemoteAddress() {
return $this->remoteAddress;
}
public function setRequestIdentifier($request_identifier) {
$this->requestIdentifier = $request_identifier;
return $this;
}
public function getRequestIdentifier() {
return $this->requestIdentifier;
}
public function setStartTime($start_time) {
$this->startTime = $start_time;
return $this;
}
public function getStartTime() {
return $this->startTime;
}
public function setSubversionTransactionInfo($transaction, $repository) {
$this->subversionTransaction = $transaction;
$this->subversionRepository = $repository;
return $this;
}
public function setStdin($stdin) {
$this->stdin = $stdin;
return $this;
}
public function getStdin() {
return $this->stdin;
}
public function setOriginalArgv(array $original_argv) {
$this->originalArgv = $original_argv;
return $this;
}
public function getOriginalArgv() {
return $this->originalArgv;
}
public function setRepository(PhabricatorRepository $repository) {
$this->repository = $repository;
return $this;
}
public function getRepository() {
return $this->repository;
}
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setMercurialHook($mercurial_hook) {
$this->mercurialHook = $mercurial_hook;
return $this;
}
public function getMercurialHook() {
return $this->mercurialHook;
}
/* -( Hook Execution )----------------------------------------------------- */
public function execute() {
$ref_updates = $this->findRefUpdates();
$all_updates = $ref_updates;
$caught = null;
try {
try {
$this->rejectDangerousChanges($ref_updates);
} catch (DiffusionCommitHookRejectException $ex) {
// If we're rejecting dangerous changes, flag everything that we've
// seen as rejected so it's clear that none of it was accepted.
$this->rejectCode = PhabricatorRepositoryPushLog::REJECT_DANGEROUS;
throw $ex;
}
$content_updates = $this->findContentUpdates($ref_updates);
$all_updates = array_merge($ref_updates, $content_updates);
// If this is an "initial import" (a sizable push to a previously empty
// repository) we'll allow enormous changes and disable Herald rules.
// These rulesets can consume a large amount of time and memory and are
// generally not relevant when importing repository history.
$is_initial_import = $this->isInitialImport($all_updates);
if (!$is_initial_import) {
$this->applyHeraldRefRules($ref_updates);
}
try {
if (!$is_initial_import) {
$this->rejectOversizedFiles($content_updates);
}
} catch (DiffusionCommitHookRejectException $ex) {
// If we're rejecting oversized files, flag everything.
$this->rejectCode = PhabricatorRepositoryPushLog::REJECT_OVERSIZED;
throw $ex;
}
try {
if (!$is_initial_import) {
$this->rejectCommitsAffectingTooManyPaths($content_updates);
}
} catch (DiffusionCommitHookRejectException $ex) {
$this->rejectCode = PhabricatorRepositoryPushLog::REJECT_TOUCHES;
throw $ex;
}
try {
if (!$is_initial_import) {
$this->rejectEnormousChanges($content_updates);
}
} catch (DiffusionCommitHookRejectException $ex) {
// If we're rejecting enormous changes, flag everything.
$this->rejectCode = PhabricatorRepositoryPushLog::REJECT_ENORMOUS;
throw $ex;
}
if (!$is_initial_import) {
$this->applyHeraldContentRules($content_updates);
}
// Run custom scripts in `hook.d/` directories.
$this->applyCustomHooks($all_updates);
// If we make it this far, we're accepting these changes. Mark all the
// logs as accepted.
$this->rejectCode = PhabricatorRepositoryPushLog::REJECT_ACCEPT;
} catch (Exception $ex) {
// We'll throw this again in a minute, but we want to save all the logs
// first.
$caught = $ex;
}
// Save all the logs no matter what the outcome was.
$event = $this->newPushEvent();
$event->setRejectCode($this->rejectCode);
$event->setRejectDetails($this->rejectDetails);
$event->saveWithLogs($all_updates);
if ($caught) {
throw $caught;
}
// If this went through cleanly and was an import, set the importing flag
// on the repository. It will be cleared once we fully process everything.
if ($is_initial_import) {
$repository = $this->getRepository();
$repository->markImporting();
}
if ($this->emailPHIDs) {
// If Herald rules triggered email to users, queue a worker to send the
// mail. We do this out-of-process so that we block pushes as briefly
// as possible.
// (We do need to pull some commit info here because the commit objects
// may not exist yet when this worker runs, which could be immediately.)
PhabricatorWorker::scheduleTask(
'PhabricatorRepositoryPushMailWorker',
array(
'eventPHID' => $event->getPHID(),
'emailPHIDs' => array_values($this->emailPHIDs),
'info' => $this->loadCommitInfoForWorker($all_updates),
),
array(
'priority' => PhabricatorWorker::PRIORITY_ALERTS,
));
}
return 0;
}
private function findRefUpdates() {
$type = $this->getRepository()->getVersionControlSystem();
switch ($type) {
case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
return $this->findGitRefUpdates();
case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL:
return $this->findMercurialRefUpdates();
case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN:
return $this->findSubversionRefUpdates();
default:
throw new Exception(pht('Unsupported repository type "%s"!', $type));
}
}
private function rejectDangerousChanges(array $ref_updates) {
assert_instances_of($ref_updates, 'PhabricatorRepositoryPushLog');
$repository = $this->getRepository();
if ($repository->shouldAllowDangerousChanges()) {
return;
}
$flag_dangerous = PhabricatorRepositoryPushLog::CHANGEFLAG_DANGEROUS;
foreach ($ref_updates as $ref_update) {
if (!$ref_update->hasChangeFlags($flag_dangerous)) {
// This is not a dangerous change.
continue;
}
// We either have a branch deletion or a non fast-forward branch update.
// Format a message and reject the push.
$message = pht(
"DANGEROUS CHANGE: %s\n".
"Dangerous change protection is enabled for this repository.\n".
"Edit the repository configuration before making dangerous changes.",
$ref_update->getDangerousChangeDescription());
throw new DiffusionCommitHookRejectException($message);
}
}
private function findContentUpdates(array $ref_updates) {
assert_instances_of($ref_updates, 'PhabricatorRepositoryPushLog');
$type = $this->getRepository()->getVersionControlSystem();
switch ($type) {
case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
return $this->findGitContentUpdates($ref_updates);
case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL:
return $this->findMercurialContentUpdates($ref_updates);
case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN:
return $this->findSubversionContentUpdates($ref_updates);
default:
throw new Exception(pht('Unsupported repository type "%s"!', $type));
}
}
/* -( Herald )------------------------------------------------------------- */
private function applyHeraldRefRules(array $ref_updates) {
$this->applyHeraldRules(
$ref_updates,
new HeraldPreCommitRefAdapter());
}
private function applyHeraldContentRules(array $content_updates) {
$this->applyHeraldRules(
$content_updates,
new HeraldPreCommitContentAdapter());
}
private function applyHeraldRules(
array $updates,
HeraldAdapter $adapter_template) {
if (!$updates) {
return;
}
$viewer = $this->getViewer();
$adapter_template
->setHookEngine($this)
->setActingAsPHID($viewer->getPHID());
$engine = new HeraldEngine();
$rules = null;
$blocking_effect = null;
$blocked_update = null;
$blocking_xscript = null;
foreach ($updates as $update) {
$adapter = id(clone $adapter_template)
->setPushLog($update);
if ($rules === null) {
$rules = $engine->loadRulesForAdapter($adapter);
}
$effects = $engine->applyRules($rules, $adapter);
$engine->applyEffects($effects, $adapter, $rules);
$xscript = $engine->getTranscript();
// Store any PHIDs we want to send email to for later.
foreach ($adapter->getEmailPHIDs() as $email_phid) {
$this->emailPHIDs[$email_phid] = $email_phid;
}
$block_action = DiffusionBlockHeraldAction::ACTIONCONST;
if ($blocking_effect === null) {
foreach ($effects as $effect) {
if ($effect->getAction() == $block_action) {
$blocking_effect = $effect;
$blocked_update = $update;
$blocking_xscript = $xscript;
break;
}
}
}
}
if ($blocking_effect) {
$rule = $blocking_effect->getRule();
$this->rejectCode = PhabricatorRepositoryPushLog::REJECT_HERALD;
$this->rejectDetails = $rule->getPHID();
$message = $blocking_effect->getTarget();
if (!strlen($message)) {
$message = pht('(None.)');
}
$blocked_ref_name = coalesce(
$blocked_update->getRefName(),
$blocked_update->getRefNewShort());
$blocked_name = $blocked_update->getRefType().'/'.$blocked_ref_name;
throw new DiffusionCommitHookRejectException(
pht(
"This push was rejected by Herald push rule %s.\n".
" Change: %s\n".
" Rule: %s\n".
" Reason: %s\n".
"Transcript: %s",
$rule->getMonogram(),
$blocked_name,
$rule->getName(),
$message,
PhabricatorEnv::getProductionURI(
'/herald/transcript/'.$blocking_xscript->getID().'/')));
}
}
public function loadViewerProjectPHIDsForHerald() {
// This just caches the viewer's projects so we don't need to load them
// over and over again when applying Herald rules.
if ($this->heraldViewerProjects === null) {
$this->heraldViewerProjects = id(new PhabricatorProjectQuery())
->setViewer($this->getViewer())
->withMemberPHIDs(array($this->getViewer()->getPHID()))
->execute();
}
return mpull($this->heraldViewerProjects, 'getPHID');
}
/* -( Git )---------------------------------------------------------------- */
private function findGitRefUpdates() {
$ref_updates = array();
// First, parse stdin, which lists all the ref changes. The input looks
// like this:
//
// <old hash> <new hash> <ref>
$stdin = $this->getStdin();
$lines = phutil_split_lines($stdin, $retain_endings = false);
foreach ($lines as $line) {
$parts = explode(' ', $line, 3);
if (count($parts) != 3) {
throw new Exception(pht('Expected "old new ref", got "%s".', $line));
}
$ref_old = $parts[0];
$ref_new = $parts[1];
$ref_raw = $parts[2];
if (preg_match('(^refs/heads/)', $ref_raw)) {
$ref_type = PhabricatorRepositoryPushLog::REFTYPE_BRANCH;
$ref_raw = substr($ref_raw, strlen('refs/heads/'));
} else if (preg_match('(^refs/tags/)', $ref_raw)) {
$ref_type = PhabricatorRepositoryPushLog::REFTYPE_TAG;
$ref_raw = substr($ref_raw, strlen('refs/tags/'));
} else {
$ref_type = PhabricatorRepositoryPushLog::REFTYPE_REF;
}
$ref_update = $this->newPushLog()
->setRefType($ref_type)
->setRefName($ref_raw)
->setRefOld($ref_old)
->setRefNew($ref_new);
$ref_updates[] = $ref_update;
}
$this->findGitMergeBases($ref_updates);
$this->findGitChangeFlags($ref_updates);
return $ref_updates;
}
private function findGitMergeBases(array $ref_updates) {
assert_instances_of($ref_updates, 'PhabricatorRepositoryPushLog');
$futures = array();
foreach ($ref_updates as $key => $ref_update) {
// If the old hash is "00000...", the ref is being created (either a new
// branch, or a new tag). If the new hash is "00000...", the ref is being
// deleted. If both are nonempty, the ref is being updated. For updates,
// we'll figure out the `merge-base` of the old and new objects here. This
// lets us reject non-FF changes cheaply; later, we'll figure out exactly
// which commits are new.
$ref_old = $ref_update->getRefOld();
$ref_new = $ref_update->getRefNew();
if (($ref_old === self::EMPTY_HASH) ||
($ref_new === self::EMPTY_HASH)) {
continue;
}
$futures[$key] = $this->getRepository()->getLocalCommandFuture(
'merge-base %s %s',
$ref_old,
$ref_new);
}
$futures = id(new FutureIterator($futures))
->limit(8);
foreach ($futures as $key => $future) {
// If 'old' and 'new' have no common ancestors (for example, a force push
// which completely rewrites a ref), `git merge-base` will exit with
// an error and no output. It would be nice to find a positive test
// for this instead, but I couldn't immediately come up with one. See
// T4224. Assume this means there are no ancestors.
list($err, $stdout) = $future->resolve();
if ($err) {
$merge_base = null;
} else {
$merge_base = rtrim($stdout, "\n");
}
$ref_update = $ref_updates[$key];
$ref_update->setMergeBase($merge_base);
}
return $ref_updates;
}
private function findGitChangeFlags(array $ref_updates) {
assert_instances_of($ref_updates, 'PhabricatorRepositoryPushLog');
foreach ($ref_updates as $key => $ref_update) {
$ref_old = $ref_update->getRefOld();
$ref_new = $ref_update->getRefNew();
$ref_type = $ref_update->getRefType();
$ref_flags = 0;
$dangerous = null;
if (($ref_old === self::EMPTY_HASH) && ($ref_new === self::EMPTY_HASH)) {
// This happens if you try to delete a tag or branch which does not
// exist by pushing directly to the ref. Git will warn about it but
// allow it. Just call it a delete, without flagging it as dangerous.
$ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_DELETE;
} else if ($ref_old === self::EMPTY_HASH) {
$ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_ADD;
} else if ($ref_new === self::EMPTY_HASH) {
$ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_DELETE;
if ($ref_type == PhabricatorRepositoryPushLog::REFTYPE_BRANCH) {
$ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_DANGEROUS;
$dangerous = pht(
"The change you're attempting to push deletes the branch '%s'.",
$ref_update->getRefName());
}
} else {
$merge_base = $ref_update->getMergeBase();
if ($merge_base == $ref_old) {
// This is a fast-forward update to an existing branch.
// These are safe.
$ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_APPEND;
} else {
$ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_REWRITE;
// For now, we don't consider deleting or moving tags to be a
// "dangerous" update. It's way harder to get wrong and should be easy
// to recover from once we have better logging. Only add the dangerous
// flag if this ref is a branch.
if ($ref_type == PhabricatorRepositoryPushLog::REFTYPE_BRANCH) {
$ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_DANGEROUS;
$dangerous = pht(
"The change you're attempting to push updates the branch '%s' ".
"from '%s' to '%s', but this is not a fast-forward. Pushes ".
"which rewrite published branch history are dangerous.",
$ref_update->getRefName(),
$ref_update->getRefOldShort(),
$ref_update->getRefNewShort());
}
}
}
$ref_update->setChangeFlags($ref_flags);
if ($dangerous !== null) {
$ref_update->attachDangerousChangeDescription($dangerous);
}
}
return $ref_updates;
}
private function findGitContentUpdates(array $ref_updates) {
$flag_delete = PhabricatorRepositoryPushLog::CHANGEFLAG_DELETE;
$futures = array();
foreach ($ref_updates as $key => $ref_update) {
if ($ref_update->hasChangeFlags($flag_delete)) {
// Deleting a branch or tag can never create any new commits.
continue;
}
// NOTE: This piece of magic finds all new commits, by walking backward
// from the new value to the value of *any* existing ref in the
// repository. Particularly, this will cover the cases of a new branch, a
// completely moved tag, etc.
$futures[$key] = $this->getRepository()->getLocalCommandFuture(
'log %s %s --not --all --',
'--format=%H',
gitsprintf('%s', $ref_update->getRefNew()));
}
$content_updates = array();
$futures = id(new FutureIterator($futures))
->limit(8);
foreach ($futures as $key => $future) {
list($stdout) = $future->resolvex();
if (!strlen(trim($stdout))) {
// This change doesn't have any new commits. One common case of this
// is creating a new tag which points at an existing commit.
continue;
}
$commits = phutil_split_lines($stdout, $retain_newlines = false);
// If we're looking at a branch, mark all of the new commits as on that
// branch. It's only possible for these commits to be on updated branches,
// since any other branch heads are necessarily behind them.
$branch_name = null;
$ref_update = $ref_updates[$key];
$type_branch = PhabricatorRepositoryPushLog::REFTYPE_BRANCH;
if ($ref_update->getRefType() == $type_branch) {
$branch_name = $ref_update->getRefName();
}
foreach ($commits as $commit) {
if ($branch_name) {
$this->gitCommits[$commit][] = $branch_name;
}
$content_updates[$commit] = $this->newPushLog()
->setRefType(PhabricatorRepositoryPushLog::REFTYPE_COMMIT)
->setRefNew($commit)
->setChangeFlags(PhabricatorRepositoryPushLog::CHANGEFLAG_ADD);
}
}
return $content_updates;
}
/* -( Custom )------------------------------------------------------------- */
private function applyCustomHooks(array $updates) {
$args = $this->getOriginalArgv();
$stdin = $this->getStdin();
$console = PhutilConsole::getConsole();
$env = array(
self::ENV_REPOSITORY => $this->getRepository()->getPHID(),
self::ENV_USER => $this->getViewer()->getUsername(),
self::ENV_REQUEST => $this->getRequestIdentifier(),
self::ENV_REMOTE_PROTOCOL => $this->getRemoteProtocol(),
self::ENV_REMOTE_ADDRESS => $this->getRemoteAddress(),
);
$repository = $this->getRepository();
$env += $repository->getPassthroughEnvironmentalVariables();
$directories = $repository->getHookDirectories();
foreach ($directories as $directory) {
$hooks = $this->getExecutablesInDirectory($directory);
sort($hooks);
foreach ($hooks as $hook) {
// NOTE: We're explicitly running the hooks in sequential order to
// make this more predictable.
$future = id(new ExecFuture('%s %Ls', $hook, $args))
->setEnv($env, $wipe_process_env = false)
->write($stdin);
list($err, $stdout, $stderr) = $future->resolve();
if (!$err) {
// This hook ran OK, but echo its output in case there was something
// informative.
$console->writeOut('%s', $stdout);
$console->writeErr('%s', $stderr);
continue;
}
$this->rejectCode = PhabricatorRepositoryPushLog::REJECT_EXTERNAL;
$this->rejectDetails = basename($hook);
throw new DiffusionCommitHookRejectException(
pht(
"This push was rejected by custom hook script '%s':\n\n%s%s",
basename($hook),
$stdout,
$stderr));
}
}
}
private function getExecutablesInDirectory($directory) {
$executables = array();
if (!Filesystem::pathExists($directory)) {
return $executables;
}
foreach (Filesystem::listDirectory($directory) as $path) {
$full_path = $directory.DIRECTORY_SEPARATOR.$path;
if (!is_executable($full_path)) {
// Don't include non-executable files.
continue;
}
if (basename($full_path) == 'README') {
// Don't include README, even if it is marked as executable. It almost
// certainly got caught in the crossfire of a sweeping `chmod`, since
// users do this with some frequency.
continue;
}
$executables[] = $full_path;
}
return $executables;
}
/* -( Mercurial )---------------------------------------------------------- */
private function findMercurialRefUpdates() {
$hook = $this->getMercurialHook();
switch ($hook) {
case 'pretxnchangegroup':
return $this->findMercurialChangegroupRefUpdates();
case 'prepushkey':
return $this->findMercurialPushKeyRefUpdates();
default:
throw new Exception(pht('Unrecognized hook "%s"!', $hook));
}
}
private function findMercurialChangegroupRefUpdates() {
$hg_node = getenv('HG_NODE');
if (!$hg_node) {
throw new Exception(
pht(
'Expected %s in environment!',
'HG_NODE'));
}
// NOTE: We need to make sure this is passed to subprocesses, or they won't
// be able to see new commits. Mercurial uses this as a marker to determine
// whether the pending changes are visible or not.
$_ENV['HG_PENDING'] = getenv('HG_PENDING');
$repository = $this->getRepository();
$futures = array();
foreach (array('old', 'new') as $key) {
$futures[$key] = $repository->getLocalCommandFuture(
'heads --template %s',
'{node}\1{branch}\2');
}
// Wipe HG_PENDING out of the old environment so we see the pre-commit
// state of the repository.
$futures['old']->updateEnv('HG_PENDING', null);
$futures['commits'] = $repository->getLocalCommandFuture(
'log --rev %s --template %s',
hgsprintf('%s:%s', $hg_node, 'tip'),
'{node}\1{branch}\2');
// Resolve all of the futures now. We don't need the 'commits' future yet,
// but it simplifies the logic to just get it out of the way.
foreach (new FutureIterator($futures) as $future) {
$future->resolve();
}
list($commit_raw) = $futures['commits']->resolvex();
$commit_map = $this->parseMercurialCommits($commit_raw);
$this->mercurialCommits = $commit_map;
// NOTE: `hg heads` exits with an error code and no output if the repository
// has no heads. Most commonly this happens on a new repository. We know
// we can run `hg` successfully since the `hg log` above didn't error, so
// just ignore the error code.
list($err, $old_raw) = $futures['old']->resolve();
$old_refs = $this->parseMercurialHeads($old_raw);
list($err, $new_raw) = $futures['new']->resolve();
$new_refs = $this->parseMercurialHeads($new_raw);
$all_refs = array_keys($old_refs + $new_refs);
$ref_updates = array();
foreach ($all_refs as $ref) {
$old_heads = idx($old_refs, $ref, array());
$new_heads = idx($new_refs, $ref, array());
sort($old_heads);
sort($new_heads);
if (!$old_heads && !$new_heads) {
// This should never be possible, as it makes no sense. Explode.
throw new Exception(
pht(
'Mercurial repository has no new or old heads for branch "%s" '.
'after push. This makes no sense; rejecting change.',
$ref));
}
if ($old_heads === $new_heads) {
// No changes to this branch, so skip it.
continue;
}
$stray_heads = array();
$head_map = array();
if ($old_heads && !$new_heads) {
// This is a branch deletion with "--close-branch".
foreach ($old_heads as $old_head) {
$head_map[$old_head] = array(self::EMPTY_HASH);
}
} else if (count($old_heads) > 1) {
// HORRIBLE: In Mercurial, branches can have multiple heads. If the
// old branch had multiple heads, we need to figure out which new
// heads descend from which old heads, so we can tell whether you're
// actively creating new heads (dangerous) or just working in a
// repository that's already full of garbage (strongly discouraged but
// not as inherently dangerous). These cases should be very uncommon.
// NOTE: We're only looking for heads on the same branch. The old
// tip of the branch may be the branchpoint for other branches, but that
// is OK.
$dfutures = array();
foreach ($old_heads as $old_head) {
$dfutures[$old_head] = $repository->getLocalCommandFuture(
'log --branch %s --rev %s --template %s',
$ref,
hgsprintf('(descendants(%s) and head())', $old_head),
'{node}\1');
}
foreach (new FutureIterator($dfutures) as $future_head => $dfuture) {
list($stdout) = $dfuture->resolvex();
$descendant_heads = array_filter(explode("\1", $stdout));
if ($descendant_heads) {
// This old head has at least one descendant in the push.
$head_map[$future_head] = $descendant_heads;
} else {
// This old head has no descendants, so it is being deleted.
$head_map[$future_head] = array(self::EMPTY_HASH);
}
}
// Now, find all the new stray heads this push creates, if any. These
// are new heads which do not descend from the old heads.
$seen = array_fuse(array_mergev($head_map));
foreach ($new_heads as $new_head) {
if ($new_head === self::EMPTY_HASH) {
// If a branch head is being deleted, don't insert it as an add.
continue;
}
if (empty($seen[$new_head])) {
$head_map[self::EMPTY_HASH][] = $new_head;
}
}
} else if ($old_heads) {
$head_map[head($old_heads)] = $new_heads;
} else {
$head_map[self::EMPTY_HASH] = $new_heads;
}
foreach ($head_map as $old_head => $child_heads) {
foreach ($child_heads as $new_head) {
if ($new_head === $old_head) {
continue;
}
$ref_flags = 0;
$dangerous = null;
if ($old_head == self::EMPTY_HASH) {
$ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_ADD;
} else {
$ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_APPEND;
}
$deletes_existing_head = ($new_head == self::EMPTY_HASH);
$splits_existing_head = (count($child_heads) > 1);
$creates_duplicate_head = ($old_head == self::EMPTY_HASH) &&
(count($head_map) > 1);
if ($splits_existing_head || $creates_duplicate_head) {
$readable_child_heads = array();
foreach ($child_heads as $child_head) {
$readable_child_heads[] = substr($child_head, 0, 12);
}
$ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_DANGEROUS;
if ($splits_existing_head) {
// We're splitting an existing head into two or more heads.
// This is dangerous, and a super bad idea. Note that we're only
// raising this if you're actively splitting a branch head. If a
// head split in the past, we don't consider appends to it
// to be dangerous.
$dangerous = pht(
"The change you're attempting to push splits the head of ".
"branch '%s' into multiple heads: %s. This is inadvisable ".
"and dangerous.",
$ref,
implode(', ', $readable_child_heads));
} else {
// We're adding a second (or more) head to a branch. The new
// head is not a descendant of any old head.
$dangerous = pht(
"The change you're attempting to push creates new, divergent ".
"heads for the branch '%s': %s. This is inadvisable and ".
"dangerous.",
$ref,
implode(', ', $readable_child_heads));
}
}
if ($deletes_existing_head) {
// TODO: Somewhere in here we should be setting CHANGEFLAG_REWRITE
// if we are also creating at least one other head to replace
// this one.
// NOTE: In Git, this is a dangerous change, but it is not dangerous
// in Mercurial. Mercurial branches are version controlled, and
// Mercurial does not prompt you for any special flags when pushing
// a `--close-branch` commit by default.
$ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_DELETE;
}
$ref_update = $this->newPushLog()
->setRefType(PhabricatorRepositoryPushLog::REFTYPE_BRANCH)
->setRefName($ref)
->setRefOld($old_head)
->setRefNew($new_head)
->setChangeFlags($ref_flags);
if ($dangerous !== null) {
$ref_update->attachDangerousChangeDescription($dangerous);
}
$ref_updates[] = $ref_update;
}
}
}
return $ref_updates;
}
private function findMercurialPushKeyRefUpdates() {
$key_namespace = getenv('HG_NAMESPACE');
if ($key_namespace === 'phases') {
// Mercurial changes commit phases as part of normal push operations. We
// just ignore these, as they don't seem to represent anything
// interesting.
return array();
}
$key_name = getenv('HG_KEY');
$key_old = getenv('HG_OLD');
if (!strlen($key_old)) {
$key_old = null;
}
$key_new = getenv('HG_NEW');
if (!strlen($key_new)) {
$key_new = null;
}
if ($key_namespace !== 'bookmarks') {
throw new Exception(
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | true |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/typeahead/DiffusionAuditorDatasource.php | src/applications/diffusion/typeahead/DiffusionAuditorDatasource.php | <?php
final class DiffusionAuditorDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Auditors');
}
public function getPlaceholderText() {
return pht('Type a user, project or package name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
public function getComponentDatasources() {
return array(
new PhabricatorPeopleDatasource(),
new PhabricatorProjectDatasource(),
new PhabricatorOwnersPackageDatasource(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/typeahead/DiffusionAuditorFunctionDatasource.php | src/applications/diffusion/typeahead/DiffusionAuditorFunctionDatasource.php | <?php
final class DiffusionAuditorFunctionDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Auditors');
}
public function getPlaceholderText() {
return pht('Type a user, project, package name or function...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
public function getComponentDatasources() {
return array(
new PhabricatorProjectOrUserFunctionDatasource(),
new PhabricatorOwnersPackageFunctionDatasource(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/typeahead/DiffusionRepositoryFunctionDatasource.php | src/applications/diffusion/typeahead/DiffusionRepositoryFunctionDatasource.php | <?php
final class DiffusionRepositoryFunctionDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Repositories');
}
public function getPlaceholderText() {
return pht('Type a repository name or function...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
public function getComponentDatasources() {
return array(
new DiffusionTaggedRepositoriesFunctionDatasource(),
new DiffusionRepositoryDatasource(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/typeahead/DiffusionIdentityAssigneeDatasource.php | src/applications/diffusion/typeahead/DiffusionIdentityAssigneeDatasource.php | <?php
final class DiffusionIdentityAssigneeDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Assignee');
}
public function getPlaceholderText() {
return pht('Type a username or function...');
}
public function getComponentDatasources() {
return array(
new PhabricatorPeopleDatasource(),
new DiffusionIdentityUnassignedDatasource(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/typeahead/DiffusionRepositoryDatasource.php | src/applications/diffusion/typeahead/DiffusionRepositoryDatasource.php | <?php
final class DiffusionRepositoryDatasource
extends PhabricatorTypeaheadDatasource {
public function getBrowseTitle() {
return pht('Browse Repositories');
}
public function getPlaceholderText() {
return pht('Type a repository name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
public function loadResults() {
$viewer = $this->getViewer();
$raw_query = $this->getRawQuery();
$query = id(new PhabricatorRepositoryQuery())
->setOrder('name')
->withDatasourceQuery($raw_query);
$repos = $this->executeQuery($query);
$type_icon = id(new PhabricatorRepositoryRepositoryPHIDType())
->getTypeIcon();
$image_sprite =
"phabricator-search-icon phui-font-fa phui-icon-view {$type_icon}";
$results = array();
foreach ($repos as $repository) {
$monogram = $repository->getMonogram();
$name = $repository->getName();
$display_name = "{$monogram} {$name}";
$parts = array();
$parts[] = $name;
$slug = $repository->getRepositorySlug();
if (strlen($slug)) {
$parts[] = $slug;
}
$callsign = $repository->getCallsign();
if ($callsign) {
$parts[] = $callsign;
}
foreach ($repository->getAllMonograms() as $monogram) {
$parts[] = $monogram;
}
$name = implode("\n", $parts);
$vcs = $repository->getVersionControlSystem();
$vcs_type = PhabricatorRepositoryType::getNameForRepositoryType($vcs);
$result = id(new PhabricatorTypeaheadResult())
->setName($name)
->setDisplayName($display_name)
->setURI($repository->getURI())
->setPHID($repository->getPHID())
->setPriorityString($repository->getMonogram())
->setPriorityType('repo')
->setImageSprite($image_sprite)
->setDisplayType(pht('Repository'))
->addAttribute($vcs_type);
if (!$repository->isTracked()) {
$result->setClosed(pht('Inactive'));
}
$results[] = $result;
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/typeahead/DiffusionRefDatasource.php | src/applications/diffusion/typeahead/DiffusionRefDatasource.php | <?php
final class DiffusionRefDatasource
extends PhabricatorTypeaheadDatasource {
public function getBrowseTitle() {
return pht('Browse Branches');
}
public function getPlaceholderText() {
// TODO: This is really "branch, tag, bookmark or ref" but we are only
// using it to pick branches for now and sometimes the UI won't let you
// pick some of these types. See also "Browse Branches" above.
return pht('Type a branch name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
public function loadResults() {
$viewer = $this->getViewer();
$raw_query = $this->getRawQuery();
$query = id(new PhabricatorRepositoryRefCursorQuery())
->withDatasourceQuery($raw_query);
$types = $this->getParameter('refTypes');
if ($types) {
$query->withRefTypes($types);
}
$repository_phids = $this->getParameter('repositoryPHIDs');
if ($repository_phids) {
$query->withRepositoryPHIDs($repository_phids);
}
$refs = $this->executeQuery($query);
$results = array();
foreach ($refs as $ref) {
$results[] = id(new PhabricatorTypeaheadResult())
->setName($ref->getRefName())
->setPHID($ref->getPHID());
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/typeahead/DiffusionTaggedRepositoriesFunctionDatasource.php | src/applications/diffusion/typeahead/DiffusionTaggedRepositoriesFunctionDatasource.php | <?php
final class DiffusionTaggedRepositoriesFunctionDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Repositories');
}
public function getPlaceholderText() {
return pht('Type tagged(<project>)...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorProjectApplication';
}
public function getComponentDatasources() {
return array(
new PhabricatorProjectDatasource(),
);
}
public function getDatasourceFunctions() {
return array(
'tagged' => array(
'name' => pht('Repositories: ...'),
'arguments' => pht('project'),
'summary' => pht('Find results for repositories of a project.'),
'description' => pht(
'This function allows you to find results for any of the `.
`repositories of a project:'.
"\n\n".
'> tagged(engineering)'),
),
);
}
protected function didLoadResults(array $results) {
foreach ($results as $result) {
$result
->setTokenType(PhabricatorTypeaheadTokenView::TYPE_FUNCTION)
->setColor(null)
->setPHID('tagged('.$result->getPHID().')')
->setDisplayName(pht('Tagged: %s', $result->getDisplayName()))
->setName('tagged '.$result->getName())
->resetAttributes()
->addAttribute(pht('Function'))
->addAttribute(pht('Select repositories tagged with this project.'));
}
return $results;
}
protected function evaluateFunction($function, array $argv_list) {
$phids = array();
foreach ($argv_list as $argv) {
$phids[] = head($argv);
}
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($this->getViewer())
->withEdgeLogicPHIDs(
PhabricatorProjectObjectHasProjectEdgeType::EDGECONST,
PhabricatorQueryConstraint::OPERATOR_OR,
$phids)
->execute();
$results = array();
foreach ($repositories as $repository) {
$results[] = $repository->getPHID();
}
if (!$results) {
// TODO: This is a little hacky, but if you query for "tagged(x)" and
// there are no such repositories, we want to match nothing. If we
// just return `array()`, that gets evaluated as "no constraint" and
// we match everything. This works correctly for now, but should be
// replaced with some more elegant/general approach eventually.
$results[] = PhabricatorPHIDConstants::PHID_VOID;
}
return $results;
}
public function renderFunctionTokens($function, array $argv_list) {
$phids = array();
foreach ($argv_list as $argv) {
$phids[] = head($argv);
}
$tokens = $this->renderTokens($phids);
foreach ($tokens as $token) {
// Remove any project color on this token.
$token->setColor(null);
if ($token->isInvalid()) {
$token
->setValue(pht('Repositories: Invalid Project'));
} else {
$token
->setTokenType(PhabricatorTypeaheadTokenView::TYPE_FUNCTION)
->setKey('tagged('.$token->getKey().')')
->setValue(pht('Tagged: %s', $token->getValue()));
}
}
return $tokens;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/typeahead/DiffusionSymbolDatasource.php | src/applications/diffusion/typeahead/DiffusionSymbolDatasource.php | <?php
final class DiffusionSymbolDatasource
extends PhabricatorTypeaheadDatasource {
public function isBrowsable() {
// This is slightly involved to make browsable, and browsing symbols
// does not seem likely to be very useful in any real software project.
return false;
}
public function getBrowseTitle() {
return pht('Browse Symbols');
}
public function getPlaceholderText() {
return pht('Type a symbol name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
public function loadResults() {
$viewer = $this->getViewer();
$raw_query = $this->getRawQuery();
$results = array();
if (strlen($raw_query)) {
$symbols = id(new DiffusionSymbolQuery())
->setViewer($viewer)
->setNamePrefix($raw_query)
->setLimit(15)
->needRepositories(true)
->needPaths(true)
->execute();
foreach ($symbols as $symbol) {
$lang = $symbol->getSymbolLanguage();
$name = $symbol->getSymbolName();
$type = $symbol->getSymbolType();
$repo = $symbol->getRepository()->getName();
$results[] = id(new PhabricatorTypeaheadResult())
->setName($name)
->setURI($symbol->getURI())
->setPHID(md5($symbol->getURI())) // Just needs to be unique.
->setDisplayName($name)
->setDisplayType(strtoupper($lang).' '.ucwords($type).' ('.$repo.')')
->setPriorityType('symb')
->setImageSprite(
'phabricator-search-icon phui-font-fa phui-icon-view fa-code '.
'lightgreytext');
}
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/typeahead/DiffusionIdentityUnassignedDatasource.php | src/applications/diffusion/typeahead/DiffusionIdentityUnassignedDatasource.php | <?php
final class DiffusionIdentityUnassignedDatasource
extends PhabricatorTypeaheadDatasource {
const FUNCTION_TOKEN = 'unassigned()';
public function getBrowseTitle() {
return pht('Browse Explicitly Unassigned');
}
public function getPlaceholderText() {
return pht('Type "unassigned"...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
public function getDatasourceFunctions() {
return array(
'unassigned' => array(
'name' => pht('Explicitly Unassigned'),
'summary' => pht('Find results which are not assigned.'),
'description' => pht(
"This function includes results which have been explicitly ".
"unassigned. Use a query like this to find explicitly ".
"unassigned results:\n\n%s\n\n".
"If you combine this function with other functions, the query will ".
"return results which match the other selectors //or// have no ".
"assignee. For example, this query will find results which are ".
"assigned to `alincoln`, and will also find results which have been ".
"unassigned:\n\n%s",
'> unassigned()',
'> alincoln, unassigned()'),
),
);
}
public function loadResults() {
$results = array(
$this->buildUnassignedResult(),
);
return $this->filterResultsAgainstTokens($results);
}
protected function evaluateFunction($function, array $argv_list) {
$results = array();
foreach ($argv_list as $argv) {
$results[] = self::FUNCTION_TOKEN;
}
return $results;
}
public function renderFunctionTokens($function, array $argv_list) {
$results = array();
foreach ($argv_list as $argv) {
$results[] = PhabricatorTypeaheadTokenView::newFromTypeaheadResult(
$this->buildUnassignedResult());
}
return $results;
}
private function buildUnassignedResult() {
$name = pht('Unassigned');
return $this->newFunctionResult()
->setName($name.' unassigned')
->setDisplayName($name)
->setIcon('fa-ban')
->setPHID('unassigned()')
->setUnique(true)
->addAttribute(pht('Select results with no owner.'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/capability/DiffusionDefaultEditCapability.php | src/applications/diffusion/capability/DiffusionDefaultEditCapability.php | <?php
final class DiffusionDefaultEditCapability extends PhabricatorPolicyCapability {
const CAPABILITY = 'diffusion.default.edit';
public function getCapabilityName() {
return pht('Default Edit Policy');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/capability/DiffusionCreateRepositoriesCapability.php | src/applications/diffusion/capability/DiffusionCreateRepositoriesCapability.php | <?php
final class DiffusionCreateRepositoriesCapability
extends PhabricatorPolicyCapability {
const CAPABILITY = 'diffusion.create';
public function getCapabilityName() {
return pht('Can Create Repositories');
}
public function describeCapabilityRejection() {
return pht('You do not have permission to create new repositories.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/capability/DiffusionDefaultViewCapability.php | src/applications/diffusion/capability/DiffusionDefaultViewCapability.php | <?php
final class DiffusionDefaultViewCapability extends PhabricatorPolicyCapability {
const CAPABILITY = 'diffusion.default.view';
public function getCapabilityName() {
return pht('Default View Policy');
}
public function shouldAllowPublicPolicySetting() {
return true;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/capability/DiffusionPushCapability.php | src/applications/diffusion/capability/DiffusionPushCapability.php | <?php
final class DiffusionPushCapability extends PhabricatorPolicyCapability {
const CAPABILITY = 'diffusion.push';
public function getCapabilityName() {
return pht('Can Push');
}
public function describeCapabilityRejection() {
return pht('You do not have permission to push to this repository.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/capability/DiffusionDefaultPushCapability.php | src/applications/diffusion/capability/DiffusionDefaultPushCapability.php | <?php
final class DiffusionDefaultPushCapability extends PhabricatorPolicyCapability {
const CAPABILITY = 'diffusion.default.push';
public function getCapabilityName() {
return pht('Default Push Policy');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/symbol/DiffusionPhpExternalSymbolsSource.php | src/applications/diffusion/symbol/DiffusionPhpExternalSymbolsSource.php | <?php
final class DiffusionPhpExternalSymbolsSource
extends DiffusionExternalSymbolsSource {
public function executeQuery(DiffusionExternalSymbolQuery $query) {
$symbols = array();
if (!$query->matchesAnyLanguage(array('php'))) {
return $symbols;
}
$names = $query->getNames();
if ($query->matchesAnyType(array('function'))) {
$functions = get_defined_functions();
$functions = $functions['internal'];
foreach ($names as $name) {
if (in_array($name, $functions)) {
$symbols[] = $this->buildExternalSymbol()
->setSymbolName($name)
->setSymbolType('function')
->setSource(pht('PHP'))
->setLocation(pht('Manual at php.net'))
->setSymbolLanguage('php')
->setExternalURI('http://www.php.net/function.'.$name);
}
}
}
if ($query->matchesAnyType(array('class'))) {
foreach ($names as $name) {
if (class_exists($name, false) || interface_exists($name, false)) {
if (id(new ReflectionClass($name))->isInternal()) {
$symbols[] = $this->buildExternalSymbol()
->setSymbolName($name)
->setSymbolType('class')
->setSource(pht('PHP'))
->setLocation(pht('Manual at php.net'))
->setSymbolLanguage('php')
->setExternalURI('http://www.php.net/class.'.$name);
}
}
}
}
return $symbols;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/symbol/DiffusionExternalSymbolsSource.php | src/applications/diffusion/symbol/DiffusionExternalSymbolsSource.php | <?php
abstract class DiffusionExternalSymbolsSource extends Phobject {
/**
* @return list of PhabricatorRepositorySymbol
*/
abstract public function executeQuery(DiffusionExternalSymbolQuery $query);
protected function buildExternalSymbol() {
return id(new PhabricatorRepositorySymbol())
->setIsExternal(true)
->makeEphemeral();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/symbol/DiffusionExternalSymbolQuery.php | src/applications/diffusion/symbol/DiffusionExternalSymbolQuery.php | <?php
final class DiffusionExternalSymbolQuery extends Phobject {
private $languages = array();
private $types = array();
private $names = array();
private $contexts = array();
private $paths = array();
private $lines = array();
private $repositories = array();
private $characterPositions = array();
public function withLanguages(array $languages) {
$this->languages = $languages;
return $this;
}
public function withTypes(array $types) {
$this->types = $types;
return $this;
}
public function withNames(array $names) {
$this->names = $names;
return $this;
}
public function withContexts(array $contexts) {
$this->contexts = $contexts;
return $this;
}
public function withPaths(array $paths) {
$this->paths = $paths;
return $this;
}
public function withLines(array $lines) {
$this->lines = $lines;
return $this;
}
public function withCharacterPositions(array $positions) {
$this->characterPositions = $positions;
return $this;
}
public function withRepositories(array $repositories) {
assert_instances_of($repositories, 'PhabricatorRepository');
$this->repositories = $repositories;
return $this;
}
public function getLanguages() {
return $this->languages;
}
public function getTypes() {
return $this->types;
}
public function getNames() {
return $this->names;
}
public function getContexts() {
return $this->contexts;
}
public function getPaths() {
return $this->paths;
}
public function getLines() {
return $this->lines;
}
public function getRepositories() {
return $this->repositories;
}
public function getCharacterPositions() {
return $this->characterPositions;
}
public function matchesAnyLanguage(array $languages) {
return (!$this->languages) || array_intersect($languages, $this->languages);
}
public function matchesAnyType(array $types) {
return (!$this->types) || array_intersect($types, $this->types);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/symbol/DiffusionPythonExternalSymbolsSource.php | src/applications/diffusion/symbol/DiffusionPythonExternalSymbolsSource.php | <?php
final class DiffusionPythonExternalSymbolsSource
extends DiffusionExternalSymbolsSource {
public function executeQuery(DiffusionExternalSymbolQuery $query) {
$symbols = array();
if (!$query->matchesAnyLanguage(array('py', 'python'))) {
return $symbols;
}
if (!$query->matchesAnyType(array('builtin', 'function'))) {
return $symbols;
}
$names = $query->getNames();
foreach ($names as $name) {
if (idx(self::$python2Builtins, $name)) {
$symbols[] = $this->buildExternalSymbol()
->setSymbolName($name)
->setSymbolType('function')
->setSource(pht('Standard Library'))
->setLocation(pht('The Python 2 Standard Library'))
->setSymbolLanguage('py')
->setExternalURI(
'https://docs.python.org/2/library/functions.html#'.$name);
}
if (idx(self::$python3Builtins, $name)) {
$symbols[] = $this->buildExternalSymbol()
->setSymbolName($name)
->setSymbolType('function')
->setSource(pht('Standard Library'))
->setLocation(pht('The Python 3 Standard Library'))
->setSymbolLanguage('py')
->setExternalURI(
'https://docs.python.org/3/library/functions.html#'.$name);
}
}
return $symbols;
}
private static $python2Builtins = array(
'__import__' => true,
'abs' => true,
'all' => true,
'any' => true,
'basestring' => true,
'bin' => true,
'bool' => true,
'bytearray' => true,
'callable' => true,
'chr' => true,
'classmethod' => true,
'cmp' => true,
'compile' => true,
'complex' => true,
'delattr' => true,
'dict' => true,
'dir' => true,
'divmod' => true,
'enumerate' => true,
'eval' => true,
'execfile' => true,
'file' => true,
'filter' => true,
'float' => true,
'format' => true,
'frozenset' => true,
'getattr' => true,
'globals' => true,
'hasattr' => true,
'hash' => true,
'help' => true,
'hex' => true,
'id' => true,
'input' => true,
'int' => true,
'isinstance' => true,
'issubclass' => true,
'iter' => true,
'len' => true,
'list' => true,
'locals' => true,
'long' => true,
'map' => true,
'max' => true,
'memoryview' => true,
'min' => true,
'next' => true,
'object' => true,
'oct' => true,
'open' => true,
'ord' => true,
'pow' => true,
'print' => true,
'property' => true,
'range' => true,
'raw_input' => true,
'reduce' => true,
'reload' => true,
'repr' => true,
'reversed' => true,
'round' => true,
'set' => true,
'setattr' => true,
'slice' => true,
'sorted' => true,
'staticmethod' => true,
'str' => true,
'sum' => true,
'super' => true,
'tuple' => true,
'type' => true,
'unichr' => true,
'unicode' => true,
'vars' => true,
'xrange' => true,
'zip' => true,
);
// This list only contains functions that are new or changed between the
// Python versions.
private static $python3Builtins = array(
'ascii' => true,
'bytes' => true,
'filter' => true,
'map' => true,
'next' => true,
'range' => true,
'super' => true,
'zip' => true,
);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/ref/DiffusionServiceRef.php | src/applications/diffusion/ref/DiffusionServiceRef.php | <?php
final class DiffusionServiceRef
extends Phobject {
private $uri;
private $protocol;
private $isWritable;
private $devicePHID;
private $deviceName;
private function __construct() {
return;
}
public static function newFromDictionary(array $map) {
$ref = new self();
$ref->uri = $map['uri'];
$ref->isWritable = $map['writable'];
$ref->devicePHID = $map['devicePHID'];
$ref->protocol = $map['protocol'];
$ref->deviceName = $map['device'];
return $ref;
}
public function isWritable() {
return $this->isWritable;
}
public function getDevicePHID() {
return $this->devicePHID;
}
public function getURI() {
return $this->uri;
}
public function getProtocol() {
return $this->protocol;
}
public function getDeviceName() {
return $this->deviceName;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/identity/DiffusionRepositoryIdentityDestructionEngineExtension.php | src/applications/diffusion/identity/DiffusionRepositoryIdentityDestructionEngineExtension.php | <?php
final class DiffusionRepositoryIdentityDestructionEngineExtension
extends PhabricatorDestructionEngineExtension {
const EXTENSIONKEY = 'repository-identities';
public function getExtensionName() {
return pht('Repository Identities');
}
public function didDestroyObject(
PhabricatorDestructionEngine $engine,
$object) {
// When users or email addresses are destroyed, queue a task to update
// any repository identities that are associated with them. See T13444.
$related_phids = array();
$email_addresses = array();
if ($object instanceof PhabricatorUser) {
$related_phids[] = $object->getPHID();
}
if ($object instanceof PhabricatorUserEmail) {
$email_addresses[] = $object->getAddress();
}
if ($related_phids || $email_addresses) {
PhabricatorWorker::scheduleTask(
'PhabricatorRepositoryIdentityChangeWorker',
array(
'relatedPHIDs' => $related_phids,
'emailAddresses' => $email_addresses,
));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/identity/DiffusionRepositoryIdentityEngine.php | src/applications/diffusion/identity/DiffusionRepositoryIdentityEngine.php | <?php
final class DiffusionRepositoryIdentityEngine
extends Phobject {
private $viewer;
private $sourcePHID;
private $dryRun;
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setSourcePHID($source_phid) {
$this->sourcePHID = $source_phid;
return $this;
}
public function getSourcePHID() {
if (!$this->sourcePHID) {
throw new PhutilInvalidStateException('setSourcePHID');
}
return $this->sourcePHID;
}
public function setDryRun($dry_run) {
$this->dryRun = $dry_run;
return $this;
}
public function getDryRun() {
return $this->dryRun;
}
public function newResolvedIdentity($raw_identity) {
$identity = $this->loadRawIdentity($raw_identity);
if (!$identity) {
$identity = $this->newIdentity($raw_identity);
}
return $this->updateIdentity($identity);
}
public function newUpdatedIdentity(PhabricatorRepositoryIdentity $identity) {
return $this->updateIdentity($identity);
}
private function loadRawIdentity($raw_identity) {
$viewer = $this->getViewer();
return id(new PhabricatorRepositoryIdentityQuery())
->setViewer($viewer)
->withIdentityNames(array($raw_identity))
->executeOne();
}
private function newIdentity($raw_identity) {
$source_phid = $this->getSourcePHID();
return id(new PhabricatorRepositoryIdentity())
->setAuthorPHID($source_phid)
->setIdentityName($raw_identity);
}
private function resolveIdentity(PhabricatorRepositoryIdentity $identity) {
$raw_identity = $identity->getIdentityName();
return id(new DiffusionResolveUserQuery())
->withName($raw_identity)
->execute();
}
private function updateIdentity(PhabricatorRepositoryIdentity $identity) {
// If we're updating an identity and it has a manual user PHID associated
// with it but the user is no longer valid, remove the value. This likely
// corresponds to a user that was destroyed.
$assigned_phid = $identity->getManuallySetUserPHID();
$unassigned = DiffusionIdentityUnassignedDatasource::FUNCTION_TOKEN;
if ($assigned_phid && ($assigned_phid !== $unassigned)) {
$viewer = $this->getViewer();
$user = id(new PhabricatorPeopleQuery())
->setViewer($viewer)
->withPHIDs(array($assigned_phid))
->executeOne();
if (!$user) {
$identity->setManuallySetUserPHID(null);
}
}
$resolved_phid = $this->resolveIdentity($identity);
$identity->setAutomaticGuessedUserPHID($resolved_phid);
if ($this->getDryRun()) {
$identity->makeEphemeral();
} else {
$identity->save();
}
return $identity;
}
public function didUpdateEmailAddress($raw_address) {
PhabricatorWorker::scheduleTask(
'PhabricatorRepositoryIdentityChangeWorker',
array(
'emailAddresses' => array($raw_address),
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/response/DiffusionMercurialResponse.php | src/applications/diffusion/response/DiffusionMercurialResponse.php | <?php
final class DiffusionMercurialResponse extends AphrontResponse {
private $content;
public function setContent($content) {
$this->content = $content;
return $this;
}
public function buildResponseString() {
return $this->content;
}
public function getHeaders() {
$headers = array(
array('Content-Type', 'application/mercurial-0.1'),
);
return array_merge(parent::getHeaders(), $headers);
}
public function getCacheHeaders() {
return array();
}
public function getHTTPResponseCode() {
return 200;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/response/DiffusionGitLFSResponse.php | src/applications/diffusion/response/DiffusionGitLFSResponse.php | <?php
final class DiffusionGitLFSResponse extends AphrontResponse {
private $content;
public static function newErrorResponse($code, $message) {
// We can optionally include "request_id" and "documentation_url" in
// this response.
return id(new self())
->setHTTPResponseCode($code)
->setContent(
array(
'message' => $message,
));
}
public function setContent(array $content) {
$this->content = phutil_json_encode($content);
return $this;
}
public function buildResponseString() {
return $this->content;
}
public function getHeaders() {
$headers = array(
array('Content-Type', 'application/vnd.git-lfs+json'),
);
return array_merge(parent::getHeaders(), $headers);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/response/DiffusionGitResponse.php | src/applications/diffusion/response/DiffusionGitResponse.php | <?php
final class DiffusionGitResponse extends AphrontResponse {
private $httpCode;
private $headers = array();
private $response;
public function setGitData($data) {
list($headers, $body) = explode("\r\n\r\n", $data, 2);
$this->response = $body;
$headers = explode("\r\n", $headers);
$matches = null;
$this->httpCode = 200;
$this->headers = array();
foreach ($headers as $header) {
if (preg_match('/^Status:\s*(\d+)/i', $header, $matches)) {
$this->httpCode = (int)$matches[1];
} else {
$this->headers[] = explode(': ', $header, 2);
}
}
return $this;
}
public function buildResponseString() {
return $this->response;
}
public function getHeaders() {
return array_merge(parent::getHeaders(), $this->headers);
}
public function getCacheHeaders() {
return array();
}
public function getHTTPResponseCode() {
return $this->httpCode;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/remarkup/DiffusionRepositoryByIDRemarkupRule.php | src/applications/diffusion/remarkup/DiffusionRepositoryByIDRemarkupRule.php | <?php
final class DiffusionRepositoryByIDRemarkupRule
extends PhabricatorObjectRemarkupRule {
protected function getObjectNamePrefix() {
return 'R';
}
protected function getObjectIDPattern() {
return '[0-9]+';
}
public function getPriority() {
return 460.0;
}
protected function loadObjects(array $ids) {
$viewer = $this->getEngine()->getConfig('viewer');
$repos = id(new PhabricatorRepositoryQuery())
->setViewer($viewer)
->withIdentifiers($ids);
$repos->execute();
return $repos->getIdentifierMap();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/remarkup/DiffusionSourceLinkRemarkupRule.php | src/applications/diffusion/remarkup/DiffusionSourceLinkRemarkupRule.php | <?php
final class DiffusionSourceLinkRemarkupRule
extends PhutilRemarkupRule {
const KEY_SOURCELINKS = 'diffusion.links';
public function getPriority() {
return 200.0;
}
public function apply($text) {
return preg_replace_callback(
'@{(?:src|source)\b((?:[^}\\\\]+|\\\\.)*)}@m',
array($this, 'markupSourceLink'),
$text);
}
public function markupSourceLink(array $matches) {
$engine = $this->getEngine();
$text_mode = $engine->isTextMode();
$mail_mode = $engine->isHTMLMailMode();
if (!$this->isFlatText($matches[0]) || $text_mode || $mail_mode) {
// We could do better than this in text mode and mail mode, but focus
// on web mode first.
return $matches[0];
}
$metadata_key = self::KEY_SOURCELINKS;
$metadata = $engine->getTextMetadata($metadata_key, array());
$token = $engine->storeText($matches[0]);
$metadata[] = array(
'token' => $token,
'raw' => $matches[0],
'input' => $matches[1],
);
$engine->setTextMetadata($metadata_key, $metadata);
return $token;
}
public function didMarkupText() {
$engine = $this->getEngine();
$metadata_key = self::KEY_SOURCELINKS;
$metadata = $engine->getTextMetadata($metadata_key, array());
if (!$metadata) {
return;
}
$viewer = $engine->getConfig('viewer');
if (!$viewer) {
return;
}
$defaults = array(
'repository' => null,
'line' => null,
'commit' => null,
'ref' => null,
);
$tags = array();
foreach ($metadata as $ref) {
$token = $ref['token'];
$raw = $ref['raw'];
$input = $ref['input'];
$pattern =
'(^'.
'[\s,]*'.
'(?:"(?P<quotedpath>(?:[^\\\\"]+|\\.)+)"|(?P<rawpath>[^\s,]+))'.
'[\s,]*'.
'(?P<options>.*)'.
'\z)';
$matches = null;
if (!preg_match($pattern, $input, $matches)) {
$hint_text = pht(
'Missing path, expected "{src path ...}" in: %s',
$raw);
$hint = $this->newSyntaxHint($hint_text);
$engine->overwriteStoredText($token, $hint);
continue;
}
$path = idx($matches, 'rawpath');
if (!strlen($path)) {
$path = idx($matches, 'quotedpath');
$path = stripcslashes($path);
}
$parts = explode(':', $path, 2);
if (count($parts) == 2) {
$repository = nonempty($parts[0], null);
$path = $parts[1];
} else {
$repository = null;
$path = $parts[0];
}
$options = $matches['options'];
$parser = new PhutilSimpleOptions();
$options = $parser->parse($options) + $defaults;
foreach ($options as $key => $value) {
if (!array_key_exists($key, $defaults)) {
$hint_text = pht(
'Unknown option "%s" in: %s',
$key,
$raw);
$hint = $this->newSyntaxHint($hint_text);
$engine->overwriteStoredText($token, $hint);
continue 2;
}
}
if ($options['repository'] !== null) {
$repository = $options['repository'];
}
if ($repository === null) {
$hint_text = pht(
'Missing repository, expected "{src repository:path ...}" '.
'or "{src path repository=...}" in: %s',
$raw);
$hint = $this->newSyntaxHint($hint_text);
$engine->overwriteStoredText($token, $hint);
continue;
}
$tags[] = array(
'token' => $token,
'raw' => $raw,
'identifier' => $repository,
'path' => $path,
'options' => $options,
);
}
if (!$tags) {
return;
}
$query = id(new PhabricatorRepositoryQuery())
->setViewer($viewer)
->withIdentifiers(ipull($tags, 'identifier'));
$query->execute();
$repository_map = $query->getIdentifierMap();
foreach ($tags as $tag) {
$token = $tag['token'];
$identifier = $tag['identifier'];
$repository = idx($repository_map, $identifier);
if (!$repository) {
// For now, just bail out here. Ideally, we should distingiush between
// restricted and invalid repositories.
continue;
}
$drequest = DiffusionRequest::newFromDictionary(
array(
'user' => $viewer,
'repository' => $repository,
));
$options = $tag['options'];
$line = $options['line'];
$commit = $options['commit'];
$ref_name = $options['ref'];
$link_uri = $drequest->generateURI(
array(
'action' => 'browse',
'path' => $tag['path'],
'commit' => $commit,
'line' => $line,
'branch' => $ref_name,
));
$view = id(new DiffusionSourceLinkView())
->setRepository($repository)
->setPath($tag['path'])
->setURI($link_uri);
if ($line !== null) {
$view->setLine($line);
}
if ($commit !== null) {
$view->setCommit($commit);
}
if ($ref_name !== null) {
$view->setRefName($ref_name);
}
$engine->overwriteStoredText($token, $view);
}
}
private function newSyntaxHint($text) {
return id(new PHUITagView())
->setType(PHUITagView::TYPE_SHADE)
->setColor('red')
->setIcon('fa-exclamation-triangle')
->setName($text);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/remarkup/DiffusionRepositoryRemarkupRule.php | src/applications/diffusion/remarkup/DiffusionRepositoryRemarkupRule.php | <?php
final class DiffusionRepositoryRemarkupRule
extends PhabricatorObjectRemarkupRule {
protected function getObjectNamePrefix() {
return 'r';
}
protected function getObjectIDPattern() {
return '[A-Z]+';
}
public function getPriority() {
return 460.0;
}
protected function loadObjects(array $ids) {
$viewer = $this->getEngine()->getConfig('viewer');
$repos = id(new PhabricatorRepositoryQuery())
->setViewer($viewer)
->withIdentifiers($ids);
$repos->execute();
return $repos->getIdentifierMap();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/remarkup/DiffusionCommitRemarkupRule.php | src/applications/diffusion/remarkup/DiffusionCommitRemarkupRule.php | <?php
final class DiffusionCommitRemarkupRule extends PhabricatorObjectRemarkupRule {
protected function getObjectNamePrefix() {
return '';
}
protected function getObjectNamePrefixBeginsWithWordCharacter() {
return true;
}
protected function getObjectIDPattern() {
return PhabricatorRepositoryCommitPHIDType::getCommitObjectNamePattern();
}
protected function getObjectNameText(
$object,
PhabricatorObjectHandle $handle,
$id) {
// If this commit is unreachable, return the handle name instead of the
// normal text because it may be able to tell the user that the commit
// was rewritten and where to find the new one.
// By default, we try to preserve what the user actually typed as
// faithfully as possible, but if they're referencing a deleted commit
// it's more valuable to try to pick up any rewrite. See T11522.
if ($object->isUnreachable()) {
return $handle->getName();
}
return parent::getObjectNameText($object, $handle, $id);
}
protected function loadObjects(array $ids) {
$viewer = $this->getEngine()->getConfig('viewer');
$query = id(new DiffusionCommitQuery())
->setViewer($viewer)
->withIdentifiers($ids);
$query->execute();
return $query->getIdentifierMap();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/remarkup/__tests__/DiffusionCommitRemarkupRuleTestCase.php | src/applications/diffusion/remarkup/__tests__/DiffusionCommitRemarkupRuleTestCase.php | <?php
final class DiffusionCommitRemarkupRuleTestCase extends PhabricatorTestCase {
public function testProjectObjectRemarkup() {
$cases = array(
'{rP12f3f6d3a9ef9c7731051815846810cb3c4cd248}' => array(
'embed' => array(
array(
'offset' => 1,
'id' => 'rP12f3f6d3a9ef9c7731051815846810cb3c4cd248',
),
),
'ref' => array(
array(
'offset' => 1,
'id' => 'rP12f3f6d3a9ef9c7731051815846810cb3c4cd248',
),
),
),
'{rP1234, key=value}' => array(
'embed' => array(
array(
'offset' => 1,
'id' => 'rP1234',
'tail' => ', key=value',
),
),
'ref' => array(
array(
'offset' => 1,
'id' => 'rP1234',
),
),
),
'{rP1234 key=value}' => array(
'embed' => array(
array(
'offset' => 1,
'id' => 'rP1234',
'tail' => ' key=value',
),
),
'ref' => array(
array(
'offset' => 1,
'id' => 'rP1234',
),
),
),
'{rP:1234 key=value}' => array(
'embed' => array(
array(
'offset' => 1,
'id' => 'rP:1234',
'tail' => ' key=value',
),
),
'ref' => array(
array(
'offset' => 1,
'id' => 'rP:1234',
),
),
),
'{R123:1234 key=value}' => array(
'embed' => array(
array(
'offset' => 1,
'id' => 'R123:1234',
'tail' => ' key=value',
),
),
'ref' => array(
array(
'offset' => 1,
'id' => 'R123:1234',
),
),
),
'{rP:12f3f6d3a9ef9c7731051815846810cb3c4cd248}' => array(
'embed' => array(
array(
'offset' => 1,
'id' => 'rP:12f3f6d3a9ef9c7731051815846810cb3c4cd248',
),
),
'ref' => array(
array(
'offset' => 1,
'id' => 'rP:12f3f6d3a9ef9c7731051815846810cb3c4cd248',
),
),
),
'{R123:12f3f6d3a9ef9c7731051815846810cb3c4cd248}' => array(
'embed' => array(
array(
'offset' => 1,
'id' => 'R123:12f3f6d3a9ef9c7731051815846810cb3c4cd248',
),
),
'ref' => array(
array(
'offset' => 1,
'id' => 'R123:12f3f6d3a9ef9c7731051815846810cb3c4cd248',
),
),
),
'{R123:12f3f6d3a9ef9c7731051815846810cb3c4cd248, key=value}' => array(
'embed' => array(
array(
'offset' => 1,
'id' => 'R123:12f3f6d3a9ef9c7731051815846810cb3c4cd248',
'tail' => ', key=value',
),
),
'ref' => array(
array(
'offset' => 1,
'id' => 'R123:12f3f6d3a9ef9c7731051815846810cb3c4cd248',
),
),
),
// After an "@", we should not be recognizing references because these
// are username mentions.
'deadbeef' => array(
'embed' => array(
),
'ref' => array(
array(
'offset' => 0,
'id' => 'deadbeef',
),
),
),
'@deadbeef' => array(
'embed' => array(
),
'ref' => array(
),
),
);
foreach ($cases as $input => $expect) {
$rule = new DiffusionCommitRemarkupRule();
$matches = $rule->extractReferences($input);
$this->assertEqual($expect, $matches, $input);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/request/DiffusionMercurialRequest.php | src/applications/diffusion/request/DiffusionMercurialRequest.php | <?php
final class DiffusionMercurialRequest extends DiffusionRequest {
protected function isStableCommit($symbol) {
return $symbol !== null && preg_match('/^[a-f0-9]{40}\z/', $symbol);
}
public function getBranch() {
if ($this->branch) {
return $this->branch;
}
if ($this->repository) {
return $this->repository->getDefaultBranch();
}
throw new Exception(pht('Unable to determine branch!'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/request/DiffusionSvnRequest.php | src/applications/diffusion/request/DiffusionSvnRequest.php | <?php
final class DiffusionSvnRequest extends DiffusionRequest {
protected function isStableCommit($symbol) {
return $symbol !== null && preg_match('/^[1-9]\d*\z/', $symbol);
}
protected function didInitialize() {
if ($this->path === null) {
$subpath = $this->repository->getDetail('svn-subpath');
if ($subpath) {
$this->path = $subpath;
}
}
}
protected function getArcanistBranch() {
return 'svn';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/request/DiffusionRequest.php | src/applications/diffusion/request/DiffusionRequest.php | <?php
/**
* Contains logic to parse Diffusion requests, which have a complicated URI
* structure.
*
* @task new Creating Requests
* @task uri Managing Diffusion URIs
*/
abstract class DiffusionRequest extends Phobject {
protected $path;
protected $line;
protected $branch;
protected $lint;
protected $symbolicCommit;
protected $symbolicType;
protected $stableCommit;
protected $repository;
protected $repositoryCommit;
protected $repositoryCommitData;
private $isClusterRequest = false;
private $initFromConduit = true;
private $user;
private $branchObject = false;
private $refAlternatives;
final public function supportsBranches() {
return $this->getRepository()->supportsRefs();
}
abstract protected function isStableCommit($symbol);
protected function didInitialize() {
return null;
}
/* -( Creating Requests )-------------------------------------------------- */
/**
* Create a new synthetic request from a parameter dictionary. If you need
* a @{class:DiffusionRequest} object in order to issue a DiffusionQuery, you
* can use this method to build one.
*
* Parameters are:
*
* - `repository` Repository object or identifier.
* - `user` Viewing user. Required if `repository` is an identifier.
* - `branch` Optional, branch name.
* - `path` Optional, file path.
* - `commit` Optional, commit identifier.
* - `line` Optional, line range.
*
* @param map See documentation.
* @return DiffusionRequest New request object.
* @task new
*/
final public static function newFromDictionary(array $data) {
$repository_key = 'repository';
$identifier_key = 'callsign';
$viewer_key = 'user';
$repository = idx($data, $repository_key);
$identifier = idx($data, $identifier_key);
$have_repository = ($repository !== null);
$have_identifier = ($identifier !== null);
if ($have_repository && $have_identifier) {
throw new Exception(
pht(
'Specify "%s" or "%s", but not both.',
$repository_key,
$identifier_key));
}
if (!$have_repository && !$have_identifier) {
throw new Exception(
pht(
'One of "%s" and "%s" is required.',
$repository_key,
$identifier_key));
}
if ($have_repository) {
if (!($repository instanceof PhabricatorRepository)) {
if (empty($data[$viewer_key])) {
throw new Exception(
pht(
'Parameter "%s" is required if "%s" is provided.',
$viewer_key,
$identifier_key));
}
$identifier = $repository;
$repository = null;
}
}
if ($identifier !== null) {
$object = self::newFromIdentifier(
$identifier,
$data[$viewer_key],
idx($data, 'edit'));
} else {
$object = self::newFromRepository($repository);
}
if (!$object) {
return null;
}
$object->initializeFromDictionary($data);
return $object;
}
/**
* Internal.
*
* @task new
*/
private function __construct() {
// <private>
}
/**
* Internal. Use @{method:newFromDictionary}, not this method.
*
* @param string Repository identifier.
* @param PhabricatorUser Viewing user.
* @return DiffusionRequest New request object.
* @task new
*/
private static function newFromIdentifier(
$identifier,
PhabricatorUser $viewer,
$need_edit = false) {
$query = id(new PhabricatorRepositoryQuery())
->setViewer($viewer)
->withIdentifiers(array($identifier))
->needProfileImage(true)
->needURIs(true);
if ($need_edit) {
$query->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
));
}
$repository = $query->executeOne();
if (!$repository) {
return null;
}
return self::newFromRepository($repository);
}
/**
* Internal. Use @{method:newFromDictionary}, not this method.
*
* @param PhabricatorRepository Repository object.
* @return DiffusionRequest New request object.
* @task new
*/
private static function newFromRepository(
PhabricatorRepository $repository) {
$map = array(
PhabricatorRepositoryType::REPOSITORY_TYPE_GIT => 'DiffusionGitRequest',
PhabricatorRepositoryType::REPOSITORY_TYPE_SVN => 'DiffusionSvnRequest',
PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL =>
'DiffusionMercurialRequest',
);
$class = idx($map, $repository->getVersionControlSystem());
if (!$class) {
throw new Exception(pht('Unknown version control system!'));
}
$object = new $class();
$object->repository = $repository;
return $object;
}
/**
* Internal. Use @{method:newFromDictionary}, not this method.
*
* @param map Map of parsed data.
* @return void
* @task new
*/
private function initializeFromDictionary(array $data) {
$blob = idx($data, 'blob');
if (phutil_nonempty_string($blob)) {
$blob = self::parseRequestBlob($blob, $this->supportsBranches());
$data = $blob + $data;
}
$this->path = idx($data, 'path');
$this->line = idx($data, 'line');
$this->initFromConduit = idx($data, 'initFromConduit', true);
$this->lint = idx($data, 'lint');
$this->symbolicCommit = idx($data, 'commit');
if ($this->supportsBranches()) {
$this->branch = idx($data, 'branch');
}
if (!$this->getUser()) {
$user = idx($data, 'user');
if (!$user) {
throw new Exception(
pht(
'You must provide a %s in the dictionary!',
'PhabricatorUser'));
}
$this->setUser($user);
}
$this->didInitialize();
}
final public function setUser(PhabricatorUser $user) {
$this->user = $user;
return $this;
}
final public function getUser() {
return $this->user;
}
public function getRepository() {
return $this->repository;
}
public function setPath($path) {
$this->path = $path;
return $this;
}
public function getPath() {
return $this->path;
}
public function getLine() {
return $this->line;
}
public function getCommit() {
// TODO: Probably remove all of this.
if ($this->getSymbolicCommit() !== null) {
return $this->getSymbolicCommit();
}
return $this->getStableCommit();
}
/**
* Get the symbolic commit associated with this request.
*
* A symbolic commit may be a commit hash, an abbreviated commit hash, a
* branch name, a tag name, or an expression like "HEAD^^^". The symbolic
* commit may also be absent.
*
* This method always returns the symbol present in the original request,
* in unmodified form.
*
* See also @{method:getStableCommit}.
*
* @return string|null Symbolic commit, if one was present in the request.
*/
public function getSymbolicCommit() {
return $this->symbolicCommit;
}
/**
* Modify the request to move the symbolic commit elsewhere.
*
* @param string New symbolic commit.
* @return this
*/
public function updateSymbolicCommit($symbol) {
$this->symbolicCommit = $symbol;
$this->symbolicType = null;
$this->stableCommit = null;
return $this;
}
/**
* Get the ref type (`commit` or `tag`) of the location associated with this
* request.
*
* If a symbolic commit is present in the request, this method identifies
* the type of the symbol. Otherwise, it identifies the type of symbol of
* the location the request is implicitly associated with. This will probably
* always be `commit`.
*
* @return string Symbolic commit type (`commit` or `tag`).
*/
public function getSymbolicType() {
if ($this->symbolicType === null) {
// As a side effect, this resolves the symbolic type.
$this->getStableCommit();
}
return $this->symbolicType;
}
/**
* Retrieve the stable, permanent commit name identifying the repository
* location associated with this request.
*
* This returns a non-symbolic identifier for the current commit: in Git and
* Mercurial, a 40-character SHA1; in SVN, a revision number.
*
* See also @{method:getSymbolicCommit}.
*
* @return string Stable commit name, like a git hash or SVN revision. Not
* a symbolic commit reference.
*/
public function getStableCommit() {
if (!$this->stableCommit) {
if ($this->isStableCommit($this->symbolicCommit)) {
$this->stableCommit = $this->symbolicCommit;
$this->symbolicType = 'commit';
} else {
$this->queryStableCommit();
}
}
return $this->stableCommit;
}
public function getBranch() {
return $this->branch;
}
public function getLint() {
return $this->lint;
}
protected function getArcanistBranch() {
return $this->getBranch();
}
public function loadBranch() {
// TODO: Get rid of this and do real Queries on real objects.
if ($this->branchObject === false) {
$this->branchObject = PhabricatorRepositoryBranch::loadBranch(
$this->getRepository()->getID(),
$this->getArcanistBranch());
}
return $this->branchObject;
}
public function loadCoverage() {
// TODO: This should also die.
$branch = $this->loadBranch();
if (!$branch) {
return;
}
$path = $this->getPath();
$path_map = id(new DiffusionPathIDQuery(array($path)))->loadPathIDs();
$coverage_row = queryfx_one(
id(new PhabricatorRepository())->establishConnection('r'),
'SELECT * FROM %T WHERE branchID = %d AND pathID = %d
ORDER BY commitID DESC LIMIT 1',
'repository_coverage',
$branch->getID(),
$path_map[$path]);
if (!$coverage_row) {
return null;
}
return idx($coverage_row, 'coverage');
}
public function loadCommit() {
if (empty($this->repositoryCommit)) {
$repository = $this->getRepository();
$commit = id(new DiffusionCommitQuery())
->setViewer($this->getUser())
->withRepository($repository)
->withIdentifiers(array($this->getStableCommit()))
->executeOne();
if ($commit) {
$commit->attachRepository($repository);
}
$this->repositoryCommit = $commit;
}
return $this->repositoryCommit;
}
public function loadCommitData() {
if (empty($this->repositoryCommitData)) {
$commit = $this->loadCommit();
$data = id(new PhabricatorRepositoryCommitData())->loadOneWhere(
'commitID = %d',
$commit->getID());
if (!$data) {
$data = new PhabricatorRepositoryCommitData();
$data->setCommitMessage(
pht('(This commit has not been fully parsed yet.)'));
}
$this->repositoryCommitData = $data;
}
return $this->repositoryCommitData;
}
/* -( Managing Diffusion URIs )-------------------------------------------- */
public function generateURI(array $params) {
if (empty($params['stable'])) {
$default_commit = $this->getSymbolicCommit();
} else {
$default_commit = $this->getStableCommit();
}
$defaults = array(
'path' => $this->getPath(),
'branch' => $this->getBranch(),
'commit' => $default_commit,
'lint' => idx($params, 'lint', $this->getLint()),
);
foreach ($defaults as $key => $val) {
if (!isset($params[$key])) { // Overwrite NULL.
$params[$key] = $val;
}
}
return $this->getRepository()->generateURI($params);
}
/**
* Internal. Public only for unit tests.
*
* Parse the request URI into components.
*
* @param string URI blob.
* @param bool True if this VCS supports branches.
* @return map Parsed URI.
*
* @task uri
*/
public static function parseRequestBlob($blob, $supports_branches) {
$result = array(
'branch' => null,
'path' => null,
'commit' => null,
'line' => null,
);
$matches = null;
if ($supports_branches) {
// Consume the front part of the URI, up to the first "/". This is the
// path-component encoded branch name.
if (preg_match('@^([^/]+)/@', $blob, $matches)) {
$result['branch'] = phutil_unescape_uri_path_component($matches[1]);
$blob = substr($blob, strlen($matches[1]) + 1);
}
}
// Consume the back part of the URI, up to the first "$". Use a negative
// lookbehind to prevent matching '$$'. We double the '$' symbol when
// encoding so that files with names like "money/$100" will survive.
$pattern = '@(?:(?:^|[^$])(?:[$][$])*)[$]([\d,-]+)$@';
if (preg_match($pattern, $blob, $matches)) {
$result['line'] = $matches[1];
$blob = substr($blob, 0, -(strlen($matches[1]) + 1));
}
// We've consumed the line number if it exists, so unescape "$" in the
// rest of the string.
$blob = str_replace('$$', '$', $blob);
// Consume the commit name, stopping on ';;'. We allow any character to
// appear in commits names, as they can sometimes be symbolic names (like
// tag names or refs).
if (preg_match('@(?:(?:^|[^;])(?:;;)*);([^;].*)$@', $blob, $matches)) {
$result['commit'] = $matches[1];
$blob = substr($blob, 0, -(strlen($matches[1]) + 1));
}
// We've consumed the commit if it exists, so unescape ";" in the rest
// of the string.
$blob = str_replace(';;', ';', $blob);
if (strlen($blob)) {
$result['path'] = $blob;
}
if ($result['path'] !== null) {
$parts = explode('/', $result['path']);
foreach ($parts as $part) {
// Prevent any hyjinx since we're ultimately shipping this to the
// filesystem under a lot of workflows.
if ($part == '..') {
throw new Exception(pht('Invalid path URI.'));
}
}
}
return $result;
}
/**
* Check that the working copy of the repository is present and readable.
*
* @param string Path to the working copy.
*/
protected function validateWorkingCopy($path) {
if (!is_readable(dirname($path))) {
$this->raisePermissionException();
}
if (!Filesystem::pathExists($path)) {
$this->raiseCloneException();
}
}
protected function raisePermissionException() {
$host = php_uname('n');
throw new DiffusionSetupException(
pht(
'The clone of this repository ("%s") on the local machine ("%s") '.
'could not be read. Ensure that the repository is in a '.
'location where the web server has read permissions.',
$this->getRepository()->getDisplayName(),
$host));
}
protected function raiseCloneException() {
$host = php_uname('n');
throw new DiffusionSetupException(
pht(
'The working copy for this repository ("%s") has not been cloned yet '.
'on this machine ("%s"). Make sure you have started the '.
'daemons. If this problem persists for longer than a clone should '.
'take, check the daemon logs (in the Daemon Console) to see if there '.
'were errors cloning the repository. Consult the "Diffusion User '.
'Guide" in the documentation for help setting up repositories.',
$this->getRepository()->getDisplayName(),
$host));
}
private function queryStableCommit() {
$types = array();
if ($this->symbolicCommit) {
$ref = $this->symbolicCommit;
} else {
if ($this->supportsBranches()) {
$ref = $this->getBranch();
$types = array(
PhabricatorRepositoryRefCursor::TYPE_BRANCH,
);
} else {
$ref = 'HEAD';
}
}
$results = $this->resolveRefs(array($ref), $types);
$matches = idx($results, $ref, array());
if (!$matches) {
$message = pht(
'Ref "%s" does not exist in this repository.',
$ref);
throw id(new DiffusionRefNotFoundException($message))
->setRef($ref);
}
if (count($matches) > 1) {
$match = $this->chooseBestRefMatch($ref, $matches);
} else {
$match = head($matches);
}
$this->stableCommit = $match['identifier'];
$this->symbolicType = $match['type'];
}
public function getRefAlternatives() {
// Make sure we've resolved the reference into a stable commit first.
try {
$this->getStableCommit();
} catch (DiffusionRefNotFoundException $ex) {
// If we have a bad reference, just return the empty set of
// alternatives.
}
return $this->refAlternatives;
}
private function chooseBestRefMatch($ref, array $results) {
// First, filter out less-desirable matches.
$candidates = array();
foreach ($results as $result) {
// Exclude closed heads.
if ($result['type'] == 'branch') {
if (idx($result, 'closed')) {
continue;
}
}
$candidates[] = $result;
}
// If we filtered everything, undo the filtering.
if (!$candidates) {
$candidates = $results;
}
// TODO: Do a better job of selecting the best match?
$match = head($candidates);
// After choosing the best alternative, save all the alternatives so the
// UI can show them to the user.
if (count($candidates) > 1) {
$this->refAlternatives = $candidates;
}
return $match;
}
public function resolveRefs(array $refs, array $types = array()) {
// First, try to resolve refs from fast cache sources.
$cached_query = id(new DiffusionCachedResolveRefsQuery())
->setRepository($this->getRepository())
->withRefs($refs);
if ($types) {
$cached_query->withTypes($types);
}
$cached_results = $cached_query->execute();
// Throw away all the refs we resolved. Hopefully, we'll throw away
// everything here.
foreach ($refs as $key => $ref) {
if (isset($cached_results[$ref])) {
unset($refs[$key]);
}
}
// If we couldn't pull everything out of the cache, execute the underlying
// VCS operation.
if ($refs) {
$vcs_results = DiffusionQuery::callConduitWithDiffusionRequest(
$this->getUser(),
$this,
'diffusion.resolverefs',
array(
'types' => $types,
'refs' => $refs,
));
} else {
$vcs_results = array();
}
return $vcs_results + $cached_results;
}
public function setIsClusterRequest($is_cluster_request) {
$this->isClusterRequest = $is_cluster_request;
return $this;
}
public function getIsClusterRequest() {
return $this->isClusterRequest;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/request/DiffusionGitRequest.php | src/applications/diffusion/request/DiffusionGitRequest.php | <?php
final class DiffusionGitRequest extends DiffusionRequest {
protected function isStableCommit($symbol) {
return $symbol !== null && preg_match('/^[a-f0-9]{40}\z/', $symbol);
}
public function getBranch() {
if ($this->branch) {
return $this->branch;
}
if ($this->repository) {
return $this->repository->getDefaultBranch();
}
throw new Exception(pht('Unable to determine branch!'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/request/__tests__/DiffusionURITestCase.php | src/applications/diffusion/request/__tests__/DiffusionURITestCase.php | <?php
final class DiffusionURITestCase extends PhutilTestCase {
public function testBlobDecode() {
$map = array(
// This is a basic blob.
'branch/path.ext;abc$3' => array(
'branch' => 'branch',
'path' => 'path.ext',
'commit' => 'abc',
'line' => '3',
),
'branch/path.ext$3' => array(
'branch' => 'branch',
'path' => 'path.ext',
'line' => '3',
),
'branch/money;;/$$100' => array(
'branch' => 'branch',
'path' => 'money;/$100',
),
'a%252Fb/' => array(
'branch' => 'a/b',
),
'branch/path/;Version-1_0_0' => array(
'branch' => 'branch',
'path' => 'path/',
'commit' => 'Version-1_0_0',
),
'branch/path/;$$moneytag$$' => array(
'branch' => 'branch',
'path' => 'path/',
'commit' => '$moneytag$',
),
'branch/path/semicolon;;;;;$$;;semicolon;;$$$$$100' => array(
'branch' => 'branch',
'path' => 'path/semicolon;;',
'commit' => '$;;semicolon;;$$',
'line' => '100',
),
'branch/path.ext;abc$3-5,7-12,14' => array(
'branch' => 'branch',
'path' => 'path.ext',
'commit' => 'abc',
'line' => '3-5,7-12,14',
),
);
foreach ($map as $input => $expect) {
// Simulate decode effect of the webserver.
$input = rawurldecode($input);
$expect = $expect + array(
'branch' => null,
'path' => null,
'commit' => null,
'line' => null,
);
$expect = array_select_keys(
$expect,
array('branch', 'path', 'commit', 'line'));
$actual = $this->parseBlob($input);
$this->assertEqual(
$expect,
$actual,
pht("Parsing '%s'", $input));
}
}
public function testBlobDecodeFail() {
$this->tryTestCaseMap(
array(
'branch/path/../../../secrets/secrets.key' => false,
),
array($this, 'parseBlob'));
}
public function parseBlob($blob) {
return DiffusionRequest::parseRequestBlob(
$blob,
$supports_branches = true);
}
public function testURIGeneration() {
$actor = PhabricatorUser::getOmnipotentUser();
$repository = PhabricatorRepository::initializeNewRepository($actor)
->setCallsign('A')
->makeEphemeral();
$map = array(
'/diffusion/A/browse/branch/path.ext;abc$1' => array(
'action' => 'browse',
'branch' => 'branch',
'path' => 'path.ext',
'commit' => 'abc',
'line' => '1',
),
'/diffusion/A/browse/a%252Fb/path.ext' => array(
'action' => 'browse',
'branch' => 'a/b',
'path' => 'path.ext',
),
'/diffusion/A/browse/%2B/%20%21' => array(
'action' => 'browse',
'path' => '+/ !',
),
'/diffusion/A/browse/money/%24%24100$2' => array(
'action' => 'browse',
'path' => 'money/$100',
'line' => '2',
),
'/diffusion/A/browse/path/to/file.ext?view=things' => array(
'action' => 'browse',
'path' => 'path/to/file.ext',
'params' => array(
'view' => 'things',
),
),
'/diffusion/A/repository/master/' => array(
'action' => 'branch',
'branch' => 'master',
),
'path/to/file.ext;abc' => array(
'action' => 'rendering-ref',
'path' => 'path/to/file.ext',
'commit' => 'abc',
),
'/diffusion/A/browse/branch/path.ext$3-5%2C7-12%2C14' => array(
'action' => 'browse',
'branch' => 'branch',
'path' => 'path.ext',
'line' => '3-5,7-12,14',
),
);
foreach ($map as $expect => $input) {
$actual = $repository->generateURI($input);
$this->assertEqual($expect, (string)$actual);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/DiffusionSubversionCommandEngine.php | src/applications/diffusion/protocol/DiffusionSubversionCommandEngine.php | <?php
final class DiffusionSubversionCommandEngine
extends DiffusionCommandEngine {
protected function canBuildForRepository(
PhabricatorRepository $repository) {
return $repository->isSVN();
}
protected function newFormattedCommand($pattern, array $argv) {
$flags = array();
$args = array();
$flags[] = '--non-interactive';
if ($this->isAnyHTTPProtocol() || $this->isSVNProtocol()) {
$flags[] = '--no-auth-cache';
if ($this->isAnyHTTPProtocol()) {
$flags[] = '--trust-server-cert';
}
$credential_phid = $this->getCredentialPHID();
if ($credential_phid) {
$key = PassphrasePasswordKey::loadFromPHID(
$credential_phid,
PhabricatorUser::getOmnipotentUser());
$flags[] = '--username %P';
$args[] = $key->getUsernameEnvelope();
$flags[] = '--password %P';
$args[] = $key->getPasswordEnvelope();
}
}
$flags = implode(' ', $flags);
$pattern = "svn {$flags} {$pattern}";
return array($pattern, array_merge($args, $argv));
}
protected function newCustomEnvironment() {
$env = array();
$env['SVN_SSH'] = $this->getSSHWrapper();
return $env;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/DiffusionGitWireProtocol.php | src/applications/diffusion/protocol/DiffusionGitWireProtocol.php | <?php
abstract class DiffusionGitWireProtocol extends Phobject {
private $protocolLog;
final public function setProtocolLog(PhabricatorProtocolLog $protocol_log) {
$this->protocolLog = $protocol_log;
return $this;
}
final public function getProtocolLog() {
return $this->protocolLog;
}
abstract public function willReadBytes($bytes);
abstract public function willWriteBytes($bytes);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/DiffusionGitUploadPackWireProtocol.php | src/applications/diffusion/protocol/DiffusionGitUploadPackWireProtocol.php | <?php
final class DiffusionGitUploadPackWireProtocol
extends DiffusionGitWireProtocol {
private $readMode = 'length';
private $readBuffer;
private $readFrameLength;
private $readFrames = array();
private $readFrameMode = 'refs';
private $refFrames = array();
private $readMessages = array();
public function willReadBytes($bytes) {
if ($this->readBuffer === null) {
$this->readBuffer = new PhutilRope();
}
$buffer = $this->readBuffer;
$buffer->append($bytes);
while (true) {
$len = $buffer->getByteLength();
switch ($this->readMode) {
case 'length':
// We're expecting 4 bytes containing the length of the protocol
// frame as hexadecimal in ASCII text, like "01ab". Wait until we
// see at least 4 bytes on the wire.
if ($len < 4) {
if ($len > 0) {
$bytes = $this->peekBytes($len);
if (!preg_match('/^[0-9a-f]+\z/', $bytes)) {
throw new Exception(
pht(
'Bad frame length character in Git protocol ("%s"), '.
'expected a 4-digit hexadecimal value encoded as ASCII '.
'text.',
$bytes));
}
}
// We can't make any more progress until we get enough bytes, so
// we're done with state processing.
break 2;
}
$frame_length = $this->readBytes(4);
$frame_length = hexdec($frame_length);
// Note that the frame length includes the 4 header bytes, so we
// usually expect a length of 5 or larger. Frames with length 0
// are boundaries.
if ($frame_length === 0) {
$this->readFrames[] = $this->newProtocolFrame('null', '');
} else if ($frame_length >= 1 && $frame_length <= 3) {
throw new Exception(
pht(
'Encountered Git protocol frame with unexpected frame '.
'length (%s)!',
$frame_length));
} else {
$this->readFrameLength = $frame_length - 4;
$this->readMode = 'frame';
}
break;
case 'frame':
// We're expecting a protocol frame of a specified length. Note that
// it is possible for a frame to have length 0.
// We don't have enough bytes yet, so wait for more.
if ($len < $this->readFrameLength) {
break 2;
}
if ($this->readFrameLength > 0) {
$bytes = $this->readBytes($this->readFrameLength);
} else {
$bytes = '';
}
// Emit a protocol frame.
$this->readFrames[] = $this->newProtocolFrame('data', $bytes);
$this->readMode = 'length';
break;
}
}
while (true) {
switch ($this->readFrameMode) {
case 'refs':
if (!$this->readFrames) {
break 2;
}
foreach ($this->readFrames as $key => $frame) {
unset($this->readFrames[$key]);
if ($frame['type'] === 'null') {
$ref_frames = $this->refFrames;
$this->refFrames = array();
$ref_frames[] = $frame;
$this->readMessages[] = $this->newProtocolRefMessage($ref_frames);
$this->readFrameMode = 'passthru';
break;
} else {
$this->refFrames[] = $frame;
}
}
break;
case 'passthru':
if (!$this->readFrames) {
break 2;
}
$this->readMessages[] = $this->newProtocolDataMessage(
$this->readFrames);
$this->readFrames = array();
break;
}
}
$wire = array();
foreach ($this->readMessages as $key => $message) {
$wire[] = $message;
unset($this->readMessages[$key]);
}
$wire = implode('', $wire);
return $wire;
}
public function willWriteBytes($bytes) {
return $bytes;
}
private function readBytes($count) {
$buffer = $this->readBuffer;
$bytes = $buffer->getPrefixBytes($count);
$buffer->removeBytesFromHead($count);
return $bytes;
}
private function peekBytes($count) {
$buffer = $this->readBuffer;
return $buffer->getPrefixBytes($count);
}
private function newProtocolFrame($type, $bytes) {
return array(
'type' => $type,
'length' => strlen($bytes),
'bytes' => $bytes,
);
}
private function newProtocolRefMessage(array $frames) {
$head_key = head_key($frames);
$last_key = last_key($frames);
$capabilities = null;
$last_frame = null;
$refs = array();
foreach ($frames as $key => $frame) {
$is_last = ($key === $last_key);
if ($is_last) {
// This is a "0000" frame at the end of the list of refs, so we pass
// it through unmodified after we figure out what the rest of the
// frames should look like, below.
$last_frame = $frame;
continue;
}
$is_first = ($key === $head_key);
// Otherwise, we expect a list of:
//
// <hash> <ref-name>\0<capabilities>
// <hash> <ref-name>
// ...
//
// See T13309. The end of this list (which may be empty if a repository
// does not have any refs) has a list of zero or more of these:
//
// shallow <hash>
//
// These entries are present if the repository is a shallow clone
// which was made with the "--depth" flag.
//
// Note that "shallow" frames do not advertise capabilities, and if
// a repository has only "shallow" frames, capabilities are never
// advertised.
$bytes = $frame['bytes'];
$matches = array();
if ($is_first) {
$capabilities_pattern = '\0(?P<capabilities>[^\n]+)';
} else {
$capabilities_pattern = '';
}
$ok = preg_match(
'('.
'^'.
'(?:'.
'(?P<hash>[0-9a-f]{40}) (?P<name>[^\0\n]+)'.$capabilities_pattern.
'|'.
'shallow (?P<shallow>[0-9a-f]{40})'.
')'.
'\n'.
'\z'.
')',
$bytes,
$matches);
if (!$ok) {
if ($is_first) {
throw new Exception(
pht(
'Unexpected "git upload-pack" initial protocol frame: expected '.
'"<hash> <name>\0<capabilities>\n", or '.
'"shallow <hash>\n", got "%s".',
$bytes));
} else {
throw new Exception(
pht(
'Unexpected "git upload-pack" protocol frame: expected '.
'"<hash> <name>\n", or "shallow <hash>\n", got "%s".',
$bytes));
}
}
if (isset($matches['shallow'])) {
$name = null;
$hash = $matches['shallow'];
$is_shallow = true;
} else {
$name = $matches['name'];
$hash = $matches['hash'];
$is_shallow = false;
}
if (isset($matches['capabilities'])) {
$capabilities = $matches['capabilities'];
}
$refs[] = array(
'hash' => $hash,
'name' => $name,
'shallow' => $is_shallow,
);
}
$capabilities = DiffusionGitWireProtocolCapabilities::newFromWireFormat(
$capabilities);
$ref_list = id(new DiffusionGitWireProtocolRefList())
->setCapabilities($capabilities);
foreach ($refs as $ref) {
$wire_ref = id(new DiffusionGitWireProtocolRef())
->setHash($ref['hash']);
if ($ref['shallow']) {
$wire_ref->setIsShallow(true);
} else {
$wire_ref->setName($ref['name']);
}
$ref_list->addRef($wire_ref);
}
// TODO: Here, we have a structured list of refs. In a future change,
// we are free to mutate the structure before flattening it back into
// wire format.
$refs = $ref_list->getRefs();
// Before we write the ref list, sort it for consistency with native
// Git output. We may have added, removed, or renamed refs and ended up
// with an out-of-order list.
$refs = msortv($refs, 'newSortVector');
// The first ref we send back includes the capabilities data. Note that if
// we send back no refs, we also don't send back capabilities! This is
// a little surprising, but is consistent with the native behavior of the
// protocol.
// Likewise, we don't send back any capabilities if we're sending only
// "shallow" frames.
$output = array();
$is_first = true;
foreach ($refs as $ref) {
$is_shallow = $ref->getIsShallow();
if ($is_shallow) {
$result = sprintf(
"shallow %s\n",
$ref->getHash());
} else if ($is_first) {
$result = sprintf(
"%s %s\0%s\n",
$ref->getHash(),
$ref->getName(),
$ref_list->getCapabilities()->toWireFormat());
} else {
$result = sprintf(
"%s %s\n",
$ref->getHash(),
$ref->getName());
}
$output[] = $this->newProtocolFrame('data', $result);
$is_first = false;
}
$output[] = $last_frame;
return $this->newProtocolDataMessage($output);
}
private function newProtocolDataMessage(array $frames) {
$message = array();
foreach ($frames as $frame) {
switch ($frame['type']) {
case 'null':
$message[] = '0000';
break;
case 'data':
$message[] = sprintf(
'%04x%s',
$frame['length'] + 4,
$frame['bytes']);
break;
}
}
$message = implode('', $message);
return $message;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/DiffusionMercurialCommandEngine.php | src/applications/diffusion/protocol/DiffusionMercurialCommandEngine.php | <?php
final class DiffusionMercurialCommandEngine
extends DiffusionCommandEngine {
protected function canBuildForRepository(
PhabricatorRepository $repository) {
return $repository->isHg();
}
protected function newFormattedCommand($pattern, array $argv) {
$args = array();
// Crudely blacklist commands which look like they may contain command
// injection via "--config" or "--debugger". See T13012. To do this, we
// print the whole command, parse it using shell rules, then examine each
// argument to see if it looks like "--config" or "--debugger".
$test_command = call_user_func_array(
'csprintf',
array_merge(array($pattern), $argv));
$test_args = id(new PhutilShellLexer())
->splitArguments($test_command);
foreach ($test_args as $test_arg) {
if (preg_match('/^--(config|debugger)/i', $test_arg)) {
throw new DiffusionMercurialFlagInjectionException(
pht(
'Mercurial command appears to contain unsafe injected "--config" '.
'or "--debugger": %s',
$test_command));
}
}
// NOTE: Here, and in Git and Subversion, we override the SSH command even
// if the repository does not use an SSH remote, since our SSH wrapper
// defuses an attack against older versions of Mercurial, Git and
// Subversion (see T12961) and it's possible to execute this attack
// in indirect ways, like by using an SSH subrepo inside an HTTP repo.
$pattern = "hg --config ui.ssh=%s {$pattern}";
$args[] = $this->getSSHWrapper();
return array($pattern, array_merge($args, $argv));
}
protected function newCustomEnvironment() {
$env = array();
// NOTE: This overrides certain configuration, extensions, and settings
// which make Mercurial commands do random unusual things.
$env['HGPLAIN'] = 1;
return $env;
}
/**
* Sanitize output of an `hg` command invoked with the `--debug` flag to make
* it usable.
*
* @param string Output from `hg --debug ...`
* @return string Usable output.
*/
public static function filterMercurialDebugOutput($stdout) {
// When hg commands are run with `--debug` and some config file isn't
// trusted, Mercurial prints out a warning to stdout, twice, after Feb 2011.
//
// http://selenic.com/pipermail/mercurial-devel/2011-February/028541.html
//
// After Jan 2015, it may also fail to write to a revision branch cache.
//
// Separately, it may fail to write to a different branch cache, and may
// encounter issues reading the branch cache.
//
// When Mercurial repositories are hosted on external systems with
// multi-user environments it's possible that the branch cache is computed
// on a revision which does not end up being published. When this happens it
// will recompute the cache but also print out "invalid branch cache".
//
// https://www.mercurial-scm.org/pipermail/mercurial/2014-June/047239.html
//
// When observing a repository which uses largefiles, the debug output may
// also contain extraneous output about largefile changes.
//
// At some point Mercurial added/improved support for pager used when
// command output is large. It includes printing out debug information that
// the pager is being started for a command. This seems to happen despite
// the output of the command being piped/read from another process.
//
// When printing color output Mercurial may run into some issue with the
// terminal info. This should never happen in Phabricator since color
// output should be turned off, however in the event it shows up we should
// filter it out anyways.
$ignore = array(
'ignoring untrusted configuration option',
"couldn't write revision branch cache:",
"couldn't write branch cache:",
'invalid branchheads cache',
'invalid branch cache',
'updated patterns: .hglf',
'starting pager for command',
'no terminfo entry for',
);
foreach ($ignore as $key => $pattern) {
$ignore[$key] = preg_quote($pattern, '/');
}
$ignore = '('.implode('|', $ignore).')';
$lines = preg_split('/(?<=\n)/', $stdout);
$regex = '/'.$ignore.'.*\n$/';
foreach ($lines as $key => $line) {
$lines[$key] = preg_replace($regex, '', $line);
}
return implode('', $lines);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/DiffusionMercurialWireProtocol.php | src/applications/diffusion/protocol/DiffusionMercurialWireProtocol.php | <?php
final class DiffusionMercurialWireProtocol extends Phobject {
public static function getCommandArgs($command) {
// We need to enumerate all of the Mercurial wire commands because the
// argument encoding varies based on the command. "Why?", you might ask,
// "Why would you do this?".
$commands = array(
'batch' => array('cmds', '*'),
'between' => array('pairs'),
'branchmap' => array(),
'branches' => array('nodes'),
'capabilities' => array(),
'changegroup' => array('roots'),
'changegroupsubset' => array('bases heads'),
'debugwireargs' => array('one two *'),
'getbundle' => array('*'),
'heads' => array(),
'hello' => array(),
'known' => array('nodes', '*'),
'listkeys' => array('namespace'),
'lookup' => array('key'),
'pushkey' => array('namespace', 'key', 'old', 'new'),
'protocaps' => array('caps'),
'stream_out' => array(''),
'unbundle' => array('heads'),
);
if (!isset($commands[$command])) {
throw new Exception(
pht(
'Unknown Mercurial command "%s"!',
$command));
}
return $commands[$command];
}
public static function isReadOnlyCommand($command) {
$read_only = array(
'between' => true,
'branchmap' => true,
'branches' => true,
'capabilities' => true,
'changegroup' => true,
'changegroupsubset' => true,
'debugwireargs' => true,
'getbundle' => true,
'heads' => true,
'hello' => true,
'known' => true,
'listkeys' => true,
'lookup' => true,
'protocaps' => true,
'stream_out' => true,
);
// Notably, the write commands are "pushkey" and "unbundle". The
// "batch" command is theoretically read only, but we require explicit
// analysis of the actual commands.
return isset($read_only[$command]);
}
public static function isReadOnlyBatchCommand($cmds) {
if (!strlen($cmds)) {
// We expect a "batch" command to always have a "cmds" string, so err
// on the side of caution and throw if we don't get any data here. This
// either indicates a mangled command from the client or a programming
// error in our code.
throw new Exception(pht("Expected nonempty '%s' specification!", 'cmds'));
}
// For "batch" we get a "cmds" argument like:
//
// heads ;known nodes=
//
// We need to examine the commands (here, "heads" and "known") to make sure
// they're all read-only.
// NOTE: Mercurial has some code to escape semicolons, but it does not
// actually function for command separation. For example, these two batch
// commands will produce completely different results (the former will run
// the lookup; the latter will fail with a parser error):
//
// lookup key=a:xb;lookup key=z* 0
// lookup key=a:;b;lookup key=z* 0
// ^
// |
// +-- Note semicolon.
//
// So just split unconditionally.
$cmds = explode(';', $cmds);
foreach ($cmds as $sub_cmd) {
$name = head(explode(' ', $sub_cmd, 2));
if (!self::isReadOnlyCommand($name)) {
return false;
}
}
return true;
}
/** If the server version is running 3.4+ it will respond
* with 'bundle2' capability in the format of "bundle2=(url-encoding)".
* Until we manage to properly package up bundles to send back we
* disallow the client from knowing we speak bundle2 by removing it
* from the capabilities listing.
*
* The format of the capabilities string is: "a space separated list
* of strings representing what commands the server supports"
* @link https://www.mercurial-scm.org/wiki/CommandServer#Protocol
*
* @param string $capabilities - The string of capabilities to
* strip the bundle2 capability from. This is expected to be
* the space-separated list of strings resulting from the
* querying the 'capabilities' command.
*
* @return string The resulting space-separated list of capabilities
* which no longer contains the 'bundle2' capability. This is meant
* to replace the original $body to send back to client.
*/
public static function filterBundle2Capability($capabilities) {
$parts = explode(' ', $capabilities);
foreach ($parts as $key => $part) {
if (preg_match('/^bundle2=/', $part)) {
unset($parts[$key]);
break;
}
}
return implode(' ', $parts);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/DiffusionGitCommandEngine.php | src/applications/diffusion/protocol/DiffusionGitCommandEngine.php | <?php
final class DiffusionGitCommandEngine
extends DiffusionCommandEngine {
protected function canBuildForRepository(
PhabricatorRepository $repository) {
return $repository->isGit();
}
protected function newFormattedCommand($pattern, array $argv) {
$pattern = "git {$pattern}";
return array($pattern, $argv);
}
protected function shouldAlwaysSudo() {
// See T13673. In Git, always try to use "sudo" to execute commands as the
// daemon user (if such a user is configured), because Git 2.35.2 and newer
// (and some older versions of Git with backported security patches) refuse
// to execute if the top level repository directory is not owned by the
// current user.
// Previously, we used "sudo" only when performing writes to the
// repository directory.
return true;
}
protected function newCustomEnvironment() {
$env = array();
// NOTE: See T2965. Some time after Git 1.7.5.4, Git started fataling if
// it can not read $HOME. For many users, $HOME points at /root (this
// seems to be a default result of Apache setup). Instead, explicitly
// point $HOME at a readable, empty directory so that Git looks for the
// config file it's after, fails to locate it, and moves on. This is
// really silly, but seems like the least damaging approach to
// mitigating the issue.
$env['HOME'] = PhabricatorEnv::getEmptyCWD();
$env['GIT_SSH'] = $this->getSSHWrapper();
$env['GIT_SSH_VARIANT'] = 'ssh';
if ($this->isAnyHTTPProtocol()) {
$uri = $this->getURI();
if ($uri) {
$proxy = PhutilHTTPEngineExtension::buildHTTPProxyURI($uri);
if ($proxy) {
if ($this->isHTTPSProtocol()) {
$env_key = 'https_proxy';
} else {
$env_key = 'http_proxy';
}
$env[$env_key] = (string)$proxy;
}
}
}
return $env;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/DiffusionGitWireProtocolRef.php | src/applications/diffusion/protocol/DiffusionGitWireProtocolRef.php | <?php
final class DiffusionGitWireProtocolRef
extends Phobject {
private $name;
private $hash;
private $isShallow;
public function setName($name) {
$this->name = $name;
return $this;
}
public function getName() {
return $this->name;
}
public function setHash($hash) {
$this->hash = $hash;
return $this;
}
public function getHash() {
return $this->hash;
}
public function setIsShallow($is_shallow) {
$this->isShallow = $is_shallow;
return $this;
}
public function getIsShallow() {
return $this->isShallow;
}
public function newSortVector() {
return id(new PhutilSortVector())
->addInt((int)$this->getIsShallow())
->addString((string)$this->getName());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/DiffusionSubversionWireProtocol.php | src/applications/diffusion/protocol/DiffusionSubversionWireProtocol.php | <?php
final class DiffusionSubversionWireProtocol extends Phobject {
private $buffer = '';
private $state = 'item';
private $expectBytes = 0;
private $byteBuffer = '';
private $stack = array();
private $list = array();
private $raw = '';
private function pushList() {
$this->stack[] = $this->list;
$this->list = array();
}
private function popList() {
$list = $this->list;
$this->list = array_pop($this->stack);
return $list;
}
private function pushItem($item, $type) {
$this->list[] = array(
'type' => $type,
'value' => $item,
);
}
public function writeData($data) {
$this->buffer .= $data;
$messages = array();
while (true) {
if ($this->state == 'space') {
// Consume zero or more extra spaces after matching an item. The
// protocol requires at least one space, but allows more than one.
$matches = null;
if (!preg_match('/^(\s*)\S/', $this->buffer, $matches)) {
// Wait for more data.
break;
}
// We have zero or more spaces and then some other character, so throw
// the spaces away and continue parsing frames.
if (strlen($matches[1])) {
$this->buffer = substr($this->buffer, strlen($matches[1]));
}
$this->state = 'item';
} else if ($this->state == 'item') {
$match = null;
$result = null;
$buf = $this->buffer;
if (preg_match('/^([a-z][a-z0-9-]*)\s/i', $buf, $match)) {
$this->pushItem($match[1], 'word');
} else if (preg_match('/^(\d+)\s/', $buf, $match)) {
$this->pushItem((int)$match[1], 'number');
} else if (preg_match('/^(\d+):/', $buf, $match)) {
// NOTE: The "+ 1" includes the space after the string.
$this->expectBytes = (int)$match[1] + 1;
$this->state = 'bytes';
} else if (preg_match('/^(\\()\s/', $buf, $match)) {
$this->pushList();
} else if (preg_match('/^(\\))\s/', $buf, $match)) {
$list = $this->popList();
if ($this->stack) {
$this->pushItem($list, 'list');
} else {
$result = $list;
}
} else {
$match = false;
}
if ($match !== false) {
$this->raw .= substr($this->buffer, 0, strlen($match[0]));
$this->buffer = substr($this->buffer, strlen($match[0]));
if ($result !== null) {
$messages[] = array(
'structure' => $list,
'raw' => $this->raw,
);
$this->raw = '';
}
// Consume any extra whitespace after an item. If we're in the
// "bytes" state, we aren't looking for whitespace.
if ($this->state == 'item') {
$this->state = 'space';
}
} else {
// No matches yet, wait for more data.
break;
}
} else if ($this->state == 'bytes') {
$new_data = substr($this->buffer, 0, $this->expectBytes);
if (!strlen($new_data)) {
// No more bytes available yet, wait for more data.
break;
}
$this->buffer = substr($this->buffer, strlen($new_data));
$this->expectBytes -= strlen($new_data);
$this->raw .= $new_data;
$this->byteBuffer .= $new_data;
if (!$this->expectBytes) {
$this->state = 'byte-space';
// Strip off the terminal space.
$this->pushItem(substr($this->byteBuffer, 0, -1), 'string');
$this->byteBuffer = '';
$this->state = 'space';
}
} else {
throw new Exception(pht("Invalid state '%s'!", $this->state));
}
}
return $messages;
}
/**
* Convert a parsed command struct into a wire protocol string.
*/
public function serializeStruct(array $struct) {
$out = array();
$out[] = '( ';
foreach ($struct as $item) {
$value = $item['value'];
$type = $item['type'];
switch ($type) {
case 'word':
$out[] = $value;
break;
case 'number':
$out[] = $value;
break;
case 'string':
$out[] = strlen($value).':'.$value;
break;
case 'list':
$out[] = self::serializeStruct($value);
break;
default:
throw new Exception(
pht(
"Unknown SVN wire protocol structure '%s'!",
$type));
}
if ($type != 'list') {
$out[] = ' ';
}
}
$out[] = ') ';
return implode('', $out);
}
public function isReadOnlyCommand(array $struct) {
if (empty($struct[0]['type']) || ($struct[0]['type'] != 'word')) {
// This isn't what we expect; fail defensively.
throw new Exception(
pht(
"Unexpected command structure, expected '%s'.",
'( word ... )'));
}
switch ($struct[0]['value']) {
// Authentication command set.
case 'EXTERNAL':
// The "Main" command set. Some of the commands in this command set are
// mutation commands, and are omitted from this list.
case 'reparent':
case 'get-latest-rev':
case 'get-dated-rev':
case 'rev-proplist':
case 'rev-prop':
case 'get-file':
case 'get-dir':
case 'check-path':
case 'stat':
case 'update':
case 'get-mergeinfo':
case 'switch':
case 'status':
case 'diff':
case 'log':
case 'get-file-revs':
case 'get-locations':
// The "Report" command set. These are not actually mutation
// operations, they just define a request for information.
case 'set-path':
case 'delete-path':
case 'link-path':
case 'finish-report':
case 'abort-report':
// These are used to report command results.
case 'success':
case 'failure':
// If we get here, we've matched some known read-only command.
return true;
default:
// Anything else isn't a known read-only command, so require write
// access to use it.
break;
}
return false;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/DiffusionRepositoryClusterEngine.php | src/applications/diffusion/protocol/DiffusionRepositoryClusterEngine.php | <?php
/**
* Manages repository synchronization for cluster repositories.
*
* @task config Configuring Synchronization
* @task sync Cluster Synchronization
* @task internal Internals
*/
final class DiffusionRepositoryClusterEngine extends Phobject {
private $repository;
private $viewer;
private $actingAsPHID;
private $logger;
private $clusterWriteLock;
private $clusterWriteVersion;
private $clusterWriteOwner;
/* -( Configuring Synchronization )---------------------------------------- */
public function setRepository(PhabricatorRepository $repository) {
$this->repository = $repository;
return $this;
}
public function getRepository() {
return $this->repository;
}
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setLog(DiffusionRepositoryClusterEngineLogInterface $log) {
$this->logger = $log;
return $this;
}
public function setActingAsPHID($acting_as_phid) {
$this->actingAsPHID = $acting_as_phid;
return $this;
}
public function getActingAsPHID() {
return $this->actingAsPHID;
}
private function getEffectiveActingAsPHID() {
if ($this->actingAsPHID) {
return $this->actingAsPHID;
}
return $this->getViewer()->getPHID();
}
/* -( Cluster Synchronization )-------------------------------------------- */
/**
* Synchronize repository version information after creating a repository.
*
* This initializes working copy versions for all currently bound devices to
* 0, so that we don't get stuck making an ambiguous choice about which
* devices are leaders when we later synchronize before a read.
*
* @task sync
*/
public function synchronizeWorkingCopyAfterCreation() {
if (!$this->shouldEnableSynchronization(false)) {
return;
}
$repository = $this->getRepository();
$repository_phid = $repository->getPHID();
$service = $repository->loadAlmanacService();
if (!$service) {
throw new Exception(pht('Failed to load repository cluster service.'));
}
$bindings = $service->getActiveBindings();
foreach ($bindings as $binding) {
PhabricatorRepositoryWorkingCopyVersion::updateVersion(
$repository_phid,
$binding->getDevicePHID(),
0);
}
return $this;
}
/**
* @task sync
*/
public function synchronizeWorkingCopyAfterHostingChange() {
if (!$this->shouldEnableSynchronization(false)) {
return;
}
$repository = $this->getRepository();
$repository_phid = $repository->getPHID();
$versions = PhabricatorRepositoryWorkingCopyVersion::loadVersions(
$repository_phid);
$versions = mpull($versions, null, 'getDevicePHID');
// After converting a hosted repository to observed, or vice versa, we
// need to reset version numbers because the clocks for observed and hosted
// repositories run on different units.
// We identify all the cluster leaders and reset their version to 0.
// We identify all the cluster followers and demote them.
// This allows the cluster to start over again at version 0 but keep the
// same leaders.
if ($versions) {
$max_version = (int)max(mpull($versions, 'getRepositoryVersion'));
foreach ($versions as $version) {
$device_phid = $version->getDevicePHID();
if ($version->getRepositoryVersion() == $max_version) {
PhabricatorRepositoryWorkingCopyVersion::updateVersion(
$repository_phid,
$device_phid,
0);
} else {
PhabricatorRepositoryWorkingCopyVersion::demoteDevice(
$repository_phid,
$device_phid);
}
}
}
return $this;
}
/**
* @task sync
*/
public function synchronizeWorkingCopyBeforeRead() {
if (!$this->shouldEnableSynchronization(true)) {
return;
}
$repository = $this->getRepository();
$repository_phid = $repository->getPHID();
$device = AlmanacKeys::getLiveDevice();
$device_phid = $device->getPHID();
$read_lock = PhabricatorRepositoryWorkingCopyVersion::getReadLock(
$repository_phid,
$device_phid);
$lock_wait = phutil_units('2 minutes in seconds');
$this->logLine(
pht(
'Acquiring read lock for repository "%s" on device "%s"...',
$repository->getDisplayName(),
$device->getName()));
try {
$start = PhabricatorTime::getNow();
$read_lock->lock($lock_wait);
$waited = (PhabricatorTime::getNow() - $start);
if ($waited) {
$this->logLine(
pht(
'Acquired read lock after %s second(s).',
new PhutilNumber($waited)));
} else {
$this->logLine(
pht(
'Acquired read lock immediately.'));
}
} catch (PhutilLockException $ex) {
throw new PhutilProxyException(
pht(
'Failed to acquire read lock after waiting %s second(s). You '.
'may be able to retry later. (%s)',
new PhutilNumber($lock_wait),
$ex->getHint()),
$ex);
}
$versions = PhabricatorRepositoryWorkingCopyVersion::loadVersions(
$repository_phid);
$versions = mpull($versions, null, 'getDevicePHID');
$this_version = idx($versions, $device_phid);
if ($this_version) {
$this_version = (int)$this_version->getRepositoryVersion();
} else {
$this_version = null;
}
if ($versions) {
// This is the normal case, where we have some version information and
// can identify which nodes are leaders. If the current node is not a
// leader, we want to fetch from a leader and then update our version.
$max_version = (int)max(mpull($versions, 'getRepositoryVersion'));
if (($this_version === null) || ($max_version > $this_version)) {
if ($repository->isHosted()) {
$fetchable = array();
foreach ($versions as $version) {
if ($version->getRepositoryVersion() == $max_version) {
$fetchable[] = $version->getDevicePHID();
}
}
$this->synchronizeWorkingCopyFromDevices(
$fetchable,
$this_version,
$max_version);
} else {
$this->synchronizeWorkingCopyFromRemote();
}
PhabricatorRepositoryWorkingCopyVersion::updateVersion(
$repository_phid,
$device_phid,
$max_version);
} else {
$this->logLine(
pht(
'Device "%s" is already a cluster leader and does not need '.
'to be synchronized.',
$device->getName()));
}
$result_version = $max_version;
} else {
// If no version records exist yet, we need to be careful, because we
// can not tell which nodes are leaders.
// There might be several nodes with arbitrary existing data, and we have
// no way to tell which one has the "right" data. If we pick wrong, we
// might erase some or all of the data in the repository.
// Since this is dangerous, we refuse to guess unless there is only one
// device. If we're the only device in the group, we obviously must be
// a leader.
$service = $repository->loadAlmanacService();
if (!$service) {
throw new Exception(pht('Failed to load repository cluster service.'));
}
$bindings = $service->getActiveBindings();
$device_map = array();
foreach ($bindings as $binding) {
$device_map[$binding->getDevicePHID()] = true;
}
if (count($device_map) > 1) {
throw new Exception(
pht(
'Repository "%s" exists on more than one device, but no device '.
'has any repository version information. There is no way for the '.
'software to determine which copy of the existing data is '.
'authoritative. Promote a device or see "Ambiguous Leaders" in '.
'the documentation.',
$repository->getDisplayName()));
}
if (empty($device_map[$device->getPHID()])) {
throw new Exception(
pht(
'Repository "%s" is being synchronized on device "%s", but '.
'this device is not bound to the corresponding cluster '.
'service ("%s").',
$repository->getDisplayName(),
$device->getName(),
$service->getName()));
}
// The current device is the only device in service, so it must be a
// leader. We can safely have any future nodes which come online read
// from it.
PhabricatorRepositoryWorkingCopyVersion::updateVersion(
$repository_phid,
$device_phid,
0);
$result_version = 0;
}
$read_lock->unlock();
return $result_version;
}
/**
* @task sync
*/
public function synchronizeWorkingCopyBeforeWrite() {
if (!$this->shouldEnableSynchronization(true)) {
return;
}
$repository = $this->getRepository();
$viewer = $this->getViewer();
$repository_phid = $repository->getPHID();
$device = AlmanacKeys::getLiveDevice();
$device_phid = $device->getPHID();
$table = new PhabricatorRepositoryWorkingCopyVersion();
$locked_connection = $table->establishConnection('w');
$write_lock = PhabricatorRepositoryWorkingCopyVersion::getWriteLock(
$repository_phid);
$write_lock->setExternalConnection($locked_connection);
$this->logLine(
pht(
'Acquiring write lock for repository "%s"...',
$repository->getDisplayName()));
// See T13590. On the HTTP pathway, it's possible for us to hit the script
// time limit while holding the durable write lock if a user makes a big
// push. Remove the time limit before we acquire the durable lock.
set_time_limit(0);
$lock_wait = phutil_units('2 minutes in seconds');
try {
$write_wait_start = microtime(true);
$start = PhabricatorTime::getNow();
$step_wait = 1;
while (true) {
try {
$write_lock->lock((int)floor($step_wait));
$write_wait_end = microtime(true);
break;
} catch (PhutilLockException $ex) {
$waited = (PhabricatorTime::getNow() - $start);
if ($waited > $lock_wait) {
throw $ex;
}
$this->logActiveWriter($viewer, $repository);
}
// Wait a little longer before the next message we print.
$step_wait = $step_wait + 0.5;
$step_wait = min($step_wait, 3);
}
$waited = (PhabricatorTime::getNow() - $start);
if ($waited) {
$this->logLine(
pht(
'Acquired write lock after %s second(s).',
new PhutilNumber($waited)));
} else {
$this->logLine(
pht(
'Acquired write lock immediately.'));
}
} catch (PhutilLockException $ex) {
throw new PhutilProxyException(
pht(
'Failed to acquire write lock after waiting %s second(s). You '.
'may be able to retry later. (%s)',
new PhutilNumber($lock_wait),
$ex->getHint()),
$ex);
}
$versions = PhabricatorRepositoryWorkingCopyVersion::loadVersions(
$repository_phid);
foreach ($versions as $version) {
if (!$version->getIsWriting()) {
continue;
}
throw new Exception(
pht(
'An previous write to this repository was interrupted; refusing '.
'new writes. This issue requires operator intervention to resolve, '.
'see "Write Interruptions" in the "Cluster: Repositories" in the '.
'documentation for instructions.'));
}
$read_wait_start = microtime(true);
try {
$max_version = $this->synchronizeWorkingCopyBeforeRead();
} catch (Exception $ex) {
$write_lock->unlock();
throw $ex;
}
$read_wait_end = microtime(true);
$pid = getmypid();
$hash = Filesystem::readRandomCharacters(12);
$this->clusterWriteOwner = "{$pid}.{$hash}";
PhabricatorRepositoryWorkingCopyVersion::willWrite(
$locked_connection,
$repository_phid,
$device_phid,
array(
'userPHID' => $this->getEffectiveActingAsPHID(),
'epoch' => PhabricatorTime::getNow(),
'devicePHID' => $device_phid,
),
$this->clusterWriteOwner);
$this->clusterWriteVersion = $max_version;
$this->clusterWriteLock = $write_lock;
$write_wait = ($write_wait_end - $write_wait_start);
$read_wait = ($read_wait_end - $read_wait_start);
$log = $this->logger;
if ($log) {
$log->writeClusterEngineLogProperty('writeWait', $write_wait);
$log->writeClusterEngineLogProperty('readWait', $read_wait);
}
}
public function synchronizeWorkingCopyAfterDiscovery($new_version) {
if (!$this->shouldEnableSynchronization(true)) {
return;
}
$repository = $this->getRepository();
$repository_phid = $repository->getPHID();
if ($repository->isHosted()) {
return;
}
$device = AlmanacKeys::getLiveDevice();
$device_phid = $device->getPHID();
// NOTE: We are not holding a lock here because this method is only called
// from PhabricatorRepositoryDiscoveryEngine, which already holds a device
// lock. Even if we do race here and record an older version, the
// consequences are mild: we only do extra work to correct it later.
$versions = PhabricatorRepositoryWorkingCopyVersion::loadVersions(
$repository_phid);
$versions = mpull($versions, null, 'getDevicePHID');
$this_version = idx($versions, $device_phid);
if ($this_version) {
$this_version = (int)$this_version->getRepositoryVersion();
} else {
$this_version = null;
}
if (($this_version === null) || ($new_version > $this_version)) {
PhabricatorRepositoryWorkingCopyVersion::updateVersion(
$repository_phid,
$device_phid,
$new_version);
}
}
/**
* @task sync
*/
public function synchronizeWorkingCopyAfterWrite() {
if (!$this->shouldEnableSynchronization(true)) {
return;
}
if (!$this->clusterWriteLock) {
throw new Exception(
pht(
'Trying to synchronize after write, but not holding a write '.
'lock!'));
}
$repository = $this->getRepository();
$repository_phid = $repository->getPHID();
$device = AlmanacKeys::getLiveDevice();
$device_phid = $device->getPHID();
// It is possible that we've lost the global lock while receiving the push.
// For example, the master database may have been restarted between the
// time we acquired the global lock and now, when the push has finished.
// We wrote a durable lock while we were holding the the global lock,
// essentially upgrading our lock. We can still safely release this upgraded
// lock even if we're no longer holding the global lock.
// If we fail to release the lock, the repository will be frozen until
// an operator can figure out what happened, so we try pretty hard to
// reconnect to the database and release the lock.
$now = PhabricatorTime::getNow();
$duration = phutil_units('5 minutes in seconds');
$try_until = $now + $duration;
$did_release = false;
$already_failed = false;
while (PhabricatorTime::getNow() <= $try_until) {
try {
// NOTE: This means we're still bumping the version when pushes fail. We
// could select only un-rejected events instead to bump a little less
// often.
$new_log = id(new PhabricatorRepositoryPushEventQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withRepositoryPHIDs(array($repository_phid))
->setLimit(1)
->executeOne();
$old_version = $this->clusterWriteVersion;
if ($new_log) {
$new_version = $new_log->getID();
} else {
$new_version = $old_version;
}
PhabricatorRepositoryWorkingCopyVersion::didWrite(
$repository_phid,
$device_phid,
$this->clusterWriteVersion,
$new_version,
$this->clusterWriteOwner);
$did_release = true;
break;
} catch (AphrontConnectionQueryException $ex) {
$connection_exception = $ex;
} catch (AphrontConnectionLostQueryException $ex) {
$connection_exception = $ex;
}
if (!$already_failed) {
$already_failed = true;
$this->logLine(
pht('CRITICAL. Failed to release cluster write lock!'));
$this->logLine(
pht(
'The connection to the master database was lost while receiving '.
'the write.'));
$this->logLine(
pht(
'This process will spend %s more second(s) attempting to '.
'recover, then give up.',
new PhutilNumber($duration)));
}
sleep(1);
}
if ($did_release) {
if ($already_failed) {
$this->logLine(
pht('RECOVERED. Link to master database was restored.'));
}
$this->logLine(pht('Released cluster write lock.'));
} else {
throw new Exception(
pht(
'Failed to reconnect to master database and release held write '.
'lock ("%s") on device "%s" for repository "%s" after trying '.
'for %s seconds(s). This repository will be frozen.',
$this->clusterWriteOwner,
$device->getName(),
$this->getDisplayName(),
new PhutilNumber($duration)));
}
// We can continue even if we've lost this lock, everything is still
// consistent.
try {
$this->clusterWriteLock->unlock();
} catch (Exception $ex) {
// Ignore.
}
$this->clusterWriteLock = null;
$this->clusterWriteOwner = null;
}
/* -( Internals )---------------------------------------------------------- */
/**
* @task internal
*/
private function shouldEnableSynchronization($require_device) {
$repository = $this->getRepository();
$service_phid = $repository->getAlmanacServicePHID();
if (!$service_phid) {
return false;
}
if (!$repository->supportsSynchronization()) {
return false;
}
if ($require_device) {
$device = AlmanacKeys::getLiveDevice();
if (!$device) {
return false;
}
}
return true;
}
/**
* @task internal
*/
private function synchronizeWorkingCopyFromRemote() {
$repository = $this->getRepository();
$device = AlmanacKeys::getLiveDevice();
$local_path = $repository->getLocalPath();
$fetch_uri = $repository->getRemoteURIEnvelope();
if ($repository->isGit()) {
$this->requireWorkingCopy();
$argv = array(
'fetch --prune -- %P %s',
$fetch_uri,
'+refs/*:refs/*',
);
} else {
throw new Exception(pht('Remote sync only supported for git!'));
}
$future = DiffusionCommandEngine::newCommandEngine($repository)
->setArgv($argv)
->setSudoAsDaemon(true)
->setCredentialPHID($repository->getCredentialPHID())
->setURI($repository->getRemoteURIObject())
->newFuture();
$future->setCWD($local_path);
try {
$future->resolvex();
} catch (Exception $ex) {
$this->logLine(
pht(
'Synchronization of "%s" from remote failed: %s',
$device->getName(),
$ex->getMessage()));
throw $ex;
}
}
/**
* @task internal
*/
private function synchronizeWorkingCopyFromDevices(
array $device_phids,
$local_version,
$remote_version) {
$repository = $this->getRepository();
$service = $repository->loadAlmanacService();
if (!$service) {
throw new Exception(pht('Failed to load repository cluster service.'));
}
$device_map = array_fuse($device_phids);
$bindings = $service->getActiveBindings();
$fetchable = array();
foreach ($bindings as $binding) {
// We can't fetch from nodes which don't have the newest version.
$device_phid = $binding->getDevicePHID();
if (empty($device_map[$device_phid])) {
continue;
}
// TODO: For now, only fetch over SSH. We could support fetching over
// HTTP eventually.
if ($binding->getAlmanacPropertyValue('protocol') != 'ssh') {
continue;
}
$fetchable[] = $binding;
}
if (!$fetchable) {
throw new Exception(
pht(
'Leader lost: no up-to-date nodes in repository cluster are '.
'fetchable.'));
}
// If we can synchronize from multiple sources, choose one at random.
shuffle($fetchable);
$caught = null;
foreach ($fetchable as $binding) {
try {
$this->synchronizeWorkingCopyFromBinding(
$binding,
$local_version,
$remote_version);
$caught = null;
break;
} catch (Exception $ex) {
$caught = $ex;
}
}
if ($caught) {
throw $caught;
}
}
/**
* @task internal
*/
private function synchronizeWorkingCopyFromBinding(
AlmanacBinding $binding,
$local_version,
$remote_version) {
$repository = $this->getRepository();
$device = AlmanacKeys::getLiveDevice();
$this->logLine(
pht(
'Synchronizing this device ("%s") from cluster leader ("%s").',
$device->getName(),
$binding->getDevice()->getName()));
$fetch_uri = $repository->getClusterRepositoryURIFromBinding($binding);
$local_path = $repository->getLocalPath();
if ($repository->isGit()) {
$this->requireWorkingCopy();
$argv = array(
'fetch --prune -- %s %s',
$fetch_uri,
'+refs/*:refs/*',
);
} else {
throw new Exception(pht('Binding sync only supported for git!'));
}
$future = DiffusionCommandEngine::newCommandEngine($repository)
->setArgv($argv)
->setConnectAsDevice(true)
->setSudoAsDaemon(true)
->setURI($fetch_uri)
->newFuture();
$future->setCWD($local_path);
$log = PhabricatorRepositorySyncEvent::initializeNewEvent()
->setRepositoryPHID($repository->getPHID())
->setEpoch(PhabricatorTime::getNow())
->setDevicePHID($device->getPHID())
->setFromDevicePHID($binding->getDevice()->getPHID())
->setDeviceVersion($local_version)
->setFromDeviceVersion($remote_version);
$sync_start = microtime(true);
try {
$future->resolvex();
} catch (Exception $ex) {
$log->setSyncWait(phutil_microseconds_since($sync_start));
if ($ex instanceof CommandException) {
if ($future->getWasKilledByTimeout()) {
$result_type = PhabricatorRepositorySyncEvent::RESULT_TIMEOUT;
} else {
$result_type = PhabricatorRepositorySyncEvent::RESULT_ERROR;
}
$log
->setResultCode($ex->getError())
->setResultType($result_type)
->setProperty('stdout', $ex->getStdout())
->setProperty('stderr', $ex->getStderr());
} else {
$log
->setResultCode(1)
->setResultType(PhabricatorRepositorySyncEvent::RESULT_EXCEPTION)
->setProperty('message', $ex->getMessage());
}
$log->save();
$this->logLine(
pht(
'Synchronization of "%s" from leader "%s" failed: %s',
$device->getName(),
$binding->getDevice()->getName(),
$ex->getMessage()));
throw $ex;
}
$log
->setSyncWait(phutil_microseconds_since($sync_start))
->setResultCode(0)
->setResultType(PhabricatorRepositorySyncEvent::RESULT_SYNC)
->save();
}
/**
* @task internal
*/
private function logLine($message) {
return $this->logText("# {$message}\n");
}
/**
* @task internal
*/
private function logText($message) {
$log = $this->logger;
if ($log) {
$log->writeClusterEngineLogMessage($message);
}
return $this;
}
private function requireWorkingCopy() {
$repository = $this->getRepository();
$local_path = $repository->getLocalPath();
if (!Filesystem::pathExists($local_path)) {
$device = AlmanacKeys::getLiveDevice();
throw new Exception(
pht(
'Repository "%s" does not have a working copy on this device '.
'yet, so it can not be synchronized. Wait for the daemons to '.
'construct one or run `bin/repository update %s` on this host '.
'("%s") to build it explicitly.',
$repository->getDisplayName(),
$repository->getMonogram(),
$device->getName()));
}
}
private function logActiveWriter(
PhabricatorUser $viewer,
PhabricatorRepository $repository) {
$writer = PhabricatorRepositoryWorkingCopyVersion::loadWriter(
$repository->getPHID());
if (!$writer) {
$this->logLine(pht('Waiting on another user to finish writing...'));
return;
}
$user_phid = $writer->getWriteProperty('userPHID');
$device_phid = $writer->getWriteProperty('devicePHID');
$epoch = $writer->getWriteProperty('epoch');
$phids = array($user_phid, $device_phid);
$handles = $viewer->loadHandles($phids);
$duration = (PhabricatorTime::getNow() - $epoch) + 1;
$this->logLine(
pht(
'Waiting for %s to finish writing (on device "%s" for %ss)...',
$handles[$user_phid]->getName(),
$handles[$device_phid]->getName(),
new PhutilNumber($duration)));
}
public function newMaintenanceEvent() {
$viewer = $this->getViewer();
$repository = $this->getRepository();
$now = PhabricatorTime::getNow();
$event = PhabricatorRepositoryPushEvent::initializeNewEvent($viewer)
->setRepositoryPHID($repository->getPHID())
->setEpoch($now)
->setPusherPHID($this->getEffectiveActingAsPHID())
->setRejectCode(PhabricatorRepositoryPushLog::REJECT_ACCEPT);
return $event;
}
public function newMaintenanceLog() {
$viewer = $this->getViewer();
$repository = $this->getRepository();
$now = PhabricatorTime::getNow();
$device = AlmanacKeys::getLiveDevice();
if ($device) {
$device_phid = $device->getPHID();
} else {
$device_phid = null;
}
return PhabricatorRepositoryPushLog::initializeNewLog($viewer)
->setDevicePHID($device_phid)
->setRepositoryPHID($repository->getPHID())
->attachRepository($repository)
->setEpoch($now)
->setPusherPHID($this->getEffectiveActingAsPHID())
->setChangeFlags(PhabricatorRepositoryPushLog::CHANGEFLAG_MAINTENANCE)
->setRefType(PhabricatorRepositoryPushLog::REFTYPE_MAINTENANCE)
->setRefNew('');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/DiffusionGitWireProtocolRefList.php | src/applications/diffusion/protocol/DiffusionGitWireProtocolRefList.php | <?php
final class DiffusionGitWireProtocolRefList
extends Phobject {
private $capabilities;
private $refs = array();
public function setCapabilities(
DiffusionGitWireProtocolCapabilities $capabilities) {
$this->capabilities = $capabilities;
return $this;
}
public function getCapabilities() {
return $this->capabilities;
}
public function addRef(DiffusionGitWireProtocolRef $ref) {
$this->refs[] = $ref;
return $this;
}
public function getRefs() {
return $this->refs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/DiffusionCommandEngine.php | src/applications/diffusion/protocol/DiffusionCommandEngine.php | <?php
abstract class DiffusionCommandEngine extends Phobject {
private $repository;
private $protocol;
private $credentialPHID;
private $argv;
private $passthru;
private $connectAsDevice;
private $sudoAsDaemon;
private $uri;
public static function newCommandEngine(PhabricatorRepository $repository) {
$engines = self::newCommandEngines();
foreach ($engines as $engine) {
if ($engine->canBuildForRepository($repository)) {
return id(clone $engine)
->setRepository($repository);
}
}
throw new Exception(
pht(
'No registered command engine can build commands for this '.
'repository ("%s").',
$repository->getDisplayName()));
}
private static function newCommandEngines() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->execute();
}
abstract protected function canBuildForRepository(
PhabricatorRepository $repository);
abstract protected function newFormattedCommand($pattern, array $argv);
abstract protected function newCustomEnvironment();
public function setRepository(PhabricatorRepository $repository) {
$this->repository = $repository;
return $this;
}
public function getRepository() {
return $this->repository;
}
public function setURI(PhutilURI $uri) {
$this->uri = $uri;
$this->setProtocol($uri->getProtocol());
return $this;
}
public function getURI() {
return $this->uri;
}
public function setProtocol($protocol) {
$this->protocol = $protocol;
return $this;
}
public function getProtocol() {
return $this->protocol;
}
public function getDisplayProtocol() {
return $this->getProtocol().'://';
}
public function setCredentialPHID($credential_phid) {
$this->credentialPHID = $credential_phid;
return $this;
}
public function getCredentialPHID() {
return $this->credentialPHID;
}
public function setArgv(array $argv) {
$this->argv = $argv;
return $this;
}
public function getArgv() {
return $this->argv;
}
public function setPassthru($passthru) {
$this->passthru = $passthru;
return $this;
}
public function getPassthru() {
return $this->passthru;
}
public function setConnectAsDevice($connect_as_device) {
$this->connectAsDevice = $connect_as_device;
return $this;
}
public function getConnectAsDevice() {
return $this->connectAsDevice;
}
public function setSudoAsDaemon($sudo_as_daemon) {
$this->sudoAsDaemon = $sudo_as_daemon;
return $this;
}
public function getSudoAsDaemon() {
return $this->sudoAsDaemon;
}
protected function shouldAlwaysSudo() {
return false;
}
public function newFuture() {
$argv = $this->newCommandArgv();
$env = $this->newCommandEnvironment();
$is_passthru = $this->getPassthru();
if ($this->getSudoAsDaemon() || $this->shouldAlwaysSudo()) {
$command = call_user_func_array('csprintf', $argv);
$command = PhabricatorDaemon::sudoCommandAsDaemonUser($command);
$argv = array('%C', $command);
}
if ($is_passthru) {
$future = newv('PhutilExecPassthru', $argv);
} else {
$future = newv('ExecFuture', $argv);
}
$future->setEnv($env);
// See T13108. By default, don't let any cluster command run indefinitely
// to try to avoid cases where `git fetch` hangs for some reason and we're
// left sitting with a held lock forever.
$repository = $this->getRepository();
if (!$is_passthru) {
$future->setTimeout($repository->getEffectiveCopyTimeLimit());
}
return $future;
}
private function newCommandArgv() {
$argv = $this->argv;
$pattern = $argv[0];
$argv = array_slice($argv, 1);
list($pattern, $argv) = $this->newFormattedCommand($pattern, $argv);
return array_merge(array($pattern), $argv);
}
private function newCommandEnvironment() {
$env = $this->newCommonEnvironment() + $this->newCustomEnvironment();
foreach ($env as $key => $value) {
if ($value === null) {
unset($env[$key]);
}
}
return $env;
}
private function newCommonEnvironment() {
$repository = $this->getRepository();
$env = array();
// NOTE: Force the language to "en_US.UTF-8", which overrides locale
// settings. This makes stuff print in English instead of, e.g., French,
// so we can parse the output of some commands, error messages, etc.
$env['LANG'] = 'en_US.UTF-8';
// Propagate PHABRICATOR_ENV explicitly. For discussion, see T4155.
$env['PHABRICATOR_ENV'] = PhabricatorEnv::getSelectedEnvironmentName();
$as_device = $this->getConnectAsDevice();
$credential_phid = $this->getCredentialPHID();
if ($as_device) {
$device = AlmanacKeys::getLiveDevice();
if (!$device) {
throw new Exception(
pht(
'Attempting to build a repository command (for repository "%s") '.
'as device, but this host ("%s") is not configured as a cluster '.
'device.',
$repository->getDisplayName(),
php_uname('n')));
}
if ($credential_phid) {
throw new Exception(
pht(
'Attempting to build a repository command (for repository "%s"), '.
'but the CommandEngine is configured to connect as both the '.
'current cluster device ("%s") and with a specific credential '.
'("%s"). These options are mutually exclusive. Connections must '.
'authenticate as one or the other, not both.',
$repository->getDisplayName(),
$device->getName(),
$credential_phid));
}
}
if ($this->isAnySSHProtocol()) {
if ($credential_phid) {
$env['PHABRICATOR_CREDENTIAL'] = $credential_phid;
}
if ($as_device) {
$env['PHABRICATOR_AS_DEVICE'] = 1;
}
}
$env += $repository->getPassthroughEnvironmentalVariables();
return $env;
}
public function isSSHProtocol() {
return ($this->getProtocol() == 'ssh');
}
public function isSVNProtocol() {
return ($this->getProtocol() == 'svn');
}
public function isSVNSSHProtocol() {
return ($this->getProtocol() == 'svn+ssh');
}
public function isHTTPProtocol() {
return ($this->getProtocol() == 'http');
}
public function isHTTPSProtocol() {
return ($this->getProtocol() == 'https');
}
public function isAnyHTTPProtocol() {
return ($this->isHTTPProtocol() || $this->isHTTPSProtocol());
}
public function isAnySSHProtocol() {
return ($this->isSSHProtocol() || $this->isSVNSSHProtocol());
}
public function isCredentialSupported() {
return ($this->getPassphraseProvidesCredentialType() !== null);
}
public function isCredentialOptional() {
if ($this->isAnySSHProtocol()) {
return false;
}
return true;
}
public function getPassphraseCredentialLabel() {
if ($this->isAnySSHProtocol()) {
return pht('SSH Key');
}
if ($this->isAnyHTTPProtocol() || $this->isSVNProtocol()) {
return pht('Password');
}
return null;
}
public function getPassphraseDefaultCredentialType() {
if ($this->isAnySSHProtocol()) {
return PassphraseSSHPrivateKeyTextCredentialType::CREDENTIAL_TYPE;
}
if ($this->isAnyHTTPProtocol() || $this->isSVNProtocol()) {
return PassphrasePasswordCredentialType::CREDENTIAL_TYPE;
}
return null;
}
public function getPassphraseProvidesCredentialType() {
if ($this->isAnySSHProtocol()) {
return PassphraseSSHPrivateKeyCredentialType::PROVIDES_TYPE;
}
if ($this->isAnyHTTPProtocol() || $this->isSVNProtocol()) {
return PassphrasePasswordCredentialType::PROVIDES_TYPE;
}
return null;
}
protected function getSSHWrapper() {
$root = dirname(phutil_get_library_root('phabricator'));
return $root.'/bin/ssh-connect';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/DiffusionRepositoryClusterEngineLogInterface.php | src/applications/diffusion/protocol/DiffusionRepositoryClusterEngineLogInterface.php | <?php
interface DiffusionRepositoryClusterEngineLogInterface {
public function writeClusterEngineLogMessage($message);
public function writeClusterEngineLogProperty($key, $value);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/DiffusionGitWireProtocolCapabilities.php | src/applications/diffusion/protocol/DiffusionGitWireProtocolCapabilities.php | <?php
final class DiffusionGitWireProtocolCapabilities
extends Phobject {
private $raw;
public static function newFromWireFormat($raw) {
$capabilities = new self();
$capabilities->raw = $raw;
return $capabilities;
}
public function toWireFormat() {
return $this->raw;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/__tests__/DiffusionMercurialWireProtocolTests.php | src/applications/diffusion/protocol/__tests__/DiffusionMercurialWireProtocolTests.php | <?php
final class DiffusionMercurialWireProtocolTests extends PhabricatorTestCase {
public function testFilteringBundle2Capability() {
// this was the result of running 'capabilities' over
// `hg serve --stdio` on my systems with Mercurial 3.5.1, 2.6.2
$capabilities_with_bundle2_hg_351 =
'lookup changegroupsubset branchmap pushkey '.
'known getbundle unbundlehash batch stream '.
'bundle2=HG20%0Achangegroup%3D01%2C02%0Adigests%3Dmd5%2Csha1%2Csha512'.
'%0Aerror%3Dabort%2Cunsupportedcontent%2Cpushraced%2Cpushkey%0A'.
'hgtagsfnodes%0Alistkeys%0Apushkey%0Aremote-changegroup%3Dhttp%2Chttps '.
'unbundle=HG10GZ,HG10BZ,HG10UN httpheader=1024';
$capabilities_without_bundle2_hg_351 =
'lookup changegroupsubset branchmap pushkey '.
'known getbundle unbundlehash batch stream '.
'unbundle=HG10GZ,HG10BZ,HG10UN httpheader=1024';
$capabilities_hg_262 =
'lookup changegroupsubset branchmap pushkey '.
'known getbundle unbundlehash batch stream '.
'unbundle=HG10GZ,HG10BZ,HG10UN httpheader=1024 largefiles=serve';
$cases = array(
array(
'name' => pht('Filter bundle2 from Mercurial 3.5.1'),
'input' => $capabilities_with_bundle2_hg_351,
'expect' => $capabilities_without_bundle2_hg_351,
),
array(
'name' => pht('Filter bundle does not affect Mercurial 2.6.2'),
'input' => $capabilities_hg_262,
'expect' => $capabilities_hg_262,
),
);
foreach ($cases as $case) {
$actual = DiffusionMercurialWireProtocol::filterBundle2Capability(
$case['input']);
$this->assertEqual($case['expect'], $actual, $case['name']);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/__tests__/DiffusionCommandEngineTestCase.php | src/applications/diffusion/protocol/__tests__/DiffusionCommandEngineTestCase.php | <?php
final class DiffusionCommandEngineTestCase extends PhabricatorTestCase {
public function testCommandEngine() {
$type_git = PhabricatorRepositoryType::REPOSITORY_TYPE_GIT;
$type_hg = PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL;
$type_svn = PhabricatorRepositoryType::REPOSITORY_TYPE_SVN;
$root = dirname(phutil_get_library_root('phabricator'));
$ssh_wrapper = $root.'/bin/ssh-connect';
$home = $root.'/support/empty/';
// Plain commands.
$this->assertCommandEngineFormat(
'git xyz',
array(
'LANG' => 'en_US.UTF-8',
'HOME' => $home,
),
array(
'vcs' => $type_git,
'argv' => 'xyz',
));
$this->assertCommandEngineFormat(
(string)csprintf('hg --config ui.ssh=%s xyz', $ssh_wrapper),
array(
'LANG' => 'en_US.UTF-8',
'HGPLAIN' => '1',
),
array(
'vcs' => $type_hg,
'argv' => 'xyz',
));
$this->assertCommandEngineFormat(
'svn --non-interactive xyz',
array(
'LANG' => 'en_US.UTF-8',
),
array(
'vcs' => $type_svn,
'argv' => 'xyz',
));
// Commands with SSH.
$this->assertCommandEngineFormat(
'git xyz',
array(
'LANG' => 'en_US.UTF-8',
'HOME' => $home,
'GIT_SSH' => $ssh_wrapper,
),
array(
'vcs' => $type_git,
'argv' => 'xyz',
'protocol' => 'ssh',
));
$this->assertCommandEngineFormat(
(string)csprintf('hg --config ui.ssh=%s xyz', $ssh_wrapper),
array(
'LANG' => 'en_US.UTF-8',
'HGPLAIN' => '1',
),
array(
'vcs' => $type_hg,
'argv' => 'xyz',
'protocol' => 'ssh',
));
$this->assertCommandEngineFormat(
'svn --non-interactive xyz',
array(
'LANG' => 'en_US.UTF-8',
'SVN_SSH' => $ssh_wrapper,
),
array(
'vcs' => $type_svn,
'argv' => 'xyz',
'protocol' => 'ssh',
));
// Commands with HTTP.
$this->assertCommandEngineFormat(
'git xyz',
array(
'LANG' => 'en_US.UTF-8',
'HOME' => $home,
),
array(
'vcs' => $type_git,
'argv' => 'xyz',
'protocol' => 'https',
));
$this->assertCommandEngineFormat(
(string)csprintf('hg --config ui.ssh=%s xyz', $ssh_wrapper),
array(
'LANG' => 'en_US.UTF-8',
'HGPLAIN' => '1',
),
array(
'vcs' => $type_hg,
'argv' => 'xyz',
'protocol' => 'https',
));
$this->assertCommandEngineFormat(
'svn --non-interactive --no-auth-cache --trust-server-cert xyz',
array(
'LANG' => 'en_US.UTF-8',
),
array(
'vcs' => $type_svn,
'argv' => 'xyz',
'protocol' => 'https',
));
// Test that filtering defenses for "--config" and "--debugger" flag
// injections in Mercurial are functional. See T13012.
$caught = null;
try {
$this->assertCommandEngineFormat(
'',
array(),
array(
'vcs' => $type_hg,
'argv' => '--debugger',
));
} catch (DiffusionMercurialFlagInjectionException $ex) {
$caught = $ex;
}
$this->assertTrue(
($caught instanceof DiffusionMercurialFlagInjectionException),
pht('Expected "--debugger" injection in Mercurial to throw.'));
$caught = null;
try {
$this->assertCommandEngineFormat(
'',
array(),
array(
'vcs' => $type_hg,
'argv' => '--config=x',
));
} catch (DiffusionMercurialFlagInjectionException $ex) {
$caught = $ex;
}
$this->assertTrue(
($caught instanceof DiffusionMercurialFlagInjectionException),
pht('Expected "--config" injection in Mercurial to throw.'));
$caught = null;
try {
$this->assertCommandEngineFormat(
'',
array(),
array(
'vcs' => $type_hg,
'argv' => (string)csprintf('%s', '--config=x'),
));
} catch (DiffusionMercurialFlagInjectionException $ex) {
$caught = $ex;
}
$this->assertTrue(
($caught instanceof DiffusionMercurialFlagInjectionException),
pht('Expected quoted "--config" injection in Mercurial to throw.'));
}
private function assertCommandEngineFormat(
$command,
array $env,
array $inputs) {
$repository = id(new PhabricatorRepository())
->setVersionControlSystem($inputs['vcs']);
$future = DiffusionCommandEngine::newCommandEngine($repository)
->setArgv((array)$inputs['argv'])
->setProtocol(idx($inputs, 'protocol'))
->newFuture();
$command_string = $future->getCommand();
$actual_command = $command_string->getUnmaskedString();
$this->assertEqual($command, $actual_command);
$actual_environment = $future->getEnv();
$compare_environment = array_select_keys(
$actual_environment,
array_keys($env));
$this->assertEqual($env, $compare_environment);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/__tests__/DiffusionMercurialCommandEngineTests.php | src/applications/diffusion/protocol/__tests__/DiffusionMercurialCommandEngineTests.php | <?php
final class DiffusionMercurialCommandEngineTests extends PhabricatorTestCase {
public function testFilteringDebugOutput() {
$map = array(
'' => '',
"quack\n" => "quack\n",
"ignoring untrusted configuration option x.y = z\nquack\n" =>
"quack\n",
"ignoring untrusted configuration option x.y = z\n".
"ignoring untrusted configuration option x.y = z\n".
"quack\n" =>
"quack\n",
"ignoring untrusted configuration option x.y = z\n".
"ignoring untrusted configuration option x.y = z\n".
"ignoring untrusted configuration option x.y = z\n".
"quack\n" =>
"quack\n",
"quack\n".
"ignoring untrusted configuration option x.y = z\n".
"ignoring untrusted configuration option x.y = z\n".
"ignoring untrusted configuration option x.y = z\n" =>
"quack\n",
"ignoring untrusted configuration option x.y = z\n".
"ignoring untrusted configuration option x.y = z\n".
"duck\n".
"ignoring untrusted configuration option x.y = z\n".
"ignoring untrusted configuration option x.y = z\n".
"bread\n".
"ignoring untrusted configuration option x.y = z\n".
"quack\n" =>
"duck\nbread\nquack\n",
"ignoring untrusted configuration option x.y = z\n".
"duckignoring untrusted configuration option x.y = z\n".
"quack" =>
'duckquack',
);
foreach ($map as $input => $expect) {
$actual = DiffusionMercurialCommandEngine::filterMercurialDebugOutput(
$input);
$this->assertEqual($expect, $actual, $input);
}
// Output that should be filtered out from the results
$output =
"ignoring untrusted configuration option\n".
"couldn't write revision branch cache:\n".
"couldn't write branch cache: blah blah blah\n".
"invalid branchheads cache\n".
"invalid branch cache (served): tip differs\n".
"starting pager for command 'log'\n".
"updated patterns: ".
".hglf/project/src/a/b/c/SomeClass.java, ".
"project/src/a/b/c/SomeClass.java\n".
"no terminfo entry for sitm\n";
$filtered_output =
DiffusionMercurialCommandEngine::filterMercurialDebugOutput($output);
$this->assertEqual('', $filtered_output);
// The output that should make it through the filtering
$output =
"0b33a9e5ceedba14b03214f743957357d7bb46a9;694".
":8b39f63eb209dd2bdfd4bd3d0721a9e38d75a6d3".
"-1:0000000000000000000000000000000000000000\n".
"8b39f63eb209dd2bdfd4bd3d0721a9e38d75a6d3;693".
":165bce9ce4ccc97024ba19ed5a22f6a066fa6844".
"-1:0000000000000000000000000000000000000000\n".
"165bce9ce4ccc97024ba19ed5a22f6a066fa6844;692:".
"2337bc9e3cf212b3b386b5197801b1c81db64920".
"-1:0000000000000000000000000000000000000000\n";
$filtered_output =
DiffusionMercurialCommandEngine::filterMercurialDebugOutput($output);
$this->assertEqual($output, $filtered_output);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/protocol/__tests__/DiffusionSubversionWireProtocolTestCase.php | src/applications/diffusion/protocol/__tests__/DiffusionSubversionWireProtocolTestCase.php | <?php
final class DiffusionSubversionWireProtocolTestCase
extends PhabricatorTestCase {
public function testSubversionWireProtocolParser() {
$this->assertSameSubversionMessages(
'( ) ',
array(
array(
),
));
$this->assertSameSubversionMessages(
'( duck 5:quack 42 ( item1 item2 ) ) ',
array(
array(
array(
'type' => 'word',
'value' => 'duck',
),
array(
'type' => 'string',
'value' => 'quack',
),
array(
'type' => 'number',
'value' => 42,
),
array(
'type' => 'list',
'value' => array(
array(
'type' => 'word',
'value' => 'item1',
),
array(
'type' => 'word',
'value' => 'item2',
),
),
),
),
));
$this->assertSameSubversionMessages(
'( msg1 ) ( msg2 ) ',
array(
array(
array(
'type' => 'word',
'value' => 'msg1',
),
),
array(
array(
'type' => 'word',
'value' => 'msg2',
),
),
));
// This is testing that multiple spaces are parsed correctly. See T13140
// for discussion.
$this->assertSameSubversionMessages(
'( get-file true false ) ',
// ^-- Note extra space!
array(
array(
array(
'type' => 'word',
'value' => 'get-file',
),
array(
'type' => 'word',
'value' => 'true',
),
array(
'type' => 'word',
'value' => 'false',
),
),
),
'( get-file true false ) ');
$this->assertSameSubversionMessages(
'( duck 5:quack moo ) ',
array(
array(
array(
'type' => 'word',
'value' => 'duck',
),
array(
'type' => 'string',
'value' => 'quack',
),
array(
'type' => 'word',
'value' => 'moo',
),
),
),
'( duck 5:quack moo ) ');
}
public function testSubversionWireProtocolPartialFrame() {
$proto = new DiffusionSubversionWireProtocol();
// This is primarily a test that we don't hang when we write() a frame
// which straddles a string boundary.
$msg1 = $proto->writeData('( duck 5:qu');
$msg2 = $proto->writeData('ack ) ');
$this->assertEqual(array(), ipull($msg1, 'structure'));
$this->assertEqual(
array(
array(
array(
'type' => 'word',
'value' => 'duck',
),
array(
'type' => 'string',
'value' => 'quack',
),
),
),
ipull($msg2, 'structure'));
}
private function assertSameSubversionMessages(
$string,
array $structs,
$serial_string = null) {
$proto = new DiffusionSubversionWireProtocol();
// Verify that the wire message parses into the structs.
$messages = $proto->writeData($string);
$messages = ipull($messages, 'structure');
$this->assertEqual($structs, $messages, 'parse<'.$string.'>');
// Verify that the structs serialize into the wire message.
$serial = array();
foreach ($structs as $struct) {
$serial[] = $proto->serializeStruct($struct);
}
$serial = implode('', $serial);
if ($serial_string === null) {
$expect_serial = $string;
} else {
$expect_serial = $serial_string;
}
$this->assertEqual($expect_serial, $serial, 'serialize<'.$string.'>');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/controller/PhabricatorFlagDeleteController.php | src/applications/flag/controller/PhabricatorFlagDeleteController.php | <?php
final class PhabricatorFlagDeleteController extends PhabricatorFlagController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$flag = id(new PhabricatorFlag())->load($id);
if (!$flag) {
return new Aphront404Response();
}
if ($flag->getOwnerPHID() != $viewer->getPHID()) {
return new Aphront400Response();
}
$flag->delete();
return id(new AphrontReloadResponse())->setURI('/flag/');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/controller/PhabricatorFlagListController.php | src/applications/flag/controller/PhabricatorFlagListController.php | <?php
final class PhabricatorFlagListController extends PhabricatorFlagController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$querykey = $request->getURIData('queryKey');
$controller = id(new PhabricatorApplicationSearchController())
->setQueryKey($querykey)
->setSearchEngine(new PhabricatorFlagSearchEngine())
->setNavigation($this->buildSideNavView());
return $this->delegateToController($controller);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/controller/PhabricatorFlagController.php | src/applications/flag/controller/PhabricatorFlagController.php | <?php
abstract class PhabricatorFlagController extends PhabricatorController {
public function buildSideNavView() {
$user = $this->getRequest()->getUser();
$nav = new AphrontSideNavFilterView();
$nav->setBaseURI(new PhutilURI($this->getApplicationURI()));
id(new PhabricatorFlagSearchEngine())
->setViewer($user)
->addNavigationItems($nav->getMenu());
$nav->selectFilter(null);
return $nav;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/controller/PhabricatorFlagEditController.php | src/applications/flag/controller/PhabricatorFlagEditController.php | <?php
final class PhabricatorFlagEditController extends PhabricatorFlagController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$phid = $request->getURIData('phid');
$handle = id(new PhabricatorHandleQuery())
->setViewer($viewer)
->withPHIDs(array($phid))
->executeOne();
if (!$handle->isComplete()) {
return new Aphront404Response();
}
$flag = PhabricatorFlagQuery::loadUserFlag($viewer, $phid);
if (!$flag) {
$flag = new PhabricatorFlag();
$flag->setOwnerPHID($viewer->getPHID());
$flag->setType($handle->getType());
$flag->setObjectPHID($handle->getPHID());
$flag->setReasonPHID($viewer->getPHID());
}
if ($request->isDialogFormPost()) {
$flag->setColor($request->getInt('color'));
$flag->setNote($request->getStr('note'));
$flag->save();
return id(new AphrontReloadResponse())->setURI('/flag/');
}
$type_name = $handle->getTypeName();
$dialog = new AphrontDialogView();
$dialog->setUser($viewer);
$dialog->setTitle(pht('Flag %s', $type_name));
require_celerity_resource('phabricator-flag-css');
$form = new PHUIFormLayoutView();
$is_new = !$flag->getID();
if ($is_new) {
$form
->appendChild(hsprintf(
'<p>%s</p><br />',
pht('You can flag this %s if you want to remember to look '.
'at it later.',
$type_name)));
}
$radio = new AphrontFormRadioButtonControl();
foreach (PhabricatorFlagColor::getColorNameMap() as $color => $text) {
$class = 'phabricator-flag-radio phabricator-flag-color-'.$color;
$radio->addButton($color, $text, '', $class);
}
$form
->appendChild(
$radio
->setName('color')
->setLabel(pht('Flag Color'))
->setValue($flag->getColor()))
->appendChild(
id(new AphrontFormTextAreaControl())
->setHeight(AphrontFormTextAreaControl::HEIGHT_VERY_SHORT)
->setName('note')
->setLabel(pht('Note'))
->setValue($flag->getNote()));
$dialog->appendChild($form);
$dialog->addCancelButton($handle->getURI());
$dialog->addSubmitButton(
$is_new ? pht('Create Flag') : pht('Save'));
return id(new AphrontDialogResponse())->setDialog($dialog);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/engineextension/PhabricatorFlagDestructionEngineExtension.php | src/applications/flag/engineextension/PhabricatorFlagDestructionEngineExtension.php | <?php
final class PhabricatorFlagDestructionEngineExtension
extends PhabricatorDestructionEngineExtension {
const EXTENSIONKEY = 'flags';
public function getExtensionName() {
return pht('Flags');
}
public function destroyObject(
PhabricatorDestructionEngine $engine,
$object) {
$object_phid = $object->getPHID();
if ($object instanceof PhabricatorFlaggableInterface) {
$flags = id(new PhabricatorFlag())->loadAllWhere(
'objectPHID = %s',
$object_phid);
foreach ($flags as $flag) {
$flag->delete();
}
}
$flags = id(new PhabricatorFlag())->loadAllWhere(
'ownerPHID = %s',
$object_phid);
foreach ($flags as $flag) {
$flag->delete();
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/storage/PhabricatorFlag.php | src/applications/flag/storage/PhabricatorFlag.php | <?php
final class PhabricatorFlag extends PhabricatorFlagDAO
implements PhabricatorPolicyInterface {
protected $ownerPHID;
protected $type;
protected $objectPHID;
protected $reasonPHID;
protected $color = PhabricatorFlagColor::COLOR_BLUE;
protected $note;
private $handle = self::ATTACHABLE;
private $object = self::ATTACHABLE;
protected function getConfiguration() {
return array(
self::CONFIG_COLUMN_SCHEMA => array(
'type' => 'text4',
'color' => 'uint32',
'note' => 'text',
),
self::CONFIG_KEY_SCHEMA => array(
'ownerPHID' => array(
'columns' => array('ownerPHID', 'type', 'objectPHID'),
'unique' => true,
),
'objectPHID' => array(
'columns' => array('objectPHID'),
),
),
) + parent::getConfiguration();
}
public function getObject() {
return $this->assertAttached($this->object);
}
public function attachObject($object) {
$this->object = $object;
return $this;
}
public function getHandle() {
return $this->assertAttached($this->handle);
}
public function attachHandle(PhabricatorObjectHandle $handle) {
$this->handle = $handle;
return $this;
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
);
}
public function getPolicy($capability) {
return PhabricatorPolicies::POLICY_NOONE;
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return ($viewer->getPHID() == $this->getOwnerPHID());
}
public function describeAutomaticCapability($capability) {
return pht('Flags are private. Only you can view or edit your flags.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/storage/PhabricatorFlagDAO.php | src/applications/flag/storage/PhabricatorFlagDAO.php | <?php
abstract class PhabricatorFlagDAO extends PhabricatorLiskDAO {
public function getApplicationName() {
return 'flag';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/query/PhabricatorFlagSearchEngine.php | src/applications/flag/query/PhabricatorFlagSearchEngine.php | <?php
final class PhabricatorFlagSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Flags');
}
public function getApplicationClassName() {
return 'PhabricatorFlagsApplication';
}
public function buildSavedQueryFromRequest(AphrontRequest $request) {
$saved = new PhabricatorSavedQuery();
$saved->setParameter('colors', $request->getArr('colors'));
$saved->setParameter('group', $request->getStr('group'));
$saved->setParameter('objectFilter', $request->getStr('objectFilter'));
return $saved;
}
public function buildQueryFromSavedQuery(PhabricatorSavedQuery $saved) {
$query = id(new PhabricatorFlagQuery())
->needHandles(true)
->withOwnerPHIDs(array($this->requireViewer()->getPHID()));
$colors = $saved->getParameter('colors');
if ($colors) {
$query->withColors($colors);
}
$group = $saved->getParameter('group');
$options = $this->getGroupOptions();
if ($group && isset($options[$group])) {
$query->setGroupBy($group);
}
$object_filter = $saved->getParameter('objectFilter');
$objects = $this->getObjectFilterOptions();
if ($object_filter && isset($objects[$object_filter])) {
$query->withTypes(array($object_filter));
}
return $query;
}
public function buildSearchForm(
AphrontFormView $form,
PhabricatorSavedQuery $saved_query) {
$form
->appendChild(
id(new PhabricatorFlagSelectControl())
->setName('colors')
->setLabel(pht('Colors'))
->setValue($saved_query->getParameter('colors', array())))
->appendChild(
id(new AphrontFormSelectControl())
->setName('group')
->setLabel(pht('Group By'))
->setValue($saved_query->getParameter('group'))
->setOptions($this->getGroupOptions()))
->appendChild(
id(new AphrontFormSelectControl())
->setName('objectFilter')
->setLabel(pht('Object Type'))
->setValue($saved_query->getParameter('objectFilter'))
->setOptions($this->getObjectFilterOptions()));
}
protected function getURI($path) {
return '/flag/'.$path;
}
protected function getBuiltinQueryNames() {
$names = array(
'all' => pht('Flagged'),
);
return $names;
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
private function getGroupOptions() {
return array(
PhabricatorFlagQuery::GROUP_NONE => pht('None'),
PhabricatorFlagQuery::GROUP_COLOR => pht('Color'),
);
}
private function getObjectFilterOptions() {
$objects = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorFlaggableInterface')
->execute();
$all_types = PhabricatorPHIDType::getAllTypes();
$options = array();
foreach ($objects as $object) {
$phid = $object->generatePHID();
$phid_type = phid_get_type($phid);
$type_object = idx($all_types, $phid_type);
if ($type_object) {
$options[$phid_type] = $type_object->getTypeName();
}
}
// sort it alphabetically...
asort($options);
$default_option = array(
0 => pht('All Object Types'),
);
// ...and stick the default option on front
$options = array_merge($default_option, $options);
return $options;
}
protected function renderResultList(
array $flags,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($flags, 'PhabricatorFlag');
$viewer = $this->requireViewer();
$list = id(new PHUIObjectItemListView())
->setUser($viewer);
foreach ($flags as $flag) {
$id = $flag->getID();
$phid = $flag->getObjectPHID();
$class = PhabricatorFlagColor::getCSSClass($flag->getColor());
$flag_icon = phutil_tag(
'div',
array(
'class' => 'phabricator-flag-icon '.$class,
),
'');
$item = id(new PHUIObjectItemView())
->addHeadIcon($flag_icon)
->setHeader($flag->getHandle()->getFullName())
->setHref($flag->getHandle()->getURI());
$status_open = PhabricatorObjectHandle::STATUS_OPEN;
if ($flag->getHandle()->getStatus() != $status_open) {
$item->setDisabled(true);
}
$item->addAction(
id(new PHUIListItemView())
->setIcon('fa-pencil')
->setHref($this->getApplicationURI("edit/{$phid}/"))
->setWorkflow(true));
$item->addAction(
id(new PHUIListItemView())
->setIcon('fa-times')
->setHref($this->getApplicationURI("delete/{$id}/"))
->setWorkflow(true));
if ($flag->getNote()) {
$item->addAttribute($flag->getNote());
}
$item->addIcon(
'none',
phabricator_datetime($flag->getDateCreated(), $viewer));
$list->addItem($item);
}
$result = new PhabricatorApplicationSearchResultView();
$result->setObjectList($list);
$result->setNoDataString(pht('No flags found.'));
return $result;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/query/PhabricatorFlagQuery.php | src/applications/flag/query/PhabricatorFlagQuery.php | <?php
final class PhabricatorFlagQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
const GROUP_COLOR = 'color';
const GROUP_NONE = 'none';
private $ids;
private $ownerPHIDs;
private $types;
private $objectPHIDs;
private $colors;
private $groupBy = self::GROUP_NONE;
private $needHandles;
private $needObjects;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withOwnerPHIDs(array $owner_phids) {
$this->ownerPHIDs = $owner_phids;
return $this;
}
public function withTypes(array $types) {
$this->types = $types;
return $this;
}
public function withObjectPHIDs(array $object_phids) {
$this->objectPHIDs = $object_phids;
return $this;
}
public function withColors(array $colors) {
$this->colors = $colors;
return $this;
}
/**
* NOTE: this is done in PHP and not in MySQL, which means its inappropriate
* for large datasets. Pragmatically, this is fine for user flags which are
* typically well under 100 flags per user.
*/
public function setGroupBy($group) {
$this->groupBy = $group;
return $this;
}
public function needHandles($need) {
$this->needHandles = $need;
return $this;
}
public function needObjects($need) {
$this->needObjects = $need;
return $this;
}
public static function loadUserFlag(PhabricatorUser $user, $object_phid) {
// Specifying the type in the query allows us to use a key.
return id(new PhabricatorFlagQuery())
->setViewer($user)
->withOwnerPHIDs(array($user->getPHID()))
->withTypes(array(phid_get_type($object_phid)))
->withObjectPHIDs(array($object_phid))
->executeOne();
}
protected function loadPage() {
$table = new PhabricatorFlag();
$conn_r = $table->establishConnection('r');
$data = queryfx_all(
$conn_r,
'SELECT * FROM %T flag %Q %Q %Q',
$table->getTableName(),
$this->buildWhereClause($conn_r),
$this->buildOrderClause($conn_r),
$this->buildLimitClause($conn_r));
return $table->loadAllFromArray($data);
}
protected function willFilterPage(array $flags) {
if ($this->needObjects) {
$objects = id(new PhabricatorObjectQuery())
->setViewer($this->getViewer())
->withPHIDs(mpull($flags, 'getObjectPHID'))
->execute();
$objects = mpull($objects, null, 'getPHID');
foreach ($flags as $key => $flag) {
$object = idx($objects, $flag->getObjectPHID());
if ($object) {
$flags[$key]->attachObject($object);
} else {
unset($flags[$key]);
}
}
}
if ($this->needHandles) {
$handles = id(new PhabricatorHandleQuery())
->setViewer($this->getViewer())
->withPHIDs(mpull($flags, 'getObjectPHID'))
->execute();
foreach ($flags as $flag) {
$flag->attachHandle($handles[$flag->getObjectPHID()]);
}
}
switch ($this->groupBy) {
case self::GROUP_COLOR:
$flags = msort($flags, 'getColor');
break;
case self::GROUP_NONE:
break;
default:
throw new Exception(
pht('Unknown groupBy parameter: %s', $this->groupBy));
break;
}
return $flags;
}
protected function buildWhereClause(AphrontDatabaseConnection $conn) {
$where = array();
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'flag.id IN (%Ld)',
$this->ids);
}
if ($this->ownerPHIDs) {
$where[] = qsprintf(
$conn,
'flag.ownerPHID IN (%Ls)',
$this->ownerPHIDs);
}
if ($this->types) {
$where[] = qsprintf(
$conn,
'flag.type IN (%Ls)',
$this->types);
}
if ($this->objectPHIDs) {
$where[] = qsprintf(
$conn,
'flag.objectPHID IN (%Ls)',
$this->objectPHIDs);
}
if ($this->colors) {
$where[] = qsprintf(
$conn,
'flag.color IN (%Ld)',
$this->colors);
}
$where[] = $this->buildPagingClause($conn);
return $this->formatWhereClause($conn, $where);
}
public function getQueryApplicationClass() {
return 'PhabricatorFlagsApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/interface/PhabricatorFlaggableInterface.php | src/applications/flag/interface/PhabricatorFlaggableInterface.php | <?php
interface PhabricatorFlaggableInterface extends PhabricatorPHIDInterface {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/application/PhabricatorFlagsApplication.php | src/applications/flag/application/PhabricatorFlagsApplication.php | <?php
final class PhabricatorFlagsApplication extends PhabricatorApplication {
public function getName() {
return pht('Flags');
}
public function getShortDescription() {
return pht('Personal Bookmarks');
}
public function getBaseURI() {
return '/flag/';
}
public function getIcon() {
return 'fa-flag';
}
public function getEventListeners() {
return array(
new PhabricatorFlagsUIEventListener(),
);
}
public function getTitleGlyph() {
return "\xE2\x9A\x90";
}
public function getApplicationGroup() {
return self::GROUP_UTILITIES;
}
public function getRoutes() {
return array(
'/flag/' => array(
'(?:query/(?P<queryKey>[^/]+)/)?' => 'PhabricatorFlagListController',
'view/(?P<view>[^/]+)/' => 'PhabricatorFlagListController',
'edit/(?P<phid>[^/]+)/' => 'PhabricatorFlagEditController',
'delete/(?P<id>[1-9]\d*)/' => 'PhabricatorFlagDeleteController',
),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/events/PhabricatorFlagsUIEventListener.php | src/applications/flag/events/PhabricatorFlagsUIEventListener.php | <?php
final class PhabricatorFlagsUIEventListener extends PhabricatorEventListener {
public function register() {
$this->listen(PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS);
}
public function handleEvent(PhutilEvent $event) {
switch ($event->getType()) {
case PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS:
$this->handleActionEvent($event);
break;
}
}
private function handleActionEvent($event) {
$user = $event->getUser();
$object = $event->getValue('object');
if (!$object || !$object->getPHID()) {
// If we have no object, or the object doesn't have a PHID yet, we can't
// flag it.
return;
}
if (!($object instanceof PhabricatorFlaggableInterface)) {
return;
}
if (!$this->canUseApplication($event->getUser())) {
return null;
}
$flag = PhabricatorFlagQuery::loadUserFlag($user, $object->getPHID());
if ($flag) {
$color = PhabricatorFlagColor::getColorName($flag->getColor());
$flag_icon = PhabricatorFlagColor::getIcon($flag->getColor());
$flag_action = id(new PhabricatorActionView())
->setWorkflow(true)
->setHref('/flag/delete/'.$flag->getID().'/')
->setName(pht('Remove %s Flag', $color))
->setIcon($flag_icon);
} else {
$flag_action = id(new PhabricatorActionView())
->setWorkflow(true)
->setHref('/flag/edit/'.$object->getPHID().'/')
->setName(pht('Flag For Later'))
->setIcon('fa-flag');
if (!$user->isLoggedIn()) {
$flag_action->setDisabled(true);
}
}
$actions = $event->getValue('actions');
$actions[] = $flag_action;
$event->setValue('actions', $actions);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/view/PhabricatorFlagSelectControl.php | src/applications/flag/view/PhabricatorFlagSelectControl.php | <?php
final class PhabricatorFlagSelectControl extends AphrontFormControl {
protected function getCustomControlClass() {
return 'phabricator-flag-select-control';
}
protected function renderInput() {
require_celerity_resource('phabricator-flag-css');
$colors = PhabricatorFlagColor::getColorNameMap();
$value_map = array_fuse($this->getValue());
$file_map = array(
PhabricatorFlagColor::COLOR_RED => 'red',
PhabricatorFlagColor::COLOR_ORANGE => 'orange',
PhabricatorFlagColor::COLOR_YELLOW => 'yellow',
PhabricatorFlagColor::COLOR_GREEN => 'green',
PhabricatorFlagColor::COLOR_BLUE => 'blue',
PhabricatorFlagColor::COLOR_PINK => 'pink',
PhabricatorFlagColor::COLOR_PURPLE => 'purple',
PhabricatorFlagColor::COLOR_CHECKERED => 'finish',
);
$out = array();
foreach ($colors as $const => $name) {
// TODO: This should probably be a sprite sheet.
$partial = $file_map[$const];
$uri = '/rsrc/image/icon/fatcow/flag_'.$partial.'.png';
$uri = celerity_get_resource_uri($uri);
$icon = id(new PHUIIconView())
->setImage($uri);
$input = phutil_tag(
'input',
array(
'type' => 'checkbox',
'name' => $this->getName().'[]',
'value' => $const,
'checked' => isset($value_map[$const])
? 'checked'
: null,
'class' => 'phabricator-flag-select-checkbox',
));
$label = phutil_tag(
'label',
array(
'class' => 'phabricator-flag-select-label',
),
array(
$icon,
$input,
));
$out[] = $label;
}
return $out;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/herald/PhabricatorFlagAddFlagHeraldAction.php | src/applications/flag/herald/PhabricatorFlagAddFlagHeraldAction.php | <?php
final class PhabricatorFlagAddFlagHeraldAction
extends PhabricatorFlagHeraldAction {
const ACTIONCONST = 'flag';
const DO_FLAG = 'do.flag';
const DO_IGNORE = 'do.flagged';
public function getHeraldActionName() {
return pht('Mark with flag');
}
public function applyEffect($object, HeraldEffect $effect) {
$phid = $this->getAdapter()->getPHID();
$rule = $effect->getRule();
$author = $rule->getAuthor();
$flag = PhabricatorFlagQuery::loadUserFlag($author, $phid);
if ($flag) {
$this->logEffect(self::DO_IGNORE, $flag->getColor());
return;
}
$flag = id(new PhabricatorFlag())
->setOwnerPHID($author->getPHID())
->setType(phid_get_type($phid))
->setObjectPHID($phid)
->setReasonPHID($rule->getPHID())
->setColor($effect->getTarget())
->setNote('')
->save();
$this->logEffect(self::DO_FLAG, $flag->getColor());
}
public function getHeraldActionValueType() {
return id(new HeraldSelectFieldValue())
->setKey('flag.color')
->setOptions(PhabricatorFlagColor::getColorNameMap())
->setDefault(PhabricatorFlagColor::COLOR_BLUE);
}
protected function getActionEffectMap() {
return array(
self::DO_IGNORE => array(
'icon' => 'fa-times',
'color' => 'grey',
'name' => pht('Already Marked'),
),
self::DO_FLAG => array(
'icon' => 'fa-flag',
'name' => pht('Flagged'),
),
);
}
public function renderActionDescription($value) {
$color = PhabricatorFlagColor::getColorName($value);
return pht('Mark with %s flag.', $color);
}
protected function renderActionEffectDescription($type, $data) {
switch ($type) {
case self::DO_IGNORE:
return pht(
'Already marked with %s flag.',
PhabricatorFlagColor::getColorName($data));
case self::DO_FLAG:
return pht(
'Marked with "%s" flag.',
PhabricatorFlagColor::getColorName($data));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/herald/PhabricatorFlagRemoveFlagHeraldAction.php | src/applications/flag/herald/PhabricatorFlagRemoveFlagHeraldAction.php | <?php
final class PhabricatorFlagRemoveFlagHeraldAction
extends PhabricatorFlagHeraldAction {
const ACTIONCONST = 'unflag';
const DO_UNFLAG = 'do.unflag';
const DO_IGNORE_UNFLAG = 'do.ignore-unflag';
public function getHeraldActionName() {
return pht('Remove flag');
}
public function applyEffect($object, HeraldEffect $effect) {
$phid = $this->getAdapter()->getPHID();
$rule = $effect->getRule();
$author = $rule->getAuthor();
$flag = PhabricatorFlagQuery::loadUserFlag($author, $phid);
if (!$flag) {
$this->logEffect(self::DO_IGNORE_UNFLAG, null);
return;
}
if ($flag->getColor() !== $effect->getTarget()) {
$this->logEffect(self::DO_IGNORE_UNFLAG, $flag->getColor());
return;
}
$flag->delete();
$this->logEffect(self::DO_UNFLAG, $flag->getColor());
}
public function getHeraldActionValueType() {
return id(new HeraldSelectFieldValue())
->setKey('flag.color')
->setOptions(PhabricatorFlagColor::getColorNameMap())
->setDefault(PhabricatorFlagColor::COLOR_BLUE);
}
protected function getActionEffectMap() {
return array(
self::DO_IGNORE_UNFLAG => array(
'icon' => 'fa-times',
'color' => 'grey',
'name' => pht('Did Not Remove Flag'),
),
self::DO_UNFLAG => array(
'icon' => 'fa-flag',
'name' => pht('Removed Flag'),
),
);
}
public function renderActionDescription($value) {
$color = PhabricatorFlagColor::getColorName($value);
return pht('Remove %s flag.', $color);
}
protected function renderActionEffectDescription($type, $data) {
switch ($type) {
case self::DO_IGNORE_UNFLAG:
if (!$data) {
return pht('Not marked with any flag.');
} else {
return pht(
'Marked with flag of the wrong color ("%s").',
PhabricatorFlagColor::getColorName($data));
}
case self::DO_UNFLAG:
return pht(
'Removed "%s" flag.',
PhabricatorFlagColor::getColorName($data));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/herald/PhabricatorFlagHeraldAction.php | src/applications/flag/herald/PhabricatorFlagHeraldAction.php | <?php
abstract class PhabricatorFlagHeraldAction
extends HeraldAction {
public function getActionGroupKey() {
return HeraldSupportActionGroup::ACTIONGROUPKEY;
}
public function supportsObject($object) {
return ($object instanceof PhabricatorFlaggableInterface);
}
public function supportsRuleType($rule_type) {
return ($rule_type === HeraldRuleTypeConfig::RULE_TYPE_PERSONAL);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/conduit/FlagEditConduitAPIMethod.php | src/applications/flag/conduit/FlagEditConduitAPIMethod.php | <?php
final class FlagEditConduitAPIMethod extends FlagConduitAPIMethod {
public function getAPIMethodName() {
return 'flag.edit';
}
public function getMethodDescription() {
return pht('Create or modify a flag.');
}
protected function defineParamTypes() {
return array(
'objectPHID' => 'required phid',
'color' => 'optional int',
'note' => 'optional string',
);
}
protected function defineReturnType() {
return 'dict';
}
protected function execute(ConduitAPIRequest $request) {
$user = $request->getUser()->getPHID();
$phid = $request->getValue('objectPHID');
$new = false;
$flag = id(new PhabricatorFlag())->loadOneWhere(
'objectPHID = %s AND ownerPHID = %s',
$phid,
$user);
if ($flag) {
$params = $request->getAllParameters();
if (isset($params['color'])) {
$flag->setColor($params['color']);
}
if (isset($params['note'])) {
$flag->setNote($params['note']);
}
} else {
$default_color = PhabricatorFlagColor::COLOR_BLUE;
$flag = id(new PhabricatorFlag())
->setOwnerPHID($user)
->setType(phid_get_type($phid))
->setObjectPHID($phid)
->setReasonPHID($user)
->setColor($request->getValue('color', $default_color))
->setNote($request->getValue('note', ''));
$new = true;
}
$this->attachHandleToFlag($flag, $request->getUser());
$flag->save();
$ret = $this->buildFlagInfoDictionary($flag);
$ret['new'] = $new;
return $ret;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/conduit/FlagQueryConduitAPIMethod.php | src/applications/flag/conduit/FlagQueryConduitAPIMethod.php | <?php
final class FlagQueryConduitAPIMethod extends FlagConduitAPIMethod {
public function getAPIMethodName() {
return 'flag.query';
}
public function getMethodDescription() {
return pht('Query flag markers.');
}
protected function defineParamTypes() {
return array(
'ownerPHIDs' => 'optional list<phid>',
'types' => 'optional list<type>',
'objectPHIDs' => 'optional list<phid>',
'offset' => 'optional int',
'limit' => 'optional int (default = 100)',
);
}
protected function defineReturnType() {
return 'list<dict>';
}
protected function execute(ConduitAPIRequest $request) {
$query = new PhabricatorFlagQuery();
$query->setViewer($request->getUser());
$owner_phids = $request->getValue('ownerPHIDs', array());
if ($owner_phids) {
$query->withOwnerPHIDs($owner_phids);
}
$object_phids = $request->getValue('objectPHIDs', array());
if ($object_phids) {
$query->withObjectPHIDs($object_phids);
}
$types = $request->getValue('types', array());
if ($types) {
$query->withTypes($types);
}
$query->needHandles(true);
$query->setOffset($request->getValue('offset', 0));
$query->setLimit($request->getValue('limit', 100));
$flags = $query->execute();
$results = array();
foreach ($flags as $flag) {
$results[] = $this->buildFlagInfoDictionary($flag);
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/conduit/FlagDeleteConduitAPIMethod.php | src/applications/flag/conduit/FlagDeleteConduitAPIMethod.php | <?php
final class FlagDeleteConduitAPIMethod extends FlagConduitAPIMethod {
public function getAPIMethodName() {
return 'flag.delete';
}
public function getMethodDescription() {
return pht('Clear a flag.');
}
protected function defineParamTypes() {
return array(
'id' => 'optional id',
'objectPHID' => 'optional phid',
);
}
protected function defineReturnType() {
return 'dict | null';
}
protected function defineErrorTypes() {
return array(
'ERR_NOT_FOUND' => pht('Bad flag ID.'),
'ERR_WRONG_USER' => pht('You are not the creator of this flag.'),
'ERR_NEED_PARAM' => pht('Must pass an id or an objectPHID.'),
);
}
protected function execute(ConduitAPIRequest $request) {
$id = $request->getValue('id');
$object = $request->getValue('objectPHID');
if ($id) {
$flag = id(new PhabricatorFlag())->load($id);
if (!$flag) {
throw new ConduitException('ERR_NOT_FOUND');
}
if ($flag->getOwnerPHID() != $request->getUser()->getPHID()) {
throw new ConduitException('ERR_WRONG_USER');
}
} else if ($object) {
$flag = id(new PhabricatorFlag())->loadOneWhere(
'objectPHID = %s AND ownerPHID = %s',
$object,
$request->getUser()->getPHID());
if (!$flag) {
return null;
}
} else {
throw new ConduitException('ERR_NEED_PARAM');
}
$this->attachHandleToFlag($flag, $request->getUser());
$ret = $this->buildFlagInfoDictionary($flag);
$flag->delete();
return $ret;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/conduit/FlagConduitAPIMethod.php | src/applications/flag/conduit/FlagConduitAPIMethod.php | <?php
abstract class FlagConduitAPIMethod extends ConduitAPIMethod {
final public function getApplication() {
return PhabricatorApplication::getByClass('PhabricatorFlagsApplication');
}
protected function attachHandleToFlag($flag, PhabricatorUser $user) {
$handle = id(new PhabricatorHandleQuery())
->setViewer($user)
->withPHIDs(array($flag->getObjectPHID()))
->executeOne();
$flag->attachHandle($handle);
}
protected function buildFlagInfoDictionary($flag) {
$color = $flag->getColor();
$uri = PhabricatorEnv::getProductionURI($flag->getHandle()->getURI());
return array(
'id' => $flag->getID(),
'ownerPHID' => $flag->getOwnerPHID(),
'type' => $flag->getType(),
'objectPHID' => $flag->getObjectPHID(),
'reasonPHID' => $flag->getReasonPHID(),
'color' => $color,
'colorName' => PhabricatorFlagColor::getColorName($color),
'note' => $flag->getNote(),
'handle' => array(
'uri' => $uri,
'name' => $flag->getHandle()->getName(),
'fullname' => $flag->getHandle()->getFullName(),
),
'dateCreated' => $flag->getDateCreated(),
'dateModified' => $flag->getDateModified(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/constants/PhabricatorFlagColor.php | src/applications/flag/constants/PhabricatorFlagColor.php | <?php
final class PhabricatorFlagColor extends PhabricatorFlagConstants {
const COLOR_RED = 0;
const COLOR_ORANGE = 1;
const COLOR_YELLOW = 2;
const COLOR_GREEN = 3;
const COLOR_BLUE = 4;
const COLOR_PINK = 5;
const COLOR_PURPLE = 6;
const COLOR_CHECKERED = 7;
public static function getColorNameMap() {
return array(
self::COLOR_RED => pht('Red'),
self::COLOR_ORANGE => pht('Orange'),
self::COLOR_YELLOW => pht('Yellow'),
self::COLOR_GREEN => pht('Green'),
self::COLOR_BLUE => pht('Blue'),
self::COLOR_PINK => pht('Pink'),
self::COLOR_PURPLE => pht('Purple'),
self::COLOR_CHECKERED => pht('Checkered'),
);
}
public static function getColorName($color) {
return idx(self::getColorNameMap(), $color, pht('Unknown'));
}
public static function getCSSClass($color) {
return 'phabricator-flag-color-'.(int)$color;
}
public static function getIcon($color) {
$map = array(
self::COLOR_RED => 'fa-flag red',
self::COLOR_ORANGE => 'fa-flag orange',
self::COLOR_YELLOW => 'fa-flag yellow',
self::COLOR_GREEN => 'fa-flag green',
self::COLOR_BLUE => 'fa-flag blue',
self::COLOR_PINK => 'fa-flag pink',
self::COLOR_PURPLE => 'fa-flag violet',
self::COLOR_CHECKERED => 'fa-flag-checkered',
);
return idx($map, $color);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/flag/constants/PhabricatorFlagConstants.php | src/applications/flag/constants/PhabricatorFlagConstants.php | <?php
abstract class PhabricatorFlagConstants extends Phobject {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/draft/storage/PhabricatorDraftDAO.php | src/applications/draft/storage/PhabricatorDraftDAO.php | <?php
abstract class PhabricatorDraftDAO extends PhabricatorLiskDAO {
public function getApplicationName() {
return 'draft';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/draft/storage/PhabricatorVersionedDraft.php | src/applications/draft/storage/PhabricatorVersionedDraft.php | <?php
final class PhabricatorVersionedDraft extends PhabricatorDraftDAO {
const KEY_VERSION = 'draft.version';
protected $objectPHID;
protected $authorPHID;
protected $version;
protected $properties = array();
protected function getConfiguration() {
return array(
self::CONFIG_SERIALIZATION => array(
'properties' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'version' => 'uint32',
),
self::CONFIG_KEY_SCHEMA => array(
'key_object' => array(
'columns' => array('objectPHID', 'authorPHID', 'version'),
'unique' => true,
),
),
) + parent::getConfiguration();
}
public function setProperty($key, $value) {
$this->properties[$key] = $value;
return $this;
}
public function getProperty($key, $default = null) {
return idx($this->properties, $key, $default);
}
public static function loadDrafts(
array $object_phids,
$viewer_phid) {
$rows = id(new self())->loadAllWhere(
'objectPHID IN (%Ls) AND authorPHID = %s ORDER BY version ASC',
$object_phids,
$viewer_phid);
$map = array();
foreach ($rows as $row) {
$map[$row->getObjectPHID()] = $row;
}
return $map;
}
public static function loadDraft(
$object_phid,
$viewer_phid) {
return id(new PhabricatorVersionedDraft())->loadOneWhere(
'objectPHID = %s AND authorPHID = %s ORDER BY version DESC LIMIT 1',
$object_phid,
$viewer_phid);
}
public static function loadOrCreateDraft(
$object_phid,
$viewer_phid,
$version) {
$draft = self::loadDraft($object_phid, $viewer_phid);
if ($draft) {
return $draft;
}
try {
return id(new self())
->setObjectPHID($object_phid)
->setAuthorPHID($viewer_phid)
->setVersion((int)$version)
->save();
} catch (AphrontDuplicateKeyQueryException $ex) {
$duplicate_exception = $ex;
}
// In rare cases we can race ourselves, and at one point there was a bug
// which caused the browser to submit two preview requests at exactly
// the same time. If the insert failed with a duplicate key exception,
// try to load the colliding row to recover from it.
$draft = self::loadDraft($object_phid, $viewer_phid);
if ($draft) {
return $draft;
}
throw $duplicate_exception;
}
public static function purgeDrafts(
$object_phid,
$viewer_phid) {
$draft = new PhabricatorVersionedDraft();
$conn_w = $draft->establishConnection('w');
queryfx(
$conn_w,
'DELETE FROM %T WHERE objectPHID = %s AND authorPHID = %s',
$draft->getTableName(),
$object_phid,
$viewer_phid);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/draft/storage/PhabricatorDraft.php | src/applications/draft/storage/PhabricatorDraft.php | <?php
final class PhabricatorDraft extends PhabricatorDraftDAO {
protected $authorPHID;
protected $draftKey;
protected $draft;
protected $metadata = array();
private $deleted = false;
protected function getConfiguration() {
return array(
self::CONFIG_SERIALIZATION => array(
'metadata' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'draftKey' => 'text64',
'draft' => 'text',
),
self::CONFIG_KEY_SCHEMA => array(
'authorPHID' => array(
'columns' => array('authorPHID', 'draftKey'),
'unique' => true,
),
),
) + parent::getConfiguration();
}
public function replaceOrDelete() {
if ($this->draft == '' && !array_filter($this->metadata)) {
queryfx(
$this->establishConnection('w'),
'DELETE FROM %T WHERE authorPHID = %s AND draftKey = %s',
$this->getTableName(),
$this->authorPHID,
$this->draftKey);
$this->deleted = true;
return $this;
}
return parent::replace();
}
protected function didDelete() {
$this->deleted = true;
}
public function isDeleted() {
return $this->deleted;
}
public static function newFromUserAndKey(PhabricatorUser $user, $key) {
if ($user->getPHID() && strlen($key)) {
$draft = id(new PhabricatorDraft())->loadOneWhere(
'authorPHID = %s AND draftKey = %s',
$user->getPHID(),
$key);
if ($draft) {
return $draft;
}
}
$draft = new PhabricatorDraft();
if ($user->getPHID()) {
$draft
->setAuthorPHID($user->getPHID())
->setDraftKey($key);
}
return $draft;
}
public static function buildFromRequest(AphrontRequest $request) {
$user = $request->getUser();
if (!$user->getPHID()) {
return null;
}
if (!$request->getStr('__draft__')) {
return null;
}
$draft = id(new PhabricatorDraft())
->setAuthorPHID($user->getPHID())
->setDraftKey($request->getStr('__draft__'));
// If this is a preview, add other data. If not, leave the draft empty so
// that replaceOrDelete() will delete it.
if ($request->isPreviewRequest()) {
$other_data = $request->getPassthroughRequestData();
unset($other_data['comment']);
$draft
->setDraft($request->getStr('comment'))
->setMetadata($other_data);
}
return $draft;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/macro/controller/PhabricatorMacroDisableController.php | src/applications/macro/controller/PhabricatorMacroDisableController.php | <?php
final class PhabricatorMacroDisableController
extends PhabricatorMacroController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$this->requireApplicationCapability(
PhabricatorMacroManageCapability::CAPABILITY);
$macro = id(new PhabricatorMacroQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
if (!$macro) {
return new Aphront404Response();
}
$view_uri = $this->getApplicationURI('/view/'.$id.'/');
if ($request->isDialogFormPost() || $macro->getIsDisabled()) {
$xaction = id(new PhabricatorMacroTransaction())
->setTransactionType(
PhabricatorMacroDisabledTransaction::TRANSACTIONTYPE)
->setNewValue($macro->getIsDisabled() ? 0 : 1);
$editor = id(new PhabricatorMacroEditor())
->setActor($viewer)
->setContentSourceFromRequest($request);
$xactions = $editor->applyTransactions($macro, array($xaction));
return id(new AphrontRedirectResponse())->setURI($view_uri);
}
$dialog = new AphrontDialogView();
$dialog
->setUser($request->getUser())
->setTitle(pht('Really disable macro?'))
->appendChild(
phutil_tag(
'p',
array(),
pht(
'Really disable the much-beloved image macro %s? '.
'It will be sorely missed.',
$macro->getName())))
->setSubmitURI($this->getApplicationURI('/disable/'.$id.'/'))
->addSubmitButton(pht('Disable'))
->addCancelButton($view_uri);
return id(new AphrontDialogResponse())->setDialog($dialog);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/macro/controller/PhabricatorMacroViewController.php | src/applications/macro/controller/PhabricatorMacroViewController.php | <?php
final class PhabricatorMacroViewController
extends PhabricatorMacroController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$macro = id(new PhabricatorMacroQuery())
->setViewer($viewer)
->withIDs(array($id))
->needFiles(true)
->executeOne();
if (!$macro) {
return new Aphront404Response();
}
$title_short = pht('Macro "%s"', $macro->getName());
$title_long = pht('Image Macro "%s"', $macro->getName());
$curtain = $this->buildCurtain($macro);
$subheader = $this->buildSubheaderView($macro);
$file = $this->buildFileView($macro);
$details = $this->buildPropertySectionView($macro);
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb($macro->getName());
$crumbs->setBorder(true);
$timeline = $this->buildTransactionTimeline(
$macro,
new PhabricatorMacroTransactionQuery());
$comment_form = $this->buildCommentForm($macro, $timeline);
$header = id(new PHUIHeaderView())
->setUser($viewer)
->setPolicyObject($macro)
->setHeader($macro->getName())
->setHeaderIcon('fa-file-image-o');
if (!$macro->getIsDisabled()) {
$header->setStatus('fa-check', 'bluegrey', pht('Active'));
} else {
$header->setStatus('fa-ban', 'indigo', pht('Archived'));
}
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setSubheader($subheader)
->setCurtain($curtain)
->setMainColumn(array(
$timeline,
$comment_form,
))
->addPropertySection(pht('Macro'), $file)
->addPropertySection(pht('Details'), $details);
return $this->newPage()
->setTitle($title_short)
->setCrumbs($crumbs)
->setPageObjectPHIDs(array($macro->getPHID()))
->appendChild($view);
}
private function buildCommentForm(
PhabricatorFileImageMacro $macro, $timeline) {
$viewer = $this->getViewer();
return id(new PhabricatorMacroEditEngine())
->setViewer($viewer)
->buildEditEngineCommentView($macro)
->setTransactionTimeline($timeline);
}
private function buildCurtain(
PhabricatorFileImageMacro $macro) {
$can_manage = $this->hasApplicationCapability(
PhabricatorMacroManageCapability::CAPABILITY);
$curtain = $this->newCurtainView($macro);
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('Edit Macro'))
->setHref($this->getApplicationURI('/edit/'.$macro->getID().'/'))
->setDisabled(!$can_manage)
->setWorkflow(!$can_manage)
->setIcon('fa-pencil'));
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('Edit Audio'))
->setHref($this->getApplicationURI('/audio/'.$macro->getID().'/'))
->setDisabled(!$can_manage)
->setWorkflow(!$can_manage)
->setIcon('fa-music'));
if ($macro->getIsDisabled()) {
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('Activate Macro'))
->setHref($this->getApplicationURI('/disable/'.$macro->getID().'/'))
->setWorkflow(true)
->setDisabled(!$can_manage)
->setIcon('fa-check'));
} else {
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('Archive Macro'))
->setHref($this->getApplicationURI('/disable/'.$macro->getID().'/'))
->setWorkflow(true)
->setDisabled(!$can_manage)
->setIcon('fa-ban'));
}
return $curtain;
}
private function buildSubheaderView(
PhabricatorFileImageMacro $macro) {
$viewer = $this->getViewer();
$author_phid = $macro->getAuthorPHID();
$author = $viewer->renderHandle($author_phid)->render();
$date = phabricator_datetime($macro->getDateCreated(), $viewer);
$author = phutil_tag('strong', array(), $author);
$handles = $viewer->loadHandles(array($author_phid));
$image_uri = $handles[$author_phid]->getImageURI();
$image_href = $handles[$author_phid]->getURI();
if (!$date) {
$content = pht(
'Masterfully imagined by %s in ages long past.', $author);
} else {
$content = pht('Masterfully imagined by %s on %s.', $author, $date);
}
return id(new PHUIHeadThingView())
->setImage($image_uri)
->setImageHref($image_href)
->setContent($content);
}
private function buildPropertySectionView(
PhabricatorFileImageMacro $macro) {
$viewer = $this->getViewer();
$view = id(new PHUIPropertyListView())
->setUser($viewer);
switch ($macro->getAudioBehavior()) {
case PhabricatorFileImageMacro::AUDIO_BEHAVIOR_ONCE:
$view->addProperty(pht('Audio Behavior'), pht('Play Once'));
break;
case PhabricatorFileImageMacro::AUDIO_BEHAVIOR_LOOP:
$view->addProperty(pht('Audio Behavior'), pht('Loop'));
break;
}
$audio_phid = $macro->getAudioPHID();
if ($audio_phid) {
$view->addProperty(
pht('Audio'),
$viewer->renderHandle($audio_phid));
}
if ($view->hasAnyProperties()) {
return $view;
}
return null;
}
private function buildFileView(
PhabricatorFileImageMacro $macro) {
$viewer = $this->getViewer();
$view = id(new PHUIPropertyListView())
->setUser($viewer);
$file = $macro->getFile();
if ($file) {
$view->addImageContent(
phutil_tag(
'img',
array(
'src' => $file->getViewURI(),
'class' => 'phabricator-image-macro-hero',
)));
return $view;
}
return null;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.