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/differential/search/DifferentialRevisionFulltextEngine.php | src/applications/differential/search/DifferentialRevisionFulltextEngine.php | <?php
final class DifferentialRevisionFulltextEngine
extends PhabricatorFulltextEngine {
protected function buildAbstractDocument(
PhabricatorSearchAbstractDocument $document,
$object) {
$revision = id(new DifferentialRevisionQuery())
->setViewer($this->getViewer())
->withPHIDs(array($object->getPHID()))
->needReviewers(true)
->executeOne();
// TODO: This isn't very clean, but custom fields currently rely on it.
$object->attachReviewers($revision->getReviewers());
$document->setDocumentTitle($revision->getTitle());
$document->addRelationship(
PhabricatorSearchRelationship::RELATIONSHIP_AUTHOR,
$revision->getAuthorPHID(),
PhabricatorPeopleUserPHIDType::TYPECONST,
$revision->getDateCreated());
$document->addRelationship(
$revision->isClosed()
? PhabricatorSearchRelationship::RELATIONSHIP_CLOSED
: PhabricatorSearchRelationship::RELATIONSHIP_OPEN,
$revision->getPHID(),
DifferentialRevisionPHIDType::TYPECONST,
PhabricatorTime::getNow());
// If a revision needs review, the owners are the reviewers. Otherwise, the
// owner is the author (e.g., accepted, rejected, closed).
if ($revision->isNeedsReview()) {
$reviewers = $revision->getReviewerPHIDs();
$reviewers = array_fuse($reviewers);
if ($reviewers) {
foreach ($reviewers as $phid) {
$document->addRelationship(
PhabricatorSearchRelationship::RELATIONSHIP_OWNER,
$phid,
PhabricatorPeopleUserPHIDType::TYPECONST,
$revision->getDateModified()); // Bogus timestamp.
}
} else {
$document->addRelationship(
PhabricatorSearchRelationship::RELATIONSHIP_UNOWNED,
$revision->getPHID(),
PhabricatorPeopleUserPHIDType::TYPECONST,
$revision->getDateModified()); // Bogus timestamp.
}
} else {
$document->addRelationship(
PhabricatorSearchRelationship::RELATIONSHIP_OWNER,
$revision->getAuthorPHID(),
PhabricatorPHIDConstants::PHID_TYPE_VOID,
$revision->getDateCreated());
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/search/DifferentialRevisionFerretEngine.php | src/applications/differential/search/DifferentialRevisionFerretEngine.php | <?php
final class DifferentialRevisionFerretEngine
extends PhabricatorFerretEngine {
public function getApplicationName() {
return 'differential';
}
public function getScopeName() {
return 'revision';
}
public function newSearchEngine() {
return new DifferentialRevisionSearchEngine();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/engine/DifferentialRevisionTimelineEngine.php | src/applications/differential/engine/DifferentialRevisionTimelineEngine.php | <?php
final class DifferentialRevisionTimelineEngine
extends PhabricatorTimelineEngine {
protected function newTimelineView() {
$viewer = $this->getViewer();
$xactions = $this->getTransactions();
$revision = $this->getObject();
$view_data = $this->getViewData();
if (!$view_data) {
$view_data = array();
}
$left = idx($view_data, 'left');
$right = idx($view_data, 'right');
$diffs = id(new DifferentialDiffQuery())
->setViewer($viewer)
->withIDs(array($left, $right))
->execute();
$diffs = mpull($diffs, null, 'getID');
$left_diff = $diffs[$left];
$right_diff = $diffs[$right];
$old_ids = idx($view_data, 'old');
$new_ids = idx($view_data, 'new');
$old_ids = array_filter(explode(',', $old_ids));
$new_ids = array_filter(explode(',', $new_ids));
$type_inline = DifferentialTransaction::TYPE_INLINE;
$changeset_ids = array_merge($old_ids, $new_ids);
$inlines = array();
foreach ($xactions as $xaction) {
if ($xaction->getTransactionType() == $type_inline) {
$inlines[] = $xaction->getComment();
$changeset_ids[] = $xaction->getComment()->getChangesetID();
}
}
if ($changeset_ids) {
$changesets = id(new DifferentialChangesetQuery())
->setViewer($viewer)
->withIDs($changeset_ids)
->execute();
$changesets = mpull($changesets, null, 'getID');
} else {
$changesets = array();
}
foreach ($inlines as $key => $inline) {
$inlines[$key] = $inline->newInlineCommentObject();
}
// NOTE: This is a bit sketchy: this method adjusts the inlines as a
// side effect, which means it will ultimately adjust the transaction
// comments and affect timeline rendering.
$old = array_select_keys($changesets, $old_ids);
$new = array_select_keys($changesets, $new_ids);
id(new PhabricatorInlineCommentAdjustmentEngine())
->setViewer($viewer)
->setRevision($revision)
->setOldChangesets($old)
->setNewChangesets($new)
->setInlines($inlines)
->execute();
return id(new DifferentialTransactionView())
->setViewData($view_data)
->setChangesets($changesets)
->setRevision($revision)
->setLeftDiff($left_diff)
->setRightDiff($right_diff);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/engine/DifferentialRevisionDraftEngine.php | src/applications/differential/engine/DifferentialRevisionDraftEngine.php | <?php
final class DifferentialRevisionDraftEngine
extends PhabricatorDraftEngine {
protected function hasCustomDraftContent() {
$viewer = $this->getViewer();
$revision = $this->getObject();
$inlines = id(new DifferentialDiffInlineCommentQuery())
->setViewer($viewer)
->withRevisionPHIDs(array($revision->getPHID()))
->withPublishableComments(true)
->setReturnPartialResultsOnOverheat(true)
->setLimit(1)
->execute();
return (bool)$inlines;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/engine/DifferentialChangesetEngine.php | src/applications/differential/engine/DifferentialChangesetEngine.php | <?php
final class DifferentialChangesetEngine extends Phobject {
private $viewer;
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function rebuildChangesets(array $changesets) {
assert_instances_of($changesets, 'DifferentialChangeset');
$changesets = $this->loadChangesetFiles($changesets);
foreach ($changesets as $changeset) {
$this->detectGeneratedCode($changeset);
$this->computeHashes($changeset);
}
$this->detectCopiedCode($changesets);
}
private function loadChangesetFiles(array $changesets) {
$viewer = $this->getViewer();
$file_phids = array();
foreach ($changesets as $changeset) {
$file_phid = $changeset->getNewFileObjectPHID();
if ($file_phid !== null) {
$file_phids[] = $file_phid;
}
}
if ($file_phids) {
$files = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs($file_phids)
->execute();
$files = mpull($files, null, 'getPHID');
} else {
$files = array();
}
foreach ($changesets as $changeset_key => $changeset) {
$file_phid = $changeset->getNewFileObjectPHID();
if ($file_phid === null) {
continue;
}
$file = idx($files, $file_phid);
if (!$file) {
unset($changesets[$changeset_key]);
continue;
}
$changeset->attachNewFileObject($file);
}
return $changesets;
}
/* -( Generated Code )----------------------------------------------------- */
private function detectGeneratedCode(DifferentialChangeset $changeset) {
$is_generated_trusted = $this->isTrustedGeneratedCode($changeset);
if ($is_generated_trusted) {
$changeset->setTrustedChangesetAttribute(
DifferentialChangeset::ATTRIBUTE_GENERATED,
$is_generated_trusted);
}
$is_generated_untrusted = $this->isUntrustedGeneratedCode($changeset);
if ($is_generated_untrusted) {
$changeset->setUntrustedChangesetAttribute(
DifferentialChangeset::ATTRIBUTE_GENERATED,
$is_generated_untrusted);
}
}
private function isTrustedGeneratedCode(DifferentialChangeset $changeset) {
$filename = $changeset->getFilename();
$paths = PhabricatorEnv::getEnvConfig('differential.generated-paths');
foreach ($paths as $regexp) {
if (preg_match($regexp, $filename)) {
return true;
}
}
return false;
}
private function isUntrustedGeneratedCode(DifferentialChangeset $changeset) {
if ($changeset->getHunks()) {
$new_data = $changeset->makeNewFile();
if (strpos($new_data, '@'.'generated') !== false) {
return true;
}
// See PHI1112. This is the official pattern for marking Go code as
// generated.
if (preg_match('(^// Code generated .* DO NOT EDIT\.$)m', $new_data)) {
return true;
}
}
return false;
}
/* -( Content Hashes )----------------------------------------------------- */
private function computeHashes(DifferentialChangeset $changeset) {
$effect_key = DifferentialChangeset::METADATA_EFFECT_HASH;
$effect_hash = $this->newEffectHash($changeset);
if ($effect_hash !== null) {
$changeset->setChangesetMetadata($effect_key, $effect_hash);
}
}
private function newEffectHash(DifferentialChangeset $changeset) {
if ($changeset->getHunks()) {
$new_data = $changeset->makeNewFile();
return PhabricatorHash::digestForIndex($new_data);
}
if ($changeset->getNewFileObjectPHID()) {
$file = $changeset->getNewFileObject();
// See T13522. For now, the "contentHash" is not really a content hash
// for files >4MB. This is okay: we will just always detect them as
// changed, which is the safer behavior.
$hash = $file->getContentHash();
if ($hash !== null) {
$hash = sprintf('file-hash:%s', $hash);
return PhabricatorHash::digestForIndex($hash);
}
}
return null;
}
/* -( Copied Code )-------------------------------------------------------- */
private function detectCopiedCode(array $changesets) {
// See PHI944. If the total number of changed lines is excessively large,
// don't bother with copied code detection. This can take a lot of time and
// memory and it's not generally of any use for very large changes.
$max_size = 65535;
$total_size = 0;
foreach ($changesets as $changeset) {
$total_size += ($changeset->getAddLines() + $changeset->getDelLines());
}
if ($total_size > $max_size) {
return;
}
$min_width = 30;
$min_lines = 3;
$map = array();
$files = array();
$types = array();
foreach ($changesets as $changeset) {
$file = $changeset->getFilename();
foreach ($changeset->getHunks() as $hunk) {
$lines = $hunk->getStructuredOldFile();
foreach ($lines as $line => $info) {
$type = $info['type'];
if ($type == '\\') {
continue;
}
$types[$file][$line] = $type;
$text = $info['text'];
$text = trim($text);
$files[$file][$line] = $text;
if (strlen($text) >= $min_width) {
$map[$text][] = array($file, $line);
}
}
}
}
foreach ($changesets as $changeset) {
$copies = array();
foreach ($changeset->getHunks() as $hunk) {
$added = $hunk->getStructuredNewFile();
$atype = array();
foreach ($added as $line => $info) {
$atype[$line] = $info['type'];
$added[$line] = trim($info['text']);
}
$skip_lines = 0;
foreach ($added as $line => $code) {
if ($skip_lines) {
// We're skipping lines that we already processed because we
// extended a block above them downward to include them.
$skip_lines--;
continue;
}
if ($atype[$line] !== '+') {
// This line hasn't been changed in the new file, so don't try
// to figure out where it came from.
continue;
}
if (empty($map[$code])) {
// This line was too short to trigger copy/move detection.
continue;
}
if (count($map[$code]) > 16) {
// If there are a large number of identical lines in this diff,
// don't try to figure out where this block came from: the analysis
// is O(N^2), since we need to compare every line against every
// other line. Even if we arrive at a result, it is unlikely to be
// meaningful. See T5041.
continue;
}
$best_length = 0;
// Explore all candidates.
foreach ($map[$code] as $val) {
list($file, $orig_line) = $val;
$length = 1;
// Search backward and forward to find all of the adjacent lines
// which match.
foreach (array(-1, 1) as $direction) {
$offset = $direction;
while (true) {
if (isset($copies[$line + $offset])) {
// If we run into a block above us which we've already
// attributed to a move or copy from elsewhere, stop
// looking.
break;
}
if (!isset($added[$line + $offset])) {
// If we've run off the beginning or end of the new file,
// stop looking.
break;
}
if (!isset($files[$file][$orig_line + $offset])) {
// If we've run off the beginning or end of the original
// file, we also stop looking.
break;
}
$old = $files[$file][$orig_line + $offset];
$new = $added[$line + $offset];
if ($old !== $new) {
// If the old line doesn't match the new line, stop
// looking.
break;
}
$length++;
$offset += $direction;
}
}
if ($length < $best_length) {
// If we already know of a better source (more matching lines)
// for this move/copy, stick with that one. We prefer long
// copies/moves which match a lot of context over short ones.
continue;
}
if ($length == $best_length) {
if (idx($types[$file], $orig_line) != '-') {
// If we already know of an equally good source (same number
// of matching lines) and this isn't a move, stick with the
// other one. We prefer moves over copies.
continue;
}
}
$best_length = $length;
// ($offset - 1) contains number of forward matching lines.
$best_offset = $offset - 1;
$best_file = $file;
$best_line = $orig_line;
}
$file = ($best_file == $changeset->getFilename() ? '' : $best_file);
for ($i = $best_length; $i--; ) {
$type = idx($types[$best_file], $best_line + $best_offset - $i);
$copies[$line + $best_offset - $i] = ($best_length < $min_lines
? array() // Ignore short blocks.
: array($file, $best_line + $best_offset - $i, $type));
}
$skip_lines = $best_offset;
}
}
$copies = array_filter($copies);
if ($copies) {
$metadata = $changeset->getMetadata();
$metadata['copy:lines'] = $copies;
$changeset->setMetadata($metadata);
}
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/engine/DifferentialFileTreeEngine.php | src/applications/differential/engine/DifferentialFileTreeEngine.php | <?php
final class DifferentialFileTreeEngine
extends Phobject {
private $viewer;
private $changesets;
private $disabled;
private $ownedChangesets;
public function setViewer($viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function getIsVisible() {
return (bool)$this->getSetting($this->getVisibleSettingKey());
}
public function setDisabled($disabled) {
$this->disabled = $disabled;
return $this;
}
public function getDisabled() {
return $this->disabled;
}
public function setChangesets(array $changesets) {
$this->changesets = $changesets;
return $this;
}
public function getChangesets() {
return $this->changesets;
}
public function newView($content) {
if ($this->getDisabled()) {
return $content;
}
require_celerity_resource('diff-tree-view-css');
$width = $this->getWidth();
$is_visible = $this->getIsVisible();
$formation_view = new PHUIFormationView();
$flank_view = $formation_view->newFlankColumn()
->setHeaderText(pht('Paths'))
->setIsResizable(true)
->setIsFixed(true)
->setIsVisible($is_visible)
->setIsDesktopOnly(true)
->setWidth($width)
->setMinimumWidth($this->getMinimumWidth())
->setMaximumWidth($this->getMaximumWidth());
$viewer = $this->getViewer();
if ($viewer->isLoggedIn()) {
$flank_view
->setExpanderTooltip(pht('Show Paths Panel'))
->setVisibleSettingKey($this->getVisibleSettingKey())
->setWidthSettingKey($this->getWidthSettingKey());
}
$head_view = id(new PHUIListView())
->addMenuItem(
id(new PHUIListItemView())
->setIcon('fa-list')
->setName(pht('Table of Contents'))
->setKeyCommand('t')
->setHref('#'));
$flank_view->setHead($head_view);
$tail_view = id(new PHUIListView());
if ($viewer->isLoggedIn()) {
$tail_view->addMenuItem(
id(new PHUIListItemView())
->setIcon('fa-comment-o')
->setName(pht('Add Comment'))
->setKeyCommand('x')
->setHref('#'));
}
$tail_view
->addMenuItem(
id(new PHUIListItemView())
->setIcon('fa-chevron-left')
->setName(pht('Hide Panel'))
->setKeyCommand('f')
->setHref('#'))
->addMenuItem(
id(new PHUIListItemView())
->setIcon('fa-keyboard-o')
->setName(pht('Keyboard Reference'))
->setKeyCommand('?')
->setHref('#'));
$flank_view->setTail($tail_view);
$main_column = $formation_view->newContentColumn()
->appendChild($content);
return $formation_view;
}
private function getVisibleSettingKey() {
return PhabricatorFiletreeVisibleSetting::SETTINGKEY;
}
private function getWidthSettingKey() {
return PhabricatorFiletreeWidthSetting::SETTINGKEY;
}
private function getWidth() {
$width = (int)$this->getSetting($this->getWidthSettingKey());
if (!$width) {
$width = $this->getDefaultWidth();
}
$min = $this->getMinimumWidth();
if ($width < $min) {
$width = $min;
}
$max = $this->getMaximumWidth();
if ($width > $max) {
$width = $max;
}
return $width;
}
private function getDefaultWidth() {
return 240;
}
private function getMinimumWidth() {
return 150;
}
private function getMaximumWidth() {
return 512;
}
private function getSetting($key) {
$viewer = $this->getViewer();
return $viewer->getUserSetting($key);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/engine/DifferentialAffectedPathEngine.php | src/applications/differential/engine/DifferentialAffectedPathEngine.php | <?php
final class DifferentialAffectedPathEngine
extends Phobject {
private $revision;
private $diff;
public function setRevision(DifferentialRevision $revision) {
$this->revision = $revision;
return $this;
}
public function getRevision() {
return $this->revision;
}
public function setDiff(DifferentialDiff $diff) {
$this->diff = $diff;
return $this;
}
public function getDiff() {
return $this->diff;
}
public function updateAffectedPaths() {
$revision = $this->getRevision();
$diff = $this->getDiff();
$repository = $revision->getRepository();
if ($repository) {
$repository_id = $repository->getID();
} else {
$repository_id = null;
}
$paths = $this->getAffectedPaths();
$path_ids =
PhabricatorRepositoryCommitChangeParserWorker::lookupOrCreatePaths(
$paths);
$table = new DifferentialAffectedPath();
$conn = $table->establishConnection('w');
$sql = array();
foreach ($path_ids as $path_id) {
$sql[] = qsprintf(
$conn,
'(%nd, %d, %d)',
$repository_id,
$path_id,
$revision->getID());
}
queryfx(
$conn,
'DELETE FROM %R WHERE revisionID = %d',
$table,
$revision->getID());
if ($sql) {
foreach (PhabricatorLiskDAO::chunkSQL($sql) as $chunk) {
queryfx(
$conn,
'INSERT INTO %R (repositoryID, pathID, revisionID) VALUES %LQ',
$table,
$chunk);
}
}
}
public function destroyAffectedPaths() {
$revision = $this->getRevision();
$table = new DifferentialAffectedPath();
$conn = $table->establishConnection('w');
queryfx(
$conn,
'DELETE FROM %R WHERE revisionID = %d',
$table,
$revision->getID());
}
public function getAffectedPaths() {
$revision = $this->getRevision();
$diff = $this->getDiff();
$repository = $revision->getRepository();
$path_prefix = null;
if ($repository) {
$local_root = $diff->getSourceControlPath();
if ($local_root) {
// We're in a working copy which supports subdirectory checkouts (e.g.,
// SVN) so we need to figure out what prefix we should add to each path
// (e.g., trunk/projects/example/) to get the absolute path from the
// root of the repository. DVCS systems like Git and Mercurial are not
// affected.
// Normalize both paths and check if the repository root is a prefix of
// the local root. If so, throw it away. Note that this correctly
// handles the case where the remote path is "/".
$local_root = id(new PhutilURI($local_root))->getPath();
$local_root = rtrim($local_root, '/');
$repo_root = id(new PhutilURI($repository->getRemoteURI()))->getPath();
$repo_root = rtrim($repo_root, '/');
if (!strncmp($repo_root, $local_root, strlen($repo_root))) {
$path_prefix = substr($local_root, strlen($repo_root));
}
}
}
$changesets = $diff->getChangesets();
$paths = array();
foreach ($changesets as $changeset) {
$paths[] = $path_prefix.'/'.$changeset->getFilename();
}
// Mark this as also touching all parent paths, so you can see all pending
// changes to any file within a directory.
$all_paths = array();
foreach ($paths as $local) {
foreach (DiffusionPathIDQuery::expandPathToRoot($local) as $path) {
$all_paths[$path] = true;
}
}
$all_paths = array_keys($all_paths);
return $all_paths;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/engine/DifferentialDiffExtractionEngine.php | src/applications/differential/engine/DifferentialDiffExtractionEngine.php | <?php
final class DifferentialDiffExtractionEngine extends Phobject {
private $viewer;
private $authorPHID;
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setAuthorPHID($author_phid) {
$this->authorPHID = $author_phid;
return $this;
}
public function getAuthorPHID() {
return $this->authorPHID;
}
public function newDiffFromCommit(PhabricatorRepositoryCommit $commit) {
$viewer = $this->getViewer();
// If we already have an unattached diff for this commit, just reuse it.
// This stops us from repeatedly generating diffs if something goes wrong
// later in the process. See T10968 for context.
$existing_diffs = id(new DifferentialDiffQuery())
->setViewer($viewer)
->withCommitPHIDs(array($commit->getPHID()))
->withHasRevision(false)
->needChangesets(true)
->execute();
if ($existing_diffs) {
return head($existing_diffs);
}
$repository = $commit->getRepository();
$identifier = $commit->getCommitIdentifier();
$monogram = $commit->getMonogram();
$drequest = DiffusionRequest::newFromDictionary(
array(
'user' => $viewer,
'repository' => $repository,
));
$diff_info = DiffusionQuery::callConduitWithDiffusionRequest(
$viewer,
$drequest,
'diffusion.rawdiffquery',
array(
'commit' => $identifier,
));
$file_phid = $diff_info['filePHID'];
$diff_file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($file_phid))
->executeOne();
if (!$diff_file) {
throw new Exception(
pht(
'Failed to load file ("%s") returned by "%s".',
$file_phid,
'diffusion.rawdiffquery'));
}
$raw_diff = $diff_file->loadFileData();
// TODO: Support adds, deletes and moves under SVN.
if (strlen($raw_diff)) {
$changes = id(new ArcanistDiffParser())->parseDiff($raw_diff);
} else {
// This is an empty diff, maybe made with `git commit --allow-empty`.
// NOTE: These diffs have the same tree hash as their ancestors, so
// they may attach to revisions in an unexpected way. Just let this
// happen for now, although it might make sense to special case it
// eventually.
$changes = array();
}
$diff = DifferentialDiff::newFromRawChanges($viewer, $changes)
->setRepositoryPHID($repository->getPHID())
->setCommitPHID($commit->getPHID())
->setCreationMethod('commit')
->setSourceControlSystem($repository->getVersionControlSystem())
->setLintStatus(DifferentialLintStatus::LINT_AUTO_SKIP)
->setUnitStatus(DifferentialUnitStatus::UNIT_AUTO_SKIP)
->setDateCreated($commit->getEpoch())
->setDescription($monogram);
$author_phid = $this->getAuthorPHID();
if ($author_phid !== null) {
$diff->setAuthorPHID($author_phid);
}
$parents = DiffusionQuery::callConduitWithDiffusionRequest(
$viewer,
$drequest,
'diffusion.commitparentsquery',
array(
'commit' => $identifier,
));
if ($parents) {
$diff->setSourceControlBaseRevision(head($parents));
}
// TODO: Attach binary files.
return $diff->save();
}
public function isDiffChangedBeforeCommit(
PhabricatorRepositoryCommit $commit,
DifferentialDiff $old,
DifferentialDiff $new) {
$viewer = $this->getViewer();
$repository = $commit->getRepository();
$identifier = $commit->getCommitIdentifier();
$vs_changesets = array();
foreach ($old->getChangesets() as $changeset) {
$path = $changeset->getAbsoluteRepositoryPath($repository, $old);
$path = ltrim($path, '/');
$vs_changesets[$path] = $changeset;
}
$changesets = array();
foreach ($new->getChangesets() as $changeset) {
$path = $changeset->getAbsoluteRepositoryPath($repository, $new);
$path = ltrim($path, '/');
$changesets[$path] = $changeset;
}
if (array_fill_keys(array_keys($changesets), true) !=
array_fill_keys(array_keys($vs_changesets), true)) {
return true;
}
$file_phids = array();
foreach ($vs_changesets as $changeset) {
$metadata = $changeset->getMetadata();
$file_phid = idx($metadata, 'new:binary-phid');
if ($file_phid) {
$file_phids[$file_phid] = $file_phid;
}
}
$files = array();
if ($file_phids) {
$files = id(new PhabricatorFileQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withPHIDs($file_phids)
->execute();
$files = mpull($files, null, 'getPHID');
}
foreach ($changesets as $path => $changeset) {
$vs_changeset = $vs_changesets[$path];
$file_phid = idx($vs_changeset->getMetadata(), 'new:binary-phid');
if ($file_phid) {
if (!isset($files[$file_phid])) {
return true;
}
$drequest = DiffusionRequest::newFromDictionary(
array(
'user' => $viewer,
'repository' => $repository,
));
try {
$response = DiffusionQuery::callConduitWithDiffusionRequest(
$viewer,
$drequest,
'diffusion.filecontentquery',
array(
'commit' => $identifier,
'path' => $path,
));
} catch (Exception $ex) {
// TODO: See PHI1044. This call may fail if the diff deleted the
// file. If the call fails, just detect a change for now. This should
// generally be made cleaner in the future.
return true;
}
$new_file_phid = $response['filePHID'];
if (!$new_file_phid) {
return true;
}
$new_file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($new_file_phid))
->executeOne();
if (!$new_file) {
return true;
}
if ($files[$file_phid]->loadFileData() != $new_file->loadFileData()) {
return true;
}
} else {
$context = implode("\n", $changeset->makeChangesWithContext());
$vs_context = implode("\n", $vs_changeset->makeChangesWithContext());
// We couldn't just compare $context and $vs_context because following
// diffs will be considered different:
//
// -(empty line)
// -echo 'test';
// (empty line)
//
// (empty line)
// -echo "test";
// -(empty line)
$hunk = id(new DifferentialHunk())->setChanges($context);
$vs_hunk = id(new DifferentialHunk())->setChanges($vs_context);
if ($hunk->makeOldFile() != $vs_hunk->makeOldFile() ||
$hunk->makeNewFile() != $vs_hunk->makeNewFile()) {
return true;
}
}
}
return false;
}
public function updateRevisionWithCommit(
DifferentialRevision $revision,
PhabricatorRepositoryCommit $commit,
array $more_xactions,
PhabricatorContentSource $content_source) {
$viewer = $this->getViewer();
$new_diff = $this->newDiffFromCommit($commit);
$old_diff = $revision->getActiveDiff();
$changed_uri = null;
if ($old_diff) {
$old_diff = id(new DifferentialDiffQuery())
->setViewer($viewer)
->withIDs(array($old_diff->getID()))
->needChangesets(true)
->executeOne();
if ($old_diff) {
$has_changed = $this->isDiffChangedBeforeCommit(
$commit,
$old_diff,
$new_diff);
if ($has_changed) {
$revision_monogram = $revision->getMonogram();
$old_id = $old_diff->getID();
$new_id = $new_diff->getID();
$changed_uri = "/{$revision_monogram}?vs={$old_id}&id={$new_id}#toc";
$changed_uri = PhabricatorEnv::getProductionURI($changed_uri);
}
}
}
$xactions = array();
// If the revision isn't closed or "Accepted", write a warning into the
// transaction log. This makes it more clear when users bend the rules.
if (!$revision->isClosed() && !$revision->isAccepted()) {
$wrong_type = DifferentialRevisionWrongStateTransaction::TRANSACTIONTYPE;
$xactions[] = id(new DifferentialTransaction())
->setTransactionType($wrong_type)
->setNewValue($revision->getModernRevisionStatus());
}
$concerning_builds = self::loadConcerningBuilds(
$this->getViewer(),
$revision,
$strict = false);
if ($concerning_builds) {
$build_list = array();
foreach ($concerning_builds as $build) {
$build_list[] = array(
'phid' => $build->getPHID(),
'status' => $build->getBuildStatus(),
);
}
$wrong_builds =
DifferentialRevisionWrongBuildsTransaction::TRANSACTIONTYPE;
$xactions[] = id(new DifferentialTransaction())
->setTransactionType($wrong_builds)
->setNewValue($build_list);
}
$type_update = DifferentialRevisionUpdateTransaction::TRANSACTIONTYPE;
$xactions[] = id(new DifferentialTransaction())
->setTransactionType($type_update)
->setIgnoreOnNoEffect(true)
->setNewValue($new_diff->getPHID())
->setMetadataValue('isCommitUpdate', true)
->setMetadataValue('commitPHIDs', array($commit->getPHID()));
foreach ($more_xactions as $more_xaction) {
$xactions[] = $more_xaction;
}
$editor = id(new DifferentialTransactionEditor())
->setActor($viewer)
->setContinueOnMissingFields(true)
->setContinueOnNoEffect(true)
->setContentSource($content_source)
->setChangedPriorToCommitURI($changed_uri)
->setIsCloseByCommit(true);
$author_phid = $this->getAuthorPHID();
if ($author_phid !== null) {
$editor->setActingAsPHID($author_phid);
}
$editor->applyTransactions($revision, $xactions);
}
public static function loadConcerningBuilds(
PhabricatorUser $viewer,
DifferentialRevision $revision,
$strict) {
$diff = $revision->getActiveDiff();
$buildables = id(new HarbormasterBuildableQuery())
->setViewer($viewer)
->withBuildablePHIDs(array($diff->getPHID()))
->needBuilds(true)
->withManualBuildables(false)
->execute();
if (!$buildables) {
return array();
}
$land_key = HarbormasterBuildPlanBehavior::BEHAVIOR_LANDWARNING;
$behavior = HarbormasterBuildPlanBehavior::getBehavior($land_key);
$key_never = HarbormasterBuildPlanBehavior::LANDWARNING_NEVER;
$key_building = HarbormasterBuildPlanBehavior::LANDWARNING_IF_BUILDING;
$key_complete = HarbormasterBuildPlanBehavior::LANDWARNING_IF_COMPLETE;
$concerning_builds = array();
foreach ($buildables as $buildable) {
$builds = $buildable->getBuilds();
foreach ($builds as $build) {
$plan = $build->getBuildPlan();
$option = $behavior->getPlanOption($plan);
$behavior_value = $option->getKey();
$if_never = ($behavior_value === $key_never);
if ($if_never) {
continue;
}
$if_building = ($behavior_value === $key_building);
if ($if_building && $build->isComplete()) {
continue;
}
$if_complete = ($behavior_value === $key_complete);
if ($if_complete) {
if (!$build->isComplete()) {
continue;
}
// TODO: If you "arc land" and a build with "Warn: If Complete"
// is still running, you may not see a warning, and push the revision
// in good faith. The build may then complete before we get here, so
// we now see a completed, failed build.
// For now, just err on the side of caution and assume these builds
// were in a good state when we prompted the user, even if they're in
// a bad state now.
// We could refine this with a rule like "if the build finished
// within a couple of minutes before the push happened, assume it was
// in good faith", but we don't currently have an especially
// convenient way to check when the build finished or when the commit
// was pushed or discovered, and this would create some issues in
// cases where the repository is observed and the fetch pipeline
// stalls for a while.
// If we're in strict mode (from a pre-commit content hook), we do
// not ignore these, since we're doing an instantaneous check against
// the current state.
if (!$strict) {
continue;
}
}
if ($build->isPassed()) {
continue;
}
$concerning_builds[] = $build;
}
}
return $concerning_builds;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/typeahead/DifferentialReviewerFunctionDatasource.php | src/applications/differential/typeahead/DifferentialReviewerFunctionDatasource.php | <?php
final class DifferentialReviewerFunctionDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Reviewers');
}
public function getPlaceholderText() {
return pht('Type a user, project, package name or function...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
public function getComponentDatasources() {
return array(
new PhabricatorProjectOrUserFunctionDatasource(),
new PhabricatorOwnersPackageFunctionDatasource(),
new DifferentialNoReviewersDatasource(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/typeahead/DifferentialResponsibleViewerFunctionDatasource.php | src/applications/differential/typeahead/DifferentialResponsibleViewerFunctionDatasource.php | <?php
final class DifferentialResponsibleViewerFunctionDatasource
extends PhabricatorTypeaheadDatasource {
public function getBrowseTitle() {
return pht('Browse Viewer');
}
public function getPlaceholderText() {
return pht('Type viewer()...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorPeopleApplication';
}
public function getDatasourceFunctions() {
return array(
'viewer' => array(
'name' => pht('Current Viewer'),
'summary' => pht('Use the current viewing user.'),
'description' => pht(
'Show revisions the current viewer is responsible for. This '.
'function includes revisions the viewer is responsible for through '.
'membership in projects and packages.'),
),
);
}
public function loadResults() {
if ($this->getViewer()->getPHID()) {
$results = array($this->renderViewerFunctionToken());
} else {
$results = array();
}
return $this->filterResultsAgainstTokens($results);
}
protected function canEvaluateFunction($function) {
if (!$this->getViewer()->getPHID()) {
return false;
}
return parent::canEvaluateFunction($function);
}
protected function evaluateFunction($function, array $argv_list) {
$results = array();
foreach ($argv_list as $argv) {
$results[] = $this->getViewer()->getPHID();
}
return DifferentialResponsibleDatasource::expandResponsibleUsers(
$this->getViewer(),
$results);
}
public function renderFunctionTokens($function, array $argv_list) {
$tokens = array();
foreach ($argv_list as $argv) {
$tokens[] = PhabricatorTypeaheadTokenView::newFromTypeaheadResult(
$this->renderViewerFunctionToken());
}
return $tokens;
}
private function renderViewerFunctionToken() {
return $this->newFunctionResult()
->setName(pht('Current Viewer'))
->setPHID('viewer()')
->setIcon('fa-user')
->setUnique(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/typeahead/DifferentialResponsibleDatasource.php | src/applications/differential/typeahead/DifferentialResponsibleDatasource.php | <?php
final class DifferentialResponsibleDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Responsible Users');
}
public function getPlaceholderText() {
return pht('Type a user, project, or package name, or function...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
public function getComponentDatasources() {
return array(
new DifferentialResponsibleUserDatasource(),
new DifferentialResponsibleViewerFunctionDatasource(),
new DifferentialExactUserFunctionDatasource(),
new PhabricatorProjectDatasource(),
new PhabricatorOwnersPackageDatasource(),
);
}
public static function expandResponsibleUsers(
PhabricatorUser $viewer,
array $values) {
$phids = array();
foreach ($values as $value) {
if (phid_get_type($value) == PhabricatorPeopleUserPHIDType::TYPECONST) {
$phids[] = $value;
}
}
if (!$phids) {
return $values;
}
$projects = id(new PhabricatorProjectQuery())
->setViewer($viewer)
->withMemberPHIDs($phids)
->execute();
foreach ($projects as $project) {
$phids[] = $project->getPHID();
$values[] = $project->getPHID();
}
$packages = id(new PhabricatorOwnersPackageQuery())
->setViewer($viewer)
->withOwnerPHIDs($phids)
->execute();
foreach ($packages as $package) {
$values[] = $package->getPHID();
}
return $values;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/typeahead/DifferentialBlockingReviewerDatasource.php | src/applications/differential/typeahead/DifferentialBlockingReviewerDatasource.php | <?php
final class DifferentialBlockingReviewerDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Blocking Reviewers');
}
public function getPlaceholderText() {
return pht('Type a user, project, or package name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
public function getComponentDatasources() {
return array(
new PhabricatorPeopleDatasource(),
new PhabricatorProjectDatasource(),
new PhabricatorOwnersPackageDatasource(),
);
}
public function getDatasourceFunctions() {
return array(
'blocking' => array(
'name' => pht('Blocking: ...'),
'arguments' => pht('reviewer'),
'summary' => pht('Select a blocking reviewer.'),
'description' => pht(
"This function allows you to add a reviewer as a blocking ".
"reviewer. For example, this will add `%s` as a blocking reviewer: ".
"\n\n%s\n\n",
'alincoln',
'> blocking(alincoln)'),
),
);
}
protected function didLoadResults(array $results) {
foreach ($results as $result) {
$result
->setColor('red')
->setTokenType(PhabricatorTypeaheadTokenView::TYPE_FUNCTION)
->setIcon('fa-asterisk')
->setPHID('blocking('.$result->getPHID().')')
->setDisplayName(pht('Blocking: %s', $result->getDisplayName()))
->setName($result->getName().' blocking');
}
return $results;
}
protected function evaluateFunction($function, array $argv_list) {
$phids = array();
foreach ($argv_list as $argv) {
$phids[] = head($argv);
}
$phids = $this->resolvePHIDs($phids);
$results = array();
foreach ($phids as $phid) {
$results[] = array(
'type' => DifferentialReviewerStatus::STATUS_BLOCKING,
'phid' => $phid,
);
}
return $results;
}
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('Blocking: Invalid Reviewer'));
} else {
$token
->setIcon('fa-asterisk')
->setTokenType(PhabricatorTypeaheadTokenView::TYPE_FUNCTION)
->setColor('red')
->setKey('blocking('.$token->getKey().')')
->setValue(pht('Blocking: %s', $token->getValue()));
}
}
return $tokens;
}
private function resolvePHIDs(array $phids) {
$usernames = array();
foreach ($phids as $key => $phid) {
if (phid_get_type($phid) != PhabricatorPeopleUserPHIDType::TYPECONST) {
$usernames[$key] = $phid;
}
}
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/differential/typeahead/DifferentialExactUserFunctionDatasource.php | src/applications/differential/typeahead/DifferentialExactUserFunctionDatasource.php | <?php
final class DifferentialExactUserFunctionDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Users');
}
public function getPlaceholderText() {
return pht('Type exact(<user>)...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorPeopleApplication';
}
public function getComponentDatasources() {
return array(
new PhabricatorPeopleDatasource(),
);
}
public function getDatasourceFunctions() {
return array(
'exact' => array(
'name' => pht('Exact: ...'),
'arguments' => pht('username'),
'summary' => pht('Find results matching users exactly.'),
'description' => pht(
"This function allows you to find results associated only with ".
"a user, exactly, and not any of their projects or packages. For ".
"example, this will find results associated with only `%s`:".
"\n\n%s\n\n",
'alincoln',
'> exact(alincoln)'),
),
);
}
protected function didLoadResults(array $results) {
foreach ($results as $result) {
$result
->setColor(null)
->setTokenType(PhabricatorTypeaheadTokenView::TYPE_FUNCTION)
->setIcon('fa-asterisk')
->setPHID('exact('.$result->getPHID().')')
->setDisplayName(pht('Exact User: %s', $result->getDisplayName()))
->setName($result->getName().' exact');
}
return $results;
}
protected function evaluateFunction($function, array $argv_list) {
$phids = array();
foreach ($argv_list as $argv) {
$phids[] = head($argv);
}
return $this->resolvePHIDs($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('Exact User: Invalid User'));
} else {
$token
->setIcon('fa-asterisk')
->setTokenType(PhabricatorTypeaheadTokenView::TYPE_FUNCTION)
->setKey('exact('.$token->getKey().')')
->setValue(pht('Exact User: %s', $token->getValue()));
}
}
return $tokens;
}
private function resolvePHIDs(array $phids) {
$usernames = array();
foreach ($phids as $key => $phid) {
if (phid_get_type($phid) != PhabricatorPeopleUserPHIDType::TYPECONST) {
$usernames[$key] = $phid;
}
}
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/differential/typeahead/DifferentialNoReviewersDatasource.php | src/applications/differential/typeahead/DifferentialNoReviewersDatasource.php | <?php
final class DifferentialNoReviewersDatasource
extends PhabricatorTypeaheadDatasource {
const FUNCTION_TOKEN = 'none()';
public function getBrowseTitle() {
return pht('Browse No Reviewers');
}
public function getPlaceholderText() {
return pht('Type "none"...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
public function getDatasourceFunctions() {
return array(
'none' => array(
'name' => pht('No Reviewers'),
'summary' => pht('Find results which have no reviewers.'),
'description' => pht(
"This function includes results which have no reviewers. Use a ".
"query like this to find results with no reviewers:\n\n%s\n\n".
"If you combine this function with other functions, the query will ".
"return results which match the other selectors //or// have no ".
"reviewers. For example, this query will find results which have ".
"`alincoln` as a reviewer, and will also find results which have ".
"no reviewers:".
"\n\n%s",
'> none()',
'> alincoln, none()'),
),
);
}
public function loadResults() {
$results = array(
$this->buildNoReviewersResult(),
);
return $this->filterResultsAgainstTokens($results);
}
protected function evaluateFunction($function, array $argv_list) {
$results = array();
foreach ($argv_list as $argv) {
$results[] = self::FUNCTION_TOKEN;
}
return $results;
}
public function renderFunctionTokens($function, array $argv_list) {
$results = array();
foreach ($argv_list as $argv) {
$results[] = PhabricatorTypeaheadTokenView::newFromTypeaheadResult(
$this->buildNoReviewersResult());
}
return $results;
}
private function buildNoReviewersResult() {
$name = pht('No Reviewers');
return $this->newFunctionResult()
->setName($name.' none')
->setDisplayName($name)
->setIcon('fa-ban')
->setPHID('none()')
->setUnique(true)
->addAttribute(pht('Select results with no reviewers.'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/typeahead/DifferentialRevisionClosedStatusDatasource.php | src/applications/differential/typeahead/DifferentialRevisionClosedStatusDatasource.php | <?php
final class DifferentialRevisionClosedStatusDatasource
extends PhabricatorTypeaheadDatasource {
const FUNCTION_TOKEN = 'closed()';
public function getBrowseTitle() {
return pht('Browse Any Closed Status');
}
public function getPlaceholderText() {
return pht('Type closed()...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
public function getDatasourceFunctions() {
return array(
'closed' => array(
'name' => pht('Any Closed Status'),
'summary' => pht('Find results with any closed status.'),
'description' => pht(
'This function includes results which have any closed status.'),
),
);
}
public function loadResults() {
$results = array(
$this->buildClosedResult(),
);
return $this->filterResultsAgainstTokens($results);
}
protected function evaluateFunction($function, array $argv_list) {
$results = array();
$map = DifferentialRevisionStatus::getAll();
foreach ($argv_list as $argv) {
foreach ($map as $status) {
if ($status->isClosedStatus()) {
$results[] = $status->getKey();
}
}
}
return $results;
}
public function renderFunctionTokens($function, array $argv_list) {
$results = array();
foreach ($argv_list as $argv) {
$results[] = PhabricatorTypeaheadTokenView::newFromTypeaheadResult(
$this->buildClosedResult());
}
return $results;
}
private function buildClosedResult() {
$name = pht('Any Closed Status');
return $this->newFunctionResult()
->setName($name.' closed')
->setDisplayName($name)
->setPHID(self::FUNCTION_TOKEN)
->setUnique(true)
->addAttribute(pht('Select any closed status.'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/typeahead/DifferentialResponsibleUserDatasource.php | src/applications/differential/typeahead/DifferentialResponsibleUserDatasource.php | <?php
final class DifferentialResponsibleUserDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Users');
}
public function getPlaceholderText() {
return pht('Type a user name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
public function getComponentDatasources() {
return array(
new PhabricatorPeopleDatasource(),
);
}
protected function evaluateValues(array $values) {
return DifferentialResponsibleDatasource::expandResponsibleUsers(
$this->getViewer(),
$values);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/typeahead/DifferentialRevisionOpenStatusDatasource.php | src/applications/differential/typeahead/DifferentialRevisionOpenStatusDatasource.php | <?php
final class DifferentialRevisionOpenStatusDatasource
extends PhabricatorTypeaheadDatasource {
const FUNCTION_TOKEN = 'open()';
public function getBrowseTitle() {
return pht('Browse Any Open Status');
}
public function getPlaceholderText() {
return pht('Type open()...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
public function getDatasourceFunctions() {
return array(
'open' => array(
'name' => pht('Any Open Status'),
'summary' => pht('Find results with any open status.'),
'description' => pht(
'This function includes results which have any open status.'),
),
);
}
public function loadResults() {
$results = array(
$this->buildOpenResult(),
);
return $this->filterResultsAgainstTokens($results);
}
protected function evaluateFunction($function, array $argv_list) {
$results = array();
$map = DifferentialRevisionStatus::getAll();
foreach ($argv_list as $argv) {
foreach ($map as $status) {
if (!$status->isClosedStatus()) {
$results[] = $status->getKey();
}
}
}
return $results;
}
public function renderFunctionTokens($function, array $argv_list) {
$results = array();
foreach ($argv_list as $argv) {
$results[] = PhabricatorTypeaheadTokenView::newFromTypeaheadResult(
$this->buildOpenResult());
}
return $results;
}
private function buildOpenResult() {
$name = pht('Any Open Status');
return $this->newFunctionResult()
->setName($name.' open')
->setDisplayName($name)
->setPHID(self::FUNCTION_TOKEN)
->setUnique(true)
->addAttribute(pht('Select any open status.'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/typeahead/DifferentialRevisionStatusFunctionDatasource.php | src/applications/differential/typeahead/DifferentialRevisionStatusFunctionDatasource.php | <?php
final class DifferentialRevisionStatusFunctionDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Statuses');
}
public function getPlaceholderText() {
return pht('Type a revision status name or function...');
}
public function getComponentDatasources() {
return array(
new DifferentialRevisionStatusDatasource(),
new DifferentialRevisionClosedStatusDatasource(),
new DifferentialRevisionOpenStatusDatasource(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/typeahead/DifferentialReviewerDatasource.php | src/applications/differential/typeahead/DifferentialReviewerDatasource.php | <?php
final class DifferentialReviewerDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Reviewers');
}
public function getPlaceholderText() {
return pht('Type a user, project, or package name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
public function getComponentDatasources() {
return array(
new PhabricatorPeopleDatasource(),
new PhabricatorProjectDatasource(),
new PhabricatorOwnersPackageDatasource(),
new DifferentialBlockingReviewerDatasource(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/typeahead/DifferentialRevisionStatusDatasource.php | src/applications/differential/typeahead/DifferentialRevisionStatusDatasource.php | <?php
final class DifferentialRevisionStatusDatasource
extends PhabricatorTypeaheadDatasource {
public function getBrowseTitle() {
return pht('Browse Statuses');
}
public function getPlaceholderText() {
return pht('Type a revision status name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
public function loadResults() {
$results = $this->buildResults();
return $this->filterResultsAgainstTokens($results);
}
protected function renderSpecialTokens(array $values) {
return $this->renderTokensFromResults($this->buildResults(), $values);
}
private function buildResults() {
$results = array();
$statuses = DifferentialRevisionStatus::getAll();
foreach ($statuses as $status) {
$key = $status->getKey();
$result = id(new PhabricatorTypeaheadResult())
->setIcon($status->getIcon())
->setPHID($key)
->setName($status->getDisplayName());
if ($status->isClosedStatus()) {
$result->addAttribute(pht('Closed Status'));
} else {
$result->addAttribute(pht('Open Status'));
}
$results[$key] = $result;
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/capability/DifferentialDefaultViewCapability.php | src/applications/differential/capability/DifferentialDefaultViewCapability.php | <?php
final class DifferentialDefaultViewCapability
extends PhabricatorPolicyCapability {
const CAPABILITY = 'differential.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/differential/remarkup/DifferentialRemarkupRule.php | src/applications/differential/remarkup/DifferentialRemarkupRule.php | <?php
final class DifferentialRemarkupRule extends PhabricatorObjectRemarkupRule {
protected function getObjectNamePrefix() {
return 'D';
}
protected function loadObjects(array $ids) {
$viewer = $this->getEngine()->getConfig('viewer');
return id(new DifferentialRevisionQuery())
->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/differential/constants/DifferentialReviewerStatus.php | src/applications/differential/constants/DifferentialReviewerStatus.php | <?php
final class DifferentialReviewerStatus extends Phobject {
const STATUS_BLOCKING = 'blocking';
const STATUS_ADDED = 'added';
const STATUS_ACCEPTED = 'accepted';
const STATUS_REJECTED = 'rejected';
const STATUS_COMMENTED = 'commented';
const STATUS_ACCEPTED_OLDER = 'accepted-older';
const STATUS_REJECTED_OLDER = 'rejected-older';
const STATUS_RESIGNED = 'resigned';
/**
* Returns the relative strength of a status, used to pick a winner when a
* transaction group makes several status changes to a particular reviewer.
*
* For example, if you accept a revision and leave a comment, the transactions
* will attempt to update you to both "commented" and "accepted". We want
* "accepted" to win, because it's the stronger of the two.
*
* @param const Reviewer status constant.
* @return int Relative strength (higher is stronger).
*/
public static function getStatusStrength($constant) {
$map = array(
self::STATUS_ADDED => 1,
self::STATUS_COMMENTED => 2,
self::STATUS_BLOCKING => 3,
self::STATUS_ACCEPTED_OLDER => 4,
self::STATUS_REJECTED_OLDER => 4,
self::STATUS_ACCEPTED => 5,
self::STATUS_REJECTED => 5,
self::STATUS_RESIGNED => 5,
);
return idx($map, $constant, 0);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/constants/DifferentialChangeType.php | src/applications/differential/constants/DifferentialChangeType.php | <?php
final class DifferentialChangeType extends Phobject {
const TYPE_ADD = 1;
const TYPE_CHANGE = 2;
const TYPE_DELETE = 3;
const TYPE_MOVE_AWAY = 4;
const TYPE_COPY_AWAY = 5;
const TYPE_MOVE_HERE = 6;
const TYPE_COPY_HERE = 7;
const TYPE_MULTICOPY = 8;
const TYPE_MESSAGE = 9;
const TYPE_CHILD = 10;
const FILE_TEXT = 1;
const FILE_IMAGE = 2;
const FILE_BINARY = 3;
const FILE_DIRECTORY = 4;
const FILE_SYMLINK = 5;
const FILE_DELETED = 6;
const FILE_NORMAL = 7;
const FILE_SUBMODULE = 8;
public static function getIconForFileType($type) {
static $icons = array(
self::FILE_TEXT => 'fa-file-text-o',
self::FILE_IMAGE => 'fa-file-image-o',
self::FILE_BINARY => 'fa-file',
self::FILE_DIRECTORY => 'fa-folder',
self::FILE_SYMLINK => 'fa-link',
self::FILE_DELETED => 'fa-file',
self::FILE_NORMAL => 'fa-file-text-o',
self::FILE_SUBMODULE => 'fa-folder-open-o',
);
return idx($icons, $type, 'fa-file');
}
public static function getIconColorForFileType($type) {
static $icons = array(
self::FILE_TEXT => 'bluetext',
self::FILE_IMAGE => 'bluetext',
self::FILE_BINARY => 'green',
self::FILE_DIRECTORY => 'bluetext',
self::FILE_SYMLINK => 'bluetext',
self::FILE_DELETED => 'red',
self::FILE_NORMAL => 'bluetext',
self::FILE_SUBMODULE => 'bluetext',
);
return idx($icons, $type, 'black');
}
public static function isOldLocationChangeType($type) {
static $types = array(
self::TYPE_MOVE_AWAY => true,
self::TYPE_COPY_AWAY => true,
self::TYPE_MULTICOPY => true,
);
return isset($types[$type]);
}
public static function isNewLocationChangeType($type) {
static $types = array(
self::TYPE_MOVE_HERE => true,
self::TYPE_COPY_HERE => true,
);
return isset($types[$type]);
}
public static function isDeleteChangeType($type) {
static $types = array(
self::TYPE_DELETE => true,
self::TYPE_MOVE_AWAY => true,
self::TYPE_MULTICOPY => true,
);
return isset($types[$type]);
}
public static function isCreateChangeType($type) {
static $types = array(
self::TYPE_ADD => true,
self::TYPE_COPY_HERE => true,
self::TYPE_MOVE_HERE => true,
);
return isset($types[$type]);
}
public static function isModifyChangeType($type) {
static $types = array(
self::TYPE_CHANGE => true,
);
return isset($types[$type]);
}
public static function getFullNameForChangeType($type) {
$types = array(
self::TYPE_ADD => pht('Added'),
self::TYPE_CHANGE => pht('Modified'),
self::TYPE_DELETE => pht('Deleted'),
self::TYPE_MOVE_AWAY => pht('Moved Away'),
self::TYPE_COPY_AWAY => pht('Copied Away'),
self::TYPE_MOVE_HERE => pht('Moved Here'),
self::TYPE_COPY_HERE => pht('Copied Here'),
self::TYPE_MULTICOPY => pht('Deleted After Multiple Copy'),
self::TYPE_MESSAGE => pht('Commit Message'),
self::TYPE_CHILD => pht('Contents Modified'),
);
return idx($types, coalesce($type, '?'), pht('Unknown'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/constants/DifferentialRevisionStatus.php | src/applications/differential/constants/DifferentialRevisionStatus.php | <?php
final class DifferentialRevisionStatus extends Phobject {
const NEEDS_REVIEW = 'needs-review';
const NEEDS_REVISION = 'needs-revision';
const CHANGES_PLANNED = 'changes-planned';
const ACCEPTED = 'accepted';
const PUBLISHED = 'published';
const ABANDONED = 'abandoned';
const DRAFT = 'draft';
private $key;
private $spec = array();
public function getKey() {
return $this->key;
}
public function getLegacyKey() {
return idx($this->spec, 'legacy');
}
public function getIcon() {
return idx($this->spec, 'icon');
}
public function getIconColor() {
return idx($this->spec, 'color.icon', 'bluegrey');
}
public function getTagColor() {
return idx($this->spec, 'color.tag', 'bluegrey');
}
public function getTimelineIcon() {
return idx($this->spec, 'icon.timeline');
}
public function getTimelineColor() {
return idx($this->spec, 'color.timeline');
}
public function getANSIColor() {
return idx($this->spec, 'color.ansi');
}
public function getDisplayName() {
return idx($this->spec, 'name');
}
public function isClosedStatus() {
return idx($this->spec, 'closed');
}
public function isAbandoned() {
return ($this->key === self::ABANDONED);
}
public function isAccepted() {
return ($this->key === self::ACCEPTED);
}
public function isNeedsReview() {
return ($this->key === self::NEEDS_REVIEW);
}
public function isNeedsRevision() {
return ($this->key === self::NEEDS_REVISION);
}
public function isPublished() {
return ($this->key === self::PUBLISHED);
}
public function isChangePlanned() {
return ($this->key === self::CHANGES_PLANNED);
}
public function isDraft() {
return ($this->key === self::DRAFT);
}
public static function newForStatus($status) {
$result = new self();
$map = self::getMap();
if (isset($map[$status])) {
$result->key = $status;
$result->spec = $map[$status];
}
return $result;
}
public static function getAll() {
$result = array();
foreach (self::getMap() as $key => $spec) {
$result[$key] = self::newForStatus($key);
}
return $result;
}
private static function getMap() {
$close_on_accept = PhabricatorEnv::getEnvConfig(
'differential.close-on-accept');
return array(
self::NEEDS_REVIEW => array(
'name' => pht('Needs Review'),
'legacy' => 0,
'icon' => 'fa-code',
'icon.timeline' => 'fa-undo',
'closed' => false,
'color.icon' => 'grey',
'color.tag' => 'bluegrey',
'color.ansi' => 'magenta',
'color.timeline' => 'orange',
),
self::NEEDS_REVISION => array(
'name' => pht('Needs Revision'),
'legacy' => 1,
'icon' => 'fa-refresh',
'icon.timeline' => 'fa-times',
'closed' => false,
'color.icon' => 'red',
'color.tag' => 'red',
'color.ansi' => 'red',
'color.timeline' => 'red',
),
self::CHANGES_PLANNED => array(
'name' => pht('Changes Planned'),
'legacy' => 5,
'icon' => 'fa-headphones',
'closed' => false,
'color.icon' => 'red',
'color.tag' => 'red',
'color.ansi' => 'red',
),
self::ACCEPTED => array(
'name' => pht('Accepted'),
'legacy' => 2,
'icon' => 'fa-check',
'icon.timeline' => 'fa-check',
'closed' => $close_on_accept,
'color.icon' => 'green',
'color.tag' => 'green',
'color.ansi' => 'green',
'color.timeline' => 'green',
),
self::PUBLISHED => array(
'name' => pht('Closed'),
'legacy' => 3,
'icon' => 'fa-check-square-o',
'closed' => true,
'color.icon' => 'black',
'color.tag' => 'indigo',
'color.ansi' => 'cyan',
),
self::ABANDONED => array(
'name' => pht('Abandoned'),
'legacy' => 4,
'icon' => 'fa-plane',
'closed' => true,
'color.icon' => 'black',
'color.tag' => 'indigo',
'color.ansi' => null,
),
self::DRAFT => array(
'name' => pht('Draft'),
// For legacy clients, treat this as though it is "Needs Review".
'legacy' => 0,
'icon' => 'fa-spinner',
'closed' => false,
'color.icon' => 'pink',
'color.tag' => 'pink',
'color.ansi' => null,
),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/constants/DifferentialRevisionControlSystem.php | src/applications/differential/constants/DifferentialRevisionControlSystem.php | <?php
// TODO: Unify with similar Repository constants
final class DifferentialRevisionControlSystem extends Phobject {
const SVN = 'svn';
const GIT = 'git';
const MERCURIAL = 'hg';
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/constants/DifferentialLegacyQuery.php | src/applications/differential/constants/DifferentialLegacyQuery.php | <?php
final class DifferentialLegacyQuery
extends Phobject {
const STATUS_ANY = 'status-any';
const STATUS_OPEN = 'status-open';
const STATUS_ACCEPTED = 'status-accepted';
const STATUS_NEEDS_REVIEW = 'status-needs-review';
const STATUS_NEEDS_REVISION = 'status-needs-revision';
const STATUS_CLOSED = 'status-closed';
const STATUS_ABANDONED = 'status-abandoned';
public static function getAllConstants() {
return array_keys(self::getMap());
}
public static function getModernValues($status) {
if ($status === self::STATUS_ANY) {
return null;
}
$map = self::getMap();
if (!isset($map[$status])) {
throw new Exception(
pht(
'Unknown revision status filter constant "%s".',
$status));
}
return $map[$status];
}
private static function getMap() {
$all = array_keys(DifferentialRevisionStatus::getAll());
$open = array();
$closed = array();
foreach ($all as $status) {
$status_object = DifferentialRevisionStatus::newForStatus($status);
if ($status_object->isClosedStatus()) {
$closed[] = $status_object->getKey();
} else {
$open[] = $status_object->getKey();
}
}
return array(
self::STATUS_ANY => $all,
self::STATUS_OPEN => $open,
self::STATUS_ACCEPTED => array(
DifferentialRevisionStatus::ACCEPTED,
),
self::STATUS_NEEDS_REVIEW => array(
DifferentialRevisionStatus::NEEDS_REVIEW,
// For legacy callers, "Draft" is treated as "Needs Review".
DifferentialRevisionStatus::DRAFT,
),
self::STATUS_NEEDS_REVISION => array(
DifferentialRevisionStatus::NEEDS_REVISION,
),
self::STATUS_CLOSED => $closed,
self::STATUS_ABANDONED => array(
DifferentialRevisionStatus::ABANDONED,
),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/constants/DifferentialAction.php | src/applications/differential/constants/DifferentialAction.php | <?php
final class DifferentialAction extends Phobject {
const ACTION_CLOSE = 'commit';
const ACTION_COMMENT = 'none';
const ACTION_ACCEPT = 'accept';
const ACTION_REJECT = 'reject';
const ACTION_RETHINK = 'rethink';
const ACTION_ABANDON = 'abandon';
const ACTION_REQUEST = 'request_review';
const ACTION_RECLAIM = 'reclaim';
const ACTION_UPDATE = 'update';
const ACTION_RESIGN = 'resign';
const ACTION_SUMMARIZE = 'summarize';
const ACTION_TESTPLAN = 'testplan';
const ACTION_CREATE = 'create';
const ACTION_ADDREVIEWERS = 'add_reviewers';
const ACTION_ADDCCS = 'add_ccs';
const ACTION_CLAIM = 'claim';
const ACTION_REOPEN = 'reopen';
public static function getBasicStoryText($action, $author_name) {
switch ($action) {
case self::ACTION_COMMENT:
$title = pht(
'%s commented on this revision.',
$author_name);
break;
case self::ACTION_ACCEPT:
$title = pht(
'%s accepted this revision.',
$author_name);
break;
case self::ACTION_REJECT:
$title = pht(
'%s requested changes to this revision.',
$author_name);
break;
case self::ACTION_RETHINK:
$title = pht(
'%s planned changes to this revision.',
$author_name);
break;
case self::ACTION_ABANDON:
$title = pht(
'%s abandoned this revision.',
$author_name);
break;
case self::ACTION_CLOSE:
$title = pht(
'%s closed this revision.',
$author_name);
break;
case self::ACTION_REQUEST:
$title = pht(
'%s requested a review of this revision.',
$author_name);
break;
case self::ACTION_RECLAIM:
$title = pht(
'%s reclaimed this revision.',
$author_name);
break;
case self::ACTION_UPDATE:
$title = pht(
'%s updated this revision.',
$author_name);
break;
case self::ACTION_RESIGN:
$title = pht(
'%s resigned from this revision.',
$author_name);
break;
case self::ACTION_SUMMARIZE:
$title = pht(
'%s summarized this revision.',
$author_name);
break;
case self::ACTION_TESTPLAN:
$title = pht(
'%s explained the test plan for this revision.',
$author_name);
break;
case self::ACTION_CREATE:
$title = pht(
'%s created this revision.',
$author_name);
break;
case self::ACTION_ADDREVIEWERS:
$title = pht(
'%s added reviewers to this revision.',
$author_name);
break;
case self::ACTION_ADDCCS:
$title = pht(
'%s added CCs to this revision.',
$author_name);
break;
case self::ACTION_CLAIM:
$title = pht(
'%s commandeered this revision.',
$author_name);
break;
case self::ACTION_REOPEN:
$title = pht(
'%s reopened this revision.',
$author_name);
break;
case DifferentialTransaction::TYPE_INLINE:
$title = pht(
'%s added an inline comment.',
$author_name);
break;
default:
$title = pht('Ghosts happened to this revision.');
break;
}
return $title;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/constants/DifferentialUnitStatus.php | src/applications/differential/constants/DifferentialUnitStatus.php | <?php
final class DifferentialUnitStatus extends Phobject {
const UNIT_NONE = 0;
const UNIT_OKAY = 1;
const UNIT_WARN = 2;
const UNIT_FAIL = 3;
const UNIT_SKIP = 4;
const UNIT_AUTO_SKIP = 6;
private $value;
public static function newStatusFromValue($value) {
$status = new self();
$status->value = $value;
return $status;
}
public function getValue() {
return $this->value;
}
public function getName() {
$name = $this->getUnitStatusProperty('name');
if ($name === null) {
$name = pht('Unknown Unit Status ("%s")', $this->getValue());
}
return $name;
}
public function getIconIcon() {
return $this->getUnitStatusProperty('icon.icon');
}
public function getIconColor() {
return $this->getUnitStatusProperty('icon.color');
}
public static function getStatusMap() {
$results = array();
foreach (self::newUnitStatusMap() as $value => $ignored) {
$results[$value] = self::newStatusFromValue($value);
}
return $results;
}
private function getUnitStatusProperty($key, $default = null) {
$map = self::newUnitStatusMap();
$properties = idx($map, $this->getValue(), array());
return idx($properties, $key, $default);
}
private static function newUnitStatusMap() {
return array(
self::UNIT_NONE => array(
'name' => pht('No Test Coverage'),
'icon.icon' => 'fa-ban',
'icon.color' => 'grey',
),
self::UNIT_OKAY => array(
'name' => pht('Tests Passed'),
'icon.icon' => 'fa-check',
'icon.color' => 'green',
),
self::UNIT_WARN => array(
'name' => pht('Test Warnings'),
'icon.icon' => 'fa-exclamation-triangle',
'icon.color' => 'yellow',
),
self::UNIT_FAIL => array(
'name' => pht('Test Failures'),
'icon.icon' => 'fa-times',
'icon.color' => 'red',
),
self::UNIT_SKIP => array(
'name' => pht('Tests Skipped'),
'icon.icon' => 'fa-fast-forward',
'icon.color' => 'blue',
),
self::UNIT_AUTO_SKIP => array(
'name' => pht('Tests Not Applicable'),
'icon.icon' => 'fa-code',
'icon.color' => 'grey',
),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/constants/DifferentialUnitTestResult.php | src/applications/differential/constants/DifferentialUnitTestResult.php | <?php
final class DifferentialUnitTestResult extends Phobject {
const RESULT_PASS = 'pass';
const RESULT_FAIL = 'fail';
const RESULT_SKIP = 'skip';
const RESULT_BROKEN = 'broken';
const RESULT_UNSOUND = 'unsound';
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/constants/DifferentialConstantsModule.php | src/applications/differential/constants/DifferentialConstantsModule.php | <?php
final class DifferentialConstantsModule
extends PhabricatorConfigModule {
public function getModuleKey() {
return 'constants.differential';
}
public function getModuleName() {
return pht('Constants: Differential');
}
public function renderModuleStatus(AphrontRequest $request) {
$viewer = $request->getViewer();
return array(
$this->renderRevisionStatuses($viewer),
$this->renderUnitStatuses($viewer),
$this->renderLintStatuses($viewer),
);
}
private function renderRevisionStatuses(PhabricatorUser $viewer) {
$statuses = DifferentialRevisionStatus::getAll();
$rows = array();
foreach ($statuses as $status) {
$icon = id(new PHUIIconView())
->setIcon(
$status->getIcon(),
$status->getIconColor());
$timeline_icon = $status->getTimelineIcon();
if ($timeline_icon !== null) {
$timeline_view = id(new PHUIIconView())
->setIcon(
$status->getTimelineIcon(),
$status->getTimelineColor());
} else {
$timeline_view = null;
}
if ($status->isClosedStatus()) {
$is_open = pht('Closed');
} else {
$is_open = pht('Open');
}
$tag_color = $status->getTagColor();
if ($tag_color !== null) {
$tag_view = id(new PHUIIconView())
->seticon('fa-tag', $tag_color);
} else {
$tag_view = null;
}
$ansi_color = $status->getAnsiColor();
if ($ansi_color !== null) {
$web_color = PHUIColor::getWebColorFromANSIColor($ansi_color);
$ansi_view = id(new PHUIIconView())
->setIcon('fa-stop', $web_color);
} else {
$ansi_view = null;
}
$rows[] = array(
$status->getKey(),
$status->getLegacyKey(),
$icon,
$timeline_view,
$tag_view,
$ansi_view,
$is_open,
$status->getDisplayName(),
);
}
$table = id(new AphrontTableView($rows))
->setHeaders(
array(
pht('Value'),
pht('Legacy Value'),
pht('Icon'),
pht('Timeline Icon'),
pht('Tag Color'),
pht('ANSI Color'),
pht('Open/Closed'),
pht('Name'),
))
->setColumnClasses(
array(
null,
null,
null,
null,
null,
null,
null,
'wide pri',
));
$view = id(new PHUIObjectBoxView())
->setHeaderText(pht('Differential Revision Statuses'))
->setTable($table);
return $view;
}
private function renderUnitStatuses(PhabricatorUser $viewer) {
$statuses = DifferentialUnitStatus::getStatusMap();
$rows = array();
foreach ($statuses as $status) {
$rows[] = array(
$status->getValue(),
id(new PHUIIconView())
->setIcon($status->getIconIcon(), $status->getIconColor()),
$status->getName(),
);
}
$table = id(new AphrontTableView($rows))
->setHeaders(
array(
pht('Value'),
pht('Icon'),
pht('Name'),
))
->setColumnClasses(
array(
null,
null,
'wide pri',
));
$view = id(new PHUIObjectBoxView())
->setHeaderText(pht('Differential Unit Statuses'))
->setTable($table);
return $view;
}
private function renderLintStatuses(PhabricatorUser $viewer) {
$statuses = DifferentialLintStatus::getStatusMap();
$rows = array();
foreach ($statuses as $status) {
$rows[] = array(
$status->getValue(),
id(new PHUIIconView())
->setIcon($status->getIconIcon(), $status->getIconColor()),
$status->getName(),
);
}
$table = id(new AphrontTableView($rows))
->setHeaders(
array(
pht('Value'),
pht('Icon'),
pht('Name'),
))
->setColumnClasses(
array(
null,
null,
'wide pri',
));
$view = id(new PHUIObjectBoxView())
->setHeaderText(pht('Differential Lint Statuses'))
->setTable($table);
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/differential/constants/DifferentialLintStatus.php | src/applications/differential/constants/DifferentialLintStatus.php | <?php
final class DifferentialLintStatus extends Phobject {
const LINT_NONE = 0;
const LINT_OKAY = 1;
const LINT_WARN = 2;
const LINT_FAIL = 3;
const LINT_SKIP = 4;
const LINT_AUTO_SKIP = 6;
private $value;
public static function newStatusFromValue($value) {
$status = new self();
$status->value = $value;
return $status;
}
public function getValue() {
return $this->value;
}
public function getName() {
$name = $this->getLintStatusProperty('name');
if ($name === null) {
$name = pht('Unknown Lint Status ("%s")', $this->getValue());
}
return $name;
}
public function getIconIcon() {
return $this->getLintStatusProperty('icon.icon');
}
public function getIconColor() {
return $this->getLintStatusProperty('icon.color');
}
public static function getStatusMap() {
$results = array();
foreach (self::newLintStatusMap() as $value => $ignored) {
$results[$value] = self::newStatusFromValue($value);
}
return $results;
}
private function getLintStatusProperty($key, $default = null) {
$map = self::newLintStatusMap();
$properties = idx($map, $this->getValue(), array());
return idx($properties, $key, $default);
}
private static function newLintStatusMap() {
return array(
self::LINT_NONE => array(
'name' => pht('No Lint Coverage'),
'icon.icon' => 'fa-ban',
'icon.color' => 'grey',
),
self::LINT_OKAY => array(
'name' => pht('Lint Passed'),
'icon.icon' => 'fa-check',
'icon.color' => 'green',
),
self::LINT_WARN => array(
'name' => pht('Lint Warnings'),
'icon.icon' => 'fa-exclamation-triangle',
'icon.color' => 'yellow',
),
self::LINT_FAIL => array(
'name' => pht('Lint Errors'),
'icon.icon' => 'fa-times',
'icon.color' => 'red',
),
self::LINT_SKIP => array(
'name' => pht('Lint Skipped'),
'icon.icon' => 'fa-fast-forward',
'icon.color' => 'blue',
),
self::LINT_AUTO_SKIP => array(
'name' => pht('Lint Not Applicable'),
'icon.icon' => 'fa-code',
'icon.color' => 'grey',
),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/parser/DifferentialCustomFieldRevertsParser.php | src/applications/differential/parser/DifferentialCustomFieldRevertsParser.php | <?php
final class DifferentialCustomFieldRevertsParser
extends PhabricatorCustomFieldMonogramParser {
protected function getPrefixes() {
// NOTE: Git language is "This reverts commit X."
// NOTE: Mercurial language is "Backed out changeset Y".
return array(
'revert',
'reverts',
'reverted',
'backout',
'backsout',
'backedout',
'back out',
'backs out',
'backed out',
'undo',
'undoes',
);
}
protected function getInfixes() {
return array(
'commit',
'commits',
'change',
'changes',
'changeset',
'changesets',
'rev',
'revs',
'revision',
'revisions',
'diff',
'diffs',
);
}
protected function getSuffixes() {
return array();
}
protected function getMonogramPattern() {
return '[rA-Z0-9a-f]+';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/parser/DifferentialCommitMessageParser.php | src/applications/differential/parser/DifferentialCommitMessageParser.php | <?php
/**
* Parses commit messages (containing relatively freeform text with textual
* field labels) into a dictionary of fields.
*
* $parser = id(new DifferentialCommitMessageParser())
* ->setLabelMap($label_map)
* ->setTitleKey($key_title)
* ->setSummaryKey($key_summary);
*
* $fields = $parser->parseCorpus($corpus);
* $errors = $parser->getErrors();
*
* This is used by Differential to parse messages entered from the command line.
*
* @task config Configuring the Parser
* @task parse Parsing Messages
* @task support Support Methods
* @task internal Internals
*/
final class DifferentialCommitMessageParser extends Phobject {
private $viewer;
private $labelMap;
private $titleKey;
private $summaryKey;
private $errors;
private $commitMessageFields;
private $raiseMissingFieldErrors = true;
private $xactions;
public static function newStandardParser(PhabricatorUser $viewer) {
$key_title = DifferentialTitleCommitMessageField::FIELDKEY;
$key_summary = DifferentialSummaryCommitMessageField::FIELDKEY;
$field_list = DifferentialCommitMessageField::newEnabledFields($viewer);
return id(new self())
->setViewer($viewer)
->setCommitMessageFields($field_list)
->setTitleKey($key_title)
->setSummaryKey($key_summary);
}
/* -( Configuring the Parser )--------------------------------------------- */
/**
* @task config
*/
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
/**
* @task config
*/
public function getViewer() {
return $this->viewer;
}
/**
* @task config
*/
public function setCommitMessageFields(array $fields) {
assert_instances_of($fields, 'DifferentialCommitMessageField');
$fields = mpull($fields, null, 'getCommitMessageFieldKey');
$this->commitMessageFields = $fields;
return $this;
}
/**
* @task config
*/
public function getCommitMessageFields() {
return $this->commitMessageFields;
}
/**
* @task config
*/
public function setRaiseMissingFieldErrors($raise) {
$this->raiseMissingFieldErrors = $raise;
return $this;
}
/**
* @task config
*/
public function getRaiseMissingFieldErrors() {
return $this->raiseMissingFieldErrors;
}
/**
* @task config
*/
public function setLabelMap(array $label_map) {
$this->labelMap = $label_map;
return $this;
}
/**
* @task config
*/
public function setTitleKey($title_key) {
$this->titleKey = $title_key;
return $this;
}
/**
* @task config
*/
public function setSummaryKey($summary_key) {
$this->summaryKey = $summary_key;
return $this;
}
/* -( Parsing Messages )--------------------------------------------------- */
/**
* @task parse
*/
public function parseCorpus($corpus) {
$this->errors = array();
$this->xactions = array();
$label_map = $this->getLabelMap();
$key_title = $this->titleKey;
$key_summary = $this->summaryKey;
if (!$key_title || !$key_summary || ($label_map === null)) {
throw new Exception(
pht(
'Expected %s, %s and %s to be set before parsing a corpus.',
'labelMap',
'summaryKey',
'titleKey'));
}
$label_regexp = $this->buildLabelRegexp($label_map);
// NOTE: We're special casing things here to make the "Title:" label
// optional in the message.
$field = $key_title;
$seen = array();
$lines = trim($corpus);
$lines = phutil_split_lines($lines, false);
$field_map = array();
foreach ($lines as $key => $line) {
// We always parse the first line of the message as a title, even if it
// contains something we recognize as a field header.
if (!isset($seen[$key_title])) {
$field = $key_title;
$lines[$key] = trim($line);
$seen[$field] = true;
} else {
$match = null;
if (preg_match($label_regexp, $line, $match)) {
$lines[$key] = trim($match['text']);
$field = $label_map[self::normalizeFieldLabel($match['field'])];
if (!empty($seen[$field])) {
$this->errors[] = pht(
'Field "%s" occurs twice in commit message!',
$match['field']);
}
$seen[$field] = true;
}
}
$field_map[$key] = $field;
}
$fields = array();
foreach ($lines as $key => $line) {
$fields[$field_map[$key]][] = $line;
}
// This is a piece of special-cased magic which allows you to omit the
// field labels for "title" and "summary". If the user enters a large block
// of text at the beginning of the commit message with an empty line in it,
// treat everything before the blank line as "title" and everything after
// as "summary".
if (isset($fields[$key_title]) && empty($fields[$key_summary])) {
$lines = $fields[$key_title];
for ($ii = 0; $ii < count($lines); $ii++) {
if (strlen(trim($lines[$ii])) == 0) {
break;
}
}
if ($ii != count($lines)) {
$fields[$key_title] = array_slice($lines, 0, $ii);
$summary = array_slice($lines, $ii);
if (strlen(trim(implode("\n", $summary)))) {
$fields[$key_summary] = $summary;
}
}
}
// Implode all the lines back into chunks of text.
foreach ($fields as $name => $lines) {
$data = rtrim(implode("\n", $lines));
$data = ltrim($data, "\n");
$fields[$name] = $data;
}
// This is another piece of special-cased magic which allows you to
// enter a ridiculously long title, or just type a big block of stream
// of consciousness text, and have some sort of reasonable result conjured
// from it.
if (isset($fields[$key_title])) {
$terminal = '...';
$title = $fields[$key_title];
$short = id(new PhutilUTF8StringTruncator())
->setMaximumBytes(250)
->setTerminator($terminal)
->truncateString($title);
if ($short != $title) {
// If we shortened the title, split the rest into the summary, so
// we end up with a title like:
//
// Title title tile title title...
//
// ...and a summary like:
//
// ...title title title.
//
// Summary summary summary summary.
$summary = idx($fields, $key_summary, '');
$offset = strlen($short) - strlen($terminal);
$remainder = ltrim(substr($fields[$key_title], $offset));
$summary = '...'.$remainder."\n\n".$summary;
$summary = rtrim($summary, "\n");
$fields[$key_title] = $short;
$fields[$key_summary] = $summary;
}
}
return $fields;
}
/**
* @task parse
*/
public function parseFields($corpus) {
$viewer = $this->getViewer();
$text_map = $this->parseCorpus($corpus);
$field_map = $this->getCommitMessageFields();
$result_map = array();
foreach ($text_map as $field_key => $text_value) {
$field = idx($field_map, $field_key);
if (!$field) {
// This is a strict error, since we only parse fields which we have
// been told are valid. The caller probably handed us an invalid label
// map.
throw new Exception(
pht(
'Parser emitted a field with key "%s", but no corresponding '.
'field definition exists.',
$field_key));
}
try {
$result = $field->parseFieldValue($text_value);
$result_map[$field_key] = $result;
try {
$xactions = $field->getFieldTransactions($result);
foreach ($xactions as $xaction) {
$this->xactions[] = $xaction;
}
} catch (Exception $ex) {
$this->errors[] = pht(
'Error extracting field transactions from "%s": %s',
$field->getFieldName(),
$ex->getMessage());
}
} catch (DifferentialFieldParseException $ex) {
$this->errors[] = pht(
'Error parsing field "%s": %s',
$field->getFieldName(),
$ex->getMessage());
}
}
if ($this->getRaiseMissingFieldErrors()) {
foreach ($field_map as $key => $field) {
try {
$field->validateFieldValue(idx($result_map, $key));
} catch (DifferentialFieldValidationException $ex) {
$this->errors[] = pht(
'Invalid or missing field "%s": %s',
$field->getFieldName(),
$ex->getMessage());
}
}
}
return $result_map;
}
/**
* @task parse
*/
public function getErrors() {
return $this->errors;
}
/**
* @task parse
*/
public function getTransactions() {
return $this->xactions;
}
/* -( Support Methods )---------------------------------------------------- */
/**
* @task support
*/
public static function normalizeFieldLabel($label) {
return phutil_utf8_strtolower($label);
}
/* -( Internals )---------------------------------------------------------- */
private function getLabelMap() {
if ($this->labelMap === null) {
$field_list = $this->getCommitMessageFields();
$label_map = array();
foreach ($field_list as $field_key => $field) {
$labels = $field->getFieldAliases();
$labels[] = $field->getFieldName();
foreach ($labels as $label) {
$normal_label = self::normalizeFieldLabel($label);
if (!empty($label_map[$normal_label])) {
throw new Exception(
pht(
'Field label "%s" is parsed by two custom fields: "%s" and '.
'"%s". Each label must be parsed by only one field.',
$label,
$field_key,
$label_map[$normal_label]));
}
$label_map[$normal_label] = $field_key;
}
}
$this->labelMap = $label_map;
}
return $this->labelMap;
}
/**
* @task internal
*/
private function buildLabelRegexp(array $label_map) {
$field_labels = array_keys($label_map);
foreach ($field_labels as $key => $label) {
$field_labels[$key] = preg_quote($label, '/');
}
$field_labels = implode('|', $field_labels);
$field_pattern = '/^(?P<field>'.$field_labels.'):(?P<text>.*)$/i';
return $field_pattern;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/parser/DifferentialHunkParser.php | src/applications/differential/parser/DifferentialHunkParser.php | <?php
final class DifferentialHunkParser extends Phobject {
private $oldLines;
private $newLines;
private $intraLineDiffs;
private $depthOnlyLines;
private $visibleLinesMask;
private $normalized;
/**
* Get a map of lines on which hunks start, other than line 1. This
* datastructure is used to determine when to render "Context not available."
* in diffs with multiple hunks.
*
* @return dict<int, bool> Map of lines where hunks start, other than line 1.
*/
public function getHunkStartLines(array $hunks) {
assert_instances_of($hunks, 'DifferentialHunk');
$map = array();
foreach ($hunks as $hunk) {
$line = $hunk->getOldOffset();
if ($line > 1) {
$map[$line] = true;
}
}
return $map;
}
private function setVisibleLinesMask($mask) {
$this->visibleLinesMask = $mask;
return $this;
}
public function getVisibleLinesMask() {
if ($this->visibleLinesMask === null) {
throw new PhutilInvalidStateException('generateVisibleLinesMask');
}
return $this->visibleLinesMask;
}
private function setIntraLineDiffs($intra_line_diffs) {
$this->intraLineDiffs = $intra_line_diffs;
return $this;
}
public function getIntraLineDiffs() {
if ($this->intraLineDiffs === null) {
throw new PhutilInvalidStateException('generateIntraLineDiffs');
}
return $this->intraLineDiffs;
}
private function setNewLines($new_lines) {
$this->newLines = $new_lines;
return $this;
}
public function getNewLines() {
if ($this->newLines === null) {
throw new PhutilInvalidStateException('parseHunksForLineData');
}
return $this->newLines;
}
private function setOldLines($old_lines) {
$this->oldLines = $old_lines;
return $this;
}
public function getOldLines() {
if ($this->oldLines === null) {
throw new PhutilInvalidStateException('parseHunksForLineData');
}
return $this->oldLines;
}
public function getOldLineTypeMap() {
$map = array();
$old = $this->getOldLines();
foreach ($old as $o) {
if (!$o) {
continue;
}
$map[$o['line']] = $o['type'];
}
return $map;
}
public function setOldLineTypeMap(array $map) {
$lines = $this->getOldLines();
foreach ($lines as $key => $data) {
$lines[$key]['type'] = idx($map, $data['line']);
}
$this->oldLines = $lines;
return $this;
}
public function getNewLineTypeMap() {
$map = array();
$new = $this->getNewLines();
foreach ($new as $n) {
if (!$n) {
continue;
}
$map[$n['line']] = $n['type'];
}
return $map;
}
public function setNewLineTypeMap(array $map) {
$lines = $this->getNewLines();
foreach ($lines as $key => $data) {
$lines[$key]['type'] = idx($map, $data['line']);
}
$this->newLines = $lines;
return $this;
}
public function setDepthOnlyLines(array $map) {
$this->depthOnlyLines = $map;
return $this;
}
public function getDepthOnlyLines() {
return $this->depthOnlyLines;
}
public function setNormalized($normalized) {
$this->normalized = $normalized;
return $this;
}
public function getNormalized() {
return $this->normalized;
}
public function getIsDeleted() {
foreach ($this->getNewLines() as $line) {
if ($line) {
// At least one new line, so the entire file wasn't deleted.
return false;
}
}
foreach ($this->getOldLines() as $line) {
if ($line) {
// No new lines, at least one old line; the entire file was deleted.
return true;
}
}
// This is an empty file.
return false;
}
/**
* Returns true if the hunks change anything, including whitespace.
*/
public function getHasAnyChanges() {
return $this->getHasChanges('any');
}
private function getHasChanges($filter) {
if ($filter !== 'any' && $filter !== 'text') {
throw new Exception(pht("Unknown change filter '%s'.", $filter));
}
$old = $this->getOldLines();
$new = $this->getNewLines();
$is_any = ($filter === 'any');
foreach ($old as $key => $o) {
$n = $new[$key];
if ($o === null || $n === null) {
// One side is missing, and it's impossible for both sides to be null,
// so the other side must have something, and thus the two sides are
// different and the file has been changed under any type of filter.
return true;
}
if ($o['type'] !== $n['type']) {
return true;
}
if ($o['text'] !== $n['text']) {
if ($is_any) {
// The text is different, so there's a change.
return true;
} else if (trim($o['text']) !== trim($n['text'])) {
return true;
}
}
}
// No changes anywhere in the file.
return false;
}
/**
* This function takes advantage of the parsing work done in
* @{method:parseHunksForLineData} and continues the struggle to hammer this
* data into something we can display to a user.
*
* In particular, this function re-parses the hunks to make them equivalent
* in length for easy rendering, adding `null` as necessary to pad the
* length.
*
* Anyhoo, this function is not particularly well-named but I try.
*
* NOTE: this function must be called after
* @{method:parseHunksForLineData}.
*/
public function reparseHunksForSpecialAttributes() {
$rebuild_old = array();
$rebuild_new = array();
$old_lines = array_reverse($this->getOldLines());
$new_lines = array_reverse($this->getNewLines());
while (count($old_lines) || count($new_lines)) {
$old_line_data = array_pop($old_lines);
$new_line_data = array_pop($new_lines);
if ($old_line_data) {
$o_type = $old_line_data['type'];
} else {
$o_type = null;
}
if ($new_line_data) {
$n_type = $new_line_data['type'];
} else {
$n_type = null;
}
// This line does not exist in the new file.
if (($o_type != null) && ($n_type == null)) {
$rebuild_old[] = $old_line_data;
$rebuild_new[] = null;
if ($new_line_data) {
array_push($new_lines, $new_line_data);
}
continue;
}
// This line does not exist in the old file.
if (($n_type != null) && ($o_type == null)) {
$rebuild_old[] = null;
$rebuild_new[] = $new_line_data;
if ($old_line_data) {
array_push($old_lines, $old_line_data);
}
continue;
}
$rebuild_old[] = $old_line_data;
$rebuild_new[] = $new_line_data;
}
$this->setOldLines($rebuild_old);
$this->setNewLines($rebuild_new);
$this->updateChangeTypesForNormalization();
return $this;
}
public function generateIntraLineDiffs() {
$old = $this->getOldLines();
$new = $this->getNewLines();
$diffs = array();
$depth_only = array();
foreach ($old as $key => $o) {
$n = $new[$key];
if (!$o || !$n) {
continue;
}
if ($o['type'] != $n['type']) {
$o_segments = array();
$n_segments = array();
$tab_width = 2;
$o_text = $o['text'];
$n_text = $n['text'];
if ($o_text !== $n_text && (ltrim($o_text) === ltrim($n_text))) {
$o_depth = $this->getIndentDepth($o_text, $tab_width);
$n_depth = $this->getIndentDepth($n_text, $tab_width);
if ($o_depth < $n_depth) {
$segment_type = '>';
$segment_width = $this->getCharacterCountForVisualWhitespace(
$n_text,
($n_depth - $o_depth),
$tab_width);
if ($segment_width) {
$n_text = substr($n_text, $segment_width);
$n_segments[] = array(
$segment_type,
$segment_width,
);
}
} else if ($o_depth > $n_depth) {
$segment_type = '<';
$segment_width = $this->getCharacterCountForVisualWhitespace(
$o_text,
($o_depth - $n_depth),
$tab_width);
if ($segment_width) {
$o_text = substr($o_text, $segment_width);
$o_segments[] = array(
$segment_type,
$segment_width,
);
}
}
// If there are no remaining changes to this line after we've marked
// off the indent depth changes, this line was only modified by
// changing the indent depth. Mark it for later so we can change how
// it is displayed.
if ($o_text === $n_text) {
$depth_only[$key] = $segment_type;
}
}
$intraline_segments = ArcanistDiffUtils::generateIntralineDiff(
$o_text,
$n_text);
foreach ($intraline_segments[0] as $o_segment) {
$o_segments[] = $o_segment;
}
foreach ($intraline_segments[1] as $n_segment) {
$n_segments[] = $n_segment;
}
$diffs[$key] = array(
$o_segments,
$n_segments,
);
}
}
$this->setIntraLineDiffs($diffs);
$this->setDepthOnlyLines($depth_only);
return $this;
}
public function generateVisibleBlocksMask($lines_context) {
// See T13468. This is similar to "generateVisibleLinesMask()", but
// attempts to work around a series of bugs which cancel each other
// out but make a mess of the intermediate steps.
$old = $this->getOldLines();
$new = $this->getNewLines();
$length = max(count($old), count($new));
$visible_lines = array();
for ($ii = 0; $ii < $length; $ii++) {
$old_visible = (isset($old[$ii]) && $old[$ii]['type']);
$new_visible = (isset($new[$ii]) && $new[$ii]['type']);
$visible_lines[$ii] = ($old_visible || $new_visible);
}
$mask = array();
$reveal_cursor = -1;
for ($ii = 0; $ii < $length; $ii++) {
// If this line isn't visible, it isn't going to reveal anything.
if (!$visible_lines[$ii]) {
// If it hasn't been revealed by a nearby line, mark it as masked.
if (empty($mask[$ii])) {
$mask[$ii] = false;
}
continue;
}
// If this line is visible, reveal all the lines nearby.
// First, compute the minimum and maximum offsets we want to reveal.
$min_reveal = max($ii - $lines_context, 0);
$max_reveal = min($ii + $lines_context, $length - 1);
// Naively, we'd do more work than necessary when revealing context for
// several adjacent visible lines: we would mark all the overlapping
// lines as revealed several times.
// To avoid duplicating work, keep track of the largest line we've
// revealed to. Since we reveal context by marking every consecutive
// line, we don't need to touch any line above it.
$min_reveal = max($min_reveal, $reveal_cursor);
// Reveal the remaining unrevealed lines.
for ($jj = $min_reveal; $jj <= $max_reveal; $jj++) {
$mask[$jj] = true;
}
// Move the cursor to the next line which may still need to be revealed.
$reveal_cursor = $max_reveal + 1;
}
$this->setVisibleLinesMask($mask);
return $mask;
}
public function generateVisibleLinesMask($lines_context) {
$old = $this->getOldLines();
$new = $this->getNewLines();
$max_length = max(count($old), count($new));
$visible = false;
$last = 0;
$mask = array();
for ($cursor = -$lines_context; $cursor < $max_length; $cursor++) {
$offset = $cursor + $lines_context;
if ((isset($old[$offset]) && $old[$offset]['type']) ||
(isset($new[$offset]) && $new[$offset]['type'])) {
$visible = true;
$last = $offset;
} else if ($cursor > $last + $lines_context) {
$visible = false;
}
if ($visible && $cursor > 0) {
$mask[$cursor] = 1;
}
}
$this->setVisibleLinesMask($mask);
return $this;
}
public function getOldCorpus() {
return $this->getCorpus($this->getOldLines());
}
public function getNewCorpus() {
return $this->getCorpus($this->getNewLines());
}
private function getCorpus(array $lines) {
$corpus = array();
foreach ($lines as $l) {
if ($l === null) {
$corpus[] = "\n";
continue;
}
if ($l['type'] != '\\') {
if ($l['text'] === null) {
// There's no text on this side of the diff, but insert a placeholder
// newline so the highlighted line numbers match up.
$corpus[] = "\n";
} else {
$corpus[] = $l['text'];
}
}
}
return $corpus;
}
public function parseHunksForLineData(array $hunks) {
assert_instances_of($hunks, 'DifferentialHunk');
$old_lines = array();
$new_lines = array();
foreach ($hunks as $hunk) {
$lines = $hunk->getSplitLines();
$line_type_map = array();
$line_text = array();
foreach ($lines as $line_index => $line) {
if (isset($line[0])) {
$char = $line[0];
switch ($char) {
case ' ':
$line_type_map[$line_index] = null;
$line_text[$line_index] = substr($line, 1);
break;
case "\r":
case "\n":
// NOTE: Normally, the first character is a space, plus, minus or
// backslash, but it may be a newline if it used to be a space and
// trailing whitespace has been stripped via email transmission or
// some similar mechanism. In these cases, we essentially pretend
// the missing space is still there.
$line_type_map[$line_index] = null;
$line_text[$line_index] = $line;
break;
case '+':
case '-':
case '\\':
$line_type_map[$line_index] = $char;
$line_text[$line_index] = substr($line, 1);
break;
default:
throw new Exception(
pht(
'Unexpected leading character "%s" at line index %s!',
$char,
$line_index));
}
} else {
$line_type_map[$line_index] = null;
$line_text[$line_index] = '';
}
}
$old_line = $hunk->getOldOffset();
$new_line = $hunk->getNewOffset();
$num_lines = count($lines);
for ($cursor = 0; $cursor < $num_lines; $cursor++) {
$type = $line_type_map[$cursor];
$data = array(
'type' => $type,
'text' => $line_text[$cursor],
'line' => $new_line,
);
if ($type == '\\') {
$type = $line_type_map[$cursor - 1];
$data['text'] = ltrim($data['text']);
}
switch ($type) {
case '+':
$new_lines[] = $data;
++$new_line;
break;
case '-':
$data['line'] = $old_line;
$old_lines[] = $data;
++$old_line;
break;
default:
$new_lines[] = $data;
$data['line'] = $old_line;
$old_lines[] = $data;
++$new_line;
++$old_line;
break;
}
}
}
$this->setOldLines($old_lines);
$this->setNewLines($new_lines);
return $this;
}
public function parseHunksForHighlightMasks(
array $changeset_hunks,
array $old_hunks,
array $new_hunks) {
assert_instances_of($changeset_hunks, 'DifferentialHunk');
assert_instances_of($old_hunks, 'DifferentialHunk');
assert_instances_of($new_hunks, 'DifferentialHunk');
// Put changes side by side.
$olds = array();
$news = array();
$olds_cursor = -1;
$news_cursor = -1;
foreach ($changeset_hunks as $hunk) {
$n_old = $hunk->getOldOffset();
$n_new = $hunk->getNewOffset();
$changes = $hunk->getSplitLines();
foreach ($changes as $line) {
$diff_type = $line[0]; // Change type in diff of diffs.
$is_same = ($diff_type === ' ');
$is_add = ($diff_type === '+');
$is_rem = ($diff_type === '-');
$orig_type = $line[1]; // Change type in the original diff.
if ($is_same) {
// Use the same key for lines that are next to each other.
if ($olds_cursor > $news_cursor) {
$key = $olds_cursor + 1;
} else {
$key = $news_cursor + 1;
}
$olds[$key] = null;
$news[$key] = null;
$olds_cursor = $key;
$news_cursor = $key;
} else if ($is_rem) {
$olds[] = array($n_old, $orig_type);
$olds_cursor++;
} else if ($is_add) {
$news[] = array($n_new, $orig_type);
$news_cursor++;
} else {
throw new Exception(
pht(
'Found unknown intradiff source line, expected a line '.
'beginning with "+", "-", or " " (space): %s.',
$line));
}
// See T13539. Don't increment the line count if this line was removed,
// or if the line is a "No newline at end of file" marker.
$not_a_line = ($orig_type === '-' || $orig_type === '\\');
if ($not_a_line) {
continue;
}
if ($is_same || $is_rem) {
$n_old++;
}
if ($is_same || $is_add) {
$n_new++;
}
}
}
$offsets_old = $this->computeOffsets($old_hunks);
$offsets_new = $this->computeOffsets($new_hunks);
// Highlight lines that were added on each side or removed on the other
// side.
$highlight_old = array();
$highlight_new = array();
$last = max(last_key($olds), last_key($news));
for ($i = 0; $i <= $last; $i++) {
if (isset($olds[$i])) {
list($n, $type) = $olds[$i];
if ($type == '+' ||
($type == ' ' && isset($news[$i]) && $news[$i][1] != ' ')) {
if (isset($offsets_old[$n])) {
$highlight_old[] = $offsets_old[$n];
}
}
}
if (isset($news[$i])) {
list($n, $type) = $news[$i];
if ($type == '+' ||
($type == ' ' && isset($olds[$i]) && $olds[$i][1] != ' ')) {
if (isset($offsets_new[$n])) {
$highlight_new[] = $offsets_new[$n];
}
}
}
}
return array($highlight_old, $highlight_new);
}
public function makeContextDiff(
array $hunks,
$is_new,
$line_number,
$line_length,
$add_context) {
assert_instances_of($hunks, 'DifferentialHunk');
$context = array();
if ($is_new) {
$prefix = '+';
} else {
$prefix = '-';
}
foreach ($hunks as $hunk) {
if ($is_new) {
$offset = $hunk->getNewOffset();
$length = $hunk->getNewLen();
} else {
$offset = $hunk->getOldOffset();
$length = $hunk->getOldLen();
}
$start = $line_number - $offset;
$end = $start + $line_length;
// We need to go in if $start == $length, because the last line
// might be a "\No newline at end of file" marker, which we want
// to show if the additional context is > 0.
if ($start <= $length && $end >= 0) {
$start = $start - $add_context;
$end = $end + $add_context;
$hunk_content = array();
$hunk_pos = array('-' => 0, '+' => 0);
$hunk_offset = array('-' => null, '+' => null);
$hunk_last = array('-' => null, '+' => null);
foreach (explode("\n", $hunk->getChanges()) as $line) {
$in_common = strncmp($line, ' ', 1) === 0;
$in_old = strncmp($line, '-', 1) === 0 || $in_common;
$in_new = strncmp($line, '+', 1) === 0 || $in_common;
$in_selected = strncmp($line, $prefix, 1) === 0;
$skip = !$in_selected && !$in_common;
if ($hunk_pos[$prefix] <= $end) {
if ($start <= $hunk_pos[$prefix]) {
if (!$skip || ($hunk_pos[$prefix] != $start &&
$hunk_pos[$prefix] != $end)) {
if ($in_old) {
if ($hunk_offset['-'] === null) {
$hunk_offset['-'] = $hunk_pos['-'];
}
$hunk_last['-'] = $hunk_pos['-'];
}
if ($in_new) {
if ($hunk_offset['+'] === null) {
$hunk_offset['+'] = $hunk_pos['+'];
}
$hunk_last['+'] = $hunk_pos['+'];
}
$hunk_content[] = $line;
}
}
if ($in_old) { ++$hunk_pos['-']; }
if ($in_new) { ++$hunk_pos['+']; }
}
}
if ($hunk_offset['-'] !== null || $hunk_offset['+'] !== null) {
$header = '@@';
if ($hunk_offset['-'] !== null) {
$header .= ' -'.($hunk->getOldOffset() + $hunk_offset['-']).
','.($hunk_last['-'] - $hunk_offset['-'] + 1);
}
if ($hunk_offset['+'] !== null) {
$header .= ' +'.($hunk->getNewOffset() + $hunk_offset['+']).
','.($hunk_last['+'] - $hunk_offset['+'] + 1);
}
$header .= ' @@';
$context[] = $header;
$context[] = implode("\n", $hunk_content);
}
}
}
return implode("\n", $context);
}
private function computeOffsets(array $hunks) {
assert_instances_of($hunks, 'DifferentialHunk');
$offsets = array();
$n = 1;
foreach ($hunks as $hunk) {
$new_length = $hunk->getNewLen();
$new_offset = $hunk->getNewOffset();
for ($i = 0; $i < $new_length; $i++) {
$offsets[$n] = $new_offset + $i;
$n++;
}
}
return $offsets;
}
private function getIndentDepth($text, $tab_width) {
$len = strlen($text);
$depth = 0;
for ($ii = 0; $ii < $len; $ii++) {
$c = $text[$ii];
// If this is a space, increase the indent depth by 1.
if ($c == ' ') {
$depth++;
continue;
}
// If this is a tab, increase the indent depth to the next tabstop.
// For example, if the tab width is 4, these sequences both lead us to
// a visual width of 8, i.e. the cursor will be in the 8th column:
//
// <tab><tab>
// <space><tab><space><space><space><tab>
if ($c == "\t") {
$depth = ($depth + $tab_width);
$depth = $depth - ($depth % $tab_width);
continue;
}
break;
}
return $depth;
}
private function getCharacterCountForVisualWhitespace(
$text,
$depth,
$tab_width) {
// Here, we know the visual indent depth of a line has been increased by
// some amount (for example, 6 characters).
// We want to find the largest whitespace prefix of the string we can
// which still fits into that amount of visual space.
// In most cases, this is very easy. For example, if the string has been
// indented by two characters and the string begins with two spaces, that's
// a perfect match.
// However, if the string has been indented by 7 characters, the tab width
// is 8, and the string begins with "<space><space><tab>", we can only
// mark the two spaces as an indent change. These cases are unusual.
$character_depth = 0;
$visual_depth = 0;
$len = strlen($text);
for ($ii = 0; $ii < $len; $ii++) {
if ($visual_depth >= $depth) {
break;
}
$c = $text[$ii];
if ($c == ' ') {
$character_depth++;
$visual_depth++;
continue;
}
if ($c == "\t") {
// Figure out how many visual spaces we have until the next tabstop.
$tab_visual = ($visual_depth + $tab_width);
$tab_visual = $tab_visual - ($tab_visual % $tab_width);
$tab_visual = ($tab_visual - $visual_depth);
// If this tab would take us over the limit, we're all done.
$remaining_depth = ($depth - $visual_depth);
if ($remaining_depth < $tab_visual) {
break;
}
$character_depth++;
$visual_depth += $tab_visual;
continue;
}
break;
}
return $character_depth;
}
private function updateChangeTypesForNormalization() {
if (!$this->getNormalized()) {
return;
}
// If we've parsed based on a normalized diff alignment, we may currently
// believe some lines are unchanged when they have actually changed. This
// happens when:
//
// - a line changes;
// - the change is a kind of change we normalize away when aligning the
// diff, like an indentation change;
// - we normalize the change away to align the diff; and so
// - the old and new copies of the line are now aligned in the new
// normalized diff.
//
// Then we end up with an alignment where the two lines that differ only
// in some some trivial way are aligned. This is great, and exactly what
// we're trying to accomplish by doing all this alignment stuff in the
// first place.
//
// However, in this case the correctly-aligned lines will be incorrectly
// marked as unchanged because the diff alorithm was fed normalized copies
// of the lines, and these copies truly weren't any different.
//
// When lines are aligned and marked identical, but they're not actually
// identical, we now mark them as changed. The rest of the processing will
// figure out how to render them appropritely.
$new = $this->getNewLines();
$old = $this->getOldLines();
foreach ($old as $key => $o) {
$n = $new[$key];
if (!$o || !$n) {
continue;
}
if ($o['type'] === null && $n['type'] === null) {
if ($o['text'] !== $n['text']) {
$old[$key]['type'] = '-';
$new[$key]['type'] = '+';
}
}
}
$this->setOldLines($old);
$this->setNewLines($new);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/parser/DifferentialCustomFieldDependsOnParser.php | src/applications/differential/parser/DifferentialCustomFieldDependsOnParser.php | <?php
final class DifferentialCustomFieldDependsOnParser
extends PhabricatorCustomFieldMonogramParser {
protected function getPrefixes() {
return array(
'depends on',
);
}
protected function getInfixes() {
return array(
'diff',
'diffs',
'change',
'changes',
'rev',
'revs',
'revision',
);
}
protected function getSuffixes() {
return array();
}
protected function getMonogramPattern() {
return '[Dd]\d+';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/parser/DifferentialLineAdjustmentMap.php | src/applications/differential/parser/DifferentialLineAdjustmentMap.php | <?php
/**
* Datastructure which follows lines of code across source changes.
*
* This map is used to update the positions of inline comments after diff
* updates. For example, if a inline comment appeared on line 30 of a diff
* but the next update adds 15 more lines above it, the comment should move
* down to line 45.
*
*/
final class DifferentialLineAdjustmentMap extends Phobject {
private $map;
private $nearestMap;
private $isInverse;
private $finalOffset;
private $nextMapInChain;
/**
* Get the raw adjustment map.
*/
public function getMap() {
return $this->map;
}
public function getNearestMap() {
if ($this->nearestMap === null) {
$this->buildNearestMap();
}
return $this->nearestMap;
}
public function getFinalOffset() {
// Make sure we've built this map already.
$this->getNearestMap();
return $this->finalOffset;
}
/**
* Add a map to the end of the chain.
*
* When a line is mapped with @{method:mapLine}, it is mapped through all
* maps in the chain.
*/
public function addMapToChain(DifferentialLineAdjustmentMap $map) {
if ($this->nextMapInChain) {
$this->nextMapInChain->addMapToChain($map);
} else {
$this->nextMapInChain = $map;
}
return $this;
}
/**
* Map a line across a change, or a series of changes.
*
* @param int Line to map
* @param bool True to map it as the end of a range.
* @return wild Spooky magic.
*/
public function mapLine($line, $is_end) {
$nmap = $this->getNearestMap();
$deleted = false;
$offset = false;
if (isset($nmap[$line])) {
$line_range = $nmap[$line];
if ($is_end) {
$to_line = end($line_range);
} else {
$to_line = reset($line_range);
}
if ($to_line <= 0) {
// If we're tracing the first line and this block is collapsing,
// compute the offset from the top of the block.
if (!$is_end && $this->isInverse) {
$offset = 1;
$cursor = $line - 1;
while (isset($nmap[$cursor])) {
$prev = $nmap[$cursor];
$prev = reset($prev);
if ($prev == $to_line) {
$offset++;
} else {
break;
}
$cursor--;
}
}
$to_line = -$to_line;
if (!$this->isInverse) {
$deleted = true;
}
}
$line = $to_line;
} else {
$line = $line + $this->finalOffset;
}
if ($this->nextMapInChain) {
$chain = $this->nextMapInChain->mapLine($line, $is_end);
list($chain_deleted, $chain_offset, $line) = $chain;
$deleted = ($deleted || $chain_deleted);
if ($chain_offset !== false) {
if ($offset === false) {
$offset = 0;
}
$offset += $chain_offset;
}
}
return array($deleted, $offset, $line);
}
/**
* Build a derived map which maps deleted lines to the nearest valid line.
*
* This computes a "nearest line" map and a final-line offset. These
* derived maps allow us to map deleted code to the previous (or next) line
* which actually exists.
*/
private function buildNearestMap() {
$map = $this->map;
$nmap = array();
$nearest = 0;
foreach ($map as $key => $value) {
if ($value) {
$nmap[$key] = $value;
$nearest = end($value);
} else {
$nmap[$key][0] = -$nearest;
}
}
if (isset($key)) {
$this->finalOffset = ($nearest - $key);
} else {
$this->finalOffset = 0;
}
foreach (array_reverse($map, true) as $key => $value) {
if ($value) {
$nearest = reset($value);
} else {
$nmap[$key][1] = -$nearest;
}
}
$this->nearestMap = $nmap;
return $this;
}
public static function newFromHunks(array $hunks) {
assert_instances_of($hunks, 'DifferentialHunk');
$map = array();
$o = 0;
$n = 0;
$hunks = msort($hunks, 'getOldOffset');
foreach ($hunks as $hunk) {
// If the hunks are disjoint, add the implied missing lines where
// nothing changed.
$min = ($hunk->getOldOffset() - 1);
while ($o < $min) {
$o++;
$n++;
$map[$o][] = $n;
}
$lines = $hunk->getStructuredLines();
foreach ($lines as $line) {
switch ($line['type']) {
case '-':
$o++;
$map[$o] = array();
break;
case '+':
$n++;
$map[$o][] = $n;
break;
case ' ':
$o++;
$n++;
$map[$o][] = $n;
break;
default:
break;
}
}
}
$map = self::reduceMapRanges($map);
return self::newFromMap($map);
}
public static function newFromMap(array $map) {
$obj = new DifferentialLineAdjustmentMap();
$obj->map = $map;
return $obj;
}
public static function newInverseMap(DifferentialLineAdjustmentMap $map) {
$old = $map->getMap();
$inv = array();
$last = 0;
foreach ($old as $k => $v) {
if (count($v) > 1) {
$v = range(reset($v), end($v));
}
if ($k == 0) {
foreach ($v as $line) {
$inv[$line] = array();
$last = $line;
}
} else if ($v) {
$first = true;
foreach ($v as $line) {
if ($first) {
$first = false;
$inv[$line][] = $k;
$last = $line;
} else {
$inv[$line] = array();
}
}
} else {
$inv[$last][] = $k;
}
}
$inv = self::reduceMapRanges($inv);
$obj = new DifferentialLineAdjustmentMap();
$obj->map = $inv;
$obj->isInverse = !$map->isInverse;
return $obj;
}
private static function reduceMapRanges(array $map) {
foreach ($map as $key => $values) {
if (count($values) > 2) {
$map[$key] = array(reset($values), end($values));
}
}
return $map;
}
public static function loadMaps(array $maps) {
$keys = array();
foreach ($maps as $map) {
list($u, $v) = $map;
$keys[self::getCacheKey($u, $v)] = $map;
}
$cache = new PhabricatorKeyValueDatabaseCache();
$cache = new PhutilKeyValueCacheProfiler($cache);
$cache->setProfiler(PhutilServiceProfiler::getInstance());
$results = array();
if ($keys) {
$caches = $cache->getKeys(array_keys($keys));
foreach ($caches as $key => $value) {
list($u, $v) = $keys[$key];
try {
$results[$u][$v] = self::newFromMap(
phutil_json_decode($value));
} catch (Exception $ex) {
// Ignore, rebuild below.
}
unset($keys[$key]);
}
}
if ($keys) {
$built = self::buildMaps($maps);
$write = array();
foreach ($built as $u => $list) {
foreach ($list as $v => $map) {
$write[self::getCacheKey($u, $v)] = json_encode($map->getMap());
$results[$u][$v] = $map;
}
}
$cache->setKeys($write);
}
return $results;
}
private static function buildMaps(array $maps) {
$need = array();
foreach ($maps as $map) {
list($u, $v) = $map;
$need[$u] = $u;
$need[$v] = $v;
}
if ($need) {
$changesets = id(new DifferentialChangesetQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withIDs($need)
->needHunks(true)
->execute();
$changesets = mpull($changesets, null, 'getID');
}
$results = array();
foreach ($maps as $map) {
list($u, $v) = $map;
$u_set = idx($changesets, $u);
$v_set = idx($changesets, $v);
if (!$u_set || !$v_set) {
continue;
}
// This is the simple case.
if ($u == $v) {
$results[$u][$v] = self::newFromHunks(
$u_set->getHunks());
continue;
}
$u_old = $u_set->makeOldFile();
$v_old = $v_set->makeOldFile();
// No difference between the two left sides.
if ($u_old == $v_old) {
$results[$u][$v] = self::newFromMap(
array());
continue;
}
// If we're missing context, this won't currently work. We can
// make this case work, but it's fairly rare.
$u_hunks = $u_set->getHunks();
$v_hunks = $v_set->getHunks();
if (count($u_hunks) != 1 ||
count($v_hunks) != 1 ||
head($u_hunks)->getOldOffset() != 1 ||
head($u_hunks)->getNewOffset() != 1 ||
head($v_hunks)->getOldOffset() != 1 ||
head($v_hunks)->getNewOffset() != 1) {
continue;
}
$changeset = id(new PhabricatorDifferenceEngine())
->generateChangesetFromFileContent($u_old, $v_old);
$results[$u][$v] = self::newFromHunks(
$changeset->getHunks());
}
return $results;
}
private static function getCacheKey($u, $v) {
return 'diffadjust.v1('.$u.','.$v.')';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/parser/DifferentialChangesetParser.php | src/applications/differential/parser/DifferentialChangesetParser.php | <?php
final class DifferentialChangesetParser extends Phobject {
const HIGHLIGHT_BYTE_LIMIT = 262144;
protected $visible = array();
protected $new = array();
protected $old = array();
protected $intra = array();
protected $depthOnlyLines = array();
protected $newRender = null;
protected $oldRender = null;
protected $filename = null;
protected $hunkStartLines = array();
protected $comments = array();
protected $specialAttributes = array();
protected $changeset;
protected $renderCacheKey = null;
private $handles = array();
private $user;
private $leftSideChangesetID;
private $leftSideAttachesToNewFile;
private $rightSideChangesetID;
private $rightSideAttachesToNewFile;
private $originalLeft;
private $originalRight;
private $renderingReference;
private $isSubparser;
private $isTopLevel;
private $coverage;
private $markupEngine;
private $highlightErrors;
private $disableCache;
private $renderer;
private $highlightingDisabled;
private $showEditAndReplyLinks = true;
private $canMarkDone;
private $objectOwnerPHID;
private $offsetMode;
private $rangeStart;
private $rangeEnd;
private $mask;
private $linesOfContext = 8;
private $highlightEngine;
private $viewer;
private $viewState;
private $availableDocumentEngines;
public function setRange($start, $end) {
$this->rangeStart = $start;
$this->rangeEnd = $end;
return $this;
}
public function setMask(array $mask) {
$this->mask = $mask;
return $this;
}
public function renderChangeset() {
return $this->render($this->rangeStart, $this->rangeEnd, $this->mask);
}
public function setShowEditAndReplyLinks($bool) {
$this->showEditAndReplyLinks = $bool;
return $this;
}
public function getShowEditAndReplyLinks() {
return $this->showEditAndReplyLinks;
}
public function setViewState(PhabricatorChangesetViewState $view_state) {
$this->viewState = $view_state;
return $this;
}
public function getViewState() {
return $this->viewState;
}
public function setRenderer(DifferentialChangesetRenderer $renderer) {
$this->renderer = $renderer;
return $this;
}
public function getRenderer() {
return $this->renderer;
}
public function setDisableCache($disable_cache) {
$this->disableCache = $disable_cache;
return $this;
}
public function getDisableCache() {
return $this->disableCache;
}
public function setCanMarkDone($can_mark_done) {
$this->canMarkDone = $can_mark_done;
return $this;
}
public function getCanMarkDone() {
return $this->canMarkDone;
}
public function setObjectOwnerPHID($phid) {
$this->objectOwnerPHID = $phid;
return $this;
}
public function getObjectOwnerPHID() {
return $this->objectOwnerPHID;
}
public function setOffsetMode($offset_mode) {
$this->offsetMode = $offset_mode;
return $this;
}
public function getOffsetMode() {
return $this->offsetMode;
}
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
private function newRenderer() {
$viewer = $this->getViewer();
$viewstate = $this->getViewstate();
$renderer_key = $viewstate->getRendererKey();
if ($renderer_key === null) {
$is_unified = $viewer->compareUserSetting(
PhabricatorUnifiedDiffsSetting::SETTINGKEY,
PhabricatorUnifiedDiffsSetting::VALUE_ALWAYS_UNIFIED);
if ($is_unified) {
$renderer_key = '1up';
} else {
$renderer_key = $viewstate->getDefaultDeviceRendererKey();
}
}
switch ($renderer_key) {
case '1up':
$renderer = new DifferentialChangesetOneUpRenderer();
break;
default:
$renderer = new DifferentialChangesetTwoUpRenderer();
break;
}
return $renderer;
}
const CACHE_VERSION = 14;
const CACHE_MAX_SIZE = 8e6;
const ATTR_GENERATED = 'attr:generated';
const ATTR_DELETED = 'attr:deleted';
const ATTR_UNCHANGED = 'attr:unchanged';
const ATTR_MOVEAWAY = 'attr:moveaway';
public function setOldLines(array $lines) {
$this->old = $lines;
return $this;
}
public function setNewLines(array $lines) {
$this->new = $lines;
return $this;
}
public function setSpecialAttributes(array $attributes) {
$this->specialAttributes = $attributes;
return $this;
}
public function setIntraLineDiffs(array $diffs) {
$this->intra = $diffs;
return $this;
}
public function setDepthOnlyLines(array $lines) {
$this->depthOnlyLines = $lines;
return $this;
}
public function getDepthOnlyLines() {
return $this->depthOnlyLines;
}
public function setVisibleLinesMask(array $mask) {
$this->visible = $mask;
return $this;
}
public function setLinesOfContext($lines_of_context) {
$this->linesOfContext = $lines_of_context;
return $this;
}
public function getLinesOfContext() {
return $this->linesOfContext;
}
/**
* Configure which Changeset comments added to the right side of the visible
* diff will be attached to. The ID must be the ID of a real Differential
* Changeset.
*
* The complexity here is that we may show an arbitrary side of an arbitrary
* changeset as either the left or right part of a diff. This method allows
* the left and right halves of the displayed diff to be correctly mapped to
* storage changesets.
*
* @param id The Differential Changeset ID that comments added to the right
* side of the visible diff should be attached to.
* @param bool If true, attach new comments to the right side of the storage
* changeset. Note that this may be false, if the left side of
* some storage changeset is being shown as the right side of
* a display diff.
* @return this
*/
public function setRightSideCommentMapping($id, $is_new) {
$this->rightSideChangesetID = $id;
$this->rightSideAttachesToNewFile = $is_new;
return $this;
}
/**
* See setRightSideCommentMapping(), but this sets information for the left
* side of the display diff.
*/
public function setLeftSideCommentMapping($id, $is_new) {
$this->leftSideChangesetID = $id;
$this->leftSideAttachesToNewFile = $is_new;
return $this;
}
public function setOriginals(
DifferentialChangeset $left,
DifferentialChangeset $right) {
$this->originalLeft = $left;
$this->originalRight = $right;
return $this;
}
public function diffOriginals() {
$engine = new PhabricatorDifferenceEngine();
$changeset = $engine->generateChangesetFromFileContent(
implode('', mpull($this->originalLeft->getHunks(), 'getChanges')),
implode('', mpull($this->originalRight->getHunks(), 'getChanges')));
$parser = new DifferentialHunkParser();
return $parser->parseHunksForHighlightMasks(
$changeset->getHunks(),
$this->originalLeft->getHunks(),
$this->originalRight->getHunks());
}
/**
* Set a key for identifying this changeset in the render cache. If set, the
* parser will attempt to use the changeset render cache, which can improve
* performance for frequently-viewed changesets.
*
* By default, there is no render cache key and parsers do not use the cache.
* This is appropriate for rarely-viewed changesets.
*
* @param string Key for identifying this changeset in the render cache.
* @return this
*/
public function setRenderCacheKey($key) {
$this->renderCacheKey = $key;
return $this;
}
private function getRenderCacheKey() {
return $this->renderCacheKey;
}
public function setChangeset(DifferentialChangeset $changeset) {
$this->changeset = $changeset;
$this->setFilename($changeset->getFilename());
return $this;
}
public function setRenderingReference($ref) {
$this->renderingReference = $ref;
return $this;
}
private function getRenderingReference() {
return $this->renderingReference;
}
public function getChangeset() {
return $this->changeset;
}
public function setFilename($filename) {
$this->filename = $filename;
return $this;
}
public function setHandles(array $handles) {
assert_instances_of($handles, 'PhabricatorObjectHandle');
$this->handles = $handles;
return $this;
}
public function setMarkupEngine(PhabricatorMarkupEngine $engine) {
$this->markupEngine = $engine;
return $this;
}
public function setCoverage($coverage) {
$this->coverage = $coverage;
return $this;
}
private function getCoverage() {
return $this->coverage;
}
public function parseInlineComment(
PhabricatorInlineComment $comment) {
// Parse only comments which are actually visible.
if ($this->isCommentVisibleOnRenderedDiff($comment)) {
$this->comments[] = $comment;
}
return $this;
}
private function loadCache() {
$render_cache_key = $this->getRenderCacheKey();
if (!$render_cache_key) {
return false;
}
$data = null;
$changeset = new DifferentialChangeset();
$conn_r = $changeset->establishConnection('r');
$data = queryfx_one(
$conn_r,
'SELECT * FROM %T WHERE cacheIndex = %s',
DifferentialChangeset::TABLE_CACHE,
PhabricatorHash::digestForIndex($render_cache_key));
if (!$data) {
return false;
}
if ($data['cache'][0] == '{') {
// This is likely an old-style JSON cache which we will not be able to
// deserialize.
return false;
}
$data = unserialize($data['cache']);
if (!is_array($data) || !$data) {
return false;
}
foreach (self::getCacheableProperties() as $cache_key) {
if (!array_key_exists($cache_key, $data)) {
// If we're missing a cache key, assume we're looking at an old cache
// and ignore it.
return false;
}
}
if ($data['cacheVersion'] !== self::CACHE_VERSION) {
return false;
}
// Someone displays contents of a partially cached shielded file.
if (!isset($data['newRender']) && (!$this->isTopLevel || $this->comments)) {
return false;
}
unset($data['cacheVersion'], $data['cacheHost']);
$cache_prop = array_select_keys($data, self::getCacheableProperties());
foreach ($cache_prop as $cache_key => $v) {
$this->$cache_key = $v;
}
return true;
}
protected static function getCacheableProperties() {
return array(
'visible',
'new',
'old',
'intra',
'depthOnlyLines',
'newRender',
'oldRender',
'specialAttributes',
'hunkStartLines',
'cacheVersion',
'cacheHost',
'highlightingDisabled',
);
}
public function saveCache() {
if (PhabricatorEnv::isReadOnly()) {
return false;
}
if ($this->highlightErrors) {
return false;
}
$render_cache_key = $this->getRenderCacheKey();
if (!$render_cache_key) {
return false;
}
$cache = array();
foreach (self::getCacheableProperties() as $cache_key) {
switch ($cache_key) {
case 'cacheVersion':
$cache[$cache_key] = self::CACHE_VERSION;
break;
case 'cacheHost':
$cache[$cache_key] = php_uname('n');
break;
default:
$cache[$cache_key] = $this->$cache_key;
break;
}
}
$cache = serialize($cache);
// We don't want to waste too much space by a single changeset.
if (strlen($cache) > self::CACHE_MAX_SIZE) {
return;
}
$changeset = new DifferentialChangeset();
$conn_w = $changeset->establishConnection('w');
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
try {
queryfx(
$conn_w,
'INSERT INTO %T (cacheIndex, cache, dateCreated) VALUES (%s, %B, %d)
ON DUPLICATE KEY UPDATE cache = VALUES(cache)',
DifferentialChangeset::TABLE_CACHE,
PhabricatorHash::digestForIndex($render_cache_key),
$cache,
PhabricatorTime::getNow());
} catch (AphrontQueryException $ex) {
// Ignore these exceptions. A common cause is that the cache is
// larger than 'max_allowed_packet', in which case we're better off
// not writing it.
// TODO: It would be nice to tailor this more narrowly.
}
unset($unguarded);
}
private function markGenerated($new_corpus_block = '') {
$generated_guess = (strpos($new_corpus_block, '@'.'generated') !== false);
if (!$generated_guess) {
$generated_path_regexps = PhabricatorEnv::getEnvConfig(
'differential.generated-paths');
foreach ($generated_path_regexps as $regexp) {
if (preg_match($regexp, $this->changeset->getFilename())) {
$generated_guess = true;
break;
}
}
}
$event = new PhabricatorEvent(
PhabricatorEventType::TYPE_DIFFERENTIAL_WILLMARKGENERATED,
array(
'corpus' => $new_corpus_block,
'is_generated' => $generated_guess,
)
);
PhutilEventEngine::dispatchEvent($event);
$generated = $event->getValue('is_generated');
$attribute = $this->changeset->isGeneratedChangeset();
if ($attribute) {
$generated = true;
}
$this->specialAttributes[self::ATTR_GENERATED] = $generated;
}
public function isGenerated() {
return idx($this->specialAttributes, self::ATTR_GENERATED, false);
}
public function isDeleted() {
return idx($this->specialAttributes, self::ATTR_DELETED, false);
}
public function isUnchanged() {
return idx($this->specialAttributes, self::ATTR_UNCHANGED, false);
}
public function isMoveAway() {
return idx($this->specialAttributes, self::ATTR_MOVEAWAY, false);
}
private function applyIntraline(&$render, $intra, $corpus) {
foreach ($render as $key => $text) {
$result = $text;
if (isset($intra[$key])) {
$result = PhabricatorDifferenceEngine::applyIntralineDiff(
$result,
$intra[$key]);
}
$result = $this->adjustRenderedLineForDisplay($result);
$render[$key] = $result;
}
}
private function getHighlightFuture($corpus) {
$language = $this->getViewState()->getHighlightLanguage();
if (!$language) {
$language = $this->highlightEngine->getLanguageFromFilename(
$this->filename);
if (($language != 'txt') &&
(strlen($corpus) > self::HIGHLIGHT_BYTE_LIMIT)) {
$this->highlightingDisabled = true;
$language = 'txt';
}
}
return $this->highlightEngine->getHighlightFuture(
$language,
$corpus);
}
protected function processHighlightedSource($data, $result) {
$result_lines = phutil_split_lines($result);
foreach ($data as $key => $info) {
if (!$info) {
unset($result_lines[$key]);
}
}
return $result_lines;
}
private function tryCacheStuff() {
$changeset = $this->getChangeset();
if (!$changeset->hasSourceTextBody()) {
// TODO: This isn't really correct (the change is not "generated"), the
// intent is just to not render a text body for Subversion directory
// changes, etc.
$this->markGenerated();
return;
}
$viewstate = $this->getViewState();
$skip_cache = false;
if ($this->disableCache) {
$skip_cache = true;
}
$character_encoding = $viewstate->getCharacterEncoding();
if ($character_encoding !== null) {
$skip_cache = true;
}
$highlight_language = $viewstate->getHighlightLanguage();
if ($highlight_language !== null) {
$skip_cache = true;
}
if ($skip_cache || !$this->loadCache()) {
$this->process();
if (!$skip_cache) {
$this->saveCache();
}
}
}
private function process() {
$changeset = $this->changeset;
$hunk_parser = new DifferentialHunkParser();
$hunk_parser->parseHunksForLineData($changeset->getHunks());
$this->realignDiff($changeset, $hunk_parser);
$hunk_parser->reparseHunksForSpecialAttributes();
$unchanged = false;
if (!$hunk_parser->getHasAnyChanges()) {
$filetype = $this->changeset->getFileType();
if ($filetype == DifferentialChangeType::FILE_TEXT ||
$filetype == DifferentialChangeType::FILE_SYMLINK) {
$unchanged = true;
}
}
$moveaway = false;
$changetype = $this->changeset->getChangeType();
if ($changetype == DifferentialChangeType::TYPE_MOVE_AWAY) {
$moveaway = true;
}
$this->setSpecialAttributes(array(
self::ATTR_UNCHANGED => $unchanged,
self::ATTR_DELETED => $hunk_parser->getIsDeleted(),
self::ATTR_MOVEAWAY => $moveaway,
));
$lines_context = $this->getLinesOfContext();
$hunk_parser->generateIntraLineDiffs();
$hunk_parser->generateVisibleLinesMask($lines_context);
$this->setOldLines($hunk_parser->getOldLines());
$this->setNewLines($hunk_parser->getNewLines());
$this->setIntraLineDiffs($hunk_parser->getIntraLineDiffs());
$this->setDepthOnlyLines($hunk_parser->getDepthOnlyLines());
$this->setVisibleLinesMask($hunk_parser->getVisibleLinesMask());
$this->hunkStartLines = $hunk_parser->getHunkStartLines(
$changeset->getHunks());
$new_corpus = $hunk_parser->getNewCorpus();
$new_corpus_block = implode('', $new_corpus);
$this->markGenerated($new_corpus_block);
if ($this->isTopLevel &&
!$this->comments &&
($this->isGenerated() ||
$this->isUnchanged() ||
$this->isDeleted())) {
return;
}
$old_corpus = $hunk_parser->getOldCorpus();
$old_corpus_block = implode('', $old_corpus);
$old_future = $this->getHighlightFuture($old_corpus_block);
$new_future = $this->getHighlightFuture($new_corpus_block);
$futures = array(
'old' => $old_future,
'new' => $new_future,
);
$corpus_blocks = array(
'old' => $old_corpus_block,
'new' => $new_corpus_block,
);
$this->highlightErrors = false;
foreach (new FutureIterator($futures) as $key => $future) {
try {
try {
$highlighted = $future->resolve();
} catch (PhutilSyntaxHighlighterException $ex) {
$this->highlightErrors = true;
$highlighted = id(new PhutilDefaultSyntaxHighlighter())
->getHighlightFuture($corpus_blocks[$key])
->resolve();
}
switch ($key) {
case 'old':
$this->oldRender = $this->processHighlightedSource(
$this->old,
$highlighted);
break;
case 'new':
$this->newRender = $this->processHighlightedSource(
$this->new,
$highlighted);
break;
}
} catch (Exception $ex) {
phlog($ex);
throw $ex;
}
}
$this->applyIntraline(
$this->oldRender,
ipull($this->intra, 0),
$old_corpus);
$this->applyIntraline(
$this->newRender,
ipull($this->intra, 1),
$new_corpus);
}
private function shouldRenderPropertyChangeHeader($changeset) {
if (!$this->isTopLevel) {
// We render properties only at top level; otherwise we get multiple
// copies of them when a user clicks "Show More".
return false;
}
return true;
}
public function render(
$range_start = null,
$range_len = null,
$mask_force = array()) {
$viewer = $this->getViewer();
$renderer = $this->getRenderer();
if (!$renderer) {
$renderer = $this->newRenderer();
$this->setRenderer($renderer);
}
// "Top level" renders are initial requests for the whole file, versus
// requests for a specific range generated by clicking "show more". We
// generate property changes and "shield" UI elements only for toplevel
// requests.
$this->isTopLevel = (($range_start === null) && ($range_len === null));
$this->highlightEngine = PhabricatorSyntaxHighlighter::newEngine();
$viewstate = $this->getViewState();
$encoding = null;
$character_encoding = $viewstate->getCharacterEncoding();
if ($character_encoding) {
// We are forcing this changeset to be interpreted with a specific
// character encoding, so force all the hunks into that encoding and
// propagate it to the renderer.
$encoding = $character_encoding;
foreach ($this->changeset->getHunks() as $hunk) {
$hunk->forceEncoding($character_encoding);
}
} else {
// We're just using the default, so tell the renderer what that is
// (by reading the encoding from the first hunk).
foreach ($this->changeset->getHunks() as $hunk) {
$encoding = $hunk->getDataEncoding();
break;
}
}
$this->tryCacheStuff();
// If we're rendering in an offset mode, treat the range numbers as line
// numbers instead of rendering offsets.
$offset_mode = $this->getOffsetMode();
if ($offset_mode) {
if ($offset_mode == 'new') {
$offset_map = $this->new;
} else {
$offset_map = $this->old;
}
// NOTE: Inline comments use zero-based lengths. For example, a comment
// that starts and ends on line 123 has length 0. Rendering considers
// this range to have length 1. Probably both should agree, but that
// ship likely sailed long ago. Tweak things here to get the two systems
// to agree. See PHI985, where this affected mail rendering of inline
// comments left on the final line of a file.
$range_end = $this->getOffset($offset_map, $range_start + $range_len);
$range_start = $this->getOffset($offset_map, $range_start);
$range_len = ($range_end - $range_start) + 1;
}
$render_pch = $this->shouldRenderPropertyChangeHeader($this->changeset);
$rows = max(
count($this->old),
count($this->new));
$renderer = $this->getRenderer()
->setUser($this->getViewer())
->setChangeset($this->changeset)
->setRenderPropertyChangeHeader($render_pch)
->setIsTopLevel($this->isTopLevel)
->setOldRender($this->oldRender)
->setNewRender($this->newRender)
->setHunkStartLines($this->hunkStartLines)
->setOldChangesetID($this->leftSideChangesetID)
->setNewChangesetID($this->rightSideChangesetID)
->setOldAttachesToNewFile($this->leftSideAttachesToNewFile)
->setNewAttachesToNewFile($this->rightSideAttachesToNewFile)
->setCodeCoverage($this->getCoverage())
->setRenderingReference($this->getRenderingReference())
->setHandles($this->handles)
->setOldLines($this->old)
->setNewLines($this->new)
->setOriginalCharacterEncoding($encoding)
->setShowEditAndReplyLinks($this->getShowEditAndReplyLinks())
->setCanMarkDone($this->getCanMarkDone())
->setObjectOwnerPHID($this->getObjectOwnerPHID())
->setHighlightingDisabled($this->highlightingDisabled)
->setDepthOnlyLines($this->getDepthOnlyLines());
if ($this->markupEngine) {
$renderer->setMarkupEngine($this->markupEngine);
}
list($engine, $old_ref, $new_ref) = $this->newDocumentEngine();
if ($engine) {
$engine_blocks = $engine->newEngineBlocks(
$old_ref,
$new_ref);
} else {
$engine_blocks = null;
}
$has_document_engine = ($engine_blocks !== null);
// Remove empty comments that don't have any unsaved draft data.
PhabricatorInlineComment::loadAndAttachVersionedDrafts(
$viewer,
$this->comments);
foreach ($this->comments as $key => $comment) {
if ($comment->isVoidComment($viewer)) {
unset($this->comments[$key]);
}
}
// See T13515. Sometimes, we collapse file content by default: for
// example, if the file is marked as containing generated code.
// If a file has inline comments, that normally means we never collapse
// it. However, if the viewer has already collapsed all of the inlines,
// it's fine to collapse the file.
$expanded_comments = array();
foreach ($this->comments as $comment) {
if ($comment->isHidden()) {
continue;
}
$expanded_comments[] = $comment;
}
$collapsed_count = (count($this->comments) - count($expanded_comments));
$shield_raw = null;
$shield_text = null;
$shield_type = null;
if ($this->isTopLevel && !$expanded_comments && !$has_document_engine) {
if ($this->isGenerated()) {
$shield_text = pht(
'This file contains generated code, which does not normally '.
'need to be reviewed.');
} else if ($this->isMoveAway()) {
// We put an empty shield on these files. Normally, they do not have
// any diff content anyway. However, if they come through `arc`, they
// may have content. We don't want to show it (it's not useful) and
// we bailed out of fully processing it earlier anyway.
// We could show a message like "this file was moved", but we show
// that as a change header anyway, so it would be redundant. Instead,
// just render an empty shield to skip rendering the diff body.
$shield_raw = '';
} else if ($this->isUnchanged()) {
$type = 'text';
if (!$rows) {
// NOTE: Normally, diffs which don't change files do not include
// file content (for example, if you "chmod +x" a file and then
// run "git show", the file content is not available). Similarly,
// if you move a file from A to B without changing it, diffs normally
// do not show the file content. In some cases `arc` is able to
// synthetically generate content for these diffs, but for raw diffs
// we'll never have it so we need to be prepared to not render a link.
$type = 'none';
}
$shield_type = $type;
$type_add = DifferentialChangeType::TYPE_ADD;
if ($this->changeset->getChangeType() == $type_add) {
// Although the generic message is sort of accurate in a technical
// sense, this more-tailored message is less confusing.
$shield_text = pht('This is an empty file.');
} else {
$shield_text = pht('The contents of this file were not changed.');
}
} else if ($this->isDeleted()) {
$shield_text = pht('This file was completely deleted.');
} else if ($this->changeset->getAffectedLineCount() > 2500) {
$shield_text = pht(
'This file has a very large number of changes (%s lines).',
new PhutilNumber($this->changeset->getAffectedLineCount()));
}
}
$shield = null;
if ($shield_raw !== null) {
$shield = $shield_raw;
} else if ($shield_text !== null) {
if ($shield_type === null) {
$shield_type = 'default';
}
// If we have inlines and the shield would normally show the whole file,
// downgrade it to show only text around the inlines.
if ($collapsed_count) {
if ($shield_type === 'text') {
$shield_type = 'default';
}
$shield_text = array(
$shield_text,
' ',
pht(
'This file has %d collapsed inline comment(s).',
new PhutilNumber($collapsed_count)),
);
}
$shield = $renderer->renderShield($shield_text, $shield_type);
}
if ($shield !== null) {
return $renderer->renderChangesetTable($shield);
}
// This request should render the "undershield" headers if it's a top-level
// request which made it this far (indicating the changeset has no shield)
// or it's a request with no mask information (indicating it's the request
// that removes the rendering shield). Possibly, this second class of
// request might need to be made more explicit.
$is_undershield = (empty($mask_force) || $this->isTopLevel);
$renderer->setIsUndershield($is_undershield);
$old_comments = array();
$new_comments = array();
$old_mask = array();
$new_mask = array();
$feedback_mask = array();
$lines_context = $this->getLinesOfContext();
if ($this->comments) {
// If there are any comments which appear in sections of the file which
// we don't have, we're going to move them backwards to the closest
// earlier line. Two cases where this may happen are:
//
// - Porting ghost comments forward into a file which was mostly
// deleted.
// - Porting ghost comments forward from a full-context diff to a
// partial-context diff.
list($old_backmap, $new_backmap) = $this->buildLineBackmaps();
foreach ($this->comments as $comment) {
$new_side = $this->isCommentOnRightSideWhenDisplayed($comment);
$line = $comment->getLineNumber();
// See T13524. Lint inlines from Harbormaster may not have a line
// number.
if ($line === null) {
$back_line = null;
} else if ($new_side) {
$back_line = idx($new_backmap, $line);
} else {
$back_line = idx($old_backmap, $line);
}
if ($back_line != $line) {
// TODO: This should probably be cleaner, but just be simple and
// obvious for now.
$ghost = $comment->getIsGhost();
if ($ghost) {
$moved = pht(
'This comment originally appeared on line %s, but that line '.
'does not exist in this version of the diff. It has been '.
'moved backward to the nearest line.',
new PhutilNumber($line));
$ghost['reason'] = $ghost['reason']."\n\n".$moved;
$comment->setIsGhost($ghost);
}
$comment->setLineNumber($back_line);
$comment->setLineLength(0);
}
$start = max($comment->getLineNumber() - $lines_context, 0);
$end = $comment->getLineNumber() +
$comment->getLineLength() +
$lines_context;
for ($ii = $start; $ii <= $end; $ii++) {
if ($new_side) {
$new_mask[$ii] = true;
} else {
$old_mask[$ii] = true;
}
}
}
foreach ($this->old as $ii => $old) {
if (isset($old['line']) && isset($old_mask[$old['line']])) {
$feedback_mask[$ii] = true;
}
}
foreach ($this->new as $ii => $new) {
if (isset($new['line']) && isset($new_mask[$new['line']])) {
$feedback_mask[$ii] = true;
}
}
$this->comments = id(new PHUIDiffInlineThreader())
->reorderAndThreadCommments($this->comments);
$old_max_display = 1;
foreach ($this->old as $old) {
if (isset($old['line'])) {
$old_max_display = $old['line'];
}
}
$new_max_display = 1;
foreach ($this->new as $new) {
if (isset($new['line'])) {
$new_max_display = $new['line'];
}
}
foreach ($this->comments as $comment) {
$display_line = $comment->getLineNumber() + $comment->getLineLength();
$display_line = max(1, $display_line);
if ($this->isCommentOnRightSideWhenDisplayed($comment)) {
$display_line = min($new_max_display, $display_line);
$new_comments[$display_line][] = $comment;
} else {
$display_line = min($old_max_display, $display_line);
$old_comments[$display_line][] = $comment;
}
}
}
$renderer
->setOldComments($old_comments)
->setNewComments($new_comments);
if ($engine_blocks !== null) {
$reference = $this->getRenderingReference();
$parts = explode('/', $reference);
if (count($parts) == 2) {
list($id, $vs) = $parts;
} else {
$id = $parts[0];
$vs = 0;
}
// If we don't have an explicit "vs" changeset, it's the left side of
// the "id" changeset.
if (!$vs) {
$vs = $id;
}
if ($mask_force) {
$engine_blocks->setRevealedIndexes(array_keys($mask_force));
}
if ($range_start !== null || $range_len !== null) {
$range_min = $range_start;
if ($range_len === null) {
$range_max = null;
} else {
$range_max = (int)$range_start + (int)$range_len;
}
$engine_blocks->setRange($range_min, $range_max);
}
$renderer
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | true |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/parser/__tests__/DifferentialCustomFieldRevertsParserTestCase.php | src/applications/differential/parser/__tests__/DifferentialCustomFieldRevertsParserTestCase.php | <?php
final class DifferentialCustomFieldRevertsParserTestCase
extends PhabricatorTestCase {
public function testParser() {
$map = array(
'quack quack quack' => array(),
// Git default message.
'This reverts commit 1234abcd.' => array(
array(
'match' => 'reverts commit 1234abcd',
'prefix' => 'reverts',
'infix' => 'commit',
'monograms' => array('1234abcd'),
'suffix' => '',
'offset' => 5,
),
),
// Mercurial default message.
'Backed out changeset 1234abcd.' => array(
array(
'match' => 'Backed out changeset 1234abcd',
'prefix' => 'Backed out',
'infix' => 'changeset',
'monograms' => array('1234abcd'),
'suffix' => '',
'offset' => 0,
),
),
'this undoes 1234abcd, 5678efab. they were bad' => array(
array(
'match' => 'undoes 1234abcd, 5678efab',
'prefix' => 'undoes',
'infix' => '',
'monograms' => array('1234abcd', '5678efab'),
'suffix' => '',
'offset' => 5,
),
),
'Reverts 123' => array(
array(
'match' => 'Reverts 123',
'prefix' => 'Reverts',
'infix' => '',
'monograms' => array('123'),
'suffix' => '',
'offset' => 0,
),
),
'Reverts r123' => array(
array(
'match' => 'Reverts r123',
'prefix' => 'Reverts',
'infix' => '',
'monograms' => array('r123'),
'suffix' => '',
'offset' => 0,
),
),
"Backs out commit\n99\n100" => array(
array(
'match' => "Backs out commit\n99\n100",
'prefix' => 'Backs out',
'infix' => 'commit',
'monograms' => array('99', '100'),
'suffix' => '',
'offset' => 0,
),
),
// This tests a degenerate regex behavior, see T9268.
'Reverts aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaz' => array(),
"This doesn't revert anything" => array(),
'nonrevert of r11' => array(),
'fixed a bug' => array(),
);
foreach ($map as $input => $expect) {
$parser = new DifferentialCustomFieldRevertsParser();
$output = $parser->parseCorpus($input);
$this->assertEqual($expect, $output, $input);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/parser/__tests__/DifferentialCommitMessageParserTestCase.php | src/applications/differential/parser/__tests__/DifferentialCommitMessageParserTestCase.php | <?php
final class DifferentialCommitMessageParserTestCase
extends PhabricatorTestCase {
public function testDifferentialCommitMessageParser() {
$dir = dirname(__FILE__).'/messages/';
$list = Filesystem::listDirectory($dir, $include_hidden = false);
foreach ($list as $file) {
if (!preg_match('/.txt$/', $file)) {
continue;
}
$data = Filesystem::readFile($dir.$file);
$divider = "~~~~~~~~~~\n";
$parts = explode($divider, $data);
if (count($parts) !== 4) {
throw new Exception(
pht(
'Expected test file "%s" to contain four parts (message, fields, '.
'output, errors) divided by "%s".',
$file,
'~~~~~~~~~~'));
}
list($message, $fields, $output, $errors) = $parts;
$fields = phutil_json_decode($fields);
$output = phutil_json_decode($output);
$errors = phutil_json_decode($errors);
$parser = id(new DifferentialCommitMessageParser())
->setLabelMap($fields)
->setTitleKey('title')
->setSummaryKey('summary');
$result_output = $parser->parseCorpus($message);
$result_errors = $parser->getErrors();
$this->assertEqual($output, $result_output);
$this->assertEqual($errors, $result_errors);
}
}
public function testDifferentialCommitMessageFieldParser() {
$message = <<<EOMESSAGE
This is the title.
Summary: This is the summary.
EOMESSAGE;
$fields = array(
new DifferentialTitleCommitMessageField(),
new DifferentialSummaryCommitMessageField(),
);
$expect = array(
DifferentialTitleCommitMessageField::FIELDKEY =>
'This is the title.',
DifferentialSummaryCommitMessageField::FIELDKEY =>
'This is the summary.',
);
$parser = id(new DifferentialCommitMessageParser())
->setCommitMessageFields($fields)
->setTitleKey(DifferentialTitleCommitMessageField::FIELDKEY)
->setSummaryKey(DifferentialSummaryCommitMessageField::FIELDKEY);
$actual = $parser->parseFields($message);
$this->assertEqual($expect, $actual);
}
public function testDifferentialCommitMessageParserNormalization() {
$map = array(
'Test Plan' => 'test plan',
'REVIEWERS' => 'reviewers',
'sUmmArY' => 'summary',
);
foreach ($map as $input => $expect) {
$this->assertEqual(
$expect,
DifferentialCommitMessageParser::normalizeFieldLabel($input),
pht('Field normalization of label "%s".', $input));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/parser/__tests__/DifferentialChangesetParserTestCase.php | src/applications/differential/parser/__tests__/DifferentialChangesetParserTestCase.php | <?php
final class DifferentialChangesetParserTestCase extends PhabricatorTestCase {
public function testDiffChangesets() {
$hunk = new DifferentialHunk();
$hunk->setChanges("+a\n b\n-c\n");
$hunk->setNewOffset(1);
$hunk->setNewLen(2);
$left = new DifferentialChangeset();
$left->attachHunks(array($hunk));
$tests = array(
"+a\n b\n-c\n" => array(array(), array()),
"+a\n x\n-c\n" => array(array(), array()),
"+aa\n b\n-c\n" => array(array(1), array(11)),
" b\n-c\n" => array(array(1), array()),
"+a\n b\n c\n" => array(array(), array(13)),
"+a\n x\n c\n" => array(array(), array(13)),
);
foreach ($tests as $changes => $expected) {
$hunk = new DifferentialHunk();
$hunk->setChanges($changes);
$hunk->setNewOffset(11);
$hunk->setNewLen(3);
$right = new DifferentialChangeset();
$right->attachHunks(array($hunk));
$parser = new DifferentialChangesetParser();
$parser->setOriginals($left, $right);
$this->assertEqual($expected, $parser->diffOriginals(), $changes);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/parser/__tests__/DifferentialTabReplacementTestCase.php | src/applications/differential/parser/__tests__/DifferentialTabReplacementTestCase.php | <?php
final class DifferentialTabReplacementTestCase
extends PhabricatorTestCase {
public function testTabReplacement() {
$tab1 = "<span data-copy-text=\"\t\"> </span>";
$tab2 = "<span data-copy-text=\"\t\"> </span>";
$cat = "\xF0\x9F\x90\xB1";
$cases = array(
'' => '',
'x' => 'x',
// Tabs inside HTML tags should not be replaced.
"<\t>x" => "<\t>x",
// Normal tabs should be replaced. These are all aligned to the tab
// width, so they'll be replaced inline.
"\tx" => "{$tab2}x",
" \tx" => " {$tab2}x",
"\t x" => "{$tab2} x",
"aa\tx" => "aa{$tab2}x",
"aa \tx" => "aa {$tab2}x",
"aa\t x" => "aa{$tab2} x",
// This tab is not tabstop-aligned, so it is replaced with fewer
// spaces to bring us to the next tabstop.
" \tx" => " {$tab1}x",
// Text inside HTML tags should not count when aligning tabs with
// tabstops.
"<tag> </tag>\tx" => "<tag> </tag>{$tab1}x",
"<tag2> </tag>\tx" => "<tag2> </tag>{$tab1}x",
// The code has to take a slow path when inputs contain unicode, but
// should produce the right results and align tabs to tabstops while
// respecting UTF8 display character widths, not byte widths.
"{$cat}\tx" => "{$cat}{$tab1}x",
"{$cat}{$cat}\tx" => "{$cat}{$cat}{$tab2}x",
);
foreach ($cases as $input => $expect) {
$actual = DifferentialChangesetParser::replaceTabsWithSpaces(
$input,
2);
$this->assertEqual(
$expect,
$actual,
pht('Tabs to Spaces: %s', $input));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/parser/__tests__/DifferentialHunkParserTestCase.php | src/applications/differential/parser/__tests__/DifferentialHunkParserTestCase.php | <?php
final class DifferentialHunkParserTestCase extends PhabricatorTestCase {
private function createComment() {
$comment = new DifferentialInlineComment();
return $comment;
}
private function createHunk(
$old_offset,
$old_len,
$new_offset,
$new_len,
$changes) {
$hunk = id(new DifferentialHunk())
->setOldOffset($old_offset)
->setOldLen($old_len)
->setNewOffset($new_offset)
->setNewLen($new_len)
->setChanges($changes);
return $hunk;
}
// Returns a change that consists of a single hunk, starting at line 1.
private function createSingleChange($old_lines, $new_lines, $changes) {
return array(
0 => $this->createHunk(1, $old_lines, 1, $new_lines, $changes),
);
}
private function createHunksFromFile($name) {
$data = Filesystem::readFile(dirname(__FILE__).'/data/'.$name);
$parser = new ArcanistDiffParser();
$changes = $parser->parseDiff($data);
if (count($changes) !== 1) {
throw new Exception(pht("Expected 1 changeset for '%s'!", $name));
}
$diff = DifferentialDiff::newFromRawChanges(
PhabricatorUser::getOmnipotentUser(),
$changes);
return head($diff->getChangesets())->getHunks();
}
public function testOneLineOldComment() {
$parser = new DifferentialHunkParser();
$hunks = $this->createSingleChange(1, 0, '-a');
$context = $parser->makeContextDiff(
$hunks,
0,
1,
0,
0);
$this->assertEqual("@@ -1,1 @@\n-a", $context);
}
public function testOneLineNewComment() {
$parser = new DifferentialHunkParser();
$hunks = $this->createSingleChange(0, 1, '+a');
$context = $parser->makeContextDiff(
$hunks,
1,
1,
0,
0);
$this->assertEqual("@@ +1,1 @@\n+a", $context);
}
public function testCannotFindContext() {
$parser = new DifferentialHunkParser();
$hunks = $this->createSingleChange(0, 1, '+a');
$context = $parser->makeContextDiff(
$hunks,
1,
2,
0,
0);
$this->assertEqual('', $context);
}
public function testOverlapFromStartOfHunk() {
$parser = new DifferentialHunkParser();
$hunks = array(
0 => $this->createHunk(23, 2, 42, 2, " 1\n 2"),
);
$context = $parser->makeContextDiff(
$hunks,
1,
41,
1,
0);
$this->assertEqual("@@ -23,1 +42,1 @@\n 1", $context);
}
public function testOverlapAfterEndOfHunk() {
$parser = new DifferentialHunkParser();
$hunks = array(
0 => $this->createHunk(23, 2, 42, 2, " 1\n 2"),
);
$context = $parser->makeContextDiff(
$hunks,
1,
43,
1,
0);
$this->assertEqual("@@ -24,1 +43,1 @@\n 2", $context);
}
public function testInclusionOfNewFileInOldCommentFromStart() {
$parser = new DifferentialHunkParser();
$hunks = $this->createSingleChange(2, 3,
"+n1\n".
" e1/2\n".
"-o2\n".
"+n3\n");
$context = $parser->makeContextDiff(
$hunks,
0,
1,
1,
0);
$this->assertEqual(
"@@ -1,2 +2,1 @@\n".
" e1/2\n".
"-o2", $context);
}
public function testInclusionOfOldFileInNewCommentFromStart() {
$parser = new DifferentialHunkParser();
$hunks = $this->createSingleChange(2, 2,
"-o1\n".
" e2/1\n".
"-o3\n".
"+n2\n");
$context = $parser->makeContextDiff(
$hunks,
1,
1,
1,
0);
$this->assertEqual(
"@@ -2,1 +1,2 @@\n".
" e2/1\n".
"+n2", $context);
}
public function testNoNewlineAtEndOfFile() {
$parser = new DifferentialHunkParser();
$hunks = $this->createSingleChange(0, 1,
"+a\n".
"\\No newline at end of file");
// Note that this only works with additional context.
$context = $parser->makeContextDiff(
$hunks,
1,
2,
0,
1);
$this->assertEqual(
"@@ +1,1 @@\n".
"+a\n".
"\\No newline at end of file", $context);
}
public function testMultiLineNewComment() {
$parser = new DifferentialHunkParser();
$hunks = $this->createSingleChange(7, 7,
" e1\n".
" e2\n".
"-o3\n".
"-o4\n".
"+n3\n".
" e5/4\n".
" e6/5\n".
"+n6\n".
" e7\n");
$context = $parser->makeContextDiff(
$hunks,
1,
2,
4,
0);
$this->assertEqual(
"@@ -2,5 +2,5 @@\n".
" e2\n".
"-o3\n".
"-o4\n".
"+n3\n".
" e5/4\n".
" e6/5\n".
"+n6", $context);
}
public function testMultiLineOldComment() {
$parser = new DifferentialHunkParser();
$hunks = $this->createSingleChange(7, 7,
" e1\n".
" e2\n".
"-o3\n".
"-o4\n".
"+n3\n".
" e5/4\n".
" e6/5\n".
"+n6\n".
" e7\n");
$context = $parser->makeContextDiff(
$hunks,
0,
2,
4,
0);
$this->assertEqual(
"@@ -2,5 +2,4 @@\n".
" e2\n".
"-o3\n".
"-o4\n".
"+n3\n".
" e5/4\n".
" e6/5", $context);
}
public function testInclusionOfNewFileInOldCommentFromStartWithContext() {
$parser = new DifferentialHunkParser();
$hunks = $this->createSingleChange(2, 3,
"+n1\n".
" e1/2\n".
"-o2\n".
"+n3\n");
$context = $parser->makeContextDiff(
$hunks,
0,
1,
1,
1);
$this->assertEqual(
"@@ -1,2 +1,2 @@\n".
"+n1\n".
" e1/2\n".
"-o2", $context);
}
public function testInclusionOfOldFileInNewCommentFromStartWithContext() {
$parser = new DifferentialHunkParser();
$hunks = $this->createSingleChange(2, 2,
"-o1\n".
" e2/1\n".
"-o3\n".
"+n2\n");
$context = $parser->makeContextDiff(
$hunks,
1,
1,
1,
1);
$this->assertEqual(
"@@ -1,3 +1,2 @@\n".
"-o1\n".
" e2/1\n".
"-o3\n".
"+n2", $context);
}
public function testMissingContext() {
$tests = array(
'missing_context.diff' => array(
4 => true,
),
'missing_context_2.diff' => array(
5 => true,
),
'missing_context_3.diff' => array(
4 => true,
13 => true,
),
);
foreach ($tests as $name => $expect) {
$hunks = $this->createHunksFromFile($name);
$parser = new DifferentialHunkParser();
$actual = $parser->getHunkStartLines($hunks);
$this->assertEqual($expect, $actual, $name);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/parser/__tests__/DifferentialCustomFieldDependsOnParserTestCase.php | src/applications/differential/parser/__tests__/DifferentialCustomFieldDependsOnParserTestCase.php | <?php
final class DifferentialCustomFieldDependsOnParserTestCase
extends PhabricatorTestCase {
public function testParser() {
$map = array(
'quack quack quack' => array(),
'D123' => array(),
'depends on D123' => array(
array(
'match' => 'depends on D123',
'prefix' => 'depends on',
'infix' => '',
'monograms' => array('D123'),
'suffix' => '',
'offset' => 0,
),
),
'depends on D123.' => array(
array(
'match' => 'depends on D123',
'prefix' => 'depends on',
'infix' => '',
'monograms' => array('D123'),
'suffix' => '',
'offset' => 0,
),
),
'depends on D123, d124' => array(
array(
'match' => 'depends on D123, d124',
'prefix' => 'depends on',
'infix' => '',
'monograms' => array('D123', 'd124'),
'suffix' => '',
'offset' => 0,
),
),
'depends on rev D123' => array(
array(
'match' => 'depends on rev D123',
'prefix' => 'depends on',
'infix' => 'rev',
'monograms' => array('D123'),
'suffix' => '',
'offset' => 0,
),
),
'depends on duck' => array(
),
'depends on D123abc' => array(
),
);
foreach ($map as $input => $expect) {
$parser = new DifferentialCustomFieldDependsOnParser();
$output = $parser->parseCorpus($input);
$this->assertEqual($expect, $output, $input);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/controller/DivinerFindController.php | src/applications/diviner/controller/DivinerFindController.php | <?php
final class DivinerFindController extends DivinerController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$book_name = $request->getStr('book');
$query_text = $request->getStr('name');
$book = null;
if ($book_name) {
$book = id(new DivinerBookQuery())
->setViewer($viewer)
->withNames(array($book_name))
->executeOne();
if (!$book) {
return new Aphront404Response();
}
}
$query = id(new DivinerAtomQuery())
->setViewer($viewer);
if ($book) {
$query->withBookPHIDs(array($book->getPHID()));
}
$context = $request->getStr('context');
if (strlen($context)) {
$query->withContexts(array($context));
}
$type = $request->getStr('type');
if (strlen($type)) {
$query->withTypes(array($type));
}
$query->withGhosts(false);
$query->withIsDocumentable(true);
$name_query = clone $query;
$name_query->withNames(
array(
$query_text,
// TODO: This could probably be more smartly normalized in the DB,
// but just fake it for now.
phutil_utf8_strtolower($query_text),
));
$atoms = $name_query->execute();
if (!$atoms) {
$title_query = clone $query;
$title_query->withTitles(array($query_text));
$atoms = $title_query->execute();
}
$not_found_uri = $this->getApplicationURI();
if (!$atoms) {
$dialog = id(new AphrontDialogView())
->setUser($viewer)
->setTitle(pht('Documentation Not Found'))
->appendChild(
pht(
'Unable to find the specified documentation. '.
'You may have followed a bad or outdated link.'))
->addCancelButton($not_found_uri, pht('Read More Documentation'));
return id(new AphrontDialogResponse())->setDialog($dialog);
}
if (count($atoms) == 1 && $request->getBool('jump')) {
$atom_uri = head($atoms)->getURI();
return id(new AphrontRedirectResponse())->setURI($atom_uri);
}
$list = $this->renderAtomList($atoms);
return $this->newPage()
->setTitle(array(pht('Find'), pht('"%s"', $query_text)))
->appendChild(array(
$list,
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/controller/DivinerController.php | src/applications/diviner/controller/DivinerController.php | <?php
abstract class DivinerController extends PhabricatorController {
public function buildApplicationMenu() {
return $this->newApplicationMenu()
->setSearchEngine(new DivinerAtomSearchEngine());
}
protected function renderAtomList(array $symbols) {
assert_instances_of($symbols, 'DivinerLiveSymbol');
$list = array();
foreach ($symbols as $symbol) {
switch ($symbol->getType()) {
case DivinerAtom::TYPE_FUNCTION:
$title = $symbol->getTitle().'()';
break;
default:
$title = $symbol->getTitle();
break;
}
$item = id(new DivinerBookItemView())
->setTitle($title)
->setHref($symbol->getURI())
->setSubtitle($symbol->getSummary())
->setType(DivinerAtom::getAtomTypeNameString($symbol->getType()));
$list[] = $item;
}
return $list;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/controller/DivinerAtomListController.php | src/applications/diviner/controller/DivinerAtomListController.php | <?php
final class DivinerAtomListController extends DivinerController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
return id(new DivinerAtomSearchEngine())
->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/diviner/controller/DivinerAtomController.php | src/applications/diviner/controller/DivinerAtomController.php | <?php
final class DivinerAtomController extends DivinerController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getUser();
$book_name = $request->getURIData('book');
$atom_type = $request->getURIData('type');
$atom_name = $request->getURIData('name');
$atom_context = nonempty($request->getURIData('context'), null);
$atom_index = nonempty($request->getURIData('index'), null);
require_celerity_resource('diviner-shared-css');
$book = id(new DivinerBookQuery())
->setViewer($viewer)
->withNames(array($book_name))
->executeOne();
if (!$book) {
return new Aphront404Response();
}
$symbol = id(new DivinerAtomQuery())
->setViewer($viewer)
->withBookPHIDs(array($book->getPHID()))
->withTypes(array($atom_type))
->withNames(array($atom_name))
->withContexts(array($atom_context))
->withIndexes(array($atom_index))
->withIsDocumentable(true)
->needAtoms(true)
->needExtends(true)
->needChildren(true)
->executeOne();
if (!$symbol) {
return new Aphront404Response();
}
$atom = $symbol->getAtom();
$crumbs = $this->buildApplicationCrumbs();
$crumbs->setBorder(true);
$crumbs->addTextCrumb(
$book->getShortTitle(),
'/book/'.$book->getName().'/');
$atom_short_title = $atom
? $atom->getDocblockMetaValue('short', $symbol->getTitle())
: $symbol->getTitle();
$crumbs->addTextCrumb($atom_short_title);
$header = id(new PHUIHeaderView())
->setHeader($this->renderFullSignature($symbol));
$properties = new PHUIPropertyListView();
$group = $atom ? $atom->getProperty('group') : $symbol->getGroupName();
if ($group) {
$group_name = $book->getGroupName($group);
} else {
$group_name = null;
}
$prop_list = new PHUIPropertyGroupView();
$prop_list->addPropertyList($properties);
$document = id(new PHUIDocumentView())
->setBook($book->getTitle(), $group_name)
->setHeader($header)
->addClass('diviner-view');
if ($atom) {
$this->buildDefined($properties, $symbol);
$this->buildExtendsAndImplements($properties, $symbol);
$this->buildRepository($properties, $symbol);
$warnings = $atom->getWarnings();
if ($warnings) {
$warnings = id(new PHUIInfoView())
->setErrors($warnings)
->setTitle(pht('Documentation Warnings'))
->setSeverity(PHUIInfoView::SEVERITY_WARNING);
}
$document->appendChild($warnings);
}
$methods = $this->composeMethods($symbol);
$field = 'default';
$engine = id(new PhabricatorMarkupEngine())
->setViewer($viewer)
->addObject($symbol, $field);
foreach ($methods as $method) {
foreach ($method['atoms'] as $matom) {
$engine->addObject($matom, $field);
}
}
$engine->process();
if ($atom) {
$content = $this->renderDocumentationText($symbol, $engine);
$document->appendChild($content);
}
$toc = $engine->getEngineMetadata(
$symbol,
$field,
PhutilRemarkupHeaderBlockRule::KEY_HEADER_TOC,
array());
if (!$atom) {
$document->appendChild(
id(new PHUIInfoView())
->setSeverity(PHUIInfoView::SEVERITY_NOTICE)
->appendChild(pht('This atom no longer exists.')));
}
if ($atom) {
$document->appendChild($this->buildParametersAndReturn(array($symbol)));
}
if ($methods) {
$tasks = $this->composeTasks($symbol);
if ($tasks) {
$methods_by_task = igroup($methods, 'task');
// Add phantom tasks for methods which have a "@task" name that isn't
// documented anywhere, or methods that have no "@task" name.
foreach ($methods_by_task as $task => $ignored) {
if (empty($tasks[$task])) {
$tasks[$task] = array(
'name' => $task,
'title' => $task ? $task : pht('Other Methods'),
'defined' => $symbol,
);
}
}
$section = id(new DivinerSectionView())
->setHeader(pht('Tasks'));
foreach ($tasks as $spec) {
$section->addContent(
id(new PHUIHeaderView())
->setNoBackground(true)
->setHeader($spec['title']));
$task_methods = idx($methods_by_task, $spec['name'], array());
$box_content = array();
if ($task_methods) {
$list_items = array();
foreach ($task_methods as $task_method) {
$atom = last($task_method['atoms']);
$item = $this->renderFullSignature($atom, true);
if (strlen($atom->getSummary())) {
$item = array(
$item,
" \xE2\x80\x94 ",
$atom->getSummary(),
);
}
$list_items[] = phutil_tag('li', array(), $item);
}
$box_content[] = phutil_tag(
'ul',
array(
'class' => 'diviner-list',
),
$list_items);
} else {
$no_methods = pht('No methods for this task.');
$box_content = phutil_tag('em', array(), $no_methods);
}
$inner_box = phutil_tag_div('diviner-task-items', $box_content);
$section->addContent($inner_box);
}
$document->appendChild($section);
}
$section = id(new DivinerSectionView())
->setHeader(pht('Methods'));
foreach ($methods as $spec) {
$matom = last($spec['atoms']);
$method_header = id(new PHUIHeaderView())
->setNoBackground(true);
$inherited = $spec['inherited'];
if ($inherited) {
$method_header->addTag(
id(new PHUITagView())
->setType(PHUITagView::TYPE_STATE)
->setBackgroundColor(PHUITagView::COLOR_GREY)
->setName(pht('Inherited')));
}
$method_header->setHeader($this->renderFullSignature($matom));
$section->addContent(
array(
$method_header,
$this->renderMethodDocumentationText($symbol, $spec, $engine),
$this->buildParametersAndReturn($spec['atoms']),
));
}
$document->appendChild($section);
}
if ($toc) {
$side = new PHUIListView();
$side->addMenuItem(
id(new PHUIListItemView())
->setName(pht('Contents'))
->setType(PHUIListItemView::TYPE_LABEL));
foreach ($toc as $key => $entry) {
$side->addMenuItem(
id(new PHUIListItemView())
->setName($entry[1])
->setHref('#'.$key));
}
$document->setToc($side);
}
$prop_list = phutil_tag_div('phui-document-view-pro-box', $prop_list);
return $this->newPage()
->setTitle($symbol->getTitle())
->setCrumbs($crumbs)
->appendChild(array(
$document,
$prop_list,
));
}
private function buildExtendsAndImplements(
PHUIPropertyListView $view,
DivinerLiveSymbol $symbol) {
$lineage = $this->getExtendsLineage($symbol);
if ($lineage) {
$tags = array();
foreach ($lineage as $item) {
$tags[] = $this->renderAtomTag($item);
}
$caret = phutil_tag('span', array('class' => 'caret-right msl msr'));
$tags = phutil_implode_html($caret, $tags);
$view->addProperty(pht('Extends'), $tags);
}
$implements = $this->getImplementsLineage($symbol);
if ($implements) {
$items = array();
foreach ($implements as $spec) {
$via = $spec['via'];
$iface = $spec['interface'];
if ($via == $symbol) {
$items[] = $this->renderAtomTag($iface);
} else {
$items[] = array(
$this->renderAtomTag($iface),
" \xE2\x97\x80 ",
$this->renderAtomTag($via),
);
}
}
$view->addProperty(
pht('Implements'),
phutil_implode_html(phutil_tag('br'), $items));
}
}
private function buildRepository(
PHUIPropertyListView $view,
DivinerLiveSymbol $symbol) {
if (!$symbol->getRepositoryPHID()) {
return;
}
$view->addProperty(
pht('Repository'),
$this->getViewer()->renderHandle($symbol->getRepositoryPHID()));
}
private function renderAtomTag(DivinerLiveSymbol $symbol) {
return id(new PHUITagView())
->setType(PHUITagView::TYPE_OBJECT)
->setName($symbol->getName())
->setHref($symbol->getURI());
}
private function getExtendsLineage(DivinerLiveSymbol $symbol) {
foreach ($symbol->getExtends() as $extends) {
if ($extends->getType() == 'class') {
$lineage = $this->getExtendsLineage($extends);
$lineage[] = $extends;
return $lineage;
}
}
return array();
}
private function getImplementsLineage(DivinerLiveSymbol $symbol) {
$implements = array();
// Do these first so we get interfaces ordered from most to least specific.
foreach ($symbol->getExtends() as $extends) {
if ($extends->getType() == 'interface') {
$implements[$extends->getName()] = array(
'interface' => $extends,
'via' => $symbol,
);
}
}
// Now do parent interfaces.
foreach ($symbol->getExtends() as $extends) {
if ($extends->getType() == 'class') {
$implements += $this->getImplementsLineage($extends);
}
}
return $implements;
}
private function buildDefined(
PHUIPropertyListView $view,
DivinerLiveSymbol $symbol) {
$atom = $symbol->getAtom();
$defined = $atom->getFile().':'.$atom->getLine();
$link = $symbol->getBook()->getConfig('uri.source');
if ($link) {
$link = strtr(
$link,
array(
'%%' => '%',
'%f' => phutil_escape_uri($atom->getFile()),
'%l' => phutil_escape_uri($atom->getLine()),
));
$defined = phutil_tag(
'a',
array(
'href' => $link,
'target' => '_blank',
),
$defined);
}
$view->addProperty(pht('Defined'), $defined);
}
private function composeMethods(DivinerLiveSymbol $symbol) {
$methods = $this->findMethods($symbol);
if (!$methods) {
return $methods;
}
foreach ($methods as $name => $method) {
// Check for "@task" on each parent, to find the most recently declared
// "@task".
$task = null;
foreach ($method['atoms'] as $key => $method_symbol) {
$atom = $method_symbol->getAtom();
if ($atom->getDocblockMetaValue('task')) {
$task = $atom->getDocblockMetaValue('task');
}
}
$methods[$name]['task'] = $task;
// Set 'inherited' if this atom has no implementation of the method.
if (last($method['implementations']) !== $symbol) {
$methods[$name]['inherited'] = true;
} else {
$methods[$name]['inherited'] = false;
}
}
return $methods;
}
private function findMethods(DivinerLiveSymbol $symbol) {
$child_specs = array();
foreach ($symbol->getExtends() as $extends) {
if ($extends->getType() == DivinerAtom::TYPE_CLASS) {
$child_specs = $this->findMethods($extends);
}
}
foreach ($symbol->getChildren() as $child) {
if ($child->getType() == DivinerAtom::TYPE_METHOD) {
$name = $child->getName();
if (isset($child_specs[$name])) {
$child_specs[$name]['atoms'][] = $child;
$child_specs[$name]['implementations'][] = $symbol;
} else {
$child_specs[$name] = array(
'atoms' => array($child),
'defined' => $symbol,
'implementations' => array($symbol),
);
}
}
}
return $child_specs;
}
private function composeTasks(DivinerLiveSymbol $symbol) {
$extends_task_specs = array();
foreach ($symbol->getExtends() as $extends) {
$extends_task_specs += $this->composeTasks($extends);
}
$task_specs = array();
$tasks = $symbol->getAtom()->getDocblockMetaValue('task');
if (!is_array($tasks)) {
if (strlen($tasks)) {
$tasks = array($tasks);
} else {
$tasks = array();
}
}
if ($tasks) {
foreach ($tasks as $task) {
list($name, $title) = explode(' ', $task, 2);
$name = trim($name);
$title = trim($title);
$task_specs[$name] = array(
'name' => $name,
'title' => $title,
'defined' => $symbol,
);
}
}
$specs = $task_specs + $extends_task_specs;
// Reorder "@tasks" in original declaration order. Basically, we want to
// use the documentation of the closest subclass, but put tasks which
// were declared by parents first.
$keys = array_keys($extends_task_specs);
$specs = array_select_keys($specs, $keys) + $specs;
return $specs;
}
private function renderFullSignature(
DivinerLiveSymbol $symbol,
$is_link = false) {
switch ($symbol->getType()) {
case DivinerAtom::TYPE_CLASS:
case DivinerAtom::TYPE_INTERFACE:
case DivinerAtom::TYPE_METHOD:
case DivinerAtom::TYPE_FUNCTION:
break;
default:
return $symbol->getTitle();
}
$atom = $symbol->getAtom();
$out = array();
if ($atom) {
if ($atom->getProperty('final')) {
$out[] = 'final';
}
if ($atom->getProperty('abstract')) {
$out[] = 'abstract';
}
if ($atom->getProperty('access')) {
$out[] = $atom->getProperty('access');
}
if ($atom->getProperty('static')) {
$out[] = 'static';
}
}
switch ($symbol->getType()) {
case DivinerAtom::TYPE_CLASS:
case DivinerAtom::TYPE_INTERFACE:
$out[] = $symbol->getType();
break;
case DivinerAtom::TYPE_FUNCTION:
switch ($atom->getLanguage()) {
case 'php':
$out[] = $symbol->getType();
break;
}
break;
case DivinerAtom::TYPE_METHOD:
switch ($atom->getLanguage()) {
case 'php':
$out[] = DivinerAtom::TYPE_FUNCTION;
break;
}
break;
}
$anchor = null;
switch ($symbol->getType()) {
case DivinerAtom::TYPE_METHOD:
$anchor = $symbol->getType().'/'.$symbol->getName();
break;
default:
break;
}
$out[] = phutil_tag(
$anchor ? 'a' : 'span',
array(
'class' => 'diviner-atom-signature-name',
'href' => $anchor ? '#'.$anchor : null,
'name' => $is_link ? null : $anchor,
),
$symbol->getName());
$out = phutil_implode_html(' ', $out);
if ($atom) {
$parameters = $atom->getProperty('parameters');
if ($parameters !== null) {
$pout = array();
foreach ($parameters as $parameter) {
$pout[] = idx($parameter, 'name', '...');
}
$out = array($out, '('.implode(', ', $pout).')');
}
}
return phutil_tag(
'span',
array(
'class' => 'diviner-atom-signature',
),
$out);
}
private function buildParametersAndReturn(array $symbols) {
assert_instances_of($symbols, 'DivinerLiveSymbol');
$symbols = array_reverse($symbols);
$out = array();
$collected_parameters = null;
foreach ($symbols as $symbol) {
$parameters = $symbol->getAtom()->getProperty('parameters');
if ($parameters !== null) {
if ($collected_parameters === null) {
$collected_parameters = array();
}
foreach ($parameters as $key => $parameter) {
if (isset($collected_parameters[$key])) {
$collected_parameters[$key] += $parameter;
} else {
$collected_parameters[$key] = $parameter;
}
}
}
}
if (nonempty($parameters)) {
$out[] = id(new DivinerParameterTableView())
->setHeader(pht('Parameters'))
->setParameters($parameters);
}
$collected_return = null;
foreach ($symbols as $symbol) {
$return = $symbol->getAtom()->getProperty('return');
if ($return) {
if ($collected_return) {
$collected_return += $return;
} else {
$collected_return = $return;
}
}
}
if (nonempty($return)) {
$out[] = id(new DivinerReturnTableView())
->setHeader(pht('Return'))
->setReturn($collected_return);
}
return $out;
}
private function renderDocumentationText(
DivinerLiveSymbol $symbol,
PhabricatorMarkupEngine $engine) {
$field = 'default';
$content = $engine->getOutput($symbol, $field);
if (strlen(trim($symbol->getMarkupText($field)))) {
$content = phutil_tag(
'div',
array(
'class' => 'phabricator-remarkup diviner-remarkup-section',
),
$content);
} else {
$atom = $symbol->getAtom();
$content = phutil_tag(
'div',
array(
'class' => 'diviner-message-not-documented',
),
DivinerAtom::getThisAtomIsNotDocumentedString($atom->getType()));
}
return $content;
}
private function renderMethodDocumentationText(
DivinerLiveSymbol $parent,
array $spec,
PhabricatorMarkupEngine $engine) {
$symbols = array_values($spec['atoms']);
$implementations = array_values($spec['implementations']);
$field = 'default';
$out = array();
foreach ($symbols as $key => $symbol) {
$impl = $implementations[$key];
if ($impl !== $parent) {
if (!strlen(trim($symbol->getMarkupText($field)))) {
continue;
}
}
$doc = $this->renderDocumentationText($symbol, $engine);
if (($impl !== $parent) || $out) {
$where = id(new PHUIBoxView())
->addClass('diviner-method-implementation-header')
->appendChild($impl->getName());
$doc = array($where, $doc);
if ($impl !== $parent) {
$doc = phutil_tag(
'div',
array(
'class' => 'diviner-method-implementation-inherited',
),
$doc);
}
}
$out[] = $doc;
}
// If we only have inherited implementations but none have documentation,
// render the last one here so we get the "this thing has no documentation"
// element.
if (!$out) {
$out[] = $this->renderDocumentationText($symbol, $engine);
}
return $out;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/controller/DivinerMainController.php | src/applications/diviner/controller/DivinerMainController.php | <?php
final class DivinerMainController extends DivinerController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$books = id(new DivinerBookQuery())
->setViewer($viewer)
->execute();
$crumbs = $this->buildApplicationCrumbs();
$crumbs->setBorder(true);
$crumbs->addTextCrumb(pht('Books'));
$query_button = id(new PHUIButtonView())
->setTag('a')
->setHref($this->getApplicationURI('query/'))
->setText(pht('Advanced Search'))
->setIcon('fa-search');
$header = id(new PHUIHeaderView())
->setHeader(pht('Documentation Books'))
->addActionLink($query_button);
$document = new PHUIDocumentView();
$document->setHeader($header);
$document->addClass('diviner-view');
if ($books) {
$books = msort($books, 'getTitle');
$list = array();
foreach ($books as $book) {
$item = id(new DivinerBookItemView())
->setTitle($book->getTitle())
->setHref('/book/'.$book->getName().'/')
->setSubtitle($book->getPreface());
$list[] = $item;
}
$list = id(new PHUIBoxView())
->addPadding(PHUI::PADDING_MEDIUM_TOP)
->appendChild($list);
$document->appendChild($list);
} else {
$text = pht(
"(NOTE) **Looking for documentation?** ".
"If you're looking for help and information about %s, ".
"you can [[https://secure.phabricator.com/diviner/ | ".
"browse the public %s documentation]] on the live site.\n\n".
"Diviner is the documentation generator used to build this ".
"documentation.\n\n".
"You haven't generated any Diviner documentation books yet, so ".
"there's nothing to show here. If you'd like to generate your own ".
"local copy of the documentation and have it appear ".
"here, run this command:\n\n".
" %s\n\n",
PlatformSymbols::getPlatformServerName(),
PlatformSymbols::getPlatformServerName(),
'$ ./bin/diviner generate');
$text = new PHUIRemarkupView($viewer, $text);
$document->appendChild($text);
}
return $this->newPage()
->setTitle(pht('Documentation Books'))
->setCrumbs($crumbs)
->appendChild(array(
$document,
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/controller/DivinerBookEditController.php | src/applications/diviner/controller/DivinerBookEditController.php | <?php
final class DivinerBookEditController extends DivinerController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$book_name = $request->getURIData('book');
$book = id(new DivinerBookQuery())
->setViewer($viewer)
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->needProjectPHIDs(true)
->withNames(array($book_name))
->executeOne();
if (!$book) {
return new Aphront404Response();
}
$view_uri = '/book/'.$book->getName().'/';
if ($request->isFormPost()) {
$v_projects = $request->getArr('projectPHIDs');
$v_view = $request->getStr('viewPolicy');
$v_edit = $request->getStr('editPolicy');
$xactions = array();
$xactions[] = id(new DivinerLiveBookTransaction())
->setTransactionType(PhabricatorTransactions::TYPE_EDGE)
->setMetadataValue(
'edge:type',
PhabricatorProjectObjectHasProjectEdgeType::EDGECONST)
->setNewValue(
array(
'=' => array_fuse($v_projects),
));
$xactions[] = id(new DivinerLiveBookTransaction())
->setTransactionType(PhabricatorTransactions::TYPE_VIEW_POLICY)
->setNewValue($v_view);
$xactions[] = id(new DivinerLiveBookTransaction())
->setTransactionType(PhabricatorTransactions::TYPE_EDIT_POLICY)
->setNewValue($v_edit);
id(new DivinerLiveBookEditor())
->setContinueOnNoEffect(true)
->setContentSourceFromRequest($request)
->setActor($viewer)
->applyTransactions($book, $xactions);
return id(new AphrontRedirectResponse())->setURI($view_uri);
}
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb(pht('Edit Basics'));
$crumbs->setBorder(true);
$title = pht('Edit Book: %s', $book->getTitle());
$header_icon = 'fa-pencil';
$policies = id(new PhabricatorPolicyQuery())
->setViewer($viewer)
->setObject($book)
->execute();
$view_capability = PhabricatorPolicyCapability::CAN_VIEW;
$edit_capability = PhabricatorPolicyCapability::CAN_EDIT;
$form = id(new AphrontFormView())
->setUser($viewer)
->appendControl(
id(new AphrontFormTokenizerControl())
->setDatasource(new PhabricatorProjectDatasource())
->setName('projectPHIDs')
->setLabel(pht('Tags'))
->setValue($book->getProjectPHIDs()))
->appendControl(
id(new AphrontFormTokenizerControl())
->setDatasource(new DiffusionRepositoryDatasource())
->setName('repositoryPHIDs')
->setLabel(pht('Repository'))
->setDisableBehavior(true)
->setLimit(1)
->setValue($book->getRepositoryPHID()
? array($book->getRepositoryPHID())
: null))
->appendChild(
id(new AphrontFormPolicyControl())
->setName('viewPolicy')
->setPolicyObject($book)
->setCapability($view_capability)
->setPolicies($policies))
->appendChild(
id(new AphrontFormPolicyControl())
->setName('editPolicy')
->setPolicyObject($book)
->setCapability($edit_capability)
->setPolicies($policies))
->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Save'))
->addCancelButton($view_uri));
$box = id(new PHUIObjectBoxView())
->setHeaderText(pht('Book'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setForm($form);
$timeline = $this->buildTransactionTimeline(
$book,
new DivinerLiveBookTransactionQuery());
$timeline->setShouldTerminate(true);
$header = id(new PHUIHeaderView())
->setHeader($title)
->setHeaderIcon($header_icon);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setFooter(array(
$box,
$timeline,
));
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/diviner/controller/DivinerBookController.php | src/applications/diviner/controller/DivinerBookController.php | <?php
final class DivinerBookController extends DivinerController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$book_name = $request->getURIData('book');
$book = id(new DivinerBookQuery())
->setViewer($viewer)
->withNames(array($book_name))
->needRepositories(true)
->executeOne();
if (!$book) {
return new Aphront404Response();
}
$actions = $this->buildActionView($viewer, $book);
$crumbs = $this->buildApplicationCrumbs();
$crumbs->setBorder(true);
$crumbs->addTextCrumb(
$book->getShortTitle(),
'/book/'.$book->getName().'/');
$header = id(new PHUIHeaderView())
->setHeader($book->getTitle())
->setUser($viewer)
->setPolicyObject($book)
->setEpoch($book->getDateModified())
->setActionList($actions);
// TODO: This could probably look better.
if ($book->getRepositoryPHID()) {
$header->addTag(
id(new PHUITagView())
->setType(PHUITagView::TYPE_STATE)
->setBackgroundColor(PHUITagView::COLOR_BLUE)
->setName($book->getRepository()->getMonogram()));
}
$document = new PHUIDocumentView();
$document->setHeader($header);
$document->addClass('diviner-view');
$atoms = id(new DivinerAtomQuery())
->setViewer($viewer)
->withBookPHIDs(array($book->getPHID()))
->withGhosts(false)
->withIsDocumentable(true)
->execute();
$atoms = msort($atoms, 'getSortKey');
$group_spec = $book->getConfig('groups');
if (!is_array($group_spec)) {
$group_spec = array();
}
$groups = mgroup($atoms, 'getGroupName');
$groups = array_select_keys($groups, array_keys($group_spec)) + $groups;
if (isset($groups[''])) {
$no_group = $groups[''];
unset($groups['']);
$groups[''] = $no_group;
}
$out = array();
foreach ($groups as $group => $atoms) {
$group_name = $book->getGroupName($group);
if (!strlen($group_name)) {
$group_name = pht('Free Radicals');
}
$section = id(new DivinerSectionView())
->setHeader($group_name);
$section->addContent($this->renderAtomList($atoms));
$out[] = $section;
}
$preface = $book->getPreface();
$preface_view = null;
if (strlen($preface)) {
$preface_view = new PHUIRemarkupView($viewer, $preface);
}
$document->appendChild($preface_view);
$document->appendChild($out);
return $this->newPage()
->setTitle($book->getTitle())
->setCrumbs($crumbs)
->appendChild(array(
$document,
));
}
private function buildActionView(
PhabricatorUser $user,
DivinerLiveBook $book) {
$can_edit = PhabricatorPolicyFilter::hasCapability(
$user,
$book,
PhabricatorPolicyCapability::CAN_EDIT);
$action_view = id(new PhabricatorActionListView())
->setUser($user)
->setObject($book);
$action_view->addAction(
id(new PhabricatorActionView())
->setName(pht('Edit Book'))
->setIcon('fa-pencil')
->setHref('/book/'.$book->getName().'/edit/')
->setDisabled(!$can_edit));
return $action_view;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/renderer/DivinerDefaultRenderer.php | src/applications/diviner/renderer/DivinerDefaultRenderer.php | <?php
final class DivinerDefaultRenderer extends DivinerRenderer {
public function renderAtom(DivinerAtom $atom) {
$out = array(
$this->renderAtomTitle($atom),
$this->renderAtomProperties($atom),
$this->renderAtomDescription($atom),
);
return phutil_tag(
'div',
array(
'class' => 'diviner-atom',
),
$out);
}
protected function renderAtomTitle(DivinerAtom $atom) {
$name = $this->renderAtomName($atom);
$type = $this->renderAtomType($atom);
return phutil_tag(
'h1',
array(
'class' => 'atom-title',
),
array($name, ' ', $type));
}
protected function renderAtomName(DivinerAtom $atom) {
return phutil_tag(
'div',
array(
'class' => 'atom-name',
),
$this->getAtomName($atom));
}
protected function getAtomName(DivinerAtom $atom) {
if ($atom->getDocblockMetaValue('title')) {
return $atom->getDocblockMetaValue('title');
}
return $atom->getName();
}
protected function renderAtomType(DivinerAtom $atom) {
return phutil_tag(
'div',
array(
'class' => 'atom-name',
),
$this->getAtomType($atom));
}
protected function getAtomType(DivinerAtom $atom) {
return ucwords($atom->getType());
}
protected function renderAtomProperties(DivinerAtom $atom) {
$props = $this->getAtomProperties($atom);
$out = array();
foreach ($props as $prop) {
list($key, $value) = $prop;
$out[] = phutil_tag('dt', array(), $key);
$out[] = phutil_tag('dd', array(), $value);
}
return phutil_tag(
'dl',
array(
'class' => 'atom-properties',
),
$out);
}
protected function getAtomProperties(DivinerAtom $atom) {
$properties = array();
$properties[] = array(
pht('Defined'),
$atom->getFile().':'.$atom->getLine(),
);
return $properties;
}
protected function renderAtomDescription(DivinerAtom $atom) {
$text = $this->getAtomDescription($atom);
$engine = $this->getBlockMarkupEngine();
$this->pushAtomStack($atom);
$description = $engine->markupText($text);
$this->popAtomStack();
return phutil_tag(
'div',
array(
'class' => 'atom-description',
),
$description);
}
protected function getAtomDescription(DivinerAtom $atom) {
return $atom->getDocblockText();
}
public function renderAtomSummary(DivinerAtom $atom) {
$text = $this->getAtomSummary($atom);
$engine = $this->getInlineMarkupEngine();
$this->pushAtomStack($atom);
$summary = $engine->markupText($text);
$this->popAtomStack();
return phutil_tag(
'span',
array(
'class' => 'atom-summary',
),
$summary);
}
public function getAtomSummary(DivinerAtom $atom) {
if ($atom->getDocblockMetaValue('summary')) {
return $atom->getDocblockMetaValue('summary');
}
$text = $this->getAtomDescription($atom);
return PhabricatorMarkupEngine::summarize($text);
}
public function renderAtomIndex(array $refs) {
$refs = msort($refs, 'getSortKey');
$groups = mgroup($refs, 'getGroup');
$out = array();
foreach ($groups as $group_key => $refs) {
$out[] = phutil_tag(
'h1',
array(
'class' => 'atom-group-name',
),
$this->getGroupName($group_key));
$items = array();
foreach ($refs as $ref) {
$items[] = phutil_tag(
'li',
array(
'class' => 'atom-index-item',
),
array(
$this->renderAtomRefLink($ref),
' - ',
$ref->getSummary(),
));
}
$out[] = phutil_tag(
'ul',
array(
'class' => 'atom-index-list',
),
$items);
}
return phutil_tag(
'div',
array(
'class' => 'atom-index',
),
$out);
}
protected function getGroupName($group_key) {
return $group_key;
}
protected function getBlockMarkupEngine() {
$engine = PhabricatorMarkupEngine::newMarkupEngine(array());
$engine->setConfig('preserve-linebreaks', false);
$engine->setConfig('viewer', new PhabricatorUser());
$engine->setConfig('diviner.renderer', $this);
$engine->setConfig('header.generate-toc', true);
return $engine;
}
protected function getInlineMarkupEngine() {
return $this->getBlockMarkupEngine();
}
public function normalizeAtomRef(DivinerAtomRef $ref) {
if (!strlen($ref->getBook())) {
$ref->setBook($this->getConfig('name'));
}
if ($ref->getBook() != $this->getConfig('name')) {
// If the ref is from a different book, we can't normalize it.
// Just return it as-is if it has enough information to resolve.
if ($ref->getName() && $ref->getType()) {
return $ref;
} else {
return null;
}
}
$atom = $this->getPublisher()->findAtomByRef($ref);
if ($atom) {
return $atom->getRef();
}
return null;
}
protected function getAtomHrefDepth(DivinerAtom $atom) {
if ($atom->getContext()) {
return 4;
} else {
return 3;
}
}
public function getHrefForAtomRef(DivinerAtomRef $ref) {
$depth = 1;
$atom = $this->peekAtomStack();
if ($atom) {
$depth = $this->getAtomHrefDepth($atom);
}
$href = str_repeat('../', $depth);
$book = $ref->getBook();
$type = $ref->getType();
$name = $ref->getName();
$context = $ref->getContext();
$href .= $book.'/'.$type.'/';
if ($context !== null) {
$href .= $context.'/';
}
$href .= $name.'/index.html';
return $href;
}
protected function renderAtomRefLink(DivinerAtomRef $ref) {
return phutil_tag(
'a',
array(
'href' => $this->getHrefForAtomRef($ref),
),
$ref->getTitle());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/renderer/DivinerRenderer.php | src/applications/diviner/renderer/DivinerRenderer.php | <?php
abstract class DivinerRenderer extends Phobject {
private $publisher;
private $atomStack = array();
public function setPublisher($publisher) {
$this->publisher = $publisher;
return $this;
}
public function getPublisher() {
return $this->publisher;
}
public function getConfig($key, $default = null) {
return $this->getPublisher()->getConfig($key, $default);
}
protected function pushAtomStack(DivinerAtom $atom) {
$this->atomStack[] = $atom;
return $this;
}
protected function peekAtomStack() {
return end($this->atomStack);
}
protected function popAtomStack() {
array_pop($this->atomStack);
return $this;
}
abstract public function renderAtom(DivinerAtom $atom);
abstract public function renderAtomSummary(DivinerAtom $atom);
abstract public function renderAtomIndex(array $refs);
abstract public function getHrefForAtomRef(DivinerAtomRef $ref);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/storage/DivinerLiveAtom.php | src/applications/diviner/storage/DivinerLiveAtom.php | <?php
final class DivinerLiveAtom extends DivinerDAO {
protected $symbolPHID;
protected $content;
protected $atomData;
protected function getConfiguration() {
return array(
self::CONFIG_TIMESTAMPS => false,
self::CONFIG_SERIALIZATION => array(
'content' => self::SERIALIZATION_JSON,
'atomData' => self::SERIALIZATION_JSON,
),
self::CONFIG_KEY_SCHEMA => array(
'symbolPHID' => array(
'columns' => array('symbolPHID'),
'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/diviner/storage/DivinerLiveBookTransaction.php | src/applications/diviner/storage/DivinerLiveBookTransaction.php | <?php
final class DivinerLiveBookTransaction
extends PhabricatorApplicationTransaction {
public function getApplicationName() {
return 'diviner';
}
public function getApplicationTransactionType() {
return DivinerBookPHIDType::TYPECONST;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/storage/DivinerLiveSymbol.php | src/applications/diviner/storage/DivinerLiveSymbol.php | <?php
final class DivinerLiveSymbol extends DivinerDAO
implements
PhabricatorPolicyInterface,
PhabricatorMarkupInterface,
PhabricatorDestructibleInterface,
PhabricatorFulltextInterface {
protected $bookPHID;
protected $repositoryPHID;
protected $context;
protected $type;
protected $name;
protected $atomIndex;
protected $graphHash;
protected $identityHash;
protected $nodeHash;
protected $title;
protected $titleSlugHash;
protected $groupName;
protected $summary;
protected $isDocumentable = 0;
private $book = self::ATTACHABLE;
private $repository = self::ATTACHABLE;
private $atom = self::ATTACHABLE;
private $extends = self::ATTACHABLE;
private $children = self::ATTACHABLE;
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_TIMESTAMPS => false,
self::CONFIG_COLUMN_SCHEMA => array(
'context' => 'text255?',
'type' => 'text32',
'name' => 'text255',
'atomIndex' => 'uint32',
'identityHash' => 'bytes12',
'graphHash' => 'text64?',
'title' => 'text?',
'titleSlugHash' => 'bytes12?',
'groupName' => 'text255?',
'summary' => 'text?',
'isDocumentable' => 'bool',
'nodeHash' => 'text64?',
'repositoryPHID' => 'phid?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_phid' => null,
'identityHash' => array(
'columns' => array('identityHash'),
'unique' => true,
),
'phid' => array(
'columns' => array('phid'),
'unique' => true,
),
'graphHash' => array(
'columns' => array('graphHash'),
'unique' => true,
),
'nodeHash' => array(
'columns' => array('nodeHash'),
'unique' => true,
),
'bookPHID' => array(
'columns' => array(
'bookPHID',
'type',
'name(64)',
'context(64)',
'atomIndex',
),
),
'name' => array(
'columns' => array('name(64)'),
),
'key_slug' => array(
'columns' => array('titleSlugHash'),
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(DivinerAtomPHIDType::TYPECONST);
}
public function getBook() {
return $this->assertAttached($this->book);
}
public function attachBook(DivinerLiveBook $book) {
$this->book = $book;
return $this;
}
public function getRepository() {
return $this->assertAttached($this->repository);
}
public function attachRepository(PhabricatorRepository $repository = null) {
$this->repository = $repository;
return $this;
}
public function getAtom() {
return $this->assertAttached($this->atom);
}
public function attachAtom(DivinerLiveAtom $atom = null) {
if ($atom === null) {
$this->atom = null;
} else {
$this->atom = DivinerAtom::newFromDictionary($atom->getAtomData());
}
return $this;
}
public function getURI() {
$parts = array(
'book',
$this->getBook()->getName(),
$this->getType(),
);
if ($this->getContext()) {
$parts[] = $this->getContext();
}
$parts[] = $this->getName();
if ($this->getAtomIndex()) {
$parts[] = $this->getAtomIndex();
}
return '/'.implode('/', $parts).'/';
}
public function getSortKey() {
// Sort articles before other types of content. Then, sort atoms in a
// case-insensitive way.
return sprintf(
'%c:%s',
($this->getType() == DivinerAtom::TYPE_ARTICLE ? '0' : '1'),
phutil_utf8_strtolower($this->getTitle()));
}
public function save() {
// NOTE: The identity hash is just a sanity check because the unique tuple
// on this table is way too long to fit into a normal `UNIQUE KEY`.
// We don't use it directly, but its existence prevents duplicate records.
if (!$this->identityHash) {
$this->identityHash = PhabricatorHash::digestForIndex(
serialize(
array(
'bookPHID' => $this->getBookPHID(),
'context' => $this->getContext(),
'type' => $this->getType(),
'name' => $this->getName(),
'index' => $this->getAtomIndex(),
)));
}
return parent::save();
}
public function getTitle() {
$title = parent::getTitle();
if (!strlen($title)) {
$title = $this->getName();
}
return $title;
}
public function setTitle($value) {
$this->writeField('title', $value);
if ($value !== null && strlen($value)) {
$slug = DivinerAtomRef::normalizeTitleString($value);
$hash = PhabricatorHash::digestForIndex($slug);
$this->titleSlugHash = $hash;
} else {
$this->titleSlugHash = null;
}
return $this;
}
public function attachExtends(array $extends) {
assert_instances_of($extends, __CLASS__);
$this->extends = $extends;
return $this;
}
public function getExtends() {
return $this->assertAttached($this->extends);
}
public function attachChildren(array $children) {
assert_instances_of($children, __CLASS__);
$this->children = $children;
return $this;
}
public function getChildren() {
return $this->assertAttached($this->children);
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return $this->getBook()->getCapabilities();
}
public function getPolicy($capability) {
return $this->getBook()->getPolicy($capability);
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return $this->getBook()->hasAutomaticCapability($capability, $viewer);
}
public function describeAutomaticCapability($capability) {
return pht('Atoms inherit the policies of the books they are part of.');
}
/* -( PhabricatorMarkupInterface )------------------------------------------ */
public function getMarkupFieldKey($field) {
return $this->getPHID().':'.$field.':'.$this->getGraphHash();
}
public function newMarkupEngine($field) {
return PhabricatorMarkupEngine::getEngine('diviner');
}
public function getMarkupText($field) {
if (!$this->getAtom()) {
return;
}
return $this->getAtom()->getDocblockText();
}
public function didMarkupText($field, $output, PhutilMarkupEngine $engine) {
return $output;
}
public function shouldUseMarkupCache($field) {
return true;
}
/* -( PhabricatorDestructibleInterface )----------------------------------- */
public function destroyObjectPermanently(
PhabricatorDestructionEngine $engine) {
$this->openTransaction();
$conn_w = $this->establishConnection('w');
queryfx(
$conn_w,
'DELETE FROM %T WHERE symbolPHID = %s',
id(new DivinerLiveAtom())->getTableName(),
$this->getPHID());
$this->delete();
$this->saveTransaction();
}
/* -( PhabricatorFulltextInterface )--------------------------------------- */
public function newFulltextEngine() {
if (!$this->getIsDocumentable()) {
return null;
}
return new DivinerLiveSymbolFulltextEngine();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/storage/DivinerSchemaSpec.php | src/applications/diviner/storage/DivinerSchemaSpec.php | <?php
final class DivinerSchemaSpec extends PhabricatorConfigSchemaSpec {
public function buildSchemata() {
$this->buildEdgeSchemata(new DivinerLiveBook());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/storage/DivinerLiveBook.php | src/applications/diviner/storage/DivinerLiveBook.php | <?php
final class DivinerLiveBook extends DivinerDAO
implements
PhabricatorPolicyInterface,
PhabricatorProjectInterface,
PhabricatorDestructibleInterface,
PhabricatorApplicationTransactionInterface,
PhabricatorFulltextInterface {
protected $name;
protected $repositoryPHID;
protected $viewPolicy;
protected $editPolicy;
protected $configurationData = array();
private $projectPHIDs = self::ATTACHABLE;
private $repository = self::ATTACHABLE;
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_SERIALIZATION => array(
'configurationData' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'name' => 'text64',
'repositoryPHID' => 'phid?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_phid' => null,
'phid' => array(
'columns' => array('phid'),
'unique' => true,
),
'name' => array(
'columns' => array('name'),
'unique' => true,
),
),
) + parent::getConfiguration();
}
public function getConfig($key, $default = null) {
return idx($this->configurationData, $key, $default);
}
public function setConfig($key, $value) {
$this->configurationData[$key] = $value;
return $this;
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(DivinerBookPHIDType::TYPECONST);
}
public function getTitle() {
return $this->getConfig('title', $this->getName());
}
public function getShortTitle() {
return $this->getConfig('short', $this->getTitle());
}
public function getPreface() {
return $this->getConfig('preface');
}
public function getGroupName($group) {
$groups = $this->getConfig('groups', array());
$spec = idx($groups, $group, array());
return idx($spec, 'name', $group);
}
public function attachRepository(PhabricatorRepository $repository = null) {
$this->repository = $repository;
return $this;
}
public function getRepository() {
return $this->assertAttached($this->repository);
}
public function attachProjectPHIDs(array $project_phids) {
$this->projectPHIDs = $project_phids;
return $this;
}
public function getProjectPHIDs() {
return $this->assertAttached($this->projectPHIDs);
}
/* -( 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) {
return false;
}
/* -( PhabricatorDestructibleInterface )----------------------------------- */
public function destroyObjectPermanently(
PhabricatorDestructionEngine $engine) {
$this->openTransaction();
$atoms = id(new DivinerAtomQuery())
->setViewer($engine->getViewer())
->withBookPHIDs(array($this->getPHID()))
->execute();
foreach ($atoms as $atom) {
$engine->destroyObject($atom);
}
$this->delete();
$this->saveTransaction();
}
/* -( PhabricatorApplicationTransactionInterface )------------------------- */
public function getApplicationTransactionEditor() {
return new DivinerLiveBookEditor();
}
public function getApplicationTransactionTemplate() {
return new DivinerLiveBookTransaction();
}
/* -( PhabricatorFulltextInterface )--------------------------------------- */
public function newFulltextEngine() {
return new DivinerLiveBookFulltextEngine();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/storage/DivinerDAO.php | src/applications/diviner/storage/DivinerDAO.php | <?php
abstract class DivinerDAO extends PhabricatorLiskDAO {
public function getApplicationName() {
return 'diviner';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/query/DivinerLiveBookTransactionQuery.php | src/applications/diviner/query/DivinerLiveBookTransactionQuery.php | <?php
final class DivinerLiveBookTransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new DivinerLiveBookTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/query/DivinerAtomSearchEngine.php | src/applications/diviner/query/DivinerAtomSearchEngine.php | <?php
final class DivinerAtomSearchEngine extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Documentation Atoms');
}
public function getApplicationClassName() {
return 'PhabricatorDivinerApplication';
}
public function canUseInPanelContext() {
return false;
}
public function buildSavedQueryFromRequest(AphrontRequest $request) {
$saved = new PhabricatorSavedQuery();
$saved->setParameter(
'bookPHIDs',
$this->readPHIDsFromRequest($request, 'bookPHIDs'));
$saved->setParameter(
'repositoryPHIDs',
$this->readPHIDsFromRequest($request, 'repositoryPHIDs'));
$saved->setParameter('name', $request->getStr('name'));
$saved->setParameter(
'types',
$this->readListFromRequest($request, 'types'));
return $saved;
}
public function buildQueryFromSavedQuery(PhabricatorSavedQuery $saved) {
$query = id(new DivinerAtomQuery());
$books = $saved->getParameter('bookPHIDs');
if ($books) {
$query->withBookPHIDs($books);
}
$repository_phids = $saved->getParameter('repositoryPHIDs');
if ($repository_phids) {
$query->withRepositoryPHIDs($repository_phids);
}
$name = $saved->getParameter('name');
if ($name) {
$query->withNameContains($name);
}
$types = $saved->getParameter('types');
if ($types) {
$query->withTypes($types);
}
return $query;
}
public function buildSearchForm(
AphrontFormView $form,
PhabricatorSavedQuery $saved) {
$form->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Name Contains'))
->setName('name')
->setValue($saved->getParameter('name')));
$all_types = array();
foreach (DivinerAtom::getAllTypes() as $type) {
$all_types[$type] = DivinerAtom::getAtomTypeNameString($type);
}
asort($all_types);
$types = $saved->getParameter('types', array());
$types = array_fuse($types);
$type_control = id(new AphrontFormCheckboxControl())
->setLabel(pht('Types'));
foreach ($all_types as $type => $name) {
$type_control->addCheckbox(
'types[]',
$type,
$name,
isset($types[$type]));
}
$form->appendChild($type_control);
$form->appendControl(
id(new AphrontFormTokenizerControl())
->setDatasource(new DivinerBookDatasource())
->setName('bookPHIDs')
->setLabel(pht('Books'))
->setValue($saved->getParameter('bookPHIDs')));
$form->appendControl(
id(new AphrontFormTokenizerControl())
->setLabel(pht('Repositories'))
->setName('repositoryPHIDs')
->setDatasource(new DiffusionRepositoryDatasource())
->setValue($saved->getParameter('repositoryPHIDs')));
}
protected function getURI($path) {
return '/diviner/'.$path;
}
protected function getBuiltinQueryNames() {
return array(
'all' => pht('All Atoms'),
);
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $symbols,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($symbols, 'DivinerLiveSymbol');
$viewer = $this->requireViewer();
$list = id(new PHUIObjectItemListView())
->setUser($viewer);
foreach ($symbols as $symbol) {
$type = $symbol->getType();
$type_name = DivinerAtom::getAtomTypeNameString($type);
$item = id(new PHUIObjectItemView())
->setHeader($symbol->getTitle())
->setHref($symbol->getURI())
->addAttribute($symbol->getSummary())
->addIcon('none', $type_name);
$list->addItem($item);
}
$result = new PhabricatorApplicationSearchResultView();
$result->setObjectList($list);
$result->setNoDataString(pht('No books found.'));
return $result;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/query/DivinerBookQuery.php | src/applications/diviner/query/DivinerBookQuery.php | <?php
final class DivinerBookQuery extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $names;
private $nameLike;
private $namePrefix;
private $repositoryPHIDs;
private $needProjectPHIDs;
private $needRepositories;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withNameLike($name) {
$this->nameLike = $name;
return $this;
}
public function withNames(array $names) {
$this->names = $names;
return $this;
}
public function withNamePrefix($prefix) {
$this->namePrefix = $prefix;
return $this;
}
public function withRepositoryPHIDs(array $repository_phids) {
$this->repositoryPHIDs = $repository_phids;
return $this;
}
public function needProjectPHIDs($need_phids) {
$this->needProjectPHIDs = $need_phids;
return $this;
}
public function needRepositories($need_repositories) {
$this->needRepositories = $need_repositories;
return $this;
}
protected function loadPage() {
$table = new DivinerLiveBook();
$conn_r = $table->establishConnection('r');
$data = queryfx_all(
$conn_r,
'SELECT * FROM %T %Q %Q %Q',
$table->getTableName(),
$this->buildWhereClause($conn_r),
$this->buildOrderClause($conn_r),
$this->buildLimitClause($conn_r));
return $table->loadAllFromArray($data);
}
protected function didFilterPage(array $books) {
assert_instances_of($books, 'DivinerLiveBook');
if ($this->needRepositories) {
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($this->getViewer())
->withPHIDs(mpull($books, 'getRepositoryPHID'))
->execute();
$repositories = mpull($repositories, null, 'getPHID');
foreach ($books as $key => $book) {
if ($book->getRepositoryPHID() === null) {
$book->attachRepository(null);
continue;
}
$repository = idx($repositories, $book->getRepositoryPHID());
if (!$repository) {
$this->didRejectResult($book);
unset($books[$key]);
continue;
}
$book->attachRepository($repository);
}
}
if ($this->needProjectPHIDs) {
$edge_query = id(new PhabricatorEdgeQuery())
->withSourcePHIDs(mpull($books, 'getPHID'))
->withEdgeTypes(
array(
PhabricatorProjectObjectHasProjectEdgeType::EDGECONST,
));
$edge_query->execute();
foreach ($books as $book) {
$project_phids = $edge_query->getDestinationPHIDs(
array(
$book->getPHID(),
));
$book->attachProjectPHIDs($project_phids);
}
}
return $books;
}
protected function buildWhereClause(AphrontDatabaseConnection $conn) {
$where = array();
if ($this->ids) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->nameLike !== null && strlen($this->nameLike)) {
$where[] = qsprintf(
$conn,
'name LIKE %~',
$this->nameLike);
}
if ($this->names !== null) {
$where[] = qsprintf(
$conn,
'name IN (%Ls)',
$this->names);
}
if ($this->namePrefix !== null && strlen($this->namePrefix)) {
$where[] = qsprintf(
$conn,
'name LIKE %>',
$this->namePrefix);
}
if ($this->repositoryPHIDs !== null) {
$where[] = qsprintf(
$conn,
'repositoryPHID IN (%Ls)',
$this->repositoryPHIDs);
}
$where[] = $this->buildPagingClause($conn);
return $this->formatWhereClause($conn, $where);
}
public function getQueryApplicationClass() {
return 'PhabricatorDivinerApplication';
}
public function getOrderableColumns() {
return parent::getOrderableColumns() + array(
'name' => array(
'column' => 'name',
'type' => 'string',
'reverse' => true,
'unique' => true,
),
);
}
protected function newPagingMapFromPartialObject($object) {
return array(
'id' => (int)$object->getID(),
'name' => $object->getName(),
);
}
public function getBuiltinOrders() {
return array(
'name' => array(
'vector' => array('name'),
'name' => pht('Name'),
),
) + parent::getBuiltinOrders();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/query/DivinerAtomQuery.php | src/applications/diviner/query/DivinerAtomQuery.php | <?php
final class DivinerAtomQuery extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $bookPHIDs;
private $names;
private $types;
private $contexts;
private $indexes;
private $isDocumentable;
private $isGhost;
private $nodeHashes;
private $titles;
private $nameContains;
private $repositoryPHIDs;
private $needAtoms;
private $needExtends;
private $needChildren;
private $needRepositories;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withBookPHIDs(array $phids) {
$this->bookPHIDs = $phids;
return $this;
}
public function withTypes(array $types) {
$this->types = $types;
return $this;
}
public function withNames(array $names) {
$this->names = $names;
return $this;
}
public function withContexts(array $contexts) {
$this->contexts = $contexts;
return $this;
}
public function withIndexes(array $indexes) {
$this->indexes = $indexes;
return $this;
}
public function withNodeHashes(array $hashes) {
$this->nodeHashes = $hashes;
return $this;
}
public function withTitles($titles) {
$this->titles = $titles;
return $this;
}
public function withNameContains($text) {
$this->nameContains = $text;
return $this;
}
public function needAtoms($need) {
$this->needAtoms = $need;
return $this;
}
public function needChildren($need) {
$this->needChildren = $need;
return $this;
}
/**
* Include or exclude "ghosts", which are symbols which used to exist but do
* not exist currently (for example, a function which existed in an older
* version of the codebase but was deleted).
*
* These symbols had PHIDs assigned to them, and may have other sorts of
* metadata that we don't want to lose (like comments or flags), so we don't
* delete them outright. They might also come back in the future: the change
* which deleted the symbol might be reverted, or the documentation might
* have been generated incorrectly by accident. In these cases, we can
* restore the original data.
*
* @param bool
* @return this
*/
public function withGhosts($ghosts) {
$this->isGhost = $ghosts;
return $this;
}
public function needExtends($need) {
$this->needExtends = $need;
return $this;
}
public function withIsDocumentable($documentable) {
$this->isDocumentable = $documentable;
return $this;
}
public function withRepositoryPHIDs(array $repository_phids) {
$this->repositoryPHIDs = $repository_phids;
return $this;
}
public function needRepositories($need_repositories) {
$this->needRepositories = $need_repositories;
return $this;
}
protected function loadPage() {
$table = new DivinerLiveSymbol();
$conn_r = $table->establishConnection('r');
$data = queryfx_all(
$conn_r,
'SELECT * FROM %T %Q %Q %Q',
$table->getTableName(),
$this->buildWhereClause($conn_r),
$this->buildOrderClause($conn_r),
$this->buildLimitClause($conn_r));
return $table->loadAllFromArray($data);
}
protected function willFilterPage(array $atoms) {
assert_instances_of($atoms, 'DivinerLiveSymbol');
$books = array_unique(mpull($atoms, 'getBookPHID'));
$books = id(new DivinerBookQuery())
->setViewer($this->getViewer())
->withPHIDs($books)
->execute();
$books = mpull($books, null, 'getPHID');
foreach ($atoms as $key => $atom) {
$book = idx($books, $atom->getBookPHID());
if (!$book) {
$this->didRejectResult($atom);
unset($atoms[$key]);
continue;
}
$atom->attachBook($book);
}
if ($this->needAtoms) {
$atom_data = id(new DivinerLiveAtom())->loadAllWhere(
'symbolPHID IN (%Ls)',
mpull($atoms, 'getPHID'));
$atom_data = mpull($atom_data, null, 'getSymbolPHID');
foreach ($atoms as $key => $atom) {
$data = idx($atom_data, $atom->getPHID());
$atom->attachAtom($data);
}
}
// Load all of the symbols this symbol extends, recursively. Commonly,
// this means all the ancestor classes and interfaces it extends and
// implements.
if ($this->needExtends) {
// First, load all the matching symbols by name. This does 99% of the
// work in most cases, assuming things are named at all reasonably.
$names = array();
foreach ($atoms as $atom) {
if (!$atom->getAtom()) {
continue;
}
foreach ($atom->getAtom()->getExtends() as $xref) {
$names[] = $xref->getName();
}
}
if ($names) {
$xatoms = id(new DivinerAtomQuery())
->setViewer($this->getViewer())
->withNames($names)
->withGhosts(false)
->needExtends(true)
->needAtoms(true)
->needChildren($this->needChildren)
->execute();
$xatoms = mgroup($xatoms, 'getName', 'getType', 'getBookPHID');
} else {
$xatoms = array();
}
foreach ($atoms as $atom) {
$atom_lang = null;
$atom_extends = array();
if ($atom->getAtom()) {
$atom_lang = $atom->getAtom()->getLanguage();
$atom_extends = $atom->getAtom()->getExtends();
}
$extends = array();
foreach ($atom_extends as $xref) {
// If there are no symbols of the matching name and type, we can't
// resolve this.
if (empty($xatoms[$xref->getName()][$xref->getType()])) {
continue;
}
// If we found matches in the same documentation book, prefer them
// over other matches. Otherwise, look at all the matches.
$matches = $xatoms[$xref->getName()][$xref->getType()];
if (isset($matches[$atom->getBookPHID()])) {
$maybe = $matches[$atom->getBookPHID()];
} else {
$maybe = array_mergev($matches);
}
if (!$maybe) {
continue;
}
// Filter out matches in a different language, since, e.g., PHP
// classes can not implement JS classes.
$same_lang = array();
foreach ($maybe as $xatom) {
if ($xatom->getAtom()->getLanguage() == $atom_lang) {
$same_lang[] = $xatom;
}
}
if (!$same_lang) {
continue;
}
// If we have duplicates remaining, just pick the first one. There's
// nothing more we can do to figure out which is the real one.
$extends[] = head($same_lang);
}
$atom->attachExtends($extends);
}
}
if ($this->needChildren) {
$child_hashes = $this->getAllChildHashes($atoms, $this->needExtends);
if ($child_hashes) {
$children = id(new DivinerAtomQuery())
->setViewer($this->getViewer())
->withNodeHashes($child_hashes)
->needAtoms($this->needAtoms)
->execute();
$children = mpull($children, null, 'getNodeHash');
} else {
$children = array();
}
$this->attachAllChildren($atoms, $children, $this->needExtends);
}
if ($this->needRepositories) {
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($this->getViewer())
->withPHIDs(mpull($atoms, 'getRepositoryPHID'))
->execute();
$repositories = mpull($repositories, null, 'getPHID');
foreach ($atoms as $key => $atom) {
if ($atom->getRepositoryPHID() === null) {
$atom->attachRepository(null);
continue;
}
$repository = idx($repositories, $atom->getRepositoryPHID());
if (!$repository) {
$this->didRejectResult($atom);
unset($atom[$key]);
continue;
}
$atom->attachRepository($repository);
}
}
return $atoms;
}
protected function buildWhereClause(AphrontDatabaseConnection $conn) {
$where = array();
if ($this->ids) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->bookPHIDs) {
$where[] = qsprintf(
$conn,
'bookPHID IN (%Ls)',
$this->bookPHIDs);
}
if ($this->types) {
$where[] = qsprintf(
$conn,
'type IN (%Ls)',
$this->types);
}
if ($this->names) {
$where[] = qsprintf(
$conn,
'name IN (%Ls)',
$this->names);
}
if ($this->titles) {
$hashes = array();
foreach ($this->titles as $title) {
$slug = DivinerAtomRef::normalizeTitleString($title);
$hash = PhabricatorHash::digestForIndex($slug);
$hashes[] = $hash;
}
$where[] = qsprintf(
$conn,
'titleSlugHash in (%Ls)',
$hashes);
}
if ($this->contexts) {
$with_null = false;
$contexts = $this->contexts;
foreach ($contexts as $key => $value) {
if ($value === null) {
unset($contexts[$key]);
$with_null = true;
continue;
}
}
if ($contexts && $with_null) {
$where[] = qsprintf(
$conn,
'context IN (%Ls) OR context IS NULL',
$contexts);
} else if ($contexts) {
$where[] = qsprintf(
$conn,
'context IN (%Ls)',
$contexts);
} else if ($with_null) {
$where[] = qsprintf(
$conn,
'context IS NULL');
}
}
if ($this->indexes) {
$where[] = qsprintf(
$conn,
'atomIndex IN (%Ld)',
$this->indexes);
}
if ($this->isDocumentable !== null) {
$where[] = qsprintf(
$conn,
'isDocumentable = %d',
(int)$this->isDocumentable);
}
if ($this->isGhost !== null) {
if ($this->isGhost) {
$where[] = qsprintf($conn, 'graphHash IS NULL');
} else {
$where[] = qsprintf($conn, 'graphHash IS NOT NULL');
}
}
if ($this->nodeHashes) {
$where[] = qsprintf(
$conn,
'nodeHash IN (%Ls)',
$this->nodeHashes);
}
if ($this->nameContains) {
// NOTE: This `CONVERT()` call makes queries case-insensitive, since
// the column has binary collation. Eventually, this should move into
// fulltext.
$where[] = qsprintf(
$conn,
'CONVERT(name USING utf8) LIKE %~',
$this->nameContains);
}
if ($this->repositoryPHIDs) {
$where[] = qsprintf(
$conn,
'repositoryPHID IN (%Ls)',
$this->repositoryPHIDs);
}
$where[] = $this->buildPagingClause($conn);
return $this->formatWhereClause($conn, $where);
}
/**
* Walk a list of atoms and collect all the node hashes of the atoms'
* children. When recursing, also walk up the tree and collect children of
* atoms they extend.
*
* @param list<DivinerLiveSymbol> List of symbols to collect child hashes of.
* @param bool True to collect children of extended atoms,
* as well.
* @return map<string, string> Hashes of atoms' children.
*/
private function getAllChildHashes(array $symbols, $recurse_up) {
assert_instances_of($symbols, 'DivinerLiveSymbol');
$hashes = array();
foreach ($symbols as $symbol) {
$child_hashes = array();
if ($symbol->getAtom()) {
$child_hashes = $symbol->getAtom()->getChildHashes();
}
foreach ($child_hashes as $hash) {
$hashes[$hash] = $hash;
}
if ($recurse_up) {
$hashes += $this->getAllChildHashes($symbol->getExtends(), true);
}
}
return $hashes;
}
/**
* Attach child atoms to existing atoms. In recursive mode, also attach child
* atoms to atoms that these atoms extend.
*
* @param list<DivinerLiveSymbol> List of symbols to attach children to.
* @param map<string, DivinerLiveSymbol> Map of symbols, keyed by node hash.
* @param bool True to attach children to extended atoms, as well.
* @return void
*/
private function attachAllChildren(
array $symbols,
array $children,
$recurse_up) {
assert_instances_of($symbols, 'DivinerLiveSymbol');
assert_instances_of($children, 'DivinerLiveSymbol');
foreach ($symbols as $symbol) {
$child_hashes = array();
$symbol_children = array();
if ($symbol->getAtom()) {
$child_hashes = $symbol->getAtom()->getChildHashes();
}
foreach ($child_hashes as $hash) {
if (isset($children[$hash])) {
$symbol_children[] = $children[$hash];
}
}
$symbol->attachChildren($symbol_children);
if ($recurse_up) {
$this->attachAllChildren($symbol->getExtends(), $children, true);
}
}
}
public function getQueryApplicationClass() {
return 'PhabricatorDivinerApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/cache/DivinerAtomCache.php | src/applications/diviner/cache/DivinerAtomCache.php | <?php
final class DivinerAtomCache extends DivinerDiskCache {
private $fileHashMap;
private $atomMap;
private $symbolMap;
private $edgeSrcMap;
private $edgeDstMap;
private $graphMap;
private $atoms = array();
private $writeAtoms = array();
public function __construct($cache_directory) {
parent::__construct($cache_directory, 'diviner-atom-cache');
}
public function delete() {
parent::delete();
$this->fileHashMap = null;
$this->atomMap = null;
$this->atoms = array();
return $this;
}
/* -( File Hash Map )------------------------------------------------------ */
public function getFileHashMap() {
if ($this->fileHashMap === null) {
$this->fileHashMap = $this->getCache()->getKey('file', array());
}
return $this->fileHashMap;
}
public function addFileHash($file_hash, $atom_hash) {
$this->getFileHashMap();
$this->fileHashMap[$file_hash] = $atom_hash;
return $this;
}
public function fileHashExists($file_hash) {
$map = $this->getFileHashMap();
return isset($map[$file_hash]);
}
public function deleteFileHash($file_hash) {
if ($this->fileHashExists($file_hash)) {
$map = $this->getFileHashMap();
$atom_hash = $map[$file_hash];
unset($this->fileHashMap[$file_hash]);
$this->deleteAtomHash($atom_hash);
}
return $this;
}
/* -( Atom Map )----------------------------------------------------------- */
public function getAtomMap() {
if ($this->atomMap === null) {
$this->atomMap = $this->getCache()->getKey('atom', array());
}
return $this->atomMap;
}
public function getAtom($atom_hash) {
if (!array_key_exists($atom_hash, $this->atoms)) {
$key = 'atom/'.$this->getHashKey($atom_hash);
$this->atoms[$atom_hash] = $this->getCache()->getKey($key);
}
return $this->atoms[$atom_hash];
}
public function addAtom(array $atom) {
$hash = $atom['hash'];
$this->atoms[$hash] = $atom;
$this->getAtomMap();
$this->atomMap[$hash] = true;
$this->writeAtoms['atom/'.$this->getHashKey($hash)] = $atom;
return $this;
}
public function deleteAtomHash($atom_hash) {
$atom = $this->getAtom($atom_hash);
if ($atom) {
foreach ($atom['childHashes'] as $child_hash) {
$this->deleteAtomHash($child_hash);
}
}
$this->getAtomMap();
unset($this->atomMap[$atom_hash]);
unset($this->writeAtoms[$atom_hash]);
$this->getCache()->deleteKey('atom/'.$this->getHashKey($atom_hash));
return $this;
}
public function saveAtoms() {
$this->getCache()->setKeys(
array(
'file' => $this->getFileHashMap(),
'atom' => $this->getAtomMap(),
) + $this->writeAtoms);
$this->writeAtoms = array();
return $this;
}
/* -( Symbol Hash Map )---------------------------------------------------- */
public function getSymbolMap() {
if ($this->symbolMap === null) {
$this->symbolMap = $this->getCache()->getKey('symbol', array());
}
return $this->symbolMap;
}
public function addSymbol($atom_hash, $symbol_hash) {
$this->getSymbolMap();
$this->symbolMap[$atom_hash] = $symbol_hash;
return $this;
}
public function deleteSymbol($atom_hash) {
$this->getSymbolMap();
unset($this->symbolMap[$atom_hash]);
return $this;
}
public function saveSymbols() {
$this->getCache()->setKeys(
array(
'symbol' => $this->getSymbolMap(),
));
return $this;
}
/* -( Edge Map )----------------------------------------------------------- */
public function getEdgeMap() {
if ($this->edgeDstMap === null) {
$this->edgeDstMap = $this->getCache()->getKey('edge', array());
$this->edgeSrcMap = array();
foreach ($this->edgeDstMap as $dst => $srcs) {
foreach ($srcs as $src => $ignored) {
$this->edgeSrcMap[$src][$dst] = true;
}
}
}
return $this->edgeDstMap;
}
public function getEdgesWithDestination($symbol_hash) {
$this->getEdgeMap();
return array_keys(idx($this->edgeDstMap, $symbol_hash, array()));
}
public function addEdges($node_hash, array $symbol_hash_list) {
$this->getEdgeMap();
$this->edgeSrcMap[$node_hash] = array_fill_keys($symbol_hash_list, true);
foreach ($symbol_hash_list as $symbol_hash) {
$this->edgeDstMap[$symbol_hash][$node_hash] = true;
}
return $this;
}
public function deleteEdges($node_hash) {
$this->getEdgeMap();
foreach (idx($this->edgeSrcMap, $node_hash, array()) as $dst => $ignored) {
unset($this->edgeDstMap[$dst][$node_hash]);
if (empty($this->edgeDstMap[$dst])) {
unset($this->edgeDstMap[$dst]);
}
}
unset($this->edgeSrcMap[$node_hash]);
return $this;
}
public function saveEdges() {
$this->getCache()->setKeys(
array(
'edge' => $this->getEdgeMap(),
));
return $this;
}
/* -( Graph Map )---------------------------------------------------------- */
public function getGraphMap() {
if ($this->graphMap === null) {
$this->graphMap = $this->getCache()->getKey('graph', array());
}
return $this->graphMap;
}
public function deleteGraph($node_hash) {
$this->getGraphMap();
unset($this->graphMap[$node_hash]);
return $this;
}
public function addGraph($node_hash, $graph_hash) {
$this->getGraphMap();
$this->graphMap[$node_hash] = $graph_hash;
return $this;
}
public function saveGraph() {
$this->getCache()->setKeys(
array(
'graph' => $this->getGraphMap(),
));
return $this;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/cache/DivinerDiskCache.php | src/applications/diviner/cache/DivinerDiskCache.php | <?php
abstract class DivinerDiskCache extends Phobject {
private $cache;
public function __construct($cache_directory, $name) {
$dir_cache = id(new PhutilDirectoryKeyValueCache())
->setCacheDirectory($cache_directory);
$profiled_cache = id(new PhutilKeyValueCacheProfiler($dir_cache))
->setProfiler(PhutilServiceProfiler::getInstance())
->setName($name);
$this->cache = $profiled_cache;
}
protected function getCache() {
return $this->cache;
}
public function delete() {
$this->getCache()->destroyCache();
return $this;
}
/**
* Convert a long-form hash key like `ccbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaN` into
* a shortened directory form, like `cc/bb/aaaaaaaaN`. In conjunction with
* @{class:PhutilDirectoryKeyValueCache}, this gives us nice directories
* inside `.divinercache` instead of a million hash files with huge names at
* the top level.
*/
protected function getHashKey($hash) {
return implode(
'/',
array(
substr($hash, 0, 2),
substr($hash, 2, 2),
substr($hash, 4, 8),
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/cache/DivinerPublishCache.php | src/applications/diviner/cache/DivinerPublishCache.php | <?php
final class DivinerPublishCache extends DivinerDiskCache {
private $pathMap;
private $index;
public function __construct($cache_directory) {
parent::__construct($cache_directory, 'diviner-publish-cache');
}
/* -( Path Map )----------------------------------------------------------- */
public function getPathMap() {
if ($this->pathMap === null) {
$this->pathMap = $this->getCache()->getKey('path', array());
}
return $this->pathMap;
}
public function writePathMap() {
$this->getCache()->setKey('path', $this->getPathMap());
}
public function getAtomPathsFromCache($hash) {
return idx($this->getPathMap(), $hash, array());
}
public function removeAtomPathsFromCache($hash) {
$map = $this->getPathMap();
unset($map[$hash]);
$this->pathMap = $map;
return $this;
}
public function addAtomPathsToCache($hash, array $paths) {
$map = $this->getPathMap();
$map[$hash] = $paths;
$this->pathMap = $map;
return $this;
}
/* -( Index )-------------------------------------------------------------- */
public function getIndex() {
if ($this->index === null) {
$this->index = $this->getCache()->getKey('index', array());
}
return $this->index;
}
public function writeIndex() {
$this->getCache()->setKey('index', $this->getIndex());
}
public function deleteAtomFromIndex($hash) {
$index = $this->getIndex();
unset($index[$hash]);
$this->index = $index;
return $this;
}
public function addAtomToIndex($hash, array $data) {
$index = $this->getIndex();
$index[$hash] = $data;
$this->index = $index;
return $this;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/publisher/DivinerLivePublisher.php | src/applications/diviner/publisher/DivinerLivePublisher.php | <?php
final class DivinerLivePublisher extends DivinerPublisher {
private $book;
protected function getBook() {
if (!$this->book) {
$book_name = $this->getConfig('name');
$book = id(new DivinerLiveBook())->loadOneWhere(
'name = %s',
$book_name);
if (!$book) {
$book = id(new DivinerLiveBook())
->setName($book_name)
->setViewPolicy(PhabricatorPolicies::getMostOpenPolicy())
->setEditPolicy(PhabricatorPolicies::POLICY_ADMIN)
->save();
}
$conn_w = $book->establishConnection('w');
$conn_w->openTransaction();
$book
->setRepositoryPHID($this->getRepositoryPHID())
->setConfigurationData($this->getConfigurationData())
->save();
// TODO: This is gross. Without this, the repository won't be updated for
// atoms which have already been published.
queryfx(
$conn_w,
'UPDATE %T SET repositoryPHID = %s WHERE bookPHID = %s',
id(new DivinerLiveSymbol())->getTableName(),
$this->getRepositoryPHID(),
$book->getPHID());
$conn_w->saveTransaction();
$this->book = $book;
PhabricatorSearchWorker::queueDocumentForIndexing($book->getPHID());
}
return $this->book;
}
private function loadSymbolForAtom(DivinerAtom $atom) {
$symbol = id(new DivinerAtomQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withBookPHIDs(array($this->getBook()->getPHID()))
->withTypes(array($atom->getType()))
->withNames(array($atom->getName()))
->withContexts(array($atom->getContext()))
->withIndexes(array($this->getAtomSimilarIndex($atom)))
->executeOne();
if ($symbol) {
return $symbol;
}
return id(new DivinerLiveSymbol())
->setBookPHID($this->getBook()->getPHID())
->setType($atom->getType())
->setName($atom->getName())
->setContext($atom->getContext())
->setAtomIndex($this->getAtomSimilarIndex($atom));
}
private function loadAtomStorageForSymbol(DivinerLiveSymbol $symbol) {
$storage = id(new DivinerLiveAtom())->loadOneWhere(
'symbolPHID = %s',
$symbol->getPHID());
if ($storage) {
return $storage;
}
return id(new DivinerLiveAtom())
->setSymbolPHID($symbol->getPHID());
}
protected function loadAllPublishedHashes() {
$symbols = id(new DivinerAtomQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withBookPHIDs(array($this->getBook()->getPHID()))
->withGhosts(false)
->execute();
return mpull($symbols, 'getGraphHash');
}
protected function deleteDocumentsByHash(array $hashes) {
$atom_table = new DivinerLiveAtom();
$symbol_table = new DivinerLiveSymbol();
$conn_w = $symbol_table->establishConnection('w');
$strings = array();
foreach ($hashes as $hash) {
$strings[] = qsprintf($conn_w, '%s', $hash);
}
foreach (PhabricatorLiskDAO::chunkSQL($strings) as $chunk) {
queryfx(
$conn_w,
'UPDATE %T SET graphHash = NULL, nodeHash = NULL
WHERE graphHash IN (%LQ)',
$symbol_table->getTableName(),
$chunk);
}
queryfx(
$conn_w,
'DELETE a FROM %T a LEFT JOIN %T s
ON a.symbolPHID = s.phid
WHERE s.graphHash IS NULL',
$atom_table->getTableName(),
$symbol_table->getTableName());
}
protected function createDocumentsByHash(array $hashes) {
foreach ($hashes as $hash) {
$atom = $this->getAtomFromGraphHash($hash);
$ref = $atom->getRef();
$symbol = $this->loadSymbolForAtom($atom);
$is_documentable = $this->shouldGenerateDocumentForAtom($atom);
$symbol
->setRepositoryPHID($this->getRepositoryPHID())
->setGraphHash($hash)
->setIsDocumentable((int)$is_documentable)
->setTitle($ref->getTitle())
->setGroupName($ref->getGroup())
->setNodeHash($atom->getHash());
if ($atom->getType() !== DivinerAtom::TYPE_FILE) {
$renderer = $this->getRenderer();
$summary = $renderer->getAtomSummary($atom);
$symbol->setSummary($summary);
} else {
$symbol->setSummary('');
}
$symbol->save();
PhabricatorSearchWorker::queueDocumentForIndexing($symbol->getPHID());
// TODO: We probably need a finer-grained sense of what "documentable"
// atoms are. Neither files nor methods are currently considered
// documentable, but for different reasons: files appear nowhere, while
// methods just don't appear at the top level. These are probably
// separate concepts. Since we need atoms in order to build method
// documentation, we insert them here. This also means we insert files,
// which are unnecessary and unused. Make sure this makes sense, but then
// probably introduce separate "isTopLevel" and "isDocumentable" flags?
// TODO: Yeah do that soon ^^^
if ($atom->getType() !== DivinerAtom::TYPE_FILE) {
$storage = $this->loadAtomStorageForSymbol($symbol)
->setAtomData($atom->toDictionary())
->setContent(null)
->save();
}
}
}
public function findAtomByRef(DivinerAtomRef $ref) {
// TODO: Actually implement this.
return null;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/publisher/DivinerStaticPublisher.php | src/applications/diviner/publisher/DivinerStaticPublisher.php | <?php
final class DivinerStaticPublisher extends DivinerPublisher {
private $publishCache;
private $atomNameMap;
private function getPublishCache() {
if (!$this->publishCache) {
$dir = implode(
DIRECTORY_SEPARATOR,
array(
$this->getConfig('root'),
'.divinercache',
$this->getConfig('name'),
'static',
));
$this->publishCache = new DivinerPublishCache($dir);
}
return $this->publishCache;
}
protected function loadAllPublishedHashes() {
return array_keys($this->getPublishCache()->getPathMap());
}
protected function deleteDocumentsByHash(array $hashes) {
$root = $this->getConfig('root');
$cache = $this->getPublishCache();
foreach ($hashes as $hash) {
$paths = $cache->getAtomPathsFromCache($hash);
foreach ($paths as $path) {
$abs = $root.DIRECTORY_SEPARATOR.$path;
Filesystem::remove($abs);
// If the parent directory is now empty, clean it up.
$dir = dirname($abs);
while (true) {
if (!Filesystem::isDescendant($dir, $root)) {
// Directory is outside of the root.
break;
}
if (Filesystem::listDirectory($dir)) {
// Directory is not empty.
break;
}
Filesystem::remove($dir);
$dir = dirname($dir);
}
}
$cache->removeAtomPathsFromCache($hash);
$cache->deleteAtomFromIndex($hash);
}
}
protected function createDocumentsByHash(array $hashes) {
$indexes = array();
$cache = $this->getPublishCache();
foreach ($hashes as $hash) {
$atom = $this->getAtomFromGraphHash($hash);
$paths = array();
if ($this->shouldGenerateDocumentForAtom($atom)) {
$content = $this->getRenderer()->renderAtom($atom);
$this->writeDocument($atom, $content);
$paths[] = $this->getAtomRelativePath($atom);
if ($this->getAtomSimilarIndex($atom) !== null) {
$index = dirname($this->getAtomRelativePath($atom)).'index.html';
$indexes[$index] = $atom;
$paths[] = $index;
}
$this->addAtomToIndex($hash, $atom);
}
$cache->addAtomPathsToCache($hash, $paths);
}
foreach ($indexes as $index => $atoms) {
// TODO: Publish disambiguation pages.
}
$this->publishIndex();
$cache->writePathMap();
$cache->writeIndex();
}
private function publishIndex() {
$index = $this->getPublishCache()->getIndex();
$refs = array();
foreach ($index as $hash => $dictionary) {
$refs[$hash] = DivinerAtomRef::newFromDictionary($dictionary);
}
$content = $this->getRenderer()->renderAtomIndex($refs);
$path = implode(
DIRECTORY_SEPARATOR,
array(
$this->getConfig('root'),
'docs',
$this->getConfig('name'),
'index.html',
));
Filesystem::writeFile($path, $content);
}
public function findAtomByRef(DivinerAtomRef $ref) {
if ($ref->getBook() != $this->getConfig('name')) {
return null;
}
if ($this->atomNameMap === null) {
$name_map = array();
foreach ($this->getPublishCache()->getIndex() as $hash => $dict) {
$name_map[$dict['name']][$hash] = $dict;
}
$this->atomNameMap = $name_map;
}
$name = $ref->getName();
if (empty($this->atomNameMap[$name])) {
return null;
}
$candidates = $this->atomNameMap[$name];
foreach ($candidates as $key => $dict) {
$candidates[$key] = DivinerAtomRef::newFromDictionary($dict);
if ($ref->getType()) {
if ($candidates[$key]->getType() != $ref->getType()) {
unset($candidates[$key]);
}
}
if ($ref->getContext()) {
if ($candidates[$key]->getContext() != $ref->getContext()) {
unset($candidates[$key]);
}
}
}
// If we have exactly one uniquely identifiable atom, return it.
if (count($candidates) == 1) {
return $this->getAtomFromNodeHash(last_key($candidates));
}
return null;
}
private function addAtomToIndex($hash, DivinerAtom $atom) {
$ref = $atom->getRef();
$ref->setIndex($this->getAtomSimilarIndex($atom));
$ref->setSummary($this->getRenderer()->renderAtomSummary($atom));
$this->getPublishCache()->addAtomToIndex($hash, $ref->toDictionary());
}
private function writeDocument(DivinerAtom $atom, $content) {
$root = $this->getConfig('root');
$path = $root.DIRECTORY_SEPARATOR.$this->getAtomRelativePath($atom);
if (!Filesystem::pathExists($path)) {
Filesystem::createDirectory($path, $umask = 0755, $recursive = true);
}
Filesystem::writeFile($path.'index.html', $content);
return $this;
}
private function getAtomRelativePath(DivinerAtom $atom) {
$ref = $atom->getRef();
$book = $ref->getBook();
$type = $ref->getType();
$context = $ref->getContext();
$name = $ref->getName();
$path = array(
'docs',
$book,
$type,
);
if ($context !== null) {
$path[] = $context;
}
$path[] = $name;
$index = $this->getAtomSimilarIndex($atom);
if ($index !== null) {
$path[] = '@'.$index;
}
$path[] = null;
return implode(DIRECTORY_SEPARATOR, $path);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/publisher/DivinerPublisher.php | src/applications/diviner/publisher/DivinerPublisher.php | <?php
abstract class DivinerPublisher extends Phobject {
private $atomCache;
private $atomGraphHashToNodeHashMap;
private $atomMap = array();
private $renderer;
private $config;
private $symbolReverseMap;
private $dropCaches;
private $repositoryPHID;
final public function setDropCaches($drop_caches) {
$this->dropCaches = $drop_caches;
return $this;
}
final public function setRenderer(DivinerRenderer $renderer) {
$renderer->setPublisher($this);
$this->renderer = $renderer;
return $this;
}
final public function getRenderer() {
return $this->renderer;
}
final public function setConfig(array $config) {
$this->config = $config;
return $this;
}
final public function getConfig($key, $default = null) {
return idx($this->config, $key, $default);
}
final public function getConfigurationData() {
return $this->config;
}
final public function setAtomCache(DivinerAtomCache $cache) {
$this->atomCache = $cache;
$graph_map = $this->atomCache->getGraphMap();
$this->atomGraphHashToNodeHashMap = array_flip($graph_map);
return $this;
}
final protected function getAtomFromGraphHash($graph_hash) {
if (empty($this->atomGraphHashToNodeHashMap[$graph_hash])) {
throw new Exception(pht("No such atom '%s'!", $graph_hash));
}
return $this->getAtomFromNodeHash(
$this->atomGraphHashToNodeHashMap[$graph_hash]);
}
final protected function getAtomFromNodeHash($node_hash) {
if (empty($this->atomMap[$node_hash])) {
$dict = $this->atomCache->getAtom($node_hash);
$this->atomMap[$node_hash] = DivinerAtom::newFromDictionary($dict);
}
return $this->atomMap[$node_hash];
}
final protected function getSimilarAtoms(DivinerAtom $atom) {
if ($this->symbolReverseMap === null) {
$rmap = array();
$smap = $this->atomCache->getSymbolMap();
foreach ($smap as $nhash => $shash) {
$rmap[$shash][$nhash] = true;
}
$this->symbolReverseMap = $rmap;
}
$shash = $atom->getRef()->toHash();
if (empty($this->symbolReverseMap[$shash])) {
throw new Exception(pht('Atom has no symbol map entry!'));
}
$hashes = $this->symbolReverseMap[$shash];
$atoms = array();
foreach ($hashes as $hash => $ignored) {
$atoms[] = $this->getAtomFromNodeHash($hash);
}
$atoms = msort($atoms, 'getSortKey');
return $atoms;
}
/**
* If a book contains multiple definitions of some atom, like some function
* `f()`, we assign them an arbitrary (but fairly stable) order and publish
* them as `function/f/1/`, `function/f/2/`, etc., or similar.
*/
final protected function getAtomSimilarIndex(DivinerAtom $atom) {
$atoms = $this->getSimilarAtoms($atom);
if (count($atoms) == 1) {
return 0;
}
$index = 1;
foreach ($atoms as $similar_atom) {
if ($atom === $similar_atom) {
return $index;
}
$index++;
}
throw new Exception(pht('Expected to find atom while disambiguating!'));
}
abstract protected function loadAllPublishedHashes();
abstract protected function deleteDocumentsByHash(array $hashes);
abstract protected function createDocumentsByHash(array $hashes);
abstract public function findAtomByRef(DivinerAtomRef $ref);
final public function publishAtoms(array $hashes) {
$existing = $this->loadAllPublishedHashes();
if ($this->dropCaches) {
$deleted = $existing;
$created = $hashes;
} else {
$existing_map = array_fill_keys($existing, true);
$hashes_map = array_fill_keys($hashes, true);
$deleted = array_diff_key($existing_map, $hashes_map);
$created = array_diff_key($hashes_map, $existing_map);
$deleted = array_keys($deleted);
$created = array_keys($created);
}
$console = PhutilConsole::getConsole();
$console->writeOut(
"%s\n",
pht(
'Deleting %s document(s).',
phutil_count($deleted)));
$this->deleteDocumentsByHash($deleted);
$console->writeOut(
"%s\n",
pht(
'Creating %s document(s).',
phutil_count($created)));
$this->createDocumentsByHash($created);
}
final protected function shouldGenerateDocumentForAtom(DivinerAtom $atom) {
switch ($atom->getType()) {
case DivinerAtom::TYPE_METHOD:
case DivinerAtom::TYPE_FILE:
return false;
case DivinerAtom::TYPE_ARTICLE:
default:
break;
}
return true;
}
final public function getRepositoryPHID() {
return $this->repositoryPHID;
}
final public function setRepositoryPHID($repository_phid) {
$this->repositoryPHID = $repository_phid;
return $this;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/editor/DivinerLiveBookEditor.php | src/applications/diviner/editor/DivinerLiveBookEditor.php | <?php
final class DivinerLiveBookEditor
extends PhabricatorApplicationTransactionEditor {
public function getEditorApplicationClass() {
return 'PhabricatorDivinerApplication';
}
public function getEditorObjectsDescription() {
return pht('Diviner Books');
}
public function getTransactionTypes() {
$types = parent::getTransactionTypes();
$types[] = PhabricatorTransactions::TYPE_VIEW_POLICY;
$types[] = PhabricatorTransactions::TYPE_EDIT_POLICY;
return $types;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/application/PhabricatorDivinerApplication.php | src/applications/diviner/application/PhabricatorDivinerApplication.php | <?php
final class PhabricatorDivinerApplication extends PhabricatorApplication {
public function getBaseURI() {
return '/diviner/';
}
public function getIcon() {
return 'fa-sun-o';
}
public function getName() {
return pht('Diviner');
}
public function getShortDescription() {
return pht('Documentation');
}
public function getHelpDocumentationArticles(PhabricatorUser $viewer) {
return array(
array(
'name' => pht('Diviner User Guide'),
'href' => PhabricatorEnv::getDoclink('Diviner User Guide'),
),
);
}
public function getTitleGlyph() {
return "\xE2\x97\x89";
}
public function getRoutes() {
return array(
'/diviner/' => array(
'' => 'DivinerMainController',
'query/((?<queryKey>[^/]+)/)?' => 'DivinerAtomListController',
'find/' => 'DivinerFindController',
),
'/book/(?P<book>[^/]+)/' => 'DivinerBookController',
'/book/(?P<book>[^/]+)/edit/' => 'DivinerBookEditController',
'/book/'.
'(?P<book>[^/]+)/'.
'(?P<type>[^/]+)/'.
'(?:(?P<context>[^/]+)/)?'.
'(?P<name>[^/]+)/'.
'(?:(?P<index>\d+)/)?' => 'DivinerAtomController',
);
}
public function getApplicationGroup() {
return self::GROUP_UTILITIES;
}
protected function getCustomCapabilities() {
return array(
DivinerDefaultViewCapability::CAPABILITY => array(
'template' => DivinerBookPHIDType::TYPECONST,
'capability' => PhabricatorPolicyCapability::CAN_VIEW,
),
DivinerDefaultEditCapability::CAPABILITY => array(
'default' => PhabricatorPolicies::POLICY_ADMIN,
'template' => DivinerBookPHIDType::TYPECONST,
'capability' => PhabricatorPolicyCapability::CAN_EDIT,
),
);
}
public function getRemarkupRules() {
return array(
new DivinerSymbolRemarkupRule(),
);
}
public function getApplicationSearchDocumentTypes() {
return array(
DivinerAtomPHIDType::TYPECONST,
DivinerBookPHIDType::TYPECONST,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/atomizer/DivinerFileAtomizer.php | src/applications/diviner/atomizer/DivinerFileAtomizer.php | <?php
final class DivinerFileAtomizer extends DivinerAtomizer {
protected function executeAtomize($file_name, $file_data) {
$atom = $this->newAtom(DivinerAtom::TYPE_FILE)
->setName($file_name)
->setFile($file_name)
->setContentRaw($file_data);
return array($atom);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/atomizer/DivinerArticleAtomizer.php | src/applications/diviner/atomizer/DivinerArticleAtomizer.php | <?php
final class DivinerArticleAtomizer extends DivinerAtomizer {
protected function executeAtomize($file_name, $file_data) {
$atom = $this->newAtom(DivinerAtom::TYPE_ARTICLE)
->setLine(1)
->setLength(count(explode("\n", $file_data)))
->setLanguage('human');
$block = "/**\n".str_replace("\n", "\n * ", $file_data)."\n */";
$atom->setDocblockRaw($block);
$meta = $atom->getDocblockMeta();
$title = idx($meta, 'title');
if (!strlen($title)) {
$title = pht('Untitled Article "%s"', basename($file_name));
$atom->addWarning(pht('Article has no %s!', '@title'));
$atom->setDocblockMetaValue('title', $title);
}
// If the article has no `@name`, use the filename after stripping any
// extension.
$name = idx($meta, 'name');
if (!$name) {
$name = basename($file_name);
$name = preg_replace('/\\.[^.]+$/', '', $name);
}
$atom->setName($name);
return array($atom);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/atomizer/DivinerPHPAtomizer.php | src/applications/diviner/atomizer/DivinerPHPAtomizer.php | <?php
final class DivinerPHPAtomizer extends DivinerAtomizer {
protected function newAtom($type) {
return parent::newAtom($type)->setLanguage('php');
}
protected function executeAtomize($file_name, $file_data) {
$future = PhutilXHPASTBinary::getParserFuture($file_data);
$tree = XHPASTTree::newFromDataAndResolvedExecFuture(
$file_data,
$future->resolve());
$atoms = array();
$root = $tree->getRootNode();
$func_decl = $root->selectDescendantsOfType('n_FUNCTION_DECLARATION');
foreach ($func_decl as $func) {
$name = $func->getChildByIndex(2);
// Don't atomize closures
if ($name->getTypeName() === 'n_EMPTY') {
continue;
}
$atom = $this->newAtom(DivinerAtom::TYPE_FUNCTION)
->setName($name->getConcreteString())
->setLine($func->getLineNumber())
->setFile($file_name);
$this->findAtomDocblock($atom, $func);
$this->parseParams($atom, $func);
$this->parseReturnType($atom, $func);
$atoms[] = $atom;
}
$class_types = array(
DivinerAtom::TYPE_CLASS => 'n_CLASS_DECLARATION',
DivinerAtom::TYPE_INTERFACE => 'n_INTERFACE_DECLARATION',
);
foreach ($class_types as $atom_type => $node_type) {
$class_decls = $root->selectDescendantsOfType($node_type);
foreach ($class_decls as $class) {
$name = $class->getChildByIndex(1, 'n_CLASS_NAME');
$atom = $this->newAtom($atom_type)
->setName($name->getConcreteString())
->setFile($file_name)
->setLine($class->getLineNumber());
// This parses `final` and `abstract`.
$attributes = $class->getChildByIndex(0, 'n_CLASS_ATTRIBUTES');
foreach ($attributes->selectDescendantsOfType('n_STRING') as $attr) {
$atom->setProperty($attr->getConcreteString(), true);
}
// If this exists, it is `n_EXTENDS_LIST`.
$extends = $class->getChildByIndex(2);
$extends_class = $extends->selectDescendantsOfType('n_CLASS_NAME');
foreach ($extends_class as $parent_class) {
$atom->addExtends(
$this->newRef(
DivinerAtom::TYPE_CLASS,
$parent_class->getConcreteString()));
}
// If this exists, it is `n_IMPLEMENTS_LIST`.
$implements = $class->getChildByIndex(3);
$iface_names = $implements->selectDescendantsOfType('n_CLASS_NAME');
foreach ($iface_names as $iface_name) {
$atom->addExtends(
$this->newRef(
DivinerAtom::TYPE_INTERFACE,
$iface_name->getConcreteString()));
}
$this->findAtomDocblock($atom, $class);
$methods = $class->selectDescendantsOfType('n_METHOD_DECLARATION');
foreach ($methods as $method) {
$matom = $this->newAtom(DivinerAtom::TYPE_METHOD);
$this->findAtomDocblock($matom, $method);
$attribute_list = $method->getChildByIndex(0);
$attributes = $attribute_list->selectDescendantsOfType('n_STRING');
if ($attributes) {
foreach ($attributes as $attribute) {
$attr = strtolower($attribute->getConcreteString());
switch ($attr) {
case 'final':
case 'abstract':
case 'static':
$matom->setProperty($attr, true);
break;
case 'public':
case 'protected':
case 'private':
$matom->setProperty('access', $attr);
break;
}
}
} else {
$matom->setProperty('access', 'public');
}
$this->parseParams($matom, $method);
$matom->setName($method->getChildByIndex(2)->getConcreteString());
$matom->setLine($method->getLineNumber());
$matom->setFile($file_name);
$this->parseReturnType($matom, $method);
$atom->addChild($matom);
$atoms[] = $matom;
}
$atoms[] = $atom;
}
}
return $atoms;
}
private function parseParams(DivinerAtom $atom, AASTNode $func) {
$params = $func
->getChildOfType(3, 'n_DECLARATION_PARAMETER_LIST')
->selectDescendantsOfType('n_DECLARATION_PARAMETER');
$param_spec = array();
if ($atom->getDocblockRaw()) {
$metadata = $atom->getDocblockMeta();
} else {
$metadata = array();
}
$docs = idx($metadata, 'param');
if ($docs) {
$docs = (array)$docs;
$docs = array_filter($docs);
} else {
$docs = array();
}
if (count($docs)) {
if (count($docs) < count($params)) {
$atom->addWarning(
pht(
'This call takes %s parameter(s), but only %s are documented.',
phutil_count($params),
phutil_count($docs)));
}
}
foreach ($params as $param) {
$name = $param->getChildByIndex(1)->getConcreteString();
$dict = array(
'type' => $param->getChildByIndex(0)->getConcreteString(),
'default' => $param->getChildByIndex(2)->getConcreteString(),
);
if ($docs) {
$doc = array_shift($docs);
if ($doc) {
$dict += $this->parseParamDoc($atom, $doc, $name);
}
}
$param_spec[] = array(
'name' => $name,
) + $dict;
}
if ($docs) {
foreach ($docs as $doc) {
if ($doc) {
$param_spec[] = $this->parseParamDoc($atom, $doc, null);
}
}
}
// TODO: Find `assert_instances_of()` calls in the function body and
// add their type information here. See T1089.
$atom->setProperty('parameters', $param_spec);
}
private function findAtomDocblock(DivinerAtom $atom, XHPASTNode $node) {
$token = $node->getDocblockToken();
if ($token) {
$atom->setDocblockRaw($token->getValue());
return true;
} else {
$tokens = $node->getTokens();
if ($tokens) {
$prev = head($tokens);
while ($prev = $prev->getPrevToken()) {
if ($prev->isAnyWhitespace()) {
continue;
}
break;
}
if ($prev && $prev->isComment()) {
$value = $prev->getValue();
$matches = null;
if (preg_match('/@(return|param|task|author)/', $value, $matches)) {
$atom->addWarning(
pht(
'Atom "%s" is preceded by a comment containing `%s`, but '.
'the comment is not a documentation comment. Documentation '.
'comments must begin with `%s`, followed by a newline. Did '.
'you mean to use a documentation comment? (As the comment is '.
'not a documentation comment, it will be ignored.)',
$atom->getName(),
'@'.$matches[1],
'/**'));
}
}
}
$atom->setDocblockRaw('');
return false;
}
}
protected function parseParamDoc(DivinerAtom $atom, $doc, $name) {
$dict = array();
$split = preg_split('/\s+/', trim($doc), 2);
if (!empty($split[0])) {
$dict['doctype'] = $split[0];
}
if (!empty($split[1])) {
$docs = $split[1];
// If the parameter is documented like `@param int $num Blah blah ..`,
// get rid of the `$num` part (which Diviner considers optional). If it
// is present and different from the declared name, raise a warning.
$matches = null;
if (preg_match('/^(\\$\S+)\s+/', $docs, $matches)) {
if ($name !== null) {
if ($matches[1] !== $name) {
$atom->addWarning(
pht(
'Parameter "%s" is named "%s" in the documentation. '.
'The documentation may be out of date.',
$name,
$matches[1]));
}
}
$docs = substr($docs, strlen($matches[0]));
}
$dict['docs'] = $docs;
}
return $dict;
}
private function parseReturnType(DivinerAtom $atom, XHPASTNode $decl) {
$return_spec = array();
$metadata = $atom->getDocblockMeta();
$return = idx($metadata, 'return');
$type = null;
$docs = null;
if (!$return) {
$return = idx($metadata, 'returns');
if ($return) {
$atom->addWarning(
pht(
'Documentation uses `%s`, but should use `%s`.',
'@returns',
'@return'));
}
}
$return = (array)$return;
if (count($return) > 1) {
$atom->addWarning(
pht(
'Documentation specifies `%s` multiple times.',
'@return'));
}
$return = head($return);
if ($atom->getName() == '__construct' && $atom->getType() == 'method') {
$return_spec = array(
'doctype' => 'this',
'docs' => '//Implicit.//',
);
if ($return) {
$atom->addWarning(
pht(
'Method `%s` has explicitly documented `%s`. The `%s` method '.
'always returns `%s`. Diviner documents this implicitly.',
'__construct()',
'@return',
'__construct()',
'$this'));
}
} else if ($return) {
$split = preg_split('/(?<!,)\s+/', trim($return), 2);
if (!empty($split[0])) {
$type = $split[0];
}
if ($decl->getChildByIndex(1)->getTypeName() == 'n_REFERENCE') {
$type = $type.' &';
}
if (!empty($split[1])) {
$docs = $split[1];
}
$return_spec = array(
'doctype' => $type,
'docs' => $docs,
);
} else {
$return_spec = array(
'type' => 'wild',
);
}
$atom->setProperty('return', $return_spec);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/atomizer/DivinerAtomizer.php | src/applications/diviner/atomizer/DivinerAtomizer.php | <?php
/**
* Generate @{class:DivinerAtom}s from source code.
*/
abstract class DivinerAtomizer extends Phobject {
private $book;
private $fileName;
private $atomContext;
/**
* If you make a significant change to an atomizer, you can bump this version
* to drop all the old atom caches.
*/
public static function getAtomizerVersion() {
return 1;
}
final public function atomize($file_name, $file_data, array $context) {
$this->fileName = $file_name;
$this->atomContext = $context;
$atoms = $this->executeAtomize($file_name, $file_data);
// Promote the `@group` special to a property. If there's no `@group` on
// an atom but the file it's in matches a group pattern, associate it with
// the right group.
foreach ($atoms as $atom) {
$group = null;
try {
$group = $atom->getDocblockMetaValue('group');
} catch (Exception $ex) {
// There's no docblock metadata.
}
// If there's no group, but the file matches a group, use that group.
if ($group === null && isset($context['group'])) {
$group = $context['group'];
}
if ($group !== null) {
$atom->setProperty('group', $group);
}
}
return $atoms;
}
abstract protected function executeAtomize($file_name, $file_data);
final public function setBook($book) {
$this->book = $book;
return $this;
}
final public function getBook() {
return $this->book;
}
protected function newAtom($type) {
return id(new DivinerAtom())
->setBook($this->getBook())
->setFile($this->fileName)
->setType($type);
}
protected function newRef($type, $name, $book = null, $context = null) {
$book = coalesce($book, $this->getBook());
return id(new DivinerAtomRef())
->setBook($book)
->setContext($context)
->setType($type)
->setName($name);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/view/DivinerReturnTableView.php | src/applications/diviner/view/DivinerReturnTableView.php | <?php
final class DivinerReturnTableView extends AphrontTagView {
private $return;
private $header;
public function setReturn(array $return) {
$this->return = $return;
return $this;
}
public function setHeader($text) {
$this->header = $text;
return $this;
}
protected function getTagName() {
return 'div';
}
protected function getTagAttributes() {
return array(
'class' => 'diviner-table-view',
);
}
protected function getTagContent() {
require_celerity_resource('diviner-shared-css');
$return = $this->return;
$type = idx($return, 'doctype');
if (!$type) {
$type = idx($return, 'type');
}
$docs = idx($return, 'docs');
$cells = array();
$cells[] = phutil_tag(
'td',
array(
'class' => 'diviner-return-table-type diviner-monospace',
),
$type);
$cells[] = phutil_tag(
'td',
array(
'class' => 'diviner-return-table-docs',
),
$docs);
$rows = phutil_tag(
'tr',
array(),
$cells);
$table = phutil_tag(
'table',
array(
'class' => 'diviner-return-table-view',
),
$rows);
$header = phutil_tag(
'span',
array(
'class' => 'diviner-table-header',
),
$this->header);
return array($header, $table);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/view/DivinerBookItemView.php | src/applications/diviner/view/DivinerBookItemView.php | <?php
final class DivinerBookItemView extends AphrontTagView {
private $title;
private $subtitle;
private $type;
private $href;
public function setTitle($title) {
$this->title = $title;
return $this;
}
public function setSubtitle($subtitle) {
$this->subtitle = $subtitle;
return $this;
}
public function setType($type) {
$this->type = $type;
return $this;
}
public function setHref($href) {
$this->href = $href;
return $this;
}
protected function getTagName() {
return 'a';
}
protected function getTagAttributes() {
return array(
'class' => 'diviner-book-item',
'href' => $this->href,
);
}
protected function getTagContent() {
require_celerity_resource('diviner-shared-css');
$title = phutil_tag(
'span',
array(
'class' => 'diviner-book-item-title',
),
$this->title);
$subtitle = phutil_tag(
'span',
array(
'class' => 'diviner-book-item-subtitle',
),
$this->subtitle);
$type = phutil_tag(
'span',
array(
'class' => 'diviner-book-item-type',
),
$this->type);
return array($title, $type, $subtitle);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/view/DivinerSectionView.php | src/applications/diviner/view/DivinerSectionView.php | <?php
final class DivinerSectionView extends AphrontTagView {
private $header;
private $content;
public function addContent($content) {
$this->content[] = $content;
return $this;
}
public function setHeader($text) {
$this->header = $text;
return $this;
}
protected function getTagName() {
return 'div';
}
protected function getTagAttributes() {
return array(
'class' => 'diviner-document-section',
);
}
protected function getTagContent() {
require_celerity_resource('diviner-shared-css');
$header = id(new PHUIHeaderView())
->setBleedHeader(true)
->addClass('diviner-section-header')
->setHeader($this->header);
$content = phutil_tag_div('diviner-section-content', $this->content);
return array($header, $content);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/view/DivinerParameterTableView.php | src/applications/diviner/view/DivinerParameterTableView.php | <?php
final class DivinerParameterTableView extends AphrontTagView {
private $parameters;
private $header;
public function setParameters(array $parameters) {
$this->parameters = $parameters;
return $this;
}
public function setHeader($text) {
$this->header = $text;
return $this;
}
protected function getTagName() {
return 'div';
}
protected function getTagAttributes() {
return array(
'class' => 'diviner-table-view',
);
}
protected function getTagContent() {
require_celerity_resource('diviner-shared-css');
$rows = array();
foreach ($this->parameters as $param) {
$cells = array();
$type = idx($param, 'doctype');
if (!$type) {
$type = idx($param, 'type');
}
$name = idx($param, 'name');
$docs = idx($param, 'docs');
$cells[] = phutil_tag(
'td',
array(
'class' => 'diviner-parameter-table-type diviner-monospace',
),
$type);
$cells[] = phutil_tag(
'td',
array(
'class' => 'diviner-parameter-table-name diviner-monospace',
),
$name);
$cells[] = phutil_tag(
'td',
array(
'class' => 'diviner-parameter-table-docs',
),
$docs);
$rows[] = phutil_tag('tr', array(), $cells);
}
$table = phutil_tag(
'table',
array(
'class' => 'diviner-parameter-table-view',
),
$rows);
$header = phutil_tag(
'span',
array(
'class' => 'diviner-table-header',
),
$this->header);
return array($header, $table);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/phid/DivinerAtomPHIDType.php | src/applications/diviner/phid/DivinerAtomPHIDType.php | <?php
final class DivinerAtomPHIDType extends PhabricatorPHIDType {
const TYPECONST = 'ATOM';
public function getTypeName() {
return pht('Diviner Atom');
}
public function newObject() {
return new DivinerLiveSymbol();
}
public function getTypeIcon() {
return 'fa-cube';
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDivinerApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new DivinerAtomQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$atom = $objects[$phid];
$book = $atom->getBook()->getName();
$name = $atom->getName();
$type = $atom->getType();
$handle
->setName($atom->getName())
->setTitle($atom->getTitle())
->setURI("/book/{$book}/{$type}/{$name}/")
->setStatus($atom->getGraphHash()
? PhabricatorObjectHandle::STATUS_OPEN
: PhabricatorObjectHandle::STATUS_CLOSED);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/phid/DivinerBookPHIDType.php | src/applications/diviner/phid/DivinerBookPHIDType.php | <?php
final class DivinerBookPHIDType extends PhabricatorPHIDType {
const TYPECONST = 'BOOK';
public function getTypeName() {
return pht('Diviner Book');
}
public function newObject() {
return new DivinerLiveBook();
}
public function getTypeIcon() {
return 'fa-book';
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDivinerApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new DivinerBookQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$book = $objects[$phid];
$name = $book->getName();
$handle
->setName($book->getShortTitle())
->setFullName($book->getTitle())
->setURI("/book/{$name}/");
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/search/DivinerLiveSymbolFulltextEngine.php | src/applications/diviner/search/DivinerLiveSymbolFulltextEngine.php | <?php
final class DivinerLiveSymbolFulltextEngine
extends PhabricatorFulltextEngine {
protected function buildAbstractDocument(
PhabricatorSearchAbstractDocument $document,
$object) {
$atom = $object;
$book = $atom->getBook();
$document
->setDocumentTitle($atom->getTitle())
->setDocumentCreated($book->getDateCreated())
->setDocumentModified($book->getDateModified());
$document->addField(
PhabricatorSearchDocumentFieldType::FIELD_BODY,
$atom->getSummary());
$document->addRelationship(
PhabricatorSearchRelationship::RELATIONSHIP_BOOK,
$atom->getBookPHID(),
DivinerBookPHIDType::TYPECONST,
PhabricatorTime::getNow());
$document->addRelationship(
PhabricatorSearchRelationship::RELATIONSHIP_REPOSITORY,
$atom->getRepositoryPHID(),
PhabricatorRepositoryRepositoryPHIDType::TYPECONST,
PhabricatorTime::getNow());
$document->addRelationship(
$atom->getGraphHash()
? PhabricatorSearchRelationship::RELATIONSHIP_OPEN
: PhabricatorSearchRelationship::RELATIONSHIP_CLOSED,
$atom->getBookPHID(),
DivinerBookPHIDType::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/diviner/search/DivinerLiveBookFulltextEngine.php | src/applications/diviner/search/DivinerLiveBookFulltextEngine.php | <?php
final class DivinerLiveBookFulltextEngine
extends PhabricatorFulltextEngine {
protected function buildAbstractDocument(
PhabricatorSearchAbstractDocument $document,
$object) {
$book = $object;
$document->setDocumentTitle($book->getTitle());
$document->addField(
PhabricatorSearchDocumentFieldType::FIELD_BODY,
$book->getPreface());
$document->addRelationship(
PhabricatorSearchRelationship::RELATIONSHIP_REPOSITORY,
$book->getRepositoryPHID(),
PhabricatorRepositoryRepositoryPHIDType::TYPECONST,
$book->getDateCreated());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/typeahead/DivinerBookDatasource.php | src/applications/diviner/typeahead/DivinerBookDatasource.php | <?php
final class DivinerBookDatasource extends PhabricatorTypeaheadDatasource {
public function getBrowseTitle() {
return pht('Browse Books');
}
public function getPlaceholderText() {
return pht('Type a book name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorDivinerApplication';
}
public function loadResults() {
$raw_query = $this->getRawQuery();
$query = id(new DivinerBookQuery())
->setOrder('name')
->withNamePrefix($raw_query);
$books = $this->executeQuery($query);
$results = array();
foreach ($books as $book) {
$results[] = id(new PhabricatorTypeaheadResult())
->setName($book->getTitle())
->setURI('/book/'.$book->getName().'/')
->setPHID($book->getPHID())
->setPriorityString($book->getName());
}
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/diviner/workflow/DivinerGenerateWorkflow.php | src/applications/diviner/workflow/DivinerGenerateWorkflow.php | <?php
final class DivinerGenerateWorkflow extends DivinerWorkflow {
private $atomCache;
protected function didConstruct() {
$this
->setName('generate')
->setSynopsis(pht('Generate documentation.'))
->setArguments(
array(
array(
'name' => 'clean',
'help' => pht('Clear the caches before generating documentation.'),
),
array(
'name' => 'book',
'param' => 'path',
'help' => pht('Path to a Diviner book configuration.'),
),
array(
'name' => 'publisher',
'param' => 'class',
'help' => pht('Specify a subclass of %s.', 'DivinerPublisher'),
'default' => 'DivinerLivePublisher',
),
array(
'name' => 'repository',
'param' => 'identifier',
'help' => pht('Repository that the documentation belongs to.'),
),
));
}
protected function getAtomCache() {
if (!$this->atomCache) {
$book_root = $this->getConfig('root');
$book_name = $this->getConfig('name');
$cache_directory = $book_root.'/.divinercache/'.$book_name;
$this->atomCache = new DivinerAtomCache($cache_directory);
}
return $this->atomCache;
}
protected function log($message) {
$console = PhutilConsole::getConsole();
$console->writeErr($message."\n");
}
public function execute(PhutilArgumentParser $args) {
$book = $args->getArg('book');
if ($book) {
$books = array($book);
} else {
$cwd = getcwd();
$this->log(pht('FINDING DOCUMENTATION BOOKS'));
$books = id(new FileFinder($cwd))
->withType('f')
->withSuffix('book')
->find();
if (!$books) {
throw new PhutilArgumentUsageException(
pht(
"There are no Diviner '%s' files anywhere beneath the current ".
"directory. Use '%s' to specify a documentation book to generate.",
'.book',
'--book <book>'));
} else {
$this->log(pht('Found %s book(s).', phutil_count($books)));
}
}
foreach ($books as $book) {
$short_name = basename($book);
$this->log(pht('Generating book "%s"...', $short_name));
$this->generateBook($book, $args);
$this->log(pht('Completed generation of "%s".', $short_name)."\n");
}
}
private function generateBook($book, PhutilArgumentParser $args) {
$this->atomCache = null;
$this->readBookConfiguration($book);
if ($args->getArg('clean')) {
$this->log(pht('CLEARING CACHES'));
$this->getAtomCache()->delete();
$this->log(pht('Done.')."\n");
}
// The major challenge of documentation generation is one of dependency
// management. When regenerating documentation, we want to do the smallest
// amount of work we can, so that regenerating documentation after minor
// changes is quick.
//
// = Atom Cache =
//
// In the first stage, we find all the direct changes to source code since
// the last run. This stage relies on two data structures:
//
// - File Hash Map: `map<file_hash, node_hash>`
// - Atom Map: `map<node_hash, true>`
//
// First, we hash all the source files in the project to detect any which
// have changed since the previous run (i.e., their hash is not present in
// the File Hash Map). If a file's content hash appears in the map, it has
// not changed, so we don't need to reparse it.
//
// We break the contents of each file into "atoms", which represent a unit
// of source code (like a function, method, class or file). Each atom has a
// "node hash" based on the content of the atom: if a function definition
// changes, the node hash of the atom changes too. The primary output of
// the atom cache is a list of node hashes which exist in the project. This
// is the Atom Map. The node hash depends only on the definition of the atom
// and the atomizer implementation. It ends with an "N", for "node".
//
// (We need the Atom Map in addition to the File Hash Map because each file
// may have several atoms in it (e.g., multiple functions, or a class and
// its methods). The File Hash Map contains an exhaustive list of all atoms
// with type "file", but not child atoms of those top-level atoms.)
//
// = Graph Cache =
//
// We now know which atoms exist, and can compare the Atom Map to some
// existing cache to figure out what has changed. However, this isn't
// sufficient to figure out which documentation actually needs to be
// regenerated, because atoms depend on other atoms. For example, if `B
// extends A` and the definition for `A` changes, we need to regenerate the
// documentation in `B`. Similarly, if `X` links to `Y` and `Y` changes, we
// should regenerate `X`. (In both these cases, the documentation for the
// connected atom may not actually change, but in some cases it will, and
// the extra work we need to do is generally very small compared to the
// size of the project.)
//
// To figure out which other nodes have changed, we compute a "graph hash"
// for each node. This hash combines the "node hash" with the node hashes
// of connected nodes. Our primary output is a list of graph hashes, which
// a documentation generator can use to easily determine what work needs
// to be done by comparing the list with a list of cached graph hashes,
// then generating documentation for new hashes and deleting documentation
// for missing hashes. The graph hash ends with a "G", for "graph".
//
// In this stage, we rely on three data structures:
//
// - Symbol Map: `map<node_hash, symbol_hash>`
// - Edge Map: `map<node_hash, list<symbol_hash>>`
// - Graph Map: `map<node_hash, graph_hash>`
//
// Calculating the graph hash requires several steps, because we need to
// figure out which nodes an atom is attached to. The atom contains symbolic
// references to other nodes by name (e.g., `extends SomeClass`) in the form
// of @{class:DivinerAtomRefs}. We can also build a symbolic reference for
// any atom from the atom itself. Each @{class:DivinerAtomRef} generates a
// symbol hash, which ends with an "S", for "symbol".
//
// First, we update the symbol map. We remove (and mark dirty) any symbols
// associated with node hashes which no longer exist (e.g., old/dead nodes).
// Second, we add (and mark dirty) any symbols associated with new nodes.
// We also add edges defined by new nodes to the graph.
//
// We initialize a list of dirty nodes to the list of new nodes, then find
// all nodes connected to dirty symbols and add them to the dirty node list.
// This list now contains every node with a new or changed graph hash.
//
// We walk the dirty list and compute the new graph hashes, adding them
// to the graph hash map. This Graph Map can then be passed to an actual
// documentation generator, which can compare the graph hashes to a list
// of already-generated graph hashes and easily assess which documents need
// to be regenerated and which can be deleted.
$this->buildAtomCache();
$this->buildGraphCache();
$publisher_class = $args->getArg('publisher');
$symbols = id(new PhutilSymbolLoader())
->setName($publisher_class)
->setConcreteOnly(true)
->setAncestorClass('DivinerPublisher')
->selectAndLoadSymbols();
if (!$symbols) {
throw new PhutilArgumentUsageException(
pht(
"Publisher class '%s' must be a concrete subclass of %s.",
$publisher_class,
'DivinerPublisher'));
}
$publisher = newv($publisher_class, array());
$identifier = $args->getArg('repository');
$repository = null;
if ($identifier !== null && strlen($identifier)) {
$repository = id(new PhabricatorRepositoryQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withIdentifiers(array($identifier))
->executeOne();
if (!$repository) {
throw new PhutilArgumentUsageException(
pht(
'Repository "%s" does not exist.',
$identifier));
}
$publisher->setRepositoryPHID($repository->getPHID());
}
$this->publishDocumentation($args->getArg('clean'), $publisher);
}
/* -( Atom Cache )--------------------------------------------------------- */
private function buildAtomCache() {
$this->log(pht('BUILDING ATOM CACHE'));
$file_hashes = $this->findFilesInProject();
$this->log(
pht(
'Found %s file(s) in project.',
phutil_count($file_hashes)));
$this->deleteDeadAtoms($file_hashes);
$atomize = $this->getFilesToAtomize($file_hashes);
$this->log(
pht(
'Found %s unatomized, uncached file(s).',
phutil_count($atomize)));
$file_atomizers = $this->getAtomizersForFiles($atomize);
$this->log(
pht(
'Found %s file(s) to atomize.',
phutil_count($file_atomizers)));
$futures = $this->buildAtomizerFutures($file_atomizers);
$this->log(
pht(
'Atomizing %s file(s).',
phutil_count($file_atomizers)));
if ($futures) {
$this->resolveAtomizerFutures($futures, $file_hashes);
$this->log(pht('Atomization complete.'));
} else {
$this->log(pht('Atom cache is up to date, no files to atomize.'));
}
$this->log(pht('Writing atom cache.'));
$this->getAtomCache()->saveAtoms();
$this->log(pht('Done.')."\n");
}
private function getAtomizersForFiles(array $files) {
$rules = $this->getRules();
$exclude = $this->getExclude();
$atomizers = array();
foreach ($files as $file) {
foreach ($exclude as $pattern) {
if (preg_match($pattern, $file)) {
continue 2;
}
}
foreach ($rules as $rule => $atomizer) {
$ok = preg_match($rule, $file);
if ($ok === false) {
throw new Exception(
pht("Rule '%s' is not a valid regular expression.", $rule));
}
if ($ok) {
$atomizers[$file] = $atomizer;
continue;
}
}
}
return $atomizers;
}
private function getRules() {
return $this->getConfig('rules', array(
'/\\.diviner$/' => 'DivinerArticleAtomizer',
'/\\.php$/' => 'DivinerPHPAtomizer',
));
}
private function getExclude() {
$exclude = (array)$this->getConfig('exclude', array());
return $exclude;
}
private function findFilesInProject() {
$raw_hashes = id(new FileFinder($this->getConfig('root')))
->excludePath('*/.*')
->withType('f')
->setGenerateChecksums(true)
->find();
$version = $this->getDivinerAtomWorldVersion();
$file_hashes = array();
foreach ($raw_hashes as $file => $md5_hash) {
$rel_file = Filesystem::readablePath($file, $this->getConfig('root'));
// We want the hash to change if the file moves or Diviner gets updated,
// not just if the file content changes. Derive a hash from everything
// we care about.
$file_hashes[$rel_file] = md5("{$rel_file}\0{$md5_hash}\0{$version}").'F';
}
return $file_hashes;
}
private function deleteDeadAtoms(array $file_hashes) {
$atom_cache = $this->getAtomCache();
$hash_to_file = array_flip($file_hashes);
foreach ($atom_cache->getFileHashMap() as $hash => $atom) {
if (empty($hash_to_file[$hash])) {
$atom_cache->deleteFileHash($hash);
}
}
}
private function getFilesToAtomize(array $file_hashes) {
$atom_cache = $this->getAtomCache();
$atomize = array();
foreach ($file_hashes as $file => $hash) {
if (!$atom_cache->fileHashExists($hash)) {
$atomize[] = $file;
}
}
return $atomize;
}
private function buildAtomizerFutures(array $file_atomizers) {
$atomizers = array();
foreach ($file_atomizers as $file => $atomizer) {
$atomizers[$atomizer][] = $file;
}
$root = dirname(phutil_get_library_root('phabricator'));
$config_root = $this->getConfig('root');
$bar = id(new PhutilConsoleProgressBar())
->setTotal(count($file_atomizers));
$futures = array();
foreach ($atomizers as $class => $files) {
foreach (array_chunk($files, 32) as $chunk) {
$future = new ExecFuture(
'%s atomize --ugly --book %s --atomizer %s -- %Ls',
$root.'/bin/diviner',
$this->getBookConfigPath(),
$class,
$chunk);
$future->setCWD($config_root);
$futures[] = $future;
$bar->update(count($chunk));
}
}
$bar->done();
return $futures;
}
private function resolveAtomizerFutures(array $futures, array $file_hashes) {
assert_instances_of($futures, 'Future');
$atom_cache = $this->getAtomCache();
$bar = id(new PhutilConsoleProgressBar())
->setTotal(count($futures));
$futures = id(new FutureIterator($futures))
->limit(4);
foreach ($futures as $key => $future) {
try {
$atoms = $future->resolveJSON();
foreach ($atoms as $atom) {
if ($atom['type'] == DivinerAtom::TYPE_FILE) {
$file_hash = $file_hashes[$atom['file']];
$atom_cache->addFileHash($file_hash, $atom['hash']);
}
$atom_cache->addAtom($atom);
}
} catch (Exception $e) {
phlog($e);
}
$bar->update(1);
}
$bar->done();
}
/**
* Get a global version number, which changes whenever any atom or atomizer
* implementation changes in a way which is not backward-compatible.
*/
private function getDivinerAtomWorldVersion() {
$version = array();
$version['atom'] = DivinerAtom::getAtomSerializationVersion();
$version['rules'] = $this->getRules();
$atomizers = id(new PhutilClassMapQuery())
->setAncestorClass('DivinerAtomizer')
->execute();
$atomizer_versions = array();
foreach ($atomizers as $atomizer) {
$name = get_class($atomizer);
$atomizer_versions[$name] = call_user_func(
array(
$name,
'getAtomizerVersion',
));
}
ksort($atomizer_versions);
$version['atomizers'] = $atomizer_versions;
return md5(serialize($version));
}
/* -( Graph Cache )-------------------------------------------------------- */
private function buildGraphCache() {
$this->log(pht('BUILDING GRAPH CACHE'));
$atom_cache = $this->getAtomCache();
$symbol_map = $atom_cache->getSymbolMap();
$atoms = $atom_cache->getAtomMap();
$dirty_symbols = array();
$dirty_nhashes = array();
$del_atoms = array_diff_key($symbol_map, $atoms);
$this->log(
pht(
'Found %s obsolete atom(s) in graph.',
phutil_count($del_atoms)));
foreach ($del_atoms as $nhash => $shash) {
$atom_cache->deleteSymbol($nhash);
$dirty_symbols[$shash] = true;
$atom_cache->deleteEdges($nhash);
$atom_cache->deleteGraph($nhash);
}
$new_atoms = array_diff_key($atoms, $symbol_map);
$this->log(
pht(
'Found %s new atom(s) in graph.',
phutil_count($new_atoms)));
foreach ($new_atoms as $nhash => $ignored) {
$shash = $this->computeSymbolHash($nhash);
$atom_cache->addSymbol($nhash, $shash);
$dirty_symbols[$shash] = true;
$atom_cache->addEdges($nhash, $this->getEdges($nhash));
$dirty_nhashes[$nhash] = true;
}
$this->log(pht('Propagating changes through the graph.'));
// Find all the nodes which point at a dirty node, and dirty them. Then
// find all the nodes which point at those nodes and dirty them, and so
// on. (This is slightly overkill since we probably don't need to propagate
// dirtiness across documentation "links" between symbols, but we do want
// to propagate it across "extends", and we suffer only a little bit of
// collateral damage by over-dirtying as long as the documentation isn't
// too well-connected.)
$symbol_stack = array_keys($dirty_symbols);
while ($symbol_stack) {
$symbol_hash = array_pop($symbol_stack);
foreach ($atom_cache->getEdgesWithDestination($symbol_hash) as $edge) {
$dirty_nhashes[$edge] = true;
$src_hash = $this->computeSymbolHash($edge);
if (empty($dirty_symbols[$src_hash])) {
$dirty_symbols[$src_hash] = true;
$symbol_stack[] = $src_hash;
}
}
}
$this->log(
pht(
'Found %s affected atoms.',
phutil_count($dirty_nhashes)));
foreach ($dirty_nhashes as $nhash => $ignored) {
$atom_cache->addGraph($nhash, $this->computeGraphHash($nhash));
}
$this->log(pht('Writing graph cache.'));
$atom_cache->saveGraph();
$atom_cache->saveEdges();
$atom_cache->saveSymbols();
$this->log(pht('Done.')."\n");
}
private function computeSymbolHash($node_hash) {
$atom_cache = $this->getAtomCache();
$atom = $atom_cache->getAtom($node_hash);
if (!$atom) {
throw new Exception(
pht("No such atom with node hash '%s'!", $node_hash));
}
$ref = DivinerAtomRef::newFromDictionary($atom['ref']);
return $ref->toHash();
}
private function getEdges($node_hash) {
$atom_cache = $this->getAtomCache();
$atom = $atom_cache->getAtom($node_hash);
$refs = array();
// Make the atom depend on its own symbol, so that all atoms with the same
// symbol are dirtied (e.g., if a codebase defines the function `f()`
// several times, all of them should be dirtied when one is dirtied).
$refs[DivinerAtomRef::newFromDictionary($atom)->toHash()] = true;
foreach (array_merge($atom['extends'], $atom['links']) as $ref_dict) {
$ref = DivinerAtomRef::newFromDictionary($ref_dict);
if ($ref->getBook() == $atom['book']) {
$refs[$ref->toHash()] = true;
}
}
return array_keys($refs);
}
private function computeGraphHash($node_hash) {
$atom_cache = $this->getAtomCache();
$atom = $atom_cache->getAtom($node_hash);
$edges = $this->getEdges($node_hash);
sort($edges);
$inputs = array(
'atomHash' => $atom['hash'],
'edges' => $edges,
);
return md5(serialize($inputs)).'G';
}
private function publishDocumentation($clean, DivinerPublisher $publisher) {
$atom_cache = $this->getAtomCache();
$graph_map = $atom_cache->getGraphMap();
$this->log(pht('PUBLISHING DOCUMENTATION'));
$publisher
->setDropCaches($clean)
->setConfig($this->getAllConfig())
->setAtomCache($atom_cache)
->setRenderer(new DivinerDefaultRenderer())
->publishAtoms(array_values($graph_map));
$this->log(pht('Done.'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/workflow/DivinerAtomizeWorkflow.php | src/applications/diviner/workflow/DivinerAtomizeWorkflow.php | <?php
final class DivinerAtomizeWorkflow extends DivinerWorkflow {
protected function didConstruct() {
$this
->setName('atomize')
->setSynopsis(pht('Build atoms from source.'))
->setArguments(
array(
array(
'name' => 'atomizer',
'param' => 'class',
'help' => pht('Specify a subclass of %s.', 'DivinerAtomizer'),
),
array(
'name' => 'book',
'param' => 'path',
'help' => pht('Path to a Diviner book configuration.'),
),
array(
'name' => 'files',
'wildcard' => true,
),
array(
'name' => 'ugly',
'help' => pht('Produce ugly (but faster) output.'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$this->readBookConfiguration($args->getArg('book'));
$console = PhutilConsole::getConsole();
$atomizer_class = $args->getArg('atomizer');
if (!$atomizer_class) {
throw new PhutilArgumentUsageException(
pht(
'Specify an atomizer class with %s.',
'--atomizer'));
}
$symbols = id(new PhutilSymbolLoader())
->setName($atomizer_class)
->setConcreteOnly(true)
->setAncestorClass('DivinerAtomizer')
->selectAndLoadSymbols();
if (!$symbols) {
throw new PhutilArgumentUsageException(
pht(
"Atomizer class '%s' must be a concrete subclass of %s.",
$atomizer_class,
'DivinerAtomizer'));
}
$atomizer = newv($atomizer_class, array());
$files = $args->getArg('files');
if (!$files) {
throw new Exception(pht('Specify one or more files to atomize.'));
}
$file_atomizer = new DivinerFileAtomizer();
foreach (array($atomizer, $file_atomizer) as $configure) {
$configure->setBook($this->getConfig('name'));
}
$group_rules = array();
foreach ($this->getConfig('groups', array()) as $group => $spec) {
$include = (array)idx($spec, 'include', array());
foreach ($include as $pattern) {
$group_rules[$pattern] = $group;
}
}
$all_atoms = array();
$context = array(
'group' => null,
);
foreach ($files as $file) {
$abs_path = Filesystem::resolvePath($file, $this->getConfig('root'));
$data = Filesystem::readFile($abs_path);
if (!$this->shouldAtomizeFile($file, $data)) {
$console->writeLog("%s\n", pht('Skipping %s...', $file));
continue;
} else {
$console->writeLog("%s\n", pht('Atomizing %s...', $file));
}
$context['group'] = null;
foreach ($group_rules as $rule => $group) {
if (preg_match($rule, $file)) {
$context['group'] = $group;
break;
}
}
$file_atoms = $file_atomizer->atomize($file, $data, $context);
$all_atoms[] = $file_atoms;
if (count($file_atoms) !== 1) {
throw new Exception(
pht('Expected exactly one atom from file atomizer.'));
}
$file_atom = head($file_atoms);
$atoms = $atomizer->atomize($file, $data, $context);
foreach ($atoms as $atom) {
if (!$atom->hasParent()) {
$file_atom->addChild($atom);
}
}
$all_atoms[] = $atoms;
}
$all_atoms = array_mergev($all_atoms);
$all_atoms = mpull($all_atoms, 'toDictionary');
$all_atoms = ipull($all_atoms, null, 'hash');
if ($args->getArg('ugly')) {
$json = json_encode($all_atoms);
} else {
$json = id(new PhutilJSON())->encodeFormatted($all_atoms);
}
$console->writeOut('%s', $json);
return 0;
}
private function shouldAtomizeFile($file_name, $file_data) {
return strpos($file_data, '@'.'undivinable') === false;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/workflow/DivinerWorkflow.php | src/applications/diviner/workflow/DivinerWorkflow.php | <?php
abstract class DivinerWorkflow extends PhabricatorManagementWorkflow {
private $config;
private $bookConfigPath;
public function getBookConfigPath() {
return $this->bookConfigPath;
}
protected function getConfig($key, $default = null) {
return idx($this->config, $key, $default);
}
protected function getAllConfig() {
return $this->config;
}
protected function readBookConfiguration($book_path) {
if ($book_path === null) {
throw new PhutilArgumentUsageException(
pht(
'Specify a Diviner book configuration file with %s.',
'--book'));
}
$book_data = Filesystem::readFile($book_path);
$book = phutil_json_decode($book_data);
PhutilTypeSpec::checkMap(
$book,
array(
'name' => 'string',
'title' => 'optional string',
'short' => 'optional string',
'preface' => 'optional string',
'root' => 'optional string',
'uri.source' => 'optional string',
'rules' => 'optional map<regex, string>',
'exclude' => 'optional regex|list<regex>',
'groups' => 'optional map<string, map<string, wild>>',
));
// If the book specifies a "root", resolve it; otherwise, use the directory
// the book configuration file lives in.
$full_path = dirname(Filesystem::resolvePath($book_path));
if (empty($book['root'])) {
$book['root'] = '.';
}
$book['root'] = Filesystem::resolvePath($book['root'], $full_path);
if (!preg_match('/^[a-z][a-z-]*\z/', $book['name'])) {
$name = $book['name'];
throw new PhutilArgumentUsageException(
pht(
"Book configuration '%s' has name '%s', but book names must ".
"include only lowercase letters and hyphens.",
$book_path,
$name));
}
foreach (idx($book, 'groups', array()) as $group) {
PhutilTypeSpec::checkMap(
$group,
array(
'name' => 'string',
'include' => 'optional regex|list<regex>',
));
}
$this->bookConfigPath = $book_path;
$this->config = $book;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/capability/DivinerDefaultViewCapability.php | src/applications/diviner/capability/DivinerDefaultViewCapability.php | <?php
final class DivinerDefaultViewCapability extends PhabricatorPolicyCapability {
const CAPABILITY = 'diviner.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/diviner/capability/DivinerDefaultEditCapability.php | src/applications/diviner/capability/DivinerDefaultEditCapability.php | <?php
final class DivinerDefaultEditCapability extends PhabricatorPolicyCapability {
const CAPABILITY = 'diviner.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/diviner/atom/DivinerAtomRef.php | src/applications/diviner/atom/DivinerAtomRef.php | <?php
final class DivinerAtomRef extends Phobject {
private $book;
private $context;
private $type;
private $name;
private $group;
private $summary;
private $index;
private $title;
public function getSortKey() {
return implode(
"\0",
array(
$this->getName(),
$this->getType(),
$this->getContext(),
$this->getBook(),
$this->getIndex(),
));
}
public function setIndex($index) {
$this->index = $index;
return $this;
}
public function getIndex() {
return $this->index;
}
public function setSummary($summary) {
$this->summary = $summary;
return $this;
}
public function getSummary() {
return $this->summary;
}
public function setName($name) {
$normal_name = self::normalizeString($name);
if (preg_match('/^@\d+\z/', $normal_name)) {
throw new Exception(
pht(
"Atom names must not be in the form '%s'. This pattern is ".
"reserved for disambiguating atoms with similar names.",
'/@\d+/'));
}
$this->name = $normal_name;
return $this;
}
public function getName() {
return $this->name;
}
public function setType($type) {
$this->type = self::normalizeString($type);
return $this;
}
public function getType() {
return $this->type;
}
public function setContext($context) {
if ($context === null) {
$this->context = $context;
} else {
$this->context = self::normalizeString($context);
}
return $this;
}
public function getContext() {
return $this->context;
}
public function setBook($book) {
if ($book === null) {
$this->book = $book;
} else {
$this->book = self::normalizeString($book);
}
return $this;
}
public function getBook() {
return $this->book;
}
public function setGroup($group) {
$this->group = $group;
return $this;
}
public function getGroup() {
return $this->group;
}
public function setTitle($title) {
$this->title = $title;
return $this;
}
public function getTitle() {
return $this->title;
}
public function getTitleSlug() {
return self::normalizeTitleString($this->getTitle());
}
public function toDictionary() {
return array(
'book' => $this->getBook(),
'context' => $this->getContext(),
'type' => $this->getType(),
'name' => $this->getName(),
'group' => $this->getGroup(),
'summary' => $this->getSummary(),
'index' => $this->getIndex(),
'title' => $this->getTitle(),
);
}
public function toHash() {
$dict = $this->toDictionary();
unset($dict['group']);
unset($dict['index']);
unset($dict['summary']);
unset($dict['title']);
ksort($dict);
return md5(serialize($dict)).'S';
}
public static function newFromDictionary(array $dict) {
return id(new DivinerAtomRef())
->setBook(idx($dict, 'book'))
->setContext(idx($dict, 'context'))
->setType(idx($dict, 'type'))
->setName(idx($dict, 'name'))
->setGroup(idx($dict, 'group'))
->setSummary(idx($dict, 'summary'))
->setIndex(idx($dict, 'index'))
->setTitle(idx($dict, 'title'));
}
public static function normalizeString($str) {
// These characters create problems on the filesystem or in URIs. Replace
// them with non-problematic approximations (instead of simply removing
// them) to keep the URIs fairly useful and avoid unnecessary collisions.
// These approximations are selected based on some domain knowledge of
// common languages: where a character is used as a delimiter, it is more
// helpful to replace it with a "." or a ":" or similar, while it's better
// if operator overloads read as, e.g., "operator_div".
$map = array(
// Hopefully not used anywhere by anything.
'#' => '.',
// Used in Ruby methods.
'?' => 'Q',
// Used in PHP namespaces.
'\\' => '.',
// Used in "operator +" in C++.
'+' => 'plus',
// Used in "operator %" in C++.
'%' => 'mod',
// Used in "operator /" in C++.
'/' => 'div',
);
$str = str_replace(array_keys($map), array_values($map), $str);
// Replace all spaces with underscores.
$str = preg_replace('/ +/', '_', $str);
// Replace control characters with "X".
$str = preg_replace('/[\x00-\x19]/', 'X', $str);
// Replace specific problematic names with alternative names.
$alternates = array(
'.' => 'dot',
'..' => 'dotdot',
'' => 'null',
);
return idx($alternates, $str, $str);
}
public static function normalizeTitleString($str) {
// Remove colons from titles. This is mostly to accommodate legacy rules
// from the old Diviner, which generated a significant number of article
// URIs without colons present in the titles.
$str = str_replace(':', '', $str);
$str = self::normalizeString($str);
return phutil_utf8_strtolower($str);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/atom/DivinerAtom.php | src/applications/diviner/atom/DivinerAtom.php | <?php
final class DivinerAtom extends Phobject {
const TYPE_ARTICLE = 'article';
const TYPE_CLASS = 'class';
const TYPE_FILE = 'file';
const TYPE_FUNCTION = 'function';
const TYPE_INTERFACE = 'interface';
const TYPE_METHOD = 'method';
private $type;
private $name;
private $file;
private $line;
private $hash;
private $contentRaw;
private $length;
private $language;
private $docblockRaw;
private $docblockText;
private $docblockMeta;
private $warnings = array();
private $parent;
private $parentHash;
private $children = array();
private $childHashes = array();
private $context;
private $extends = array();
private $links = array();
private $book;
private $properties = array();
/**
* Returns a sorting key which imposes an unambiguous, stable order on atoms.
*/
public function getSortKey() {
return implode(
"\0",
array(
$this->getBook(),
$this->getType(),
$this->getContext(),
$this->getName(),
$this->getFile(),
sprintf('%08d', $this->getLine()),
));
}
public function setBook($book) {
$this->book = $book;
return $this;
}
public function getBook() {
return $this->book;
}
public function setContext($context) {
$this->context = $context;
return $this;
}
public function getContext() {
return $this->context;
}
public static function getAtomSerializationVersion() {
return 2;
}
public function addWarning($warning) {
$this->warnings[] = $warning;
return $this;
}
public function getWarnings() {
return $this->warnings;
}
public function setDocblockRaw($docblock_raw) {
$this->docblockRaw = $docblock_raw;
if ($docblock_raw !== null) {
$parser = new PhutilDocblockParser();
list($text, $meta) = $parser->parse($docblock_raw);
$this->docblockText = $text;
$this->docblockMeta = $meta;
} else {
$this->docblockText = null;
$this->docblockMeta = null;
}
return $this;
}
public function getDocblockRaw() {
return $this->docblockRaw;
}
public function getDocblockText() {
if ($this->docblockText === null) {
throw new PhutilInvalidStateException('setDocblockRaw');
}
return $this->docblockText;
}
public function getDocblockMeta() {
if ($this->docblockMeta === null) {
throw new PhutilInvalidStateException('setDocblockRaw');
}
return $this->docblockMeta;
}
public function getDocblockMetaValue($key, $default = null) {
$meta = $this->getDocblockMeta();
return idx($meta, $key, $default);
}
public function setDocblockMetaValue($key, $value) {
$meta = $this->getDocblockMeta();
$meta[$key] = $value;
$this->docblockMeta = $meta;
return $this;
}
public function setType($type) {
$this->type = $type;
return $this;
}
public function getType() {
return $this->type;
}
public function setName($name) {
$this->name = $name;
return $this;
}
public function getName() {
return $this->name;
}
public function setFile($file) {
$this->file = $file;
return $this;
}
public function getFile() {
return $this->file;
}
public function setLine($line) {
$this->line = $line;
return $this;
}
public function getLine() {
return $this->line;
}
public function setContentRaw($content_raw) {
$this->contentRaw = $content_raw;
return $this;
}
public function getContentRaw() {
return $this->contentRaw;
}
public function setHash($hash) {
$this->hash = $hash;
return $this;
}
public function addLink(DivinerAtomRef $ref) {
$this->links[] = $ref;
return $this;
}
public function addExtends(DivinerAtomRef $ref) {
$this->extends[] = $ref;
return $this;
}
public function getLinkDictionaries() {
return mpull($this->links, 'toDictionary');
}
public function getExtendsDictionaries() {
return mpull($this->extends, 'toDictionary');
}
public function getExtends() {
return $this->extends;
}
public function getHash() {
if ($this->hash) {
return $this->hash;
}
$parts = array(
$this->getBook(),
$this->getType(),
$this->getName(),
$this->getFile(),
$this->getLine(),
$this->getLength(),
$this->getLanguage(),
$this->getContentRaw(),
$this->getDocblockRaw(),
$this->getProperties(),
$this->getChildHashes(),
mpull($this->extends, 'toHash'),
mpull($this->links, 'toHash'),
);
$this->hash = md5(serialize($parts)).'N';
return $this->hash;
}
public function setLength($length) {
$this->length = $length;
return $this;
}
public function getLength() {
return $this->length;
}
public function setLanguage($language) {
$this->language = $language;
return $this;
}
public function getLanguage() {
return $this->language;
}
public function addChildHash($child_hash) {
$this->childHashes[] = $child_hash;
return $this;
}
public function getChildHashes() {
if (!$this->childHashes && $this->children) {
$this->childHashes = mpull($this->children, 'getHash');
}
return $this->childHashes;
}
public function setParentHash($parent_hash) {
if ($this->parentHash) {
throw new Exception(pht('Atom already has a parent!'));
}
$this->parentHash = $parent_hash;
return $this;
}
public function hasParent() {
return $this->parent || $this->parentHash;
}
public function setParent(DivinerAtom $atom) {
if ($this->parentHash) {
throw new Exception(pht('Parent hash has already been computed!'));
}
$this->parent = $atom;
return $this;
}
public function getParentHash() {
if ($this->parent && !$this->parentHash) {
$this->parentHash = $this->parent->getHash();
}
return $this->parentHash;
}
public function addChild(DivinerAtom $atom) {
if ($this->childHashes) {
throw new Exception(pht('Child hashes have already been computed!'));
}
$atom->setParent($this);
$this->children[] = $atom;
return $this;
}
public function getURI() {
$parts = array();
$parts[] = phutil_escape_uri_path_component($this->getType());
if ($this->getContext()) {
$parts[] = phutil_escape_uri_path_component($this->getContext());
}
$parts[] = phutil_escape_uri_path_component($this->getName());
$parts[] = null;
return implode('/', $parts);
}
public function toDictionary() {
// NOTE: If you change this format, bump the format version in
// @{method:getAtomSerializationVersion}.
return array(
'book' => $this->getBook(),
'type' => $this->getType(),
'name' => $this->getName(),
'file' => $this->getFile(),
'line' => $this->getLine(),
'hash' => $this->getHash(),
'uri' => $this->getURI(),
'length' => $this->getLength(),
'context' => $this->getContext(),
'language' => $this->getLanguage(),
'docblockRaw' => $this->getDocblockRaw(),
'warnings' => $this->getWarnings(),
'parentHash' => $this->getParentHash(),
'childHashes' => $this->getChildHashes(),
'extends' => $this->getExtendsDictionaries(),
'links' => $this->getLinkDictionaries(),
'ref' => $this->getRef()->toDictionary(),
'properties' => $this->getProperties(),
);
}
public function getRef() {
$title = null;
if ($this->docblockMeta) {
$title = $this->getDocblockMetaValue('title');
}
return id(new DivinerAtomRef())
->setBook($this->getBook())
->setContext($this->getContext())
->setType($this->getType())
->setName($this->getName())
->setTitle($title)
->setGroup($this->getProperty('group'));
}
public static function newFromDictionary(array $dictionary) {
$atom = id(new DivinerAtom())
->setBook(idx($dictionary, 'book'))
->setType(idx($dictionary, 'type'))
->setName(idx($dictionary, 'name'))
->setFile(idx($dictionary, 'file'))
->setLine(idx($dictionary, 'line'))
->setHash(idx($dictionary, 'hash'))
->setLength(idx($dictionary, 'length'))
->setContext(idx($dictionary, 'context'))
->setLanguage(idx($dictionary, 'language'))
->setParentHash(idx($dictionary, 'parentHash'))
->setDocblockRaw(idx($dictionary, 'docblockRaw'))
->setProperties(idx($dictionary, 'properties'));
foreach (idx($dictionary, 'warnings', array()) as $warning) {
$atom->addWarning($warning);
}
foreach (idx($dictionary, 'childHashes', array()) as $child) {
$atom->addChildHash($child);
}
foreach (idx($dictionary, 'extends', array()) as $extends) {
$atom->addExtends(DivinerAtomRef::newFromDictionary($extends));
}
return $atom;
}
public function getProperty($key, $default = null) {
return idx($this->properties, $key, $default);
}
public function setProperty($key, $value) {
$this->properties[$key] = $value;
return $this;
}
public function getProperties() {
return $this->properties;
}
public function setProperties(array $properties) {
$this->properties = $properties;
return $this;
}
public static function getThisAtomIsNotDocumentedString($type) {
switch ($type) {
case self::TYPE_ARTICLE:
return pht('This article is not documented.');
case self::TYPE_CLASS:
return pht('This class is not documented.');
case self::TYPE_FILE:
return pht('This file is not documented.');
case self::TYPE_FUNCTION:
return pht('This function is not documented.');
case self::TYPE_INTERFACE:
return pht('This interface is not documented.');
case self::TYPE_METHOD:
return pht('This method is not documented.');
default:
phlog(pht("Need translation for '%s'.", $type));
return pht('This %s is not documented.', $type);
}
}
public static function getAllTypes() {
return array(
self::TYPE_ARTICLE,
self::TYPE_CLASS,
self::TYPE_FILE,
self::TYPE_FUNCTION,
self::TYPE_INTERFACE,
self::TYPE_METHOD,
);
}
public static function getAtomTypeNameString($type) {
switch ($type) {
case self::TYPE_ARTICLE:
return pht('Article');
case self::TYPE_CLASS:
return pht('Class');
case self::TYPE_FILE:
return pht('File');
case self::TYPE_FUNCTION:
return pht('Function');
case self::TYPE_INTERFACE:
return pht('Interface');
case self::TYPE_METHOD:
return pht('Method');
default:
phlog(pht("Need translation for '%s'.", $type));
return ucwords($type);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diviner/markup/DivinerSymbolRemarkupRule.php | src/applications/diviner/markup/DivinerSymbolRemarkupRule.php | <?php
final class DivinerSymbolRemarkupRule extends PhutilRemarkupRule {
const KEY_RULE_ATOM_REF = 'rule.diviner.atomref';
public function getPriority() {
return 200.0;
}
public function apply($text) {
// Grammar here is:
//
// rule = '@{' maybe_type name maybe_title '}'
// maybe_type = null | type ':' | type '@' book ':'
// name = name | name '@' context
// maybe_title = null | '|' title
//
// So these are all valid:
//
// @{name}
// @{type : name}
// @{name | title}
// @{type @ book : name @ context | title}
return preg_replace_callback(
'/(?:^|\B)@{'.
'(?:(?P<type>[^:]+?):)?'.
'(?P<name>[^}|]+?)'.
'(?:[|](?P<title>[^}]+))?'.
'}/',
array($this, 'markupSymbol'),
$text);
}
public function markupSymbol(array $matches) {
if (!$this->isFlatText($matches[0])) {
return $matches[0];
}
$type = (string)idx($matches, 'type');
$name = (string)$matches['name'];
$title = (string)idx($matches, 'title');
// Collapse sequences of whitespace into a single space.
$type = preg_replace('/\s+/', ' ', trim($type));
$name = preg_replace('/\s+/', ' ', trim($name));
$title = preg_replace('/\s+/', ' ', trim($title));
$ref = array();
if (strpos($type, '@') !== false) {
list($type, $book) = explode('@', $type, 2);
$ref['type'] = trim($type);
$ref['book'] = trim($book);
} else {
$ref['type'] = $type;
}
if (strpos($name, '@') !== false) {
list($name, $context) = explode('@', $name, 2);
$ref['name'] = trim($name);
$ref['context'] = trim($context);
} else {
$ref['name'] = $name;
}
$ref['title'] = nonempty($title, $name);
foreach ($ref as $key => $value) {
if ($value === '') {
unset($ref[$key]);
}
}
$engine = $this->getEngine();
$token = $engine->storeText('');
$key = self::KEY_RULE_ATOM_REF;
$data = $engine->getTextMetadata($key, array());
$data[$token] = $ref;
$engine->setTextMetadata($key, $data);
return $token;
}
public function didMarkupText() {
$engine = $this->getEngine();
$key = self::KEY_RULE_ATOM_REF;
$data = $engine->getTextMetadata($key, array());
$renderer = $engine->getConfig('diviner.renderer');
foreach ($data as $token => $ref_dict) {
$ref = DivinerAtomRef::newFromDictionary($ref_dict);
$title = $ref->getTitle();
$href = null;
if ($renderer) {
// Here, we're generating documentation. If possible, we want to find
// the real atom ref so we can render the correct default title and
// render invalid links in an alternate style.
$ref = $renderer->normalizeAtomRef($ref);
if ($ref) {
$title = nonempty($ref->getTitle(), $ref->getName());
$href = $renderer->getHrefForAtomRef($ref);
}
} else {
// Here, we're generating comment text or something like that. Just
// link to Diviner and let it sort things out.
$params = array(
'book' => $ref->getBook(),
'name' => $ref->getName(),
'type' => $ref->getType(),
'context' => $ref->getContext(),
'jump' => true,
);
$href = new PhutilURI('/diviner/find/', $params);
}
// TODO: This probably is not the best place to do this. Move it somewhere
// better when it becomes more clear where it should actually go.
if ($ref) {
switch ($ref->getType()) {
case 'function':
case 'method':
$title = $title.'()';
break;
}
}
if ($this->getEngine()->isTextMode()) {
if ($href) {
$link = $title.' <'.PhabricatorEnv::getProductionURI($href).'>';
} else {
$link = $title;
}
} else if ($href) {
if ($this->getEngine()->isHTMLMailMode()) {
$href = PhabricatorEnv::getProductionURI($href);
}
$link = $this->newTag(
'a',
array(
'class' => 'atom-ref',
'href' => $href,
),
$title);
} else {
$link = $this->newTag(
'span',
array(
'class' => 'atom-ref-invalid',
),
$title);
}
$engine->overwriteStoredText($token, $link);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/console/controller/DarkConsoleDataController.php | src/applications/console/controller/DarkConsoleDataController.php | <?php
final class DarkConsoleDataController extends PhabricatorController {
public function shouldRequireLogin() {
return !PhabricatorEnv::getEnvConfig('darkconsole.always-on');
}
public function shouldRequireEnabledUser() {
return !PhabricatorEnv::getEnvConfig('darkconsole.always-on');
}
public function shouldAllowPartialSessions() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$key = $request->getURIData('key');
$cache = new PhabricatorKeyValueDatabaseCache();
$cache = new PhutilKeyValueCacheProfiler($cache);
$cache->setProfiler(PhutilServiceProfiler::getInstance());
$result = $cache->getKey('darkconsole:'.$key);
if (!$result) {
return new Aphront400Response();
}
try {
$result = phutil_json_decode($result);
} catch (PhutilJSONParserException $ex) {
return new Aphront400Response();
}
if ($result['vers'] != DarkConsoleCore::STORAGE_VERSION) {
return new Aphront400Response();
}
if ($result['user'] != $viewer->getPHID()) {
return new Aphront400Response();
}
$output = array();
$output['tabs'] = $result['tabs'];
$output['panel'] = array();
foreach ($result['data'] as $class => $data) {
try {
$obj = newv($class, array());
$obj->setData($data);
$obj->setRequest($request);
$panel = $obj->renderPanel();
// Because cookie names can now be prefixed, wipe out any cookie value
// with the session cookie name anywhere in its name.
$pattern = '('.preg_quote(PhabricatorCookies::COOKIE_SESSION).')';
foreach ($_COOKIE as $cookie_name => $cookie_value) {
if (preg_match($pattern, $cookie_name)) {
$panel = PhutilSafeHTML::applyFunction(
'str_replace',
$cookie_value,
'(session-key)',
$panel);
}
}
$output['panel'][$class] = $panel;
} catch (Exception $ex) {
$output['panel'][$class] = 'error';
}
}
return id(new AphrontAjaxResponse())->setContent($output);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/console/controller/DarkConsoleController.php | src/applications/console/controller/DarkConsoleController.php | <?php
final class DarkConsoleController extends PhabricatorController {
protected $op;
protected $data;
public function shouldRequireLogin() {
return !PhabricatorEnv::getEnvConfig('darkconsole.always-on');
}
public function shouldRequireEnabledUser() {
return !PhabricatorEnv::getEnvConfig('darkconsole.always-on');
}
public function shouldAllowPartialSessions() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$response = id(new AphrontAjaxResponse())->setDisableConsole(true);
if (!$viewer->isLoggedIn()) {
return $response;
}
$visible = $request->getStr('visible');
if (phutil_nonempty_string($visible)) {
$this->writeDarkConsoleSetting(
PhabricatorDarkConsoleVisibleSetting::SETTINGKEY,
(int)$visible);
return $response;
}
$tab = $request->getStr('tab');
if (phutil_nonempty_string($tab)) {
$this->writeDarkConsoleSetting(
PhabricatorDarkConsoleTabSetting::SETTINGKEY,
$tab);
return $response;
}
return new Aphront404Response();
}
private function writeDarkConsoleSetting($key, $value) {
$viewer = $this->getViewer();
$request = $this->getRequest();
$preferences = PhabricatorUserPreferences::loadUserPreferences($viewer);
$editor = id(new PhabricatorUserPreferencesEditor())
->setActor($viewer)
->setContentSourceFromRequest($request)
->setContinueOnNoEffect(true)
->setContinueOnMissingFields(true);
$xactions = array();
$xactions[] = $preferences->newTransaction($key, $value);
$editor->applyTransactions($preferences, $xactions);
// Reload the user to regenerate their preferences cache. If we don't
// do this, the "Services" tab gets misleadingly spammed up with cache
// fills that are only filling because you toggled the console or switched
// tabs. This makes it harder to see what's really going on, so just force
// a cache regeneration here.
id(new PhabricatorPeopleQuery())
->setViewer($viewer)
->withPHIDs(array($viewer->getPHID()))
->needUserSettings(true)
->execute();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/console/plugin/DarkConsoleRequestPlugin.php | src/applications/console/plugin/DarkConsoleRequestPlugin.php | <?php
final class DarkConsoleRequestPlugin extends DarkConsolePlugin {
public function getName() {
return pht('Request');
}
public function getDescription() {
return pht(
'Information about %s and %s.',
'$_REQUEST',
'$_SERVER');
}
public function generateData() {
$addr = idx($_SERVER, 'SERVER_ADDR');
if ($addr) {
$hostname = @gethostbyaddr($addr);
} else {
$hostname = null;
}
$controller = $this->getRequest()->getController();
if ($controller) {
$controller_class = get_class($controller);
} else {
$controller_class = null;
}
$site = $this->getRequest()->getSite();
if ($site) {
$site_class = get_class($site);
} else {
$site_class = null;
}
return array(
'request' => $_REQUEST,
'server' => $_SERVER,
'special' => array(
'site' => $site_class,
'controller' => $controller_class,
'machine' => php_uname('n'),
'host' => $addr,
'hostname' => $hostname,
),
);
}
public function renderPanel() {
$data = $this->getData();
$special_map = array(
'site' => pht('Site'),
'controller' => pht('Controller'),
'machine' => pht('Machine'),
'host' => pht('Host'),
'hostname' => pht('Hostname'),
);
$special = idx($data, 'special', array());
$rows = array();
foreach ($special_map as $key => $label) {
$rows[] = array(
$label,
idx($special, $key),
);
}
$sections = array();
$sections[] = array(
'name' => pht('Basics'),
'rows' => $rows,
);
$mask = array(
'HTTP_COOKIE' => true,
'HTTP_X_PHABRICATOR_CSRF' => true,
);
$maps = array(
array(
'name' => pht('Request'),
'data' => idx($data, 'request', array()),
),
array(
'name' => pht('Server'),
'data' => idx($data, 'server', array()),
),
);
foreach ($maps as $map) {
$data = $map['data'];
$rows = array();
foreach ($data as $key => $value) {
if (isset($mask[$key])) {
$value = phutil_tag('em', array(), pht('(Masked)'));
} else if (is_array($value)) {
$value = @json_encode($value);
} else {
$value = $value;
}
$rows[] = array(
$key,
$value,
);
}
$sections[] = array(
'name' => $map['name'],
'rows' => $rows,
);
}
$out = array();
foreach ($sections as $section) {
$out[] = id(new AphrontTableView($section['rows']))
->setHeaders(
array(
$section['name'],
null,
))
->setColumnClasses(
array(
'header',
'wide wrap',
));
}
return $out;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/console/plugin/DarkConsoleServicesPlugin.php | src/applications/console/plugin/DarkConsoleServicesPlugin.php | <?php
final class DarkConsoleServicesPlugin extends DarkConsolePlugin {
protected $observations;
public function getName() {
return pht('Services');
}
public function getDescription() {
return pht('Information about services.');
}
public static function getQueryAnalyzerHeader() {
return 'X-Phabricator-QueryAnalyzer';
}
public static function isQueryAnalyzerRequested() {
if (!empty($_REQUEST['__analyze__'])) {
return true;
}
$header = AphrontRequest::getHTTPHeader(self::getQueryAnalyzerHeader());
if ($header) {
return true;
}
return false;
}
public function didStartup() {
$should_analyze = self::isQueryAnalyzerRequested();
if ($should_analyze) {
PhutilServiceProfiler::getInstance()
->setCollectStackTraces(true);
}
return null;
}
/**
* @phutil-external-symbol class PhabricatorStartup
*/
public function generateData() {
$should_analyze = self::isQueryAnalyzerRequested();
$log = PhutilServiceProfiler::getInstance()->getServiceCallLog();
foreach ($log as $key => $entry) {
$config = idx($entry, 'config', array());
unset($log[$key]['config']);
if (!$should_analyze) {
$log[$key]['explain'] = array(
'sev' => 7,
'size' => null,
'reason' => pht('Disabled'),
);
// Query analysis is disabled for this request, so don't do any of it.
continue;
}
if ($entry['type'] != 'query') {
continue;
}
// For each SELECT query, go issue an EXPLAIN on it so we can flag stuff
// causing table scans, etc.
if (preg_match('/^\s*SELECT\b/i', $entry['query'])) {
$conn = PhabricatorDatabaseRef::newRawConnection($entry['config']);
try {
$explain = queryfx_all(
$conn,
'EXPLAIN %Q',
$entry['query']);
$badness = 0;
$size = 1;
$reason = null;
foreach ($explain as $table) {
$size *= (int)$table['rows'];
switch ($table['type']) {
case 'index':
$cur_badness = 1;
$cur_reason = 'Index';
break;
case 'const':
$cur_badness = 1;
$cur_reason = 'Const';
break;
case 'eq_ref';
$cur_badness = 2;
$cur_reason = 'EqRef';
break;
case 'range':
$cur_badness = 3;
$cur_reason = 'Range';
break;
case 'ref':
$cur_badness = 3;
$cur_reason = 'Ref';
break;
case 'fulltext':
$cur_badness = 3;
$cur_reason = 'Fulltext';
break;
case 'ALL':
if (preg_match('/Using where/', $table['Extra'])) {
if ($table['rows'] < 256 && !empty($table['possible_keys'])) {
$cur_badness = 2;
$cur_reason = pht('Small Table Scan');
} else {
$cur_badness = 6;
$cur_reason = pht('TABLE SCAN!');
}
} else {
$cur_badness = 3;
$cur_reason = pht('Whole Table');
}
break;
default:
if (preg_match('/No tables used/i', $table['Extra'])) {
$cur_badness = 1;
$cur_reason = pht('No Tables');
} else if (preg_match('/Impossible/i', $table['Extra'])) {
$cur_badness = 1;
$cur_reason = pht('Empty');
} else {
$cur_badness = 4;
$cur_reason = pht("Can't Analyze");
}
break;
}
if ($cur_badness > $badness) {
$badness = $cur_badness;
$reason = $cur_reason;
}
}
$log[$key]['explain'] = array(
'sev' => $badness,
'size' => $size,
'reason' => $reason,
);
} catch (Exception $ex) {
$log[$key]['explain'] = array(
'sev' => 5,
'size' => null,
'reason' => $ex->getMessage(),
);
}
}
}
return array(
'start' => PhabricatorStartup::getStartTime(),
'end' => microtime(true),
'log' => $log,
'analyzeURI' => (string)$this
->getRequestURI()
->alter('__analyze__', true),
'didAnalyze' => $should_analyze,
);
}
public function renderPanel() {
$data = $this->getData();
$log = $data['log'];
$results = array();
$results[] = phutil_tag(
'div',
array('class' => 'dark-console-panel-header'),
array(
phutil_tag(
'a',
array(
'href' => $data['analyzeURI'],
'class' => $data['didAnalyze'] ?
'disabled button' : 'button button-green',
),
pht('Analyze Query Plans')),
phutil_tag('h1', array(), pht('Calls to External Services')),
phutil_tag('div', array('style' => 'clear: both;')),
));
$page_total = $data['end'] - $data['start'];
$totals = array();
$counts = array();
foreach ($log as $row) {
$totals[$row['type']] = idx($totals, $row['type'], 0) + $row['duration'];
$counts[$row['type']] = idx($counts, $row['type'], 0) + 1;
}
$totals['All Services'] = array_sum($totals);
$counts['All Services'] = array_sum($counts);
$totals['Entire Page'] = $page_total;
$counts['Entire Page'] = 0;
$summary = array();
foreach ($totals as $type => $total) {
$summary[] = array(
$type,
number_format($counts[$type]),
pht('%s us', new PhutilNumber((int)(1000000 * $totals[$type]))),
sprintf('%.1f%%', 100 * $totals[$type] / $page_total),
);
}
$summary_table = new AphrontTableView($summary);
$summary_table->setColumnClasses(
array(
'',
'n',
'n',
'wide',
));
$summary_table->setHeaders(
array(
pht('Type'),
pht('Count'),
pht('Total Cost'),
pht('Page Weight'),
));
$results[] = $summary_table->render();
$rows = array();
foreach ($log as $row) {
$analysis = null;
switch ($row['type']) {
case 'query':
$info = $row['query'];
$info = wordwrap($info, 128, "\n", true);
if (!empty($row['explain'])) {
$analysis = phutil_tag(
'span',
array(
'class' => 'explain-sev-'.$row['explain']['sev'],
),
$row['explain']['reason']);
}
break;
case 'connect':
$info = $row['host'].':'.$row['database'];
break;
case 'exec':
$info = $row['command'];
break;
case 's3':
case 'conduit':
$info = $row['method'];
break;
case 'http':
$info = $row['uri'];
break;
default:
$info = '-';
break;
}
$offset = ($row['begin'] - $data['start']);
$rows[] = array(
$row['type'],
pht('+%s ms', new PhutilNumber(1000 * $offset)),
pht('%s us', new PhutilNumber(1000000 * $row['duration'])),
$info,
$analysis,
);
if (isset($row['trace'])) {
$rows[] = array(
null,
null,
null,
$row['trace'],
null,
);
}
}
$table = new AphrontTableView($rows);
$table->setColumnClasses(
array(
null,
'n',
'n',
'wide prewrap',
'',
));
$table->setHeaders(
array(
pht('Event'),
pht('Start'),
pht('Duration'),
pht('Details'),
pht('Analysis'),
));
$results[] = $table->render();
return phutil_implode_html("\n", $results);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/console/plugin/DarkConsoleXHProfPlugin.php | src/applications/console/plugin/DarkConsoleXHProfPlugin.php | <?php
final class DarkConsoleXHProfPlugin extends DarkConsolePlugin {
protected $profileFilePHID;
public function getName() {
return pht('XHProf');
}
public function getColor() {
$data = $this->getData();
if ($data['profileFilePHID']) {
return '#ff00ff';
}
return null;
}
public function getDescription() {
return pht('Provides detailed PHP profiling information through XHProf.');
}
public function generateData() {
return array(
'profileFilePHID' => $this->profileFilePHID,
'profileURI' => (string)$this
->getRequestURI()
->alter('__profile__', 'page'),
);
}
public function getXHProfRunID() {
return $this->profileFilePHID;
}
public function renderPanel() {
$data = $this->getData();
$run = $data['profileFilePHID'];
$profile_uri = $data['profileURI'];
if (!DarkConsoleXHProfPluginAPI::isProfilerAvailable()) {
$href = PhabricatorEnv::getDoclink('Installation Guide');
$install_guide = phutil_tag(
'a',
array(
'href' => $href,
'class' => 'bright-link',
),
pht('Installation Guide'));
return hsprintf(
'<div class="dark-console-no-content">%s</div>',
pht(
'The "xhprof" PHP extension is not available. Install xhprof '.
'to enable the XHProf console plugin. You can find instructions in '.
'the %s.',
$install_guide));
}
$result = array();
$header = phutil_tag(
'div',
array('class' => 'dark-console-panel-header'),
array(
phutil_tag(
'a',
array(
'href' => $profile_uri,
'class' => $run ? 'disabled button' : 'button button-green',
),
pht('Profile Page')),
phutil_tag('h1', array(), pht('XHProf Profiler')),
));
$result[] = $header;
if ($run) {
$result[] = phutil_tag(
'a',
array(
'href' => "/xhprof/profile/$run/",
'class' => 'bright-link',
'style' => 'float: right; margin: 1em 2em 0 0; font-weight: bold;',
'target' => '_blank',
),
pht('Profile Permalink'));
$result[] = phutil_tag(
'iframe',
array('src' => "/xhprof/profile/$run/?frame=true"));
} else {
$result[] = phutil_tag(
'div',
array('class' => 'dark-console-no-content'),
pht(
'Profiling was not enabled for this page. Use the button above '.
'to enable it.'));
}
return phutil_implode_html("\n", $result);
}
public function willShutdown() {
$this->profileFilePHID = DarkConsoleXHProfPluginAPI::getProfileFilePHID();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/console/plugin/DarkConsoleStartupPlugin.php | src/applications/console/plugin/DarkConsoleStartupPlugin.php | <?php
final class DarkConsoleStartupPlugin extends DarkConsolePlugin {
public function getName() {
return pht('Startup');
}
public function getDescription() {
return pht('Timing information about the startup sequence.');
}
/**
* @phutil-external-symbol class PhabricatorStartup
*/
public function generateData() {
return PhabricatorStartup::getPhases();
}
public function renderPanel() {
$data = $this->getData();
// Compute the time offset and duration of each startup phase.
$prev_key = null;
$init = null;
$phases = array();
foreach ($data as $key => $value) {
if ($init === null) {
$init = $value;
}
$offset = (int)floor(1000 * ($value - $init));
$phases[$key] = array(
'time' => $value,
'offset' => $value - $init,
);
if ($prev_key !== null) {
$phases[$prev_key]['duration'] = $value - $phases[$prev_key]['time'];
}
$prev_key = $key;
}
// Render the phases.
$rows = array();
foreach ($phases as $key => $phase) {
$offset_ms = (int)floor(1000 * $phase['offset']);
if (isset($phase['duration'])) {
$duration_us = (int)floor(1000000 * $phase['duration']);
} else {
$duration_us = null;
}
$rows[] = array(
$key,
pht('+%s ms', new PhutilNumber($offset_ms)),
($duration_us === null)
? pht('-')
: pht('%s us', new PhutilNumber($duration_us)),
null,
);
}
return id(new AphrontTableView($rows))
->setHeaders(
array(
pht('Phase'),
pht('Offset'),
pht('Duration'),
null,
))
->setColumnClasses(
array(
'',
'n right',
'n right',
'wide',
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/console/plugin/DarkConsolePlugin.php | src/applications/console/plugin/DarkConsolePlugin.php | <?php
abstract class DarkConsolePlugin extends Phobject {
private $data;
private $request;
private $core;
abstract public function getName();
abstract public function getDescription();
abstract public function renderPanel();
public function __construct() {}
public function getColor() {
return null;
}
final public function getOrderKey() {
return sprintf(
'%09d%s',
(int)(999999999 * $this->getOrder()),
$this->getName());
}
public function getOrder() {
return 1.0;
}
public function setConsoleCore(DarkConsoleCore $core) {
$this->core = $core;
return $this;
}
public function getConsoleCore() {
return $this->core;
}
public function generateData() {
return null;
}
public function setData($data) {
$this->data = $data;
return $this;
}
public function getData() {
return $this->data;
}
public function setRequest($request) {
$this->request = $request;
return $this;
}
public function getRequest() {
return $this->request;
}
public function getRequestURI() {
return $this->getRequest()->getRequestURI();
}
public function didStartup() {
return null;
}
public function willShutdown() {
return null;
}
public function didShutdown() {
return null;
}
public function processRequest() {
return null;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/console/plugin/DarkConsoleEventPlugin.php | src/applications/console/plugin/DarkConsoleEventPlugin.php | <?php
final class DarkConsoleEventPlugin extends DarkConsolePlugin {
public function getName() {
return pht('Events');
}
public function getDescription() {
return pht('Information about events and event listeners.');
}
public function generateData() {
$listeners = PhutilEventEngine::getInstance()->getAllListeners();
foreach ($listeners as $key => $listener) {
$listeners[$key] = array(
'id' => $listener->getListenerID(),
'class' => get_class($listener),
);
}
$events = DarkConsoleEventPluginAPI::getEvents();
foreach ($events as $key => $event) {
$events[$key] = array(
'type' => $event->getType(),
'stopped' => $event->isStopped(),
);
}
return array(
'listeners' => $listeners,
'events' => $events,
);
}
public function renderPanel() {
$data = $this->getData();
$out = array();
$out[] = phutil_tag(
'div',
array('class' => 'dark-console-panel-header'),
phutil_tag('h1', array(), pht('Registered Event Listeners')));
$rows = array();
foreach ($data['listeners'] as $listener) {
$rows[] = array($listener['id'], $listener['class']);
}
$table = new AphrontTableView($rows);
$table->setHeaders(
array(
pht('Internal ID'),
pht('Listener Class'),
));
$table->setColumnClasses(
array(
'',
'wide',
));
$out[] = $table->render();
$out[] = phutil_tag(
'div',
array('class' => 'dark-console-panel-header'),
phutil_tag('h1', array(), pht('Event Log')));
$rows = array();
foreach ($data['events'] as $event) {
$rows[] = array(
$event['type'],
$event['stopped'] ? pht('STOPPED') : null,
);
}
$table = new AphrontTableView($rows);
$table->setColumnClasses(
array(
'wide',
));
$table->setHeaders(
array(
pht('Event Type'),
pht('Stopped'),
));
$out[] = $table->render();
return phutil_implode_html("\n", $out);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.