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/multimeter/data/MultimeterControl.php
src/applications/multimeter/data/MultimeterControl.php
<?php final class MultimeterControl extends Phobject { private static $instance; private $events = array(); private $sampleRate; private $pauseDepth; private $eventViewer; private $eventContext; private function __construct() { // Private. } public static function newInstance() { $instance = new MultimeterControl(); // NOTE: We don't set the sample rate yet. This allows the multimeter to // be initialized and begin recording events, then make a decision about // whether the page will be sampled or not later on (once we've loaded // enough configuration). self::$instance = $instance; return self::getInstance(); } public static function getInstance() { return self::$instance; } public function isActive() { return ($this->sampleRate !== 0) && ($this->pauseDepth == 0); } public function setSampleRate($rate) { if ($rate && (mt_rand(1, $rate) == $rate)) { $sample_rate = $rate; } else { $sample_rate = 0; } $this->sampleRate = $sample_rate; return; } public function pauseMultimeter() { $this->pauseDepth++; return $this; } public function unpauseMultimeter() { if (!$this->pauseDepth) { throw new Exception(pht('Trying to unpause an active multimeter!')); } $this->pauseDepth--; return $this; } public function newEvent($type, $label, $cost) { if (!$this->isActive()) { return null; } $event = id(new MultimeterEvent()) ->setEventType($type) ->setEventLabel($label) ->setResourceCost($cost) ->setEpoch(PhabricatorTime::getNow()); $this->events[] = $event; return $event; } public function saveEvents() { if (!$this->isActive()) { return; } $events = $this->events; if (!$events) { return; } if ($this->sampleRate === null) { throw new PhutilInvalidStateException('setSampleRate'); } $this->addServiceEvents(); // Don't sample any of this stuff. $this->pauseMultimeter(); $use_scope = AphrontWriteGuard::isGuardActive(); if ($use_scope) { $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); } else { AphrontWriteGuard::allowDangerousUnguardedWrites(true); } $caught = null; try { $this->writeEvents(); } catch (Exception $ex) { $caught = $ex; } if ($use_scope) { unset($unguarded); } else { AphrontWriteGuard::allowDangerousUnguardedWrites(false); } $this->unpauseMultimeter(); if ($caught) { throw $caught; } } private function writeEvents() { if (PhabricatorEnv::isReadOnly()) { return; } $events = $this->events; $random = Filesystem::readRandomBytes(32); $request_key = PhabricatorHash::digestForIndex($random); $host_id = $this->loadHostID(php_uname('n')); $context_id = $this->loadEventContextID($this->eventContext); $viewer_id = $this->loadEventViewerID($this->eventViewer); $label_map = $this->loadEventLabelIDs(mpull($events, 'getEventLabel')); foreach ($events as $event) { $event ->setRequestKey($request_key) ->setSampleRate($this->sampleRate) ->setEventHostID($host_id) ->setEventContextID($context_id) ->setEventViewerID($viewer_id) ->setEventLabelID($label_map[$event->getEventLabel()]) ->save(); } } public function setEventContext($event_context) { $this->eventContext = $event_context; return $this; } public function getEventContext() { return $this->eventContext; } public function setEventViewer($viewer) { $this->eventViewer = $viewer; return $this; } private function loadHostID($host) { $map = $this->loadDimensionMap(new MultimeterHost(), array($host)); return idx($map, $host); } private function loadEventViewerID($viewer) { $map = $this->loadDimensionMap(new MultimeterViewer(), array($viewer)); return idx($map, $viewer); } private function loadEventContextID($context) { $map = $this->loadDimensionMap(new MultimeterContext(), array($context)); return idx($map, $context); } private function loadEventLabelIDs(array $labels) { return $this->loadDimensionMap(new MultimeterLabel(), $labels); } private function loadDimensionMap(MultimeterDimension $table, array $names) { $hashes = array(); foreach ($names as $name) { $hashes[] = PhabricatorHash::digestForIndex($name); } $objects = $table->loadAllWhere('nameHash IN (%Ls)', $hashes); $map = mpull($objects, 'getID', 'getName'); $need = array(); foreach ($names as $name) { if (isset($map[$name])) { continue; } $need[$name] = $name; } foreach ($need as $name) { $object = id(clone $table) ->setName($name) ->save(); $map[$name] = $object->getID(); } return $map; } private function addServiceEvents() { $events = PhutilServiceProfiler::getInstance()->getServiceCallLog(); foreach ($events as $event) { $type = idx($event, 'type'); switch ($type) { case 'exec': $this->newEvent( MultimeterEvent::TYPE_EXEC_TIME, $label = $this->getLabelForCommandEvent($event['command']), (1000000 * $event['duration'])); break; } } } private function getLabelForCommandEvent($command) { $argv = preg_split('/\s+/', $command); $bin = array_shift($argv); $bin = basename($bin); $bin = trim($bin, '"\''); // It's important to avoid leaking details about command parameters, // because some may be sensitive. Given this, it's not trivial to // determine which parts of a command are arguments and which parts are // flags. // Rather than try too hard for now, just whitelist some workflows that we // know about and record everything else generically. Overall, this will // produce labels like "pygmentize" or "git log", discarding all flags and // arguments. $workflows = array( 'git' => array( 'log' => true, 'for-each-ref' => true, 'pull' => true, 'clone' => true, 'fetch' => true, 'cat-file' => true, 'init' => true, 'config' => true, 'remote' => true, 'rev-parse' => true, 'diff' => true, 'ls-tree' => true, ), 'svn' => array( 'log' => true, 'diff' => true, ), 'hg' => array( 'log' => true, 'locate' => true, 'pull' => true, 'clone' => true, 'init' => true, 'diff' => true, 'cat' => true, 'files' => true, ), 'svnadmin' => array( 'create' => true, ), ); $workflow = null; $candidates = idx($workflows, $bin); if ($candidates) { foreach ($argv as $arg) { if (isset($candidates[$arg])) { $workflow = $arg; break; } } } if ($workflow) { return 'bin.'.$bin.' '.$workflow; } else { return 'bin.'.$bin; } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/controller/PhabricatorOwnersArchiveController.php
src/applications/owners/controller/PhabricatorOwnersArchiveController.php
<?php final class PhabricatorOwnersArchiveController extends PhabricatorOwnersController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); $package = id(new PhabricatorOwnersPackageQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$package) { return new Aphront404Response(); } $view_uri = $this->getApplicationURI('package/'.$package->getID().'/'); if ($request->isFormPost()) { if ($package->isArchived()) { $new_status = PhabricatorOwnersPackage::STATUS_ACTIVE; } else { $new_status = PhabricatorOwnersPackage::STATUS_ARCHIVED; } $xactions = array(); $type = PhabricatorOwnersPackageStatusTransaction::TRANSACTIONTYPE; $xactions[] = id(new PhabricatorOwnersPackageTransaction()) ->setTransactionType($type) ->setNewValue($new_status); id(new PhabricatorOwnersPackageTransactionEditor()) ->setActor($viewer) ->setContentSourceFromRequest($request) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->applyTransactions($package, $xactions); return id(new AphrontRedirectResponse())->setURI($view_uri); } if ($package->isArchived()) { $title = pht('Activate Package'); $body = pht('This package will become active again.'); $button = pht('Activate Package'); } else { $title = pht('Archive Package'); $body = pht('This package will be marked as archived.'); $button = pht('Archive Package'); } return $this->newDialog() ->setTitle($title) ->appendChild($body) ->addCancelButton($view_uri) ->addSubmitButton($button); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/controller/PhabricatorOwnersController.php
src/applications/owners/controller/PhabricatorOwnersController.php
<?php abstract class PhabricatorOwnersController extends PhabricatorController {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/controller/PhabricatorOwnersPathsController.php
src/applications/owners/controller/PhabricatorOwnersPathsController.php
<?php final class PhabricatorOwnersPathsController extends PhabricatorOwnersController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getUser(); $package = id(new PhabricatorOwnersPackageQuery()) ->setViewer($viewer) ->withIDs(array($request->getURIData('id'))) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->needPaths(true) ->executeOne(); if (!$package) { return new Aphront404Response(); } if ($request->isFormPost()) { $paths = $request->getArr('path'); $repos = $request->getArr('repo'); $excludes = $request->getArr('exclude'); $path_refs = array(); foreach ($paths as $key => $path) { if (!isset($repos[$key]) || !strlen($repos[$key])) { throw new Exception( pht( 'No repository PHID for path "%s"!', $key)); } if (!isset($excludes[$key])) { throw new Exception( pht( 'No exclusion value for path "%s"!', $key)); } $path_refs[] = array( 'repositoryPHID' => $repos[$key], 'path' => $path, 'excluded' => (int)$excludes[$key], ); } $type_paths = PhabricatorOwnersPackagePathsTransaction::TRANSACTIONTYPE; $xactions = array(); $xactions[] = id(new PhabricatorOwnersPackageTransaction()) ->setTransactionType($type_paths) ->setNewValue($path_refs); $editor = id(new PhabricatorOwnersPackageTransactionEditor()) ->setActor($viewer) ->setContentSourceFromRequest($request) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true); $editor->applyTransactions($package, $xactions); return id(new AphrontRedirectResponse()) ->setURI($package->getURI()); } else { $paths = $package->getPaths(); $path_refs = mpull($paths, 'getRef'); } $template = new AphrontTokenizerTemplateView(); $datasource = id(new DiffusionRepositoryDatasource()) ->setViewer($viewer); $tokenizer_spec = array( 'markup' => $template->render(), 'config' => array( 'src' => $datasource->getDatasourceURI(), 'browseURI' => $datasource->getBrowseURI(), 'placeholder' => $datasource->getPlaceholderText(), 'limit' => 1, ), ); foreach ($path_refs as $key => $path_ref) { $path_refs[$key]['repositoryValue'] = $datasource->getWireTokens( array( $path_ref['repositoryPHID'], )); } $icon_test = id(new PHUIIconView()) ->setIcon('fa-spinner grey') ->setTooltip(pht('Validating...')); $icon_okay = id(new PHUIIconView()) ->setIcon('fa-check-circle green') ->setTooltip(pht('Path Exists in Repository')); $icon_fail = id(new PHUIIconView()) ->setIcon('fa-question-circle-o red') ->setTooltip(pht('Path Not Found On Default Branch')); $template = new AphrontTypeaheadTemplateView(); $template = $template->render(); Javelin::initBehavior( 'owners-path-editor', array( 'root' => 'path-editor', 'table' => 'paths', 'add_button' => 'addpath', 'input_template' => $template, 'pathRefs' => $path_refs, 'completeURI' => '/diffusion/services/path/complete/', 'validateURI' => '/diffusion/services/path/validate/', 'repositoryTokenizerSpec' => $tokenizer_spec, 'icons' => array( 'test' => hsprintf('%s', $icon_test), 'okay' => hsprintf('%s', $icon_okay), 'fail' => hsprintf('%s', $icon_fail), ), 'modeOptions' => array( 0 => pht('Include'), 1 => pht('Exclude'), ), )); require_celerity_resource('owners-path-editor-css'); $cancel_uri = $package->getURI(); $form = id(new AphrontFormView()) ->setUser($viewer) ->appendChild( id(new PHUIFormInsetView()) ->setTitle(pht('Paths')) ->addDivAttributes(array('id' => 'path-editor')) ->setRightButton(javelin_tag( 'a', array( 'href' => '#', 'class' => 'button button-green', 'sigil' => 'addpath', 'mustcapture' => true, ), pht('Add New Path'))) ->setDescription( pht( 'Specify the files and directories which comprise '. 'this package.')) ->setContent(javelin_tag( 'table', array( 'class' => 'owners-path-editor-table', 'sigil' => 'paths', ), ''))) ->appendChild( id(new AphrontFormSubmitControl()) ->addCancelButton($cancel_uri) ->setValue(pht('Save Paths'))); $box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Paths')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setForm($form); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb( $package->getName(), $this->getApplicationURI('package/'.$package->getID().'/')); $crumbs->addTextCrumb(pht('Edit Paths')); $crumbs->setBorder(true); $header = id(new PHUIHeaderView()) ->setHeader(pht('Edit Paths: %s', $package->getName())) ->setHeaderIcon('fa-pencil'); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter($box); $title = array($package->getName(), pht('Edit Paths')); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/controller/PhabricatorOwnersListController.php
src/applications/owners/controller/PhabricatorOwnersListController.php
<?php final class PhabricatorOwnersListController extends PhabricatorOwnersController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { return id(new PhabricatorOwnersPackageSearchEngine()) ->setController($this) ->buildResponse(); } protected function buildApplicationCrumbs() { $crumbs = parent::buildApplicationCrumbs(); id(new PhabricatorOwnersPackageEditEngine()) ->setViewer($this->getViewer()) ->addActionToCrumbs($crumbs); return $crumbs; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/controller/PhabricatorOwnersEditController.php
src/applications/owners/controller/PhabricatorOwnersEditController.php
<?php final class PhabricatorOwnersEditController extends PhabricatorOwnersController { public function handleRequest(AphrontRequest $request) { return id(new PhabricatorOwnersPackageEditEngine()) ->setController($this) ->buildResponse(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/controller/PhabricatorOwnersDetailController.php
src/applications/owners/controller/PhabricatorOwnersDetailController.php
<?php final class PhabricatorOwnersDetailController extends PhabricatorOwnersController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $package = id(new PhabricatorOwnersPackageQuery()) ->setViewer($viewer) ->withIDs(array($request->getURIData('id'))) ->needPaths(true) ->executeOne(); if (!$package) { return new Aphront404Response(); } $paths = $package->getPaths(); $repository_phids = array(); foreach ($paths as $path) { $repository_phids[$path->getRepositoryPHID()] = true; } if ($repository_phids) { $repositories = id(new PhabricatorRepositoryQuery()) ->setViewer($viewer) ->withPHIDs(array_keys($repository_phids)) ->execute(); $repositories = mpull($repositories, null, 'getPHID'); } else { $repositories = array(); } $field_list = PhabricatorCustomField::getObjectFields( $package, PhabricatorCustomField::ROLE_VIEW); $field_list ->setViewer($viewer) ->readFieldsFromStorage($package); $curtain = $this->buildCurtain($package); $details = $this->buildPackageDetailView($package, $field_list); if ($package->isArchived()) { $header_icon = 'fa-ban'; $header_name = pht('Archived'); $header_color = 'dark'; } else { $header_icon = 'fa-check'; $header_name = pht('Active'); $header_color = 'bluegrey'; } $header = id(new PHUIHeaderView()) ->setUser($viewer) ->setHeader($package->getName()) ->setStatus($header_icon, $header_color, $header_name) ->setPolicyObject($package) ->setHeaderIcon('fa-gift'); $commit_views = array(); $params = array( 'package' => $package->getPHID(), ); $commit_uri = new PhutilURI('/diffusion/commit/', $params); $status_concern = DiffusionCommitAuditStatus::CONCERN_RAISED; $attention_commits = id(new DiffusionCommitQuery()) ->setViewer($request->getUser()) ->withPackagePHIDs(array($package->getPHID())) ->withStatuses( array( $status_concern, )) ->needCommitData(true) ->needAuditRequests(true) ->needIdentities(true) ->setLimit(10) ->execute(); $view = id(new DiffusionCommitGraphView()) ->setViewer($viewer) ->setCommits($attention_commits) ->newObjectItemListView(); $view->setNoDataString(pht('This package has no open problem commits.')); $commit_views[] = array( 'view' => $view, 'header' => pht('Needs Attention'), 'icon' => 'fa-warning', 'button' => id(new PHUIButtonView()) ->setTag('a') ->setHref($commit_uri->alter('status', $status_concern)) ->setIcon('fa-list-ul') ->setText(pht('View All')), ); $all_commits = id(new DiffusionCommitQuery()) ->setViewer($request->getUser()) ->withPackagePHIDs(array($package->getPHID())) ->needCommitData(true) ->needAuditRequests(true) ->needIdentities(true) ->setLimit(25) ->execute(); $view = id(new DiffusionCommitGraphView()) ->setViewer($viewer) ->setCommits($all_commits) ->newObjectItemListView(); $view->setNoDataString(pht('No commits in this package.')); $commit_views[] = array( 'view' => $view, 'header' => pht('Recent Commits'), 'icon' => 'fa-code', 'button' => id(new PHUIButtonView()) ->setTag('a') ->setHref($commit_uri) ->setIcon('fa-list-ul') ->setText(pht('View All')), ); $commit_panels = array(); foreach ($commit_views as $commit_view) { $commit_panel = id(new PHUIObjectBoxView()) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY); $commit_header = id(new PHUIHeaderView()) ->setHeader($commit_view['header']) ->setHeaderIcon($commit_view['icon']); if (isset($commit_view['button'])) { $commit_header->addActionLink($commit_view['button']); } $commit_panel->setHeader($commit_header); $commit_panel->appendChild($commit_view['view']); $commit_panels[] = $commit_panel; } $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb($package->getMonogram()); $crumbs->setBorder(true); $rules_view = $this->newRulesView($package); $timeline = $this->buildTransactionTimeline( $package, new PhabricatorOwnersPackageTransactionQuery()); $timeline->setShouldTerminate(true); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setCurtain($curtain) ->setMainColumn(array( $this->renderPathsTable($paths, $repositories), $rules_view, $commit_panels, $timeline, )) ->addPropertySection(pht('Details'), $details); return $this->newPage() ->setTitle($package->getName()) ->setCrumbs($crumbs) ->appendChild($view); } private function buildPackageDetailView( PhabricatorOwnersPackage $package, PhabricatorCustomFieldList $field_list) { $viewer = $this->getViewer(); $view = id(new PHUIPropertyListView()) ->setUser($viewer); $owners = $package->getOwners(); if ($owners) { $owner_list = $viewer->renderHandleList(mpull($owners, 'getUserPHID')); } else { $owner_list = phutil_tag('em', array(), pht('None')); } $view->addProperty(pht('Owners'), $owner_list); $dominion = $package->getDominion(); $dominion_map = PhabricatorOwnersPackage::getDominionOptionsMap(); $spec = idx($dominion_map, $dominion, array()); $name = idx($spec, 'short', $dominion); $view->addProperty(pht('Dominion'), $name); $authority_mode = $package->getAuthorityMode(); $authority_map = PhabricatorOwnersPackage::getAuthorityOptionsMap(); $spec = idx($authority_map, $authority_mode, array()); $name = idx($spec, 'short', $authority_mode); $view->addProperty(pht('Authority'), $name); $auto = $package->getAutoReview(); $autoreview_map = PhabricatorOwnersPackage::getAutoreviewOptionsMap(); $spec = idx($autoreview_map, $auto, array()); $name = idx($spec, 'name', $auto); $view->addProperty(pht('Auto Review'), $name); $rule = $package->newAuditingRule(); $view->addProperty(pht('Auditing'), $rule->getDisplayName()); $ignored = $package->getIgnoredPathAttributes(); $ignored = array_keys($ignored); if ($ignored) { $ignored = implode(', ', $ignored); } else { $ignored = phutil_tag('em', array(), pht('None')); } $view->addProperty(pht('Ignored Attributes'), $ignored); $description = $package->getDescription(); if (strlen($description)) { $description = new PHUIRemarkupView($viewer, $description); $view->addSectionHeader(pht('Description')); $view->addTextContent($description); } $field_list->appendFieldsToPropertyList( $package, $viewer, $view); return $view; } private function buildCurtain(PhabricatorOwnersPackage $package) { $viewer = $this->getViewer(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $package, PhabricatorPolicyCapability::CAN_EDIT); $id = $package->getID(); $edit_uri = $this->getApplicationURI("/edit/{$id}/"); $paths_uri = $this->getApplicationURI("/paths/{$id}/"); $curtain = $this->newCurtainView($package); $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Edit Package')) ->setIcon('fa-pencil') ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit) ->setHref($edit_uri)); if ($package->isArchived()) { $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Activate Package')) ->setIcon('fa-check') ->setDisabled(!$can_edit) ->setWorkflow($can_edit) ->setHref($this->getApplicationURI("/archive/{$id}/"))); } else { $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Archive Package')) ->setIcon('fa-ban') ->setDisabled(!$can_edit) ->setWorkflow($can_edit) ->setHref($this->getApplicationURI("/archive/{$id}/"))); } $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Edit Paths')) ->setIcon('fa-folder-open') ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit) ->setHref($paths_uri)); return $curtain; } private function renderPathsTable(array $paths, array $repositories) { $viewer = $this->getViewer(); $rows = array(); foreach ($paths as $path) { $repo = idx($repositories, $path->getRepositoryPHID()); if (!$repo) { continue; } $href = $repo->generateURI( array( 'branch' => $repo->getDefaultBranch(), 'path' => $path->getPathDisplay(), 'action' => 'browse', )); $path_link = phutil_tag( 'a', array( 'href' => (string)$href, ), $path->getPathDisplay()); $rows[] = array( ($path->getExcluded() ? '-' : '+'), $repo->getName(), $path_link, ); } $info = null; if (!$paths) { $info = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->setErrors( array( pht( 'This package does not contain any paths yet. Use '. '"Edit Paths" to add some.'), )); } $table = id(new AphrontTableView($rows)) ->setHeaders( array( null, pht('Repository'), pht('Path'), )) ->setColumnClasses( array( null, null, 'wide', )); if ($info) { $table->setNotice($info); } $header = id(new PHUIHeaderView()) ->setHeader(pht('Paths')) ->setHeaderIcon('fa-folder-open'); $box = id(new PHUIObjectBoxView()) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setTable($table); return $box; } private function newRulesView(PhabricatorOwnersPackage $package) { $viewer = $this->getViewer(); $limit = 10; $rules = id(new HeraldRuleQuery()) ->setViewer($viewer) ->withDisabled(false) ->withAffectedObjectPHIDs(array($package->getPHID())) ->needValidateAuthors(true) ->setLimit($limit + 1) ->execute(); $more_results = (count($rules) > $limit); $rules = array_slice($rules, 0, $limit); $list = id(new HeraldRuleListView()) ->setViewer($viewer) ->setRules($rules) ->newObjectList(); $list->setNoDataString( pht( 'No active Herald rules add this package as an auditor, reviewer, '. 'or subscriber.')); $more_href = new PhutilURI( '/herald/', array('affectedPHID' => $package->getPHID())); if ($more_results) { $list->newTailButton() ->setHref($more_href); } $more_link = id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-list-ul') ->setText(pht('View All Rules')) ->setHref($more_href); $header = id(new PHUIHeaderView()) ->setHeader(pht('Affected By Herald Rules')) ->setHeaderIcon(id(new PhabricatorHeraldApplication())->getIcon()) ->addActionLink($more_link); return id(new PHUIObjectBoxView()) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->appendChild($list); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/engineextension/PhabricatorOwnersHovercardEngineExtension.php
src/applications/owners/engineextension/PhabricatorOwnersHovercardEngineExtension.php
<?php final class PhabricatorOwnersHovercardEngineExtension extends PhabricatorHovercardEngineExtension { const EXTENSIONKEY = 'owners'; public function isExtensionEnabled() { return PhabricatorApplication::isClassInstalled( 'PhabricatorOwnersApplication'); } public function getExtensionName() { return pht('Owner Packages'); } public function canRenderObjectHovercard($object) { return ($object instanceof PhabricatorOwnersPackage); } public function willRenderHovercards(array $objects) { $viewer = $this->getViewer(); $phids = mpull($objects, 'getPHID'); $packages = id(new PhabricatorOwnersPackageQuery()) ->setViewer($viewer) ->withPHIDs($phids) ->execute(); $packages = mpull($packages, null, 'getPHID'); return array( 'packages' => $packages, ); } public function renderHovercard( PHUIHovercardView $hovercard, PhabricatorObjectHandle $handle, $object, $data) { $viewer = $this->getViewer(); $package = idx($data['packages'], $object->getPHID()); if (!$package) { return; } $title = pht('%s: %s', 'O'.$package->getID(), $package->getName()); $hovercard->setTitle($title); $dominion = $package->getDominion(); $dominion_map = PhabricatorOwnersPackage::getDominionOptionsMap(); $spec = idx($dominion_map, $dominion, array()); $name = idx($spec, 'short', $dominion); $hovercard->addField(pht('Dominion'), $name); $auto = $package->getAutoReview(); $autoreview_map = PhabricatorOwnersPackage::getAutoreviewOptionsMap(); $spec = idx($autoreview_map, $auto, array()); $name = idx($spec, 'name', $auto); $hovercard->addField(pht('Auto Review'), $name); if ($package->isArchived()) { $tag = id(new PHUITagView()) ->setName(pht('Archived')) ->setColor(PHUITagView::COLOR_INDIGO) ->setType(PHUITagView::TYPE_OBJECT); $hovercard->addTag($tag); } $owner_phids = $package->getOwnerPHIDs(); $hovercard->addField( pht('Owners'), $viewer->renderHandleList($owner_phids)->setAsInline(true)); $description = $package->getDescription(); if (strlen($description)) { $description = id(new PhutilUTF8StringTruncator()) ->setMaximumGlyphs(120) ->truncateString($description); $hovercard->addField(pht('Description'), $description); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/engineextension/PhabricatorOwnersPathsSearchEngineAttachment.php
src/applications/owners/engineextension/PhabricatorOwnersPathsSearchEngineAttachment.php
<?php final class PhabricatorOwnersPathsSearchEngineAttachment extends PhabricatorSearchEngineAttachment { public function getAttachmentName() { return pht('Included Paths'); } public function getAttachmentDescription() { return pht('Get the paths for each package.'); } public function willLoadAttachmentData($query, $spec) { $query->needPaths(true); } public function getAttachmentForObject($object, $data, $spec) { $paths = $object->getPaths(); $list = array(); foreach ($paths as $path) { $list[] = array( 'repositoryPHID' => $path->getRepositoryPHID(), 'path' => $path->getPathDisplay(), 'excluded' => (bool)$path->getExcluded(), ); } return array( 'paths' => $list, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/storage/PhabricatorOwnersPackage.php
src/applications/owners/storage/PhabricatorOwnersPackage.php
<?php final class PhabricatorOwnersPackage extends PhabricatorOwnersDAO implements PhabricatorPolicyInterface, PhabricatorApplicationTransactionInterface, PhabricatorCustomFieldInterface, PhabricatorDestructibleInterface, PhabricatorConduitResultInterface, PhabricatorFulltextInterface, PhabricatorFerretInterface, PhabricatorNgramsInterface { protected $name; protected $autoReview; protected $description; protected $status; protected $viewPolicy; protected $editPolicy; protected $dominion; protected $properties = array(); protected $auditingState; protected $authorityMode; private $paths = self::ATTACHABLE; private $owners = self::ATTACHABLE; private $customFields = self::ATTACHABLE; private $pathRepositoryMap = array(); const STATUS_ACTIVE = 'active'; const STATUS_ARCHIVED = 'archived'; const AUTOREVIEW_NONE = 'none'; const AUTOREVIEW_SUBSCRIBE = 'subscribe'; const AUTOREVIEW_SUBSCRIBE_ALWAYS = 'subscribe-always'; const AUTOREVIEW_REVIEW = 'review'; const AUTOREVIEW_REVIEW_ALWAYS = 'review-always'; const AUTOREVIEW_BLOCK = 'block'; const AUTOREVIEW_BLOCK_ALWAYS = 'block-always'; const DOMINION_STRONG = 'strong'; const DOMINION_WEAK = 'weak'; const AUTHORITY_STRONG = 'strong'; const AUTHORITY_WEAK = 'weak'; const PROPERTY_IGNORED = 'ignored'; public static function initializeNewPackage(PhabricatorUser $actor) { $app = id(new PhabricatorApplicationQuery()) ->setViewer($actor) ->withClasses(array('PhabricatorOwnersApplication')) ->executeOne(); $view_policy = $app->getPolicy( PhabricatorOwnersDefaultViewCapability::CAPABILITY); $edit_policy = $app->getPolicy( PhabricatorOwnersDefaultEditCapability::CAPABILITY); return id(new PhabricatorOwnersPackage()) ->setAuditingState(PhabricatorOwnersAuditRule::AUDITING_NONE) ->setAutoReview(self::AUTOREVIEW_NONE) ->setDominion(self::DOMINION_STRONG) ->setAuthorityMode(self::AUTHORITY_STRONG) ->setViewPolicy($view_policy) ->setEditPolicy($edit_policy) ->attachPaths(array()) ->setStatus(self::STATUS_ACTIVE) ->attachOwners(array()) ->setDescription(''); } public static function getStatusNameMap() { return array( self::STATUS_ACTIVE => pht('Active'), self::STATUS_ARCHIVED => pht('Archived'), ); } public static function getAutoreviewOptionsMap() { return array( self::AUTOREVIEW_NONE => array( 'name' => pht('No Autoreview'), ), self::AUTOREVIEW_REVIEW => array( 'name' => pht('Review Changes With Non-Owner Author'), 'authority' => true, ), self::AUTOREVIEW_BLOCK => array( 'name' => pht('Review Changes With Non-Owner Author (Blocking)'), 'authority' => true, ), self::AUTOREVIEW_SUBSCRIBE => array( 'name' => pht('Subscribe to Changes With Non-Owner Author'), 'authority' => true, ), self::AUTOREVIEW_REVIEW_ALWAYS => array( 'name' => pht('Review All Changes'), ), self::AUTOREVIEW_BLOCK_ALWAYS => array( 'name' => pht('Review All Changes (Blocking)'), ), self::AUTOREVIEW_SUBSCRIBE_ALWAYS => array( 'name' => pht('Subscribe to All Changes'), ), ); } public static function getDominionOptionsMap() { return array( self::DOMINION_STRONG => array( 'name' => pht('Strong (Control All Paths)'), 'short' => pht('Strong'), ), self::DOMINION_WEAK => array( 'name' => pht('Weak (Control Unowned Paths)'), 'short' => pht('Weak'), ), ); } public static function getAuthorityOptionsMap() { return array( self::AUTHORITY_STRONG => array( 'name' => pht('Strong (Package Owns Paths)'), 'short' => pht('Strong'), ), self::AUTHORITY_WEAK => array( 'name' => pht('Weak (Package Watches Paths)'), 'short' => pht('Weak'), ), ); } protected function getConfiguration() { return array( // This information is better available from the history table. self::CONFIG_TIMESTAMPS => false, self::CONFIG_AUX_PHID => true, self::CONFIG_SERIALIZATION => array( 'properties' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'name' => 'sort', 'description' => 'text', 'auditingState' => 'text32', 'status' => 'text32', 'autoReview' => 'text32', 'dominion' => 'text32', 'authorityMode' => 'text32', ), ) + parent::getConfiguration(); } public function getPHIDType() { return PhabricatorOwnersPackagePHIDType::TYPECONST; } public function isArchived() { return ($this->getStatus() == self::STATUS_ARCHIVED); } public function getMustMatchUngeneratedPaths() { $ignore_attributes = $this->getIgnoredPathAttributes(); return !empty($ignore_attributes['generated']); } public function getPackageProperty($key, $default = null) { return idx($this->properties, $key, $default); } public function setPackageProperty($key, $value) { $this->properties[$key] = $value; return $this; } public function getIgnoredPathAttributes() { return $this->getPackageProperty(self::PROPERTY_IGNORED, array()); } public function setIgnoredPathAttributes(array $attributes) { return $this->setPackageProperty(self::PROPERTY_IGNORED, $attributes); } public function loadOwners() { if (!$this->getID()) { return array(); } return id(new PhabricatorOwnersOwner())->loadAllWhere( 'packageID = %d', $this->getID()); } public function loadPaths() { if (!$this->getID()) { return array(); } return id(new PhabricatorOwnersPath())->loadAllWhere( 'packageID = %d', $this->getID()); } public static function loadAffectedPackages( PhabricatorRepository $repository, array $paths) { if (!$paths) { return array(); } return self::loadPackagesForPaths($repository, $paths); } public static function loadAffectedPackagesForChangesets( PhabricatorRepository $repository, DifferentialDiff $diff, array $changesets) { assert_instances_of($changesets, 'DifferentialChangeset'); $paths_all = array(); $paths_ungenerated = array(); foreach ($changesets as $changeset) { $path = $changeset->getAbsoluteRepositoryPath($repository, $diff); $paths_all[] = $path; if (!$changeset->isGeneratedChangeset()) { $paths_ungenerated[] = $path; } } if (!$paths_all) { return array(); } $packages_all = self::loadAffectedPackages( $repository, $paths_all); // If there are no generated changesets, we can't possibly need to throw // away any packages for matching only generated paths. Just return the // full set of packages. if ($paths_ungenerated === $paths_all) { return $packages_all; } $must_match_ungenerated = array(); foreach ($packages_all as $package) { if ($package->getMustMatchUngeneratedPaths()) { $must_match_ungenerated[] = $package; } } // If no affected packages have the "Ignore Generated Paths" flag set, we // can't possibly need to throw any away. if (!$must_match_ungenerated) { return $packages_all; } if ($paths_ungenerated) { $packages_ungenerated = self::loadAffectedPackages( $repository, $paths_ungenerated); } else { $packages_ungenerated = array(); } // We have some generated paths, and some packages that ignore generated // paths. Take all the packages which: // // - ignore generated paths; and // - didn't match any ungenerated paths // // ...and remove them from the list. $must_match_ungenerated = mpull($must_match_ungenerated, null, 'getID'); $packages_ungenerated = mpull($packages_ungenerated, null, 'getID'); $packages_all = mpull($packages_all, null, 'getID'); foreach ($must_match_ungenerated as $package_id => $package) { if (!isset($packages_ungenerated[$package_id])) { unset($packages_all[$package_id]); } } return $packages_all; } public static function loadOwningPackages($repository, $path) { if (empty($path)) { return array(); } return self::loadPackagesForPaths($repository, array($path), 1); } private static function loadPackagesForPaths( PhabricatorRepository $repository, array $paths, $limit = 0) { $fragments = array(); foreach ($paths as $path) { foreach (self::splitPath($path) as $fragment) { $fragments[$fragment][$path] = true; } } $package = new PhabricatorOwnersPackage(); $path = new PhabricatorOwnersPath(); $conn = $package->establishConnection('r'); $repository_clause = qsprintf( $conn, 'AND p.repositoryPHID = %s', $repository->getPHID()); // NOTE: The list of $paths may be very large if we're coming from // the OwnersWorker and processing, e.g., an SVN commit which created a new // branch. Break it apart so that it will fit within 'max_allowed_packet', // and then merge results in PHP. $rows = array(); foreach (array_chunk(array_keys($fragments), 1024) as $chunk) { $indexes = array(); foreach ($chunk as $fragment) { $indexes[] = PhabricatorHash::digestForIndex($fragment); } $rows[] = queryfx_all( $conn, 'SELECT pkg.id, pkg.dominion, p.excluded, p.path FROM %T pkg JOIN %T p ON p.packageID = pkg.id WHERE p.pathIndex IN (%Ls) AND pkg.status IN (%Ls) %Q', $package->getTableName(), $path->getTableName(), $indexes, array( self::STATUS_ACTIVE, ), $repository_clause); } $rows = array_mergev($rows); $ids = self::findLongestPathsPerPackage($rows, $fragments); if (!$ids) { return array(); } arsort($ids); if ($limit) { $ids = array_slice($ids, 0, $limit, $preserve_keys = true); } $ids = array_keys($ids); $packages = $package->loadAllWhere('id in (%Ld)', $ids); $packages = array_select_keys($packages, $ids); return $packages; } public static function loadPackagesForRepository($repository) { $package = new PhabricatorOwnersPackage(); $ids = ipull( queryfx_all( $package->establishConnection('r'), 'SELECT DISTINCT packageID FROM %T WHERE repositoryPHID = %s', id(new PhabricatorOwnersPath())->getTableName(), $repository->getPHID()), 'packageID'); return $package->loadAllWhere('id in (%Ld)', $ids); } public static function findLongestPathsPerPackage(array $rows, array $paths) { // Build a map from each path to all the package paths which match it. $path_hits = array(); $weak = array(); foreach ($rows as $row) { $id = $row['id']; $path = $row['path']; $length = strlen($path); $excluded = $row['excluded']; if ($row['dominion'] === self::DOMINION_WEAK) { $weak[$id] = true; } $matches = $paths[$path]; foreach ($matches as $match => $ignored) { $path_hits[$match][] = array( 'id' => $id, 'excluded' => $excluded, 'length' => $length, ); } } // For each path, process the matching package paths to figure out which // packages actually own it. $path_packages = array(); foreach ($path_hits as $match => $hits) { $hits = isort($hits, 'length'); $packages = array(); foreach ($hits as $hit) { $package_id = $hit['id']; if ($hit['excluded']) { unset($packages[$package_id]); } else { $packages[$package_id] = $hit; } } $path_packages[$match] = $packages; } // Remove packages with weak dominion rules that should cede control to // a more specific package. if ($weak) { foreach ($path_packages as $match => $packages) { // Group packages by length. $length_map = array(); foreach ($packages as $package_id => $package) { $length_map[$package['length']][$package_id] = $package; } // For each path length, remove all weak packages if there are any // strong packages of the same length. This makes sure that if there // are one or more strong claims on a particular path, only those // claims stand. foreach ($length_map as $package_list) { $any_strong = false; foreach ($package_list as $package_id => $package) { if (!isset($weak[$package_id])) { $any_strong = true; break; } } if ($any_strong) { foreach ($package_list as $package_id => $package) { if (isset($weak[$package_id])) { unset($packages[$package_id]); } } } } $packages = isort($packages, 'length'); $packages = array_reverse($packages, true); $best_length = null; foreach ($packages as $package_id => $package) { // If this is the first package we've encountered, note its length. // We're iterating over the packages from longest to shortest match, // so packages of this length always have the best claim on the path. if ($best_length === null) { $best_length = $package['length']; } // If this package has the same length as the best length, its claim // stands. if ($package['length'] === $best_length) { continue; } // If this is a weak package and does not have the best length, // cede its claim to the stronger package. if (isset($weak[$package_id])) { unset($packages[$package_id]); } } $path_packages[$match] = $packages; } } // For each package that owns at least one path, identify the longest // path it owns. $package_lengths = array(); foreach ($path_packages as $match => $hits) { foreach ($hits as $hit) { $length = $hit['length']; $id = $hit['id']; if (empty($package_lengths[$id])) { $package_lengths[$id] = $length; } else { $package_lengths[$id] = max($package_lengths[$id], $length); } } } return $package_lengths; } public static function splitPath($path) { $result = array( '/', ); $parts = explode('/', $path); $buffer = '/'; foreach ($parts as $part) { if (!strlen($part)) { continue; } $buffer = $buffer.$part.'/'; $result[] = $buffer; } return $result; } public function attachPaths(array $paths) { assert_instances_of($paths, 'PhabricatorOwnersPath'); $this->paths = $paths; // Drop this cache if we're attaching new paths. $this->pathRepositoryMap = array(); return $this; } public function getPaths() { return $this->assertAttached($this->paths); } public function getPathsForRepository($repository_phid) { if (isset($this->pathRepositoryMap[$repository_phid])) { return $this->pathRepositoryMap[$repository_phid]; } $map = array(); foreach ($this->getPaths() as $path) { if ($path->getRepositoryPHID() == $repository_phid) { $map[] = $path; } } $this->pathRepositoryMap[$repository_phid] = $map; return $this->pathRepositoryMap[$repository_phid]; } public function attachOwners(array $owners) { assert_instances_of($owners, 'PhabricatorOwnersOwner'); $this->owners = $owners; return $this; } public function getOwners() { return $this->assertAttached($this->owners); } public function getOwnerPHIDs() { return mpull($this->getOwners(), 'getUserPHID'); } public function isOwnerPHID($phid) { if (!$phid) { return false; } $owner_phids = $this->getOwnerPHIDs(); $owner_phids = array_fuse($owner_phids); return isset($owner_phids[$phid]); } public function getMonogram() { return 'O'.$this->getID(); } public function getURI() { // TODO: Move these to "/O123" for consistency. return '/owners/package/'.$this->getID().'/'; } public function newAuditingRule() { return PhabricatorOwnersAuditRule::newFromState($this->getAuditingState()); } public function getHasStrongAuthority() { return ($this->getAuthorityMode() === self::AUTHORITY_STRONG); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ); } public function getPolicy($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: return $this->getViewPolicy(); case PhabricatorPolicyCapability::CAN_EDIT: return $this->getEditPolicy(); } } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: if ($this->isOwnerPHID($viewer->getPHID())) { return true; } break; } return false; } public function describeAutomaticCapability($capability) { return pht('Owners of a package may always view it.'); } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new PhabricatorOwnersPackageTransactionEditor(); } public function getApplicationTransactionTemplate() { return new PhabricatorOwnersPackageTransaction(); } /* -( PhabricatorCustomFieldInterface )------------------------------------ */ public function getCustomFieldSpecificationForRole($role) { return PhabricatorEnv::getEnvConfig('owners.fields'); } public function getCustomFieldBaseClass() { return 'PhabricatorOwnersCustomField'; } public function getCustomFields() { return $this->assertAttached($this->customFields); } public function attachCustomFields(PhabricatorCustomFieldAttachment $fields) { $this->customFields = $fields; return $this; } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $this->openTransaction(); $conn_w = $this->establishConnection('w'); queryfx( $conn_w, 'DELETE FROM %T WHERE packageID = %d', id(new PhabricatorOwnersPath())->getTableName(), $this->getID()); queryfx( $conn_w, 'DELETE FROM %T WHERE packageID = %d', id(new PhabricatorOwnersOwner())->getTableName(), $this->getID()); $this->delete(); $this->saveTransaction(); } /* -( PhabricatorConduitResultInterface )---------------------------------- */ public function getFieldSpecificationsForConduit() { return array( id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('name') ->setType('string') ->setDescription(pht('The name of the package.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('description') ->setType('string') ->setDescription(pht('The package description.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('status') ->setType('string') ->setDescription(pht('Active or archived status of the package.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('owners') ->setType('list<map<string, wild>>') ->setDescription(pht('List of package owners.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('review') ->setType('map<string, wild>') ->setDescription(pht('Auto review information.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('audit') ->setType('map<string, wild>') ->setDescription(pht('Auto audit information.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('dominion') ->setType('map<string, wild>') ->setDescription(pht('Dominion setting information.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('authority') ->setType('map<string, wild>') ->setDescription(pht('Authority setting information.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('ignored') ->setType('map<string, wild>') ->setDescription(pht('Ignored attribute information.')), ); } public function getFieldValuesForConduit() { $owner_list = array(); foreach ($this->getOwners() as $owner) { $owner_list[] = array( 'ownerPHID' => $owner->getUserPHID(), ); } $review_map = self::getAutoreviewOptionsMap(); $review_value = $this->getAutoReview(); if (isset($review_map[$review_value])) { $review_label = $review_map[$review_value]['name']; } else { $review_label = pht('Unknown ("%s")', $review_value); } $review = array( 'value' => $review_value, 'label' => $review_label, ); $audit_rule = $this->newAuditingRule(); $audit = array( 'value' => $audit_rule->getKey(), 'label' => $audit_rule->getDisplayName(), ); $dominion_value = $this->getDominion(); $dominion_map = self::getDominionOptionsMap(); if (isset($dominion_map[$dominion_value])) { $dominion_label = $dominion_map[$dominion_value]['name']; $dominion_short = $dominion_map[$dominion_value]['short']; } else { $dominion_label = pht('Unknown ("%s")', $dominion_value); $dominion_short = pht('Unknown ("%s")', $dominion_value); } $dominion = array( 'value' => $dominion_value, 'label' => $dominion_label, 'short' => $dominion_short, ); $authority_value = $this->getAuthorityMode(); $authority_map = self::getAuthorityOptionsMap(); if (isset($authority_map[$authority_value])) { $authority_label = $authority_map[$authority_value]['name']; $authority_short = $authority_map[$authority_value]['short']; } else { $authority_label = pht('Unknown ("%s")', $authority_value); $authority_short = pht('Unknown ("%s")', $authority_value); } $authority = array( 'value' => $authority_value, 'label' => $authority_label, 'short' => $authority_short, ); // Force this to always emit as a JSON object even if empty, never as // a JSON list. $ignored = $this->getIgnoredPathAttributes(); if (!$ignored) { $ignored = (object)array(); } return array( 'name' => $this->getName(), 'description' => $this->getDescription(), 'status' => $this->getStatus(), 'owners' => $owner_list, 'review' => $review, 'audit' => $audit, 'dominion' => $dominion, 'authority' => $authority, 'ignored' => $ignored, ); } public function getConduitSearchAttachments() { return array( id(new PhabricatorOwnersPathsSearchEngineAttachment()) ->setAttachmentKey('paths'), ); } /* -( PhabricatorFulltextInterface )--------------------------------------- */ public function newFulltextEngine() { return new PhabricatorOwnersPackageFulltextEngine(); } /* -( PhabricatorFerretInterface )----------------------------------------- */ public function newFerretEngine() { return new PhabricatorOwnersPackageFerretEngine(); } /* -( PhabricatorNgramsInterface )----------------------------------------- */ public function newNgrams() { return array( id(new PhabricatorOwnersPackageNameNgrams()) ->setValue($this->getName()), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/storage/PhabricatorOwnersOwner.php
src/applications/owners/storage/PhabricatorOwnersOwner.php
<?php final class PhabricatorOwnersOwner extends PhabricatorOwnersDAO { protected $packageID; // this can be a project or a user. We assume that all members of a project // owner also own the package; use the loadAffiliatedUserPHIDs method if // you want to recursively grab all user ids that own a package protected $userPHID; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_KEY_SCHEMA => array( 'packageID' => array( 'columns' => array('packageID', 'userPHID'), 'unique' => true, ), 'userPHID' => array( 'columns' => array('userPHID'), ), ), ) + parent::getConfiguration(); } public static function loadAllForPackages(array $packages) { assert_instances_of($packages, 'PhabricatorOwnersPackage'); if (!$packages) { return array(); } return id(new PhabricatorOwnersOwner())->loadAllWhere( 'packageID IN (%Ls)', mpull($packages, 'getID')); } // Loads all user phids affiliated with a set of packages. This includes both // user owners and all members of any project owners public static function loadAffiliatedUserPHIDs(array $package_ids) { if (!$package_ids) { return array(); } $owners = id(new PhabricatorOwnersOwner())->loadAllWhere( 'packageID IN (%Ls)', $package_ids); $type_user = PhabricatorPeopleUserPHIDType::TYPECONST; $type_project = PhabricatorProjectProjectPHIDType::TYPECONST; $user_phids = array(); $project_phids = array(); foreach ($owners as $owner) { $owner_phid = $owner->getUserPHID(); switch (phid_get_type($owner_phid)) { case PhabricatorPeopleUserPHIDType::TYPECONST: $user_phids[] = $owner_phid; break; case PhabricatorProjectProjectPHIDType::TYPECONST: $project_phids[] = $owner_phid; break; } } if ($project_phids) { $projects = id(new PhabricatorProjectQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs($project_phids) ->needMembers(true) ->execute(); foreach ($projects as $project) { foreach ($project->getMemberPHIDs() as $member_phid) { $user_phids[] = $member_phid; } } } $user_phids = array_fuse($user_phids); return array_values($user_phids); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/storage/PhabricatorOwnersSchemaSpec.php
src/applications/owners/storage/PhabricatorOwnersSchemaSpec.php
<?php final class PhabricatorOwnersSchemaSpec extends PhabricatorConfigSchemaSpec { public function buildSchemata() { $this->buildEdgeSchemata(new PhabricatorOwnersPackage()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/storage/PhabricatorOwnersDAO.php
src/applications/owners/storage/PhabricatorOwnersDAO.php
<?php abstract class PhabricatorOwnersDAO extends PhabricatorLiskDAO { public function getApplicationName() { return 'owners'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/storage/PhabricatorOwnersPath.php
src/applications/owners/storage/PhabricatorOwnersPath.php
<?php final class PhabricatorOwnersPath extends PhabricatorOwnersDAO { protected $packageID; protected $repositoryPHID; protected $pathIndex; protected $path; protected $pathDisplay; protected $excluded; private $fragments; private $fragmentCount; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'path' => 'text', 'pathDisplay' => 'text', 'pathIndex' => 'bytes12', 'excluded' => 'bool', ), self::CONFIG_KEY_SCHEMA => array( 'key_path' => array( 'columns' => array('packageID', 'repositoryPHID', 'pathIndex'), 'unique' => true, ), 'key_repository' => array( 'columns' => array('repositoryPHID', 'pathIndex'), ), ), ) + parent::getConfiguration(); } public static function newFromRef(array $ref) { $path = new PhabricatorOwnersPath(); $path->repositoryPHID = $ref['repositoryPHID']; $raw_path = $ref['path']; $path->pathIndex = PhabricatorHash::digestForIndex($raw_path); $path->path = $raw_path; $path->pathDisplay = $raw_path; $path->excluded = $ref['excluded']; return $path; } public function getRef() { return array( 'repositoryPHID' => $this->getRepositoryPHID(), 'path' => $this->getPath(), 'display' => $this->getPathDisplay(), 'excluded' => (int)$this->getExcluded(), ); } public static function getTransactionValueChanges(array $old, array $new) { return array( self::getTransactionValueDiff($old, $new), self::getTransactionValueDiff($new, $old), ); } private static function getTransactionValueDiff(array $u, array $v) { $set = self::getSetFromTransactionValue($v); foreach ($u as $key => $ref) { if (self::isRefInSet($ref, $set)) { unset($u[$key]); } } return $u; } public static function getSetFromTransactionValue(array $v) { $set = array(); foreach ($v as $ref) { $key = self::getScalarKeyForRef($ref); $set[$key] = true; } return $set; } public static function isRefInSet(array $ref, array $set) { $key = self::getScalarKeyForRef($ref); return isset($set[$key]); } private static function getScalarKeyForRef(array $ref) { // See T13464. When building refs from raw transactions, the path has // not been normalized yet and doesn't have a separate "display" path. // If the "display" path isn't populated, just use the actual path to // build the ref key. if (isset($ref['display'])) { $display = $ref['display']; } else { $display = $ref['path']; } return sprintf( 'repository=%s path=%s display=%s excluded=%d', $ref['repositoryPHID'], $ref['path'], $display, $ref['excluded']); } /** * Get the number of directory matches between this path specification and * some real path. */ public function getPathMatchStrength($path_fragments, $path_count) { $this_path = $this->path; if ($this_path === '/') { // The root path "/" just matches everything with strength 1. return 1; } if ($this->fragments === null) { $this->fragments = PhabricatorOwnersPackage::splitPath($this_path); $this->fragmentCount = count($this->fragments); } $self_fragments = $this->fragments; $self_count = $this->fragmentCount; if ($self_count > $path_count) { // If this path is longer (and therefore more specific) than the target // path, we don't match it at all. return 0; } for ($ii = 0; $ii < $self_count; $ii++) { if ($self_fragments[$ii] != $path_fragments[$ii]) { return 0; } } return $self_count; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/storage/PhabricatorOwnersCustomFieldNumericIndex.php
src/applications/owners/storage/PhabricatorOwnersCustomFieldNumericIndex.php
<?php final class PhabricatorOwnersCustomFieldNumericIndex extends PhabricatorCustomFieldNumericIndexStorage { public function getApplicationName() { return 'owners'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/storage/PhabricatorOwnersCustomFieldStorage.php
src/applications/owners/storage/PhabricatorOwnersCustomFieldStorage.php
<?php final class PhabricatorOwnersCustomFieldStorage extends PhabricatorCustomFieldStorage { public function getApplicationName() { return 'owners'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/storage/PhabricatorOwnersCustomFieldStringIndex.php
src/applications/owners/storage/PhabricatorOwnersCustomFieldStringIndex.php
<?php final class PhabricatorOwnersCustomFieldStringIndex extends PhabricatorCustomFieldStringIndexStorage { public function getApplicationName() { return 'owners'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/storage/PhabricatorOwnersPackageNameNgrams.php
src/applications/owners/storage/PhabricatorOwnersPackageNameNgrams.php
<?php final class PhabricatorOwnersPackageNameNgrams extends PhabricatorSearchNgrams { public function getNgramKey() { return 'name'; } public function getColumnName() { return 'name'; } public function getApplicationName() { return 'owners'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/storage/PhabricatorOwnersPackageTransaction.php
src/applications/owners/storage/PhabricatorOwnersPackageTransaction.php
<?php final class PhabricatorOwnersPackageTransaction extends PhabricatorModularTransaction { public function getApplicationName() { return 'owners'; } public function getApplicationTransactionType() { return PhabricatorOwnersPackagePHIDType::TYPECONST; } public function getBaseTransactionClass() { return 'PhabricatorOwnersPackageTransactionType'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/storage/__tests__/PhabricatorOwnersPackageTestCase.php
src/applications/owners/storage/__tests__/PhabricatorOwnersPackageTestCase.php
<?php final class PhabricatorOwnersPackageTestCase extends PhabricatorTestCase { public function testFindLongestPathsPerPackage() { $rows = array( array( 'id' => 1, 'excluded' => 0, 'dominion' => PhabricatorOwnersPackage::DOMINION_STRONG, 'path' => 'src/', ), array( 'id' => 1, 'excluded' => 1, 'dominion' => PhabricatorOwnersPackage::DOMINION_STRONG, 'path' => 'src/example/', ), array( 'id' => 2, 'excluded' => 0, 'dominion' => PhabricatorOwnersPackage::DOMINION_STRONG, 'path' => 'src/example/', ), ); $paths = array( 'src/' => array('src/a.php' => true, 'src/example/b.php' => true), 'src/example/' => array('src/example/b.php' => true), ); $this->assertEqual( array( 1 => strlen('src/'), 2 => strlen('src/example/'), ), PhabricatorOwnersPackage::findLongestPathsPerPackage($rows, $paths)); $paths = array( 'src/' => array('src/example/b.php' => true), 'src/example/' => array('src/example/b.php' => true), ); $this->assertEqual( array( 2 => strlen('src/example/'), ), PhabricatorOwnersPackage::findLongestPathsPerPackage($rows, $paths)); // Test packages with weak dominion. Here, only package #2 should own the // path. Package #1's claim is ceded to Package #2 because it uses weak // rules. Package #2 gets the claim even though it also has weak rules // because there is no more-specific package. $rows = array( array( 'id' => 1, 'excluded' => 0, 'dominion' => PhabricatorOwnersPackage::DOMINION_WEAK, 'path' => 'src/', ), array( 'id' => 2, 'excluded' => 0, 'dominion' => PhabricatorOwnersPackage::DOMINION_WEAK, 'path' => 'src/applications/', ), ); $pvalue = array('src/applications/main/main.c' => true); $paths = array( 'src/' => $pvalue, 'src/applications/' => $pvalue, ); $this->assertEqual( array( 2 => strlen('src/applications/'), ), PhabricatorOwnersPackage::findLongestPathsPerPackage($rows, $paths)); // Now, add a more specific path to Package #1. This tests nested ownership // in packages with weak dominion rules. This time, Package #1 should end // up back on top, with Package #2 ceding control to its more specific // path. $rows[] = array( 'id' => 1, 'excluded' => 0, 'dominion' => PhabricatorOwnersPackage::DOMINION_WEAK, 'path' => 'src/applications/main/', ); $paths['src/applications/main/'] = $pvalue; $this->assertEqual( array( 1 => strlen('src/applications/main/'), ), PhabricatorOwnersPackage::findLongestPathsPerPackage($rows, $paths)); // Test cases where multiple packages own the same path, with various // dominion rules. $main_c = 'src/applications/main/main.c'; $rules = array( // All claims strong. array( PhabricatorOwnersPackage::DOMINION_STRONG, PhabricatorOwnersPackage::DOMINION_STRONG, PhabricatorOwnersPackage::DOMINION_STRONG, ), // All claims weak. array( PhabricatorOwnersPackage::DOMINION_WEAK, PhabricatorOwnersPackage::DOMINION_WEAK, PhabricatorOwnersPackage::DOMINION_WEAK, ), // Mixture of strong and weak claims, strong first. array( PhabricatorOwnersPackage::DOMINION_STRONG, PhabricatorOwnersPackage::DOMINION_STRONG, PhabricatorOwnersPackage::DOMINION_WEAK, ), // Mixture of strong and weak claims, weak first. array( PhabricatorOwnersPackage::DOMINION_WEAK, PhabricatorOwnersPackage::DOMINION_STRONG, PhabricatorOwnersPackage::DOMINION_STRONG, ), ); foreach ($rules as $rule_idx => $rule) { $rows = array( array( 'id' => 1, 'excluded' => 0, 'dominion' => $rule[0], 'path' => $main_c, ), array( 'id' => 2, 'excluded' => 0, 'dominion' => $rule[1], 'path' => $main_c, ), array( 'id' => 3, 'excluded' => 0, 'dominion' => $rule[2], 'path' => $main_c, ), ); $paths = array( $main_c => $pvalue, ); // If one or more packages have strong dominion, they should own the // path. If not, all the packages with weak dominion should own the // path. $strong = array(); $weak = array(); foreach ($rule as $idx => $dominion) { if ($dominion == PhabricatorOwnersPackage::DOMINION_STRONG) { $strong[] = $idx + 1; } else { $weak[] = $idx + 1; } } if ($strong) { $expect = $strong; } else { $expect = $weak; } $expect = array_fill_keys($expect, strlen($main_c)); $actual = PhabricatorOwnersPackage::findLongestPathsPerPackage( $rows, $paths); ksort($actual); $this->assertEqual( $expect, $actual, pht('Ruleset "%s" for Identical Ownership', $rule_idx)); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/query/PhabricatorOwnersPackageQuery.php
src/applications/owners/query/PhabricatorOwnersPackageQuery.php
<?php final class PhabricatorOwnersPackageQuery extends PhabricatorCursorPagedPolicyAwareQuery { private $ids; private $phids; private $ownerPHIDs; private $authorityPHIDs; private $repositoryPHIDs; private $paths; private $statuses; private $authorityModes; private $controlMap = array(); private $controlResults; private $needPaths; /** * Query owner PHIDs exactly. This does not expand authorities, so a user * PHID will not match projects the user is a member of. */ public function withOwnerPHIDs(array $phids) { $this->ownerPHIDs = $phids; return $this; } /** * Query owner authority. This will expand authorities, so a user PHID will * match both packages they own directly and packages owned by a project they * are a member of. */ public function withAuthorityPHIDs(array $phids) { $this->authorityPHIDs = $phids; return $this; } public function withPHIDs(array $phids) { $this->phids = $phids; return $this; } public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withRepositoryPHIDs(array $phids) { $this->repositoryPHIDs = $phids; return $this; } public function withPaths(array $paths) { $this->paths = $paths; return $this; } public function withStatuses(array $statuses) { $this->statuses = $statuses; return $this; } public function withControl($repository_phid, array $paths) { if (empty($this->controlMap[$repository_phid])) { $this->controlMap[$repository_phid] = array(); } foreach ($paths as $path) { $path = (string)$path; $this->controlMap[$repository_phid][$path] = $path; } // We need to load paths to execute control queries. $this->needPaths = true; return $this; } public function withAuthorityModes(array $modes) { $this->authorityModes = $modes; return $this; } public function withNameNgrams($ngrams) { return $this->withNgramsConstraint( new PhabricatorOwnersPackageNameNgrams(), $ngrams); } public function needPaths($need_paths) { $this->needPaths = $need_paths; return $this; } public function newResultObject() { return new PhabricatorOwnersPackage(); } protected function willExecute() { $this->controlResults = array(); } protected function willFilterPage(array $packages) { $package_ids = mpull($packages, 'getID'); $owners = id(new PhabricatorOwnersOwner())->loadAllWhere( 'packageID IN (%Ld)', $package_ids); $owners = mgroup($owners, 'getPackageID'); foreach ($packages as $package) { $package->attachOwners(idx($owners, $package->getID(), array())); } return $packages; } protected function didFilterPage(array $packages) { $package_ids = mpull($packages, 'getID'); if ($this->needPaths) { $paths = id(new PhabricatorOwnersPath())->loadAllWhere( 'packageID IN (%Ld)', $package_ids); $paths = mgroup($paths, 'getPackageID'); foreach ($packages as $package) { $package->attachPaths(idx($paths, $package->getID(), array())); } } if ($this->controlMap) { foreach ($packages as $package) { // If this package is archived, it's no longer a controlling package // for any path. In particular, it can not force active packages with // weak dominion to give up control. if ($package->isArchived()) { continue; } $this->controlResults[$package->getID()] = $package; } } return $packages; } protected function buildJoinClauseParts(AphrontDatabaseConnection $conn) { $joins = parent::buildJoinClauseParts($conn); if ($this->shouldJoinOwnersTable()) { $joins[] = qsprintf( $conn, 'JOIN %T o ON o.packageID = p.id', id(new PhabricatorOwnersOwner())->getTableName()); } if ($this->shouldJoinPathTable()) { $joins[] = qsprintf( $conn, 'JOIN %T rpath ON rpath.packageID = p.id', id(new PhabricatorOwnersPath())->getTableName()); } return $joins; } protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) { $where = parent::buildWhereClauseParts($conn); if ($this->phids !== null) { $where[] = qsprintf( $conn, 'p.phid IN (%Ls)', $this->phids); } if ($this->ids !== null) { $where[] = qsprintf( $conn, 'p.id IN (%Ld)', $this->ids); } if ($this->repositoryPHIDs !== null) { $where[] = qsprintf( $conn, 'rpath.repositoryPHID IN (%Ls)', $this->repositoryPHIDs); } if ($this->authorityPHIDs !== null) { $authority_phids = $this->expandAuthority($this->authorityPHIDs); $where[] = qsprintf( $conn, 'o.userPHID IN (%Ls)', $authority_phids); } if ($this->ownerPHIDs !== null) { $where[] = qsprintf( $conn, 'o.userPHID IN (%Ls)', $this->ownerPHIDs); } if ($this->paths !== null) { $where[] = qsprintf( $conn, 'rpath.pathIndex IN (%Ls)', $this->getFragmentIndexesForPaths($this->paths)); } if ($this->statuses !== null) { $where[] = qsprintf( $conn, 'p.status IN (%Ls)', $this->statuses); } if ($this->controlMap) { $clauses = array(); foreach ($this->controlMap as $repository_phid => $paths) { $indexes = $this->getFragmentIndexesForPaths($paths); $clauses[] = qsprintf( $conn, '(rpath.repositoryPHID = %s AND rpath.pathIndex IN (%Ls))', $repository_phid, $indexes); } $where[] = qsprintf($conn, '%LO', $clauses); } if ($this->authorityModes !== null) { $where[] = qsprintf( $conn, 'authorityMode IN (%Ls)', $this->authorityModes); } return $where; } protected function shouldGroupQueryResultRows() { if ($this->shouldJoinOwnersTable()) { return true; } if ($this->shouldJoinPathTable()) { return true; } return parent::shouldGroupQueryResultRows(); } public function getBuiltinOrders() { return array( 'name' => array( 'vector' => array('name'), 'name' => pht('Name'), ), ) + parent::getBuiltinOrders(); } public function getOrderableColumns() { return parent::getOrderableColumns() + array( 'name' => array( 'table' => $this->getPrimaryTableAlias(), 'column' => 'name', 'type' => 'string', 'unique' => true, 'reverse' => true, ), ); } protected function newPagingMapFromPartialObject($object) { return array( 'id' => (int)$object->getID(), 'name' => $object->getName(), ); } public function getQueryApplicationClass() { return 'PhabricatorOwnersApplication'; } protected function getPrimaryTableAlias() { return 'p'; } private function shouldJoinOwnersTable() { if ($this->ownerPHIDs !== null) { return true; } if ($this->authorityPHIDs !== null) { return true; } return false; } private function shouldJoinPathTable() { if ($this->repositoryPHIDs !== null) { return true; } if ($this->paths !== null) { return true; } if ($this->controlMap) { return true; } return false; } private function expandAuthority(array $phids) { $projects = id(new PhabricatorProjectQuery()) ->setViewer($this->getViewer()) ->withMemberPHIDs($phids) ->execute(); $project_phids = mpull($projects, 'getPHID'); return array_fuse($phids) + array_fuse($project_phids); } private function getFragmentsForPaths(array $paths) { $fragments = array(); foreach ($paths as $path) { foreach (PhabricatorOwnersPackage::splitPath($path) as $fragment) { $fragments[$fragment] = $fragment; } } return $fragments; } private function getFragmentIndexesForPaths(array $paths) { $indexes = array(); foreach ($this->getFragmentsForPaths($paths) as $fragment) { $indexes[] = PhabricatorHash::digestForIndex($fragment); } return $indexes; } /* -( Path Control )------------------------------------------------------- */ /** * Get a list of all packages which control a path or its parent directories, * ordered from weakest to strongest. * * The first package has the most specific claim on the path; the last * package has the most general claim. Multiple packages may have claims of * equal strength, so this ordering is primarily one of usability and * convenience. * * @return list<PhabricatorOwnersPackage> List of controlling packages. */ public function getControllingPackagesForPath( $repository_phid, $path, $ignore_dominion = false) { $path = (string)$path; if (!isset($this->controlMap[$repository_phid][$path])) { throw new PhutilInvalidStateException('withControl'); } if ($this->controlResults === null) { throw new PhutilInvalidStateException('execute'); } $packages = $this->controlResults; $weak_dominion = PhabricatorOwnersPackage::DOMINION_WEAK; $path_fragments = PhabricatorOwnersPackage::splitPath($path); $fragment_count = count($path_fragments); $matches = array(); foreach ($packages as $package_id => $package) { $best_match = null; $include = false; $repository_paths = $package->getPathsForRepository($repository_phid); foreach ($repository_paths as $package_path) { $strength = $package_path->getPathMatchStrength( $path_fragments, $fragment_count); if ($strength > $best_match) { $best_match = $strength; $include = !$package_path->getExcluded(); } } if ($best_match && $include) { if ($ignore_dominion) { $is_weak = false; } else { $is_weak = ($package->getDominion() == $weak_dominion); } $matches[$package_id] = array( 'strength' => $best_match, 'weak' => $is_weak, 'package' => $package, ); } } // At each strength level, drop weak packages if there are also strong // packages of the same strength. $strength_map = igroup($matches, 'strength'); foreach ($strength_map as $strength => $package_list) { $any_strong = false; foreach ($package_list as $package_id => $package) { if (!$package['weak']) { $any_strong = true; break; } } if ($any_strong) { foreach ($package_list as $package_id => $package) { if ($package['weak']) { unset($matches[$package_id]); } } } } $matches = isort($matches, 'strength'); $matches = array_reverse($matches); $strongest = null; foreach ($matches as $package_id => $match) { if ($strongest === null) { $strongest = $match['strength']; } if ($match['strength'] === $strongest) { continue; } if ($match['weak']) { unset($matches[$package_id]); } } return array_values(ipull($matches, 'package')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/query/PhabricatorOwnerPathQuery.php
src/applications/owners/query/PhabricatorOwnerPathQuery.php
<?php final class PhabricatorOwnerPathQuery extends Phobject { public static function loadAffectedPaths( PhabricatorRepository $repository, PhabricatorRepositoryCommit $commit, PhabricatorUser $user) { $drequest = DiffusionRequest::newFromDictionary( array( 'user' => $user, 'repository' => $repository, 'commit' => $commit->getCommitIdentifier(), )); $path_query = DiffusionPathChangeQuery::newFromDiffusionRequest( $drequest); $paths = $path_query->loadChanges(); $result = array(); foreach ($paths as $path) { $basic_path = '/'.$path->getPath(); if ($path->getFileType() == DifferentialChangeType::FILE_DIRECTORY) { $basic_path = rtrim($basic_path, '/').'/'; } $result[] = $basic_path; } return $result; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/query/PhabricatorOwnersPackageTransactionQuery.php
src/applications/owners/query/PhabricatorOwnersPackageTransactionQuery.php
<?php final class PhabricatorOwnersPackageTransactionQuery extends PhabricatorApplicationTransactionQuery { public function getTemplateApplicationTransaction() { return new PhabricatorOwnersPackageTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/query/PhabricatorOwnersPackageSearchEngine.php
src/applications/owners/query/PhabricatorOwnersPackageSearchEngine.php
<?php final class PhabricatorOwnersPackageSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('Owners Packages'); } public function getApplicationClassName() { return 'PhabricatorOwnersApplication'; } public function newQuery() { return new PhabricatorOwnersPackageQuery(); } protected function buildCustomSearchFields() { return array( id(new PhabricatorSearchDatasourceField()) ->setLabel(pht('Authority')) ->setKey('authorityPHIDs') ->setAliases(array('authority', 'authorities')) ->setConduitKey('owners') ->setDescription( pht('Search for packages with specific owners.')) ->setDatasource(new PhabricatorProjectOrUserDatasource()), id(new PhabricatorSearchTextField()) ->setLabel(pht('Name Contains')) ->setKey('name') ->setDescription(pht('Search for packages by name substrings.')), id(new PhabricatorSearchDatasourceField()) ->setLabel(pht('Repositories')) ->setKey('repositoryPHIDs') ->setConduitKey('repositories') ->setAliases(array('repository', 'repositories')) ->setDescription( pht('Search for packages by included repositories.')) ->setDatasource(new DiffusionRepositoryDatasource()), id(new PhabricatorSearchStringListField()) ->setLabel(pht('Paths')) ->setKey('paths') ->setAliases(array('path')) ->setDescription( pht('Search for packages affecting specific paths.')), id(new PhabricatorSearchCheckboxesField()) ->setKey('statuses') ->setLabel(pht('Status')) ->setDescription( pht('Search for active or archived packages.')) ->setOptions( id(new PhabricatorOwnersPackage()) ->getStatusNameMap()), ); } protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); if ($map['authorityPHIDs']) { $query->withAuthorityPHIDs($map['authorityPHIDs']); } if ($map['repositoryPHIDs']) { $query->withRepositoryPHIDs($map['repositoryPHIDs']); } if ($map['paths']) { $query->withPaths($map['paths']); } if ($map['statuses']) { $query->withStatuses($map['statuses']); } if (strlen($map['name'])) { $query->withNameNgrams($map['name']); } return $query; } protected function getURI($path) { return '/owners/'.$path; } protected function getBuiltinQueryNames() { $names = array(); if ($this->requireViewer()->isLoggedIn()) { $names['authority'] = pht('Owned'); } $names += array( 'active' => pht('Active Packages'), 'all' => pht('All Packages'), ); return $names; } public function buildSavedQueryFromBuiltin($query_key) { $query = $this->newSavedQuery(); $query->setQueryKey($query_key); switch ($query_key) { case 'all': return $query; case 'active': return $query->setParameter( 'statuses', array( PhabricatorOwnersPackage::STATUS_ACTIVE, )); case 'authority': return $query->setParameter( 'authorityPHIDs', array($this->requireViewer()->getPHID())); } return parent::buildSavedQueryFromBuiltin($query_key); } protected function renderResultList( array $packages, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($packages, 'PhabricatorOwnersPackage'); $viewer = $this->requireViewer(); $list = id(new PHUIObjectItemListView()) ->setUser($viewer); foreach ($packages as $package) { $id = $package->getID(); $item = id(new PHUIObjectItemView()) ->setObject($package) ->setObjectName($package->getMonogram()) ->setHeader($package->getName()) ->setHref($package->getURI()); if ($package->isArchived()) { $item->setDisabled(true); } $list->addItem($item); } $result = new PhabricatorApplicationSearchResultView(); $result->setObjectList($list); $result->setNoDataString(pht('No packages found.')); return $result; } protected function getNewUserBody() { $create_button = id(new PHUIButtonView()) ->setTag('a') ->setText(pht('Create a Package')) ->setHref('/owners/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( 'Group sections of a codebase into packages for re-use in other '. 'applications, like Herald rules.')) ->addAction($create_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/owners/mail/OwnersPackageReplyHandler.php
src/applications/owners/mail/OwnersPackageReplyHandler.php
<?php final class OwnersPackageReplyHandler extends PhabricatorMailReplyHandler { public function validateMailReceiver($mail_receiver) { if (!($mail_receiver instanceof PhabricatorOwnersPackage)) { throw new Exception( pht( 'Receiver is not a %s!', 'PhabricatorOwnersPackage')); } } public function getPrivateReplyHandlerEmailAddress( PhabricatorUser $user) { return null; } public function getPublicReplyHandlerEmailAddress() { 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/owners/customfield/PhabricatorOwnersCustomField.php
src/applications/owners/customfield/PhabricatorOwnersCustomField.php
<?php abstract class PhabricatorOwnersCustomField extends PhabricatorCustomField { public function newStorageObject() { return new PhabricatorOwnersCustomFieldStorage(); } protected function newStringIndexStorage() { return new PhabricatorOwnersCustomFieldStringIndex(); } protected function newNumericIndexStorage() { return new PhabricatorOwnersCustomFieldNumericIndex(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/customfield/PhabricatorOwnersConfiguredCustomField.php
src/applications/owners/customfield/PhabricatorOwnersConfiguredCustomField.php
<?php final class PhabricatorOwnersConfiguredCustomField extends PhabricatorOwnersCustomField implements PhabricatorStandardCustomFieldInterface { public function getStandardCustomFieldNamespace() { return 'owners'; } public function createFields($object) { $config = PhabricatorEnv::getEnvConfig('owners.custom-field-definitions'); $fields = PhabricatorStandardCustomField::buildStandardFields( $this, $config); return $fields; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/editor/PhabricatorOwnersPackageTransactionEditor.php
src/applications/owners/editor/PhabricatorOwnersPackageTransactionEditor.php
<?php final class PhabricatorOwnersPackageTransactionEditor extends PhabricatorApplicationTransactionEditor { public function getEditorApplicationClass() { return 'PhabricatorOwnersApplication'; } public function getEditorObjectsDescription() { return pht('Owners Packages'); } public function getTransactionTypes() { $types = parent::getTransactionTypes(); $types[] = PhabricatorTransactions::TYPE_VIEW_POLICY; $types[] = PhabricatorTransactions::TYPE_EDIT_POLICY; return $types; } protected function shouldSendMail( PhabricatorLiskDAO $object, array $xactions) { return true; } protected function getMailSubjectPrefix() { return pht('[Package]'); } protected function getMailTo(PhabricatorLiskDAO $object) { return array( $this->requireActor()->getPHID(), ); } protected function getMailCC(PhabricatorLiskDAO $object) { return mpull($object->getOwners(), 'getUserPHID'); } protected function buildReplyHandler(PhabricatorLiskDAO $object) { return id(new OwnersPackageReplyHandler()) ->setMailReceiver($object); } protected function buildMailTemplate(PhabricatorLiskDAO $object) { $name = $object->getName(); return id(new PhabricatorMetaMTAMail()) ->setSubject($name); } protected function buildMailBody( PhabricatorLiskDAO $object, array $xactions) { $body = parent::buildMailBody($object, $xactions); $detail_uri = PhabricatorEnv::getProductionURI($object->getURI()); $body->addLinkSection( pht('PACKAGE DETAIL'), $detail_uri); return $body; } protected function supportsSearch() { 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/owners/editor/PhabricatorOwnersPackageEditEngine.php
src/applications/owners/editor/PhabricatorOwnersPackageEditEngine.php
<?php final class PhabricatorOwnersPackageEditEngine extends PhabricatorEditEngine { const ENGINECONST = 'owners.package'; public function getEngineName() { return pht('Owners Packages'); } public function getSummaryHeader() { return pht('Configure Owners Package Forms'); } public function getSummaryText() { return pht('Configure forms for creating and editing packages in Owners.'); } public function getEngineApplicationClass() { return 'PhabricatorOwnersApplication'; } protected function newEditableObject() { return PhabricatorOwnersPackage::initializeNewPackage($this->getViewer()); } protected function newObjectQuery() { return id(new PhabricatorOwnersPackageQuery()) ->needPaths(true); } protected function getObjectCreateTitleText($object) { return pht('Create New Package'); } protected function getObjectEditTitleText($object) { return pht('Edit Package: %s', $object->getName()); } protected function getObjectEditShortText($object) { return pht('Package %d', $object->getID()); } protected function getObjectCreateShortText() { return pht('Create Package'); } protected function getObjectName() { return pht('Package'); } protected function getObjectViewURI($object) { return $object->getURI(); } protected function buildCustomEditFields($object) { $paths_help = pht(<<<EOTEXT When updating the paths for a package, pass a list of dictionaries like this as the `value` for the transaction: ```lang=json, name="Example Paths Value" [ { "repositoryPHID": "PHID-REPO-1234", "path": "/path/to/directory/", "excluded": false }, { "repositoryPHID": "PHID-REPO-1234", "path": "/another/example/path/", "excluded": false } ] ``` This transaction will set the paths to the list you provide, overwriting any previous paths. Generally, you will call `owners.search` first to get a list of current paths (which are provided in the same format), make changes, then update them by applying a transaction of this type. EOTEXT ); $autoreview_map = PhabricatorOwnersPackage::getAutoreviewOptionsMap(); $autoreview_map = ipull($autoreview_map, 'name'); $dominion_map = PhabricatorOwnersPackage::getDominionOptionsMap(); $dominion_map = ipull($dominion_map, 'name'); $authority_map = PhabricatorOwnersPackage::getAuthorityOptionsMap(); $authority_map = ipull($authority_map, 'name'); return array( id(new PhabricatorTextEditField()) ->setKey('name') ->setLabel(pht('Name')) ->setDescription(pht('Name of the package.')) ->setTransactionType( PhabricatorOwnersPackageNameTransaction::TRANSACTIONTYPE) ->setIsRequired(true) ->setValue($object->getName()), id(new PhabricatorDatasourceEditField()) ->setKey('owners') ->setLabel(pht('Owners')) ->setDescription(pht('Users and projects which own the package.')) ->setTransactionType( PhabricatorOwnersPackageOwnersTransaction::TRANSACTIONTYPE) ->setDatasource(new PhabricatorProjectOrUserDatasource()) ->setIsCopyable(true) ->setValue($object->getOwnerPHIDs()), id(new PhabricatorSelectEditField()) ->setKey('dominion') ->setLabel(pht('Dominion')) ->setDescription( pht('Change package dominion rules.')) ->setTransactionType( PhabricatorOwnersPackageDominionTransaction::TRANSACTIONTYPE) ->setIsCopyable(true) ->setValue($object->getDominion()) ->setOptions($dominion_map), id(new PhabricatorSelectEditField()) ->setKey('authority') ->setLabel(pht('Authority')) ->setDescription( pht('Change package authority rules.')) ->setTransactionType( PhabricatorOwnersPackageAuthorityTransaction::TRANSACTIONTYPE) ->setIsCopyable(true) ->setValue($object->getAuthorityMode()) ->setOptions($authority_map), id(new PhabricatorSelectEditField()) ->setKey('autoReview') ->setLabel(pht('Auto Review')) ->setDescription( pht( 'Automatically trigger reviews for commits affecting files in '. 'this package.')) ->setTransactionType( PhabricatorOwnersPackageAutoreviewTransaction::TRANSACTIONTYPE) ->setIsCopyable(true) ->setValue($object->getAutoReview()) ->setOptions($autoreview_map), id(new PhabricatorSelectEditField()) ->setKey('auditing') ->setLabel(pht('Auditing')) ->setDescription( pht( 'Automatically trigger audits for commits affecting files in '. 'this package.')) ->setTransactionType( PhabricatorOwnersPackageAuditingTransaction::TRANSACTIONTYPE) ->setIsCopyable(true) ->setValue($object->getAuditingState()) ->setOptions(PhabricatorOwnersAuditRule::newSelectControlMap()), id(new PhabricatorRemarkupEditField()) ->setKey('description') ->setLabel(pht('Description')) ->setDescription(pht('Human-readable description of the package.')) ->setTransactionType( PhabricatorOwnersPackageDescriptionTransaction::TRANSACTIONTYPE) ->setValue($object->getDescription()), id(new PhabricatorSelectEditField()) ->setKey('status') ->setLabel(pht('Status')) ->setDescription(pht('Archive or enable the package.')) ->setTransactionType( PhabricatorOwnersPackageStatusTransaction::TRANSACTIONTYPE) ->setIsFormField(false) ->setValue($object->getStatus()) ->setOptions($object->getStatusNameMap()), id(new PhabricatorCheckboxesEditField()) ->setKey('ignored') ->setLabel(pht('Ignored Attributes')) ->setDescription(pht('Ignore paths with any of these attributes.')) ->setTransactionType( PhabricatorOwnersPackageIgnoredTransaction::TRANSACTIONTYPE) ->setValue(array_keys($object->getIgnoredPathAttributes())) ->setOptions( array( 'generated' => pht('Ignore generated files (review only).'), )), id(new PhabricatorConduitEditField()) ->setKey('paths.set') ->setLabel(pht('Paths')) ->setIsFormField(false) ->setTransactionType( PhabricatorOwnersPackagePathsTransaction::TRANSACTIONTYPE) ->setConduitDescription( pht('Overwrite existing package paths with new paths.')) ->setConduitTypeDescription( pht('List of dictionaries, each describing a path.')) ->setConduitDocumentation($paths_help), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/xaction/PhabricatorOwnersPackageAutoreviewTransaction.php
src/applications/owners/xaction/PhabricatorOwnersPackageAutoreviewTransaction.php
<?php final class PhabricatorOwnersPackageAutoreviewTransaction extends PhabricatorOwnersPackageTransactionType { const TRANSACTIONTYPE = 'owners.autoreview'; public function generateOldValue($object) { return $object->getAutoReview(); } public function validateTransactions($object, array $xactions) { $errors = array(); $map = PhabricatorOwnersPackage::getAutoreviewOptionsMap(); foreach ($xactions as $xaction) { $new = $xaction->getNewValue(); if (empty($map[$new])) { $valid = array_keys($map); $errors[] = $this->newInvalidError( pht( 'Autoreview setting "%s" is not valid. '. 'Valid settings are: %s.', $new, implode(', ', $valid)), $xaction); } } return $errors; } public function applyInternalEffects($object, $value) { $object->setAutoReview($value); } public function getTitle() { $map = PhabricatorOwnersPackage::getAutoreviewOptionsMap(); $map = ipull($map, 'name'); $old = $this->getOldValue(); $new = $this->getNewValue(); $old = idx($map, $old, $old); $new = idx($map, $new, $new); return pht( '%s adjusted autoreview from %s to %s.', $this->renderAuthor(), $this->renderValue($old), $this->renderValue($new)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/xaction/PhabricatorOwnersPackagePathsTransaction.php
src/applications/owners/xaction/PhabricatorOwnersPackagePathsTransaction.php
<?php final class PhabricatorOwnersPackagePathsTransaction extends PhabricatorOwnersPackageTransactionType { const TRANSACTIONTYPE = 'owners.paths'; public function generateOldValue($object) { $paths = $object->getPaths(); return mpull($paths, 'getRef'); } public function generateNewValue($object, $value) { $new = $value; foreach ($new as $key => $info) { $info['excluded'] = (int)idx($info, 'excluded'); // The input has one "path" key with the display path. // Move it to "display", then normalize the value in "path". $display_path = $info['path']; $raw_path = rtrim($display_path, '/').'/'; $info['path'] = $raw_path; $info['display'] = $display_path; $new[$key] = $info; } return $new; } public function getTransactionHasEffect($object, $old, $new) { list($add, $rem) = PhabricatorOwnersPath::getTransactionValueChanges( $old, $new); return ($add || $rem); } public function validateTransactions($object, array $xactions) { $errors = array(); if (!$xactions) { return $errors; } $old = mpull($object->getPaths(), 'getRef'); foreach ($xactions as $xaction) { $new = $xaction->getNewValue(); // Check that we have a list of paths. if (!is_array($new)) { $errors[] = $this->newInvalidError( pht('Path specification must be a list of paths.'), $xaction); continue; } // Check that each item in the list is formatted properly. $type_exception = null; foreach ($new as $key => $value) { try { PhutilTypeSpec::checkMap( $value, array( 'repositoryPHID' => 'string', 'path' => 'string', 'excluded' => 'optional wild', )); } catch (PhutilTypeCheckException $ex) { $errors[] = $this->newInvalidError( pht( 'Path specification list contains invalid value '. 'in key "%s": %s.', $key, $ex->getMessage()), $xaction); $type_exception = $ex; } } if ($type_exception) { continue; } // Check that any new paths reference legitimate repositories which // the viewer has permission to see. list($rem, $add) = PhabricatorOwnersPath::getTransactionValueChanges( $old, $new); if ($add) { $repository_phids = ipull($add, 'repositoryPHID'); $repositories = id(new PhabricatorRepositoryQuery()) ->setViewer($this->getActor()) ->withPHIDs($repository_phids) ->execute(); $repositories = mpull($repositories, null, 'getPHID'); foreach ($add as $ref) { $repository_phid = $ref['repositoryPHID']; if (isset($repositories[$repository_phid])) { continue; } $errors[] = $this->newInvalidError( pht( 'Path specification list references repository PHID "%s", '. 'but that is not a valid, visible repository.', $repository_phid)); } } } return $errors; } public function applyExternalEffects($object, $value) { $old = $this->generateOldValue($object); $new = $value; $paths = $object->getPaths(); // We store paths in a normalized format with a trailing slash, regardless // of whether the user enters "path/to/file.c" or "src/backend/". Normalize // paths now. $display_map = array(); $seen_map = array(); foreach ($new as $key => $spec) { $raw_path = $spec['path']; $display_path = $spec['display']; // If the user entered two paths in the same repository which normalize // to the same value (like "src/main.c" and "src/main.c/"), discard the // duplicates. $repository_phid = $spec['repositoryPHID']; if (isset($seen_map[$repository_phid][$raw_path])) { unset($new[$key]); continue; } $new[$key]['path'] = $raw_path; $display_map[$raw_path] = $display_path; $seen_map[$repository_phid][$raw_path] = true; } $diffs = PhabricatorOwnersPath::getTransactionValueChanges($old, $new); list($rem, $add) = $diffs; $set = PhabricatorOwnersPath::getSetFromTransactionValue($rem); foreach ($paths as $path) { $ref = $path->getRef(); if (PhabricatorOwnersPath::isRefInSet($ref, $set)) { $path->delete(); continue; } // If the user has changed the display value for a path but the raw // storage value hasn't changed, update the display value. if (isset($display_map[$path->getPath()])) { $path ->setPathDisplay($display_map[$path->getPath()]) ->save(); continue; } } foreach ($add as $ref) { $path = PhabricatorOwnersPath::newFromRef($ref) ->setPackageID($object->getID()) ->setPathDisplay($display_map[$ref['path']]) ->save(); } } public function getTitle() { // TODO: Flesh this out. return pht( '%s updated paths for this package.', $this->renderAuthor()); } public function hasChangeDetailView() { return true; } public function newChangeDetailView() { $old = $this->getOldValue(); $new = $this->getNewValue(); $diffs = PhabricatorOwnersPath::getTransactionValueChanges($old, $new); list($rem, $add) = $diffs; $rows = array(); foreach ($rem as $ref) { $rows[] = array( 'class' => 'diff-removed', 'change' => '-', ) + $ref; } foreach ($add as $ref) { $rows[] = array( 'class' => 'diff-added', 'change' => '+', ) + $ref; } $rowc = array(); foreach ($rows as $key => $row) { $rowc[] = $row['class']; if (array_key_exists('display', $row)) { $display_path = $row['display']; } else { $display_path = $row['path']; } $rows[$key] = array( $row['change'], $row['excluded'] ? pht('Exclude') : pht('Include'), $this->renderHandle($row['repositoryPHID']), $display_path, ); } $table = id(new AphrontTableView($rows)) ->setViewer($this->getViewer()) ->setRowClasses($rowc) ->setHeaders( array( null, pht('Type'), pht('Repository'), pht('Path'), )) ->setColumnClasses( array( null, null, null, 'wide', )); return $table; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/xaction/PhabricatorOwnersPackageAuthorityTransaction.php
src/applications/owners/xaction/PhabricatorOwnersPackageAuthorityTransaction.php
<?php final class PhabricatorOwnersPackageAuthorityTransaction extends PhabricatorOwnersPackageTransactionType { const TRANSACTIONTYPE = 'owners.authority'; public function generateOldValue($object) { return $object->getAuthorityMode(); } public function validateTransactions($object, array $xactions) { $errors = array(); $map = PhabricatorOwnersPackage::getAuthorityOptionsMap(); foreach ($xactions as $xaction) { $new = $xaction->getNewValue(); if (empty($map[$new])) { $valid = array_keys($map); $errors[] = $this->newInvalidError( pht( 'Authority setting "%s" is not valid. '. 'Valid settings are: %s.', $new, implode(', ', $valid)), $xaction); } } return $errors; } public function applyInternalEffects($object, $value) { $object->setAuthorityMode($value); } public function getTitle() { $map = PhabricatorOwnersPackage::getAuthorityOptionsMap(); $map = ipull($map, 'short'); $old = $this->getOldValue(); $new = $this->getNewValue(); $old = idx($map, $old, $old); $new = idx($map, $new, $new); return pht( '%s adjusted package authority rules from %s to %s.', $this->renderAuthor(), $this->renderValue($old), $this->renderValue($new)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/xaction/PhabricatorOwnersPackageAuditingTransaction.php
src/applications/owners/xaction/PhabricatorOwnersPackageAuditingTransaction.php
<?php final class PhabricatorOwnersPackageAuditingTransaction extends PhabricatorOwnersPackageTransactionType { const TRANSACTIONTYPE = 'owners.auditing'; public function generateOldValue($object) { return $object->getAuditingState(); } public function generateNewValue($object, $value) { return PhabricatorOwnersAuditRule::getStorageValueFromAPIValue($value); } public function applyInternalEffects($object, $value) { $object->setAuditingState($value); } public function getTitle() { $old_value = $this->getOldValue(); $new_value = $this->getNewValue(); $old_rule = PhabricatorOwnersAuditRule::newFromState($old_value); $new_rule = PhabricatorOwnersAuditRule::newFromState($new_value); return pht( '%s changed the audit rule for this package from %s to %s.', $this->renderAuthor(), $this->renderValue($old_rule->getDisplayName()), $this->renderValue($new_rule->getDisplayName())); } public function validateTransactions($object, array $xactions) { $errors = array(); // See PHI1047. This transaction type accepted some weird stuff. Continue // supporting it for now, but move toward sensible consistency. $modern_options = PhabricatorOwnersAuditRule::getModernValueMap(); $deprecated_options = PhabricatorOwnersAuditRule::getDeprecatedValueMap(); foreach ($xactions as $xaction) { $new_value = $xaction->getNewValue(); if (isset($modern_options[$new_value])) { continue; } if (isset($deprecated_options[$new_value])) { continue; } $errors[] = $this->newInvalidError( pht( 'Package auditing value "%s" is not supported. Supported options '. 'are: %s. Deprecated options are: %s.', $new_value, implode(', ', $modern_options), implode(', ', $deprecated_options)), $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/owners/xaction/PhabricatorOwnersPackageDominionTransaction.php
src/applications/owners/xaction/PhabricatorOwnersPackageDominionTransaction.php
<?php final class PhabricatorOwnersPackageDominionTransaction extends PhabricatorOwnersPackageTransactionType { const TRANSACTIONTYPE = 'owners.dominion'; public function generateOldValue($object) { return $object->getDominion(); } public function validateTransactions($object, array $xactions) { $errors = array(); $map = PhabricatorOwnersPackage::getDominionOptionsMap(); foreach ($xactions as $xaction) { $new = $xaction->getNewValue(); if (empty($map[$new])) { $valid = array_keys($map); $errors[] = $this->newInvalidError( pht( 'Dominion setting "%s" is not valid. '. 'Valid settings are: %s.', $new, implode(', ', $valid)), $xaction); } } return $errors; } public function applyInternalEffects($object, $value) { $object->setDominion($value); } public function getTitle() { $map = PhabricatorOwnersPackage::getDominionOptionsMap(); $map = ipull($map, 'short'); $old = $this->getOldValue(); $new = $this->getNewValue(); $old = idx($map, $old, $old); $new = idx($map, $new, $new); return pht( '%s adjusted package dominion rules from %s to %s.', $this->renderAuthor(), $this->renderValue($old), $this->renderValue($new)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/xaction/PhabricatorOwnersPackageOwnersTransaction.php
src/applications/owners/xaction/PhabricatorOwnersPackageOwnersTransaction.php
<?php final class PhabricatorOwnersPackageOwnersTransaction extends PhabricatorOwnersPackageTransactionType { const TRANSACTIONTYPE = 'owners.owners'; public function generateOldValue($object) { $phids = mpull($object->getOwners(), 'getUserPHID'); $phids = array_values($phids); return $phids; } public function generateNewValue($object, $value) { $phids = array_unique($value); $phids = array_values($phids); return $phids; } public function applyExternalEffects($object, $value) { $old = $this->generateOldValue($object); $new = $value; $owners = $object->getOwners(); $owners = mpull($owners, null, 'getUserPHID'); $rem = array_diff($old, $new); foreach ($rem as $phid) { if (isset($owners[$phid])) { $owners[$phid]->delete(); unset($owners[$phid]); } } $add = array_diff($new, $old); foreach ($add as $phid) { $owners[$phid] = id(new PhabricatorOwnersOwner()) ->setPackageID($object->getID()) ->setUserPHID($phid) ->save(); } // TODO: Attach owners here } 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 added %s owner(s): %s.', $this->renderAuthor(), count($add), $this->renderHandleList($add)); } else if ($rem && !$add) { return pht( '%s removed %s owner(s): %s.', $this->renderAuthor(), count($rem), $this->renderHandleList($rem)); } else { return pht( '%s changed %s package owner(s), added %s: %s; removed %s: %s.', $this->renderAuthor(), count($add) + count($rem), count($add), $this->renderHandleList($add), count($rem), $this->renderHandleList($rem)); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/xaction/PhabricatorOwnersPackageIgnoredTransaction.php
src/applications/owners/xaction/PhabricatorOwnersPackageIgnoredTransaction.php
<?php final class PhabricatorOwnersPackageIgnoredTransaction extends PhabricatorOwnersPackageTransactionType { const TRANSACTIONTYPE = 'owners.ignored'; public function generateOldValue($object) { return $object->getIgnoredPathAttributes(); } public function generateNewValue($object, $value) { return array_fill_keys($value, true); } public function applyInternalEffects($object, $value) { $object->setIgnoredPathAttributes($value); } public function getTitle() { $old = array_keys($this->getOldValue()); $new = array_keys($this->getNewValue()); $add = array_diff($new, $old); $rem = array_diff($old, $new); $all_n = new PhutilNumber(count($add) + count($rem)); $add_n = phutil_count($add); $rem_n = phutil_count($rem); if ($new && $old) { return pht( '%s changed %s ignored attribute(s), added %s: %s; removed %s: %s.', $this->renderAuthor(), $all_n, $add_n, $this->renderValueList($add), $rem_n, $this->renderValueList($rem)); } else if ($new) { return pht( '%s changed %s ignored attribute(s), added %s: %s.', $this->renderAuthor(), $all_n, $add_n, $this->rendervalueList($add)); } else { return pht( '%s changed %s ignored attribute(s), removed %s: %s.', $this->renderAuthor(), $all_n, $rem_n, $this->rendervalueList($rem)); } } public function validateTransactions($object, array $xactions) { $errors = array(); $valid_attributes = array( 'generated' => true, ); foreach ($xactions as $xaction) { $new = $xaction->getNewValue(); foreach ($new as $attribute) { if (isset($valid_attributes[$attribute])) { continue; } $errors[] = $this->newInvalidError( pht( 'Changeset attribute "%s" is not valid. Valid changeset '. 'attributes are: %s.', $attribute, implode(', ', array_keys($valid_attributes))), $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/owners/xaction/PhabricatorOwnersPackageDescriptionTransaction.php
src/applications/owners/xaction/PhabricatorOwnersPackageDescriptionTransaction.php
<?php final class PhabricatorOwnersPackageDescriptionTransaction extends PhabricatorOwnersPackageTransactionType { const TRANSACTIONTYPE = 'owners.description'; public function generateOldValue($object) { return $object->getDescription(); } public function applyInternalEffects($object, $value) { $object->setDescription($value); } public function getTitle() { return pht( '%s updated the description for this package.', $this->renderAuthor()); } public function getMailDiffSectionHeader() { return pht('CHANGES TO PACKAGE DESCRIPTION'); } public function newChangeDetailView() { return id(new PhabricatorApplicationTransactionTextDiffDetailView()) ->setViewer($this->getViewer()) ->setOldText($this->getOldValue()) ->setNewText($this->getNewValue()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/xaction/PhabricatorOwnersPackagePrimaryTransaction.php
src/applications/owners/xaction/PhabricatorOwnersPackagePrimaryTransaction.php
<?php /** * @deprecated */ final class PhabricatorOwnersPackagePrimaryTransaction extends PhabricatorOwnersPackageTransactionType { const TRANSACTIONTYPE = 'owners.primary'; public function shouldHide() { 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/owners/xaction/PhabricatorOwnersPackageNameTransaction.php
src/applications/owners/xaction/PhabricatorOwnersPackageNameTransaction.php
<?php final class PhabricatorOwnersPackageNameTransaction extends PhabricatorOwnersPackageTransactionType { const TRANSACTIONTYPE = 'owners.name'; public function generateOldValue($object) { return $object->getName(); } public function validateTransactions($object, array $xactions) { $errors = array(); $missing = $this->isEmptyTextTransaction( $object->getName(), $xactions); if ($missing) { $errors[] = $this->newRequiredError( pht('Package name is required.'), nonempty(last($xactions), null)); } foreach ($xactions as $xaction) { $new = $xaction->getNewValue(); if (preg_match('([,!])', $new)) { $errors[] = $this->newInvalidError( pht( 'Package names may not contain commas (",") or exclamation '. 'marks ("!"). These characters are ambiguous when package '. 'names are parsed from the command line.'), $xaction); } } return $errors; } public function applyInternalEffects($object, $value) { $object->setName($value); } public function getTitle() { return pht( '%s renamed this package 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/owners/xaction/PhabricatorOwnersPackageTransactionType.php
src/applications/owners/xaction/PhabricatorOwnersPackageTransactionType.php
<?php abstract class PhabricatorOwnersPackageTransactionType 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/owners/xaction/PhabricatorOwnersPackageStatusTransaction.php
src/applications/owners/xaction/PhabricatorOwnersPackageStatusTransaction.php
<?php final class PhabricatorOwnersPackageStatusTransaction extends PhabricatorOwnersPackageTransactionType { const TRANSACTIONTYPE = 'owners.status'; public function generateOldValue($object) { return $object->getStatus(); } public function applyInternalEffects($object, $value) { $object->setStatus($value); } public function getTitle() { $new = $this->getNewValue(); if ($new == PhabricatorOwnersPackage::STATUS_ACTIVE) { return pht( '%s activated this package.', $this->renderAuthor()); } else if ($new == PhabricatorOwnersPackage::STATUS_ARCHIVED) { return pht( '%s archived this package.', $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/owners/searchfield/PhabricatorOwnersSearchField.php
src/applications/owners/searchfield/PhabricatorOwnersSearchField.php
<?php final class PhabricatorOwnersSearchField extends PhabricatorSearchTokenizerField { protected function getDefaultValue() { return array(); } protected function getValueFromRequest(AphrontRequest $request, $key) { return $this->getUsersFromRequest($request, $key); } protected function newDatasource() { return new PhabricatorPeopleOwnerDatasource(); } protected function newConduitParameterType() { return new ConduitUserListParameterType(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/application/PhabricatorOwnersApplication.php
src/applications/owners/application/PhabricatorOwnersApplication.php
<?php final class PhabricatorOwnersApplication extends PhabricatorApplication { public function getName() { return pht('Owners'); } public function getBaseURI() { return '/owners/'; } public function getIcon() { return 'fa-gift'; } public function getShortDescription() { return pht('Own Source Code'); } public function getTitleGlyph() { return "\xE2\x98\x81"; } public function getHelpDocumentationArticles(PhabricatorUser $viewer) { return array( array( 'name' => pht('Owners User Guide'), 'href' => PhabricatorEnv::getDoclink('Owners User Guide'), ), ); } public function getFlavorText() { return pht('Adopt today!'); } public function getApplicationGroup() { return self::GROUP_UTILITIES; } public function getRemarkupRules() { return array( new PhabricatorOwnersPackageRemarkupRule(), ); } public function getRoutes() { return array( '/owners/' => array( '(?:query/(?P<queryKey>[^/]+)/)?' => 'PhabricatorOwnersListController', 'new/' => 'PhabricatorOwnersEditController', 'package/(?P<id>[1-9]\d*)/' => 'PhabricatorOwnersDetailController', 'archive/(?P<id>[1-9]\d*)/' => 'PhabricatorOwnersArchiveController', 'paths/(?P<id>[1-9]\d*)/' => 'PhabricatorOwnersPathsController', $this->getEditRoutePattern('edit/') => 'PhabricatorOwnersEditController', ), ); } protected function getCustomCapabilities() { return array( PhabricatorOwnersDefaultViewCapability::CAPABILITY => array( 'caption' => pht('Default view policy for newly created packages.'), 'template' => PhabricatorOwnersPackagePHIDType::TYPECONST, 'capability' => PhabricatorPolicyCapability::CAN_VIEW, ), PhabricatorOwnersDefaultEditCapability::CAPABILITY => array( 'caption' => pht('Default edit policy for newly created packages.'), 'template' => PhabricatorOwnersPackagePHIDType::TYPECONST, 'capability' => PhabricatorPolicyCapability::CAN_EDIT, ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/lipsum/PhabricatorOwnersPackageTestDataGenerator.php
src/applications/owners/lipsum/PhabricatorOwnersPackageTestDataGenerator.php
<?php final class PhabricatorOwnersPackageTestDataGenerator extends PhabricatorTestDataGenerator { const GENERATORKEY = 'owners'; public function getGeneratorName() { return pht('Owners Packages'); } public function generateObject() { $author = $this->loadRandomUser(); $name = id(new PhabricatorOwnersPackageContextFreeGrammar()) ->generate(); switch ($this->roll(1, 4)) { case 1: case 2: // Most packages own only one path. $path_count = 1; break; case 3: // Some packages own a few paths. $path_count = mt_rand(1, 4); break; case 4: // Some packages own a very large number of paths. $path_count = mt_rand(1, 1024); break; } $xactions = array(); $xactions[] = array( 'type' => 'name', 'value' => $name, ); $xactions[] = array( 'type' => 'owners', 'value' => array($author->getPHID()), ); $dominion = PhabricatorOwnersPackage::getDominionOptionsMap(); $dominion = array_rand($dominion); $xactions[] = array( 'type' => 'dominion', 'value' => $dominion, ); $paths = id(new PhabricatorOwnersPathContextFreeGrammar()) ->generateSeveral($path_count, "\n"); $paths = explode("\n", $paths); $paths = array_unique($paths); $repository_phid = $this->loadOneRandom('PhabricatorRepository') ->getPHID(); $paths_value = array(); foreach ($paths as $path) { $paths_value[] = array( 'repositoryPHID' => $repository_phid, 'path' => $path, // Excluded paths are relatively rare. 'excluded' => (mt_rand(1, 10) == 1), ); } $xactions[] = array( 'type' => 'paths.set', 'value' => $paths_value, ); $params = array( 'transactions' => $xactions, ); $result = id(new ConduitCall('owners.edit', $params)) ->setUser($author) ->execute(); return $result['object']['phid']; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/lipsum/PhabricatorOwnersPackageContextFreeGrammar.php
src/applications/owners/lipsum/PhabricatorOwnersPackageContextFreeGrammar.php
<?php final class PhabricatorOwnersPackageContextFreeGrammar extends PhutilContextFreeGrammar { protected function getRules() { return array( 'start' => array( '[package]', ), 'package' => array( '[adjective] [noun]', '[adjective] [noun]', '[adjective] [noun]', '[adjective] [noun]', '[adjective] [adjective] [noun]', '[adjective] [noun] [noun]', '[adjective] [adjective] [noun] [noun]', ), 'adjective' => array( 'Temporary', 'Backend', 'External', 'Emergency', 'Applied', 'Advanced', 'Experimental', 'Logging', 'Test', 'Network', 'Ephemeral', 'Clustered', 'Mining', 'Core', 'Remote', ), 'noun' => array( 'Support', 'Services', 'Infrastructure', 'Mail', 'Security', 'Application', 'Microservices', 'Monoservices', 'Megaservices', 'API', 'Storage', 'Records', 'Package', 'Directories', 'Library', 'Concern', 'Cluster', 'Engine', ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/lipsum/PhabricatorOwnersPathContextFreeGrammar.php
src/applications/owners/lipsum/PhabricatorOwnersPathContextFreeGrammar.php
<?php final class PhabricatorOwnersPathContextFreeGrammar extends PhutilContextFreeGrammar { protected function getRules() { return array( 'start' => array( '[path]', ), 'path' => array( '/', '/[directories]', ), 'directories' => array( '[directory-name]', '[directories][directory-name]', ), 'directory-name' => array( '[directory-part]/', ), 'directory-part' => array( 'src', 'doc', 'bin', 'tmp', 'log', 'bak', 'applications', 'var', 'home', 'user', 'lib', 'tests', 'webroot', 'externals', 'third-party', 'libraries', 'config', 'media', 'resources', 'support', 'scripts', ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/phid/PhabricatorOwnersPackagePHIDType.php
src/applications/owners/phid/PhabricatorOwnersPackagePHIDType.php
<?php final class PhabricatorOwnersPackagePHIDType extends PhabricatorPHIDType { const TYPECONST = 'OPKG'; public function getTypeName() { return pht('Owners Package'); } public function getTypeIcon() { return 'fa-shopping-bag'; } public function newObject() { return new PhabricatorOwnersPackage(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorOwnersApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorOwnersPackageQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $package = $objects[$phid]; $monogram = $package->getMonogram(); $name = $package->getName(); $id = $package->getID(); $uri = $package->getURI(); $handle ->setName($monogram) ->setFullName("{$monogram}: {$name}") ->setCommandLineObjectName("{$monogram} {$name}") ->setMailStampName($monogram) ->setURI($uri); if ($package->isArchived()) { $handle->setStatus(PhabricatorObjectHandle::STATUS_CLOSED); } } } public function canLoadNamedObject($name) { return preg_match('/^O\d*[1-9]\d*$/i', $name); } public function loadNamedObjects( PhabricatorObjectQuery $query, array $names) { $id_map = array(); foreach ($names as $name) { $id = (int)substr($name, 1); $id_map[$id][] = $name; } $objects = id(new PhabricatorOwnersPackageQuery()) ->setViewer($query->getViewer()) ->withIDs(array_keys($id_map)) ->execute(); $results = array(); foreach ($objects as $id => $object) { foreach (idx($id_map, $id, array()) as $name) { $results[$name] = $object; } } 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/owners/config/PhabricatorOwnersConfigOptions.php
src/applications/owners/config/PhabricatorOwnersConfigOptions.php
<?php final class PhabricatorOwnersConfigOptions extends PhabricatorApplicationConfigOptions { public function getName() { return pht('Owners'); } public function getDescription() { return pht('Configure Owners.'); } public function getIcon() { return 'fa-gift'; } public function getGroup() { return 'apps'; } public function getOptions() { $custom_field_type = 'custom:PhabricatorCustomFieldConfigOptionType'; $default_fields = array(); $field_base_class = id(new PhabricatorOwnersPackage()) ->getCustomFieldBaseClass(); $fields_example = array( 'mycompany:lore' => array( 'name' => pht('Package Lore'), 'type' => 'remarkup', 'caption' => pht('Tales of adventure for this package.'), ), ); $fields_example = id(new PhutilJSON())->encodeFormatted($fields_example); return array( $this->newOption('owners.fields', $custom_field_type, $default_fields) ->setCustomData($field_base_class) ->setDescription(pht('Select and reorder package fields.')), $this->newOption('owners.custom-field-definitions', 'wild', array()) ->setSummary(pht('Custom Owners fields.')) ->setDescription( pht( 'Map of custom fields for Owners packages. For details on '. 'adding custom fields to Owners, see "Configuring Custom '. 'Fields" in the documentation.')) ->addExample($fields_example, pht('Valid Setting')), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/conduit/OwnersEditConduitAPIMethod.php
src/applications/owners/conduit/OwnersEditConduitAPIMethod.php
<?php final class OwnersEditConduitAPIMethod extends PhabricatorEditEngineAPIMethod { public function getAPIMethodName() { return 'owners.edit'; } public function newEditEngine() { return new PhabricatorOwnersPackageEditEngine(); } public function getMethodSummary() { return pht( 'Apply transactions to create a new Owners package or edit an existing '. 'one.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/conduit/OwnersConduitAPIMethod.php
src/applications/owners/conduit/OwnersConduitAPIMethod.php
<?php abstract class OwnersConduitAPIMethod extends ConduitAPIMethod { final public function getApplication() { return PhabricatorApplication::getByClass('PhabricatorOwnersApplication'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/conduit/OwnersSearchConduitAPIMethod.php
src/applications/owners/conduit/OwnersSearchConduitAPIMethod.php
<?php final class OwnersSearchConduitAPIMethod extends PhabricatorSearchEngineAPIMethod { public function getAPIMethodName() { return 'owners.search'; } public function newSearchEngine() { return new PhabricatorOwnersPackageSearchEngine(); } public function getMethodSummary() { return pht('Read information about Owners packages.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/search/PhabricatorOwnersPackageFulltextEngine.php
src/applications/owners/search/PhabricatorOwnersPackageFulltextEngine.php
<?php final class PhabricatorOwnersPackageFulltextEngine extends PhabricatorFulltextEngine { protected function buildAbstractDocument( PhabricatorSearchAbstractDocument $document, $object) { $package = $object; $document->setDocumentTitle($package->getName()); // TODO: These are bogus, but not currently stored on packages. $document->setDocumentCreated(PhabricatorTime::getNow()); $document->setDocumentModified(PhabricatorTime::getNow()); $document->addRelationship( $package->isArchived() ? PhabricatorSearchRelationship::RELATIONSHIP_CLOSED : PhabricatorSearchRelationship::RELATIONSHIP_OPEN, $package->getPHID(), PhabricatorOwnersPackagePHIDType::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/owners/search/PhabricatorOwnersPackageFerretEngine.php
src/applications/owners/search/PhabricatorOwnersPackageFerretEngine.php
<?php final class PhabricatorOwnersPackageFerretEngine extends PhabricatorFerretEngine { public function getApplicationName() { return 'owners'; } public function getScopeName() { return 'package'; } public function newSearchEngine() { return new PhabricatorOwnersPackageSearchEngine(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/typeahead/PhabricatorOwnersPackageOwnerDatasource.php
src/applications/owners/typeahead/PhabricatorOwnersPackageOwnerDatasource.php
<?php final class PhabricatorOwnersPackageOwnerDatasource extends PhabricatorTypeaheadCompositeDatasource { public function getBrowseTitle() { return pht('Browse Packages by Owner'); } public function getPlaceholderText() { return pht('Type packages(<user>) or packages(<project>)...'); } public function getDatasourceApplicationClass() { return 'PhabricatorOwnersApplication'; } public function getComponentDatasources() { return array( new PhabricatorPeopleDatasource(), new PhabricatorProjectDatasource(), ); } public function getDatasourceFunctions() { return array( 'packages' => array( 'name' => pht('Packages: ...'), 'arguments' => pht('owner'), 'summary' => pht("Find results in any of an owner's packages."), 'description' => pht( "This function allows you to find results associated with any ". "of the packages a specified user or project is an owner of. ". "For example, this will find results associated with all of ". "the projects `%s` owns:\n\n%s\n\n", 'alincoln', '> packages(alincoln)'), ), ); } protected function didLoadResults(array $results) { foreach ($results as $result) { $result ->setColor(null) ->setTokenType(PhabricatorTypeaheadTokenView::TYPE_FUNCTION) ->setIcon('fa-asterisk') ->setPHID('packages('.$result->getPHID().')') ->setDisplayName(pht('Packages: %s', $result->getDisplayName())) ->setName($result->getName().' packages'); } return $results; } protected function evaluateFunction($function, array $argv_list) { $phids = array(); foreach ($argv_list as $argv) { $phids[] = head($argv); } $phids = $this->resolvePHIDs($phids); $owner_phids = array(); foreach ($phids as $key => $phid) { switch (phid_get_type($phid)) { case PhabricatorPeopleUserPHIDType::TYPECONST: case PhabricatorProjectProjectPHIDType::TYPECONST: $owner_phids[] = $phid; unset($phids[$key]); break; } } if ($owner_phids) { $packages = id(new PhabricatorOwnersPackageQuery()) ->setViewer($this->getViewer()) ->withOwnerPHIDs($owner_phids) ->execute(); foreach ($packages as $package) { $phids[] = $package->getPHID(); } } return $phids; } public function renderFunctionTokens($function, array $argv_list) { $phids = array(); foreach ($argv_list as $argv) { $phids[] = head($argv); } $phids = $this->resolvePHIDs($phids); $tokens = $this->renderTokens($phids); foreach ($tokens as $token) { $token->setColor(null); if ($token->isInvalid()) { $token ->setValue(pht('Packages: Invalid Owner')); } else { $token ->setIcon('fa-asterisk') ->setTokenType(PhabricatorTypeaheadTokenView::TYPE_FUNCTION) ->setKey('packages('.$token->getKey().')') ->setValue(pht('Packages: %s', $token->getValue())); } } return $tokens; } private function resolvePHIDs(array $phids) { // TODO: It would be nice for this to handle `packages(#project)` from a // query string or eventually via Conduit. This could also share code with // PhabricatorProjectLogicalUserDatasource. $usernames = array(); foreach ($phids as $key => $phid) { switch (phid_get_type($phid)) { case PhabricatorPeopleUserPHIDType::TYPECONST: case PhabricatorProjectProjectPHIDType::TYPECONST: break; default: $usernames[$key] = $phid; break; } } if ($usernames) { $users = id(new PhabricatorPeopleQuery()) ->setViewer($this->getViewer()) ->withUsernames($usernames) ->execute(); $users = mpull($users, null, 'getUsername'); foreach ($usernames as $key => $username) { $user = idx($users, $username); if ($user) { $phids[$key] = $user->getPHID(); } } } return $phids; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/typeahead/PhabricatorOwnersPackageDatasource.php
src/applications/owners/typeahead/PhabricatorOwnersPackageDatasource.php
<?php final class PhabricatorOwnersPackageDatasource extends PhabricatorTypeaheadDatasource { public function getBrowseTitle() { return pht('Browse Packages'); } public function getPlaceholderText() { return pht('Type a package name...'); } public function getDatasourceApplicationClass() { return 'PhabricatorOwnersApplication'; } public function loadResults() { $viewer = $this->getViewer(); $raw_query = $this->getRawQuery(); $results = array(); $query = id(new PhabricatorOwnersPackageQuery()) ->setOrder('name'); if ($raw_query !== null && strlen($raw_query)) { // If the user is querying by monogram explicitly, like "O123", do an ID // search. Otherwise, do an ngram substring search. if (preg_match('/^[oO]\d+\z/', $raw_query)) { $id = trim($raw_query, 'oO'); $id = (int)$id; $query->withIDs(array($id)); } else { $query->withNameNgrams($raw_query); } } $packages = $this->executeQuery($query); foreach ($packages as $package) { $name = $package->getName(); $monogram = $package->getMonogram(); $result = id(new PhabricatorTypeaheadResult()) ->setName("{$monogram}: {$name}") ->setURI($package->getURI()) ->setPHID($package->getPHID()); if ($package->isArchived()) { $result->setClosed(pht('Archived')); } $results[] = $result; } return $this->filterResultsAgainstTokens($results); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/typeahead/PhabricatorOwnersPackageFunctionDatasource.php
src/applications/owners/typeahead/PhabricatorOwnersPackageFunctionDatasource.php
<?php final class PhabricatorOwnersPackageFunctionDatasource extends PhabricatorTypeaheadCompositeDatasource { public function getBrowseTitle() { return pht('Browse Packages'); } public function getPlaceholderText() { return pht('Type a package name or function...'); } public function getDatasourceApplicationClass() { return 'PhabricatorOwnersApplication'; } public function getComponentDatasources() { return array( new PhabricatorOwnersPackageDatasource(), new PhabricatorOwnersPackageOwnerDatasource(), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/capability/PhabricatorOwnersDefaultEditCapability.php
src/applications/owners/capability/PhabricatorOwnersDefaultEditCapability.php
<?php final class PhabricatorOwnersDefaultEditCapability extends PhabricatorPolicyCapability { const CAPABILITY = 'owners.default.edit'; public function getCapabilityName() { return pht('Default Edit Policy'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/capability/PhabricatorOwnersDefaultViewCapability.php
src/applications/owners/capability/PhabricatorOwnersDefaultViewCapability.php
<?php final class PhabricatorOwnersDefaultViewCapability extends PhabricatorPolicyCapability { const CAPABILITY = 'owners.default.view'; public function getCapabilityName() { return pht('Default View Policy'); } public function shouldAllowPublicPolicySetting() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/remarkup/PhabricatorOwnersPackageRemarkupRule.php
src/applications/owners/remarkup/PhabricatorOwnersPackageRemarkupRule.php
<?php final class PhabricatorOwnersPackageRemarkupRule extends PhabricatorObjectRemarkupRule { protected function getObjectNamePrefix() { return 'O'; } protected function loadObjects(array $ids) { $viewer = $this->getEngine()->getConfig('viewer'); return id(new PhabricatorOwnersPackageQuery()) ->setViewer($viewer) ->withIDs($ids) ->execute(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/owners/constants/PhabricatorOwnersAuditRule.php
src/applications/owners/constants/PhabricatorOwnersAuditRule.php
<?php final class PhabricatorOwnersAuditRule extends Phobject { const AUDITING_NONE = 'none'; const AUDITING_NO_OWNER = 'audit'; const AUDITING_UNREVIEWED = 'unreviewed'; const AUDITING_NO_OWNER_AND_UNREVIEWED = 'uninvolved-unreviewed'; const AUDITING_ALL = 'all'; private $key; private $spec; public static function newFromState($key) { $specs = self::newSpecifications(); $spec = idx($specs, $key, array()); $rule = new self(); $rule->key = $key; $rule->spec = $spec; return $rule; } public function getKey() { return $this->key; } public function getDisplayName() { return idx($this->spec, 'name', $this->key); } public function getIconIcon() { return idx($this->spec, 'icon.icon'); } public static function newSelectControlMap() { $specs = self::newSpecifications(); return ipull($specs, 'name'); } public static function getStorageValueFromAPIValue($value) { $specs = self::newSpecifications(); $map = array(); foreach ($specs as $key => $spec) { $deprecated = idx($spec, 'deprecated', array()); if (isset($deprecated[$value])) { return $key; } } return $value; } public static function getModernValueMap() { $specs = self::newSpecifications(); $map = array(); foreach ($specs as $key => $spec) { $map[$key] = pht('"%s"', $key); } return $map; } public static function getDeprecatedValueMap() { $specs = self::newSpecifications(); $map = array(); foreach ($specs as $key => $spec) { $deprecated_map = idx($spec, 'deprecated', array()); foreach ($deprecated_map as $deprecated_key => $label) { $map[$deprecated_key] = $label; } } return $map; } private static function newSpecifications() { return array( self::AUDITING_NONE => array( 'name' => pht('No Auditing'), 'icon.icon' => 'fa-ban', 'deprecated' => array( '' => pht('"" (empty string)'), '0' => '"0"', ), ), self::AUDITING_UNREVIEWED => array( 'name' => pht('Audit Unreviewed Commits'), 'icon.icon' => 'fa-check', ), self::AUDITING_NO_OWNER => array( 'name' => pht('Audit Commits With No Owner Involvement'), 'icon.icon' => 'fa-check', 'deprecated' => array( '1' => '"1"', ), ), self::AUDITING_NO_OWNER_AND_UNREVIEWED => array( 'name' => pht( 'Audit Unreviewed Commits and Commits With No Owner Involvement'), 'icon.icon' => 'fa-check', ), self::AUDITING_ALL => array( 'name' => pht('Audit All Commits'), 'icon.icon' => 'fa-check', ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/DifferentialGetWorkingCopy.php
src/applications/differential/DifferentialGetWorkingCopy.php
<?php /** * Can't find a good place for this, so I'm putting it in the most notably * wrong place. */ final class DifferentialGetWorkingCopy extends Phobject { /** * Creates and/or cleans a workspace for the requested repo. * * return ArcanistGitAPI */ public static function getCleanGitWorkspace( PhabricatorRepository $repo) { $origin_path = $repo->getLocalPath(); $path = rtrim($origin_path, '/'); $path = $path.'__workspace'; if (!Filesystem::pathExists($path)) { $repo->execxLocalCommand( 'clone -- file://%s %s', $origin_path, $path); if (!$repo->isHosted()) { id(new ArcanistGitAPI($path))->execxLocal( 'remote set-url origin %s', $repo->getRemoteURI()); } } $workspace = new ArcanistGitAPI($path); $workspace->execxLocal('clean -f -d'); $workspace->execxLocal('checkout master'); $workspace->execxLocal('fetch'); $workspace->execxLocal('reset --hard origin/master'); $workspace->reloadWorkingCopy(); return $workspace; } /** * Creates and/or cleans a workspace for the requested repo. * * return ArcanistMercurialAPI */ public static function getCleanMercurialWorkspace( PhabricatorRepository $repo) { $origin_path = $repo->getLocalPath(); $path = rtrim($origin_path, '/'); $path = $path.'__workspace'; if (!Filesystem::pathExists($path)) { $repo->execxLocalCommand( 'clone -- file://%s %s', $origin_path, $path); } $workspace = new ArcanistMercurialAPI($path); $workspace->execxLocal('pull'); $workspace->execxLocal('update --clean default'); $workspace->reloadWorkingCopy(); return $workspace; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/controller/DifferentialRevisionInlinesController.php
src/applications/differential/controller/DifferentialRevisionInlinesController.php
<?php final class DifferentialRevisionInlinesController extends DifferentialController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $id = $request->getURIData('id'); $revision = id(new DifferentialRevisionQuery()) ->withIDs(array($id)) ->setViewer($viewer) ->needDiffIDs(true) ->executeOne(); if (!$revision) { return new Aphront404Response(); } $revision_monogram = $revision->getMonogram(); $revision_uri = $revision->getURI(); $revision_title = $revision->getTitle(); $inlines = id(new DifferentialDiffInlineCommentQuery()) ->setViewer($viewer) ->withRevisionPHIDs(array($revision->getPHID())) ->withPublishedComments(true) ->execute(); $inlines = mpull($inlines, 'newInlineCommentObject'); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb($revision_monogram, $revision_uri); $crumbs->addTextCrumb(pht('Inline Comments')); $crumbs->setBorder(true); $content = $this->renderInlineTable($revision, $inlines); $header = $this->buildHeader($revision); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter($content); return $this->newPage() ->setTitle( array( "{$revision_monogram} {$revision_title}", pht('Inlines'), )) ->setCrumbs($crumbs) ->appendChild($view); } private function buildHeader(DifferentialRevision $revision) { $viewer = $this->getViewer(); $button = id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-chevron-left') ->setHref($revision->getURI()) ->setText(pht('Back to Revision')); return id(new PHUIHeaderView()) ->setHeader($revision->getTitle()) ->setUser($viewer) ->setHeaderIcon('fa-cog') ->addActionLink($button); } private function renderInlineTable( DifferentialRevision $revision, array $inlines) { $viewer = $this->getViewer(); $inlines = id(new PHUIDiffInlineThreader()) ->reorderAndThreadCommments($inlines); $handle_phids = array(); $changeset_ids = array(); foreach ($inlines as $inline) { $handle_phids[] = $inline->getAuthorPHID(); $changeset_ids[] = $inline->getChangesetID(); } $handles = $viewer->loadHandles($handle_phids); $handles = iterator_to_array($handles); if ($changeset_ids) { $changesets = id(new DifferentialChangesetQuery()) ->setViewer($viewer) ->withIDs($changeset_ids) ->execute(); $changesets = mpull($changesets, null, 'getID'); } else { $changesets = array(); } $current_changeset = head($revision->getDiffIDs()); $rows = array(); foreach ($inlines as $inline) { $status_icons = array(); $c_id = $inline->getChangesetID(); $d_id = $changesets[$c_id]->getDiffID(); if ($d_id == $current_changeset) { $diff_id = phutil_tag('strong', array(), pht('Current')); } else { $diff_id = pht('Diff %d', $d_id); } $reviewer = $handles[$inline->getAuthorPHID()]->renderLink(); $now = PhabricatorTime::getNow(); $then = $inline->getDateModified(); $datetime = phutil_format_relative_time($now - $then); $comment_href = $revision->getURI().'#inline-'.$inline->getID(); $comment = phutil_tag( 'a', array( 'href' => $comment_href, ), $inline->getContent()); $state = $inline->getFixedState(); if ($state == PhabricatorInlineComment::STATE_DONE) { $status_icons[] = id(new PHUIIconView()) ->setIcon('fa-check green') ->addClass('mmr'); } else if ($inline->getReplyToCommentPHID() && $inline->getAuthorPHID() == $revision->getAuthorPHID()) { $status_icons[] = id(new PHUIIconView()) ->setIcon('fa-commenting-o blue') ->addClass('mmr'); } else { $status_icons[] = id(new PHUIIconView()) ->setIcon('fa-circle-o grey') ->addClass('mmr'); } if ($inline->getReplyToCommentPHID()) { $reply_icon = id(new PHUIIconView()) ->setIcon('fa-reply mmr darkgrey'); $comment = array($reply_icon, $comment); } $rows[] = array( $diff_id, $status_icons, $reviewer, AphrontTableView::renderSingleDisplayLine($comment), $datetime, ); } $table = new AphrontTableView($rows); $table->setHeaders( array( pht('Diff'), pht('Status'), pht('Reviewer'), pht('Comment'), pht('Created'), )); $table->setColumnClasses( array( '', '', '', 'wide', 'right', )); $table->setColumnVisibility( array( true, true, true, true, true, )); return id(new PHUIObjectBoxView()) ->setHeaderText(pht('Inline Comments')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setTable($table); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/controller/DifferentialRevisionListController.php
src/applications/differential/controller/DifferentialRevisionListController.php
<?php final class DifferentialRevisionListController extends DifferentialController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $controller = id(new PhabricatorApplicationSearchController()) ->setQueryKey($request->getURIData('queryKey')) ->setSearchEngine(new DifferentialRevisionSearchEngine()) ->setNavigation($this->buildSideNavView()); return $this->delegateToController($controller); } protected function buildApplicationCrumbs() { $crumbs = parent::buildApplicationCrumbs(); $crumbs->addAction( id(new PHUIListItemView()) ->setHref($this->getApplicationURI('/diff/create/')) ->setName(pht('Create Diff')) ->setIcon('fa-plus-square')); return $crumbs; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/controller/DifferentialController.php
src/applications/differential/controller/DifferentialController.php
<?php abstract class DifferentialController extends PhabricatorController { private $packageChangesetMap; private $pathPackageMap; private $authorityPackages; public function buildSideNavView($for_app = false) { $viewer = $this->getRequest()->getUser(); $nav = new AphrontSideNavFilterView(); $nav->setBaseURI(new PhutilURI($this->getApplicationURI())); id(new DifferentialRevisionSearchEngine()) ->setViewer($viewer) ->addNavigationItems($nav->getMenu()); $nav->selectFilter(null); return $nav; } public function buildApplicationMenu() { return $this->buildSideNavView(true)->getMenu(); } protected function buildPackageMaps(array $changesets) { assert_instances_of($changesets, 'DifferentialChangeset'); $this->packageChangesetMap = array(); $this->pathPackageMap = array(); $this->authorityPackages = array(); if (!$changesets) { return; } $viewer = $this->getViewer(); $have_owners = PhabricatorApplication::isClassInstalledForViewer( 'PhabricatorOwnersApplication', $viewer); if (!$have_owners) { return; } $changeset = head($changesets); $diff = $changeset->getDiff(); $repository_phid = $diff->getRepositoryPHID(); if (!$repository_phid) { return; } if ($viewer->getPHID()) { $packages = id(new PhabricatorOwnersPackageQuery()) ->setViewer($viewer) ->withStatuses(array(PhabricatorOwnersPackage::STATUS_ACTIVE)) ->withAuthorityPHIDs(array($viewer->getPHID())) ->execute(); $this->authorityPackages = $packages; } $paths = mpull($changesets, 'getOwnersFilename'); $control_query = id(new PhabricatorOwnersPackageQuery()) ->setViewer($viewer) ->withStatuses(array(PhabricatorOwnersPackage::STATUS_ACTIVE)) ->withControl($repository_phid, $paths); $control_query->execute(); foreach ($changesets as $changeset) { $changeset_path = $changeset->getOwnersFilename(); $packages = $control_query->getControllingPackagesForPath( $repository_phid, $changeset_path); // If this particular changeset is generated code and the package does // not match generated code, remove it from the list. if ($changeset->isGeneratedChangeset()) { foreach ($packages as $key => $package) { if ($package->getMustMatchUngeneratedPaths()) { unset($packages[$key]); } } } $this->pathPackageMap[$changeset_path] = $packages; foreach ($packages as $package) { $this->packageChangesetMap[$package->getPHID()][] = $changeset; } } } protected function getAuthorityPackages() { if ($this->authorityPackages === null) { throw new PhutilInvalidStateException('buildPackageMaps'); } return $this->authorityPackages; } protected function getChangesetPackages(DifferentialChangeset $changeset) { if ($this->pathPackageMap === null) { throw new PhutilInvalidStateException('buildPackageMaps'); } $path = $changeset->getOwnersFilename(); return idx($this->pathPackageMap, $path, array()); } protected function getPackageChangesets($package_phid) { if ($this->packageChangesetMap === null) { throw new PhutilInvalidStateException('buildPackageMaps'); } return idx($this->packageChangesetMap, $package_phid, array()); } protected function buildTableOfContents( array $changesets, array $visible_changesets, array $coverage) { $viewer = $this->getViewer(); $toc_view = id(new PHUIDiffTableOfContentsListView()) ->setViewer($viewer) ->setBare(true) ->setAuthorityPackages($this->getAuthorityPackages()); foreach ($changesets as $changeset_id => $changeset) { $is_visible = isset($visible_changesets[$changeset_id]); $anchor = $changeset->getAnchorName(); $filename = $changeset->getFilename(); $coverage_id = 'differential-mcoverage-'.md5($filename); $item = id(new PHUIDiffTableOfContentsItemView()) ->setChangeset($changeset) ->setIsVisible($is_visible) ->setAnchor($anchor) ->setCoverage(idx($coverage, $filename)) ->setCoverageID($coverage_id); $packages = $this->getChangesetPackages($changeset); $item->setPackages($packages); $toc_view->addItem($item); } return $toc_view; } protected function loadDiffProperties(array $diffs) { $diffs = mpull($diffs, null, 'getID'); $properties = id(new DifferentialDiffProperty())->loadAllWhere( 'diffID IN (%Ld)', array_keys($diffs)); $properties = mgroup($properties, 'getDiffID'); foreach ($diffs as $id => $diff) { $values = idx($properties, $id, array()); $values = mpull($values, 'getData', 'getName'); $diff->attachDiffProperties($values); } } protected function loadHarbormasterData(array $diffs) { $viewer = $this->getViewer(); $diffs = mpull($diffs, null, 'getPHID'); $buildables = id(new HarbormasterBuildableQuery()) ->setViewer($viewer) ->withBuildablePHIDs(array_keys($diffs)) ->withManualBuildables(false) ->needBuilds(true) ->needTargets(true) ->execute(); $buildables = mpull($buildables, null, 'getBuildablePHID'); foreach ($diffs as $phid => $diff) { $diff->attachBuildable(idx($buildables, $phid)); } $target_map = array(); foreach ($diffs as $phid => $diff) { $target_map[$phid] = $diff->getBuildTargetPHIDs(); } $all_target_phids = array_mergev($target_map); if ($all_target_phids) { $unit_messages = id(new HarbormasterBuildUnitMessageQuery()) ->setViewer($viewer) ->withBuildTargetPHIDs($all_target_phids) ->execute(); $unit_messages = mgroup($unit_messages, 'getBuildTargetPHID'); } else { $unit_messages = array(); } foreach ($diffs as $phid => $diff) { $target_phids = idx($target_map, $phid, array()); $messages = array_select_keys($unit_messages, $target_phids); $messages = array_mergev($messages); $diff->attachUnitMessages($messages); } // For diffs with no messages, look for legacy unit messages stored on the // diff itself. foreach ($diffs as $phid => $diff) { if ($diff->getUnitMessages()) { continue; } if (!$diff->hasDiffProperty('arc:unit')) { continue; } $legacy_messages = $diff->getProperty('arc:unit'); if (!$legacy_messages) { continue; } // Show the top 100 legacy lint messages. Previously, we showed some // by default and let the user toggle the rest. With modern messages, // we can send the user to the Harbormaster detail page. Just show // "a lot" of messages in legacy cases to try to strike a balance // between implementation simplicity and compatibility. $legacy_messages = array_slice($legacy_messages, 0, 100); $messages = array(); foreach ($legacy_messages as $message) { $messages[] = HarbormasterBuildUnitMessage::newFromDictionary( new HarbormasterBuildTarget(), $this->getModernUnitMessageDictionary($message)); } $diff->attachUnitMessages($messages); } } private function getModernUnitMessageDictionary(array $map) { // Strip out `null` values to satisfy stricter typechecks. foreach ($map as $key => $value) { if ($value === null) { unset($map[$key]); } } // Cast duration to a float since it used to be a string in some // cases. if (isset($map['duration'])) { $map['duration'] = (double)$map['duration']; } return $map; } protected function getDiffTabLabels(array $diffs) { // Make sure we're only going to render unique diffs. $diffs = mpull($diffs, null, 'getID'); $labels = array(pht('Left'), pht('Right')); $results = array(); foreach ($diffs as $diff) { if (count($diffs) == 2) { $label = array_shift($labels); $label = pht('%s (Diff %d)', $label, $diff->getID()); } else { $label = pht('Diff %d', $diff->getID()); } $results[] = array( $label, $diff, ); } 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/differential/controller/DifferentialRevisionViewController.php
src/applications/differential/controller/DifferentialRevisionViewController.php
<?php final class DifferentialRevisionViewController extends DifferentialController { private $revisionID; private $changesetCount; private $hiddenChangesets; private $warnings = array(); public function shouldAllowPublic() { return true; } public function isLargeDiff() { return ($this->getChangesetCount() > $this->getLargeDiffLimit()); } public function isVeryLargeDiff() { return ($this->getChangesetCount() > $this->getVeryLargeDiffLimit()); } public function getLargeDiffLimit() { return 100; } public function getVeryLargeDiffLimit() { return 1000; } public function getChangesetCount() { if ($this->changesetCount === null) { throw new PhutilInvalidStateException('setChangesetCount'); } return $this->changesetCount; } public function setChangesetCount($count) { $this->changesetCount = $count; return $this; } public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $this->revisionID = $request->getURIData('id'); $viewer_is_anonymous = !$viewer->isLoggedIn(); $revision = id(new DifferentialRevisionQuery()) ->withIDs(array($this->revisionID)) ->setViewer($viewer) ->needReviewers(true) ->needReviewerAuthority(true) ->needCommitPHIDs(true) ->executeOne(); if (!$revision) { return new Aphront404Response(); } $diffs = id(new DifferentialDiffQuery()) ->setViewer($viewer) ->withRevisionIDs(array($this->revisionID)) ->execute(); $diffs = array_reverse($diffs, $preserve_keys = true); if (!$diffs) { throw new Exception( pht('This revision has no diffs. Something has gone quite wrong.')); } $revision->attachActiveDiff(last($diffs)); $diff_vs = $this->getOldDiffID($revision, $diffs); if ($diff_vs instanceof AphrontResponse) { return $diff_vs; } $target_id = $this->getNewDiffID($revision, $diffs); if ($target_id instanceof AphrontResponse) { return $target_id; } $target = $diffs[$target_id]; $target_manual = $target; if (!$target_id) { foreach ($diffs as $diff) { if ($diff->getCreationMethod() != 'commit') { $target_manual = $diff; } } } $repository = null; $repository_phid = $target->getRepositoryPHID(); if ($repository_phid) { if ($repository_phid == $revision->getRepositoryPHID()) { $repository = $revision->getRepository(); } else { $repository = id(new PhabricatorRepositoryQuery()) ->setViewer($viewer) ->withPHIDs(array($repository_phid)) ->executeOne(); } } list($changesets, $vs_map, $vs_changesets, $rendering_references) = $this->loadChangesetsAndVsMap( $target, idx($diffs, $diff_vs), $repository); $this->setChangesetCount(count($rendering_references)); if ($request->getExists('download')) { return $this->buildRawDiffResponse( $revision, $changesets, $vs_changesets, $vs_map, $repository); } $map = $vs_map; if (!$map) { $map = array_fill_keys(array_keys($changesets), 0); } $old_ids = array(); $new_ids = array(); foreach ($map as $id => $vs) { if ($vs <= 0) { $old_ids[] = $id; $new_ids[] = $id; } else { $new_ids[] = $id; $new_ids[] = $vs; } } $this->loadDiffProperties($diffs); $props = $target_manual->getDiffProperties(); $subscriber_phids = PhabricatorSubscribersQuery::loadSubscribersForPHID( $revision->getPHID()); $object_phids = array_merge( $revision->getReviewerPHIDs(), $subscriber_phids, $revision->getCommitPHIDs(), array( $revision->getAuthorPHID(), $viewer->getPHID(), )); foreach ($revision->getAttached() as $type => $phids) { foreach ($phids as $phid => $info) { $object_phids[] = $phid; } } $field_list = PhabricatorCustomField::getObjectFields( $revision, PhabricatorCustomField::ROLE_VIEW); $field_list->setViewer($viewer); $field_list->readFieldsFromStorage($revision); $warning_handle_map = array(); foreach ($field_list->getFields() as $key => $field) { $req = $field->getRequiredHandlePHIDsForRevisionHeaderWarnings(); foreach ($req as $phid) { $warning_handle_map[$key][] = $phid; $object_phids[] = $phid; } } $handles = $this->loadViewerHandles($object_phids); $warnings = $this->warnings; $request_uri = $request->getRequestURI(); $large = $request->getStr('large'); $large_warning = ($this->isLargeDiff()) && (!$this->isVeryLargeDiff()) && (!$large); if ($large_warning) { $count = $this->getChangesetCount(); $expand_uri = $request_uri ->alter('large', 'true') ->setFragment('toc'); $message = array( pht( 'This large diff affects %s files. Files without inline '. 'comments have been collapsed.', new PhutilNumber($count)), ' ', phutil_tag( 'strong', array(), phutil_tag( 'a', array( 'href' => $expand_uri, ), pht('Expand All Files'))), ); $warnings[] = id(new PHUIInfoView()) ->setTitle(pht('Large Diff')) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->appendChild($message); $folded_changesets = $changesets; } else { $folded_changesets = array(); } // Don't hide or fold changesets which have inline comments. $hidden_changesets = $this->hiddenChangesets; if ($hidden_changesets || $folded_changesets) { $old = array_select_keys($changesets, $old_ids); $new = array_select_keys($changesets, $new_ids); $inlines = id(new DifferentialDiffInlineCommentQuery()) ->setViewer($viewer) ->withRevisionPHIDs(array($revision->getPHID())) ->withPublishableComments(true) ->withPublishedComments(true) ->execute(); $inlines = mpull($inlines, 'newInlineCommentObject'); $inlines = id(new PhabricatorInlineCommentAdjustmentEngine()) ->setViewer($viewer) ->setRevision($revision) ->setOldChangesets($old) ->setNewChangesets($new) ->setInlines($inlines) ->execute(); foreach ($inlines as $inline) { $changeset_id = $inline->getChangesetID(); if (!isset($changesets[$changeset_id])) { continue; } unset($hidden_changesets[$changeset_id]); unset($folded_changesets[$changeset_id]); } } // If we would hide only one changeset, don't hide anything. The notice // we'd render about it is about the same size as the changeset. if (count($hidden_changesets) < 2) { $hidden_changesets = array(); } // Update the set of hidden changesets, since we may have just un-hidden // some of them. if ($hidden_changesets) { $warnings[] = id(new PHUIInfoView()) ->setTitle(pht('Showing Only Differences')) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->appendChild( pht( 'This revision modifies %s more files that are hidden because '. 'they were not modified between selected diffs and they have no '. 'inline comments.', phutil_count($hidden_changesets))); } // Compute the unfolded changesets. By default, everything is unfolded. $unfolded_changesets = $changesets; foreach ($folded_changesets as $changeset_id => $changeset) { unset($unfolded_changesets[$changeset_id]); } // Throw away any hidden changesets. foreach ($hidden_changesets as $changeset_id => $changeset) { unset($changesets[$changeset_id]); unset($unfolded_changesets[$changeset_id]); } $commit_hashes = mpull($diffs, 'getSourceControlBaseRevision'); $local_commits = idx($props, 'local:commits', array()); foreach ($local_commits as $local_commit) { $commit_hashes[] = idx($local_commit, 'tree'); $commit_hashes[] = idx($local_commit, 'local'); } $commit_hashes = array_unique(array_filter($commit_hashes)); if ($commit_hashes) { $commits_for_links = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withIdentifiers($commit_hashes) ->execute(); $commits_for_links = mpull( $commits_for_links, null, 'getCommitIdentifier'); } else { $commits_for_links = array(); } $header = $this->buildHeader($revision); $subheader = $this->buildSubheaderView($revision); $details = $this->buildDetails($revision, $field_list); $curtain = $this->buildCurtain($revision); $repository = $revision->getRepository(); if ($repository) { $symbol_indexes = $this->buildSymbolIndexes( $repository, $unfolded_changesets); } else { $symbol_indexes = array(); } $revision_warnings = $this->buildRevisionWarnings( $revision, $field_list, $warning_handle_map, $handles); $info_view = null; if ($revision_warnings) { $info_view = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->setErrors($revision_warnings); } $detail_diffs = array_select_keys( $diffs, array($diff_vs, $target->getID())); $detail_diffs = mpull($detail_diffs, null, 'getPHID'); $this->loadHarbormasterData($detail_diffs); $diff_detail_box = $this->buildDiffDetailView( $detail_diffs, $revision, $field_list); $unit_box = $this->buildUnitMessagesView( $target, $revision); $timeline = $this->buildTransactions( $revision, $diff_vs ? $diffs[$diff_vs] : $target, $target, $old_ids, $new_ids); $timeline->setQuoteRef($revision->getMonogram()); if ($this->isVeryLargeDiff()) { $messages = array(); $messages[] = pht( 'This very large diff affects more than %s files. Use the %s to '. 'browse changes.', new PhutilNumber($this->getVeryLargeDiffLimit()), phutil_tag( 'a', array( 'href' => '/differential/diff/'.$target->getID().'/changesets/', ), phutil_tag('strong', array(), pht('Changeset List')))); $changeset_view = id(new PHUIInfoView()) ->setErrors($messages); } else { $changeset_view = id(new DifferentialChangesetListView()) ->setChangesets($changesets) ->setVisibleChangesets($unfolded_changesets) ->setStandaloneURI('/differential/changeset/') ->setRawFileURIs( '/differential/changeset/?view=old', '/differential/changeset/?view=new') ->setUser($viewer) ->setDiff($target) ->setRenderingReferences($rendering_references) ->setVsMap($vs_map) ->setSymbolIndexes($symbol_indexes) ->setTitle(pht('Diff %s', $target->getID())) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY); $revision_id = $revision->getID(); $inline_list_uri = "/revision/inlines/{$revision_id}/"; $inline_list_uri = $this->getApplicationURI($inline_list_uri); $changeset_view->setInlineListURI($inline_list_uri); if ($repository) { $changeset_view->setRepository($repository); } if (!$viewer_is_anonymous) { $changeset_view->setInlineCommentControllerURI( '/differential/comment/inline/edit/'.$revision->getID().'/'); } } $broken_diffs = $this->loadHistoryDiffStatus($diffs); $history = id(new DifferentialRevisionUpdateHistoryView()) ->setUser($viewer) ->setDiffs($diffs) ->setDiffUnitStatuses($broken_diffs) ->setSelectedVersusDiffID($diff_vs) ->setSelectedDiffID($target->getID()) ->setCommitsForLinks($commits_for_links); $local_table = id(new DifferentialLocalCommitsView()) ->setUser($viewer) ->setLocalCommits(idx($props, 'local:commits')) ->setCommitsForLinks($commits_for_links); if ($repository && !$this->isVeryLargeDiff()) { $other_revisions = $this->loadOtherRevisions( $changesets, $target, $repository); } else { $other_revisions = array(); } $other_view = null; if ($other_revisions) { $other_view = $this->renderOtherRevisions($other_revisions); } if ($this->isVeryLargeDiff()) { $toc_view = null; // When rendering a "very large" diff, we skip computation of owners // that own no files because it is significantly expensive and not very // valuable. foreach ($revision->getReviewers() as $reviewer) { // Give each reviewer a dummy nonempty value so the UI does not render // the "(Owns No Changed Paths)" note. If that behavior becomes more // sophisticated in the future, this behavior might also need to. $reviewer->attachChangesets($changesets); } } else { $this->buildPackageMaps($changesets); $toc_view = $this->buildTableOfContents( $changesets, $unfolded_changesets, $target->loadCoverageMap($viewer)); // Attach changesets to each reviewer so we can show which Owners package // reviewers own no files. foreach ($revision->getReviewers() as $reviewer) { $reviewer_phid = $reviewer->getReviewerPHID(); $reviewer_changesets = $this->getPackageChangesets($reviewer_phid); $reviewer->attachChangesets($reviewer_changesets); } $authority_packages = $this->getAuthorityPackages(); foreach ($changesets as $changeset) { $changeset_packages = $this->getChangesetPackages($changeset); $changeset ->setAuthorityPackages($authority_packages) ->setChangesetPackages($changeset_packages); } } $tab_group = new PHUITabGroupView(); if ($toc_view) { $tab_group->addTab( id(new PHUITabView()) ->setName(pht('Files')) ->setKey('files') ->appendChild($toc_view)); } $tab_group->addTab( id(new PHUITabView()) ->setName(pht('History')) ->setKey('history') ->appendChild($history)); $filetree = id(new DifferentialFileTreeEngine()) ->setViewer($viewer); $filetree_collapsed = !$filetree->getIsVisible(); // See PHI811. If the viewer has the file tree on, the files tab with the // table of contents is redundant, so default to the "History" tab instead. if (!$filetree_collapsed) { $tab_group->selectTab('history'); } $tab_group->addTab( id(new PHUITabView()) ->setName(pht('Commits')) ->setKey('commits') ->appendChild($local_table)); $stack_graph = id(new DifferentialRevisionGraph()) ->setViewer($viewer) ->setSeedPHID($revision->getPHID()) ->setLoadEntireGraph(true) ->loadGraph(); if (!$stack_graph->isEmpty()) { // See PHI1900. The graph UI element now tries to figure out the correct // height automatically, but currently can't in this case because the // element is not visible when the page loads. Set an explicit height. $stack_graph->setHeight(34); $stack_table = $stack_graph->newGraphTable(); $parent_type = DifferentialRevisionDependsOnRevisionEdgeType::EDGECONST; $reachable = $stack_graph->getReachableObjects($parent_type); foreach ($reachable as $key => $reachable_revision) { if ($reachable_revision->isClosed()) { unset($reachable[$key]); } } if ($reachable) { $stack_name = pht('Stack (%s Open)', phutil_count($reachable)); $stack_color = PHUIListItemView::STATUS_FAIL; } else { $stack_name = pht('Stack'); $stack_color = null; } $tab_group->addTab( id(new PHUITabView()) ->setName($stack_name) ->setKey('stack') ->setColor($stack_color) ->appendChild($stack_table)); } if ($other_view) { $tab_group->addTab( id(new PHUITabView()) ->setName(pht('Similar')) ->setKey('similar') ->appendChild($other_view)); } $view_button = id(new PHUIButtonView()) ->setTag('a') ->setText(pht('Changeset List')) ->setHref('/differential/diff/'.$target->getID().'/changesets/') ->setIcon('fa-align-left'); $tab_header = id(new PHUIHeaderView()) ->setHeader(pht('Revision Contents')) ->addActionLink($view_button); $tab_view = id(new PHUIObjectBoxView()) ->setHeader($tab_header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->addTabGroup($tab_group); $signatures = DifferentialRequiredSignaturesField::loadForRevision( $revision); $missing_signatures = false; foreach ($signatures as $phid => $signed) { if (!$signed) { $missing_signatures = true; } } $footer = array(); $signature_message = null; if ($missing_signatures) { $signature_message = id(new PHUIInfoView()) ->setTitle(pht('Content Hidden')) ->appendChild( pht( 'The content of this revision is hidden until the author has '. 'signed all of the required legal agreements.')); } else { $anchor = id(new PhabricatorAnchorView()) ->setAnchorName('toc') ->setNavigationMarker(true); $footer[] = array( $anchor, $warnings, $tab_view, $changeset_view, ); } $comment_view = id(new DifferentialRevisionEditEngine()) ->setViewer($viewer) ->buildEditEngineCommentView($revision); $comment_view->setTransactionTimeline($timeline); $review_warnings = array(); foreach ($field_list->getFields() as $field) { $review_warnings[] = $field->getWarningsForDetailView(); } $review_warnings = array_mergev($review_warnings); if ($review_warnings) { $warnings_view = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->setErrors($review_warnings); $comment_view->setInfoView($warnings_view); } $footer[] = $comment_view; $monogram = $revision->getMonogram(); $operations_box = $this->buildOperationsBox($revision); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb($monogram); $crumbs->setBorder(true); $filetree ->setChangesets($changesets) ->setDisabled($this->isVeryLargeDiff()); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setSubheader($subheader) ->setCurtain($curtain) ->setMainColumn( array( $operations_box, $info_view, $details, $diff_detail_box, $unit_box, $timeline, $signature_message, )) ->setFooter($footer); $main_content = array( $crumbs, $view, ); $main_content = $filetree->newView($main_content); if (!$filetree->getDisabled()) { $changeset_view->setFormationView($main_content); } $page = $this->newPage() ->setTitle($monogram.' '.$revision->getTitle()) ->setPageObjectPHIDs(array($revision->getPHID())) ->appendChild($main_content); return $page; } private function buildHeader(DifferentialRevision $revision) { $view = id(new PHUIHeaderView()) ->setHeader($revision->getTitle($revision)) ->setUser($this->getViewer()) ->setPolicyObject($revision) ->setHeaderIcon('fa-cog'); $status_tag = id(new PHUITagView()) ->setName($revision->getStatusDisplayName()) ->setIcon($revision->getStatusIcon()) ->setColor($revision->getStatusTagColor()) ->setType(PHUITagView::TYPE_SHADE); $view->addProperty(PHUIHeaderView::PROPERTY_STATUS, $status_tag); // If the revision is in a status other than "Draft", but not broadcasting, // add an additional "Draft" tag to the header to make it clear that this // revision hasn't promoted yet. if (!$revision->getShouldBroadcast() && !$revision->isDraft()) { $draft_status = DifferentialRevisionStatus::newForStatus( DifferentialRevisionStatus::DRAFT); $draft_tag = id(new PHUITagView()) ->setName($draft_status->getDisplayName()) ->setIcon($draft_status->getIcon()) ->setColor($draft_status->getTagColor()) ->setType(PHUITagView::TYPE_SHADE); $view->addTag($draft_tag); } return $view; } private function buildSubheaderView(DifferentialRevision $revision) { $viewer = $this->getViewer(); $author_phid = $revision->getAuthorPHID(); $author = $viewer->renderHandle($author_phid)->render(); $date = phabricator_datetime($revision->getDateCreated(), $viewer); $author = phutil_tag('strong', array(), $author); $handles = $viewer->loadHandles(array($author_phid)); $image_uri = $handles[$author_phid]->getImageURI(); $image_href = $handles[$author_phid]->getURI(); $content = pht('Authored by %s on %s.', $author, $date); return id(new PHUIHeadThingView()) ->setImage($image_uri) ->setImageHref($image_href) ->setContent($content); } private function buildDetails( DifferentialRevision $revision, $custom_fields) { $viewer = $this->getViewer(); $properties = id(new PHUIPropertyListView()) ->setUser($viewer); if ($custom_fields) { $custom_fields->appendFieldsToPropertyList( $revision, $viewer, $properties); } $header = id(new PHUIHeaderView()) ->setHeader(pht('Details')); return id(new PHUIObjectBoxView()) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->appendChild($properties); } private function buildCurtain(DifferentialRevision $revision) { $viewer = $this->getViewer(); $revision_id = $revision->getID(); $revision_phid = $revision->getPHID(); $curtain = $this->newCurtainView($revision); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $revision, PhabricatorPolicyCapability::CAN_EDIT); $curtain->addAction( id(new PhabricatorActionView()) ->setIcon('fa-pencil') ->setHref("/differential/revision/edit/{$revision_id}/") ->setName(pht('Edit Revision')) ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); $curtain->addAction( id(new PhabricatorActionView()) ->setIcon('fa-upload') ->setHref("/differential/revision/update/{$revision_id}/") ->setName(pht('Update Diff')) ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); $request_uri = $this->getRequest()->getRequestURI(); $curtain->addAction( id(new PhabricatorActionView()) ->setIcon('fa-download') ->setName(pht('Download Raw Diff')) ->setHref($request_uri->alter('download', 'true'))); $relationship_list = PhabricatorObjectRelationshipList::newForObject( $viewer, $revision); $revision_actions = array( DifferentialRevisionHasParentRelationship::RELATIONSHIPKEY, DifferentialRevisionHasChildRelationship::RELATIONSHIPKEY, ); $revision_submenu = $relationship_list->newActionSubmenu($revision_actions) ->setName(pht('Edit Related Revisions...')) ->setIcon('fa-cog'); $curtain->addAction($revision_submenu); $relationship_submenu = $relationship_list->newActionMenu(); if ($relationship_submenu) { $curtain->addAction($relationship_submenu); } $repository = $revision->getRepository(); if ($repository && $repository->canPerformAutomation()) { $revision_id = $revision->getID(); $op = new DrydockLandRepositoryOperation(); $barrier = $op->getBarrierToLanding($viewer, $revision); if ($barrier) { $can_land = false; } else { $can_land = true; } $action = id(new PhabricatorActionView()) ->setName(pht('Land Revision')) ->setIcon('fa-fighter-jet') ->setHref("/differential/revision/operation/{$revision_id}/") ->setWorkflow(true) ->setDisabled(!$can_land); $curtain->addAction($action); } return $curtain; } private function loadHistoryDiffStatus(array $diffs) { assert_instances_of($diffs, 'DifferentialDiff'); $diff_phids = mpull($diffs, 'getPHID'); $bad_unit_status = array( ArcanistUnitTestResult::RESULT_FAIL, ArcanistUnitTestResult::RESULT_BROKEN, ); $message = new HarbormasterBuildUnitMessage(); $target = new HarbormasterBuildTarget(); $build = new HarbormasterBuild(); $buildable = new HarbormasterBuildable(); $broken_diffs = queryfx_all( $message->establishConnection('r'), 'SELECT distinct a.buildablePHID FROM %T m JOIN %T t ON m.buildTargetPHID = t.phid JOIN %T b ON t.buildPHID = b.phid JOIN %T a ON b.buildablePHID = a.phid WHERE a.buildablePHID IN (%Ls) AND m.result in (%Ls)', $message->getTableName(), $target->getTableName(), $build->getTableName(), $buildable->getTableName(), $diff_phids, $bad_unit_status); $unit_status = array(); foreach ($broken_diffs as $broken) { $phid = $broken['buildablePHID']; $unit_status[$phid] = DifferentialUnitStatus::UNIT_FAIL; } return $unit_status; } private function loadChangesetsAndVsMap( DifferentialDiff $target, DifferentialDiff $diff_vs = null, PhabricatorRepository $repository = null) { $viewer = $this->getViewer(); $load_diffs = array($target); if ($diff_vs) { $load_diffs[] = $diff_vs; } $raw_changesets = id(new DifferentialChangesetQuery()) ->setViewer($viewer) ->withDiffs($load_diffs) ->execute(); $changeset_groups = mgroup($raw_changesets, 'getDiffID'); $changesets = idx($changeset_groups, $target->getID(), array()); $changesets = mpull($changesets, null, 'getID'); $refs = array(); $vs_map = array(); $vs_changesets = array(); $must_compare = array(); if ($diff_vs) { $vs_id = $diff_vs->getID(); $vs_changesets_path_map = array(); foreach (idx($changeset_groups, $vs_id, array()) as $changeset) { $path = $changeset->getAbsoluteRepositoryPath($repository, $diff_vs); $vs_changesets_path_map[$path] = $changeset; $vs_changesets[$changeset->getID()] = $changeset; } foreach ($changesets as $key => $changeset) { $path = $changeset->getAbsoluteRepositoryPath($repository, $target); if (isset($vs_changesets_path_map[$path])) { $vs_map[$changeset->getID()] = $vs_changesets_path_map[$path]->getID(); $refs[$changeset->getID()] = $changeset->getID().'/'.$vs_changesets_path_map[$path]->getID(); unset($vs_changesets_path_map[$path]); $must_compare[] = $changeset->getID(); } else { $refs[$changeset->getID()] = $changeset->getID(); } } foreach ($vs_changesets_path_map as $path => $changeset) { $changesets[$changeset->getID()] = $changeset; $vs_map[$changeset->getID()] = -1; $refs[$changeset->getID()] = $changeset->getID().'/-1'; } } else { foreach ($changesets as $changeset) { $refs[$changeset->getID()] = $changeset->getID(); } } $changesets = msort($changesets, 'getSortKey'); // See T13137. When displaying the diff between two updates, hide any // changesets which haven't actually changed. $this->hiddenChangesets = array(); foreach ($must_compare as $changeset_id) { $changeset = $changesets[$changeset_id]; $vs_changeset = $vs_changesets[$vs_map[$changeset_id]]; if ($changeset->hasSameEffectAs($vs_changeset)) { $this->hiddenChangesets[$changeset_id] = $changesets[$changeset_id]; } } return array($changesets, $vs_map, $vs_changesets, $refs); } private function buildSymbolIndexes( PhabricatorRepository $repository, array $unfolded_changesets) { assert_instances_of($unfolded_changesets, 'DifferentialChangeset'); $engine = PhabricatorSyntaxHighlighter::newEngine(); $langs = $repository->getSymbolLanguages(); $langs = nonempty($langs, array()); $sources = $repository->getSymbolSources(); $sources = nonempty($sources, array()); $symbol_indexes = array(); if ($langs && $sources) { $have_symbols = id(new DiffusionSymbolQuery()) ->existsSymbolsInRepository($repository->getPHID()); if (!$have_symbols) { return $symbol_indexes; } } $repository_phids = array_merge( array($repository->getPHID()), $sources); $indexed_langs = array_fill_keys($langs, true); foreach ($unfolded_changesets as $key => $changeset) { $lang = $engine->getLanguageFromFilename($changeset->getFilename()); if (empty($indexed_langs) || isset($indexed_langs[$lang])) { $symbol_indexes[$key] = array( 'lang' => $lang, 'repositories' => $repository_phids, ); } } return $symbol_indexes; } private function loadOtherRevisions( array $changesets, DifferentialDiff $target, PhabricatorRepository $repository) { assert_instances_of($changesets, 'DifferentialChangeset'); $viewer = $this->getViewer(); $paths = array(); foreach ($changesets as $changeset) { $paths[] = $changeset->getAbsoluteRepositoryPath( $repository, $target); } if (!$paths) { return array(); } $recent = (PhabricatorTime::getNow() - phutil_units('30 days in seconds')); $query = id(new DifferentialRevisionQuery()) ->setViewer($viewer) ->withIsOpen(true) ->withUpdatedEpochBetween($recent, null) ->setOrder(DifferentialRevisionQuery::ORDER_MODIFIED) ->setLimit(10) ->needFlags(true) ->needDrafts(true) ->needReviewers(true) ->withRepositoryPHIDs( array( $repository->getPHID(), )) ->withPaths($paths); $results = $query->execute(); // Strip out *this* revision. foreach ($results as $key => $result) { if ($result->getID() == $this->revisionID) { unset($results[$key]); break; } } return $results; } private function renderOtherRevisions(array $revisions) { assert_instances_of($revisions, 'DifferentialRevision'); $viewer = $this->getViewer(); $header = id(new PHUIHeaderView()) ->setHeader(pht('Recent Similar Revisions')); return id(new DifferentialRevisionListView()) ->setViewer($viewer) ->setRevisions($revisions) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setNoBox(true); } private function buildRawDiffResponse( DifferentialRevision $revision, array $changesets, array $vs_changesets, array $vs_map, PhabricatorRepository $repository = null) { assert_instances_of($changesets, 'DifferentialChangeset'); assert_instances_of($vs_changesets, 'DifferentialChangeset'); $viewer = $this->getViewer(); id(new DifferentialHunkQuery()) ->setViewer($viewer) ->withChangesets($changesets) ->needAttachToChangesets(true) ->execute(); $diff = new DifferentialDiff(); $diff->attachChangesets($changesets); $raw_changes = $diff->buildChangesList(); $changes = array(); foreach ($raw_changes as $changedict) { $changes[] = ArcanistDiffChange::newFromDictionary($changedict); } $loader = id(new PhabricatorFileBundleLoader()) ->setViewer($viewer); $bundle = ArcanistBundle::newFromChanges($changes); $bundle->setLoadFileDataCallback(array($loader, 'loadFileData')); $vcs = $repository ? $repository->getVersionControlSystem() : null; switch ($vcs) { case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: $raw_diff = $bundle->toGitPatch(); break; case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: default: $raw_diff = $bundle->toUnifiedDiff(); break; } $request_uri = $this->getRequest()->getRequestURI();
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
true
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/controller/DifferentialRevisionOperationController.php
src/applications/differential/controller/DifferentialRevisionOperationController.php
<?php final class DifferentialRevisionOperationController extends DifferentialController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $id = $request->getURIData('id'); $revision = id(new DifferentialRevisionQuery()) ->withIDs(array($id)) ->setViewer($viewer) ->needActiveDiffs(true) ->executeOne(); if (!$revision) { return new Aphront404Response(); } $detail_uri = "/D{$id}"; $op = new DrydockLandRepositoryOperation(); $barrier = $op->getBarrierToLanding($viewer, $revision); if ($barrier) { return $this->newDialog() ->setTitle($barrier['title']) ->appendParagraph($barrier['body']) ->addCancelButton($detail_uri); } $diff = $revision->getActiveDiff(); $repository = $revision->getRepository(); $default_ref = $this->loadDefaultRef($repository, $diff); if ($default_ref) { $v_ref = array($default_ref->getPHID()); } else { $v_ref = array(); } $e_ref = true; $errors = array(); if ($request->isFormPost()) { $v_ref = $request->getArr('refPHIDs'); $ref_phid = head($v_ref); if (!strlen($ref_phid)) { $e_ref = pht('Required'); $errors[] = pht( 'You must select a branch to land this revision onto.'); } else { $ref = $this->newRefQuery($repository) ->withPHIDs(array($ref_phid)) ->executeOne(); if (!$ref) { $e_ref = pht('Invalid'); $errors[] = pht( 'You must select a branch from this repository to land this '. 'revision onto.'); } } if (!$errors) { // NOTE: The operation is locked to the current active diff, so if the // revision is updated before the operation applies nothing sneaky // occurs. $target = 'branch:'.$ref->getRefName(); $operation = DrydockRepositoryOperation::initializeNewOperation($op) ->setAuthorPHID($viewer->getPHID()) ->setObjectPHID($revision->getPHID()) ->setRepositoryPHID($repository->getPHID()) ->setRepositoryTarget($target) ->setProperty('differential.diffPHID', $diff->getPHID()); $operation->save(); $operation->scheduleUpdate(); return id(new AphrontRedirectResponse()) ->setURI($detail_uri); } } $ref_datasource = id(new DiffusionRefDatasource()) ->setParameters( array( 'repositoryPHIDs' => array($repository->getPHID()), 'refTypes' => $this->getTargetableRefTypes(), )); $form = id(new AphrontFormView()) ->setUser($viewer) ->appendRemarkupInstructions( pht( '(NOTE) This feature is new and experimental.')) ->appendControl( id(new AphrontFormTokenizerControl()) ->setLabel(pht('Onto Branch')) ->setName('refPHIDs') ->setLimit(1) ->setError($e_ref) ->setValue($v_ref) ->setDatasource($ref_datasource)); return $this->newDialog() ->setWidth(AphrontDialogView::WIDTH_FORM) ->setTitle(pht('Land Revision')) ->setErrors($errors) ->appendForm($form) ->addCancelButton($detail_uri) ->addSubmitButton(pht('Land Revision')); } private function newRefQuery(PhabricatorRepository $repository) { $viewer = $this->getViewer(); return id(new PhabricatorRepositoryRefCursorQuery()) ->setViewer($viewer) ->withRepositoryPHIDs(array($repository->getPHID())) ->withRefTypes($this->getTargetableRefTypes()); } private function getTargetableRefTypes() { return array( PhabricatorRepositoryRefCursor::TYPE_BRANCH, ); } private function loadDefaultRef( PhabricatorRepository $repository, DifferentialDiff $diff) { $default_name = $this->getDefaultRefName($repository, $diff); if (!strlen($default_name)) { return null; } return $this->newRefQuery($repository) ->withRefNames(array($default_name)) ->executeOne(); } private function getDefaultRefName( PhabricatorRepository $repository, DifferentialDiff $diff) { $onto = $diff->loadTargetBranch(); if ($onto !== null) { return $onto; } return $repository->getDefaultBranch(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/controller/DifferentialChangesetListController.php
src/applications/differential/controller/DifferentialChangesetListController.php
<?php final class DifferentialChangesetListController extends DifferentialController { private $diff; public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $diff = id(new DifferentialDiffQuery()) ->setViewer($viewer) ->withIDs(array($request->getURIData('id'))) ->executeOne(); if (!$diff) { return new Aphront404Response(); } $this->diff = $diff; return id(new DifferentialChangesetSearchEngine()) ->setController($this) ->setDiff($diff) ->buildResponse(); } protected function buildApplicationCrumbs() { $crumbs = parent::buildApplicationCrumbs(); $diff = $this->diff; if ($diff) { $revision = $diff->getRevision(); if ($revision) { $crumbs->addTextCrumb( $revision->getMonogram(), $revision->getURI()); } $crumbs->addTextCrumb( pht('Diff %d', $diff->getID()), $diff->getURI()); } return $crumbs; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/controller/DifferentialRevisionEditController.php
src/applications/differential/controller/DifferentialRevisionEditController.php
<?php final class DifferentialRevisionEditController extends DifferentialController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); // If we have a Diff ID, this is an "/attach/123/to/456/" action. The // user just created a diff and is trying to use it to create or update // a revision. $diff_id = $request->getURIData('diffID'); if ($diff_id) { $diff = id(new DifferentialDiffQuery()) ->setViewer($viewer) ->withIDs(array($diff_id)) ->executeOne(); if (!$diff) { return new Aphront404Response(); } if ($diff->getRevisionID()) { $revision = $diff->getRevision(); return $this->newDialog() ->setTitle(pht('Diff Already Attached')) ->appendParagraph( pht( 'This diff is already attached to a revision.')) ->addCancelButton($revision->getURI(), pht('Continue')); } } else { $diff = null; } $revision_id = $request->getURIData('id'); if (!$diff && !$revision_id) { return $this->newDialog() ->setTitle(pht('Diff Required')) ->appendParagraph( pht( 'You can not create a revision without a diff.')) ->addCancelButton($this->getApplicationURI()); } $engine = id(new DifferentialRevisionEditEngine()) ->setController($this); if ($diff) { $engine->setDiff($diff); } return $engine->buildResponse(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/controller/DifferentialInlineCommentEditController.php
src/applications/differential/controller/DifferentialInlineCommentEditController.php
<?php final class DifferentialInlineCommentEditController extends PhabricatorInlineCommentController { protected function newInlineCommentQuery() { return new DifferentialDiffInlineCommentQuery(); } protected function newContainerObject() { return $this->loadRevision(); } private function getRevisionID() { return $this->getRequest()->getURIData('id'); } private function loadRevision() { $viewer = $this->getViewer(); $revision_id = $this->getRevisionID(); $revision = id(new DifferentialRevisionQuery()) ->setViewer($viewer) ->withIDs(array($revision_id)) ->executeOne(); if (!$revision) { throw new Exception(pht('Invalid revision ID "%s".', $revision_id)); } return $revision; } protected function createComment() { // Verify revision and changeset correspond to actual objects, and are // connected to one another. $changeset_id = $this->getChangesetID(); $viewer = $this->getViewer(); $revision = $this->loadRevision(); $changeset = id(new DifferentialChangesetQuery()) ->setViewer($viewer) ->withIDs(array($changeset_id)) ->executeOne(); if (!$changeset) { throw new Exception( pht( 'Invalid changeset ID "%s"!', $changeset_id)); } $diff = $changeset->getDiff(); if ($diff->getRevisionID() != $revision->getID()) { throw new Exception( pht( 'Changeset ID "%s" is part of diff ID "%s", but that diff '. 'is attached to revision "%s", not revision "%s".', $changeset_id, $diff->getID(), $diff->getRevisionID(), $revision->getID())); } return id(new DifferentialInlineComment()) ->setRevision($revision) ->setChangesetID($changeset_id); } protected function loadCommentForDone($id) { $viewer = $this->getViewer(); $inline = $this->loadCommentByID($id); if (!$inline) { throw new Exception(pht('Unable to load inline "%d".', $id)); } $changeset = id(new DifferentialChangesetQuery()) ->setViewer($viewer) ->withIDs(array($inline->getChangesetID())) ->executeOne(); if (!$changeset) { throw new Exception(pht('Unable to load changeset.')); } $diff = id(new DifferentialDiffQuery()) ->setViewer($viewer) ->withIDs(array($changeset->getDiffID())) ->executeOne(); if (!$diff) { throw new Exception(pht('Unable to load diff.')); } $revision = id(new DifferentialRevisionQuery()) ->setViewer($viewer) ->withIDs(array($diff->getRevisionID())) ->executeOne(); if (!$revision) { throw new Exception(pht('Unable to load revision.')); } $viewer_phid = $viewer->getPHID(); $is_owner = ($viewer_phid == $revision->getAuthorPHID()); $is_author = ($viewer_phid == $inline->getAuthorPHID()); $is_draft = ($inline->isDraft()); if ($is_owner) { // You own the revision, so you can mark the comment as "Done". } else if ($is_author && $is_draft) { // You made this comment and it's still a draft, so you can mark // it as "Done". } else { throw new Exception( pht( 'You are not the revision owner, and this is not a draft comment '. 'you authored.')); } return $inline; } protected function canEditInlineComment( PhabricatorUser $viewer, DifferentialInlineComment $inline) { // Only the author may edit a comment. if ($inline->getAuthorPHID() != $viewer->getPHID()) { return false; } // Saved comments may not be edited, for now, although the schema now // supports it. if (!$inline->isDraft()) { return false; } // Inline must be attached to the active revision. if ($inline->getRevisionID() != $this->getRevisionID()) { return false; } return true; } protected function loadObjectOwnerPHID( PhabricatorInlineComment $inline) { return $this->loadRevision()->getAuthorPHID(); } protected function hideComments(array $ids) { $viewer = $this->getViewer(); $table = new DifferentialHiddenComment(); $conn_w = $table->establishConnection('w'); $sql = array(); foreach ($ids as $id) { $sql[] = qsprintf( $conn_w, '(%s, %d)', $viewer->getPHID(), $id); } queryfx( $conn_w, 'INSERT IGNORE INTO %T (userPHID, commentID) VALUES %LQ', $table->getTableName(), $sql); } protected function showComments(array $ids) { $viewer = $this->getViewer(); $table = new DifferentialHiddenComment(); $conn_w = $table->establishConnection('w'); queryfx( $conn_w, 'DELETE FROM %T WHERE userPHID = %s AND commentID IN (%Ld)', $table->getTableName(), $viewer->getPHID(), $ids); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/controller/DifferentialDiffViewController.php
src/applications/differential/controller/DifferentialDiffViewController.php
<?php final class DifferentialDiffViewController extends DifferentialController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $id = $request->getURIData('id'); $diff = id(new DifferentialDiffQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->executeOne(); if (!$diff) { return new Aphront404Response(); } if ($diff->getRevisionID()) { return id(new AphrontRedirectResponse()) ->setURI('/D'.$diff->getRevisionID().'?id='.$diff->getID()); } if ($request->isFormPost()) { $diff_id = $diff->getID(); $revision_id = $request->getInt('revisionID'); if ($revision_id) { $attach_uri = "/revision/attach/{$diff_id}/to/{$revision_id}/"; } else { $attach_uri = "/revision/attach/{$diff_id}/to/"; } $attach_uri = $this->getApplicationURI($attach_uri); return id(new AphrontRedirectResponse()) ->setURI($attach_uri); } $diff_phid = $diff->getPHID(); $buildables = id(new HarbormasterBuildableQuery()) ->setViewer($viewer) ->withBuildablePHIDs(array($diff_phid)) ->withManualBuildables(false) ->needBuilds(true) ->needTargets(true) ->execute(); $buildables = mpull($buildables, null, 'getBuildablePHID'); $diff->attachBuildable(idx($buildables, $diff_phid)); // TODO: implement optgroup support in AphrontFormSelectControl? $select = array(); $select[] = hsprintf('<optgroup label="%s">', pht('Create New Revision')); $select[] = phutil_tag( 'option', array('value' => ''), pht('Create a new Revision...')); $select[] = hsprintf('</optgroup>'); $selected_id = $request->getInt('revisionID'); $revisions = $this->loadSelectableRevisions($viewer, $selected_id); if ($revisions) { $select[] = hsprintf( '<optgroup label="%s">', pht('Update Existing Revision')); foreach ($revisions as $revision) { if ($selected_id == $revision->getID()) { $selected = 'selected'; } else { $selected = null; } $select[] = phutil_tag( 'option', array( 'value' => $revision->getID(), 'selected' => $selected, ), id(new PhutilUTF8StringTruncator()) ->setMaximumGlyphs(128) ->truncateString( 'D'.$revision->getID().' '.$revision->getTitle())); } $select[] = hsprintf('</optgroup>'); } $select = phutil_tag( 'select', array('name' => 'revisionID'), $select); $form = id(new AphrontFormView()) ->setViewer($viewer) ->appendRemarkupInstructions( pht( 'Review the diff for correctness. When you are satisfied, either '. '**create a new revision** or **update an existing revision**.')) ->appendChild( id(new AphrontFormMarkupControl()) ->setLabel(pht('Attach To')) ->setValue($select)) ->appendChild( id(new AphrontFormSubmitControl()) ->setValue(pht('Continue'))); $props = id(new DifferentialDiffProperty())->loadAllWhere( 'diffID = %d', $diff->getID()); $props = mpull($props, 'getData', 'getName'); $property_head = id(new PHUIHeaderView()) ->setHeader(pht('Properties')); $property_view = new PHUIPropertyListView(); $changesets = $diff->loadChangesets(); $changesets = msort($changesets, 'getSortKey'); $this->buildPackageMaps($changesets); $table_of_contents = $this->buildTableOfContents( $changesets, $changesets, $diff->loadCoverageMap($viewer)); $refs = array(); foreach ($changesets as $changeset) { $refs[$changeset->getID()] = $changeset->getID(); } $details = id(new DifferentialChangesetListView()) ->setChangesets($changesets) ->setVisibleChangesets($changesets) ->setRenderingReferences($refs) ->setStandaloneURI('/differential/changeset/') ->setDiff($diff) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setTitle(pht('Diff %d', $diff->getID())) ->setUser($request->getUser()); $title = pht('Diff %d', $diff->getID()); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb($title); $crumbs->setBorder(true); $header = id(new PHUIHeaderView()) ->setHeader($title); $prop_box = id(new PHUIObjectBoxView()) ->setHeader($property_head) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->addPropertyList($property_view) ->setForm($form); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setMainColumn(array( )) ->setFooter(array( $prop_box, $table_of_contents, $details, )); $page = $this->newPage() ->setTitle(pht('Diff View')) ->setCrumbs($crumbs) ->appendChild($view); return $page; } private function loadSelectableRevisions( PhabricatorUser $viewer, $selected_id) { $revisions = id(new DifferentialRevisionQuery()) ->setViewer($viewer) ->withAuthors(array($viewer->getPHID())) ->withIsOpen(true) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->execute(); $revisions = mpull($revisions, null, 'getID'); // If a specific revision is selected (for example, because the user is // following the "Update Diff" workflow), but not present in the dropdown, // try to add it to the dropdown even if it is closed. This allows the // workflow to be used to update abandoned revisions. if ($selected_id) { if (empty($revisions[$selected_id])) { $selected = id(new DifferentialRevisionQuery()) ->setViewer($viewer) ->withAuthors(array($viewer->getPHID())) ->withIDs(array($selected_id)) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->execute(); $revisions = mpull($selected, null, 'getID') + $revisions; } } return $revisions; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/controller/DifferentialDiffCreateController.php
src/applications/differential/controller/DifferentialDiffCreateController.php
<?php final class DifferentialDiffCreateController extends DifferentialController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); // If we're on the "Update Diff" workflow, load the revision we're going // to update. $revision = null; $revision_id = $request->getURIData('revisionID'); if ($revision_id) { $revision = id(new DifferentialRevisionQuery()) ->setViewer($viewer) ->withIDs(array($revision_id)) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$revision) { return new Aphront404Response(); } } $diff = null; // This object is just for policy stuff $diff_object = DifferentialDiff::initializeNewDiff($viewer); if ($revision) { $repository_phid = $revision->getRepositoryPHID(); } else { $repository_phid = null; } $errors = array(); $e_diff = null; $e_file = null; $validation_exception = null; if ($request->isFormPost()) { $repository_tokenizer = $request->getArr( id(new DifferentialRepositoryField())->getFieldKey()); if ($repository_tokenizer) { $repository_phid = reset($repository_tokenizer); } if ($request->getFileExists('diff-file')) { $diff = PhabricatorFile::readUploadedFileData($_FILES['diff-file']); } else { $diff = $request->getStr('diff'); } if (!strlen($diff)) { $errors[] = pht( 'You can not create an empty diff. Paste a diff or upload a '. 'file containing a diff.'); $e_diff = pht('Required'); $e_file = pht('Required'); } if (!$errors) { try { $call = new ConduitCall( 'differential.createrawdiff', array( 'diff' => $diff, 'repositoryPHID' => $repository_phid, 'viewPolicy' => $request->getStr('viewPolicy'), )); $call->setUser($viewer); $result = $call->execute(); $diff_id = $result['id']; $uri = $this->getApplicationURI("diff/{$diff_id}/"); $uri = new PhutilURI($uri); if ($revision) { $uri->replaceQueryParam('revisionID', $revision->getID()); } return id(new AphrontRedirectResponse())->setURI($uri); } catch (PhabricatorApplicationTransactionValidationException $ex) { $validation_exception = $ex; } } } $form = new AphrontFormView(); $arcanist_href = PhabricatorEnv::getDoclink('Arcanist User Guide'); $arcanist_link = phutil_tag( 'a', array( 'href' => $arcanist_href, 'target' => '_blank', ), pht('Learn More')); $cancel_uri = $this->getApplicationURI(); $policies = id(new PhabricatorPolicyQuery()) ->setViewer($viewer) ->setObject($diff_object) ->execute(); $info_view = null; if (!$request->isFormPost()) { $info_view = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->setErrors( array( array( pht( 'The best way to create a diff is to use the %s '. 'command-line tool.', PlatformSymbols::getPlatformClientName()), ' ', $arcanist_link, ), pht( 'You can also paste a diff above, or upload a file '. 'containing a diff (for example, from %s, %s or %s).', phutil_tag('tt', array(), 'svn diff'), phutil_tag('tt', array(), 'git diff'), phutil_tag('tt', array(), 'hg diff --git')), )); } if ($revision) { $title = pht('Update Diff'); $header = pht('Update Diff'); $button = pht('Continue'); $header_icon = 'fa-upload'; } else { $title = pht('Create Diff'); $header = pht('Create New Diff'); $button = pht('Create Diff'); $header_icon = 'fa-plus-square'; } $form ->setEncType('multipart/form-data') ->setUser($viewer); if ($revision) { $form->appendChild( id(new AphrontFormMarkupControl()) ->setLabel(pht('Updating Revision')) ->setValue($viewer->renderHandle($revision->getPHID()))); } if ($repository_phid) { $repository_value = array($repository_phid); } else { $repository_value = array(); } $form ->appendChild( id(new AphrontFormTextAreaControl()) ->setLabel(pht('Raw Diff')) ->setName('diff') ->setValue($diff) ->setHeight(AphrontFormTextAreaControl::HEIGHT_VERY_TALL) ->setError($e_diff)) ->appendChild( id(new AphrontFormFileControl()) ->setLabel(pht('Raw Diff From File')) ->setName('diff-file') ->setError($e_file)) ->appendControl( id(new AphrontFormTokenizerControl()) ->setName(id(new DifferentialRepositoryField())->getFieldKey()) ->setLabel(pht('Repository')) ->setDatasource(new DiffusionRepositoryDatasource()) ->setValue($repository_value) ->setLimit(1)) ->appendChild( id(new AphrontFormPolicyControl()) ->setUser($viewer) ->setName('viewPolicy') ->setPolicyObject($diff_object) ->setPolicies($policies) ->setCapability(PhabricatorPolicyCapability::CAN_VIEW)) ->appendChild( id(new AphrontFormSubmitControl()) ->addCancelButton($cancel_uri) ->setValue($button)); $form_box = id(new PHUIObjectBoxView()) ->setHeaderText($title) ->setValidationException($validation_exception) ->setForm($form) ->setBackground(PHUIObjectBoxView::WHITE_CONFIG) ->setFormErrors($errors); $crumbs = $this->buildApplicationCrumbs(); if ($revision) { $crumbs->addTextCrumb( $revision->getMonogram(), '/'.$revision->getMonogram()); } $crumbs->addTextCrumb($title); $crumbs->setBorder(true); $view = id(new PHUITwoColumnView()) ->setFooter(array( $form_box, $info_view, )); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/controller/DifferentialChangesetViewController.php
src/applications/differential/controller/DifferentialChangesetViewController.php
<?php final class DifferentialChangesetViewController extends DifferentialController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $rendering_reference = $request->getStr('ref'); $parts = explode('/', $rendering_reference); if (count($parts) == 2) { list($id, $vs) = $parts; } else { $id = $parts[0]; $vs = 0; } $id = (int)$id; $vs = (int)$vs; $load_ids = array($id); if ($vs && ($vs != -1)) { $load_ids[] = $vs; } $changesets = id(new DifferentialChangesetQuery()) ->setViewer($viewer) ->withIDs($load_ids) ->needHunks(true) ->execute(); $changesets = mpull($changesets, null, 'getID'); $changeset = idx($changesets, $id); if (!$changeset) { return new Aphront404Response(); } $vs_changeset = null; if ($vs && ($vs != -1)) { $vs_changeset = idx($changesets, $vs); if (!$vs_changeset) { return new Aphront404Response(); } } $view = $request->getStr('view'); if ($view) { $phid = idx($changeset->getMetadata(), "$view:binary-phid"); if ($phid) { return id(new AphrontRedirectResponse())->setURI("/file/info/$phid/"); } switch ($view) { case 'new': return $this->buildRawFileResponse($changeset, $is_new = true); case 'old': if ($vs_changeset) { return $this->buildRawFileResponse($vs_changeset, $is_new = true); } return $this->buildRawFileResponse($changeset, $is_new = false); default: return new Aphront400Response(); } } $old = array(); $new = array(); if (!$vs) { $right = $changeset; $left = null; $right_source = $right->getID(); $right_new = true; $left_source = $right->getID(); $left_new = false; $render_cache_key = $right->getID(); $old[] = $changeset; $new[] = $changeset; } else if ($vs == -1) { $right = null; $left = $changeset; $right_source = $left->getID(); $right_new = false; $left_source = $left->getID(); $left_new = true; $render_cache_key = null; $old[] = $changeset; $new[] = $changeset; } else { $right = $changeset; $left = $vs_changeset; $right_source = $right->getID(); $right_new = true; $left_source = $left->getID(); $left_new = true; $render_cache_key = null; $new[] = $left; $new[] = $right; } if ($left) { $changeset = $left->newComparisonChangeset($right); } if ($left_new || $right_new) { $diff_map = array(); if ($left) { $diff_map[] = $left->getDiff(); } if ($right) { $diff_map[] = $right->getDiff(); } $diff_map = mpull($diff_map, null, 'getPHID'); $buildables = id(new HarbormasterBuildableQuery()) ->setViewer($viewer) ->withBuildablePHIDs(array_keys($diff_map)) ->withManualBuildables(false) ->needBuilds(true) ->needTargets(true) ->execute(); $buildables = mpull($buildables, null, 'getBuildablePHID'); foreach ($diff_map as $diff_phid => $changeset_diff) { $changeset_diff->attachBuildable(idx($buildables, $diff_phid)); } } $coverage = null; if ($right_new) { $coverage = $this->loadCoverage($right); } $spec = $request->getStr('range'); list($range_s, $range_e, $mask) = DifferentialChangesetParser::parseRangeSpecification($spec); $diff = $changeset->getDiff(); $revision_id = $diff->getRevisionID(); $can_mark = false; $object_owner_phid = null; $revision = null; if ($revision_id) { $revision = id(new DifferentialRevisionQuery()) ->setViewer($viewer) ->withIDs(array($revision_id)) ->executeOne(); if ($revision) { $can_mark = ($revision->getAuthorPHID() == $viewer->getPHID()); $object_owner_phid = $revision->getAuthorPHID(); } } if ($revision) { $container_phid = $revision->getPHID(); } else { $container_phid = $diff->getPHID(); } $viewstate_engine = id(new PhabricatorChangesetViewStateEngine()) ->setViewer($viewer) ->setObjectPHID($container_phid) ->setChangeset($changeset); $viewstate = $viewstate_engine->newViewStateFromRequest($request); if ($viewstate->getDiscardResponse()) { return new AphrontAjaxResponse(); } $parser = id(new DifferentialChangesetParser()) ->setViewer($viewer) ->setViewState($viewstate) ->setCoverage($coverage) ->setChangeset($changeset) ->setRenderingReference($rendering_reference) ->setRenderCacheKey($render_cache_key) ->setRightSideCommentMapping($right_source, $right_new) ->setLeftSideCommentMapping($left_source, $left_new); if ($left && $right) { $parser->setOriginals($left, $right); } // Load both left-side and right-side inline comments. if ($revision) { $inlines = id(new DifferentialDiffInlineCommentQuery()) ->setViewer($viewer) ->withRevisionPHIDs(array($revision->getPHID())) ->withPublishableComments(true) ->withPublishedComments(true) ->needHidden(true) ->needInlineContext(true) ->execute(); $inlines = mpull($inlines, 'newInlineCommentObject'); $inlines = id(new PhabricatorInlineCommentAdjustmentEngine()) ->setViewer($viewer) ->setRevision($revision) ->setOldChangesets($old) ->setNewChangesets($new) ->setInlines($inlines) ->execute(); } else { $inlines = array(); } if ($left_new) { $inlines = array_merge( $inlines, $this->buildLintInlineComments($left)); } if ($right_new) { $inlines = array_merge( $inlines, $this->buildLintInlineComments($right)); } $phids = array(); foreach ($inlines as $inline) { $parser->parseInlineComment($inline); if ($inline->getAuthorPHID()) { $phids[$inline->getAuthorPHID()] = true; } } $phids = array_keys($phids); $handles = $this->loadViewerHandles($phids); $parser->setHandles($handles); $engine = new PhabricatorMarkupEngine(); $engine->setViewer($viewer); foreach ($inlines as $inline) { $engine->addObject( $inline, PhabricatorInlineComment::MARKUP_FIELD_BODY); } $engine->process(); $parser ->setViewer($viewer) ->setMarkupEngine($engine) ->setShowEditAndReplyLinks(true) ->setCanMarkDone($can_mark) ->setObjectOwnerPHID($object_owner_phid) ->setRange($range_s, $range_e) ->setMask($mask); if ($request->isAjax()) { // NOTE: We must render the changeset before we render coverage // information, since it builds some caches. $response = $parser->newChangesetResponse(); $mcov = $parser->renderModifiedCoverage(); $coverage_data = array( 'differential-mcoverage-'.md5($changeset->getFilename()) => $mcov, ); $response->setCoverage($coverage_data); return $response; } $detail = id(new DifferentialChangesetListView()) ->setUser($this->getViewer()) ->setChangesets(array($changeset)) ->setVisibleChangesets(array($changeset)) ->setRenderingReferences(array($rendering_reference)) ->setRenderURI('/differential/changeset/') ->setDiff($diff) ->setTitle(pht('Standalone View')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setIsStandalone(true) ->setParser($parser); if ($revision_id) { $detail->setInlineCommentControllerURI( '/differential/comment/inline/edit/'.$revision_id.'/'); } $crumbs = $this->buildApplicationCrumbs(); if ($revision_id) { $crumbs->addTextCrumb('D'.$revision_id, '/D'.$revision_id); } $diff_id = $diff->getID(); if ($diff_id) { $crumbs->addTextCrumb( pht('Diff %d', $diff_id), $this->getApplicationURI('diff/'.$diff_id)); } $crumbs->addTextCrumb($changeset->getDisplayFilename()); $crumbs->setBorder(true); $header = id(new PHUIHeaderView()) ->setHeader(pht('Changeset View')) ->setHeaderIcon('fa-gear'); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter($detail); return $this->newPage() ->setTitle(pht('Changeset View')) ->setCrumbs($crumbs) ->appendChild($view); } private function buildRawFileResponse( DifferentialChangeset $changeset, $is_new) { $viewer = $this->getViewer(); if ($is_new) { $key = 'raw:new:phid'; } else { $key = 'raw:old:phid'; } $metadata = $changeset->getMetadata(); $file = null; $phid = idx($metadata, $key); if ($phid) { $file = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withPHIDs(array($phid)) ->execute(); if ($file) { $file = head($file); } } if (!$file) { // This is just building a cache of the changeset content in the file // tool, and is safe to run on a read pathway. $unguard = AphrontWriteGuard::beginScopedUnguardedWrites(); if ($is_new) { $data = $changeset->makeNewFile(); } else { $data = $changeset->makeOldFile(); } $diff = $changeset->getDiff(); $file = PhabricatorFile::newFromFileData( $data, array( 'name' => $changeset->getFilename(), 'mime-type' => 'text/plain', 'ttl.relative' => phutil_units('24 hours in seconds'), 'viewPolicy' => PhabricatorPolicies::POLICY_NOONE, )); $file->attachToObject($diff->getPHID()); $metadata[$key] = $file->getPHID(); $changeset->setMetadata($metadata); $changeset->save(); unset($unguard); } return $file->getRedirectResponse(); } private function buildLintInlineComments($changeset) { $diff = $changeset->getDiff(); $target_phids = $diff->getBuildTargetPHIDs(); if (!$target_phids) { return array(); } $messages = id(new HarbormasterBuildLintMessage())->loadAllWhere( 'buildTargetPHID IN (%Ls) AND path = %s', $target_phids, $changeset->getFilename()); if (!$messages) { return array(); } $change_type = $changeset->getChangeType(); if (DifferentialChangeType::isDeleteChangeType($change_type)) { // If this is a lint message on a deleted file, show it on the left // side of the UI because there are no source code lines on the right // side of the UI so inlines don't have anywhere to render. See PHI416. $is_new = 0; } else { $is_new = 1; } $template = id(new DifferentialInlineComment()) ->setChangesetID($changeset->getID()) ->setIsNewFile($is_new) ->setLineLength(0); $inlines = array(); foreach ($messages as $message) { $description = $message->getProperty('description'); $inlines[] = id(clone $template) ->setSyntheticAuthor(pht('Lint: %s', $message->getName())) ->setLineNumber($message->getLine()) ->setContent($description); } return $inlines; } private function loadCoverage(DifferentialChangeset $changeset) { $viewer = $this->getViewer(); $target_phids = $changeset->getDiff()->getBuildTargetPHIDs(); if (!$target_phids) { return null; } $unit = id(new HarbormasterBuildUnitMessageQuery()) ->setViewer($viewer) ->withBuildTargetPHIDs($target_phids) ->execute(); if (!$unit) { return null; } $coverage = array(); foreach ($unit as $message) { $test_coverage = $message->getProperty('coverage'); if ($test_coverage === null) { continue; } $coverage_data = idx($test_coverage, $changeset->getFileName()); if (!strlen($coverage_data)) { continue; } $coverage[] = $coverage_data; } if (!$coverage) { return null; } return ArcanistUnitTestResult::mergeCoverage($coverage); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/controller/DifferentialRevisionCloseDetailsController.php
src/applications/differential/controller/DifferentialRevisionCloseDetailsController.php
<?php final class DifferentialRevisionCloseDetailsController extends DifferentialController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $xaction = id(new PhabricatorObjectQuery()) ->withPHIDs(array($request->getURIData('phid'))) ->setViewer($viewer) ->executeOne(); if (!$xaction) { return new Aphront404Response(); } $obj_phid = $xaction->getObjectPHID(); $obj_handle = id(new PhabricatorHandleQuery()) ->setViewer($viewer) ->withPHIDs(array($obj_phid)) ->executeOne(); $body = $this->getRevisionMatchExplanation( $xaction->getMetadataValue('revisionMatchData'), $obj_handle); $dialog = id(new AphrontDialogView()) ->setUser($viewer) ->setTitle(pht('Commit Close Explanation')) ->appendParagraph($body) ->addCancelButton($obj_handle->getURI()); return id(new AphrontDialogResponse())->setDialog($dialog); } private function getRevisionMatchExplanation( $revision_match_data, PhabricatorObjectHandle $obj_handle) { if (!$revision_match_data) { return pht( 'This commit was made before this feature was built and thus this '. 'information is unavailable.'); } $body_why = array(); if ($revision_match_data['usedURI']) { return pht( 'We found a "%s" field with value "%s" in the commit message, '. 'and the domain on the URI matches this install, so '. 'we linked this commit to %s.', 'Differential Revision', $revision_match_data['foundURI'], phutil_tag( 'a', array( 'href' => $obj_handle->getURI(), ), $obj_handle->getName())); } else if ($revision_match_data['foundURI']) { $body_why[] = pht( 'We found a "%s" field with value "%s" in the commit message, '. 'but the domain on this URI did not match the configured '. 'domain for this install, "%s", so we ignored it under '. 'the assumption that it refers to some third-party revision.', 'Differential Revision', $revision_match_data['foundURI'], $revision_match_data['validDomain']); } else { $body_why[] = pht( 'We didn\'t find a "%s" field in the commit message.', 'Differential Revision'); } switch ($revision_match_data['matchHashType']) { case ArcanistDifferentialRevisionHash::HASH_GIT_TREE: $hash_info = true; $hash_type = 'tree'; break; case ArcanistDifferentialRevisionHash::HASH_GIT_COMMIT: case ArcanistDifferentialRevisionHash::HASH_MERCURIAL_COMMIT: $hash_info = true; $hash_type = 'commit'; break; default: $hash_info = false; break; } if ($hash_info) { $diff_link = phutil_tag( 'a', array( 'href' => $obj_handle->getURI(), ), $obj_handle->getName()); $body_why[] = pht( 'This commit and the active diff of %s had the same %s hash '. '(%s) so we linked this commit to %s.', $diff_link, $hash_type, $revision_match_data['matchHashValue'], $diff_link); } return phutil_implode_html("\n", $body_why); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/controller/DifferentialRevisionAffectedPathsController.php
src/applications/differential/controller/DifferentialRevisionAffectedPathsController.php
<?php final class DifferentialRevisionAffectedPathsController extends DifferentialController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $id = $request->getURIData('id'); $revision = id(new DifferentialRevisionQuery()) ->withIDs(array($id)) ->setViewer($viewer) ->executeOne(); if (!$revision) { return new Aphront404Response(); } $table = new DifferentialAffectedPath(); $conn = $table->establishConnection('r'); $paths = queryfx_all( $conn, 'SELECT * FROM %R WHERE revisionID = %d', $table, $revision->getID()); $repository_ids = array(); $path_ids = array(); foreach ($paths as $path) { $repository_id = $path['repositoryID']; $path_id = $path['pathID']; $repository_ids[] = $repository_id; $path_ids[] = $path_id; } $repository_ids = array_fuse($repository_ids); if ($repository_ids) { $repositories = id(new PhabricatorRepositoryQuery()) ->setViewer($viewer) ->withIDs($repository_ids) ->execute(); $repositories = mpull($repositories, null, 'getID'); } else { $repositories = array(); } $handles = $viewer->loadHandles(mpull($repositories, 'getPHID')); $path_ids = array_fuse($path_ids); if ($path_ids) { $path_names = id(new DiffusionPathQuery()) ->withPathIDs($path_ids) ->execute(); } else { $path_names = array(); } $rows = array(); foreach ($paths as $path) { $repository_id = $path['repositoryID']; $path_id = $path['pathID']; $repository = idx($repositories, $repository_id); if ($repository) { $repository_phid = $repository->getPHID(); $repository_link = $handles[$repository_phid]->renderLink(); } else { $repository_link = null; } $path_name = idx($path_names, $path_id); if ($path_name !== null) { $path_view = $path_name['path']; } else { $path_view = null; } $rows[] = array( $repository_id, $repository_link, $path_id, $path_view, ); } // Sort rows by path name. $rows = isort($rows, 3); $table_view = id(new AphrontTableView($rows)) ->setNoDataString(pht('This revision has no indexed affected paths.')) ->setHeaders( array( pht('Repository ID'), pht('Repository'), pht('Path ID'), pht('Path'), )) ->setColumnClasses( array( null, null, null, 'wide', )); $box_view = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Affected Path Index')) ->setTable($table_view); $crumbs = $this->buildApplicationCrumbs() ->addTextCrumb($revision->getMonogram(), $revision->getURI()) ->addTextCrumb(pht('Affected Path Index')); return $this->newPage() ->setCrumbs($crumbs) ->setTitle( array( $revision->getMonogram(), pht('Affected Path Index'), )) ->appendChild($box_view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/engineextension/DifferentialMailEngineExtension.php
src/applications/differential/engineextension/DifferentialMailEngineExtension.php
<?php final class DifferentialMailEngineExtension extends PhabricatorMailEngineExtension { const EXTENSIONKEY = 'differential'; public function supportsObject($object) { return ($object instanceof DifferentialRevision); } public function newMailStampTemplates($object) { return array( id(new PhabricatorPHIDMailStamp()) ->setKey('author') ->setLabel(pht('Author')), id(new PhabricatorPHIDMailStamp()) ->setKey('reviewer') ->setLabel(pht('Reviewer')), id(new PhabricatorPHIDMailStamp()) ->setKey('blocking-reviewer') ->setLabel(pht('Reviewer')), id(new PhabricatorPHIDMailStamp()) ->setKey('resigned-reviewer') ->setLabel(pht('Reviewer')), id(new PhabricatorPHIDMailStamp()) ->setKey('revision-repository') ->setLabel(pht('Revision Repository')), id(new PhabricatorPHIDMailStamp()) ->setKey('revision-status') ->setLabel(pht('Revision Status')), ); } public function newMailStamps($object, array $xactions) { $editor = $this->getEditor(); $viewer = $this->getViewer(); $revision = id(new DifferentialRevisionQuery()) ->setViewer($viewer) ->needReviewers(true) ->withPHIDs(array($object->getPHID())) ->executeOne(); $reviewers = array(); $blocking = array(); $resigned = array(); foreach ($revision->getReviewers() as $reviewer) { $reviewer_phid = $reviewer->getReviewerPHID(); if ($reviewer->isResigned()) { $resigned[] = $reviewer_phid; } else { $reviewers[] = $reviewer_phid; if ($reviewer->isBlocking()) { $blocking[] = $reviewer_phid; } } } $this->getMailStamp('author') ->setValue($revision->getAuthorPHID()); $this->getMailStamp('reviewer') ->setValue($reviewers); $this->getMailStamp('blocking-reviewer') ->setValue($blocking); $this->getMailStamp('resigned-reviewer') ->setValue($resigned); $this->getMailStamp('revision-repository') ->setValue($revision->getRepositoryPHID()); $this->getMailStamp('revision-status') ->setValue($revision->getModernRevisionStatus()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/engineextension/DifferentialCommitsSearchEngineAttachment.php
src/applications/differential/engineextension/DifferentialCommitsSearchEngineAttachment.php
<?php final class DifferentialCommitsSearchEngineAttachment extends PhabricatorSearchEngineAttachment { public function getAttachmentName() { return pht('Diff Commits'); } public function getAttachmentDescription() { return pht('Get the local commits (if any) for each diff.'); } public function loadAttachmentData(array $objects, $spec) { $properties = id(new DifferentialDiffProperty())->loadAllWhere( 'diffID IN (%Ld) AND name = %s', mpull($objects, 'getID'), 'local:commits'); $map = array(); foreach ($properties as $property) { $map[$property->getDiffID()] = $property->getData(); } return $map; } public function getAttachmentForObject($object, $data, $spec) { $diff_id = $object->getID(); $info = idx($data, $diff_id, array()); // NOTE: This should be similar to the information returned about commits // by "diffusion.commit.search". $list = array(); foreach ($info as $commit) { $author_epoch = idx($commit, 'time'); if ($author_epoch) { $author_epoch = (int)$author_epoch; } // TODO: Currently, we don't upload the raw author string from "arc". // Reconstruct a plausible version of it until we begin uploading this // information. $author_name = idx($commit, 'author'); $author_email = idx($commit, 'authorEmail'); if (strlen($author_name) && strlen($author_email)) { $author_raw = (string)id(new PhutilEmailAddress()) ->setDisplayName($author_name) ->setAddress($author_email); } else if (strlen($author_email)) { $author_raw = $author_email; } else { $author_raw = $author_name; } $list[] = array( 'identifier' => $commit['commit'], 'tree' => idx($commit, 'tree'), 'parents' => idx($commit, 'parents', array()), 'author' => array( 'name' => $author_name, 'email' => $author_email, 'raw' => $author_raw, 'epoch' => $author_epoch, ), 'message' => idx($commit, 'message'), ); } return array( 'commits' => $list, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/engineextension/DifferentialHovercardEngineExtension.php
src/applications/differential/engineextension/DifferentialHovercardEngineExtension.php
<?php final class DifferentialHovercardEngineExtension extends PhabricatorHovercardEngineExtension { const EXTENSIONKEY = 'differential'; public function isExtensionEnabled() { return PhabricatorApplication::isClassInstalled( 'PhabricatorDifferentialApplication'); } public function getExtensionName() { return pht('Differential Revisions'); } public function canRenderObjectHovercard($object) { return ($object instanceof DifferentialRevision); } public function willRenderHovercards(array $objects) { $viewer = $this->getViewer(); $phids = mpull($objects, 'getPHID'); $revisions = id(new DifferentialRevisionQuery()) ->setViewer($viewer) ->withPHIDs($phids) ->needReviewers(true) ->execute(); $revisions = mpull($revisions, null, 'getPHID'); return array( 'revisions' => $revisions, ); } public function renderHovercard( PHUIHovercardView $hovercard, PhabricatorObjectHandle $handle, $object, $data) { $viewer = $this->getViewer(); $revision = idx($data['revisions'], $object->getPHID()); if (!$revision) { return; } $hovercard->setTitle('D'.$revision->getID()); $hovercard->setDetail($revision->getTitle()); $hovercard->addField( pht('Author'), $viewer->renderHandle($revision->getAuthorPHID())); $reviewer_phids = $revision->getReviewerPHIDs(); $hovercard->addField( pht('Reviewers'), $viewer->renderHandleList($reviewer_phids)->setAsInline(true)); $summary = $revision->getSummary(); if (strlen($summary)) { $summary = id(new PhutilUTF8StringTruncator()) ->setMaximumGlyphs(120) ->truncateString($summary); $hovercard->addField(pht('Summary'), $summary); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/engineextension/DifferentialReviewersSearchEngineAttachment.php
src/applications/differential/engineextension/DifferentialReviewersSearchEngineAttachment.php
<?php final class DifferentialReviewersSearchEngineAttachment extends PhabricatorSearchEngineAttachment { public function getAttachmentName() { return pht('Differential Reviewers'); } public function getAttachmentDescription() { return pht('Get the reviewers for each revision.'); } public function willLoadAttachmentData($query, $spec) { $query->needReviewers(true); } public function getAttachmentForObject($object, $data, $spec) { $reviewers = $object->getReviewers(); $status_blocking = DifferentialReviewerStatus::STATUS_BLOCKING; $list = array(); foreach ($reviewers as $reviewer) { $status = $reviewer->getReviewerStatus(); $is_blocking = ($status == $status_blocking); $list[] = array( 'reviewerPHID' => $reviewer->getReviewerPHID(), 'status' => $status, 'isBlocking' => $is_blocking, 'actorPHID' => $reviewer->getLastActorPHID(), ); } return array( 'reviewers' => $list, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialDiff.php
src/applications/differential/storage/DifferentialDiff.php
<?php final class DifferentialDiff extends DifferentialDAO implements PhabricatorPolicyInterface, PhabricatorExtendedPolicyInterface, HarbormasterBuildableInterface, HarbormasterCircleCIBuildableInterface, HarbormasterBuildkiteBuildableInterface, PhabricatorApplicationTransactionInterface, PhabricatorDestructibleInterface, PhabricatorConduitResultInterface { protected $revisionID; protected $authorPHID; protected $repositoryPHID; protected $commitPHID; protected $sourceMachine; protected $sourcePath; protected $sourceControlSystem; protected $sourceControlBaseRevision; protected $sourceControlPath; protected $lintStatus; protected $unitStatus; protected $lineCount; protected $branch; protected $bookmark; protected $creationMethod; protected $repositoryUUID; protected $description; protected $viewPolicy; private $unsavedChangesets = array(); private $changesets = self::ATTACHABLE; private $revision = self::ATTACHABLE; private $properties = self::ATTACHABLE; private $buildable = self::ATTACHABLE; private $unitMessages = self::ATTACHABLE; protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_COLUMN_SCHEMA => array( 'revisionID' => 'id?', 'authorPHID' => 'phid?', 'repositoryPHID' => 'phid?', 'sourceMachine' => 'text255?', 'sourcePath' => 'text255?', 'sourceControlSystem' => 'text64?', 'sourceControlBaseRevision' => 'text255?', 'sourceControlPath' => 'text255?', 'lintStatus' => 'uint32', 'unitStatus' => 'uint32', 'lineCount' => 'uint32', 'branch' => 'text255?', 'bookmark' => 'text255?', 'repositoryUUID' => 'text64?', 'commitPHID' => 'phid?', // T6203/NULLABILITY // These should be non-null; all diffs should have a creation method // and the description should just be empty. 'creationMethod' => 'text255?', 'description' => 'text255?', ), self::CONFIG_KEY_SCHEMA => array( 'revisionID' => array( 'columns' => array('revisionID'), ), 'key_commit' => array( 'columns' => array('commitPHID'), ), ), ) + parent::getConfiguration(); } public function generatePHID() { return PhabricatorPHID::generateNewPHID( DifferentialDiffPHIDType::TYPECONST); } public function addUnsavedChangeset(DifferentialChangeset $changeset) { if ($this->changesets === null) { $this->changesets = array(); } $this->unsavedChangesets[] = $changeset; $this->changesets[] = $changeset; return $this; } public function attachChangesets(array $changesets) { assert_instances_of($changesets, 'DifferentialChangeset'); $this->changesets = $changesets; return $this; } public function getChangesets() { return $this->assertAttached($this->changesets); } public function loadChangesets() { if (!$this->getID()) { return array(); } $changesets = id(new DifferentialChangeset())->loadAllWhere( 'diffID = %d', $this->getID()); foreach ($changesets as $changeset) { $changeset->attachDiff($this); } return $changesets; } public function save() { $this->openTransaction(); $ret = parent::save(); foreach ($this->unsavedChangesets as $changeset) { $changeset->setDiffID($this->getID()); $changeset->save(); } $this->saveTransaction(); return $ret; } public static function initializeNewDiff(PhabricatorUser $actor) { $app = id(new PhabricatorApplicationQuery()) ->setViewer($actor) ->withClasses(array('PhabricatorDifferentialApplication')) ->executeOne(); $view_policy = $app->getPolicy( DifferentialDefaultViewCapability::CAPABILITY); $diff = id(new DifferentialDiff()) ->setViewPolicy($view_policy); return $diff; } public static function newFromRawChanges( PhabricatorUser $actor, array $changes) { assert_instances_of($changes, 'ArcanistDiffChange'); $diff = self::initializeNewDiff($actor); return self::buildChangesetsFromRawChanges($diff, $changes); } public static function newEphemeralFromRawChanges(array $changes) { assert_instances_of($changes, 'ArcanistDiffChange'); $diff = id(new DifferentialDiff())->makeEphemeral(); return self::buildChangesetsFromRawChanges($diff, $changes); } private static function buildChangesetsFromRawChanges( DifferentialDiff $diff, array $changes) { // There may not be any changes; initialize the changesets list so that // we don't throw later when accessing it. $diff->attachChangesets(array()); $lines = 0; foreach ($changes as $change) { if ($change->getType() == ArcanistDiffChangeType::TYPE_MESSAGE) { // If a user pastes a diff into Differential which includes a commit // message (e.g., they ran `git show` to generate it), discard that // change when constructing a DifferentialDiff. continue; } $changeset = new DifferentialChangeset(); $add_lines = 0; $del_lines = 0; $first_line = PHP_INT_MAX; $hunks = $change->getHunks(); if ($hunks) { foreach ($hunks as $hunk) { $dhunk = new DifferentialHunk(); $dhunk->setOldOffset($hunk->getOldOffset()); $dhunk->setOldLen($hunk->getOldLength()); $dhunk->setNewOffset($hunk->getNewOffset()); $dhunk->setNewLen($hunk->getNewLength()); $dhunk->setChanges($hunk->getCorpus()); $changeset->addUnsavedHunk($dhunk); $add_lines += $hunk->getAddLines(); $del_lines += $hunk->getDelLines(); $added_lines = $hunk->getChangedLines('new'); if ($added_lines) { $first_line = min($first_line, head_key($added_lines)); } } $lines += $add_lines + $del_lines; } else { // This happens when you add empty files. $changeset->attachHunks(array()); } $metadata = $change->getAllMetadata(); if ($first_line != PHP_INT_MAX) { $metadata['line:first'] = $first_line; } $changeset->setOldFile($change->getOldPath()); $changeset->setFilename($change->getCurrentPath()); $changeset->setChangeType($change->getType()); $changeset->setFileType($change->getFileType()); $changeset->setMetadata($metadata); $changeset->setOldProperties($change->getOldProperties()); $changeset->setNewProperties($change->getNewProperties()); $changeset->setAwayPaths($change->getAwayPaths()); $changeset->setAddLines($add_lines); $changeset->setDelLines($del_lines); $diff->addUnsavedChangeset($changeset); } $diff->setLineCount($lines); $changesets = $diff->getChangesets(); // TODO: This is "safe", but it would be better to propagate a real user // down the stack. $viewer = PhabricatorUser::getOmnipotentUser(); id(new DifferentialChangesetEngine()) ->setViewer($viewer) ->rebuildChangesets($changesets); return $diff; } public function getDiffDict() { $dict = array( 'id' => $this->getID(), 'revisionID' => $this->getRevisionID(), 'dateCreated' => $this->getDateCreated(), 'dateModified' => $this->getDateModified(), 'sourceControlBaseRevision' => $this->getSourceControlBaseRevision(), 'sourceControlPath' => $this->getSourceControlPath(), 'sourceControlSystem' => $this->getSourceControlSystem(), 'branch' => $this->getBranch(), 'bookmark' => $this->getBookmark(), 'creationMethod' => $this->getCreationMethod(), 'description' => $this->getDescription(), 'unitStatus' => $this->getUnitStatus(), 'lintStatus' => $this->getLintStatus(), 'changes' => array(), ); $dict['changes'] = $this->buildChangesList(); return $dict + $this->getDiffAuthorshipDict(); } public function getDiffAuthorshipDict() { $dict = array('properties' => array()); $properties = id(new DifferentialDiffProperty())->loadAllWhere( 'diffID = %d', $this->getID()); foreach ($properties as $property) { $dict['properties'][$property->getName()] = $property->getData(); if ($property->getName() == 'local:commits') { foreach ($property->getData() as $commit) { $dict['authorName'] = $commit['author']; $dict['authorEmail'] = idx($commit, 'authorEmail'); break; } } } return $dict; } public function buildChangesList() { $changes = array(); foreach ($this->getChangesets() as $changeset) { $hunks = array(); foreach ($changeset->getHunks() as $hunk) { $hunks[] = array( 'oldOffset' => $hunk->getOldOffset(), 'newOffset' => $hunk->getNewOffset(), 'oldLength' => $hunk->getOldLen(), 'newLength' => $hunk->getNewLen(), 'addLines' => null, 'delLines' => null, 'isMissingOldNewline' => null, 'isMissingNewNewline' => null, 'corpus' => $hunk->getChanges(), ); } $change = array( 'id' => $changeset->getID(), 'metadata' => $changeset->getMetadata(), 'oldPath' => $changeset->getOldFile(), 'currentPath' => $changeset->getFilename(), 'awayPaths' => $changeset->getAwayPaths(), 'oldProperties' => $changeset->getOldProperties(), 'newProperties' => $changeset->getNewProperties(), 'type' => $changeset->getChangeType(), 'fileType' => $changeset->getFileType(), 'commitHash' => null, 'addLines' => $changeset->getAddLines(), 'delLines' => $changeset->getDelLines(), 'hunks' => $hunks, ); $changes[] = $change; } return $changes; } public function hasRevision() { return $this->revision !== self::ATTACHABLE; } public function getRevision() { return $this->assertAttached($this->revision); } public function attachRevision(DifferentialRevision $revision = null) { $this->revision = $revision; return $this; } public function attachProperty($key, $value) { if (!is_array($this->properties)) { $this->properties = array(); } $this->properties[$key] = $value; return $this; } public function getProperty($key) { return $this->assertAttachedKey($this->properties, $key); } public function hasDiffProperty($key) { $properties = $this->getDiffProperties(); return array_key_exists($key, $properties); } public function attachDiffProperties(array $properties) { $this->properties = $properties; return $this; } public function getDiffProperties() { return $this->assertAttached($this->properties); } public function attachBuildable(HarbormasterBuildable $buildable = null) { $this->buildable = $buildable; return $this; } public function getBuildable() { return $this->assertAttached($this->buildable); } public function getBuildTargetPHIDs() { $buildable = $this->getBuildable(); if (!$buildable) { return array(); } $target_phids = array(); foreach ($buildable->getBuilds() as $build) { foreach ($build->getBuildTargets() as $target) { $target_phids[] = $target->getPHID(); } } return $target_phids; } public function loadCoverageMap(PhabricatorUser $viewer) { $target_phids = $this->getBuildTargetPHIDs(); if (!$target_phids) { return array(); } $unit = id(new HarbormasterBuildUnitMessageQuery()) ->setViewer($viewer) ->withBuildTargetPHIDs($target_phids) ->execute(); $map = array(); foreach ($unit as $message) { $coverage = $message->getProperty('coverage', array()); foreach ($coverage as $path => $coverage_data) { $map[$path][] = $coverage_data; } } foreach ($map as $path => $coverage_items) { $map[$path] = ArcanistUnitTestResult::mergeCoverage($coverage_items); } return $map; } public function getURI() { $id = $this->getID(); return "/differential/diff/{$id}/"; } public function attachUnitMessages(array $unit_messages) { $this->unitMessages = $unit_messages; return $this; } public function getUnitMessages() { return $this->assertAttached($this->unitMessages); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { if ($this->hasRevision()) { return PhabricatorPolicies::getMostOpenPolicy(); } return $this->viewPolicy; } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { if ($this->hasRevision()) { return $this->getRevision()->hasAutomaticCapability($capability, $viewer); } return ($this->getAuthorPHID() == $viewer->getPHID()); } public function describeAutomaticCapability($capability) { if ($this->hasRevision()) { return pht( 'This diff is attached to a revision, and inherits its policies.'); } return pht('The author of a diff can see it.'); } /* -( PhabricatorExtendedPolicyInterface )--------------------------------- */ public function getExtendedPolicy($capability, PhabricatorUser $viewer) { $extended = array(); switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: if ($this->hasRevision()) { $extended[] = array( $this->getRevision(), PhabricatorPolicyCapability::CAN_VIEW, ); } else if ($this->getRepositoryPHID()) { $extended[] = array( $this->getRepositoryPHID(), PhabricatorPolicyCapability::CAN_VIEW, ); } break; } return $extended; } /* -( HarbormasterBuildableInterface )------------------------------------- */ public function getHarbormasterBuildableDisplayPHID() { $container_phid = $this->getHarbormasterContainerPHID(); if ($container_phid) { return $container_phid; } return $this->getHarbormasterBuildablePHID(); } public function getHarbormasterBuildablePHID() { return $this->getPHID(); } public function getHarbormasterContainerPHID() { if ($this->getRevisionID()) { $revision = id(new DifferentialRevision())->load($this->getRevisionID()); if ($revision) { return $revision->getPHID(); } } return null; } public function getBuildVariables() { $results = array(); $results['buildable.diff'] = $this->getID(); if ($this->revisionID) { $revision = $this->getRevision(); $results['buildable.revision'] = $revision->getID(); $repo = $revision->getRepository(); if ($repo) { $results['repository.callsign'] = $repo->getCallsign(); $results['repository.phid'] = $repo->getPHID(); $results['repository.vcs'] = $repo->getVersionControlSystem(); $results['repository.uri'] = $repo->getPublicCloneURI(); $results['repository.staging.uri'] = $repo->getStagingURI(); $results['repository.staging.ref'] = $this->getStagingRef(); } } return $results; } public function getAvailableBuildVariables() { return array( 'buildable.diff' => pht('The differential diff ID, if applicable.'), 'buildable.revision' => pht('The differential revision ID, if applicable.'), 'repository.callsign' => pht('The callsign of the repository.'), 'repository.phid' => pht('The PHID of the repository.'), 'repository.vcs' => pht('The version control system, either "svn", "hg" or "git".'), 'repository.uri' => pht('The URI to clone or checkout the repository from.'), 'repository.staging.uri' => pht('The URI of the staging repository.'), 'repository.staging.ref' => pht('The ref name for this change in the staging repository.'), ); } public function newBuildableEngine() { return new DifferentialBuildableEngine(); } /* -( HarbormasterCircleCIBuildableInterface )----------------------------- */ public function getCircleCIGitHubRepositoryURI() { $diff_phid = $this->getPHID(); $repository_phid = $this->getRepositoryPHID(); if (!$repository_phid) { throw new Exception( pht( 'This diff ("%s") is not associated with a repository. A diff '. 'must belong to a tracked repository to be built by CircleCI.', $diff_phid)); } $repository = id(new PhabricatorRepositoryQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs(array($repository_phid)) ->executeOne(); if (!$repository) { throw new Exception( pht( 'This diff ("%s") is associated with a repository ("%s") which '. 'could not be loaded.', $diff_phid, $repository_phid)); } $staging_uri = $repository->getStagingURI(); if (!$staging_uri) { throw new Exception( pht( 'This diff ("%s") is associated with a repository ("%s") that '. 'does not have a Staging Area configured. You must configure a '. 'Staging Area to use CircleCI integration.', $diff_phid, $repository_phid)); } $path = HarbormasterCircleCIBuildStepImplementation::getGitHubPath( $staging_uri); if (!$path) { throw new Exception( pht( 'This diff ("%s") is associated with a repository ("%s") that '. 'does not have a Staging Area ("%s") that is hosted on GitHub. '. 'CircleCI can only build from GitHub, so the Staging Area for '. 'the repository must be hosted there.', $diff_phid, $repository_phid, $staging_uri)); } return $staging_uri; } public function getCircleCIBuildIdentifierType() { return 'tag'; } public function getCircleCIBuildIdentifier() { $ref = $this->getStagingRef(); $ref = preg_replace('(^refs/tags/)', '', $ref); return $ref; } /* -( HarbormasterBuildkiteBuildableInterface )---------------------------- */ public function getBuildkiteBranch() { $ref = $this->getStagingRef(); // NOTE: Circa late January 2017, Buildkite fails with the error message // "Tags have been disabled for this project" if we pass the "refs/tags/" // prefix via the API and the project doesn't have GitHub tag builds // enabled, even if GitHub builds are disabled. The tag builds fine // without this prefix. $ref = preg_replace('(^refs/tags/)', '', $ref); return $ref; } public function getBuildkiteCommit() { return 'HEAD'; } public function getStagingRef() { // TODO: We're just hoping to get lucky. Instead, `arc` should store // where it sent changes and we should only provide staging details // if we reasonably believe they are accurate. return 'refs/tags/phabricator/diff/'.$this->getID(); } public function loadTargetBranch() { // TODO: This is sketchy, but just eat the query cost until this can get // cleaned up. // For now, we're only returning a target if there's exactly one and it's // a branch, since we don't support landing to more esoteric targets like // tags yet. $property = id(new DifferentialDiffProperty())->loadOneWhere( 'diffID = %d AND name = %s', $this->getID(), 'arc:onto'); if (!$property) { return null; } $data = $property->getData(); if (!$data) { return null; } if (!is_array($data)) { return null; } if (count($data) != 1) { return null; } $onto = head($data); if (!is_array($onto)) { return null; } $type = idx($onto, 'type'); if ($type != 'branch') { return null; } return idx($onto, 'name'); } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new DifferentialDiffEditor(); } public function getApplicationTransactionTemplate() { return new DifferentialDiffTransaction(); } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $viewer = $engine->getViewer(); $this->openTransaction(); $this->delete(); foreach ($this->loadChangesets() as $changeset) { $engine->destroyObject($changeset); } $properties = id(new DifferentialDiffProperty())->loadAllWhere( 'diffID = %d', $this->getID()); foreach ($properties as $prop) { $prop->delete(); } $viewstate_query = id(new DifferentialViewStateQuery()) ->setViewer($viewer) ->withObjectPHIDs(array($this->getPHID())); $viewstates = new PhabricatorQueryIterator($viewstate_query); foreach ($viewstates as $viewstate) { $viewstate->delete(); } $this->saveTransaction(); } /* -( PhabricatorConduitResultInterface )---------------------------------- */ public function getFieldSpecificationsForConduit() { return array( id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('revisionPHID') ->setType('phid') ->setDescription(pht('Associated revision PHID.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('authorPHID') ->setType('phid') ->setDescription(pht('Revision author PHID.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('repositoryPHID') ->setType('phid') ->setDescription(pht('Associated repository PHID.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('refs') ->setType('map<string, wild>') ->setDescription(pht('List of related VCS references.')), ); } public function getFieldValuesForConduit() { $refs = array(); $branch = $this->getBranch(); if (strlen($branch)) { $refs[] = array( 'type' => 'branch', 'name' => $branch, ); } $onto = $this->loadTargetBranch(); if (strlen($onto)) { $refs[] = array( 'type' => 'onto', 'name' => $onto, ); } $base = $this->getSourceControlBaseRevision(); if (strlen($base)) { $refs[] = array( 'type' => 'base', 'identifier' => $base, ); } $bookmark = $this->getBookmark(); if (strlen($bookmark)) { $refs[] = array( 'type' => 'bookmark', 'name' => $bookmark, ); } $revision_phid = null; if ($this->getRevisionID()) { $revision_phid = $this->getRevision()->getPHID(); } return array( 'revisionPHID' => $revision_phid, 'authorPHID' => $this->getAuthorPHID(), 'repositoryPHID' => $this->getRepositoryPHID(), 'refs' => $refs, ); } public function getConduitSearchAttachments() { return array( id(new DifferentialCommitsSearchEngineAttachment()) ->setAttachmentKey('commits'), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialSchemaSpec.php
src/applications/differential/storage/DifferentialSchemaSpec.php
<?php final class DifferentialSchemaSpec extends PhabricatorConfigSchemaSpec { public function buildSchemata() { $this->buildEdgeSchemata(new DifferentialRevision()); $this->buildRawSchema( id(new DifferentialRevision())->getApplicationName(), DifferentialChangeset::TABLE_CACHE, array( 'id' => 'auto', 'cacheIndex' => 'bytes12', 'cache' => 'bytes', 'dateCreated' => 'epoch', ), array( 'PRIMARY' => array( 'columns' => array('id'), 'unique' => true, ), 'key_cacheIndex' => array( 'columns' => array('cacheIndex'), 'unique' => true, ), 'key_created' => array( 'columns' => array('dateCreated'), ), ), array( 'persistence' => PhabricatorConfigTableSchema::PERSISTENCE_CACHE, )); $this->buildRawSchema( id(new DifferentialRevision())->getApplicationName(), ArcanistDifferentialRevisionHash::TABLE_NAME, array( 'revisionID' => 'id', 'type' => 'bytes4', 'hash' => 'bytes40', ), array( 'type' => array( 'columns' => array('type', 'hash'), ), 'revisionID' => array( 'columns' => array('revisionID'), ), )); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialAffectedPath.php
src/applications/differential/storage/DifferentialAffectedPath.php
<?php /** * Denormalized index table which stores relationships between revisions in * Differential and paths in Diffusion. */ final class DifferentialAffectedPath extends DifferentialDAO { protected $repositoryID; protected $pathID; protected $revisionID; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'id' => null, 'repositoryID' => 'id?', ), self::CONFIG_KEY_SCHEMA => array( 'PRIMARY' => null, 'revisionID' => array( 'columns' => array('revisionID'), ), 'key_path' => array( 'columns' => array('pathID', 'repositoryID'), ), ), ) + parent::getConfiguration(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialInlineComment.php
src/applications/differential/storage/DifferentialInlineComment.php
<?php final class DifferentialInlineComment extends PhabricatorInlineComment { protected function newStorageObject() { return new DifferentialTransactionComment(); } public function getControllerURI() { return urisprintf( '/differential/comment/inline/edit/%s/', $this->getRevisionID()); } public function getTransactionCommentForSave() { $content_source = PhabricatorContentSource::newForSource( PhabricatorOldWorldContentSource::SOURCECONST); $this->getStorageObject() ->setViewPolicy('public') ->setEditPolicy($this->getAuthorPHID()) ->setContentSource($content_source) ->attachIsHidden(false) ->setCommentVersion(1); return $this->getStorageObject(); } public function supportsHiding() { if ($this->getSyntheticAuthor()) { return false; } return true; } public function isHidden() { if (!$this->supportsHiding()) { return false; } return $this->getStorageObject()->getIsHidden(); } public static function newFromModernComment( DifferentialTransactionComment $comment) { $obj = new DifferentialInlineComment(); $obj->setStorageObject($comment); return $obj; } public function setChangesetID($id) { $this->getStorageObject()->setChangesetID($id); return $this; } public function getChangesetID() { return $this->getStorageObject()->getChangesetID(); } public function setRevision(DifferentialRevision $revision) { $this->getStorageObject()->setRevisionPHID($revision->getPHID()); return $this; } public function getRevisionPHID() { return $this->getStorageObject()->getRevisionPHID(); } // Although these are purely transitional, they're also *extra* dumb. public function setRevisionID($revision_id) { $revision = id(new DifferentialRevision())->load($revision_id); return $this->setRevision($revision); } public function getRevisionID() { $phid = $this->getStorageObject()->getRevisionPHID(); if (!$phid) { return null; } $revision = id(new DifferentialRevision())->loadOneWhere( 'phid = %s', $phid); if (!$revision) { return null; } return $revision->getID(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialViewState.php
src/applications/differential/storage/DifferentialViewState.php
<?php final class DifferentialViewState extends DifferentialDAO implements PhabricatorPolicyInterface { protected $viewerPHID; protected $objectPHID; protected $viewState = array(); private $hasModifications; protected function getConfiguration() { return array( self::CONFIG_SERIALIZATION => array( 'viewState' => self::SERIALIZATION_JSON, ), self::CONFIG_KEY_SCHEMA => array( 'key_viewer' => array( 'columns' => array('viewerPHID', 'objectPHID'), 'unique' => true, ), 'key_object' => array( 'columns' => array('objectPHID'), ), 'key_modified' => array( 'columns' => array('dateModified'), ), ), ) + parent::getConfiguration(); } public function setChangesetProperty( DifferentialChangeset $changeset, $key, $value) { if ($this->getChangesetProperty($changeset, $key) === $value) { return; } $properties = array( 'value' => $value, 'epoch' => PhabricatorTime::getNow(), ); $diff_id = $changeset->getDiffID(); if ($diff_id !== null) { $properties['diffID'] = (int)$diff_id; } $changeset_id = $changeset->getID(); if ($changeset_id !== null) { $properties['changesetID'] = (int)$changeset_id; } $path_hash = $this->getChangesetPathHash($changeset); $changeset_phid = $this->getChangesetKey($changeset); $this->hasModifications = true; $this->viewState['changesets'][$path_hash][$key][$changeset_phid] = $properties; } public function getChangesetProperty( DifferentialChangeset $changeset, $key, $default = null) { $entries = $this->getChangesetPropertyEntries( $changeset, $key); $entries = isort($entries, 'epoch'); $entry = last($entries); if (!is_array($entry)) { $entry = array(); } return idx($entry, 'value', $default); } public function getChangesetPropertyEntries( DifferentialChangeset $changeset, $key) { $path_hash = $this->getChangesetPathHash($changeset); $entries = idxv($this->viewState, array('changesets', $path_hash, $key)); if (!is_array($entries)) { $entries = array(); } return $entries; } public function getHasModifications() { return $this->hasModifications; } private function getChangesetPathHash(DifferentialChangeset $changeset) { $path = $changeset->getFilename(); return PhabricatorHash::digestForIndex($path); } private function getChangesetKey(DifferentialChangeset $changeset) { $key = $changeset->getID(); if ($key === null) { return '*'; } return (string)$key; } public static function copyViewStatesToObject($src_phid, $dst_phid) { $table = new self(); $conn = $table->establishConnection('w'); queryfx( $conn, 'INSERT IGNORE INTO %R (viewerPHID, objectPHID, viewState, dateCreated, dateModified) SELECT viewerPHID, %s, viewState, dateCreated, dateModified FROM %R WHERE objectPHID = %s', $table, $dst_phid, $table, $src_phid); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { return PhabricatorPolicies::POLICY_NOONE; } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return ($viewer->getPHID() === $this->getViewerPHID()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialTransactionComment.php
src/applications/differential/storage/DifferentialTransactionComment.php
<?php final class DifferentialTransactionComment extends PhabricatorApplicationTransactionComment implements PhabricatorInlineCommentInterface { protected $revisionPHID; protected $changesetID; protected $isNewFile = 0; protected $lineNumber = 0; protected $lineLength = 0; protected $fixedState; protected $hasReplies = 0; protected $replyToCommentPHID; protected $attributes = array(); private $replyToComment = self::ATTACHABLE; private $isHidden = self::ATTACHABLE; private $changeset = self::ATTACHABLE; private $inlineContext = self::ATTACHABLE; public function getApplicationTransactionObject() { return new DifferentialTransaction(); } public function attachReplyToComment( DifferentialTransactionComment $comment = null) { $this->replyToComment = $comment; return $this; } public function getReplyToComment() { return $this->assertAttached($this->replyToComment); } protected function getConfiguration() { $config = parent::getConfiguration(); $config[self::CONFIG_COLUMN_SCHEMA] = array( 'revisionPHID' => 'phid?', 'changesetID' => 'id?', 'isNewFile' => 'bool', 'lineNumber' => 'uint32', 'lineLength' => 'uint32', 'fixedState' => 'text12?', 'hasReplies' => 'bool', 'replyToCommentPHID' => 'phid?', ) + $config[self::CONFIG_COLUMN_SCHEMA]; $config[self::CONFIG_KEY_SCHEMA] = array( 'key_draft' => array( 'columns' => array('authorPHID', 'transactionPHID'), ), 'key_changeset' => array( 'columns' => array('changesetID'), ), 'key_revision' => array( 'columns' => array('revisionPHID'), ), ) + $config[self::CONFIG_KEY_SCHEMA]; $config[self::CONFIG_SERIALIZATION] = array( 'attributes' => self::SERIALIZATION_JSON, ) + idx($config, self::CONFIG_SERIALIZATION, array()); return $config; } public function shouldUseMarkupCache($field) { // Only cache submitted comments. return ($this->getTransactionPHID() != null); } public static function sortAndGroupInlines( array $inlines, array $changesets) { assert_instances_of($inlines, 'DifferentialTransaction'); assert_instances_of($changesets, 'DifferentialChangeset'); $changesets = mpull($changesets, null, 'getID'); $changesets = msort($changesets, 'getFilename'); // Group the changesets by file and reorder them by display order. $inline_groups = array(); foreach ($inlines as $inline) { $changeset_id = $inline->getComment()->getChangesetID(); $inline_groups[$changeset_id][] = $inline; } $inline_groups = array_select_keys($inline_groups, array_keys($changesets)); foreach ($inline_groups as $changeset_id => $group) { // Sort the group of inlines by line number. $items = array(); foreach ($group as $inline) { $comment = $inline->getComment(); $num = $comment->getLineNumber(); $len = $comment->getLineLength(); $id = $comment->getID(); $items[] = array( 'inline' => $inline, 'sort' => sprintf('~%010d%010d%010d', $num, $len, $id), ); } $items = isort($items, 'sort'); $items = ipull($items, 'inline'); $inline_groups[$changeset_id] = $items; } return $inline_groups; } public function getIsHidden() { return $this->assertAttached($this->isHidden); } public function attachIsHidden($hidden) { $this->isHidden = $hidden; return $this; } public function getAttribute($key, $default = null) { return idx($this->attributes, $key, $default); } public function setAttribute($key, $value) { $this->attributes[$key] = $value; return $this; } public function newInlineCommentObject() { return DifferentialInlineComment::newFromModernComment($this); } public function getInlineContext() { return $this->assertAttached($this->inlineContext); } public function attachInlineContext( PhabricatorInlineCommentContext $context = null) { $this->inlineContext = $context; return $this; } public function isEmptyComment() { if (!parent::isEmptyComment()) { return false; } return $this->newInlineCommentObject() ->getContentState() ->isEmptyContentState(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialChangeset.php
src/applications/differential/storage/DifferentialChangeset.php
<?php final class DifferentialChangeset extends DifferentialDAO implements PhabricatorPolicyInterface, PhabricatorDestructibleInterface, PhabricatorConduitResultInterface { protected $diffID; protected $oldFile; protected $filename; protected $awayPaths; protected $changeType; protected $fileType; protected $metadata = array(); protected $oldProperties; protected $newProperties; protected $addLines; protected $delLines; private $unsavedHunks = array(); private $hunks = self::ATTACHABLE; private $diff = self::ATTACHABLE; private $authorityPackages; private $changesetPackages; private $newFileObject = self::ATTACHABLE; private $oldFileObject = self::ATTACHABLE; private $hasOldState; private $hasNewState; private $oldStateMetadata; private $newStateMetadata; private $oldFileType; private $newFileType; const TABLE_CACHE = 'differential_changeset_parse_cache'; const METADATA_TRUSTED_ATTRIBUTES = 'attributes.trusted'; const METADATA_UNTRUSTED_ATTRIBUTES = 'attributes.untrusted'; const METADATA_EFFECT_HASH = 'hash.effect'; const ATTRIBUTE_GENERATED = 'generated'; protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_SERIALIZATION => array( 'metadata' => self::SERIALIZATION_JSON, 'oldProperties' => self::SERIALIZATION_JSON, 'newProperties' => self::SERIALIZATION_JSON, 'awayPaths' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'oldFile' => 'bytes?', 'filename' => 'bytes', 'changeType' => 'uint32', 'fileType' => 'uint32', 'addLines' => 'uint32', 'delLines' => 'uint32', // T6203/NULLABILITY // These should all be non-nullable, and store reasonable default // JSON values if empty. 'awayPaths' => 'text?', 'metadata' => 'text?', 'oldProperties' => 'text?', 'newProperties' => 'text?', ), self::CONFIG_KEY_SCHEMA => array( 'diffID' => array( 'columns' => array('diffID'), ), ), ) + parent::getConfiguration(); } public function getPHIDType() { return DifferentialChangesetPHIDType::TYPECONST; } public function getAffectedLineCount() { return $this->getAddLines() + $this->getDelLines(); } public function attachHunks(array $hunks) { assert_instances_of($hunks, 'DifferentialHunk'); $this->hunks = $hunks; return $this; } public function getHunks() { return $this->assertAttached($this->hunks); } public function getDisplayFilename() { $name = $this->getFilename(); if ($this->getFileType() == DifferentialChangeType::FILE_DIRECTORY) { $name .= '/'; } return $name; } public function getOwnersFilename() { // TODO: For Subversion, we should adjust these paths to be relative to // the repository root where possible. $path = $this->getFilename(); if (!isset($path[0])) { return '/'; } if ($path[0] != '/') { $path = '/'.$path; } return $path; } public function addUnsavedHunk(DifferentialHunk $hunk) { if ($this->hunks === self::ATTACHABLE) { $this->hunks = array(); } $this->hunks[] = $hunk; $this->unsavedHunks[] = $hunk; return $this; } public function setAuthorityPackages(array $authority_packages) { $this->authorityPackages = mpull($authority_packages, null, 'getPHID'); return $this; } public function getAuthorityPackages() { return $this->authorityPackages; } public function setChangesetPackages($changeset_packages) { $this->changesetPackages = mpull($changeset_packages, null, 'getPHID'); return $this; } public function getChangesetPackages() { return $this->changesetPackages; } public function setHasOldState($has_old_state) { $this->hasOldState = $has_old_state; return $this; } public function setHasNewState($has_new_state) { $this->hasNewState = $has_new_state; return $this; } public function hasOldState() { if ($this->hasOldState !== null) { return $this->hasOldState; } $change_type = $this->getChangeType(); return !DifferentialChangeType::isCreateChangeType($change_type); } public function hasNewState() { if ($this->hasNewState !== null) { return $this->hasNewState; } $change_type = $this->getChangeType(); return !DifferentialChangeType::isDeleteChangeType($change_type); } public function save() { $this->openTransaction(); $ret = parent::save(); foreach ($this->unsavedHunks as $hunk) { $hunk->setChangesetID($this->getID()); $hunk->save(); } $this->saveTransaction(); return $ret; } public function delete() { $this->openTransaction(); $hunks = id(new DifferentialHunk())->loadAllWhere( 'changesetID = %d', $this->getID()); foreach ($hunks as $hunk) { $hunk->delete(); } $this->unsavedHunks = array(); queryfx( $this->establishConnection('w'), 'DELETE FROM %T WHERE id = %d', self::TABLE_CACHE, $this->getID()); $ret = parent::delete(); $this->saveTransaction(); return $ret; } /** * Test if this changeset and some other changeset put the affected file in * the same state. * * @param DifferentialChangeset Changeset to compare against. * @return bool True if the two changesets have the same effect. */ public function hasSameEffectAs(DifferentialChangeset $other) { if ($this->getFilename() !== $other->getFilename()) { return false; } $hash_key = self::METADATA_EFFECT_HASH; $u_hash = $this->getChangesetMetadata($hash_key); if ($u_hash === null) { return false; } $v_hash = $other->getChangesetMetadata($hash_key); if ($v_hash === null) { return false; } if ($u_hash !== $v_hash) { return false; } // Make sure the final states for the file properties (like the "+x" // executable bit) match one another. $u_props = $this->getNewProperties(); $v_props = $other->getNewProperties(); ksort($u_props); ksort($v_props); if ($u_props !== $v_props) { return false; } return true; } public function getSortKey() { $sort_key = $this->getFilename(); // Sort files with ".h" in them first, so headers (.h, .hpp) come before // implementations (.c, .cpp, .cs). $sort_key = str_replace('.h', '.!h', $sort_key); return $sort_key; } public function makeNewFile() { $file = mpull($this->getHunks(), 'makeNewFile'); return implode('', $file); } public function makeOldFile() { $file = mpull($this->getHunks(), 'makeOldFile'); return implode('', $file); } public function makeChangesWithContext($num_lines = 3) { $with_context = array(); foreach ($this->getHunks() as $hunk) { $context = array(); $changes = explode("\n", $hunk->getChanges()); foreach ($changes as $l => $line) { $type = substr($line, 0, 1); if ($type == '+' || $type == '-') { $context += array_fill($l - $num_lines, 2 * $num_lines + 1, true); } } $with_context[] = array_intersect_key($changes, $context); } return array_mergev($with_context); } public function getAnchorName() { return 'change-'.PhabricatorHash::digestForAnchor($this->getFilename()); } public function getAbsoluteRepositoryPath( PhabricatorRepository $repository = null, DifferentialDiff $diff = null) { $base = '/'; if ($diff && $diff->getSourceControlPath()) { $base = id(new PhutilURI($diff->getSourceControlPath()))->getPath(); } $path = $this->getFilename(); $path = rtrim($base, '/').'/'.ltrim($path, '/'); $svn = PhabricatorRepositoryType::REPOSITORY_TYPE_SVN; if ($repository && $repository->getVersionControlSystem() == $svn) { $prefix = $repository->getDetail('remote-uri'); $prefix = id(new PhutilURI($prefix))->getPath(); if (!strncmp($path, $prefix, strlen($prefix))) { $path = substr($path, strlen($prefix)); } $path = '/'.ltrim($path, '/'); } return $path; } public function attachDiff(DifferentialDiff $diff) { $this->diff = $diff; return $this; } public function getDiff() { return $this->assertAttached($this->diff); } public function getOldStatePathVector() { $path = $this->getOldFile(); if ($path === null || !strlen($path)) { $path = $this->getFilename(); } $path = trim($path, '/'); $path = explode('/', $path); return $path; } public function getNewStatePathVector() { if (!$this->hasNewState()) { return null; } $path = $this->getFilename(); $path = trim($path, '/'); $path = explode('/', $path); return $path; } public function newFileTreeIcon() { $icon = $this->getPathIconIcon(); $color = $this->getPathIconColor(); return id(new PHUIIconView()) ->setIcon("{$icon} {$color}"); } public function getIsOwnedChangeset() { $authority_packages = $this->getAuthorityPackages(); $changeset_packages = $this->getChangesetPackages(); if (!$authority_packages || !$changeset_packages) { return false; } return (bool)array_intersect_key($authority_packages, $changeset_packages); } public function getIsLowImportanceChangeset() { if (!$this->hasNewState()) { return true; } if ($this->isGeneratedChangeset()) { return true; } return false; } public function getPathIconIcon() { return idx($this->getPathIconDetails(), 'icon'); } public function getPathIconColor() { return idx($this->getPathIconDetails(), 'color'); } private function getPathIconDetails() { $change_icons = array( DifferentialChangeType::TYPE_DELETE => array( 'icon' => 'fa-times', 'color' => 'delete-color', ), DifferentialChangeType::TYPE_ADD => array( 'icon' => 'fa-plus', 'color' => 'create-color', ), DifferentialChangeType::TYPE_MOVE_AWAY => array( 'icon' => 'fa-circle-o', 'color' => 'grey', ), DifferentialChangeType::TYPE_MULTICOPY => array( 'icon' => 'fa-circle-o', 'color' => 'grey', ), DifferentialChangeType::TYPE_MOVE_HERE => array( 'icon' => 'fa-plus-circle', 'color' => 'create-color', ), DifferentialChangeType::TYPE_COPY_HERE => array( 'icon' => 'fa-plus-circle', 'color' => 'create-color', ), ); $change_type = $this->getChangeType(); if (isset($change_icons[$change_type])) { return $change_icons[$change_type]; } if ($this->isGeneratedChangeset()) { return array( 'icon' => 'fa-cogs', 'color' => 'grey', ); } $file_type = $this->getFileType(); $icon = DifferentialChangeType::getIconForFileType($file_type); return array( 'icon' => $icon, 'color' => 'bluetext', ); } public function setChangesetMetadata($key, $value) { if (!is_array($this->metadata)) { $this->metadata = array(); } $this->metadata[$key] = $value; return $this; } public function getChangesetMetadata($key, $default = null) { if (!is_array($this->metadata)) { return $default; } return idx($this->metadata, $key, $default); } private function setInternalChangesetAttribute($trusted, $key, $value) { if ($trusted) { $meta_key = self::METADATA_TRUSTED_ATTRIBUTES; } else { $meta_key = self::METADATA_UNTRUSTED_ATTRIBUTES; } $attributes = $this->getChangesetMetadata($meta_key, array()); $attributes[$key] = $value; $this->setChangesetMetadata($meta_key, $attributes); return $this; } private function getInternalChangesetAttributes($trusted) { if ($trusted) { $meta_key = self::METADATA_TRUSTED_ATTRIBUTES; } else { $meta_key = self::METADATA_UNTRUSTED_ATTRIBUTES; } return $this->getChangesetMetadata($meta_key, array()); } public function setTrustedChangesetAttribute($key, $value) { return $this->setInternalChangesetAttribute(true, $key, $value); } public function getTrustedChangesetAttributes() { return $this->getInternalChangesetAttributes(true); } public function getTrustedChangesetAttribute($key, $default = null) { $map = $this->getTrustedChangesetAttributes(); return idx($map, $key, $default); } public function setUntrustedChangesetAttribute($key, $value) { return $this->setInternalChangesetAttribute(false, $key, $value); } public function getUntrustedChangesetAttributes() { return $this->getInternalChangesetAttributes(false); } public function getUntrustedChangesetAttribute($key, $default = null) { $map = $this->getUntrustedChangesetAttributes(); return idx($map, $key, $default); } public function getChangesetAttributes() { // Prefer trusted values over untrusted values when both exist. return $this->getTrustedChangesetAttributes() + $this->getUntrustedChangesetAttributes(); } public function getChangesetAttribute($key, $default = null) { $map = $this->getChangesetAttributes(); return idx($map, $key, $default); } public function isGeneratedChangeset() { return $this->getChangesetAttribute(self::ATTRIBUTE_GENERATED); } public function getNewFileObjectPHID() { $metadata = $this->getMetadata(); return idx($metadata, 'new:binary-phid'); } public function getOldFileObjectPHID() { $metadata = $this->getMetadata(); return idx($metadata, 'old:binary-phid'); } public function attachNewFileObject(PhabricatorFile $file) { $this->newFileObject = $file; return $this; } public function getNewFileObject() { return $this->assertAttached($this->newFileObject); } public function attachOldFileObject(PhabricatorFile $file) { $this->oldFileObject = $file; return $this; } public function getOldFileObject() { return $this->assertAttached($this->oldFileObject); } public function newComparisonChangeset( DifferentialChangeset $against = null) { $left = $this; $right = $against; $left_data = $left->makeNewFile(); $left_properties = $left->getNewProperties(); $left_metadata = $left->getNewStateMetadata(); $left_state = $left->hasNewState(); $shared_metadata = $left->getMetadata(); $left_type = $left->getNewFileType(); if ($right) { $right_data = $right->makeNewFile(); $right_properties = $right->getNewProperties(); $right_metadata = $right->getNewStateMetadata(); $right_state = $right->hasNewState(); $shared_metadata = $right->getMetadata(); $right_type = $right->getNewFileType(); $file_name = $right->getFilename(); } else { $right_data = $left->makeOldFile(); $right_properties = $left->getOldProperties(); $right_metadata = $left->getOldStateMetadata(); $right_state = $left->hasOldState(); $right_type = $left->getOldFileType(); $file_name = $left->getFilename(); } $engine = new PhabricatorDifferenceEngine(); $synthetic = $engine->generateChangesetFromFileContent( $left_data, $right_data); $comparison = id(new self()) ->makeEphemeral(true) ->attachDiff($left->getDiff()) ->setOldFile($left->getFilename()) ->setFilename($file_name); // TODO: Change type? // TODO: Away paths? // TODO: View state key? $comparison->attachHunks($synthetic->getHunks()); $comparison->setOldProperties($left_properties); $comparison->setNewProperties($right_properties); $comparison ->setOldStateMetadata($left_metadata) ->setNewStateMetadata($right_metadata) ->setHasOldState($left_state) ->setHasNewState($right_state) ->setOldFileType($left_type) ->setNewFileType($right_type); // NOTE: Some metadata is not stored statefully, like the "generated" // flag. For now, use the rightmost "new state" metadata to fill in these // values. $metadata = $comparison->getMetadata(); $metadata = $metadata + $shared_metadata; $comparison->setMetadata($metadata); return $comparison; } public function setNewFileType($new_file_type) { $this->newFileType = $new_file_type; return $this; } public function getNewFileType() { if ($this->newFileType !== null) { return $this->newFileType; } return $this->getFiletype(); } public function setOldFileType($old_file_type) { $this->oldFileType = $old_file_type; return $this; } public function getOldFileType() { if ($this->oldFileType !== null) { return $this->oldFileType; } return $this->getFileType(); } public function hasSourceTextBody() { $type_map = array( DifferentialChangeType::FILE_TEXT => true, DifferentialChangeType::FILE_SYMLINK => true, ); $old_body = isset($type_map[$this->getOldFileType()]); $new_body = isset($type_map[$this->getNewFileType()]); return ($old_body || $new_body); } public function getNewStateMetadata() { return $this->getMetadataWithPrefix('new:'); } public function setNewStateMetadata(array $metadata) { return $this->setMetadataWithPrefix($metadata, 'new:'); } public function getOldStateMetadata() { return $this->getMetadataWithPrefix('old:'); } public function setOldStateMetadata(array $metadata) { return $this->setMetadataWithPrefix($metadata, 'old:'); } private function getMetadataWithPrefix($prefix) { $length = strlen($prefix); $result = array(); foreach ($this->getMetadata() as $key => $value) { if (strncmp($key, $prefix, $length)) { continue; } $key = substr($key, $length); $result[$key] = $value; } return $result; } private function setMetadataWithPrefix(array $metadata, $prefix) { foreach ($metadata as $key => $value) { $key = $prefix.$key; $this->metadata[$key] = $value; } return $this; } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { return $this->getDiff()->getPolicy($capability); } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return $this->getDiff()->hasAutomaticCapability($capability, $viewer); } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $this->openTransaction(); $hunks = id(new DifferentialHunk())->loadAllWhere( 'changesetID = %d', $this->getID()); foreach ($hunks as $hunk) { $engine->destroyObject($hunk); } $this->delete(); $this->saveTransaction(); } /* -( PhabricatorConduitResultInterface )---------------------------------- */ public function getFieldSpecificationsForConduit() { return array( id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('diffPHID') ->setType('phid') ->setDescription(pht('The diff the changeset is attached to.')), ); } public function getFieldValuesForConduit() { $diff = $this->getDiff(); $repository = null; if ($diff) { $revision = $diff->getRevision(); if ($revision) { $repository = $revision->getRepository(); } } $absolute_path = $this->getAbsoluteRepositoryPath($repository, $diff); if (strlen($absolute_path)) { $absolute_path = base64_encode($absolute_path); } else { $absolute_path = null; } $display_path = $this->getDisplayFilename(); return array( 'diffPHID' => $diff->getPHID(), 'path' => array( 'displayPath' => $display_path, 'absolutePath.base64' => $absolute_path, ), ); } public function getConduitSearchAttachments() { 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/differential/storage/DifferentialHiddenComment.php
src/applications/differential/storage/DifferentialHiddenComment.php
<?php final class DifferentialHiddenComment extends DifferentialDAO { protected $userPHID; protected $commentID; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_KEY_SCHEMA => array( 'key_user' => array( 'columns' => array('userPHID', 'commentID'), 'unique' => true, ), 'key_comment' => array( 'columns' => array('commentID'), ), ), ) + parent::getConfiguration(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialDiffTransaction.php
src/applications/differential/storage/DifferentialDiffTransaction.php
<?php final class DifferentialDiffTransaction extends PhabricatorApplicationTransaction { const TYPE_DIFF_CREATE = 'differential:diff:create'; public function getApplicationName() { return 'differential'; } public function getApplicationTransactionType() { return DifferentialDiffPHIDType::TYPECONST; } public function shouldHideForMail(array $xactions) { return true; } public function getActionName() { switch ($this->getTransactionType()) { case self::TYPE_DIFF_CREATE; return pht('Created'); } return parent::getActionName(); } public function getTitle() { $author_phid = $this->getAuthorPHID(); $author_handle = $this->renderHandleLink($author_phid); $old = $this->getOldValue(); $new = $this->getNewValue(); switch ($this->getTransactionType()) { case self::TYPE_DIFF_CREATE; return pht( '%s created this diff.', $author_handle); } return parent::getTitle(); } public function getIcon() { switch ($this->getTransactionType()) { case self::TYPE_DIFF_CREATE: return 'fa-refresh'; } return parent::getIcon(); } public function getColor() { switch ($this->getTransactionType()) { case self::TYPE_DIFF_CREATE: return PhabricatorTransactions::COLOR_SKY; } return parent::getColor(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialReviewer.php
src/applications/differential/storage/DifferentialReviewer.php
<?php final class DifferentialReviewer extends DifferentialDAO { protected $revisionPHID; protected $reviewerPHID; protected $reviewerStatus; protected $lastActionDiffPHID; protected $lastCommentDiffPHID; protected $lastActorPHID; protected $voidedPHID; protected $options = array(); private $authority = array(); private $changesets = self::ATTACHABLE; protected function getConfiguration() { return array( self::CONFIG_SERIALIZATION => array( 'options' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'reviewerStatus' => 'text64', 'lastActionDiffPHID' => 'phid?', 'lastCommentDiffPHID' => 'phid?', 'lastActorPHID' => 'phid?', 'voidedPHID' => 'phid?', ), self::CONFIG_KEY_SCHEMA => array( 'key_revision' => array( 'columns' => array('revisionPHID', 'reviewerPHID'), 'unique' => true, ), 'key_reviewer' => array( 'columns' => array('reviewerPHID', 'revisionPHID'), ), ), ) + parent::getConfiguration(); } public function isUser() { $user_type = PhabricatorPeopleUserPHIDType::TYPECONST; return (phid_get_type($this->getReviewerPHID()) == $user_type); } public function isPackage() { $package_type = PhabricatorOwnersPackagePHIDType::TYPECONST; return (phid_get_type($this->getReviewerPHID()) == $package_type); } public function attachAuthority(PhabricatorUser $user, $has_authority) { $this->authority[$user->getCacheFragment()] = $has_authority; return $this; } public function hasAuthority(PhabricatorUser $viewer) { $cache_fragment = $viewer->getCacheFragment(); return $this->assertAttachedKey($this->authority, $cache_fragment); } public function attachChangesets(array $changesets) { $this->changesets = $changesets; return $this; } public function getChangesets() { return $this->assertAttached($this->changesets); } public function setOption($key, $value) { $this->options[$key] = $value; return $this; } public function getOption($key, $default = null) { return idx($this->options, $key, $default); } public function isResigned() { $status_resigned = DifferentialReviewerStatus::STATUS_RESIGNED; return ($this->getReviewerStatus() == $status_resigned); } public function isBlocking() { $status_blocking = DifferentialReviewerStatus::STATUS_BLOCKING; return ($this->getReviewerStatus() == $status_blocking); } public function isRejected($diff_phid) { $status_rejected = DifferentialReviewerStatus::STATUS_REJECTED; if ($this->getReviewerStatus() != $status_rejected) { return false; } if ($this->getVoidedPHID()) { return false; } if ($this->isCurrentAction($diff_phid)) { return true; } return false; } public function isAccepted($diff_phid) { $status_accepted = DifferentialReviewerStatus::STATUS_ACCEPTED; if ($this->getReviewerStatus() != $status_accepted) { return false; } // If this accept has been voided (for example, but a reviewer using // "Request Review"), don't count it as a real "Accept" even if it is // against the current diff PHID. if ($this->getVoidedPHID()) { return false; } if ($this->isCurrentAction($diff_phid)) { return true; } $sticky_key = 'differential.sticky-accept'; $is_sticky = PhabricatorEnv::getEnvConfig($sticky_key); if ($is_sticky) { return true; } return false; } private function isCurrentAction($diff_phid) { if (!$diff_phid) { return true; } $action_phid = $this->getLastActionDiffPHID(); if (!$action_phid) { return true; } if ($action_phid == $diff_phid) { return true; } return false; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialDAO.php
src/applications/differential/storage/DifferentialDAO.php
<?php abstract class DifferentialDAO extends PhabricatorLiskDAO { public function getApplicationName() { return 'differential'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialTransaction.php
src/applications/differential/storage/DifferentialTransaction.php
<?php final class DifferentialTransaction extends PhabricatorModularTransaction { private $isCommandeerSideEffect; const TYPE_INLINE = 'differential:inline'; const TYPE_ACTION = 'differential:action'; const MAILTAG_REVIEWERS = 'differential-reviewers'; const MAILTAG_CLOSED = 'differential-committed'; const MAILTAG_CC = 'differential-cc'; const MAILTAG_COMMENT = 'differential-comment'; const MAILTAG_UPDATED = 'differential-updated'; const MAILTAG_REVIEW_REQUEST = 'differential-review-request'; const MAILTAG_OTHER = 'differential-other'; public function getBaseTransactionClass() { return 'DifferentialRevisionTransactionType'; } protected function newFallbackModularTransactionType() { // TODO: This allows us to render modern strings for older transactions // without doing a migration. At some point, we should do a migration and // throw this away. // NOTE: Old reviewer edits are raw edge transactions. They could be // migrated to modular transactions when the rest of this migrates. $xaction_type = $this->getTransactionType(); if ($xaction_type == PhabricatorTransactions::TYPE_CUSTOMFIELD) { switch ($this->getMetadataValue('customfield:key')) { case 'differential:title': return new DifferentialRevisionTitleTransaction(); case 'differential:test-plan': return new DifferentialRevisionTestPlanTransaction(); case 'differential:repository': return new DifferentialRevisionRepositoryTransaction(); } } return parent::newFallbackModularTransactionType(); } public function setIsCommandeerSideEffect($is_side_effect) { $this->isCommandeerSideEffect = $is_side_effect; return $this; } public function getIsCommandeerSideEffect() { return $this->isCommandeerSideEffect; } public function getApplicationName() { return 'differential'; } public function getApplicationTransactionType() { return DifferentialRevisionPHIDType::TYPECONST; } public function getApplicationTransactionCommentObject() { return new DifferentialTransactionComment(); } public function shouldHide() { $old = $this->getOldValue(); $new = $this->getNewValue(); switch ($this->getTransactionType()) { case DifferentialRevisionRequestReviewTransaction::TRANSACTIONTYPE: // Don't hide the initial "X requested review: ..." transaction from // mail or feed even when it occurs during creation. We need this // transaction to survive so we'll generate mail and feed stories when // revisions immediately leave the draft state. See T13035 for // discussion. return false; } return parent::shouldHide(); } public function shouldHideForMail(array $xactions) { switch ($this->getTransactionType()) { case DifferentialRevisionReviewersTransaction::TRANSACTIONTYPE: // Don't hide the initial "X added reviewers: ..." transaction during // object creation from mail. See T12118 and PHI54. return false; } return parent::shouldHideForMail($xactions); } public function isInlineCommentTransaction() { switch ($this->getTransactionType()) { case self::TYPE_INLINE: return true; } return parent::isInlineCommentTransaction(); } public function getRequiredHandlePHIDs() { $phids = parent::getRequiredHandlePHIDs(); $old = $this->getOldValue(); $new = $this->getNewValue(); switch ($this->getTransactionType()) { case self::TYPE_ACTION: if ($new == DifferentialAction::ACTION_CLOSE && $this->getMetadataValue('isCommitClose')) { $phids[] = $this->getMetadataValue('commitPHID'); if ($this->getMetadataValue('committerPHID')) { $phids[] = $this->getMetadataValue('committerPHID'); } if ($this->getMetadataValue('authorPHID')) { $phids[] = $this->getMetadataValue('authorPHID'); } } break; } return $phids; } public function getActionStrength() { switch ($this->getTransactionType()) { case self::TYPE_ACTION: return 300; } return parent::getActionStrength(); } public function getActionName() { switch ($this->getTransactionType()) { case self::TYPE_INLINE: return pht('Commented On'); case self::TYPE_ACTION: $map = array( DifferentialAction::ACTION_ACCEPT => pht('Accepted'), DifferentialAction::ACTION_REJECT => pht('Requested Changes To'), DifferentialAction::ACTION_RETHINK => pht('Planned Changes To'), DifferentialAction::ACTION_ABANDON => pht('Abandoned'), DifferentialAction::ACTION_CLOSE => pht('Closed'), DifferentialAction::ACTION_REQUEST => pht('Requested A Review Of'), DifferentialAction::ACTION_RESIGN => pht('Resigned From'), DifferentialAction::ACTION_ADDREVIEWERS => pht('Added Reviewers'), DifferentialAction::ACTION_CLAIM => pht('Commandeered'), DifferentialAction::ACTION_REOPEN => pht('Reopened'), ); $name = idx($map, $this->getNewValue()); if ($name !== null) { return $name; } break; } return parent::getActionName(); } public function getMailTags() { $tags = array(); switch ($this->getTransactionType()) { case PhabricatorTransactions::TYPE_SUBSCRIBERS; $tags[] = self::MAILTAG_CC; break; case self::TYPE_ACTION: switch ($this->getNewValue()) { case DifferentialAction::ACTION_CLOSE: $tags[] = self::MAILTAG_CLOSED; break; } break; case DifferentialRevisionUpdateTransaction::TRANSACTIONTYPE: $old = $this->getOldValue(); if ($old === null) { $tags[] = self::MAILTAG_REVIEW_REQUEST; } else { $tags[] = self::MAILTAG_UPDATED; } break; case PhabricatorTransactions::TYPE_COMMENT: case self::TYPE_INLINE: $tags[] = self::MAILTAG_COMMENT; break; case DifferentialRevisionReviewersTransaction::TRANSACTIONTYPE: $tags[] = self::MAILTAG_REVIEWERS; break; case DifferentialRevisionCloseTransaction::TRANSACTIONTYPE: $tags[] = self::MAILTAG_CLOSED; break; } if (!$tags) { $tags[] = self::MAILTAG_OTHER; } return $tags; } public function getTitle() { $author_phid = $this->getAuthorPHID(); $author_handle = $this->renderHandleLink($author_phid); $old = $this->getOldValue(); $new = $this->getNewValue(); switch ($this->getTransactionType()) { case self::TYPE_INLINE: return pht( '%s added inline comments.', $author_handle); case self::TYPE_ACTION: switch ($new) { case DifferentialAction::ACTION_CLOSE: if (!$this->getMetadataValue('isCommitClose')) { return DifferentialAction::getBasicStoryText( $new, $author_handle); } $commit_name = $this->renderHandleLink( $this->getMetadataValue('commitPHID')); $committer_phid = $this->getMetadataValue('committerPHID'); $author_phid = $this->getMetadataValue('authorPHID'); if ($this->getHandleIfExists($committer_phid)) { $committer_name = $this->renderHandleLink($committer_phid); } else { $committer_name = $this->getMetadataValue('committerName'); } if ($this->getHandleIfExists($author_phid)) { $author_name = $this->renderHandleLink($author_phid); } else { $author_name = $this->getMetadataValue('authorName'); } if ($committer_name && ($committer_name != $author_name)) { return pht( 'Closed by commit %s (authored by %s, committed by %s).', $commit_name, $author_name, $committer_name); } else { return pht( 'Closed by commit %s (authored by %s).', $commit_name, $author_name); } break; default: return DifferentialAction::getBasicStoryText($new, $author_handle); } break; } return parent::getTitle(); } public function renderExtraInformationLink() { if ($this->getMetadataValue('revisionMatchData')) { $details_href = '/differential/revision/closedetails/'.$this->getPHID().'/'; $details_link = javelin_tag( 'a', array( 'href' => $details_href, 'sigil' => 'workflow', ), pht('Explain Why')); return $details_link; } return parent::renderExtraInformationLink(); } public function getTitleForFeed() { $author_phid = $this->getAuthorPHID(); $object_phid = $this->getObjectPHID(); $old = $this->getOldValue(); $new = $this->getNewValue(); $author_link = $this->renderHandleLink($author_phid); $object_link = $this->renderHandleLink($object_phid); switch ($this->getTransactionType()) { case self::TYPE_INLINE: return pht( '%s added inline comments to %s.', $author_link, $object_link); case self::TYPE_ACTION: switch ($new) { case DifferentialAction::ACTION_ACCEPT: return pht( '%s accepted %s.', $author_link, $object_link); case DifferentialAction::ACTION_REJECT: return pht( '%s requested changes to %s.', $author_link, $object_link); case DifferentialAction::ACTION_RETHINK: return pht( '%s planned changes to %s.', $author_link, $object_link); case DifferentialAction::ACTION_ABANDON: return pht( '%s abandoned %s.', $author_link, $object_link); case DifferentialAction::ACTION_CLOSE: if (!$this->getMetadataValue('isCommitClose')) { return pht( '%s closed %s.', $author_link, $object_link); } else { $commit_name = $this->renderHandleLink( $this->getMetadataValue('commitPHID')); $committer_phid = $this->getMetadataValue('committerPHID'); $author_phid = $this->getMetadataValue('authorPHID'); if ($this->getHandleIfExists($committer_phid)) { $committer_name = $this->renderHandleLink($committer_phid); } else { $committer_name = $this->getMetadataValue('committerName'); } if ($this->getHandleIfExists($author_phid)) { $author_name = $this->renderHandleLink($author_phid); } else { $author_name = $this->getMetadataValue('authorName'); } // Check if the committer and author are the same. They're the // same if both resolved and are the same user, or if neither // resolved and the text is identical. if ($committer_phid && $author_phid) { $same_author = ($committer_phid == $author_phid); } else if (!$committer_phid && !$author_phid) { $same_author = ($committer_name == $author_name); } else { $same_author = false; } if ($committer_name && !$same_author) { return pht( '%s closed %s by committing %s (authored by %s).', $author_link, $object_link, $commit_name, $author_name); } else { return pht( '%s closed %s by committing %s.', $author_link, $object_link, $commit_name); } } break; case DifferentialAction::ACTION_REQUEST: return pht( '%s requested review of %s.', $author_link, $object_link); case DifferentialAction::ACTION_RECLAIM: return pht( '%s reclaimed %s.', $author_link, $object_link); case DifferentialAction::ACTION_RESIGN: return pht( '%s resigned from %s.', $author_link, $object_link); case DifferentialAction::ACTION_CLAIM: return pht( '%s commandeered %s.', $author_link, $object_link); case DifferentialAction::ACTION_REOPEN: return pht( '%s reopened %s.', $author_link, $object_link); } break; } return parent::getTitleForFeed(); } public function getIcon() { switch ($this->getTransactionType()) { case self::TYPE_INLINE: return 'fa-comment'; case self::TYPE_ACTION: switch ($this->getNewValue()) { case DifferentialAction::ACTION_CLOSE: return 'fa-check'; case DifferentialAction::ACTION_ACCEPT: return 'fa-check-circle-o'; case DifferentialAction::ACTION_REJECT: return 'fa-times-circle-o'; case DifferentialAction::ACTION_ABANDON: return 'fa-plane'; case DifferentialAction::ACTION_RETHINK: return 'fa-headphones'; case DifferentialAction::ACTION_REQUEST: return 'fa-refresh'; case DifferentialAction::ACTION_RECLAIM: case DifferentialAction::ACTION_REOPEN: return 'fa-bullhorn'; case DifferentialAction::ACTION_RESIGN: return 'fa-flag'; case DifferentialAction::ACTION_CLAIM: return 'fa-flag'; } case PhabricatorTransactions::TYPE_EDGE: switch ($this->getMetadataValue('edge:type')) { case DifferentialRevisionHasReviewerEdgeType::EDGECONST: return 'fa-user'; } } return parent::getIcon(); } public function shouldDisplayGroupWith(array $group) { // Never group status changes with other types of actions, they're indirect // and don't make sense when combined with direct actions. if ($this->isStatusTransaction($this)) { return false; } foreach ($group as $xaction) { if ($this->isStatusTransaction($xaction)) { return false; } } return parent::shouldDisplayGroupWith($group); } private function isStatusTransaction($xaction) { $status_type = DifferentialRevisionStatusTransaction::TRANSACTIONTYPE; if ($xaction->getTransactionType() == $status_type) { return true; } return false; } public function getColor() { switch ($this->getTransactionType()) { case self::TYPE_ACTION: switch ($this->getNewValue()) { case DifferentialAction::ACTION_CLOSE: return PhabricatorTransactions::COLOR_INDIGO; case DifferentialAction::ACTION_ACCEPT: return PhabricatorTransactions::COLOR_GREEN; case DifferentialAction::ACTION_REJECT: return PhabricatorTransactions::COLOR_RED; case DifferentialAction::ACTION_ABANDON: return PhabricatorTransactions::COLOR_INDIGO; case DifferentialAction::ACTION_RETHINK: return PhabricatorTransactions::COLOR_RED; case DifferentialAction::ACTION_REQUEST: return PhabricatorTransactions::COLOR_SKY; case DifferentialAction::ACTION_RECLAIM: return PhabricatorTransactions::COLOR_SKY; case DifferentialAction::ACTION_REOPEN: return PhabricatorTransactions::COLOR_SKY; case DifferentialAction::ACTION_RESIGN: return PhabricatorTransactions::COLOR_ORANGE; case DifferentialAction::ACTION_CLAIM: return PhabricatorTransactions::COLOR_YELLOW; } } return parent::getColor(); } public function getNoEffectDescription() { switch ($this->getTransactionType()) { case self::TYPE_ACTION: switch ($this->getNewValue()) { case DifferentialAction::ACTION_CLOSE: return pht('This revision is already closed.'); case DifferentialAction::ACTION_ABANDON: return pht('This revision has already been abandoned.'); case DifferentialAction::ACTION_RECLAIM: return pht( 'You can not reclaim this revision because his revision is '. 'not abandoned.'); case DifferentialAction::ACTION_REOPEN: return pht( 'You can not reopen this revision because this revision is '. 'not closed.'); case DifferentialAction::ACTION_RETHINK: return pht('This revision already requires changes.'); case DifferentialAction::ACTION_CLAIM: return pht( 'You can not commandeer this revision because you already own '. 'it.'); } break; } return parent::getNoEffectDescription(); } public function renderAsTextForDoorkeeper( DoorkeeperFeedStoryPublisher $publisher, PhabricatorFeedStory $story, array $xactions) { $body = parent::renderAsTextForDoorkeeper($publisher, $story, $xactions); $inlines = array(); foreach ($xactions as $xaction) { if ($xaction->getTransactionType() == self::TYPE_INLINE) { $inlines[] = $xaction; } } // TODO: This is a bit gross, but far less bad than it used to be. It // could be further cleaned up at some point. if ($inlines) { $engine = PhabricatorMarkupEngine::newMarkupEngine(array()) ->setConfig('viewer', new PhabricatorUser()) ->setMode(PhutilRemarkupEngine::MODE_TEXT); $body .= "\n\n"; $body .= pht('Inline Comments'); $body .= "\n"; $changeset_ids = array(); foreach ($inlines as $inline) { $changeset_ids[] = $inline->getComment()->getChangesetID(); } $changesets = id(new DifferentialChangeset())->loadAllWhere( 'id IN (%Ld)', $changeset_ids); foreach ($inlines as $inline) { $comment = $inline->getComment(); $changeset = idx($changesets, $comment->getChangesetID()); if (!$changeset) { continue; } $filename = $changeset->getDisplayFilename(); $linenumber = $comment->getLineNumber(); $inline_text = $engine->markupText($comment->getContent()); $inline_text = rtrim($inline_text); $body .= "{$filename}:{$linenumber} {$inline_text}\n"; } } return $body; } public function newWarningForTransactions($object, array $xactions) { $warning = new PhabricatorTransactionWarning(); switch ($this->getTransactionType()) { case self::TYPE_INLINE: $warning->setTitleText(pht('Warning: Editing Inlines')); $warning->setContinueActionText(pht('Save Inlines and Continue')); $count = phutil_count($xactions); $body = array(); $body[] = pht( 'You are currently editing %s inline comment(s) on this '. 'revision.', $count); $body[] = pht( 'These %s inline comment(s) will be saved and published.', $count); $warning->setWarningParagraphs($body); break; case PhabricatorTransactions::TYPE_SUBSCRIBERS: $warning->setTitleText(pht('Warning: Draft Revision')); $warning->setContinueActionText(pht('Tell No One')); $body = array(); $body[] = pht( 'This is a draft revision that will not publish any '. 'notifications until the author requests review.'); $body[] = pht('Mentioned or subscribed users will not be notified.'); $warning->setWarningParagraphs($body); break; } return $warning; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialDiffProperty.php
src/applications/differential/storage/DifferentialDiffProperty.php
<?php final class DifferentialDiffProperty extends DifferentialDAO { protected $diffID; protected $name; protected $data; protected function getConfiguration() { return array( self::CONFIG_SERIALIZATION => array( 'data' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'name' => 'text128', ), self::CONFIG_KEY_SCHEMA => array( 'diffID' => array( 'columns' => array('diffID', 'name'), 'unique' => true, ), ), ) + parent::getConfiguration(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialRevision.php
src/applications/differential/storage/DifferentialRevision.php
<?php final class DifferentialRevision extends DifferentialDAO implements PhabricatorTokenReceiverInterface, PhabricatorPolicyInterface, PhabricatorExtendedPolicyInterface, PhabricatorFlaggableInterface, PhrequentTrackableInterface, HarbormasterBuildableInterface, PhabricatorSubscribableInterface, PhabricatorCustomFieldInterface, PhabricatorApplicationTransactionInterface, PhabricatorTimelineInterface, PhabricatorMentionableInterface, PhabricatorDestructibleInterface, PhabricatorProjectInterface, PhabricatorFulltextInterface, PhabricatorFerretInterface, PhabricatorConduitResultInterface, PhabricatorDraftInterface { protected $title = ''; protected $status; protected $summary = ''; protected $testPlan = ''; protected $authorPHID; protected $lastReviewerPHID; protected $lineCount = 0; protected $attached = array(); protected $mailKey; protected $branchName; protected $repositoryPHID; protected $activeDiffPHID; protected $viewPolicy = PhabricatorPolicies::POLICY_USER; protected $editPolicy = PhabricatorPolicies::POLICY_USER; protected $properties = array(); private $commitPHIDs = self::ATTACHABLE; private $activeDiff = self::ATTACHABLE; private $diffIDs = self::ATTACHABLE; private $hashes = self::ATTACHABLE; private $repository = self::ATTACHABLE; private $reviewerStatus = self::ATTACHABLE; private $customFields = self::ATTACHABLE; private $drafts = array(); private $flags = array(); private $forceMap = array(); const RELATION_REVIEWER = 'revw'; const RELATION_SUBSCRIBED = 'subd'; const PROPERTY_CLOSED_FROM_ACCEPTED = 'wasAcceptedBeforeClose'; const PROPERTY_DRAFT_HOLD = 'draft.hold'; const PROPERTY_SHOULD_BROADCAST = 'draft.broadcast'; const PROPERTY_LINES_ADDED = 'lines.added'; const PROPERTY_LINES_REMOVED = 'lines.removed'; const PROPERTY_BUILDABLES = 'buildables'; const PROPERTY_WRONG_BUILDS = 'wrong.builds'; public static function initializeNewRevision(PhabricatorUser $actor) { $app = id(new PhabricatorApplicationQuery()) ->setViewer($actor) ->withClasses(array('PhabricatorDifferentialApplication')) ->executeOne(); $view_policy = $app->getPolicy( DifferentialDefaultViewCapability::CAPABILITY); $initial_state = DifferentialRevisionStatus::DRAFT; $should_broadcast = false; return id(new DifferentialRevision()) ->setViewPolicy($view_policy) ->setAuthorPHID($actor->getPHID()) ->attachRepository(null) ->attachActiveDiff(null) ->attachReviewers(array()) ->setModernRevisionStatus($initial_state) ->setShouldBroadcast($should_broadcast); } protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_SERIALIZATION => array( 'attached' => self::SERIALIZATION_JSON, 'unsubscribed' => self::SERIALIZATION_JSON, 'properties' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'title' => 'text255', 'status' => 'text32', 'summary' => 'text', 'testPlan' => 'text', 'authorPHID' => 'phid?', 'lastReviewerPHID' => 'phid?', 'lineCount' => 'uint32?', 'mailKey' => 'bytes40', 'branchName' => 'text255?', 'repositoryPHID' => 'phid?', ), self::CONFIG_KEY_SCHEMA => array( 'authorPHID' => array( 'columns' => array('authorPHID', 'status'), ), 'repositoryPHID' => array( 'columns' => array('repositoryPHID'), ), // If you (or a project you are a member of) is reviewing a significant // fraction of the revisions on an install, the result set of open // revisions may be smaller than the result set of revisions where you // are a reviewer. In these cases, this key is better than keys on the // edge table. 'key_status' => array( 'columns' => array('status', 'phid'), ), 'key_modified' => array( 'columns' => array('dateModified'), ), ), ) + parent::getConfiguration(); } public function setProperty($key, $value) { $this->properties[$key] = $value; return $this; } public function getProperty($key, $default = null) { return idx($this->properties, $key, $default); } public function hasRevisionProperty($key) { return array_key_exists($key, $this->properties); } public function getMonogram() { $id = $this->getID(); return "D{$id}"; } public function getURI() { return '/'.$this->getMonogram(); } public function getCommitPHIDs() { return $this->assertAttached($this->commitPHIDs); } public function getActiveDiff() { // TODO: Because it's currently technically possible to create a revision // without an associated diff, we allow an attached-but-null active diff. // It would be good to get rid of this once we make diff-attaching // transactional. return $this->assertAttached($this->activeDiff); } public function attachActiveDiff($diff) { $this->activeDiff = $diff; return $this; } public function getDiffIDs() { return $this->assertAttached($this->diffIDs); } public function attachDiffIDs(array $ids) { rsort($ids); $this->diffIDs = array_values($ids); return $this; } public function attachCommitPHIDs(array $phids) { $this->commitPHIDs = $phids; return $this; } public function getAttachedPHIDs($type) { return array_keys(idx($this->attached, $type, array())); } public function setAttachedPHIDs($type, array $phids) { $this->attached[$type] = array_fill_keys($phids, array()); return $this; } public function generatePHID() { return PhabricatorPHID::generateNewPHID( DifferentialRevisionPHIDType::TYPECONST); } public function loadActiveDiff() { return id(new DifferentialDiff())->loadOneWhere( 'revisionID = %d ORDER BY id DESC LIMIT 1', $this->getID()); } public function save() { if (!$this->getMailKey()) { $this->mailKey = Filesystem::readRandomCharacters(40); } return parent::save(); } public function getHashes() { return $this->assertAttached($this->hashes); } public function attachHashes(array $hashes) { $this->hashes = $hashes; return $this; } public function canReviewerForceAccept( PhabricatorUser $viewer, DifferentialReviewer $reviewer) { if (!$reviewer->isPackage()) { return false; } $map = $this->getReviewerForceAcceptMap($viewer); if (!$map) { return false; } if (isset($map[$reviewer->getReviewerPHID()])) { return true; } return false; } private function getReviewerForceAcceptMap(PhabricatorUser $viewer) { $fragment = $viewer->getCacheFragment(); if (!array_key_exists($fragment, $this->forceMap)) { $map = $this->newReviewerForceAcceptMap($viewer); $this->forceMap[$fragment] = $map; } return $this->forceMap[$fragment]; } private function newReviewerForceAcceptMap(PhabricatorUser $viewer) { $diff = $this->getActiveDiff(); if (!$diff) { return null; } $repository_phid = $diff->getRepositoryPHID(); if (!$repository_phid) { return null; } $paths = array(); try { $changesets = $diff->getChangesets(); } catch (Exception $ex) { $changesets = id(new DifferentialChangesetQuery()) ->setViewer($viewer) ->withDiffs(array($diff)) ->execute(); } foreach ($changesets as $changeset) { $paths[] = $changeset->getOwnersFilename(); } if (!$paths) { return null; } $reviewer_phids = array(); foreach ($this->getReviewers() as $reviewer) { if (!$reviewer->isPackage()) { continue; } $reviewer_phids[] = $reviewer->getReviewerPHID(); } if (!$reviewer_phids) { return null; } // Load all the reviewing packages which have control over some of the // paths in the change. These are packages which the actor may be able // to force-accept on behalf of. $control_query = id(new PhabricatorOwnersPackageQuery()) ->setViewer($viewer) ->withStatuses(array(PhabricatorOwnersPackage::STATUS_ACTIVE)) ->withPHIDs($reviewer_phids) ->withControl($repository_phid, $paths); $control_packages = $control_query->execute(); if (!$control_packages) { return null; } // Load all the packages which have potential control over some of the // paths in the change and are owned by the actor. These are packages // which the actor may be able to use their authority over to gain the // ability to force-accept for other packages. This query doesn't apply // dominion rules yet, and we'll bypass those rules later on. // See T13657. We ignore "watcher" packages which don't grant their owners // permission to force accept anything. $authority_query = id(new PhabricatorOwnersPackageQuery()) ->setViewer($viewer) ->withStatuses(array(PhabricatorOwnersPackage::STATUS_ACTIVE)) ->withAuthorityModes( array( PhabricatorOwnersPackage::AUTHORITY_STRONG, )) ->withAuthorityPHIDs(array($viewer->getPHID())) ->withControl($repository_phid, $paths); $authority_packages = $authority_query->execute(); if (!$authority_packages) { return null; } $authority_packages = mpull($authority_packages, null, 'getPHID'); // Build a map from each path in the revision to the reviewer packages // which control it. $control_map = array(); foreach ($paths as $path) { $control_packages = $control_query->getControllingPackagesForPath( $repository_phid, $path); // Remove packages which the viewer has authority over. We don't need // to check these for force-accept because they can just accept them // normally. $control_packages = mpull($control_packages, null, 'getPHID'); foreach ($control_packages as $phid => $control_package) { if (isset($authority_packages[$phid])) { unset($control_packages[$phid]); } } if (!$control_packages) { continue; } $control_map[$path] = $control_packages; } if (!$control_map) { return null; } // From here on out, we only care about paths which we have at least one // controlling package for. $paths = array_keys($control_map); // Now, build a map from each path to the packages which would control it // if there were no dominion rules. $authority_map = array(); foreach ($paths as $path) { $authority_packages = $authority_query->getControllingPackagesForPath( $repository_phid, $path, $ignore_dominion = true); $authority_map[$path] = mpull($authority_packages, null, 'getPHID'); } // For each path, find the most general package that the viewer has // authority over. For example, we'll prefer a package that owns "/" to a // package that owns "/src/". $force_map = array(); foreach ($authority_map as $path => $package_map) { $path_fragments = PhabricatorOwnersPackage::splitPath($path); $fragment_count = count($path_fragments); // Find the package that we have authority over which has the most // general match for this path. $best_match = null; $best_package = null; foreach ($package_map as $package_phid => $package) { $package_paths = $package->getPathsForRepository($repository_phid); foreach ($package_paths as $package_path) { // NOTE: A strength of 0 means "no match". A strength of 1 means // that we matched "/", so we can not possibly find another stronger // match. $strength = $package_path->getPathMatchStrength( $path_fragments, $fragment_count); if (!$strength) { continue; } if ($strength < $best_match || !$best_package) { $best_match = $strength; $best_package = $package; if ($strength == 1) { break 2; } } } } if ($best_package) { $force_map[$path] = array( 'strength' => $best_match, 'package' => $best_package, ); } } // For each path which the viewer owns a package for, find other packages // which that authority can be used to force-accept. Once we find a way to // force-accept a package, we don't need to keep looking. $has_control = array(); foreach ($force_map as $path => $spec) { $path_fragments = PhabricatorOwnersPackage::splitPath($path); $fragment_count = count($path_fragments); $authority_strength = $spec['strength']; $control_packages = $control_map[$path]; foreach ($control_packages as $control_phid => $control_package) { if (isset($has_control[$control_phid])) { continue; } $control_paths = $control_package->getPathsForRepository( $repository_phid); foreach ($control_paths as $control_path) { $strength = $control_path->getPathMatchStrength( $path_fragments, $fragment_count); if (!$strength) { continue; } if ($strength > $authority_strength) { $authority = $spec['package']; $has_control[$control_phid] = array( 'authority' => $authority, 'phid' => $authority->getPHID(), ); break; } } } } // Return a map from packages which may be force accepted to the packages // which permit that forced acceptance. return ipull($has_control, 'phid'); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ); } public function getPolicy($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: return $this->getViewPolicy(); case PhabricatorPolicyCapability::CAN_EDIT: return $this->getEditPolicy(); } } public function hasAutomaticCapability($capability, PhabricatorUser $user) { // A revision's author (which effectively means "owner" after we added // commandeering) can always view and edit it. $author_phid = $this->getAuthorPHID(); if ($author_phid) { if ($user->getPHID() == $author_phid) { return true; } } return false; } public function describeAutomaticCapability($capability) { $description = array( pht('The owner of a revision can always view and edit it.'), ); switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: $description[] = pht( 'If a revision belongs to a repository, other users must be able '. 'to view the repository in order to view the revision.'); break; } return $description; } /* -( PhabricatorExtendedPolicyInterface )--------------------------------- */ public function getExtendedPolicy($capability, PhabricatorUser $viewer) { $extended = array(); switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: $repository_phid = $this->getRepositoryPHID(); $repository = $this->getRepository(); // Try to use the object if we have it, since it will save us some // data fetching later on. In some cases, we might not have it. $repository_ref = nonempty($repository, $repository_phid); if ($repository_ref) { $extended[] = array( $repository_ref, PhabricatorPolicyCapability::CAN_VIEW, ); } break; } return $extended; } /* -( PhabricatorTokenReceiverInterface )---------------------------------- */ public function getUsersToNotifyOfTokenGiven() { return array( $this->getAuthorPHID(), ); } public function getReviewers() { return $this->assertAttached($this->reviewerStatus); } public function attachReviewers(array $reviewers) { assert_instances_of($reviewers, 'DifferentialReviewer'); $reviewers = mpull($reviewers, null, 'getReviewerPHID'); $this->reviewerStatus = $reviewers; return $this; } public function hasAttachedReviewers() { return ($this->reviewerStatus !== self::ATTACHABLE); } public function getReviewerPHIDs() { $reviewers = $this->getReviewers(); return mpull($reviewers, 'getReviewerPHID'); } public function getReviewerPHIDsForEdit() { $reviewers = $this->getReviewers(); $status_blocking = DifferentialReviewerStatus::STATUS_BLOCKING; $value = array(); foreach ($reviewers as $reviewer) { $phid = $reviewer->getReviewerPHID(); if ($reviewer->getReviewerStatus() == $status_blocking) { $value[] = 'blocking('.$phid.')'; } else { $value[] = $phid; } } return $value; } public function getRepository() { return $this->assertAttached($this->repository); } public function attachRepository(PhabricatorRepository $repository = null) { $this->repository = $repository; return $this; } public function setModernRevisionStatus($status) { return $this->setStatus($status); } public function getModernRevisionStatus() { return $this->getStatus(); } public function getLegacyRevisionStatus() { return $this->getStatusObject()->getLegacyKey(); } public function isClosed() { return $this->getStatusObject()->isClosedStatus(); } public function isAbandoned() { return $this->getStatusObject()->isAbandoned(); } public function isAccepted() { return $this->getStatusObject()->isAccepted(); } public function isNeedsReview() { return $this->getStatusObject()->isNeedsReview(); } public function isNeedsRevision() { return $this->getStatusObject()->isNeedsRevision(); } public function isChangePlanned() { return $this->getStatusObject()->isChangePlanned(); } public function isPublished() { return $this->getStatusObject()->isPublished(); } public function isDraft() { return $this->getStatusObject()->isDraft(); } public function getStatusIcon() { return $this->getStatusObject()->getIcon(); } public function getStatusDisplayName() { return $this->getStatusObject()->getDisplayName(); } public function getStatusIconColor() { return $this->getStatusObject()->getIconColor(); } public function getStatusTagColor() { return $this->getStatusObject()->getTagColor(); } public function getStatusObject() { $status = $this->getStatus(); return DifferentialRevisionStatus::newForStatus($status); } public function getFlag(PhabricatorUser $viewer) { return $this->assertAttachedKey($this->flags, $viewer->getPHID()); } public function attachFlag( PhabricatorUser $viewer, PhabricatorFlag $flag = null) { $this->flags[$viewer->getPHID()] = $flag; return $this; } public function getHasDraft(PhabricatorUser $viewer) { return $this->assertAttachedKey($this->drafts, $viewer->getCacheFragment()); } public function attachHasDraft(PhabricatorUser $viewer, $has_draft) { $this->drafts[$viewer->getCacheFragment()] = $has_draft; return $this; } public function getHoldAsDraft() { return $this->getProperty(self::PROPERTY_DRAFT_HOLD, false); } public function setHoldAsDraft($hold) { return $this->setProperty(self::PROPERTY_DRAFT_HOLD, $hold); } public function getShouldBroadcast() { return $this->getProperty(self::PROPERTY_SHOULD_BROADCAST, true); } public function setShouldBroadcast($should_broadcast) { return $this->setProperty( self::PROPERTY_SHOULD_BROADCAST, $should_broadcast); } public function setAddedLineCount($count) { return $this->setProperty(self::PROPERTY_LINES_ADDED, $count); } public function getAddedLineCount() { return $this->getProperty(self::PROPERTY_LINES_ADDED); } public function setRemovedLineCount($count) { return $this->setProperty(self::PROPERTY_LINES_REMOVED, $count); } public function getRemovedLineCount() { return $this->getProperty(self::PROPERTY_LINES_REMOVED); } public function hasLineCounts() { // This data was not populated on older revisions, so it may not be // present on all revisions. return isset($this->properties[self::PROPERTY_LINES_ADDED]); } public function getRevisionScaleGlyphs() { $add = $this->getAddedLineCount(); $rem = $this->getRemovedLineCount(); $all = ($add + $rem); if (!$all) { return ' '; } $map = array( 20 => 2, 50 => 3, 150 => 4, 375 => 5, 1000 => 6, 2500 => 7, ); $n = 1; foreach ($map as $size => $count) { if ($size <= $all) { $n = $count; } else { break; } } $add_n = (int)ceil(($add / $all) * $n); $rem_n = (int)ceil(($rem / $all) * $n); while ($add_n + $rem_n > $n) { if ($add_n > 1) { $add_n--; } else { $rem_n--; } } return str_repeat('+', $add_n). str_repeat('-', $rem_n). str_repeat(' ', (7 - $n)); } public function getBuildableStatus($phid) { $buildables = $this->getProperty(self::PROPERTY_BUILDABLES); if (!is_array($buildables)) { $buildables = array(); } $buildable = idx($buildables, $phid); if (!is_array($buildable)) { $buildable = array(); } return idx($buildable, 'status'); } public function setBuildableStatus($phid, $status) { $buildables = $this->getProperty(self::PROPERTY_BUILDABLES); if (!is_array($buildables)) { $buildables = array(); } $buildable = idx($buildables, $phid); if (!is_array($buildable)) { $buildable = array(); } $buildable['status'] = $status; $buildables[$phid] = $buildable; return $this->setProperty(self::PROPERTY_BUILDABLES, $buildables); } public function newBuildableStatus(PhabricatorUser $viewer, $phid) { // For Differential, we're ignoring autobuilds (local lint and unit) // when computing build status. Differential only cares about remote // builds when making publishing and undrafting decisions. $builds = $this->loadImpactfulBuildsForBuildablePHIDs( $viewer, array($phid)); return $this->newBuildableStatusForBuilds($builds); } public function newBuildableStatusForBuilds(array $builds) { // If we have nothing but passing builds, the buildable passes. if (!$builds) { return HarbormasterBuildableStatus::STATUS_PASSED; } // If we have any completed, non-passing builds, the buildable fails. foreach ($builds as $build) { if ($build->isComplete()) { return HarbormasterBuildableStatus::STATUS_FAILED; } } // Otherwise, we're still waiting for the build to pass or fail. return null; } public function loadImpactfulBuilds(PhabricatorUser $viewer) { $diff = $this->getActiveDiff(); // NOTE: We can't use `withContainerPHIDs()` here because the container // update in Harbormaster is not synchronous. $buildables = id(new HarbormasterBuildableQuery()) ->setViewer($viewer) ->withBuildablePHIDs(array($diff->getPHID())) ->withManualBuildables(false) ->execute(); if (!$buildables) { return array(); } return $this->loadImpactfulBuildsForBuildablePHIDs( $viewer, mpull($buildables, 'getPHID')); } private function loadImpactfulBuildsForBuildablePHIDs( PhabricatorUser $viewer, array $phids) { $builds = id(new HarbormasterBuildQuery()) ->setViewer($viewer) ->withBuildablePHIDs($phids) ->withAutobuilds(false) ->withBuildStatuses( array( HarbormasterBuildStatus::STATUS_INACTIVE, HarbormasterBuildStatus::STATUS_PENDING, HarbormasterBuildStatus::STATUS_BUILDING, HarbormasterBuildStatus::STATUS_FAILED, HarbormasterBuildStatus::STATUS_ABORTED, HarbormasterBuildStatus::STATUS_ERROR, HarbormasterBuildStatus::STATUS_PAUSED, HarbormasterBuildStatus::STATUS_DEADLOCKED, )) ->execute(); // Filter builds based on the "Hold Drafts" behavior of their associated // build plans. $hold_drafts = HarbormasterBuildPlanBehavior::BEHAVIOR_DRAFTS; $behavior = HarbormasterBuildPlanBehavior::getBehavior($hold_drafts); $key_never = HarbormasterBuildPlanBehavior::DRAFTS_NEVER; $key_building = HarbormasterBuildPlanBehavior::DRAFTS_IF_BUILDING; foreach ($builds as $key => $build) { $plan = $build->getBuildPlan(); // See T13526. If the viewer can't see the build plan, pretend it has // generic options. This is often wrong, but "often wrong" is better than // "fatal". if ($plan) { $hold_key = $behavior->getPlanOption($plan)->getKey(); $hold_never = ($hold_key === $key_never); $hold_building = ($hold_key === $key_building); } else { $hold_never = false; $hold_building = false; } // If the build "Never" holds drafts from promoting, we don't care what // the status is. if ($hold_never) { unset($builds[$key]); continue; } // If the build holds drafts from promoting "While Building", we only // care about the status until it completes. if ($hold_building) { if ($build->isComplete()) { unset($builds[$key]); continue; } } } return $builds; } /* -( HarbormasterBuildableInterface )------------------------------------- */ public function getHarbormasterBuildableDisplayPHID() { return $this->getHarbormasterContainerPHID(); } public function getHarbormasterBuildablePHID() { return $this->loadActiveDiff()->getPHID(); } public function getHarbormasterContainerPHID() { return $this->getPHID(); } public function getBuildVariables() { return array(); } public function getAvailableBuildVariables() { return array(); } public function newBuildableEngine() { return new DifferentialBuildableEngine(); } /* -( PhabricatorSubscribableInterface )----------------------------------- */ public function isAutomaticallySubscribed($phid) { if ($phid == $this->getAuthorPHID()) { return true; } // TODO: This only happens when adding or removing CCs, and is safe from a // policy perspective, but the subscription pathway should have some // opportunity to load this data properly. For now, this is the only case // where implicit subscription is not an intrinsic property of the object. if ($this->reviewerStatus == self::ATTACHABLE) { $reviewers = id(new DifferentialRevisionQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs(array($this->getPHID())) ->needReviewers(true) ->executeOne() ->getReviewers(); } else { $reviewers = $this->getReviewers(); } foreach ($reviewers as $reviewer) { if ($reviewer->getReviewerPHID() !== $phid) { continue; } if ($reviewer->isResigned()) { continue; } return true; } return false; } /* -( PhabricatorCustomFieldInterface )------------------------------------ */ public function getCustomFieldSpecificationForRole($role) { return PhabricatorEnv::getEnvConfig('differential.fields'); } public function getCustomFieldBaseClass() { return 'DifferentialCustomField'; } public function getCustomFields() { return $this->assertAttached($this->customFields); } public function attachCustomFields(PhabricatorCustomFieldAttachment $fields) { $this->customFields = $fields; return $this; } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new DifferentialTransactionEditor(); } public function getApplicationTransactionTemplate() { return new DifferentialTransaction(); } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $viewer = $engine->getViewer(); $this->openTransaction(); $diffs = id(new DifferentialDiffQuery()) ->setViewer($viewer) ->withRevisionIDs(array($this->getID())) ->execute(); foreach ($diffs as $diff) { $engine->destroyObject($diff); } id(new DifferentialAffectedPathEngine()) ->setRevision($this) ->destroyAffectedPaths(); $viewstate_query = id(new DifferentialViewStateQuery()) ->setViewer($viewer) ->withObjectPHIDs(array($this->getPHID())); $viewstates = new PhabricatorQueryIterator($viewstate_query); foreach ($viewstates as $viewstate) { $viewstate->delete(); } $this->delete(); $this->saveTransaction(); } /* -( PhabricatorFulltextInterface )--------------------------------------- */ public function newFulltextEngine() { return new DifferentialRevisionFulltextEngine(); } /* -( PhabricatorFerretInterface )----------------------------------------- */ public function newFerretEngine() { return new DifferentialRevisionFerretEngine(); } /* -( PhabricatorConduitResultInterface )---------------------------------- */ public function getFieldSpecificationsForConduit() { return array( id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('title') ->setType('string') ->setDescription(pht('The revision title.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('uri') ->setType('uri') ->setDescription(pht('View URI for the revision.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('authorPHID') ->setType('phid') ->setDescription(pht('Revision author PHID.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('status') ->setType('map<string, wild>') ->setDescription(pht('Information about revision status.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('repositoryPHID') ->setType('phid?') ->setDescription(pht('Revision repository PHID.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('diffPHID') ->setType('phid') ->setDescription(pht('Active diff PHID.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('summary') ->setType('string') ->setDescription(pht('Revision summary.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('testPlan') ->setType('string') ->setDescription(pht('Revision test plan.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('isDraft') ->setType('bool') ->setDescription( pht( 'True if this revision is in any draft state, and thus not '. 'notifying reviewers and subscribers about changes.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('holdAsDraft') ->setType('bool') ->setDescription( pht( 'True if this revision is being held as a draft. It will not be '. 'automatically submitted for review even if tests pass.')), ); } public function getFieldValuesForConduit() { $status = $this->getStatusObject(); $status_info = array( 'value' => $status->getKey(), 'name' => $status->getDisplayName(), 'closed' => $status->isClosedStatus(), 'color.ansi' => $status->getANSIColor(), ); return array( 'title' => $this->getTitle(), 'uri' => PhabricatorEnv::getURI($this->getURI()), 'authorPHID' => $this->getAuthorPHID(), 'status' => $status_info, 'repositoryPHID' => $this->getRepositoryPHID(), 'diffPHID' => $this->getActiveDiffPHID(), 'summary' => $this->getSummary(),
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
true
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialCustomFieldNumericIndex.php
src/applications/differential/storage/DifferentialCustomFieldNumericIndex.php
<?php final class DifferentialCustomFieldNumericIndex extends PhabricatorCustomFieldNumericIndexStorage { public function getApplicationName() { return 'differential'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialCustomFieldStorage.php
src/applications/differential/storage/DifferentialCustomFieldStorage.php
<?php final class DifferentialCustomFieldStorage extends PhabricatorCustomFieldStorage { public function getApplicationName() { return 'differential'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialHunk.php
src/applications/differential/storage/DifferentialHunk.php
<?php final class DifferentialHunk extends DifferentialDAO implements PhabricatorPolicyInterface, PhabricatorDestructibleInterface { protected $changesetID; protected $oldOffset; protected $oldLen; protected $newOffset; protected $newLen; protected $dataType; protected $dataEncoding; protected $dataFormat; protected $data; private $changeset; private $splitLines; private $structuredLines; private $structuredFiles = array(); private $rawData; private $forcedEncoding; private $fileData; const FLAG_LINES_ADDED = 1; const FLAG_LINES_REMOVED = 2; const FLAG_LINES_STABLE = 4; const DATATYPE_TEXT = 'text'; const DATATYPE_FILE = 'file'; const DATAFORMAT_RAW = 'byte'; const DATAFORMAT_DEFLATED = 'gzde'; protected function getConfiguration() { return array( self::CONFIG_BINARY => array( 'data' => true, ), self::CONFIG_COLUMN_SCHEMA => array( 'dataType' => 'bytes4', 'dataEncoding' => 'text16?', 'dataFormat' => 'bytes4', 'oldOffset' => 'uint32', 'oldLen' => 'uint32', 'newOffset' => 'uint32', 'newLen' => 'uint32', ), self::CONFIG_KEY_SCHEMA => array( 'key_changeset' => array( 'columns' => array('changesetID'), ), 'key_created' => array( 'columns' => array('dateCreated'), ), ), ) + parent::getConfiguration(); } public function getAddedLines() { return $this->makeContent($include = '+'); } public function getRemovedLines() { return $this->makeContent($include = '-'); } public function makeNewFile() { return implode('', $this->makeContent($include = ' +')); } public function makeOldFile() { return implode('', $this->makeContent($include = ' -')); } public function makeChanges() { return implode('', $this->makeContent($include = '-+')); } public function getStructuredOldFile() { return $this->getStructuredFile('-'); } public function getStructuredNewFile() { return $this->getStructuredFile('+'); } private function getStructuredFile($kind) { if ($kind !== '+' && $kind !== '-') { throw new Exception( pht( 'Structured file kind should be "+" or "-", got "%s".', $kind)); } if (!isset($this->structuredFiles[$kind])) { if ($kind == '+') { $number = $this->newOffset; } else { $number = $this->oldOffset; } $lines = $this->getStructuredLines(); // NOTE: We keep the "\ No newline at end of file" line if it appears // after a line which is not excluded. For example, if we're constructing // the "+" side of the diff, we want to ignore this one since it's // relevant only to the "-" side of the diff: // // - x // \ No newline at end of file // + x // // ...but we want to keep this one: // // - x // + x // \ No newline at end of file $file = array(); $keep = true; foreach ($lines as $line) { switch ($line['type']) { case ' ': case $kind: $file[$number++] = $line; $keep = true; break; case '\\': if ($keep) { // Strip the actual newline off the line's text. $text = $file[$number - 1]['text']; $text = rtrim($text, "\r\n"); $file[$number - 1]['text'] = $text; $file[$number++] = $line; $keep = false; } break; default: $keep = false; break; } } $this->structuredFiles[$kind] = $file; } return $this->structuredFiles[$kind]; } public function getSplitLines() { if ($this->splitLines === null) { $this->splitLines = phutil_split_lines($this->getChanges()); } return $this->splitLines; } public function getStructuredLines() { if ($this->structuredLines === null) { $lines = $this->getSplitLines(); $structured = array(); foreach ($lines as $line) { if (empty($line[0])) { // TODO: Can we just get rid of this? continue; } $structured[] = array( 'type' => $line[0], 'text' => substr($line, 1), ); } $this->structuredLines = $structured; } return $this->structuredLines; } public function getContentWithMask($mask) { $include = array(); if (($mask & self::FLAG_LINES_ADDED)) { $include[] = '+'; } if (($mask & self::FLAG_LINES_REMOVED)) { $include[] = '-'; } if (($mask & self::FLAG_LINES_STABLE)) { $include[] = ' '; } $include = implode('', $include); return implode('', $this->makeContent($include)); } private function makeContent($include) { $lines = $this->getSplitLines(); $results = array(); $include_map = array(); for ($ii = 0; $ii < strlen($include); $ii++) { $include_map[$include[$ii]] = true; } if (isset($include_map['+'])) { $n = $this->newOffset; } else { $n = $this->oldOffset; } $use_next_newline = false; foreach ($lines as $line) { if (!isset($line[0])) { continue; } if ($line[0] == '\\') { if ($use_next_newline) { $results[last_key($results)] = rtrim(end($results), "\n"); } } else if (empty($include_map[$line[0]])) { $use_next_newline = false; } else { $use_next_newline = true; $results[$n] = substr($line, 1); } if ($line[0] == ' ' || isset($include_map[$line[0]])) { $n++; } } return $results; } public function getChangeset() { return $this->assertAttached($this->changeset); } public function attachChangeset(DifferentialChangeset $changeset) { $this->changeset = $changeset; return $this; } /* -( Storage )------------------------------------------------------------ */ public function setChanges($text) { $this->rawData = $text; $this->dataEncoding = $this->detectEncodingForStorage($text); $this->dataType = self::DATATYPE_TEXT; list($format, $data) = $this->formatDataForStorage($text); $this->dataFormat = $format; $this->data = $data; return $this; } public function getChanges() { return $this->getUTF8StringFromStorage( $this->getRawData(), nonempty($this->forcedEncoding, $this->getDataEncoding())); } public function forceEncoding($encoding) { $this->forcedEncoding = $encoding; return $this; } private function formatDataForStorage($data) { $deflated = PhabricatorCaches::maybeDeflateData($data); if ($deflated !== null) { return array(self::DATAFORMAT_DEFLATED, $deflated); } return array(self::DATAFORMAT_RAW, $data); } public function getAutomaticDataFormat() { // If the hunk is already stored deflated, just keep it deflated. This is // mostly a performance improvement for "bin/differential migrate-hunk" so // that we don't have to recompress all the stored hunks when looking for // stray uncompressed hunks. if ($this->dataFormat === self::DATAFORMAT_DEFLATED) { return self::DATAFORMAT_DEFLATED; } list($format) = $this->formatDataForStorage($this->getRawData()); return $format; } public function saveAsText() { $old_type = $this->getDataType(); $old_data = $this->getData(); $raw_data = $this->getRawData(); $this->setDataType(self::DATATYPE_TEXT); list($format, $data) = $this->formatDataForStorage($raw_data); $this->setDataFormat($format); $this->setData($data); $result = $this->save(); $this->destroyData($old_type, $old_data); return $result; } public function saveAsFile() { $old_type = $this->getDataType(); $old_data = $this->getData(); $raw_data = $this->getRawData(); list($format, $data) = $this->formatDataForStorage($raw_data); $this->setDataFormat($format); $file = PhabricatorFile::newFromFileData( $data, array( 'name' => 'differential-hunk', 'mime-type' => 'application/octet-stream', 'viewPolicy' => PhabricatorPolicies::POLICY_NOONE, )); $this->setDataType(self::DATATYPE_FILE); $this->setData($file->getPHID()); // NOTE: Because hunks don't have a PHID and we just load hunk data with // the omnipotent viewer, we do not need to attach the file to anything. $result = $this->save(); $this->destroyData($old_type, $old_data); return $result; } private function getRawData() { if ($this->rawData === null) { $type = $this->getDataType(); $data = $this->getData(); switch ($type) { case self::DATATYPE_TEXT: // In this storage type, the changes are stored on the object. $data = $data; break; case self::DATATYPE_FILE: $data = $this->loadFileData(); break; default: throw new Exception( pht('Hunk has unsupported data type "%s"!', $type)); } $format = $this->getDataFormat(); switch ($format) { case self::DATAFORMAT_RAW: // In this format, the changes are stored as-is. $data = $data; break; case self::DATAFORMAT_DEFLATED: $data = PhabricatorCaches::inflateData($data); break; default: throw new Exception( pht('Hunk has unsupported data encoding "%s"!', $type)); } $this->rawData = $data; } return $this->rawData; } private function loadFileData() { if ($this->fileData === null) { $type = $this->getDataType(); if ($type !== self::DATATYPE_FILE) { throw new Exception( pht( 'Unable to load file data for hunk with wrong data type ("%s").', $type)); } $file_phid = $this->getData(); $file = $this->loadRawFile($file_phid); $data = $file->loadFileData(); $this->fileData = $data; } return $this->fileData; } private function loadRawFile($file_phid) { $viewer = PhabricatorUser::getOmnipotentUser(); $files = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withPHIDs(array($file_phid)) ->execute(); if (!$files) { throw new Exception( pht( 'Failed to load file ("%s") with hunk data.', $file_phid)); } $file = head($files); return $file; } private function destroyData( $type, $data, PhabricatorDestructionEngine $engine = null) { if (!$engine) { $engine = new PhabricatorDestructionEngine(); } switch ($type) { case self::DATATYPE_FILE: $file = $this->loadRawFile($data); $engine->destroyObject($file); break; } } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { return $this->getChangeset()->getPolicy($capability); } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return $this->getChangeset()->hasAutomaticCapability($capability, $viewer); } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $type = $this->getDataType(); $data = $this->getData(); $this->destroyData($type, $data, $engine); $this->delete(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/DifferentialCustomFieldStringIndex.php
src/applications/differential/storage/DifferentialCustomFieldStringIndex.php
<?php final class DifferentialCustomFieldStringIndex extends PhabricatorCustomFieldStringIndexStorage { public function getApplicationName() { return 'differential'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/__tests__/DifferentialDiffTestCase.php
src/applications/differential/storage/__tests__/DifferentialDiffTestCase.php
<?php final class DifferentialDiffTestCase extends PhutilTestCase { public function testDetectCopiedCode() { $copies = $this->detectCopiesIn('lint_engine.diff'); $this->assertEqual( array_combine(range(237, 252), range(167, 182)), ipull($copies, 1)); } public function testDetectCopiedOverlaidCode() { $copies = $this->detectCopiesIn('copy_overlay.diff'); $this->assertEqual( array( 7 => 22, 8 => 23, 9 => 24, 10 => 25, 11 => 26, 12 => 27, ), ipull($copies, 1)); } private function detectCopiesIn($file) { $root = dirname(__FILE__).'/diff/'; $parser = new ArcanistDiffParser(); $diff = DifferentialDiff::newFromRawChanges( PhabricatorUser::getOmnipotentUser(), $parser->parseDiff(Filesystem::readFile($root.$file))); return idx(head($diff->getChangesets())->getMetadata(), 'copy:lines'); } public function testDetectSlowCopiedCode() { // This tests that the detector has a reasonable runtime when a diff // contains a very large number of identical lines. See T5041. $parser = new ArcanistDiffParser(); $line = str_repeat('x', 60); $oline = '-'.$line."\n"; $nline = '+'.$line."\n"; $n = 1000; $oblock = str_repeat($oline, $n); $nblock = str_repeat($nline, $n); $raw_diff = <<<EODIFF diff --git a/dst b/dst new file mode 100644 index 0000000..1234567 --- /dev/null +++ b/dst @@ -0,0 +1,{$n} @@ {$nblock} diff --git a/src b/src deleted file mode 100644 index 123457..0000000 --- a/src +++ /dev/null @@ -1,{$n} +0,0 @@ {$oblock} EODIFF; $diff = DifferentialDiff::newFromRawChanges( PhabricatorUser::getOmnipotentUser(), $parser->parseDiff($raw_diff)); $this->assertTrue(true); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/__tests__/DifferentialHunkTestCase.php
src/applications/differential/storage/__tests__/DifferentialHunkTestCase.php
<?php final class DifferentialHunkTestCase extends PhutilTestCase { public function testMakeChanges() { $root = dirname(__FILE__).'/hunk/'; $hunk = new DifferentialHunk(); $hunk->setChanges(Filesystem::readFile($root.'basic.diff')); $hunk->setOldOffset(1); $hunk->setNewOffset(11); $old = Filesystem::readFile($root.'old.txt'); $this->assertEqual($old, $hunk->makeOldFile()); $new = Filesystem::readFile($root.'new.txt'); $this->assertEqual($new, $hunk->makeNewFile()); $added = array( 12 => "1 quack\n", 13 => "1 quack\n", 16 => "5 drake\n", ); $this->assertEqual($added, $hunk->getAddedLines()); $hunk = new DifferentialHunk(); $hunk->setChanges(Filesystem::readFile($root.'newline.diff')); $hunk->setOldOffset(1); $hunk->setNewOffset(11); $this->assertEqual("a\n", $hunk->makeOldFile()); $this->assertEqual('a', $hunk->makeNewFile()); $this->assertEqual(array(11 => 'a'), $hunk->getAddedLines()); } public function testMakeStructuredChanges1() { $hunk = $this->loadHunk('fruit1.diff'); $this->assertEqual( array( 1 => array( 'type' => ' ', 'text' => "apple\n", ), 2 => array( 'type' => ' ', 'text' => "cherry\n", ), ), $hunk->getStructuredOldFile()); $this->assertEqual( array( 1 => array( 'type' => ' ', 'text' => "apple\n", ), 2 => array( 'type' => '+', 'text' => "banana\n", ), 3 => array( 'type' => '+', 'text' => "plum\n", ), 4 => array( 'type' => ' ', 'text' => "cherry\n", ), ), $hunk->getStructuredNewFile()); } public function testMakeStructuredChanges2() { $hunk = $this->loadHunk('fruit2.diff'); $this->assertEqual( array( 1 => array( 'type' => ' ', 'text' => "apple\n", ), 2 => array( 'type' => ' ', 'text' => "banana\n", ), 3 => array( 'type' => '-', 'text' => "plum\n", ), 4 => array( 'type' => ' ', 'text' => "cherry\n", ), ), $hunk->getStructuredOldFile()); $this->assertEqual( array( 1 => array( 'type' => ' ', 'text' => "apple\n", ), 2 => array( 'type' => ' ', 'text' => "banana\n", ), 3 => array( 'type' => ' ', 'text' => "cherry\n", ), ), $hunk->getStructuredNewFile()); } public function testMakeStructuredNewlineAdded() { $hunk = $this->loadHunk('trailing_newline_added.diff'); $this->assertEqual( array( 1 => array( 'type' => ' ', 'text' => "quack\n", ), 2 => array( 'type' => ' ', 'text' => "quack\n", ), 3 => array( 'type' => '-', 'text' => 'quack', ), 4 => array( 'type' => '\\', 'text' => " No newline at end of file\n", ), ), $hunk->getStructuredOldFile()); $this->assertEqual( array( 1 => array( 'type' => ' ', 'text' => "quack\n", ), 2 => array( 'type' => ' ', 'text' => "quack\n", ), 3 => array( 'type' => '+', 'text' => "quack\n", ), ), $hunk->getStructuredNewFile()); } public function testMakeStructuredNewlineRemoved() { $hunk = $this->loadHunk('trailing_newline_removed.diff'); $this->assertEqual( array( 1 => array( 'type' => ' ', 'text' => "quack\n", ), 2 => array( 'type' => ' ', 'text' => "quack\n", ), 3 => array( 'type' => '-', 'text' => "quack\n", ), ), $hunk->getStructuredOldFile()); $this->assertEqual( array( 1 => array( 'type' => ' ', 'text' => "quack\n", ), 2 => array( 'type' => ' ', 'text' => "quack\n", ), 3 => array( 'type' => '+', 'text' => 'quack', ), 4 => array( 'type' => '\\', 'text' => " No newline at end of file\n", ), ), $hunk->getStructuredNewFile()); } public function testMakeStructuredNewlineAbsent() { $hunk = $this->loadHunk('trailing_newline_absent.diff'); $this->assertEqual( array( 1 => array( 'type' => '-', 'text' => "quack\n", ), 2 => array( 'type' => ' ', 'text' => "quack\n", ), 3 => array( 'type' => ' ', 'text' => 'quack', ), 4 => array( 'type' => '\\', 'text' => " No newline at end of file\n", ), ), $hunk->getStructuredOldFile()); $this->assertEqual( array( 1 => array( 'type' => '+', 'text' => "meow\n", ), 2 => array( 'type' => ' ', 'text' => "quack\n", ), 3 => array( 'type' => ' ', 'text' => 'quack', ), 4 => array( 'type' => '\\', 'text' => " No newline at end of file\n", ), ), $hunk->getStructuredNewFile()); } public function testMakeStructuredOffset() { $hunk = $this->loadHunk('offset.diff'); $this->assertEqual( array( 76 => array( 'type' => ' ', 'text' => " \$bits .= '0';\n", ), 77 => array( 'type' => ' ', 'text' => " }\n", ), 78 => array( 'type' => ' ', 'text' => " }\n", ), 79 => array( 'type' => ' ', 'text' => " }\n", ), 80 => array( 'type' => '-', 'text' => " \$this->bits = \$bits;\n", ), 81 => array( 'type' => ' ', 'text' => " }\n", ), 82 => array( 'type' => ' ', 'text' => " return \$this->bits;\n", ), ), $hunk->getStructuredOldFile()); $this->assertEqual( array( 76 => array( 'type' => ' ', 'text' => " \$bits .= '0';\n", ), 77 => array( 'type' => ' ', 'text' => " }\n", ), 78 => array( 'type' => ' ', 'text' => " }\n", ), 79 => array( 'type' => '+', 'text' => " break;\n", ), 80 => array( 'type' => ' ', 'text' => " }\n", ), 81 => array( 'type' => '+', 'text' => " \$this->bits = \$bytes;\n", ), 82 => array( 'type' => ' ', 'text' => " }\n", ), 83 => array( 'type' => ' ', 'text' => " return \$this->bits;\n", ), ), $hunk->getStructuredNewFile()); } private function loadHunk($name) { $root = dirname(__FILE__).'/hunk/'; $data = Filesystem::readFile($root.$name); $parser = new ArcanistDiffParser(); $changes = $parser->parseDiff($data); $viewer = PhabricatorUser::getOmnipotentUser(); $diff = DifferentialDiff::newFromRawChanges($viewer, $changes); $changesets = $diff->getChangesets(); if (count($changesets) !== 1) { throw new Exception( pht( 'Expected exactly one changeset from "%s".', $name)); } $changeset = head($changesets); $hunks = $changeset->getHunks(); if (count($hunks) !== 1) { throw new Exception( pht( 'Expected exactly one hunk from "%s".', $name)); } $hunk = head($hunks); return $hunk; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/storage/__tests__/DifferentialAdjustmentMapTestCase.php
src/applications/differential/storage/__tests__/DifferentialAdjustmentMapTestCase.php
<?php final class DifferentialAdjustmentMapTestCase extends PhabricatorTestCase { public function testBasicMaps() { $change_map = array( 1 => array(1), 2 => array(2), 3 => array(3), 4 => array(), 5 => array(), 6 => array(), 7 => array(4), 8 => array(5), 9 => array(6), 10 => array(7), 11 => array(8), 12 => array(9), 13 => array(10), 14 => array(11), 15 => array(12), 16 => array(13), 17 => array(14), 18 => array(15), 19 => array(16), 20 => array(17, 20), 21 => array(21), 22 => array(22), 23 => array(23), 24 => array(24), 25 => array(25), 26 => array(26), ); $hunks = $this->loadHunks('add.diff'); $this->assertEqual( array( 0 => array(1, 26), ), DifferentialLineAdjustmentMap::newFromHunks($hunks)->getMap()); $hunks = $this->loadHunks('change.diff'); $this->assertEqual( $change_map, DifferentialLineAdjustmentMap::newFromHunks($hunks)->getMap()); $hunks = $this->loadHunks('remove.diff'); $this->assertEqual( array_fill_keys(range(1, 26), array()), DifferentialLineAdjustmentMap::newFromHunks($hunks)->getMap()); // With the contextless diff, we don't get the last few similar lines // in the map. $reduced_map = $change_map; unset($reduced_map[24]); unset($reduced_map[25]); unset($reduced_map[26]); $hunks = $this->loadHunks('context.diff'); $this->assertEqual( $reduced_map, DifferentialLineAdjustmentMap::newFromHunks($hunks)->getMap()); } public function testInverseMaps() { $change_map = array( 1 => array(1), 2 => array(2), 3 => array(3, 6), 4 => array(7), 5 => array(8), 6 => array(9), 7 => array(10), 8 => array(11), 9 => array(12), 10 => array(13), 11 => array(14), 12 => array(15), 13 => array(16), 14 => array(17), 15 => array(18), 16 => array(19), 17 => array(20), 18 => array(), 19 => array(), 20 => array(), 21 => array(21), 22 => array(22), 23 => array(23), 24 => array(24), 25 => array(25), 26 => array(26), ); $hunks = $this->loadHunks('add.diff'); $this->assertEqual( array_fill_keys(range(1, 26), array()), DifferentialLineAdjustmentMap::newInverseMap( DifferentialLineAdjustmentMap::newFromHunks($hunks))->getMap()); $hunks = $this->loadHunks('change.diff'); $this->assertEqual( $change_map, DifferentialLineAdjustmentMap::newInverseMap( DifferentialLineAdjustmentMap::newFromHunks($hunks))->getMap()); $hunks = $this->loadHunks('remove.diff'); $this->assertEqual( array( 0 => array(1, 26), ), DifferentialLineAdjustmentMap::newInverseMap( DifferentialLineAdjustmentMap::newFromHunks($hunks))->getMap()); // With the contextless diff, we don't get the last few similar lines // in the map. $reduced_map = $change_map; unset($reduced_map[24]); unset($reduced_map[25]); unset($reduced_map[26]); $hunks = $this->loadHunks('context.diff'); $this->assertEqual( $reduced_map, DifferentialLineAdjustmentMap::newInverseMap( DifferentialLineAdjustmentMap::newFromHunks($hunks))->getMap()); } public function testNearestMaps() { $change_map = array( 1 => array(1), 2 => array(2), 3 => array(3), 4 => array(-3, -4), 5 => array(-3, -4), 6 => array(-3, -4), 7 => array(4), 8 => array(5), 9 => array(6), 10 => array(7), 11 => array(8), 12 => array(9), 13 => array(10), 14 => array(11), 15 => array(12), 16 => array(13), 17 => array(14), 18 => array(15), 19 => array(16), 20 => array(17, 20), 21 => array(21), 22 => array(22), 23 => array(23), 24 => array(24), 25 => array(25), 26 => array(26), ); $hunks = $this->loadHunks('add.diff'); $map = DifferentialLineAdjustmentMap::newFromHunks($hunks); $this->assertEqual( array( 0 => array(1, 26), ), $map->getNearestMap()); $this->assertEqual(26, $map->getFinalOffset()); $hunks = $this->loadHunks('change.diff'); $map = DifferentialLineAdjustmentMap::newFromHunks($hunks); $this->assertEqual( $change_map, $map->getNearestMap()); $this->assertEqual(0, $map->getFinalOffset()); $hunks = $this->loadHunks('remove.diff'); $map = DifferentialLineAdjustmentMap::newFromHunks($hunks); $this->assertEqual( array_fill_keys( range(1, 26), array(0, 0)), $map->getNearestMap()); $this->assertEqual(-26, $map->getFinalOffset()); $reduced_map = $change_map; unset($reduced_map[24]); unset($reduced_map[25]); unset($reduced_map[26]); $hunks = $this->loadHunks('context.diff'); $map = DifferentialLineAdjustmentMap::newFromHunks($hunks); $this->assertEqual( $reduced_map, $map->getNearestMap()); $this->assertEqual(0, $map->getFinalOffset()); $hunks = $this->loadHunks('insert.diff'); $map = DifferentialLineAdjustmentMap::newFromHunks($hunks); $this->assertEqual( array( 1 => array(1), 2 => array(2), 3 => array(3), 4 => array(4), 5 => array(5), 6 => array(6), 7 => array(7), 8 => array(8), 9 => array(9), 10 => array(10, 13), 11 => array(14), 12 => array(15), 13 => array(16), ), $map->getNearestMap()); $this->assertEqual(3, $map->getFinalOffset()); } public function testUnchangedUpdate() { $diff1 = $this->loadHunks('insert.diff'); $diff2 = $this->loadHunks('insert.diff'); $map = DifferentialLineAdjustmentMap::newInverseMap( DifferentialLineAdjustmentMap::newFromHunks($diff1)); $map->addMapToChain( DifferentialLineAdjustmentMap::newFromHunks($diff2)); $actual = array(); for ($ii = 1; $ii <= 16; $ii++) { $actual[$ii] = array( $map->mapLine($ii, false), $map->mapLine($ii, true), ); } $expect = array( 1 => array(array(false, false, 1), array(false, false, 1)), 2 => array(array(false, false, 2), array(false, false, 2)), 3 => array(array(false, false, 3), array(false, false, 3)), 4 => array(array(false, false, 4), array(false, false, 4)), 5 => array(array(false, false, 5), array(false, false, 5)), 6 => array(array(false, false, 6), array(false, false, 6)), 7 => array(array(false, false, 7), array(false, false, 7)), 8 => array(array(false, false, 8), array(false, false, 8)), 9 => array(array(false, false, 9), array(false, false, 9)), 10 => array(array(false, false, 10), array(false, false, 13)), 11 => array(array(false, 1, 10), array(false, false, 14)), 12 => array(array(false, 2, 10), array(false, false, 14)), 13 => array(array(false, 3, 10), array(false, false, 14)), 14 => array(array(false, false, 14), array(false, false, 14)), 15 => array(array(false, false, 15), array(false, false, 15)), 16 => array(array(false, false, 16), array(false, false, 16)), ); $this->assertEqual($expect, $actual); } public function testChainMaps() { // This test simulates porting inlines forward across a rebase. // Part 1 is the original diff. // Part 2 is the rebase, which we would normally compute synthetically. // Part 3 is the updated diff against the rebased changes. $diff1 = $this->loadHunks('chain.adjust.1.diff'); $diff2 = $this->loadHunks('chain.adjust.2.diff'); $diff3 = $this->loadHunks('chain.adjust.3.diff'); $map = DifferentialLineAdjustmentMap::newInverseMap( DifferentialLineAdjustmentMap::newFromHunks($diff1)); $map->addMapToChain( DifferentialLineAdjustmentMap::newFromHunks($diff2)); $map->addMapToChain( DifferentialLineAdjustmentMap::newFromHunks($diff3)); $actual = array(); for ($ii = 1; $ii <= 13; $ii++) { $actual[$ii] = array( $map->mapLine($ii, false), $map->mapLine($ii, true), ); } $this->assertEqual( array( 1 => array(array(false, false, 1), array(false, false, 1)), 2 => array(array(true, false, 1), array(true, false, 2)), 3 => array(array(true, false, 1), array(true, false, 2)), 4 => array(array(false, false, 2), array(false, false, 2)), 5 => array(array(false, false, 3), array(false, false, 3)), 6 => array(array(false, false, 4), array(false, false, 4)), 7 => array(array(false, false, 5), array(false, false, 8)), 8 => array(array(false, 1, 5), array(false, false, 9)), 9 => array(array(false, 2, 5), array(false, false, 9)), 10 => array(array(false, 3, 5), array(false, false, 9)), 11 => array(array(false, false, 9), array(false, false, 9)), 12 => array(array(false, false, 10), array(false, false, 10)), 13 => array(array(false, false, 11), array(false, false, 11)), ), $actual); } private function loadHunks($name) { $root = dirname(__FILE__).'/map/'; $data = Filesystem::readFile($root.$name); $parser = new ArcanistDiffParser(); $changes = $parser->parseDiff($data); $viewer = PhabricatorUser::getOmnipotentUser(); $diff = DifferentialDiff::newFromRawChanges($viewer, $changes); $changesets = $diff->getChangesets(); if (count($changesets) !== 1) { throw new Exception( pht( 'Expected exactly one changeset from "%s".', $name)); } $changeset = head($changesets); return $changeset->getHunks(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/management/PhabricatorDifferentialRebuildChangesetsWorkflow.php
src/applications/differential/management/PhabricatorDifferentialRebuildChangesetsWorkflow.php
<?php final class PhabricatorDifferentialRebuildChangesetsWorkflow extends PhabricatorDifferentialManagementWorkflow { protected function didConstruct() { $this ->setName('rebuild-changesets') ->setExamples('**rebuild-changesets** --revision __revision__') ->setSynopsis(pht('Rebuild changesets for a revision.')) ->setArguments( array( array( 'name' => 'revision', 'param' => 'revision', 'help' => pht('Revision to rebuild changesets for.'), ), )); } public function execute(PhutilArgumentParser $args) { $viewer = $this->getViewer(); $revision_identifier = $args->getArg('revision'); if (!$revision_identifier) { throw new PhutilArgumentUsageException( pht('Specify a revision to rebuild changesets for with "--revision".')); } $revision = id(new PhabricatorObjectQuery()) ->setViewer($viewer) ->withNames(array($revision_identifier)) ->executeOne(); if ($revision) { if (!($revision instanceof DifferentialRevision)) { throw new PhutilArgumentUsageException( pht( 'Object "%s" specified by "--revision" must be a Differential '. 'revision.', $revision_identifier)); } } else { $revision = id(new DifferentialRevisionQuery()) ->setViewer($viewer) ->withIDs(array($revision_identifier)) ->executeOne(); } if (!$revision) { throw new PhutilArgumentUsageException( pht( 'No revision "%s" exists.', $revision_identifier)); } $diffs = id(new DifferentialDiffQuery()) ->setViewer($viewer) ->withRevisionIDs(array($revision->getID())) ->execute(); $changesets = id(new DifferentialChangesetQuery()) ->setViewer($viewer) ->withDiffs($diffs) ->needHunks(true) ->execute(); $changeset_groups = mgroup($changesets, 'getDiffID'); foreach ($changeset_groups as $diff_id => $changesets) { echo tsprintf( "%s\n", pht( 'Rebuilding %s changeset(s) for diff ID %d.', phutil_count($changesets), $diff_id)); foreach ($changesets as $changeset) { echo tsprintf( " %s\n", $changeset->getFilename()); } id(new DifferentialChangesetEngine()) ->setViewer($viewer) ->rebuildChangesets($changesets); foreach ($changesets as $changeset) { $changeset->save(); } echo tsprintf( "%s\n", pht('Done.')); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false