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/repository/management/PhabricatorRepositoryManagementMarkImportedWorkflow.php | src/applications/repository/management/PhabricatorRepositoryManagementMarkImportedWorkflow.php | <?php
final class PhabricatorRepositoryManagementMarkImportedWorkflow
extends PhabricatorRepositoryManagementWorkflow {
protected function didConstruct() {
$this
->setName('mark-imported')
->setExamples('**mark-imported** __repository__ ...')
->setSynopsis(pht('Mark __repository__ as imported.'))
->setArguments(
array(
array(
'name' => 'mark-not-imported',
'help' => pht('Instead, mark repositories as NOT imported.'),
),
array(
'name' => 'repos',
'wildcard' => true,
),
));
}
public function execute(PhutilArgumentParser $args) {
$repos = $this->loadRepositories($args, 'repos');
if (!$repos) {
throw new PhutilArgumentUsageException(
pht('Specify one or more repositories to mark imported.'));
}
$new_importing_value = (bool)$args->getArg('mark-not-imported');
$console = PhutilConsole::getConsole();
foreach ($repos as $repo) {
$name = $repo->getDisplayName();
if ($repo->isImporting() && $new_importing_value) {
$console->writeOut(
"%s\n",
pht(
'Repository "%s" is already importing.',
$name));
} else if (!$repo->isImporting() && !$new_importing_value) {
$console->writeOut(
"%s\n",
pht(
'Repository "%s" is already imported.',
$name));
} else {
if ($new_importing_value) {
$console->writeOut(
"%s\n",
pht(
'Marking repository "%s" as importing.',
$name));
} else {
$console->writeOut(
"%s\n",
pht(
'Marking repository "%s" as imported.',
$name));
}
$repo->setDetail('importing', $new_importing_value);
$repo->save();
}
}
$console->writeOut("%s\n", pht('Done.'));
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/repository/management/PhabricatorRepositoryManagementUpdateWorkflow.php | src/applications/repository/management/PhabricatorRepositoryManagementUpdateWorkflow.php | <?php
final class PhabricatorRepositoryManagementUpdateWorkflow
extends PhabricatorRepositoryManagementWorkflow {
private $verbose;
public function setVerbose($verbose) {
$this->verbose = $verbose;
return $this;
}
public function getVerbose() {
return $this->verbose;
}
protected function didConstruct() {
$this
->setName('update')
->setExamples('**update** [options] __repository__')
->setSynopsis(
pht(
'Update __repository__. This performs the __pull__, __discover__, '.
'__refs__ and __mirror__ operations and is primarily an internal '.
'workflow.'))
->setArguments(
array(
array(
'name' => 'verbose',
'help' => pht('Show additional debugging information.'),
),
array(
'name' => 'no-discovery',
'help' => pht('Do not perform discovery.'),
),
array(
'name' => 'repos',
'wildcard' => true,
),
));
}
public function execute(PhutilArgumentParser $args) {
$this->setVerbose($args->getArg('verbose'));
$console = PhutilConsole::getConsole();
$repos = $this->loadLocalRepositories($args, 'repos');
if (count($repos) !== 1) {
throw new PhutilArgumentUsageException(
pht('Specify exactly one repository to update.'));
}
$repository = head($repos);
try {
id(new PhabricatorRepositoryPullEngine())
->setRepository($repository)
->setVerbose($this->getVerbose())
->pullRepository();
$no_discovery = $args->getArg('no-discovery');
if ($no_discovery) {
return 0;
}
// TODO: It would be nice to discover only if we pulled something, but
// this isn't totally trivial. It's slightly more complicated with
// hosted repositories, too.
$repository->writeStatusMessage(
PhabricatorRepositoryStatusMessage::TYPE_NEEDS_UPDATE,
null);
$this->discoverRepository($repository);
$this->checkIfRepositoryIsFullyImported($repository);
$this->updateRepositoryRefs($repository);
$this->mirrorRepository($repository);
$repository->writeStatusMessage(
PhabricatorRepositoryStatusMessage::TYPE_FETCH,
PhabricatorRepositoryStatusMessage::CODE_OKAY);
} catch (DiffusionDaemonLockException $ex) {
// If we miss a pull or discover because some other process is already
// doing the work, just bail out.
echo tsprintf(
"%s\n",
$ex->getMessage());
return 0;
} catch (Exception $ex) {
$repository->writeStatusMessage(
PhabricatorRepositoryStatusMessage::TYPE_FETCH,
PhabricatorRepositoryStatusMessage::CODE_ERROR,
array(
'message' => pht(
'Error updating working copy: %s', $ex->getMessage()),
));
throw $ex;
}
echo tsprintf(
"%s\n",
pht(
'Updated repository "%s".',
$repository->getDisplayName()));
return 0;
}
private function discoverRepository(PhabricatorRepository $repository) {
$refs = id(new PhabricatorRepositoryDiscoveryEngine())
->setRepository($repository)
->setVerbose($this->getVerbose())
->discoverCommits();
return (bool)count($refs);
}
private function mirrorRepository(PhabricatorRepository $repository) {
try {
id(new PhabricatorRepositoryMirrorEngine())
->setRepository($repository)
->pushToMirrors();
} catch (Exception $ex) {
// TODO: We should report these into the UI properly, but for now just
// complain. These errors are much less severe than pull errors.
$proxy = new PhutilProxyException(
pht(
'Error while pushing "%s" repository to mirrors.',
$repository->getMonogram()),
$ex);
phlog($proxy);
}
}
private function updateRepositoryRefs(PhabricatorRepository $repository) {
id(new PhabricatorRepositoryRefEngine())
->setRepository($repository)
->updateRefs();
}
private function checkIfRepositoryIsFullyImported(
PhabricatorRepository $repository) {
// Check if the repository has the "Importing" flag set. We want to clear
// the flag if we can.
$importing = $repository->getDetail('importing');
if (!$importing) {
// This repository isn't marked as "Importing", so we're done.
return;
}
// Look for any commit which is reachable and hasn't imported.
$unparsed_commit = queryfx_one(
$repository->establishConnection('r'),
'SELECT * FROM %T WHERE repositoryID = %d
AND (importStatus & %d) != %d
AND (importStatus & %d) != %d
LIMIT 1',
id(new PhabricatorRepositoryCommit())->getTableName(),
$repository->getID(),
PhabricatorRepositoryCommit::IMPORTED_ALL,
PhabricatorRepositoryCommit::IMPORTED_ALL,
PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE,
PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE);
if ($unparsed_commit) {
// We found a commit which still needs to import, so we can't clear the
// flag.
return;
}
// Clear the "importing" flag.
$repository->openTransaction();
$repository->beginReadLocking();
$repository = $repository->reload();
$repository->setDetail('importing', false);
$repository->save();
$repository->endReadLocking();
$repository->saveTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementRebuildIdentitiesWorkflow.php | src/applications/repository/management/PhabricatorRepositoryManagementRebuildIdentitiesWorkflow.php | <?php
final class PhabricatorRepositoryManagementRebuildIdentitiesWorkflow
extends PhabricatorRepositoryManagementWorkflow {
private $identityCache = array();
private $phidCache = array();
private $dryRun;
protected function didConstruct() {
$this
->setName('rebuild-identities')
->setExamples(
'**rebuild-identities** [__options__] __repository__')
->setSynopsis(pht('Rebuild repository identities from commits.'))
->setArguments(
array(
array(
'name' => 'all-repositories',
'help' => pht('Rebuild identities across all repositories.'),
),
array(
'name' => 'all-identities',
'help' => pht('Rebuild all currently-known identities.'),
),
array(
'name' => 'repository',
'param' => 'repository',
'repeat' => true,
'help' => pht('Rebuild identities in a repository.'),
),
array(
'name' => 'commit',
'param' => 'commit',
'repeat' => true,
'help' => pht('Rebuild identities for a commit.'),
),
array(
'name' => 'user',
'param' => 'user',
'repeat' => true,
'help' => pht('Rebuild identities for a user.'),
),
array(
'name' => 'email',
'param' => 'email',
'repeat' => true,
'help' => pht('Rebuild identities for an email address.'),
),
array(
'name' => 'raw',
'param' => 'raw',
'repeat' => true,
'help' => pht('Rebuild identities for a raw commit string.'),
),
array(
'name' => 'dry-run',
'help' => pht('Show changes, but do not make any changes.'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$rebuilt_anything = false;
$all_repositories = $args->getArg('all-repositories');
$repositories = $args->getArg('repository');
if ($all_repositories && $repositories) {
throw new PhutilArgumentUsageException(
pht(
'Flags "--all-repositories" and "--repository" are not '.
'compatible.'));
}
$all_identities = $args->getArg('all-identities');
$raw = $args->getArg('raw');
if ($all_identities && $raw) {
throw new PhutilArgumentUsageException(
pht(
'Flags "--all-identities" and "--raw" are not '.
'compatible.'));
}
$dry_run = $args->getArg('dry-run');
$this->dryRun = $dry_run;
if ($this->dryRun) {
$this->logWarn(
pht('DRY RUN'),
pht('This is a dry run, so no changes will be written.'));
}
if ($all_repositories || $repositories) {
$rebuilt_anything = true;
if ($repositories) {
$repository_list = $this->loadRepositories($args, 'repository');
} else {
$repository_query = id(new PhabricatorRepositoryQuery())
->setViewer($viewer);
$repository_list = new PhabricatorQueryIterator($repository_query);
}
foreach ($repository_list as $repository) {
$commit_query = id(new DiffusionCommitQuery())
->setViewer($viewer)
->needCommitData(true)
->withRepositoryIDs(array($repository->getID()));
// See T13457. Adjust ordering to hit keys better and tweak page size
// to improve performance slightly, since these records are small.
$commit_query->setOrderVector(array('-epoch', '-id'));
$commit_iterator = id(new PhabricatorQueryIterator($commit_query))
->setPageSize(1000);
$this->rebuildCommits($commit_iterator);
}
}
$commits = $args->getArg('commit');
if ($commits) {
$rebuilt_anything = true;
$commit_list = $this->loadCommits($args, 'commit');
// Reload commits to get commit data.
$commit_list = id(new DiffusionCommitQuery())
->setViewer($viewer)
->needCommitData(true)
->withIDs(mpull($commit_list, 'getID'))
->execute();
$this->rebuildCommits($commit_list);
}
$users = $args->getArg('user');
if ($users) {
$rebuilt_anything = true;
$user_list = $this->loadUsersFromArguments($users);
$this->rebuildUsers($user_list);
}
$emails = $args->getArg('email');
if ($emails) {
$rebuilt_anything = true;
$this->rebuildEmails($emails);
}
if ($all_identities || $raw) {
$rebuilt_anything = true;
if ($raw) {
$identities = id(new PhabricatorRepositoryIdentityQuery())
->setViewer($viewer)
->withIdentityNames($raw)
->execute();
$identities = mpull($identities, null, 'getIdentityNameRaw');
foreach ($raw as $raw_identity) {
if (!isset($identities[$raw_identity])) {
throw new PhutilArgumentUsageException(
pht(
'No identity "%s" exists. When selecting identities with '.
'"--raw", the entire identity must match exactly.',
$raw_identity));
}
}
$identity_list = $identities;
} else {
$identity_query = id(new PhabricatorRepositoryIdentityQuery())
->setViewer($viewer);
$identity_list = new PhabricatorQueryIterator($identity_query);
$this->logInfo(
pht('REBUILD'),
pht('Rebuilding all existing identities.'));
}
$this->rebuildIdentities($identity_list);
}
if (!$rebuilt_anything) {
throw new PhutilArgumentUsageException(
pht(
'Nothing specified to rebuild. Use flags to choose which '.
'identities to rebuild, or "--help" for help.'));
}
return 0;
}
private function rebuildCommits($commits) {
foreach ($commits as $commit) {
$needs_update = false;
$data = $commit->getCommitData();
$author = $data->getAuthorString();
$author_identity = $this->getIdentityForCommit(
$commit,
$author);
$author_phid = $commit->getAuthorIdentityPHID();
$identity_phid = $author_identity->getPHID();
$aidentity_phid = $identity_phid;
if ($author_phid !== $identity_phid) {
$commit->setAuthorIdentityPHID($identity_phid);
$data->setCommitDetail('authorIdentityPHID', $identity_phid);
$needs_update = true;
}
$committer_name = $data->getCommitterString();
$committer_phid = $commit->getCommitterIdentityPHID();
if (phutil_nonempty_string($committer_name)) {
$committer_identity = $this->getIdentityForCommit(
$commit,
$committer_name);
$identity_phid = $committer_identity->getPHID();
} else {
$identity_phid = null;
}
if ($committer_phid !== $identity_phid) {
$commit->setCommitterIdentityPHID($identity_phid);
$data->setCommitDetail('committerIdentityPHID', $identity_phid);
$needs_update = true;
}
if ($needs_update) {
$commit->save();
$data->save();
$this->logInfo(
pht('COMMIT'),
pht(
'Rebuilt identities for "%s".',
$commit->getDisplayName()));
} else {
$this->logInfo(
pht('SKIP'),
pht(
'No changes for commit "%s".',
$commit->getDisplayName()));
}
}
}
private function getIdentityForCommit(
PhabricatorRepositoryCommit $commit,
$raw_identity) {
if (!isset($this->identityCache[$raw_identity])) {
$identity = $this->newIdentityEngine()
->setSourcePHID($commit->getPHID())
->newResolvedIdentity($raw_identity);
$this->identityCache[$raw_identity] = $identity;
}
return $this->identityCache[$raw_identity];
}
private function rebuildUsers($users) {
$viewer = $this->getViewer();
foreach ($users as $user) {
$this->logInfo(
pht('USER'),
pht(
'Rebuilding identities for user "%s".',
$user->getMonogram()));
$emails = id(new PhabricatorUserEmail())->loadAllWhere(
'userPHID = %s',
$user->getPHID());
if ($emails) {
$this->rebuildEmails(mpull($emails, 'getAddress'));
}
$identities = id(new PhabricatorRepositoryIdentityQuery())
->setViewer($viewer)
->withRelatedPHIDs(array($user->getPHID()))
->execute();
if (!$identities) {
$this->logWarn(
pht('NO IDENTITIES'),
pht('Found no identities directly related to user.'));
continue;
}
$this->rebuildIdentities($identities);
}
}
private function rebuildEmails($emails) {
$viewer = $this->getViewer();
foreach ($emails as $email) {
$this->logInfo(
pht('EMAIL'),
pht('Rebuilding identities for email address "%s".', $email));
$identities = id(new PhabricatorRepositoryIdentityQuery())
->setViewer($viewer)
->withEmailAddresses(array($email))
->execute();
if (!$identities) {
$this->logWarn(
pht('NO IDENTITIES'),
pht('Found no identities for email address "%s".', $email));
continue;
}
$this->rebuildIdentities($identities);
}
}
private function rebuildIdentities($identities) {
$dry_run = $this->dryRun;
foreach ($identities as $identity) {
$raw_identity = $identity->getIdentityName();
if (isset($this->identityCache[$raw_identity])) {
$this->logInfo(
pht('SKIP'),
pht(
'Identity "%s" has already been rebuilt.',
$raw_identity));
continue;
}
$this->logInfo(
pht('IDENTITY'),
pht(
'Rebuilding identity "%s".',
$raw_identity));
$old_auto = $identity->getAutomaticGuessedUserPHID();
$old_assign = $identity->getManuallySetUserPHID();
$identity = $this->newIdentityEngine()
->newUpdatedIdentity($identity);
$this->identityCache[$raw_identity] = $identity;
$new_auto = $identity->getAutomaticGuessedUserPHID();
$new_assign = $identity->getManuallySetUserPHID();
$same_auto = ($old_auto === $new_auto);
$same_assign = ($old_assign === $new_assign);
if ($same_auto && $same_assign) {
$this->logInfo(
pht('UNCHANGED'),
pht('No changes to identity.'));
} else {
if (!$same_auto) {
if ($dry_run) {
$this->logWarn(
pht('DETECTED PHID'),
pht(
'(Dry Run) Would update detected user from "%s" to "%s".',
$this->renderPHID($old_auto),
$this->renderPHID($new_auto)));
} else {
$this->logWarn(
pht('DETECTED PHID'),
pht(
'Detected user updated from "%s" to "%s".',
$this->renderPHID($old_auto),
$this->renderPHID($new_auto)));
}
}
if (!$same_assign) {
if ($dry_run) {
$this->logWarn(
pht('ASSIGNED PHID'),
pht(
'(Dry Run) Would update assigned user from "%s" to "%s".',
$this->renderPHID($old_assign),
$this->renderPHID($new_assign)));
} else {
$this->logWarn(
pht('ASSIGNED PHID'),
pht(
'Assigned user updated from "%s" to "%s".',
$this->renderPHID($old_assign),
$this->renderPHID($new_assign)));
}
}
}
}
}
private function renderPHID($phid) {
if ($phid == null) {
return pht('NULL');
}
if (!isset($this->phidCache[$phid])) {
$viewer = $this->getViewer();
$handles = $viewer->loadHandles(array($phid));
$this->phidCache[$phid] = pht(
'%s <%s>',
$handles[$phid]->getFullName(),
$phid);
}
return $this->phidCache[$phid];
}
private function newIdentityEngine() {
$viewer = $this->getViewer();
return id(new DiffusionRepositoryIdentityEngine())
->setViewer($viewer)
->setDryRun($this->dryRun);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementWorkflow.php | src/applications/repository/management/PhabricatorRepositoryManagementWorkflow.php | <?php
abstract class PhabricatorRepositoryManagementWorkflow
extends PhabricatorManagementWorkflow {
protected function loadRepositories(PhutilArgumentParser $args, $param) {
$identifiers = $args->getArg($param);
if (!$identifiers) {
return array();
}
$query = id(new PhabricatorRepositoryQuery())
->setViewer($this->getViewer())
->needURIs(true)
->withIdentifiers($identifiers);
$query->execute();
$map = $query->getIdentifierMap();
foreach ($identifiers as $identifier) {
if (empty($map[$identifier])) {
throw new PhutilArgumentUsageException(
pht(
'Repository "%s" does not exist!',
$identifier));
}
}
// Reorder repositories according to argument order.
$repositories = array_select_keys($map, $identifiers);
return array_values($repositories);
}
protected function loadLocalRepositories(
PhutilArgumentParser $args,
$param,
$ignore_locality = false) {
$repositories = $this->loadRepositories($args, $param);
if (!$repositories) {
return $repositories;
}
if ($ignore_locality) {
return $repositories;
}
$device = AlmanacKeys::getLiveDevice();
$viewer = $this->getViewer();
$filter = id(new DiffusionLocalRepositoryFilter())
->setViewer($viewer)
->setDevice($device)
->setRepositories($repositories);
$repositories = $filter->execute();
foreach ($filter->getRejectionReasons() as $reason) {
throw new PhutilArgumentUsageException($reason);
}
return $repositories;
}
protected function loadCommits(PhutilArgumentParser $args, $param) {
$names = $args->getArg($param);
if (!$names) {
return null;
}
return $this->loadNamedCommits($names);
}
protected function loadNamedCommit($name) {
$map = $this->loadNamedCommits(array($name));
return $map[$name];
}
protected function loadNamedCommits(array $names) {
$query = id(new DiffusionCommitQuery())
->setViewer($this->getViewer())
->withIdentifiers($names);
$query->execute();
$map = $query->getIdentifierMap();
foreach ($names as $name) {
if (empty($map[$name])) {
throw new PhutilArgumentUsageException(
pht('Commit "%s" does not exist or is ambiguous.', $name));
}
}
return $map;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementMirrorWorkflow.php | src/applications/repository/management/PhabricatorRepositoryManagementMirrorWorkflow.php | <?php
final class PhabricatorRepositoryManagementMirrorWorkflow
extends PhabricatorRepositoryManagementWorkflow {
protected function didConstruct() {
$this
->setName('mirror')
->setExamples('**mirror** [__options__] __repository__ ...')
->setSynopsis(
pht('Push __repository__ to mirrors.'))
->setArguments(
array(
array(
'name' => 'verbose',
'help' => pht('Show additional debugging information.'),
),
array(
'name' => 'repos',
'wildcard' => true,
),
));
}
public function execute(PhutilArgumentParser $args) {
$repos = $this->loadLocalRepositories($args, 'repos');
if (!$repos) {
throw new PhutilArgumentUsageException(
pht(
'Specify one or more repositories to push to mirrors.'));
}
foreach ($repos as $repo) {
echo tsprintf(
"%s\n",
pht(
'Pushing "%s" to mirrors...',
$repo->getDisplayName()));
$engine = id(new PhabricatorRepositoryMirrorEngine())
->setRepository($repo)
->setVerbose($args->getArg('verbose'))
->pushToMirrors();
}
echo tsprintf(
"%s\n",
pht('Done.'));
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/repository/management/PhabricatorRepositoryManagementThawWorkflow.php | src/applications/repository/management/PhabricatorRepositoryManagementThawWorkflow.php | <?php
final class PhabricatorRepositoryManagementThawWorkflow
extends PhabricatorRepositoryManagementWorkflow {
protected function didConstruct() {
$this
->setName('thaw')
->setExamples('**thaw** [options] __repository__ ...')
->setSynopsis(
pht(
'Resolve issues with frozen cluster repositories. Very advanced '.
'and dangerous.'))
->setArguments(
array(
array(
'name' => 'demote',
'param' => 'device|service',
'help' => pht(
'Demote a device (or all devices in a service) discarding '.
'unsynchronized changes. Clears stuck write locks and recovers '.
'from lost leaders.'),
),
array(
'name' => 'promote',
'param' => 'device',
'help' => pht(
'Promote a device, discarding changes on other devices. '.
'Resolves ambiguous leadership and recovers from demotion '.
'mistakes.'),
),
array(
'name' => 'force',
'help' => pht('Run operations without asking for confirmation.'),
),
array(
'name' => 'all-repositories',
'help' => pht(
'Apply the promotion or demotion to all repositories hosted '.
'on the device.'),
),
array(
'name' => 'repositories',
'wildcard' => true,
),
));
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$promote = $args->getArg('promote');
$demote = $args->getArg('demote');
if (!$promote && !$demote) {
throw new PhutilArgumentUsageException(
pht('You must choose a device to --promote or --demote.'));
}
if ($promote && $demote) {
throw new PhutilArgumentUsageException(
pht('Specify either --promote or --demote, but not both.'));
}
$target_name = nonempty($promote, $demote);
$devices = id(new AlmanacDeviceQuery())
->setViewer($viewer)
->withNames(array($target_name))
->execute();
if (!$devices) {
$service = id(new AlmanacServiceQuery())
->setViewer($viewer)
->withNames(array($target_name))
->executeOne();
if (!$service) {
throw new PhutilArgumentUsageException(
pht('No device or service named "%s" exists.', $target_name));
}
if ($promote) {
throw new PhutilArgumentUsageException(
pht(
'You can not "--promote" an entire service ("%s"). Only a single '.
'device may be promoted.',
$target_name));
}
$bindings = id(new AlmanacBindingQuery())
->setViewer($viewer)
->withServicePHIDs(array($service->getPHID()))
->execute();
if (!$bindings) {
throw new PhutilArgumentUsageException(
pht(
'Service "%s" is not bound to any devices.',
$target_name));
}
$interfaces = id(new AlmanacInterfaceQuery())
->setViewer($viewer)
->withPHIDs(mpull($bindings, 'getInterfacePHID'))
->execute();
$device_phids = mpull($interfaces, 'getDevicePHID');
$devices = id(new AlmanacDeviceQuery())
->setViewer($viewer)
->withPHIDs($device_phids)
->execute();
}
$repository_names = $args->getArg('repositories');
$all_repositories = $args->getArg('all-repositories');
if ($repository_names && $all_repositories) {
throw new PhutilArgumentUsageException(
pht(
'Specify a list of repositories or "--all-repositories", '.
'but not both.'));
} else if (!$repository_names && !$all_repositories) {
throw new PhutilArgumentUsageException(
pht(
'Select repositories to affect by providing a list of repositories '.
'or using the "--all-repositories" flag.'));
}
if ($repository_names) {
$repositories = $this->loadRepositories($args, 'repositories');
if (!$repositories) {
throw new PhutilArgumentUsageException(
pht('Specify one or more repositories to thaw.'));
}
} else {
$repositories = array();
$services = id(new AlmanacServiceQuery())
->setViewer($viewer)
->withDevicePHIDs(mpull($devices, 'getPHID'))
->execute();
if ($services) {
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($viewer)
->withAlmanacServicePHIDs(mpull($services, 'getPHID'))
->execute();
}
if (!$repositories) {
throw new PhutilArgumentUsageException(
pht('There are no repositories on the selected device or service.'));
}
}
$display_list = new PhutilConsoleList();
foreach ($repositories as $repository) {
$display_list->addItem(
pht(
'%s %s',
$repository->getMonogram(),
$repository->getName()));
}
echo tsprintf(
"%s\n\n%B\n",
pht('These repositories will be thawed:'),
$display_list->drawConsoleString());
if ($promote) {
$risk_message = pht(
'Promoting a device can cause the loss of any repository data which '.
'only exists on other devices. The version of the repository on the '.
'promoted device will become authoritative.');
} else {
$risk_message = pht(
'Demoting a device can cause the loss of any repository data which '.
'only exists on the demoted device. The version of the repository '.
'on some other device will become authoritative.');
}
echo tsprintf(
"**<bg:red> %s </bg>** %s\n",
pht('DATA AT RISK'),
$risk_message);
$is_force = $args->getArg('force');
$prompt = pht('Accept the possibility of permanent data loss?');
if (!$is_force && !phutil_console_confirm($prompt)) {
throw new PhutilArgumentUsageException(
pht('User aborted the workflow.'));
}
foreach ($devices as $device) {
foreach ($repositories as $repository) {
$repository_phid = $repository->getPHID();
$write_lock = PhabricatorRepositoryWorkingCopyVersion::getWriteLock(
$repository_phid);
echo tsprintf(
"%s\n",
pht(
'Waiting to acquire write lock for "%s"...',
$repository->getDisplayName()));
$write_lock->lock(phutil_units('5 minutes in seconds'));
try {
$service = $repository->loadAlmanacService();
if (!$service) {
throw new PhutilArgumentUsageException(
pht(
'Repository "%s" is not a cluster repository: it is not '.
'bound to an Almanac service.',
$repository->getDisplayName()));
}
if ($promote) {
// You can only promote active devices. (You may demote active or
// inactive devices.)
$bindings = $service->getActiveBindings();
$bindings = mpull($bindings, null, 'getDevicePHID');
if (empty($bindings[$device->getPHID()])) {
throw new PhutilArgumentUsageException(
pht(
'Repository "%s" has no active binding to device "%s". '.
'Only actively bound devices can be promoted.',
$repository->getDisplayName(),
$device->getName()));
}
$versions = PhabricatorRepositoryWorkingCopyVersion::loadVersions(
$repository->getPHID());
$versions = mpull($versions, null, 'getDevicePHID');
// Before we promote, make sure there are no outstanding versions
// on devices with inactive bindings. If there are, you need to
// demote these first.
$inactive = array();
foreach ($versions as $device_phid => $version) {
if (isset($bindings[$device_phid])) {
continue;
}
$inactive[$device_phid] = $version;
}
if ($inactive) {
$handles = $viewer->loadHandles(array_keys($inactive));
$handle_list = iterator_to_array($handles);
$handle_list = mpull($handle_list, 'getName');
$handle_list = implode(', ', $handle_list);
throw new PhutilArgumentUsageException(
pht(
'Repository "%s" has versions on inactive devices. Demote '.
'(or reactivate) these devices before promoting a new '.
'leader: %s.',
$repository->getDisplayName(),
$handle_list));
}
// Now, make sure there are no outstanding versions on devices with
// active bindings. These also need to be demoted (or promoting is
// a mistake or already happened).
$active = array_select_keys($versions, array_keys($bindings));
if ($active) {
$handles = $viewer->loadHandles(array_keys($active));
$handle_list = iterator_to_array($handles);
$handle_list = mpull($handle_list, 'getName');
$handle_list = implode(', ', $handle_list);
throw new PhutilArgumentUsageException(
pht(
'Unable to promote "%s" for repository "%s" because this '.
'cluster already has one or more unambiguous leaders: %s.',
$device->getName(),
$repository->getDisplayName(),
$handle_list));
}
PhabricatorRepositoryWorkingCopyVersion::updateVersion(
$repository->getPHID(),
$device->getPHID(),
0);
echo tsprintf(
"%s\n",
pht(
'Promoted "%s" to become a leader for "%s".',
$device->getName(),
$repository->getDisplayName()));
}
if ($demote) {
PhabricatorRepositoryWorkingCopyVersion::demoteDevice(
$repository->getPHID(),
$device->getPHID());
echo tsprintf(
"%s\n",
pht(
'Demoted "%s" from leadership of repository "%s".',
$device->getName(),
$repository->getDisplayName()));
}
} catch (Exception $ex) {
$write_lock->unlock();
throw $ex;
}
$write_lock->unlock();
}
}
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/repository/worker/PhabricatorRepositoryCommitParserWorker.php | src/applications/repository/worker/PhabricatorRepositoryCommitParserWorker.php | <?php
abstract class PhabricatorRepositoryCommitParserWorker
extends PhabricatorWorker {
protected $commit;
protected $repository;
private function loadCommit() {
if ($this->commit) {
return $this->commit;
}
$viewer = $this->getViewer();
$task_data = $this->getTaskData();
$commit_query = id(new DiffusionCommitQuery())
->setViewer($viewer);
$commit_phid = idx($task_data, 'commitPHID');
// TODO: See T13591. This supports execution of legacy tasks and can
// eventually be removed. Newer tasks use "commitPHID" instead of
// "commitID".
if (!$commit_phid) {
$commit_id = idx($task_data, 'commitID');
if ($commit_id) {
$legacy_commit = id(clone $commit_query)
->withIDs(array($commit_id))
->executeOne();
if ($legacy_commit) {
$commit_phid = $legacy_commit->getPHID();
}
}
}
if (!$commit_phid) {
throw new PhabricatorWorkerPermanentFailureException(
pht('Task data has no "commitPHID".'));
}
$commit = id(clone $commit_query)
->withPHIDs(array($commit_phid))
->executeOne();
if (!$commit) {
throw new PhabricatorWorkerPermanentFailureException(
pht('Commit "%s" does not exist.', $commit_phid));
}
if ($commit->isUnreachable()) {
throw new PhabricatorWorkerPermanentFailureException(
pht(
'Commit "%s" (with PHID "%s") is no longer reachable from any '.
'branch, tag, or ref in this repository, so it will not be '.
'imported. This usually means that the branch the commit was on '.
'was deleted or overwritten.',
$commit->getMonogram(),
$commit_phid));
}
$this->commit = $commit;
return $commit;
}
final protected function doWork() {
$commit = $this->loadCommit();
$repository = $commit->getRepository();
$this->repository = $repository;
$this->parseCommit($repository, $this->commit);
}
private function shouldQueueFollowupTasks() {
return !idx($this->getTaskData(), 'only');
}
final protected function queueCommitTask($task_class) {
if (!$this->shouldQueueFollowupTasks()) {
return;
}
$commit = $this->loadCommit();
$repository = $commit->getRepository();
$data = array(
'commitPHID' => $commit->getPHID(),
);
$task_data = $this->getTaskData();
if (isset($task_data['via'])) {
$data['via'] = $task_data['via'];
}
$options = array(
// We queue followup tasks at default priority so that the queue finishes
// work it has started before starting more work. If followups are queued
// at the same priority level, we do all message parses first, then all
// change parses, etc. This makes progress uneven. See T11677 for
// discussion.
'priority' => parent::PRIORITY_DEFAULT,
'objectPHID' => $commit->getPHID(),
'containerPHID' => $repository->getPHID(),
);
$this->queueTask($task_class, $data, $options);
}
protected function getImportStepFlag() {
return null;
}
final protected function shouldSkipImportStep() {
// If this step has already been performed and this is a "natural" task
// which was queued by the normal daemons, decline to do the work again.
// This mitigates races if commits are rapidly deleted and revived.
$flag = $this->getImportStepFlag();
if (!$flag) {
// This step doesn't have an associated flag.
return false;
}
$commit = $this->commit;
if (!$commit->isPartiallyImported($flag)) {
// This commit doesn't have the flag set yet.
return false;
}
if (!$this->shouldQueueFollowupTasks()) {
// This task was queued by administrative tools, so do the work even
// if it duplicates existing work.
return false;
}
$this->log(
"%s\n",
pht(
'Skipping import step; this step was previously completed for '.
'this commit.'));
return true;
}
abstract protected function parseCommit(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit);
protected function loadCommitHint(PhabricatorRepositoryCommit $commit) {
$viewer = PhabricatorUser::getOmnipotentUser();
$repository = $commit->getRepository();
return id(new DiffusionCommitHintQuery())
->setViewer($viewer)
->withRepositoryPHIDs(array($repository->getPHID()))
->withOldCommitIdentifiers(array($commit->getCommitIdentifier()))
->executeOne();
}
public function renderForDisplay(PhabricatorUser $viewer) {
$suffix = parent::renderForDisplay($viewer);
$commit = id(new DiffusionCommitQuery())
->setViewer($viewer)
->withPHIDs(array(idx($this->getTaskData(), 'commitPHID')))
->executeOne();
if (!$commit) {
return $suffix;
}
$link = DiffusionView::linkCommit(
$commit->getRepository(),
$commit->getCommitIdentifier());
return array($link, $suffix);
}
final protected function loadCommitData(PhabricatorRepositoryCommit $commit) {
if ($commit->hasCommitData()) {
return $commit->getCommitData();
}
$commit_id = $commit->getID();
$data = id(new PhabricatorRepositoryCommitData())->loadOneWhere(
'commitID = %d',
$commit_id);
if (!$data) {
$data = id(new PhabricatorRepositoryCommitData())
->setCommitID($commit_id);
}
$commit->attachCommitData($data);
return $data;
}
final public function getViewer() {
return PhabricatorUser::getOmnipotentUser();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/worker/PhabricatorRepositoryPushMailWorker.php | src/applications/repository/worker/PhabricatorRepositoryPushMailWorker.php | <?php
final class PhabricatorRepositoryPushMailWorker
extends PhabricatorWorker {
protected function doWork() {
$viewer = PhabricatorUser::getOmnipotentUser();
$task_data = $this->getTaskData();
$email_phids = idx($task_data, 'emailPHIDs');
if (!$email_phids) {
// If we don't have any email targets, don't send any email.
return;
}
$event_phid = idx($task_data, 'eventPHID');
$event = id(new PhabricatorRepositoryPushEventQuery())
->setViewer($viewer)
->withPHIDs(array($event_phid))
->needLogs(true)
->executeOne();
$repository = $event->getRepository();
$publisher = $repository->newPublisher();
if (!$publisher->shouldPublishRepository()) {
// If the repository is still importing, don't send email.
return;
}
$targets = id(new PhabricatorRepositoryPushReplyHandler())
->setMailReceiver($repository)
->getMailTargets($email_phids, array());
$messages = array();
foreach ($targets as $target) {
$messages[] = $this->sendMail($target, $repository, $event);
}
foreach ($messages as $message) {
$message->save();
}
}
private function sendMail(
PhabricatorMailTarget $target,
PhabricatorRepository $repository,
PhabricatorRepositoryPushEvent $event) {
$task_data = $this->getTaskData();
$viewer = $target->getViewer();
$locale = PhabricatorEnv::beginScopedLocale($viewer->getTranslation());
$logs = $event->getLogs();
list($ref_lines, $ref_list) = $this->renderRefs($logs);
list($commit_lines, $subject_line) = $this->renderCommits(
$repository,
$logs,
idx($task_data, 'info', array()));
$ref_count = count($ref_lines);
$commit_count = count($commit_lines);
$handles = id(new PhabricatorHandleQuery())
->setViewer($viewer)
->withPHIDs(array($event->getPusherPHID()))
->execute();
$pusher_name = $handles[$event->getPusherPHID()]->getName();
$repo_name = $repository->getMonogram();
if ($commit_count) {
$overview = pht(
'%s pushed %d commit(s) to %s.',
$pusher_name,
$commit_count,
$repo_name);
} else {
$overview = pht(
'%s pushed to %s.',
$pusher_name,
$repo_name);
}
$details_uri = PhabricatorEnv::getProductionURI(
'/diffusion/pushlog/view/'.$event->getID().'/');
$body = new PhabricatorMetaMTAMailBody();
$body->addRawSection($overview);
$body->addLinkSection(pht('DETAILS'), $details_uri);
if ($commit_lines) {
$body->addTextSection(pht('COMMITS'), implode("\n", $commit_lines));
}
if ($ref_lines) {
$body->addTextSection(pht('REFERENCES'), implode("\n", $ref_lines));
}
$prefix = pht('[Diffusion]');
$parts = array();
if ($commit_count) {
$parts[] = pht('%s commit(s)', $commit_count);
}
if ($ref_count) {
$parts[] = implode(', ', $ref_list);
}
$parts = implode(', ', $parts);
if ($subject_line) {
$subject = pht('(%s) %s', $parts, $subject_line);
} else {
$subject = pht('(%s)', $parts);
}
$mail = id(new PhabricatorMetaMTAMail())
->setRelatedPHID($event->getPHID())
->setSubjectPrefix($prefix)
->setVarySubjectPrefix(pht('[Push]'))
->setSubject($subject)
->setFrom($event->getPusherPHID())
->setBody($body->render())
->setHTMLBody($body->renderHTML())
->setThreadID($event->getPHID(), $is_new = true)
->setIsBulk(true);
return $target->willSendMail($mail);
}
private function renderRefs(array $logs) {
$ref_lines = array();
$ref_list = array();
foreach ($logs as $log) {
$type_name = null;
$type_prefix = null;
switch ($log->getRefType()) {
case PhabricatorRepositoryPushLog::REFTYPE_BRANCH:
$type_name = pht('branch');
break;
case PhabricatorRepositoryPushLog::REFTYPE_TAG:
$type_name = pht('tag');
$type_prefix = pht('tag:');
break;
case PhabricatorRepositoryPushLog::REFTYPE_BOOKMARK:
$type_name = pht('bookmark');
$type_prefix = pht('bookmark:');
break;
case PhabricatorRepositoryPushLog::REFTYPE_REF:
$type_name = pht('ref');
$type_prefix = pht('ref:');
break;
case PhabricatorRepositoryPushLog::REFTYPE_COMMIT:
default:
break;
}
if ($type_name === null) {
continue;
}
$flags = $log->getChangeFlags();
if ($flags & PhabricatorRepositoryPushLog::CHANGEFLAG_DANGEROUS) {
$action = '!';
} else if ($flags & PhabricatorRepositoryPushLog::CHANGEFLAG_DELETE) {
$action = '-';
} else if ($flags & PhabricatorRepositoryPushLog::CHANGEFLAG_REWRITE) {
$action = '~';
} else if ($flags & PhabricatorRepositoryPushLog::CHANGEFLAG_APPEND) {
$action = ' ';
} else if ($flags & PhabricatorRepositoryPushLog::CHANGEFLAG_ADD) {
$action = '+';
} else {
$action = '?';
}
$old = nonempty($log->getRefOldShort(), pht('<null>'));
$new = nonempty($log->getRefNewShort(), pht('<null>'));
$name = $log->getRefName();
$ref_lines[] = "{$action} {$type_name} {$name} {$old} > {$new}";
$ref_list[] = $type_prefix.$name;
}
return array(
$ref_lines,
array_unique($ref_list),
);
}
private function renderCommits(
PhabricatorRepository $repository,
array $logs,
array $info) {
$commit_lines = array();
$subject_line = null;
foreach ($logs as $log) {
if ($log->getRefType() != PhabricatorRepositoryPushLog::REFTYPE_COMMIT) {
continue;
}
$commit_info = idx($info, $log->getRefNew(), array());
$name = $repository->formatCommitName($log->getRefNew());
$branches = null;
if (idx($commit_info, 'branches')) {
$branches = ' ('.implode(', ', $commit_info['branches']).')';
}
$summary = null;
if (strlen(idx($commit_info, 'summary'))) {
$summary = ' '.$commit_info['summary'];
}
$commit_lines[] = "{$name}{$branches}{$summary}";
if ($subject_line === null) {
$subject_line = "{$name}{$summary}";
}
}
return array($commit_lines, $subject_line);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/worker/PhabricatorRepositoryCommitPublishWorker.php | src/applications/repository/worker/PhabricatorRepositoryCommitPublishWorker.php | <?php
final class PhabricatorRepositoryCommitPublishWorker
extends PhabricatorRepositoryCommitParserWorker {
protected function getImportStepFlag() {
return PhabricatorRepositoryCommit::IMPORTED_PUBLISH;
}
public function getRequiredLeaseTime() {
// Herald rules may take a long time to process.
return phutil_units('4 hours in seconds');
}
protected function parseCommit(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit) {
if (!$this->shouldSkipImportStep()) {
$this->publishCommit($repository, $commit);
$commit->writeImportStatusFlag($this->getImportStepFlag());
}
// This is the last task in the sequence, so we don't need to queue any
// followup workers.
}
private function publishCommit(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit) {
$viewer = PhabricatorUser::getOmnipotentUser();
$commit_phid = $commit->getPHID();
// Reload the commit to get the commit data, identities, and any
// outstanding audit requests.
$commit = id(new DiffusionCommitQuery())
->setViewer($viewer)
->withPHIDs(array($commit_phid))
->needCommitData(true)
->needIdentities(true)
->needAuditRequests(true)
->executeOne();
if (!$commit) {
throw new PhabricatorWorkerPermanentFailureException(
pht(
'Failed to reload commit "%s".',
$commit_phid));
}
$publisher = $repository->newPublisher();
$should_publish = $publisher->shouldPublishCommit($commit);
if (!$should_publish) {
$hold_reasons = $publisher->getCommitHoldReasons($commit);
} else {
$hold_reasons = array();
}
$data = $commit->getCommitData();
if ($data->getCommitDetail('holdReasons') !== $hold_reasons) {
$data->setCommitDetail('holdReasons', $hold_reasons);
$data->save();
}
if (!$should_publish) {
return;
}
// NOTE: Close revisions and tasks before applying transactions, because
// we want a side effect of closure (the commit being associated with
// a revision) to occur before a side effect of transactions (Herald
// executing). The close methods queue tasks for the actual updates to
// commits/revisions, so those won't occur until after the commit gets
// transactions.
$this->closeRevisions($viewer, $commit);
$this->closeTasks($viewer, $commit);
$this->applyTransactions($viewer, $repository, $commit);
}
private function applyTransactions(
PhabricatorUser $actor,
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit) {
$xactions = array(
$this->newAuditTransactions($commit),
$this->newPublishTransactions($commit),
);
$xactions = array_mergev($xactions);
$acting_phid = $this->getPublishAsPHID($commit);
$content_source = $this->newContentSource();
$revision = DiffusionCommitRevisionQuery::loadRevisionForCommit(
$actor,
$commit);
// Prevent the commit from generating a mention of the associated
// revision, if one exists, so we don't double up because of the URI
// in the commit message.
$unmentionable_phids = array();
if ($revision) {
$unmentionable_phids[] = $revision->getPHID();
}
$editor = $commit->getApplicationTransactionEditor()
->setActor($actor)
->setActingAsPHID($acting_phid)
->setContinueOnNoEffect(true)
->setContinueOnMissingFields(true)
->setContentSource($content_source)
->addUnmentionablePHIDs($unmentionable_phids);
try {
$raw_patch = $this->loadRawPatchText($repository, $commit);
} catch (Exception $ex) {
$raw_patch = pht('Unable to generate patch: %s', $ex->getMessage());
}
$editor->setRawPatch($raw_patch);
$editor->applyTransactions($commit, $xactions);
}
private function getPublishAsPHID(PhabricatorRepositoryCommit $commit) {
if ($commit->hasCommitterIdentity()) {
return $commit->getCommitterIdentity()->getIdentityDisplayPHID();
}
if ($commit->hasAuthorIdentity()) {
return $commit->getAuthorIdentity()->getIdentityDisplayPHID();
}
return id(new PhabricatorDiffusionApplication())->getPHID();
}
private function newPublishTransactions(PhabricatorRepositoryCommit $commit) {
$data = $commit->getCommitData();
$xactions = array();
$xactions[] = $commit->getApplicationTransactionTemplate()
->setTransactionType(PhabricatorAuditTransaction::TYPE_COMMIT)
->setDateCreated($commit->getEpoch())
->setNewValue(
array(
'description' => $data->getCommitMessage(),
'summary' => $data->getSummary(),
'authorName' => $data->getAuthorString(),
'authorPHID' => $commit->getAuthorPHID(),
'committerName' => $data->getCommitterString(),
'committerPHID' => $data->getCommitDetail('committerPHID'),
));
return $xactions;
}
private function newAuditTransactions(PhabricatorRepositoryCommit $commit) {
$viewer = PhabricatorUser::getOmnipotentUser();
$repository = $commit->getRepository();
$affected_paths = PhabricatorOwnerPathQuery::loadAffectedPaths(
$repository,
$commit,
PhabricatorUser::getOmnipotentUser());
$affected_packages = PhabricatorOwnersPackage::loadAffectedPackages(
$repository,
$affected_paths);
$commit->writeOwnersEdges(mpull($affected_packages, 'getPHID'));
if (!$affected_packages) {
return array();
}
$data = $commit->getCommitData();
$author_phid = $commit->getEffectiveAuthorPHID();
$revision = DiffusionCommitRevisionQuery::loadRevisionForCommit(
$viewer,
$commit);
$requests = $commit->getAudits();
$requests = mpull($requests, null, 'getAuditorPHID');
$auditor_phids = array();
foreach ($affected_packages as $package) {
$request = idx($requests, $package->getPHID());
if ($request) {
// Don't update request if it exists already.
continue;
}
$should_audit = $this->shouldTriggerAudit(
$commit,
$package,
$author_phid,
$revision);
if (!$should_audit) {
continue;
}
$auditor_phids[] = $package->getPHID();
}
// If none of the packages are triggering audits, we're all done.
if (!$auditor_phids) {
return array();
}
$audit_type = DiffusionCommitAuditorsTransaction::TRANSACTIONTYPE;
$xactions = array();
$xactions[] = $commit->getApplicationTransactionTemplate()
->setTransactionType($audit_type)
->setNewValue(
array(
'+' => array_fuse($auditor_phids),
));
return $xactions;
}
private function shouldTriggerAudit(
PhabricatorRepositoryCommit $commit,
PhabricatorOwnersPackage $package,
$author_phid,
$revision) {
$audit_uninvolved = false;
$audit_unreviewed = false;
$rule = $package->newAuditingRule();
switch ($rule->getKey()) {
case PhabricatorOwnersAuditRule::AUDITING_NONE:
return false;
case PhabricatorOwnersAuditRule::AUDITING_ALL:
return true;
case PhabricatorOwnersAuditRule::AUDITING_NO_OWNER:
$audit_uninvolved = true;
break;
case PhabricatorOwnersAuditRule::AUDITING_UNREVIEWED:
$audit_unreviewed = true;
break;
case PhabricatorOwnersAuditRule::AUDITING_NO_OWNER_AND_UNREVIEWED:
$audit_uninvolved = true;
$audit_unreviewed = true;
break;
}
// If auditing is configured to trigger on unreviewed changes, check if
// the revision was "Accepted" when it landed. If not, trigger an audit.
// We may be running before the revision actually closes, so we'll count
// either an "Accepted" or a "Closed, Previously Accepted" revision as
// good enough.
if ($audit_unreviewed) {
$commit_unreviewed = true;
if ($revision) {
if ($revision->isAccepted()) {
$commit_unreviewed = false;
} else {
$was_accepted = DifferentialRevision::PROPERTY_CLOSED_FROM_ACCEPTED;
if ($revision->isPublished()) {
if ($revision->getProperty($was_accepted)) {
$commit_unreviewed = false;
}
}
}
}
if ($commit_unreviewed) {
return true;
}
}
// If auditing is configured to trigger on changes with no involved owner,
// check for an owner. If we don't find one, trigger an audit.
if ($audit_uninvolved) {
$owner_involved = $this->isOwnerInvolved(
$commit,
$package,
$author_phid,
$revision);
if (!$owner_involved) {
return true;
}
}
// We can't find any reason to trigger an audit for this commit.
return false;
}
private function isOwnerInvolved(
PhabricatorRepositoryCommit $commit,
PhabricatorOwnersPackage $package,
$author_phid,
$revision) {
$owner_phids = PhabricatorOwnersOwner::loadAffiliatedUserPHIDs(
array(
$package->getID(),
));
$owner_phids = array_fuse($owner_phids);
// For the purposes of deciding whether the owners were involved in the
// revision or not, consider a review by the package itself to count as
// involvement. This can happen when human reviewers force-accept on
// behalf of packages they don't own but have authority over.
$owner_phids[$package->getPHID()] = $package->getPHID();
// If the commit author is identifiable and a package owner, they're
// involved.
if ($author_phid) {
if (isset($owner_phids[$author_phid])) {
return true;
}
}
// Otherwise, we need to find an owner as a reviewer.
// If we don't have a revision, this is hopeless: no owners are involved.
if (!$revision) {
return true;
}
$accepted_statuses = array(
DifferentialReviewerStatus::STATUS_ACCEPTED,
DifferentialReviewerStatus::STATUS_ACCEPTED_OLDER,
);
$accepted_statuses = array_fuse($accepted_statuses);
$found_accept = false;
foreach ($revision->getReviewers() as $reviewer) {
$reviewer_phid = $reviewer->getReviewerPHID();
// If this reviewer isn't a package owner or the package itself,
// just ignore them.
if (empty($owner_phids[$reviewer_phid])) {
continue;
}
// If this reviewer accepted the revision and owns the package (or is
// the package), we've found an involved owner.
if (isset($accepted_statuses[$reviewer->getReviewerStatus()])) {
$found_accept = true;
break;
}
}
if ($found_accept) {
return true;
}
return false;
}
private function loadRawPatchText(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit) {
$viewer = PhabricatorUser::getOmnipotentUser();
$identifier = $commit->getCommitIdentifier();
$drequest = DiffusionRequest::newFromDictionary(
array(
'user' => $viewer,
'repository' => $repository,
));
$time_key = 'metamta.diffusion.time-limit';
$byte_key = 'metamta.diffusion.byte-limit';
$time_limit = PhabricatorEnv::getEnvConfig($time_key);
$byte_limit = PhabricatorEnv::getEnvConfig($byte_key);
$diff_info = DiffusionQuery::callConduitWithDiffusionRequest(
$viewer,
$drequest,
'diffusion.rawdiffquery',
array(
'commit' => $identifier,
'linesOfContext' => 3,
'timeout' => $time_limit,
'byteLimit' => $byte_limit,
));
if ($diff_info['tooSlow']) {
throw new Exception(
pht(
'Patch generation took longer than configured limit ("%s") of '.
'%s second(s).',
$time_key,
new PhutilNumber($time_limit)));
}
if ($diff_info['tooHuge']) {
$pretty_limit = phutil_format_bytes($byte_limit);
throw new Exception(
pht(
'Patch size exceeds configured byte size limit ("%s") of %s.',
$byte_key,
$pretty_limit));
}
$file_phid = $diff_info['filePHID'];
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($file_phid))
->executeOne();
if (!$file) {
throw new Exception(
pht(
'Failed to load file ("%s") returned by "%s".',
$file_phid,
'diffusion.rawdiffquery'));
}
return $file->loadFileData();
}
private function closeRevisions(
PhabricatorUser $actor,
PhabricatorRepositoryCommit $commit) {
$differential = 'PhabricatorDifferentialApplication';
if (!PhabricatorApplication::isClassInstalled($differential)) {
return;
}
$repository = $commit->getRepository();
$data = $commit->getCommitData();
$ref = $data->getCommitRef();
$field_query = id(new DiffusionLowLevelCommitFieldsQuery())
->setRepository($repository)
->withCommitRef($ref);
$field_values = $field_query->execute();
$revision_id = idx($field_values, 'revisionID');
if (!$revision_id) {
return;
}
$revision = id(new DifferentialRevisionQuery())
->setViewer($actor)
->withIDs(array($revision_id))
->executeOne();
if (!$revision) {
return;
}
// NOTE: This is very old code from when revisions had a single reviewer.
// It still powers the "Reviewer (Deprecated)" field in Herald, but should
// be removed.
if (!empty($field_values['reviewedByPHIDs'])) {
$data->setCommitDetail(
'reviewerPHID',
head($field_values['reviewedByPHIDs']));
}
$match_data = $field_query->getRevisionMatchData();
$data->setCommitDetail('differential.revisionID', $revision_id);
$data->setCommitDetail('revisionMatchData', $match_data);
$data->save();
$properties = array(
'revisionMatchData' => $match_data,
);
$this->queueObjectUpdate($commit, $revision, $properties);
}
private function closeTasks(
PhabricatorUser $actor,
PhabricatorRepositoryCommit $commit) {
$maniphest = 'PhabricatorManiphestApplication';
if (!PhabricatorApplication::isClassInstalled($maniphest)) {
return;
}
$data = $commit->getCommitData();
$prefixes = ManiphestTaskStatus::getStatusPrefixMap();
$suffixes = ManiphestTaskStatus::getStatusSuffixMap();
$message = $data->getCommitMessage();
$matches = id(new ManiphestCustomFieldStatusParser())
->parseCorpus($message);
$task_map = array();
foreach ($matches as $match) {
$prefix = phutil_utf8_strtolower($match['prefix']);
$suffix = phutil_utf8_strtolower($match['suffix']);
$status = idx($suffixes, $suffix);
if (!$status) {
$status = idx($prefixes, $prefix);
}
foreach ($match['monograms'] as $task_monogram) {
$task_id = (int)trim($task_monogram, 'tT');
$task_map[$task_id] = $status;
}
}
if (!$task_map) {
return;
}
$tasks = id(new ManiphestTaskQuery())
->setViewer($actor)
->withIDs(array_keys($task_map))
->execute();
foreach ($tasks as $task_id => $task) {
$status = $task_map[$task_id];
$properties = array(
'status' => $status,
);
$this->queueObjectUpdate($commit, $task, $properties);
}
}
private function queueObjectUpdate(
PhabricatorRepositoryCommit $commit,
$object,
array $properties) {
$this->queueTask(
'DiffusionUpdateObjectAfterCommitWorker',
array(
'commitPHID' => $commit->getPHID(),
'objectPHID' => $object->getPHID(),
'properties' => $properties,
),
array(
'priority' => PhabricatorWorker::PRIORITY_DEFAULT,
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/worker/PhabricatorRepositoryIdentityChangeWorker.php | src/applications/repository/worker/PhabricatorRepositoryIdentityChangeWorker.php | <?php
final class PhabricatorRepositoryIdentityChangeWorker
extends PhabricatorWorker {
protected function doWork() {
$viewer = PhabricatorUser::getOmnipotentUser();
$related_phids = $this->getTaskDataValue('relatedPHIDs');
$email_addresses = $this->getTaskDataValue('emailAddresses');
// Retain backward compatibility with older tasks which may still be in
// queue. Previously, this worker accepted a single "userPHID". See
// T13444. This can be removed in some future version of Phabricator once
// these tasks have likely flushed out of queue.
$legacy_phid = $this->getTaskDataValue('userPHID');
if ($legacy_phid) {
if (!is_array($related_phids)) {
$related_phids = array();
}
$related_phids[] = $legacy_phid;
}
// Note that we may arrive in this worker after the associated objects
// have already been destroyed, so we can't (and shouldn't) verify that
// PHIDs correspond to real objects. If you "bin/remove destroy" a user,
// we'll end up here with a now-bogus user PHID that we should
// disassociate from identities.
$identity_map = array();
if ($related_phids) {
$identities = id(new PhabricatorRepositoryIdentityQuery())
->setViewer($viewer)
->withRelatedPHIDs($related_phids)
->execute();
$identity_map += mpull($identities, null, 'getPHID');
}
if ($email_addresses) {
$identities = id(new PhabricatorRepositoryIdentityQuery())
->setViewer($viewer)
->withEmailAddresses($email_addresses)
->execute();
$identity_map += mpull($identities, null, 'getPHID');
}
// If we didn't find any related identities, we're all set.
if (!$identity_map) {
return;
}
$identity_engine = id(new DiffusionRepositoryIdentityEngine())
->setViewer($viewer);
foreach ($identity_map as $identity) {
$identity_engine->newUpdatedIdentity($identity);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/worker/commitmessageparser/PhabricatorRepositoryCommitMessageParserWorker.php | src/applications/repository/worker/commitmessageparser/PhabricatorRepositoryCommitMessageParserWorker.php | <?php
abstract class PhabricatorRepositoryCommitMessageParserWorker
extends PhabricatorRepositoryCommitParserWorker {
protected function getImportStepFlag() {
return PhabricatorRepositoryCommit::IMPORTED_MESSAGE;
}
abstract protected function getFollowupTaskClass();
final protected function parseCommit(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit) {
if (!$this->shouldSkipImportStep()) {
$viewer = $this->getViewer();
$ref = $commit->newCommitRef($viewer);
$data = $this->loadCommitData($commit);
$data->setCommitRef($ref);
$this->updateCommitData($commit, $data);
}
$this->queueCommitTask($this->getFollowupTaskClass());
}
final protected function updateCommitData(
PhabricatorRepositoryCommit $commit,
PhabricatorRepositoryCommitData $data) {
$ref = $data->getCommitRef();
$viewer = $this->getViewer();
$author = $ref->getAuthor();
$committer = $ref->getCommitter();
$has_committer = $committer !== null && (bool)strlen($committer);
$identity_engine = id(new DiffusionRepositoryIdentityEngine())
->setViewer($viewer)
->setSourcePHID($commit->getPHID());
// See T13538. It is possible to synthetically construct a Git commit with
// no author and arrive here with NULL for the author value.
// This is distinct from a commit with an empty author. Because both these
// cases are degenerate and we can't resolve NULL into an identity, cast
// NULL to the empty string and merge the flows.
$author = phutil_string_cast($author);
$author_identity = $identity_engine->newResolvedIdentity($author);
if ($has_committer) {
$committer_identity = $identity_engine->newResolvedIdentity($committer);
} else {
$committer_identity = null;
}
$data->setAuthorName(id(new PhutilUTF8StringTruncator())
->setMaximumBytes(255)
->truncateString((string)$author));
$data->setCommitDetail('authorEpoch', $ref->getAuthorEpoch());
$data->setCommitDetail('authorName', $ref->getAuthorName());
$data->setCommitDetail('authorEmail', $ref->getAuthorEmail());
$data->setCommitDetail(
'authorIdentityPHID', $author_identity->getPHID());
$data->setCommitDetail(
'authorPHID',
$author_identity->getCurrentEffectiveUserPHID());
// See T13538. It is possible to synthetically construct a Git commit with
// no message. As above, treat this as though it is the same as the empty
// message.
$message = $ref->getMessage();
$message = phutil_string_cast($message);
$data->setCommitMessage($message);
if ($has_committer) {
$data->setCommitDetail('committer', $committer);
$data->setCommitDetail('committerName', $ref->getCommitterName());
$data->setCommitDetail('committerEmail', $ref->getCommitterEmail());
$data->setCommitDetail(
'committerPHID',
$committer_identity->getCurrentEffectiveUserPHID());
$data->setCommitDetail(
'committerIdentityPHID', $committer_identity->getPHID());
$commit->setCommitterIdentityPHID($committer_identity->getPHID());
}
$repository = $this->repository;
$author_phid = $data->getCommitDetail('authorPHID');
$committer_phid = $data->getCommitDetail('committerPHID');
if ($author_phid != $commit->getAuthorPHID()) {
$commit->setAuthorPHID($author_phid);
}
$commit->setAuthorIdentityPHID($author_identity->getPHID());
$commit->setSummary($data->getSummary());
$commit->save();
$data->save();
$commit->writeImportStatusFlag(
PhabricatorRepositoryCommit::IMPORTED_MESSAGE);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/worker/commitmessageparser/PhabricatorRepositoryMercurialCommitMessageParserWorker.php | src/applications/repository/worker/commitmessageparser/PhabricatorRepositoryMercurialCommitMessageParserWorker.php | <?php
final class PhabricatorRepositoryMercurialCommitMessageParserWorker
extends PhabricatorRepositoryCommitMessageParserWorker {
protected function getFollowupTaskClass() {
return 'PhabricatorRepositoryMercurialCommitChangeParserWorker';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/worker/commitmessageparser/PhabricatorRepositorySvnCommitMessageParserWorker.php | src/applications/repository/worker/commitmessageparser/PhabricatorRepositorySvnCommitMessageParserWorker.php | <?php
final class PhabricatorRepositorySvnCommitMessageParserWorker
extends PhabricatorRepositoryCommitMessageParserWorker {
protected function getFollowupTaskClass() {
return 'PhabricatorRepositorySvnCommitChangeParserWorker';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/worker/commitmessageparser/PhabricatorRepositoryGitCommitMessageParserWorker.php | src/applications/repository/worker/commitmessageparser/PhabricatorRepositoryGitCommitMessageParserWorker.php | <?php
final class PhabricatorRepositoryGitCommitMessageParserWorker
extends PhabricatorRepositoryCommitMessageParserWorker {
protected function getFollowupTaskClass() {
return 'PhabricatorRepositoryGitCommitChangeParserWorker';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/worker/commitchangeparser/PhabricatorRepositorySvnCommitChangeParserWorker.php | src/applications/repository/worker/commitchangeparser/PhabricatorRepositorySvnCommitChangeParserWorker.php | <?php
final class PhabricatorRepositorySvnCommitChangeParserWorker
extends PhabricatorRepositoryCommitChangeParserWorker {
protected function parseCommitChanges(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit) {
// PREAMBLE: This class is absurdly complicated because it is very difficult
// to get the information we need out of SVN. The actual data we need is:
//
// 1. Recursively, what were the affected paths?
// 2. For each affected path, is it a file or a directory?
// 3. How was each path affected (e.g. add, delete, move, copy)?
//
// We spend nearly all of our effort figuring out (1) and (2) because
// "svn log" is not recursive and does not give us file/directory
// information (that is, it will report a directory move as a single move,
// even if many thousands of paths are affected).
//
// Instead, we have to "svn ls -R" the location of each path in its previous
// life to figure out whether it is a file or a directory and exactly which
// recursive paths were affected if it was moved or copied. This is very
// complicated and has many special cases.
$uri = $repository->getSubversionPathURI();
$svn_commit = $commit->getCommitIdentifier();
// Pull the top-level path changes out of "svn log". This is pretty
// straightforward; just parse the XML log.
$log = $this->getSVNLogXMLObject($repository, $uri, $svn_commit);
$entry = $log->logentry[0];
if (!$entry->paths) {
// TODO: Explicitly mark this commit as broken elsewhere? This isn't
// supposed to happen but we have some cases like rE27 and rG935 in the
// Facebook repositories where things got all clowned up.
return array();
}
$raw_paths = array();
foreach ($entry->paths->path as $path) {
$name = trim((string)$path);
$raw_paths[$name] = array(
'rawPath' => $name,
'rawTargetPath' => (string)$path['copyfrom-path'],
'rawChangeType' => (string)$path['action'],
'rawTargetCommit' => (string)$path['copyfrom-rev'],
);
}
$copied_or_moved_map = array();
$deleted_paths = array();
$add_paths = array();
foreach ($raw_paths as $path => $raw_info) {
if ($raw_info['rawTargetPath']) {
$copied_or_moved_map[$raw_info['rawTargetPath']][] = $raw_info;
}
switch ($raw_info['rawChangeType']) {
case 'D':
$deleted_paths[$path] = $raw_info;
break;
case 'A':
case 'R':
$add_paths[$path] = $raw_info;
break;
}
}
// If a path was deleted, we need to look in the repository history to
// figure out where the former valid location for it is so we can figure out
// if it was a directory or not, among other things.
$lookup_here = array();
foreach ($raw_paths as $path => $raw_info) {
if ($raw_info['rawChangeType'] != 'D') {
continue;
}
// If a change copies a directory and then deletes something from it,
// we need to look at the old location for information about the path, not
// the new location. This workflow is pretty ridiculous -- so much so that
// Trac gets it wrong. See Facebook rO6 for an example, if you happen to
// work at Facebook.
$parents = $this->expandAllParentPaths($path, $include_self = true);
foreach ($parents as $parent) {
if (isset($add_paths[$parent])) {
$relative_path = substr($path, strlen($parent));
$lookup_here[$path] = array(
'rawPath' => $add_paths[$parent]['rawTargetPath'].$relative_path,
'rawCommit' => $add_paths[$parent]['rawTargetCommit'],
);
continue 2;
}
}
// Otherwise we can just look at the previous revision.
$lookup_here[$path] = array(
'rawPath' => $path,
'rawCommit' => $svn_commit - 1,
);
}
$lookup = array();
foreach ($raw_paths as $path => $raw_info) {
if ($raw_info['rawChangeType'] == 'D') {
$lookup[$path] = $lookup_here[$path];
} else {
// For everything that wasn't deleted, we can just look it up directly.
$lookup[$path] = array(
'rawPath' => $path,
'rawCommit' => $svn_commit,
);
}
}
$effects = array();
$path_file_types = $this->lookupPathFileTypes($repository, $lookup);
foreach ($raw_paths as $path => $raw_info) {
if ($raw_info['rawChangeType'] == 'D' &&
$path_file_types[$path] == DifferentialChangeType::FILE_DIRECTORY) {
// Bad. Child paths aren't enumerated in "svn log" so we need
// to go fishing.
$list = $this->lookupRecursiveFileList(
$repository,
$lookup[$path]);
foreach ($list as $deleted_path => $path_file_type) {
$deleted_path = rtrim($path.'/'.$deleted_path, '/');
if (!empty($raw_paths[$deleted_path])) {
// We somehow learned about this deletion explicitly?
// TODO: Unclear how this is possible.
continue;
}
$effect_type = DifferentialChangeType::TYPE_DELETE;
$effect_target_path = null;
if (isset($copied_or_moved_map[$deleted_path])) {
$effect_target_path = $path;
if (count($copied_or_moved_map[$deleted_path]) > 1) {
$effect_type = DifferentialChangeType::TYPE_MULTICOPY;
} else {
$effect_type = DifferentialChangeType::TYPE_MOVE_AWAY;
}
}
$effects[$deleted_path] = array(
'rawPath' => $deleted_path,
'rawTargetPath' => $effect_target_path,
'rawTargetCommit' => null,
'rawDirect' => true,
'changeType' => $effect_type,
'fileType' => $path_file_type,
);
$deleted_paths[$deleted_path] = $effects[$deleted_path];
}
}
}
$resolved_types = array();
$supplemental = array();
foreach ($raw_paths as $path => $raw_info) {
if (isset($resolved_types[$path])) {
$type = $resolved_types[$path];
} else {
switch ($raw_info['rawChangeType']) {
case 'D':
if (isset($copied_or_moved_map[$path])) {
if (count($copied_or_moved_map[$path]) > 1) {
$type = DifferentialChangeType::TYPE_MULTICOPY;
} else {
$type = DifferentialChangeType::TYPE_MOVE_AWAY;
}
} else {
$type = DifferentialChangeType::TYPE_DELETE;
}
break;
case 'A':
$copy_from = $raw_info['rawTargetPath'];
$copy_rev = $raw_info['rawTargetCommit'];
if (!strlen($copy_from)) {
$type = DifferentialChangeType::TYPE_ADD;
} else {
if (isset($deleted_paths[$copy_from])) {
$type = DifferentialChangeType::TYPE_MOVE_HERE;
$other_type = DifferentialChangeType::TYPE_MOVE_AWAY;
} else {
$type = DifferentialChangeType::TYPE_COPY_HERE;
$other_type = DifferentialChangeType::TYPE_COPY_AWAY;
}
$source_file_type = $this->lookupPathFileType(
$repository,
$copy_from,
array(
'rawPath' => $copy_from,
'rawCommit' => $copy_rev,
));
if ($source_file_type == DifferentialChangeType::FILE_DELETED) {
throw new Exception(
pht('Something is wrong; source of a copy must exist.'));
}
if ($source_file_type != DifferentialChangeType::FILE_DIRECTORY) {
if (isset($raw_paths[$copy_from]) ||
isset($effects[$copy_from])) {
break;
}
$effects[$copy_from] = array(
'rawPath' => $copy_from,
'rawTargetPath' => null,
'rawTargetCommit' => null,
'rawDirect' => false,
'changeType' => $other_type,
'fileType' => $source_file_type,
);
} else {
// ULTRADISASTER. We've added a directory which was copied
// or moved from somewhere else. This is the most complex and
// ridiculous case.
$list = $this->lookupRecursiveFileList(
$repository,
array(
'rawPath' => $copy_from,
'rawCommit' => $copy_rev,
));
foreach ($list as $from_path => $from_file_type) {
$full_from = rtrim($copy_from.'/'.$from_path, '/');
$full_to = rtrim($path.'/'.$from_path, '/');
if (empty($raw_paths[$full_to])) {
$effects[$full_to] = array(
'rawPath' => $full_to,
'rawTargetPath' => $full_from,
'rawTargetCommit' => $copy_rev,
'rawDirect' => true,
'changeType' => $type,
'fileType' => $from_file_type,
);
} else {
// This means we picked the file up explicitly elsewhere.
// If the file as modified, SVN will drop the copy
// information. We need to restore it.
$supplemental[$full_to]['rawTargetPath'] = $full_from;
$supplemental[$full_to]['rawTargetCommit'] = $copy_rev;
if ($raw_paths[$full_to]['rawChangeType'] == 'M') {
$resolved_types[$full_to] = $type;
}
}
if (empty($raw_paths[$full_from]) &&
empty($effects[$full_from])) {
if ($other_type == DifferentialChangeType::TYPE_COPY_AWAY) {
// Add an indirect effect for the copied file, if we
// don't already have an entry for it (e.g., a separate
// change).
$effects[$full_from] = array(
'rawPath' => $full_from,
'rawTargetPath' => null,
'rawTargetCommit' => null,
'rawDirect' => false,
'changeType' => $other_type,
'fileType' => $from_file_type,
);
}
}
}
}
}
break;
// This is "replaced", caused by "svn rm"-ing a file, putting another
// in its place, and then "svn add"-ing it. We do not distinguish
// between this and "M".
case 'R':
case 'M':
if (isset($copied_or_moved_map[$path])) {
$type = DifferentialChangeType::TYPE_COPY_AWAY;
} else {
$type = DifferentialChangeType::TYPE_CHANGE;
}
break;
}
}
$resolved_types[$path] = $type;
}
foreach ($raw_paths as $path => $raw_info) {
$raw_paths[$path]['changeType'] = $resolved_types[$path];
if (isset($supplemental[$path])) {
foreach ($supplemental[$path] as $key => $value) {
$raw_paths[$path][$key] = $value;
}
}
}
foreach ($raw_paths as $path => $raw_info) {
$effects[$path] = array(
'rawPath' => $path,
'rawTargetPath' => $raw_info['rawTargetPath'],
'rawTargetCommit' => $raw_info['rawTargetCommit'],
'rawDirect' => true,
'changeType' => $raw_info['changeType'],
'fileType' => $path_file_types[$path],
);
}
$parents = array();
foreach ($effects as $path => $effect) {
foreach ($this->expandAllParentPaths($path) as $parent_path) {
$parents[$parent_path] = true;
}
}
$parents = array_keys($parents);
foreach ($parents as $parent) {
if (isset($effects[$parent])) {
continue;
}
$effects[$parent] = array(
'rawPath' => $parent,
'rawTargetPath' => null,
'rawTargetCommit' => null,
'rawDirect' => false,
'changeType' => DifferentialChangeType::TYPE_CHILD,
'fileType' => DifferentialChangeType::FILE_DIRECTORY,
);
}
$lookup_paths = array();
foreach ($effects as $effect) {
$lookup_paths[$effect['rawPath']] = true;
if ($effect['rawTargetPath']) {
$lookup_paths[$effect['rawTargetPath']] = true;
}
}
$lookup_paths = array_keys($lookup_paths);
$lookup_commits = array();
foreach ($effects as $effect) {
if ($effect['rawTargetCommit']) {
$lookup_commits[$effect['rawTargetCommit']] = true;
}
}
$lookup_commits = array_keys($lookup_commits);
$path_map = $this->lookupOrCreatePaths($lookup_paths);
$commit_map = $this->lookupSvnCommits($repository, $lookup_commits);
$this->writeBrowse($repository, $commit, $effects, $path_map);
return $this->buildChanges(
$repository,
$commit,
$effects,
$path_map,
$commit_map);
}
private function buildChanges(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit,
array $effects,
array $path_map,
array $commit_map) {
$results = array();
foreach ($effects as $effect) {
$path_id = $path_map[$effect['rawPath']];
$target_path_id = null;
if ($effect['rawTargetPath']) {
$target_path_id = $path_map[$effect['rawTargetPath']];
}
$target_commit_id = null;
if ($effect['rawTargetCommit']) {
$target_commit_id = $commit_map[$effect['rawTargetCommit']];
}
$result = id(new PhabricatorRepositoryParsedChange())
->setPathID($path_id)
->setTargetPathID($target_path_id)
->setTargetCommitID($target_commit_id)
->setChangeType($effect['changeType'])
->setFileType($effect['fileType'])
->setIsDirect($effect['rawDirect'])
->setCommitSequence($commit->getCommitIdentifier());
$results[] = $result;
}
return $results;
}
private function writeBrowse(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit,
array $effects,
array $path_map) {
$conn_w = $repository->establishConnection('w');
$sql = array();
foreach ($effects as $effect) {
$type = $effect['changeType'];
if (!$effect['rawDirect']) {
if ($type == DifferentialChangeType::TYPE_COPY_AWAY) {
// Don't write COPY_AWAY to the filesystem table if it isn't a direct
// event.
continue;
}
if ($type == DifferentialChangeType::TYPE_CHILD) {
// Don't write CHILD to the filesystem table. Although doing these
// writes has the nice property of letting you see when a directory's
// contents were last changed, it explodes the table tremendously
// and makes Diffusion far slower.
continue;
}
}
if ($effect['rawPath'] == '/') {
// Don't write any events on '/' to the filesystem table; in
// particular, it doesn't have a meaningful parentID.
continue;
}
$existed = !DifferentialChangeType::isDeleteChangeType($type);
$sql[] = qsprintf(
$conn_w,
'(%d, %d, %d, %d, %d, %d)',
$repository->getID(),
$path_map[$this->getParentPath($effect['rawPath'])],
$commit->getCommitIdentifier(),
$path_map[$effect['rawPath']],
$existed
? 1
: 0,
$effect['fileType']);
}
queryfx(
$conn_w,
'DELETE FROM %T WHERE repositoryID = %d AND svnCommit = %d',
PhabricatorRepository::TABLE_FILESYSTEM,
$repository->getID(),
$commit->getCommitIdentifier());
foreach (array_chunk($sql, 512) as $sql_chunk) {
queryfx(
$conn_w,
'INSERT INTO %T
(repositoryID, parentID, svnCommit, pathID, existed, fileType)
VALUES %LQ',
PhabricatorRepository::TABLE_FILESYSTEM,
$sql_chunk);
}
}
private function lookupSvnCommits(
PhabricatorRepository $repository,
array $commits) {
if (!$commits) {
return array();
}
$commit_table = new PhabricatorRepositoryCommit();
$commit_data = queryfx_all(
$commit_table->establishConnection('w'),
'SELECT id, commitIdentifier FROM %T
WHERE repositoryID = %d AND commitIdentifier in (%Ls)',
$commit_table->getTableName(),
$repository->getID(),
$commits);
$commit_map = ipull($commit_data, 'id', 'commitIdentifier');
$need = array();
foreach ($commits as $commit) {
if (empty($commit_map[$commit])) {
$need[] = $commit;
}
}
// If we are parsing a Subversion repository and have been configured to
// import only some subdirectory of it, we may find commits which reference
// other foreign commits outside of the directory (for instance, because of
// a move or copy). Rather than trying to execute full parses on them, just
// create stub commits and identify the stubs as foreign commits.
if ($need) {
$subpath = $repository->getDetail('svn-subpath');
if (!$subpath) {
throw new Exception(
pht(
'Missing commits (%s) in a SVN repository which is not '.
'configured for subdirectory-only parsing!',
implode(', ', $need)));
}
foreach ($need as $foreign_commit) {
$commit = new PhabricatorRepositoryCommit();
$commit->setRepositoryID($repository->getID());
$commit->setCommitIdentifier($foreign_commit);
$commit->setEpoch(0);
// Mark this commit as imported so it doesn't prevent the repository
// from transitioning into the "Imported" state.
$commit->setImportStatus(PhabricatorRepositoryCommit::IMPORTED_ALL);
$commit->save();
$data = new PhabricatorRepositoryCommitData();
$data->setCommitID($commit->getID());
$data->setAuthorName('');
$data->setCommitMessage('');
$data->setCommitDetails(
array(
'foreign-svn-stub' => true,
// Denormalize this to make it easier to debug cases where someone
// did half a parse and then changed the subdirectory or something
// like that.
'svn-subpath' => $subpath,
));
$data->save();
$commit_map[$foreign_commit] = $commit->getID();
}
}
return $commit_map;
}
private function lookupPathFileType(
PhabricatorRepository $repository,
$path,
array $path_info) {
$result = $this->lookupPathFileTypes(
$repository,
array(
$path => $path_info,
));
return $result[$path];
}
private function lookupPathFileTypes(
PhabricatorRepository $repository,
array $paths) {
$result_map = array();
$repository_uri = $repository->getSubversionPathURI();
if (isset($paths['/'])) {
$result_map['/'] = DifferentialChangeType::FILE_DIRECTORY;
unset($paths['/']);
}
$parents = array();
$path_mapping = array();
foreach ($paths as $path => $lookup) {
$parent = dirname($lookup['rawPath']);
$parent = $repository->getSubversionPathURI(
$parent,
$lookup['rawCommit']);
$parent = escapeshellarg($parent);
$parents[$parent] = true;
$path_mapping[$parent][] = dirname($path);
}
// Reverse this list so we can pop $path_mapping, as that's more efficient
// than shifting it. We need to associate these maps positionally because
// a change can copy the same source path from multiple revisions via
// "svn cp path@1 a; svn cp path@2 b;" and the XML output gives us no way
// to distinguish which revision we're looking at except based on its
// position in the document.
$all_paths = array_reverse(array_keys($parents));
foreach (array_chunk($all_paths, 64) as $path_chunk) {
list($raw_xml) = $repository->execxRemoteCommand(
'--xml ls %C',
implode(' ', $path_chunk));
$xml = new SimpleXMLElement($raw_xml);
foreach ($xml->list as $list) {
$list_path = (string)$list['path'];
// SVN is a big mess. See Facebook rG8 (a revision which adds files
// with spaces in their names) for an example.
$list_path = rawurldecode($list_path);
if ($list_path == $repository_uri) {
$base = '/';
} else {
$base = substr($list_path, strlen($repository_uri));
}
$mapping = array_pop($path_mapping);
foreach ($list->entry as $entry) {
$val = $this->getFileTypeFromSVNKind($entry['kind']);
foreach ($mapping as $base_path) {
// rtrim() causes us to handle top-level directories correctly.
$key = rtrim($base_path, '/').'/'.$entry->name;
$result_map[$key] = $val;
}
}
}
}
foreach ($paths as $path => $lookup) {
if (empty($result_map[$path])) {
$result_map[$path] = DifferentialChangeType::FILE_DELETED;
}
}
return $result_map;
}
private function getFileTypeFromSVNKind($kind) {
$kind = (string)$kind;
switch ($kind) {
case 'dir': return DifferentialChangeType::FILE_DIRECTORY;
case 'file': return DifferentialChangeType::FILE_NORMAL;
default:
throw new Exception(pht("Unknown SVN file kind '%s'.", $kind));
}
}
private function lookupRecursiveFileList(
PhabricatorRepository $repository,
array $info) {
$path = $info['rawPath'];
$rev = $info['rawCommit'];
$path_uri = $repository->getSubversionPathURI($path, $rev);
$hashkey = md5($path_uri);
// This method is quite horrible. The underlying challenge is that some
// commits in the Facebook repository are enormous, taking multiple hours
// to 'ls -R' out of the repository and producing XML files >1GB in size.
// If we try to SimpleXML them, the object exhausts available memory on a
// 64G machine. Instead, cache the XML output and then parse it line by line
// to limit space requirements.
$cache_loc = sys_get_temp_dir().'/diffusion.'.$hashkey.'.svnls';
if (!Filesystem::pathExists($cache_loc)) {
$tmp = new TempFile();
$repository->execxRemoteCommand(
'--xml ls -R %s > %s',
$path_uri,
$tmp);
execx(
'mv %s %s',
$tmp,
$cache_loc);
}
$map = $this->parseRecursiveListFileData($cache_loc);
Filesystem::remove($cache_loc);
return $map;
}
private function parseRecursiveListFileData($file_path) {
$map = array();
$mode = 'xml';
$done = false;
$entry = null;
foreach (new LinesOfALargeFile($file_path) as $lno => $line) {
switch ($mode) {
case 'entry':
if ($line == '</entry>') {
$entry = implode('', $entry);
$pattern = '@^\s+kind="(file|dir)">'.
'<name>(.*?)</name>'.
'(<size>(.*?)</size>)?@';
$matches = null;
if (!preg_match($pattern, $entry, $matches)) {
throw new Exception(pht('Unable to parse entry!'));
}
$map[html_entity_decode($matches[2])] =
$this->getFileTypeFromSVNKind($matches[1]);
$mode = 'entry-or-end';
} else {
$entry[] = $line;
}
break;
case 'entry-or-end':
if ($line == '</list>') {
$done = true;
break 2;
} else if ($line == '<entry') {
$mode = 'entry';
$entry = array();
} else {
throw new Exception(
pht(
'Expected %s or %s, got %s.',
'</list>',
'<entry',
$line));
}
break;
case 'xml':
$expect = '/<?xml version="1.0".*?>/';
if (!preg_match($expect, $line)) {
throw new Exception(
pht(
"Expected '%s', got %s.",
$expect,
$line));
}
$mode = 'list';
break;
case 'list':
$expect = '<lists>';
if ($line !== $expect) {
throw new Exception(
pht(
"Expected '%s', got %s.",
$expect,
$line));
}
$mode = 'list1';
break;
case 'list1':
$expect = '<list';
if ($line !== $expect) {
throw new Exception(
pht(
"Expected '%s', got %s.",
$expect,
$line));
}
$mode = 'list2';
break;
case 'list2':
if (!preg_match('/^\s+path="/', $line)) {
throw new Exception(
pht(
"Expected '%s', got %s.",
' path=...',
$line));
}
$mode = 'entry-or-end';
break;
}
}
if (!$done) {
throw new Exception(pht('Unexpected end of file.'));
}
return $map;
}
// TODO: Replace with DiffusionPathIDQuery::getParentPath().
private function getParentPath($path) {
$path = rtrim($path, '/');
$path = dirname($path);
if (!$path) {
$path = '/';
}
return $path;
}
// TODO: Replace with DiffusionPathIDQuery::expandPathToRoot().
private function expandAllParentPaths($path, $include_self = false) {
$parents = array();
if ($include_self) {
$parents[] = '/'.rtrim($path, '/');
}
$parts = explode('/', trim($path, '/'));
while (count($parts) >= 1) {
array_pop($parts);
$parents[] = '/'.implode('/', $parts);
}
return $parents;
}
private function getSVNLogXMLObject(
PhabricatorRepository $repository,
$uri,
$revision) {
list($xml) = $repository->execxRemoteCommand(
'log --xml --verbose --limit 1 %s@%d',
$uri,
$revision);
// 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);
return new SimpleXMLElement($xml);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/worker/commitchangeparser/PhabricatorRepositoryCommitChangeParserWorker.php | src/applications/repository/worker/commitchangeparser/PhabricatorRepositoryCommitChangeParserWorker.php | <?php
abstract class PhabricatorRepositoryCommitChangeParserWorker
extends PhabricatorRepositoryCommitParserWorker {
protected function getImportStepFlag() {
return PhabricatorRepositoryCommit::IMPORTED_CHANGE;
}
public function getRequiredLeaseTime() {
// It can take a very long time to parse commits; some commits in the
// Facebook repository affect many millions of paths. Acquire 24h leases.
return phutil_units('24 hours in seconds');
}
abstract protected function parseCommitChanges(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit);
protected function parseCommit(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit) {
$this->log("%s\n", pht('Parsing "%s"...', $commit->getMonogram()));
$hint = $this->loadCommitHint($commit);
if ($hint && $hint->isUnreadable()) {
$this->log(
pht(
'This commit is marked as unreadable, so changes will not be '.
'parsed.'));
return;
}
if (!$this->shouldSkipImportStep()) {
$results = $this->parseCommitChanges($repository, $commit);
if ($results) {
$this->writeCommitChanges($repository, $commit, $results);
}
$commit->writeImportStatusFlag($this->getImportStepFlag());
PhabricatorSearchWorker::queueDocumentForIndexing($commit->getPHID());
}
$this->finishParse();
}
public function parseChangesForUnitTest(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit) {
return $this->parseCommitChanges($repository, $commit);
}
public static function lookupOrCreatePaths(array $paths) {
$repository = new PhabricatorRepository();
$conn_w = $repository->establishConnection('w');
$result_map = self::lookupPaths($paths);
$missing_paths = array_fill_keys($paths, true);
$missing_paths = array_diff_key($missing_paths, $result_map);
$missing_paths = array_keys($missing_paths);
if ($missing_paths) {
foreach (array_chunk($missing_paths, 128) as $path_chunk) {
$sql = array();
foreach ($path_chunk as $path) {
$sql[] = qsprintf($conn_w, '(%s, %s)', $path, md5($path));
}
queryfx(
$conn_w,
'INSERT IGNORE INTO %T (path, pathHash) VALUES %LQ',
PhabricatorRepository::TABLE_PATH,
$sql);
}
$result_map += self::lookupPaths($missing_paths);
}
return $result_map;
}
private static function lookupPaths(array $paths) {
$repository = new PhabricatorRepository();
$conn_w = $repository->establishConnection('w');
$result_map = array();
foreach (array_chunk($paths, 128) as $path_chunk) {
$chunk_map = queryfx_all(
$conn_w,
'SELECT path, id FROM %T WHERE pathHash IN (%Ls)',
PhabricatorRepository::TABLE_PATH,
array_map('md5', $path_chunk));
foreach ($chunk_map as $row) {
$result_map[$row['path']] = $row['id'];
}
}
return $result_map;
}
protected function finishParse() {
$this->queueCommitTask('PhabricatorRepositoryCommitPublishWorker');
}
private function writeCommitChanges(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit,
array $changes) {
$conn = $repository->establishConnection('w');
$repository_id = (int)$repository->getID();
$commit_id = (int)$commit->getID();
$changes_sql = array();
foreach ($changes as $change) {
$changes_sql[] = qsprintf(
$conn,
'(%d, %d, %d, %nd, %nd, %d, %d, %d, %d)',
$repository_id,
(int)$change->getPathID(),
$commit_id,
nonempty((int)$change->getTargetPathID(), null),
nonempty((int)$change->getTargetCommitID(), null),
(int)$change->getChangeType(),
(int)$change->getFileType(),
(int)$change->getIsDirect(),
(int)$change->getCommitSequence());
}
queryfx(
$conn,
'DELETE FROM %T WHERE commitID = %d',
PhabricatorRepository::TABLE_PATHCHANGE,
$commit_id);
foreach (PhabricatorLiskDAO::chunkSQL($changes_sql) as $chunk) {
queryfx(
$conn,
'INSERT INTO %T
(repositoryID, pathID, commitID, targetPathID, targetCommitID,
changeType, fileType, isDirect, commitSequence)
VALUES %LQ',
PhabricatorRepository::TABLE_PATHCHANGE,
$chunk);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/worker/commitchangeparser/PhabricatorRepositoryGitCommitChangeParserWorker.php | src/applications/repository/worker/commitchangeparser/PhabricatorRepositoryGitCommitChangeParserWorker.php | <?php
final class PhabricatorRepositoryGitCommitChangeParserWorker
extends PhabricatorRepositoryCommitChangeParserWorker {
protected function parseCommitChanges(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit) {
$viewer = PhabricatorUser::getOmnipotentUser();
$raw = DiffusionQuery::callConduitWithDiffusionRequest(
$viewer,
DiffusionRequest::newFromDictionary(
array(
'repository' => $repository,
'user' => $viewer,
)),
'diffusion.internal.gitrawdiffquery',
array(
'commit' => $commit->getCommitIdentifier(),
));
$changes = array();
$move_away = array();
$copy_away = array();
$lines = explode("\n", $raw);
foreach ($lines as $line) {
if (!strlen(trim($line))) {
continue;
}
list($old_mode, $new_mode,
$old_hash, $new_hash,
$more_stuff) = preg_split('/ +/', $line, 5);
// We may only have two pieces here.
list($action, $src_path, $dst_path) = array_merge(
explode("\t", $more_stuff),
array(null));
// Normalize the paths for consistency with the SVN workflow.
$src_path = '/'.$src_path;
if ($dst_path) {
$dst_path = '/'.$dst_path;
}
$old_mode = intval($old_mode, 8);
$new_mode = intval($new_mode, 8);
switch ($new_mode & 0160000) {
case 0160000:
$file_type = DifferentialChangeType::FILE_SUBMODULE;
break;
case 0120000:
$file_type = DifferentialChangeType::FILE_SYMLINK;
break;
case 0040000:
$file_type = DifferentialChangeType::FILE_DIRECTORY;
break;
default:
$file_type = DifferentialChangeType::FILE_NORMAL;
break;
}
// TODO: We can detect binary changes as git does, through a combination
// of running 'git check-attr' for stuff like 'binary', 'merge' or 'diff',
// and by falling back to inspecting the first 8,000 characters of the
// buffer for null bytes (this is seriously git's algorithm, see
// buffer_is_binary() in xdiff-interface.c).
$change_type = null;
$change_path = $src_path;
$change_target = null;
$is_direct = true;
switch ($action[0]) {
case 'A':
$change_type = DifferentialChangeType::TYPE_ADD;
break;
case 'D':
$change_type = DifferentialChangeType::TYPE_DELETE;
break;
case 'C':
$change_type = DifferentialChangeType::TYPE_COPY_HERE;
$change_path = $dst_path;
$change_target = $src_path;
$copy_away[$change_target][] = $change_path;
break;
case 'R':
$change_type = DifferentialChangeType::TYPE_MOVE_HERE;
$change_path = $dst_path;
$change_target = $src_path;
$move_away[$change_target][] = $change_path;
break;
case 'T':
// Type of the file changed, fall through and treat it as a
// modification. Not 100% sure this is the right thing to do but it
// seems reasonable.
case 'M':
if ($file_type == DifferentialChangeType::FILE_DIRECTORY) {
$change_type = DifferentialChangeType::TYPE_CHILD;
$is_direct = false;
} else {
$change_type = DifferentialChangeType::TYPE_CHANGE;
}
break;
// NOTE: "U" (unmerged) and "X" (unknown) statuses are also possible
// in theory but shouldn't appear here.
default:
throw new Exception(pht("Failed to parse line '%s'.", $line));
}
$changes[$change_path] = array(
'repositoryID' => $repository->getID(),
'commitID' => $commit->getID(),
'path' => $change_path,
'changeType' => $change_type,
'fileType' => $file_type,
'isDirect' => $is_direct,
'commitSequence' => $commit->getEpoch(),
'targetPath' => $change_target,
'targetCommitID' => $change_target ? $commit->getID() : null,
);
}
// Add a change to '/' since git doesn't mention it.
$changes['/'] = array(
'repositoryID' => $repository->getID(),
'commitID' => $commit->getID(),
'path' => '/',
'changeType' => DifferentialChangeType::TYPE_CHILD,
'fileType' => DifferentialChangeType::FILE_DIRECTORY,
'isDirect' => false,
'commitSequence' => $commit->getEpoch(),
'targetPath' => null,
'targetCommitID' => null,
);
foreach ($copy_away as $change_path => $destinations) {
if (isset($move_away[$change_path])) {
$change_type = DifferentialChangeType::TYPE_MULTICOPY;
$is_direct = true;
unset($move_away[$change_path]);
} else {
$change_type = DifferentialChangeType::TYPE_COPY_AWAY;
// This change is direct if we picked up a modification above (i.e.,
// the original copy source was also edited). Otherwise the original
// wasn't touched, so leave it as an indirect change.
$is_direct = isset($changes[$change_path]);
}
$reference = $changes[reset($destinations)];
$changes[$change_path] = array(
'repositoryID' => $repository->getID(),
'commitID' => $commit->getID(),
'path' => $change_path,
'changeType' => $change_type,
'fileType' => $reference['fileType'],
'isDirect' => $is_direct,
'commitSequence' => $commit->getEpoch(),
'targetPath' => null,
'targetCommitID' => null,
);
}
foreach ($move_away as $change_path => $destinations) {
$reference = $changes[reset($destinations)];
$changes[$change_path] = array(
'repositoryID' => $repository->getID(),
'commitID' => $commit->getID(),
'path' => $change_path,
'changeType' => DifferentialChangeType::TYPE_MOVE_AWAY,
'fileType' => $reference['fileType'],
'isDirect' => true,
'commitSequence' => $commit->getEpoch(),
'targetPath' => null,
'targetCommitID' => null,
);
}
$paths = array();
foreach ($changes as $change) {
$paths[$change['path']] = true;
if ($change['targetPath']) {
$paths[$change['targetPath']] = true;
}
}
$path_map = $this->lookupOrCreatePaths(array_keys($paths));
foreach ($changes as $key => $change) {
$changes[$key]['pathID'] = $path_map[$change['path']];
if ($change['targetPath']) {
$changes[$key]['targetPathID'] = $path_map[$change['targetPath']];
} else {
$changes[$key]['targetPathID'] = null;
}
}
$results = array();
foreach ($changes as $change) {
$result = id(new PhabricatorRepositoryParsedChange())
->setPathID($change['pathID'])
->setTargetPathID($change['targetPathID'])
->setTargetCommitID($change['targetCommitID'])
->setChangeType($change['changeType'])
->setFileType($change['fileType'])
->setIsDirect($change['isDirect'])
->setCommitSequence($change['commitSequence']);
$results[] = $result;
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/worker/commitchangeparser/PhabricatorRepositoryMercurialCommitChangeParserWorker.php | src/applications/repository/worker/commitchangeparser/PhabricatorRepositoryMercurialCommitChangeParserWorker.php | <?php
final class PhabricatorRepositoryMercurialCommitChangeParserWorker
extends PhabricatorRepositoryCommitChangeParserWorker {
protected function parseCommitChanges(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit) {
list($stdout) = $repository->execxLocalCommand(
'status -C --change %s',
$commit->getCommitIdentifier());
$status = ArcanistMercurialParser::parseMercurialStatusDetails($stdout);
$common_attributes = array(
'repositoryID' => $repository->getID(),
'commitID' => $commit->getID(),
'commitSequence' => $commit->getEpoch(),
);
$changes = array();
// Like Git, Mercurial doesn't track directories directly. We need to infer
// directory creation and removal by observing file creation and removal
// and testing if the directories in question are previously empty (thus,
// created) or subsequently empty (thus, removed).
$maybe_new_directories = array();
$maybe_del_directories = array();
$all_directories = array();
// Parse the basic information from "hg status", which shows files that
// were directly affected by the change.
foreach ($status as $path => $path_info) {
$path = '/'.$path;
$flags = $path_info['flags'];
$change_target = $path_info['from'] ? '/'.$path_info['from'] : null;
$changes[$path] = array(
'path' => $path,
'isDirect' => true,
'targetPath' => $change_target,
'targetCommitID' => $change_target ? $commit->getID() : null,
// We're going to fill these in shortly.
'changeType' => null,
'fileType' => null,
'flags' => $flags,
) + $common_attributes;
if ($flags & ArcanistRepositoryAPI::FLAG_ADDED) {
$maybe_new_directories[] = dirname($path);
} else if ($flags & ArcanistRepositoryAPI::FLAG_DELETED) {
$maybe_del_directories[] = dirname($path);
}
$all_directories[] = dirname($path);
}
// Add change information for each source path which doesn't appear in the
// status. These files were copied, but were not modified. We also know they
// must exist.
foreach ($changes as $path => $change) {
$from = $change['targetPath'];
if ($from && empty($changes[$from])) {
$changes[$from] = array(
'path' => $from,
'isDirect' => false,
'targetPath' => null,
'targetCommitID' => null,
'changeType' => DifferentialChangeType::TYPE_COPY_AWAY,
'fileType' => null,
'flags' => 0,
) + $common_attributes;
}
}
$away = array();
foreach ($changes as $path => $change) {
$target_path = $change['targetPath'];
if ($target_path) {
$away[$target_path][] = $path;
}
}
// Now that we have all the direct changes, figure out change types.
foreach ($changes as $path => $change) {
$flags = $change['flags'];
$from = $change['targetPath'];
if ($from) {
$target = $changes[$from];
} else {
$target = null;
}
if ($flags & ArcanistRepositoryAPI::FLAG_ADDED) {
if ($target) {
if ($target['flags'] & ArcanistRepositoryAPI::FLAG_DELETED) {
$change_type = DifferentialChangeType::TYPE_MOVE_HERE;
} else {
$change_type = DifferentialChangeType::TYPE_COPY_HERE;
}
} else {
$change_type = DifferentialChangeType::TYPE_ADD;
}
} else if ($flags & ArcanistRepositoryAPI::FLAG_DELETED) {
if (isset($away[$path])) {
if (count($away[$path]) > 1) {
$change_type = DifferentialChangeType::TYPE_MULTICOPY;
} else {
$change_type = DifferentialChangeType::TYPE_MOVE_AWAY;
}
} else {
$change_type = DifferentialChangeType::TYPE_DELETE;
}
} else {
if (isset($away[$path])) {
$change_type = DifferentialChangeType::TYPE_COPY_AWAY;
} else {
$change_type = DifferentialChangeType::TYPE_CHANGE;
}
}
$changes[$path]['changeType'] = $change_type;
}
// Go through all the affected directories and identify any which were
// actually added or deleted.
$dir_status = array();
foreach ($maybe_del_directories as $dir) {
$exists = false;
foreach (DiffusionPathIDQuery::expandPathToRoot($dir) as $path) {
if (isset($dir_status[$path])) {
break;
}
// If we know some child exists, we know this path exists. If we don't
// know that a child exists, test if this directory still exists.
if (!$exists) {
$exists = $this->mercurialPathExists(
$repository,
$path,
$commit->getCommitIdentifier());
}
if ($exists) {
$dir_status[$path] = DifferentialChangeType::TYPE_CHILD;
} else {
$dir_status[$path] = DifferentialChangeType::TYPE_DELETE;
}
}
}
list($stdout) = $repository->execxLocalCommand(
'parents --rev %s --style default',
$commit->getCommitIdentifier());
$parents = ArcanistMercurialParser::parseMercurialLog($stdout);
$parent = reset($parents);
if ($parent) {
// TODO: We should expand this to a full 40-character hash using "hg id".
$parent = $parent['rev'];
}
foreach ($maybe_new_directories as $dir) {
$exists = false;
foreach (DiffusionPathIDQuery::expandPathToRoot($dir) as $path) {
if (isset($dir_status[$path])) {
break;
}
if (!$exists) {
if ($parent) {
$exists = $this->mercurialPathExists($repository, $path, $parent);
} else {
$exists = false;
}
}
if ($exists) {
$dir_status[$path] = DifferentialChangeType::TYPE_CHILD;
} else {
$dir_status[$path] = DifferentialChangeType::TYPE_ADD;
}
}
}
foreach ($all_directories as $dir) {
foreach (DiffusionPathIDQuery::expandPathToRoot($dir) as $path) {
if (isset($dir_status[$path])) {
break;
}
$dir_status[$path] = DifferentialChangeType::TYPE_CHILD;
}
}
// Merge all the directory statuses into the path statuses.
foreach ($dir_status as $path => $status) {
if (isset($changes[$path])) {
// TODO: The UI probably doesn't handle any of these cases with
// terrible elegance, but they are exceedingly rare.
$existing_type = $changes[$path]['changeType'];
if ($existing_type == DifferentialChangeType::TYPE_DELETE) {
// This change removes a file, replaces it with a directory, and then
// adds children of that directory. Mark it as a "change" instead,
// and make the type a directory.
$changes[$path]['fileType'] = DifferentialChangeType::FILE_DIRECTORY;
$changes[$path]['changeType'] = DifferentialChangeType::TYPE_CHANGE;
} else if ($existing_type == DifferentialChangeType::TYPE_MOVE_AWAY ||
$existing_type == DifferentialChangeType::TYPE_MULTICOPY) {
// This change moves or copies a file, replaces it with a directory,
// and then adds children to that directory. Mark it as "copy away"
// instead of whatever it was, and make the type a directory.
$changes[$path]['fileType'] = DifferentialChangeType::FILE_DIRECTORY;
$changes[$path]['changeType']
= DifferentialChangeType::TYPE_COPY_AWAY;
} else if ($existing_type == DifferentialChangeType::TYPE_ADD) {
// This change removes a directory and replaces it with a file. Mark
// it as "change" instead of "add".
$changes[$path]['changeType'] = DifferentialChangeType::TYPE_CHANGE;
}
continue;
}
$changes[$path] = array(
'path' => $path,
'isDirect' => ($status == DifferentialChangeType::TYPE_CHILD)
? false
: true,
'fileType' => DifferentialChangeType::FILE_DIRECTORY,
'changeType' => $status,
'targetPath' => null,
'targetCommitID' => null,
) + $common_attributes;
}
// TODO: use "hg diff --git" to figure out which files are symlinks.
foreach ($changes as $path => $change) {
if (empty($change['fileType'])) {
$changes[$path]['fileType'] = DifferentialChangeType::FILE_NORMAL;
}
}
$all_paths = array();
foreach ($changes as $path => $change) {
$all_paths[$path] = true;
if ($change['targetPath']) {
$all_paths[$change['targetPath']] = true;
}
}
$path_map = $this->lookupOrCreatePaths(array_keys($all_paths));
foreach ($changes as $key => $change) {
$changes[$key]['pathID'] = $path_map[$change['path']];
if ($change['targetPath']) {
$changes[$key]['targetPathID'] = $path_map[$change['targetPath']];
} else {
$changes[$key]['targetPathID'] = null;
}
}
$results = array();
foreach ($changes as $change) {
$result = id(new PhabricatorRepositoryParsedChange())
->setPathID($change['pathID'])
->setTargetPathID($change['targetPathID'])
->setTargetCommitID($change['targetCommitID'])
->setChangeType($change['changeType'])
->setFileType($change['fileType'])
->setIsDirect($change['isDirect'])
->setCommitSequence($change['commitSequence']);
$results[] = $result;
}
return $results;
}
private function mercurialPathExists(
PhabricatorRepository $repository,
$path,
$rev) {
if ($path == '/') {
return true;
}
// NOTE: For directories, this grabs the entire directory contents, but
// we don't have any more surgical approach available to us in Mercurial.
// We can't use "log" because it doesn't have enough information for us
// to figure out when a directory is deleted by a change.
list($err) = $repository->execLocalCommand(
'cat --rev %s -- %s > /dev/null',
$rev,
$path);
if ($err) {
return false;
} else {
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/repository/worker/__tests__/PhabricatorChangeParserTestCase.php | src/applications/repository/worker/__tests__/PhabricatorChangeParserTestCase.php | <?php
final class PhabricatorChangeParserTestCase
extends PhabricatorWorkingCopyTestCase {
public function testGitParser() {
$repository = $this->buildDiscoveredRepository('CHA');
$viewer = PhabricatorUser::getOmnipotentUser();
$commits = id(new DiffusionCommitQuery())
->setViewer($viewer)
->withRepositoryIDs(array($repository->getID()))
->execute();
$this->expectChanges(
$repository,
$commits,
array(
// 8ebb73c add +x
'8ebb73c3f127625ad090472f4f3bfc72804def54' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
1389892449,
),
array(
'/file_moved',
null,
null,
DifferentialChangeType::TYPE_CHANGE,
DifferentialChangeType::FILE_NORMAL,
1,
1389892449,
),
),
// ee9c790 add symlink
'ee9c7909e012da7d75e8e1293c7803a6e73ac26a' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
1389892436,
),
array(
'/file_link',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_SYMLINK,
1,
1389892436,
),
),
// 7260ca4 add directory file
'7260ca4b6cec35e755bb5365c4ccdd3f1977772e' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
1389892408,
),
array(
'/dir',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_DIRECTORY,
1,
1389892408,
),
array(
'/dir/subfile',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_NORMAL,
1,
1389892408,
),
),
// 1fe783c move a file
'1fe783cf207c1e5f3e01650d2d9cb80b8a707f0e' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
1389892388,
),
array(
'/file',
null,
null,
DifferentialChangeType::TYPE_MOVE_AWAY,
DifferentialChangeType::FILE_NORMAL,
1,
1389892388,
),
array(
'/file_moved',
'/file',
'1fe783cf207c1e5f3e01650d2d9cb80b8a707f0e',
DifferentialChangeType::TYPE_MOVE_HERE,
DifferentialChangeType::FILE_NORMAL,
1,
1389892388,
),
),
// 376af8c copy a file
'376af8cd8f5b96ec55b7d9a86ccc85b8df8fb833' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
1389892377,
),
array(
'/file',
null,
null,
DifferentialChangeType::TYPE_COPY_AWAY,
DifferentialChangeType::FILE_NORMAL,
0,
1389892377,
),
array(
'/file_copy',
'/file',
'376af8cd8f5b96ec55b7d9a86ccc85b8df8fb833',
DifferentialChangeType::TYPE_COPY_HERE,
DifferentialChangeType::FILE_NORMAL,
1,
1389892377,
),
),
// ece6ea6 changed a file
'ece6ea6c6836e8b11a103e21707b8f30e6840c94' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
1389892352,
),
array(
'/file',
null,
null,
DifferentialChangeType::TYPE_CHANGE,
DifferentialChangeType::FILE_NORMAL,
1,
1389892352,
),
),
// 513103f added a file
'513103f65b8413dd2f1a1b5c1d4852a4a598540f' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
// This is the initial commit and technically created this
// directory; arguably the parser should figure this out and
// mark this as a direct change.
0,
1389892330,
),
array(
'/file',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_NORMAL,
1,
1389892330,
),
),
));
}
public function testMercurialParser() {
$this->requireBinaryForTest('hg');
$repository = $this->buildDiscoveredRepository('CHB');
$viewer = PhabricatorUser::getOmnipotentUser();
$commits = id(new DiffusionCommitQuery())
->setViewer($viewer)
->withRepositoryIDs(array($repository->getID()))
->execute();
$this->expectChanges(
$repository,
$commits,
array(
'970357a2dc4264060e65d68e42240bb4e5984085' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
1390249395,
),
array(
'/file_moved',
null,
null,
DifferentialChangeType::TYPE_CHANGE,
DifferentialChangeType::FILE_NORMAL,
1,
1390249395,
),
),
'fbb49af9788e5dbffbc05a060b680df1fd457be3' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
1390249380,
),
array(
'/file_link',
null,
null,
DifferentialChangeType::TYPE_ADD,
// TODO: This is not correct, and should be FILE_SYMLINK. See
// note in the parser about this. This is a known bug.
DifferentialChangeType::FILE_NORMAL,
1,
1390249380,
),
),
'0e8d3465944c7ed7a7c139da7edc652cf80dba69' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
1390249342,
),
array(
'/dir',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_DIRECTORY,
1,
1390249342,
),
array(
'/dir/subfile',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_NORMAL,
1,
1390249342,
),
),
'22c75131ff15c8a44d7a729c4542b7f4c8ed27f4' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
1390249320,
),
array(
'/file',
null,
null,
DifferentialChangeType::TYPE_MOVE_AWAY,
DifferentialChangeType::FILE_NORMAL,
1,
1390249320,
),
array(
'/file_moved',
'/file',
'22c75131ff15c8a44d7a729c4542b7f4c8ed27f4',
DifferentialChangeType::TYPE_MOVE_HERE,
DifferentialChangeType::FILE_NORMAL,
1,
1390249320,
),
),
'd9d252df30cb7251ad3ea121eff30c7d2e36dd67' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
1390249308,
),
array(
'/file',
null,
null,
DifferentialChangeType::TYPE_COPY_AWAY,
DifferentialChangeType::FILE_NORMAL,
0,
1390249308,
),
array(
'/file_copy',
'/file',
'd9d252df30cb7251ad3ea121eff30c7d2e36dd67',
DifferentialChangeType::TYPE_COPY_HERE,
DifferentialChangeType::FILE_NORMAL,
1,
1390249308,
),
),
'1fc0445d5e3d0f33e9dcbb68bbe419a847460d25' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
1390249294,
),
array(
'/file',
null,
null,
DifferentialChangeType::TYPE_CHANGE,
DifferentialChangeType::FILE_NORMAL,
1,
1390249294,
),
),
'61518e196efb7f80700333cc0d00634c2578871a' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_DIRECTORY,
1,
1390249286,
),
array(
'/file',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_NORMAL,
1,
1390249286,
),
),
));
}
public function testSubversionParser() {
$this->requireBinaryForTest('svn');
$repository = $this->buildDiscoveredRepository('CHC');
$viewer = PhabricatorUser::getOmnipotentUser();
$commits = id(new DiffusionCommitQuery())
->setViewer($viewer)
->withRepositoryIDs(array($repository->getID()))
->execute();
$this->expectChanges(
$repository,
$commits,
array(
'15' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
15,
),
array(
'/file_copy',
null,
null,
DifferentialChangeType::TYPE_MULTICOPY,
DifferentialChangeType::FILE_NORMAL,
1,
15,
),
array(
'/file_copy_x',
'/file_copy',
'12',
DifferentialChangeType::TYPE_MOVE_HERE,
DifferentialChangeType::FILE_NORMAL,
1,
15,
),
array(
'/file_copy_y',
'/file_copy',
'12',
DifferentialChangeType::TYPE_MOVE_HERE,
DifferentialChangeType::FILE_NORMAL,
1,
15,
),
array(
'/file_copy_z',
'/file_copy',
'12',
DifferentialChangeType::TYPE_MOVE_HERE,
DifferentialChangeType::FILE_NORMAL,
1,
15,
),
),
// Add a file from a different revision
'14' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
14,
),
array(
'/file',
null,
null,
DifferentialChangeType::TYPE_COPY_AWAY,
DifferentialChangeType::FILE_NORMAL,
0,
14,
),
array(
'/file_1',
'/file',
'1',
DifferentialChangeType::TYPE_COPY_HERE,
DifferentialChangeType::FILE_NORMAL,
1,
14,
),
),
// Property change on "/"
'13' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHANGE,
DifferentialChangeType::FILE_DIRECTORY,
1,
13,
),
),
// Copy a directory, removing and adding files to the copy
'12' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
12,
),
array(
'/dir',
null,
null,
// TODO: This might reasonbly be considered a bug in the parser; it
// should probably be COPY_AWAY.
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
12,
),
array(
'/dir/a',
null,
null,
DifferentialChangeType::TYPE_COPY_AWAY,
DifferentialChangeType::FILE_NORMAL,
0,
12,
),
array(
'/dir/b',
null,
null,
DifferentialChangeType::TYPE_COPY_AWAY,
DifferentialChangeType::FILE_NORMAL,
0,
12,
),
array(
'/dir/subdir',
null,
null,
DifferentialChangeType::TYPE_COPY_AWAY,
DifferentialChangeType::FILE_DIRECTORY,
0,
12,
),
array(
'/dir/subdir/a',
null,
null,
DifferentialChangeType::TYPE_COPY_AWAY,
DifferentialChangeType::FILE_NORMAL,
0,
12,
),
array(
'/dir/subdir/b',
null,
null,
DifferentialChangeType::TYPE_COPY_AWAY,
DifferentialChangeType::FILE_NORMAL,
0,
12,
),
array(
'/dir_copy',
'/dir',
'11',
DifferentialChangeType::TYPE_COPY_HERE,
DifferentialChangeType::FILE_DIRECTORY,
1,
12,
),
array(
'/dir_copy/a',
'/dir/a',
'11',
DifferentialChangeType::TYPE_COPY_HERE,
DifferentialChangeType::FILE_NORMAL,
1,
12,
),
array(
'/dir_copy/b',
'/dir/b',
'11',
DifferentialChangeType::TYPE_COPY_HERE,
DifferentialChangeType::FILE_NORMAL,
1,
12,
),
array(
'/dir_copy/subdir',
'/dir/subdir',
'11',
DifferentialChangeType::TYPE_COPY_HERE,
DifferentialChangeType::FILE_DIRECTORY,
1,
12,
),
array(
'/dir_copy/subdir/a',
'/dir/subdir/a',
'11',
DifferentialChangeType::TYPE_COPY_HERE,
DifferentialChangeType::FILE_NORMAL,
1,
12,
),
array(
'/dir_copy/subdir/b',
'/dir/subdir/b',
'11',
DifferentialChangeType::TYPE_DELETE,
DifferentialChangeType::FILE_NORMAL,
1,
12,
),
array(
'/dir_copy/subdir/c',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_NORMAL,
1,
12,
),
),
// Add a directory with a subdirectory and files, sets up next commit
'11' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
11,
),
array(
'/dir',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_DIRECTORY,
1,
11,
),
array(
'/dir/a',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_NORMAL,
1,
11,
),
array(
'/dir/b',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_NORMAL,
1,
11,
),
array(
'/dir/subdir',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_DIRECTORY,
1,
11,
),
array(
'/dir/subdir/a',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_NORMAL,
1,
11,
),
array(
'/dir/subdir/b',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_NORMAL,
1,
11,
),
),
// Remove directory
'10' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
10,
),
array(
'/dir',
null,
null,
DifferentialChangeType::TYPE_DELETE,
DifferentialChangeType::FILE_DIRECTORY,
1,
10,
),
array(
'/dir/subfile',
null,
null,
DifferentialChangeType::TYPE_DELETE,
DifferentialChangeType::FILE_NORMAL,
1,
10,
),
),
// Replace directory with file
'9' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
9,
),
array(
'/file_moved',
null,
null,
DifferentialChangeType::TYPE_CHANGE,
DifferentialChangeType::FILE_DIRECTORY,
1,
9,
),
),
// Replace file with file
'8' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
8,
),
array(
'/file_moved',
null,
null,
DifferentialChangeType::TYPE_CHANGE,
DifferentialChangeType::FILE_NORMAL,
1,
8,
),
),
'7' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
7,
),
array(
'/file_moved',
null,
null,
DifferentialChangeType::TYPE_CHANGE,
DifferentialChangeType::FILE_NORMAL,
1,
7,
),
),
'6' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
6,
),
array(
'/file_link',
null,
null,
DifferentialChangeType::TYPE_ADD,
// TODO: This is not correct, and should be FILE_SYMLINK.
DifferentialChangeType::FILE_NORMAL,
1,
6,
),
),
'5' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
5,
),
array(
'/dir',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_DIRECTORY,
1,
5,
),
array(
'/dir/subfile',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_NORMAL,
1,
5,
),
),
'4' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
4,
),
array(
'/file',
null,
null,
DifferentialChangeType::TYPE_MOVE_AWAY,
DifferentialChangeType::FILE_NORMAL,
1,
4,
),
array(
'/file_moved',
'/file',
'2',
DifferentialChangeType::TYPE_MOVE_HERE,
DifferentialChangeType::FILE_NORMAL,
1,
4,
),
),
'3' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
3,
),
array(
'/file',
null,
null,
DifferentialChangeType::TYPE_COPY_AWAY,
DifferentialChangeType::FILE_NORMAL,
0,
3,
),
array(
'/file_copy',
'/file',
'2',
DifferentialChangeType::TYPE_COPY_HERE,
DifferentialChangeType::FILE_NORMAL,
1,
3,
),
),
'2' => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
2,
),
array(
'/file',
null,
null,
DifferentialChangeType::TYPE_CHANGE,
DifferentialChangeType::FILE_NORMAL,
1,
2,
),
),
'1' => array(
array(
'/',
null,
null,
// The Git and Svn parsers don't recognize the first commit as
// creating "/", while the Mercurial parser does. All the parsers
// should probably behave like the Mercurial parser.
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
1,
),
array(
'/file',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_NORMAL,
1,
1,
),
),
));
}
public function testSubversionPartialParser() {
$this->requireBinaryForTest('svn');
$repository = $this->buildBareRepository('CHD');
$repository->setDetail('svn-subpath', 'trunk/');
id(new PhabricatorRepositoryPullEngine())
->setRepository($repository)
->pullRepository();
id(new PhabricatorRepositoryDiscoveryEngine())
->setRepository($repository)
->discoverCommits();
$viewer = PhabricatorUser::getOmnipotentUser();
$commits = id(new DiffusionCommitQuery())
->setViewer($viewer)
->withRepositoryIDs(array($repository->getID()))
->execute();
$this->expectChanges(
$repository,
$commits,
array(
// Copy of a file outside of the subpath from an earlier revision
// into the subpath.
4 => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
4,
),
array(
'/goat',
null,
null,
DifferentialChangeType::TYPE_COPY_AWAY,
DifferentialChangeType::FILE_NORMAL,
0,
4,
),
array(
'/trunk',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
4,
),
array(
'/trunk/goat',
'/goat',
'1',
DifferentialChangeType::TYPE_COPY_HERE,
DifferentialChangeType::FILE_NORMAL,
1,
4,
),
),
3 => array(
array(
'/',
null,
null,
DifferentialChangeType::TYPE_CHILD,
DifferentialChangeType::FILE_DIRECTORY,
0,
3,
),
array(
'/trunk',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_DIRECTORY,
1,
3,
),
array(
'/trunk/apple',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_NORMAL,
1,
3,
),
array(
'/trunk/banana',
null,
null,
DifferentialChangeType::TYPE_ADD,
DifferentialChangeType::FILE_NORMAL,
1,
3,
),
),
));
}
public function testSubversionValidRootParser() {
$this->requireBinaryForTest('svn');
// First, automatically configure the root correctly.
$repository = $this->buildBareRepository('CHD');
id(new PhabricatorRepositoryPullEngine())
->setRepository($repository)
->pullRepository();
$caught = null;
try {
id(new PhabricatorRepositoryDiscoveryEngine())
->setRepository($repository)
->discoverCommits();
} catch (Exception $ex) {
$caught = $ex;
}
$this->assertFalse(
($caught instanceof Exception),
pht('Natural SVN root should work properly.'));
// This time, artificially break the root. We expect this to fail.
$repository = $this->buildBareRepository('CHD');
$repository->setDetail(
'remote-uri',
$repository->getDetail('remote-uri').'trunk/');
id(new PhabricatorRepositoryPullEngine())
->setRepository($repository)
->pullRepository();
$caught = null;
try {
id(new PhabricatorRepositoryDiscoveryEngine())
->setRepository($repository)
->discoverCommits();
} catch (Exception $ex) {
$caught = $ex;
}
$this->assertTrue(
($caught instanceof Exception),
pht('Artificial SVN root should fail.'));
}
public function testSubversionForeignStubsParser() {
$this->requireBinaryForTest('svn');
$repository = $this->buildBareRepository('CHE');
$repository->setDetail('svn-subpath', 'branch/');
id(new PhabricatorRepositoryPullEngine())
->setRepository($repository)
->pullRepository();
id(new PhabricatorRepositoryDiscoveryEngine())
->setRepository($repository)
->discoverCommits();
$viewer = PhabricatorUser::getOmnipotentUser();
$commits = id(new DiffusionCommitQuery())
->setViewer($viewer)
->withRepositoryIDs(array($repository->getID()))
->execute();
foreach ($commits as $commit) {
$this->parseCommit($repository, $commit);
}
// As a side effect, we expect parsing these commits to have created
// foreign stubs of other commits.
$commits = id(new DiffusionCommitQuery())
->setViewer($viewer)
->withRepositoryIDs(array($repository->getID()))
->execute();
$commits = mpull($commits, null, 'getCommitIdentifier');
$this->assertTrue(
isset($commits['2']),
pht('Expect %s to exist as a foreign stub.', 'rCHE2'));
// The foreign stub should be marked imported.
$commit = $commits['2'];
$this->assertEqual(
PhabricatorRepositoryCommit::IMPORTED_ALL,
(int)$commit->getImportStatus());
}
private function parseCommit(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit) {
switch ($repository->getVersionControlSystem()) {
case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
$parser = 'PhabricatorRepositoryGitCommitChangeParserWorker';
break;
case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL:
$parser = 'PhabricatorRepositoryMercurialCommitChangeParserWorker';
break;
case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN:
$parser = 'PhabricatorRepositorySvnCommitChangeParserWorker';
break;
default:
throw new Exception(pht('No support yet.'));
}
$parser_object = newv($parser, array(array()));
return $parser_object->parseChangesForUnitTest($repository, $commit);
}
private function expectChanges(
PhabricatorRepository $repository,
array $commits,
array $expect) {
foreach ($commits as $commit) {
$commit_identifier = $commit->getCommitIdentifier();
$expect_changes = idx($expect, $commit_identifier);
if ($expect_changes === null) {
$this->assertEqual(
$commit_identifier,
null,
pht(
'No test entry for commit "%s" in repository "%s"!',
$commit_identifier,
$repository->getDisplayName()));
}
$changes = $this->parseCommit($repository, $commit);
$path_map = id(new DiffusionPathQuery())
->withPathIDs(mpull($changes, 'getPathID'))
->execute();
$path_map = ipull($path_map, 'path');
$target_commits = array_filter(mpull($changes, 'getTargetCommitID'));
if ($target_commits) {
$commits = id(new DiffusionCommitQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withIDs($target_commits)
->execute();
$target_commits = mpull($commits, 'getCommitIdentifier', 'getID');
}
$dicts = array();
foreach ($changes as $key => $change) {
$target_path = idx($path_map, $change->getTargetPathID());
$target_commit = idx($target_commits, $change->getTargetCommitID());
$dicts[$key] = array(
$path_map[(int)$change->getPathID()],
$target_path,
$target_commit ? (string)$target_commit : null,
(int)$change->getChangeType(),
(int)$change->getFileType(),
(int)$change->getIsDirect(),
(int)$change->getCommitSequence(),
);
}
$dicts = ipull($dicts, null, 0);
$expect_changes = ipull($expect_changes, null, 0);
ksort($dicts);
ksort($expect_changes);
$this->assertEqual(
$expect_changes,
$dicts,
pht('Commit %s', $commit_identifier));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/query/PhabricatorRepositoryURIQuery.php | src/applications/repository/query/PhabricatorRepositoryURIQuery.php | <?php
final class PhabricatorRepositoryURIQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $repositoryPHIDs;
private $repositories = array();
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withRepositoryPHIDs(array $phids) {
$this->repositoryPHIDs = $phids;
return $this;
}
public function withRepositories(array $repositories) {
$repositories = mpull($repositories, null, 'getPHID');
$this->withRepositoryPHIDs(array_keys($repositories));
$this->repositories = $repositories;
return $this;
}
public function newResultObject() {
return new PhabricatorRepositoryURI();
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->repositoryPHIDs !== null) {
$where[] = qsprintf(
$conn,
'repositoryPHID IN (%Ls)',
$this->repositoryPHIDs);
}
return $where;
}
protected function willFilterPage(array $uris) {
$repositories = $this->repositories;
$repository_phids = mpull($uris, 'getRepositoryPHID');
$repository_phids = array_fuse($repository_phids);
$repository_phids = array_diff_key($repository_phids, $repositories);
if ($repository_phids) {
$more_repositories = id(new PhabricatorRepositoryQuery())
->setViewer($this->getViewer())
->withPHIDs($repository_phids)
->execute();
$repositories += mpull($more_repositories, null, 'getPHID');
}
foreach ($uris as $key => $uri) {
$repository_phid = $uri->getRepositoryPHID();
$repository = idx($repositories, $repository_phid);
if (!$repository) {
$this->didRejectResult($uri);
unset($uris[$key]);
continue;
}
$uri->attachRepository($repository);
}
return $uris;
}
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/repository/query/PhabricatorRepositoryQuery.php | src/applications/repository/query/PhabricatorRepositoryQuery.php | <?php
final class PhabricatorRepositoryQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $callsigns;
private $types;
private $uuids;
private $uris;
private $datasourceQuery;
private $slugs;
private $almanacServicePHIDs;
private $numericIdentifiers;
private $callsignIdentifiers;
private $phidIdentifiers;
private $monogramIdentifiers;
private $slugIdentifiers;
private $identifierMap;
const STATUS_OPEN = 'status-open';
const STATUS_CLOSED = 'status-closed';
const STATUS_ALL = 'status-all';
private $status = self::STATUS_ALL;
const HOSTED_PHABRICATOR = 'hosted-phab';
const HOSTED_REMOTE = 'hosted-remote';
const HOSTED_ALL = 'hosted-all';
private $hosted = self::HOSTED_ALL;
private $needMostRecentCommits;
private $needCommitCounts;
private $needProjectPHIDs;
private $needURIs;
private $needProfileImage;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withCallsigns(array $callsigns) {
$this->callsigns = $callsigns;
return $this;
}
public function withIdentifiers(array $identifiers) {
$identifiers = array_fuse($identifiers);
$ids = array();
$callsigns = array();
$phids = array();
$monograms = array();
$slugs = array();
foreach ($identifiers as $identifier) {
if (ctype_digit((string)$identifier)) {
$ids[$identifier] = $identifier;
continue;
}
if (preg_match('/^(r[A-Z]+|R[1-9]\d*)\z/', $identifier)) {
$monograms[$identifier] = $identifier;
continue;
}
$repository_type = PhabricatorRepositoryRepositoryPHIDType::TYPECONST;
if (phid_get_type($identifier) === $repository_type) {
$phids[$identifier] = $identifier;
continue;
}
if (preg_match('/^[A-Z]+\z/', $identifier)) {
$callsigns[$identifier] = $identifier;
continue;
}
$slugs[$identifier] = $identifier;
}
$this->numericIdentifiers = $ids;
$this->callsignIdentifiers = $callsigns;
$this->phidIdentifiers = $phids;
$this->monogramIdentifiers = $monograms;
$this->slugIdentifiers = $slugs;
return $this;
}
public function withStatus($status) {
$this->status = $status;
return $this;
}
public function withHosted($hosted) {
$this->hosted = $hosted;
return $this;
}
public function withTypes(array $types) {
$this->types = $types;
return $this;
}
public function withUUIDs(array $uuids) {
$this->uuids = $uuids;
return $this;
}
public function withURIs(array $uris) {
$this->uris = $uris;
return $this;
}
public function withDatasourceQuery($query) {
$this->datasourceQuery = $query;
return $this;
}
public function withSlugs(array $slugs) {
$this->slugs = $slugs;
return $this;
}
public function withAlmanacServicePHIDs(array $phids) {
$this->almanacServicePHIDs = $phids;
return $this;
}
public function needCommitCounts($need_counts) {
$this->needCommitCounts = $need_counts;
return $this;
}
public function needMostRecentCommits($need_commits) {
$this->needMostRecentCommits = $need_commits;
return $this;
}
public function needProjectPHIDs($need_phids) {
$this->needProjectPHIDs = $need_phids;
return $this;
}
public function needURIs($need_uris) {
$this->needURIs = $need_uris;
return $this;
}
public function needProfileImage($need) {
$this->needProfileImage = $need;
return $this;
}
public function getBuiltinOrders() {
return array(
'committed' => array(
'vector' => array('committed', 'id'),
'name' => pht('Most Recent Commit'),
),
'name' => array(
'vector' => array('name', 'id'),
'name' => pht('Name'),
),
'callsign' => array(
'vector' => array('callsign'),
'name' => pht('Callsign'),
),
'size' => array(
'vector' => array('size', 'id'),
'name' => pht('Size'),
),
) + parent::getBuiltinOrders();
}
public function getIdentifierMap() {
if ($this->identifierMap === null) {
throw new PhutilInvalidStateException('execute');
}
return $this->identifierMap;
}
protected function willExecute() {
$this->identifierMap = array();
}
public function newResultObject() {
return new PhabricatorRepository();
}
protected function loadPage() {
$table = $this->newResultObject();
$data = $this->loadStandardPageRows($table);
$repositories = $table->loadAllFromArray($data);
if ($this->needCommitCounts) {
$sizes = ipull($data, 'size', 'id');
foreach ($repositories as $id => $repository) {
$repository->attachCommitCount(nonempty($sizes[$id], 0));
}
}
if ($this->needMostRecentCommits) {
$commit_ids = ipull($data, 'lastCommitID', 'id');
$commit_ids = array_filter($commit_ids);
if ($commit_ids) {
$commits = id(new DiffusionCommitQuery())
->setViewer($this->getViewer())
->withIDs($commit_ids)
->needCommitData(true)
->needIdentities(true)
->execute();
} else {
$commits = array();
}
foreach ($repositories as $id => $repository) {
$commit = null;
if (idx($commit_ids, $id)) {
$commit = idx($commits, $commit_ids[$id]);
}
$repository->attachMostRecentCommit($commit);
}
}
return $repositories;
}
protected function willFilterPage(array $repositories) {
assert_instances_of($repositories, 'PhabricatorRepository');
// TODO: Denormalize repository status into the PhabricatorRepository
// table so we can do this filtering in the database.
foreach ($repositories as $key => $repo) {
$status = $this->status;
switch ($status) {
case self::STATUS_OPEN:
if (!$repo->isTracked()) {
unset($repositories[$key]);
}
break;
case self::STATUS_CLOSED:
if ($repo->isTracked()) {
unset($repositories[$key]);
}
break;
case self::STATUS_ALL:
break;
default:
throw new Exception("Unknown status '{$status}'!");
}
// TODO: This should also be denormalized.
$hosted = $this->hosted;
switch ($hosted) {
case self::HOSTED_PHABRICATOR:
if (!$repo->isHosted()) {
unset($repositories[$key]);
}
break;
case self::HOSTED_REMOTE:
if ($repo->isHosted()) {
unset($repositories[$key]);
}
break;
case self::HOSTED_ALL:
break;
default:
throw new Exception(pht("Unknown hosted failed '%s'!", $hosted));
}
}
// Build the identifierMap
if ($this->numericIdentifiers) {
foreach ($this->numericIdentifiers as $id) {
if (isset($repositories[$id])) {
$this->identifierMap[$id] = $repositories[$id];
}
}
}
if ($this->callsignIdentifiers) {
$repository_callsigns = mpull($repositories, null, 'getCallsign');
foreach ($this->callsignIdentifiers as $callsign) {
if (isset($repository_callsigns[$callsign])) {
$this->identifierMap[$callsign] = $repository_callsigns[$callsign];
}
}
}
if ($this->phidIdentifiers) {
$repository_phids = mpull($repositories, null, 'getPHID');
foreach ($this->phidIdentifiers as $phid) {
if (isset($repository_phids[$phid])) {
$this->identifierMap[$phid] = $repository_phids[$phid];
}
}
}
if ($this->monogramIdentifiers) {
$monogram_map = array();
foreach ($repositories as $repository) {
foreach ($repository->getAllMonograms() as $monogram) {
$monogram_map[$monogram] = $repository;
}
}
foreach ($this->monogramIdentifiers as $monogram) {
if (isset($monogram_map[$monogram])) {
$this->identifierMap[$monogram] = $monogram_map[$monogram];
}
}
}
if ($this->slugIdentifiers) {
$slug_map = array();
foreach ($repositories as $repository) {
$slug = $repository->getRepositorySlug();
if ($slug === null) {
continue;
}
$normal = phutil_utf8_strtolower($slug);
$slug_map[$normal] = $repository;
}
foreach ($this->slugIdentifiers as $slug) {
$normal = phutil_utf8_strtolower($slug);
if (isset($slug_map[$normal])) {
$this->identifierMap[$slug] = $slug_map[$normal];
}
}
}
return $repositories;
}
protected function didFilterPage(array $repositories) {
if ($this->needProjectPHIDs) {
$type_project = PhabricatorProjectObjectHasProjectEdgeType::EDGECONST;
$edge_query = id(new PhabricatorEdgeQuery())
->withSourcePHIDs(mpull($repositories, 'getPHID'))
->withEdgeTypes(array($type_project));
$edge_query->execute();
foreach ($repositories as $repository) {
$project_phids = $edge_query->getDestinationPHIDs(
array(
$repository->getPHID(),
));
$repository->attachProjectPHIDs($project_phids);
}
}
$viewer = $this->getViewer();
if ($this->needURIs) {
$uris = id(new PhabricatorRepositoryURIQuery())
->setViewer($viewer)
->withRepositories($repositories)
->execute();
$uri_groups = mgroup($uris, 'getRepositoryPHID');
foreach ($repositories as $repository) {
$repository_uris = idx($uri_groups, $repository->getPHID(), array());
$repository->attachURIs($repository_uris);
}
}
if ($this->needProfileImage) {
$default = null;
$file_phids = mpull($repositories, 'getProfileImagePHID');
$file_phids = array_filter($file_phids);
if ($file_phids) {
$files = id(new PhabricatorFileQuery())
->setParentQuery($this)
->setViewer($this->getViewer())
->withPHIDs($file_phids)
->execute();
$files = mpull($files, null, 'getPHID');
} else {
$files = array();
}
foreach ($repositories as $repository) {
$file = idx($files, $repository->getProfileImagePHID());
if (!$file) {
if (!$default) {
$default = PhabricatorFile::loadBuiltin(
$this->getViewer(),
'repo/code.png');
}
$file = $default;
}
$repository->attachProfileImageFile($file);
}
}
return $repositories;
}
protected function getPrimaryTableAlias() {
return 'r';
}
public function getOrderableColumns() {
return parent::getOrderableColumns() + array(
'committed' => array(
'table' => 's',
'column' => 'epoch',
'type' => 'int',
'null' => 'tail',
),
'callsign' => array(
'table' => 'r',
'column' => 'callsign',
'type' => 'string',
'unique' => true,
'reverse' => true,
'null' => 'tail',
),
'name' => array(
'table' => 'r',
'column' => 'name',
'type' => 'string',
'reverse' => true,
),
'size' => array(
'table' => 's',
'column' => 'size',
'type' => 'int',
'null' => 'tail',
),
);
}
protected function newPagingMapFromCursorObject(
PhabricatorQueryCursor $cursor,
array $keys) {
$repository = $cursor->getObject();
$map = array(
'id' => (int)$repository->getID(),
'callsign' => $repository->getCallsign(),
'name' => $repository->getName(),
);
if (isset($keys['committed'])) {
$map['committed'] = $cursor->getRawRowProperty('epoch');
}
if (isset($keys['size'])) {
$map['size'] = $cursor->getRawRowProperty('size');
}
return $map;
}
protected function buildSelectClauseParts(AphrontDatabaseConnection $conn) {
$parts = parent::buildSelectClauseParts($conn);
if ($this->shouldJoinSummaryTable()) {
$parts[] = qsprintf($conn, 's.*');
}
return $parts;
}
protected function buildJoinClauseParts(AphrontDatabaseConnection $conn) {
$joins = parent::buildJoinClauseParts($conn);
if ($this->shouldJoinSummaryTable()) {
$joins[] = qsprintf(
$conn,
'LEFT JOIN %T s ON r.id = s.repositoryID',
PhabricatorRepository::TABLE_SUMMARY);
}
if ($this->shouldJoinURITable()) {
$joins[] = qsprintf(
$conn,
'LEFT JOIN %R uri ON r.phid = uri.repositoryPHID',
new PhabricatorRepositoryURIIndex());
}
return $joins;
}
protected function shouldGroupQueryResultRows() {
if ($this->shouldJoinURITable()) {
return true;
}
return parent::shouldGroupQueryResultRows();
}
private function shouldJoinURITable() {
return ($this->uris !== null);
}
private function shouldJoinSummaryTable() {
if ($this->needCommitCounts) {
return true;
}
if ($this->needMostRecentCommits) {
return true;
}
$vector = $this->getOrderVector();
if ($vector->containsKey('committed')) {
return true;
}
if ($vector->containsKey('size')) {
return true;
}
return false;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'r.id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'r.phid IN (%Ls)',
$this->phids);
}
if ($this->callsigns !== null) {
$where[] = qsprintf(
$conn,
'r.callsign IN (%Ls)',
$this->callsigns);
}
if ($this->numericIdentifiers ||
$this->callsignIdentifiers ||
$this->phidIdentifiers ||
$this->monogramIdentifiers ||
$this->slugIdentifiers) {
$identifier_clause = array();
if ($this->numericIdentifiers) {
$identifier_clause[] = qsprintf(
$conn,
'r.id IN (%Ld)',
$this->numericIdentifiers);
}
if ($this->callsignIdentifiers) {
$identifier_clause[] = qsprintf(
$conn,
'r.callsign IN (%Ls)',
$this->callsignIdentifiers);
}
if ($this->phidIdentifiers) {
$identifier_clause[] = qsprintf(
$conn,
'r.phid IN (%Ls)',
$this->phidIdentifiers);
}
if ($this->monogramIdentifiers) {
$monogram_callsigns = array();
$monogram_ids = array();
foreach ($this->monogramIdentifiers as $identifier) {
if ($identifier[0] == 'r') {
$monogram_callsigns[] = substr($identifier, 1);
} else {
$monogram_ids[] = substr($identifier, 1);
}
}
if ($monogram_ids) {
$identifier_clause[] = qsprintf(
$conn,
'r.id IN (%Ld)',
$monogram_ids);
}
if ($monogram_callsigns) {
$identifier_clause[] = qsprintf(
$conn,
'r.callsign IN (%Ls)',
$monogram_callsigns);
}
}
if ($this->slugIdentifiers) {
$identifier_clause[] = qsprintf(
$conn,
'r.repositorySlug IN (%Ls)',
$this->slugIdentifiers);
}
$where[] = qsprintf($conn, '%LO', $identifier_clause);
}
if ($this->types) {
$where[] = qsprintf(
$conn,
'r.versionControlSystem IN (%Ls)',
$this->types);
}
if ($this->uuids) {
$where[] = qsprintf(
$conn,
'r.uuid IN (%Ls)',
$this->uuids);
}
if (phutil_nonempty_string($this->datasourceQuery)) {
// This handles having "rP" match callsigns starting with "P...".
$query = trim($this->datasourceQuery);
if (preg_match('/^r/', $query)) {
$callsign = substr($query, 1);
} else {
$callsign = $query;
}
$where[] = qsprintf(
$conn,
'r.name LIKE %> OR r.callsign LIKE %> OR r.repositorySlug LIKE %>',
$query,
$callsign,
$query);
}
if ($this->slugs !== null) {
$where[] = qsprintf(
$conn,
'r.repositorySlug IN (%Ls)',
$this->slugs);
}
if ($this->uris !== null) {
$try_uris = $this->getNormalizedURIs();
$try_uris = array_fuse($try_uris);
$where[] = qsprintf(
$conn,
'uri.repositoryURI IN (%Ls)',
$try_uris);
}
if ($this->almanacServicePHIDs !== null) {
$where[] = qsprintf(
$conn,
'r.almanacServicePHID IN (%Ls)',
$this->almanacServicePHIDs);
}
return $where;
}
public function getQueryApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
private function getNormalizedURIs() {
$normalized_uris = array();
// Since we don't know which type of repository this URI is in the general
// case, just generate all the normalizations. We could refine this in some
// cases: if the query specifies VCS types, or the URI is a git-style URI
// or an `svn+ssh` URI, we could deduce how to normalize it. However, this
// would be more complicated and it's not clear if it matters in practice.
$domain_map = PhabricatorRepositoryURI::getURINormalizerDomainMap();
$types = ArcanistRepositoryURINormalizer::getAllURITypes();
foreach ($this->uris as $uri) {
foreach ($types as $type) {
$normalized_uri = new ArcanistRepositoryURINormalizer($type, $uri);
$normalized_uri->setDomainMap($domain_map);
$normalized_uris[] = $normalized_uri->getNormalizedURI();
}
}
return array_unique($normalized_uris);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/query/PhabricatorRepositoryGitLFSRefQuery.php | src/applications/repository/query/PhabricatorRepositoryGitLFSRefQuery.php | <?php
final class PhabricatorRepositoryGitLFSRefQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $repositoryPHIDs;
private $objectHashes;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withRepositoryPHIDs(array $phids) {
$this->repositoryPHIDs = $phids;
return $this;
}
public function withObjectHashes(array $hashes) {
$this->objectHashes = $hashes;
return $this;
}
public function newResultObject() {
return new PhabricatorRepositoryGitLFSRef();
}
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->objectHashes !== null) {
$where[] = qsprintf(
$conn,
'objectHash IN (%Ls)',
$this->objectHashes);
}
return $where;
}
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/repository/query/PhabricatorRepositoryIdentityQuery.php | src/applications/repository/query/PhabricatorRepositoryIdentityQuery.php | <?php
final class PhabricatorRepositoryIdentityQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $identityNames;
private $emailAddresses;
private $assignedPHIDs;
private $effectivePHIDs;
private $identityNameLike;
private $hasEffectivePHID;
private $relatedPHIDs;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withIdentityNames(array $names) {
$this->identityNames = $names;
return $this;
}
public function withIdentityNameLike($name_like) {
$this->identityNameLike = $name_like;
return $this;
}
public function withEmailAddresses(array $addresses) {
$this->emailAddresses = $addresses;
return $this;
}
public function withAssignedPHIDs(array $assigned) {
$this->assignedPHIDs = $assigned;
return $this;
}
public function withEffectivePHIDs(array $effective) {
$this->effectivePHIDs = $effective;
return $this;
}
public function withRelatedPHIDs(array $related) {
$this->relatedPHIDs = $related;
return $this;
}
public function withHasEffectivePHID($has_effective_phid) {
$this->hasEffectivePHID = $has_effective_phid;
return $this;
}
public function newResultObject() {
return new PhabricatorRepositoryIdentity();
}
protected function getPrimaryTableAlias() {
return 'identity';
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'identity.id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'identity.phid IN (%Ls)',
$this->phids);
}
if ($this->assignedPHIDs !== null) {
$where[] = qsprintf(
$conn,
'identity.manuallySetUserPHID IN (%Ls)',
$this->assignedPHIDs);
}
if ($this->effectivePHIDs !== null) {
$where[] = qsprintf(
$conn,
'identity.currentEffectiveUserPHID IN (%Ls)',
$this->effectivePHIDs);
}
if ($this->hasEffectivePHID !== null) {
if ($this->hasEffectivePHID) {
$where[] = qsprintf(
$conn,
'identity.currentEffectiveUserPHID IS NOT NULL');
} else {
$where[] = qsprintf(
$conn,
'identity.currentEffectiveUserPHID IS NULL');
}
}
if ($this->identityNames !== null) {
$name_hashes = array();
foreach ($this->identityNames as $name) {
$name_hashes[] = PhabricatorHash::digestForIndex($name);
}
$where[] = qsprintf(
$conn,
'identity.identityNameHash IN (%Ls)',
$name_hashes);
}
if ($this->emailAddresses !== null) {
$where[] = qsprintf(
$conn,
'identity.emailAddress IN (%Ls)',
$this->emailAddresses);
}
if ($this->identityNameLike != null) {
$where[] = qsprintf(
$conn,
'identity.identityNameRaw LIKE %~',
$this->identityNameLike);
}
if ($this->relatedPHIDs !== null) {
$where[] = qsprintf(
$conn,
'(identity.manuallySetUserPHID IN (%Ls) OR
identity.currentEffectiveUserPHID IN (%Ls) OR
identity.automaticGuessedUserPHID IN (%Ls))',
$this->relatedPHIDs,
$this->relatedPHIDs,
$this->relatedPHIDs);
}
return $where;
}
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/repository/query/PhabricatorRepositoryTransactionQuery.php | src/applications/repository/query/PhabricatorRepositoryTransactionQuery.php | <?php
final class PhabricatorRepositoryTransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new PhabricatorRepositoryTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/query/PhabricatorRepositoryPushLogSearchEngine.php | src/applications/repository/query/PhabricatorRepositoryPushLogSearchEngine.php | <?php
final class PhabricatorRepositoryPushLogSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Push Logs');
}
public function getApplicationClassName() {
return 'PhabricatorDiffusionApplication';
}
public function newQuery() {
return new PhabricatorRepositoryPushLogQuery();
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['repositoryPHIDs']) {
$query->withRepositoryPHIDs($map['repositoryPHIDs']);
}
if ($map['pusherPHIDs']) {
$query->withPusherPHIDs($map['pusherPHIDs']);
}
if ($map['createdStart'] || $map['createdEnd']) {
$query->withEpochBetween(
$map['createdStart'],
$map['createdEnd']);
}
if ($map['blockingHeraldRulePHIDs']) {
$query->withBlockingHeraldRulePHIDs($map['blockingHeraldRulePHIDs']);
}
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 push logs for specific repositories.')),
id(new PhabricatorUsersSearchField())
->setKey('pusherPHIDs')
->setAliases(array('pusher', 'pushers', 'pusherPHID'))
->setLabel(pht('Pushers'))
->setDescription(
pht('Search for push logs by specific users.')),
id(new PhabricatorSearchDatasourceField())
->setDatasource(new HeraldRuleDatasource())
->setKey('blockingHeraldRulePHIDs')
->setLabel(pht('Blocked By'))
->setDescription(
pht('Search for pushes blocked by particular Herald rules.')),
id(new PhabricatorSearchDateField())
->setLabel(pht('Created After'))
->setKey('createdStart'),
id(new PhabricatorSearchDateField())
->setLabel(pht('Created Before'))
->setKey('createdEnd'),
);
}
protected function getURI($path) {
return '/diffusion/pushlog/'.$path;
}
protected function getBuiltinQueryNames() {
return array(
'all' => pht('All Push 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 DiffusionPushLogListView())
->setViewer($this->requireViewer())
->setLogs($logs);
return id(new PhabricatorApplicationSearchResultView())
->setTable($table);
}
protected function newExportFields() {
$viewer = $this->requireViewer();
$fields = array(
id(new PhabricatorIDExportField())
->setKey('pushID')
->setLabel(pht('Push ID')),
id(new PhabricatorStringExportField())
->setKey('unique')
->setLabel(pht('Unique')),
id(new PhabricatorStringExportField())
->setKey('protocol')
->setLabel(pht('Protocol')),
id(new PhabricatorPHIDExportField())
->setKey('repositoryPHID')
->setLabel(pht('Repository PHID')),
id(new PhabricatorStringExportField())
->setKey('repository')
->setLabel(pht('Repository')),
id(new PhabricatorPHIDExportField())
->setKey('pusherPHID')
->setLabel(pht('Pusher PHID')),
id(new PhabricatorStringExportField())
->setKey('pusher')
->setLabel(pht('Pusher')),
id(new PhabricatorPHIDExportField())
->setKey('devicePHID')
->setLabel(pht('Device PHID')),
id(new PhabricatorStringExportField())
->setKey('device')
->setLabel(pht('Device')),
id(new PhabricatorStringExportField())
->setKey('type')
->setLabel(pht('Ref Type')),
id(new PhabricatorStringExportField())
->setKey('name')
->setLabel(pht('Ref Name')),
id(new PhabricatorStringExportField())
->setKey('old')
->setLabel(pht('Ref Old')),
id(new PhabricatorStringExportField())
->setKey('new')
->setLabel(pht('Ref New')),
id(new PhabricatorIntExportField())
->setKey('flags')
->setLabel(pht('Flags')),
id(new PhabricatorStringListExportField())
->setKey('flagNames')
->setLabel(pht('Flag Names')),
id(new PhabricatorIntExportField())
->setKey('result')
->setLabel(pht('Result')),
id(new PhabricatorStringExportField())
->setKey('resultName')
->setLabel(pht('Result Name')),
id(new PhabricatorStringExportField())
->setKey('resultDetails')
->setLabel(pht('Result Details')),
id(new PhabricatorIntExportField())
->setKey('hostWait')
->setLabel(pht('Host Wait (us)')),
id(new PhabricatorIntExportField())
->setKey('writeWait')
->setLabel(pht('Write Wait (us)')),
id(new PhabricatorIntExportField())
->setKey('readWait')
->setLabel(pht('Read Wait (us)')),
id(new PhabricatorIntExportField())
->setKey('hookWait')
->setLabel(pht('Hook Wait (us)')),
);
if ($viewer->getIsAdmin()) {
$fields[] = id(new PhabricatorStringExportField())
->setKey('remoteAddress')
->setLabel(pht('Remote Address'));
}
return $fields;
}
protected function newExportData(array $logs) {
$viewer = $this->requireViewer();
$phids = array();
foreach ($logs as $log) {
$phids[] = $log->getPusherPHID();
$phids[] = $log->getDevicePHID();
$phids[] = $log->getPushEvent()->getRepositoryPHID();
}
$handles = $viewer->loadHandles($phids);
$flag_map = PhabricatorRepositoryPushLog::getFlagDisplayNames();
$reject_map = PhabricatorRepositoryPushLog::getRejectCodeDisplayNames();
$export = array();
foreach ($logs as $log) {
$event = $log->getPushEvent();
$repository_phid = $event->getRepositoryPHID();
if ($repository_phid) {
$repository_name = $handles[$repository_phid]->getName();
} else {
$repository_name = null;
}
$pusher_phid = $log->getPusherPHID();
if ($pusher_phid) {
$pusher_name = $handles[$pusher_phid]->getName();
} else {
$pusher_name = null;
}
$device_phid = $log->getDevicePHID();
if ($device_phid) {
$device_name = $handles[$device_phid]->getName();
} else {
$device_name = 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;
}
}
$result = $event->getRejectCode();
$result_name = idx($reject_map, $result, pht('Unknown ("%s")', $result));
$map = array(
'pushID' => $event->getID(),
'unique' => $event->getRequestIdentifier(),
'protocol' => $event->getRemoteProtocol(),
'repositoryPHID' => $repository_phid,
'repository' => $repository_name,
'pusherPHID' => $pusher_phid,
'pusher' => $pusher_name,
'devicePHID' => $device_phid,
'device' => $device_name,
'type' => $log->getRefType(),
'name' => $log->getRefName(),
'old' => $log->getRefOld(),
'new' => $log->getRefNew(),
'flags' => $flags,
'flagNames' => $flag_names,
'result' => $result,
'resultName' => $result_name,
'resultDetails' => $event->getRejectDetails(),
'hostWait' => $event->getHostWait(),
'writeWait' => $event->getWriteWait(),
'readWait' => $event->getReadWait(),
'hookWait' => $event->getHookWait(),
);
if ($viewer->getIsAdmin()) {
$map['remoteAddress'] = $event->getRemoteAddress();
}
$export[] = $map;
}
return $export;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/query/PhabricatorRepositoryPullEventQuery.php | src/applications/repository/query/PhabricatorRepositoryPullEventQuery.php | <?php
final class PhabricatorRepositoryPullEventQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $repositoryPHIDs;
private $pullerPHIDs;
private $epochMin;
private $epochMax;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withRepositoryPHIDs(array $repository_phids) {
$this->repositoryPHIDs = $repository_phids;
return $this;
}
public function withPullerPHIDs(array $puller_phids) {
$this->pullerPHIDs = $puller_phids;
return $this;
}
public function withEpochBetween($min, $max) {
$this->epochMin = $min;
$this->epochMax = $max;
return $this;
}
public function newResultObject() {
return new PhabricatorRepositoryPullEvent();
}
protected function willFilterPage(array $events) {
// If a pull targets an invalid repository or fails before authenticating,
// it may not have an associated repository.
$repository_phids = mpull($events, 'getRepositoryPHID');
$repository_phids = array_filter($repository_phids);
if ($repository_phids) {
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($this->getViewer())
->withPHIDs($repository_phids)
->execute();
$repositories = mpull($repositories, null, 'getPHID');
} else {
$repositories = array();
}
foreach ($events as $key => $event) {
$phid = $event->getRepositoryPHID();
if (!$phid) {
$event->attachRepository(null);
continue;
}
if (empty($repositories[$phid])) {
unset($events[$key]);
$this->didRejectResult($event);
continue;
}
$event->attachRepository($repositories[$phid]);
}
return $events;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->repositoryPHIDs !== null) {
$where[] = qsprintf(
$conn,
'repositoryPHID IN (%Ls)',
$this->repositoryPHIDs);
}
if ($this->pullerPHIDs !== null) {
$where[] = qsprintf(
$conn,
'pullerPHID in (%Ls)',
$this->pullerPHIDs);
}
if ($this->epochMin !== null) {
$where[] = qsprintf(
$conn,
'epoch >= %d',
$this->epochMin);
}
if ($this->epochMax !== null) {
$where[] = qsprintf(
$conn,
'epoch <= %d',
$this->epochMax);
}
return $where;
}
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/repository/query/PhabricatorRepositoryPublisher.php | src/applications/repository/query/PhabricatorRepositoryPublisher.php | <?php
final class PhabricatorRepositoryPublisher
extends Phobject {
private $repository;
const HOLD_IMPORTING = 'auto/importing';
const HOLD_PUBLISHING_DISABLED = 'auto/disabled';
const HOLD_REF_NOT_BRANCH = 'not-branch';
const HOLD_NOT_REACHABLE_FROM_PERMANENT_REF = 'auto/nobranch';
const HOLD_UNTRACKED = 'auto/notrack';
const HOLD_NOT_PERMANENT_REF = 'auto/noclose';
public function setRepository(PhabricatorRepository $repository) {
$this->repository = $repository;
return $this;
}
public function getRepository() {
if (!$this->repository) {
throw new PhutilInvalidStateException('setRepository');
}
return $this->repository;
}
/* -( Publishing )--------------------------------------------------------- */
public function shouldPublishRepository() {
return !$this->getRepositoryHoldReasons();
}
public function shouldPublishRef(DiffusionRepositoryRef $ref) {
return !$this->getRefHoldReasons($ref);
}
public function shouldPublishCommit(PhabricatorRepositoryCommit $commit) {
return !$this->getCommitHoldReasons($commit);
}
public function isPermanentRef(DiffusionRepositoryRef $ref) {
return !$this->getRefImpermanentReasons($ref);
}
/* -( Hold Reasons )------------------------------------------------------- */
public function getRepositoryHoldReasons() {
$repository = $this->getRepository();
$reasons = array();
if ($repository->isImporting()) {
$reasons[] = self::HOLD_IMPORTING;
}
if ($repository->isPublishingDisabled()) {
$reasons[] = self::HOLD_PUBLISHING_DISABLED;
}
return $reasons;
}
public function getRefHoldReasons(DiffusionRepositoryRef $ref) {
$repository = $this->getRepository();
$reasons = $this->getRepositoryHoldReasons();
foreach ($this->getRefImpermanentReasons($ref) as $reason) {
$reasons[] = $reason;
}
return $reasons;
}
public function getCommitHoldReasons(PhabricatorRepositoryCommit $commit) {
$repository = $this->getRepository();
$reasons = $this->getRepositoryHoldReasons();
if ($repository->isGit()) {
if (!$commit->isPermanentCommit()) {
$reasons[] = self::HOLD_NOT_REACHABLE_FROM_PERMANENT_REF;
}
}
return $reasons;
}
public function getRefImpermanentReasons(DiffusionRepositoryRef $ref) {
$repository = $this->getRepository();
$reasons = array();
if (!$ref->isBranch()) {
$reasons[] = self::HOLD_REF_NOT_BRANCH;
} else {
$branch_name = $ref->getShortName();
if (!$repository->shouldTrackBranch($branch_name)) {
$reasons[] = self::HOLD_UNTRACKED;
}
if (!$repository->isBranchPermanentRef($branch_name)) {
$reasons[] = self::HOLD_NOT_PERMANENT_REF;
}
}
return $reasons;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/query/PhabricatorRepositoryPushEventQuery.php | src/applications/repository/query/PhabricatorRepositoryPushEventQuery.php | <?php
final class PhabricatorRepositoryPushEventQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $repositoryPHIDs;
private $pusherPHIDs;
private $needLogs;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withRepositoryPHIDs(array $repository_phids) {
$this->repositoryPHIDs = $repository_phids;
return $this;
}
public function withPusherPHIDs(array $pusher_phids) {
$this->pusherPHIDs = $pusher_phids;
return $this;
}
public function needLogs($need_logs) {
$this->needLogs = $need_logs;
return $this;
}
public function newResultObject() {
return new PhabricatorRepositoryPushEvent();
}
protected function willFilterPage(array $events) {
$repository_phids = mpull($events, 'getRepositoryPHID');
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($this->getViewer())
->withPHIDs($repository_phids)
->execute();
$repositories = mpull($repositories, null, 'getPHID');
foreach ($events as $key => $event) {
$phid = $event->getRepositoryPHID();
if (empty($repositories[$phid])) {
unset($events[$key]);
continue;
}
$event->attachRepository($repositories[$phid]);
}
return $events;
}
protected function didFilterPage(array $events) {
$phids = mpull($events, 'getPHID');
if ($this->needLogs) {
$logs = id(new PhabricatorRepositoryPushLogQuery())
->setParentQuery($this)
->setViewer($this->getViewer())
->withPushEventPHIDs($phids)
->execute();
$logs = mgroup($logs, 'getPushEventPHID');
foreach ($events as $key => $event) {
$event_logs = idx($logs, $event->getPHID(), array());
$event->attachLogs($event_logs);
}
}
return $events;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->repositoryPHIDs !== null) {
$where[] = qsprintf(
$conn,
'repositoryPHID IN (%Ls)',
$this->repositoryPHIDs);
}
if ($this->pusherPHIDs !== null) {
$where[] = qsprintf(
$conn,
'pusherPHID in (%Ls)',
$this->pusherPHIDs);
}
return $where;
}
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/repository/query/PhabricatorRepositoryRefCursorQuery.php | src/applications/repository/query/PhabricatorRepositoryRefCursorQuery.php | <?php
final class PhabricatorRepositoryRefCursorQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $repositoryPHIDs;
private $refTypes;
private $refNames;
private $datasourceQuery;
private $needPositions;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withRepositoryPHIDs(array $phids) {
$this->repositoryPHIDs = $phids;
return $this;
}
public function withRefTypes(array $types) {
$this->refTypes = $types;
return $this;
}
public function withRefNames(array $names) {
$this->refNames = $names;
return $this;
}
public function withDatasourceQuery($query) {
$this->datasourceQuery = $query;
return $this;
}
public function needPositions($need) {
$this->needPositions = $need;
return $this;
}
public function newResultObject() {
return new PhabricatorRepositoryRefCursor();
}
protected function willFilterPage(array $refs) {
$repository_phids = mpull($refs, 'getRepositoryPHID');
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withPHIDs($repository_phids)
->execute();
$repositories = mpull($repositories, null, 'getPHID');
foreach ($refs as $key => $ref) {
$repository = idx($repositories, $ref->getRepositoryPHID());
if (!$repository) {
$this->didRejectResult($ref);
unset($refs[$key]);
continue;
}
$ref->attachRepository($repository);
}
if (!$refs) {
return $refs;
}
if ($this->needPositions) {
$positions = id(new PhabricatorRepositoryRefPosition())->loadAllWhere(
'cursorID IN (%Ld)',
mpull($refs, 'getID'));
$positions = mgroup($positions, 'getCursorID');
foreach ($refs as $key => $ref) {
$ref_positions = idx($positions, $ref->getID(), array());
$ref->attachPositions($ref_positions);
}
}
return $refs;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->repositoryPHIDs !== null) {
$where[] = qsprintf(
$conn,
'repositoryPHID IN (%Ls)',
$this->repositoryPHIDs);
}
if ($this->refTypes !== null) {
$where[] = qsprintf(
$conn,
'refType IN (%Ls)',
$this->refTypes);
}
if ($this->refNames !== null) {
$name_hashes = array();
foreach ($this->refNames as $name) {
$name_hashes[] = PhabricatorHash::digestForIndex($name);
}
$where[] = qsprintf(
$conn,
'refNameHash IN (%Ls)',
$name_hashes);
}
if ($this->datasourceQuery !== null && strlen($this->datasourceQuery)) {
$where[] = qsprintf(
$conn,
'refNameRaw LIKE %>',
$this->datasourceQuery);
}
return $where;
}
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/repository/query/PhabricatorRepositoryIdentityTransactionQuery.php | src/applications/repository/query/PhabricatorRepositoryIdentityTransactionQuery.php | <?php
final class PhabricatorRepositoryIdentityTransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new PhabricatorRepositoryIdentityTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/query/PhabricatorRepositorySearchEngine.php | src/applications/repository/query/PhabricatorRepositorySearchEngine.php | <?php
final class PhabricatorRepositorySearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Repositories');
}
public function getApplicationClassName() {
return 'PhabricatorDiffusionApplication';
}
public function newQuery() {
return id(new PhabricatorRepositoryQuery())
->needProjectPHIDs(true)
->needCommitCounts(true)
->needMostRecentCommits(true)
->needProfileImage(true);
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorSearchStringListField())
->setLabel(pht('Callsigns'))
->setKey('callsigns'),
id(new PhabricatorSearchStringListField())
->setLabel(pht('Short Names'))
->setKey('shortNames'),
id(new PhabricatorSearchSelectField())
->setLabel(pht('Status'))
->setKey('status')
->setOptions($this->getStatusOptions()),
id(new PhabricatorSearchSelectField())
->setLabel(pht('Hosted'))
->setKey('hosted')
->setOptions($this->getHostedOptions()),
id(new PhabricatorSearchCheckboxesField())
->setLabel(pht('Types'))
->setKey('types')
->setOptions(PhabricatorRepositoryType::getAllRepositoryTypes()),
id(new PhabricatorSearchStringListField())
->setLabel(pht('URIs'))
->setKey('uris')
->setDescription(
pht('Search for repositories by clone/checkout URI.')),
id(new PhabricatorPHIDsSearchField())
->setLabel(pht('Services'))
->setKey('almanacServicePHIDs')
->setAliases(
array(
'almanacServicePHID',
'almanacService',
'almanacServices',
)),
);
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['callsigns']) {
$query->withCallsigns($map['callsigns']);
}
if ($map['shortNames']) {
$query->withSlugs($map['shortNames']);
}
if ($map['status']) {
$status = idx($this->getStatusValues(), $map['status']);
if ($status) {
$query->withStatus($status);
}
}
if ($map['hosted']) {
$hosted = idx($this->getHostedValues(), $map['hosted']);
if ($hosted) {
$query->withHosted($hosted);
}
}
if ($map['types']) {
$query->withTypes($map['types']);
}
if ($map['uris']) {
$query->withURIs($map['uris']);
}
if ($map['almanacServicePHIDs']) {
$query->withAlmanacServicePHIDs($map['almanacServicePHIDs']);
}
return $query;
}
protected function getURI($path) {
return '/diffusion/'.$path;
}
protected function getBuiltinQueryNames() {
$names = array(
'active' => pht('Active Repositories'),
'all' => pht('All Repositories'),
);
return $names;
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'active':
return $query->setParameter('status', 'open');
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
private function getStatusOptions() {
return array(
'' => pht('Active and Inactive Repositories'),
'open' => pht('Active Repositories'),
'closed' => pht('Inactive Repositories'),
);
}
private function getStatusValues() {
return array(
'' => PhabricatorRepositoryQuery::STATUS_ALL,
'open' => PhabricatorRepositoryQuery::STATUS_OPEN,
'closed' => PhabricatorRepositoryQuery::STATUS_CLOSED,
);
}
private function getHostedOptions() {
return array(
'' => pht('Hosted and Remote Repositories'),
'phabricator' => pht('Hosted Repositories'),
'remote' => pht('Remote Repositories'),
);
}
private function getHostedValues() {
return array(
'' => PhabricatorRepositoryQuery::HOSTED_ALL,
'phabricator' => PhabricatorRepositoryQuery::HOSTED_PHABRICATOR,
'remote' => PhabricatorRepositoryQuery::HOSTED_REMOTE,
);
}
protected function getRequiredHandlePHIDsForResultList(
array $repositories,
PhabricatorSavedQuery $query) {
return array_mergev(mpull($repositories, 'getProjectPHIDs'));
}
protected function renderResultList(
array $repositories,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($repositories, 'PhabricatorRepository');
$viewer = $this->requireViewer();
$list = new PHUIObjectItemListView();
foreach ($repositories as $repository) {
$id = $repository->getID();
$item = id(new PHUIObjectItemView())
->setUser($viewer)
->setObject($repository)
->setHeader($repository->getName())
->setObjectName($repository->getMonogram())
->setHref($repository->getURI())
->setImageURI($repository->getProfileImageURI());
$commit = $repository->getMostRecentCommit();
if ($commit) {
$commit_link = phutil_tag(
'a',
array(
'href' => $commit->getURI(),
),
pht(
'%s: %s',
$commit->getLocalName(),
$commit->getSummary()));
$item->setSubhead($commit_link);
$item->setEpoch($commit->getEpoch());
}
$item->addIcon(
'none',
PhabricatorRepositoryType::getNameForRepositoryType(
$repository->getVersionControlSystem()));
$size = $repository->getCommitCount();
if ($size) {
$history_uri = $repository->generateURI(
array(
'action' => 'history',
));
$item->addAttribute(
phutil_tag(
'a',
array(
'href' => $history_uri,
),
pht('%s Commit(s)', new PhutilNumber($size))));
} else {
$item->addAttribute(pht('No Commits'));
}
$project_handles = array_select_keys(
$handles,
$repository->getProjectPHIDs());
if ($project_handles) {
$item->addAttribute(
id(new PHUIHandleTagListView())
->setSlim(true)
->setHandles($project_handles));
}
if (!$repository->isTracked()) {
$item->setDisabled(true);
$item->addIcon('disable-grey', pht('Inactive'));
} else if ($repository->isImporting()) {
$item->addIcon('fa-clock-o indigo', pht('Importing...'));
}
$list->addItem($item);
}
$result = new PhabricatorApplicationSearchResultView();
$result->setObjectList($list);
$result->setNoDataString(pht('No repositories found for this query.'));
return $result;
}
protected function willUseSavedQuery(PhabricatorSavedQuery $saved) {
$project_phids = $saved->getParameter('projectPHIDs', array());
$old = $saved->getParameter('projects', array());
foreach ($old as $phid) {
$project_phids[] = $phid;
}
$any = $saved->getParameter('anyProjectPHIDs', array());
foreach ($any as $project) {
$project_phids[] = 'any('.$project.')';
}
$saved->setParameter('projectPHIDs', $project_phids);
}
protected function getNewUserBody() {
$new_button = id(new PHUIButtonView())
->setTag('a')
->setText(pht('New Repository'))
->setHref('/diffusion/edit/')
->setColor(PHUIButtonView::GREEN);
$icon = $this->getApplication()->getIcon();
$app_name = $this->getApplication()->getName();
$view = id(new PHUIBigInfoView())
->setIcon($icon)
->setTitle(pht('Welcome to %s', $app_name))
->setDescription(
pht('Import, create, or just browse repositories in Diffusion.'))
->addAction($new_button);
return $view;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/query/PhabricatorRepositoryURITransactionQuery.php | src/applications/repository/query/PhabricatorRepositoryURITransactionQuery.php | <?php
final class PhabricatorRepositoryURITransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new PhabricatorRepositoryURITransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/query/PhabricatorRepositoryPushLogQuery.php | src/applications/repository/query/PhabricatorRepositoryPushLogQuery.php | <?php
final class PhabricatorRepositoryPushLogQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $repositoryPHIDs;
private $pusherPHIDs;
private $refTypes;
private $newRefs;
private $pushEventPHIDs;
private $epochMin;
private $epochMax;
private $blockingHeraldRulePHIDs;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withRepositoryPHIDs(array $repository_phids) {
$this->repositoryPHIDs = $repository_phids;
return $this;
}
public function withPusherPHIDs(array $pusher_phids) {
$this->pusherPHIDs = $pusher_phids;
return $this;
}
public function withRefTypes(array $ref_types) {
$this->refTypes = $ref_types;
return $this;
}
public function withNewRefs(array $new_refs) {
$this->newRefs = $new_refs;
return $this;
}
public function withPushEventPHIDs(array $phids) {
$this->pushEventPHIDs = $phids;
return $this;
}
public function withEpochBetween($min, $max) {
$this->epochMin = $min;
$this->epochMax = $max;
return $this;
}
public function withBlockingHeraldRulePHIDs(array $phids) {
$this->blockingHeraldRulePHIDs = $phids;
return $this;
}
public function newResultObject() {
return new PhabricatorRepositoryPushLog();
}
protected function willFilterPage(array $logs) {
$event_phids = mpull($logs, 'getPushEventPHID');
$events = id(new PhabricatorObjectQuery())
->setParentQuery($this)
->setViewer($this->getViewer())
->withPHIDs($event_phids)
->execute();
$events = mpull($events, null, 'getPHID');
foreach ($logs as $key => $log) {
$event = idx($events, $log->getPushEventPHID());
if (!$event) {
unset($logs[$key]);
continue;
}
$log->attachPushEvent($event);
}
return $logs;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'log.id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'log.phid IN (%Ls)',
$this->phids);
}
if ($this->repositoryPHIDs !== null) {
$where[] = qsprintf(
$conn,
'log.repositoryPHID IN (%Ls)',
$this->repositoryPHIDs);
}
if ($this->pusherPHIDs !== null) {
$where[] = qsprintf(
$conn,
'log.pusherPHID in (%Ls)',
$this->pusherPHIDs);
}
if ($this->pushEventPHIDs !== null) {
$where[] = qsprintf(
$conn,
'log.pushEventPHID in (%Ls)',
$this->pushEventPHIDs);
}
if ($this->refTypes !== null) {
$where[] = qsprintf(
$conn,
'log.refType IN (%Ls)',
$this->refTypes);
}
if ($this->newRefs !== null) {
$where[] = qsprintf(
$conn,
'log.refNew IN (%Ls)',
$this->newRefs);
}
if ($this->epochMin !== null) {
$where[] = qsprintf(
$conn,
'log.epoch >= %d',
$this->epochMin);
}
if ($this->epochMax !== null) {
$where[] = qsprintf(
$conn,
'log.epoch <= %d',
$this->epochMax);
}
if ($this->blockingHeraldRulePHIDs !== null) {
$where[] = qsprintf(
$conn,
'(event.rejectCode = %d AND event.rejectDetails IN (%Ls))',
PhabricatorRepositoryPushLog::REJECT_HERALD,
$this->blockingHeraldRulePHIDs);
}
return $where;
}
protected function buildJoinClauseParts(AphrontDatabaseConnection $conn) {
$joins = parent::buildJoinClauseParts($conn);
if ($this->shouldJoinPushEventTable()) {
$joins[] = qsprintf(
$conn,
'JOIN %T event ON event.phid = log.pushEventPHID',
id(new PhabricatorRepositoryPushEvent())->getTableName());
}
return $joins;
}
private function shouldJoinPushEventTable() {
if ($this->blockingHeraldRulePHIDs !== null) {
return true;
}
return false;
}
public function getQueryApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
protected function getPrimaryTableAlias() {
return 'log';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/query/PhabricatorRepositorySyncEventQuery.php | src/applications/repository/query/PhabricatorRepositorySyncEventQuery.php | <?php
final class PhabricatorRepositorySyncEventQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $repositoryPHIDs;
private $epochMin;
private $epochMax;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withRepositoryPHIDs(array $repository_phids) {
$this->repositoryPHIDs = $repository_phids;
return $this;
}
public function withEpochBetween($min, $max) {
$this->epochMin = $min;
$this->epochMax = $max;
return $this;
}
public function newResultObject() {
return new PhabricatorRepositorySyncEvent();
}
protected function willFilterPage(array $events) {
$repository_phids = mpull($events, 'getRepositoryPHID');
$repository_phids = array_filter($repository_phids);
if ($repository_phids) {
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($this->getViewer())
->withPHIDs($repository_phids)
->execute();
$repositories = mpull($repositories, null, 'getPHID');
} else {
$repositories = array();
}
foreach ($events as $key => $event) {
$phid = $event->getRepositoryPHID();
if (empty($repositories[$phid])) {
unset($events[$key]);
$this->didRejectResult($event);
continue;
}
$event->attachRepository($repositories[$phid]);
}
return $events;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->repositoryPHIDs !== null) {
$where[] = qsprintf(
$conn,
'repositoryPHID IN (%Ls)',
$this->repositoryPHIDs);
}
if ($this->epochMin !== null) {
$where[] = qsprintf(
$conn,
'epoch >= %d',
$this->epochMin);
}
if ($this->epochMax !== null) {
$where[] = qsprintf(
$conn,
'epoch <= %d',
$this->epochMax);
}
return $where;
}
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/repository/query/PhabricatorRepositoryPublisherHoldReason.php | src/applications/repository/query/PhabricatorRepositoryPublisherHoldReason.php | <?php
final class PhabricatorRepositoryPublisherHoldReason
extends Phobject {
private $key;
private $spec;
public static function newForHoldKey($key) {
$spec = self::getSpecForHoldKey($key);
$hold = new self();
$hold->key = $key;
$hold->spec = $spec;
return $hold;
}
private static function getSpecForHoldKey($key) {
$specs = self::getHoldReasonSpecs();
$spec = idx($specs, $key);
if (!$spec) {
$spec = array(
'name' => pht('Unknown Hold ("%s")', $key),
);
}
return $spec;
}
public function getName() {
return $this->getProperty('name');
}
public function getSummary() {
return $this->getProperty('summary');
}
private function getProperty($key, $default = null) {
return idx($this->spec, $key, $default);
}
private static function getHoldReasonSpecs() {
$map = array(
PhabricatorRepositoryPublisher::HOLD_IMPORTING => array(
'name' => pht('Repository Importing'),
'summary' => pht('This repository is still importing.'),
),
PhabricatorRepositoryPublisher::HOLD_PUBLISHING_DISABLED => array(
'name' => pht('Publishing Disabled'),
'summary' => pht('All publishing is disabled for this repository.'),
),
PhabricatorRepositoryPublisher::HOLD_NOT_REACHABLE_FROM_PERMANENT_REF =>
array(
'name' => pht('Not On Permanent Ref'),
'summary' => pht(
'This commit is not an ancestor of any permanent ref.'),
),
PhabricatorRepositoryPublisher::HOLD_REF_NOT_BRANCH => array(
'name' => pht('Not a Branch'),
'summary' => pht('This ref is not a branch.'),
),
PhabricatorRepositoryPublisher::HOLD_UNTRACKED => array(
'name' => pht('Untracked Ref'),
'summary' => pht('This ref is configured as untracked.'),
),
PhabricatorRepositoryPublisher::HOLD_NOT_PERMANENT_REF => array(
'name' => pht('Not a Permanent Ref'),
'summary' => pht('This ref is not configured as a permanent ref.'),
),
);
return $map;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/mail/PhabricatorRepositoryPushReplyHandler.php | src/applications/repository/mail/PhabricatorRepositoryPushReplyHandler.php | <?php
final class PhabricatorRepositoryPushReplyHandler
extends PhabricatorMailReplyHandler {
public function validateMailReceiver($mail_receiver) {
return;
}
public function getPrivateReplyHandlerEmailAddress(
PhabricatorUser $user) {
return null;
}
protected function receiveEmail(PhabricatorMetaMTAReceivedMail $mail) {
return;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/customfield/PhabricatorCommitCustomField.php | src/applications/repository/customfield/PhabricatorCommitCustomField.php | <?php
abstract class PhabricatorCommitCustomField
extends PhabricatorCustomField {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/customfield/PhabricatorCommitMergedCommitsField.php | src/applications/repository/customfield/PhabricatorCommitMergedCommitsField.php | <?php
final class PhabricatorCommitMergedCommitsField
extends PhabricatorCommitCustomField {
public function getFieldKey() {
return 'diffusion:mergedcommits';
}
public function getFieldName() {
return pht('Merged Commits');
}
public function getFieldDescription() {
return pht('For merge commits, shows merged changes in email.');
}
public function shouldDisableByDefault() {
return true;
}
public function shouldAppearInTransactionMail() {
return true;
}
public function updateTransactionMailBody(
PhabricatorMetaMTAMailBody $body,
PhabricatorApplicationTransactionEditor $editor,
array $xactions) {
// Put all the merged commits info int the mail body if this is a merge
$merges_caption = '';
// TODO: Make this limit configurable after T6030
$limit = 50;
$commit = $this->getObject();
try {
$merges = DiffusionPathChange::newFromConduit(
id(new ConduitCall('diffusion.mergedcommitsquery', array(
'commit' => $commit->getCommitIdentifier(),
'limit' => $limit + 1,
'repository' => $commit->getRepository()->getPHID(),
)))
->setUser($this->getViewer())
->execute());
if (count($merges) > $limit) {
$merges = array_slice($merges, 0, $limit);
$merges_caption =
pht("This commit merges more than %d changes. Only the first ".
"%d are shown.\n", $limit, $limit);
}
if ($merges) {
$merge_commits = array();
foreach ($merges as $merge) {
$merge_commits[] = $merge->getAuthorName().
': '.
$merge->getSummary();
}
$body->addTextSection(
pht('MERGED COMMITS'),
$merges_caption.implode("\n", $merge_commits));
}
} catch (ConduitException $ex) {
// Log the exception into the email body
$body->addTextSection(
pht('MERGED COMMITS'),
pht('Error generating merged commits: ').$ex->getMessage());
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/customfield/PhabricatorCommitTagsField.php | src/applications/repository/customfield/PhabricatorCommitTagsField.php | <?php
final class PhabricatorCommitTagsField
extends PhabricatorCommitCustomField {
public function getFieldKey() {
return 'diffusion:tags';
}
public function getFieldName() {
return pht('Tags');
}
public function getFieldDescription() {
return pht('Shows commit tags in email.');
}
public function shouldAppearInTransactionMail() {
return true;
}
public function updateTransactionMailBody(
PhabricatorMetaMTAMailBody $body,
PhabricatorApplicationTransactionEditor $editor,
array $xactions) {
$params = array(
'commit' => $this->getObject()->getCommitIdentifier(),
'repository' => $this->getObject()->getRepository()->getPHID(),
);
try {
$tags_raw = id(new ConduitCall('diffusion.tagsquery', $params))
->setUser($this->getViewer())
->execute();
$tags = DiffusionRepositoryTag::newFromConduit($tags_raw);
if (!$tags) {
return;
}
$tag_names = mpull($tags, 'getName');
sort($tag_names);
$tag_names = implode(', ', $tag_names);
} catch (Exception $ex) {
$tag_names = pht('<%s: %s>', get_class($ex), $ex->getMessage());
}
$body->addTextSection(pht('TAGS'), $tag_names);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/customfield/PhabricatorCommitRepositoryField.php | src/applications/repository/customfield/PhabricatorCommitRepositoryField.php | <?php
final class PhabricatorCommitRepositoryField
extends PhabricatorCommitCustomField {
public function getFieldKey() {
return 'diffusion:repository';
}
public function getFieldName() {
return pht('Repository');
}
public function getFieldDescription() {
return pht('Shows repository in email.');
}
public function shouldDisableByDefault() {
return true;
}
public function shouldAppearInTransactionMail() {
return true;
}
public function updateTransactionMailBody(
PhabricatorMetaMTAMailBody $body,
PhabricatorApplicationTransactionEditor $editor,
array $xactions) {
$repository = $this->getObject()->getRepository();
$body->addTextSection(
pht('REPOSITORY'),
$repository->getMonogram().' '.$repository->getName());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/customfield/PhabricatorCommitBranchesField.php | src/applications/repository/customfield/PhabricatorCommitBranchesField.php | <?php
final class PhabricatorCommitBranchesField
extends PhabricatorCommitCustomField {
public function getFieldKey() {
return 'diffusion:branches';
}
public function getFieldName() {
return pht('Branches');
}
public function getFieldDescription() {
return pht('Shows branches a commit appears on in email.');
}
public function shouldAppearInTransactionMail() {
return true;
}
public function updateTransactionMailBody(
PhabricatorMetaMTAMailBody $body,
PhabricatorApplicationTransactionEditor $editor,
array $xactions) {
$params = array(
'contains' => $this->getObject()->getCommitIdentifier(),
'repository' => $this->getObject()->getRepository()->getPHID(),
);
try {
$branches_raw = id(new ConduitCall('diffusion.branchquery', $params))
->setUser($this->getViewer())
->execute();
$branches = DiffusionRepositoryRef::loadAllFromDictionaries(
$branches_raw);
if (!$branches) {
return;
}
$branch_names = mpull($branches, 'getShortName');
sort($branch_names);
$branch_text = implode(', ', $branch_names);
} catch (Exception $ex) {
$branch_text = pht('<%s: %s>', get_class($ex), $ex->getMessage());
}
$body->addTextSection(pht('BRANCHES'), $branch_text);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/editor/PhabricatorRepositoryEditor.php | src/applications/repository/editor/PhabricatorRepositoryEditor.php | <?php
final class PhabricatorRepositoryEditor
extends PhabricatorApplicationTransactionEditor {
public function getEditorApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
public function getEditorObjectsDescription() {
return pht('Repositories');
}
public function getTransactionTypes() {
$types = parent::getTransactionTypes();
$types[] = PhabricatorTransactions::TYPE_EDGE;
$types[] = PhabricatorTransactions::TYPE_VIEW_POLICY;
$types[] = PhabricatorTransactions::TYPE_EDIT_POLICY;
return $types;
}
protected function didCatchDuplicateKeyException(
PhabricatorLiskDAO $object,
array $xactions,
Exception $ex) {
$errors = array();
$errors[] = new PhabricatorApplicationTransactionValidationError(
null,
pht('Invalid'),
pht(
'The chosen callsign or repository short name is already in '.
'use by another repository.'),
null);
throw new PhabricatorApplicationTransactionValidationException($errors);
}
protected function supportsSearch() {
return true;
}
protected function applyFinalEffects(
PhabricatorLiskDAO $object,
array $xactions) {
// If the repository does not have a local path yet, assign it one based
// on its ID. We can't do this earlier because we won't have an ID yet.
$local_path = $object->getLocalPath();
if ($local_path === null || !strlen($local_path)) {
$local_key = 'repository.default-local-path';
$local_root = PhabricatorEnv::getEnvConfig($local_key);
$local_root = rtrim($local_root, '/');
$id = $object->getID();
$local_path = "{$local_root}/{$id}/";
$object->setLocalPath($local_path);
$object->save();
}
if ($this->getIsNewObject()) {
// The default state of repositories is to be hosted, if they are
// enabled without configuring any "Observe" URIs.
$object->setHosted(true);
$object->save();
// Create this repository's builtin URIs.
$builtin_uris = $object->newBuiltinURIs();
foreach ($builtin_uris as $uri) {
$uri->save();
}
id(new DiffusionRepositoryClusterEngine())
->setViewer($this->getActor())
->setRepository($object)
->synchronizeWorkingCopyAfterCreation();
}
$object->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/repository/xaction/PhabricatorRepositoryCallsignTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryCallsignTransaction.php | <?php
final class PhabricatorRepositoryCallsignTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:callsign';
public function generateOldValue($object) {
return $object->getCallsign();
}
public function generateNewValue($object, $value) {
if (strlen($value)) {
return $value;
}
return null;
}
public function applyInternalEffects($object, $value) {
$object->setCallsign($value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if (!strlen($old)) {
return pht(
'%s set the callsign for this repository to %s.',
$this->renderAuthor(),
$this->renderNewValue());
} else if (!strlen($new)) {
return pht(
'%s removed the callsign (%s) for this repository.',
$this->renderAuthor(),
$this->renderOldValue());
} else {
return pht(
'%s changed the callsign for this repository from %s to %s.',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
foreach ($xactions as $xaction) {
$old = $xaction->getOldValue();
$new = $xaction->getNewValue();
if (!strlen($new)) {
continue;
}
if ($new === $old) {
continue;
}
try {
PhabricatorRepository::assertValidCallsign($new);
} catch (Exception $ex) {
$errors[] = $this->newInvalidError(
$ex->getMessage(),
$xaction);
continue;
}
$other = id(new PhabricatorRepositoryQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withCallsigns(array($new))
->executeOne();
if ($other && ($other->getID() !== $object->getID())) {
$errors[] = $this->newError(
pht('Duplicate'),
pht(
'The selected callsign ("%s") is already in use by another '.
'repository. Choose a unique callsign.',
$new),
$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/repository/xaction/PhabricatorRepositoryNotifyTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryNotifyTransaction.php | <?php
final class PhabricatorRepositoryNotifyTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:notify';
public function generateOldValue($object) {
return (int)!$object->getDetail('herald-disabled');
}
public function generateNewValue($object, $value) {
return (int)$value;
}
public function applyInternalEffects($object, $value) {
$object->setDetail('herald-disabled', (int)!$value);
}
public function getTitle() {
$new = $this->getNewValue();
if ($new) {
return pht(
'%s enabled publishing for this repository.',
$this->renderAuthor());
} else {
return pht(
'%s disabled publishing for this repository.',
$this->renderAuthor());
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/xaction/PhabricatorRepositoryTrackOnlyTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryTrackOnlyTransaction.php | <?php
final class PhabricatorRepositoryTrackOnlyTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:track-only';
public function generateOldValue($object) {
return $object->getTrackOnlyRules();
}
public function applyInternalEffects($object, $value) {
$object->setTrackOnlyRules($value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if (!$new) {
return pht(
'%s set this repository to track all branches.',
$this->renderAuthor());
} else if (!$old) {
return pht(
'%s set this repository to track branches: %s.',
$this->renderAuthor(),
$this->renderValue(implode(', ', $new)));
} else {
return pht(
'%s changed tracked branches from %s to %s.',
$this->renderAuthor(),
$this->renderValue(implode(', ', $old)),
$this->renderValue(implode(', ', $new)));
}
}
public function validateTransactions($object, array $xactions) {
return $this->validateRefList($object, $xactions);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/xaction/PhabricatorRepositoryCopyTimeLimitTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryCopyTimeLimitTransaction.php | <?php
final class PhabricatorRepositoryCopyTimeLimitTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'limit.copy';
public function generateOldValue($object) {
return $object->getCopyTimeLimit();
}
public function generateNewValue($object, $value) {
if (!strlen($value)) {
return null;
}
$value = (int)$value;
if (!$value) {
return null;
}
return $value;
}
public function applyInternalEffects($object, $value) {
$object->setCopyTimeLimit($value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if ($old && $new) {
return pht(
'%s changed the copy time limit for this repository from %s seconds '.
'to %s seconds.',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
} else if ($new) {
return pht(
'%s set the copy time limit for this repository to %s seconds.',
$this->renderAuthor(),
$this->renderNewValue());
} else {
return pht(
'%s reset the copy time limit (%s seconds) for this repository '.
'to the default value.',
$this->renderAuthor(),
$this->renderOldValue());
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
foreach ($xactions as $xaction) {
$new = $xaction->getNewValue();
if (!strlen($new)) {
continue;
}
if (!preg_match('/^\d+\z/', $new)) {
$errors[] = $this->newInvalidError(
pht(
'Unable to parse copy time limit, specify a positive number '.
'of seconds.'),
$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/repository/xaction/PhabricatorRepositorySlugTransaction.php | src/applications/repository/xaction/PhabricatorRepositorySlugTransaction.php | <?php
final class PhabricatorRepositorySlugTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:slug';
public function generateOldValue($object) {
return $object->getRepositorySlug();
}
public function generateNewValue($object, $value) {
if (strlen($value)) {
return $value;
}
return null;
}
public function applyInternalEffects($object, $value) {
$object->setRepositorySlug($value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if (strlen($old) && !strlen($new)) {
return pht(
'%s removed the short name of this repository.',
$this->renderAuthor());
} else if (strlen($new) && !strlen($old)) {
return pht(
'%s set the short name of this repository to %s.',
$this->renderAuthor(),
$this->renderNewValue());
} else {
return pht(
'%s changed the short name of this repository from %s to %s.',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
foreach ($xactions as $xaction) {
$old = $xaction->getOldValue();
$new = $xaction->getNewValue();
if (!strlen($new)) {
continue;
}
if ($new === $old) {
continue;
}
try {
PhabricatorRepository::assertValidRepositorySlug($new);
} catch (Exception $ex) {
$errors[] = $this->newInvalidError(
$ex->getMessage(),
$xaction);
continue;
}
$other = id(new PhabricatorRepositoryQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withSlugs(array($new))
->executeOne();
if ($other && ($other->getID() !== $object->getID())) {
$errors[] = $this->newError(
pht('Duplicate'),
pht(
'The selected repository short name is already in use by '.
'another repository. Choose a unique short name.'),
$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/repository/xaction/PhabricatorRepositoryPushPolicyTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryPushPolicyTransaction.php | <?php
final class PhabricatorRepositoryPushPolicyTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:push-policy';
public function generateOldValue($object) {
return $object->getPushPolicy();
}
public function applyInternalEffects($object, $value) {
$object->setPushPolicy($value);
}
public function getTitle() {
return pht(
'%s changed the push policy of this repository from %s to %s.',
$this->renderAuthor(),
$this->renderOldPolicy(),
$this->renderNewPolicy());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/xaction/PhabricatorRepositoryEncodingTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryEncodingTransaction.php | <?php
final class PhabricatorRepositoryEncodingTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:encoding';
public function generateOldValue($object) {
return $object->getDetail('encoding');
}
public function applyInternalEffects($object, $value) {
$object->setDetail('encoding', $value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if (strlen($old) && !strlen($new)) {
return pht(
'%s removed the %s encoding configured for this repository.',
$this->renderAuthor(),
$this->renderOldValue());
} else if (strlen($new) && !strlen($old)) {
return pht(
'%s set the encoding for this repository to %s.',
$this->renderAuthor(),
$this->renderNewValue());
} else {
return pht(
'%s changed the repository encoding from %s to %s.',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
foreach ($xactions as $xaction) {
// Make sure the encoding is valid by converting to UTF-8. This tests
// that the user has mbstring installed, and also that they didn't
// type a garbage encoding name. Note that we're converting from
// UTF-8 to the target encoding, because mbstring is fine with
// converting from a nonsense encoding.
$encoding = $xaction->getNewValue();
if (!strlen($encoding)) {
continue;
}
try {
phutil_utf8_convert('.', $encoding, 'UTF-8');
} catch (Exception $ex) {
$errors[] = $this->newInvalidError(
pht(
'Repository encoding "%s" is not valid: %s',
$encoding,
$ex->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/repository/xaction/PhabricatorRepositoryDescriptionTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryDescriptionTransaction.php | <?php
final class PhabricatorRepositoryDescriptionTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:description';
public function generateOldValue($object) {
return $object->getDetail('description');
}
public function applyInternalEffects($object, $value) {
$object->setDetail('description', $value);
}
public function getTitle() {
return pht(
'%s updated the description for this repository.',
$this->renderAuthor());
}
public function hasChangeDetailView() {
return true;
}
public function getMailDiffSectionHeader() {
return pht('CHANGES TO REPOSITORY DESCRIPTION');
}
public function newChangeDetailView() {
$viewer = $this->getViewer();
return id(new PhabricatorApplicationTransactionTextDiffDetailView())
->setViewer($viewer)
->setOldText($this->getOldValue())
->setNewText($this->getNewValue());
}
public function newRemarkupChanges() {
$changes = array();
$changes[] = $this->newRemarkupChange()
->setOldValue($this->getOldValue())
->setNewValue($this->getNewValue());
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/repository/xaction/PhabricatorRepositoryDangerousTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryDangerousTransaction.php | <?php
final class PhabricatorRepositoryDangerousTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:dangerous';
public function generateOldValue($object) {
return $object->shouldAllowDangerousChanges();
}
public function applyInternalEffects($object, $value) {
$object->setDetail('allow-dangerous-changes', $value);
}
public function getTitle() {
$new = $this->getNewValue();
if ($new) {
return pht(
'%s disabled protection against dangerous changes.',
$this->renderAuthor());
} else {
return pht(
'%s enabled protection against dangerous changes.',
$this->renderAuthor());
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/xaction/PhabricatorRepositoryDefaultBranchTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryDefaultBranchTransaction.php | <?php
final class PhabricatorRepositoryDefaultBranchTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:default-branch';
public function generateOldValue($object) {
return $object->getDetail('default-branch');
}
public function applyInternalEffects($object, $value) {
$object->setDetail('default-branch', $value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if (!strlen($new)) {
return pht(
'%s removed %s as the default branch.',
$this->renderAuthor(),
$this->renderOldValue());
} else if (!strlen($old)) {
return pht(
'%s set the default branch to %s.',
$this->renderAuthor(),
$this->renderNewValue());
} else {
return pht(
'%s changed the default branch from %s to %s.',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/xaction/PhabricatorRepositoryNameTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryNameTransaction.php | <?php
final class PhabricatorRepositoryNameTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:name';
public function generateOldValue($object) {
return $object->getName();
}
public function applyInternalEffects($object, $value) {
$object->setName($value);
}
public function getTitle() {
return pht(
'%s renamed this repository from %s to %s.',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
}
public function validateTransactions($object, array $xactions) {
$errors = array();
if ($this->isEmptyTextTransaction($object->getName(), $xactions)) {
$errors[] = $this->newRequiredError(
pht('Repositories must have a name.'));
}
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/repository/xaction/PhabricatorRepositoryTouchLimitTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryTouchLimitTransaction.php | <?php
final class PhabricatorRepositoryTouchLimitTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'limit.touch';
public function generateOldValue($object) {
return $object->getTouchLimit();
}
public function generateNewValue($object, $value) {
if (!strlen($value)) {
return null;
}
$value = (int)$value;
if (!$value) {
return null;
}
return $value;
}
public function applyInternalEffects($object, $value) {
$object->setTouchLimit($value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if ($old && $new) {
return pht(
'%s changed the touch limit for this repository from %s paths to '.
'%s paths.',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
} else if ($new) {
return pht(
'%s set the touch limit for this repository to %s paths.',
$this->renderAuthor(),
$this->renderNewValue());
} else {
return pht(
'%s removed the touch limit (%s paths) for this repository.',
$this->renderAuthor(),
$this->renderOldValue());
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
foreach ($xactions as $xaction) {
$new = $xaction->getNewValue();
if (!strlen($new)) {
continue;
}
if (!preg_match('/^\d+\z/', $new)) {
$errors[] = $this->newInvalidError(
pht(
'Unable to parse touch limit, specify a positive number of '.
'paths.'),
$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/repository/xaction/PhabricatorRepositoryIdentityTransactionType.php | src/applications/repository/xaction/PhabricatorRepositoryIdentityTransactionType.php | <?php
abstract class PhabricatorRepositoryIdentityTransactionType
extends PhabricatorModularTransactionType {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/xaction/PhabricatorRepositoryStagingURITransaction.php | src/applications/repository/xaction/PhabricatorRepositoryStagingURITransaction.php | <?php
final class PhabricatorRepositoryStagingURITransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:staging-uri';
public function generateOldValue($object) {
return $object->getDetail('staging-uri');
}
public function applyInternalEffects($object, $value) {
$object->setDetail('staging-uri', $value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if (!strlen($old)) {
return pht(
'%s set %s as the staging area for this repository.',
$this->renderAuthor(),
$this->renderNewValue());
} else if (!strlen($new)) {
return pht(
'%s removed %s as the staging area for this repository.',
$this->renderAuthor(),
$this->renderOldValue());
} else {
return pht(
'%s changed the staging area for this repository from '.
'%s to %s.',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
$old = $this->generateOldValue($object);
foreach ($xactions as $xaction) {
$new = $xaction->getNewValue();
if (!strlen($new)) {
continue;
}
if ($new === $old) {
continue;
}
try {
PhabricatorRepository::assertValidRemoteURI($new);
} catch (Exception $ex) {
$errors[] = $this->newInvalidError(
$ex->getMessage(),
$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/repository/xaction/PhabricatorRepositoryFilesizeLimitTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryFilesizeLimitTransaction.php | <?php
final class PhabricatorRepositoryFilesizeLimitTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'limit.filesize';
public function generateOldValue($object) {
return $object->getFilesizeLimit();
}
public function generateNewValue($object, $value) {
if (!strlen($value)) {
return null;
}
$value = phutil_parse_bytes($value);
if (!$value) {
return null;
}
return $value;
}
public function applyInternalEffects($object, $value) {
$object->setFilesizeLimit($value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if ($old && $new) {
return pht(
'%s changed the filesize limit for this repository from %s bytes to '.
'%s bytes.',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
} else if ($new) {
return pht(
'%s set the filesize limit for this repository to %s bytes.',
$this->renderAuthor(),
$this->renderNewValue());
} else {
return pht(
'%s removed the filesize limit (%s bytes) for this repository.',
$this->renderAuthor(),
$this->renderOldValue());
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
foreach ($xactions as $xaction) {
$new = $xaction->getNewValue();
if (!strlen($new)) {
continue;
}
try {
$value = phutil_parse_bytes($new);
} catch (Exception $ex) {
$errors[] = $this->newInvalidError(
pht(
'Unable to parse filesize limit: %s',
$ex->getMessage()),
$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/repository/xaction/PhabricatorRepositoryBlueprintsTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryBlueprintsTransaction.php | <?php
final class PhabricatorRepositoryBlueprintsTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:automation-blueprints';
public function generateOldValue($object) {
return $object->getDetail('automation.blueprintPHIDs', array());
}
public function applyInternalEffects($object, $value) {
$object->setDetail('automation.blueprintPHIDs', $value);
}
public function applyExternalEffects($object, $value) {
DrydockAuthorization::applyAuthorizationChanges(
$this->getActor(),
$object->getPHID(),
$this->getOldValue(),
$this->getNewValue());
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
$add = array_diff($new, $old);
$rem = array_diff($old, $new);
if ($add && $rem) {
return pht(
'%s changed %s automation blueprint(s), '.
'added %s: %s; removed %s: %s.',
$this->renderAuthor(),
new PhutilNumber(count($add) + count($rem)),
new PhutilNumber(count($add)),
$this->renderHandleList($add),
new PhutilNumber(count($rem)),
$this->renderHandleList($rem));
} else if ($add) {
return pht(
'%s added %s automation blueprint(s): %s.',
$this->renderAuthor(),
new PhutilNumber(count($add)),
$this->renderHandleList($add));
} else {
return pht(
'%s removed %s automation blueprint(s): %s.',
$this->renderAuthor(),
new PhutilNumber(count($rem)),
$this->renderHandleList($rem));
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
foreach ($xactions as $xaction) {
$old = nonempty($xaction->getOldValue(), array());
$new = nonempty($xaction->getNewValue(), array());
$add = array_diff($new, $old);
$invalid = PhabricatorObjectQuery::loadInvalidPHIDsForViewer(
$this->getActor(),
$add);
if ($invalid) {
$errors[] = $this->newInvalidError(
pht(
'Some of the selected automation blueprints are invalid '.
'or restricted: %s.',
implode(', ', $invalid)),
$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/repository/xaction/PhabricatorRepositoryEnormousTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryEnormousTransaction.php | <?php
final class PhabricatorRepositoryEnormousTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:enormous';
public function generateOldValue($object) {
return $object->shouldAllowEnormousChanges();
}
public function applyInternalEffects($object, $value) {
$object->setDetail('allow-enormous-changes', $value);
}
public function getTitle() {
$new = $this->getNewValue();
if ($new) {
return pht(
'%s disabled protection against enormous changes.',
$this->renderAuthor());
} else {
return pht(
'%s enabled protection against enormous changes.',
$this->renderAuthor());
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/xaction/PhabricatorRepositorySymbolLanguagesTransaction.php | src/applications/repository/xaction/PhabricatorRepositorySymbolLanguagesTransaction.php | <?php
final class PhabricatorRepositorySymbolLanguagesTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:symbol-language';
public function generateOldValue($object) {
return $object->getSymbolLanguages();
}
public function applyInternalEffects($object, $value) {
$object->setDetail('symbol-languages', $value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if ($old) {
$display_old = implode(', ', $old);
} else {
$display_old = pht('Any');
}
if ($new) {
$display_new = implode(', ', $new);
} else {
$display_new = pht('Any');
}
return pht(
'%s changed indexed languages from %s to %s.',
$this->renderAuthor(),
$this->renderValue($display_old),
$this->renderValue($display_new));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/xaction/PhabricatorRepositoryServiceTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryServiceTransaction.php | <?php
final class PhabricatorRepositoryServiceTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:service';
public function generateOldValue($object) {
return $object->getAlmanacServicePHID();
}
public function generateNewValue($object, $value) {
if (strlen($value)) {
return $value;
}
return null;
}
public function applyInternalEffects($object, $value) {
$object->setAlmanacServicePHID($value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getOldValue();
if (strlen($old) && !strlen($new)) {
return pht(
'%s moved storage for this repository from %s to local.',
$this->renderAuthor(),
$this->renderOldHandle());
} else if (!strlen($old) && strlen($new)) {
// TODO: Possibly, we should distinguish between automatic assignment
// on creation vs explicit adjustment.
return pht(
'%s set storage for this repository to %s.',
$this->renderAuthor(),
$this->renderNewHandle());
} else {
return pht(
'%s moved storage for this repository from %s to %s.',
$this->renderAuthor(),
$this->renderOldHandle(),
$this->renderNewHandle());
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
// TODO: This could use some validation, values should be valid Almanac
// services of appropriate types. It's only reachable via the CLI so it's
// difficult to get wrong in practice.
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/repository/xaction/PhabricatorRepositorySVNSubpathTransaction.php | src/applications/repository/xaction/PhabricatorRepositorySVNSubpathTransaction.php | <?php
final class PhabricatorRepositorySVNSubpathTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:svn-subpath';
public function generateOldValue($object) {
return $object->getDetail('svn-subpath');
}
public function applyInternalEffects($object, $value) {
$object->setDetail('svn-subpath', $value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if (!strlen($new)) {
return pht(
'%s removed %s as the "Import Only" path.',
$this->renderAuthor(),
$this->renderOldValue());
} else if (!strlen($old)) {
return pht(
'%s set the repository "Import Only" path to %s.',
$this->renderAuthor(),
$this->renderNewValue());
} else {
return pht(
'%s changed the "Import Only" path from %s to %s.',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/xaction/PhabricatorRepositoryIdentityAssignTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryIdentityAssignTransaction.php | <?php
final class PhabricatorRepositoryIdentityAssignTransaction
extends PhabricatorRepositoryIdentityTransactionType {
const TRANSACTIONTYPE = 'repository:identity:assign';
public function generateOldValue($object) {
return nonempty($object->getManuallySetUserPHID(), null);
}
public function applyInternalEffects($object, $value) {
$object->setManuallySetUserPHID($value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if (!$old) {
return pht(
'%s assigned this identity to %s.',
$this->renderAuthor(),
$this->renderIdentityHandle($new));
} else if (!$new) {
return pht(
'%s removed %s as the assignee of this identity.',
$this->renderAuthor(),
$this->renderIdentityHandle($old));
} else {
return pht(
'%s changed the assigned user for this identity from %s to %s.',
$this->renderAuthor(),
$this->renderIdentityHandle($old),
$this->renderIdentityHandle($new));
}
}
private function renderIdentityHandle($handle) {
$unassigned_token = DiffusionIdentityUnassignedDatasource::FUNCTION_TOKEN;
if ($handle === $unassigned_token) {
return phutil_tag('em', array(), pht('Explicitly Unassigned'));
} else {
return $this->renderHandle($handle);
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
$unassigned_token = DiffusionIdentityUnassignedDatasource::FUNCTION_TOKEN;
foreach ($xactions as $xaction) {
$old = $xaction->getOldValue();
$new = $xaction->getNewValue();
if (!strlen($new)) {
continue;
}
if ($new === $old) {
continue;
}
if ($new === $unassigned_token) {
continue;
}
$assignee_list = id(new PhabricatorPeopleQuery())
->setViewer($this->getActor())
->withPHIDs(array($new))
->execute();
if (!$assignee_list) {
$errors[] = $this->newInvalidError(
pht('User "%s" is not a valid user.',
$new));
}
}
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/repository/xaction/PhabricatorRepositorySymbolSourcesTransaction.php | src/applications/repository/xaction/PhabricatorRepositorySymbolSourcesTransaction.php | <?php
final class PhabricatorRepositorySymbolSourcesTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:symbol-source';
public function generateOldValue($object) {
return $object->getSymbolSources();
}
public function applyInternalEffects($object, $value) {
$object->setDetail('symbol-sources', $value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if ($old) {
$display_old = $this->renderHandleList($old);
} else {
$display_old = $this->renderValue(pht('None'));
}
if ($new) {
$display_new = $this->renderHandleList($new);
} else {
$display_new = $this->renderValue(pht('None'));
}
return pht(
'%s changed symbol sources from %s to %s.',
$this->renderAuthor(),
$display_old,
$display_new);
}
public function validateTransactions($object, array $xactions) {
$errors = array();
foreach ($xactions as $xaction) {
$old = $object->getSymbolSources();
$new = $xaction->getNewValue();
// If the viewer is adding new repositories, make sure they are
// valid and visible.
$add = array_diff($new, $old);
if (!$add) {
continue;
}
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($this->getActor())
->withPHIDs($add)
->execute();
$repositories = mpull($repositories, null, 'getPHID');
foreach ($add as $phid) {
if (isset($repositories[$phid])) {
continue;
}
$errors[] = $this->newInvalidError(
pht(
'Repository ("%s") does not exist, or you do not have '.
'permission to see it.',
$phid),
$xaction);
break;
}
}
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/repository/xaction/PhabricatorRepositoryTransactionType.php | src/applications/repository/xaction/PhabricatorRepositoryTransactionType.php | <?php
abstract class PhabricatorRepositoryTransactionType
extends PhabricatorModularTransactionType {
protected function validateRefList($object, array $xactions) {
$errors = array();
foreach ($xactions as $xaction) {
foreach ($xaction->getNewValue() as $pattern) {
// Check for invalid regular expressions.
$regexp = PhabricatorRepository::extractBranchRegexp($pattern);
if ($regexp !== null) {
$ok = @preg_match($regexp, '');
if ($ok === false) {
$errors[] = $this->newInvalidError(
pht(
'Expression "%s" is not a valid regular expression. Note '.
'that you must include delimiters.',
$regexp),
$xaction);
continue;
}
}
// Check for formatting mistakes like `regex(...)` instead of
// `regexp(...)`.
$matches = null;
if (preg_match('/^([^(]+)\\(.*\\)\z/', $pattern, $matches)) {
switch ($matches[1]) {
case 'regexp':
break;
default:
$errors[] = $this->newInvalidError(
pht(
'Matching function "%s(...)" is not recognized. Valid '.
'functions are: regexp(...).',
$matches[1]),
$xaction);
break;
}
}
}
}
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/repository/xaction/PhabricatorRepositoryActivateTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryActivateTransaction.php | <?php
final class PhabricatorRepositoryActivateTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:activate';
public function generateOldValue($object) {
return $object->isTracked();
}
public function applyInternalEffects($object, $value) {
// The first time a repository is activated, clear the "new repository"
// flag so we stop showing setup hints.
if ($value) {
$object->setDetail('newly-initialized', false);
}
$object->setDetail('tracking-enabled', $value);
}
public function getTitle() {
$new = $this->getNewValue();
// TODO: Old versions of this transaction use a boolean value, but
// should be migrated.
$is_deactivate =
(!$new) ||
($new == PhabricatorRepository::STATUS_INACTIVE);
if (!$is_deactivate) {
return pht(
'%s activated this repository.',
$this->renderAuthor());
} else {
return pht(
'%s deactivated this repository.',
$this->renderAuthor());
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
$status_map = PhabricatorRepository::getStatusMap();
foreach ($xactions as $xaction) {
$status = $xaction->getNewValue();
if (empty($status_map[$status])) {
$errors[] = $this->newInvalidError(
pht(
'Repository status "%s" is not valid. Valid statuses are: %s.',
$status,
implode(', ', array_keys($status_map))),
$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/repository/xaction/PhabricatorRepositoryFetchRefsTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryFetchRefsTransaction.php | <?php
final class PhabricatorRepositoryFetchRefsTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'fetch-refs';
public function generateOldValue($object) {
return $object->getFetchRules();
}
public function applyInternalEffects($object, $value) {
$object->setFetchRules($value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if (!$new) {
return pht(
'%s set this repository to fetch all refs.',
$this->renderAuthor());
} else if (!$old) {
return pht(
'%s set this repository to fetch refs: %s.',
$this->renderAuthor(),
$this->renderValue(implode(', ', $new)));
} else {
return pht(
'%s changed fetched refs from %s to %s.',
$this->renderAuthor(),
$this->renderValue(implode(', ', $old)),
$this->renderValue(implode(', ', $new)));
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
foreach ($xactions as $xaction) {
$new_value = $xaction->getNewValue();
if (!is_array($new_value) || !phutil_is_natural_list($new_value)) {
$errors[] = $this->newInvalidError(
pht(
'Fetch rules must be a list of strings, got "%s".',
phutil_describe_type($new_value)),
$xaction);
continue;
}
foreach ($new_value as $idx => $rule) {
if (!is_string($rule)) {
$errors[] = $this->newInvalidError(
pht(
'Fetch rule (at index "%s") must be a string, got "%s".',
$idx,
phutil_describe_type($rule)),
$xaction);
continue;
}
if (!strlen($rule)) {
$errors[] = $this->newInvalidError(
pht(
'Fetch rule (at index "%s") is empty. Fetch rules must '.
'contain text.',
$idx),
$xaction);
continue;
}
// Since we fetch ref "X" as "+X:X", don't allow rules to include
// colons. This is specific to Git and may not be relevant if
// Mercurial repositories eventually get fetch rules.
if (preg_match('/:/', $rule)) {
$errors[] = $this->newInvalidError(
pht(
'Fetch rule ("%s", at index "%s") is invalid: fetch rules '.
'must not contain colons.',
$rule,
$idx),
$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/repository/xaction/PhabricatorRepositoryMaintenanceTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryMaintenanceTransaction.php | <?php
final class PhabricatorRepositoryMaintenanceTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'maintenance';
public function generateOldValue($object) {
return $object->getReadOnlyMessage();
}
public function applyInternalEffects($object, $value) {
if ($value === null) {
$object
->setReadOnly(false)
->setReadOnlyMessage(null);
} else {
$object
->setReadOnly(true)
->setReadOnlyMessage($value);
}
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if (strlen($old) && !strlen($new)) {
return pht(
'%s took this repository out of maintenance mode.',
$this->renderAuthor());
} else if (!strlen($old) && strlen($new)) {
return pht(
'%s put this repository into maintenance mode.',
$this->renderAuthor());
} else {
return pht(
'%s updated the maintenance message for this repository.',
$this->renderAuthor());
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/xaction/PhabricatorRepositoryPermanentRefsTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryPermanentRefsTransaction.php | <?php
final class PhabricatorRepositoryPermanentRefsTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:autoclose-only';
public function generateOldValue($object) {
return $object->getPermanentRefRules();
}
public function applyInternalEffects($object, $value) {
$object->setPermanentRefRules($value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if (!$new) {
return pht(
'%s marked all branches in this repository as permanent.',
$this->renderAuthor());
} else if (!$old) {
return pht(
'%s set the permanent refs for this repository to: %s.',
$this->renderAuthor(),
$this->renderValue(implode(', ', $new)));
} else {
return pht(
'%s changed permanent refs for this repository from %s to %s.',
$this->renderAuthor(),
$this->renderValue(implode(', ', $old)),
$this->renderValue(implode(', ', $new)));
}
}
public function validateTransactions($object, array $xactions) {
return $this->validateRefList($object, $xactions);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/xaction/PhabricatorRepositoryVCSTransaction.php | src/applications/repository/xaction/PhabricatorRepositoryVCSTransaction.php | <?php
final class PhabricatorRepositoryVCSTransaction
extends PhabricatorRepositoryTransactionType {
const TRANSACTIONTYPE = 'repo:vcs';
public function generateOldValue($object) {
return $object->getVersionControlSystem();
}
public function applyInternalEffects($object, $value) {
$object->setVersionControlSystem($value);
}
public function validateTransactions($object, array $xactions) {
$errors = array();
$vcs_map = PhabricatorRepositoryType::getAllRepositoryTypes();
$current_vcs = $object->getVersionControlSystem();
if (!$this->isNewObject()) {
foreach ($xactions as $xaction) {
if ($xaction->getNewValue() == $current_vcs) {
continue;
}
$errors[] = $this->newInvalidError(
pht(
'You can not change the version control system an existing '.
'repository uses. It can only be set when a repository is '.
'first created.'),
$xaction);
}
return $errors;
}
$value = $object->getVersionControlSystem();
foreach ($xactions as $xaction) {
$value = $xaction->getNewValue();
if (isset($vcs_map[$value])) {
continue;
}
$errors[] = $this->newInvalidError(
pht(
'Specified version control system must be a VCS '.
'recognized by this software. Valid systems are: %s.',
implode(', ', array_keys($vcs_map))),
$xaction);
}
if ($value === null) {
$errors[] = $this->newRequiredError(
pht(
'When creating a repository, you must specify a valid '.
'underlying version control system. Valid systems are: %s.',
implode(', ', array_keys($vcs_map))));
}
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/repository/phid/PhabricatorRepositoryPullEventPHIDType.php | src/applications/repository/phid/PhabricatorRepositoryPullEventPHIDType.php | <?php
final class PhabricatorRepositoryPullEventPHIDType extends PhabricatorPHIDType {
const TYPECONST = 'PULE';
public function getTypeName() {
return pht('Pull Event');
}
public function newObject() {
return new PhabricatorRepositoryPullEvent();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new PhabricatorRepositoryPullEventQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$event = $objects[$phid];
$handle->setName(pht('Pull Event %d', $event->getID()));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/phid/PhabricatorRepositoryIdentityPHIDType.php | src/applications/repository/phid/PhabricatorRepositoryIdentityPHIDType.php | <?php
final class PhabricatorRepositoryIdentityPHIDType
extends PhabricatorPHIDType {
const TYPECONST = 'RIDT';
public function getTypeName() {
return pht('Repository Identity');
}
public function newObject() {
return new PhabricatorRepositoryIdentity();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new PhabricatorRepositoryIdentityQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
$avatar_uri = celerity_get_resource_uri('/rsrc/image/avatar.png');
foreach ($handles as $phid => $handle) {
$identity = $objects[$phid];
$id = $identity->getID();
$name = $identity->getIdentityNameRaw();
$handle->setObjectName(pht('Identity %d', $id));
$handle->setName($name);
$handle->setURI($identity->getURI());
$handle->setIcon('fa-user');
$handle->setImageURI($avatar_uri);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/phid/PhabricatorRepositoryRepositoryPHIDType.php | src/applications/repository/phid/PhabricatorRepositoryRepositoryPHIDType.php | <?php
final class PhabricatorRepositoryRepositoryPHIDType
extends PhabricatorPHIDType {
const TYPECONST = 'REPO';
public function getTypeName() {
return pht('Repository');
}
public function getTypeIcon() {
return 'fa-code';
}
public function newObject() {
return new PhabricatorRepository();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new PhabricatorRepositoryQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$repository = $objects[$phid];
$monogram = $repository->getMonogram();
$name = $repository->getName();
$uri = $repository->getURI();
$handle
->setName($monogram)
->setFullName("{$monogram} {$name}")
->setURI($uri)
->setMailStampName($monogram);
if ($repository->getStatus() !== PhabricatorRepository::STATUS_ACTIVE) {
$handle->setStatus(PhabricatorObjectHandle::STATUS_CLOSED);
}
}
}
public function canLoadNamedObject($name) {
return preg_match('/^(r[A-Z]+|R[1-9]\d*)\z/', $name);
}
public function loadNamedObjects(
PhabricatorObjectQuery $query,
array $names) {
$results = array();
$id_map = array();
foreach ($names as $key => $name) {
$id = substr($name, 1);
$id_map[$id][] = $name;
$names[$key] = substr($name, 1);
}
$query = id(new PhabricatorRepositoryQuery())
->setViewer($query->getViewer())
->withIdentifiers($names);
if ($query->execute()) {
$objects = $query->getIdentifierMap();
foreach ($objects as $key => $object) {
foreach (idx($id_map, $key, array()) as $name) {
$results[$name] = $object;
}
}
return $results;
} else {
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/repository/phid/PhabricatorRepositoryCommitPHIDType.php | src/applications/repository/phid/PhabricatorRepositoryCommitPHIDType.php | <?php
final class PhabricatorRepositoryCommitPHIDType extends PhabricatorPHIDType {
const TYPECONST = 'CMIT';
public function getTypeName() {
return pht('Diffusion Commit');
}
public function newObject() {
return new PhabricatorRepositoryCommit();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new DiffusionCommitQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
$unreachable = array();
foreach ($handles as $phid => $handle) {
$commit = $objects[$phid];
if ($commit->isUnreachable()) {
$unreachable[$phid] = $commit;
}
}
if ($unreachable) {
$query = id(new DiffusionCommitHintQuery())
->setViewer($query->getViewer())
->withCommits($unreachable);
$query->execute();
$hints = $query->getCommitMap();
} else {
$hints = array();
}
foreach ($handles as $phid => $handle) {
$commit = $objects[$phid];
$repository = $commit->getRepository();
$commit_identifier = $commit->getCommitIdentifier();
$name = $repository->formatCommitName($commit_identifier);
if ($commit->isUnreachable()) {
$handle->setStatus(PhabricatorObjectHandle::STATUS_CLOSED);
// If we have a hint about this commit being rewritten, add the
// rewrite target to the handle name. This reduces the chance users
// will be caught offguard by the rewrite.
$hint = idx($hints, $phid);
if ($hint && $hint->isRewritten()) {
$new_name = $hint->getNewCommitIdentifier();
$new_name = $repository->formatCommitName($new_name);
$name = pht("%s \xE2\x99\xBB %s", $name, $new_name);
}
}
$summary = $commit->getSummary();
if (strlen($summary)) {
$full_name = $name.': '.$summary;
} else {
$full_name = $name;
}
$handle->setName($name);
$handle->setFullName($full_name);
$handle->setURI($commit->getURI());
$handle->setTimestamp($commit->getEpoch());
}
}
public static function getCommitObjectNamePattern() {
$min_unqualified = PhabricatorRepository::MINIMUM_UNQUALIFIED_HASH;
$min_qualified = PhabricatorRepository::MINIMUM_QUALIFIED_HASH;
return
'(?:r[A-Z]+:?|R[0-9]+:)[1-9]\d*'.
'|'.
'(?:r[A-Z]+:?|R[0-9]+:)[a-f0-9]{'.$min_qualified.',40}'.
'|'.
'[a-f0-9]{'.$min_unqualified.',40}';
}
public function canLoadNamedObject($name) {
$pattern = self::getCommitObjectNamePattern();
return preg_match('(^'.$pattern.'$)', $name);
}
public function loadNamedObjects(
PhabricatorObjectQuery $query,
array $names) {
$query = id(new DiffusionCommitQuery())
->setViewer($query->getViewer())
->withIdentifiers($names);
$query->execute();
return $query->getIdentifierMap();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/phid/PhabricatorRepositoryURIPHIDType.php | src/applications/repository/phid/PhabricatorRepositoryURIPHIDType.php | <?php
final class PhabricatorRepositoryURIPHIDType extends PhabricatorPHIDType {
const TYPECONST = 'RURI';
public function getTypeName() {
return pht('Repository URI');
}
public function newObject() {
return new PhabricatorRepositoryURI();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new PhabricatorRepositoryURIQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$uri = $objects[$phid];
$handle->setName(
pht('URI %d %s', $uri->getID(), $uri->getDisplayURI()));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/phid/PhabricatorRepositoryRefCursorPHIDType.php | src/applications/repository/phid/PhabricatorRepositoryRefCursorPHIDType.php | <?php
final class PhabricatorRepositoryRefCursorPHIDType
extends PhabricatorPHIDType {
const TYPECONST = 'RREF';
public function getTypeName() {
return pht('Repository Ref');
}
public function getTypeIcon() {
return 'fa-code-fork';
}
public function newObject() {
return new PhabricatorRepositoryRefCursor();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new PhabricatorRepositoryRefCursorQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$ref = $objects[$phid];
$name = $ref->getRefName();
$handle->setName($name);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/phid/PhabricatorRepositorySyncEventPHIDType.php | src/applications/repository/phid/PhabricatorRepositorySyncEventPHIDType.php | <?php
final class PhabricatorRepositorySyncEventPHIDType extends PhabricatorPHIDType {
const TYPECONST = 'SYNE';
public function getTypeName() {
return pht('Sync Event');
}
public function newObject() {
return new PhabricatorRepositorySyncEvent();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new PhabricatorRepositorySyncEventQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$event = $objects[$phid];
$handle->setName(pht('Sync Event %d', $event->getID()));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/phid/PhabricatorRepositoryPushLogPHIDType.php | src/applications/repository/phid/PhabricatorRepositoryPushLogPHIDType.php | <?php
final class PhabricatorRepositoryPushLogPHIDType extends PhabricatorPHIDType {
const TYPECONST = 'PSHL';
public function getTypeName() {
return pht('Push Log');
}
public function newObject() {
return new PhabricatorRepositoryPushLog();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new PhabricatorRepositoryPushLogQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$log = $objects[$phid];
$handle->setName(pht('Push Log %d', $log->getID()));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/phid/PhabricatorRepositoryPushEventPHIDType.php | src/applications/repository/phid/PhabricatorRepositoryPushEventPHIDType.php | <?php
final class PhabricatorRepositoryPushEventPHIDType extends PhabricatorPHIDType {
const TYPECONST = 'PSHE';
public function getTypeName() {
return pht('Push Event');
}
public function newObject() {
return new PhabricatorRepositoryPushEvent();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new PhabricatorRepositoryPushEventQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$event = $objects[$phid];
$handle->setName(pht('Push Event %d', $event->getID()));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/config/PhabricatorRepositoryConfigOptions.php | src/applications/repository/config/PhabricatorRepositoryConfigOptions.php | <?php
final class PhabricatorRepositoryConfigOptions
extends PhabricatorApplicationConfigOptions {
public function getName() {
return pht('Repositories');
}
public function getDescription() {
return pht('Configure repositories.');
}
public function getIcon() {
return 'fa-hdd-o';
}
public function getGroup() {
return 'apps';
}
public function getOptions() {
return array(
$this->newOption('repository.default-local-path', 'string', '/var/repo/')
->setLocked(true)
->setSummary(
pht('Default location to store local copies of repositories.'))
->setDescription(
pht(
'The default location in which to store working copies and other '.
'data about repositories. %s will control and manage '.
'data here, so you should **not** choose an existing directory '.
'full of data you care about.',
PlatformSymbols::getPlatformServerName())),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/conduit/RepositoryConduitAPIMethod.php | src/applications/repository/conduit/RepositoryConduitAPIMethod.php | <?php
abstract class RepositoryConduitAPIMethod extends ConduitAPIMethod {
final public function getApplication() {
return PhabricatorApplication::getByClass(
'PhabricatorDiffusionApplication');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/conduit/RepositoryQueryConduitAPIMethod.php | src/applications/repository/conduit/RepositoryQueryConduitAPIMethod.php | <?php
final class RepositoryQueryConduitAPIMethod
extends RepositoryConduitAPIMethod {
public function getAPIMethodName() {
return 'repository.query';
}
public function getMethodStatus() {
return self::METHOD_STATUS_FROZEN;
}
public function getMethodStatusDescription() {
return pht(
'This method is frozen and will eventually be deprecated. New code '.
'should use "diffusion.repository.search" instead.');
}
public function getMethodDescription() {
return pht('Query repositories.');
}
public function newQueryObject() {
return new PhabricatorRepositoryQuery();
}
protected function defineParamTypes() {
return array(
'ids' => 'optional list<int>',
'phids' => 'optional list<phid>',
'callsigns' => 'optional list<string>',
'vcsTypes' => 'optional list<string>',
'remoteURIs' => 'optional list<string>',
'uuids' => 'optional list<string>',
);
}
protected function defineReturnType() {
return 'list<dict>';
}
protected function execute(ConduitAPIRequest $request) {
$query = $this->newQueryForRequest($request);
$ids = $request->getValue('ids', array());
if ($ids) {
$query->withIDs($ids);
}
$phids = $request->getValue('phids', array());
if ($phids) {
$query->withPHIDs($phids);
}
$callsigns = $request->getValue('callsigns', array());
if ($callsigns) {
$query->withCallsigns($callsigns);
}
$vcs_types = $request->getValue('vcsTypes', array());
if ($vcs_types) {
$query->withTypes($vcs_types);
}
$remote_uris = $request->getValue('remoteURIs', array());
if ($remote_uris) {
$query->withURIs($remote_uris);
}
$uuids = $request->getValue('uuids', array());
if ($uuids) {
$query->withUUIDs($uuids);
}
$pager = $this->newPager($request);
$repositories = $query->executeWithCursorPager($pager);
$results = array();
foreach ($repositories as $repository) {
$results[] = $repository->toDictionary();
}
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/repository/search/DiffusionCommitFulltextEngine.php | src/applications/repository/search/DiffusionCommitFulltextEngine.php | <?php
final class DiffusionCommitFulltextEngine
extends PhabricatorFulltextEngine {
protected function buildAbstractDocument(
PhabricatorSearchAbstractDocument $document,
$object) {
$commit = id(new DiffusionCommitQuery())
->setViewer($this->getViewer())
->withPHIDs(array($object->getPHID()))
->needCommitData(true)
->executeOne();
$repository = $commit->getRepository();
$commit_data = $commit->getCommitData();
$date_created = $commit->getEpoch();
$commit_message = $commit_data->getCommitMessage();
$author_phid = $commit_data->getCommitDetail('authorPHID');
$monogram = $commit->getMonogram();
$summary = $commit_data->getSummary();
$title = "{$monogram} {$summary}";
$document
->setDocumentCreated($date_created)
->setDocumentModified($date_created)
->setDocumentTitle($title);
$document->addField(
PhabricatorSearchDocumentFieldType::FIELD_BODY,
$commit_message);
if ($author_phid) {
$document->addRelationship(
PhabricatorSearchRelationship::RELATIONSHIP_AUTHOR,
$author_phid,
PhabricatorPeopleUserPHIDType::TYPECONST,
$date_created);
}
$document->addRelationship(
PhabricatorSearchRelationship::RELATIONSHIP_REPOSITORY,
$repository->getPHID(),
PhabricatorRepositoryRepositoryPHIDType::TYPECONST,
$date_created);
$document->addRelationship(
$commit->isUnreachable()
? PhabricatorSearchRelationship::RELATIONSHIP_CLOSED
: PhabricatorSearchRelationship::RELATIONSHIP_OPEN,
$commit->getPHID(),
PhabricatorRepositoryCommitPHIDType::TYPECONST,
PhabricatorTime::getNow());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/search/PhabricatorRepositoryFerretEngine.php | src/applications/repository/search/PhabricatorRepositoryFerretEngine.php | <?php
final class PhabricatorRepositoryFerretEngine
extends PhabricatorFerretEngine {
public function getApplicationName() {
return 'repository';
}
public function getScopeName() {
return 'repository';
}
public function newSearchEngine() {
return new PhabricatorRepositorySearchEngine();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/search/DiffusionCommitFerretEngine.php | src/applications/repository/search/DiffusionCommitFerretEngine.php | <?php
final class DiffusionCommitFerretEngine
extends PhabricatorFerretEngine {
public function getApplicationName() {
return 'repository';
}
public function getScopeName() {
return 'commit';
}
public function newSearchEngine() {
return new PhabricatorCommitSearchEngine();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/search/PhabricatorRepositoryIdentityFerretEngine.php | src/applications/repository/search/PhabricatorRepositoryIdentityFerretEngine.php | <?php
final class PhabricatorRepositoryIdentityFerretEngine
extends PhabricatorFerretEngine {
public function getApplicationName() {
return 'repository';
}
public function getScopeName() {
return 'identity';
}
public function newSearchEngine() {
return new DiffusionRepositoryIdentitySearchEngine();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/search/PhabricatorRepositoryFulltextEngine.php | src/applications/repository/search/PhabricatorRepositoryFulltextEngine.php | <?php
final class PhabricatorRepositoryFulltextEngine
extends PhabricatorFulltextEngine {
protected function buildAbstractDocument(
PhabricatorSearchAbstractDocument $document,
$object) {
$repo = $object;
$document->setDocumentTitle($repo->getName());
$document->addField(
PhabricatorSearchDocumentFieldType::FIELD_BODY,
$repo->getRepositorySlug()."\n".$repo->getDetail('description'));
$document->setDocumentCreated($repo->getDateCreated());
$document->setDocumentModified($repo->getDateModified());
$document->addRelationship(
$repo->isTracked()
? PhabricatorSearchRelationship::RELATIONSHIP_OPEN
: PhabricatorSearchRelationship::RELATIONSHIP_CLOSED,
$repo->getPHID(),
PhabricatorRepositoryRepositoryPHIDType::TYPECONST,
PhabricatorTime::getNow());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/data/PhabricatorRepositoryParsedChange.php | src/applications/repository/data/PhabricatorRepositoryParsedChange.php | <?php
final class PhabricatorRepositoryParsedChange extends Phobject {
private $pathID;
private $targetPathID;
private $targetCommitID;
private $changeType;
private $fileType;
private $isDirect;
private $commitSequence;
public function setPathID($path_id) {
$this->pathID = $path_id;
return $this;
}
public function getPathID() {
return $this->pathID;
}
public function setCommitSequence($commit_sequence) {
$this->commitSequence = $commit_sequence;
return $this;
}
public function getCommitSequence() {
return $this->commitSequence;
}
public function setIsDirect($is_direct) {
$this->isDirect = $is_direct;
return $this;
}
public function getIsDirect() {
return $this->isDirect;
}
public function setFileType($file_type) {
$this->fileType = $file_type;
return $this;
}
public function getFileType() {
return $this->fileType;
}
public function setChangeType($change_type) {
$this->changeType = $change_type;
return $this;
}
public function getChangeType() {
return $this->changeType;
}
public function setTargetCommitID($target_commit_id) {
$this->targetCommitID = $target_commit_id;
return $this;
}
public function getTargetCommitID() {
return $this->targetCommitID;
}
public function setTargetPathID($target_path_id) {
$this->targetPathID = $target_path_id;
return $this;
}
public function getTargetPathID() {
return $this->targetPathID;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php | src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php | <?php
/**
* Given a commit and a path, efficiently determine the most recent ancestor
* commit where the path was touched.
*
* In Git and Mercurial, log operations with a path are relatively slow. For
* example:
*
* git log -n1 <commit> -- <path>
*
* ...routinely takes several hundred milliseconds, and equivalent requests
* often take longer in Mercurial.
*
* Unfortunately, this operation is fundamental to rendering a repository for
* the web, and essentially everything else that's slow can be reduced to this
* plus some trivial work afterward. Making this fast is desirable and powerful,
* and allows us to make other things fast by expressing them in terms of this
* query.
*
* Because the query is fundamentally a graph query, it isn't easy to express
* in a reasonable way in MySQL, and we can't do round trips to the server to
* walk the graph without incurring huge performance penalties.
*
* However, the total amount of data in the graph is relatively small. By
* caching it in chunks and keeping it in APC, we can reasonably load and walk
* the graph in PHP quickly.
*
* For more context, see T2683.
*
* Structure of the Cache
* ======================
*
* The cache divides commits into buckets (see @{method:getBucketSize}). To
* walk the graph, we pull a commit's bucket. The bucket is a map from commit
* IDs to a list of parents and changed paths, separated by `null`. For
* example, a bucket might look like this:
*
* array(
* 1 => array(0, null, 17, 18),
* 2 => array(1, null, 4),
* // ...
* )
*
* This means that commit ID 1 has parent commit 0 (a special value meaning
* no parents) and affected path IDs 17 and 18. Commit ID 2 has parent commit 1,
* and affected path 4.
*
* This data structure attempts to balance compactness, ease of construction,
* simplicity of cache semantics, and lookup performance. In the average case,
* it appears to do a reasonable job at this.
*
* @task query Querying the Graph Cache
* @task cache Cache Internals
*/
final class PhabricatorRepositoryGraphCache extends Phobject {
private $rebuiltKeys = array();
/* -( Querying the Graph Cache )------------------------------------------- */
/**
* Search the graph cache for the most modification to a path.
*
* @param int The commit ID to search ancestors of.
* @param int The path ID to search for changes to.
* @param float Maximum number of seconds to spend trying to satisfy this
* query using the graph cache. By default, `0.5` (500ms).
* @return mixed Commit ID, or `null` if no ancestors exist, or `false` if
* the graph cache was unable to determine the answer.
* @task query
*/
public function loadLastModifiedCommitID($commit_id, $path_id, $time = 0.5) {
$commit_id = (int)$commit_id;
$path_id = (int)$path_id;
$bucket_data = null;
$data_key = null;
$seen = array();
$t_start = microtime(true);
$iterations = 0;
while (true) {
$bucket_key = $this->getBucketKey($commit_id);
if (($data_key != $bucket_key) || $bucket_data === null) {
$bucket_data = $this->getBucketData($bucket_key);
$data_key = $bucket_key;
}
if (empty($bucket_data[$commit_id])) {
// Rebuild the cache bucket, since the commit might be a very recent
// one that we'll pick up by rebuilding.
$bucket_data = $this->getBucketData($bucket_key, $bucket_data);
if (empty($bucket_data[$commit_id])) {
// A rebuild didn't help. This can occur legitimately if the commit
// is new and hasn't parsed yet.
return false;
}
// Otherwise, the rebuild gave us the data, so we can keep going.
$did_fill = true;
} else {
$did_fill = false;
}
// Sanity check so we can survive and recover from bad data.
if (isset($seen[$commit_id])) {
phlog(pht('Unexpected infinite loop in %s!', __CLASS__));
return false;
} else {
$seen[$commit_id] = true;
}
// `$data` is a list: the commit's parent IDs, followed by `null`,
// followed by the modified paths in ascending order. We figure out the
// first parent first, then check if the path was touched. If the path
// was touched, this is the commit we're after. If not, walk backward
// in the tree.
$items = $bucket_data[$commit_id];
$size = count($items);
// Walk past the parent information.
$parent_id = null;
for ($ii = 0;; ++$ii) {
if ($items[$ii] === null) {
break;
}
if ($parent_id === null) {
$parent_id = $items[$ii];
}
}
// Look for a modification to the path.
for (; $ii < $size; ++$ii) {
$item = $items[$ii];
if ($item > $path_id) {
break;
}
if ($item === $path_id) {
return $commit_id;
}
}
if ($parent_id) {
$commit_id = $parent_id;
// Periodically check if we've spent too long looking for a result
// in the cache, and return so we can fall back to a VCS operation.
// This keeps us from having a degenerate worst case if, e.g., the
// cache is cold and we need to inspect a very large number of blocks
// to satisfy the query.
++$iterations;
// If we performed a cache fill in this cycle, always check the time
// limit, since cache fills may take a significant amount of time.
if ($did_fill || ($iterations % 64 === 0)) {
$t_end = microtime(true);
if (($t_end - $t_start) > $time) {
return false;
}
}
continue;
}
// If we have an explicit 0, that means this commit really has no parents.
// Usually, it is the first commit in the repository.
if ($parent_id === 0) {
return null;
}
// If we didn't find a parent, the parent data isn't available. We fail
// to find an answer in the cache and fall back to querying the VCS.
return false;
}
}
/* -( Cache Internals )---------------------------------------------------- */
/**
* Get the bucket key for a given commit ID.
*
* @param int Commit ID.
* @return int Bucket key.
* @task cache
*/
private function getBucketKey($commit_id) {
return (int)floor($commit_id / $this->getBucketSize());
}
/**
* Get the cache key for a given bucket key (from @{method:getBucketKey}).
*
* @param int Bucket key.
* @return string Cache key.
* @task cache
*/
private function getBucketCacheKey($bucket_key) {
static $prefix;
if ($prefix === null) {
$self = get_class($this);
$size = $this->getBucketSize();
$prefix = "{$self}:{$size}:2:";
}
return $prefix.$bucket_key;
}
/**
* Get the number of items per bucket.
*
* @return int Number of items to store per bucket.
* @task cache
*/
private function getBucketSize() {
return 4096;
}
/**
* Retrieve or build a graph cache bucket from the cache.
*
* Normally, this operates as a readthrough cache call. It can also be used
* to force a cache update by passing the existing data to `$rebuild_data`.
*
* @param int Bucket key, from @{method:getBucketKey}.
* @param mixed Current data, to force a cache rebuild of this bucket.
* @return array Data from the cache.
* @task cache
*/
private function getBucketData($bucket_key, $rebuild_data = null) {
$cache_key = $this->getBucketCacheKey($bucket_key);
// TODO: This cache stuff could be handled more gracefully, but the
// database cache currently requires values to be strings and needs
// some tweaking to support this as part of a stack. Our cache semantics
// here are also unusual (not purely readthrough) because this cache is
// appendable.
$cache_level1 = PhabricatorCaches::getRepositoryGraphL1Cache();
$cache_level2 = PhabricatorCaches::getRepositoryGraphL2Cache();
if ($rebuild_data === null) {
$bucket_data = $cache_level1->getKey($cache_key);
if ($bucket_data) {
return $bucket_data;
}
$bucket_data = $cache_level2->getKey($cache_key);
if ($bucket_data) {
$unserialized = @unserialize($bucket_data);
if ($unserialized) {
// Fill APC if we got a database hit but missed in APC.
$cache_level1->setKey($cache_key, $unserialized);
return $unserialized;
}
}
}
if (!is_array($rebuild_data)) {
$rebuild_data = array();
}
$bucket_data = $this->rebuildBucket($bucket_key, $rebuild_data);
// Don't bother writing the data if we didn't update anything.
if ($bucket_data !== $rebuild_data) {
$cache_level2->setKey($cache_key, serialize($bucket_data));
$cache_level1->setKey($cache_key, $bucket_data);
}
return $bucket_data;
}
/**
* Rebuild a cache bucket, amending existing data if available.
*
* @param int Bucket key, from @{method:getBucketKey}.
* @param array Existing bucket data.
* @return array Rebuilt bucket data.
* @task cache
*/
private function rebuildBucket($bucket_key, array $current_data) {
// First, check if we've already rebuilt this bucket. In some cases (like
// browsing a repository at some commit) it's common to issue many lookups
// against one commit. If that commit has been discovered but not yet
// fully imported, we'll repeatedly attempt to rebuild the bucket. If the
// first rebuild did not work, subsequent rebuilds are very unlikely to
// have any effect. We can just skip the rebuild in these cases.
if (isset($this->rebuiltKeys[$bucket_key])) {
return $current_data;
} else {
$this->rebuiltKeys[$bucket_key] = true;
}
$bucket_min = ($bucket_key * $this->getBucketSize());
$bucket_max = ($bucket_min + $this->getBucketSize()) - 1;
// We need to reload all of the commits in the bucket because there is
// no guarantee that they'll get parsed in order, so we can fill large
// commit IDs before small ones. Later on, we'll ignore the commits we
// already know about.
$table_commit = new PhabricatorRepositoryCommit();
$table_repository = new PhabricatorRepository();
$conn_r = $table_commit->establishConnection('r');
// Find all the Git and Mercurial commits in the block which have completed
// change import. We can't fill the cache accurately for commits which have
// not completed change import, so just pretend we don't know about them.
// In these cases, we will ultimately fall back to VCS queries.
$commit_rows = queryfx_all(
$conn_r,
'SELECT c.id FROM %T c
JOIN %T r ON c.repositoryID = r.id AND r.versionControlSystem IN (%Ls)
WHERE c.id BETWEEN %d AND %d
AND (c.importStatus & %d) = %d',
$table_commit->getTableName(),
$table_repository->getTableName(),
array(
PhabricatorRepositoryType::REPOSITORY_TYPE_GIT,
PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL,
),
$bucket_min,
$bucket_max,
PhabricatorRepositoryCommit::IMPORTED_CHANGE,
PhabricatorRepositoryCommit::IMPORTED_CHANGE);
// If we don't have any data, just return the existing data.
if (!$commit_rows) {
return $current_data;
}
// Remove the commits we already have data for. We don't need to rebuild
// these. If there's nothing left, return the existing data.
$commit_ids = ipull($commit_rows, 'id', 'id');
$commit_ids = array_diff_key($commit_ids, $current_data);
if (!$commit_ids) {
return $current_data;
}
// Find all the path changes for the new commits.
$path_changes = queryfx_all(
$conn_r,
'SELECT commitID, pathID FROM %T
WHERE commitID IN (%Ld)
AND (isDirect = 1 OR changeType = %d)',
PhabricatorRepository::TABLE_PATHCHANGE,
$commit_ids,
DifferentialChangeType::TYPE_CHILD);
$path_changes = igroup($path_changes, 'commitID');
// Find all the parents for the new commits.
$parents = queryfx_all(
$conn_r,
'SELECT childCommitID, parentCommitID FROM %T
WHERE childCommitID IN (%Ld)
ORDER BY id ASC',
PhabricatorRepository::TABLE_PARENTS,
$commit_ids);
$parents = igroup($parents, 'childCommitID');
// Build the actual data for the cache.
foreach ($commit_ids as $commit_id) {
$parent_ids = array();
if (!empty($parents[$commit_id])) {
foreach ($parents[$commit_id] as $row) {
$parent_ids[] = (int)$row['parentCommitID'];
}
} else {
// We expect all rows to have parents (commits with no parents get
// an explicit "0" placeholder). If we're in an older repository, the
// parent information might not have been populated yet. Decline to fill
// the cache if we don't have the parent information, since the fill
// will be incorrect.
continue;
}
if (isset($path_changes[$commit_id])) {
$path_ids = $path_changes[$commit_id];
foreach ($path_ids as $key => $path_id) {
$path_ids[$key] = (int)$path_id['pathID'];
}
sort($path_ids);
} else {
$path_ids = array();
}
$value = $parent_ids;
$value[] = null;
foreach ($path_ids as $path_id) {
$value[] = $path_id;
}
$current_data[$commit_id] = $value;
}
return $current_data;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/daemon/PhabricatorRepositoryGraphStream.php | src/applications/repository/daemon/PhabricatorRepositoryGraphStream.php | <?php
abstract class PhabricatorRepositoryGraphStream extends Phobject {
abstract public function getParents($commit);
abstract public function getCommitDate($commit);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/daemon/PhabricatorGitGraphStream.php | src/applications/repository/daemon/PhabricatorGitGraphStream.php | <?php
final class PhabricatorGitGraphStream
extends PhabricatorRepositoryGraphStream {
private $repository;
private $iterator;
private $startCommit;
private $parents = array();
private $dates = array();
public function __construct(
PhabricatorRepository $repository,
$start_commit = null) {
$this->repository = $repository;
$this->startCommit = $start_commit;
if ($start_commit !== null) {
$future = $repository->getLocalCommandFuture(
'log %s %s --',
'--format=%H%x01%P%x01%ct',
gitsprintf('%s', $start_commit));
} else {
$future = $repository->getLocalCommandFuture(
'log %s --all --',
'--format=%H%x01%P%x01%ct');
}
$this->iterator = new LinesOfALargeExecFuture($future);
$this->iterator->setDelimiter("\n");
$this->iterator->rewind();
}
public function getParents($commit) {
if (!isset($this->parents[$commit])) {
$this->parseUntil($commit);
}
$parents = $this->parents[$commit];
// NOTE: In Git, it is possible for a commit to list the same parent more
// than once. See T5226. Discard duplicate parents.
return array_unique($parents);
}
public function getCommitDate($commit) {
if (!isset($this->dates[$commit])) {
$this->parseUntil($commit);
}
return $this->dates[$commit];
}
private function parseUntil($commit) {
if ($this->isParsed($commit)) {
return;
}
$gitlog = $this->iterator;
while ($gitlog->valid()) {
$line = $gitlog->current();
$gitlog->next();
$line = trim($line);
if (!strlen($line)) {
break;
}
list($hash, $parents, $epoch) = explode("\1", $line);
if ($parents) {
$parents = explode(' ', $parents);
} else {
// First commit.
$parents = array();
}
$this->dates[$hash] = $epoch;
$this->parents[$hash] = $parents;
if ($this->isParsed($commit)) {
return;
}
}
if ($this->startCommit !== null) {
throw new Exception(
pht(
'Commit "%s" is not a reachable ancestor of "%s".',
$commit,
$this->startCommit));
} else {
throw new Exception(
pht(
'Commit "%s" is not a reachable ancestor of any ref.',
$commit));
}
}
private function isParsed($commit) {
return isset($this->dates[$commit]);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/daemon/PhabricatorMercurialGraphStream.php | src/applications/repository/daemon/PhabricatorMercurialGraphStream.php | <?php
/**
* Streaming interface on top of "hg log" that gives us performant access to
* the Mercurial commit graph with one nonblocking invocation of "hg". See
* @{class:PhabricatorRepositoryPullLocalDaemon}.
*/
final class PhabricatorMercurialGraphStream
extends PhabricatorRepositoryGraphStream {
private $repository;
private $iterator;
private $parents = array();
private $dates = array();
private $local = array();
private $localParents = array();
public function __construct(PhabricatorRepository $repository,
$start_commit = null) {
$this->repository = $repository;
$command = 'log --template %s --rev %s';
$template = '{rev}\1{node}\1{date}\1{parents}\2';
if ($start_commit !== null) {
$revset = hgsprintf('reverse(ancestors(%s))', $start_commit);
} else {
$revset = 'reverse(all())';
}
$future = $repository->getLocalCommandFuture(
$command,
$template,
$revset);
$this->iterator = new LinesOfALargeExecFuture($future);
$this->iterator->setDelimiter("\2");
$this->iterator->rewind();
}
public function getParents($commit) {
if (!isset($this->parents[$commit])) {
$this->parseUntil('node', $commit);
$local = $this->localParents[$commit];
// The normal parsing pass gives us the local revision numbers of the
// parents, but since we've decided we care about this data, we need to
// convert them into full hashes. To do this, we parse to the deepest
// one and then just look them up.
$parents = array();
if ($local) {
$this->parseUntil('rev', min($local));
foreach ($local as $rev) {
$parents[] = $this->local[$rev];
}
}
$this->parents[$commit] = $parents;
// Throw away the local info for this commit, we no longer need it.
unset($this->localParents[$commit]);
}
return $this->parents[$commit];
}
public function getCommitDate($commit) {
if (!isset($this->dates[$commit])) {
$this->parseUntil('node', $commit);
}
return $this->dates[$commit];
}
/**
* Parse until we have consumed some object. There are two types of parses:
* parse until we find a commit hash ($until_type = "node"), or parse until we
* find a local commit number ($until_type = "rev"). We use the former when
* looking up commits, and the latter when resolving parents.
*/
private function parseUntil($until_type, $until_name) {
if ($this->isParsed($until_type, $until_name)) {
return;
}
$hglog = $this->iterator;
while ($hglog->valid()) {
$line = $hglog->current();
$hglog->next();
$line = trim($line);
if (!strlen($line)) {
break;
}
list($rev, $node, $date, $parents) = explode("\1", $line);
$rev = (int)$rev;
$date = (int)head(explode('.', $date));
$this->dates[$node] = $date;
$this->local[$rev] = $node;
$this->localParents[$node] = $this->parseParents($parents, $rev);
if ($this->isParsed($until_type, $until_name)) {
return;
}
}
throw new Exception(
pht(
"No such %s '%s' in repository!",
$until_type,
$until_name));
}
/**
* Parse a {parents} template, returning the local commit numbers.
*/
private function parseParents($parents, $target_rev) {
// The hg '{parents}' token is empty if there is one "natural" parent
// (predecessor local commit ID). Otherwise, it may have one or two
// parents. The string looks like this:
//
// 151:1f6c61a60586 154:1d5f799ebe1e
$parents = trim($parents);
if (strlen($parents)) {
$local = array();
$parents = explode(' ', $parents);
foreach ($parents as $key => $parent) {
$parent = (int)head(explode(':', $parent));
if ($parent == -1) {
// Initial commits will sometimes have "-1" as a parent.
continue;
}
$local[] = $parent;
}
} else if ($target_rev) {
// We have empty parents. If there's a predecessor, that's the local
// parent number.
$local = array($target_rev - 1);
} else {
// Initial commits will sometimes have no parents.
$local = array();
}
return $local;
}
/**
* Returns true if the object specified by $type ('rev' or 'node') and
* $name (rev or node name) has been consumed from the hg process.
*/
private function isParsed($type, $name) {
switch ($type) {
case 'rev':
return isset($this->local[$name]);
case 'node':
return isset($this->dates[$name]);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/daemon/PhabricatorRepositoryPullLocalDaemonModule.php | src/applications/repository/daemon/PhabricatorRepositoryPullLocalDaemonModule.php | <?php
final class PhabricatorRepositoryPullLocalDaemonModule
extends PhutilDaemonOverseerModule {
private $cursor = 0;
public function shouldWakePool(PhutilDaemonPool $pool) {
$class = $pool->getPoolDaemonClass();
if ($class != 'PhabricatorRepositoryPullLocalDaemon') {
return false;
}
if ($this->shouldThrottle($class, 1)) {
return false;
}
$table = new PhabricatorRepositoryStatusMessage();
$table_name = $table->getTableName();
$conn = $table->establishConnection('r');
$row = queryfx_one(
$conn,
'SELECT id FROM %T WHERE statusType = %s
AND id > %d ORDER BY id DESC LIMIT 1',
$table_name,
PhabricatorRepositoryStatusMessage::TYPE_NEEDS_UPDATE,
$this->cursor);
if (!$row) {
return false;
}
$this->cursor = (int)$row['id'];
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/repository/daemon/PhabricatorRepositoryPullLocalDaemon.php | src/applications/repository/daemon/PhabricatorRepositoryPullLocalDaemon.php | <?php
/**
* Run pull commands on local working copies to keep them up to date. This
* daemon handles all repository types.
*
* By default, the daemon pulls **every** repository. If you want it to be
* responsible for only some repositories, you can launch it with a list of
* repositories:
*
* ./phd launch repositorypulllocal -- X Q Z
*
* You can also launch a daemon which is responsible for all //but// one or
* more repositories:
*
* ./phd launch repositorypulllocal -- --not A --not B
*
* If you have a very large number of repositories and some aren't being pulled
* as frequently as you'd like, you can either change the pull frequency of
* the less-important repositories to a larger number (so the daemon will skip
* them more often) or launch one daemon for all the less-important repositories
* and one for the more important repositories (or one for each more important
* repository).
*
* @task pull Pulling Repositories
*/
final class PhabricatorRepositoryPullLocalDaemon
extends PhabricatorDaemon {
private $statusMessageCursor = 0;
/* -( Pulling Repositories )----------------------------------------------- */
/**
* @task pull
*/
protected function run() {
$argv = $this->getArgv();
array_unshift($argv, __CLASS__);
$args = new PhutilArgumentParser($argv);
$args->parse(
array(
array(
'name' => 'no-discovery',
'help' => pht('Pull only, without discovering commits.'),
),
array(
'name' => 'not',
'param' => 'repository',
'repeat' => true,
'help' => pht('Do not pull __repository__.'),
),
array(
'name' => 'repositories',
'wildcard' => true,
'help' => pht('Pull specific __repositories__ instead of all.'),
),
));
$no_discovery = $args->getArg('no-discovery');
$include = $args->getArg('repositories');
$exclude = $args->getArg('not');
// Each repository has an individual pull frequency; after we pull it,
// wait that long to pull it again. When we start up, try to pull everything
// serially.
$retry_after = array();
$min_sleep = 15;
$max_sleep = phutil_units('5 minutes in seconds');
$max_futures = 4;
$futures = array();
$queue = array();
$future_pool = new FuturePool();
$future_pool->getIteratorTemplate()
->setUpdateInterval($min_sleep);
$sync_wait = phutil_units('2 minutes in seconds');
$last_sync = array();
while (!$this->shouldExit()) {
PhabricatorCaches::destroyRequestCache();
$device = AlmanacKeys::getLiveDevice();
$pullable = $this->loadPullableRepositories($include, $exclude, $device);
// If any repositories have the NEEDS_UPDATE flag set, pull them
// as soon as possible.
$need_update_messages = $this->loadRepositoryUpdateMessages(true);
foreach ($need_update_messages as $message) {
$repo = idx($pullable, $message->getRepositoryID());
if (!$repo) {
continue;
}
$this->log(
pht(
'Got an update message for repository "%s"!',
$repo->getMonogram()));
$retry_after[$message->getRepositoryID()] = time();
}
if ($device) {
$unsynchronized = $this->loadUnsynchronizedRepositories($device);
$now = PhabricatorTime::getNow();
foreach ($unsynchronized as $repository) {
$id = $repository->getID();
$this->log(
pht(
'Cluster repository ("%s") is out of sync on this node ("%s").',
$repository->getDisplayName(),
$device->getName()));
// Don't let out-of-sync conditions trigger updates too frequently,
// since we don't want to get trapped in a death spiral if sync is
// failing.
$sync_at = idx($last_sync, $id, 0);
$wait_duration = ($now - $sync_at);
if ($wait_duration < $sync_wait) {
$this->log(
pht(
'Skipping forced out-of-sync update because the last update '.
'was too recent (%s seconds ago).',
$wait_duration));
continue;
}
$last_sync[$id] = $now;
$retry_after[$id] = $now;
}
}
// If any repositories were deleted, remove them from the retry timer map
// so we don't end up with a retry timer that never gets updated and
// causes us to sleep for the minimum amount of time.
$retry_after = array_select_keys(
$retry_after,
array_keys($pullable));
// Figure out which repositories we need to queue for an update.
foreach ($pullable as $id => $repository) {
$now = PhabricatorTime::getNow();
$display_name = $repository->getDisplayName();
if (isset($futures[$id])) {
$this->log(
pht(
'Repository "%s" is currently updating.',
$display_name));
continue;
}
if (isset($queue[$id])) {
$this->log(
pht(
'Repository "%s" is already queued.',
$display_name));
continue;
}
$after = idx($retry_after, $id);
if (!$after) {
$smart_wait = $repository->loadUpdateInterval($min_sleep);
$last_update = $this->loadLastUpdate($repository);
$after = $last_update + $smart_wait;
$retry_after[$id] = $after;
$this->log(
pht(
'Scheduling repository "%s" with an update window of %s '.
'second(s). Last update was %s second(s) ago.',
$display_name,
new PhutilNumber($smart_wait),
new PhutilNumber($now - $last_update)));
}
if ($after > time()) {
$this->log(
pht(
'Repository "%s" is not due for an update for %s second(s).',
$display_name,
new PhutilNumber($after - $now)));
continue;
}
$this->log(
pht(
'Scheduling repository "%s" for an update (%s seconds overdue).',
$display_name,
new PhutilNumber($now - $after)));
$queue[$id] = $after;
}
// Process repositories in the order they became candidates for updates.
asort($queue);
// Dequeue repositories until we hit maximum parallelism.
while ($queue && (count($futures) < $max_futures)) {
foreach ($queue as $id => $time) {
$repository = idx($pullable, $id);
if (!$repository) {
$this->log(
pht('Repository %s is no longer pullable; skipping.', $id));
unset($queue[$id]);
continue;
}
$display_name = $repository->getDisplayName();
$this->log(
pht(
'Starting update for repository "%s".',
$display_name));
unset($queue[$id]);
$future = $this->buildUpdateFuture(
$repository,
$no_discovery);
$futures[$id] = $future->getFutureKey();
$future_pool->addFuture($future);
break;
}
}
if ($queue) {
$this->log(
pht(
'Not enough process slots to schedule the other %s '.
'repository(s) for updates yet.',
phutil_count($queue)));
}
if ($future_pool->hasFutures()) {
while ($future_pool->hasFutures()) {
$future = $future_pool->resolve();
$this->stillWorking();
if ($future === null) {
$this->log(pht('Waiting for updates to complete...'));
if ($this->loadRepositoryUpdateMessages()) {
$this->log(pht('Interrupted by pending updates!'));
break;
}
continue;
}
$future_key = $future->getFutureKey();
$repository_id = null;
foreach ($futures as $id => $key) {
if ($key === $future_key) {
$repository_id = $id;
unset($futures[$id]);
break;
}
}
$retry_after[$repository_id] = $this->resolveUpdateFuture(
$pullable[$repository_id],
$future,
$min_sleep);
// We have a free slot now, so go try to fill it.
break;
}
// Jump back into prioritization if we had any futures to deal with.
continue;
}
$should_hibernate = $this->waitForUpdates($max_sleep, $retry_after);
if ($should_hibernate) {
break;
}
}
}
/**
* @task pull
*/
private function buildUpdateFuture(
PhabricatorRepository $repository,
$no_discovery) {
$bin = dirname(phutil_get_library_root('phabricator')).'/bin/repository';
$flags = array();
if ($no_discovery) {
$flags[] = '--no-discovery';
}
$monogram = $repository->getMonogram();
$future = new ExecFuture('%s update %Ls -- %s', $bin, $flags, $monogram);
// Sometimes, the underlying VCS commands will hang indefinitely. We've
// observed this occasionally with GitHub, and other users have observed
// it with other VCS servers.
// To limit the damage this can cause, kill the update out after a
// reasonable amount of time, under the assumption that it has hung.
// Since it's hard to know what a "reasonable" amount of time is given that
// users may be downloading a repository full of pirated movies over a
// potato, these limits are fairly generous. Repositories exceeding these
// limits can be manually pulled with `bin/repository update X`, which can
// just run for as long as it wants.
if ($repository->isImporting()) {
$timeout = phutil_units('4 hours in seconds');
} else {
$timeout = phutil_units('15 minutes in seconds');
}
$future->setTimeout($timeout);
// The default TERM inherited by this process is "unknown", which causes PHP
// to produce a warning upon startup. Override it to squash this output to
// STDERR.
$future->updateEnv('TERM', 'dumb');
return $future;
}
/**
* Check for repositories that should be updated immediately.
*
* With the `$consume` flag, an internal cursor will also be incremented so
* that these messages are not returned by subsequent calls.
*
* @param bool Pass `true` to consume these messages, so the process will
* not see them again.
* @return list<wild> Pending update messages.
*
* @task pull
*/
private function loadRepositoryUpdateMessages($consume = false) {
$type_need_update = PhabricatorRepositoryStatusMessage::TYPE_NEEDS_UPDATE;
$messages = id(new PhabricatorRepositoryStatusMessage())->loadAllWhere(
'statusType = %s AND id > %d',
$type_need_update,
$this->statusMessageCursor);
// Keep track of messages we've seen so that we don't load them again.
// If we reload messages, we can get stuck a loop if we have a failing
// repository: we update immediately in response to the message, but do
// not clear the message because the update does not succeed. We then
// immediately retry. Instead, messages are only permitted to trigger
// an immediate update once.
if ($consume) {
foreach ($messages as $message) {
$this->statusMessageCursor = max(
$this->statusMessageCursor,
$message->getID());
}
}
return $messages;
}
/**
* @task pull
*/
private function loadLastUpdate(PhabricatorRepository $repository) {
$table = new PhabricatorRepositoryStatusMessage();
$conn = $table->establishConnection('r');
$epoch = queryfx_one(
$conn,
'SELECT MAX(epoch) last_update FROM %T
WHERE repositoryID = %d
AND statusType IN (%Ls)',
$table->getTableName(),
$repository->getID(),
array(
PhabricatorRepositoryStatusMessage::TYPE_INIT,
PhabricatorRepositoryStatusMessage::TYPE_FETCH,
));
if ($epoch) {
return (int)$epoch['last_update'];
}
return PhabricatorTime::getNow();
}
/**
* @task pull
*/
private function loadPullableRepositories(
array $include,
array $exclude,
AlmanacDevice $device = null) {
$query = id(new PhabricatorRepositoryQuery())
->setViewer($this->getViewer());
if ($include) {
$query->withIdentifiers($include);
}
$repositories = $query->execute();
$repositories = mpull($repositories, null, 'getPHID');
if ($include) {
$map = $query->getIdentifierMap();
foreach ($include as $identifier) {
if (empty($map[$identifier])) {
throw new Exception(
pht(
'No repository "%s" exists!',
$identifier));
}
}
}
if ($exclude) {
$xquery = id(new PhabricatorRepositoryQuery())
->setViewer($this->getViewer())
->withIdentifiers($exclude);
$excluded_repos = $xquery->execute();
$xmap = $xquery->getIdentifierMap();
foreach ($exclude as $identifier) {
if (empty($xmap[$identifier])) {
throw new Exception(
pht(
'No repository "%s" exists!',
$identifier));
}
}
foreach ($excluded_repos as $excluded_repo) {
unset($repositories[$excluded_repo->getPHID()]);
}
}
foreach ($repositories as $key => $repository) {
if (!$repository->isTracked()) {
unset($repositories[$key]);
}
}
$viewer = $this->getViewer();
$filter = id(new DiffusionLocalRepositoryFilter())
->setViewer($viewer)
->setDevice($device)
->setRepositories($repositories);
$repositories = $filter->execute();
foreach ($filter->getRejectionReasons() as $reason) {
$this->log($reason);
}
// Shuffle the repositories, then re-key the array since shuffle()
// discards keys. This is mostly for startup, we'll use soft priorities
// later.
shuffle($repositories);
$repositories = mpull($repositories, null, 'getID');
return $repositories;
}
/**
* @task pull
*/
private function resolveUpdateFuture(
PhabricatorRepository $repository,
ExecFuture $future,
$min_sleep) {
$display_name = $repository->getDisplayName();
$this->log(pht('Resolving update for "%s".', $display_name));
try {
list($stdout, $stderr) = $future->resolvex();
} catch (Exception $ex) {
$proxy = new PhutilProxyException(
pht(
'Error while updating the "%s" repository.',
$display_name),
$ex);
phlog($proxy);
$smart_wait = $repository->loadUpdateInterval($min_sleep);
return PhabricatorTime::getNow() + $smart_wait;
}
if (strlen($stderr)) {
$stderr_msg = pht(
'Unexpected output while updating repository "%s": %s',
$display_name,
$stderr);
phlog($stderr_msg);
}
$smart_wait = $repository->loadUpdateInterval($min_sleep);
$this->log(
pht(
'Based on activity in repository "%s", considering a wait of %s '.
'seconds before update.',
$display_name,
new PhutilNumber($smart_wait)));
return PhabricatorTime::getNow() + $smart_wait;
}
/**
* Sleep for a short period of time, waiting for update messages from the
*
*
* @task pull
*/
private function waitForUpdates($min_sleep, array $retry_after) {
$this->log(
pht('No repositories need updates right now, sleeping...'));
$sleep_until = time() + $min_sleep;
if ($retry_after) {
$sleep_until = min($sleep_until, min($retry_after));
}
while (($sleep_until - time()) > 0) {
$sleep_duration = ($sleep_until - time());
if ($this->shouldHibernate($sleep_duration)) {
return true;
}
$this->log(
pht(
'Sleeping for %s more second(s)...',
new PhutilNumber($sleep_duration)));
$this->sleep(1);
if ($this->shouldExit()) {
$this->log(pht('Awakened from sleep by graceful shutdown!'));
return false;
}
if ($this->loadRepositoryUpdateMessages()) {
$this->log(pht('Awakened from sleep by pending updates!'));
break;
}
}
return false;
}
private function loadUnsynchronizedRepositories(AlmanacDevice $device) {
$viewer = $this->getViewer();
$table = new PhabricatorRepositoryWorkingCopyVersion();
$conn = $table->establishConnection('r');
$our_versions = queryfx_all(
$conn,
'SELECT repositoryPHID, repositoryVersion FROM %R WHERE devicePHID = %s',
$table,
$device->getPHID());
$our_versions = ipull($our_versions, 'repositoryVersion', 'repositoryPHID');
$max_versions = queryfx_all(
$conn,
'SELECT repositoryPHID, MAX(repositoryVersion) maxVersion FROM %R
GROUP BY repositoryPHID',
$table);
$max_versions = ipull($max_versions, 'maxVersion', 'repositoryPHID');
$unsynchronized_phids = array();
foreach ($max_versions as $repository_phid => $max_version) {
$our_version = idx($our_versions, $repository_phid);
if (($our_version === null) || ($our_version < $max_version)) {
$unsynchronized_phids[] = $repository_phid;
}
}
if (!$unsynchronized_phids) {
return array();
}
return id(new PhabricatorRepositoryQuery())
->setViewer($viewer)
->withPHIDs($unsynchronized_phids)
->execute();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/engine/PhabricatorRepositoryIdentityEditEngine.php | src/applications/repository/engine/PhabricatorRepositoryIdentityEditEngine.php | <?php
final class PhabricatorRepositoryIdentityEditEngine
extends PhabricatorEditEngine {
const ENGINECONST = 'repository.identity';
public function isEngineConfigurable() {
return false;
}
public function getEngineName() {
return pht('Repository Identities');
}
public function getSummaryHeader() {
return pht('Edit Repository Identity Configurations');
}
public function getSummaryText() {
return pht('This engine is used to edit Repository identities.');
}
public function getEngineApplicationClass() {
return 'PhabricatorDiffusionApplication';
}
protected function newEditableObject() {
return new PhabricatorRepositoryIdentity();
}
protected function newObjectQuery() {
return new PhabricatorRepositoryIdentityQuery();
}
protected function getObjectCreateTitleText($object) {
return pht('Create Identity');
}
protected function getObjectCreateButtonText($object) {
return pht('Create Identity');
}
protected function getObjectEditTitleText($object) {
return pht('Edit Identity: %s', $object->getIdentityShortName());
}
protected function getObjectEditShortText($object) {
return pht('Edit Identity');
}
protected function getObjectCreateShortText() {
return pht('Create Identity');
}
protected function getObjectName() {
return pht('Identity');
}
protected function getEditorURI() {
return '/diffusion/identity/edit/';
}
protected function getObjectCreateCancelURI($object) {
return '/diffusion/identity/';
}
protected function getObjectViewURI($object) {
return $object->getURI();
}
protected function getCreateNewObjectPolicy() {
return PhabricatorPolicies::POLICY_USER;
}
protected function buildCustomEditFields($object) {
return array(
id(new DiffusionIdentityAssigneeEditField())
->setKey('manuallySetUserPHID')
->setLabel(pht('Assigned To'))
->setDescription(pht('Override this identity\'s assignment.'))
->setTransactionType(
PhabricatorRepositoryIdentityAssignTransaction::TRANSACTIONTYPE)
->setIsCopyable(true)
->setIsNullable(true)
->setSingleValue($object->getManuallySetUserPHID()),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/engine/PhabricatorRepositoryRefEngine.php | src/applications/repository/engine/PhabricatorRepositoryRefEngine.php | <?php
/**
* Update the ref cursors for a repository, which track the positions of
* branches, bookmarks, and tags.
*/
final class PhabricatorRepositoryRefEngine
extends PhabricatorRepositoryEngine {
private $newPositions = array();
private $deadPositions = array();
private $permanentCommits = array();
private $rebuild;
public function setRebuild($rebuild) {
$this->rebuild = $rebuild;
return $this;
}
public function getRebuild() {
return $this->rebuild;
}
public function updateRefs() {
$this->newPositions = array();
$this->deadPositions = array();
$this->permanentCommits = array();
$repository = $this->getRepository();
$viewer = $this->getViewer();
$branches_may_close = false;
$vcs = $repository->getVersionControlSystem();
switch ($vcs) {
case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN:
// No meaningful refs of any type in Subversion.
$maps = array();
break;
case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL:
$branches = $this->loadMercurialBranchPositions($repository);
$bookmarks = $this->loadMercurialBookmarkPositions($repository);
$maps = array(
PhabricatorRepositoryRefCursor::TYPE_BRANCH => $branches,
PhabricatorRepositoryRefCursor::TYPE_BOOKMARK => $bookmarks,
);
$branches_may_close = true;
break;
case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
$maps = $this->loadGitRefPositions($repository);
break;
default:
throw new Exception(pht('Unknown VCS "%s"!', $vcs));
}
// Fill in any missing types with empty lists.
$maps = $maps + array(
PhabricatorRepositoryRefCursor::TYPE_BRANCH => array(),
PhabricatorRepositoryRefCursor::TYPE_TAG => array(),
PhabricatorRepositoryRefCursor::TYPE_BOOKMARK => array(),
PhabricatorRepositoryRefCursor::TYPE_REF => array(),
);
$all_cursors = id(new PhabricatorRepositoryRefCursorQuery())
->setViewer($viewer)
->withRepositoryPHIDs(array($repository->getPHID()))
->needPositions(true)
->execute();
$cursor_groups = mgroup($all_cursors, 'getRefType');
// Find all the heads of permanent refs.
$all_closing_heads = array();
foreach ($all_cursors as $cursor) {
// See T13284. Note that we're considering whether this ref was a
// permanent ref or not the last time we updated refs for this
// repository. This allows us to handle things properly when a ref
// is reconfigured from non-permanent to permanent.
$was_permanent = $cursor->getIsPermanent();
if (!$was_permanent) {
continue;
}
foreach ($cursor->getPositionIdentifiers() as $identifier) {
$all_closing_heads[] = $identifier;
}
}
$all_closing_heads = array_unique($all_closing_heads);
$all_closing_heads = $this->removeMissingCommits($all_closing_heads);
foreach ($maps as $type => $refs) {
$cursor_group = idx($cursor_groups, $type, array());
$this->updateCursors($cursor_group, $refs, $type, $all_closing_heads);
}
if ($this->permanentCommits) {
$this->setPermanentFlagOnCommits($this->permanentCommits);
}
$save_cursors = $this->getCursorsForUpdate($repository, $all_cursors);
if ($this->newPositions || $this->deadPositions || $save_cursors) {
$repository->openTransaction();
$this->saveNewPositions();
$this->deleteDeadPositions();
foreach ($save_cursors as $cursor) {
$cursor->save();
}
$repository->saveTransaction();
}
$branches = $maps[PhabricatorRepositoryRefCursor::TYPE_BRANCH];
if ($branches && $branches_may_close) {
$this->updateBranchStates($repository, $branches);
}
}
private function getCursorsForUpdate(
PhabricatorRepository $repository,
array $cursors) {
assert_instances_of($cursors, 'PhabricatorRepositoryRefCursor');
$publisher = $repository->newPublisher();
$results = array();
foreach ($cursors as $cursor) {
$diffusion_ref = $cursor->newDiffusionRepositoryRef();
$is_permanent = $publisher->isPermanentRef($diffusion_ref);
if ($is_permanent == $cursor->getIsPermanent()) {
continue;
}
$cursor->setIsPermanent((int)$is_permanent);
$results[] = $cursor;
}
return $results;
}
private function updateBranchStates(
PhabricatorRepository $repository,
array $branches) {
assert_instances_of($branches, 'DiffusionRepositoryRef');
$viewer = $this->getViewer();
$all_cursors = id(new PhabricatorRepositoryRefCursorQuery())
->setViewer($viewer)
->withRepositoryPHIDs(array($repository->getPHID()))
->needPositions(true)
->execute();
$state_map = array();
$type_branch = PhabricatorRepositoryRefCursor::TYPE_BRANCH;
foreach ($all_cursors as $cursor) {
if ($cursor->getRefType() !== $type_branch) {
continue;
}
$raw_name = $cursor->getRefNameRaw();
foreach ($cursor->getPositions() as $position) {
$hash = $position->getCommitIdentifier();
$state_map[$raw_name][$hash] = $position;
}
}
$updates = array();
foreach ($branches as $branch) {
$position = idx($state_map, $branch->getShortName(), array());
$position = idx($position, $branch->getCommitIdentifier());
if (!$position) {
continue;
}
$fields = $branch->getRawFields();
$position_state = (bool)$position->getIsClosed();
$branch_state = (bool)idx($fields, 'closed');
if ($position_state != $branch_state) {
$updates[$position->getID()] = (int)$branch_state;
}
}
if ($updates) {
$position_table = id(new PhabricatorRepositoryRefPosition());
$conn = $position_table->establishConnection('w');
$position_table->openTransaction();
foreach ($updates as $position_id => $branch_state) {
queryfx(
$conn,
'UPDATE %T SET isClosed = %d WHERE id = %d',
$position_table->getTableName(),
$branch_state,
$position_id);
}
$position_table->saveTransaction();
}
}
private function markPositionNew(
PhabricatorRepositoryRefPosition $position) {
$this->newPositions[] = $position;
return $this;
}
private function markPositionDead(
PhabricatorRepositoryRefPosition $position) {
$this->deadPositions[] = $position;
return $this;
}
private function markPermanentCommits(array $identifiers) {
foreach ($identifiers as $identifier) {
$this->permanentCommits[$identifier] = $identifier;
}
return $this;
}
/**
* Remove commits which no longer exist in the repository from a list.
*
* After a force push and garbage collection, we may have branch cursors which
* point at commits which no longer exist. This can make commands issued later
* fail. See T5839 for discussion.
*
* @param list<string> List of commit identifiers.
* @return list<string> List with nonexistent identifiers removed.
*/
private function removeMissingCommits(array $identifiers) {
if (!$identifiers) {
return array();
}
$resolved = id(new DiffusionLowLevelResolveRefsQuery())
->setRepository($this->getRepository())
->withRefs($identifiers)
->execute();
foreach ($identifiers as $key => $identifier) {
if (empty($resolved[$identifier])) {
unset($identifiers[$key]);
}
}
return $identifiers;
}
private function updateCursors(
array $cursors,
array $new_refs,
$ref_type,
array $all_closing_heads) {
$repository = $this->getRepository();
$publisher = $repository->newPublisher();
// NOTE: Mercurial branches may have multiple branch heads; this logic
// is complex primarily to account for that.
$cursors = mpull($cursors, null, 'getRefNameRaw');
// Group all the new ref values by their name. As above, these groups may
// have multiple members in Mercurial.
$ref_groups = mgroup($new_refs, 'getShortName');
foreach ($ref_groups as $name => $refs) {
$new_commits = mpull($refs, 'getCommitIdentifier', 'getCommitIdentifier');
$ref_cursor = idx($cursors, $name);
if ($ref_cursor) {
$old_positions = $ref_cursor->getPositions();
} else {
$old_positions = array();
}
// We're going to delete all the cursors pointing at commits which are
// no longer associated with the refs. This primarily makes the Mercurial
// multiple head case easier, and means that when we update a ref we
// delete the old one and write a new one.
foreach ($old_positions as $old_position) {
$hash = $old_position->getCommitIdentifier();
if (isset($new_commits[$hash])) {
// This ref previously pointed at this commit, and still does.
$this->log(
pht(
'Ref %s "%s" still points at %s.',
$ref_type,
$name,
$hash));
continue;
}
// This ref previously pointed at this commit, but no longer does.
$this->log(
pht(
'Ref %s "%s" no longer points at %s.',
$ref_type,
$name,
$hash));
// Nuke the obsolete cursor.
$this->markPositionDead($old_position);
}
// Now, we're going to insert new cursors for all the commits which are
// associated with this ref that don't currently have cursors.
$old_commits = mpull($old_positions, 'getCommitIdentifier');
$old_commits = array_fuse($old_commits);
$added_commits = array_diff_key($new_commits, $old_commits);
foreach ($added_commits as $identifier) {
$this->log(
pht(
'Ref %s "%s" now points at %s.',
$ref_type,
$name,
$identifier));
if (!$ref_cursor) {
// If this is the first time we've seen a particular ref (for
// example, a new branch) we need to insert a RefCursor record
// for it before we can insert a RefPosition.
$ref_cursor = $this->newRefCursor(
$repository,
$ref_type,
$name);
}
$new_position = id(new PhabricatorRepositoryRefPosition())
->setCursorID($ref_cursor->getID())
->setCommitIdentifier($identifier)
->setIsClosed(0);
$this->markPositionNew($new_position);
}
if ($publisher->isPermanentRef(head($refs))) {
// See T13284. If this cursor was already marked as permanent, we
// only need to publish the newly created ref positions. However, if
// this cursor was not previously permanent but has become permanent,
// we need to publish all the ref positions.
// This corresponds to users reconfiguring a branch to make it
// permanent without pushing any new commits to it.
$is_rebuild = $this->getRebuild();
$was_permanent = $ref_cursor->getIsPermanent();
if ($is_rebuild || !$was_permanent) {
$update_all = true;
} else {
$update_all = false;
}
if ($update_all) {
$update_commits = $new_commits;
} else {
$update_commits = $added_commits;
}
if ($is_rebuild) {
$exclude = array();
} else {
$exclude = $all_closing_heads;
}
foreach ($update_commits as $identifier) {
$new_identifiers = $this->loadNewCommitIdentifiers(
$identifier,
$exclude);
$this->markPermanentCommits($new_identifiers);
}
}
}
// Find any cursors for refs which no longer exist. This happens when a
// branch, tag or bookmark is deleted.
foreach ($cursors as $name => $cursor) {
if (!empty($ref_groups[$name])) {
// This ref still has some positions, so we don't need to wipe it
// out. Try the next one.
continue;
}
foreach ($cursor->getPositions() as $position) {
$this->log(
pht(
'Ref %s "%s" no longer exists.',
$cursor->getRefType(),
$cursor->getRefName()));
$this->markPositionDead($position);
}
}
}
/**
* Find all ancestors of a new closing branch head which are not ancestors
* of any old closing branch head.
*/
private function loadNewCommitIdentifiers(
$new_head,
array $all_closing_heads) {
$repository = $this->getRepository();
$vcs = $repository->getVersionControlSystem();
switch ($vcs) {
case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL:
if ($all_closing_heads) {
$parts = array();
foreach ($all_closing_heads as $head) {
$parts[] = hgsprintf('%s', $head);
}
// See T5896. Mercurial can not parse an "X or Y or ..." rev list
// with more than about 300 items, because it exceeds the maximum
// allowed recursion depth. Split all the heads into chunks of
// 256, and build a query like this:
//
// ((1 or 2 or ... or 255) or (256 or 257 or ... 511))
//
// If we have more than 65535 heads, we'll do that again:
//
// (((1 or ...) or ...) or ((65536 or ...) or ...))
$chunk_size = 256;
while (count($parts) > $chunk_size) {
$chunks = array_chunk($parts, $chunk_size);
foreach ($chunks as $key => $chunk) {
$chunks[$key] = '('.implode(' or ', $chunk).')';
}
$parts = array_values($chunks);
}
$parts = '('.implode(' or ', $parts).')';
list($stdout) = $this->getRepository()->execxLocalCommand(
'log --template %s --rev %s',
'{node}\n',
hgsprintf('%s', $new_head).' - '.$parts);
} else {
list($stdout) = $this->getRepository()->execxLocalCommand(
'log --template %s --rev %s',
'{node}\n',
hgsprintf('%s', $new_head));
}
$stdout = trim($stdout);
if (!strlen($stdout)) {
return array();
}
return phutil_split_lines($stdout, $retain_newlines = false);
case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
if ($all_closing_heads) {
// See PHI1474. This length of list may exceed the maximum size of
// a command line argument list, so pipe the list in using "--stdin"
// instead.
$ref_list = array();
$ref_list[] = $new_head;
foreach ($all_closing_heads as $old_head) {
$ref_list[] = '^'.$old_head;
}
$ref_list[] = '--';
$ref_list = implode("\n", $ref_list)."\n";
$future = $this->getRepository()->getLocalCommandFuture(
'log %s --stdin --',
'--format=%H');
list($stdout) = $future
->write($ref_list)
->resolvex();
} else {
list($stdout) = $this->getRepository()->execxLocalCommand(
'log %s %s --',
'--format=%H',
gitsprintf('%s', $new_head));
}
$stdout = trim($stdout);
if (!strlen($stdout)) {
return array();
}
return phutil_split_lines($stdout, $retain_newlines = false);
default:
throw new Exception(pht('Unsupported VCS "%s"!', $vcs));
}
}
/**
* Mark a list of commits as permanent, and queue workers for those commits
* which don't already have the flag.
*/
private function setPermanentFlagOnCommits(array $identifiers) {
$repository = $this->getRepository();
$commit_table = new PhabricatorRepositoryCommit();
$conn = $commit_table->establishConnection('w');
$vcs = $repository->getVersionControlSystem();
switch ($vcs) {
case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
$class = 'PhabricatorRepositoryGitCommitMessageParserWorker';
break;
case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN:
$class = 'PhabricatorRepositorySvnCommitMessageParserWorker';
break;
case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL:
$class = 'PhabricatorRepositoryMercurialCommitMessageParserWorker';
break;
default:
throw new Exception(pht("Unknown repository type '%s'!", $vcs));
}
$identifier_tokens = array();
foreach ($identifiers as $identifier) {
$identifier_tokens[] = qsprintf(
$conn,
'%s',
$identifier);
}
$all_commits = array();
foreach (PhabricatorLiskDAO::chunkSQL($identifier_tokens) as $chunk) {
$rows = queryfx_all(
$conn,
'SELECT id, phid, commitIdentifier, importStatus FROM %T
WHERE repositoryID = %d AND commitIdentifier IN (%LQ)',
$commit_table->getTableName(),
$repository->getID(),
$chunk);
foreach ($rows as $row) {
$all_commits[] = $row;
}
}
$commit_refs = array();
foreach ($identifiers as $identifier) {
// See T13591. This construction is a bit ad-hoc, but the priority
// function currently only cares about the number of refs we have
// discovered, so we'll get the right result even without filling
// these records out in detail.
$commit_refs[] = id(new PhabricatorRepositoryCommitRef())
->setIdentifier($identifier);
}
$task_priority = $this->getImportTaskPriority(
$repository,
$commit_refs);
$permanent_flag = PhabricatorRepositoryCommit::IMPORTED_PERMANENT;
$published_flag = PhabricatorRepositoryCommit::IMPORTED_PUBLISH;
$all_commits = ipull($all_commits, null, 'commitIdentifier');
foreach ($identifiers as $identifier) {
$row = idx($all_commits, $identifier);
if (!$row) {
throw new Exception(
pht(
'Commit "%s" has not been discovered yet! Run discovery before '.
'updating refs.',
$identifier));
}
$import_status = $row['importStatus'];
if (!($import_status & $permanent_flag)) {
// Set the "permanent" flag.
$import_status = ($import_status | $permanent_flag);
// See T13580. Clear the "published" flag, so publishing executes
// again. We may have previously performed a no-op "publish" on the
// commit to make sure it has all bits in the "IMPORTED_ALL" bitmask.
$import_status = ($import_status & ~$published_flag);
queryfx(
$conn,
'UPDATE %T SET importStatus = %d WHERE id = %d',
$commit_table->getTableName(),
$import_status,
$row['id']);
$this->queueCommitImportTask(
$repository,
$row['phid'],
$task_priority,
$via = 'ref');
}
}
return $this;
}
private function newRefCursor(
PhabricatorRepository $repository,
$ref_type,
$ref_name) {
$cursor = id(new PhabricatorRepositoryRefCursor())
->setRepositoryPHID($repository->getPHID())
->setRefType($ref_type)
->setRefName($ref_name);
$publisher = $repository->newPublisher();
$diffusion_ref = $cursor->newDiffusionRepositoryRef();
$is_permanent = $publisher->isPermanentRef($diffusion_ref);
$cursor->setIsPermanent((int)$is_permanent);
try {
return $cursor->save();
} catch (AphrontDuplicateKeyQueryException $ex) {
// If we raced another daemon to create this position and lost the race,
// load the cursor the other daemon created instead.
}
$viewer = $this->getViewer();
$cursor = id(new PhabricatorRepositoryRefCursorQuery())
->setViewer($viewer)
->withRepositoryPHIDs(array($repository->getPHID()))
->withRefTypes(array($ref_type))
->withRefNames(array($ref_name))
->needPositions(true)
->executeOne();
if (!$cursor) {
throw new Exception(
pht(
'Failed to create a new ref cursor (for "%s", of type "%s", in '.
'repository "%s") because it collided with an existing cursor, '.
'but then failed to load that cursor.',
$ref_name,
$ref_type,
$repository->getDisplayName()));
}
return $cursor;
}
private function saveNewPositions() {
$positions = $this->newPositions;
foreach ($positions as $position) {
try {
$position->save();
} catch (AphrontDuplicateKeyQueryException $ex) {
// We may race another daemon to create this position. If we do, and
// we lose the race, that's fine: the other daemon did our work for
// us and we can continue.
}
}
$this->newPositions = array();
}
private function deleteDeadPositions() {
$positions = $this->deadPositions;
$repository = $this->getRepository();
foreach ($positions as $position) {
// Shove this ref into the old refs table so the discovery engine
// can check if any commits have been rendered unreachable.
id(new PhabricatorRepositoryOldRef())
->setRepositoryPHID($repository->getPHID())
->setCommitIdentifier($position->getCommitIdentifier())
->save();
$position->delete();
}
$this->deadPositions = array();
}
/* -( Updating Git Refs )-------------------------------------------------- */
/**
* @task git
*/
private function loadGitRefPositions(PhabricatorRepository $repository) {
$refs = id(new DiffusionLowLevelGitRefQuery())
->setRepository($repository)
->execute();
return mgroup($refs, 'getRefType');
}
/* -( Updating Mercurial Refs )-------------------------------------------- */
/**
* @task hg
*/
private function loadMercurialBranchPositions(
PhabricatorRepository $repository) {
return id(new DiffusionLowLevelMercurialBranchesQuery())
->setRepository($repository)
->execute();
}
/**
* @task hg
*/
private function loadMercurialBookmarkPositions(
PhabricatorRepository $repository) {
// TODO: Implement support for Mercurial bookmarks.
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/repository/engine/PhabricatorRepositoryPullEngine.php | src/applications/repository/engine/PhabricatorRepositoryPullEngine.php | <?php
/**
* Manages execution of `git pull` and `hg pull` commands for
* @{class:PhabricatorRepository} objects. Used by
* @{class:PhabricatorRepositoryPullLocalDaemon}.
*
* This class also covers initial working copy setup through `git clone`,
* `git init`, `hg clone`, `hg init`, or `svnadmin create`.
*
* @task pull Pulling Working Copies
* @task git Pulling Git Working Copies
* @task hg Pulling Mercurial Working Copies
* @task svn Pulling Subversion Working Copies
* @task internal Internals
*/
final class PhabricatorRepositoryPullEngine
extends PhabricatorRepositoryEngine {
/* -( Pulling Working Copies )--------------------------------------------- */
public function pullRepository() {
$repository = $this->getRepository();
$lock = $this->newRepositoryLock($repository, 'repo.pull', true);
try {
$lock->lock();
} catch (PhutilLockException $ex) {
throw new DiffusionDaemonLockException(
pht(
'Another process is currently updating repository "%s", '.
'skipping pull.',
$repository->getDisplayName()));
}
try {
$result = $this->pullRepositoryWithLock();
} catch (Exception $ex) {
$lock->unlock();
throw $ex;
}
$lock->unlock();
return $result;
}
private function pullRepositoryWithLock() {
$repository = $this->getRepository();
$viewer = PhabricatorUser::getOmnipotentUser();
if ($repository->isReadOnly()) {
$this->skipPull(
pht(
"Skipping pull on read-only repository.\n\n%s",
$repository->getReadOnlyMessageForDisplay()));
}
$is_hg = false;
$is_git = false;
$is_svn = false;
$vcs = $repository->getVersionControlSystem();
switch ($vcs) {
case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN:
// We never pull a local copy of non-hosted Subversion repositories.
if (!$repository->isHosted()) {
$this->skipPull(
pht(
'Repository "%s" is a non-hosted Subversion repository, which '.
'does not require a local working copy to be pulled.',
$repository->getDisplayName()));
return;
}
$is_svn = true;
break;
case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
$is_git = true;
break;
case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL:
$is_hg = true;
break;
default:
$this->abortPull(pht('Unknown VCS "%s"!', $vcs));
break;
}
$local_path = $repository->getLocalPath();
if ($local_path === null) {
$this->abortPull(
pht(
'No local path is configured for repository "%s".',
$repository->getDisplayName()));
}
try {
$dirname = dirname($local_path);
if (!Filesystem::pathExists($dirname)) {
Filesystem::createDirectory($dirname, 0755, $recursive = true);
}
if (!Filesystem::pathExists($local_path)) {
$this->logPull(
pht(
'Creating a new working copy for repository "%s".',
$repository->getDisplayName()));
if ($is_git) {
$this->executeGitCreate();
} else if ($is_hg) {
$this->executeMercurialCreate();
} else {
$this->executeSubversionCreate();
}
}
id(new DiffusionRepositoryClusterEngine())
->setViewer($viewer)
->setRepository($repository)
->synchronizeWorkingCopyBeforeRead();
if (!$repository->isHosted()) {
$this->logPull(
pht(
'Updating the working copy for repository "%s".',
$repository->getDisplayName()));
if ($is_git) {
$this->executeGitUpdate();
} else if ($is_hg) {
$this->executeMercurialUpdate();
}
}
if ($repository->isHosted()) {
if ($is_git) {
$this->installGitHook();
} else if ($is_svn) {
$this->installSubversionHook();
} else if ($is_hg) {
$this->installMercurialHook();
}
foreach ($repository->getHookDirectories() as $directory) {
$this->installHookDirectory($directory);
}
}
if ($is_git) {
$this->updateGitWorkingCopyConfiguration();
}
} catch (Exception $ex) {
$this->abortPull(
pht(
"Pull of '%s' failed: %s",
$repository->getDisplayName(),
$ex->getMessage()),
$ex);
}
$this->donePull();
return $this;
}
private function skipPull($message) {
$this->log($message);
$this->donePull();
}
private function abortPull($message, Exception $ex = null) {
$code_error = PhabricatorRepositoryStatusMessage::CODE_ERROR;
$this->updateRepositoryInitStatus($code_error, $message);
if ($ex) {
throw $ex;
} else {
throw new Exception($message);
}
}
private function logPull($message) {
$this->log($message);
}
private function donePull() {
$code_okay = PhabricatorRepositoryStatusMessage::CODE_OKAY;
$this->updateRepositoryInitStatus($code_okay);
}
private function updateRepositoryInitStatus($code, $message = null) {
$this->getRepository()->writeStatusMessage(
PhabricatorRepositoryStatusMessage::TYPE_INIT,
$code,
array(
'message' => $message,
));
}
private function installHook($path, array $hook_argv = array()) {
$this->log(pht('Installing commit hook to "%s"...', $path));
$repository = $this->getRepository();
$identifier = $this->getHookContextIdentifier($repository);
$root = dirname(phutil_get_library_root('phabricator'));
$bin = $root.'/bin/commit-hook';
$full_php_path = Filesystem::resolveBinary('php');
$cmd = csprintf(
'exec %s -f %s -- %s %Ls "$@"',
$full_php_path,
$bin,
$identifier,
$hook_argv);
$hook = "#!/bin/sh\nexport TERM=dumb\n{$cmd}\n";
Filesystem::writeFile($path, $hook);
Filesystem::changePermissions($path, 0755);
}
private function installHookDirectory($path) {
$readme = pht(
"To add custom hook scripts to this repository, add them to this ".
"directory.\n\nPhabricator will run any executables in this directory ".
"after running its own checks, as though they were normal hook ".
"scripts.");
Filesystem::createDirectory($path, 0755);
Filesystem::writeFile($path.'/README', $readme);
}
private function getHookContextIdentifier(PhabricatorRepository $repository) {
$identifier = $repository->getPHID();
$instance = PhabricatorEnv::getEnvConfig('cluster.instance');
if ($instance !== null && strlen($instance)) {
$identifier = "{$identifier}:{$instance}";
}
return $identifier;
}
/* -( Pulling Git Working Copies )----------------------------------------- */
/**
* @task git
*/
private function executeGitCreate() {
$repository = $this->getRepository();
$path = rtrim($repository->getLocalPath(), '/');
// See T13448. In all cases, we create repositories by using "git init"
// to build a bare, empty working copy. If we try to use "git clone"
// instead, we'll pull in too many refs if "Fetch Refs" is also
// configured. There's no apparent way to make "git clone" behave narrowly
// and no apparent reason to bother.
$repository->execxRemoteCommand(
'init --bare -- %s',
$path);
}
/**
* @task git
*/
private function executeGitUpdate() {
$repository = $this->getRepository();
// See T13479. We previously used "--show-toplevel", but this stopped
// working in Git 2.25.0 when run in a bare repository.
// NOTE: As of Git 2.21.1, "git rev-parse" can not parse "--" in its
// argument list, so we can not specify arguments unambiguously. Any
// version of Git which does not recognize the "--git-dir" flag will
// treat this as a request to parse the literal refname "--git-dir".
list($err, $stdout) = $repository->execLocalCommand(
'rev-parse --git-dir');
$repository_root = null;
$path = $repository->getLocalPath();
if (!$err) {
$repository_root = Filesystem::resolvePath(
rtrim($stdout, "\n"),
$path);
// If we're in a bare Git repository, the "--git-dir" will be the
// root directory. If we're in a working copy, the "--git-dir" will
// be the ".git/" directory.
// Test if the result is the root directory. If it is, we're in good
// shape and appear to be inside a bare repository. If not, take the
// parent directory to get out of the ".git/" folder.
if (!Filesystem::pathsAreEquivalent($repository_root, $path)) {
$repository_root = dirname($repository_root);
}
}
$message = null;
if ($err) {
// Try to raise a more tailored error message in the more common case
// of the user creating an empty directory. (We could try to remove it,
// but might not be able to, and it's much simpler to raise a good
// message than try to navigate those waters.)
if (is_dir($path)) {
$files = Filesystem::listDirectory($path, $include_hidden = true);
if (!$files) {
$message = pht(
'Expected to find a Git repository at "%s", but there is an '.
'empty directory there. Remove the directory. A daemon will '.
'construct the working copy for you.',
$path);
} else {
$message = pht(
'Expected to find a Git repository at "%s", but there is '.
'a non-repository directory (with other stuff in it) there. '.
'Move or remove this directory. A daemon will construct '.
'the working copy for you.',
$path);
}
} else if (is_file($path)) {
$message = pht(
'Expected to find a Git repository at "%s", but there is a '.
'file there instead. Move or remove this file. A daemon will '.
'construct the working copy for you.',
$path);
} else {
$message = pht(
'Expected to find a git repository at "%s", but did not.',
$path);
}
} else {
// Prior to Git 2.25.0, we used "--show-toplevel", which had a weird
// case here when the working copy was inside another working copy.
// The switch to "--git-dir" seems to have resolved this; we now seem
// to find the nearest git directory and thus the correct repository
// root.
if (!Filesystem::pathsAreEquivalent($repository_root, $path)) {
$err = true;
$message = pht(
'Expected to find a Git repository at "%s", but the actual Git '.
'repository root for this directory is "%s". Something is '.
'misconfigured. This directory should be writable by the daemons '.
'and not inside another Git repository.',
$path,
$repository_root);
}
}
if ($err && $repository->canDestroyWorkingCopy()) {
phlog(
pht(
"Repository working copy at '%s' failed sanity check; ".
"destroying and re-cloning. %s",
$path,
$message));
Filesystem::remove($path);
$this->executeGitCreate();
} else if ($err) {
throw new Exception($message);
}
// Load the refs we're planning to fetch from the remote repository.
$remote_refs = $this->loadGitRemoteRefs(
$repository,
$repository->getRemoteURIEnvelope(),
$is_local = false);
// Load the refs we're planning to fetch from the local repository, by
// using the local working copy path as the "remote" repository URI.
$local_refs = $this->loadGitRemoteRefs(
$repository,
new PhutilOpaqueEnvelope($path),
$is_local = true);
// See T13448. The "git fetch --prune ..." flag only prunes local refs
// matching the refspecs we pass it. If "Fetch Refs" is configured, we'll
// pass it a very narrow list of refspecs, and it won't prune older refs
// that aren't currently subject to fetching.
// Since we want to prune everything that isn't (a) on the fetch list and
// (b) in the remote, handle pruning of any surplus leftover refs ourselves
// before we fetch anything.
// (We don't have to do this if "Fetch Refs" isn't set up, since "--prune"
// will work in that case, but it's a little simpler to always go down the
// same code path.)
$surplus_refs = array();
foreach ($local_refs as $local_ref => $local_hash) {
$remote_hash = idx($remote_refs, $local_ref);
if ($remote_hash === null) {
$surplus_refs[] = $local_ref;
}
}
if ($surplus_refs) {
$this->log(
pht(
'Found %s surplus local ref(s) to delete.',
phutil_count($surplus_refs)));
foreach ($surplus_refs as $surplus_ref) {
$this->log(
pht(
'Deleting surplus local ref "%s" ("%s").',
$surplus_ref,
$local_refs[$surplus_ref]));
$repository->execLocalCommand(
'update-ref -d %R --',
$surplus_ref);
unset($local_refs[$surplus_ref]);
}
}
if ($remote_refs === $local_refs) {
$this->log(
pht(
'Skipping fetch because local and remote refs are already '.
'identical.'));
return false;
}
$this->logRefDifferences($remote_refs, $local_refs);
$fetch_rules = $this->getGitFetchRules($repository);
// For very old non-bare working copies, we need to use "--update-head-ok"
// to tell Git that it is allowed to overwrite whatever is currently
// checked out. See T13280.
$future = $repository->getRemoteCommandFuture(
'fetch --no-tags --update-head-ok -- %P %Ls',
$repository->getRemoteURIEnvelope(),
$fetch_rules);
$future
->setCWD($path)
->resolvex();
}
private function getGitRefRules(PhabricatorRepository $repository) {
$ref_rules = $repository->getFetchRules($repository);
if (!$ref_rules) {
$ref_rules = array(
'refs/*',
);
}
return $ref_rules;
}
private function getGitFetchRules(PhabricatorRepository $repository) {
$ref_rules = $this->getGitRefRules($repository);
// Rewrite each ref rule "X" into "+X:X".
// The "X" means "fetch ref X".
// The "...:X" means "...and copy it into local ref X".
// The "+..." means "...and overwrite the local ref if it already exists".
$fetch_rules = array();
foreach ($ref_rules as $key => $ref_rule) {
$fetch_rules[] = sprintf(
'+%s:%s',
$ref_rule,
$ref_rule);
}
return $fetch_rules;
}
/**
* @task git
*/
private function installGitHook() {
$repository = $this->getRepository();
$root = $repository->getLocalPath();
if ($repository->isWorkingCopyBare()) {
$path = '/hooks/pre-receive';
} else {
$path = '/.git/hooks/pre-receive';
}
$this->installHook($root.$path);
}
private function updateGitWorkingCopyConfiguration() {
$repository = $this->getRepository();
// See T5963. When you "git clone" from a remote with no "master", the
// client warns you that it isn't sure what it should check out as an
// initial state:
// warning: remote HEAD refers to nonexistent ref, unable to checkout
// We can tell the client what it should check out by making "HEAD"
// point somewhere. However:
//
// (1) If we don't set "receive.denyDeleteCurrent" to "ignore" and a user
// tries to delete the default branch, Git raises an error and refuses.
// We want to allow this; we already have sufficient protections around
// dangerous changes and do not need to special case the default branch.
//
// (2) A repository may have a nonexistent default branch configured.
// For now, we just respect configuration. This will raise a warning when
// users clone the repository.
//
// In any case, these changes are both advisory, so ignore any errors we
// may encounter.
// We do this for both hosted and observed repositories. Although it is
// not terribly common to clone from Phabricator's copy of an observed
// repository, it works fine and makes sense occasionally.
if ($repository->isWorkingCopyBare()) {
$repository->execLocalCommand(
'config -- receive.denyDeleteCurrent ignore');
$repository->execLocalCommand(
'symbolic-ref HEAD %s',
'refs/heads/'.$repository->getDefaultBranch());
}
}
private function loadGitRemoteRefs(
PhabricatorRepository $repository,
PhutilOpaqueEnvelope $remote_envelope,
$is_local) {
// See T13448. When listing local remotes, we want to list everything,
// not just refs we expect to fetch. This allows us to detect that we have
// undesirable refs (which have been deleted in the remote, but are still
// present locally) so we can update our state to reflect the correct
// remote state.
if ($is_local) {
$ref_rules = array();
} else {
$ref_rules = $this->getGitRefRules($repository);
// NOTE: "git ls-remote" does not support "--" until circa January 2016.
// See T12416. None of the flags to "ls-remote" appear dangerous, but
// refuse to list any refs beginning with "-" just in case.
foreach ($ref_rules as $ref_rule) {
if (preg_match('/^-/', $ref_rule)) {
throw new Exception(
pht(
'Refusing to list potentially dangerous ref ("%s") beginning '.
'with "-".',
$ref_rule));
}
}
}
list($stdout) = $repository->execxRemoteCommand(
'ls-remote %P %Ls',
$remote_envelope,
$ref_rules);
// Empty repositories don't have any refs.
if ($stdout === null || !strlen(rtrim($stdout))) {
return array();
}
$map = array();
$lines = phutil_split_lines($stdout, false);
foreach ($lines as $line) {
list($hash, $name) = preg_split('/\s+/', $line, 2);
// If the remote has a HEAD, just ignore it.
if ($name == 'HEAD') {
continue;
}
// If the remote ref is itself a remote ref, ignore it.
if (preg_match('(^refs/remotes/)', $name)) {
continue;
}
$map[$name] = $hash;
}
ksort($map);
return $map;
}
private function loadGitLocalRefs(PhabricatorRepository $repository) {
$refs = id(new DiffusionLowLevelGitRefQuery())
->setRepository($repository)
->execute();
$map = array();
foreach ($refs as $ref) {
$fields = $ref->getRawFields();
$map[idx($fields, 'refname')] = $ref->getCommitIdentifier();
}
ksort($map);
return $map;
}
private function logRefDifferences(array $remote, array $local) {
$all = $local + $remote;
$differences = array();
foreach ($all as $key => $ignored) {
$remote_ref = idx($remote, $key, pht('<null>'));
$local_ref = idx($local, $key, pht('<null>'));
if ($remote_ref !== $local_ref) {
$differences[] = pht(
'%s (remote: "%s", local: "%s")',
$key,
$remote_ref,
$local_ref);
}
}
$this->log(
pht(
"Updating repository after detecting ref differences:\n%s",
implode("\n", $differences)));
}
/* -( Pulling Mercurial Working Copies )----------------------------------- */
/**
* @task hg
*/
private function executeMercurialCreate() {
$repository = $this->getRepository();
$path = rtrim($repository->getLocalPath(), '/');
if ($repository->isHosted()) {
$repository->execxRemoteCommand(
'init -- %s',
$path);
} else {
$remote = $repository->getRemoteURIEnvelope();
// NOTE: Mercurial prior to 3.2.4 has an severe command injection
// vulnerability. See: <http://bit.ly/19B58E9>
// On vulnerable versions of Mercurial, we refuse to clone remotes which
// contain characters which may be interpreted by the shell.
$hg_binary = PhutilBinaryAnalyzer::getForBinary('hg');
$is_vulnerable = $hg_binary->isMercurialVulnerableToInjection();
if ($is_vulnerable) {
$cleartext = $remote->openEnvelope();
// The use of "%R" here is an attempt to limit collateral damage
// for normal URIs because it isn't clear how long this vulnerability
// has been around for.
$escaped = csprintf('%R', $cleartext);
if ((string)$escaped !== (string)$cleartext) {
throw new Exception(
pht(
'You have an old version of Mercurial (%s) which has a severe '.
'command injection security vulnerability. The remote URI for '.
'this repository (%s) is potentially unsafe. Upgrade Mercurial '.
'to at least 3.2.4 to clone it.',
$hg_binary->getBinaryVersion(),
$repository->getMonogram()));
}
}
try {
$repository->execxRemoteCommand(
'clone --noupdate -- %P %s',
$remote,
$path);
} catch (Exception $ex) {
$message = $ex->getMessage();
$message = $this->censorMercurialErrorMessage($message);
throw new Exception($message);
}
}
}
/**
* @task hg
*/
private function executeMercurialUpdate() {
$repository = $this->getRepository();
$path = $repository->getLocalPath();
// This is a local command, but needs credentials.
$remote = $repository->getRemoteURIEnvelope();
$future = $repository->getRemoteCommandFuture('pull -- %P', $remote);
$future->setCWD($path);
try {
$future->resolvex();
} catch (CommandException $ex) {
$err = $ex->getError();
$stdout = $ex->getStdout();
// NOTE: Between versions 2.1 and 2.1.1, Mercurial changed the behavior
// of "hg pull" to return 1 in case of a successful pull with no changes.
// This behavior has been reverted, but users who updated between Feb 1,
// 2012 and Mar 1, 2012 will have the erroring version. Do a dumb test
// against stdout to check for this possibility.
// NOTE: Mercurial has translated versions, which translate this error
// string. In a translated version, the string will be something else,
// like "aucun changement trouve". There didn't seem to be an easy way
// to handle this (there are hard ways but this is not a common problem
// and only creates log spam, not application failures). Assume English.
// TODO: Remove this once we're far enough in the future that deployment
// of 2.1 is exceedingly rare?
if ($err == 1 && preg_match('/no changes found/', $stdout)) {
return;
} else {
$message = $ex->getMessage();
$message = $this->censorMercurialErrorMessage($message);
throw new Exception($message);
}
}
}
/**
* Censor response bodies from Mercurial error messages.
*
* When Mercurial attempts to clone an HTTP repository but does not
* receive a response it expects, it emits the response body in the
* command output.
*
* This represents a potential SSRF issue, because an attacker with
* permission to create repositories can create one which points at the
* remote URI for some local service, then read the response from the
* error message. To prevent this, censor response bodies out of error
* messages.
*
* @param string Uncensored Mercurial command output.
* @return string Censored Mercurial command output.
*/
private function censorMercurialErrorMessage($message) {
return preg_replace(
'/^---%<---.*/sm',
pht('<Response body omitted from Mercurial error message.>')."\n",
$message);
}
/**
* @task hg
*/
private function installMercurialHook() {
$repository = $this->getRepository();
$path = $repository->getLocalPath().'/.hg/hgrc';
$identifier = $this->getHookContextIdentifier($repository);
$root = dirname(phutil_get_library_root('phabricator'));
$bin = $root.'/bin/commit-hook';
$data = array();
$data[] = '[hooks]';
// This hook handles normal pushes.
$data[] = csprintf(
'pretxnchangegroup.phabricator = TERM=dumb %s %s %s',
$bin,
$identifier,
'pretxnchangegroup');
// This one handles creating bookmarks.
$data[] = csprintf(
'prepushkey.phabricator = TERM=dumb %s %s %s',
$bin,
$identifier,
'prepushkey');
$data[] = null;
$data = implode("\n", $data);
$this->log('%s', pht('Installing commit hook config to "%s"...', $path));
Filesystem::writeFile($path, $data);
}
/* -( Pulling Subversion Working Copies )---------------------------------- */
/**
* @task svn
*/
private function executeSubversionCreate() {
$repository = $this->getRepository();
$path = rtrim($repository->getLocalPath(), '/');
execx('svnadmin create -- %s', $path);
}
/**
* @task svn
*/
private function installSubversionHook() {
$repository = $this->getRepository();
$root = $repository->getLocalPath();
$path = '/hooks/pre-commit';
$this->installHook($root.$path);
$revprop_path = '/hooks/pre-revprop-change';
$revprop_argv = array(
'--hook-mode',
'svn-revprop',
);
$this->installHook($root.$revprop_path, $revprop_argv);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/engine/PhabricatorRepositoryCommitRef.php | src/applications/repository/engine/PhabricatorRepositoryCommitRef.php | <?php
final class PhabricatorRepositoryCommitRef extends Phobject {
private $identifier;
private $epoch;
private $branch;
private $isPermanent;
private $parents = array();
public function setIdentifier($identifier) {
$this->identifier = $identifier;
return $this;
}
public function getIdentifier() {
return $this->identifier;
}
public function setEpoch($epoch) {
$this->epoch = $epoch;
return $this;
}
public function getEpoch() {
return $this->epoch;
}
public function setBranch($branch) {
$this->branch = $branch;
return $this;
}
public function getBranch() {
return $this->branch;
}
public function setIsPermanent($is_permanent) {
$this->isPermanent = $is_permanent;
return $this;
}
public function getIsPermanent() {
return $this->isPermanent;
}
public function setParents(array $parents) {
$this->parents = $parents;
return $this;
}
public function getParents() {
return $this->parents;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/engine/PhabricatorRepositoryEngine.php | src/applications/repository/engine/PhabricatorRepositoryEngine.php | <?php
/**
* @task config Configuring Repository Engines
* @task internal Internals
*/
abstract class PhabricatorRepositoryEngine extends Phobject {
private $repository;
private $verbose;
/**
* @task config
*/
public function setRepository(PhabricatorRepository $repository) {
$this->repository = $repository;
return $this;
}
/**
* @task config
*/
protected function getRepository() {
if ($this->repository === null) {
throw new PhutilInvalidStateException('setRepository');
}
return $this->repository;
}
/**
* @task config
*/
public function setVerbose($verbose) {
$this->verbose = $verbose;
return $this;
}
/**
* @task config
*/
public function getVerbose() {
return $this->verbose;
}
public function getViewer() {
return PhabricatorUser::getOmnipotentUser();
}
protected function newRepositoryLock(
PhabricatorRepository $repository,
$lock_key,
$lock_device_only) {
$lock_parts = array(
'repositoryPHID' => $repository->getPHID(),
);
if ($lock_device_only) {
$device = AlmanacKeys::getLiveDevice();
if ($device) {
$lock_parts['devicePHID'] = $device->getPHID();
}
}
return PhabricatorGlobalLock::newLock($lock_key, $lock_parts);
}
/**
* @task internal
*/
protected function log($pattern /* ... */) {
if ($this->getVerbose()) {
$console = PhutilConsole::getConsole();
$argv = func_get_args();
array_unshift($argv, "%s\n");
call_user_func_array(array($console, 'writeOut'), $argv);
}
return $this;
}
final protected function queueCommitImportTask(
PhabricatorRepository $repository,
$commit_phid,
$task_priority,
$via) {
$vcs = $repository->getVersionControlSystem();
switch ($vcs) {
case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
$class = 'PhabricatorRepositoryGitCommitMessageParserWorker';
break;
case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN:
$class = 'PhabricatorRepositorySvnCommitMessageParserWorker';
break;
case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL:
$class = 'PhabricatorRepositoryMercurialCommitMessageParserWorker';
break;
default:
throw new Exception(
pht(
'Unknown repository type "%s"!',
$vcs));
}
$data = array(
'commitPHID' => $commit_phid,
);
if ($via !== null) {
$data['via'] = $via;
}
$options = array(
'priority' => $task_priority,
'objectPHID' => $commit_phid,
'containerPHID' => $repository->getPHID(),
);
PhabricatorWorker::scheduleTask($class, $data, $options);
}
final protected function getImportTaskPriority(
PhabricatorRepository $repository,
array $refs) {
assert_instances_of($refs, 'PhabricatorRepositoryCommitRef');
// If the repository is importing for the first time, we schedule tasks
// at IMPORT priority, which is very low. Making progress on importing a
// new repository for the first time is less important than any other
// daemon task.
// If the repository has finished importing and we're just catching up
// on recent commits, we usually schedule discovery at COMMIT priority,
// which is slightly below the default priority.
// Note that followup tasks and triggered tasks (like those generated by
// Herald or Harbormaster) will queue at DEFAULT priority, so that each
// commit tends to fully import before we start the next one. This tends
// to give imports fairly predictable progress. See T11677 for some
// discussion.
if ($repository->isImporting()) {
$this->log(
pht(
'Importing %s commit(s) at low priority ("PRIORITY_IMPORT") '.
'because this repository is still importing.',
phutil_count($refs)));
return PhabricatorWorker::PRIORITY_IMPORT;
}
// See T13369. If we've discovered a lot of commits at once, import them
// at lower priority.
// This is mostly aimed at reducing the impact that synchronizing thousands
// of commits from a remote upstream has on other repositories. The queue
// is "mostly FIFO", so queueing a thousand commit imports can stall other
// repositories.
// In a perfect world we'd probably give repositories round-robin queue
// priority, but we don't currently have the primitives for this and there
// isn't a strong case for building them.
// Use "a whole lot of commits showed up at once" as a heuristic for
// detecting "someone synchronized an upstream", and import them at a lower
// priority to more closely approximate fair scheduling.
if (count($refs) >= PhabricatorRepository::LOWPRI_THRESHOLD) {
$this->log(
pht(
'Importing %s commit(s) at low priority ("PRIORITY_IMPORT") '.
'because many commits were discovered at once.',
phutil_count($refs)));
return PhabricatorWorker::PRIORITY_IMPORT;
}
// Otherwise, import at normal priority.
if ($refs) {
$this->log(
pht(
'Importing %s commit(s) at normal priority ("PRIORITY_COMMIT").',
phutil_count($refs)));
}
return PhabricatorWorker::PRIORITY_COMMIT;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/engine/PhabricatorRepositoryDiscoveryEngine.php | src/applications/repository/engine/PhabricatorRepositoryDiscoveryEngine.php | <?php
/**
* @task discover Discovering Repositories
* @task svn Discovering Subversion Repositories
* @task git Discovering Git Repositories
* @task hg Discovering Mercurial Repositories
* @task internal Internals
*/
final class PhabricatorRepositoryDiscoveryEngine
extends PhabricatorRepositoryEngine {
private $repairMode;
private $commitCache = array();
private $workingSet = array();
const MAX_COMMIT_CACHE_SIZE = 65535;
/* -( Discovering Repositories )------------------------------------------- */
public function setRepairMode($repair_mode) {
$this->repairMode = $repair_mode;
return $this;
}
public function getRepairMode() {
return $this->repairMode;
}
/**
* @task discovery
*/
public function discoverCommits() {
$repository = $this->getRepository();
$lock = $this->newRepositoryLock($repository, 'repo.look', false);
try {
$lock->lock();
} catch (PhutilLockException $ex) {
throw new DiffusionDaemonLockException(
pht(
'Another process is currently discovering repository "%s", '.
'skipping discovery.',
$repository->getDisplayName()));
}
try {
$result = $this->discoverCommitsWithLock();
} catch (Exception $ex) {
$lock->unlock();
throw $ex;
}
$lock->unlock();
return $result;
}
private function discoverCommitsWithLock() {
$repository = $this->getRepository();
$viewer = $this->getViewer();
$vcs = $repository->getVersionControlSystem();
switch ($vcs) {
case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN:
$refs = $this->discoverSubversionCommits();
break;
case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL:
$refs = $this->discoverMercurialCommits();
break;
case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
$refs = $this->discoverGitCommits();
break;
default:
throw new Exception(pht("Unknown VCS '%s'!", $vcs));
}
if ($this->isInitialImport($refs)) {
$this->log(
pht(
'Discovered more than %s commit(s) in an empty repository, '.
'marking repository as importing.',
new PhutilNumber(PhabricatorRepository::IMPORT_THRESHOLD)));
$repository->markImporting();
}
// Clear the working set cache.
$this->workingSet = array();
$task_priority = $this->getImportTaskPriority($repository, $refs);
// Record discovered commits and mark them in the cache.
foreach ($refs as $ref) {
$this->recordCommit(
$repository,
$ref->getIdentifier(),
$ref->getEpoch(),
$ref->getIsPermanent(),
$ref->getParents(),
$task_priority);
$this->commitCache[$ref->getIdentifier()] = true;
}
$this->markUnreachableCommits($repository);
$version = $this->getObservedVersion($repository);
if ($version !== null) {
id(new DiffusionRepositoryClusterEngine())
->setViewer($viewer)
->setRepository($repository)
->synchronizeWorkingCopyAfterDiscovery($version);
}
return $refs;
}
/* -( Discovering Git Repositories )--------------------------------------- */
/**
* @task git
*/
private function discoverGitCommits() {
$repository = $this->getRepository();
$publisher = $repository->newPublisher();
$heads = id(new DiffusionLowLevelGitRefQuery())
->setRepository($repository)
->execute();
if (!$heads) {
// This repository has no heads at all, so we don't need to do
// anything. Generally, this means the repository is empty.
return array();
}
$this->log(
pht(
'Discovering commits in repository "%s".',
$repository->getDisplayName()));
$ref_lists = array();
$head_groups = $this->getRefGroupsForDiscovery($heads);
foreach ($head_groups as $head_group) {
$group_identifiers = mpull($head_group, 'getCommitIdentifier');
$group_identifiers = array_fuse($group_identifiers);
$this->fillCommitCache($group_identifiers);
foreach ($head_group as $ref) {
$name = $ref->getShortName();
$commit = $ref->getCommitIdentifier();
$this->log(
pht(
'Examining "%s" (%s) at "%s".',
$name,
$ref->getRefType(),
$commit));
if (!$repository->shouldTrackRef($ref)) {
$this->log(pht('Skipping, ref is untracked.'));
continue;
}
if ($this->isKnownCommit($commit)) {
$this->log(pht('Skipping, HEAD is known.'));
continue;
}
// In Git, it's possible to tag anything. We just skip tags that don't
// point to a commit. See T11301.
$fields = $ref->getRawFields();
$ref_type = idx($fields, 'objecttype');
$tag_type = idx($fields, '*objecttype');
if ($ref_type != 'commit' && $tag_type != 'commit') {
$this->log(pht('Skipping, this is not a commit.'));
continue;
}
$this->log(pht('Looking for new commits.'));
$head_refs = $this->discoverStreamAncestry(
new PhabricatorGitGraphStream($repository, $commit),
$commit,
$publisher->isPermanentRef($ref));
$this->didDiscoverRefs($head_refs);
$ref_lists[] = $head_refs;
}
}
$refs = array_mergev($ref_lists);
return $refs;
}
/**
* @task git
*/
private function getRefGroupsForDiscovery(array $heads) {
$heads = $this->sortRefs($heads);
// See T13593. We hold a commit cache with a fixed maximum size. Split the
// refs into chunks no larger than the cache size, so we don't overflow the
// cache when testing them.
$array_iterator = new ArrayIterator($heads);
$chunk_iterator = new PhutilChunkedIterator(
$array_iterator,
self::MAX_COMMIT_CACHE_SIZE);
return $chunk_iterator;
}
/* -( Discovering Subversion Repositories )-------------------------------- */
/**
* @task svn
*/
private function discoverSubversionCommits() {
$repository = $this->getRepository();
if (!$repository->isHosted()) {
$this->verifySubversionRoot($repository);
}
$upper_bound = null;
$limit = 1;
$refs = array();
do {
// Find all the unknown commits on this path. Note that we permit
// importing an SVN subdirectory rather than the entire repository, so
// commits may be nonsequential.
if ($upper_bound === null) {
$at_rev = 'HEAD';
} else {
$at_rev = ($upper_bound - 1);
}
try {
list($xml, $stderr) = $repository->execxRemoteCommand(
'log --xml --quiet --limit %d %s',
$limit,
$repository->getSubversionBaseURI($at_rev));
} catch (CommandException $ex) {
$stderr = $ex->getStderr();
if (preg_match('/(path|File) not found/', $stderr)) {
// We've gone all the way back through history and this path was not
// affected by earlier commits.
break;
}
throw $ex;
}
$xml = phutil_utf8ize($xml);
$log = new SimpleXMLElement($xml);
foreach ($log->logentry as $entry) {
$identifier = (int)$entry['revision'];
$epoch = (int)strtotime((string)$entry->date[0]);
$refs[$identifier] = id(new PhabricatorRepositoryCommitRef())
->setIdentifier($identifier)
->setEpoch($epoch)
->setIsPermanent(true);
if ($upper_bound === null) {
$upper_bound = $identifier;
} else {
$upper_bound = min($upper_bound, $identifier);
}
}
// Discover 2, 4, 8, ... 256 logs at a time. This allows us to initially
// import large repositories fairly quickly, while pulling only as much
// data as we need in the common case (when we've already imported the
// repository and are just grabbing one commit at a time).
$limit = min($limit * 2, 256);
} while ($upper_bound > 1 && !$this->isKnownCommit($upper_bound));
krsort($refs);
while ($refs && $this->isKnownCommit(last($refs)->getIdentifier())) {
array_pop($refs);
}
$refs = array_reverse($refs);
$this->didDiscoverRefs($refs);
return $refs;
}
private function verifySubversionRoot(PhabricatorRepository $repository) {
list($xml) = $repository->execxRemoteCommand(
'info --xml %s',
$repository->getSubversionPathURI());
$xml = phutil_utf8ize($xml);
$xml = new SimpleXMLElement($xml);
$remote_root = (string)($xml->entry[0]->repository[0]->root[0]);
$expect_root = $repository->getSubversionPathURI();
$normal_type_svn = ArcanistRepositoryURINormalizer::TYPE_SVN;
$remote_normal = id(new ArcanistRepositoryURINormalizer(
$normal_type_svn,
$remote_root))->getNormalizedPath();
$expect_normal = id(new ArcanistRepositoryURINormalizer(
$normal_type_svn,
$expect_root))->getNormalizedPath();
if ($remote_normal != $expect_normal) {
throw new Exception(
pht(
'Repository "%s" does not have a correctly configured remote URI. '.
'The remote URI for a Subversion repository MUST point at the '.
'repository root. The root for this repository is "%s", but the '.
'configured URI is "%s". To resolve this error, set the remote URI '.
'to point at the repository root. If you want to import only part '.
'of a Subversion repository, use the "Import Only" option.',
$repository->getDisplayName(),
$remote_root,
$expect_root));
}
}
/* -( Discovering Mercurial Repositories )--------------------------------- */
/**
* @task hg
*/
private function discoverMercurialCommits() {
$repository = $this->getRepository();
$branches = id(new DiffusionLowLevelMercurialBranchesQuery())
->setRepository($repository)
->execute();
$this->fillCommitCache(mpull($branches, 'getCommitIdentifier'));
$refs = array();
foreach ($branches as $branch) {
// NOTE: Mercurial branches may have multiple heads, so the names may
// not be unique.
$name = $branch->getShortName();
$commit = $branch->getCommitIdentifier();
$this->log(pht('Examining branch "%s" head "%s".', $name, $commit));
if (!$repository->shouldTrackBranch($name)) {
$this->log(pht('Skipping, branch is untracked.'));
continue;
}
if ($this->isKnownCommit($commit)) {
$this->log(pht('Skipping, this head is a known commit.'));
continue;
}
$this->log(pht('Looking for new commits.'));
$branch_refs = $this->discoverStreamAncestry(
new PhabricatorMercurialGraphStream($repository, $commit),
$commit,
$is_permanent = true);
$this->didDiscoverRefs($branch_refs);
$refs[] = $branch_refs;
}
return array_mergev($refs);
}
/* -( Internals )---------------------------------------------------------- */
private function discoverStreamAncestry(
PhabricatorRepositoryGraphStream $stream,
$commit,
$is_permanent) {
$discover = array($commit);
$graph = array();
$seen = array();
// Find all the reachable, undiscovered commits. Build a graph of the
// edges.
while ($discover) {
$target = array_pop($discover);
if (empty($graph[$target])) {
$graph[$target] = array();
}
$parents = $stream->getParents($target);
foreach ($parents as $parent) {
if ($this->isKnownCommit($parent)) {
continue;
}
$graph[$target][$parent] = true;
if (empty($seen[$parent])) {
$seen[$parent] = true;
$discover[] = $parent;
}
}
}
// Now, sort them topologically.
$commits = $this->reduceGraph($graph);
$refs = array();
foreach ($commits as $commit) {
$epoch = $stream->getCommitDate($commit);
// If the epoch doesn't fit into a uint32, treat it as though it stores
// the current time. For discussion, see T11537.
if ($epoch > 0xFFFFFFFF) {
$epoch = PhabricatorTime::getNow();
}
// If the epoch is not present at all, treat it as though it stores the
// value "0". For discussion, see T12062. This behavior is consistent
// with the behavior of "git show".
if (!strlen($epoch)) {
$epoch = 0;
}
$refs[] = id(new PhabricatorRepositoryCommitRef())
->setIdentifier($commit)
->setEpoch($epoch)
->setIsPermanent($is_permanent)
->setParents($stream->getParents($commit));
}
return $refs;
}
private function reduceGraph(array $edges) {
foreach ($edges as $commit => $parents) {
$edges[$commit] = array_keys($parents);
}
$graph = new PhutilDirectedScalarGraph();
$graph->addNodes($edges);
$commits = $graph->getNodesInTopologicalOrder();
// NOTE: We want the most ancestral nodes first, so we need to reverse the
// list we get out of AbstractDirectedGraph.
$commits = array_reverse($commits);
return $commits;
}
private function isKnownCommit($identifier) {
if (isset($this->commitCache[$identifier])) {
return true;
}
if (isset($this->workingSet[$identifier])) {
return true;
}
$this->fillCommitCache(array($identifier));
return isset($this->commitCache[$identifier]);
}
private function fillCommitCache(array $identifiers) {
if (!$identifiers) {
return;
}
if ($this->repairMode) {
// In repair mode, rediscover the entire repository, ignoring the
// database state. The engine still maintains a local cache (the
// "Working Set") but we just give up before looking in the database.
return;
}
$max_size = self::MAX_COMMIT_CACHE_SIZE;
// If we're filling more identifiers than would fit in the cache, ignore
// the ones that don't fit. Because the cache is FIFO, overfilling it can
// cause the entire cache to miss. See T12296.
if (count($identifiers) > $max_size) {
$identifiers = array_slice($identifiers, 0, $max_size);
}
// When filling the cache we ignore commits which have been marked as
// unreachable, treating them as though they do not exist. When recording
// commits later we'll revive commits that exist but are unreachable.
$commits = id(new PhabricatorRepositoryCommit())->loadAllWhere(
'repositoryID = %d AND commitIdentifier IN (%Ls)
AND (importStatus & %d) != %d',
$this->getRepository()->getID(),
$identifiers,
PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE,
PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE);
foreach ($commits as $commit) {
$this->commitCache[$commit->getCommitIdentifier()] = true;
}
while (count($this->commitCache) > $max_size) {
array_shift($this->commitCache);
}
}
/**
* Sort refs so we process permanent refs first. This makes the whole import
* process a little cheaper, since we can publish these commits the first
* time through rather than catching them in the refs step.
*
* @task internal
*
* @param list<DiffusionRepositoryRef> List of refs.
* @return list<DiffusionRepositoryRef> Sorted list of refs.
*/
private function sortRefs(array $refs) {
$repository = $this->getRepository();
$publisher = $repository->newPublisher();
$head_refs = array();
$tail_refs = array();
foreach ($refs as $ref) {
if ($publisher->isPermanentRef($ref)) {
$head_refs[] = $ref;
} else {
$tail_refs[] = $ref;
}
}
return array_merge($head_refs, $tail_refs);
}
private function recordCommit(
PhabricatorRepository $repository,
$commit_identifier,
$epoch,
$is_permanent,
array $parents,
$task_priority) {
$commit = new PhabricatorRepositoryCommit();
$conn_w = $repository->establishConnection('w');
// First, try to revive an existing unreachable commit (if one exists) by
// removing the "unreachable" flag. If we succeed, we don't need to do
// anything else: we already discovered this commit some time ago.
queryfx(
$conn_w,
'UPDATE %T SET importStatus = (importStatus & ~%d)
WHERE repositoryID = %d AND commitIdentifier = %s',
$commit->getTableName(),
PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE,
$repository->getID(),
$commit_identifier);
if ($conn_w->getAffectedRows()) {
$commit = $commit->loadOneWhere(
'repositoryID = %d AND commitIdentifier = %s',
$repository->getID(),
$commit_identifier);
// After reviving a commit, schedule new daemons for it.
$this->didDiscoverCommit($repository, $commit, $epoch, $task_priority);
return;
}
$commit->setRepositoryID($repository->getID());
$commit->setCommitIdentifier($commit_identifier);
$commit->setEpoch($epoch);
if ($is_permanent) {
$commit->setImportStatus(PhabricatorRepositoryCommit::IMPORTED_PERMANENT);
}
$data = new PhabricatorRepositoryCommitData();
try {
// If this commit has parents, look up their IDs. The parent commits
// should always exist already.
$parent_ids = array();
if ($parents) {
$parent_rows = queryfx_all(
$conn_w,
'SELECT id, commitIdentifier FROM %T
WHERE commitIdentifier IN (%Ls) AND repositoryID = %d',
$commit->getTableName(),
$parents,
$repository->getID());
$parent_map = ipull($parent_rows, 'id', 'commitIdentifier');
foreach ($parents as $parent) {
if (empty($parent_map[$parent])) {
throw new Exception(
pht('Unable to identify parent "%s"!', $parent));
}
$parent_ids[] = $parent_map[$parent];
}
} else {
// Write an explicit 0 so we can distinguish between "really no
// parents" and "data not available".
if (!$repository->isSVN()) {
$parent_ids = array(0);
}
}
$commit->openTransaction();
$commit->save();
$data->setCommitID($commit->getID());
$data->save();
foreach ($parent_ids as $parent_id) {
queryfx(
$conn_w,
'INSERT IGNORE INTO %T (childCommitID, parentCommitID)
VALUES (%d, %d)',
PhabricatorRepository::TABLE_PARENTS,
$commit->getID(),
$parent_id);
}
$commit->saveTransaction();
$this->didDiscoverCommit($repository, $commit, $epoch, $task_priority);
if ($this->repairMode) {
// Normally, the query should throw a duplicate key exception. If we
// reach this in repair mode, we've actually performed a repair.
$this->log(pht('Repaired commit "%s".', $commit_identifier));
}
PhutilEventEngine::dispatchEvent(
new PhabricatorEvent(
PhabricatorEventType::TYPE_DIFFUSION_DIDDISCOVERCOMMIT,
array(
'repository' => $repository,
'commit' => $commit,
)));
} catch (AphrontDuplicateKeyQueryException $ex) {
$commit->killTransaction();
// Ignore. This can happen because we discover the same new commit
// more than once when looking at history, or because of races or
// data inconsistency or cosmic radiation; in any case, we're still
// in a good state if we ignore the failure.
}
}
private function didDiscoverCommit(
PhabricatorRepository $repository,
PhabricatorRepositoryCommit $commit,
$epoch,
$task_priority) {
$this->queueCommitImportTask(
$repository,
$commit->getPHID(),
$task_priority,
$via = 'discovery');
// Update the repository summary table.
queryfx(
$commit->establishConnection('w'),
'INSERT INTO %T (repositoryID, size, lastCommitID, epoch)
VALUES (%d, 1, %d, %d)
ON DUPLICATE KEY UPDATE
size = size + 1,
lastCommitID =
IF(VALUES(epoch) > epoch, VALUES(lastCommitID), lastCommitID),
epoch = IF(VALUES(epoch) > epoch, VALUES(epoch), epoch)',
PhabricatorRepository::TABLE_SUMMARY,
$repository->getID(),
$commit->getID(),
$epoch);
}
private function didDiscoverRefs(array $refs) {
foreach ($refs as $ref) {
$this->workingSet[$ref->getIdentifier()] = true;
}
}
private function isInitialImport(array $refs) {
$commit_count = count($refs);
if ($commit_count <= PhabricatorRepository::IMPORT_THRESHOLD) {
// If we fetched a small number of commits, assume it's an initial
// commit or a stack of a few initial commits.
return false;
}
$viewer = $this->getViewer();
$repository = $this->getRepository();
$any_commits = id(new DiffusionCommitQuery())
->setViewer($viewer)
->withRepository($repository)
->setLimit(1)
->execute();
if ($any_commits) {
// If the repository already has commits, this isn't an import.
return false;
}
return true;
}
private function getObservedVersion(PhabricatorRepository $repository) {
if ($repository->isHosted()) {
return null;
}
if ($repository->isGit()) {
return $this->getGitObservedVersion($repository);
}
return null;
}
private function getGitObservedVersion(PhabricatorRepository $repository) {
$refs = id(new DiffusionLowLevelGitRefQuery())
->setRepository($repository)
->execute();
if (!$refs) {
return null;
}
// In Git, the observed version is the most recently discovered commit
// at any repository HEAD. It's possible for this to regress temporarily
// if a branch is pushed and then deleted. This is acceptable because it
// doesn't do anything meaningfully bad and will fix itself on the next
// push.
$ref_identifiers = mpull($refs, 'getCommitIdentifier');
$ref_identifiers = array_fuse($ref_identifiers);
$version = queryfx_one(
$repository->establishConnection('w'),
'SELECT MAX(id) version FROM %T WHERE repositoryID = %d
AND commitIdentifier IN (%Ls)',
id(new PhabricatorRepositoryCommit())->getTableName(),
$repository->getID(),
$ref_identifiers);
if (!$version) {
return null;
}
return (int)$version['version'];
}
private function markUnreachableCommits(PhabricatorRepository $repository) {
if (!$repository->isGit() && !$repository->isHg()) {
return;
}
// Find older versions of refs which we haven't processed yet. We're going
// to make sure their commits are still reachable.
$old_refs = id(new PhabricatorRepositoryOldRef())->loadAllWhere(
'repositoryPHID = %s',
$repository->getPHID());
// If we don't have any refs to update, bail out before building a graph
// stream. In particular, this improves behavior in empty repositories,
// where `git log` exits with an error.
if (!$old_refs) {
return;
}
// We can share a single graph stream across all the checks we need to do.
if ($repository->isGit()) {
$stream = new PhabricatorGitGraphStream($repository);
} else if ($repository->isHg()) {
$stream = new PhabricatorMercurialGraphStream($repository);
}
foreach ($old_refs as $old_ref) {
$identifier = $old_ref->getCommitIdentifier();
$this->markUnreachableFrom($repository, $stream, $identifier);
// If nothing threw an exception, we're all done with this ref.
$old_ref->delete();
}
}
private function markUnreachableFrom(
PhabricatorRepository $repository,
PhabricatorRepositoryGraphStream $stream,
$identifier) {
$unreachable = array();
$commit = id(new PhabricatorRepositoryCommit())->loadOneWhere(
'repositoryID = %s AND commitIdentifier = %s',
$repository->getID(),
$identifier);
if (!$commit) {
return;
}
$look = array($commit);
$seen = array();
while ($look) {
$target = array_pop($look);
// If we've already checked this commit (for example, because history
// branches and then merges) we don't need to check it again.
$target_identifier = $target->getCommitIdentifier();
if (isset($seen[$target_identifier])) {
continue;
}
$seen[$target_identifier] = true;
// See PHI1688. If this commit is already marked as unreachable, we don't
// need to consider its ancestors. This may skip a lot of work if many
// branches with a lot of shared ancestry are deleted at the same time.
if ($target->isUnreachable()) {
continue;
}
try {
$stream->getCommitDate($target_identifier);
$reachable = true;
} catch (Exception $ex) {
$reachable = false;
}
if ($reachable) {
// This commit is reachable, so we don't need to go any further
// down this road.
continue;
}
$unreachable[] = $target;
// Find the commit's parents and check them for reachability, too. We
// have to look in the database since we no may longer have the commit
// in the repository.
$rows = queryfx_all(
$commit->establishConnection('w'),
'SELECT commit.* FROM %T commit
JOIN %T parents ON commit.id = parents.parentCommitID
WHERE parents.childCommitID = %d',
$commit->getTableName(),
PhabricatorRepository::TABLE_PARENTS,
$target->getID());
if (!$rows) {
continue;
}
$parents = id(new PhabricatorRepositoryCommit())
->loadAllFromArray($rows);
foreach ($parents as $parent) {
$look[] = $parent;
}
}
$unreachable = array_reverse($unreachable);
$flag = PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE;
foreach ($unreachable as $unreachable_commit) {
$unreachable_commit->writeImportStatusFlag($flag);
}
// If anything was unreachable, just rebuild the whole summary table.
// We can't really update it incrementally when a commit becomes
// unreachable.
if ($unreachable) {
$this->rebuildSummaryTable($repository);
}
}
private function rebuildSummaryTable(PhabricatorRepository $repository) {
$conn_w = $repository->establishConnection('w');
$data = queryfx_one(
$conn_w,
'SELECT COUNT(*) N, MAX(id) id, MAX(epoch) epoch
FROM %T WHERE repositoryID = %d AND (importStatus & %d) != %d',
id(new PhabricatorRepositoryCommit())->getTableName(),
$repository->getID(),
PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE,
PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE);
queryfx(
$conn_w,
'INSERT INTO %T (repositoryID, size, lastCommitID, epoch)
VALUES (%d, %d, %d, %d)
ON DUPLICATE KEY UPDATE
size = VALUES(size),
lastCommitID = VALUES(lastCommitID),
epoch = VALUES(epoch)',
PhabricatorRepository::TABLE_SUMMARY,
$repository->getID(),
$data['N'],
$data['id'],
$data['epoch']);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.