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/query/DiffusionCommitHintQuery.php
src/applications/diffusion/query/DiffusionCommitHintQuery.php
<?php final class DiffusionCommitHintQuery extends PhabricatorCursorPagedPolicyAwareQuery { private $ids; private $repositoryPHIDs; private $oldCommitIdentifiers; private $commits; private $commitMap; public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withRepositoryPHIDs(array $phids) { $this->repositoryPHIDs = $phids; return $this; } public function withOldCommitIdentifiers(array $identifiers) { $this->oldCommitIdentifiers = $identifiers; return $this; } public function withCommits(array $commits) { assert_instances_of($commits, 'PhabricatorRepositoryCommit'); $repository_phids = array(); foreach ($commits as $commit) { $repository_phids[] = $commit->getRepository()->getPHID(); } $this->repositoryPHIDs = $repository_phids; $this->oldCommitIdentifiers = mpull($commits, 'getCommitIdentifier'); $this->commits = $commits; return $this; } public function getCommitMap() { if ($this->commitMap === null) { throw new PhutilInvalidStateException('execute'); } return $this->commitMap; } public function newResultObject() { return new PhabricatorRepositoryCommitHint(); } protected function willExecute() { $this->commitMap = array(); } protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) { $where = parent::buildWhereClauseParts($conn); if ($this->ids !== null) { $where[] = qsprintf( $conn, 'id IN (%Ld)', $this->ids); } if ($this->repositoryPHIDs !== null) { $where[] = qsprintf( $conn, 'repositoryPHID IN (%Ls)', $this->repositoryPHIDs); } if ($this->oldCommitIdentifiers !== null) { $where[] = qsprintf( $conn, 'oldCommitIdentifier IN (%Ls)', $this->oldCommitIdentifiers); } return $where; } protected function didFilterPage(array $hints) { if ($this->commits) { $map = array(); foreach ($this->commits as $commit) { $repository_phid = $commit->getRepository()->getPHID(); $identifier = $commit->getCommitIdentifier(); $map[$repository_phid][$identifier] = $commit->getPHID(); } foreach ($hints as $hint) { $repository_phid = $hint->getRepositoryPHID(); $identifier = $hint->getOldCommitIdentifier(); if (isset($map[$repository_phid][$identifier])) { $commit_phid = $map[$repository_phid][$identifier]; $this->commitMap[$commit_phid] = $hint; } } } return $hints; } public function getQueryApplicationClass() { return 'PhabricatorDiffusionApplication'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/DiffusionPathQuery.php
src/applications/diffusion/query/DiffusionPathQuery.php
<?php final class DiffusionPathQuery extends Phobject { private $pathIDs; public function withPathIDs(array $path_ids) { $this->pathIDs = $path_ids; return $this; } public function execute() { $conn = id(new PhabricatorRepository())->establishConnection('r'); $where = $this->buildWhereClause($conn); $results = queryfx_all( $conn, 'SELECT * FROM %T %Q', PhabricatorRepository::TABLE_PATH, $where); return ipull($results, null, 'id'); } protected function buildWhereClause(AphrontDatabaseConnection $conn) { $where = array(); if ($this->pathIDs) { $where[] = qsprintf( $conn, 'id IN (%Ld)', $this->pathIDs); } if ($where) { return qsprintf($conn, 'WHERE %LA', $where); } else { return qsprintf($conn, ''); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/DiffusionCachedResolveRefsQuery.php
src/applications/diffusion/query/DiffusionCachedResolveRefsQuery.php
<?php /** * Resolves references into canonical, stable commit identifiers by examining * database caches. * * This is a counterpart to @{class:DiffusionLowLevelResolveRefsQuery}. This * query offers fast resolution, but can not resolve everything that the * low-level query can. * * This class can resolve the most common refs (commits, branches, tags) and * can do so cheaply (by examining the database, without needing to make calls * to the VCS or the service host). */ final class DiffusionCachedResolveRefsQuery extends DiffusionLowLevelQuery { private $refs; private $types; public function withRefs(array $refs) { $this->refs = $refs; return $this; } public function withTypes(array $types) { $this->types = $types; return $this; } protected function executeQuery() { if (!$this->refs) { return array(); } switch ($this->getRepository()->getVersionControlSystem()) { case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: $result = $this->resolveGitAndMercurialRefs(); break; case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: $result = $this->resolveSubversionRefs(); break; default: throw new Exception(pht('Unsupported repository type!')); } if ($this->types !== null) { $result = $this->filterRefsByType($result, $this->types); } return $result; } /** * Resolve refs in Git and Mercurial repositories. * * We can resolve commit hashes from the commits table, and branch and tag * names from the refcursor table. */ private function resolveGitAndMercurialRefs() { $repository = $this->getRepository(); $conn_r = $repository->establishConnection('r'); $results = array(); $prefixes = array(); foreach ($this->refs as $ref) { // We require refs to look like hashes and be at least 4 characters // long. This is similar to the behavior of git. if (preg_match('/^[a-f0-9]{4,}$/', $ref)) { $prefixes[] = qsprintf( $conn_r, '(commitIdentifier LIKE %>)', $ref); } } if ($prefixes) { $commits = queryfx_all( $conn_r, 'SELECT commitIdentifier FROM %T WHERE repositoryID = %s AND %LO', id(new PhabricatorRepositoryCommit())->getTableName(), $repository->getID(), $prefixes); foreach ($commits as $commit) { $hash = $commit['commitIdentifier']; foreach ($this->refs as $ref) { if (!strncmp($hash, $ref, strlen($ref))) { $results[$ref][] = array( 'type' => 'commit', 'identifier' => $hash, ); } } } } $name_hashes = array(); foreach ($this->refs as $ref) { $name_hashes[PhabricatorHash::digestForIndex($ref)] = $ref; } $cursors = queryfx_all( $conn_r, 'SELECT c.refNameHash, c.refType, p.commitIdentifier, p.isClosed FROM %T c JOIN %T p ON p.cursorID = c.id WHERE c.repositoryPHID = %s AND c.refNameHash IN (%Ls)', id(new PhabricatorRepositoryRefCursor())->getTableName(), id(new PhabricatorRepositoryRefPosition())->getTableName(), $repository->getPHID(), array_keys($name_hashes)); foreach ($cursors as $cursor) { if (isset($name_hashes[$cursor['refNameHash']])) { $results[$name_hashes[$cursor['refNameHash']]][] = array( 'type' => $cursor['refType'], 'identifier' => $cursor['commitIdentifier'], 'closed' => (bool)$cursor['isClosed'], ); // TODO: In Git, we don't store (and thus don't return) the hash // of the tag itself. It would be vaguely nice to do this. } } return $results; } /** * Resolve refs in Subversion repositories. * * We can resolve all numeric identifiers and the keyword `HEAD`. */ private function resolveSubversionRefs() { $repository = $this->getRepository(); $max_commit = id(new PhabricatorRepositoryCommit()) ->loadOneWhere( 'repositoryID = %d ORDER BY epoch DESC, id DESC LIMIT 1', $repository->getID()); if (!$max_commit) { // This repository is empty or hasn't parsed yet, so none of the refs are // going to resolve. return array(); } $max_commit_id = (int)$max_commit->getCommitIdentifier(); $results = array(); foreach ($this->refs as $ref) { if ($ref == 'HEAD') { // Resolve "HEAD" to mean "the most recent commit". $results[$ref][] = array( 'type' => 'commit', 'identifier' => $max_commit_id, ); continue; } if (!preg_match('/^\d+$/', $ref)) { // This ref is non-numeric, so it doesn't resolve to anything. continue; } // Resolve other commits if we can deduce their existence. // TODO: When we import only part of a repository, we won't necessarily // have all of the smaller commits. Should we fail to resolve them here // for repositories with a subpath? It might let us simplify other things // elsewhere. if ((int)$ref <= $max_commit_id) { $results[$ref][] = array( 'type' => 'commit', 'identifier' => (int)$ref, ); } } 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/query/DiffusionCommitRevisionQuery.php
src/applications/diffusion/query/DiffusionCommitRevisionQuery.php
<?php final class DiffusionCommitRevisionQuery extends Phobject { public static function loadRevisionMapForCommits( PhabricatorUser $viewer, array $commits) { assert_instances_of($commits, 'PhabricatorRepositoryCommit'); if (!$commits) { return array(); } $commit_phids = mpull($commits, 'getPHID'); $edge_query = id(new PhabricatorEdgeQuery()) ->withSourcePHIDs($commit_phids) ->withEdgeTypes( array( DiffusionCommitHasRevisionEdgeType::EDGECONST, )); $edge_query->execute(); $revision_phids = $edge_query->getDestinationPHIDs(); if (!$revision_phids) { return array(); } $revisions = id(new DifferentialRevisionQuery()) ->setViewer($viewer) ->withPHIDs($revision_phids) ->execute(); $revisions = mpull($revisions, null, 'getPHID'); $map = array(); foreach ($commit_phids as $commit_phid) { $revision_phids = $edge_query->getDestinationPHIDs( array( $commit_phid, )); $map[$commit_phid] = array_select_keys($revisions, $revision_phids); } return $map; } public static function loadRevisionForCommit( PhabricatorUser $viewer, PhabricatorRepositoryCommit $commit) { $data = $commit->getCommitData(); $revision_id = $data->getCommitDetail('differential.revisionID'); if (!$revision_id) { return null; } return id(new DifferentialRevisionQuery()) ->setViewer($viewer) ->withIDs(array($revision_id)) ->needReviewers(true) ->executeOne(); } public static function loadRevertedObjects( PhabricatorUser $viewer, $source_object, array $object_names, PhabricatorRepository $repository_scope = null) { // Fetch commits first, since we need to load data on commits in order // to identify associated revisions later on. $commit_query = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withIdentifiers($object_names) ->needCommitData(true); // If we're acting in a specific repository, only allow commits in that // repository to be affected: when commit X reverts commit Y by hash, we // only want to revert commit Y in the same repository, even if other // repositories have a commit with the same hash. if ($repository_scope) { $commit_query->withRepository($repository_scope); } $objects = $commit_query->execute(); $more_objects = id(new PhabricatorObjectQuery()) ->setViewer($viewer) ->withNames($object_names) ->withTypes( array( DifferentialRevisionPHIDType::TYPECONST, )) ->execute(); foreach ($more_objects as $object) { $objects[] = $object; } // See PHI1008 and T13276. If something reverts commit X, we also revert // any associated revision. // For now, we don't try to find associated commits if something reverts // revision Y. This is less common, although we could make more of an // effort in the future. foreach ($objects as $object) { if (!($object instanceof PhabricatorRepositoryCommit)) { continue; } // NOTE: If our object "reverts X", where "X" is a commit hash, it is // possible that "X" will not have parsed yet, so we'll fail to find // a revision even though one exists. // For now, do nothing. It's rare to push a commit which reverts some // commit "X" before "X" has parsed, so we expect this to be unusual. $revision = self::loadRevisionForCommit( $viewer, $object); if ($revision) { $objects[] = $revision; } } $objects = mpull($objects, null, 'getPHID'); // Prevent an object from reverting itself, although this would be very // clever in Git or Mercurial. unset($objects[$source_object->getPHID()]); return $objects; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/DiffusionPullLogSearchEngine.php
src/applications/diffusion/query/DiffusionPullLogSearchEngine.php
<?php final class DiffusionPullLogSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('Pull Logs'); } public function getApplicationClassName() { return 'PhabricatorDiffusionApplication'; } public function newQuery() { return new PhabricatorRepositoryPullEventQuery(); } protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); if ($map['repositoryPHIDs']) { $query->withRepositoryPHIDs($map['repositoryPHIDs']); } if ($map['pullerPHIDs']) { $query->withPullerPHIDs($map['pullerPHIDs']); } if ($map['createdStart'] || $map['createdEnd']) { $query->withEpochBetween( $map['createdStart'], $map['createdEnd']); } return $query; } protected function buildCustomSearchFields() { return array( id(new PhabricatorSearchDatasourceField()) ->setDatasource(new DiffusionRepositoryDatasource()) ->setKey('repositoryPHIDs') ->setAliases(array('repository', 'repositories', 'repositoryPHID')) ->setLabel(pht('Repositories')) ->setDescription( pht('Search for pull logs for specific repositories.')), id(new PhabricatorUsersSearchField()) ->setKey('pullerPHIDs') ->setAliases(array('puller', 'pullers', 'pullerPHID')) ->setLabel(pht('Pullers')) ->setDescription( pht('Search for pull logs by specific users.')), id(new PhabricatorSearchDateField()) ->setLabel(pht('Created After')) ->setKey('createdStart'), id(new PhabricatorSearchDateField()) ->setLabel(pht('Created Before')) ->setKey('createdEnd'), ); } protected function newExportFields() { $viewer = $this->requireViewer(); $fields = array( id(new PhabricatorPHIDExportField()) ->setKey('repositoryPHID') ->setLabel(pht('Repository PHID')), id(new PhabricatorStringExportField()) ->setKey('repository') ->setLabel(pht('Repository')), id(new PhabricatorPHIDExportField()) ->setKey('pullerPHID') ->setLabel(pht('Puller PHID')), id(new PhabricatorStringExportField()) ->setKey('puller') ->setLabel(pht('Puller')), id(new PhabricatorStringExportField()) ->setKey('protocol') ->setLabel(pht('Protocol')), id(new PhabricatorStringExportField()) ->setKey('result') ->setLabel(pht('Result')), id(new PhabricatorIntExportField()) ->setKey('code') ->setLabel(pht('Code')), id(new PhabricatorEpochExportField()) ->setKey('date') ->setLabel(pht('Date')), ); if ($viewer->getIsAdmin()) { $fields[] = id(new PhabricatorStringExportField()) ->setKey('remoteAddress') ->setLabel(pht('Remote Address')); } return $fields; } protected function newExportData(array $events) { $viewer = $this->requireViewer(); $phids = array(); foreach ($events as $event) { if ($event->getPullerPHID()) { $phids[] = $event->getPullerPHID(); } } $handles = $viewer->loadHandles($phids); $export = array(); foreach ($events as $event) { $repository = $event->getRepository(); if ($repository) { $repository_phid = $repository->getPHID(); $repository_name = $repository->getDisplayName(); } else { $repository_phid = null; $repository_name = null; } $puller_phid = $event->getPullerPHID(); if ($puller_phid) { $puller_name = $handles[$puller_phid]->getName(); } else { $puller_name = null; } $map = array( 'repositoryPHID' => $repository_phid, 'repository' => $repository_name, 'pullerPHID' => $puller_phid, 'puller' => $puller_name, 'protocol' => $event->getRemoteProtocol(), 'result' => $event->getResultType(), 'code' => $event->getResultCode(), 'date' => $event->getEpoch(), ); if ($viewer->getIsAdmin()) { $map['remoteAddress'] = $event->getRemoteAddress(); } $export[] = $map; } return $export; } protected function getURI($path) { return '/diffusion/pulllog/'.$path; } protected function getBuiltinQueryNames() { return array( 'all' => pht('All Pull Logs'), ); } public function buildSavedQueryFromBuiltin($query_key) { $query = $this->newSavedQuery(); $query->setQueryKey($query_key); switch ($query_key) { case 'all': return $query; } return parent::buildSavedQueryFromBuiltin($query_key); } protected function renderResultList( array $logs, PhabricatorSavedQuery $query, array $handles) { $table = id(new DiffusionPullLogListView()) ->setViewer($this->requireViewer()) ->setLogs($logs); return id(new PhabricatorApplicationSearchResultView()) ->setTable($table); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/DiffusionLintCountQuery.php
src/applications/diffusion/query/DiffusionLintCountQuery.php
<?php final class DiffusionLintCountQuery extends PhabricatorQuery { private $branchIDs; private $paths; private $codes; public function withBranchIDs(array $branch_ids) { $this->branchIDs = $branch_ids; return $this; } public function withPaths(array $paths) { $this->paths = $paths; return $this; } public function withCodes(array $codes) { $this->codes = $codes; return $this; } public function execute() { if (!$this->paths) { throw new PhutilInvalidStateException('withPaths'); } if (!$this->branchIDs) { throw new PhutilInvalidStateException('withBranchIDs'); } $conn_r = id(new PhabricatorRepositoryCommit())->establishConnection('r'); $this->paths = array_unique($this->paths); list($dirs, $paths) = $this->processPaths(); $parts = array(); foreach ($dirs as $dir) { $parts[$dir] = qsprintf( $conn_r, 'path LIKE %>', $dir); } foreach ($paths as $path) { $parts[$path] = qsprintf( $conn_r, 'path = %s', $path); } $queries = array(); foreach ($parts as $key => $part) { $queries[] = qsprintf( $conn_r, 'SELECT %s path_prefix, COUNT(*) N FROM %T %Q', $key, PhabricatorRepository::TABLE_LINTMESSAGE, $this->buildCustomWhereClause($conn_r, $part)); } $huge_union_query = '('.implode(') UNION ALL (', $queries).')'; $data = queryfx_all( $conn_r, '%Q', $huge_union_query); return $this->processResults($data); } protected function buildCustomWhereClause( AphrontDatabaseConnection $conn, $part) { $where = array(); $where[] = $part; if ($this->codes !== null) { $where[] = qsprintf( $conn, 'code IN (%Ls)', $this->codes); } if ($this->branchIDs !== null) { $where[] = qsprintf( $conn, 'branchID IN (%Ld)', $this->branchIDs); } return $this->formatWhereClause($conn, $where); } private function processPaths() { $dirs = array(); $paths = array(); foreach ($this->paths as $path) { $path = '/'.$path; if (substr($path, -1) == '/') { $dirs[] = $path; } else { $paths[] = $path; } } return array($dirs, $paths); } private function processResults(array $data) { $data = ipull($data, 'N', 'path_prefix'); // Strip the leading "/" back off each path. $output = array(); foreach ($data as $path => $count) { $output[substr($path, 1)] = $count; } return $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/query/DiffusionRepositoryIdentitySearchEngine.php
src/applications/diffusion/query/DiffusionRepositoryIdentitySearchEngine.php
<?php final class DiffusionRepositoryIdentitySearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('Repository Identities'); } public function getApplicationClassName() { return 'PhabricatorDiffusionApplication'; } public function newQuery() { return new PhabricatorRepositoryIdentityQuery(); } protected function buildCustomSearchFields() { return array( id(new PhabricatorUsersSearchField()) ->setLabel(pht('Matching Users')) ->setKey('effectivePHIDs') ->setAliases( array( 'effective', 'effectivePHID', )) ->setDescription(pht('Search for identities by effective user.')), id(new DiffusionIdentityAssigneeSearchField()) ->setLabel(pht('Assigned To')) ->setKey('assignedPHIDs') ->setAliases( array( 'assigned', 'assignedPHID', )) ->setDescription(pht('Search for identities by explicit assignee.')), id(new PhabricatorSearchTextField()) ->setLabel(pht('Identity Contains')) ->setKey('match') ->setDescription(pht('Search for identities by substring.')), id(new PhabricatorSearchThreeStateField()) ->setLabel(pht('Has Matching User')) ->setKey('hasEffectivePHID') ->setOptions( pht('(Show All)'), pht('Show Identities With Matching Users'), pht('Show Identities Without Matching Users')), ); } protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); if ($map['hasEffectivePHID'] !== null) { $query->withHasEffectivePHID($map['hasEffectivePHID']); } if ($map['match'] !== null) { $query->withIdentityNameLike($map['match']); } if ($map['assignedPHIDs']) { $query->withAssignedPHIDs($map['assignedPHIDs']); } if ($map['effectivePHIDs']) { $query->withEffectivePHIDs($map['effectivePHIDs']); } return $query; } protected function getURI($path) { return '/diffusion/identity/'.$path; } protected function getBuiltinQueryNames() { $names = array( 'all' => pht('All Identities'), ); 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); } protected function renderResultList( array $identities, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($identities, 'PhabricatorRepositoryIdentity'); $viewer = $this->requireViewer(); $list = id(new PHUIObjectItemListView()) ->setViewer($viewer); $phids = array(); foreach ($identities as $identity) { $phids[] = $identity->getCurrentEffectiveUserPHID(); $phids[] = $identity->getManuallySetUserPHID(); } $handles = $viewer->loadHandles($phids); $unassigned = DiffusionIdentityUnassignedDatasource::FUNCTION_TOKEN; foreach ($identities as $identity) { $item = id(new PHUIObjectItemView()) ->setObjectName($identity->getObjectName()) ->setHeader($identity->getIdentityShortName()) ->setHref($identity->getURI()) ->setObject($identity); $status_icon = 'fa-circle-o grey'; $effective_phid = $identity->getCurrentEffectiveUserPHID(); if ($effective_phid) { $item->addIcon( 'fa-id-badge', pht('Matches User: %s', $handles[$effective_phid]->getName())); $status_icon = 'fa-id-badge'; } $assigned_phid = $identity->getManuallySetUserPHID(); if ($assigned_phid) { if ($assigned_phid === $unassigned) { $item->addIcon( 'fa-ban', pht('Explicitly Unassigned')); $status_icon = 'fa-ban'; } else { $item->addIcon( 'fa-user', pht('Assigned To: %s', $handles[$assigned_phid]->getName())); $status_icon = 'fa-user'; } } $item->setStatusIcon($status_icon); $list->addItem($item); } $result = new PhabricatorApplicationSearchResultView(); $result->setObjectList($list); $result->setNoDataString(pht('No Identities 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/diffusion/query/DiffusionSymbolQuery.php
src/applications/diffusion/query/DiffusionSymbolQuery.php
<?php /** * Query symbol information (class and function names and location), returning * a list of matching @{class:PhabricatorRepositorySymbol} objects and possibly * attached data. * * @task config Configuring the Query * @task exec Executing the Query * @task internal Internals */ final class DiffusionSymbolQuery extends PhabricatorOffsetPagedQuery { private $viewer; private $context; private $namePrefix; private $name; private $repositoryPHIDs; private $language; private $type; private $needPaths; private $needRepositories; /* -( Configuring the Query )---------------------------------------------- */ /** * @task config */ public function setViewer(PhabricatorUser $viewer) { $this->viewer = $viewer; return $this; } /** * @task config */ public function getViewer() { return $this->viewer; } /** * @task config */ public function setContext($context) { $this->context = $context; return $this; } /** * @task config */ public function setName($name) { $this->name = $name; return $this; } /** * @task config */ public function setNamePrefix($name_prefix) { $this->namePrefix = $name_prefix; return $this; } /** * @task config */ public function withRepositoryPHIDs(array $repository_phids) { $this->repositoryPHIDs = $repository_phids; return $this; } /** * @task config */ public function setLanguage($language) { $this->language = $language; return $this; } /** * @task config */ public function setType($type) { $this->type = $type; return $this; } /** * @task config */ public function needPaths($need_paths) { $this->needPaths = $need_paths; return $this; } /** * @task config */ public function needRepositories($need_repositories) { $this->needRepositories = $need_repositories; return $this; } /* -( Specialized Query )-------------------------------------------------- */ public function existsSymbolsInRepository($repository_phid) { $this ->withRepositoryPHIDs(array($repository_phid)) ->setLimit(1); $symbol = new PhabricatorRepositorySymbol(); $conn_r = $symbol->establishConnection('r'); $data = queryfx_all( $conn_r, 'SELECT * FROM %T %Q %Q', $symbol->getTableName(), $this->buildWhereClause($conn_r), $this->buildLimitClause($conn_r)); return (!empty($data)); } /* -( Executing the Query )------------------------------------------------ */ /** * @task exec */ public function execute() { if ($this->name && $this->namePrefix) { throw new Exception( pht('You can not set both a name and a name prefix!')); } else if (!$this->name && !$this->namePrefix) { throw new Exception( pht('You must set a name or a name prefix!')); } $symbol = new PhabricatorRepositorySymbol(); $conn_r = $symbol->establishConnection('r'); $data = queryfx_all( $conn_r, 'SELECT * FROM %T %Q %Q %Q', $symbol->getTableName(), $this->buildWhereClause($conn_r), $this->buildOrderClause($conn_r), $this->buildLimitClause($conn_r)); $symbols = $symbol->loadAllFromArray($data); if ($symbols) { if ($this->needPaths) { $this->loadPaths($symbols); } if ($this->needRepositories) { $symbols = $this->loadRepositories($symbols); } } return $symbols; } /* -( Internals )---------------------------------------------------------- */ /** * @task internal */ private function buildOrderClause($conn_r) { return qsprintf( $conn_r, 'ORDER BY symbolName ASC'); } /** * @task internal */ protected function buildWhereClause(AphrontDatabaseConnection $conn) { $where = array(); if (isset($this->context)) { $where[] = qsprintf( $conn, 'symbolContext = %s', $this->context); } if ($this->name) { $where[] = qsprintf( $conn, 'symbolName = %s', $this->name); } if ($this->namePrefix) { $where[] = qsprintf( $conn, 'symbolName LIKE %>', $this->namePrefix); } if ($this->repositoryPHIDs) { $where[] = qsprintf( $conn, 'repositoryPHID IN (%Ls)', $this->repositoryPHIDs); } if ($this->language) { $where[] = qsprintf( $conn, 'symbolLanguage = %s', $this->language); } if ($this->type) { $where[] = qsprintf( $conn, 'symbolType = %s', $this->type); } return $this->formatWhereClause($conn, $where); } /** * @task internal */ private function loadPaths(array $symbols) { assert_instances_of($symbols, 'PhabricatorRepositorySymbol'); $path_map = queryfx_all( id(new PhabricatorRepository())->establishConnection('r'), 'SELECT * FROM %T WHERE id IN (%Ld)', PhabricatorRepository::TABLE_PATH, mpull($symbols, 'getPathID')); $path_map = ipull($path_map, 'path', 'id'); foreach ($symbols as $symbol) { $symbol->attachPath(idx($path_map, $symbol->getPathID())); } } /** * @task internal */ private function loadRepositories(array $symbols) { assert_instances_of($symbols, 'PhabricatorRepositorySymbol'); $repos = id(new PhabricatorRepositoryQuery()) ->setViewer($this->viewer) ->withPHIDs(mpull($symbols, 'getRepositoryPHID')) ->execute(); $repos = mpull($repos, null, 'getPHID'); $visible = array(); foreach ($symbols as $symbol) { $repository = idx($repos, $symbol->getRepositoryPHID()); // repository is null mean "user can't view repo", so hide the symbol if ($repository) { $symbol->attachRepository($repository); $visible[] = $symbol; } } return $visible; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/DiffusionDiffInlineCommentQuery.php
src/applications/diffusion/query/DiffusionDiffInlineCommentQuery.php
<?php final class DiffusionDiffInlineCommentQuery extends PhabricatorDiffInlineCommentQuery { private $commitPHIDs; private $pathIDs; protected function newApplicationTransactionCommentTemplate() { return new PhabricatorAuditTransactionComment(); } public function withCommitPHIDs(array $phids) { $this->commitPHIDs = $phids; return $this; } public function withObjectPHIDs(array $phids) { return $this->withCommitPHIDs($phids); } public function withPathIDs(array $path_ids) { $this->pathIDs = $path_ids; return $this; } protected function buildInlineCommentWhereClauseParts( AphrontDatabaseConnection $conn) { $where = array(); $alias = $this->getPrimaryTableAlias(); $where[] = qsprintf( $conn, '%T.pathID IS NOT NULL', $alias); return $where; } protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) { $where = parent::buildWhereClauseParts($conn); $alias = $this->getPrimaryTableAlias(); if ($this->commitPHIDs !== null) { $where[] = qsprintf( $conn, '%T.commitPHID IN (%Ls)', $alias, $this->commitPHIDs); } if ($this->pathIDs !== null) { $where[] = qsprintf( $conn, '%T.pathID IN (%Ld)', $alias, $this->pathIDs); } return $where; } protected function loadHiddenCommentIDs( $viewer_phid, array $comments) { return array(); } protected function newInlineContextMap(array $inlines) { return array(); } protected function newInlineContextFromCacheData(array $map) { return PhabricatorDiffInlineCommentContext::newFromCacheData($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/query/DiffusionQuery.php
src/applications/diffusion/query/DiffusionQuery.php
<?php abstract class DiffusionQuery extends PhabricatorQuery { private $request; final protected function __construct() { // <protected> } protected static function newQueryObject( $base_class, DiffusionRequest $request) { $repository = $request->getRepository(); $obj = self::initQueryObject($base_class, $repository); $obj->request = $request; return $obj; } final protected static function initQueryObject( $base_class, PhabricatorRepository $repository) { $map = array( PhabricatorRepositoryType::REPOSITORY_TYPE_GIT => 'Git', PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL => 'Mercurial', PhabricatorRepositoryType::REPOSITORY_TYPE_SVN => 'Svn', ); $name = idx($map, $repository->getVersionControlSystem()); if (!$name) { throw new Exception(pht('Unsupported VCS!')); } $class = str_replace('Diffusion', 'Diffusion'.$name, $base_class); $obj = new $class(); return $obj; } final protected function getRequest() { return $this->request; } final public static function callConduitWithDiffusionRequest( PhabricatorUser $user, DiffusionRequest $drequest, $method, array $params = array(), $return_future = false) { $repository = $drequest->getRepository(); $core_params = array( 'repository' => $repository->getPHID(), ); if ($drequest->getBranch() !== null) { $core_params['branch'] = $drequest->getBranch(); } // If the method we're calling doesn't actually take some of the implicit // parameters we derive from the DiffusionRequest, omit them. $method_object = ConduitAPIMethod::getConduitMethod($method); $method_params = $method_object->getParamTypes(); foreach ($core_params as $key => $value) { if (empty($method_params[$key])) { unset($core_params[$key]); } } $params = $params + $core_params; $future = $repository->newConduitFuture( $user, $method, $params, $drequest->getIsClusterRequest()); if (!$return_future) { return $future->resolve(); } return $future; } public function execute() { return $this->executeQuery(); } abstract protected function executeQuery(); /* -( Query Utilities )---------------------------------------------------- */ final public static function loadCommitsByIdentifiers( array $identifiers, DiffusionRequest $drequest) { if (!$identifiers) { return array(); } $commits = array(); $commit_data = array(); $repository = $drequest->getRepository(); $commits = id(new PhabricatorRepositoryCommit())->loadAllWhere( 'repositoryID = %d AND commitIdentifier IN (%Ls)', $repository->getID(), $identifiers); $commits = mpull($commits, null, 'getCommitIdentifier'); // Build empty commit objects for every commit, so we can show unparsed // commits in history views (as "Importing") instead of not showing them. // This makes the process of importing and parsing commits clearer to the // user. $commit_list = array(); foreach ($identifiers as $identifier) { $commit_obj = idx($commits, $identifier); if (!$commit_obj) { $commit_obj = new PhabricatorRepositoryCommit(); $commit_obj->setRepositoryID($repository->getID()); $commit_obj->setCommitIdentifier($identifier); $commit_obj->makeEphemeral(); } $commit_list[$identifier] = $commit_obj; } $commits = $commit_list; $commit_ids = array_filter(mpull($commits, 'getID')); if ($commit_ids) { $commit_data = id(new PhabricatorRepositoryCommitData())->loadAllWhere( 'commitID in (%Ld)', $commit_ids); $commit_data = mpull($commit_data, null, 'getCommitID'); } foreach ($commits as $commit) { if (!$commit->getID()) { continue; } if (idx($commit_data, $commit->getID())) { $commit->attachCommitData($commit_data[$commit->getID()]); } } return $commits; } final public static function loadHistoryForCommitIdentifiers( array $identifiers, DiffusionRequest $drequest) { if (!$identifiers) { return array(); } $repository = $drequest->getRepository(); $commits = self::loadCommitsByIdentifiers($identifiers, $drequest); if (!$commits) { return array(); } $path = $drequest->getPath(); $conn_r = $repository->establishConnection('r'); $path_normal = DiffusionPathIDQuery::normalizePath($path); $paths = queryfx_all( $conn_r, 'SELECT id, path FROM %T WHERE pathHash IN (%Ls)', PhabricatorRepository::TABLE_PATH, array(md5($path_normal))); $paths = ipull($paths, 'id', 'path'); $path_id = idx($paths, $path_normal); $commit_ids = array_filter(mpull($commits, 'getID')); $path_changes = array(); if ($path_id && $commit_ids) { $path_changes = queryfx_all( $conn_r, 'SELECT * FROM %T WHERE commitID IN (%Ld) AND pathID = %d', PhabricatorRepository::TABLE_PATHCHANGE, $commit_ids, $path_id); $path_changes = ipull($path_changes, null, 'commitID'); } $history = array(); foreach ($identifiers as $identifier) { $item = new DiffusionPathChange(); $item->setCommitIdentifier($identifier); $commit = idx($commits, $identifier); if ($commit) { $item->setCommit($commit); try { $item->setCommitData($commit->getCommitData()); } catch (Exception $ex) { // Ignore, commit just doesn't have data. } $change = idx($path_changes, $commit->getID()); if ($change) { $item->setChangeType($change['changeType']); $item->setFileType($change['fileType']); } } $history[] = $item; } return $history; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/DiffusionSyncLogSearchEngine.php
src/applications/diffusion/query/DiffusionSyncLogSearchEngine.php
<?php final class DiffusionSyncLogSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('Sync Logs'); } public function getApplicationClassName() { return 'PhabricatorDiffusionApplication'; } public function newQuery() { return new PhabricatorRepositorySyncEventQuery(); } protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); if ($map['repositoryPHIDs']) { $query->withRepositoryPHIDs($map['repositoryPHIDs']); } if ($map['createdStart'] || $map['createdEnd']) { $query->withEpochBetween( $map['createdStart'], $map['createdEnd']); } return $query; } protected function buildCustomSearchFields() { return array( id(new PhabricatorSearchDatasourceField()) ->setDatasource(new DiffusionRepositoryDatasource()) ->setKey('repositoryPHIDs') ->setAliases(array('repository', 'repositories', 'repositoryPHID')) ->setLabel(pht('Repositories')) ->setDescription( pht('Search for sync logs for specific repositories.')), id(new PhabricatorSearchDateField()) ->setLabel(pht('Created After')) ->setKey('createdStart'), id(new PhabricatorSearchDateField()) ->setLabel(pht('Created Before')) ->setKey('createdEnd'), ); } protected function newExportFields() { $viewer = $this->requireViewer(); $fields = array( id(new PhabricatorPHIDExportField()) ->setKey('repositoryPHID') ->setLabel(pht('Repository PHID')), id(new PhabricatorStringExportField()) ->setKey('repository') ->setLabel(pht('Repository')), id(new PhabricatorPHIDExportField()) ->setKey('devicePHID') ->setLabel(pht('Device PHID')), id(new PhabricatorPHIDExportField()) ->setKey('fromDevicePHID') ->setLabel(pht('From Device PHID')), id(new PhabricatorIntExportField()) ->setKey('deviceVersion') ->setLabel(pht('Device Version')), id(new PhabricatorIntExportField()) ->setKey('fromDeviceVersion') ->setLabel(pht('From Device Version')), id(new PhabricatorStringExportField()) ->setKey('result') ->setLabel(pht('Result')), id(new PhabricatorIntExportField()) ->setKey('code') ->setLabel(pht('Code')), id(new PhabricatorEpochExportField()) ->setKey('date') ->setLabel(pht('Date')), id(new PhabricatorIntExportField()) ->setKey('syncWait') ->setLabel(pht('Sync Wait')), ); return $fields; } protected function newExportData(array $events) { $viewer = $this->requireViewer(); $export = array(); foreach ($events as $event) { $repository = $event->getRepository(); $repository_phid = $repository->getPHID(); $repository_name = $repository->getDisplayName(); $map = array( 'repositoryPHID' => $repository_phid, 'repository' => $repository_name, 'devicePHID' => $event->getDevicePHID(), 'fromDevicePHID' => $event->getFromDevicePHID(), 'deviceVersion' => $event->getDeviceVersion(), 'fromDeviceVersion' => $event->getFromDeviceVersion(), 'result' => $event->getResultType(), 'code' => $event->getResultCode(), 'date' => $event->getEpoch(), 'syncWait' => $event->getSyncWait(), ); $export[] = $map; } return $export; } protected function getURI($path) { return '/diffusion/synclog/'.$path; } protected function getBuiltinQueryNames() { return array( 'all' => pht('All Sync Logs'), ); } public function buildSavedQueryFromBuiltin($query_key) { $query = $this->newSavedQuery(); $query->setQueryKey($query_key); switch ($query_key) { case 'all': return $query; } return parent::buildSavedQueryFromBuiltin($query_key); } protected function renderResultList( array $logs, PhabricatorSavedQuery $query, array $handles) { $table = id(new DiffusionSyncLogListView()) ->setViewer($this->requireViewer()) ->setLogs($logs); return id(new PhabricatorApplicationSearchResultView()) ->setTable($table); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/DiffusionCommitResultBucket.php
src/applications/diffusion/query/DiffusionCommitResultBucket.php
<?php abstract class DiffusionCommitResultBucket extends PhabricatorSearchResultBucket { public static function getAllResultBuckets() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getResultBucketKey') ->execute(); } protected function hasAuditorsWithStatus( PhabricatorRepositoryCommit $commit, array $phids, array $statuses) { foreach ($commit->getAudits() as $audit) { if (!isset($phids[$audit->getAuditorPHID()])) { continue; } if (!isset($statuses[$audit->getAuditStatus()])) { continue; } return true; } 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/query/filecontent/DiffusionGitFileContentQuery.php
src/applications/diffusion/query/filecontent/DiffusionGitFileContentQuery.php
<?php final class DiffusionGitFileContentQuery extends DiffusionFileContentQuery { protected function newQueryFuture() { $drequest = $this->getRequest(); $repository = $drequest->getRepository(); $path = $drequest->getPath(); $commit = $drequest->getCommit(); return $repository->getLocalCommandFuture( 'cat-file blob -- %s', sprintf('%s:%s', $commit, $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/query/filecontent/DiffusionFileContentQuery.php
src/applications/diffusion/query/filecontent/DiffusionFileContentQuery.php
<?php abstract class DiffusionFileContentQuery extends DiffusionFileFutureQuery { final public static function newFromDiffusionRequest( DiffusionRequest $request) { return parent::newQueryObject(__CLASS__, $request); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/filecontent/DiffusionSvnFileContentQuery.php
src/applications/diffusion/query/filecontent/DiffusionSvnFileContentQuery.php
<?php final class DiffusionSvnFileContentQuery extends DiffusionFileContentQuery { protected function newQueryFuture() { $drequest = $this->getRequest(); $repository = $drequest->getRepository(); $path = $drequest->getPath(); $commit = $drequest->getCommit(); return $repository->getRemoteCommandFuture( 'cat %s', $repository->getSubversionPathURI($path, $commit)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/filecontent/DiffusionMercurialFileContentQuery.php
src/applications/diffusion/query/filecontent/DiffusionMercurialFileContentQuery.php
<?php final class DiffusionMercurialFileContentQuery extends DiffusionFileContentQuery { protected function newQueryFuture() { $drequest = $this->getRequest(); $repository = $drequest->getRepository(); $path = $drequest->getPath(); $commit = $drequest->getCommit(); return $repository->getLocalCommandFuture( 'cat --rev %s -- %s', $commit, $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/query/rawdiff/DiffusionSvnRawDiffQuery.php
src/applications/diffusion/query/rawdiff/DiffusionSvnRawDiffQuery.php
<?php final class DiffusionSvnRawDiffQuery extends DiffusionRawDiffQuery { protected function newQueryFuture() { $drequest = $this->getRequest(); $repository = $drequest->getRepository(); $commit = $this->getAnchorCommit(); $arc_root = phutil_get_library_root('arcanist'); $against = $this->getAgainstCommit(); if ($against === null) { $against = $commit - 1; } $future = $repository->getRemoteCommandFuture( 'diff --diff-cmd %s -x -U%d -r %d:%d %s', $arc_root.'/../scripts/repository/binary_safe_diff.sh', $this->getLinesOfContext(), $against, $commit, $repository->getSubversionPathURI($drequest->getPath())); return $future; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/rawdiff/DiffusionMercurialRawDiffQuery.php
src/applications/diffusion/query/rawdiff/DiffusionMercurialRawDiffQuery.php
<?php final class DiffusionMercurialRawDiffQuery extends DiffusionRawDiffQuery { protected function newQueryFuture() { $drequest = $this->getRequest(); $repository = $drequest->getRepository(); $commit = $this->getAnchorCommit(); // If there's no path, get the entire raw diff. $path = nonempty($drequest->getPath(), '.'); $against = $this->getAgainstCommit(); if ($against === null) { // If `$commit` has no parents (usually because it's the first commit // in the repository), we want to diff against `null`. This revset will // do that for us automatically. $against = hgsprintf('(%s^ or null)', $commit); } $future = $repository->getLocalCommandFuture( 'diff -U %d --git --rev %s --rev %s -- %s', $this->getLinesOfContext(), $against, hgsprintf('%s', $commit), $path); return $future; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/rawdiff/DiffusionRawDiffQuery.php
src/applications/diffusion/query/rawdiff/DiffusionRawDiffQuery.php
<?php abstract class DiffusionRawDiffQuery extends DiffusionFileFutureQuery { private $linesOfContext = 65535; private $anchorCommit; private $againstCommit; final public static function newFromDiffusionRequest( DiffusionRequest $request) { return parent::newQueryObject(__CLASS__, $request); } final public function setLinesOfContext($lines_of_context) { $this->linesOfContext = $lines_of_context; return $this; } final public function getLinesOfContext() { return $this->linesOfContext; } final public function setAgainstCommit($value) { $this->againstCommit = $value; return $this; } final public function getAgainstCommit() { return $this->againstCommit; } public function setAnchorCommit($anchor_commit) { $this->anchorCommit = $anchor_commit; return $this; } public function getAnchorCommit() { if ($this->anchorCommit) { return $this->anchorCommit; } return $this->getRequest()->getStableCommit(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/rawdiff/DiffusionGitRawDiffQuery.php
src/applications/diffusion/query/rawdiff/DiffusionGitRawDiffQuery.php
<?php final class DiffusionGitRawDiffQuery extends DiffusionRawDiffQuery { protected function newQueryFuture() { $drequest = $this->getRequest(); $repository = $drequest->getRepository(); $commit = $this->getAnchorCommit(); $options = array( '-M', '-C', '--no-ext-diff', '--no-color', '--src-prefix=a/', '--dst-prefix=b/', '-U'.(int)$this->getLinesOfContext(), ); $against = $this->getAgainstCommit(); if ($against === null) { // Check if this is the root commit by seeing if it has parents, since // `git diff X^ X` does not work if "X" is the initial commit. list($parents) = $repository->execxLocalCommand( 'log -n 1 %s %s --', '--format=%P', gitsprintf('%s', $commit)); if (strlen(trim($parents))) { $against = $commit.'^'; } else { $against = ArcanistGitAPI::GIT_MAGIC_ROOT_COMMIT; } } $path = $drequest->getPath(); if ($path === null || !strlen($path)) { $path = '.'; } return $repository->getLocalCommandFuture( 'diff %Ls %s %s -- %s', $options, gitsprintf('%s', $against), gitsprintf('%s', $commit), $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/query/pathchange/DiffusionPathChangeQuery.php
src/applications/diffusion/query/pathchange/DiffusionPathChangeQuery.php
<?php final class DiffusionPathChangeQuery extends Phobject { private $request; private $limit; public function setLimit($limit) { $this->limit = $limit; return $this; } public function getLimit() { return $this->limit; } private function __construct() { // <private> } public static function newFromDiffusionRequest( DiffusionRequest $request) { $query = new DiffusionPathChangeQuery(); $query->request = $request; return $query; } protected function getRequest() { return $this->request; } public function loadChanges() { return $this->executeQuery(); } protected function executeQuery() { $drequest = $this->getRequest(); $repository = $drequest->getRepository(); $commit = $drequest->loadCommit(); $conn_r = $repository->establishConnection('r'); if ($this->limit) { $limit = qsprintf( $conn_r, 'LIMIT %d', $this->limit + 1); } else { $limit = qsprintf($conn_r, ''); } $raw_changes = queryfx_all( $conn_r, 'SELECT c.*, p.path pathName, t.path targetPathName, i.commitIdentifier targetCommitIdentifier FROM %T c LEFT JOIN %T p ON c.pathID = p.id LEFT JOIN %T t ON c.targetPathID = t.id LEFT JOIN %T i ON c.targetCommitID = i.id WHERE c.commitID = %d AND isDirect = 1 %Q', PhabricatorRepository::TABLE_PATHCHANGE, PhabricatorRepository::TABLE_PATH, PhabricatorRepository::TABLE_PATH, $commit->getTableName(), $commit->getID(), $limit); $limited = $this->limit && (count($raw_changes) > $this->limit); if ($limited) { $raw_changes = array_slice($raw_changes, 0, $this->limit); } $changes = array(); $raw_changes = isort($raw_changes, 'pathName'); foreach ($raw_changes as $raw_change) { $type = $raw_change['changeType']; if ($type == DifferentialChangeType::TYPE_CHILD) { continue; } $change = new DiffusionPathChange(); $change->setPath(ltrim($raw_change['pathName'], '/')); $change->setChangeType($raw_change['changeType']); $change->setFileType($raw_change['fileType']); $change->setCommitIdentifier($commit->getCommitIdentifier()); $target_path = $raw_change['targetPathName']; if ($target_path !== null) { $target_path = ltrim($target_path, '/'); } $change->setTargetPath($target_path); $change->setTargetCommitIdentifier($raw_change['targetCommitIdentifier']); $id = $raw_change['pathID']; $changes[$id] = $change; } // Deduce the away paths by examining all the changes, if we loaded them // all. if (!$limited) { $away = array(); foreach ($changes as $change) { if ($change->getTargetPath()) { $away[$change->getTargetPath()][] = $change->getPath(); } } foreach ($changes as $change) { if (isset($away[$change->getPath()])) { $change->setAwayPaths($away[$change->getPath()]); } } } return $changes; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/lowlevel/DiffusionLowLevelMercurialBranchesQuery.php
src/applications/diffusion/query/lowlevel/DiffusionLowLevelMercurialBranchesQuery.php
<?php /** * Execute and parse a low-level Mercurial branches query using `hg branches`. */ final class DiffusionLowLevelMercurialBranchesQuery extends DiffusionLowLevelQuery { private $contains; public function withContainsCommit($commit) { $this->contains = $commit; return $this; } protected function executeQuery() { $repository = $this->getRepository(); $specs = array(); if ($this->contains !== null) { $specs['all'] = hgsprintf( '(descendants(%s) and head())', $this->contains); $specs['open'] = hgsprintf( '(descendants(%s) and head() and not closed())', $this->contains); } else { $specs['all'] = hgsprintf('head()'); $specs['open'] = hgsprintf('head() and not closed()'); } $futures = array(); foreach ($specs as $key => $spec) { $futures[$key] = $repository->getLocalCommandFuture( 'log --template %s --rev %s', '{node}\1{branch}\2', $spec); } $branches = array(); $open = array(); foreach (new FutureIterator($futures) as $key => $future) { list($stdout) = $future->resolvex(); $lines = explode("\2", $stdout); $lines = array_filter($lines); foreach ($lines as $line) { list($node, $branch) = explode("\1", $line); $id = $node.'/'.$branch; if (empty($branches[$id])) { $branches[$id] = id(new DiffusionRepositoryRef()) ->setShortName($branch) ->setCommitIdentifier($node); } if ($key == 'open') { $open[$id] = true; } } } foreach ($branches as $id => $branch) { $branch->setRawFields( array( 'closed' => (empty($open[$id])), )); } return array_values($branches); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/lowlevel/DiffusionLowLevelResolveRefsQuery.php
src/applications/diffusion/query/lowlevel/DiffusionLowLevelResolveRefsQuery.php
<?php /** * Resolves references (like short commit names, branch names, tag names, etc.) * into canonical, stable commit identifiers. This query works for all * repository types. * * This query will always resolve refs which can be resolved, but may need to * perform VCS operations. A faster (but less complete) counterpart query is * available in @{class:DiffusionCachedResolveRefsQuery}; that query can * resolve most refs without VCS operations. */ final class DiffusionLowLevelResolveRefsQuery extends DiffusionLowLevelQuery { private $refs; private $types; public function withRefs(array $refs) { $this->refs = $refs; return $this; } public function withTypes(array $types) { $this->types = $types; return $this; } protected function executeQuery() { if (!$this->refs) { return array(); } $repository = $this->getRepository(); if (!$repository->hasLocalWorkingCopy()) { return array(); } switch ($this->getRepository()->getVersionControlSystem()) { case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: $result = $this->resolveGitRefs(); break; case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: $result = $this->resolveMercurialRefs(); break; case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: $result = $this->resolveSubversionRefs(); break; default: throw new Exception(pht('Unsupported repository type!')); } if ($this->types !== null) { $result = $this->filterRefsByType($result, $this->types); } return $result; } private function resolveGitRefs() { $repository = $this->getRepository(); $unresolved = array_fuse($this->refs); $results = array(); $possible_symbols = array(); foreach ($unresolved as $ref) { // See T13647. If this symbol is exactly 40 hex characters long, it may // never resolve as a branch or tag name. Filter these symbols out for // consistency with Git behavior -- and to avoid an expensive // "git for-each-ref" when resolving only commit hashes, which happens // during repository updates. if (preg_match('(^[a-f0-9]{40}\z)', $ref)) { continue; } $possible_symbols[$ref] = $ref; } // First, resolve branches and tags. if ($possible_symbols) { $ref_map = id(new DiffusionLowLevelGitRefQuery()) ->setRepository($repository) ->withRefTypes( array( PhabricatorRepositoryRefCursor::TYPE_BRANCH, PhabricatorRepositoryRefCursor::TYPE_TAG, )) ->execute(); $ref_map = mgroup($ref_map, 'getShortName'); $tag_prefix = 'refs/tags/'; foreach ($possible_symbols as $ref) { if (empty($ref_map[$ref])) { continue; } foreach ($ref_map[$ref] as $result) { $fields = $result->getRawFields(); $objectname = idx($fields, 'refname'); if (!strncmp($objectname, $tag_prefix, strlen($tag_prefix))) { $type = 'tag'; } else { $type = 'branch'; } $info = array( 'type' => $type, 'identifier' => $result->getCommitIdentifier(), ); if ($type == 'tag') { $alternate = idx($fields, 'objectname'); if ($alternate) { $info['alternate'] = $alternate; } } $results[$ref][] = $info; } unset($unresolved[$ref]); } } // If we resolved everything, we're done. if (!$unresolved) { return $results; } // Try to resolve anything else. This stuff either doesn't exist or is // some ref like "HEAD^^^". $future = $repository->getLocalCommandFuture('cat-file --batch-check'); $future->write(implode("\n", $unresolved)); list($stdout) = $future->resolvex(); $lines = explode("\n", rtrim($stdout, "\n")); if (count($lines) !== count($unresolved)) { throw new Exception( pht( 'Unexpected line count from `%s`!', 'git cat-file')); } $hits = array(); $tags = array(); $lines = array_combine($unresolved, $lines); foreach ($lines as $ref => $line) { $parts = explode(' ', $line); if (count($parts) < 2) { throw new Exception( pht( 'Failed to parse `%s` output: %s', 'git cat-file', $line)); } list($identifier, $type) = $parts; if ($type == 'missing') { // This is either an ambiguous reference which resolves to several // objects, or an invalid reference. For now, always treat it as // invalid. It would be nice to resolve all possibilities for // ambiguous references at some point, although the strategy for doing // so isn't clear to me. continue; } switch ($type) { case 'commit': break; case 'tag': $tags[] = $identifier; break; default: throw new Exception( pht( 'Unexpected object type from `%s`: %s', 'git cat-file', $line)); } $hits[] = array( 'ref' => $ref, 'type' => $type, 'identifier' => $identifier, ); } $tag_map = array(); if ($tags) { // If some of the refs were tags, just load every tag in order to figure // out which commits they map to. This might be somewhat inefficient in // repositories with a huge number of tags. $tag_refs = id(new DiffusionLowLevelGitRefQuery()) ->setRepository($repository) ->withRefTypes( array( PhabricatorRepositoryRefCursor::TYPE_TAG, )) ->executeQuery(); foreach ($tag_refs as $tag_ref) { $tag_map[$tag_ref->getShortName()] = $tag_ref->getCommitIdentifier(); } } $results = array(); foreach ($hits as $hit) { $type = $hit['type']; $ref = $hit['ref']; $alternate = null; if ($type == 'tag') { $tag_identifier = idx($tag_map, $ref); if ($tag_identifier === null) { // This can happen when we're asked to resolve the hash of a "tag" // object created with "git tag --annotate" that isn't currently // reachable from any ref. Just leave things as they are. } else { // Otherwise, we have a normal named tag. $alternate = $identifier; $identifier = $tag_identifier; } } $result = array( 'type' => $type, 'identifier' => $identifier, ); if ($alternate !== null) { $result['alternate'] = $alternate; } $results[$ref][] = $result; } return $results; } private function resolveMercurialRefs() { $repository = $this->getRepository(); // First, pull all of the branch heads in the repository. Doing this in // bulk is much faster than querying each individual head if we're // checking even a small number of refs. $branches = id(new DiffusionLowLevelMercurialBranchesQuery()) ->setRepository($repository) ->executeQuery(); $branches = mgroup($branches, 'getShortName'); $results = array(); $unresolved = $this->refs; foreach ($unresolved as $key => $ref) { if (empty($branches[$ref])) { continue; } foreach ($branches[$ref] as $branch) { $fields = $branch->getRawFields(); $results[$ref][] = array( 'type' => 'branch', 'identifier' => $branch->getCommitIdentifier(), 'closed' => idx($fields, 'closed', false), ); } unset($unresolved[$key]); } if (!$unresolved) { return $results; } // If some of the refs look like hashes, try to bulk resolve them. This // workflow happens via RefEngine and bulk resolution is dramatically // faster than individual resolution. See PHI158. $hashlike = array(); foreach ($unresolved as $key => $ref) { if (preg_match('/^[a-f0-9]{40}\z/', $ref)) { $hashlike[$key] = $ref; } } if (count($hashlike) > 1) { $hashlike_map = array(); $hashlike_groups = array_chunk($hashlike, 64, true); foreach ($hashlike_groups as $hashlike_group) { $hashlike_arg = array(); foreach ($hashlike_group as $hashlike_ref) { $hashlike_arg[] = hgsprintf('%s', $hashlike_ref); } $hashlike_arg = '('.implode(' or ', $hashlike_arg).')'; list($err, $refs) = $repository->execLocalCommand( 'log --template=%s --rev %s', '{node}\n', $hashlike_arg); if ($err) { // NOTE: If any ref fails to resolve, Mercurial will exit with an // error. We just give up on the whole group and resolve it // individually below. In theory, we could split it into subgroups // but the pathway where this bulk resolution matters rarely tries // to resolve missing refs (see PHI158). continue; } $refs = phutil_split_lines($refs, false); foreach ($refs as $ref) { $hashlike_map[$ref] = true; } } foreach ($unresolved as $key => $ref) { if (!isset($hashlike_map[$ref])) { continue; } $results[$ref][] = array( 'type' => 'commit', 'identifier' => $ref, ); unset($unresolved[$key]); } } if (!$unresolved) { return $results; } // If we still have unresolved refs (which might be things like "tip"), // try to resolve them individually. $futures = array(); foreach ($unresolved as $ref) { $futures[$ref] = $repository->getLocalCommandFuture( 'log --template=%s --rev %s', '{node}', hgsprintf('%s', $ref)); } foreach (new FutureIterator($futures) as $ref => $future) { try { list($stdout) = $future->resolvex(); } catch (CommandException $ex) { if (preg_match('/ambiguous identifier/', $ex->getStderr())) { // This indicates that the ref ambiguously matched several things. // Eventually, it would be nice to return all of them, but it is // unclear how to best do that. For now, treat it as a miss instead. continue; } if (preg_match('/unknown revision/', $ex->getStderr())) { // No matches for this ref. continue; } throw $ex; } // It doesn't look like we can figure out the type (commit/branch/rev) // from this output very easily. For now, just call everything a commit. $type = 'commit'; $results[$ref][] = array( 'type' => $type, 'identifier' => trim($stdout), ); } return $results; } private function resolveSubversionRefs() { // We don't have any VCS logic for Subversion, so just use the cached // query. return id(new DiffusionCachedResolveRefsQuery()) ->setRepository($this->getRepository()) ->withRefs($this->refs) ->execute(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/lowlevel/DiffusionLowLevelFilesizeQuery.php
src/applications/diffusion/query/lowlevel/DiffusionLowLevelFilesizeQuery.php
<?php final class DiffusionLowLevelFilesizeQuery extends DiffusionLowLevelQuery { private $identifier; public function withIdentifier($identifier) { $this->identifier = $identifier; return $this; } protected function executeQuery() { if (!strlen($this->identifier)) { throw new PhutilInvalidStateException('withIdentifier'); } $type = $this->getRepository()->getVersionControlSystem(); switch ($type) { case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: $result = $this->loadGitFilesizes(); break; default: throw new Exception(pht('Unsupported repository type "%s"!', $type)); } return $result; } private function loadGitFilesizes() { $repository = $this->getRepository(); $identifier = $this->identifier; $paths_future = $repository->getLocalCommandFuture( 'diff-tree -z -r --no-commit-id %s --', gitsprintf('%s', $identifier)); // With "-z" we get "<fields>\0<filename>\0" for each line. Process the // delimited text as "<fields>, <filename>" pairs. $path_lines = id(new LinesOfALargeExecFuture($paths_future)) ->setDelimiter("\0"); $paths = array(); $path_pairs = new PhutilChunkedIterator($path_lines, 2); foreach ($path_pairs as $path_pair) { if (count($path_pair) != 2) { throw new Exception( pht( 'Unexpected number of output lines from "git diff-tree" when '. 'processing commit ("%s"): expected an even number of lines.', $identifier)); } list($fields, $pathname) = array_values($path_pair); $fields = explode(' ', $fields); // Fields are: // // :100644 100644 aaaa bbbb M // // [0] Old file mode. // [1] New file mode. // [2] Old object hash. // [3] New object hash. // [4] Change mode. $paths[] = array( 'path' => $pathname, 'newHash' => $fields[3], ); } $path_sizes = array(); if (!$paths) { return $path_sizes; } $check_paths = array(); foreach ($paths as $path) { if ($path['newHash'] === DiffusionCommitHookEngine::EMPTY_HASH) { $path_sizes[$path['path']] = 0; continue; } $check_paths[$path['newHash']][] = $path['path']; } if (!$check_paths) { return $path_sizes; } $future = $repository->getLocalCommandFuture( 'cat-file --batch-check=%s', '%(objectsize)'); $future->write(implode("\n", array_keys($check_paths))); $size_lines = id(new LinesOfALargeExecFuture($future)) ->setDelimiter("\n"); foreach ($size_lines as $line) { $object_size = (int)$line; $object_hash = head_key($check_paths); $path_names = $check_paths[$object_hash]; unset($check_paths[$object_hash]); foreach ($path_names as $path_name) { $path_sizes[$path_name] = $object_size; } } if ($check_paths) { throw new Exception( pht( 'Unexpected number of output lines from "git cat-file" when '. 'processing commit ("%s").', $identifier)); } return $path_sizes; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/lowlevel/DiffusionLowLevelCommitQuery.php
src/applications/diffusion/query/lowlevel/DiffusionLowLevelCommitQuery.php
<?php /** * Populate a @{class:DiffusionCommitRef} with information about a specific * commit in a repository. This is a low-level query which talks directly to * the underlying VCS. */ final class DiffusionLowLevelCommitQuery extends DiffusionLowLevelQuery { private $identifier; public function withIdentifier($identifier) { $this->identifier = $identifier; return $this; } protected function executeQuery() { if (!strlen($this->identifier)) { throw new PhutilInvalidStateException('withIdentifier'); } $type = $this->getRepository()->getVersionControlSystem(); switch ($type) { case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: $result = $this->loadGitCommitRef(); break; case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: $result = $this->loadMercurialCommitRef(); break; case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: $result = $this->loadSubversionCommitRef(); break; default: throw new Exception(pht('Unsupported repository type "%s"!', $type)); } return $result; } private function loadGitCommitRef() { $repository = $this->getRepository(); // See T5028. The "%B" (raw body) mode is not present in very old versions // of Git. Use "%s" and "%b" ("subject" and "wrapped body") as an // approximation. $git_binary = PhutilBinaryAnalyzer::getForBinary('git'); $git_version = $git_binary->getBinaryVersion(); if (version_compare($git_version, '1.7.2', '>=')) { $body_format = '%B'; $split_body = false; } else { $body_format = '%s%x00%b'; $split_body = true; } $argv = array(); $argv[] = '-n'; $argv[] = '1'; $argv[] = '--encoding=UTF-8'; $argv[] = sprintf( '--format=%s', implode( '%x00', array( '%e', '%cn', '%ce', '%an', '%ae', '%T', '%at', $body_format, // The "git log" output includes a trailing newline. We want to // faithfully capture only the exact text of the commit message, // so include an explicit terminator: this makes sure the exact // body text is surrounded by "\0" characters. '~', ))); // Even though we pass --encoding here, git doesn't always succeed, so // we try a little harder, since git *does* tell us what the actual encoding // is correctly (unless it doesn't; encoding is sometimes empty). list($info) = $repository->execxLocalCommand( 'log -n 1 %Ls %s --', $argv, gitsprintf('%s', $this->identifier)); $parts = explode("\0", $info); $encoding = array_shift($parts); foreach ($parts as $key => $part) { if ($encoding) { $part = phutil_utf8_convert($part, 'UTF-8', $encoding); } $parts[$key] = phutil_utf8ize($part); if (!strlen($parts[$key])) { $parts[$key] = null; } } $hashes = array( id(new DiffusionCommitHash()) ->setHashType(ArcanistDifferentialRevisionHash::HASH_GIT_COMMIT) ->setHashValue($this->identifier), id(new DiffusionCommitHash()) ->setHashType(ArcanistDifferentialRevisionHash::HASH_GIT_TREE) ->setHashValue($parts[4]), ); $author_epoch = (int)$parts[5]; if (!$author_epoch) { $author_epoch = null; } if ($split_body) { // Here, the body is: "subject", "\0", "wrapped body". Stitch the // pieces back together by putting a newline between them if both // parts are nonempty. $head = $parts[6]; $tail = $parts[7]; if (strlen($head) && strlen($tail)) { $body = $head."\n\n".$tail; } else if (strlen($head)) { $body = $head; } else if (strlen($tail)) { $body = $tail; } else { $body = ''; } } else { // Here, the body is the raw unwrapped body. $body = $parts[6]; } return id(new DiffusionCommitRef()) ->setCommitterName($parts[0]) ->setCommitterEmail($parts[1]) ->setAuthorName($parts[2]) ->setAuthorEmail($parts[3]) ->setHashes($hashes) ->setAuthorEpoch($author_epoch) ->setMessage($body); } private function loadMercurialCommitRef() { $repository = $this->getRepository(); list($stdout) = $repository->execxLocalCommand( 'log --template %s --rev %s', '{author}\\n{desc}', hgsprintf('%s', $this->identifier)); list($author, $message) = explode("\n", $stdout, 2); $author = phutil_utf8ize($author); $message = phutil_utf8ize($message); list($author_name, $author_email) = $this->splitUserIdentifier($author); $hashes = array( id(new DiffusionCommitHash()) ->setHashType(ArcanistDifferentialRevisionHash::HASH_MERCURIAL_COMMIT) ->setHashValue($this->identifier), ); return id(new DiffusionCommitRef()) ->setAuthorName($author_name) ->setAuthorEmail($author_email) ->setMessage($message) ->setHashes($hashes); } private function loadSubversionCommitRef() { $repository = $this->getRepository(); list($xml) = $repository->execxRemoteCommand( 'log --xml --limit 1 %s', $repository->getSubversionPathURI(null, $this->identifier)); // Subversion may send us back commit messages which won't parse because // they have non UTF-8 garbage in them. Slam them into valid UTF-8. $xml = phutil_utf8ize($xml); $log = new SimpleXMLElement($xml); $entry = $log->logentry[0]; $author = (string)$entry->author; $message = (string)$entry->msg; list($author_name, $author_email) = $this->splitUserIdentifier($author); // No hashes in Subversion. $hashes = array(); return id(new DiffusionCommitRef()) ->setAuthorName($author_name) ->setAuthorEmail($author_email) ->setMessage($message) ->setHashes($hashes); } private function splitUserIdentifier($user) { $email = new PhutilEmailAddress($user); if ($email->getDisplayName() || $email->getDomainName()) { $user_name = $email->getDisplayName(); $user_email = $email->getAddress(); } else { $user_name = $email->getAddress(); $user_email = null; } return array($user_name, $user_email); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/lowlevel/DiffusionLowLevelMercurialPathsQuery.php
src/applications/diffusion/query/lowlevel/DiffusionLowLevelMercurialPathsQuery.php
<?php /** * Execute and parse a low-level Mercurial paths query using `hg locate`. */ final class DiffusionLowLevelMercurialPathsQuery extends DiffusionLowLevelQuery { private $commit; private $path; public function withCommit($commit) { $this->commit = $commit; return $this; } public function withPath($path) { $this->path = $path; return $this; } protected function executeQuery() { $repository = $this->getRepository(); $path = $this->path; $commit = $this->commit; $has_files = PhutilBinaryAnalyzer::getForBinary('hg') ->isMercurialFilesCommandAvailable(); if ($has_files) { $hg_paths_command = 'files --print0 --rev %s -I %s'; } else { $hg_paths_command = 'locate --print0 --rev %s -I %s'; } if ($path !== null) { $match_against = trim($path, '/'); $prefix = trim('./'.$match_against, '/'); } else { $prefix = '.'; } list($entire_manifest) = $repository->execxLocalCommand( $hg_paths_command, hgsprintf('%s', $commit), $prefix); return explode("\0", $entire_manifest); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/lowlevel/DiffusionLowLevelGitRefQuery.php
src/applications/diffusion/query/lowlevel/DiffusionLowLevelGitRefQuery.php
<?php /** * Execute and parse a low-level Git ref query using `git for-each-ref`. This * is useful for returning a list of tags or branches. */ final class DiffusionLowLevelGitRefQuery extends DiffusionLowLevelQuery { private $refTypes; public function withRefTypes(array $ref_types) { $this->refTypes = $ref_types; return $this; } protected function executeQuery() { $type_branch = PhabricatorRepositoryRefCursor::TYPE_BRANCH; $type_tag = PhabricatorRepositoryRefCursor::TYPE_TAG; $type_ref = PhabricatorRepositoryRefCursor::TYPE_REF; $ref_types = $this->refTypes; if (!$ref_types) { $ref_types = array($type_branch, $type_tag, $type_ref); } $ref_types = array_fuse($ref_types); $with_branches = isset($ref_types[$type_branch]); $with_tags = isset($ref_types[$type_tag]); $with_refs = isset($refs_types[$type_ref]); $repository = $this->getRepository(); $prefixes = array(); $branch_prefix = 'refs/heads/'; $tag_prefix = 'refs/tags/'; if ($with_refs || count($ref_types) > 1) { // If we're loading refs or more than one type of ref, just query // everything. $prefix = 'refs/'; } else { if ($with_branches) { $prefix = $branch_prefix; } if ($with_tags) { $prefix = $tag_prefix; } } $branch_len = strlen($branch_prefix); $tag_len = strlen($tag_prefix); list($stdout) = $repository->execxLocalCommand( 'for-each-ref --sort=%s --format=%s -- %s', '-creatordate', $this->getFormatString(), $prefix); $stdout = rtrim($stdout); if (!strlen($stdout)) { return array(); } $remote_prefix = 'refs/remotes/'; $remote_len = strlen($remote_prefix); // NOTE: Although git supports --count, we can't apply any offset or // limit logic until the very end because we may encounter a HEAD which // we want to discard. $lines = explode("\n", $stdout); $results = array(); foreach ($lines as $line) { $fields = $this->extractFields($line); $refname = $fields['refname']; if (!strncmp($refname, $branch_prefix, $branch_len)) { $short = substr($refname, $branch_len); $type = $type_branch; } else if (!strncmp($refname, $tag_prefix, $tag_len)) { $short = substr($refname, $tag_len); $type = $type_tag; } else if (!strncmp($refname, $remote_prefix, $remote_len)) { // If we've found a remote ref that we didn't recognize as naming a // branch, just ignore it. This can happen if we're observing a remote, // and that remote has its own remotes. We don't care about their // state and they may be out of date, so ignore them. continue; } else { $short = $refname; $type = $type_ref; } // If this isn't a type of ref we care about, skip it. if (empty($ref_types[$type])) { continue; } // If this is the local HEAD, skip it. if ($short == 'HEAD') { continue; } $creator = $fields['creator']; $matches = null; if (preg_match('/^(.*) ([0-9]+) ([0-9+-]+)$/', $creator, $matches)) { $fields['author'] = $matches[1]; $fields['epoch'] = (int)$matches[2]; } else { $fields['author'] = null; $fields['epoch'] = null; } $commit = nonempty($fields['*objectname'], $fields['objectname']); $ref = id(new DiffusionRepositoryRef()) ->setRefType($type) ->setShortName($short) ->setCommitIdentifier($commit) ->setRawFields($fields); $results[] = $ref; } return $results; } /** * List of git `--format` fields we want to grab. */ private function getFields() { return array( 'objectname', 'objecttype', 'refname', '*objectname', '*objecttype', 'subject', 'creator', ); } /** * Get a string for `--format` which enumerates all the fields we want. */ private function getFormatString() { $fields = $this->getFields(); foreach ($fields as $key => $field) { $fields[$key] = '%('.$field.')'; } return implode('%01', $fields); } /** * Parse a line back into fields. */ private function extractFields($line) { $fields = $this->getFields(); $parts = explode("\1", $line, count($fields)); $dict = array(); foreach ($fields as $index => $field) { $dict[$field] = idx($parts, $index); } return $dict; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/lowlevel/DiffusionLowLevelQuery.php
src/applications/diffusion/query/lowlevel/DiffusionLowLevelQuery.php
<?php abstract class DiffusionLowLevelQuery extends Phobject { private $repository; abstract protected function executeQuery(); public function setRepository(PhabricatorRepository $repository) { $this->repository = $repository; return $this; } public function getRepository() { return $this->repository; } public function execute() { if (!$this->getRepository()) { throw new PhutilInvalidStateException('setRepository'); } return $this->executeQuery(); } protected function filterRefsByType(array $refs, array $types) { $type_map = array_fuse($types); foreach ($refs as $name => $ref_list) { foreach ($ref_list as $key => $ref) { if (empty($type_map[$ref['type']])) { unset($refs[$name][$key]); } } if (!$refs[$name]) { unset($refs[$name]); } } 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/query/lowlevel/DiffusionLowLevelParentsQuery.php
src/applications/diffusion/query/lowlevel/DiffusionLowLevelParentsQuery.php
<?php final class DiffusionLowLevelParentsQuery extends DiffusionLowLevelQuery { private $identifier; public function withIdentifier($identifier) { $this->identifier = $identifier; return $this; } protected function executeQuery() { if (!strlen($this->identifier)) { throw new PhutilInvalidStateException('withIdentifier'); } $type = $this->getRepository()->getVersionControlSystem(); switch ($type) { case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: $result = $this->loadGitParents(); break; case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: $result = $this->loadMercurialParents(); break; case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: $result = $this->loadSubversionParents(); break; default: throw new Exception(pht('Unsupported repository type "%s"!', $type)); } return $result; } private function loadGitParents() { $repository = $this->getRepository(); list($stdout) = $repository->execxLocalCommand( 'log -n 1 %s %s --', '--format=%P', gitsprintf('%s', $this->identifier)); return preg_split('/\s+/', trim($stdout)); } private function loadMercurialParents() { $repository = $this->getRepository(); $hg_analyzer = PhutilBinaryAnalyzer::getForBinary('hg'); if ($hg_analyzer->isMercurialTemplatePnodeAvailable()) { $hg_log_template = '{p1.node} {p2.node}'; } else { $hg_log_template = '{p1node} {p2node}'; } list($stdout) = $repository->execxLocalCommand( 'log --limit 1 --template %s --rev %s', $hg_log_template, $this->identifier); $hashes = preg_split('/\s+/', trim($stdout)); foreach ($hashes as $key => $value) { // We get 40-character hashes but also get the "000000..." hash for // missing parents; ignore it. if (preg_match('/^0+\z/', $value)) { unset($hashes[$key]); } } return $hashes; } private function loadSubversionParents() { $repository = $this->getRepository(); $identifier = $this->identifier; $refs = id(new DiffusionCachedResolveRefsQuery()) ->setRepository($repository) ->withRefs(array($identifier)) ->execute(); if (!$refs) { throw new Exception( pht( 'No commit "%s" in this repository.', $identifier)); } $n = (int)$identifier; if ($n > 1) { $ids = array($n - 1); } else { $ids = array(); } return $ids; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/lowlevel/DiffusionLowLevelCommitFieldsQuery.php
src/applications/diffusion/query/lowlevel/DiffusionLowLevelCommitFieldsQuery.php
<?php final class DiffusionLowLevelCommitFieldsQuery extends DiffusionLowLevelQuery { private $ref; private $revisionMatchData = array( 'usedURI' => null, 'foundURI' => null, 'validDomain' => null, 'matchHashType' => null, 'matchHashValue' => null, ); public function withCommitRef(DiffusionCommitRef $ref) { $this->ref = $ref; return $this; } public function getRevisionMatchData() { return $this->revisionMatchData; } private function setRevisionMatchData($key, $value) { $this->revisionMatchData[$key] = $value; return $this; } protected function executeQuery() { $ref = $this->ref; $message = $ref->getMessage(); $hashes = $ref->getHashes(); $params = array( 'corpus' => $message, 'partial' => true, ); $result = id(new ConduitCall('differential.parsecommitmessage', $params)) ->setUser(PhabricatorUser::getOmnipotentUser()) ->execute(); $fields = $result['fields']; $revision_id = idx($fields, 'revisionID'); if ($revision_id) { $this->setRevisionMatchData('usedURI', true); } else { $this->setRevisionMatchData('usedURI', false); } $revision_id_info = $result['revisionIDFieldInfo']; $this->setRevisionMatchData('foundURI', $revision_id_info['value']); $this->setRevisionMatchData( 'validDomain', $revision_id_info['validDomain']); // If there is no "Differential Revision:" field in the message, try to // identify the revision by doing a hash lookup. if (!$revision_id && $hashes) { $hash_list = array(); foreach ($hashes as $hash) { $hash_list[] = array($hash->getHashType(), $hash->getHashValue()); } $revisions = id(new DifferentialRevisionQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->needHashes(true) ->withCommitHashes($hash_list) ->execute(); if ($revisions) { $revision = $this->pickBestRevision($revisions); $fields['revisionID'] = $revision->getID(); $revision_hashes = $revision->getHashes(); $revision_hashes = DiffusionCommitHash::convertArrayToObjects( $revision_hashes); $revision_hashes = mpull($revision_hashes, null, 'getHashType'); // sort the hashes in the order the mighty // @{class:ArcanstDifferentialRevisionHash} does; probably unnecessary // but should future proof things nicely. $revision_hashes = array_select_keys( $revision_hashes, ArcanistDifferentialRevisionHash::getTypes()); foreach ($hashes as $hash) { $revision_hash = idx($revision_hashes, $hash->getHashType()); if (!$revision_hash) { continue; } if ($revision_hash->getHashValue() == $hash->getHashValue()) { $this->setRevisionMatchData( 'matchHashType', $hash->getHashType()); $this->setRevisionMatchData( 'matchHashValue', $hash->getHashValue()); break; } } } } return $fields; } /** * When querying for revisions by hash, more than one revision may be found. * This function identifies the "best" revision from such a set. Typically, * there is only one revision found. Otherwise, we try to pick an accepted * revision first, followed by an open revision, and otherwise we go with a * closed or abandoned revision as a last resort. */ private function pickBestRevision(array $revisions) { assert_instances_of($revisions, 'DifferentialRevision'); // If we have more than one revision of a given status, choose the most // recently updated one. $revisions = msort($revisions, 'getDateModified'); $revisions = array_reverse($revisions); // Try to find an accepted revision first. foreach ($revisions as $revision) { if ($revision->isAccepted()) { return $revision; } } // Try to find an open revision. foreach ($revisions as $revision) { if (!$revision->isClosed()) { return $revision; } } // Settle for whatever's left. return head($revisions); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/pathid/DiffusionPathIDQuery.php
src/applications/diffusion/query/pathid/DiffusionPathIDQuery.php
<?php /** * @task pathutil Path Utilities */ final class DiffusionPathIDQuery extends Phobject { private $paths = array(); public function __construct(array $paths) { $this->paths = $paths; } public function loadPathIDs() { $repository = new PhabricatorRepository(); $path_normal_map = array(); foreach ($this->paths as $path) { $normal = self::normalizePath($path); $path_normal_map[$normal][] = $path; } $paths = queryfx_all( $repository->establishConnection('r'), 'SELECT * FROM %T WHERE pathHash IN (%Ls)', PhabricatorRepository::TABLE_PATH, array_map('md5', array_keys($path_normal_map))); $paths = ipull($paths, 'id', 'path'); $result = array(); foreach ($path_normal_map as $normal => $originals) { foreach ($originals as $original) { $result[$original] = idx($paths, $normal); } } return $result; } /** * Convert a path to the canonical, absolute representation used by Diffusion. * * @param string Some repository path. * @return string Canonicalized Diffusion path. * @task pathutil */ public static function normalizePath($path) { if ($path === null) { return '/'; } // Normalize to single slashes, e.g. "///" => "/". $path = preg_replace('@[/]{2,}@', '/', $path); return '/'.trim($path, '/'); } /** * Return the canonical parent directory for a path. Note, returns "/" when * passed "/". * * @param string Some repository path. * @return string That path's canonical parent directory. * @task pathutil */ public static function getParentPath($path) { $path = self::normalizePath($path); $path = dirname($path); if (phutil_is_windows() && $path == '\\') { $path = '/'; } return $path; } /** * Generate a list of parents for a repository path. The path itself is * included. * * @param string Some repository path. * @return list List of canonical paths between the path and the root. * @task pathutil */ public static function expandPathToRoot($path) { $path = self::normalizePath($path); $parents = array($path); $parts = explode('/', trim($path, '/')); while (count($parts) >= 1) { if (array_pop($parts)) { $parents[] = '/'.implode('/', $parts); } } return $parents; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/pathid/__tests__/DiffusionPathQueryTestCase.php
src/applications/diffusion/query/pathid/__tests__/DiffusionPathQueryTestCase.php
<?php final class DiffusionPathQueryTestCase extends PhabricatorTestCase { public function testParentEdgeCases() { $this->assertEqual( '/', DiffusionPathIDQuery::getParentPath('/'), pht('Parent of %s', '/')); $this->assertEqual( '/', DiffusionPathIDQuery::getParentPath('x.txt'), pht('Parent of %s', 'x.txt')); $this->assertEqual( '/a', DiffusionPathIDQuery::getParentPath('/a/b'), pht('Parent of %s', '/a/b')); $this->assertEqual( '/a', DiffusionPathIDQuery::getParentPath('/a///b'), pht('Parent of %s', '/a///b')); } public function testExpandEdgeCases() { $this->assertEqual( array('/'), DiffusionPathIDQuery::expandPathToRoot('/')); $this->assertEqual( array('/'), DiffusionPathIDQuery::expandPathToRoot('//')); $this->assertEqual( array('/a/b', '/a', '/'), DiffusionPathIDQuery::expandPathToRoot('/a/b')); $this->assertEqual( array('/a/b', '/a', '/'), DiffusionPathIDQuery::expandPathToRoot('/a//b')); $this->assertEqual( array('/a/b', '/a', '/'), DiffusionPathIDQuery::expandPathToRoot('a/b')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/blame/DiffusionMercurialBlameQuery.php
src/applications/diffusion/query/blame/DiffusionMercurialBlameQuery.php
<?php final class DiffusionMercurialBlameQuery extends DiffusionBlameQuery { protected function newBlameFuture(DiffusionRequest $request, $path) { $repository = $request->getRepository(); $commit = $request->getCommit(); // NOTE: Using "--template" or "--debug" to get the full commit hashes. $hg_analyzer = PhutilBinaryAnalyzer::getForBinary('hg'); if ($hg_analyzer->isMercurialAnnotateTemplatesAvailable()) { // See `hg help annotate --verbose` for more info on the template format. // Use array of arguments so the template line does not need wrapped in // quotes. $template = array( '--template', "{lines % '{node}: {line}'}", ); } else { $template = array( '--debug', '--changeset', ); } return $repository->getLocalCommandFuture( 'annotate %Ls --rev %s -- %s', $template, $commit, $path); } protected function resolveBlameFuture(ExecFuture $future) { list($err, $stdout) = $future->resolve(); if ($err) { return null; } $result = array(); $lines = phutil_split_lines($stdout); foreach ($lines as $line) { // If the `--debug` flag was used above instead of `--template` then // there's a good change additional output was included which is not // relevant to the information we want. It should be safe to call this // regardless of whether we used `--debug` or `--template` so there isn't // a need to track which argument was used. $line = DiffusionMercurialCommandEngine::filterMercurialDebugOutput( $line); // Just in case new versions of Mercurial add arbitrary output when using // the `--debug`, do a quick sanity check that this line is formatted in // a way we're expecting. if (strpos($line, ':') === false) { phlog(pht('Unexpected output from hg annotate: %s', $line)); continue; } list($commit) = explode(':', $line, 2); $result[] = $commit; } 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/diffusion/query/blame/DiffusionSvnBlameQuery.php
src/applications/diffusion/query/blame/DiffusionSvnBlameQuery.php
<?php final class DiffusionSvnBlameQuery extends DiffusionBlameQuery { protected function newBlameFuture(DiffusionRequest $request, $path) { $repository = $request->getRepository(); $commit = $request->getCommit(); return $repository->getRemoteCommandFuture( 'blame --force %s', $repository->getSubversionPathURI($path, $commit)); } protected function resolveBlameFuture(ExecFuture $future) { list($err, $stdout) = $future->resolve(); if ($err) { return null; } $result = array(); $matches = null; $lines = phutil_split_lines($stdout); foreach ($lines as $line) { if (preg_match('/^\s*(\d+)/', $line, $matches)) { $result[] = (int)$matches[1]; } else { $result[] = null; } } 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/diffusion/query/blame/DiffusionBlameQuery.php
src/applications/diffusion/query/blame/DiffusionBlameQuery.php
<?php abstract class DiffusionBlameQuery extends DiffusionQuery { private $timeout; private $paths; public function setTimeout($timeout) { $this->timeout = $timeout; return $this; } public function getTimeout() { return $this->timeout; } public function setPaths(array $paths) { $this->paths = $paths; return $this; } public function getPaths() { return $this->paths; } abstract protected function newBlameFuture(DiffusionRequest $request, $path); abstract protected function resolveBlameFuture(ExecFuture $future); final public static function newFromDiffusionRequest( DiffusionRequest $request) { return parent::newQueryObject(__CLASS__, $request); } final protected function executeQuery() { $paths = $this->getPaths(); $blame = array(); // Load cache keys: these are the commits at which each path was last // touched. $keys = $this->loadCacheKeys($paths); // Try to read blame data from cache. $cache = $this->readCacheData($keys); foreach ($paths as $key => $path) { if (!isset($cache[$path])) { continue; } $blame[$path] = $cache[$path]; unset($paths[$key]); } // If we have no paths left, we filled everything from cache and can // bail out early. if (!$paths) { return $blame; } $request = $this->getRequest(); $timeout = $this->getTimeout(); // We're still missing at least some data, so we need to run VCS commands // to pull it. $futures = array(); foreach ($paths as $path) { $future = $this->newBlameFuture($request, $path); if ($timeout) { $future->setTimeout($timeout); } $futures[$path] = $future; } $futures = id(new FutureIterator($futures)) ->limit(4); foreach ($futures as $path => $future) { $path_blame = $this->resolveBlameFuture($future); if ($path_blame !== null) { $blame[$path] = $path_blame; } } // Fill the cache with anything we generated. $this->writeCacheData( array_select_keys($keys, $paths), $blame); return $blame; } private function loadCacheKeys(array $paths) { $request = $this->getRequest(); $viewer = $request->getUser(); $repository = $request->getRepository(); $repository_id = $repository->getID(); $last_modified = parent::callConduitWithDiffusionRequest( $viewer, $request, 'diffusion.lastmodifiedquery', array( 'paths' => array_fill_keys($paths, $request->getCommit()), )); $map = array(); foreach ($paths as $path) { $identifier = idx($last_modified, $path); if ($identifier === null) { continue; } $path_hash = PhabricatorHash::digestForIndex($path); $map[$path] = "blame({$repository_id}, {$identifier}, {$path_hash}, raw)"; } return $map; } private function readCacheData(array $keys) { $cache = PhabricatorCaches::getImmutableCache(); $data = $cache->getKeys($keys); $results = array(); foreach ($keys as $path => $key) { if (!isset($data[$key])) { continue; } $results[$path] = $data[$key]; } // Decode the cache storage format. foreach ($results as $path => $cache) { list($head, $body) = explode("\n", $cache, 2); switch ($head) { case 'raw': $body = explode("\n", $body); break; default: $body = null; break; } if ($body === null) { unset($results[$path]); } else { $results[$path] = $body; } } return $results; } private function writeCacheData(array $keys, array $blame) { $writes = array(); foreach ($keys as $path => $key) { $value = idx($blame, $path); if ($value === null) { continue; } // For now, just store the entire value with a "raw" header. In the // future, we could compress this or use IDs instead. $value = "raw\n".implode("\n", $value); $writes[$key] = $value; } if (!$writes) { return; } $cache = PhabricatorCaches::getImmutableCache(); $data = $cache->setKeys($writes, phutil_units('14 days in seconds')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/blame/DiffusionGitBlameQuery.php
src/applications/diffusion/query/blame/DiffusionGitBlameQuery.php
<?php final class DiffusionGitBlameQuery extends DiffusionBlameQuery { protected function newBlameFuture(DiffusionRequest $request, $path) { $repository = $request->getRepository(); $commit = $request->getCommit(); // NOTE: The "--root" flag suppresses the addition of the "^" boundary // commit marker. Without it, root commits render with a "^" before them, // and one fewer character of the commit hash. return $repository->getLocalCommandFuture( '--no-pager blame --root -s -l %s -- %s', gitsprintf('%s', $commit), $path); } protected function resolveBlameFuture(ExecFuture $future) { list($err, $stdout) = $future->resolve(); if ($err) { return null; } $result = array(); $lines = phutil_split_lines($stdout); foreach ($lines as $line) { list($commit) = explode(' ', $line, 2); $result[] = $commit; } 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/diffusion/doorkeeper/DiffusionDoorkeeperCommitFeedStoryPublisher.php
src/applications/diffusion/doorkeeper/DiffusionDoorkeeperCommitFeedStoryPublisher.php
<?php final class DiffusionDoorkeeperCommitFeedStoryPublisher extends DoorkeeperFeedStoryPublisher { private $auditRequests; private $activePHIDs; private $passivePHIDs; private function getAuditRequests() { return $this->auditRequests; } public function canPublishStory(PhabricatorFeedStory $story, $object) { return ($story instanceof PhabricatorApplicationTransactionFeedStory) && ($object instanceof PhabricatorRepositoryCommit); } public function isStoryAboutObjectCreation($object) { // TODO: Although creation stories exist, they currently don't have a // primary object PHID set, so they'll never make it here because they // won't pass `canPublishStory()`. return false; } public function isStoryAboutObjectClosure($object) { // TODO: This isn't quite accurate, but pretty close: check if this story // is a close (which clearly is about object closure) or is an "Accept" and // the commit is fully audited (which is almost certainly a closure). // After ApplicationTransactions, we could annotate feed stories more // explicitly. $story = $this->getFeedStory(); $xaction = $story->getPrimaryTransaction(); switch ($xaction->getTransactionType()) { case PhabricatorAuditActionConstants::ACTION: switch ($xaction->getNewValue()) { case PhabricatorAuditActionConstants::CLOSE: return true; case PhabricatorAuditActionConstants::ACCEPT: if ($object->isAuditStatusAudited()) { return true; } break; } } return false; } public function willPublishStory($commit) { $requests = id(new DiffusionCommitQuery()) ->setViewer($this->getViewer()) ->withPHIDs(array($commit->getPHID())) ->needAuditRequests(true) ->executeOne() ->getAudits(); // TODO: This is messy and should be generalized, but we don't have a good // query for it yet. Since we run in the daemons, just do the easiest thing // we can for the moment. Figure out who all of the "active" (need to // audit) and "passive" (no action necessary) users are. $auditor_phids = mpull($requests, 'getAuditorPHID'); $objects = id(new PhabricatorObjectQuery()) ->setViewer($this->getViewer()) ->withPHIDs($auditor_phids) ->execute(); $active = array(); $passive = array(); foreach ($requests as $request) { $status = $request->getAuditStatus(); $object = idx($objects, $request->getAuditorPHID()); if (!$object) { continue; } $request_phids = array(); if ($object instanceof PhabricatorUser) { $request_phids = array($object->getPHID()); } else if ($object instanceof PhabricatorOwnersPackage) { $request_phids = PhabricatorOwnersOwner::loadAffiliatedUserPHIDs( array($object->getID())); } else if ($object instanceof PhabricatorProject) { $project = id(new PhabricatorProjectQuery()) ->setViewer($this->getViewer()) ->withIDs(array($object->getID())) ->needMembers(true) ->executeOne(); $request_phids = $project->getMemberPHIDs(); } else { // Dunno what this is. $request_phids = array(); } switch ($status) { case PhabricatorAuditRequestStatus::AUDIT_REQUIRED: case PhabricatorAuditRequestStatus::AUDIT_REQUESTED: case PhabricatorAuditRequestStatus::CONCERNED: $active += array_fuse($request_phids); break; default: $passive += array_fuse($request_phids); break; } } // Remove "Active" users from the "Passive" list. $passive = array_diff_key($passive, $active); $this->activePHIDs = $active; $this->passivePHIDs = $passive; $this->auditRequests = $requests; return $commit; } public function getOwnerPHID($object) { return $object->getAuthorPHID(); } public function getActiveUserPHIDs($object) { return $this->activePHIDs; } public function getPassiveUserPHIDs($object) { return $this->passivePHIDs; } public function getCCUserPHIDs($object) { return PhabricatorSubscribersQuery::loadSubscribersForPHID( $object->getPHID()); } public function getObjectTitle($object) { $prefix = $this->getTitlePrefix($object); $repository = $object->getRepository(); $name = $repository->formatCommitName($object->getCommitIdentifier()); $title = $object->getSummary(); return ltrim("{$prefix} {$name}: {$title}"); } public function getObjectURI($object) { $repository = $object->getRepository(); $name = $repository->formatCommitName($object->getCommitIdentifier()); return PhabricatorEnv::getProductionURI('/'.$name); } public function getObjectDescription($object) { $data = $object->loadCommitData(); if ($data) { return $data->getCommitMessage(); } return null; } public function isObjectClosed($object) { return $object->getAuditStatusObject()->getIsClosed(); } public function getResponsibilityTitle($object) { $prefix = $this->getTitlePrefix($object); return pht('%s Audit', $prefix); } private function getTitlePrefix(PhabricatorRepositoryCommit $commit) { return pht('[Diffusion]'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/harbormaster/DiffusionBuildableEngine.php
src/applications/diffusion/harbormaster/DiffusionBuildableEngine.php
<?php final class DiffusionBuildableEngine extends HarbormasterBuildableEngine { public function publishBuildable( HarbormasterBuildable $old, HarbormasterBuildable $new) { // Don't publish manual buildables. if ($new->getIsManualBuildable()) { return; } // Don't publish anything if the buildable status has not changed. At // least for now, Diffusion handles buildable status exactly the same // way that Harbormaster does. $old_status = $old->getBuildableStatus(); $new_status = $new->getBuildableStatus(); if ($old_status === $new_status) { return; } // Don't publish anything if the buildable is still building. if ($new->isBuilding()) { return; } $xaction = $this->newTransaction() ->setMetadataValue('harbormaster:buildablePHID', $new->getPHID()) ->setTransactionType(DiffusionCommitBuildableTransaction::TRANSACTIONTYPE) ->setNewValue($new->getBuildableStatus()); $this->applyTransactions(array($xaction)); } public function getAuthorIdentity() { return $this->getObject() ->loadIdentities($this->getViewer()) ->getAuthorIdentity(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/editor/DiffusionCommitEditEngine.php
src/applications/diffusion/editor/DiffusionCommitEditEngine.php
<?php final class DiffusionCommitEditEngine extends PhabricatorEditEngine { const ENGINECONST = 'diffusion.commit'; const ACTIONGROUP_AUDIT = 'audit'; const ACTIONGROUP_COMMIT = 'commit'; public function isEngineConfigurable() { return false; } public function getEngineName() { return pht('Commits'); } public function getSummaryHeader() { return pht('Edit Commits'); } public function getSummaryText() { return pht('Edit commits.'); } public function getEngineApplicationClass() { return 'PhabricatorDiffusionApplication'; } protected function newEditableObject() { // NOTE: We must return a valid object here so that things like Conduit // documentation generation work. You can't actually create commits via // EditEngine. This is enforced with a "No One" creation policy. $repository = new PhabricatorRepository(); $data = new PhabricatorRepositoryCommitData(); return id(new PhabricatorRepositoryCommit()) ->attachRepository($repository) ->attachCommitData($data) ->attachAudits(array()); } protected function newObjectQuery() { $viewer = $this->getViewer(); return id(new DiffusionCommitQuery()) ->needCommitData(true) ->needAuditRequests(true) ->needAuditAuthority(array($viewer)) ->needIdentities(true); } protected function getEditorURI() { return $this->getApplication()->getApplicationURI('commit/edit/'); } protected function newCommentActionGroups() { return array( id(new PhabricatorEditEngineCommentActionGroup()) ->setKey(self::ACTIONGROUP_AUDIT) ->setLabel(pht('Audit Actions')), id(new PhabricatorEditEngineCommentActionGroup()) ->setKey(self::ACTIONGROUP_COMMIT) ->setLabel(pht('Commit Actions')), ); } protected function getObjectCreateTitleText($object) { return pht('Create Commit'); } protected function getObjectCreateShortText() { return pht('Create Commit'); } protected function getObjectEditTitleText($object) { return pht('Edit Commit: %s', $object->getDisplayName()); } protected function getObjectEditShortText($object) { return $object->getDisplayName(); } protected function getObjectName() { return pht('Commit'); } protected function getObjectViewURI($object) { return $object->getURI(); } protected function getCreateNewObjectPolicy() { return PhabricatorPolicies::POLICY_NOONE; } protected function buildCustomEditFields($object) { $viewer = $this->getViewer(); $data = $object->getCommitData(); $fields = array(); $fields[] = id(new PhabricatorDatasourceEditField()) ->setKey('auditors') ->setLabel(pht('Auditors')) ->setDatasource(new DiffusionAuditorDatasource()) ->setUseEdgeTransactions(true) ->setTransactionType( DiffusionCommitAuditorsTransaction::TRANSACTIONTYPE) ->setCommentActionLabel(pht('Change Auditors')) ->setDescription(pht('Auditors for this commit.')) ->setConduitDescription(pht('Change the auditors for this commit.')) ->setConduitTypeDescription(pht('New auditors.')) ->setValue($object->getAuditorPHIDsForEdit()); $actions = DiffusionCommitActionTransaction::loadAllActions(); $actions = msortv($actions, 'getCommitActionOrderVector'); foreach ($actions as $key => $action) { $fields[] = $action->newEditField($object, $viewer); } return $fields; } protected function newAutomaticCommentTransactions($object) { $viewer = $this->getViewer(); $editor = $object->getApplicationTransactionEditor() ->setActor($viewer); $xactions = $editor->newAutomaticInlineTransactions( $object, PhabricatorAuditActionConstants::INLINE, new DiffusionDiffInlineCommentQuery()); return $xactions; } protected function newCommentPreviewContent($object, array $xactions) { $viewer = $this->getViewer(); $type_inline = PhabricatorAuditActionConstants::INLINE; $inlines = array(); foreach ($xactions as $xaction) { if ($xaction->getTransactionType() === $type_inline) { $inlines[] = $xaction->getComment(); } } $content = array(); if ($inlines) { $inline_preview = id(new PHUIDiffInlineCommentPreviewListView()) ->setViewer($viewer) ->setInlineComments($inlines); $content[] = phutil_tag( 'div', array( 'id' => 'inline-comment-preview', ), $inline_preview); } return $content; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/editor/DiffusionURIEditor.php
src/applications/diffusion/editor/DiffusionURIEditor.php
<?php final class DiffusionURIEditor extends PhabricatorApplicationTransactionEditor { private $repository; private $repositoryPHID; public function getEditorApplicationClass() { return 'PhabricatorDiffusionApplication'; } public function getEditorObjectsDescription() { return pht('Diffusion URIs'); } public function getTransactionTypes() { $types = parent::getTransactionTypes(); $types[] = PhabricatorRepositoryURITransaction::TYPE_REPOSITORY; $types[] = PhabricatorRepositoryURITransaction::TYPE_URI; $types[] = PhabricatorRepositoryURITransaction::TYPE_IO; $types[] = PhabricatorRepositoryURITransaction::TYPE_DISPLAY; $types[] = PhabricatorRepositoryURITransaction::TYPE_CREDENTIAL; $types[] = PhabricatorRepositoryURITransaction::TYPE_DISABLE; return $types; } protected function getCustomTransactionOldValue( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorRepositoryURITransaction::TYPE_URI: return $object->getURI(); case PhabricatorRepositoryURITransaction::TYPE_IO: return $object->getIOType(); case PhabricatorRepositoryURITransaction::TYPE_DISPLAY: return $object->getDisplayType(); case PhabricatorRepositoryURITransaction::TYPE_REPOSITORY: return $object->getRepositoryPHID(); case PhabricatorRepositoryURITransaction::TYPE_CREDENTIAL: return $object->getCredentialPHID(); case PhabricatorRepositoryURITransaction::TYPE_DISABLE: return (int)$object->getIsDisabled(); } return parent::getCustomTransactionOldValue($object, $xaction); } protected function getCustomTransactionNewValue( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorRepositoryURITransaction::TYPE_URI: case PhabricatorRepositoryURITransaction::TYPE_IO: case PhabricatorRepositoryURITransaction::TYPE_DISPLAY: case PhabricatorRepositoryURITransaction::TYPE_REPOSITORY: case PhabricatorRepositoryURITransaction::TYPE_CREDENTIAL: return $xaction->getNewValue(); case PhabricatorRepositoryURITransaction::TYPE_DISABLE: return (int)$xaction->getNewValue(); } return parent::getCustomTransactionNewValue($object, $xaction); } protected function applyCustomInternalTransaction( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorRepositoryURITransaction::TYPE_URI: if (!$this->getIsNewObject()) { $old_uri = $object->getEffectiveURI(); } else { $old_uri = null; // When creating a URI via the API, we may not have processed the // repository transaction yet. Attach the repository here to make // sure we have it for the calls below. if ($this->repository) { $object->attachRepository($this->repository); } } $object->setURI($xaction->getNewValue()); // If we've changed the domain or protocol of the URI, remove the // current credential. This improves behavior in several cases: // If a user switches between protocols with different credential // types, like HTTP and SSH, the old credential won't be valid anyway. // It's cleaner to remove it than leave a bad credential in place. // If a user switches hosts, the old credential is probably not // correct (and potentially confusing/misleading). Removing it forces // users to double check that they have the correct credentials. // If an attacker can't see a symmetric credential like a username and // password, they could still potentially capture it by changing the // host for a URI that uses it to `evil.com`, a server they control, // then observing the requests. Removing the credential prevents this // kind of escalation. // Since port and path changes are less likely to fall among these // cases, they don't trigger a credential wipe. $new_uri = $object->getEffectiveURI(); if ($old_uri) { $new_proto = ($old_uri->getProtocol() != $new_uri->getProtocol()); $new_domain = ($old_uri->getDomain() != $new_uri->getDomain()); if ($new_proto || $new_domain) { $object->setCredentialPHID(null); } } break; case PhabricatorRepositoryURITransaction::TYPE_IO: $object->setIOType($xaction->getNewValue()); break; case PhabricatorRepositoryURITransaction::TYPE_DISPLAY: $object->setDisplayType($xaction->getNewValue()); break; case PhabricatorRepositoryURITransaction::TYPE_REPOSITORY: $object->setRepositoryPHID($xaction->getNewValue()); $object->attachRepository($this->repository); break; case PhabricatorRepositoryURITransaction::TYPE_CREDENTIAL: $object->setCredentialPHID($xaction->getNewValue()); break; case PhabricatorRepositoryURITransaction::TYPE_DISABLE: $object->setIsDisabled($xaction->getNewValue()); break; } } protected function applyCustomExternalTransaction( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorRepositoryURITransaction::TYPE_URI: case PhabricatorRepositoryURITransaction::TYPE_IO: case PhabricatorRepositoryURITransaction::TYPE_DISPLAY: case PhabricatorRepositoryURITransaction::TYPE_REPOSITORY: case PhabricatorRepositoryURITransaction::TYPE_CREDENTIAL: case PhabricatorRepositoryURITransaction::TYPE_DISABLE: return; } return parent::applyCustomExternalTransaction($object, $xaction); } protected function validateTransaction( PhabricatorLiskDAO $object, $type, array $xactions) { $errors = parent::validateTransaction($object, $type, $xactions); switch ($type) { case PhabricatorRepositoryURITransaction::TYPE_REPOSITORY: // Save this, since we need it to validate TYPE_IO transactions. $this->repositoryPHID = $object->getRepositoryPHID(); $missing = $this->validateIsEmptyTextField( $object->getRepositoryPHID(), $xactions); if ($missing) { // NOTE: This isn't being marked as a missing field error because // it's a fundamental, required property of the URI. $errors[] = new PhabricatorApplicationTransactionValidationError( $type, pht('Required'), pht( 'When creating a repository URI, you must specify which '. 'repository the URI will belong to.'), nonempty(last($xactions), null)); break; } $viewer = $this->getActor(); foreach ($xactions as $xaction) { $repository_phid = $xaction->getNewValue(); // If this isn't changing anything, let it through as-is. if ($repository_phid == $object->getRepositoryPHID()) { continue; } if (!$this->getIsNewObject()) { $errors[] = new PhabricatorApplicationTransactionValidationError( $type, pht('Invalid'), pht( 'The repository a URI is associated with is immutable, and '. 'can not be changed after the URI is created.'), $xaction); continue; } $repository = id(new PhabricatorRepositoryQuery()) ->setViewer($viewer) ->withPHIDs(array($repository_phid)) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$repository) { $errors[] = new PhabricatorApplicationTransactionValidationError( $type, pht('Invalid'), pht( 'To create a URI for a repository ("%s"), it must exist and '. 'you must have permission to edit it.', $repository_phid), $xaction); continue; } $this->repository = $repository; $this->repositoryPHID = $repository_phid; } break; case PhabricatorRepositoryURITransaction::TYPE_CREDENTIAL: $viewer = $this->getActor(); foreach ($xactions as $xaction) { $credential_phid = $xaction->getNewValue(); if ($credential_phid == $object->getCredentialPHID()) { continue; } // Anyone who can edit a URI can remove the credential. if ($credential_phid === null) { continue; } $credential = id(new PassphraseCredentialQuery()) ->setViewer($viewer) ->withPHIDs(array($credential_phid)) ->executeOne(); if (!$credential) { $errors[] = new PhabricatorApplicationTransactionValidationError( $type, pht('Invalid'), pht( 'You can only associate a credential ("%s") with a repository '. 'URI if it exists and you have permission to see it.', $credential_phid), $xaction); continue; } } break; case PhabricatorRepositoryURITransaction::TYPE_URI: $missing = $this->validateIsEmptyTextField( $object->getURI(), $xactions); if ($missing) { $error = new PhabricatorApplicationTransactionValidationError( $type, pht('Required'), pht('A repository URI must have a nonempty URI.'), nonempty(last($xactions), null)); $error->setIsMissingFieldError(true); $errors[] = $error; break; } foreach ($xactions as $xaction) { $new_uri = $xaction->getNewValue(); if ($new_uri == $object->getURI()) { continue; } try { PhabricatorRepository::assertValidRemoteURI($new_uri); } catch (Exception $ex) { $errors[] = new PhabricatorApplicationTransactionValidationError( $type, pht('Invalid'), $ex->getMessage(), $xaction); continue; } } break; case PhabricatorRepositoryURITransaction::TYPE_IO: $available = $object->getAvailableIOTypeOptions(); foreach ($xactions as $xaction) { $new = $xaction->getNewValue(); if (empty($available[$new])) { $errors[] = new PhabricatorApplicationTransactionValidationError( $type, pht('Invalid'), pht( 'Value "%s" is not a valid IO setting for this URI. '. 'Available types for this URI are: %s.', $new, implode(', ', array_keys($available))), $xaction); continue; } // If we are setting this URI to use "Observe", we must have no // other "Observe" URIs and must also have no "Read/Write" URIs. // If we are setting this URI to "Read/Write", we must have no // other "Observe" URIs. It's OK to have other "Read/Write" URIs. $no_observers = false; $no_readwrite = false; switch ($new) { case PhabricatorRepositoryURI::IO_OBSERVE: $no_readwrite = true; $no_observers = true; break; case PhabricatorRepositoryURI::IO_READWRITE: $no_observers = true; break; } if ($no_observers || $no_readwrite) { $repository = id(new PhabricatorRepositoryQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs(array($this->repositoryPHID)) ->needURIs(true) ->executeOne(); $uris = $repository->getURIs(); $observe_conflict = null; $readwrite_conflict = null; foreach ($uris as $uri) { // If this is the URI being edited, it can not conflict with // itself. if ($uri->getID() == $object->getID()) { continue; } $io_type = $uri->getEffectiveIOType(); if ($io_type == PhabricatorRepositoryURI::IO_READWRITE) { if ($no_readwrite) { $readwrite_conflict = $uri; break; } } if ($io_type == PhabricatorRepositoryURI::IO_OBSERVE) { if ($no_observers) { $observe_conflict = $uri; break; } } } if ($observe_conflict) { if ($new == PhabricatorRepositoryURI::IO_OBSERVE) { $message = pht( 'You can not set this URI to use Observe IO because '. 'another URI for this repository is already configured '. 'in Observe IO mode. A repository can not observe two '. 'different remotes simultaneously. Turn off IO for the '. 'other URI first.'); } else { $message = pht( 'You can not set this URI to use Read/Write IO because '. 'another URI for this repository is already configured '. 'in Observe IO mode. An observed repository can not be '. 'made writable. Turn off IO for the other URI first.'); } $errors[] = new PhabricatorApplicationTransactionValidationError( $type, pht('Invalid'), $message, $xaction); continue; } if ($readwrite_conflict) { $message = pht( 'You can not set this URI to use Observe IO because '. 'another URI for this repository is already configured '. 'in Read/Write IO mode. A repository can not simultaneously '. 'be writable and observe a remote. Turn off IO for the '. 'other URI first.'); $errors[] = new PhabricatorApplicationTransactionValidationError( $type, pht('Invalid'), $message, $xaction); continue; } } } break; case PhabricatorRepositoryURITransaction::TYPE_DISPLAY: $available = $object->getAvailableDisplayTypeOptions(); foreach ($xactions as $xaction) { $new = $xaction->getNewValue(); if (empty($available[$new])) { $errors[] = new PhabricatorApplicationTransactionValidationError( $type, pht('Invalid'), pht( 'Value "%s" is not a valid display setting for this URI. '. 'Available types for this URI are: %s.', $new, implode(', ', array_keys($available)))); } } break; case PhabricatorRepositoryURITransaction::TYPE_DISABLE: $old = $object->getIsDisabled(); foreach ($xactions as $xaction) { $new = $xaction->getNewValue(); if ($old == $new) { continue; } if (!$object->isBuiltin()) { continue; } $errors[] = new PhabricatorApplicationTransactionValidationError( $type, pht('Invalid'), pht('You can not manually disable builtin URIs.')); } break; } return $errors; } protected function applyFinalEffects( PhabricatorLiskDAO $object, array $xactions) { // Synchronize the repository state based on the presence of an "Observe" // URI. $repository = $object->getRepository(); $uris = id(new PhabricatorRepositoryURIQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withRepositories(array($repository)) ->execute(); // Reattach the current URIs to the repository: we're going to rebuild // the index explicitly below, and want to include any changes made to // this URI in the index update. $repository->attachURIs($uris); $observe_uri = null; foreach ($uris as $uri) { if ($uri->getIoType() != PhabricatorRepositoryURI::IO_OBSERVE) { continue; } $observe_uri = $uri; break; } $was_hosted = $repository->isHosted(); if ($observe_uri) { $repository ->setHosted(false) ->setDetail('remote-uri', (string)$observe_uri->getEffectiveURI()) ->setCredentialPHID($observe_uri->getCredentialPHID()); } else { $repository ->setHosted(true) ->setDetail('remote-uri', null) ->setCredentialPHID(null); } $repository->save(); // Explicitly update the URI index. $repository->updateURIIndex(); $is_hosted = $repository->isHosted(); // If we've swapped the repository from hosted to observed or vice versa, // reset all the cluster version clocks. if ($was_hosted != $is_hosted) { $cluster_engine = id(new DiffusionRepositoryClusterEngine()) ->setViewer($this->getActor()) ->setRepository($repository) ->synchronizeWorkingCopyAfterHostingChange(); } $repository->writeStatusMessage( PhabricatorRepositoryStatusMessage::TYPE_NEEDS_UPDATE, null); return $xactions; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/editor/DiffusionRepositoryEditEngine.php
src/applications/diffusion/editor/DiffusionRepositoryEditEngine.php
<?php final class DiffusionRepositoryEditEngine extends PhabricatorEditEngine { const ENGINECONST = 'diffusion.repository'; private $versionControlSystem; public function setVersionControlSystem($version_control_system) { $this->versionControlSystem = $version_control_system; return $this; } public function getVersionControlSystem() { return $this->versionControlSystem; } public function isEngineConfigurable() { return false; } public function isDefaultQuickCreateEngine() { return true; } public function getQuickCreateOrderVector() { return id(new PhutilSortVector())->addInt(300); } public function getEngineName() { return pht('Repositories'); } public function getSummaryHeader() { return pht('Edit Repositories'); } public function getSummaryText() { return pht('Creates and edits repositories.'); } public function getEngineApplicationClass() { return 'PhabricatorDiffusionApplication'; } protected function newEditableObject() { $viewer = $this->getViewer(); $repository = PhabricatorRepository::initializeNewRepository($viewer); $repository->setDetail('newly-initialized', true); $vcs = $this->getVersionControlSystem(); if ($vcs) { $repository->setVersionControlSystem($vcs); } // Pick a random open service to allocate this repository on, if any exist. // If there are no services, we aren't in cluster mode and will allocate // locally. If there are services but none permit allocations, we fail. // Eventually we can make this more flexible, but this rule is a reasonable // starting point as we begin to deploy cluster services. $services = id(new AlmanacServiceQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withServiceTypes( array( AlmanacClusterRepositoryServiceType::SERVICETYPE, )) ->needProperties(true) ->execute(); if ($services) { // Filter out services which do not permit new allocations. foreach ($services as $key => $possible_service) { if ($possible_service->getAlmanacPropertyValue('closed')) { unset($services[$key]); } } if (!$services) { throw new Exception( pht( 'This install is configured in cluster mode, but all available '. 'repository cluster services are closed to new allocations. '. 'At least one service must be open to allow new allocations to '. 'take place.')); } shuffle($services); $service = head($services); $repository->setAlmanacServicePHID($service->getPHID()); } return $repository; } protected function newObjectQuery() { return new PhabricatorRepositoryQuery(); } protected function getObjectCreateTitleText($object) { return pht('Create Repository'); } protected function getObjectCreateButtonText($object) { return pht('Create Repository'); } protected function getObjectEditTitleText($object) { return pht('Edit Repository: %s', $object->getName()); } protected function getObjectEditShortText($object) { return $object->getDisplayName(); } protected function getObjectCreateShortText() { return pht('Create Repository'); } protected function getObjectName() { return pht('Repository'); } protected function getObjectViewURI($object) { return $object->getPathURI('manage/'); } protected function getCreateNewObjectPolicy() { return $this->getApplication()->getPolicy( DiffusionCreateRepositoriesCapability::CAPABILITY); } protected function newPages($object) { $panels = DiffusionRepositoryManagementPanel::getAllPanels(); $pages = array(); $uris = array(); foreach ($panels as $panel_key => $panel) { $panel->setRepository($object); $uris[$panel_key] = $panel->getPanelURI(); $page = $panel->newEditEnginePage(); if (!$page) { continue; } $pages[] = $page; } $basics_key = DiffusionRepositoryBasicsManagementPanel::PANELKEY; $basics_uri = $uris[$basics_key]; $more_pages = array( id(new PhabricatorEditPage()) ->setKey('encoding') ->setLabel(pht('Text Encoding')) ->setViewURI($basics_uri) ->setFieldKeys( array( 'encoding', )), id(new PhabricatorEditPage()) ->setKey('extensions') ->setLabel(pht('Extensions')) ->setIsDefault(true), ); foreach ($more_pages as $page) { $pages[] = $page; } return $pages; } protected function willConfigureFields($object, array $fields) { // Change the default field order so related fields are adjacent. $after = array( 'policy.edit' => array('policy.push'), ); $result = array(); foreach ($fields as $key => $value) { $result[$key] = $value; if (!isset($after[$key])) { continue; } foreach ($after[$key] as $next_key) { if (!isset($fields[$next_key])) { continue; } unset($result[$next_key]); $result[$next_key] = $fields[$next_key]; unset($fields[$next_key]); } } return $result; } protected function buildCustomEditFields($object) { $viewer = $this->getViewer(); $policies = id(new PhabricatorPolicyQuery()) ->setViewer($viewer) ->setObject($object) ->execute(); $fetch_value = $object->getFetchRules(); $track_value = $object->getTrackOnlyRules(); $permanent_value = $object->getPermanentRefRules(); $automation_instructions = pht( "Configure **Repository Automation** to allow this server to ". "write to this repository.". "\n\n". "IMPORTANT: This feature is new, experimental, and not supported. ". "Use it at your own risk."); $staging_instructions = pht( "To make it easier to run integration tests and builds on code ". "under review, you can configure a **Staging Area**. When `arc` ". "creates a diff, it will push a copy of the changes to the ". "configured staging area with a corresponding tag.". "\n\n". "IMPORTANT: This feature is new, experimental, and not supported. ". "Use it at your own risk."); $subpath_instructions = pht( 'If you want to import only part of a repository, like `trunk/`, '. 'you can set a path in **Import Only**. The import process will ignore '. 'commits which do not affect this path.'); $filesize_warning = null; if ($object->isGit()) { $git_binary = PhutilBinaryAnalyzer::getForBinary('git'); $git_version = $git_binary->getBinaryVersion(); $filesize_version = '1.8.4'; if (version_compare($git_version, $filesize_version, '<')) { $filesize_warning = pht( '(WARNING) {icon exclamation-triangle} The version of "git" ("%s") '. 'installed on this server does not support '. '"--batch-check=<format>", a feature required to enforce filesize '. 'limits. Upgrade to "git" %s or newer to use this feature.', $git_version, $filesize_version); } } $track_instructions = pht( 'WARNING: The "Track Only" feature is deprecated. Use "Fetch Refs" '. 'and "Permanent Refs" instead. This feature will be removed in a '. 'future version of this software.'); return array( id(new PhabricatorSelectEditField()) ->setKey('vcs') ->setLabel(pht('Version Control System')) ->setTransactionType( PhabricatorRepositoryVCSTransaction::TRANSACTIONTYPE) ->setIsFormField(false) ->setIsCopyable(true) ->setOptions(PhabricatorRepositoryType::getAllRepositoryTypes()) ->setDescription(pht('Underlying repository version control system.')) ->setConduitDescription( pht( 'Choose which version control system to use when creating a '. 'repository.')) ->setConduitTypeDescription(pht('Version control system selection.')) ->setValue($object->getVersionControlSystem()), id(new PhabricatorTextEditField()) ->setKey('name') ->setLabel(pht('Name')) ->setIsRequired(true) ->setTransactionType( PhabricatorRepositoryNameTransaction::TRANSACTIONTYPE) ->setDescription(pht('The repository name.')) ->setConduitDescription(pht('Rename the repository.')) ->setConduitTypeDescription(pht('New repository name.')) ->setValue($object->getName()), id(new PhabricatorTextEditField()) ->setKey('callsign') ->setLabel(pht('Callsign')) ->setTransactionType( PhabricatorRepositoryCallsignTransaction::TRANSACTIONTYPE) ->setDescription(pht('The repository callsign.')) ->setConduitDescription(pht('Change the repository callsign.')) ->setConduitTypeDescription(pht('New repository callsign.')) ->setValue($object->getCallsign()), id(new PhabricatorTextEditField()) ->setKey('shortName') ->setLabel(pht('Short Name')) ->setTransactionType( PhabricatorRepositorySlugTransaction::TRANSACTIONTYPE) ->setDescription(pht('Short, unique repository name.')) ->setConduitDescription(pht('Change the repository short name.')) ->setConduitTypeDescription(pht('New short name for the repository.')) ->setValue($object->getRepositorySlug()), id(new PhabricatorRemarkupEditField()) ->setKey('description') ->setLabel(pht('Description')) ->setTransactionType( PhabricatorRepositoryDescriptionTransaction::TRANSACTIONTYPE) ->setDescription(pht('Repository description.')) ->setConduitDescription(pht('Change the repository description.')) ->setConduitTypeDescription(pht('New repository description.')) ->setValue($object->getDetail('description')), id(new PhabricatorTextEditField()) ->setKey('encoding') ->setLabel(pht('Text Encoding')) ->setIsCopyable(true) ->setTransactionType( PhabricatorRepositoryEncodingTransaction::TRANSACTIONTYPE) ->setDescription(pht('Default text encoding.')) ->setConduitDescription(pht('Change the default text encoding.')) ->setConduitTypeDescription(pht('New text encoding.')) ->setValue($object->getDetail('encoding')), id(new PhabricatorBoolEditField()) ->setKey('allowDangerousChanges') ->setLabel(pht('Allow Dangerous Changes')) ->setIsCopyable(true) ->setIsFormField(false) ->setOptions( pht('Prevent Dangerous Changes'), pht('Allow Dangerous Changes')) ->setTransactionType( PhabricatorRepositoryDangerousTransaction::TRANSACTIONTYPE) ->setDescription(pht('Permit dangerous changes to be made.')) ->setConduitDescription(pht('Allow or prevent dangerous changes.')) ->setConduitTypeDescription(pht('New protection setting.')) ->setValue($object->shouldAllowDangerousChanges()), id(new PhabricatorBoolEditField()) ->setKey('allowEnormousChanges') ->setLabel(pht('Allow Enormous Changes')) ->setIsCopyable(true) ->setIsFormField(false) ->setOptions( pht('Prevent Enormous Changes'), pht('Allow Enormous Changes')) ->setTransactionType( PhabricatorRepositoryEnormousTransaction::TRANSACTIONTYPE) ->setDescription(pht('Permit enormous changes to be made.')) ->setConduitDescription(pht('Allow or prevent enormous changes.')) ->setConduitTypeDescription(pht('New protection setting.')) ->setValue($object->shouldAllowEnormousChanges()), id(new PhabricatorSelectEditField()) ->setKey('status') ->setLabel(pht('Status')) ->setTransactionType( PhabricatorRepositoryActivateTransaction::TRANSACTIONTYPE) ->setIsFormField(false) ->setOptions(PhabricatorRepository::getStatusNameMap()) ->setDescription(pht('Active or inactive status.')) ->setConduitDescription(pht('Active or deactivate the repository.')) ->setConduitTypeDescription(pht('New repository status.')) ->setValue($object->getStatus()), id(new PhabricatorTextEditField()) ->setKey('defaultBranch') ->setLabel(pht('Default Branch')) ->setTransactionType( PhabricatorRepositoryDefaultBranchTransaction::TRANSACTIONTYPE) ->setIsCopyable(true) ->setDescription(pht('Default branch name.')) ->setConduitDescription(pht('Set the default branch name.')) ->setConduitTypeDescription(pht('New default branch name.')) ->setValue($object->getDetail('default-branch')), id(new PhabricatorTextAreaEditField()) ->setIsStringList(true) ->setKey('fetchRefs') ->setLabel(pht('Fetch Refs')) ->setTransactionType( PhabricatorRepositoryFetchRefsTransaction::TRANSACTIONTYPE) ->setIsCopyable(true) ->setDescription(pht('Fetch only these refs.')) ->setConduitDescription(pht('Set the fetched refs.')) ->setConduitTypeDescription(pht('New fetched refs.')) ->setValue($fetch_value), id(new PhabricatorTextAreaEditField()) ->setIsStringList(true) ->setKey('permanentRefs') ->setLabel(pht('Permanent Refs')) ->setTransactionType( PhabricatorRepositoryPermanentRefsTransaction::TRANSACTIONTYPE) ->setIsCopyable(true) ->setDescription(pht('Only these refs are considered permanent.')) ->setConduitDescription(pht('Set the permanent refs.')) ->setConduitTypeDescription(pht('New permanent ref rules.')) ->setValue($permanent_value), id(new PhabricatorTextAreaEditField()) ->setIsStringList(true) ->setKey('trackOnly') ->setLabel(pht('Track Only')) ->setTransactionType( PhabricatorRepositoryTrackOnlyTransaction::TRANSACTIONTYPE) ->setIsCopyable(true) ->setControlInstructions($track_instructions) ->setDescription(pht('Track only these branches.')) ->setConduitDescription(pht('Set the tracked branches.')) ->setConduitTypeDescription(pht('New tracked branches.')) ->setValue($track_value), id(new PhabricatorTextEditField()) ->setKey('importOnly') ->setLabel(pht('Import Only')) ->setTransactionType( PhabricatorRepositorySVNSubpathTransaction::TRANSACTIONTYPE) ->setIsCopyable(true) ->setDescription(pht('Subpath to selectively import.')) ->setConduitDescription(pht('Set the subpath to import.')) ->setConduitTypeDescription(pht('New subpath to import.')) ->setValue($object->getDetail('svn-subpath')) ->setControlInstructions($subpath_instructions), id(new PhabricatorTextEditField()) ->setKey('stagingAreaURI') ->setLabel(pht('Staging Area URI')) ->setTransactionType( PhabricatorRepositoryStagingURITransaction::TRANSACTIONTYPE) ->setIsCopyable(true) ->setDescription(pht('Staging area URI.')) ->setConduitDescription(pht('Set the staging area URI.')) ->setConduitTypeDescription(pht('New staging area URI.')) ->setValue($object->getStagingURI()) ->setControlInstructions($staging_instructions), id(new PhabricatorDatasourceEditField()) ->setKey('automationBlueprintPHIDs') ->setLabel(pht('Use Blueprints')) ->setTransactionType( PhabricatorRepositoryBlueprintsTransaction::TRANSACTIONTYPE) ->setIsCopyable(true) ->setDatasource(new DrydockBlueprintDatasource()) ->setDescription(pht('Automation blueprints.')) ->setConduitDescription(pht('Change automation blueprints.')) ->setConduitTypeDescription(pht('New blueprint PHIDs.')) ->setValue($object->getAutomationBlueprintPHIDs()) ->setControlInstructions($automation_instructions), id(new PhabricatorStringListEditField()) ->setKey('symbolLanguages') ->setLabel(pht('Languages')) ->setTransactionType( PhabricatorRepositorySymbolLanguagesTransaction::TRANSACTIONTYPE) ->setIsCopyable(true) ->setDescription( pht('Languages which define symbols in this repository.')) ->setConduitDescription( pht('Change symbol languages for this repository.')) ->setConduitTypeDescription( pht('New symbol languages.')) ->setValue($object->getSymbolLanguages()), id(new PhabricatorDatasourceEditField()) ->setKey('symbolRepositoryPHIDs') ->setLabel(pht('Uses Symbols From')) ->setTransactionType( PhabricatorRepositorySymbolSourcesTransaction::TRANSACTIONTYPE) ->setIsCopyable(true) ->setDatasource(new DiffusionRepositoryDatasource()) ->setDescription(pht('Repositories to link symbols from.')) ->setConduitDescription(pht('Change symbol source repositories.')) ->setConduitTypeDescription(pht('New symbol repositories.')) ->setValue($object->getSymbolSources()), id(new PhabricatorBoolEditField()) ->setKey('publish') ->setLabel(pht('Publish/Notify')) ->setTransactionType( PhabricatorRepositoryNotifyTransaction::TRANSACTIONTYPE) ->setIsCopyable(true) ->setOptions( pht('Disable Notifications, Feed, and Herald'), pht('Enable Notifications, Feed, and Herald')) ->setDescription(pht('Configure how changes are published.')) ->setConduitDescription(pht('Change publishing options.')) ->setConduitTypeDescription(pht('New notification setting.')) ->setValue(!$object->isPublishingDisabled()), id(new PhabricatorPolicyEditField()) ->setKey('policy.push') ->setLabel(pht('Push Policy')) ->setAliases(array('push')) ->setIsCopyable(true) ->setCapability(DiffusionPushCapability::CAPABILITY) ->setPolicies($policies) ->setTransactionType( PhabricatorRepositoryPushPolicyTransaction::TRANSACTIONTYPE) ->setDescription( pht('Controls who can push changes to the repository.')) ->setConduitDescription( pht('Change the push policy of the repository.')) ->setConduitTypeDescription(pht('New policy PHID or constant.')) ->setValue($object->getPolicy(DiffusionPushCapability::CAPABILITY)), id(new PhabricatorTextEditField()) ->setKey('filesizeLimit') ->setLabel(pht('Filesize Limit')) ->setTransactionType( PhabricatorRepositoryFilesizeLimitTransaction::TRANSACTIONTYPE) ->setDescription(pht('Maximum permitted file size.')) ->setConduitDescription(pht('Change the filesize limit.')) ->setConduitTypeDescription(pht('New repository filesize limit.')) ->setControlInstructions($filesize_warning) ->setValue($object->getFilesizeLimit()), id(new PhabricatorTextEditField()) ->setKey('copyTimeLimit') ->setLabel(pht('Clone/Fetch Timeout')) ->setTransactionType( PhabricatorRepositoryCopyTimeLimitTransaction::TRANSACTIONTYPE) ->setDescription( pht('Maximum permitted duration of internal clone/fetch.')) ->setConduitDescription(pht('Change the copy time limit.')) ->setConduitTypeDescription(pht('New repository copy time limit.')) ->setValue($object->getCopyTimeLimit()), id(new PhabricatorTextEditField()) ->setKey('touchLimit') ->setLabel(pht('Touched Paths Limit')) ->setTransactionType( PhabricatorRepositoryTouchLimitTransaction::TRANSACTIONTYPE) ->setDescription(pht('Maximum permitted paths touched per commit.')) ->setConduitDescription(pht('Change the touch limit.')) ->setConduitTypeDescription(pht('New repository touch limit.')) ->setValue($object->getTouchLimit()), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/editor/DiffusionRepositoryIdentityEditor.php
src/applications/diffusion/editor/DiffusionRepositoryIdentityEditor.php
<?php final class DiffusionRepositoryIdentityEditor extends PhabricatorApplicationTransactionEditor { public function getEditorObjectsDescription() { return pht('Repository Identity'); } public function getCreateObjectTitle($author, $object) { return pht('%s created this identity.', $author); } public function getCreateObjectTitleForFeed($author, $object) { return pht('%s created %s.', $author, $object); } protected function supportsSearch() { return true; } public function getEditorApplicationClass() { return 'PhabricatorDiffusionApplication'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/editor/DiffusionURIEditEngine.php
src/applications/diffusion/editor/DiffusionURIEditEngine.php
<?php final class DiffusionURIEditEngine extends PhabricatorEditEngine { const ENGINECONST = 'diffusion.uri'; private $repository; public function setRepository(PhabricatorRepository $repository) { $this->repository = $repository; return $this; } public function getRepository() { return $this->repository; } public function isEngineConfigurable() { return false; } public function getEngineName() { return pht('Repository URIs'); } public function getSummaryHeader() { return pht('Edit Repository URI'); } public function getSummaryText() { return pht('Creates and edits repository URIs.'); } public function getEngineApplicationClass() { return 'PhabricatorDiffusionApplication'; } protected function newEditableObject() { $uri = PhabricatorRepositoryURI::initializeNewURI(); $repository = $this->getRepository(); if ($repository) { $uri->setRepositoryPHID($repository->getPHID()); $uri->attachRepository($repository); } return $uri; } protected function newObjectQuery() { return new PhabricatorRepositoryURIQuery(); } protected function getObjectCreateTitleText($object) { return pht('Create Repository URI'); } protected function getObjectCreateButtonText($object) { return pht('Create Repository URI'); } protected function getObjectEditTitleText($object) { return pht('Edit Repository URI %d', $object->getID()); } protected function getObjectEditShortText($object) { return pht('URI %d', $object->getID()); } protected function getObjectCreateShortText() { return pht('Create Repository URI'); } protected function getObjectName() { return pht('Repository URI'); } protected function getObjectViewURI($object) { return $object->getViewURI(); } protected function buildCustomEditFields($object) { $viewer = $this->getViewer(); $uri_instructions = null; if ($object->isBuiltin()) { $is_builtin = true; $uri_value = (string)$object->getDisplayURI(); switch ($object->getBuiltinProtocol()) { case PhabricatorRepositoryURI::BUILTIN_PROTOCOL_SSH: $uri_instructions = pht( " - Configure [[ %s | %s ]] to change the SSH username.\n". " - Configure [[ %s | %s ]] to change the SSH host.\n". " - Configure [[ %s | %s ]] to change the SSH port.", '/config/edit/diffusion.ssh-user/', 'diffusion.ssh-user', '/config/edit/diffusion.ssh-host/', 'diffusion.ssh-host', '/config/edit/diffusion.ssh-port/', 'diffusion.ssh-port'); break; } } else { $is_builtin = false; $uri_value = $object->getURI(); if ($object->getRepositoryPHID()) { $repository = $object->getRepository(); if ($repository->isGit()) { $uri_instructions = pht( "Provide the URI of a Git repository. It should usually look ". "like one of these examples:\n". "\n". "| Example Git URIs\n". "| -----------------------\n". "| `git@github.com:example/example.git`\n". "| `ssh://user@host.com/git/example.git`\n". "| `https://example.com/repository.git`"); } else if ($repository->isHg()) { $uri_instructions = pht( "Provide the URI of a Mercurial repository. It should usually ". "look like one of these examples:\n". "\n". "| Example Mercurial URIs\n". "|-----------------------\n". "| `ssh://hg@bitbucket.org/example/repository`\n". "| `https://bitbucket.org/example/repository`"); } else if ($repository->isSVN()) { $uri_instructions = pht( "Provide the **Repository Root** of a Subversion repository. ". "You can identify this by running `svn info` in a working ". "copy. It should usually look like one of these examples:\n". "\n". "| Example Subversion URIs\n". "|-----------------------\n". "| `http://svn.example.org/svnroot/`\n". "| `svn+ssh://svn.example.com/svnroot/`\n". "| `svn://svn.example.net/svnroot/`\n\n". "You **MUST** specify the root of the repository, not a ". "subdirectory."); } } } return array( id(new PhabricatorHandlesEditField()) ->setKey('repository') ->setAliases(array('repositoryPHID')) ->setLabel(pht('Repository')) ->setIsRequired(true) ->setIsFormField(false) ->setTransactionType( PhabricatorRepositoryURITransaction::TYPE_REPOSITORY) ->setDescription(pht('The repository this URI is associated with.')) ->setConduitDescription( pht( 'Create a URI in a given repository. This transaction type '. 'must be present when creating a new URI and must not be '. 'present when editing an existing URI.')) ->setConduitTypeDescription( pht('Repository PHID to create a new URI for.')) ->setSingleValue($object->getRepositoryPHID()), id(new PhabricatorTextEditField()) ->setKey('uri') ->setLabel(pht('URI')) ->setTransactionType(PhabricatorRepositoryURITransaction::TYPE_URI) ->setDescription(pht('The repository URI.')) ->setConduitDescription(pht('Change the repository URI.')) ->setConduitTypeDescription(pht('New repository URI.')) ->setIsRequired(!$is_builtin) ->setIsLocked($is_builtin) ->setValue($uri_value) ->setControlInstructions($uri_instructions), id(new PhabricatorSelectEditField()) ->setKey('io') ->setLabel(pht('I/O Type')) ->setTransactionType(PhabricatorRepositoryURITransaction::TYPE_IO) ->setDescription(pht('URI I/O behavior.')) ->setConduitDescription(pht('Adjust I/O behavior.')) ->setConduitTypeDescription(pht('New I/O behavior.')) ->setValue($object->getIOType()) ->setOptions($object->getAvailableIOTypeOptions()), id(new PhabricatorSelectEditField()) ->setKey('display') ->setLabel(pht('Display Type')) ->setTransactionType(PhabricatorRepositoryURITransaction::TYPE_DISPLAY) ->setDescription(pht('URI display behavior.')) ->setConduitDescription(pht('Change display behavior.')) ->setConduitTypeDescription(pht('New display behavior.')) ->setValue($object->getDisplayType()) ->setOptions($object->getAvailableDisplayTypeOptions()), id(new PhabricatorHandlesEditField()) ->setKey('credential') ->setAliases(array('credentialPHID')) ->setLabel(pht('Credential')) ->setIsFormField(false) ->setTransactionType( PhabricatorRepositoryURITransaction::TYPE_CREDENTIAL) ->setDescription( pht('The credential to use when interacting with this URI.')) ->setConduitDescription(pht('Change the credential for this URI.')) ->setConduitTypeDescription(pht('New credential PHID, or null.')) ->setSingleValue($object->getCredentialPHID()), id(new PhabricatorBoolEditField()) ->setKey('disable') ->setLabel(pht('Disabled')) ->setIsFormField(false) ->setTransactionType(PhabricatorRepositoryURITransaction::TYPE_DISABLE) ->setDescription(pht('Active status of the URI.')) ->setConduitDescription(pht('Disable or activate the URI.')) ->setConduitTypeDescription(pht('True to disable the URI.')) ->setOptions(pht('Enable'), pht('Disable')) ->setValue($object->getIsDisabled()), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/xaction/DiffusionCommitTransactionType.php
src/applications/diffusion/xaction/DiffusionCommitTransactionType.php
<?php abstract class DiffusionCommitTransactionType extends PhabricatorModularTransactionType { protected function updateAudits( PhabricatorRepositoryCommit $commit, array $new) { $audits = $commit->getAudits(); $audits = mpull($audits, null, 'getAuditorPHID'); foreach ($new as $phid => $status) { $audit = idx($audits, $phid); if (!$audit) { $audit = id(new PhabricatorRepositoryAuditRequest()) ->setAuditorPHID($phid) ->setCommitPHID($commit->getPHID()); $audits[$phid] = $audit; } else { if ($audit->getAuditStatus() === $status) { continue; } } $audit ->setAuditStatus($status) ->save(); } $commit->attachAudits($audits); return $audits; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/xaction/DiffusionCommitStateTransaction.php
src/applications/diffusion/xaction/DiffusionCommitStateTransaction.php
<?php final class DiffusionCommitStateTransaction extends DiffusionCommitTransactionType { const TRANSACTIONTYPE = 'diffusion.commit.state'; public function generateNewValue($object, $value) { // NOTE: This transaction can not be generated or applied normally. It is // written to the transaction log as a side effect of a state change. throw new PhutilMethodNotImplementedException(); } private function getAuditStatusObject() { $new = $this->getNewValue(); return DiffusionCommitAuditStatus::newForStatus($new); } public function getIcon() { return $this->getAuditStatusObject()->getIcon(); } public function getColor() { return $this->getAuditStatusObject()->getColor(); } public function getTitle() { $status = $this->getAuditStatusObject(); switch ($status->getKey()) { case DiffusionCommitAuditStatus::NONE: return pht('This commit no longer requires audit.'); case DiffusionCommitAuditStatus::NEEDS_AUDIT: return pht('This commit now requires audit.'); case DiffusionCommitAuditStatus::CONCERN_RAISED: return pht('This commit now has outstanding concerns.'); case DiffusionCommitAuditStatus::NEEDS_VERIFICATION: return pht('This commit now requires verification by auditors.'); case DiffusionCommitAuditStatus::AUDITED: return pht('All concerns with this commit have now been addressed.'); } return null; } public function getTitleForFeed() { $status = $this->getAuditStatusObject(); switch ($status->getKey()) { case DiffusionCommitAuditStatus::NONE: return pht( '%s no longer requires audit.', $this->renderObject()); case DiffusionCommitAuditStatus::NEEDS_AUDIT: return pht( '%s now requires audit.', $this->renderObject()); case DiffusionCommitAuditStatus::CONCERN_RAISED: return pht( '%s now has outstanding concerns.', $this->renderObject()); case DiffusionCommitAuditStatus::NEEDS_VERIFICATION: return pht( '%s now requires verification by auditors.', $this->renderObject()); case DiffusionCommitAuditStatus::AUDITED: return pht( 'All concerns with %s have now been addressed.', $this->renderObject()); } 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/xaction/DiffusionCommitAuditorsTransaction.php
src/applications/diffusion/xaction/DiffusionCommitAuditorsTransaction.php
<?php final class DiffusionCommitAuditorsTransaction extends DiffusionCommitTransactionType { const TRANSACTIONTYPE = 'diffusion.commit.auditors'; public function generateOldValue($object) { $auditors = $object->getAudits(); return mpull($auditors, 'getAuditStatus', 'getAuditorPHID'); } public function generateNewValue($object, $value) { $actor = $this->getActor(); $auditors = $this->generateOldValue($object); $old_auditors = $auditors; $request_status = PhabricatorAuditRequestStatus::AUDIT_REQUESTED; $rem = idx($value, '-', array()); foreach ($rem as $phid) { unset($auditors[$phid]); } $add = idx($value, '+', array()); $add_map = array(); foreach ($add as $phid) { $add_map[$phid] = $request_status; } $set = idx($value, '=', null); if ($set !== null) { foreach ($set as $phid) { $add_map[$phid] = $request_status; } $auditors = array(); } foreach ($add_map as $phid => $new_status) { $old_status = idx($old_auditors, $phid); if ($old_status) { $auditors[$phid] = $old_status; continue; } $auditors[$phid] = $new_status; } return $auditors; } public function getTransactionHasEffect($object, $old, $new) { ksort($old); ksort($new); return ($old !== $new); } public function mergeTransactions( $object, PhabricatorApplicationTransaction $u, PhabricatorApplicationTransaction $v) { $u_new = $u->getNewValue(); $v_new = $v->getNewValue(); $result = $v_new; foreach (array('-', '+') as $key) { $u_value = idx($u_new, $key, array()); $v_value = idx($v_new, $key, array()); $merged = $u_value + $v_value; if ($merged) { $result[$key] = $merged; } } $u->setNewValue($result); return $u; } public function applyExternalEffects($object, $value) { $src_phid = $object->getPHID(); $old = $this->generateOldValue($object); $new = $value; $auditors = $object->getAudits(); $auditors = mpull($auditors, null, 'getAuditorPHID'); $rem = array_diff_key($old, $new); foreach ($rem as $phid => $status) { $auditor = idx($auditors, $phid); if ($auditor) { $auditor->delete(); } } $this->updateAudits($object, $new); } public function getTitle() { $old = $this->getOldValue(); $new = $this->getNewValue(); $rem = array_diff_key($old, $new); $add = array_diff_key($new, $old); $rem_phids = array_keys($rem); $add_phids = array_keys($add); $total_count = count($rem) + count($add); if ($rem && $add) { return pht( '%s edited %s auditor(s), removed %s: %s; added %s: %s.', $this->renderAuthor(), new PhutilNumber($total_count), phutil_count($rem_phids), $this->renderHandleList($rem_phids), phutil_count($add_phids), $this->renderHandleList($add_phids)); } else if ($add) { return pht( '%s added %s auditor(s): %s.', $this->renderAuthor(), phutil_count($add_phids), $this->renderHandleList($add_phids)); } else { return pht( '%s removed %s auditor(s): %s.', $this->renderAuthor(), phutil_count($rem_phids), $this->renderHandleList($rem_phids)); } } public function getTitleForFeed() { $old = $this->getOldValue(); $new = $this->getNewValue(); $rem = array_diff_key($old, $new); $add = array_diff_key($new, $old); $rem_phids = array_keys($rem); $add_phids = array_keys($add); $total_count = count($rem) + count($add); if ($rem && $add) { return pht( '%s edited %s auditor(s) for %s, removed %s: %s; added %s: %s.', $this->renderAuthor(), new PhutilNumber($total_count), $this->renderObject(), phutil_count($rem_phids), $this->renderHandleList($rem_phids), phutil_count($add_phids), $this->renderHandleList($add_phids)); } else if ($add) { return pht( '%s added %s auditor(s) for %s: %s.', $this->renderAuthor(), phutil_count($add_phids), $this->renderObject(), $this->renderHandleList($add_phids)); } else { return pht( '%s removed %s auditor(s) for %s: %s.', $this->renderAuthor(), phutil_count($rem_phids), $this->renderObject(), $this->renderHandleList($rem_phids)); } } public function validateTransactions($object, array $xactions) { $actor = $this->getActor(); $errors = array(); if (!$xactions) { return $errors; } $author_phid = $object->getEffectiveAuthorPHID(); $can_author_close_key = 'audit.can-author-close-audit'; $can_author_close = PhabricatorEnv::getEnvConfig($can_author_close_key); $old = $this->generateOldValue($object); foreach ($xactions as $xaction) { $new = $this->generateNewValue($object, $xaction->getNewValue()); $add = array_diff_key($new, $old); if (!$add) { continue; } $objects = id(new PhabricatorObjectQuery()) ->setViewer($actor) ->withPHIDs(array_keys($add)) ->execute(); $objects = mpull($objects, null, 'getPHID'); foreach ($add as $phid => $status) { if (!isset($objects[$phid])) { $errors[] = $this->newInvalidError( pht( 'Auditor "%s" is not a valid object.', $phid), $xaction); continue; } switch (phid_get_type($phid)) { case PhabricatorPeopleUserPHIDType::TYPECONST: case PhabricatorOwnersPackagePHIDType::TYPECONST: case PhabricatorProjectProjectPHIDType::TYPECONST: break; default: $errors[] = $this->newInvalidError( pht( 'Auditor "%s" must be a user, a package, or a project.', $phid), $xaction); continue 2; } $is_self = ($phid === $author_phid); if ($is_self && !$can_author_close) { $errors[] = $this->newInvalidError( pht('The author of a commit can not be an auditor.'), $xaction); continue; } } } return $errors; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/xaction/DiffusionCommitAuditTransaction.php
src/applications/diffusion/xaction/DiffusionCommitAuditTransaction.php
<?php abstract class DiffusionCommitAuditTransaction extends DiffusionCommitActionTransaction { protected function getCommitActionGroupKey() { return DiffusionCommitEditEngine::ACTIONGROUP_AUDIT; } public function generateOldValue($object) { return false; } protected function isViewerAnyAuditor( PhabricatorRepositoryCommit $commit, PhabricatorUser $viewer) { return ($this->getViewerAuditStatus($commit, $viewer) !== null); } protected function isViewerAnyActiveAuditor( PhabricatorRepositoryCommit $commit, PhabricatorUser $viewer) { // This omits inactive states; currently just "Resigned". $active = array( PhabricatorAuditRequestStatus::AUDIT_REQUIRED, PhabricatorAuditRequestStatus::CONCERNED, PhabricatorAuditRequestStatus::ACCEPTED, PhabricatorAuditRequestStatus::AUDIT_REQUESTED, ); $active = array_fuse($active); $viewer_status = $this->getViewerAuditStatus($commit, $viewer); return isset($active[$viewer_status]); } protected function isViewerFullyAccepted( PhabricatorRepositoryCommit $commit, PhabricatorUser $viewer) { return $this->isViewerAuditStatusFullyAmong( $commit, $viewer, array( PhabricatorAuditRequestStatus::ACCEPTED, )); } protected function isViewerFullyRejected( PhabricatorRepositoryCommit $commit, PhabricatorUser $viewer) { return $this->isViewerAuditStatusFullyAmong( $commit, $viewer, array( PhabricatorAuditRequestStatus::CONCERNED, )); } protected function getViewerAuditStatus( PhabricatorRepositoryCommit $commit, PhabricatorUser $viewer) { if (!$viewer->getPHID()) { return null; } foreach ($commit->getAudits() as $audit) { if ($audit->getAuditorPHID() != $viewer->getPHID()) { continue; } return $audit->getAuditStatus(); } return null; } protected function isViewerAuditStatusFullyAmong( PhabricatorRepositoryCommit $commit, PhabricatorUser $viewer, array $status_list) { $status = $this->getViewerAuditStatus($commit, $viewer); if ($status === null) { return false; } $status_map = array_fuse($status_list); foreach ($commit->getAudits() as $audit) { if (!$commit->hasAuditAuthority($viewer, $audit)) { continue; } $status = $audit->getAuditStatus(); if (isset($status_map[$status])) { continue; } return false; } return true; } protected function applyAuditorEffect( PhabricatorRepositoryCommit $commit, PhabricatorUser $viewer, $value, $status) { $actor = $this->getActor(); $acting_phid = $this->getActingAsPHID(); $audits = $commit->getAudits(); $audits = mpull($audits, null, 'getAuditorPHID'); $map = array(); $with_authority = ($status != PhabricatorAuditRequestStatus::RESIGNED); if ($with_authority) { foreach ($audits as $audit) { if ($commit->hasAuditAuthority($actor, $audit, $acting_phid)) { $map[$audit->getAuditorPHID()] = $status; } } } // In all cases, you affect yourself. $map[$viewer->getPHID()] = $status; $this->updateAudits($commit, $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/xaction/DiffusionCommitConcernTransaction.php
src/applications/diffusion/xaction/DiffusionCommitConcernTransaction.php
<?php final class DiffusionCommitConcernTransaction extends DiffusionCommitAuditTransaction { const TRANSACTIONTYPE = 'diffusion.commit.concern'; const ACTIONKEY = 'concern'; protected function getCommitActionLabel() { return pht('Raise Concern'); } protected function getCommitActionDescription() { return pht('This commit will be returned to the author for consideration.'); } public function getIcon() { return 'fa-times-circle-o'; } public function getColor() { return 'red'; } protected function getCommitActionOrder() { return 600; } public function getActionName() { return pht('Raised Concern'); } public function applyInternalEffects($object, $value) { // NOTE: We force the commit directly into "Concern Raised" so that we // override a possible "Needs Verification" state. $object->setAuditStatus(DiffusionCommitAuditStatus::CONCERN_RAISED); } public function applyExternalEffects($object, $value) { $status = PhabricatorAuditRequestStatus::CONCERNED; $actor = $this->getActor(); $this->applyAuditorEffect($object, $actor, $value, $status); } protected function validateAction($object, PhabricatorUser $viewer) { if ($this->isViewerCommitAuthor($object, $viewer)) { throw new Exception( pht( 'You can not raise a concern with this commit because you are '. 'the commit author. You can only raise concerns with commits '. 'you did not author.')); } // Even if you've already raised a concern, you can raise again as long // as the author requested you verify. if ($this->isViewerFullyRejected($object, $viewer)) { if (!$object->isAuditStatusNeedsVerification()) { throw new Exception( pht( 'You can not raise a concern with this commit because you have '. 'already raised a concern with it.')); } } } public function getTitle() { return pht( '%s raised a concern with this commit.', $this->renderAuthor()); } public function getTitleForFeed() { return pht( '%s raised a concern with %s.', $this->renderAuthor(), $this->renderObject()); } public function getTransactionTypeForConduit($xaction) { return 'concern'; } public function getFieldValuesForConduit($object, $data) { 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/xaction/DiffusionCommitBuildableTransaction.php
src/applications/diffusion/xaction/DiffusionCommitBuildableTransaction.php
<?php final class DiffusionCommitBuildableTransaction extends DiffusionCommitTransactionType { // NOTE: This uses an older constant for compatibility. We should perhaps // migrate these at some point. const TRANSACTIONTYPE = 'harbormaster:buildable'; public function generateNewValue($object, $value) { return $value; } public function generateOldValue($object) { return null; } public function getIcon() { return $this->newBuildableStatus()->getIcon(); } public function getColor() { return $this->newBuildableStatus()->getColor(); } public function getActionName() { return $this->newBuildableStatus()->getActionName(); } public function shouldHideForFeed() { return !$this->newBuildableStatus()->isFailed(); } public function shouldHideForMail() { return !$this->newBuildableStatus()->isFailed(); } public function getTitle() { $new = $this->getNewValue(); $buildable_phid = $this->getBuildablePHID(); switch ($new) { case HarbormasterBuildableStatus::STATUS_PASSED: return pht( '%s completed building %s.', $this->renderAuthor(), $this->renderHandle($buildable_phid)); case HarbormasterBuildableStatus::STATUS_FAILED: return pht( '%s failed to build %s!', $this->renderAuthor(), $this->renderHandle($buildable_phid)); } return null; } public function getTitleForFeed() { $new = $this->getNewValue(); $buildable_phid = $this->getBuildablePHID(); switch ($new) { case HarbormasterBuildableStatus::STATUS_PASSED: return pht( '%s completed building %s for %s.', $this->renderAuthor(), $this->renderHandle($buildable_phid), $this->renderObject()); case HarbormasterBuildableStatus::STATUS_FAILED: return pht( '%s failed to build %s for %s!', $this->renderAuthor(), $this->renderHandle($buildable_phid), $this->renderObject()); } return null; } private function newBuildableStatus() { $new = $this->getNewValue(); return HarbormasterBuildableStatus::newBuildableStatusObject($new); } private function getBuildablePHID() { return $this->getMetadataValue('harbormaster:buildablePHID'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/xaction/DiffusionCommitActionTransaction.php
src/applications/diffusion/xaction/DiffusionCommitActionTransaction.php
<?php abstract class DiffusionCommitActionTransaction extends DiffusionCommitTransactionType { final public function getCommitActionKey() { return $this->getPhobjectClassConstant('ACTIONKEY', 32); } public function isActionAvailable($object, PhabricatorUser $viewer) { try { $this->validateAction($object, $viewer); return true; } catch (Exception $ex) { return false; } } abstract protected function validateAction($object, PhabricatorUser $viewer); abstract protected function getCommitActionLabel(); public function getCommandKeyword() { return null; } public function getCommandAliases() { return array(); } public function getCommandSummary() { return null; } protected function getCommitActionOrder() { return 1000; } public function getCommitActionOrderVector() { return id(new PhutilSortVector()) ->addInt($this->getCommitActionOrder()); } protected function getCommitActionGroupKey() { return DiffusionCommitEditEngine::ACTIONGROUP_COMMIT; } protected function getCommitActionDescription() { return null; } public static function loadAllActions() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getCommitActionKey') ->execute(); } protected function isViewerCommitAuthor( PhabricatorRepositoryCommit $commit, PhabricatorUser $viewer) { if (!$viewer->getPHID()) { return false; } return ($viewer->getPHID() === $commit->getEffectiveAuthorPHID()); } public function newEditField( PhabricatorRepositoryCommit $commit, PhabricatorUser $viewer) { // Actions in the "audit" group, like "Accept Commit", do not require // that the actor be able to edit the commit. $group_audit = DiffusionCommitEditEngine::ACTIONGROUP_AUDIT; $is_audit = ($this->getCommitActionGroupKey() == $group_audit); $field = id(new PhabricatorApplyEditField()) ->setKey($this->getCommitActionKey()) ->setTransactionType($this->getTransactionTypeConstant()) ->setCanApplyWithoutEditCapability($is_audit) ->setValue(true); if ($this->isActionAvailable($commit, $viewer)) { $label = $this->getCommitActionLabel(); if ($label !== null) { $field->setCommentActionLabel($label); $description = $this->getCommitActionDescription(); $field->setActionDescription($description); $group_key = $this->getCommitActionGroupKey(); $field->setCommentActionGroupKey($group_key); $field->setActionConflictKey('commit.action'); } } return $field; } public function validateTransactions($object, array $xactions) { $errors = array(); $actor = $this->getActor(); $action_exception = null; try { $this->validateAction($object, $actor); } catch (Exception $ex) { $action_exception = $ex; } foreach ($xactions as $xaction) { if ($action_exception) { $errors[] = $this->newInvalidError( $action_exception->getMessage(), $xaction); } } return $errors; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/xaction/DiffusionCommitResignTransaction.php
src/applications/diffusion/xaction/DiffusionCommitResignTransaction.php
<?php final class DiffusionCommitResignTransaction extends DiffusionCommitAuditTransaction { const TRANSACTIONTYPE = 'diffusion.commit.resign'; const ACTIONKEY = 'resign'; protected function getCommitActionLabel() { return pht('Resign as Auditor'); } protected function getCommitActionDescription() { return pht('You will resign as an auditor for this commit.'); } public function getIcon() { return 'fa-flag'; } public function getColor() { return 'orange'; } protected function getCommitActionOrder() { return 700; } public function getActionName() { return pht('Resigned'); } public function generateOldValue($object) { $actor = $this->getActor(); return !$this->isViewerAnyActiveAuditor($object, $actor); } public function applyExternalEffects($object, $value) { $status = PhabricatorAuditRequestStatus::RESIGNED; $actor = $this->getActor(); $this->applyAuditorEffect($object, $actor, $value, $status); } protected function validateAction($object, PhabricatorUser $viewer) { if (!$this->isViewerAnyActiveAuditor($object, $viewer)) { throw new Exception( pht( 'You can not resign from this commit because you are not an '. 'active auditor.')); } } public function getTitle() { return pht( '%s resigned from this commit.', $this->renderAuthor()); } public function getTitleForFeed() { return pht( '%s resigned from %s.', $this->renderAuthor(), $this->renderObject()); } public function getTransactionTypeForConduit($xaction) { return 'resign'; } public function getFieldValuesForConduit($object, $data) { 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/xaction/DiffusionCommitAcceptTransaction.php
src/applications/diffusion/xaction/DiffusionCommitAcceptTransaction.php
<?php final class DiffusionCommitAcceptTransaction extends DiffusionCommitAuditTransaction { const TRANSACTIONTYPE = 'diffusion.commit.accept'; const ACTIONKEY = 'accept'; protected function getCommitActionLabel() { return pht('Accept Commit'); } protected function getCommitActionDescription() { return pht('This commit will be approved.'); } public function getIcon() { return 'fa-check-circle-o'; } public function getColor() { return 'green'; } protected function getCommitActionOrder() { return 500; } public function getActionName() { return pht('Accepted'); } public function applyExternalEffects($object, $value) { $status = PhabricatorAuditRequestStatus::ACCEPTED; $actor = $this->getActor(); $this->applyAuditorEffect($object, $actor, $value, $status); } protected function validateAction($object, PhabricatorUser $viewer) { $config_key = 'audit.can-author-close-audit'; if (!PhabricatorEnv::getEnvConfig($config_key)) { if ($this->isViewerCommitAuthor($object, $viewer)) { throw new Exception( pht( 'You can not accept this commit because you are the commit '. 'author. You can only accept commits you did not author. You can '. 'change this behavior by adjusting the "%s" setting in Config.', $config_key)); } } if ($this->isViewerFullyAccepted($object, $viewer)) { throw new Exception( pht( 'You can not accept this commit because you have already '. 'accepted it.')); } } public function getTitle() { return pht( '%s accepted this commit.', $this->renderAuthor()); } public function getTitleForFeed() { return pht( '%s accepted %s.', $this->renderAuthor(), $this->renderObject()); } public function getTransactionTypeForConduit($xaction) { return 'accept'; } public function getFieldValuesForConduit($object, $data) { 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/xaction/DiffusionCommitVerifyTransaction.php
src/applications/diffusion/xaction/DiffusionCommitVerifyTransaction.php
<?php final class DiffusionCommitVerifyTransaction extends DiffusionCommitAuditTransaction { const TRANSACTIONTYPE = 'diffusion.commit.verify'; const ACTIONKEY = 'verify'; protected function getCommitActionLabel() { return pht('Request Verification'); } protected function getCommitActionDescription() { return pht( 'Auditors will be asked to verify that concerns have been addressed.'); } protected function getCommitActionGroupKey() { return DiffusionCommitEditEngine::ACTIONGROUP_COMMIT; } public function getIcon() { return 'fa-refresh'; } public function getColor() { return 'indigo'; } protected function getCommitActionOrder() { return 600; } public function getActionName() { return pht('Requested Verification'); } public function applyInternalEffects($object, $value) { $object->setAuditStatus(DiffusionCommitAuditStatus::NEEDS_VERIFICATION); } protected function validateAction($object, PhabricatorUser $viewer) { if (!$this->isViewerCommitAuthor($object, $viewer)) { throw new Exception( pht( 'You can not request verification of this commit because you '. 'are not the author.')); } if (!$object->isAuditStatusConcernRaised()) { throw new Exception( pht( 'You can not request verification of this commit because no '. 'auditors have raised concerns with it.')); } } public function getTitle() { return pht( '%s requested verification of this commit.', $this->renderAuthor()); } public function getTitleForFeed() { return pht( '%s requested verification of %s.', $this->renderAuthor(), $this->renderObject()); } public function getTransactionTypeForConduit($xaction) { return 'request-verification'; } public function getFieldValuesForConduit($object, $data) { 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/exception/DiffusionDaemonLockException.php
src/applications/diffusion/exception/DiffusionDaemonLockException.php
<?php final class DiffusionDaemonLockException extends Exception {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/exception/DiffusionSetupException.php
src/applications/diffusion/exception/DiffusionSetupException.php
<?php final class DiffusionSetupException extends Exception {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/exception/DiffusionMercurialFlagInjectionException.php
src/applications/diffusion/exception/DiffusionMercurialFlagInjectionException.php
<?php final class DiffusionMercurialFlagInjectionException extends Exception {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/exception/DiffusionCommitHookRejectException.php
src/applications/diffusion/exception/DiffusionCommitHookRejectException.php
<?php final class DiffusionCommitHookRejectException extends Exception {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/exception/DiffusionRefNotFoundException.php
src/applications/diffusion/exception/DiffusionRefNotFoundException.php
<?php final class DiffusionRefNotFoundException extends Exception { private $ref; public function setRef($ref) { $this->ref = $ref; return $this; } public function getRef() { return $this->ref; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/relationships/DiffusionCommitHasTaskRelationship.php
src/applications/diffusion/relationships/DiffusionCommitHasTaskRelationship.php
<?php final class DiffusionCommitHasTaskRelationship extends DiffusionCommitRelationship { const RELATIONSHIPKEY = 'commit.has-task'; public function getEdgeConstant() { return DiffusionCommitHasTaskEdgeType::EDGECONST; } protected function getActionName() { return pht('Edit Tasks'); } protected function getActionIcon() { return 'fa-anchor'; } public function canRelateObjects($src, $dst) { return ($dst instanceof ManiphestTask); } public function getDialogTitleText() { return pht('Edit Related Tasks'); } public function getDialogHeaderText() { return pht('Current Tasks'); } public function getDialogButtonText() { return pht('Save Related Tasks'); } protected function newRelationshipSource() { return new ManiphestTaskRelationshipSource(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/relationships/DiffusionCommitHasRevisionRelationship.php
src/applications/diffusion/relationships/DiffusionCommitHasRevisionRelationship.php
<?php final class DiffusionCommitHasRevisionRelationship extends DiffusionCommitRelationship { const RELATIONSHIPKEY = 'commit.has-revision'; public function getEdgeConstant() { return DiffusionCommitHasRevisionEdgeType::EDGECONST; } protected function getActionName() { return pht('Edit Revisions'); } protected function getActionIcon() { return 'fa-cog'; } public function canRelateObjects($src, $dst) { return ($dst instanceof DifferentialRevision); } public function getDialogTitleText() { return pht('Edit Related Revisions'); } public function getDialogHeaderText() { return pht('Current Revisions'); } public function getDialogButtonText() { return pht('Save Related Revisions'); } protected function newRelationshipSource() { return new DifferentialRevisionRelationshipSource(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/relationships/DiffusionCommitRelationship.php
src/applications/diffusion/relationships/DiffusionCommitRelationship.php
<?php abstract class DiffusionCommitRelationship extends PhabricatorObjectRelationship { public function isEnabledForObject($object) { $viewer = $this->getViewer(); $has_app = PhabricatorApplication::isClassInstalledForViewer( 'PhabricatorDiffusionApplication', $viewer); if (!$has_app) { return false; } return ($object instanceof PhabricatorRepositoryCommit); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/searchfield/DiffusionIdentityAssigneeSearchField.php
src/applications/diffusion/searchfield/DiffusionIdentityAssigneeSearchField.php
<?php final class DiffusionIdentityAssigneeSearchField extends PhabricatorSearchTokenizerField { protected function getDefaultValue() { return array(); } protected function getValueFromRequest(AphrontRequest $request, $key) { return $this->getUsersFromRequest($request, $key); } protected function newDatasource() { return new DiffusionIdentityAssigneeDatasource(); } protected function newConduitParameterType() { return new ConduitUserListParameterType(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/panel/DiffusionSetPasswordSettingsPanel.php
src/applications/diffusion/panel/DiffusionSetPasswordSettingsPanel.php
<?php final class DiffusionSetPasswordSettingsPanel extends PhabricatorSettingsPanel { public function isManagementPanel() { if ($this->getUser()->getIsMailingList()) { return false; } return true; } public function getPanelKey() { return 'vcspassword'; } public function getPanelName() { return pht('VCS Password'); } public function getPanelMenuIcon() { return 'fa-code'; } public function getPanelGroupKey() { return PhabricatorSettingsAuthenticationPanelGroup::PANELGROUPKEY; } public function isEnabled() { return PhabricatorEnv::getEnvConfig('diffusion.allow-http-auth'); } public function processRequest(AphrontRequest $request) { $viewer = $request->getUser(); $user = $this->getUser(); $token = id(new PhabricatorAuthSessionEngine())->requireHighSecuritySession( $viewer, $request, '/settings/'); $vcs_type = PhabricatorAuthPassword::PASSWORD_TYPE_VCS; $vcspasswords = id(new PhabricatorAuthPasswordQuery()) ->setViewer($viewer) ->withObjectPHIDs(array($user->getPHID())) ->withPasswordTypes(array($vcs_type)) ->withIsRevoked(false) ->execute(); if ($vcspasswords) { $vcspassword = head($vcspasswords); } else { $vcspassword = PhabricatorAuthPassword::initializeNewPassword( $user, $vcs_type); } $panel_uri = $this->getPanelURI('?saved=true'); $errors = array(); $e_password = true; $e_confirm = true; $content_source = PhabricatorContentSource::newFromRequest($request); // NOTE: This test is against $viewer (not $user), so that the error // message below makes sense in the case that the two are different, // and because an admin reusing their own password is bad, while // system agents generally do not have passwords anyway. $engine = id(new PhabricatorAuthPasswordEngine()) ->setViewer($viewer) ->setContentSource($content_source) ->setObject($viewer) ->setPasswordType($vcs_type); if ($request->isFormPost()) { if ($request->getBool('remove')) { if ($vcspassword->getID()) { $vcspassword->delete(); return id(new AphrontRedirectResponse())->setURI($panel_uri); } } $new_password = $request->getStr('password'); $confirm = $request->getStr('confirm'); $envelope = new PhutilOpaqueEnvelope($new_password); $confirm_envelope = new PhutilOpaqueEnvelope($confirm); try { $engine->checkNewPassword($envelope, $confirm_envelope); $e_password = null; $e_confirm = null; } catch (PhabricatorAuthPasswordException $ex) { $errors[] = $ex->getMessage(); $e_password = $ex->getPasswordError(); $e_confirm = $ex->getConfirmError(); } if (!$errors) { $vcspassword ->setPassword($envelope, $user) ->save(); return id(new AphrontRedirectResponse())->setURI($panel_uri); } } $title = pht('Set VCS Password'); $form = id(new AphrontFormView()) ->setUser($viewer) ->appendRemarkupInstructions( pht( 'To access repositories hosted on this server over HTTP, you must '. 'set a version control password. This password should be unique.'. "\n\n". "This password applies to all repositories available over ". "HTTP.")); if ($vcspassword->getID()) { $form ->appendChild( id(new AphrontFormPasswordControl()) ->setDisableAutocomplete(true) ->setLabel(pht('Current Password')) ->setDisabled(true) ->setValue('********************')); } else { $form ->appendChild( id(new AphrontFormMarkupControl()) ->setLabel(pht('Current Password')) ->setValue(phutil_tag('em', array(), pht('No Password Set')))); } $form ->appendChild( id(new AphrontFormPasswordControl()) ->setDisableAutocomplete(true) ->setName('password') ->setLabel(pht('New VCS Password')) ->setError($e_password)) ->appendChild( id(new AphrontFormPasswordControl()) ->setDisableAutocomplete(true) ->setName('confirm') ->setLabel(pht('Confirm VCS Password')) ->setError($e_confirm)) ->appendChild( id(new AphrontFormSubmitControl()) ->setValue(pht('Change Password'))); if (!$vcspassword->getID()) { $is_serious = PhabricatorEnv::getEnvConfig( 'phabricator.serious-business'); $suggest = Filesystem::readRandomBytes(128); $suggest = preg_replace('([^A-Za-z0-9/!().,;{}^&*%~])', '', $suggest); $suggest = substr($suggest, 0, 20); if ($is_serious) { $form->appendRemarkupInstructions( pht( 'Having trouble coming up with a good password? Try this randomly '. 'generated one, made by a computer:'. "\n\n". "`%s`", $suggest)); } else { $form->appendRemarkupInstructions( pht( 'Having trouble coming up with a good password? Try this '. 'artisanal password, hand made in small batches by our expert '. 'craftspeople: '. "\n\n". "`%s`", $suggest)); } } $hash_envelope = new PhutilOpaqueEnvelope($vcspassword->getPasswordHash()); $form->appendChild( id(new AphrontFormStaticControl()) ->setLabel(pht('Current Algorithm')) ->setValue( PhabricatorPasswordHasher::getCurrentAlgorithmName($hash_envelope))); $form->appendChild( id(new AphrontFormStaticControl()) ->setLabel(pht('Best Available Algorithm')) ->setValue(PhabricatorPasswordHasher::getBestAlgorithmName())); if (strlen($hash_envelope->openEnvelope())) { try { $can_upgrade = PhabricatorPasswordHasher::canUpgradeHash( $hash_envelope); } catch (PhabricatorPasswordHasherUnavailableException $ex) { $can_upgrade = false; $errors[] = pht( 'Your VCS password is currently hashed using an algorithm which is '. 'no longer available on this install.'); $errors[] = pht( 'Because the algorithm implementation is missing, your password '. 'can not be used.'); $errors[] = pht( 'You can set a new password to replace the old password.'); } if ($can_upgrade) { $errors[] = pht( 'The strength of your stored VCS password hash can be upgraded. '. 'To upgrade, either: use the password to authenticate with a '. 'repository; or change your password.'); } } $object_box = id(new PHUIObjectBoxView()) ->setHeaderText($title) ->setBackground(PHUIObjectBoxView::WHITE_CONFIG) ->setForm($form) ->setFormErrors($errors); $remove_form = id(new AphrontFormView()) ->setUser($viewer); if ($vcspassword->getID()) { $remove_form ->addHiddenInput('remove', true) ->appendRemarkupInstructions( pht( 'You can remove your VCS password, which will prevent your '. 'account from accessing repositories.')) ->appendChild( id(new AphrontFormSubmitControl()) ->setValue(pht('Remove Password'))); } else { $remove_form->appendRemarkupInstructions( pht( 'You do not currently have a VCS password set. If you set one, you '. 'can remove it here later.')); } $remove_box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Remove VCS Password')) ->setBackground(PHUIObjectBoxView::WHITE_CONFIG) ->setForm($remove_form); $saved = null; if ($request->getBool('saved')) { $saved = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->setTitle(pht('Password Updated')) ->appendChild(pht('Your VCS password has been updated.')); } return array( $saved, $object_box, $remove_box, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/ssh/DiffusionSubversionSSHWorkflow.php
src/applications/diffusion/ssh/DiffusionSubversionSSHWorkflow.php
<?php abstract class DiffusionSubversionSSHWorkflow extends DiffusionSSHWorkflow { protected function writeError($message) { // Subversion assumes we'll add our own newlines. return parent::writeError($message."\n"); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/ssh/DiffusionGitSSHWorkflow.php
src/applications/diffusion/ssh/DiffusionGitSSHWorkflow.php
<?php abstract class DiffusionGitSSHWorkflow extends DiffusionSSHWorkflow implements DiffusionRepositoryClusterEngineLogInterface { private $engineLogProperties = array(); private $protocolLog; private $wireProtocol; private $ioBytesRead = 0; private $ioBytesWritten = 0; private $requestAttempts = 0; private $requestFailures = 0; protected function writeError($message) { // Git assumes we'll add our own newlines. return parent::writeError($message."\n"); } public function writeClusterEngineLogMessage($message) { parent::writeError($message); $this->getErrorChannel()->update(); } public function writeClusterEngineLogProperty($key, $value) { $this->engineLogProperties[$key] = $value; } protected function getClusterEngineLogProperty($key, $default = null) { return idx($this->engineLogProperties, $key, $default); } protected function identifyRepository() { $args = $this->getArgs(); $path = head($args->getArg('dir')); return $this->loadRepositoryWithPath( $path, PhabricatorRepositoryType::REPOSITORY_TYPE_GIT); } protected function waitForGitClient() { $io_channel = $this->getIOChannel(); // If we don't wait for the client to close the connection, `git` will // consider it an early abort and fail. Sit around until Git is comfortable // that it really received all the data. while ($io_channel->isOpenForReading()) { $io_channel->update(); $this->getErrorChannel()->flush(); PhutilChannel::waitForAny(array($io_channel)); } } protected function raiseWrongVCSException( PhabricatorRepository $repository) { throw new Exception( pht( 'This repository ("%s") is not a Git repository. Use "%s" to '. 'interact with this repository.', $repository->getDisplayName(), $repository->getVersionControlSystem())); } protected function newPassthruCommand() { return parent::newPassthruCommand() ->setWillWriteCallback(array($this, 'willWriteMessageCallback')) ->setWillReadCallback(array($this, 'willReadMessageCallback')); } protected function newProtocolLog($is_proxy) { if ($is_proxy) { return null; } // While developing, do this to write a full protocol log to disk: // // return new PhabricatorProtocolLog('/tmp/git-protocol.log'); return null; } final protected function getProtocolLog() { return $this->protocolLog; } final protected function setProtocolLog(PhabricatorProtocolLog $log) { $this->protocolLog = $log; } final protected function getWireProtocol() { return $this->wireProtocol; } final protected function setWireProtocol( DiffusionGitWireProtocol $protocol) { $this->wireProtocol = $protocol; return $this; } public function willWriteMessageCallback( PhabricatorSSHPassthruCommand $command, $message) { $this->ioBytesWritten += strlen($message); $log = $this->getProtocolLog(); if ($log) { $log->didWriteBytes($message); } $protocol = $this->getWireProtocol(); if ($protocol) { $message = $protocol->willWriteBytes($message); } return $message; } public function willReadMessageCallback( PhabricatorSSHPassthruCommand $command, $message) { $log = $this->getProtocolLog(); if ($log) { $log->didReadBytes($message); } $protocol = $this->getWireProtocol(); if ($protocol) { $message = $protocol->willReadBytes($message); } // Note that bytes aren't counted until they're emittted by the protocol // layer. This means the underlying command might emit bytes, but if they // are buffered by the protocol layer they won't count as read bytes yet. $this->ioBytesRead += strlen($message); return $message; } final protected function getIOBytesRead() { return $this->ioBytesRead; } final protected function getIOBytesWritten() { return $this->ioBytesWritten; } final protected function executeRepositoryProxyOperations($for_write) { $device = AlmanacKeys::getLiveDevice(); $refs = $this->getAlmanacServiceRefs($for_write); $err = 1; while (true) { $ref = head($refs); $command = $this->getProxyCommandForServiceRef($ref); if ($device) { $this->writeClusterEngineLogMessage( pht( "# Request received by \"%s\", forwarding to cluster ". "host \"%s\".\n", $device->getName(), $ref->getDeviceName())); } $command = PhabricatorDaemon::sudoCommandAsDaemonUser($command); $future = id(new ExecFuture('%C', $command)) ->setEnv($this->getEnvironment()); $this->didBeginRequest(); $err = $this->newPassthruCommand() ->setIOChannel($this->getIOChannel()) ->setCommandChannelFromExecFuture($future) ->execute(); // TODO: Currently, when proxying, we do not write an event log on the // proxy. Perhaps we should write a "proxy log". This is not very useful // for statistics or auditing, but could be useful for diagnostics. // Marking the proxy logs as proxied (and recording devicePHID on all // logs) would make differentiating between these use cases easier. if (!$err) { $this->waitForGitClient(); return $err; } // Throw away this service: the request failed and we're treating the // failure as persistent, so we don't want to retry another request to // the same host. array_shift($refs); $should_retry = $this->shouldRetryRequest($refs); if (!$should_retry) { return $err; } // If we haven't bailed out yet, we'll retry the request with the next // service. } throw new Exception(pht('Reached an unreachable place.')); } private function didBeginRequest() { $this->requestAttempts++; return $this; } private function shouldRetryRequest(array $remaining_refs) { $this->requestFailures++; if ($this->requestFailures > $this->requestAttempts) { throw new Exception( pht( "Workflow has recorded more failures than attempts; there is a ". "missing call to \"didBeginRequest()\".\n")); } if (!$remaining_refs) { $this->writeClusterEngineLogMessage( pht( "# All available services failed to serve the request, ". "giving up.\n")); return false; } $read_len = $this->getIOBytesRead(); if ($read_len) { $this->writeClusterEngineLogMessage( pht( "# Client already read from service (%s bytes), unable to retry.\n", new PhutilNumber($read_len))); return false; } $write_len = $this->getIOBytesWritten(); if ($write_len) { $this->writeClusterEngineLogMessage( pht( "# Client already wrote to service (%s bytes), unable to retry.\n", new PhutilNumber($write_len))); return false; } $this->writeClusterEngineLogMessage( pht( "# Service request failed, retrying (making attempt %s of %s).\n", new PhutilNumber($this->requestAttempts + 1), new PhutilNumber($this->requestAttempts + count($remaining_refs)))); 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/ssh/DiffusionSSHWorkflow.php
src/applications/diffusion/ssh/DiffusionSSHWorkflow.php
<?php abstract class DiffusionSSHWorkflow extends PhabricatorSSHWorkflow { private $args; private $repository; private $hasWriteAccess; private $shouldProxy; private $baseRequestPath; public function getRepository() { if (!$this->repository) { throw new Exception(pht('Repository is not available yet!')); } return $this->repository; } private function setRepository(PhabricatorRepository $repository) { $this->repository = $repository; return $this; } public function getArgs() { return $this->args; } public function getEnvironment() { $env = array( DiffusionCommitHookEngine::ENV_USER => $this->getSSHUser()->getUsername(), DiffusionCommitHookEngine::ENV_REMOTE_PROTOCOL => 'ssh', ); $identifier = $this->getRequestIdentifier(); if ($identifier !== null) { $env[DiffusionCommitHookEngine::ENV_REQUEST] = $identifier; } $remote_address = $this->getSSHRemoteAddress(); if ($remote_address !== null) { $env[DiffusionCommitHookEngine::ENV_REMOTE_ADDRESS] = $remote_address; } return $env; } /** * Identify and load the affected repository. */ abstract protected function identifyRepository(); abstract protected function executeRepositoryOperations(); abstract protected function raiseWrongVCSException( PhabricatorRepository $repository); protected function getBaseRequestPath() { return $this->baseRequestPath; } protected function writeError($message) { $this->getErrorChannel()->write($message); return $this; } protected function getCurrentDeviceName() { $device = AlmanacKeys::getLiveDevice(); if ($device) { return $device->getName(); } return php_uname('n'); } protected function shouldProxy() { return $this->shouldProxy; } final protected function getAlmanacServiceRefs($for_write) { $viewer = $this->getSSHUser(); $repository = $this->getRepository(); $is_cluster_request = $this->getIsClusterRequest(); $refs = $repository->getAlmanacServiceRefs( $viewer, array( 'neverProxy' => $is_cluster_request, 'protocols' => array( 'ssh', ), 'writable' => $for_write, )); if (!$refs) { throw new Exception( pht( 'Failed to generate an intracluster proxy URI even though this '. 'request was routed as a proxy request.')); } return $refs; } final protected function getProxyCommand($for_write) { $refs = $this->getAlmanacServiceRefs($for_write); $ref = head($refs); return $this->getProxyCommandForServiceRef($ref); } final protected function getProxyCommandForServiceRef( DiffusionServiceRef $ref) { $uri = new PhutilURI($ref->getURI()); $username = AlmanacKeys::getClusterSSHUser(); if ($username === null) { throw new Exception( pht( 'Unable to determine the username to connect with when trying '. 'to proxy an SSH request within the cluster.')); } $port = $uri->getPort(); $host = $uri->getDomain(); $key_path = AlmanacKeys::getKeyPath('device.key'); if (!Filesystem::pathExists($key_path)) { throw new Exception( pht( 'Unable to proxy this SSH request within the cluster: this device '. 'is not registered and has a missing device key (expected to '. 'find key at "%s").', $key_path)); } $options = array(); $options[] = '-o'; $options[] = 'StrictHostKeyChecking=no'; $options[] = '-o'; $options[] = 'UserKnownHostsFile=/dev/null'; // This is suppressing "added <address> to the list of known hosts" // messages, which are confusing and irrelevant when they arise from // proxied requests. It might also be suppressing lots of useful errors, // of course. Ideally, we would enforce host keys eventually. See T13121. $options[] = '-o'; $options[] = 'LogLevel=ERROR'; // NOTE: We prefix the command with "@username", which the far end of the // connection will parse in order to act as the specified user. This // behavior is only available to cluster requests signed by a trusted // device key. return csprintf( 'ssh %Ls -l %s -i %s -p %s %s -- %s %Ls', $options, $username, $key_path, $port, $host, '@'.$this->getSSHUser()->getUsername(), $this->getOriginalArguments()); } final public function execute(PhutilArgumentParser $args) { $this->args = $args; $viewer = $this->getSSHUser(); $have_diffusion = PhabricatorApplication::isClassInstalledForViewer( 'PhabricatorDiffusionApplication', $viewer); if (!$have_diffusion) { throw new Exception( pht( 'You do not have permission to access the Diffusion application, '. 'so you can not interact with repositories over SSH.')); } $repository = $this->identifyRepository(); $this->setRepository($repository); // NOTE: Here, we're just figuring out if this is a proxyable request to // a clusterized repository or not. We don't (and can't) use the URI we get // back directly. // For example, we may get a read-only URI here but be handling a write // request. We only care if we get back `null` (which means we should // handle the request locally) or anything else (which means we should // proxy it to an appropriate device). $is_cluster_request = $this->getIsClusterRequest(); $uri = $repository->getAlmanacServiceURI( $viewer, array( 'neverProxy' => $is_cluster_request, 'protocols' => array( 'ssh', ), )); $this->shouldProxy = (bool)$uri; try { return $this->executeRepositoryOperations(); } catch (Exception $ex) { $this->writeError(get_class($ex).': '.$ex->getMessage()); return 1; } } protected function loadRepositoryWithPath($path, $vcs) { $viewer = $this->getSSHUser(); $info = PhabricatorRepository::parseRepositoryServicePath($path, $vcs); if ($info === null) { throw new Exception( pht( 'Unrecognized repository path "%s". Expected a path like "%s", '. '"%s", or "%s".', $path, '/diffusion/X/', '/diffusion/123/', '/source/thaumaturgy.git')); } $identifier = $info['identifier']; $base = $info['base']; $this->baseRequestPath = $base; $repository = id(new PhabricatorRepositoryQuery()) ->setViewer($viewer) ->withIdentifiers(array($identifier)) ->needURIs(true) ->executeOne(); if (!$repository) { throw new Exception( pht('No repository "%s" exists!', $identifier)); } $is_cluster = $this->getIsClusterRequest(); $protocol = PhabricatorRepositoryURI::BUILTIN_PROTOCOL_SSH; if (!$repository->canServeProtocol($protocol, false, $is_cluster)) { throw new Exception( pht( 'This repository ("%s") is not available over SSH.', $repository->getDisplayName())); } if ($repository->getVersionControlSystem() != $vcs) { $this->raiseWrongVCSException($repository); } return $repository; } protected function requireWriteAccess($protocol_command = null) { if ($this->hasWriteAccess === true) { return; } $repository = $this->getRepository(); $viewer = $this->getSSHUser(); if ($viewer->isOmnipotent()) { throw new Exception( pht( 'This request is authenticated as a cluster device, but is '. 'performing a write. Writes must be performed with a real '. 'user account.')); } if ($repository->isReadOnly()) { throw new Exception($repository->getReadOnlyMessageForDisplay()); } $protocol = PhabricatorRepositoryURI::BUILTIN_PROTOCOL_SSH; if ($repository->canServeProtocol($protocol, true)) { $can_push = PhabricatorPolicyFilter::hasCapability( $viewer, $repository, DiffusionPushCapability::CAPABILITY); if (!$can_push) { throw new Exception( pht('You do not have permission to push to this repository.')); } } else { if ($protocol_command !== null) { throw new Exception( pht( 'This repository is read-only over SSH (tried to execute '. 'protocol command "%s").', $protocol_command)); } else { throw new Exception( pht('This repository is read-only over SSH.')); } } $this->hasWriteAccess = true; return $this->hasWriteAccess; } protected function shouldSkipReadSynchronization() { $viewer = $this->getSSHUser(); // Currently, the only case where devices interact over SSH without // assuming user credentials is when synchronizing before a read. These // synchronizing reads do not themselves need to be synchronized. if ($viewer->isOmnipotent()) { return true; } return false; } protected function newPullEvent() { $viewer = $this->getSSHUser(); $repository = $this->getRepository(); $remote_address = $this->getSSHRemoteAddress(); return id(new PhabricatorRepositoryPullEvent()) ->setEpoch(PhabricatorTime::getNow()) ->setRemoteAddress($remote_address) ->setRemoteProtocol(PhabricatorRepositoryPullEvent::PROTOCOL_SSH) ->setPullerPHID($viewer->getPHID()) ->setRepositoryPHID($repository->getPHID()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/ssh/DiffusionGitUploadPackSSHWorkflow.php
src/applications/diffusion/ssh/DiffusionGitUploadPackSSHWorkflow.php
<?php final class DiffusionGitUploadPackSSHWorkflow extends DiffusionGitSSHWorkflow { protected function didConstruct() { $this->setName('git-upload-pack'); $this->setArguments( array( array( 'name' => 'dir', 'wildcard' => true, ), )); } protected function executeRepositoryOperations() { $is_proxy = $this->shouldProxy(); if ($is_proxy) { return $this->executeRepositoryProxyOperations($for_write = false); } $viewer = $this->getSSHUser(); $repository = $this->getRepository(); $device = AlmanacKeys::getLiveDevice(); $skip_sync = $this->shouldSkipReadSynchronization(); $command = csprintf('git-upload-pack -- %s', $repository->getLocalPath()); if (!$skip_sync) { $cluster_engine = id(new DiffusionRepositoryClusterEngine()) ->setViewer($viewer) ->setRepository($repository) ->setLog($this) ->synchronizeWorkingCopyBeforeRead(); if ($device) { $this->writeClusterEngineLogMessage( pht( "# Cleared to fetch on cluster host \"%s\".\n", $device->getName())); } } $command = PhabricatorDaemon::sudoCommandAsDaemonUser($command); $pull_event = $this->newPullEvent(); $future = id(new ExecFuture('%C', $command)) ->setEnv($this->getEnvironment()); $log = $this->newProtocolLog($is_proxy); if ($log) { $this->setProtocolLog($log); $log->didStartSession($command); } if (PhabricatorEnv::getEnvConfig('phabricator.show-prototypes')) { $protocol = new DiffusionGitUploadPackWireProtocol(); if ($log) { $protocol->setProtocolLog($log); } $this->setWireProtocol($protocol); } $err = $this->newPassthruCommand() ->setIOChannel($this->getIOChannel()) ->setCommandChannelFromExecFuture($future) ->execute(); if ($log) { $log->didEndSession(); } if ($err) { $pull_event ->setResultType(PhabricatorRepositoryPullEvent::RESULT_ERROR) ->setResultCode($err); } else { $pull_event ->setResultType(PhabricatorRepositoryPullEvent::RESULT_PULL) ->setResultCode(0); } $pull_event->save(); if (!$err) { $this->waitForGitClient(); } return $err; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/ssh/DiffusionSubversionServeSSHWorkflow.php
src/applications/diffusion/ssh/DiffusionSubversionServeSSHWorkflow.php
<?php /** * This protocol has a good spec here: * * http://svn.apache.org/repos/asf/subversion/trunk/subversion/libsvn_ra_svn/protocol */ final class DiffusionSubversionServeSSHWorkflow extends DiffusionSubversionSSHWorkflow { private $didSeeWrite; private $inProtocol; private $outProtocol; private $inSeenGreeting; private $outPhaseCount = 0; private $internalBaseURI; private $externalBaseURI; private $peekBuffer; private $command; private $isProxying; private function getCommand() { return $this->command; } protected function didConstruct() { $this->setName('svnserve'); $this->setArguments( array( array( 'name' => 'tunnel', 'short' => 't', ), )); } protected function identifyRepository() { // NOTE: In SVN, we need to read the first few protocol frames before we // can determine which repository the user is trying to access. We're // going to peek at the data on the wire to identify the repository. $io_channel = $this->getIOChannel(); // Before the client will send us the first protocol frame, we need to send // it a connection frame with server capabilities. To figure out the // correct frame we're going to start `svnserve`, read the frame from it, // send it to the client, then kill the subprocess. // TODO: This is pretty inelegant and the protocol frame will change very // rarely. We could cache it if we can find a reasonable way to dirty the // cache. $command = csprintf('svnserve -t'); $command = PhabricatorDaemon::sudoCommandAsDaemonUser($command); $future = new ExecFuture('%C', $command); $exec_channel = new PhutilExecChannel($future); $exec_protocol = new DiffusionSubversionWireProtocol(); while (true) { PhutilChannel::waitForAny(array($exec_channel)); $exec_channel->update(); $exec_message = $exec_channel->read(); if ($exec_message !== null) { $messages = $exec_protocol->writeData($exec_message); if ($messages) { $message = head($messages); $raw = $message['raw']; // Write the greeting frame to the client. $io_channel->write($raw); // Kill the subprocess. $future->resolveKill(); break; } } if (!$exec_channel->isOpenForReading()) { throw new Exception( pht( '%s subprocess exited before emitting a protocol frame.', 'svnserve')); } } $io_protocol = new DiffusionSubversionWireProtocol(); while (true) { PhutilChannel::waitForAny(array($io_channel)); $io_channel->update(); $in_message = $io_channel->read(); if ($in_message !== null) { $this->peekBuffer .= $in_message; if (strlen($this->peekBuffer) > (1024 * 1024)) { throw new Exception( pht( 'Client transmitted more than 1MB of data without transmitting '. 'a recognizable protocol frame.')); } $messages = $io_protocol->writeData($in_message); if ($messages) { $message = head($messages); $struct = $message['structure']; // This is the: // // ( version ( cap1 ... ) url ... ) // // The `url` allows us to identify the repository. $uri = $struct[2]['value']; $path = $this->getPathFromSubversionURI($uri); return $this->loadRepositoryWithPath( $path, PhabricatorRepositoryType::REPOSITORY_TYPE_SVN); } } if (!$io_channel->isOpenForReading()) { throw new Exception( pht( 'Client closed connection before sending a complete protocol '. 'frame.')); } // If the client has disconnected, kill the subprocess and bail. if (!$io_channel->isOpenForWriting()) { throw new Exception( pht( 'Client closed connection before receiving response.')); } } } protected function executeRepositoryOperations() { $repository = $this->getRepository(); $args = $this->getArgs(); if (!$args->getArg('tunnel')) { throw new Exception(pht('Expected `%s`!', 'svnserve -t')); } if ($this->shouldProxy()) { // NOTE: We're always requesting a writable device here. The request // might be read-only, but we can't currently tell, and SVN requests // can mix reads and writes. $command = $this->getProxyCommand(true); $this->isProxying = true; $cwd = null; } else { $command = csprintf( 'svnserve -t --tunnel-user=%s', $this->getSSHUser()->getUsername()); $cwd = PhabricatorEnv::getEmptyCWD(); } $command = PhabricatorDaemon::sudoCommandAsDaemonUser($command); $future = new ExecFuture('%C', $command); // If we're receiving a commit, svnserve will fail to execute the commit // hook with an unhelpful error if the CWD isn't readable by the user we // are sudoing to. Switch to a readable, empty CWD before running // svnserve. See T10941. if ($cwd !== null) { $future->setCWD($cwd); } $this->inProtocol = new DiffusionSubversionWireProtocol(); $this->outProtocol = new DiffusionSubversionWireProtocol(); $this->command = id($this->newPassthruCommand()) ->setIOChannel($this->getIOChannel()) ->setCommandChannelFromExecFuture($future) ->setWillWriteCallback(array($this, 'willWriteMessageCallback')) ->setWillReadCallback(array($this, 'willReadMessageCallback')); $this->command->setPauseIOReads(true); $err = $this->command->execute(); if (!$err && $this->didSeeWrite) { $this->getRepository()->writeStatusMessage( PhabricatorRepositoryStatusMessage::TYPE_NEEDS_UPDATE, PhabricatorRepositoryStatusMessage::CODE_OKAY); } return $err; } public function willWriteMessageCallback( PhabricatorSSHPassthruCommand $command, $message) { $proto = $this->inProtocol; $messages = $proto->writeData($message); $result = array(); foreach ($messages as $message) { $message_raw = $message['raw']; $struct = $message['structure']; if (!$this->inSeenGreeting) { $this->inSeenGreeting = true; // The first message the client sends looks like: // // ( version ( cap1 ... ) url ... ) // // We want to grab the URL, load the repository, make sure it exists and // is accessible, and then replace it with the location of the // repository on disk. $uri = $struct[2]['value']; $struct[2]['value'] = $this->makeInternalURI($uri); $message_raw = $proto->serializeStruct($struct); } else if (isset($struct[0]) && $struct[0]['type'] == 'word') { if (!$proto->isReadOnlyCommand($struct)) { $this->didSeeWrite = true; $this->requireWriteAccess($struct[0]['value']); } // Several other commands also pass in URLs. We need to translate // all of these into the internal representation; this also makes sure // they're valid and accessible. switch ($struct[0]['value']) { case 'reparent': // ( reparent ( url ) ) $struct[1]['value'][0]['value'] = $this->makeInternalURI( $struct[1]['value'][0]['value']); $message_raw = $proto->serializeStruct($struct); break; case 'switch': // ( switch ( ( rev ) target recurse url ... ) ) $struct[1]['value'][3]['value'] = $this->makeInternalURI( $struct[1]['value'][3]['value']); $message_raw = $proto->serializeStruct($struct); break; case 'diff': // ( diff ( ( rev ) target recurse ignore-ancestry url ... ) ) $struct[1]['value'][4]['value'] = $this->makeInternalURI( $struct[1]['value'][4]['value']); $message_raw = $proto->serializeStruct($struct); break; case 'add-file': case 'add-dir': // ( add-file ( path dir-token file-token [ copy-path copy-rev ] ) ) // ( add-dir ( path parent child [ copy-path copy-rev ] ) ) if (isset($struct[1]['value'][3]['value'][0]['value'])) { $copy_from = $struct[1]['value'][3]['value'][0]['value']; $copy_from = $this->makeInternalURI($copy_from); $struct[1]['value'][3]['value'][0]['value'] = $copy_from; } $message_raw = $proto->serializeStruct($struct); break; } } $result[] = $message_raw; } if (!$result) { return null; } return implode('', $result); } public function willReadMessageCallback( PhabricatorSSHPassthruCommand $command, $message) { $proto = $this->outProtocol; $messages = $proto->writeData($message); $result = array(); foreach ($messages as $message) { $message_raw = $message['raw']; $struct = $message['structure']; if (isset($struct[0]) && ($struct[0]['type'] == 'word')) { if ($struct[0]['value'] == 'success') { switch ($this->outPhaseCount) { case 0: // This is the "greeting", which announces capabilities. // We already sent this when we were figuring out which // repository this request is for, so we aren't going to send // it again. // Instead, we're going to replay the client's response (which // we also already read). $command = $this->getCommand(); $command->writeIORead($this->peekBuffer); $command->setPauseIOReads(false); $message_raw = null; break; case 1: // This responds to the client greeting, and announces auth. break; case 2: // This responds to auth, which should be trivial over SSH. break; case 3: // This contains the URI of the repository. We need to edit it; // if it does not match what the client requested it will reject // the response. $struct[1]['value'][1]['value'] = $this->makeExternalURI( $struct[1]['value'][1]['value']); $message_raw = $proto->serializeStruct($struct); break; default: // We don't care about other protocol frames. break; } $this->outPhaseCount++; } else if ($struct[0]['value'] == 'failure') { // Find any error messages which include the internal URI, and // replace the text with the external URI. foreach ($struct[1]['value'] as $key => $error) { $code = $error['value'][0]['value']; $message = $error['value'][1]['value']; $message = str_replace( $this->internalBaseURI, $this->externalBaseURI, $message); // Derp derp derp derp derp. The structure looks like this: // ( failure ( ( code message ... ) ... ) ) $struct[1]['value'][$key]['value'][1]['value'] = $message; } $message_raw = $proto->serializeStruct($struct); } } if ($message_raw !== null) { $result[] = $message_raw; } } if (!$result) { return null; } return implode('', $result); } private function getPathFromSubversionURI($uri_string) { $uri = new PhutilURI($uri_string); $proto = $uri->getProtocol(); if ($proto !== 'svn+ssh') { throw new Exception( pht( 'Protocol for URI "%s" MUST be "%s".', $uri_string, 'svn+ssh')); } $path = $uri->getPath(); // Subversion presumably deals with this, but make sure there's nothing // sketchy going on with the URI. if (preg_match('(/\\.\\./)', $path)) { throw new Exception( pht( 'String "%s" is invalid in path specification "%s".', '/../', $uri_string)); } $path = $this->normalizeSVNPath($path); return $path; } private function makeInternalURI($uri_string) { if ($this->isProxying) { return $uri_string; } $uri = new PhutilURI($uri_string); $repository = $this->getRepository(); $path = $this->getPathFromSubversionURI($uri_string); $external_base = $this->getBaseRequestPath(); // Replace "/diffusion/X" in the request with the repository local path, // so "/diffusion/X/master/" becomes "/path/to/repository/X/master/". $local_path = rtrim($repository->getLocalPath(), '/'); $path = $local_path.substr($path, strlen($external_base)); // NOTE: We are intentionally NOT removing username information from the // URI. Subversion retains it over the course of the request and considers // two repositories with different username identifiers to be distinct and // incompatible. $uri->setPath($path); // If this is happening during the handshake, these are the base URIs for // the request. if ($this->externalBaseURI === null) { $pre = (string)id(clone $uri)->setPath(''); $external_path = $external_base; $external_path = $this->normalizeSVNPath($external_path); $this->externalBaseURI = $pre.$external_path; $internal_path = rtrim($repository->getLocalPath(), '/'); $internal_path = $this->normalizeSVNPath($internal_path); $this->internalBaseURI = $pre.$internal_path; } return (string)$uri; } private function makeExternalURI($uri) { if ($this->isProxying) { return $uri; } $internal = $this->internalBaseURI; $external = $this->externalBaseURI; if (strncmp($uri, $internal, strlen($internal)) === 0) { $uri = $external.substr($uri, strlen($internal)); } return $uri; } private function normalizeSVNPath($path) { // Subversion normalizes redundant slashes internally, so normalize them // here as well to make sure things match up. $path = preg_replace('(/+)', '/', $path); return $path; } protected function raiseWrongVCSException( PhabricatorRepository $repository) { throw new Exception( pht( 'This repository ("%s") is not a Subversion repository. Use "%s" to '. 'interact with this repository.', $repository->getDisplayName(), $repository->getVersionControlSystem())); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/ssh/DiffusionMercurialWireClientSSHProtocolChannel.php
src/applications/diffusion/ssh/DiffusionMercurialWireClientSSHProtocolChannel.php
<?php final class DiffusionMercurialWireClientSSHProtocolChannel extends PhutilProtocolChannel { private $buffer = ''; private $state = 'command'; private $expectArgumentCount; private $argumentName; private $expectBytes; private $command; private $arguments; private $raw; protected function encodeMessage($message) { return $message; } private function initializeState($last_command = null) { if ($last_command == 'unbundle') { $this->command = '<raw-data>'; $this->state = 'data-length'; } else { $this->state = 'command'; } $this->expectArgumentCount = null; $this->expectBytes = null; $this->command = null; $this->argumentName = null; $this->arguments = array(); $this->raw = ''; } private function readProtocolLine() { $pos = strpos($this->buffer, "\n"); if ($pos === false) { return null; } $line = substr($this->buffer, 0, $pos); $this->raw .= $line."\n"; $this->buffer = substr($this->buffer, $pos + 1); return $line; } private function readProtocolBytes() { if (strlen($this->buffer) < $this->expectBytes) { return null; } $bytes = substr($this->buffer, 0, $this->expectBytes); $this->raw .= $bytes; $this->buffer = substr($this->buffer, $this->expectBytes); return $bytes; } private function newMessageAndResetState() { $message = array( 'command' => $this->command, 'arguments' => $this->arguments, 'raw' => $this->raw, ); $this->initializeState($this->command); return $message; } private function newDataMessage($bytes) { $message = array( 'command' => '<raw-data>', 'raw' => strlen($bytes)."\n".$bytes, ); return $message; } protected function decodeStream($data) { $this->buffer .= $data; $out = array(); $messages = array(); while (true) { if ($this->state == 'command') { $this->initializeState(); // We're reading a command. It looks like: // // <command> $line = $this->readProtocolLine(); if ($line === null) { break; } $this->command = $line; $this->state = 'arguments'; } else if ($this->state == 'arguments') { // Check if we're still waiting for arguments. $args = DiffusionMercurialWireProtocol::getCommandArgs($this->command); $have = array_select_keys($this->arguments, $args); if (count($have) == count($args)) { // We have all the arguments. Emit a message and read the next // command. $messages[] = $this->newMessageAndResetState(); } else { // We're still reading arguments. They can either look like: // // <name> <length(value)> // <value> // ... // // ...or like this: // // * <count> // <name1> <length(value1)> // <value1> // ... $line = $this->readProtocolLine(); if ($line === null) { break; } list($arg, $size) = explode(' ', $line, 2); $size = (int)$size; if ($arg != '*') { $this->expectBytes = $size; $this->argumentName = $arg; $this->state = 'value'; } else { $this->arguments['*'] = array(); $this->expectArgumentCount = $size; $this->state = 'argv'; } } } else if ($this->state == 'value' || $this->state == 'argv-value') { // We're reading the value of an argument. We just need to wait for // the right number of bytes to show up. $bytes = $this->readProtocolBytes(); if ($bytes === null) { break; } if ($this->state == 'argv-value') { $this->arguments['*'][$this->argumentName] = $bytes; $this->state = 'argv'; } else { $this->arguments[$this->argumentName] = $bytes; $this->state = 'arguments'; } } else if ($this->state == 'argv') { // We're reading a variable number of arguments. We need to wait for // the arguments to arrive. if ($this->expectArgumentCount) { $line = $this->readProtocolLine(); if ($line === null) { break; } list($arg, $size) = explode(' ', $line, 2); $size = (int)$size; $this->expectBytes = $size; $this->argumentName = $arg; $this->state = 'argv-value'; $this->expectArgumentCount--; } else { $this->state = 'arguments'; } } else if ($this->state == 'data-length') { // We're reading the length of a chunk of raw data. It looks like // this: // // <length-in-bytes>\n // // The length is human-readable text (for example, "4096"), and // may be 0. $line = $this->readProtocolLine(); if ($line === null) { break; } $this->expectBytes = (int)$line; if (!$this->expectBytes) { $messages[] = $this->newDataMessage(''); $this->initializeState(); } else { $this->state = 'data-bytes'; } } else if ($this->state == 'data-bytes') { // We're reading some known, nonzero number of raw bytes of data. // If we don't have any more bytes on the buffer yet, just bail: // otherwise, we'll emit a pointless and possibly harmful 0-byte data // frame. See T13036 for discussion. if (!strlen($this->buffer)) { break; } $bytes = substr($this->buffer, 0, $this->expectBytes); $this->buffer = substr($this->buffer, strlen($bytes)); $this->expectBytes -= strlen($bytes); // NOTE: We emit a data frame as soon as we read some data. This can // cause us to repackage frames: for example, if we receive one large // frame slowly, we may emit it as several smaller frames. In theory // this is good; in practice, Mercurial never seems to select a frame // size larger than 4096 bytes naturally and this may be more // complexity and trouble than it is worth. See T13036. $messages[] = $this->newDataMessage($bytes); if (!$this->expectBytes) { // We've finished reading this chunk, so go read the next chunk. $this->state = 'data-length'; } else { // We're waiting for more data, and have read everything available // to us so far. break; } } else { throw new Exception(pht("Bad parser state '%s'!", $this->state)); } } return $messages; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/ssh/DiffusionMercurialSSHWorkflow.php
src/applications/diffusion/ssh/DiffusionMercurialSSHWorkflow.php
<?php abstract class DiffusionMercurialSSHWorkflow extends DiffusionSSHWorkflow {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/ssh/DiffusionMercurialServeSSHWorkflow.php
src/applications/diffusion/ssh/DiffusionMercurialServeSSHWorkflow.php
<?php final class DiffusionMercurialServeSSHWorkflow extends DiffusionMercurialSSHWorkflow { protected $didSeeWrite; protected function didConstruct() { $this->setName('hg'); $this->setArguments( array( array( 'name' => 'repository', 'short' => 'R', 'param' => 'repo', ), array( 'name' => 'stdio', ), array( 'name' => 'command', 'wildcard' => true, ), )); } protected function identifyRepository() { $args = $this->getArgs(); $path = $args->getArg('repository'); return $this->loadRepositoryWithPath( $path, PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL); } protected function executeRepositoryOperations() { $repository = $this->getRepository(); $args = $this->getArgs(); if (!$args->getArg('stdio')) { throw new Exception(pht('Expected `%s`!', 'hg ... --stdio')); } if ($args->getArg('command') !== array('serve')) { throw new Exception(pht('Expected `%s`!', 'hg ... serve')); } if ($this->shouldProxy()) { // NOTE: For now, we're always requesting a writable node. The request // may not actually need one, but we can't currently determine whether // it is read-only or not at this phase of evaluation. $command = $this->getProxyCommand(true); } else { $command = csprintf( 'hg -R %s serve --stdio', $repository->getLocalPath()); } $command = PhabricatorDaemon::sudoCommandAsDaemonUser($command); $future = id(new ExecFuture('%C', $command)) ->setEnv($this->getEnvironment()); $io_channel = $this->getIOChannel(); $protocol_channel = new DiffusionMercurialWireClientSSHProtocolChannel( $io_channel); $err = id($this->newPassthruCommand()) ->setIOChannel($protocol_channel) ->setCommandChannelFromExecFuture($future) ->setWillWriteCallback(array($this, 'willWriteMessageCallback')) ->execute(); if (!$err && $this->didSeeWrite) { $repository->writeStatusMessage( PhabricatorRepositoryStatusMessage::TYPE_NEEDS_UPDATE, PhabricatorRepositoryStatusMessage::CODE_OKAY); } return $err; } public function willWriteMessageCallback( PhabricatorSSHPassthruCommand $command, $message) { $command = $message['command']; // Check if this is a readonly command. $is_readonly = false; if ($command == 'batch') { $cmds = idx($message['arguments'], 'cmds'); if (DiffusionMercurialWireProtocol::isReadOnlyBatchCommand($cmds)) { $is_readonly = true; } } else if (DiffusionMercurialWireProtocol::isReadOnlyCommand($command)) { $is_readonly = true; } if (!$is_readonly) { $this->requireWriteAccess(); $this->didSeeWrite = true; } return $message['raw']; } protected function raiseWrongVCSException( PhabricatorRepository $repository) { throw new Exception( pht( 'This repository ("%s") is not a Mercurial repository. Use "%s" to '. 'interact with this repository.', $repository->getDisplayName(), $repository->getVersionControlSystem())); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/ssh/DiffusionGitReceivePackSSHWorkflow.php
src/applications/diffusion/ssh/DiffusionGitReceivePackSSHWorkflow.php
<?php final class DiffusionGitReceivePackSSHWorkflow extends DiffusionGitSSHWorkflow { protected function didConstruct() { $this->setName('git-receive-pack'); $this->setArguments( array( array( 'name' => 'dir', 'wildcard' => true, ), )); } protected function executeRepositoryOperations() { // This is a write, and must have write access. $this->requireWriteAccess(); $is_proxy = $this->shouldProxy(); if ($is_proxy) { return $this->executeRepositoryProxyOperations($for_write = true); } $host_wait_start = microtime(true); $repository = $this->getRepository(); $viewer = $this->getSSHUser(); $device = AlmanacKeys::getLiveDevice(); $cluster_engine = id(new DiffusionRepositoryClusterEngine()) ->setViewer($viewer) ->setRepository($repository) ->setLog($this); $command = csprintf('git-receive-pack %s', $repository->getLocalPath()); $cluster_engine->synchronizeWorkingCopyBeforeWrite(); if ($device) { $this->writeClusterEngineLogMessage( pht( "# Ready to receive on cluster host \"%s\".\n", $device->getName())); } $log = $this->newProtocolLog($is_proxy); if ($log) { $this->setProtocolLog($log); $log->didStartSession($command); } $caught = null; try { $err = $this->executeRepositoryCommand($command); } catch (Exception $ex) { $caught = $ex; } if ($log) { $log->didEndSession(); } // We've committed the write (or rejected it), so we can release the lock // without waiting for the client to receive the acknowledgement. $cluster_engine->synchronizeWorkingCopyAfterWrite(); if ($caught) { throw $caught; } if (!$err) { $this->waitForGitClient(); // When a repository is clustered, we reach this cleanup code on both // the proxy and the actual final endpoint node. Don't do more cleanup // or logging than we need to. $repository->writeStatusMessage( PhabricatorRepositoryStatusMessage::TYPE_NEEDS_UPDATE, PhabricatorRepositoryStatusMessage::CODE_OKAY); $host_wait_end = microtime(true); $this->updatePushLogWithTimingInformation( $this->getClusterEngineLogProperty('writeWait'), $this->getClusterEngineLogProperty('readWait'), ($host_wait_end - $host_wait_start)); } return $err; } private function executeRepositoryCommand($command) { $repository = $this->getRepository(); $command = PhabricatorDaemon::sudoCommandAsDaemonUser($command); $future = id(new ExecFuture('%C', $command)) ->setEnv($this->getEnvironment()); return $this->newPassthruCommand() ->setIOChannel($this->getIOChannel()) ->setCommandChannelFromExecFuture($future) ->execute(); } private function updatePushLogWithTimingInformation( $write_wait, $read_wait, $host_wait) { if ($write_wait !== null) { $write_wait = (int)(1000000 * $write_wait); } if ($read_wait !== null) { $read_wait = (int)(1000000 * $read_wait); } if ($host_wait !== null) { $host_wait = (int)(1000000 * $host_wait); } $identifier = $this->getRequestIdentifier(); $event = new PhabricatorRepositoryPushEvent(); $conn = $event->establishConnection('w'); queryfx( $conn, 'UPDATE %T SET writeWait = %nd, readWait = %nd, hostWait = %nd WHERE requestIdentifier = %s', $event->getTableName(), $write_wait, $read_wait, $host_wait, $identifier); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/ssh/__tests__/DiffusionMercurialWireSSHTestCase.php
src/applications/diffusion/ssh/__tests__/DiffusionMercurialWireSSHTestCase.php
<?php final class DiffusionMercurialWireSSHTestCase extends PhabricatorTestCase { public function testMercurialClientWireProtocolParser() { $data = dirname(__FILE__).'/hgwiredata/'; $dir = Filesystem::listDirectory($data, $include_hidden = false); foreach ($dir as $file) { $raw = Filesystem::readFile($data.$file); $raw = explode("\n~~~~~~~~~~\n", $raw, 2); $this->assertEqual(2, count($raw)); $expect = phutil_json_decode($raw[1]); $this->assertTrue(is_array($expect), $file); $this->assertParserResult($expect, $raw[0], $file); } } private function assertParserResult(array $expect, $input, $file) { list($x, $y) = PhutilSocketChannel::newChannelPair(); $xp = new DiffusionMercurialWireClientSSHProtocolChannel($x); $y->write($input); $y->flush(); $y->closeWriteChannel(); $messages = array(); for ($ii = 0; $ii < count($expect); $ii++) { try { $messages[] = $xp->waitForMessage(); } catch (Exception $ex) { // This is probably the parser not producing as many messages as // we expect. Log the exception, but continue to the assertion below // since that will often be easier to diagnose. phlog($ex); break; } } $this->assertEqual($expect, $messages, $file); // Now, make sure the channel doesn't have *more* messages than we expect. // Specifically, it should throw when we try to read another message. $caught = null; try { $xp->waitForMessage(); } catch (Exception $ex) { $caught = $ex; } $this->assertTrue( ($caught instanceof Exception), pht("No extra messages for '%s'.", $file)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/gitlfs/DiffusionGitLFSAuthenticateWorkflow.php
src/applications/diffusion/gitlfs/DiffusionGitLFSAuthenticateWorkflow.php
<?php final class DiffusionGitLFSAuthenticateWorkflow extends DiffusionGitSSHWorkflow { protected function didConstruct() { $this->setName('git-lfs-authenticate'); $this->setArguments( array( array( 'name' => 'argv', 'wildcard' => true, ), )); } protected function identifyRepository() { return $this->loadRepositoryWithPath( $this->getLFSPathArgument(), PhabricatorRepositoryType::REPOSITORY_TYPE_GIT); } private function getLFSPathArgument() { return $this->getLFSArgument(0); } private function getLFSOperationArgument() { return $this->getLFSArgument(1); } private function getLFSArgument($position) { $args = $this->getArgs(); $argv = $args->getArg('argv'); if (!isset($argv[$position])) { throw new Exception( pht( 'Expected `git-lfs-authenticate <path> <operation>`, but received '. 'too few arguments.')); } return $argv[$position]; } protected function executeRepositoryOperations() { $operation = $this->getLFSOperationArgument(); // NOTE: We aren't checking write access here, even for "upload". The // HTTP endpoint should be able to do that for us. switch ($operation) { case 'upload': case 'download': break; default: throw new Exception( pht( 'Git LFS operation "%s" is not supported by this server.', $operation)); } $repository = $this->getRepository(); if (!$repository->isGit()) { throw new Exception( pht( 'Repository "%s" is not a Git repository. Git LFS is only '. 'supported for Git repositories.', $repository->getDisplayName())); } if (!$repository->canUseGitLFS()) { throw new Exception( pht('Git LFS is not enabled for this repository.')); } // NOTE: This is usually the same as the default URI (which does not // need to be specified in the response), but the protocol or domain may // differ in some situations. $lfs_uri = $repository->getGitLFSURI('info/lfs'); // Generate a temporary token to allow the user to access LFS over HTTP. // This works even if normal HTTP repository operations are not available // on this host, and does not require the user to have a VCS password. $user = $this->getSSHUser(); $authorization = DiffusionGitLFSTemporaryTokenType::newHTTPAuthorization( $repository, $user, $operation); $headers = array( 'authorization' => $authorization, ); $result = array( 'header' => $headers, 'href' => $lfs_uri, ); $result = phutil_json_encode($result); $this->writeIO($result); $this->waitForGitClient(); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/gitlfs/DiffusionGitLFSTemporaryTokenType.php
src/applications/diffusion/gitlfs/DiffusionGitLFSTemporaryTokenType.php
<?php final class DiffusionGitLFSTemporaryTokenType extends PhabricatorAuthTemporaryTokenType { const TOKENTYPE = 'diffusion.git.lfs'; const HTTP_USERNAME = '@git-lfs'; public function getTokenTypeDisplayName() { return pht('Git Large File Storage'); } public function getTokenReadableTypeName( PhabricatorAuthTemporaryToken $token) { return pht('Git LFS Token'); } public static function newHTTPAuthorization( PhabricatorRepository $repository, PhabricatorUser $viewer, $operation) { $lfs_user = self::HTTP_USERNAME; $lfs_pass = Filesystem::readRandomCharacters(32); $lfs_hash = PhabricatorHash::weakDigest($lfs_pass); $ttl = PhabricatorTime::getNow() + phutil_units('1 day in seconds'); $token = id(new PhabricatorAuthTemporaryToken()) ->setTokenResource($repository->getPHID()) ->setTokenType(self::TOKENTYPE) ->setTokenCode($lfs_hash) ->setUserPHID($viewer->getPHID()) ->setTemporaryTokenProperty('lfs.operation', $operation) ->setTokenExpires($ttl) ->save(); $authorization_header = base64_encode($lfs_user.':'.$lfs_pass); return 'Basic '.$authorization_header; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/application/PhabricatorDiffusionApplication.php
src/applications/diffusion/application/PhabricatorDiffusionApplication.php
<?php final class PhabricatorDiffusionApplication extends PhabricatorApplication { public function getName() { return pht('Diffusion'); } public function getShortDescription() { return pht('Host and Browse Repositories'); } public function getBaseURI() { return '/diffusion/'; } public function getIcon() { return 'fa-code'; } public function isPinnedByDefault(PhabricatorUser $viewer) { return true; } public function getHelpDocumentationArticles(PhabricatorUser $viewer) { return array( array( 'name' => pht('Diffusion User Guide'), 'href' => PhabricatorEnv::getDoclink('Diffusion User Guide'), ), array( 'name' => pht('Audit User Guide'), 'href' => PhabricatorEnv::getDoclink('Audit User Guide'), ), ); } public function getRemarkupRules() { return array( new DiffusionCommitRemarkupRule(), new DiffusionRepositoryRemarkupRule(), new DiffusionRepositoryByIDRemarkupRule(), new DiffusionSourceLinkRemarkupRule(), ); } public function getRoutes() { $repository_routes = array( '/' => array( '' => 'DiffusionRepositoryController', 'repository/(?P<dblob>.*)' => 'DiffusionRepositoryController', 'change/(?P<dblob>.*)' => 'DiffusionChangeController', 'clone/' => 'DiffusionCloneController', 'history/(?P<dblob>.*)' => 'DiffusionHistoryController', 'browse/(?P<dblob>.*)' => 'DiffusionBrowseController', 'document/(?P<dblob>.*)' => 'DiffusionDocumentController', 'blame/(?P<dblob>.*)' => 'DiffusionBlameController', 'lastmodified/(?P<dblob>.*)' => 'DiffusionLastModifiedController', 'diff/' => 'DiffusionDiffController', 'tags/(?P<dblob>.*)' => 'DiffusionTagListController', 'branches/(?P<dblob>.*)' => 'DiffusionBranchTableController', 'refs/(?P<dblob>.*)' => 'DiffusionRefTableController', 'lint/(?P<dblob>.*)' => 'DiffusionLintController', 'commit/(?P<commit>[a-z0-9]+)' => array( '/?' => 'DiffusionCommitController', '/branches/' => 'DiffusionCommitBranchesController', '/tags/' => 'DiffusionCommitTagsController', ), 'compare/' => 'DiffusionCompareController', 'manage/(?:(?P<panel>[^/]+)/)?' => 'DiffusionRepositoryManagePanelsController', 'uri/' => array( 'view/(?P<id>[0-9]\d*)/' => 'DiffusionRepositoryURIViewController', 'disable/(?P<id>[0-9]\d*)/' => 'DiffusionRepositoryURIDisableController', $this->getEditRoutePattern('edit/') => 'DiffusionRepositoryURIEditController', 'credential/(?P<id>[0-9]\d*)/(?P<action>edit|remove)/' => 'DiffusionRepositoryURICredentialController', ), 'edit/' => array( 'activate/' => 'DiffusionRepositoryEditActivateController', 'dangerous/' => 'DiffusionRepositoryEditDangerousController', 'enormous/' => 'DiffusionRepositoryEditEnormousController', 'delete/' => 'DiffusionRepositoryEditDeleteController', 'update/' => 'DiffusionRepositoryEditUpdateController', 'publish/' => 'DiffusionRepositoryEditPublishingController', 'testautomation/' => 'DiffusionRepositoryTestAutomationController', ), 'pathtree/(?P<dblob>.*)' => 'DiffusionPathTreeController', ), // NOTE: This must come after the rules above; it just gives us a // catch-all for serving repositories over HTTP. We must accept requests // without the trailing "/" because SVN commands don't necessarily // include it. '(?:/.*)?' => 'DiffusionRepositoryDefaultController', ); return array( '/(?:'. 'r(?P<repositoryCallsign>[A-Z]+)'. '|'. 'R(?P<repositoryID>[1-9]\d*):'. ')(?P<commit>[a-f0-9]+)' => 'DiffusionCommitController', '/source/(?P<repositoryShortName>[^/]+)' => $repository_routes, '/diffusion/' => array( $this->getQueryRoutePattern() => 'DiffusionRepositoryListController', $this->getEditRoutePattern('edit/') => 'DiffusionRepositoryEditController', 'pushlog/' => array( $this->getQueryRoutePattern() => 'DiffusionPushLogListController', 'view/(?P<id>\d+)/' => 'DiffusionPushEventViewController', ), 'synclog/' => array( $this->getQueryRoutePattern() => 'DiffusionSyncLogListController', ), 'pulllog/' => array( $this->getQueryRoutePattern() => 'DiffusionPullLogListController', ), '(?P<repositoryCallsign>[A-Z]+)' => $repository_routes, '(?P<repositoryID>[1-9]\d*)' => $repository_routes, 'identity/' => array( $this->getQueryRoutePattern() => 'DiffusionIdentityListController', $this->getEditRoutePattern('edit/') => 'DiffusionIdentityEditController', 'view/(?P<id>[^/]+)/' => 'DiffusionIdentityViewController', ), 'inline/' => array( 'edit/(?P<phid>[^/]+)/' => 'DiffusionInlineCommentController', ), 'services/' => array( 'path/' => array( 'complete/' => 'DiffusionPathCompleteController', 'validate/' => 'DiffusionPathValidateController', ), ), 'symbol/(?P<name>[^/]+)/' => 'DiffusionSymbolController', 'external/' => 'DiffusionExternalController', 'lint/' => 'DiffusionLintController', 'commit/' => array( $this->getQueryRoutePattern() => 'DiffusionCommitListController', $this->getEditRoutePattern('edit/') => 'DiffusionCommitEditController', ), 'picture/(?P<id>[0-9]\d*)/' => 'DiffusionRepositoryProfilePictureController', ), ); } public function getApplicationOrder() { return 0.120; } protected function getCustomCapabilities() { return array( DiffusionDefaultViewCapability::CAPABILITY => array( 'template' => PhabricatorRepositoryRepositoryPHIDType::TYPECONST, 'capability' => PhabricatorPolicyCapability::CAN_VIEW, ), DiffusionDefaultEditCapability::CAPABILITY => array( 'default' => PhabricatorPolicies::POLICY_ADMIN, 'template' => PhabricatorRepositoryRepositoryPHIDType::TYPECONST, 'capability' => PhabricatorPolicyCapability::CAN_EDIT, ), DiffusionDefaultPushCapability::CAPABILITY => array( 'template' => PhabricatorRepositoryRepositoryPHIDType::TYPECONST, ), DiffusionCreateRepositoriesCapability::CAPABILITY => array( 'default' => PhabricatorPolicies::POLICY_ADMIN, ), ); } public function getMailCommandObjects() { return array( 'commit' => array( 'name' => pht('Email Commands: Commits'), 'header' => pht('Interacting with Commits'), 'object' => new PhabricatorRepositoryCommit(), 'summary' => pht( 'This page documents the commands you can use to interact with '. 'commits and audits in Diffusion.'), ), ); } public function getApplicationSearchDocumentTypes() { return array( PhabricatorRepositoryCommitPHIDType::TYPECONST, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/garbagecollector/DiffusionPullEventGarbageCollector.php
src/applications/diffusion/garbagecollector/DiffusionPullEventGarbageCollector.php
<?php final class DiffusionPullEventGarbageCollector extends PhabricatorGarbageCollector { const COLLECTORCONST = 'diffusion.pull'; public function getCollectorName() { return pht('Repository Pull Events'); } public function getDefaultRetentionPolicy() { return phutil_units('30 days in seconds'); } protected function collectGarbage() { $table = new PhabricatorRepositoryPullEvent(); $conn_w = $table->establishConnection('w'); queryfx( $conn_w, 'DELETE FROM %T WHERE epoch < %d LIMIT 100', $table->getTableName(), $this->getGarbageEpoch()); return ($conn_w->getAffectedRows() == 100); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/view/DiffusionView.php
src/applications/diffusion/view/DiffusionView.php
<?php abstract class DiffusionView extends AphrontView { private $diffusionRequest; final public function setDiffusionRequest(DiffusionRequest $request) { $this->diffusionRequest = $request; return $this; } final public function getDiffusionRequest() { return $this->diffusionRequest; } final public function linkHistory($path) { $href = $this->getDiffusionRequest()->generateURI( array( 'action' => 'history', 'path' => $path, )); return $this->renderHistoryLink($href); } final public function linkBranchHistory($branch) { $href = $this->getDiffusionRequest()->generateURI( array( 'action' => 'history', 'branch' => $branch, )); return $this->renderHistoryLink($href); } final public function linkTagHistory($tag) { $href = $this->getDiffusionRequest()->generateURI( array( 'action' => 'history', 'commit' => $tag, )); return $this->renderHistoryLink($href); } private function renderHistoryLink($href) { return javelin_tag( 'a', array( 'href' => $href, 'class' => 'diffusion-link-icon', 'sigil' => 'has-tooltip', 'meta' => array( 'tip' => pht('History'), 'align' => 'E', ), ), id(new PHUIIconView())->setIcon('fa-history bluegrey')); } final public function linkBrowse( $path, array $details = array(), $button = false) { require_celerity_resource('diffusion-icons-css'); Javelin::initBehavior('phabricator-tooltips'); $file_type = idx($details, 'type'); unset($details['type']); $display_name = idx($details, 'name'); unset($details['name']); if ($display_name !== null && strlen($display_name)) { $display_name = phutil_tag( 'span', array( 'class' => 'diffusion-browse-name', ), $display_name); } if (isset($details['external'])) { $params = array( 'uri' => idx($details, 'external'), 'id' => idx($details, 'hash'), ); $href = new PhutilURI('/diffusion/external/', $params); $tip = pht('Browse External'); } else { $href = $this->getDiffusionRequest()->generateURI( $details + array( 'action' => 'browse', 'path' => $path, )); $tip = pht('Browse'); } $icon = DifferentialChangeType::getIconForFileType($file_type); $color = DifferentialChangeType::getIconColorForFileType($file_type); $icon_view = id(new PHUIIconView()) ->setIcon($icon.' '.$color); // If we're rendering a file or directory name, don't show the tooltip. if ($display_name !== null) { $sigil = null; $meta = null; } else { $sigil = 'has-tooltip'; $meta = array( 'tip' => $tip, 'align' => 'E', ); } if ($button) { return id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-code') ->setHref($href) ->setToolTip(pht('Browse')) ->setButtonType(PHUIButtonView::BUTTONTYPE_SIMPLE); } return javelin_tag( 'a', array( 'href' => $href, 'class' => 'diffusion-link-icon', 'sigil' => $sigil, 'meta' => $meta, ), array( $icon_view, $display_name, )); } final public static function linkCommit( PhabricatorRepository $repository, $commit, $summary = '') { $commit_name = $repository->formatCommitName($commit, $local = true); if (strlen($summary)) { $commit_name .= ': '.$summary; } return phutil_tag( 'a', array( 'href' => $repository->getCommitURI($commit), ), $commit_name); } final public static function linkDetail( PhabricatorRepository $repository, $commit, $detail) { return phutil_tag( 'a', array( 'href' => $repository->getCommitURI($commit), ), $detail); } final public static function renderName($name) { $email = new PhutilEmailAddress($name); if ($email->getDisplayName() && $email->getDomainName()) { Javelin::initBehavior('phabricator-tooltips', array()); require_celerity_resource('aphront-tooltip-css'); return javelin_tag( 'span', array( 'sigil' => 'has-tooltip', 'meta' => array( 'tip' => $email->getAddress(), 'align' => 'S', 'size' => 'auto', ), ), $email->getDisplayName()); } return hsprintf('%s', $name); } final protected function renderBuildable( HarbormasterBuildable $buildable, $type = null) { Javelin::initBehavior('phabricator-tooltips'); $icon = $buildable->getStatusIcon(); $color = $buildable->getStatusColor(); $name = $buildable->getStatusDisplayName(); if ($type == 'button') { return id(new PHUIButtonView()) ->setTag('a') ->setText($name) ->setIcon($icon) ->setColor($color) ->setHref('/'.$buildable->getMonogram()) ->addClass('mmr') ->setButtonType(PHUIButtonView::BUTTONTYPE_SIMPLE) ->addClass('diffusion-list-build-status'); } return id(new PHUIIconView()) ->setIcon($icon.' '.$color) ->addSigil('has-tooltip') ->setHref('/'.$buildable->getMonogram()) ->setMetadata( array( 'tip' => $name, )); } final protected function loadBuildables(array $commits) { assert_instances_of($commits, 'PhabricatorRepositoryCommit'); if (!$commits) { return array(); } $viewer = $this->getUser(); $harbormaster_app = 'PhabricatorHarbormasterApplication'; $have_harbormaster = PhabricatorApplication::isClassInstalledForViewer( $harbormaster_app, $viewer); if ($have_harbormaster) { $buildables = id(new HarbormasterBuildableQuery()) ->setViewer($viewer) ->withBuildablePHIDs(mpull($commits, 'getPHID')) ->withManualBuildables(false) ->execute(); $buildables = mpull($buildables, null, 'getBuildablePHID'); } else { $buildables = array(); } return $buildables; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/view/DiffusionCommitGraphView.php
src/applications/diffusion/view/DiffusionCommitGraphView.php
<?php final class DiffusionCommitGraphView extends DiffusionView { private $history; private $commits; private $isHead; private $isTail; private $parents; private $filterParents; private $commitMap; private $buildableMap; private $revisionMap; private $showAuditors; public function setHistory(array $history) { assert_instances_of($history, 'DiffusionPathChange'); $this->history = $history; return $this; } public function getHistory() { return $this->history; } public function setCommits(array $commits) { assert_instances_of($commits, 'PhabricatorRepositoryCommit'); $this->commits = $commits; return $this; } public function getCommits() { return $this->commits; } public function setShowAuditors($show_auditors) { $this->showAuditors = $show_auditors; return $this; } public function getShowAuditors() { return $this->showAuditors; } public function setParents(array $parents) { $this->parents = $parents; return $this; } public function getParents() { return $this->parents; } public function setIsHead($is_head) { $this->isHead = $is_head; return $this; } public function getIsHead() { return $this->isHead; } public function setIsTail($is_tail) { $this->isTail = $is_tail; return $this; } public function getIsTail() { return $this->isTail; } public function setFilterParents($filter_parents) { $this->filterParents = $filter_parents; return $this; } public function getFilterParents() { return $this->filterParents; } private function getRepository() { $drequest = $this->getDiffusionRequest(); if (!$drequest) { return null; } return $drequest->getRepository(); } public function newObjectItemListView() { $list_view = id(new PHUIObjectItemListView()); $item_views = $this->newObjectItemViews(); foreach ($item_views as $item_view) { $list_view->addItem($item_view); } return $list_view; } private function newObjectItemViews() { $viewer = $this->getViewer(); require_celerity_resource('diffusion-css'); $show_builds = $this->shouldShowBuilds(); $show_revisions = $this->shouldShowRevisions(); $show_auditors = $this->shouldShowAuditors(); $phids = array(); if ($show_revisions) { $revision_map = $this->getRevisionMap(); foreach ($revision_map as $revisions) { foreach ($revisions as $revision) { $phids[] = $revision->getPHID(); } } } $commits = $this->getCommitMap(); foreach ($commits as $commit) { $author_phid = $commit->getAuthorDisplayPHID(); if ($author_phid !== null) { $phids[] = $author_phid; } } if ($show_auditors) { foreach ($commits as $commit) { $audits = $commit->getAudits(); foreach ($audits as $auditor) { $phids[] = $auditor->getAuditorPHID(); } } } $handles = $viewer->loadHandles($phids); $views = array(); $items = $this->newHistoryItems(); foreach ($items as $hash => $item) { $content = array(); $commit = $item['commit']; $commit_description = $this->getCommitDescription($commit); $commit_link = $this->getCommitURI($hash); $short_hash = $this->getCommitObjectName($hash); $is_disabled = $this->getCommitIsDisabled($commit); $item_view = id(new PHUIObjectItemView()) ->setViewer($viewer) ->setHeader($commit_description) ->setObjectName($short_hash) ->setHref($commit_link) ->setDisabled($is_disabled); $this->addBrowseAction($item_view, $hash); if ($show_builds) { $this->addBuildAction($item_view, $hash); } $this->addAuditAction($item_view, $hash); if ($show_auditors) { $auditor_list = $item_view->newMapView(); if ($commit) { $auditors = $this->newAuditorList($commit, $handles); $auditor_list->newItem() ->setName(pht('Auditors')) ->setValue($auditors); } } $property_list = $item_view->newMapView(); if ($commit) { $author_view = $this->getCommitAuthorView($commit); if ($author_view) { $property_list->newItem() ->setName(pht('Author')) ->setValue($author_view); } } if ($show_revisions) { if ($commit) { $revisions = $this->getRevisions($commit); if ($revisions) { $list_view = $handles->newSublist(mpull($revisions, 'getPHID')) ->newListView(); $property_list->newItem() ->setName(pht('Revisions')) ->setValue($list_view); } } } $views[$hash] = $item_view; } return $views; } private function newObjectItemRows() { $viewer = $this->getViewer(); $items = $this->newHistoryItems(); $views = $this->newObjectItemViews(); $last_date = null; $rows = array(); foreach ($items as $hash => $item) { $item_epoch = $item['epoch']; $item_date = phabricator_date($item_epoch, $viewer); if ($item_date !== $last_date) { $last_date = $item_date; $header = $item_date; } else { $header = null; } $item_view = $views[$hash]; $list_view = id(new PHUIObjectItemListView()) ->setViewer($viewer) ->setFlush(true) ->addItem($item_view); if ($header !== null) { $list_view->setHeader($header); } $rows[] = $list_view; } return $rows; } public function render() { $rows = $this->newObjectItemRows(); $graph = $this->newGraphView(); foreach ($rows as $idx => $row) { $cells = array(); if ($graph) { $cells[] = phutil_tag( 'td', array( 'class' => 'diffusion-commit-graph-path-cell', ), $graph[$idx]); } $cells[] = phutil_tag( 'td', array( 'class' => 'diffusion-commit-graph-content-cell', ), $row); $rows[$idx] = phutil_tag('tr', array(), $cells); } $table = phutil_tag( 'table', array( 'class' => 'diffusion-commit-graph-table', ), $rows); return $table; } private function newGraphView() { if (!$this->getParents()) { return null; } $parents = $this->getParents(); // If we're filtering parents, remove relationships which point to // commits that are not part of the visible graph. Otherwise, we get // a big tree of nonsense when viewing release branches like "stable" // versus "master". if ($this->getFilterParents()) { foreach ($parents as $key => $nodes) { foreach ($nodes as $nkey => $node) { if (empty($parents[$node])) { unset($parents[$key][$nkey]); } } } } return id(new PHUIDiffGraphView()) ->setIsHead($this->getIsHead()) ->setIsTail($this->getIsTail()) ->renderGraph($parents); } private function shouldShowBuilds() { $viewer = $this->getViewer(); $show_builds = PhabricatorApplication::isClassInstalledForViewer( 'PhabricatorHarbormasterApplication', $this->getUser()); return $show_builds; } private function shouldShowRevisions() { $viewer = $this->getViewer(); $show_revisions = PhabricatorApplication::isClassInstalledForViewer( 'PhabricatorDifferentialApplication', $viewer); return $show_revisions; } private function shouldShowAuditors() { return $this->getShowAuditors(); } private function newHistoryItems() { $items = array(); $history = $this->getHistory(); if ($history !== null) { foreach ($history as $history_item) { $commit_hash = $history_item->getCommitIdentifier(); $items[$commit_hash] = array( 'epoch' => $history_item->getEpoch(), 'hash' => $commit_hash, 'commit' => $this->getCommit($commit_hash), ); } } else { $commits = $this->getCommitMap(); foreach ($commits as $commit) { $commit_hash = $commit->getCommitIdentifier(); $items[$commit_hash] = array( 'epoch' => $commit->getEpoch(), 'hash' => $commit_hash, 'commit' => $commit, ); } } return $items; } private function getCommitDescription($commit) { if (!$commit) { return phutil_tag('em', array(), pht("Discovering\xE2\x80\xA6")); } // We can show details once the message and change have been imported. $partial_import = PhabricatorRepositoryCommit::IMPORTED_MESSAGE | PhabricatorRepositoryCommit::IMPORTED_CHANGE; if (!$commit->isPartiallyImported($partial_import)) { return phutil_tag('em', array(), pht("Importing\xE2\x80\xA6")); } return $commit->getCommitData()->getSummary(); } private function getCommitURI($hash) { $repository = $this->getRepository(); if ($repository) { return $repository->getCommitURI($hash); } $commit = $this->getCommit($hash); if ($commit) { return $commit->getURI(); } return null; } private function getCommitObjectName($hash) { $repository = $this->getRepository(); if ($repository) { return $repository->formatCommitName( $hash, $is_local = true); } $commit = $this->getCommit($hash); if ($commit) { return $commit->getDisplayName(); } return null; } private function getCommitIsDisabled($commit) { if (!$commit) { return true; } if ($commit->isUnreachable()) { return true; } return false; } private function getCommitAuthorView($commit) { if (!$commit) { return null; } $viewer = $this->getViewer(); $author_phid = $commit->getAuthorDisplayPHID(); if ($author_phid) { return $viewer->loadHandles(array($author_phid)) ->newListView(); } return $commit->newCommitAuthorView($viewer); } private function getCommit($hash) { $commit_map = $this->getCommitMap(); return idx($commit_map, $hash); } private function getCommitMap() { if ($this->commitMap === null) { $commit_list = $this->newCommitList(); $this->commitMap = mpull($commit_list, null, 'getCommitIdentifier'); } return $this->commitMap; } private function addBrowseAction(PHUIObjectItemView $item, $hash) { $repository = $this->getRepository(); if (!$repository) { return; } $drequest = $this->getDiffusionRequest(); $path = $drequest->getPath(); $uri = $drequest->generateURI( array( 'action' => 'browse', 'path' => $path, 'commit' => $hash, )); $menu_item = $item->newMenuItem() ->setName(pht('Browse Repository')) ->setURI($uri); $menu_item->newIcon() ->setIcon('fa-folder-open-o') ->setColor('bluegrey'); } private function addBuildAction(PHUIObjectItemView $item, $hash) { $is_disabled = true; $buildable = null; $commit = $this->getCommit($hash); if ($commit) { $buildable = $this->getBuildable($commit); } if ($buildable) { $icon = $buildable->getStatusIcon(); $color = $buildable->getStatusColor(); $name = $buildable->getStatusDisplayName(); $uri = $buildable->getURI(); } else { $icon = 'fa-times'; $color = 'grey'; $name = pht('No Builds'); $uri = null; } $menu_item = $item->newMenuItem() ->setName($name) ->setURI($uri) ->setDisabled(($uri === null)); $menu_item->newIcon() ->setIcon($icon) ->setColor($color); } private function addAuditAction(PHUIObjectItemView $item_view, $hash) { $commit = $this->getCommit($hash); if ($commit) { $status = $commit->getAuditStatusObject(); $text = $status->getName(); $icon = $status->getIcon(); $is_disabled = $status->isNoAudit(); if ($is_disabled) { $uri = null; $color = 'grey'; } else { $color = $status->getColor(); $uri = $commit->getURI(); } } else { $text = pht('No Audit'); $color = 'grey'; $icon = 'fa-times'; $uri = null; $is_disabled = true; } $menu_item = $item_view->newMenuItem() ->setName($text) ->setURI($uri) ->setBackgroundColor($color) ->setDisabled($is_disabled); $menu_item->newIcon() ->setIcon($icon) ->setColor($color); } private function getBuildable(PhabricatorRepositoryCommit $commit) { $buildable_map = $this->getBuildableMap(); return idx($buildable_map, $commit->getPHID()); } private function getBuildableMap() { if ($this->buildableMap === null) { $commits = $this->getCommitMap(); $buildables = $this->loadBuildables($commits); $this->buildableMap = $buildables; } return $this->buildableMap; } private function getRevisions(PhabricatorRepositoryCommit $commit) { $revision_map = $this->getRevisionMap(); return idx($revision_map, $commit->getPHID(), array()); } private function getRevisionMap() { if ($this->revisionMap === null) { $this->revisionMap = $this->newRevisionMap(); } return $this->revisionMap; } private function newRevisionMap() { $viewer = $this->getViewer(); $commits = $this->getCommitMap(); return DiffusionCommitRevisionQuery::loadRevisionMapForCommits( $viewer, $commits); } private function newCommitList() { $commits = $this->getCommits(); if ($commits !== null) { return $commits; } $repository = $this->getRepository(); if (!$repository) { return array(); } $history = $this->getHistory(); if ($history === null) { return array(); } $identifiers = array(); foreach ($history as $item) { $identifiers[] = $item->getCommitIdentifier(); } if (!$identifiers) { return array(); } $viewer = $this->getViewer(); $commits = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withRepository($repository) ->withIdentifiers($identifiers) ->needCommitData(true) ->needIdentities(true) ->execute(); return $commits; } private function newAuditorList( PhabricatorRepositoryCommit $commit, $handles) { $auditors = $commit->getAudits(); if (!$auditors) { return phutil_tag('em', array(), pht('None')); } $auditor_phids = mpull($auditors, 'getAuditorPHID'); $auditor_list = $handles->newSublist($auditor_phids) ->newListView(); return $auditor_list; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/view/DiffusionPushLogListView.php
src/applications/diffusion/view/DiffusionPushLogListView.php
<?php final class DiffusionPushLogListView extends AphrontView { private $logs; public function setLogs(array $logs) { assert_instances_of($logs, 'PhabricatorRepositoryPushLog'); $this->logs = $logs; return $this; } public function render() { $logs = $this->logs; $viewer = $this->getViewer(); $reject_herald = PhabricatorRepositoryPushLog::REJECT_HERALD; $handle_phids = array(); foreach ($logs as $log) { $handle_phids[] = $log->getPusherPHID(); $device_phid = $log->getDevicePHID(); if ($device_phid) { $handle_phids[] = $device_phid; } if ($log->getPushEvent()->getRejectCode() == $reject_herald) { $handle_phids[] = $log->getPushEvent()->getRejectDetails(); } } $viewer->loadHandles($handle_phids); // Only administrators can view remote addresses. $remotes_visible = $viewer->getIsAdmin(); $flag_map = PhabricatorRepositoryPushLog::getFlagDisplayNames(); $reject_map = PhabricatorRepositoryPushLog::getRejectCodeDisplayNames(); $rows = array(); $any_host = false; foreach ($logs as $log) { $repository = $log->getRepository(); $event = $log->getPushEvent(); if ($remotes_visible) { $remote_address = $event->getRemoteAddress(); } else { $remote_address = null; } $event_id = $log->getPushEvent()->getID(); $old_ref_link = null; if ($log->getRefOld() != DiffusionCommitHookEngine::EMPTY_HASH) { $old_ref_link = phutil_tag( 'a', array( 'href' => $repository->getCommitURI($log->getRefOld()), ), $log->getRefOldShort()); } $device_phid = $log->getDevicePHID(); if ($device_phid) { $device = $viewer->renderHandle($device_phid); $any_host = true; } else { $device = null; } $flags = $log->getChangeFlags(); $flag_names = array(); foreach ($flag_map as $flag_key => $flag_name) { if (($flags & $flag_key) === $flag_key) { $flag_names[] = $flag_name; } } $flag_names = phutil_implode_html( phutil_tag('br'), $flag_names); $reject_code = $event->getRejectCode(); if ($reject_code == $reject_herald) { $rule_phid = $event->getRejectDetails(); $handle = $viewer->renderHandle($rule_phid); $reject_label = pht('Blocked: %s', $handle); } else { $reject_label = idx( $reject_map, $reject_code, pht('Unknown ("%s")', $reject_code)); } $host_wait = $this->formatMicroseconds($event->getHostWait()); $write_wait = $this->formatMicroseconds($event->getWriteWait()); $read_wait = $this->formatMicroseconds($event->getReadWait()); $hook_wait = $this->formatMicroseconds($event->getHookWait()); $rows[] = array( phutil_tag( 'a', array( 'href' => '/diffusion/pushlog/view/'.$event_id.'/', ), $event_id), phutil_tag( 'a', array( 'href' => $repository->getURI(), ), $repository->getDisplayName()), $viewer->renderHandle($log->getPusherPHID()), $remote_address, $event->getRemoteProtocol(), $device, $log->getRefType(), $log->getRefName(), $old_ref_link, phutil_tag( 'a', array( 'href' => $repository->getCommitURI($log->getRefNew()), ), $log->getRefNewShort()), $flag_names, $reject_label, $viewer->formatShortDateTime($log->getEpoch()), $host_wait, $write_wait, $read_wait, $hook_wait, ); } $table = id(new AphrontTableView($rows)) ->setHeaders( array( pht('Push'), pht('Repository'), pht('Pusher'), pht('From'), pht('Via'), pht('Host'), pht('Type'), pht('Name'), pht('Old'), pht('New'), pht('Flags'), pht('Result'), pht('Date'), pht('Host Wait'), pht('Write Wait'), pht('Read Wait'), pht('Hook Wait'), )) ->setColumnClasses( array( '', '', '', '', '', '', '', 'wide', 'n', 'n', '', '', 'right', 'n right', 'n right', 'n right', 'n right', )) ->setColumnVisibility( array( true, true, true, $remotes_visible, true, $any_host, )); return $table; } private function formatMicroseconds($duration) { if ($duration === null) { return null; } return pht('%sus', new PhutilNumber($duration)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/view/DiffusionSyncLogListView.php
src/applications/diffusion/view/DiffusionSyncLogListView.php
<?php final class DiffusionSyncLogListView extends AphrontView { private $logs; public function setLogs(array $logs) { assert_instances_of($logs, 'PhabricatorRepositorySyncEvent'); $this->logs = $logs; return $this; } public function render() { $events = $this->logs; $viewer = $this->getViewer(); $rows = array(); foreach ($events as $event) { $repository = $event->getRepository(); $repository_link = phutil_tag( 'a', array( 'href' => $repository->getURI(), ), $repository->getDisplayName()); $event_id = $event->getID(); $sync_wait = pht('%sus', new PhutilNumber($event->getSyncWait())); $device_link = $viewer->renderHandle($event->getDevicePHID()); $from_device_link = $viewer->renderHandle($event->getFromDevicePHID()); $rows[] = array( $event_id, $repository_link, $device_link, $from_device_link, $event->getDeviceVersion(), $event->getFromDeviceVersion(), $event->getResultType(), $event->getResultCode(), phabricator_datetime($event->getEpoch(), $viewer), $sync_wait, ); } $table = id(new AphrontTableView($rows)) ->setHeaders( array( pht('Sync'), pht('Repository'), pht('Device'), pht('From Device'), pht('Version'), pht('From Version'), pht('Result'), pht('Code'), pht('Date'), pht('Sync Wait'), )) ->setColumnClasses( array( 'n', '', '', '', 'n', 'n', 'wide right', 'n', 'right', 'n right', )); return $table; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/view/DiffusionPatternSearchView.php
src/applications/diffusion/view/DiffusionPatternSearchView.php
<?php final class DiffusionPatternSearchView extends DiffusionView { private $path; private $matches; private $pattern; public function setPath($path) { $this->path = $path; return $this; } public function setMatches(array $matches) { $this->matches = $matches; return $this; } public function setPattern($pattern) { $this->pattern = $pattern; return $this; } public function render() { $drequest = $this->getDiffusionRequest(); $path = $this->path; $pattern = $this->pattern; $rows = array(); foreach ($this->matches as $result) { list($line, $string) = $result; $matches = null; $count = @preg_match_all( '('.$pattern.')u', $string, $matches, PREG_OFFSET_CAPTURE); if (!$count) { $output = ltrim($string); } else { $output = array(); $cursor = 0; $length = strlen($string); foreach ($matches[0] as $match) { $offset = $match[1]; if ($cursor != $offset) { $output[] = array( 'text' => substr($string, $cursor, ($offset - $cursor)), 'highlight' => false, ); } $output[] = array( 'text' => $match[0], 'highlight' => true, ); $cursor = $offset + strlen($match[0]); } if ($cursor != $length) { $output[] = array( 'text' => substr($string, $cursor), 'highlight' => false, ); } if ($output) { $output[0]['text'] = ltrim($output[0]['text']); } foreach ($output as $key => $segment) { if ($segment['highlight']) { $output[$key] = phutil_tag('strong', array(), $segment['text']); } else { $output[$key] = $segment['text']; } } } $string = phutil_tag( 'pre', array('class' => 'PhabricatorMonospaced phui-source-fragment'), $output); $href = $drequest->generateURI(array( 'action' => 'browse', 'path' => $path, 'line' => $line, )); $rows[] = array( phutil_tag('a', array('href' => $href), $line), $string, ); } $path_title = Filesystem::readablePath($this->path, $drequest->getPath()); $href = $drequest->generateURI( array( 'action' => 'browse', 'path' => $this->path, )); $title = phutil_tag('a', array('href' => $href), $path_title); $table = id(new AphrontTableView($rows)) ->setClassName('remarkup-code') ->setHeaders(array(pht('Line'), pht('String'))) ->setColumnClasses(array('n', 'wide')); $header = id(new PHUIHeaderView()) ->setHeader($title); $box = id(new PHUIObjectBoxView()) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setTable($table); return $box->render(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/view/DiffusionBrowseTableView.php
src/applications/diffusion/view/DiffusionBrowseTableView.php
<?php final class DiffusionBrowseTableView extends DiffusionView { private $paths; public function setPaths(array $paths) { assert_instances_of($paths, 'DiffusionRepositoryPath'); $this->paths = $paths; return $this; } public function render() { $request = $this->getDiffusionRequest(); $repository = $request->getRepository(); require_celerity_resource('diffusion-css'); if ($request->getPath() !== null) { $base_path = trim($request->getPath(), '/'); if ($base_path) { $base_path = $base_path.'/'; } } else { $base_path = ''; } $need_pull = array(); $rows = array(); foreach ($this->paths as $path) { $full_path = $base_path.$path->getPath(); $dir_slash = null; $file_type = $path->getFileType(); if ($file_type == DifferentialChangeType::FILE_DIRECTORY) { $browse_text = $path->getPath().'/'; $dir_slash = '/'; $browse_link = phutil_tag('strong', array(), $this->linkBrowse( $full_path.$dir_slash, array( 'type' => $file_type, 'name' => $browse_text, ))); $history_path = $full_path.'/'; } else if ($file_type == DifferentialChangeType::FILE_SUBMODULE) { $browse_text = $path->getPath().'/'; $browse_link = phutil_tag('strong', array(), $this->linkBrowse( null, array( 'type' => $file_type, 'name' => $browse_text, 'hash' => $path->getHash(), 'external' => $path->getExternalURI(), ))); $history_path = $full_path.'/'; } else { $browse_text = $path->getPath(); $browse_link = $this->linkBrowse( $full_path, array( 'type' => $file_type, 'name' => $browse_text, )); $history_path = $full_path; } $history_link = $this->linkHistory($history_path); $dict = array( 'lint' => celerity_generate_unique_node_id(), 'date' => celerity_generate_unique_node_id(), 'details' => celerity_generate_unique_node_id(), ); $need_pull[$full_path.$dir_slash] = $dict; foreach ($dict as $k => $uniq) { $dict[$k] = phutil_tag('span', array('id' => $uniq), ''); } $rows[] = array( $browse_link, idx($dict, 'lint'), $dict['details'], $dict['date'], $history_link, ); } if ($need_pull) { Javelin::initBehavior( 'diffusion-pull-lastmodified', array( 'uri' => (string)$request->generateURI( array( 'action' => 'lastmodified', 'stable' => true, )), 'map' => $need_pull, )); } $branch = $this->getDiffusionRequest()->loadBranch(); $show_lint = ($branch && $branch->getLintCommit()); $lint = $request->getLint(); $view = new AphrontTableView($rows); $view->setColumnClasses( array( '', '', 'wide commit-detail', 'right', 'right narrow', )); $view->setColumnVisibility( array( true, $show_lint, true, true, true, )); $view->setDeviceVisibility( array( true, false, false, false, false, )); return phutil_tag_div('diffusion-browse-table', $view->render()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/view/DiffusionTagListView.php
src/applications/diffusion/view/DiffusionTagListView.php
<?php final class DiffusionTagListView extends DiffusionView { private $tags; private $commits = array(); private $handles = array(); public function setTags($tags) { $this->tags = $tags; return $this; } public function setCommits(array $commits) { $this->commits = mpull($commits, null, 'getCommitIdentifier'); return $this; } public function setHandles(array $handles) { $this->handles = $handles; return $this; } public function getRequiredHandlePHIDs() { return array_filter(mpull($this->commits, 'getAuthorPHID')); } public function render() { $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $viewer = $this->getViewer(); require_celerity_resource('diffusion-css'); $buildables = $this->loadBuildables($this->commits); $list = id(new PHUIObjectItemListView()) ->setFlush(true) ->addClass('diffusion-history-list'); foreach ($this->tags as $tag) { $commit = idx($this->commits, $tag->getCommitIdentifier()); $button_bar = new PHUIButtonBarView(); $tag_href = $drequest->generateURI( array( 'action' => 'history', 'commit' => $tag->getName(), )); $commit_href = $drequest->generateURI( array( 'action' => 'commit', 'commit' => $tag->getCommitIdentifier(), )); if ($commit) { $author = $this->renderAuthor($tag, $commit); } else { $author = null; } $description = null; if ($tag->getType() == 'git/tag') { // In Git, a tag may be a "real" tag, or just a reference to a commit. // If it's a real tag, use the message on the tag, since this may be // unique data which isn't otherwise available. $description = $tag->getDescription(); } else { if ($commit) { $description = $commit->getSummary(); } else { $description = $tag->getDescription(); } } $build_view = null; if ($commit) { $buildable = idx($buildables, $commit->getPHID()); if ($buildable) { $build_view = $this->renderBuildable($buildable, 'button'); } } if ($repository->supportsBranchComparison()) { $compare_uri = $drequest->generateURI( array( 'action' => 'compare', 'head' => $tag->getName(), )); $button_bar->addButton( id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-balance-scale') ->setToolTip(pht('Compare')) ->setButtonType(PHUIButtonView::BUTTONTYPE_SIMPLE) ->setWorkflow(true) ->setHref($compare_uri)); } $commit_name = $repository->formatCommitName( $tag->getCommitIdentifier(), $local = true); $browse_href = $drequest->generateURI( array( 'action' => 'browse', 'commit' => $tag->getName(), )); $button_bar->addButton( id(new PHUIButtonView()) ->setTooltip(pht('Browse')) ->setIcon('fa-code') ->setHref($browse_href) ->setTag('a') ->setButtonType(PHUIButtonView::BUTTONTYPE_SIMPLE)); $commit_tag = id(new PHUITagView()) ->setName($commit_name) ->setHref($commit_href) ->setType(PHUITagView::TYPE_SHADE) ->setColor(PHUITagView::COLOR_INDIGO) ->setBorder(PHUITagView::BORDER_NONE) ->setSlimShady(true); $item = id(new PHUIObjectItemView()) ->setHeader($tag->getName()) ->setHref($tag_href) ->addAttribute(array($commit_tag)) ->addAttribute($description) ->setSideColumn(array( $build_view, $button_bar, )); if ($author) { $item->addAttribute($author); } $list->addItem($item); } return $list; } private function renderAuthor( DiffusionRepositoryTag $tag, PhabricatorRepositoryCommit $commit) { $viewer = $this->getViewer(); if ($commit->getAuthorPHID()) { $author = $this->handles[$commit->getAuthorPHID()]->renderLink(); } else if ($commit->getCommitData()) { $author = self::renderName($commit->getCommitData()->getAuthorString()); } else { $author = self::renderName($tag->getAuthor()); } $committed = phabricator_datetime($commit->getEpoch(), $viewer); $author_name = phutil_tag( 'strong', array( 'class' => 'diffusion-history-author-name', ), $author); return pht('%s on %s.', $author_name, $committed); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/view/DiffusionCloneURIView.php
src/applications/diffusion/view/DiffusionCloneURIView.php
<?php final class DiffusionCloneURIView extends AphrontView { private $repository; private $repositoryURI; private $displayURI; public function setRepository(PhabricatorRepository $repository) { $this->repository = $repository; return $this; } public function getRepository() { return $this->repository; } public function setRepositoryURI(PhabricatorRepositoryURI $repository_uri) { $this->repositoryURI = $repository_uri; return $this; } public function getRepositoryURI() { return $this->repositoryURI; } public function setDisplayURI($display_uri) { $this->displayURI = $display_uri; return $this; } public function getDisplayURI() { return $this->displayURI; } public function render() { $viewer = $this->getViewer(); require_celerity_resource('diffusion-icons-css'); Javelin::initBehavior('select-content'); $uri_id = celerity_generate_unique_node_id(); $display = $this->getDisplayURI(); $input = javelin_tag( 'input', array( 'id' => $uri_id, 'type' => 'text', 'value' => $display, 'class' => 'diffusion-clone-uri', 'readonly' => 'true', )); $uri = $this->getRepositoryURI(); switch ($uri->getEffectiveIOType()) { case PhabricatorRepositoryURI::IO_READ: $io_icon = 'fa-eye'; $io_tip = pht('Read-Only'); break; case PhabricatorRepositoryURI::IO_READWRITE: $io_icon = 'fa-download'; $io_tip = pht('Read / Write'); break; default: $io_icon = 'fa-cloud'; $io_tip = pht('External'); break; } $io = id(new PHUIButtonView()) ->setTag('a') ->setColor(PHUIButtonView::GREY) ->setIcon($io_icon) ->setHref('#') ->addSigil('select-content') ->addSigil('has-tooltip') ->setMetadata( array( 'tip' => $io_tip, 'selectID' => $uri_id, )); switch ($uri->getEffectiveIOType()) { case PhabricatorRepositoryURI::IO_READ: case PhabricatorRepositoryURI::IO_READWRITE: switch ($uri->getBuiltinProtocol()) { case PhabricatorRepositoryURI::BUILTIN_PROTOCOL_SSH: $auth_uri = id(new PhabricatorSSHKeysSettingsPanel()) ->setViewer($viewer) ->setUser($viewer) ->getPanelURI(); $auth_tip = pht('Manage SSH Keys'); $auth_disabled = false; break; default: $auth_uri = id(new DiffusionSetPasswordSettingsPanel()) ->setViewer($viewer) ->setUser($viewer) ->getPanelURI(); $auth_tip = pht('Manage Password'); $auth_disabled = false; break; } break; default: $auth_disabled = true; $auth_tip = pht('External'); $auth_uri = '#'; break; } $credentials = id(new PHUIButtonView()) ->setTag('a') ->setColor(PHUIButtonView::GREY) ->setIcon('fa-key') ->setTooltip($auth_tip) ->setHref($auth_uri) ->setDisabled($auth_disabled); $cells = array(); $cells[] = phutil_tag('td', array(), $input); $cells[] = phutil_tag('th', array(), $io); $cells[] = phutil_tag('th', array(), $credentials); $row = phutil_tag('tr', array(), $cells); return phutil_tag( 'table', array( 'class' => 'diffusion-clone-uri-table', ), $row); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/view/DiffusionBranchListView.php
src/applications/diffusion/view/DiffusionBranchListView.php
<?php final class DiffusionBranchListView extends DiffusionView { private $branches; private $commits = array(); public function setBranches(array $branches) { assert_instances_of($branches, 'DiffusionRepositoryRef'); $this->branches = $branches; return $this; } public function setCommits(array $commits) { assert_instances_of($commits, 'PhabricatorRepositoryCommit'); $this->commits = mpull($commits, null, 'getCommitIdentifier'); return $this; } public function render() { $drequest = $this->getDiffusionRequest(); $current_branch = $drequest->getBranch(); $repository = $drequest->getRepository(); $commits = $this->commits; $viewer = $this->getUser(); require_celerity_resource('diffusion-css'); $buildables = $this->loadBuildables($commits); $have_builds = false; $can_close_branches = ($repository->isHg()); Javelin::initBehavior('phabricator-tooltips'); $list = id(new PHUIObjectItemListView()) ->addClass('diffusion-history-list') ->addClass('diffusion-branch-list'); $publisher = $repository->newPublisher(); foreach ($this->branches as $branch) { $build_view = null; $button_bar = new PHUIButtonBarView(); $commit = idx($commits, $branch->getCommitIdentifier()); if ($commit) { $details = $commit->getSummary(); $datetime = phabricator_datetime($commit->getEpoch(), $viewer); $buildable = idx($buildables, $commit->getPHID()); if ($buildable) { $build_view = $this->renderBuildable($buildable, 'button'); } } else { $datetime = null; $details = null; } if ($repository->supportsBranchComparison()) { $compare_uri = $drequest->generateURI( array( 'action' => 'compare', 'head' => $branch->getShortName(), )); $can_compare = ($branch->getShortName() != $current_branch); if ($can_compare) { $button_bar->addButton( id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-balance-scale') ->setToolTip(pht('Compare')) ->setButtonType(PHUIButtonView::BUTTONTYPE_SIMPLE) ->setWorkflow(true) ->setHref($compare_uri)); } } $browse_href = $drequest->generateURI( array( 'action' => 'browse', 'branch' => $branch->getShortName(), )); $button_bar->addButton( id(new PHUIButtonView()) ->setIcon('fa-code') ->setHref($browse_href) ->setTag('a') ->setTooltip(pht('Browse')) ->setButtonType(PHUIButtonView::BUTTONTYPE_SIMPLE)); $commit_link = $repository->getCommitURI( $branch->getCommitIdentifier()); $commit_name = $repository->formatCommitName( $branch->getCommitIdentifier(), $local = true); $commit_tag = id(new PHUITagView()) ->setName($commit_name) ->setHref($commit_link) ->setType(PHUITagView::TYPE_SHADE) ->setColor(PHUITagView::COLOR_INDIGO) ->setBorder(PHUITagView::BORDER_NONE) ->setSlimShady(true); $subhead = array($commit_tag, ' ', $details); $item = id(new PHUIObjectItemView()) ->setHeader($branch->getShortName()) ->setHref($drequest->generateURI( array( 'action' => 'history', 'branch' => $branch->getShortName(), ))) ->setSubhead($subhead) ->setSideColumn(array( $build_view, $button_bar, )); if ($branch->getShortName() == $repository->getDefaultBranch()) { $item->setStatusIcon('fa-star', pht('Default Branch')); } else { if ($publisher->shouldPublishRef($branch)) { $item->setStatusIcon('fa-code-fork', pht('Permanent Ref')); } else { $item->setStatusIcon( 'fa-folder-open-o grey', pht('Not a Permanent Ref')); } } $item->addAttribute(array($datetime)); if ($can_close_branches) { $fields = $branch->getRawFields(); $closed = idx($fields, 'closed'); if ($closed) { $status = pht('Branch Closed'); $item->setDisabled(true); } else { $status = pht('Branch Open'); } $item->addAttribute($status); } $list->addItem($item); } return $list; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/view/DiffusionPullLogListView.php
src/applications/diffusion/view/DiffusionPullLogListView.php
<?php final class DiffusionPullLogListView extends AphrontView { private $logs; public function setLogs(array $logs) { assert_instances_of($logs, 'PhabricatorRepositoryPullEvent'); $this->logs = $logs; return $this; } public function render() { $events = $this->logs; $viewer = $this->getViewer(); $handle_phids = array(); foreach ($events as $event) { if ($event->getPullerPHID()) { $handle_phids[] = $event->getPullerPHID(); } } $handles = $viewer->loadHandles($handle_phids); // Only administrators can view remote addresses. $remotes_visible = $viewer->getIsAdmin(); $rows = array(); foreach ($events as $event) { if ($event->getRepositoryPHID()) { $repository = $event->getRepository(); } else { $repository = null; } if ($remotes_visible) { $remote_address = $event->getRemoteAddress(); } else { $remote_address = null; } $event_id = $event->getID(); $repository_link = null; if ($repository) { $repository_link = phutil_tag( 'a', array( 'href' => $repository->getURI(), ), $repository->getDisplayName()); } $puller_link = null; if ($event->getPullerPHID()) { $puller_link = $viewer->renderHandle($event->getPullerPHID()); } $rows[] = array( $event_id, $repository_link, $puller_link, $remote_address, $event->getRemoteProtocolDisplayName(), $event->newResultIcon(), $event->getResultCode(), phabricator_datetime($event->getEpoch(), $viewer), ); } $table = id(new AphrontTableView($rows)) ->setHeaders( array( pht('Pull'), pht('Repository'), pht('Puller'), pht('From'), pht('Via'), null, pht('Code'), pht('Date'), )) ->setColumnClasses( array( 'n', '', '', 'n', 'wide', '', 'n', 'right', )) ->setColumnVisibility( array( true, true, true, $remotes_visible, )); return $table; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/view/DiffusionSourceLinkView.php
src/applications/diffusion/view/DiffusionSourceLinkView.php
<?php final class DiffusionSourceLinkView extends AphrontView { private $repository; private $text; private $uri; private $blob; private $blobMap; private $refName; private $path; private $line; private $commit; public function setRepository($repository) { $this->repository = $repository; $this->blobMap = null; return $this; } public function getRepository() { return $this->repository; } public function setText($text) { $this->text = $text; return $this; } public function getText() { return $this->text; } public function setURI($uri) { $this->uri = $uri; return $this; } public function getURI() { return $this->uri; } public function setBlob($blob) { $this->blob = $blob; $this->blobMap = null; return $this; } public function getBlob() { return $this->blob; } public function setRefName($ref_name) { $this->refName = $ref_name; return $this; } public function getRefName() { return $this->refName; } public function setPath($path) { $this->path = $path; return $this; } public function getPath() { return $this->path; } public function setCommit($commit) { $this->commit = $commit; return $this; } public function getCommit() { return $this->commit; } public function setLine($line) { $this->line = $line; return $this; } public function getLine() { return $this->line; } public function getDisplayPath() { if ($this->path !== null) { return $this->path; } return $this->getBlobPath(); } public function getDisplayRefName() { if ($this->refName !== null) { return $this->refName; } return $this->getBlobRefName(); } public function getDisplayCommit() { if ($this->commit !== null) { return $this->commit; } return $this->getBlobCommit(); } public function getDisplayLine() { if ($this->line !== null) { return $this->line; } return $this->getBlobLine(); } private function getBlobPath() { return idx($this->getBlobMap(), 'path'); } private function getBlobRefName() { return idx($this->getBlobMap(), 'branch'); } private function getBlobLine() { return idx($this->getBlobMap(), 'line'); } private function getBlobCommit() { return idx($this->getBlobMap(), 'commit'); } private function getBlobMap() { if ($this->blobMap === null) { $repository = $this->getRepository(); $blob = $this->blob; if ($repository && ($blob !== null)) { $map = DiffusionRequest::parseRequestBlob( $blob, $repository->supportsRefs()); } else { $map = array(); } $this->blobMap = $map; } return $this->blobMap; } public function render() { $repository = $this->getRepository(); $uri = $this->getURI(); $color = 'blue'; $icon = 'fa-file-text-o'; $text = $this->getText(); if (!strlen($text)) { $path = $this->getDisplayPath(); $line = $this->getDisplayLine(); if ($line !== null) { $path = pht('%s:%s', $path, $line); } if ($repository) { $path = pht('%s %s', $repository->getMonogram(), $path); } if ($repository && $repository->supportsRefs()) { $default_ref = $repository->getDefaultBranch(); } else { $default_ref = null; } $ref_name = $this->getDisplayRefName(); if ($ref_name === $default_ref) { $ref_name = null; } $commit = $this->getDisplayCommit(); if ($ref_name !== null && $commit !== null) { $text = pht('%s (on %s at %s)', $path, $ref_name, $commit); } else if ($ref_name !== null) { $text = pht('%s (on %s)', $path, $ref_name); } else if ($commit !== null) { $text = pht('%s (at %s)', $path, $commit); } else { $text = $path; } } return id(new PHUITagView()) ->setType(PHUITagView::TYPE_SHADE) ->setColor($color) ->setIcon($icon) ->setHref($uri) ->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/view/DiffusionEmptyResultView.php
src/applications/diffusion/view/DiffusionEmptyResultView.php
<?php final class DiffusionEmptyResultView extends DiffusionView { private $browseResultSet; private $view; public function setDiffusionBrowseResultSet(DiffusionBrowseResultSet $set) { $this->browseResultSet = $set; return $this; } public function setView($view) { $this->view = $view; return $this; } public function render() { $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $commit = $drequest->getCommit(); if ($commit) { $commit = $repository->formatCommitName($commit); } else { $commit = 'HEAD'; } $reason = $this->browseResultSet->getReasonForEmptyResultSet(); switch ($reason) { case DiffusionBrowseResultSet::REASON_IS_NONEXISTENT: $title = pht('Path Does Not Exist'); // TODO: Under git, this error message should be more specific. It // may exist on some other branch. $body = pht('This path does not exist anywhere.'); $severity = PHUIInfoView::SEVERITY_ERROR; break; case DiffusionBrowseResultSet::REASON_IS_EMPTY: $title = pht('Empty Directory'); $body = pht('This path was an empty directory at %s.', $commit); $severity = PHUIInfoView::SEVERITY_NOTICE; break; case DiffusionBrowseResultSet::REASON_IS_SUBMODULE: $title = pht('Submodule'); // TODO: We could improve this, but it is normally difficult to // reach this page for a submodule. $body = pht('This path was a submodule at %s.', $commit); $severity = PHUIInfoView::SEVERITY_NOTICE; break; case DiffusionBrowseResultSet::REASON_IS_DELETED: $deleted = $this->browseResultSet->getDeletedAtCommit(); $existed = $this->browseResultSet->getExistedAtCommit(); $existed_text = $repository->formatCommitName($existed); $existed_href = $drequest->generateURI( array( 'action' => 'browse', 'path' => $drequest->getPath(), 'commit' => $existed, 'params' => array( 'view' => $this->view, ), )); $existed_link = phutil_tag( 'a', array( 'href' => $existed_href, ), $existed_text); $title = pht('Path Was Deleted'); $body = pht( 'This path does not exist at %s. It was deleted in %s and last '. 'existed at %s.', $commit, self::linkCommit($drequest->getRepository(), $deleted), $existed_link); $severity = PHUIInfoView::SEVERITY_WARNING; break; case DiffusionBrowseResultSet::REASON_IS_UNTRACKED_PARENT: $subdir = $drequest->getRepository()->getDetail('svn-subpath'); $title = pht('Directory Not Tracked'); $body = pht( "This repository is configured to track only one subdirectory ". "of the entire repository ('%s'), but you aren't looking at ". "something in that subdirectory, so no information is available.", $subdir); $severity = PHUIInfoView::SEVERITY_WARNING; break; default: throw new Exception(pht('Unknown failure reason: %s', $reason)); } $error_view = new PHUIInfoView(); $error_view->setSeverity($severity); $error_view->setTitle($title); $error_view->appendChild(phutil_tag('p', array(), $body)); return $error_view->render(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/view/DiffusionReadmeView.php
src/applications/diffusion/view/DiffusionReadmeView.php
<?php final class DiffusionReadmeView extends DiffusionView { private $path; private $content; public function setPath($path) { $this->path = $path; return $this; } public function getPath() { return $this->path; } public function setContent($content) { $this->content = $content; return $this; } public function getContent() { return $this->content; } /** * Get the markup language a README should be interpreted as. * * @param string Local README path, like "README.txt". * @return string Best markup interpreter (like "remarkup") for this file. */ private function getReadmeLanguage($path) { $path = phutil_utf8_strtolower($path); if ($path == 'readme') { return 'remarkup'; } $ext = last(explode('.', $path)); switch ($ext) { case 'remarkup': case 'md': return 'remarkup'; case 'rainbow': return 'rainbow'; case 'txt': default: return 'text'; } } public function render() { $readme_path = $this->getPath(); $readme_name = basename($readme_path); $interpreter = $this->getReadmeLanguage($readme_name); require_celerity_resource('diffusion-readme-css'); $content = $this->getContent(); $class = null; switch ($interpreter) { case 'remarkup': // TODO: This is sketchy, but make sure we hit the markup cache. $markup_object = id(new PhabricatorMarkupOneOff()) ->setEngineRuleset('diffusion-readme') ->setContent($content); $markup_field = 'default'; $content = id(new PhabricatorMarkupEngine()) ->setViewer($this->getUser()) ->addObject($markup_object, $markup_field) ->process() ->getOutput($markup_object, $markup_field); $engine = $markup_object->newMarkupEngine($markup_field); $readme_content = $content; $class = 'ml'; break; case 'rainbow': $content = id(new PhutilRainbowSyntaxHighlighter()) ->getHighlightFuture($content) ->resolve(); $readme_content = phutil_escape_html_newlines($content); require_celerity_resource('syntax-highlighting-css'); $class = 'remarkup-code ml'; break; default: case 'text': $readme_content = phutil_escape_html_newlines($content); $class = 'ml'; break; } $readme_content = phutil_tag( 'div', array( 'class' => $class, ), $readme_content); $header = id(new PHUIHeaderView()) ->setHeader($readme_name) ->addClass('diffusion-panel-header-view'); return id(new PHUIObjectBoxView()) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->addClass('diffusion-mobile-view') ->appendChild($readme_content) ->addClass('diffusion-readme-view'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/editfield/DiffusionIdentityAssigneeEditField.php
src/applications/diffusion/editfield/DiffusionIdentityAssigneeEditField.php
<?php final class DiffusionIdentityAssigneeEditField extends PhabricatorTokenizerEditField { protected function newDatasource() { return new DiffusionIdentityAssigneeDatasource(); } protected function newHTTPParameterType() { return new AphrontUserListHTTPParameterType(); } protected function newConduitParameterType() { if ($this->getIsSingleValue()) { return new ConduitUserParameterType(); } else { return new ConduitUserListParameterType(); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/edge/DiffusionCommitRevertedByCommitEdgeType.php
src/applications/diffusion/edge/DiffusionCommitRevertedByCommitEdgeType.php
<?php final class DiffusionCommitRevertedByCommitEdgeType extends PhabricatorEdgeType { const EDGECONST = 56; public function getInverseEdgeConstant() { return DiffusionCommitRevertsCommitEdgeType::EDGECONST; } public function shouldWriteInverseTransactions() { return true; } public function getTransactionAddString( $actor, $add_count, $add_edges) { return pht( '%s added %s reverting change(s): %s.', $actor, $add_count, $add_edges); } public function getTransactionRemoveString( $actor, $rem_count, $rem_edges) { return pht( '%s removed %s reverting change(s): %s.', $actor, $rem_count, $rem_edges); } public function getTransactionEditString( $actor, $total_count, $add_count, $add_edges, $rem_count, $rem_edges) { return pht( '%s edited reverting change(s), added %s: %s; removed %s: %s.', $actor, $add_count, $add_edges, $rem_count, $rem_edges); } public function getFeedAddString( $actor, $object, $add_count, $add_edges) { return pht( '%s added %s reverting change(s) for %s: %s.', $actor, $add_count, $object, $add_edges); } public function getFeedRemoveString( $actor, $object, $rem_count, $rem_edges) { return pht( '%s removed %s reverting change(s) for %s: %s.', $actor, $rem_count, $object, $rem_edges); } public function getFeedEditString( $actor, $object, $total_count, $add_count, $add_edges, $rem_count, $rem_edges) { return pht( '%s edited reverting change(s) for %s, added %s: %s; removed %s: %s.', $actor, $object, $add_count, $add_edges, $rem_count, $rem_edges); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/edge/DiffusionCommitHasPackageEdgeType.php
src/applications/diffusion/edge/DiffusionCommitHasPackageEdgeType.php
<?php final class DiffusionCommitHasPackageEdgeType extends PhabricatorEdgeType { const EDGECONST = 65; }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/edge/DiffusionCommitHasRevisionEdgeType.php
src/applications/diffusion/edge/DiffusionCommitHasRevisionEdgeType.php
<?php final class DiffusionCommitHasRevisionEdgeType extends PhabricatorEdgeType { const EDGECONST = 32; public function getInverseEdgeConstant() { return DifferentialRevisionHasCommitEdgeType::EDGECONST; } public function shouldWriteInverseTransactions() { return true; } public function getConduitKey() { return 'commit.revision'; } public function getConduitName() { return pht('Commit Has Revision'); } public function getConduitDescription() { return pht( 'The source commit is associated with the destination revision.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/edge/DiffusionCommitHasTaskEdgeType.php
src/applications/diffusion/edge/DiffusionCommitHasTaskEdgeType.php
<?php final class DiffusionCommitHasTaskEdgeType extends PhabricatorEdgeType { const EDGECONST = 2; public function shouldWriteInverseTransactions() { return true; } public function getInverseEdgeConstant() { return ManiphestTaskHasCommitEdgeType::EDGECONST; } public function getConduitKey() { return 'commit.task'; } public function getConduitName() { return pht('Commit Has Task'); } public function getConduitDescription() { return pht('The source commit is associated with the destination task.'); } public function getTransactionAddString( $actor, $add_count, $add_edges) { return pht( '%s added %s task(s): %s.', $actor, $add_count, $add_edges); } public function getTransactionRemoveString( $actor, $rem_count, $rem_edges) { return pht( '%s removed %s task(s): %s.', $actor, $rem_count, $rem_edges); } public function getTransactionEditString( $actor, $total_count, $add_count, $add_edges, $rem_count, $rem_edges) { return pht( '%s edited %s task(s), added %s: %s; removed %s: %s.', $actor, $total_count, $add_count, $add_edges, $rem_count, $rem_edges); } public function getFeedAddString( $actor, $object, $add_count, $add_edges) { return pht( '%s added %s task(s) to %s: %s.', $actor, $add_count, $object, $add_edges); } public function getFeedRemoveString( $actor, $object, $rem_count, $rem_edges) { return pht( '%s removed %s task(s) from %s: %s.', $actor, $rem_count, $object, $rem_edges); } public function getFeedEditString( $actor, $object, $total_count, $add_count, $add_edges, $rem_count, $rem_edges) { return pht( '%s edited %s task(s) for %s, added %s: %s; removed %s: %s.', $actor, $total_count, $object, $add_count, $add_edges, $rem_count, $rem_edges); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/edge/DiffusionCommitRevertsCommitEdgeType.php
src/applications/diffusion/edge/DiffusionCommitRevertsCommitEdgeType.php
<?php final class DiffusionCommitRevertsCommitEdgeType extends PhabricatorEdgeType { const EDGECONST = 55; public function getInverseEdgeConstant() { return DiffusionCommitRevertedByCommitEdgeType::EDGECONST; } public function shouldWriteInverseTransactions() { return true; } public function shouldPreventCycles() { return true; } public function getTransactionAddString( $actor, $add_count, $add_edges) { return pht( '%s added %s reverted change(s): %s.', $actor, $add_count, $add_edges); } public function getTransactionRemoveString( $actor, $rem_count, $rem_edges) { return pht( '%s removed %s reverted change(s): %s.', $actor, $rem_count, $rem_edges); } public function getTransactionEditString( $actor, $total_count, $add_count, $add_edges, $rem_count, $rem_edges) { return pht( '%s edited reverted change(s), added %s: %s; removed %s: %s.', $actor, $add_count, $add_edges, $rem_count, $rem_edges); } public function getFeedAddString( $actor, $object, $add_count, $add_edges) { return pht( '%s added %s reverted change(s) for %s: %s.', $actor, $add_count, $object, $add_edges); } public function getFeedRemoveString( $actor, $object, $rem_count, $rem_edges) { return pht( '%s removed %s reverted change(s) for %s: %s.', $actor, $rem_count, $object, $rem_edges); } public function getFeedEditString( $actor, $object, $total_count, $add_count, $add_edges, $rem_count, $rem_edges) { return pht( '%s edited reverted change(s) for %s, added %s: %s; removed %s: %s.', $actor, $object, $add_count, $add_edges, $rem_count, $rem_edges); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/herald/DiffusionAuditorsAddSelfHeraldAction.php
src/applications/diffusion/herald/DiffusionAuditorsAddSelfHeraldAction.php
<?php final class DiffusionAuditorsAddSelfHeraldAction extends DiffusionAuditorsHeraldAction { const ACTIONCONST = 'diffusion.auditors.self.add'; public function getHeraldActionName() { return pht('Add me as an auditor'); } public function supportsRuleType($rule_type) { return ($rule_type == HeraldRuleTypeConfig::RULE_TYPE_PERSONAL); } public function applyEffect($object, HeraldEffect $effect) { $rule = $effect->getRule(); $phid = $rule->getAuthorPHID(); return $this->applyAuditors(array($phid), $rule); } public function getHeraldActionStandardType() { return self::STANDARD_NONE; } public function renderActionDescription($value) { return pht('Add rule author as auditor.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/herald/HeraldCommitAdapter.php
src/applications/diffusion/herald/HeraldCommitAdapter.php
<?php final class HeraldCommitAdapter extends HeraldAdapter implements HarbormasterBuildableAdapterInterface { protected $diff; protected $revision; protected $commit; private $commitDiff; protected $affectedPaths; protected $affectedRevision; protected $affectedPackages; protected $auditNeededPackages; private $buildRequests = array(); public function getAdapterApplicationClass() { return 'PhabricatorDiffusionApplication'; } protected function newObject() { return new PhabricatorRepositoryCommit(); } public function isTestAdapterForObject($object) { return ($object instanceof PhabricatorRepositoryCommit); } public function getAdapterTestDescription() { return pht( 'Test rules which run after a commit is discovered and imported.'); } public function newTestAdapter(PhabricatorUser $viewer, $object) { return id(clone $this) ->setObject($object); } protected function initializeNewAdapter() { $this->commit = $this->newObject(); } public function setObject($object) { $viewer = $this->getViewer(); $commit_phid = $object->getPHID(); $commit = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withPHIDs(array($commit_phid)) ->needCommitData(true) ->needIdentities(true) ->needAuditRequests(true) ->executeOne(); if (!$commit) { throw new Exception( pht( 'Failed to reload commit ("%s") to fetch commit data.', $commit_phid)); } $this->commit = $commit; return $this; } public function getObject() { return $this->commit; } public function getAdapterContentType() { return 'commit'; } public function getAdapterContentName() { return pht('Commits'); } public function getAdapterContentDescription() { return pht( "React to new commits appearing in tracked repositories.\n". "Commit rules can send email, flag commits, trigger audits, ". "and run build plans."); } public function supportsRuleType($rule_type) { switch ($rule_type) { case HeraldRuleTypeConfig::RULE_TYPE_GLOBAL: case HeraldRuleTypeConfig::RULE_TYPE_PERSONAL: case HeraldRuleTypeConfig::RULE_TYPE_OBJECT: return true; default: return false; } } public function canTriggerOnObject($object) { if ($object instanceof PhabricatorRepository) { return true; } if ($object instanceof PhabricatorProject) { return true; } return false; } public function getTriggerObjectPHIDs() { $project_type = PhabricatorProjectObjectHasProjectEdgeType::EDGECONST; $repository_phid = $this->getRepository()->getPHID(); $commit_phid = $this->getObject()->getPHID(); $phids = array(); $phids[] = $commit_phid; $phids[] = $repository_phid; // NOTE: This is projects for the repository, not for the commit. When // Herald evaluates, commits normally can not have any project tags yet. $repository_project_phids = PhabricatorEdgeQuery::loadDestinationPHIDs( $repository_phid, $project_type); foreach ($repository_project_phids as $phid) { $phids[] = $phid; } $phids = array_unique($phids); $phids = array_values($phids); return $phids; } public function explainValidTriggerObjects() { return pht('This rule can trigger for **repositories** and **projects**.'); } public function getHeraldName() { return $this->commit->getMonogram(); } public function loadAffectedPaths() { $viewer = $this->getViewer(); if ($this->affectedPaths === null) { $result = PhabricatorOwnerPathQuery::loadAffectedPaths( $this->getRepository(), $this->commit, $viewer); $this->affectedPaths = $result; } return $this->affectedPaths; } public function loadAffectedPackages() { if ($this->affectedPackages === null) { $packages = PhabricatorOwnersPackage::loadAffectedPackages( $this->getRepository(), $this->loadAffectedPaths()); $this->affectedPackages = $packages; } return $this->affectedPackages; } public function loadAuditNeededPackages() { if ($this->auditNeededPackages === null) { $status_arr = array( PhabricatorAuditRequestStatus::AUDIT_REQUIRED, PhabricatorAuditRequestStatus::CONCERNED, ); $requests = id(new PhabricatorRepositoryAuditRequest()) ->loadAllWhere( 'commitPHID = %s AND auditStatus IN (%Ls)', $this->commit->getPHID(), $status_arr); $this->auditNeededPackages = $requests; } return $this->auditNeededPackages; } public function loadDifferentialRevision() { if ($this->affectedRevision === null) { $viewer = $this->getViewer(); // NOTE: The viewer here is omnipotent, which means that Herald discloses // some information users do not normally have access to when rules load // the revision related to a commit. See D20468. // A user who wants to learn about "Dxyz" can write a Herald rule which // uses all the "Related revision..." fields, then push a commit which // contains "Differential Revision: Dxyz" in the message to make Herald // evaluate the commit with "Dxyz" as the related revision. // At time of writing, this commit will link to the revision and the // transcript for the commit will disclose some information about the // revision (like reviewers, subscribers, and build status) which the // commit author could not otherwise see. // For now, we just accept this. The disclosures are relatively // uninteresting and you have to jump through a lot of hoops (and leave // a lot of evidence) to get this information. $revision = DiffusionCommitRevisionQuery::loadRevisionForCommit( $viewer, $this->getObject()); if ($revision) { $this->affectedRevision = $revision; } else { $this->affectedRevision = false; } } return $this->affectedRevision; } public static function getEnormousByteLimit() { return 256 * 1024 * 1024; // 256MB. See T13142 and T13143. } public static function getEnormousTimeLimit() { return 60 * 15; // 15 Minutes } private function loadCommitDiff() { $viewer = $this->getViewer(); $byte_limit = self::getEnormousByteLimit(); $time_limit = self::getEnormousTimeLimit(); $diff_info = $this->callConduit( 'diffusion.rawdiffquery', array( 'commit' => $this->commit->getCommitIdentifier(), 'timeout' => $time_limit, 'byteLimit' => $byte_limit, 'linesOfContext' => 0, )); if ($diff_info['tooHuge']) { throw new Exception( pht( 'The raw text of this change is enormous (larger than %s byte(s)). '. 'Herald can not process it.', new PhutilNumber($byte_limit))); } if ($diff_info['tooSlow']) { throw new Exception( pht( 'The raw text of this change took too long to process (longer '. 'than %s second(s)). Herald can not process it.', new PhutilNumber($time_limit))); } $file_phid = $diff_info['filePHID']; $diff_file = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withPHIDs(array($file_phid)) ->executeOne(); if (!$diff_file) { throw new Exception( pht( 'Failed to load diff ("%s") for this change.', $file_phid)); } $raw = $diff_file->loadFileData(); // See T13667. This happens when a commit is empty and affects no files. if (!strlen($raw)) { return false; } $parser = new ArcanistDiffParser(); $changes = $parser->parseDiff($raw); $diff = DifferentialDiff::newEphemeralFromRawChanges( $changes); return $diff; } public function isDiffEnormous() { $this->loadDiffContent('*'); return ($this->commitDiff instanceof Exception); } public function loadDiffContent($type) { if ($this->commitDiff === null) { try { $this->commitDiff = $this->loadCommitDiff(); } catch (Exception $ex) { $this->commitDiff = $ex; phlog($ex); } } if ($this->commitDiff === false) { return array(); } if ($this->commitDiff instanceof Exception) { $ex = $this->commitDiff; $ex_class = get_class($ex); $ex_message = pht('Failed to load changes: %s', $ex->getMessage()); return array( '<'.$ex_class.'>' => $ex_message, ); } $changes = $this->commitDiff->getChangesets(); $result = array(); foreach ($changes as $change) { $lines = array(); foreach ($change->getHunks() as $hunk) { switch ($type) { case '-': $lines[] = $hunk->makeOldFile(); break; case '+': $lines[] = $hunk->makeNewFile(); break; case '*': $lines[] = $hunk->makeChanges(); break; default: throw new Exception(pht("Unknown content selection '%s'!", $type)); } } $result[$change->getFilename()] = implode("\n", $lines); } return $result; } public function loadIsMergeCommit() { $parents = $this->callConduit( 'diffusion.commitparentsquery', array( 'commit' => $this->getObject()->getCommitIdentifier(), )); return (count($parents) > 1); } private function callConduit($method, array $params) { $viewer = $this->getViewer(); $drequest = DiffusionRequest::newFromDictionary( array( 'user' => $viewer, 'repository' => $this->getRepository(), 'commit' => $this->commit->getCommitIdentifier(), )); return DiffusionQuery::callConduitWithDiffusionRequest( $viewer, $drequest, $method, $params); } private function getRepository() { return $this->getObject()->getRepository(); } public function getAuthorPHID() { return $this->getObject()->getEffectiveAuthorPHID(); } public function getCommitterPHID() { $commit = $this->getObject(); if ($commit->hasCommitterIdentity()) { $identity = $commit->getCommitterIdentity(); return $identity->getCurrentEffectiveUserPHID(); } return null; } /* -( HarbormasterBuildableAdapterInterface )------------------------------ */ public function getHarbormasterBuildablePHID() { return $this->getObject()->getPHID(); } public function getHarbormasterContainerPHID() { return $this->getObject()->getRepository()->getPHID(); } public function getQueuedHarbormasterBuildRequests() { return $this->buildRequests; } public function queueHarbormasterBuildRequest( HarbormasterBuildRequest $request) { $this->buildRequests[] = $request; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/herald/DiffusionPreCommitContentPackageHeraldField.php
src/applications/diffusion/herald/DiffusionPreCommitContentPackageHeraldField.php
<?php final class DiffusionPreCommitContentPackageHeraldField extends DiffusionPreCommitContentHeraldField { const FIELDCONST = 'diffusion.pre.content.package'; public function getHeraldFieldName() { return pht('Affected packages'); } public function getFieldGroupKey() { return HeraldRelatedFieldGroup::FIELDGROUPKEY; } public function getHeraldFieldValue($object) { $packages = $this->getAdapter()->loadAffectedPackages(); return mpull($packages, 'getPHID'); } protected function getHeraldFieldStandardType() { return self::STANDARD_PHID_LIST; } protected function getDatasource() { return 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/herald/DiffusionCommitHeraldField.php
src/applications/diffusion/herald/DiffusionCommitHeraldField.php
<?php abstract class DiffusionCommitHeraldField extends HeraldField { public function supportsObject($object) { return ($object instanceof PhabricatorRepositoryCommit); } public function getFieldGroupKey() { return DiffusionCommitHeraldFieldGroup::FIELDGROUPKEY; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false