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/doorkeeper/view/DoorkeeperTagView.php | src/applications/doorkeeper/view/DoorkeeperTagView.php | <?php
final class DoorkeeperTagView extends AphrontView {
private $xobj;
public function setExternalObject(DoorkeeperExternalObject $xobj) {
$this->xobj = $xobj;
return $this;
}
public function render() {
$xobj = $this->xobj;
if (!$xobj) {
throw new PhutilInvalidStateException('setExternalObject');
}
$tag_id = celerity_generate_unique_node_id();
$href = $xobj->getObjectURI();
$spec = array(
'id' => $tag_id,
'ref' => array(
$xobj->getApplicationType(),
$xobj->getApplicationDomain(),
$xobj->getObjectType(),
$xobj->getObjectID(),
),
);
Javelin::initBehavior('doorkeeper-tag', array('tags' => array($spec)));
return id(new PHUITagView())
->setID($tag_id)
->setHref($href)
->setName($href)
->setType(PHUITagView::TYPE_OBJECT)
->setExternal(true);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/edge/PhabricatorObjectHasJiraIssueEdgeType.php | src/applications/doorkeeper/edge/PhabricatorObjectHasJiraIssueEdgeType.php | <?php
final class PhabricatorObjectHasJiraIssueEdgeType extends PhabricatorEdgeType {
const EDGECONST = 80005;
public function getInverseEdgeConstant() {
return PhabricatorJiraIssueHasObjectEdgeType::EDGECONST;
}
public function shouldWriteInverseTransactions() {
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/doorkeeper/edge/PhabricatorJiraIssueHasObjectEdgeType.php | src/applications/doorkeeper/edge/PhabricatorJiraIssueHasObjectEdgeType.php | <?php
final class PhabricatorJiraIssueHasObjectEdgeType extends PhabricatorEdgeType {
const EDGECONST = 80004;
public function getInverseEdgeConstant() {
return PhabricatorObjectHasJiraIssueEdgeType::EDGECONST;
}
public function shouldWriteInverseTransactions() {
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/doorkeeper/edge/PhabricatorObjectHasAsanaSubtaskEdgeType.php | src/applications/doorkeeper/edge/PhabricatorObjectHasAsanaSubtaskEdgeType.php | <?php
final class PhabricatorObjectHasAsanaSubtaskEdgeType
extends PhabricatorEdgeType {
const EDGECONST = 80003;
public function getInverseEdgeConstant() {
return PhabricatorAsanaSubtaskHasObjectEdgeType::EDGECONST;
}
public function shouldWriteInverseTransactions() {
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/doorkeeper/edge/PhabricatorAsanaTaskHasObjectEdgeType.php | src/applications/doorkeeper/edge/PhabricatorAsanaTaskHasObjectEdgeType.php | <?php
final class PhabricatorAsanaTaskHasObjectEdgeType extends PhabricatorEdgeType {
const EDGECONST = 80000;
public function getInverseEdgeConstant() {
return PhabricatorObjectHasAsanaTaskEdgeType::EDGECONST;
}
public function shouldWriteInverseTransactions() {
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/doorkeeper/edge/PhabricatorAsanaSubtaskHasObjectEdgeType.php | src/applications/doorkeeper/edge/PhabricatorAsanaSubtaskHasObjectEdgeType.php | <?php
final class PhabricatorAsanaSubtaskHasObjectEdgeType
extends PhabricatorEdgeType {
const EDGECONST = 80002;
public function getInverseEdgeConstant() {
return PhabricatorObjectHasAsanaSubtaskEdgeType::EDGECONST;
}
public function shouldWriteInverseTransactions() {
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/doorkeeper/edge/PhabricatorObjectHasAsanaTaskEdgeType.php | src/applications/doorkeeper/edge/PhabricatorObjectHasAsanaTaskEdgeType.php | <?php
final class PhabricatorObjectHasAsanaTaskEdgeType extends PhabricatorEdgeType {
const EDGECONST = 80001;
public function getInverseEdgeConstant() {
return PhabricatorAsanaTaskHasObjectEdgeType::EDGECONST;
}
public function shouldWriteInverseTransactions() {
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/doorkeeper/phid/DoorkeeperExternalObjectPHIDType.php | src/applications/doorkeeper/phid/DoorkeeperExternalObjectPHIDType.php | <?php
final class DoorkeeperExternalObjectPHIDType
extends PhabricatorPHIDType {
const TYPECONST = 'XOBJ';
public function getTypeName() {
return pht('External Object');
}
public function newObject() {
return new DoorkeeperExternalObject();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorDoorkeeperApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new DoorkeeperExternalObjectQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$xobj = $objects[$phid];
$uri = $xobj->getObjectURI();
$name = $xobj->getDisplayName();
$full_name = $xobj->getDisplayFullName();
$handle
->setURI($uri)
->setName($name)
->setFullName($full_name);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/engine/DoorkeeperURIRef.php | src/applications/doorkeeper/engine/DoorkeeperURIRef.php | <?php
final class DoorkeeperURIRef extends Phobject {
private $uri;
private $applicationType;
private $applicationDomain;
private $objectType;
private $objectID;
private $text;
private $displayMode = self::DISPLAY_FULL;
const DISPLAY_FULL = 'full';
const DISPLAY_SHORT = 'short';
public function setURI(PhutilURI $uri) {
$this->uri = $uri;
return $this;
}
public function getURI() {
return $this->uri;
}
public function setApplicationType($application_type) {
$this->applicationType = $application_type;
return $this;
}
public function getApplicationType() {
return $this->applicationType;
}
public function setApplicationDomain($application_domain) {
$this->applicationDomain = $application_domain;
return $this;
}
public function getApplicationDomain() {
return $this->applicationDomain;
}
public function setObjectType($object_type) {
$this->objectType = $object_type;
return $this;
}
public function getObjectType() {
return $this->objectType;
}
public function setObjectID($object_id) {
$this->objectID = $object_id;
return $this;
}
public function getObjectID() {
return $this->objectID;
}
public function setText($text) {
$this->text = $text;
return $this;
}
public function getText() {
return $this->text;
}
public function setDisplayMode($display_mode) {
$options = array(
self::DISPLAY_FULL => true,
self::DISPLAY_SHORT => true,
);
if (!isset($options[$display_mode])) {
throw new Exception(
pht(
'DoorkeeperURIRef display mode "%s" is unknown.',
$display_mode));
}
$this->displayMode = $display_mode;
return $this;
}
public function getDisplayMode() {
return $this->displayMode;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/engine/DoorkeeperImportEngine.php | src/applications/doorkeeper/engine/DoorkeeperImportEngine.php | <?php
final class DoorkeeperImportEngine extends Phobject {
private $viewer;
private $refs = array();
private $phids = array();
private $localOnly;
private $throwOnMissingLink;
private $context = array();
private $timeout;
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setRefs(array $refs) {
assert_instances_of($refs, 'DoorkeeperObjectRef');
$this->refs = $refs;
return $this;
}
public function getRefs() {
return $this->refs;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function needLocalOnly($local_only) {
$this->localOnly = $local_only;
return $this;
}
public function setContextProperty($key, $value) {
$this->context[$key] = $value;
return $this;
}
public function setTimeout($timeout) {
$this->timeout = $timeout;
return $this;
}
public function getTimeout() {
return $this->timeout;
}
/**
* Configure behavior if remote refs can not be retrieved because an
* authentication link is missing.
*/
public function setThrowOnMissingLink($throw) {
$this->throwOnMissingLink = $throw;
return $this;
}
public function execute() {
$refs = $this->getRefs();
$viewer = $this->getViewer();
$keys = mpull($refs, 'getObjectKey');
if ($keys) {
$xobjs = id(new DoorkeeperExternalObjectQuery())
->setViewer($viewer)
->withObjectKeys($keys)
->execute();
$xobjs = mpull($xobjs, null, 'getObjectKey');
foreach ($refs as $ref) {
$xobj = idx($xobjs, $ref->getObjectKey());
if (!$xobj) {
$xobj = $ref
->newExternalObject()
->setImporterPHID($viewer->getPHID());
// NOTE: Fill the new external object into the object map, so we'll
// reference the same external object if more than one ref is the
// same. This prevents issues later where we double-populate
// external objects when handed duplicate refs.
$xobjs[$ref->getObjectKey()] = $xobj;
}
$ref->attachExternalObject($xobj);
}
}
if ($this->phids) {
$xobjs = id(new DoorkeeperExternalObjectQuery())
->setViewer($viewer)
->withPHIDs($this->phids)
->execute();
foreach ($xobjs as $xobj) {
$ref = $xobj->getRef();
$ref->attachExternalObject($xobj);
$refs[$ref->getObjectKey()] = $ref;
}
}
if (!$this->localOnly) {
$bridges = id(new PhutilClassMapQuery())
->setAncestorClass('DoorkeeperBridge')
->setFilterMethod('isEnabled')
->execute();
$timeout = $this->getTimeout();
foreach ($bridges as $key => $bridge) {
$bridge
->setViewer($viewer)
->setThrowOnMissingLink($this->throwOnMissingLink)
->setContext($this->context);
if ($timeout !== null) {
$bridge->setTimeout($timeout);
}
}
$working_set = $refs;
foreach ($bridges as $bridge) {
$bridge_refs = array();
foreach ($working_set as $key => $ref) {
if ($bridge->canPullRef($ref)) {
$bridge_refs[$key] = $ref;
unset($working_set[$key]);
}
}
if ($bridge_refs) {
$bridge->pullRefs($bridge_refs);
}
}
}
return $refs;
}
public function executeOne() {
return head($this->execute());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/engine/DoorkeeperFeedStoryPublisher.php | src/applications/doorkeeper/engine/DoorkeeperFeedStoryPublisher.php | <?php
/**
* @task config Configuration
*/
abstract class DoorkeeperFeedStoryPublisher extends Phobject {
private $feedStory;
private $viewer;
private $renderWithImpliedContext;
/* -( Configuration )------------------------------------------------------ */
/**
* Render story text using contextual language to identify the object the
* story is about, instead of the full object name. For example, without
* contextual language a story might render like this:
*
* alincoln created D123: Chop Wood for Log Cabin v2.0
*
* With contextual language, it will render like this instead:
*
* alincoln created this revision.
*
* If the interface where the text will be displayed is specific to an
* individual object (like Asana tasks that represent one review or commit
* are), it's generally more natural to use language that assumes context.
* If the target context may show information about several objects (like
* JIRA issues which can have several linked revisions), it's generally
* more useful not to assume context.
*
* @param bool True to assume object context when rendering.
* @return this
* @task config
*/
public function setRenderWithImpliedContext($render_with_implied_context) {
$this->renderWithImpliedContext = $render_with_implied_context;
return $this;
}
/**
* Determine if rendering should assume object context. For discussion, see
* @{method:setRenderWithImpliedContext}.
*
* @return bool True if rendering should assume object context is implied.
* @task config
*/
public function getRenderWithImpliedContext() {
return $this->renderWithImpliedContext;
}
public function setFeedStory(PhabricatorFeedStory $feed_story) {
$this->feedStory = $feed_story;
return $this;
}
public function getFeedStory() {
return $this->feedStory;
}
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
abstract public function canPublishStory(
PhabricatorFeedStory $story,
$object);
/**
* Hook for publishers to mutate the story object, particularly by loading
* and attaching additional data.
*/
public function willPublishStory($object) {
return $object;
}
public function getStoryText($object) {
return $this->getFeedStory()->renderAsTextForDoorkeeper($this);
}
abstract public function isStoryAboutObjectCreation($object);
abstract public function isStoryAboutObjectClosure($object);
abstract public function getOwnerPHID($object);
abstract public function getActiveUserPHIDs($object);
abstract public function getPassiveUserPHIDs($object);
abstract public function getCCUserPHIDs($object);
abstract public function getObjectTitle($object);
abstract public function getObjectURI($object);
abstract public function getObjectDescription($object);
abstract public function isObjectClosed($object);
abstract public function getResponsibilityTitle($object);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/engine/DoorkeeperObjectRef.php | src/applications/doorkeeper/engine/DoorkeeperObjectRef.php | <?php
final class DoorkeeperObjectRef extends Phobject {
private $objectKey;
private $applicationType;
private $applicationDomain;
private $objectType;
private $objectID;
private $attributes = array();
private $isVisible;
private $syncFailed;
private $externalObject;
public function newExternalObject() {
return id(new DoorkeeperExternalObject())
->setApplicationType($this->getApplicationType())
->setApplicationDomain($this->getApplicationDomain())
->setObjectType($this->getObjectType())
->setObjectID($this->getObjectID())
->setViewPolicy(PhabricatorPolicies::POLICY_USER);
}
public function attachExternalObject(
DoorkeeperExternalObject $external_object) {
$this->externalObject = $external_object;
return $this;
}
public function getExternalObject() {
if (!$this->externalObject) {
throw new PhutilInvalidStateException('attachExternalObject');
}
return $this->externalObject;
}
public function setIsVisible($is_visible) {
$this->isVisible = $is_visible;
return $this;
}
public function getIsVisible() {
return $this->isVisible;
}
public function setSyncFailed($sync_failed) {
$this->syncFailed = $sync_failed;
return $this;
}
public function getSyncFailed() {
return $this->syncFailed;
}
public function getAttribute($key, $default = null) {
return idx($this->attributes, $key, $default);
}
public function setAttribute($key, $value) {
$this->attributes[$key] = $value;
return $this;
}
public function setObjectID($object_id) {
$this->objectID = $object_id;
return $this;
}
public function getObjectID() {
return $this->objectID;
}
public function setObjectType($object_type) {
$this->objectType = $object_type;
return $this;
}
public function getObjectType() {
return $this->objectType;
}
public function setApplicationDomain($application_domain) {
$this->applicationDomain = $application_domain;
return $this;
}
public function getApplicationDomain() {
return $this->applicationDomain;
}
public function setApplicationType($application_type) {
$this->applicationType = $application_type;
return $this;
}
public function getApplicationType() {
return $this->applicationType;
}
public function getFullName() {
return coalesce(
$this->getAttribute('fullname'),
$this->getAttribute('name'),
pht('External Object'));
}
public function getShortName() {
return coalesce(
$this->getAttribute('shortname'),
$this->getAttribute('name'),
pht('External Object'));
}
public function getObjectKey() {
if (!$this->objectKey) {
$this->objectKey = PhabricatorHash::digestForIndex(
implode(
':',
array(
$this->getApplicationType(),
$this->getApplicationDomain(),
$this->getObjectType(),
$this->getObjectID(),
)));
}
return $this->objectKey;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterPlanBehaviorController.php | src/applications/harbormaster/controller/HarbormasterPlanBehaviorController.php | <?php
final class HarbormasterPlanBehaviorController
extends HarbormasterPlanController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$plan = id(new HarbormasterBuildPlanQuery())
->setViewer($viewer)
->withIDs(array($request->getURIData('id')))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$plan) {
return new Aphront404Response();
}
$behavior_key = $request->getURIData('behaviorKey');
$metadata_key = HarbormasterBuildPlanBehavior::getTransactionMetadataKey();
$behaviors = HarbormasterBuildPlanBehavior::newPlanBehaviors();
$behavior = idx($behaviors, $behavior_key);
if (!$behavior) {
return new Aphront404Response();
}
$plan_uri = $plan->getURI();
$v_option = $behavior->getPlanOption($plan)->getKey();
if ($request->isFormPost()) {
$v_option = $request->getStr('option');
$xactions = array();
$xactions[] = id(new HarbormasterBuildPlanTransaction())
->setTransactionType(
HarbormasterBuildPlanBehaviorTransaction::TRANSACTIONTYPE)
->setMetadataValue($metadata_key, $behavior_key)
->setNewValue($v_option);
$editor = id(new HarbormasterBuildPlanEditor())
->setActor($viewer)
->setContinueOnNoEffect(true)
->setContinueOnMissingFields(true)
->setContentSourceFromRequest($request);
$editor->applyTransactions($plan, $xactions);
return id(new AphrontRedirectResponse())->setURI($plan_uri);
}
$select_control = id(new AphrontFormRadioButtonControl())
->setName('option')
->setValue($v_option)
->setLabel(pht('Option'));
foreach ($behavior->getOptions() as $option) {
$icon = id(new PHUIIconView())
->setIcon($option->getIcon());
$select_control->addButton(
$option->getKey(),
array(
$icon,
' ',
$option->getName(),
),
$option->getDescription());
}
$form = id(new AphrontFormView())
->setViewer($viewer)
->appendInstructions(
pht(
'Choose a build plan behavior for "%s".',
phutil_tag('strong', array(), $behavior->getName())))
->appendRemarkupInstructions($behavior->getEditInstructions())
->appendControl($select_control);
return $this->newDialog()
->setTitle(pht('Edit Behavior: %s', $behavior->getName()))
->appendForm($form)
->setWidth(AphrontDialogView::WIDTH_FORM)
->addSubmitButton(pht('Save Changes'))
->addCancelButton($plan_uri);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterPlanDisableController.php | src/applications/harbormaster/controller/HarbormasterPlanDisableController.php | <?php
final class HarbormasterPlanDisableController
extends HarbormasterPlanController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$plan = id(new HarbormasterBuildPlanQuery())
->setViewer($viewer)
->withIDs(array($request->getURIData('id')))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$plan) {
return new Aphront404Response();
}
$plan_uri = $plan->getURI();
if ($request->isFormPost()) {
$type_status = HarbormasterBuildPlanStatusTransaction::TRANSACTIONTYPE;
$v_status = $plan->isDisabled()
? HarbormasterBuildPlan::STATUS_ACTIVE
: HarbormasterBuildPlan::STATUS_DISABLED;
$xactions = array();
$xactions[] = id(new HarbormasterBuildPlanTransaction())
->setTransactionType($type_status)
->setNewValue($v_status);
$editor = id(new HarbormasterBuildPlanEditor())
->setActor($viewer)
->setContinueOnNoEffect(true)
->setContinueOnMissingFields(true)
->setContentSourceFromRequest($request);
$editor->applyTransactions($plan, $xactions);
return id(new AphrontRedirectResponse())->setURI($plan_uri);
}
if ($plan->isDisabled()) {
$title = pht('Enable Build Plan');
$body = pht('Enable this build plan?');
$button = pht('Enable Plan');
} else {
$title = pht('Disable Build Plan');
$body = pht(
'Disable this build plan? It will no longer be executed '.
'automatically.');
$button = pht('Disable Plan');
}
return $this->newDialog()
->setTitle($title)
->appendChild($body)
->addSubmitButton($button)
->addCancelButton($plan_uri);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterBuildableViewController.php | src/applications/harbormaster/controller/HarbormasterBuildableViewController.php | <?php
final class HarbormasterBuildableViewController
extends HarbormasterController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$buildable = id(new HarbormasterBuildableQuery())
->setViewer($viewer)
->withIDs(array($request->getURIData('id')))
->executeOne();
if (!$buildable) {
return new Aphront404Response();
}
$id = $buildable->getID();
// Pull builds and build targets.
$builds = id(new HarbormasterBuildQuery())
->setViewer($viewer)
->withBuildablePHIDs(array($buildable->getPHID()))
->needBuildTargets(true)
->execute();
list($lint, $unit) = $this->renderLintAndUnit($buildable, $builds);
$buildable->attachBuilds($builds);
$object = $buildable->getBuildableObject();
$build_list = $this->buildBuildList($buildable);
$title = pht('Buildable %d', $id);
$header = id(new PHUIHeaderView())
->setHeader($title)
->setUser($viewer)
->setPolicyObject($buildable)
->setStatus(
$buildable->getStatusIcon(),
$buildable->getStatusColor(),
$buildable->getStatusDisplayName())
->setHeaderIcon('fa-recycle');
$timeline = $this->buildTransactionTimeline(
$buildable,
new HarbormasterBuildableTransactionQuery());
$timeline->setShouldTerminate(true);
$curtain = $this->buildCurtainView($buildable);
$properties = $this->buildPropertyList($buildable);
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb($buildable->getMonogram());
$crumbs->setBorder(true);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setCurtain($curtain)
->setMainColumn(array(
$properties,
$lint,
$unit,
$build_list,
$timeline,
));
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->appendChild($view);
}
private function buildCurtainView(HarbormasterBuildable $buildable) {
$viewer = $this->getViewer();
$id = $buildable->getID();
$curtain = $this->newCurtainView($buildable);
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$buildable,
PhabricatorPolicyCapability::CAN_EDIT);
$messages = array(
new HarbormasterBuildMessageRestartTransaction(),
new HarbormasterBuildMessagePauseTransaction(),
new HarbormasterBuildMessageResumeTransaction(),
new HarbormasterBuildMessageAbortTransaction(),
);
foreach ($messages as $message) {
// Messages are enabled if they can be sent to at least one build.
$can_send = false;
foreach ($buildable->getBuilds() as $build) {
$can_send = $message->canSendMessage($viewer, $build);
if ($can_send) {
break;
}
}
$message_uri = urisprintf(
'/buildable/%d/%s/',
$id,
$message->getHarbormasterBuildMessageType());
$message_uri = $this->getApplicationURI($message_uri);
$action = id(new PhabricatorActionView())
->setName($message->getHarbormasterBuildableMessageName())
->setIcon($message->getIcon())
->setHref($message_uri)
->setDisabled(!$can_send || !$can_edit)
->setWorkflow(true);
$curtain->addAction($action);
}
return $curtain;
}
private function buildPropertyList(HarbormasterBuildable $buildable) {
$viewer = $this->getViewer();
$properties = id(new PHUIPropertyListView())
->setUser($viewer);
$container_phid = $buildable->getContainerPHID();
$buildable_phid = $buildable->getBuildablePHID();
if ($container_phid) {
$properties->addProperty(
pht('Container'),
$viewer->renderHandle($container_phid));
}
$properties->addProperty(
pht('Buildable'),
$viewer->renderHandle($buildable_phid));
$properties->addProperty(
pht('Origin'),
$buildable->getIsManualBuildable()
? pht('Manual Buildable')
: pht('Automatic Buildable'));
return id(new PHUIObjectBoxView())
->setHeaderText(pht('Properties'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($properties);
}
private function buildBuildList(HarbormasterBuildable $buildable) {
$viewer = $this->getRequest()->getUser();
$build_list = id(new PHUIObjectItemListView())
->setUser($viewer);
foreach ($buildable->getBuilds() as $build) {
$view_uri = $this->getApplicationURI('/build/'.$build->getID().'/');
$item = id(new PHUIObjectItemView())
->setObjectName(pht('Build %d', $build->getID()))
->setHeader($build->getName())
->setHref($view_uri);
$status = $build->getBuildPendingStatusObject();
$item->setStatusIcon(
$status->getIconIcon().' '.$status->getIconColor(),
$status->getName());
$targets = $build->getBuildTargets();
if ($targets) {
$target_list = id(new PHUIStatusListView());
foreach ($targets as $target) {
$status = $target->getTargetStatus();
$icon = HarbormasterBuildTarget::getBuildTargetStatusIcon($status);
$color = HarbormasterBuildTarget::getBuildTargetStatusColor($status);
$status_name =
HarbormasterBuildTarget::getBuildTargetStatusName($status);
$name = $target->getName();
$target_list->addItem(
id(new PHUIStatusItemView())
->setIcon($icon, $color, $status_name)
->setTarget(pht('Target %d', $target->getID()))
->setNote($name));
}
$target_box = id(new PHUIBoxView())
->addPadding(PHUI::PADDING_SMALL)
->appendChild($target_list);
$item->appendChild($target_box);
}
$build_list->addItem($item);
}
$build_list->setFlush(true);
$box = id(new PHUIObjectBoxView())
->setHeaderText(pht('Builds'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($build_list);
return $box;
}
private function renderLintAndUnit(
HarbormasterBuildable $buildable,
array $builds) {
$viewer = $this->getViewer();
$targets = array();
foreach ($builds as $build) {
foreach ($build->getBuildTargets() as $target) {
$targets[] = $target;
}
}
if (!$targets) {
return;
}
$target_phids = mpull($targets, 'getPHID');
$lint_data = id(new HarbormasterBuildLintMessage())->loadAllWhere(
'buildTargetPHID IN (%Ls)',
$target_phids);
$unit_data = id(new HarbormasterBuildUnitMessageQuery())
->setViewer($viewer)
->withBuildTargetPHIDs($target_phids)
->execute();
if ($lint_data) {
$lint_table = id(new HarbormasterLintPropertyView())
->setViewer($viewer)
->setLimit(10)
->setLintMessages($lint_data);
$lint_href = $this->getApplicationURI('lint/'.$buildable->getID().'/');
$lint_header = id(new PHUIHeaderView())
->setHeader(pht('Lint Messages'))
->addActionLink(
id(new PHUIButtonView())
->setTag('a')
->setHref($lint_href)
->setIcon('fa-list-ul')
->setText('View All'));
$lint = id(new PHUIObjectBoxView())
->setHeader($lint_header)
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setTable($lint_table);
} else {
$lint = null;
}
if ($unit_data) {
$unit = id(new HarbormasterUnitSummaryView())
->setViewer($viewer)
->setBuildable($buildable)
->setUnitMessages($unit_data)
->setShowViewAll(true)
->setLimit(5);
} else {
$unit = null;
}
return array($lint, $unit);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterBuildableActionController.php | src/applications/harbormaster/controller/HarbormasterBuildableActionController.php | <?php
final class HarbormasterBuildableActionController
extends HarbormasterController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$id = $request->getURIData('id');
$action = $request->getURIData('action');
$buildable = id(new HarbormasterBuildableQuery())
->setViewer($viewer)
->withIDs(array($id))
->needBuilds(true)
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$buildable) {
return new Aphront404Response();
}
$message =
HarbormasterBuildMessageTransaction::getTransactionObjectForMessageType(
$action);
if (!$message) {
return new Aphront404Response();
}
$return_uri = '/'.$buildable->getMonogram();
// See T13348. Actions may apply to only a subset of builds, so give the
// user a preview of what will happen.
$can_send = array();
$rows = array();
$builds = $buildable->getBuilds();
foreach ($builds as $key => $build) {
$exception = null;
try {
$message->assertCanSendMessage($viewer, $build);
$can_send[$key] = $build;
} catch (HarbormasterMessageException $ex) {
$exception = $ex;
}
if (!$exception) {
$icon_icon = $message->getIcon();
$icon_color = 'green';
$title = $message->getHarbormasterBuildMessageName();
$body = $message->getHarbormasterBuildableMessageEffect();
} else {
$icon_icon = 'fa-times';
$icon_color = 'red';
$title = $ex->getTitle();
$body = $ex->getBody();
}
$icon = id(new PHUIIconView())
->setIcon($icon_icon)
->setColor($icon_color);
$build_name = phutil_tag(
'a',
array(
'href' => $build->getURI(),
'target' => '_blank',
),
pht('%s %s', $build->getObjectName(), $build->getName()));
$rows[] = array(
$icon,
$build_name,
$title,
$body,
);
}
$table = id(new AphrontTableView($rows))
->setHeaders(
array(
null,
pht('Build'),
pht('Action'),
pht('Details'),
))
->setColumnClasses(
array(
null,
null,
'pri',
'wide',
));
$table = phutil_tag(
'div',
array(
'class' => 'mlt mlb',
),
$table);
if ($request->isDialogFormPost() && $can_send) {
$editor = id(new HarbormasterBuildableTransactionEditor())
->setActor($viewer)
->setContentSourceFromRequest($request)
->setContinueOnNoEffect(true)
->setContinueOnMissingFields(true);
$xaction_type = HarbormasterBuildableMessageTransaction::TRANSACTIONTYPE;
$xaction = id(new HarbormasterBuildableTransaction())
->setTransactionType($xaction_type)
->setNewValue($action);
$editor->applyTransactions($buildable, array($xaction));
foreach ($can_send as $build) {
$build->sendMessage(
$viewer,
$message->getHarbormasterBuildMessageType());
}
return id(new AphrontRedirectResponse())->setURI($return_uri);
}
if (!$builds) {
$title = pht('No Builds');
$body = pht(
'This buildable has no builds, so you can not issue any commands.');
} else {
if ($can_send) {
$title = $message->newBuildableConfirmPromptTitle(
$builds,
$can_send);
$body = $message->newBuildableConfirmPromptBody(
$builds,
$can_send);
} else {
$title = pht('Unable to Send Command');
$body = pht(
'You can not send this command to any of the current builds '.
'for this buildable.');
}
$body = array(
pht('Builds for this buildable:'),
$table,
$body,
);
}
$warnings = $message->newBuildableConfirmPromptWarnings(
$builds,
$can_send);
if ($warnings) {
$body[] = id(new PHUIInfoView())
->setSeverity(PHUIInfoView::SEVERITY_WARNING)
->setErrors($warnings);
}
$submit = $message->getHarbormasterBuildableMessageName();
$dialog = $this->newDialog()
->setWidth(AphrontDialogView::WIDTH_FULL)
->setTitle($title)
->appendChild($body)
->addCancelButton($return_uri);
if ($can_send) {
$dialog->addSubmitButton($submit);
}
return $dialog;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterBuildLogViewController.php | src/applications/harbormaster/controller/HarbormasterBuildLogViewController.php | <?php
final class HarbormasterBuildLogViewController
extends HarbormasterController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$id = $request->getURIData('id');
$log = id(new HarbormasterBuildLogQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
if (!$log) {
return new Aphront404Response();
}
$target = $log->getBuildTarget();
$build = $target->getBuild();
$page_title = pht('Build Log %d', $log->getID());
$log_view = id(new HarbormasterBuildLogView())
->setViewer($viewer)
->setBuildLog($log)
->setHighlightedLineRange($request->getURIData('lines'))
->setEnableHighlighter(true);
$crumbs = $this->buildApplicationCrumbs()
->addTextCrumb(pht('Build Logs'))
->addTextCrumb(
pht('Build %d', $build->getID()),
$build->getURI())
->addTextCrumb($page_title)
->setBorder(true);
$page_header = id(new PHUIHeaderView())
->setHeader($page_title);
$page_view = id(new PHUITwoColumnView())
->setHeader($page_header)
->setFooter($log_view);
return $this->newPage()
->setTitle($page_title)
->setCrumbs($crumbs)
->appendChild($page_view);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterController.php | src/applications/harbormaster/controller/HarbormasterController.php | <?php
abstract class HarbormasterController extends PhabricatorController {
public function buildApplicationMenu() {
return $this->newApplicationMenu()
->setSearchEngine(new HarbormasterBuildableSearchEngine());
}
protected function addBuildableCrumb(
PHUICrumbsView $crumbs,
HarbormasterBuildable $buildable) {
$monogram = $buildable->getMonogram();
$uri = '/'.$monogram;
$crumbs->addTextCrumb($monogram, $uri);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterStepAddController.php | src/applications/harbormaster/controller/HarbormasterStepAddController.php | <?php
final class HarbormasterStepAddController
extends HarbormasterPlanController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$plan = id(new HarbormasterBuildPlanQuery())
->setViewer($viewer)
->withIDs(array($request->getURIData('id')))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$plan) {
return new Aphront404Response();
}
$plan_id = $plan->getID();
$cancel_uri = $this->getApplicationURI("plan/{$plan_id}/");
$plan_title = pht('Plan %d', $plan_id);
$all = HarbormasterBuildStepImplementation::getImplementations();
$all = msort($all, 'getName');
$all_groups = HarbormasterBuildStepGroup::getAllGroups();
foreach ($all as $impl) {
$group_key = $impl->getBuildStepGroupKey();
if (empty($all_groups[$group_key])) {
throw new Exception(
pht(
'Build step "%s" has step group key "%s", but no step group '.
'with that key exists.',
get_class($impl),
$group_key));
}
}
$groups = mgroup($all, 'getBuildStepGroupKey');
$boxes = array();
$enabled_groups = HarbormasterBuildStepGroup::getAllEnabledGroups();
foreach ($enabled_groups as $group) {
$list = id(new PHUIObjectItemListView())
->setNoDataString(
pht('This group has no available build steps.'));
$steps = idx($groups, $group->getGroupKey(), array());
foreach ($steps as $key => $impl) {
if ($impl->shouldRequireAutotargeting()) {
unset($steps[$key]);
continue;
}
}
if (!$steps && !$group->shouldShowIfEmpty()) {
continue;
}
foreach ($steps as $key => $impl) {
$class = get_class($impl);
$new_uri = $this->getApplicationURI("step/new/{$plan_id}/{$class}/");
$item = id(new PHUIObjectItemView())
->setHeader($impl->getName())
->setHref($new_uri)
->addAttribute($impl->getGenericDescription());
$list->addItem($item);
}
$box = id(new PHUIObjectBoxView())
->setHeaderText($group->getGroupName())
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($list);
$boxes[] = $box;
}
$crumbs = $this->buildApplicationCrumbs()
->addTextCrumb($plan_title, $cancel_uri)
->addTextCrumb(pht('Add Build Step'))
->setBorder(true);
$title = array($plan_title, pht('Add Build Step'));
$header = id(new PHUIHeaderView())
->setHeader(pht('Add Build Step'))
->setHeaderIcon('fa-plus-square');
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setFooter(array(
$boxes,
));
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/harbormaster/controller/HarbormasterStepViewController.php | src/applications/harbormaster/controller/HarbormasterStepViewController.php | <?php
final class HarbormasterStepViewController
extends HarbormasterPlanController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$id = $request->getURIData('id');
$step = id(new HarbormasterBuildStepQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
if (!$step) {
return new Aphront404Response();
}
$plan = $step->getBuildPlan();
$plan_id = $plan->getID();
$plan_uri = $this->getApplicationURI("plan/{$plan_id}/");
$field_list = PhabricatorCustomField::getObjectFields(
$step,
PhabricatorCustomField::ROLE_VIEW);
$field_list
->setViewer($viewer)
->readFieldsFromStorage($step);
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb(pht('Plan %d', $plan_id), $plan_uri);
$crumbs->addTextCrumb(pht('Step %d', $id));
$crumbs->setBorder(true);
$header = id(new PHUIHeaderView())
->setHeader(pht('Build Step %d: %s', $id, $step->getName()))
->setHeaderIcon('fa-chevron-circle-right');
$properties = $this->buildPropertyList($step, $field_list);
$curtain = $this->buildCurtainView($step);
$timeline = $this->buildTransactionTimeline(
$step,
new HarbormasterBuildStepTransactionQuery());
$timeline->setShouldTerminate(true);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setCurtain($curtain)
->setMainColumn(array(
$properties,
$timeline,
));
return $this->newPage()
->setTitle(pht('Step %d', $id))
->setCrumbs($crumbs)
->appendChild($view);
}
private function buildPropertyList(
HarbormasterBuildStep $step,
PhabricatorCustomFieldList $field_list) {
$viewer = $this->getViewer();
$view = id(new PHUIPropertyListView())
->setUser($viewer);
try {
$implementation = $step->getStepImplementation();
} catch (Exception $ex) {
$implementation = null;
}
if ($implementation) {
$type = $implementation->getName();
} else {
$type = phutil_tag(
'em',
array(),
pht(
'Invalid Implementation ("%s")!',
$step->getClassName()));
}
$view->addProperty(pht('Step Type'), $type);
$view->addProperty(
pht('Created'),
phabricator_datetime($step->getDateCreated(), $viewer));
$field_list->appendFieldsToPropertyList(
$step,
$viewer,
$view);
$description = $step->getDescription();
if (strlen($description)) {
$view->addSectionHeader(
pht('Description'),
PHUIPropertyListView::ICON_SUMMARY);
$view->addTextContent(
new PHUIRemarkupView($viewer, $description));
}
return id(new PHUIObjectBoxView())
->setHeaderText(pht('Properties'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($view);
}
private function buildCurtainView(HarbormasterBuildStep $step) {
$viewer = $this->getViewer();
$id = $step->getID();
$curtain = $this->newCurtainView($step);
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$step,
PhabricatorPolicyCapability::CAN_EDIT);
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('Edit Step'))
->setHref($this->getApplicationURI("step/edit/{$id}/"))
->setWorkflow(!$can_edit)
->setDisabled(!$can_edit)
->setIcon('fa-pencil'));
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('Delete Step'))
->setHref($this->getApplicationURI("step/delete/{$id}/"))
->setWorkflow(true)
->setDisabled(!$can_edit)
->setIcon('fa-times'));
return $curtain;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterPlanViewController.php | src/applications/harbormaster/controller/HarbormasterPlanViewController.php | <?php
final class HarbormasterPlanViewController extends HarbormasterPlanController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$id = $request->getURIData('id');
$plan = id(new HarbormasterBuildPlanQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
if (!$plan) {
return new Aphront404Response();
}
$title = $plan->getName();
$header = id(new PHUIHeaderView())
->setHeader($plan->getName())
->setUser($viewer)
->setPolicyObject($plan)
->setHeaderIcon('fa-ship');
$curtain = $this->buildCurtainView($plan);
$crumbs = $this->buildApplicationCrumbs()
->addTextCrumb($plan->getObjectName())
->setBorder(true);
list($step_list, $has_any_conflicts, $would_deadlock, $steps) =
$this->buildStepList($plan);
$error = null;
if (!$steps) {
$error = pht(
'This build plan does not have any build steps yet, so it will '.
'not do anything when run.');
} else if ($would_deadlock) {
$error = pht(
'This build plan will deadlock when executed, due to circular '.
'dependencies present in the build plan. Examine the step list '.
'and resolve the deadlock.');
} else if ($has_any_conflicts) {
// A deadlocking build will also cause all the artifacts to be
// invalid, so we just skip showing this message if that's the
// case.
$error = pht(
'This build plan has conflicts in one or more build steps. '.
'Examine the step list and resolve the listed errors.');
}
if ($error) {
$error = id(new PHUIInfoView())
->setSeverity(PHUIInfoView::SEVERITY_WARNING)
->appendChild($error);
}
$builds_view = $this->newBuildsView($plan);
$options_view = $this->newOptionsView($plan);
$rules_view = $this->newRulesView($plan);
$timeline = $this->buildTransactionTimeline(
$plan,
new HarbormasterBuildPlanTransactionQuery());
$timeline->setShouldTerminate(true);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setCurtain($curtain)
->setMainColumn(
array(
$error,
$step_list,
$options_view,
$rules_view,
$builds_view,
$timeline,
));
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->setPageObjectPHIDs(array($plan->getPHID()))
->appendChild($view);
}
private function buildStepList(HarbormasterBuildPlan $plan) {
$viewer = $this->getViewer();
$run_order = HarbormasterBuildGraph::determineDependencyExecution($plan);
$steps = id(new HarbormasterBuildStepQuery())
->setViewer($viewer)
->withBuildPlanPHIDs(array($plan->getPHID()))
->execute();
$steps = mpull($steps, null, 'getPHID');
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$plan,
PhabricatorPolicyCapability::CAN_EDIT);
$step_list = id(new PHUIObjectItemListView())
->setUser($viewer)
->setNoDataString(
pht('This build plan does not have any build steps yet.'));
$i = 1;
$last_depth = 0;
$has_any_conflicts = false;
$is_deadlocking = false;
foreach ($run_order as $run_ref) {
$step = $steps[$run_ref['node']->getPHID()];
$depth = $run_ref['depth'] + 1;
if ($last_depth !== $depth) {
$last_depth = $depth;
$i = 1;
} else {
$i++;
}
$step_id = $step->getID();
$view_uri = $this->getApplicationURI("step/view/{$step_id}/");
$item = id(new PHUIObjectItemView())
->setObjectName(pht('Step %d.%d', $depth, $i))
->setHeader($step->getName())
->setHref($view_uri);
$step_list->addItem($item);
$implementation = null;
try {
$implementation = $step->getStepImplementation();
} catch (Exception $ex) {
// We can't initialize the implementation. This might be because
// it's been renamed or no longer exists.
$item
->setStatusIcon('fa-warning red')
->addAttribute(pht(
'This step has an invalid implementation (%s).',
$step->getClassName()));
continue;
}
$item->addAttribute($implementation->getDescription());
$item->setHref($view_uri);
$depends = $step->getStepImplementation()->getDependencies($step);
$inputs = $step->getStepImplementation()->getArtifactInputs();
$outputs = $step->getStepImplementation()->getArtifactOutputs();
$has_conflicts = false;
if ($depends || $inputs || $outputs) {
$available_artifacts =
HarbormasterBuildStepImplementation::getAvailableArtifacts(
$plan,
$step,
null);
$available_artifacts = ipull($available_artifacts, 'type');
list($depends_ui, $has_conflicts) = $this->buildDependsOnList(
$depends,
pht('Depends On'),
$steps);
list($inputs_ui, $has_conflicts) = $this->buildArtifactList(
$inputs,
'in',
pht('Input Artifacts'),
$available_artifacts);
list($outputs_ui) = $this->buildArtifactList(
$outputs,
'out',
pht('Output Artifacts'),
array());
$item->appendChild(
phutil_tag(
'div',
array(
'class' => 'harbormaster-artifact-io',
),
array(
$depends_ui,
$inputs_ui,
$outputs_ui,
)));
}
if ($has_conflicts) {
$has_any_conflicts = true;
$item->setStatusIcon('fa-warning red');
}
if ($run_ref['cycle']) {
$is_deadlocking = true;
}
if ($is_deadlocking) {
$item->setStatusIcon('fa-warning red');
}
}
$step_list->setFlush(true);
$plan_id = $plan->getID();
$header = id(new PHUIHeaderView())
->setHeader(pht('Build Steps'))
->addActionLink(
id(new PHUIButtonView())
->setText(pht('Add Build Step'))
->setHref($this->getApplicationURI("step/add/{$plan_id}/"))
->setTag('a')
->setIcon('fa-plus')
->setDisabled(!$can_edit)
->setWorkflow(!$can_edit));
$step_box = id(new PHUIObjectBoxView())
->setHeader($header)
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($step_list);
return array($step_box, $has_any_conflicts, $is_deadlocking, $steps);
}
private function buildCurtainView(HarbormasterBuildPlan $plan) {
$viewer = $this->getViewer();
$id = $plan->getID();
$curtain = $this->newCurtainView($plan);
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$plan,
PhabricatorPolicyCapability::CAN_EDIT);
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('Edit Plan'))
->setHref($this->getApplicationURI("plan/edit/{$id}/"))
->setWorkflow(!$can_edit)
->setDisabled(!$can_edit)
->setIcon('fa-pencil'));
if ($plan->isDisabled()) {
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('Enable Plan'))
->setHref($this->getApplicationURI("plan/disable/{$id}/"))
->setWorkflow(true)
->setDisabled(!$can_edit)
->setIcon('fa-check'));
} else {
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('Disable Plan'))
->setHref($this->getApplicationURI("plan/disable/{$id}/"))
->setWorkflow(true)
->setDisabled(!$can_edit)
->setIcon('fa-ban'));
}
$can_run = ($plan->hasRunCapability($viewer) && $plan->canRunManually());
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('Run Plan Manually'))
->setHref($this->getApplicationURI("plan/run/{$id}/"))
->setWorkflow(true)
->setDisabled(!$can_run)
->setIcon('fa-play-circle'));
return $curtain;
}
private function buildArtifactList(
array $artifacts,
$kind,
$name,
array $available_artifacts) {
$has_conflicts = false;
if (!$artifacts) {
return array(null, $has_conflicts);
}
$this->requireResource('harbormaster-css');
$header = phutil_tag(
'div',
array(
'class' => 'harbormaster-artifact-summary-header',
),
$name);
$is_input = ($kind == 'in');
$list = new PHUIStatusListView();
foreach ($artifacts as $artifact) {
$error = null;
$key = idx($artifact, 'key');
if (!strlen($key)) {
$bound = phutil_tag('em', array(), pht('(null)'));
if ($is_input) {
// This is an unbound input. For now, all inputs are always required.
$icon = PHUIStatusItemView::ICON_WARNING;
$color = 'red';
$icon_label = pht('Required Input');
$has_conflicts = true;
$error = pht('This input is required, but not configured.');
} else {
// This is an unnamed output. Outputs do not necessarily need to be
// named.
$icon = PHUIStatusItemView::ICON_OPEN;
$color = 'bluegrey';
$icon_label = pht('Unused Output');
}
} else {
$bound = phutil_tag('strong', array(), $key);
if ($is_input) {
if (isset($available_artifacts[$key])) {
if ($available_artifacts[$key] == idx($artifact, 'type')) {
$icon = PHUIStatusItemView::ICON_ACCEPT;
$color = 'green';
$icon_label = pht('Valid Input');
} else {
$icon = PHUIStatusItemView::ICON_WARNING;
$color = 'red';
$icon_label = pht('Bad Input Type');
$has_conflicts = true;
$error = pht(
'This input is bound to the wrong artifact type. It is bound '.
'to a "%s" artifact, but should be bound to a "%s" artifact.',
$available_artifacts[$key],
idx($artifact, 'type'));
}
} else {
$icon = PHUIStatusItemView::ICON_QUESTION;
$color = 'red';
$icon_label = pht('Unknown Input');
$has_conflicts = true;
$error = pht(
'This input is bound to an artifact ("%s") which does not exist '.
'at this stage in the build process.',
$key);
}
} else {
$icon = PHUIStatusItemView::ICON_DOWN;
$color = 'green';
$icon_label = pht('Valid Output');
}
}
if ($error) {
$note = array(
phutil_tag('strong', array(), pht('ERROR:')),
' ',
$error,
);
} else {
$note = $bound;
}
$list->addItem(
id(new PHUIStatusItemView())
->setIcon($icon, $color, $icon_label)
->setTarget($artifact['name'])
->setNote($note));
}
$ui = array(
$header,
$list,
);
return array($ui, $has_conflicts);
}
private function buildDependsOnList(
array $step_phids,
$name,
array $steps) {
$has_conflicts = false;
if (!$step_phids) {
return null;
}
$this->requireResource('harbormaster-css');
$steps = mpull($steps, null, 'getPHID');
$header = phutil_tag(
'div',
array(
'class' => 'harbormaster-artifact-summary-header',
),
$name);
$list = new PHUIStatusListView();
foreach ($step_phids as $step_phid) {
$error = null;
if (idx($steps, $step_phid) === null) {
$icon = PHUIStatusItemView::ICON_WARNING;
$color = 'red';
$icon_label = pht('Missing Dependency');
$has_conflicts = true;
$error = pht(
"This dependency specifies a build step which doesn't exist.");
} else {
$bound = phutil_tag(
'strong',
array(),
idx($steps, $step_phid)->getName());
$icon = PHUIStatusItemView::ICON_ACCEPT;
$color = 'green';
$icon_label = pht('Valid Input');
}
if ($error) {
$note = array(
phutil_tag('strong', array(), pht('ERROR:')),
' ',
$error,
);
} else {
$note = $bound;
}
$list->addItem(
id(new PHUIStatusItemView())
->setIcon($icon, $color, $icon_label)
->setTarget(pht('Build Step'))
->setNote($note));
}
$ui = array(
$header,
$list,
);
return array($ui, $has_conflicts);
}
private function newBuildsView(HarbormasterBuildPlan $plan) {
$viewer = $this->getViewer();
$limit = 10;
$builds = id(new HarbormasterBuildQuery())
->setViewer($viewer)
->withBuildPlanPHIDs(array($plan->getPHID()))
->setLimit($limit + 1)
->execute();
$more_results = (count($builds) > $limit);
$builds = array_slice($builds, 0, $limit);
$list = id(new HarbormasterBuildView())
->setViewer($viewer)
->setBuilds($builds)
->newObjectList();
$list->setNoDataString(pht('No recent builds.'));
$more_href = new PhutilURI(
$this->getApplicationURI('/build/'),
array('plan' => $plan->getPHID()));
if ($more_results) {
$list->newTailButton()
->setHref($more_href);
}
$more_link = id(new PHUIButtonView())
->setTag('a')
->setIcon('fa-list-ul')
->setText(pht('View All Builds'))
->setHref($more_href);
$header = id(new PHUIHeaderView())
->setHeader(pht('Recent Builds'))
->addActionLink($more_link);
return id(new PHUIObjectBoxView())
->setHeader($header)
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($list);
}
private function newRulesView(HarbormasterBuildPlan $plan) {
$viewer = $this->getViewer();
$limit = 10;
$rules = id(new HeraldRuleQuery())
->setViewer($viewer)
->withDisabled(false)
->withAffectedObjectPHIDs(array($plan->getPHID()))
->needValidateAuthors(true)
->setLimit($limit + 1)
->execute();
$more_results = (count($rules) > $limit);
$rules = array_slice($rules, 0, $limit);
$list = id(new HeraldRuleListView())
->setViewer($viewer)
->setRules($rules)
->newObjectList();
$list->setNoDataString(pht('No active Herald rules trigger this build.'));
$more_href = new PhutilURI(
'/herald/',
array('affectedPHID' => $plan->getPHID()));
if ($more_results) {
$list->newTailButton()
->setHref($more_href);
}
$more_link = id(new PHUIButtonView())
->setTag('a')
->setIcon('fa-list-ul')
->setText(pht('View All Rules'))
->setHref($more_href);
$header = id(new PHUIHeaderView())
->setHeader(pht('Run By Herald Rules'))
->addActionLink($more_link);
return id(new PHUIObjectBoxView())
->setHeader($header)
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($list);
}
private function newOptionsView(HarbormasterBuildPlan $plan) {
$viewer = $this->getViewer();
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$plan,
PhabricatorPolicyCapability::CAN_EDIT);
$behaviors = HarbormasterBuildPlanBehavior::newPlanBehaviors();
$rows = array();
foreach ($behaviors as $behavior) {
$option = $behavior->getPlanOption($plan);
$icon = $option->getIcon();
$icon = id(new PHUIIconView())->setIcon($icon);
$edit_uri = new PhutilURI(
$this->getApplicationURI(
urisprintf(
'plan/behavior/%d/%s/',
$plan->getID(),
$behavior->getKey())));
$edit_button = id(new PHUIButtonView())
->setTag('a')
->setColor(PHUIButtonView::GREY)
->setSize(PHUIButtonView::SMALL)
->setDisabled(!$can_edit)
->setWorkflow(true)
->setText(pht('Edit'))
->setHref($edit_uri);
$rows[] = array(
$icon,
$behavior->getName(),
$option->getName(),
$option->getDescription(),
$edit_button,
);
}
$table = id(new AphrontTableView($rows))
->setHeaders(
array(
null,
pht('Name'),
pht('Behavior'),
pht('Details'),
null,
))
->setColumnClasses(
array(
null,
'pri',
null,
'wide',
null,
));
$header = id(new PHUIHeaderView())
->setHeader(pht('Plan Behaviors'));
return id(new PHUIObjectBoxView())
->setHeader($header)
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setTable($table);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterBuildLogDownloadController.php | src/applications/harbormaster/controller/HarbormasterBuildLogDownloadController.php | <?php
final class HarbormasterBuildLogDownloadController
extends HarbormasterController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$request = $this->getRequest();
$viewer = $request->getUser();
$id = $request->getURIData('id');
$log = id(new HarbormasterBuildLogQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
if (!$log) {
return new Aphront404Response();
}
$cancel_uri = $log->getURI();
$file_phid = $log->getFilePHID();
if (!$file_phid) {
return $this->newDialog()
->setTitle(pht('Log Not Finalized'))
->appendParagraph(
pht(
'Logs must be fully written and processed before they can be '.
'downloaded. This log is still being written or processed.'))
->addCancelButton($cancel_uri, pht('Wait Patiently'));
}
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($file_phid))
->executeOne();
if (!$file) {
return $this->newDialog()
->setTitle(pht('Unable to Load File'))
->appendParagraph(
pht(
'Unable to load the file for this log. The file may have been '.
'destroyed.'))
->addCancelButton($cancel_uri);
}
return $file->newDownloadResponse();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterBuildkiteHookController.php | src/applications/harbormaster/controller/HarbormasterBuildkiteHookController.php | <?php
final class HarbormasterBuildkiteHookController
extends HarbormasterController {
public function shouldRequireLogin() {
return false;
}
/**
* @phutil-external-symbol class PhabricatorStartup
*/
public function handleRequest(AphrontRequest $request) {
$raw_body = PhabricatorStartup::getRawInput();
$body = phutil_json_decode($raw_body);
$event = idx($body, 'event');
if ($event != 'build.finished') {
return $this->newHookResponse(pht('OK: Ignored event.'));
}
$build = idx($body, 'build');
if (!is_array($build)) {
throw new Exception(
pht(
'Expected "%s" property to contain a dictionary.',
'build'));
}
$meta_data = idx($build, 'meta_data');
if (!is_array($meta_data)) {
throw new Exception(
pht(
'Expected "%s" property to contain a dictionary.',
'build.meta_data'));
}
$target_phid = idx($meta_data, 'buildTargetPHID');
if (!$target_phid) {
return $this->newHookResponse(pht('OK: No Harbormaster target PHID.'));
}
$viewer = PhabricatorUser::getOmnipotentUser();
$target = id(new HarbormasterBuildTargetQuery())
->setViewer($viewer)
->withPHIDs(array($target_phid))
->needBuildSteps(true)
->executeOne();
if (!$target) {
throw new Exception(
pht(
'Harbormaster build target "%s" does not exist.',
$target_phid));
}
$step = $target->getBuildStep();
$impl = $step->getStepImplementation();
if (!($impl instanceof HarbormasterBuildkiteBuildStepImplementation)) {
throw new Exception(
pht(
'Harbormaster build target "%s" is not a Buildkite build step. '.
'Only Buildkite steps may be updated via the Buildkite hook.',
$target_phid));
}
$webhook_token = $impl->getSetting('webhook.token');
$request_token = $request->getHTTPHeader('X-Buildkite-Token');
if (!phutil_hashes_are_identical($webhook_token, $request_token)) {
throw new Exception(
pht(
'Buildkite request to target "%s" had the wrong authentication '.
'token. The Buildkite pipeline and Harbormaster build step must '.
'be configured with the same token.',
$target_phid));
}
$state = idx($build, 'state');
switch ($state) {
case 'passed':
$message_type = HarbormasterMessageType::MESSAGE_PASS;
break;
default:
$message_type = HarbormasterMessageType::MESSAGE_FAIL;
break;
}
$api_method = 'harbormaster.sendmessage';
$api_params = array(
'buildTargetPHID' => $target_phid,
'type' => $message_type,
);
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
id(new ConduitCall($api_method, $api_params))
->setUser($viewer)
->execute();
unset($unguarded);
return $this->newHookResponse(pht('OK: Processed event.'));
}
private function newHookResponse($message) {
$response = new AphrontWebpageResponse();
$response->setContent($message);
return $response;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterPlanRunController.php | src/applications/harbormaster/controller/HarbormasterPlanRunController.php | <?php
final class HarbormasterPlanRunController extends HarbormasterPlanController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$plan_id = $request->getURIData('id');
$plan = id(new HarbormasterBuildPlanQuery())
->setViewer($viewer)
->withIDs(array($plan_id))
->executeOne();
if (!$plan) {
return new Aphront404Response();
}
$plan->assertHasRunCapability($viewer);
$cancel_uri = $this->getApplicationURI("plan/{$plan_id}/");
if (!$plan->canRunManually()) {
return $this->newDialog()
->setTitle(pht('Can Not Run Plan'))
->appendParagraph(pht('This plan can not be run manually.'))
->addCancelButton($cancel_uri);
}
$e_name = true;
$v_name = null;
$errors = array();
if ($request->isFormPost()) {
$buildable = HarbormasterBuildable::initializeNewBuildable($viewer)
->setIsManualBuildable(true);
$v_name = $request->getStr('buildablePHID');
if ($v_name) {
$object = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withNames(array($v_name))
->executeOne();
if ($object instanceof HarbormasterBuildableInterface) {
$buildable
->setBuildablePHID($object->getHarbormasterBuildablePHID())
->setContainerPHID($object->getHarbormasterContainerPHID());
} else {
$e_name = pht('Invalid');
$errors[] = pht('Enter the name of a revision or commit.');
}
} else {
$e_name = pht('Required');
$errors[] = pht('You must choose a revision or commit to build.');
}
if (!$errors) {
$buildable->save();
$buildable->sendMessage(
$viewer,
HarbormasterMessageType::BUILDABLE_BUILD,
false);
$buildable->applyPlan($plan, array(), $viewer->getPHID());
$buildable_uri = '/B'.$buildable->getID();
return id(new AphrontRedirectResponse())->setURI($buildable_uri);
}
}
if ($errors) {
$errors = id(new PHUIInfoView())->setErrors($errors);
}
$title = pht('Run Build Plan Manually');
$save_button = pht('Run Plan Manually');
$form = id(new PHUIFormLayoutView())
->setUser($viewer)
->appendRemarkupInstructions(
pht(
"Enter the name of a commit or revision to run this plan on (for ".
"example, `rX123456` or `D123`).\n\n".
"For more detailed output, you can also run manual builds from ".
"the command line:\n\n".
" $ ./bin/harbormaster build <object> --plan %s",
$plan->getID()))
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Buildable Name'))
->setName('buildablePHID')
->setError($e_name)
->setValue($v_name));
return $this->newDialog()
->setWidth(AphrontDialogView::WIDTH_FULL)
->setTitle($title)
->appendChild($form)
->addCancelButton($cancel_uri)
->addSubmitButton($save_button);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterBuildActionController.php | src/applications/harbormaster/controller/HarbormasterBuildActionController.php | <?php
final class HarbormasterBuildActionController
extends HarbormasterController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$id = $request->getURIData('id');
$action = $request->getURIData('action');
$via = $request->getURIData('via');
$build = id(new HarbormasterBuildQuery())
->setViewer($viewer)
->withIDs(array($id))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$build) {
return new Aphront404Response();
}
$xaction =
HarbormasterBuildMessageTransaction::getTransactionObjectForMessageType(
$action);
if (!$xaction) {
return new Aphront404Response();
}
switch ($via) {
case 'buildable':
$return_uri = '/'.$build->getBuildable()->getMonogram();
break;
default:
$return_uri = $this->getApplicationURI('/build/'.$build->getID().'/');
break;
}
try {
$xaction->assertCanSendMessage($viewer, $build);
} catch (HarbormasterMessageException $ex) {
return $this->newDialog()
->setTitle($ex->getTitle())
->appendChild($ex->getBody())
->addCancelButton($return_uri);
}
if ($request->isDialogFormPost()) {
$build->sendMessage($viewer, $xaction->getHarbormasterBuildMessageType());
return id(new AphrontRedirectResponse())->setURI($return_uri);
}
$title = $xaction->newConfirmPromptTitle();
$body = $xaction->newConfirmPromptBody();
$submit = $xaction->getHarbormasterBuildMessageName();
return $this->newDialog()
->setTitle($title)
->appendChild($body)
->addCancelButton($return_uri)
->addSubmitButton($submit);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterUnitMessageListController.php | src/applications/harbormaster/controller/HarbormasterUnitMessageListController.php | <?php
final class HarbormasterUnitMessageListController
extends HarbormasterController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$buildable = id(new HarbormasterBuildableQuery())
->setViewer($viewer)
->withIDs(array($request->getURIData('id')))
->needBuilds(true)
->needTargets(true)
->executeOne();
if (!$buildable) {
return new Aphront404Response();
}
$id = $buildable->getID();
$target_phids = array();
foreach ($buildable->getBuilds() as $build) {
foreach ($build->getBuildTargets() as $target) {
$target_phids[] = $target->getPHID();
}
}
$unit_data = array();
if ($target_phids) {
$unit_data = id(new HarbormasterBuildUnitMessageQuery())
->setViewer($viewer)
->withBuildTargetPHIDs($target_phids)
->execute();
} else {
$unit_data = array();
}
$unit = id(new HarbormasterUnitSummaryView())
->setViewer($viewer)
->setBuildable($buildable)
->setUnitMessages($unit_data);
$crumbs = $this->buildApplicationCrumbs();
$this->addBuildableCrumb($crumbs, $buildable);
$crumbs->addTextCrumb(pht('Unit Tests'));
$crumbs->setBorder(true);
$title = array(
$buildable->getMonogram(),
pht('Unit Tests'),
);
$header = id(new PHUIHeaderView())
->setHeader($buildable->getMonogram().' '.pht('Unit Tests'));
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setFooter(array(
$unit,
));
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/harbormaster/controller/HarbormasterUnitMessageViewController.php | src/applications/harbormaster/controller/HarbormasterUnitMessageViewController.php | <?php
final class HarbormasterUnitMessageViewController
extends HarbormasterController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$message_id = $request->getURIData('id');
$message = id(new HarbormasterBuildUnitMessageQuery())
->setViewer($viewer)
->withIDs(array($message_id))
->executeOne();
if (!$message) {
return new Aphront404Response();
}
$build_target = id(new HarbormasterBuildTargetQuery())
->setViewer($viewer)
->withPHIDs(array($message->getBuildTargetPHID()))
->executeOne();
if (!$build_target) {
return new Aphront404Response();
}
$build = $build_target->getBuild();
$buildable = $build->getBuildable();
$buildable_id = $buildable->getID();
$id = $message->getID();
$display_name = $message->getUnitMessageDisplayName();
$status = $message->getResult();
$status_icon = HarbormasterUnitStatus::getUnitStatusIcon($status);
$status_color = HarbormasterUnitStatus::getUnitStatusColor($status);
$status_label = HarbormasterUnitStatus::getUnitStatusLabel($status);
$header = id(new PHUIHeaderView())
->setHeader($display_name)
->setStatus($status_icon, $status_color, $status_label);
$properties = $this->buildPropertyListView($message);
$curtain = $this->buildCurtainView($message, $build);
$unit = id(new PHUIObjectBoxView())
->setHeaderText(pht('TEST RESULT'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->addPropertyList($properties);
$crumbs = $this->buildApplicationCrumbs();
$this->addBuildableCrumb($crumbs, $buildable);
$crumbs->addTextCrumb(
pht('Unit Tests'),
"/harbormaster/unit/{$buildable_id}/");
$crumbs->addTextCrumb(pht('Unit %d', $id));
$crumbs->setBorder(true);
$title = array(
$display_name,
$buildable->getMonogram(),
);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setCurtain($curtain)
->setMainColumn(array(
$unit,
));
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->appendChild($view);
}
private function buildPropertyListView(
HarbormasterBuildUnitMessage $message) {
$viewer = $this->getViewer();
$view = id(new PHUIPropertyListView())
->setUser($viewer);
$view->addProperty(
pht('Run At'),
phabricator_datetime($message->getDateCreated(), $viewer));
$details = $message->newUnitMessageDetailsView($viewer);
$view->addSectionHeader(
pht('Details'),
PHUIPropertyListView::ICON_TESTPLAN);
$view->addTextContent($details);
return $view;
}
private function buildCurtainView(
HarbormasterBuildUnitMessage $message,
HarbormasterBuild $build) {
$viewer = $this->getViewer();
$curtain = $this->newCurtainView($build);
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('View Build'))
->setHref($build->getURI())
->setIcon('fa-wrench'));
return $curtain;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterBuildableListController.php | src/applications/harbormaster/controller/HarbormasterBuildableListController.php | <?php
final class HarbormasterBuildableListController extends HarbormasterController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$items = array();
$items[] = id(new PHUIListItemView())
->setType(PHUIListItemView::TYPE_LABEL)
->setName(pht('Builds'));
$items[] = id(new PHUIListItemView())
->setType(PHUIListItemView::TYPE_LINK)
->setName(pht('Browse Builds'))
->setHref($this->getApplicationURI('build/'));
$items[] = id(new PHUIListItemView())
->setType(PHUIListItemView::TYPE_LABEL)
->setName(pht('Build Plans'));
$items[] = id(new PHUIListItemView())
->setType(PHUIListItemView::TYPE_LINK)
->setName(pht('Manage Build Plans'))
->setHref($this->getApplicationURI('plan/'));
return id(new HarbormasterBuildableSearchEngine())
->setController($this)
->setNavigationItems($items)
->buildResponse();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterStepEditController.php | src/applications/harbormaster/controller/HarbormasterStepEditController.php | <?php
final class HarbormasterStepEditController
extends HarbormasterPlanController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$id = $request->getURIData('id');
if ($id) {
$step = id(new HarbormasterBuildStepQuery())
->setViewer($viewer)
->withIDs(array($id))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$step) {
return new Aphront404Response();
}
$plan = $step->getBuildPlan();
$is_new = false;
} else {
$plan_id = $request->getURIData('plan');
$class = $request->getURIData('class');
$plan = id(new HarbormasterBuildPlanQuery())
->setViewer($viewer)
->withIDs(array($plan_id))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$plan) {
return new Aphront404Response();
}
$impl = HarbormasterBuildStepImplementation::getImplementation($class);
if (!$impl) {
return new Aphront404Response();
}
if ($impl->shouldRequireAutotargeting()) {
// No manual creation of autotarget steps.
return new Aphront404Response();
}
$step = HarbormasterBuildStep::initializeNewStep($viewer)
->setBuildPlanPHID($plan->getPHID())
->setClassName($class);
$is_new = true;
}
$plan_uri = $this->getApplicationURI('plan/'.$plan->getID().'/');
if ($is_new) {
$cancel_uri = $plan_uri;
} else {
$cancel_uri = $this->getApplicationURI('step/view/'.$step->getID().'/');
}
$implementation = $step->getStepImplementation();
$field_list = PhabricatorCustomField::getObjectFields(
$step,
PhabricatorCustomField::ROLE_EDIT);
$field_list
->setViewer($viewer)
->readFieldsFromStorage($step);
$e_name = true;
$v_name = $step->getName();
$e_description = null;
$v_description = $step->getDescription();
$e_depends_on = null;
$v_depends_on = $step->getDetail('dependsOn', array());
$errors = array();
$validation_exception = null;
if ($request->isFormPost()) {
$e_name = null;
$v_name = $request->getStr('name');
$v_description = $request->getStr('description');
$v_depends_on = $request->getArr('dependsOn');
$xactions = $field_list->buildFieldTransactionsFromRequest(
new HarbormasterBuildStepTransaction(),
$request);
$editor = id(new HarbormasterBuildStepEditor())
->setActor($viewer)
->setContinueOnNoEffect(true)
->setContentSourceFromRequest($request);
$name_xaction = id(new HarbormasterBuildStepTransaction())
->setTransactionType(HarbormasterBuildStepTransaction::TYPE_NAME)
->setNewValue($v_name);
array_unshift($xactions, $name_xaction);
$depends_on_xaction = id(new HarbormasterBuildStepTransaction())
->setTransactionType(
HarbormasterBuildStepTransaction::TYPE_DEPENDS_ON)
->setNewValue($v_depends_on);
array_unshift($xactions, $depends_on_xaction);
$description_xaction = id(new HarbormasterBuildStepTransaction())
->setTransactionType(
HarbormasterBuildStepTransaction::TYPE_DESCRIPTION)
->setNewValue($v_description);
array_unshift($xactions, $description_xaction);
if ($is_new) {
// When creating a new step, make sure we have a create transaction
// so we'll apply the transactions even if the step has no
// configurable options.
$create_xaction = id(new HarbormasterBuildStepTransaction())
->setTransactionType(HarbormasterBuildStepTransaction::TYPE_CREATE);
array_unshift($xactions, $create_xaction);
}
try {
$editor->applyTransactions($step, $xactions);
$step_uri = $this->getApplicationURI('step/view/'.$step->getID().'/');
return id(new AphrontRedirectResponse())->setURI($step_uri);
} catch (PhabricatorApplicationTransactionValidationException $ex) {
$validation_exception = $ex;
}
}
$form = id(new AphrontFormView())
->setUser($viewer);
$instructions = $implementation->getEditInstructions();
if (strlen($instructions)) {
$form->appendRemarkupInstructions($instructions);
}
$form->appendChild(
id(new AphrontFormTextControl())
->setName('name')
->setLabel(pht('Name'))
->setError($e_name)
->setValue($v_name));
$form->appendChild(id(new AphrontFormDividerControl()));
$field_list->appendFieldsToForm($form);
$form->appendChild(id(new AphrontFormDividerControl()));
$form
->appendControl(
id(new AphrontFormTokenizerControl())
->setDatasource(id(new HarbormasterBuildDependencyDatasource())
->setParameters(array(
'planPHID' => $plan->getPHID(),
'stepPHID' => $is_new ? null : $step->getPHID(),
)))
->setName('dependsOn')
->setLabel(pht('Depends On'))
->setError($e_depends_on)
->setValue($v_depends_on));
$form
->appendChild(
id(new PhabricatorRemarkupControl())
->setUser($viewer)
->setName('description')
->setLabel(pht('Description'))
->setError($e_description)
->setValue($v_description));
$crumbs = $this->buildApplicationCrumbs();
$id = $plan->getID();
$crumbs->addTextCrumb(pht('Plan %d', $id), $plan_uri);
if ($is_new) {
$submit = pht('Create Build Step');
$header = id(new PHUIHeaderView())
->setHeader(pht('New Step: %s', $implementation->getName()))
->setHeaderIcon('fa-plus-square');
$crumbs->addTextCrumb(pht('Add Step'));
} else {
$submit = pht('Save Build Step');
$header = id(new PHUIHeaderView())
->setHeader(pht('Edit Step: %s', $implementation->getName()))
->setHeaderIcon('fa-pencil');
$crumbs->addTextCrumb(pht('Step %d', $step->getID()), $cancel_uri);
$crumbs->addTextCrumb(pht('Edit Step'));
}
$crumbs->setBorder(true);
$form->appendChild(
id(new AphrontFormSubmitControl())
->setValue($submit)
->addCancelButton($cancel_uri));
$box = id(new PHUIObjectBoxView())
->setHeaderText(pht('Step'))
->setValidationException($validation_exception)
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setForm($form);
$variables = $this->renderBuildVariablesTable();
if ($is_new) {
$xaction_view = null;
$timeline = null;
} else {
$timeline = $this->buildTransactionTimeline(
$step,
new HarbormasterBuildStepTransactionQuery());
$timeline->setShouldTerminate(true);
}
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setFooter(array(
$box,
$variables,
$timeline,
));
return $this->newPage()
->setTitle($implementation->getName())
->setCrumbs($crumbs)
->appendChild($view);
}
private function renderBuildVariablesTable() {
$viewer = $this->getRequest()->getUser();
$variables = HarbormasterBuild::getAvailableBuildVariables();
ksort($variables);
$rows = array();
$rows[] = pht(
'The following variables can be used in most fields. '.
'To reference a variable, use `%s` in a field.',
'${name}');
$rows[] = sprintf(
'| %s | %s |',
pht('Variable'),
pht('Description'));
$rows[] = '|---|---|';
foreach ($variables as $name => $description) {
$rows[] = '| `'.$name.'` | '.$description.' |';
}
$rows = implode("\n", $rows);
$form = id(new AphrontFormView())
->setUser($viewer)
->appendRemarkupInstructions($rows);
return id(new PHUIObjectBoxView())
->setHeaderText(pht('Build Variables'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($form);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterBuildViewController.php | src/applications/harbormaster/controller/HarbormasterBuildViewController.php | <?php
final class HarbormasterBuildViewController
extends HarbormasterController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$request = $this->getRequest();
$viewer = $request->getUser();
$id = $request->getURIData('id');
$build = id(new HarbormasterBuildQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
if (!$build) {
return new Aphront404Response();
}
require_celerity_resource('harbormaster-css');
$title = pht('Build %d', $id);
$warnings = array();
$page_header = id(new PHUIHeaderView())
->setHeader($title)
->setUser($viewer)
->setPolicyObject($build)
->setHeaderIcon('fa-cubes');
$status = $build->getBuildPendingStatusObject();
$status_icon = $status->getIconIcon();
$status_color = $status->getIconColor();
$status_name = $status->getName();
$page_header->setStatus($status_icon, $status_color, $status_name);
$max_generation = (int)$build->getBuildGeneration();
if ($max_generation === 0) {
$min_generation = 0;
} else {
$min_generation = 1;
}
if ($build->isRestarting()) {
$max_generation = $max_generation + 1;
}
$generation = $request->getURIData('generation');
if ($generation === null) {
$generation = $max_generation;
} else {
$generation = (int)$generation;
}
if ($generation < $min_generation || $generation > $max_generation) {
return new Aphront404Response();
}
if ($generation < $max_generation) {
$warnings[] = pht(
'You are viewing an older run of this build. %s',
phutil_tag(
'a',
array(
'href' => $build->getURI(),
),
pht('View Current Build')));
}
$curtain = $this->buildCurtainView($build);
$properties = $this->buildPropertyList($build);
$history = $this->buildHistoryTable(
$build,
$generation,
$min_generation,
$max_generation);
$crumbs = $this->buildApplicationCrumbs();
$this->addBuildableCrumb($crumbs, $build->getBuildable());
$crumbs->addTextCrumb($title);
$crumbs->setBorder(true);
$build_targets = id(new HarbormasterBuildTargetQuery())
->setViewer($viewer)
->needBuildSteps(true)
->withBuildPHIDs(array($build->getPHID()))
->withBuildGenerations(array($generation))
->execute();
if ($build_targets) {
$messages = id(new HarbormasterBuildMessageQuery())
->setViewer($viewer)
->withReceiverPHIDs(mpull($build_targets, 'getPHID'))
->execute();
$messages = mgroup($messages, 'getReceiverPHID');
} else {
$messages = array();
}
if ($build_targets) {
$artifacts = id(new HarbormasterBuildArtifactQuery())
->setViewer($viewer)
->withBuildTargetPHIDs(mpull($build_targets, 'getPHID'))
->execute();
$artifacts = msort($artifacts, 'getArtifactKey');
$artifacts = mgroup($artifacts, 'getBuildTargetPHID');
} else {
$artifacts = array();
}
$targets = array();
foreach ($build_targets as $build_target) {
$header = id(new PHUIHeaderView())
->setHeader($build_target->getName())
->setUser($viewer)
->setHeaderIcon('fa-bullseye');
$target_box = id(new PHUIObjectBoxView())
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setHeader($header);
$tab_group = new PHUITabGroupView();
$target_box->addTabGroup($tab_group);
$property_list = new PHUIPropertyListView();
$target_artifacts = idx($artifacts, $build_target->getPHID(), array());
$links = array();
$type_uri = HarbormasterURIArtifact::ARTIFACTCONST;
foreach ($target_artifacts as $artifact) {
if ($artifact->getArtifactType() == $type_uri) {
$impl = $artifact->getArtifactImplementation();
if ($impl->isExternalLink()) {
$links[] = $impl->renderLink();
}
}
}
if ($links) {
$links = phutil_implode_html(phutil_tag('br'), $links);
$property_list->addProperty(
pht('External Link'),
$links);
}
$status_view = new PHUIStatusListView();
$item = new PHUIStatusItemView();
$status = $build_target->getTargetStatus();
$status_name =
HarbormasterBuildTarget::getBuildTargetStatusName($status);
$icon = HarbormasterBuildTarget::getBuildTargetStatusIcon($status);
$color = HarbormasterBuildTarget::getBuildTargetStatusColor($status);
$item->setTarget($status_name);
$item->setIcon($icon, $color);
$status_view->addItem($item);
$when = array();
$started = $build_target->getDateStarted();
$now = PhabricatorTime::getNow();
if ($started) {
$ended = $build_target->getDateCompleted();
if ($ended) {
$when[] = pht(
'Completed at %s',
phabricator_datetime($ended, $viewer));
$duration = ($ended - $started);
if ($duration) {
$when[] = pht(
'Built for %s',
phutil_format_relative_time_detailed($duration));
} else {
$when[] = pht('Built instantly');
}
} else {
$when[] = pht(
'Started at %s',
phabricator_datetime($started, $viewer));
$duration = ($now - $started);
if ($duration) {
$when[] = pht(
'Running for %s',
phutil_format_relative_time_detailed($duration));
}
}
} else {
$created = $build_target->getDateCreated();
$when[] = pht(
'Queued at %s',
phabricator_datetime($started, $viewer));
$duration = ($now - $created);
if ($duration) {
$when[] = pht(
'Waiting for %s',
phutil_format_relative_time_detailed($duration));
}
}
$property_list->addProperty(
pht('When'),
phutil_implode_html(" \xC2\xB7 ", $when));
$property_list->addProperty(pht('Status'), $status_view);
$tab_group->addTab(
id(new PHUITabView())
->setName(pht('Overview'))
->setKey('overview')
->appendChild($property_list));
$step = $build_target->getBuildStep();
if ($step) {
$description = $step->getDescription();
if ($description) {
$description = new PHUIRemarkupView($viewer, $description);
$property_list->addSectionHeader(
pht('Description'), PHUIPropertyListView::ICON_SUMMARY);
$property_list->addTextContent($description);
}
} else {
$target_box->setFormErrors(
array(
pht(
'This build step has since been deleted on the build plan. '.
'Some information may be omitted.'),
));
}
$details = $build_target->getDetails();
$property_list = new PHUIPropertyListView();
foreach ($details as $key => $value) {
$property_list->addProperty($key, $value);
}
$tab_group->addTab(
id(new PHUITabView())
->setName(pht('Configuration'))
->setKey('configuration')
->appendChild($property_list));
$variables = $build_target->getVariables();
$variables_tab = $this->buildProperties($variables);
$tab_group->addTab(
id(new PHUITabView())
->setName(pht('Variables'))
->setKey('variables')
->appendChild($variables_tab));
$artifacts_tab = $this->buildArtifacts($build_target, $target_artifacts);
$tab_group->addTab(
id(new PHUITabView())
->setName(pht('Artifacts'))
->setKey('artifacts')
->appendChild($artifacts_tab));
$build_messages = idx($messages, $build_target->getPHID(), array());
$messages_tab = $this->buildMessages($build_messages);
$tab_group->addTab(
id(new PHUITabView())
->setName(pht('Messages'))
->setKey('messages')
->appendChild($messages_tab));
$property_list = new PHUIPropertyListView();
$property_list->addProperty(
pht('Build Target ID'),
$build_target->getID());
$property_list->addProperty(
pht('Build Target PHID'),
$build_target->getPHID());
$tab_group->addTab(
id(new PHUITabView())
->setName(pht('Metadata'))
->setKey('metadata')
->appendChild($property_list));
$targets[] = $target_box;
$targets[] = $this->buildLog($build, $build_target, $generation);
}
$timeline = $this->buildTransactionTimeline(
$build,
new HarbormasterBuildTransactionQuery());
$timeline->setShouldTerminate(true);
if ($warnings) {
$warnings = id(new PHUIInfoView())
->setErrors($warnings)
->setSeverity(PHUIInfoView::SEVERITY_WARNING);
} else {
$warnings = null;
}
$view = id(new PHUITwoColumnView())
->setHeader($page_header)
->setCurtain($curtain)
->setMainColumn(
array(
$warnings,
$properties,
$history,
$targets,
$timeline,
));
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->appendChild($view);
}
private function buildArtifacts(
HarbormasterBuildTarget $build_target,
array $artifacts) {
$viewer = $this->getViewer();
$rows = array();
foreach ($artifacts as $artifact) {
$impl = $artifact->getArtifactImplementation();
if ($impl) {
$summary = $impl->renderArtifactSummary($viewer);
$type_name = $impl->getArtifactTypeName();
} else {
$summary = pht('<Unknown Artifact Type>');
$type_name = $artifact->getType();
}
$rows[] = array(
$artifact->getArtifactKey(),
$type_name,
$summary,
);
}
$table = id(new AphrontTableView($rows))
->setNoDataString(pht('This target has no associated artifacts.'))
->setHeaders(
array(
pht('Key'),
pht('Type'),
pht('Summary'),
))
->setColumnClasses(
array(
'pri',
'',
'wide',
));
return $table;
}
private function buildLog(
HarbormasterBuild $build,
HarbormasterBuildTarget $build_target,
$generation) {
$request = $this->getRequest();
$viewer = $request->getUser();
$limit = $request->getInt('l', 25);
$logs = id(new HarbormasterBuildLogQuery())
->setViewer($viewer)
->withBuildTargetPHIDs(array($build_target->getPHID()))
->execute();
$empty_logs = array();
$log_boxes = array();
foreach ($logs as $log) {
$start = 1;
$lines = preg_split("/\r\n|\r|\n/", $log->getLogText());
if ($limit !== 0) {
$start = count($lines) - $limit;
if ($start >= 1) {
$lines = array_slice($lines, -$limit, $limit);
} else {
$start = 1;
}
}
$id = null;
$is_empty = false;
if (count($lines) === 1 && trim($lines[0]) === '') {
// Prevent Harbormaster from showing empty build logs.
$id = celerity_generate_unique_node_id();
$empty_logs[] = $id;
$is_empty = true;
}
$log_view = new ShellLogView();
$log_view->setLines($lines);
$log_view->setStart($start);
$subheader = $this->createLogHeader($build, $log, $limit, $generation);
$prototype_view = id(new PHUIButtonView())
->setTag('a')
->setHref($log->getURI())
->setIcon('fa-file-text-o')
->setText(pht('New View (Prototype)'));
$header = id(new PHUIHeaderView())
->setHeader(pht(
'Build Log %d (%s - %s)',
$log->getID(),
$log->getLogSource(),
$log->getLogType()))
->addActionLink($prototype_view)
->setSubheader($subheader)
->setUser($viewer);
$log_box = id(new PHUIObjectBoxView())
->setHeader($header)
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setForm($log_view);
if ($is_empty) {
$log_box = phutil_tag(
'div',
array(
'style' => 'display: none',
'id' => $id,
),
$log_box);
}
$log_boxes[] = $log_box;
}
if ($empty_logs) {
$hide_id = celerity_generate_unique_node_id();
Javelin::initBehavior('phabricator-reveal-content');
$expand = phutil_tag(
'div',
array(
'id' => $hide_id,
'class' => 'harbormaster-empty-logs-are-hidden',
),
array(
pht(
'%s empty logs are hidden.',
phutil_count($empty_logs)),
' ',
javelin_tag(
'a',
array(
'href' => '#',
'sigil' => 'reveal-content',
'meta' => array(
'showIDs' => $empty_logs,
'hideIDs' => array($hide_id),
),
),
pht('Show all logs.')),
));
array_unshift($log_boxes, $expand);
}
return $log_boxes;
}
private function createLogHeader($build, $log, $limit, $generation) {
$options = array(
array(
'n' => 25,
),
array(
'n' => 50,
),
array(
'n' => 100,
),
array(
'n' => 0,
'label' => pht('Unlimited'),
),
);
$base_uri = id(new PhutilURI($build->getURI().$generation.'/'));
$links = array();
foreach ($options as $option) {
$n = $option['n'];
$label = idx($option, 'label', $n);
$is_selected = ($limit == $n);
if ($is_selected) {
$links[] = phutil_tag(
'strong',
array(),
$label);
} else {
$links[] = phutil_tag(
'a',
array(
'href' => (string)$base_uri->alter('l', $n),
),
$label);
}
}
return phutil_tag(
'span',
array(),
array(
phutil_implode_html(' - ', $links),
' ',
pht('Lines'),
));
}
private function buildCurtainView(HarbormasterBuild $build) {
$viewer = $this->getViewer();
$id = $build->getID();
$curtain = $this->newCurtainView($build);
$messages = array(
new HarbormasterBuildMessageRestartTransaction(),
new HarbormasterBuildMessagePauseTransaction(),
new HarbormasterBuildMessageResumeTransaction(),
new HarbormasterBuildMessageAbortTransaction(),
);
foreach ($messages as $message) {
$can_send = $message->canSendMessage($viewer, $build);
$message_uri = urisprintf(
'/build/%s/%d/',
$message->getHarbormasterBuildMessageType(),
$id);
$message_uri = $this->getApplicationURI($message_uri);
$action = id(new PhabricatorActionView())
->setName($message->getHarbormasterBuildMessageName())
->setIcon($message->getIcon())
->setHref($message_uri)
->setDisabled(!$can_send)
->setWorkflow(true);
$curtain->addAction($action);
}
return $curtain;
}
private function buildPropertyList(HarbormasterBuild $build) {
$viewer = $this->getViewer();
$properties = id(new PHUIPropertyListView())
->setUser($viewer);
$handles = id(new PhabricatorHandleQuery())
->setViewer($viewer)
->withPHIDs(array(
$build->getBuildablePHID(),
$build->getBuildPlanPHID(),
))
->execute();
$properties->addProperty(
pht('Buildable'),
$handles[$build->getBuildablePHID()]->renderLink());
$properties->addProperty(
pht('Build Plan'),
$handles[$build->getBuildPlanPHID()]->renderLink());
return id(new PHUIObjectBoxView())
->setHeaderText(pht('Properties'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($properties);
}
private function buildHistoryTable(
HarbormasterBuild $build,
$generation,
$min_generation,
$max_generation) {
if ($max_generation === $min_generation) {
return null;
}
$viewer = $this->getViewer();
$uri = $build->getURI();
$rows = array();
$rowc = array();
for ($ii = $max_generation; $ii >= $min_generation; $ii--) {
if ($generation == $ii) {
$rowc[] = 'highlighted';
} else {
$rowc[] = null;
}
$rows[] = array(
phutil_tag(
'a',
array(
'href' => $uri.$ii.'/',
),
pht('Run %d', $ii)),
);
}
$table = id(new AphrontTableView($rows))
->setColumnClasses(
array(
'pri wide',
))
->setRowClasses($rowc);
return id(new PHUIObjectBoxView())
->setHeaderText(pht('History'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setTable($table);
}
private function buildMessages(array $messages) {
$viewer = $this->getRequest()->getUser();
if ($messages) {
$handles = id(new PhabricatorHandleQuery())
->setViewer($viewer)
->withPHIDs(mpull($messages, 'getAuthorPHID'))
->execute();
} else {
$handles = array();
}
$rows = array();
foreach ($messages as $message) {
$rows[] = array(
$message->getID(),
$handles[$message->getAuthorPHID()]->renderLink(),
$message->getType(),
$message->getIsConsumed() ? pht('Consumed') : null,
phabricator_datetime($message->getDateCreated(), $viewer),
);
}
$table = new AphrontTableView($rows);
$table->setNoDataString(pht('No messages for this build target.'));
$table->setHeaders(
array(
pht('ID'),
pht('From'),
pht('Type'),
pht('Consumed'),
pht('Received'),
));
$table->setColumnClasses(
array(
'',
'',
'wide',
'',
'date',
));
return $table;
}
private function buildProperties(array $properties) {
ksort($properties);
$rows = array();
foreach ($properties as $key => $value) {
$rows[] = array(
$key,
$value,
);
}
$table = id(new AphrontTableView($rows))
->setHeaders(
array(
pht('Key'),
pht('Value'),
))
->setColumnClasses(
array(
'pri right',
'wide',
));
return $table;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterLintMessagesController.php | src/applications/harbormaster/controller/HarbormasterLintMessagesController.php | <?php
final class HarbormasterLintMessagesController
extends HarbormasterController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$buildable = id(new HarbormasterBuildableQuery())
->setViewer($viewer)
->withIDs(array($request->getURIData('id')))
->needBuilds(true)
->needTargets(true)
->executeOne();
if (!$buildable) {
return new Aphront404Response();
}
$id = $buildable->getID();
$target_phids = array();
foreach ($buildable->getBuilds() as $build) {
foreach ($build->getBuildTargets() as $target) {
$target_phids[] = $target->getPHID();
}
}
$lint_data = array();
if ($target_phids) {
$lint_data = id(new HarbormasterBuildLintMessage())->loadAllWhere(
'buildTargetPHID IN (%Ls)',
$target_phids);
} else {
$lint_data = array();
}
$lint_table = id(new HarbormasterLintPropertyView())
->setUser($viewer)
->setLintMessages($lint_data);
$lint = id(new PHUIObjectBoxView())
->setHeaderText(pht('Lint Messages'))
->appendChild($lint_table);
$crumbs = $this->buildApplicationCrumbs();
$this->addBuildableCrumb($crumbs, $buildable);
$crumbs->addTextCrumb(pht('Lint'));
$crumbs->setBorder(true);
$title = array(
$buildable->getMonogram(),
pht('Lint'),
);
$header = id(new PHUIHeaderView())
->setHeader($title);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setFooter(array(
$lint,
));
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/harbormaster/controller/HarbormasterBuildListController.php | src/applications/harbormaster/controller/HarbormasterBuildListController.php | <?php
final class HarbormasterBuildListController extends HarbormasterController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
return id(new HarbormasterBuildSearchEngine())
->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/harbormaster/controller/HarbormasterStepDeleteController.php | src/applications/harbormaster/controller/HarbormasterStepDeleteController.php | <?php
final class HarbormasterStepDeleteController
extends HarbormasterPlanController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$id = $request->getURIData('id');
$step = id(new HarbormasterBuildStepQuery())
->setViewer($viewer)
->withIDs(array($id))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$step) {
return new Aphront404Response();
}
$plan_id = $step->getBuildPlan()->getID();
$done_uri = $this->getApplicationURI('plan/'.$plan_id.'/');
if ($request->isDialogFormPost()) {
$step->delete();
return id(new AphrontRedirectResponse())->setURI($done_uri);
}
return $this->newDialog()
->setTitle(pht('Really Delete Step?'))
->appendParagraph(
pht(
"Are you sure you want to delete this step? ".
"This can't be undone!"))
->addCancelButton($done_uri)
->addSubmitButton(pht('Delete Build Step'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterPlanController.php | src/applications/harbormaster/controller/HarbormasterPlanController.php | <?php
abstract class HarbormasterPlanController extends HarbormasterController {
public function buildApplicationMenu() {
return $this->newApplicationMenu()
->setSearchEngine(new HarbormasterBuildPlanSearchEngine());
}
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
$crumbs->addTextCrumb(
pht('Build Plans'),
$this->getApplicationURI('plan/'));
return $crumbs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterPlanListController.php | src/applications/harbormaster/controller/HarbormasterPlanListController.php | <?php
final class HarbormasterPlanListController extends HarbormasterPlanController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
return id(new HarbormasterBuildPlanSearchEngine())
->setController($this)
->buildResponse();
}
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
id(new HarbormasterBuildPlanEditEngine())
->setViewer($this->getViewer())
->addActionToCrumbs($crumbs);
return $crumbs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterPlanEditController.php | src/applications/harbormaster/controller/HarbormasterPlanEditController.php | <?php
final class HarbormasterPlanEditController extends HarbormasterPlanController {
public function handleRequest(AphrontRequest $request) {
return id(new HarbormasterBuildPlanEditEngine())
->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/harbormaster/controller/HarbormasterBuildLogRenderController.php | src/applications/harbormaster/controller/HarbormasterBuildLogRenderController.php | <?php
final class HarbormasterBuildLogRenderController
extends HarbormasterController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$id = $request->getURIData('id');
$log = id(new HarbormasterBuildLogQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
if (!$log) {
return new Aphront404Response();
}
$highlight_range = $request->getURILineRange('lines', 1000);
$log_size = $this->getTotalByteLength($log);
$head_lines = $request->getInt('head');
if ($head_lines === null) {
$head_lines = 8;
}
$head_lines = min($head_lines, 1024);
$head_lines = max($head_lines, 0);
$tail_lines = $request->getInt('tail');
if ($tail_lines === null) {
$tail_lines = 16;
}
$tail_lines = min($tail_lines, 1024);
$tail_lines = max($tail_lines, 0);
$head_offset = $request->getInt('headOffset');
if ($head_offset === null) {
$head_offset = 0;
}
$tail_offset = $request->getInt('tailOffset');
if ($tail_offset === null) {
$tail_offset = $log_size;
}
// Figure out which ranges we're actually going to read. We'll read either
// one range (either just at the head, or just at the tail) or two ranges
// (one at the head and one at the tail).
// This gets a little bit tricky because: the ranges may overlap; we just
// want to do one big read if there is only a little bit of text left
// between the ranges; we may not know where the tail range ends; and we
// can only read forward from line map markers, not from any arbitrary
// position in the file.
$bytes_per_line = 140;
$body_lines = 8;
$views = array();
if ($head_lines > 0) {
$views[] = array(
'offset' => $head_offset,
'lines' => $head_lines,
'direction' => 1,
'limit' => $tail_offset,
);
}
if ($highlight_range) {
$highlight_views = $this->getHighlightViews(
$log,
$highlight_range,
$log_size);
foreach ($highlight_views as $highlight_view) {
$views[] = $highlight_view;
}
}
if ($tail_lines > 0) {
$views[] = array(
'offset' => $tail_offset,
'lines' => $tail_lines,
'direction' => -1,
'limit' => $head_offset,
);
}
$reads = $views;
foreach ($reads as $key => $read) {
$offset = $read['offset'];
$lines = $read['lines'];
$read_length = 0;
$read_length += ($lines * $bytes_per_line);
$read_length += ($body_lines * $bytes_per_line);
$direction = $read['direction'];
if ($direction < 0) {
if ($offset > $read_length) {
$offset -= $read_length;
} else {
$read_length = $offset;
$offset = 0;
}
}
$position = $log->getReadPosition($offset);
list($position_offset, $position_line) = $position;
$read_length += ($offset - $position_offset);
$reads[$key]['fetchOffset'] = $position_offset;
$reads[$key]['fetchLength'] = $read_length;
$reads[$key]['fetchLine'] = $position_line;
}
$reads = $this->mergeOverlappingReads($reads);
foreach ($reads as $key => $read) {
$fetch_offset = $read['fetchOffset'];
$fetch_length = $read['fetchLength'];
if ($fetch_offset + $fetch_length > $log_size) {
$fetch_length = $log_size - $fetch_offset;
}
$data = $log->loadData($fetch_offset, $fetch_length);
$offset = $read['fetchOffset'];
$line = $read['fetchLine'];
$lines = $this->getLines($data);
$line_data = array();
foreach ($lines as $line_text) {
$length = strlen($line_text);
$line_data[] = array(
'offset' => $offset,
'length' => $length,
'line' => $line,
'data' => $line_text,
);
$line += 1;
$offset += $length;
}
$reads[$key]['data'] = $data;
$reads[$key]['lines'] = $line_data;
}
foreach ($views as $view_key => $view) {
$anchor_byte = $view['offset'];
if ($view['direction'] < 0) {
$anchor_byte = $anchor_byte - 1;
}
$data_key = null;
foreach ($reads as $read_key => $read) {
$s = $read['fetchOffset'];
$e = $s + $read['fetchLength'];
if (($s <= $anchor_byte) && ($e >= $anchor_byte)) {
$data_key = $read_key;
break;
}
}
if ($data_key === null) {
throw new Exception(
pht('Unable to find fetch!'));
}
$anchor_key = null;
foreach ($reads[$data_key]['lines'] as $line_key => $line) {
$s = $line['offset'];
$e = $s + $line['length'];
if (($s <= $anchor_byte) && ($e > $anchor_byte)) {
$anchor_key = $line_key;
break;
}
}
if ($anchor_key === null) {
throw new Exception(
pht(
'Unable to find lines.'));
}
if ($view['direction'] > 0) {
$slice_offset = $anchor_key;
} else {
$slice_offset = max(0, $anchor_key - ($view['lines'] - 1));
}
$slice_length = $view['lines'];
$views[$view_key] += array(
'sliceKey' => $data_key,
'sliceOffset' => $slice_offset,
'sliceLength' => $slice_length,
);
}
foreach ($views as $view_key => $view) {
$slice_key = $view['sliceKey'];
$lines = array_slice(
$reads[$slice_key]['lines'],
$view['sliceOffset'],
$view['sliceLength']);
$data_offset = null;
$data_length = null;
foreach ($lines as $line) {
if ($data_offset === null) {
$data_offset = $line['offset'];
}
$data_length += $line['length'];
}
// If the view cursor starts in the middle of a line, we're going to
// strip part of the line.
$direction = $view['direction'];
if ($direction > 0) {
$view_offset = $view['offset'];
$view_length = $data_length;
if ($data_offset < $view_offset) {
$trim = ($view_offset - $data_offset);
$view_length -= $trim;
}
$limit = $view['limit'];
if ($limit !== null) {
if ($limit < ($view_offset + $view_length)) {
$view_length = ($limit - $view_offset);
}
}
} else {
$view_offset = $data_offset;
$view_length = $data_length;
if ($data_offset + $data_length > $view['offset']) {
$view_length -= (($data_offset + $data_length) - $view['offset']);
}
$limit = $view['limit'];
if ($limit !== null) {
if ($limit > $view_offset) {
$view_length -= ($limit - $view_offset);
$view_offset = $limit;
}
}
}
$views[$view_key] += array(
'viewOffset' => $view_offset,
'viewLength' => $view_length,
);
}
$views = $this->mergeOverlappingViews($views);
foreach ($views as $view_key => $view) {
$slice_key = $view['sliceKey'];
$lines = array_slice(
$reads[$slice_key]['lines'],
$view['sliceOffset'],
$view['sliceLength']);
$view_offset = $view['viewOffset'];
foreach ($lines as $line_key => $line) {
$line_offset = $line['offset'];
if ($line_offset >= $view_offset) {
break;
}
$trim = ($view_offset - $line_offset);
if ($trim && ($trim >= strlen($line['data']))) {
unset($lines[$line_key]);
continue;
}
$line_data = substr($line['data'], $trim);
$lines[$line_key]['data'] = $line_data;
$lines[$line_key]['length'] = strlen($line_data);
$lines[$line_key]['offset'] += $trim;
break;
}
$view_end = $view['viewOffset'] + $view['viewLength'];
foreach ($lines as $line_key => $line) {
$line_end = $line['offset'] + $line['length'];
if ($line_end <= $view_end) {
continue;
}
$trim = ($line_end - $view_end);
if ($trim && ($trim >= strlen($line['data']))) {
unset($lines[$line_key]);
continue;
}
$line_data = substr($line['data'], -$trim);
$lines[$line_key]['data'] = $line_data;
$lines[$line_key]['length'] = strlen($line_data);
}
$views[$view_key]['viewData'] = $lines;
}
$spacer = null;
$render = array();
$head_view = head($views);
if ($head_view['viewOffset'] > $head_offset) {
$render[] = array(
'spacer' => true,
'head' => $head_offset,
'tail' => $head_view['viewOffset'],
);
}
foreach ($views as $view) {
if ($spacer) {
$spacer['tail'] = $view['viewOffset'];
$render[] = $spacer;
}
$render[] = $view;
$spacer = array(
'spacer' => true,
'head' => ($view['viewOffset'] + $view['viewLength']),
);
}
$tail_view = last($views);
if ($tail_view['viewOffset'] + $tail_view['viewLength'] < $tail_offset) {
$render[] = array(
'spacer' => true,
'head' => $tail_view['viewOffset'] + $tail_view['viewLength'],
'tail' => $tail_offset,
);
}
$uri = $log->getURI();
$rows = array();
foreach ($render as $range) {
if (isset($range['spacer'])) {
$rows[] = $this->renderExpandRow($range);
continue;
}
$lines = $range['viewData'];
foreach ($lines as $line) {
$display_line = ($line['line'] + 1);
$display_text = ($line['data']);
$row_attr = array();
if ($highlight_range) {
if (($display_line >= $highlight_range[0]) &&
($display_line <= $highlight_range[1])) {
$row_attr = array(
'class' => 'phabricator-source-highlight',
);
}
}
$display_line = phutil_tag(
'a',
array(
'href' => $uri.'$'.$display_line,
'data-n' => $display_line,
),
'');
$line_cell = phutil_tag('th', array(), $display_line);
$text_cell = phutil_tag('td', array(), $display_text);
$rows[] = phutil_tag(
'tr',
$row_attr,
array(
$line_cell,
$text_cell,
));
}
}
if ($log->getLive()) {
$last_view = last($views);
$last_line = last($last_view['viewData']);
if ($last_line) {
$last_offset = $last_line['offset'];
} else {
$last_offset = 0;
}
$last_tail = $last_view['viewOffset'] + $last_view['viewLength'];
$show_live = ($last_tail === $log_size);
if ($show_live) {
$rows[] = $this->renderLiveRow($last_offset);
}
}
$table = javelin_tag(
'table',
array(
'class' => 'harbormaster-log-table PhabricatorMonospaced',
'sigil' => 'phabricator-source',
'meta' => array(
'uri' => $log->getURI(),
),
),
$rows);
// When this is a normal AJAX request, return the rendered log fragment
// in an AJAX payload.
if ($request->isAjax()) {
return id(new AphrontAjaxResponse())
->setContent(
array(
'markup' => hsprintf('%s', $table),
));
}
// If the page is being accessed as a standalone page, present a
// readable version of the fragment for debugging.
require_celerity_resource('harbormaster-css');
$header = pht('Standalone Log Fragment');
$render_view = id(new PHUIObjectBoxView())
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setHeaderText($header)
->appendChild($table);
$page_view = id(new PHUITwoColumnView())
->setFooter($render_view);
$crumbs = $this->buildApplicationCrumbs()
->addTextCrumb(pht('Build Log %d', $log->getID()), $log->getURI())
->addTextCrumb(pht('Fragment'))
->setBorder(true);
return $this->newPage()
->setTitle(
array(
pht('Build Log %d', $log->getID()),
pht('Standalone Fragment'),
))
->setCrumbs($crumbs)
->appendChild($page_view);
}
private function getTotalByteLength(HarbormasterBuildLog $log) {
$total_bytes = $log->getByteLength();
if ($total_bytes) {
return (int)$total_bytes;
}
// TODO: Remove this after enough time has passed for installs to run
// log rebuilds or decide they don't care about older logs.
// Older logs don't have this data denormalized onto the log record unless
// an administrator has run `bin/harbormaster rebuild-log --all` or
// similar. Try to figure it out by summing up the size of each chunk.
// Note that the log may also be legitimately empty and have actual size
// zero.
$chunk = new HarbormasterBuildLogChunk();
$conn = $chunk->establishConnection('r');
$row = queryfx_one(
$conn,
'SELECT SUM(size) total FROM %T WHERE logID = %d',
$chunk->getTableName(),
$log->getID());
return (int)$row['total'];
}
private function getLines($data) {
$parts = preg_split("/(\r\n|\r|\n)/", $data, 0, PREG_SPLIT_DELIM_CAPTURE);
if (last($parts) === '') {
array_pop($parts);
}
$lines = array();
for ($ii = 0; $ii < count($parts); $ii += 2) {
$line = $parts[$ii];
if (isset($parts[$ii + 1])) {
$line .= $parts[$ii + 1];
}
$lines[] = $line;
}
return $lines;
}
private function mergeOverlappingReads(array $reads) {
// Find planned reads which will overlap and merge them into a single
// larger read.
$uk = array_keys($reads);
$vk = array_keys($reads);
foreach ($uk as $ukey) {
foreach ($vk as $vkey) {
// Don't merge a range into itself, even though they do technically
// overlap.
if ($ukey === $vkey) {
continue;
}
$uread = idx($reads, $ukey);
if ($uread === null) {
continue;
}
$vread = idx($reads, $vkey);
if ($vread === null) {
continue;
}
$us = $uread['fetchOffset'];
$ue = $us + $uread['fetchLength'];
$vs = $vread['fetchOffset'];
$ve = $vs + $vread['fetchLength'];
if (($vs > $ue) || ($ve < $us)) {
continue;
}
$min = min($us, $vs);
$max = max($ue, $ve);
$reads[$ukey]['fetchOffset'] = $min;
$reads[$ukey]['fetchLength'] = ($max - $min);
$reads[$ukey]['fetchLine'] = min(
$uread['fetchLine'],
$vread['fetchLine']);
unset($reads[$vkey]);
}
}
return $reads;
}
private function mergeOverlappingViews(array $views) {
$uk = array_keys($views);
$vk = array_keys($views);
$body_lines = 8;
$body_bytes = ($body_lines * 140);
foreach ($uk as $ukey) {
foreach ($vk as $vkey) {
if ($ukey === $vkey) {
continue;
}
$uview = idx($views, $ukey);
if ($uview === null) {
continue;
}
$vview = idx($views, $vkey);
if ($vview === null) {
continue;
}
// If these views don't use the same line data, don't try to
// merge them.
if ($uview['sliceKey'] != $vview['sliceKey']) {
continue;
}
// If these views are overlapping or separated by only a few bytes,
// merge them into a single view.
$us = $uview['viewOffset'];
$ue = $us + $uview['viewLength'];
$vs = $vview['viewOffset'];
$ve = $vs + $vview['viewLength'];
// Don't merge if one of the slices starts at a byte offset
// significantly after the other ends.
if (($vs > $ue + $body_bytes) || ($us > $ve + $body_bytes)) {
continue;
}
$uss = $uview['sliceOffset'];
$use = $uss + $uview['sliceLength'];
$vss = $vview['sliceOffset'];
$vse = $vss + $vview['sliceLength'];
// Don't merge if one of the slices starts at a line offset
// significantly after the other ends.
if ($uss > ($vse + $body_lines) || $vss > ($use + $body_lines)) {
continue;
}
// These views are overlapping or nearly overlapping, so we merge
// them. We merge views even if they aren't exactly adjacent since
// it's silly to render an "expand more" which only expands a couple
// of lines.
$offset = min($us, $vs);
$length = max($ue, $ve) - $offset;
$slice_offset = min($uss, $vss);
$slice_length = max($use, $vse) - $slice_offset;
$views[$ukey] = array(
'viewOffset' => $offset,
'viewLength' => $length,
'sliceOffset' => $slice_offset,
'sliceLength' => $slice_length,
) + $views[$ukey];
unset($views[$vkey]);
}
}
return $views;
}
private function renderExpandRow($range) {
$icon_up = id(new PHUIIconView())
->setIcon('fa-chevron-up');
$icon_down = id(new PHUIIconView())
->setIcon('fa-chevron-down');
$up_text = array(
pht('Show More Above'),
' ',
$icon_up,
);
$expand_up = javelin_tag(
'a',
array(
'sigil' => 'harbormaster-log-expand',
'meta' => array(
'headOffset' => $range['head'],
'tailOffset' => $range['tail'],
'head' => 128,
'tail' => 0,
),
),
$up_text);
$mid_text = pht(
'Show More (%s Bytes)',
new PhutilNumber($range['tail'] - $range['head']));
$expand_mid = javelin_tag(
'a',
array(
'sigil' => 'harbormaster-log-expand',
'meta' => array(
'headOffset' => $range['head'],
'tailOffset' => $range['tail'],
'head' => 128,
'tail' => 128,
),
),
$mid_text);
$down_text = array(
$icon_down,
' ',
pht('Show More Below'),
);
$expand_down = javelin_tag(
'a',
array(
'sigil' => 'harbormaster-log-expand',
'meta' => array(
'headOffset' => $range['head'],
'tailOffset' => $range['tail'],
'head' => 0,
'tail' => 128,
),
),
$down_text);
$expand_cells = array(
phutil_tag(
'td',
array(
'class' => 'harbormaster-log-expand-up',
),
$expand_up),
phutil_tag(
'td',
array(
'class' => 'harbormaster-log-expand-mid',
),
$expand_mid),
phutil_tag(
'td',
array(
'class' => 'harbormaster-log-expand-down',
),
$expand_down),
);
return $this->renderActionTable($expand_cells);
}
private function renderLiveRow($log_size) {
$icon_down = id(new PHUIIconView())
->setIcon('fa-angle-double-down');
$icon_pause = id(new PHUIIconView())
->setIcon('fa-pause');
$follow = javelin_tag(
'a',
array(
'sigil' => 'harbormaster-log-expand harbormaster-log-live',
'class' => 'harbormaster-log-follow-start',
'meta' => array(
'headOffset' => $log_size,
'head' => 0,
'tail' => 1024,
'live' => true,
),
),
array(
$icon_down,
' ',
pht('Follow Log'),
));
$stop_following = javelin_tag(
'a',
array(
'sigil' => 'harbormaster-log-expand',
'class' => 'harbormaster-log-follow-stop',
'meta' => array(
'stop' => true,
),
),
array(
$icon_pause,
' ',
pht('Stop Following Log'),
));
$expand_cells = array(
phutil_tag(
'td',
array(
'class' => 'harbormaster-log-follow',
),
array(
$follow,
$stop_following,
)),
);
return $this->renderActionTable($expand_cells);
}
private function renderActionTable(array $action_cells) {
$action_row = phutil_tag('tr', array(), $action_cells);
$action_table = phutil_tag(
'table',
array(
'class' => 'harbormaster-log-expand-table',
),
$action_row);
$format_cells = array(
phutil_tag('th', array()),
phutil_tag(
'td',
array(
'class' => 'harbormaster-log-expand-cell',
),
$action_table),
);
return phutil_tag('tr', array(), $format_cells);
}
private function getHighlightViews(
HarbormasterBuildLog $log,
array $range,
$log_size) {
// If we're highlighting a line range in the file, we first need to figure
// out the offsets for the lines we care about.
list($range_min, $range_max) = $range;
// Read the markers to find a range we can load which includes both lines.
$read_range = $log->getLineSpanningRange($range_min, $range_max);
list($min_pos, $max_pos, $min_line) = $read_range;
$length = ($max_pos - $min_pos);
// Reject to do the read if it requires us to examine a huge amount of
// data. For example, the user may request lines "$1-1000" of a file where
// each line has 100MB of text.
$limit = (1024 * 1024 * 16);
if ($length > $limit) {
return array();
}
$data = $log->loadData($min_pos, $length);
$offset = $min_pos;
$min_offset = null;
$max_offset = null;
$lines = $this->getLines($data);
$number = ($min_line + 1);
foreach ($lines as $line) {
if ($min_offset === null) {
if ($number === $range_min) {
$min_offset = $offset;
}
}
$offset += strlen($line);
if ($max_offset === null) {
if ($number === $range_max) {
$max_offset = $offset;
break;
}
}
$number += 1;
}
$context_lines = 8;
// Build views around the beginning and ends of the respective lines. We
// expect these views to overlap significantly in normal circumstances
// and be merged later.
$views = array();
if ($min_offset !== null) {
$views[] = array(
'offset' => $min_offset,
'lines' => $context_lines + ($range_max - $range_min) - 1,
'direction' => 1,
'limit' => null,
);
if ($min_offset > 0) {
$views[] = array(
'offset' => $min_offset,
'lines' => $context_lines,
'direction' => -1,
'limit' => null,
);
}
}
if ($max_offset !== null) {
$views[] = array(
'offset' => $max_offset,
'lines' => $context_lines + ($range_max - $range_min),
'direction' => -1,
'limit' => null,
);
if ($max_offset < $log_size) {
$views[] = array(
'offset' => $max_offset,
'lines' => $context_lines,
'direction' => 1,
'limit' => null,
);
}
}
return $views;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/controller/HarbormasterCircleCIHookController.php | src/applications/harbormaster/controller/HarbormasterCircleCIHookController.php | <?php
final class HarbormasterCircleCIHookController
extends HarbormasterController {
public function shouldRequireLogin() {
return false;
}
/**
* @phutil-external-symbol class PhabricatorStartup
*/
public function handleRequest(AphrontRequest $request) {
$raw_body = PhabricatorStartup::getRawInput();
$body = phutil_json_decode($raw_body);
$payload = $body['payload'];
$parameters = idx($payload, 'build_parameters');
if (!$parameters) {
$parameters = array();
}
$target_phid = idx($parameters, 'HARBORMASTER_BUILD_TARGET_PHID');
// NOTE: We'll get callbacks here for builds we triggered, but also for
// arbitrary builds the system executes for other reasons. So it's normal
// to get some notifications with no Build Target PHID. We just ignore
// these under the assumption that they're routine builds caused by events
// like branch updates.
if ($target_phid) {
$viewer = PhabricatorUser::getOmnipotentUser();
$target = id(new HarbormasterBuildTargetQuery())
->setViewer($viewer)
->withPHIDs(array($target_phid))
->needBuildSteps(true)
->executeOne();
if ($target) {
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$this->updateTarget($target, $payload);
}
}
$response = new AphrontWebpageResponse();
$response->setContent(pht("Request OK\n"));
return $response;
}
private function updateTarget(
HarbormasterBuildTarget $target,
array $payload) {
$step = $target->getBuildStep();
$impl = $step->getStepImplementation();
if (!($impl instanceof HarbormasterCircleCIBuildStepImplementation)) {
throw new Exception(
pht(
'Build target ("%s") has the wrong type of build step. Only '.
'CircleCI build steps may be updated via the CircleCI webhook.',
$target->getPHID()));
}
switch (idx($payload, 'status')) {
case 'success':
case 'fixed':
$message_type = HarbormasterMessageType::MESSAGE_PASS;
break;
default:
$message_type = HarbormasterMessageType::MESSAGE_FAIL;
break;
}
$viewer = PhabricatorUser::getOmnipotentUser();
$api_method = 'harbormaster.sendmessage';
$api_params = array(
'buildTargetPHID' => $target->getPHID(),
'type' => $message_type,
);
id(new ConduitCall($api_method, $api_params))
->setUser($viewer)
->execute();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/engineextension/HarbormasterQueryBuildsSearchEngineAttachment.php | src/applications/harbormaster/engineextension/HarbormasterQueryBuildsSearchEngineAttachment.php | <?php
final class HarbormasterQueryBuildsSearchEngineAttachment
extends PhabricatorSearchEngineAttachment {
public function getAttachmentName() {
return pht('Harbormaster Query Builds');
}
public function getAttachmentDescription() {
return pht(
'This attachment exists solely to provide compatibility with the '.
'message format returned by an outdated API method. It will be '.
'taken away at some point and you should not rely on these fields '.
'being available.');
}
public function getAttachmentForObject($object, $data, $spec) {
$status_name = HarbormasterBuildStatus::getBuildStatusName(
$object->getBuildStatus());
return array(
'uri' => PhabricatorEnv::getProductionURI($object->getURI()),
'name' => $object->getName(),
'buildStatusName' => $status_name,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/HarbormasterBuildableTransaction.php | src/applications/harbormaster/storage/HarbormasterBuildableTransaction.php | <?php
final class HarbormasterBuildableTransaction
extends PhabricatorModularTransaction {
public function getApplicationName() {
return 'harbormaster';
}
public function getApplicationTransactionType() {
return HarbormasterBuildablePHIDType::TYPECONST;
}
public function getBaseTransactionClass() {
return 'HarbormasterBuildableTransactionType';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/HarbormasterBuildMessage.php | src/applications/harbormaster/storage/HarbormasterBuildMessage.php | <?php
/**
* A message sent to an executing build target by an external system. We
* capture these messages and process them asynchronously to avoid race
* conditions where we receive a message before a build plan is ready to
* accept it.
*/
final class HarbormasterBuildMessage
extends HarbormasterDAO
implements
PhabricatorPolicyInterface,
PhabricatorDestructibleInterface {
protected $authorPHID;
protected $receiverPHID;
protected $type;
protected $isConsumed;
private $receiver = self::ATTACHABLE;
public static function initializeNewMessage(PhabricatorUser $actor) {
$actor_phid = $actor->getPHID();
if (!$actor_phid) {
$actor_phid = id(new PhabricatorHarbormasterApplication())->getPHID();
}
return id(new HarbormasterBuildMessage())
->setAuthorPHID($actor_phid)
->setIsConsumed(0);
}
protected function getConfiguration() {
return array(
self::CONFIG_COLUMN_SCHEMA => array(
'type' => 'text16',
'isConsumed' => 'bool',
),
self::CONFIG_KEY_SCHEMA => array(
'key_receiver' => array(
'columns' => array('receiverPHID'),
),
),
) + parent::getConfiguration();
}
public function getReceiver() {
return $this->assertAttached($this->receiver);
}
public function attachReceiver($receiver) {
$this->receiver = $receiver;
return $this;
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
return $this->getReceiver()->getPolicy($capability);
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return $this->getReceiver()->hasAutomaticCapability(
$capability,
$viewer);
}
public function describeAutomaticCapability($capability) {
return pht('Build messages have the same policies as their receivers.');
}
/* -( PhabricatorDestructibleInterface )----------------------------------- */
public function destroyObjectPermanently(
PhabricatorDestructionEngine $engine) {
$this->delete();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/HarbormasterScratchTable.php | src/applications/harbormaster/storage/HarbormasterScratchTable.php | <?php
/**
* This is just a test table that unit tests can use if they need to test
* generic database operations. It won't change and break tests and stuff, and
* mistakes in test construction or isolation won't impact the application in
* any way.
*/
final class HarbormasterScratchTable extends HarbormasterDAO {
protected $data;
protected $bigData;
protected $nonmutableData;
protected function getConfiguration() {
return array(
self::CONFIG_COLUMN_SCHEMA => array(
'data' => 'text64',
'bigData' => 'text?',
'nonmutableData' => 'text64?',
),
self::CONFIG_KEY_SCHEMA => array(
'data' => array(
'columns' => array('data'),
),
),
self::CONFIG_NO_MUTATE => array(
'nonmutableData',
),
) + 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/harbormaster/storage/HarbormasterBuildable.php | src/applications/harbormaster/storage/HarbormasterBuildable.php | <?php
final class HarbormasterBuildable
extends HarbormasterDAO
implements
PhabricatorApplicationTransactionInterface,
PhabricatorPolicyInterface,
HarbormasterBuildableInterface,
PhabricatorConduitResultInterface,
PhabricatorDestructibleInterface {
protected $buildablePHID;
protected $containerPHID;
protected $buildableStatus;
protected $isManualBuildable;
private $buildableObject = self::ATTACHABLE;
private $containerObject = self::ATTACHABLE;
private $builds = self::ATTACHABLE;
public static function initializeNewBuildable(PhabricatorUser $actor) {
return id(new HarbormasterBuildable())
->setIsManualBuildable(0)
->setBuildableStatus(HarbormasterBuildableStatus::STATUS_PREPARING);
}
public function getMonogram() {
return 'B'.$this->getID();
}
public function getURI() {
return '/'.$this->getMonogram();
}
/**
* Returns an existing buildable for the object's PHID or creates a
* new buildable implicitly if needed.
*/
public static function createOrLoadExisting(
PhabricatorUser $actor,
$buildable_object_phid,
$container_object_phid) {
$buildable = id(new HarbormasterBuildableQuery())
->setViewer($actor)
->withBuildablePHIDs(array($buildable_object_phid))
->withManualBuildables(false)
->setLimit(1)
->executeOne();
if ($buildable) {
return $buildable;
}
$buildable = self::initializeNewBuildable($actor)
->setBuildablePHID($buildable_object_phid)
->setContainerPHID($container_object_phid);
$buildable->save();
return $buildable;
}
/**
* Start builds for a given buildable.
*
* @param phid PHID of the object to build.
* @param phid Container PHID for the buildable.
* @param list<HarbormasterBuildRequest> List of builds to perform.
* @return void
*/
public static function applyBuildPlans(
$phid,
$container_phid,
array $requests) {
assert_instances_of($requests, 'HarbormasterBuildRequest');
if (!$requests) {
return;
}
// Skip all of this logic if the Harbormaster application
// isn't currently installed.
$harbormaster_app = 'PhabricatorHarbormasterApplication';
if (!PhabricatorApplication::isClassInstalled($harbormaster_app)) {
return;
}
$viewer = PhabricatorUser::getOmnipotentUser();
$buildable = self::createOrLoadExisting(
$viewer,
$phid,
$container_phid);
$plan_phids = mpull($requests, 'getBuildPlanPHID');
$plans = id(new HarbormasterBuildPlanQuery())
->setViewer($viewer)
->withPHIDs($plan_phids)
->execute();
$plans = mpull($plans, null, 'getPHID');
foreach ($requests as $request) {
$plan_phid = $request->getBuildPlanPHID();
$plan = idx($plans, $plan_phid);
if (!$plan) {
throw new Exception(
pht(
'Failed to load build plan ("%s").',
$plan_phid));
}
if ($plan->isDisabled()) {
// TODO: This should be communicated more clearly -- maybe we should
// create the build but set the status to "disabled" or "derelict".
continue;
}
$parameters = $request->getBuildParameters();
$buildable->applyPlan($plan, $parameters, $request->getInitiatorPHID());
}
}
public function applyPlan(
HarbormasterBuildPlan $plan,
array $parameters,
$initiator_phid) {
$viewer = PhabricatorUser::getOmnipotentUser();
$build = HarbormasterBuild::initializeNewBuild($viewer)
->setBuildablePHID($this->getPHID())
->setBuildPlanPHID($plan->getPHID())
->setBuildParameters($parameters)
->setBuildStatus(HarbormasterBuildStatus::STATUS_PENDING);
if ($initiator_phid) {
$build->setInitiatorPHID($initiator_phid);
}
$auto_key = $plan->getPlanAutoKey();
if ($auto_key) {
$build->setPlanAutoKey($auto_key);
}
$build->save();
$steps = id(new HarbormasterBuildStepQuery())
->setViewer($viewer)
->withBuildPlanPHIDs(array($plan->getPHID()))
->execute();
foreach ($steps as $step) {
$step->willStartBuild($viewer, $this, $build, $plan);
}
PhabricatorWorker::scheduleTask(
'HarbormasterBuildWorker',
array(
'buildID' => $build->getID(),
),
array(
'objectPHID' => $build->getPHID(),
));
return $build;
}
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_COLUMN_SCHEMA => array(
'containerPHID' => 'phid?',
'buildableStatus' => 'text32',
'isManualBuildable' => 'bool',
),
self::CONFIG_KEY_SCHEMA => array(
'key_buildable' => array(
'columns' => array('buildablePHID'),
),
'key_container' => array(
'columns' => array('containerPHID'),
),
'key_manual' => array(
'columns' => array('isManualBuildable'),
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
HarbormasterBuildablePHIDType::TYPECONST);
}
public function attachBuildableObject($buildable_object) {
$this->buildableObject = $buildable_object;
return $this;
}
public function getBuildableObject() {
return $this->assertAttached($this->buildableObject);
}
public function attachContainerObject($container_object) {
$this->containerObject = $container_object;
return $this;
}
public function getContainerObject() {
return $this->assertAttached($this->containerObject);
}
public function attachBuilds(array $builds) {
assert_instances_of($builds, 'HarbormasterBuild');
$this->builds = $builds;
return $this;
}
public function getBuilds() {
return $this->assertAttached($this->builds);
}
/* -( Status )------------------------------------------------------------- */
public function getBuildableStatusObject() {
$status = $this->getBuildableStatus();
return HarbormasterBuildableStatus::newBuildableStatusObject($status);
}
public function getStatusIcon() {
return $this->getBuildableStatusObject()->getIcon();
}
public function getStatusDisplayName() {
return $this->getBuildableStatusObject()->getDisplayName();
}
public function getStatusColor() {
return $this->getBuildableStatusObject()->getColor();
}
public function isPreparing() {
return $this->getBuildableStatusObject()->isPreparing();
}
public function isBuilding() {
return $this->getBuildableStatusObject()->isBuilding();
}
/* -( Messages )----------------------------------------------------------- */
public function sendMessage(
PhabricatorUser $viewer,
$message_type,
$queue_update) {
$message = HarbormasterBuildMessage::initializeNewMessage($viewer)
->setReceiverPHID($this->getPHID())
->setType($message_type)
->save();
if ($queue_update) {
PhabricatorWorker::scheduleTask(
'HarbormasterBuildWorker',
array(
'buildablePHID' => $this->getPHID(),
),
array(
'objectPHID' => $this->getPHID(),
));
}
return $message;
}
/* -( PhabricatorApplicationTransactionInterface )------------------------- */
public function getApplicationTransactionEditor() {
return new HarbormasterBuildableTransactionEditor();
}
public function getApplicationTransactionTemplate() {
return new HarbormasterBuildableTransaction();
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
);
}
public function getPolicy($capability) {
return $this->getBuildableObject()->getPolicy($capability);
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return $this->getBuildableObject()->hasAutomaticCapability(
$capability,
$viewer);
}
public function describeAutomaticCapability($capability) {
return pht('A buildable inherits policies from the underlying object.');
}
/* -( HarbormasterBuildableInterface )------------------------------------- */
public function getHarbormasterBuildableDisplayPHID() {
return $this->getBuildableObject()->getHarbormasterBuildableDisplayPHID();
}
public function getHarbormasterBuildablePHID() {
// NOTE: This is essentially just for convenience, as it allows you create
// a copy of a buildable by specifying `B123` without bothering to go
// look up the underlying object.
return $this->getBuildablePHID();
}
public function getHarbormasterContainerPHID() {
return $this->getContainerPHID();
}
public function getBuildVariables() {
return array();
}
public function getAvailableBuildVariables() {
return array();
}
public function newBuildableEngine() {
return $this->getBuildableObject()->newBuildableEngine();
}
/* -( PhabricatorConduitResultInterface )---------------------------------- */
public function getFieldSpecificationsForConduit() {
return array(
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('objectPHID')
->setType('phid')
->setDescription(pht('PHID of the object that is built.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('containerPHID')
->setType('phid')
->setDescription(pht('PHID of the object containing this buildable.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('buildableStatus')
->setType('map<string, wild>')
->setDescription(pht('The current status of this buildable.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('isManual')
->setType('bool')
->setDescription(pht('True if this is a manual buildable.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('uri')
->setType('uri')
->setDescription(pht('View URI for the buildable.')),
);
}
public function getFieldValuesForConduit() {
return array(
'objectPHID' => $this->getBuildablePHID(),
'containerPHID' => $this->getContainerPHID(),
'buildableStatus' => array(
'value' => $this->getBuildableStatus(),
),
'isManual' => (bool)$this->getIsManualBuildable(),
'uri' => PhabricatorEnv::getURI($this->getURI()),
);
}
public function getConduitSearchAttachments() {
return array();
}
/* -( PhabricatorDestructibleInterface )----------------------------------- */
public function destroyObjectPermanently(
PhabricatorDestructionEngine $engine) {
$viewer = $engine->getViewer();
$this->openTransaction();
$builds = id(new HarbormasterBuildQuery())
->setViewer($viewer)
->withBuildablePHIDs(array($this->getPHID()))
->execute();
foreach ($builds as $build) {
$engine->destroyObject($build);
}
$messages = id(new HarbormasterBuildMessageQuery())
->setViewer($viewer)
->withReceiverPHIDs(array($this->getPHID()))
->execute();
foreach ($messages as $message) {
$engine->destroyObject($message);
}
$this->delete();
$this->saveTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/HarbormasterDAO.php | src/applications/harbormaster/storage/HarbormasterDAO.php | <?php
abstract class HarbormasterDAO extends PhabricatorLiskDAO {
public function getApplicationName() {
return 'harbormaster';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/HarbormasterBuildTransaction.php | src/applications/harbormaster/storage/HarbormasterBuildTransaction.php | <?php
final class HarbormasterBuildTransaction
extends PhabricatorModularTransaction {
public function getApplicationName() {
return 'harbormaster';
}
public function getApplicationTransactionType() {
return HarbormasterBuildPHIDType::TYPECONST;
}
public function getBaseTransactionClass() {
return 'HarbormasterBuildTransactionType';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/HarbormasterSchemaSpec.php | src/applications/harbormaster/storage/HarbormasterSchemaSpec.php | <?php
final class HarbormasterSchemaSpec extends PhabricatorConfigSchemaSpec {
public function buildSchemata() {
$this->buildEdgeSchemata(new HarbormasterBuildable());
// NOTE: This table is not used by any Harbormaster objects, but is used
// by unit tests.
$this->buildRawSchema(
id(new HarbormasterObject())->getApplicationName(),
PhabricatorLiskDAO::COUNTER_TABLE_NAME,
array(
'counterName' => 'text32',
'counterValue' => 'id64',
),
array(
'PRIMARY' => array(
'columns' => array('counterName'),
'unique' => true,
),
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/HarbormasterString.php | src/applications/harbormaster/storage/HarbormasterString.php | <?php
final class HarbormasterString
extends HarbormasterDAO {
protected $stringIndex;
protected $stringValue;
protected function getConfiguration() {
return array(
self::CONFIG_TIMESTAMPS => false,
self::CONFIG_COLUMN_SCHEMA => array(
'stringIndex' => 'bytes12',
'stringValue' => 'text',
),
self::CONFIG_KEY_SCHEMA => array(
'key_string' => array(
'columns' => array('stringIndex'),
'unique' => true,
),
),
) + parent::getConfiguration();
}
public static function newIndex($string) {
$index = PhabricatorHash::digestForIndex($string);
$table = new self();
$conn = $table->establishConnection('w');
queryfx(
$conn,
'INSERT IGNORE INTO %R (stringIndex, stringValue) VALUES (%s, %s)',
$table,
$index,
$string);
return $index;
}
public static function newIndexMap(array $indexes) {
$table = new self();
$conn = $table->establishConnection('r');
$rows = queryfx_all(
$conn,
'SELECT stringIndex, stringValue FROM %R WHERE stringIndex IN (%Ls)',
$table,
$indexes);
return ipull($rows, 'stringValue', 'stringIndex');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/HarbormasterObject.php | src/applications/harbormaster/storage/HarbormasterObject.php | <?php
final class HarbormasterObject extends HarbormasterDAO {
protected $name;
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_COLUMN_SCHEMA => array(
'name' => 'text255?',
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
PhabricatorPHIDConstants::PHID_TYPE_TOBJ);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/configuration/HarbormasterBuildPlan.php | src/applications/harbormaster/storage/configuration/HarbormasterBuildPlan.php | <?php
/**
* @task autoplan Autoplans
*/
final class HarbormasterBuildPlan extends HarbormasterDAO
implements
PhabricatorApplicationTransactionInterface,
PhabricatorPolicyInterface,
PhabricatorSubscribableInterface,
PhabricatorNgramsInterface,
PhabricatorConduitResultInterface,
PhabricatorProjectInterface,
PhabricatorPolicyCodexInterface {
protected $name;
protected $planStatus;
protected $planAutoKey;
protected $viewPolicy;
protected $editPolicy;
protected $properties = array();
const STATUS_ACTIVE = 'active';
const STATUS_DISABLED = 'disabled';
private $buildSteps = self::ATTACHABLE;
public static function initializeNewBuildPlan(PhabricatorUser $actor) {
$app = id(new PhabricatorApplicationQuery())
->setViewer($actor)
->withClasses(array('PhabricatorHarbormasterApplication'))
->executeOne();
$view_policy = $app->getPolicy(
HarbormasterBuildPlanDefaultViewCapability::CAPABILITY);
$edit_policy = $app->getPolicy(
HarbormasterBuildPlanDefaultEditCapability::CAPABILITY);
return id(new HarbormasterBuildPlan())
->setName('')
->setPlanStatus(self::STATUS_ACTIVE)
->attachBuildSteps(array())
->setViewPolicy($view_policy)
->setEditPolicy($edit_policy);
}
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_SERIALIZATION => array(
'properties' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'name' => 'sort128',
'planStatus' => 'text32',
'planAutoKey' => 'text32?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_status' => array(
'columns' => array('planStatus'),
),
'key_name' => array(
'columns' => array('name'),
),
'key_planautokey' => array(
'columns' => array('planAutoKey'),
'unique' => true,
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
HarbormasterBuildPlanPHIDType::TYPECONST);
}
public function attachBuildSteps(array $steps) {
assert_instances_of($steps, 'HarbormasterBuildStep');
$this->buildSteps = $steps;
return $this;
}
public function getBuildSteps() {
return $this->assertAttached($this->buildSteps);
}
public function isDisabled() {
return ($this->getPlanStatus() == self::STATUS_DISABLED);
}
public function getURI() {
return urisprintf(
'/harbormaster/plan/%s/',
$this->getID());
}
public function getObjectName() {
return pht('Plan %d', $this->getID());
}
public function getPlanProperty($key, $default = null) {
return idx($this->properties, $key, $default);
}
public function setPlanProperty($key, $value) {
$this->properties[$key] = $value;
return $this;
}
/* -( Autoplans )---------------------------------------------------------- */
public function isAutoplan() {
return ($this->getPlanAutoKey() !== null);
}
public function getAutoplan() {
if (!$this->isAutoplan()) {
return null;
}
return HarbormasterBuildAutoplan::getAutoplan($this->getPlanAutoKey());
}
public function canRunManually() {
if ($this->isAutoplan()) {
return false;
}
return true;
}
public function getName() {
$autoplan = $this->getAutoplan();
if ($autoplan) {
return $autoplan->getAutoplanName();
}
return parent::getName();
}
public function hasRunCapability(PhabricatorUser $viewer) {
try {
$this->assertHasRunCapability($viewer);
return true;
} catch (PhabricatorPolicyException $ex) {
return false;
}
}
public function canRunWithoutEditCapability() {
$runnable = HarbormasterBuildPlanBehavior::BEHAVIOR_RUNNABLE;
$if_viewable = HarbormasterBuildPlanBehavior::RUNNABLE_IF_VIEWABLE;
$option = HarbormasterBuildPlanBehavior::getBehavior($runnable)
->getPlanOption($this);
return ($option->getKey() === $if_viewable);
}
public function assertHasRunCapability(PhabricatorUser $viewer) {
if ($this->canRunWithoutEditCapability()) {
$capability = PhabricatorPolicyCapability::CAN_VIEW;
} else {
$capability = PhabricatorPolicyCapability::CAN_EDIT;
}
PhabricatorPolicyFilter::requireCapability(
$viewer,
$this,
$capability);
}
/* -( PhabricatorSubscribableInterface )----------------------------------- */
public function isAutomaticallySubscribed($phid) {
return false;
}
/* -( PhabricatorApplicationTransactionInterface )------------------------- */
public function getApplicationTransactionEditor() {
return new HarbormasterBuildPlanEditor();
}
public function getApplicationTransactionTemplate() {
return new HarbormasterBuildPlanTransaction();
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
);
}
public function getPolicy($capability) {
switch ($capability) {
case PhabricatorPolicyCapability::CAN_VIEW:
if ($this->isAutoplan()) {
return PhabricatorPolicies::getMostOpenPolicy();
}
return $this->getViewPolicy();
case PhabricatorPolicyCapability::CAN_EDIT:
if ($this->isAutoplan()) {
return PhabricatorPolicies::POLICY_NOONE;
}
return $this->getEditPolicy();
}
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return false;
}
public function describeAutomaticCapability($capability) {
$messages = array();
switch ($capability) {
case PhabricatorPolicyCapability::CAN_EDIT:
if ($this->isAutoplan()) {
$messages[] = pht(
'This is an autoplan (a builtin plan provided by an application) '.
'so it can not be edited.');
}
break;
}
return $messages;
}
/* -( PhabricatorNgramsInterface )----------------------------------------- */
public function newNgrams() {
return array(
id(new HarbormasterBuildPlanNameNgrams())
->setValue($this->getName()),
);
}
/* -( PhabricatorConduitResultInterface )---------------------------------- */
public function getFieldSpecificationsForConduit() {
return array(
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('name')
->setType('string')
->setDescription(pht('The name of this build plan.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('status')
->setType('map<string, wild>')
->setDescription(pht('The current status of this build plan.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('behaviors')
->setType('map<string, string>')
->setDescription(pht('Behavior configuration for the build plan.')),
);
}
public function getFieldValuesForConduit() {
$behavior_map = array();
$behaviors = HarbormasterBuildPlanBehavior::newPlanBehaviors();
foreach ($behaviors as $behavior) {
$option = $behavior->getPlanOption($this);
$behavior_map[$behavior->getKey()] = array(
'value' => $option->getKey(),
);
}
return array(
'name' => $this->getName(),
'status' => array(
'value' => $this->getPlanStatus(),
),
'behaviors' => $behavior_map,
);
}
public function getConduitSearchAttachments() {
return array();
}
/* -( PhabricatorPolicyCodexInterface )------------------------------------ */
public function newPolicyCodex() {
return new HarbormasterBuildPlanPolicyCodex();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/configuration/HarbormasterBuildPlanNameNgrams.php | src/applications/harbormaster/storage/configuration/HarbormasterBuildPlanNameNgrams.php | <?php
final class HarbormasterBuildPlanNameNgrams
extends PhabricatorSearchNgrams {
public function getNgramKey() {
return 'buildplanname';
}
public function getColumnName() {
return 'name';
}
public function getApplicationName() {
return 'harbormaster';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/configuration/HarbormasterBuildStepTransaction.php | src/applications/harbormaster/storage/configuration/HarbormasterBuildStepTransaction.php | <?php
final class HarbormasterBuildStepTransaction
extends PhabricatorApplicationTransaction {
const TYPE_CREATE = 'harbormaster:step:create';
const TYPE_NAME = 'harbormaster:step:name';
const TYPE_DEPENDS_ON = 'harbormaster:step:depends';
const TYPE_DESCRIPTION = 'harbormaster:step:description';
public function getApplicationName() {
return 'harbormaster';
}
public function getApplicationTransactionType() {
return HarbormasterBuildStepPHIDType::TYPECONST;
}
public function getTitle() {
$author_phid = $this->getAuthorPHID();
$old = $this->getOldValue();
$new = $this->getNewValue();
switch ($this->getTransactionType()) {
case self::TYPE_CREATE:
return pht(
'%s created this build step.',
$this->renderHandleLink($author_phid));
}
return parent::getTitle();
}
public function getIcon() {
$author_phid = $this->getAuthorPHID();
$old = $this->getOldValue();
$new = $this->getNewValue();
switch ($this->getTransactionType()) {
case self::TYPE_CREATE:
return 'fa-plus';
}
return parent::getIcon();
}
public function getColor() {
$author_phid = $this->getAuthorPHID();
$old = $this->getOldValue();
$new = $this->getNewValue();
switch ($this->getTransactionType()) {
case self::TYPE_CREATE:
return 'green';
}
return parent::getColor();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/configuration/HarbormasterBuildPlanTransaction.php | src/applications/harbormaster/storage/configuration/HarbormasterBuildPlanTransaction.php | <?php
final class HarbormasterBuildPlanTransaction
extends PhabricatorModularTransaction {
public function getApplicationName() {
return 'harbormaster';
}
public function getApplicationTransactionType() {
return HarbormasterBuildPlanPHIDType::TYPECONST;
}
public function getBaseTransactionClass() {
return 'HarbormasterBuildPlanTransactionType';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/configuration/HarbormasterBuildStep.php | src/applications/harbormaster/storage/configuration/HarbormasterBuildStep.php | <?php
final class HarbormasterBuildStep extends HarbormasterDAO
implements
PhabricatorApplicationTransactionInterface,
PhabricatorPolicyInterface,
PhabricatorCustomFieldInterface,
PhabricatorConduitResultInterface {
protected $name;
protected $description;
protected $buildPlanPHID;
protected $className;
protected $details = array();
protected $sequence = 0;
protected $stepAutoKey;
private $buildPlan = self::ATTACHABLE;
private $customFields = self::ATTACHABLE;
private $implementation;
public static function initializeNewStep(PhabricatorUser $actor) {
return id(new HarbormasterBuildStep())
->setName('')
->setDescription('');
}
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_SERIALIZATION => array(
'details' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'className' => 'text255',
'sequence' => 'uint32',
'description' => 'text',
// T6203/NULLABILITY
// This should not be nullable. Current `null` values indicate steps
// which predated editable names. These should be backfilled with
// default names, then the code for handling `null` should be removed.
'name' => 'text255?',
'stepAutoKey' => 'text32?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_plan' => array(
'columns' => array('buildPlanPHID'),
),
'key_stepautokey' => array(
'columns' => array('buildPlanPHID', 'stepAutoKey'),
'unique' => true,
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
HarbormasterBuildStepPHIDType::TYPECONST);
}
public function attachBuildPlan(HarbormasterBuildPlan $plan) {
$this->buildPlan = $plan;
return $this;
}
public function getBuildPlan() {
return $this->assertAttached($this->buildPlan);
}
public function getDetail($key, $default = null) {
return idx($this->details, $key, $default);
}
public function setDetail($key, $value) {
$this->details[$key] = $value;
return $this;
}
public function getName() {
if (strlen($this->name)) {
return $this->name;
}
return $this->getStepImplementation()->getName();
}
public function getStepImplementation() {
if ($this->implementation === null) {
$obj = HarbormasterBuildStepImplementation::requireImplementation(
$this->className);
$obj->loadSettings($this);
$this->implementation = $obj;
}
return $this->implementation;
}
public function isAutostep() {
return ($this->getStepAutoKey() !== null);
}
public function willStartBuild(
PhabricatorUser $viewer,
HarbormasterBuildable $buildable,
HarbormasterBuild $build,
HarbormasterBuildPlan $plan) {
return $this->getStepImplementation()->willStartBuild(
$viewer,
$buildable,
$build,
$plan,
$this);
}
/* -( PhabricatorApplicationTransactionInterface )------------------------- */
public function getApplicationTransactionEditor() {
return new HarbormasterBuildStepEditor();
}
public function getApplicationTransactionTemplate() {
return new HarbormasterBuildStepTransaction();
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
);
}
public function getPolicy($capability) {
return $this->getBuildPlan()->getPolicy($capability);
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return $this->getBuildPlan()->hasAutomaticCapability($capability, $viewer);
}
public function describeAutomaticCapability($capability) {
return pht('A build step has the same policies as its build plan.');
}
/* -( PhabricatorCustomFieldInterface )------------------------------------ */
public function getCustomFieldSpecificationForRole($role) {
return array();
}
public function getCustomFieldBaseClass() {
return 'HarbormasterBuildStepCustomField';
}
public function getCustomFields() {
return $this->assertAttached($this->customFields);
}
public function attachCustomFields(PhabricatorCustomFieldAttachment $fields) {
$this->customFields = $fields;
return $this;
}
/* -( PhabricatorConduitResultInterface )---------------------------------- */
public function getFieldSpecificationsForConduit() {
return array(
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('name')
->setType('string')
->setDescription(pht('The name of the build step.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('description')
->setType('remarkup')
->setDescription(pht('The build step description.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('buildPlanPHID')
->setType('phid')
->setDescription(
pht(
'The PHID of the build plan this build step belongs to.')),
);
}
public function getFieldValuesForConduit() {
// T6203: This can be removed once the field becomes non-nullable.
$name = $this->getName();
$name = phutil_string_cast($name);
return array(
'name' => $name,
'description' => array(
'raw' => $this->getDescription(),
),
'buildPlanPHID' => $this->getBuildPlanPHID(),
);
}
public function getConduitSearchAttachments() {
return array();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/build/HarbormasterBuildArtifact.php | src/applications/harbormaster/storage/build/HarbormasterBuildArtifact.php | <?php
final class HarbormasterBuildArtifact
extends HarbormasterDAO
implements
PhabricatorPolicyInterface,
PhabricatorDestructibleInterface,
PhabricatorConduitResultInterface {
protected $buildTargetPHID;
protected $artifactType;
protected $artifactIndex;
protected $artifactKey;
protected $artifactData = array();
protected $isReleased = 0;
private $buildTarget = self::ATTACHABLE;
private $artifactImplementation;
public static function initializeNewBuildArtifact(
HarbormasterBuildTarget $build_target) {
return id(new HarbormasterBuildArtifact())
->attachBuildTarget($build_target)
->setBuildTargetPHID($build_target->getPHID());
}
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_SERIALIZATION => array(
'artifactData' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'artifactType' => 'text32',
'artifactIndex' => 'bytes12',
'artifactKey' => 'text255',
'isReleased' => 'bool',
),
self::CONFIG_KEY_SCHEMA => array(
'key_artifact' => array(
'columns' => array('artifactType', 'artifactIndex'),
'unique' => true,
),
'key_garbagecollect' => array(
'columns' => array('artifactType', 'dateCreated'),
),
'key_target' => array(
'columns' => array('buildTargetPHID', 'artifactType'),
),
'key_index' => array(
'columns' => array('artifactIndex'),
),
),
) + parent::getConfiguration();
}
public function getPHIDType() {
return HarbormasterBuildArtifactPHIDType::TYPECONST;
}
public function attachBuildTarget(HarbormasterBuildTarget $build_target) {
$this->buildTarget = $build_target;
return $this;
}
public function getBuildTarget() {
return $this->assertAttached($this->buildTarget);
}
public function setArtifactKey($key) {
$target = $this->getBuildTarget();
$this->artifactIndex = self::getArtifactIndex($target, $key);
$this->artifactKey = $key;
return $this;
}
public static function getArtifactIndex(
HarbormasterBuildTarget $target,
$artifact_key) {
$build = $target->getBuild();
$parts = array(
$build->getPHID(),
$target->getBuildGeneration(),
$artifact_key,
);
$parts = implode("\0", $parts);
return PhabricatorHash::digestForIndex($parts);
}
public function releaseArtifact() {
if ($this->getIsReleased()) {
return $this;
}
$impl = $this->getArtifactImplementation();
if ($impl) {
$impl->releaseArtifact(PhabricatorUser::getOmnipotentUser());
}
return $this
->setIsReleased(1)
->save();
}
public function getArtifactImplementation() {
if ($this->artifactImplementation === null) {
$type = $this->getArtifactType();
$impl = HarbormasterArtifact::getArtifactType($type);
if (!$impl) {
return null;
}
$impl = clone $impl;
$impl->setBuildArtifact($this);
$this->artifactImplementation = $impl;
}
return $this->artifactImplementation;
}
public function getProperty($key, $default = null) {
return idx($this->artifactData, $key, $default);
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
return $this->getBuildTarget()->getPolicy($capability);
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return $this->getBuildTarget()->hasAutomaticCapability(
$capability,
$viewer);
}
public function describeAutomaticCapability($capability) {
return pht(
'Users must be able to see a build target to see its artifacts.');
}
/* -( PhabricatorDestructibleInterface )----------------------------------- */
public function destroyObjectPermanently(
PhabricatorDestructionEngine $engine) {
$viewer = $this->getViewer();
$this->openTransaction();
$this->releaseArtifact($viewer);
$this->delete();
$this->saveTransaction();
}
/* -( PhabricatorConduitResultInterface )---------------------------------- */
public function getFieldSpecificationsForConduit() {
return array(
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('buildTargetPHID')
->setType('phid')
->setDescription(pht('The build target this artifact is attached to.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('artifactType')
->setType('string')
->setDescription(pht('The artifact type.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('artifactKey')
->setType('string')
->setDescription(pht('The artifact key.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('isReleased')
->setType('bool')
->setDescription(pht('True if this artifact has been released.')),
);
}
public function getFieldValuesForConduit() {
return array(
'buildTargetPHID' => $this->getBuildTargetPHID(),
'artifactType' => $this->getArtifactType(),
'artifactKey' => $this->getArtifactKey(),
'isReleased' => (bool)$this->getIsReleased(),
);
}
public function getConduitSearchAttachments() {
return array();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/build/HarbormasterBuildUnitMessage.php | src/applications/harbormaster/storage/build/HarbormasterBuildUnitMessage.php | <?php
final class HarbormasterBuildUnitMessage
extends HarbormasterDAO
implements PhabricatorPolicyInterface {
protected $buildTargetPHID;
protected $engine;
protected $namespace;
protected $name;
protected $nameIndex;
protected $result;
protected $duration;
protected $properties = array();
private $buildTarget = self::ATTACHABLE;
const FORMAT_TEXT = 'text';
const FORMAT_REMARKUP = 'remarkup';
public static function initializeNewUnitMessage(
HarbormasterBuildTarget $build_target) {
return id(new HarbormasterBuildUnitMessage())
->setBuildTargetPHID($build_target->getPHID());
}
public static function getParameterSpec() {
return array(
'name' => array(
'type' => 'string',
'description' => pht(
'Short test name, like "ExampleTest".'),
),
'result' => array(
'type' => 'string',
'description' => pht(
'Result of the test.'),
),
'namespace' => array(
'type' => 'optional string',
'description' => pht(
'Optional namespace for this test. This is organizational and '.
'is often a class or module name, like "ExampleTestCase".'),
),
'engine' => array(
'type' => 'optional string',
'description' => pht(
'Test engine running the test, like "JavascriptTestEngine". This '.
'primarily prevents collisions between tests with the same name '.
'in different test suites (for example, a Javascript test and a '.
'Python test).'),
),
'duration' => array(
'type' => 'optional float|int',
'description' => pht(
'Runtime duration of the test, in seconds.'),
),
'path' => array(
'type' => 'optional string',
'description' => pht(
'Path to the file where the test is declared, relative to the '.
'project root.'),
),
'coverage' => array(
'type' => 'optional map<string, wild>',
'description' => pht(
'Coverage information for this test.'),
),
'details' => array(
'type' => 'optional string',
'description' => pht(
'Additional human-readable information about the failure.'),
),
'format' => array(
'type' => 'optional string',
'description' => pht(
'Format for the text provided in "details". Valid values are '.
'"text" (default) or "remarkup". This controls how test details '.
'are rendered when shown to users.'),
),
);
}
public static function newFromDictionary(
HarbormasterBuildTarget $build_target,
array $dict) {
$obj = self::initializeNewUnitMessage($build_target);
$spec = self::getParameterSpec();
$spec = ipull($spec, 'type');
// We're just going to ignore extra keys for now, to make it easier to
// add stuff here later on.
$dict = array_select_keys($dict, array_keys($spec));
PhutilTypeSpec::checkMap($dict, $spec);
$obj->setEngine(idx($dict, 'engine', ''));
$obj->setNamespace(idx($dict, 'namespace', ''));
$obj->setName($dict['name']);
$obj->setResult($dict['result']);
$obj->setDuration((float)idx($dict, 'duration'));
$path = idx($dict, 'path');
if (strlen($path)) {
$obj->setProperty('path', $path);
}
$coverage = idx($dict, 'coverage');
if ($coverage) {
$obj->setProperty('coverage', $coverage);
}
$details = idx($dict, 'details');
if ($details) {
$obj->setProperty('details', $details);
}
$format = idx($dict, 'format');
if ($format) {
$obj->setProperty('format', $format);
}
return $obj;
}
protected function getConfiguration() {
return array(
self::CONFIG_SERIALIZATION => array(
'properties' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'engine' => 'text255',
'namespace' => 'text255',
'name' => 'text255',
'nameIndex' => 'bytes12',
'result' => 'text32',
'duration' => 'double?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_target' => array(
'columns' => array('buildTargetPHID'),
),
),
) + parent::getConfiguration();
}
public function attachBuildTarget(HarbormasterBuildTarget $build_target) {
$this->buildTarget = $build_target;
return $this;
}
public function getBuildTarget() {
return $this->assertAttached($this->buildTarget);
}
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 getUnitMessageDetails() {
return $this->getProperty('details', '');
}
public function getUnitMessageDetailsFormat() {
return $this->getProperty('format', self::FORMAT_TEXT);
}
public function newUnitMessageDetailsView(
PhabricatorUser $viewer,
$summarize = false) {
$format = $this->getUnitMessageDetailsFormat();
$is_text = ($format !== self::FORMAT_REMARKUP);
$is_remarkup = ($format === self::FORMAT_REMARKUP);
$message = null;
$full_details = $this->getUnitMessageDetails();
$byte_length = strlen($full_details);
$text_limit = 1024 * 2;
$remarkup_limit = 1024 * 8;
if (!$byte_length) {
if ($summarize) {
return null;
}
$message = phutil_tag('em', array(), pht('No details provided.'));
} else if ($summarize) {
if ($is_text) {
$details = id(new PhutilUTF8StringTruncator())
->setMaximumBytes($text_limit)
->truncateString($full_details);
$details = phutil_split_lines($details);
$limit = 3;
if (count($details) > $limit) {
$details = array_slice($details, 0, $limit);
}
$details = implode('', $details);
} else {
if ($byte_length > $remarkup_limit) {
$uri = $this->getURI();
if ($uri) {
$link = phutil_tag(
'a',
array(
'href' => $uri,
'target' => '_blank',
),
pht('View Details'));
} else {
$link = null;
}
$message = array();
$message[] = phutil_tag(
'em',
array(),
pht('This test has too much data to display inline.'));
if ($link) {
$message[] = $link;
}
$message = phutil_implode_html(" \xC2\xB7 ", $message);
} else {
$details = $full_details;
}
}
} else {
$details = $full_details;
}
require_celerity_resource('harbormaster-css');
$classes = array();
$classes[] = 'harbormaster-unit-details';
if ($message !== null) {
// If we have a message, show that instead of rendering any test details.
$details = $message;
} else if ($is_remarkup) {
$details = new PHUIRemarkupView($viewer, $details);
} else {
$classes[] = 'harbormaster-unit-details-text';
$classes[] = 'PhabricatorMonospaced';
}
$warning = null;
if (!$summarize) {
$warnings = array();
if ($is_remarkup && ($byte_length > $remarkup_limit)) {
$warnings[] = pht(
'This test result has %s bytes of Remarkup test details. Remarkup '.
'blocks longer than %s bytes are not rendered inline when showing '.
'test summaries.',
new PhutilNumber($byte_length),
new PhutilNumber($remarkup_limit));
}
if ($warnings) {
$warning = id(new PHUIInfoView())
->setSeverity(PHUIInfoView::SEVERITY_WARNING)
->setErrors($warnings);
}
}
$content = phutil_tag(
'div',
array(
'class' => implode(' ', $classes),
),
$details);
return array(
$warning,
$content,
);
}
public function getUnitMessageDisplayName() {
$name = $this->getName();
$namespace = $this->getNamespace();
if (strlen($namespace)) {
$name = $namespace.'::'.$name;
}
$engine = $this->getEngine();
if (strlen($engine)) {
$name = $engine.' > '.$name;
}
if (!strlen($name)) {
return pht('Nameless Test (%d)', $this->getID());
}
return $name;
}
public function getSortKey() {
$status = $this->getResult();
$sort = HarbormasterUnitStatus::getUnitStatusSort($status);
$parts = array(
$sort,
$this->getEngine(),
$this->getNamespace(),
$this->getName(),
$this->getID(),
);
return implode("\0", $parts);
}
public function getURI() {
$id = $this->getID();
if (!$id) {
return null;
}
return urisprintf(
'/harbormaster/unit/view/%d/',
$id);
}
public function save() {
if ($this->nameIndex === null) {
$this->nameIndex = HarbormasterString::newIndex($this->getName());
}
// See T13088. While we're letting installs do online migrations to avoid
// downtime, don't populate the "name" column for new writes. New writes
// use the "HarbormasterString" table instead.
$old_name = $this->name;
$this->name = '';
$caught = null;
try {
$result = parent::save();
} catch (Exception $ex) {
$caught = $ex;
}
$this->name = $old_name;
if ($caught) {
throw $caught;
}
return $result;
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
switch ($capability) {
case PhabricatorPolicyCapability::CAN_VIEW:
return PhabricatorPolicies::getMostOpenPolicy();
}
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return false;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/build/HarbormasterBuildTarget.php | src/applications/harbormaster/storage/build/HarbormasterBuildTarget.php | <?php
final class HarbormasterBuildTarget
extends HarbormasterDAO
implements
PhabricatorPolicyInterface,
PhabricatorDestructibleInterface,
PhabricatorConduitResultInterface {
protected $name;
protected $buildPHID;
protected $buildStepPHID;
protected $className;
protected $details;
protected $variables;
protected $targetStatus;
protected $dateStarted;
protected $dateCompleted;
protected $buildGeneration;
const STATUS_PENDING = 'target/pending';
const STATUS_BUILDING = 'target/building';
const STATUS_WAITING = 'target/waiting';
const STATUS_PASSED = 'target/passed';
const STATUS_FAILED = 'target/failed';
const STATUS_ABORTED = 'target/aborted';
private $build = self::ATTACHABLE;
private $buildStep = self::ATTACHABLE;
private $implementation;
public static function getBuildTargetStatusName($status) {
switch ($status) {
case self::STATUS_PENDING:
return pht('Pending');
case self::STATUS_BUILDING:
return pht('Building');
case self::STATUS_WAITING:
return pht('Waiting for Message');
case self::STATUS_PASSED:
return pht('Passed');
case self::STATUS_FAILED:
return pht('Failed');
case self::STATUS_ABORTED:
return pht('Aborted');
default:
return pht('Unknown');
}
}
public static function getBuildTargetStatusIcon($status) {
switch ($status) {
case self::STATUS_PENDING:
return PHUIStatusItemView::ICON_OPEN;
case self::STATUS_BUILDING:
case self::STATUS_WAITING:
return PHUIStatusItemView::ICON_RIGHT;
case self::STATUS_PASSED:
return PHUIStatusItemView::ICON_ACCEPT;
case self::STATUS_FAILED:
return PHUIStatusItemView::ICON_REJECT;
case self::STATUS_ABORTED:
return PHUIStatusItemView::ICON_MINUS;
default:
return PHUIStatusItemView::ICON_QUESTION;
}
}
public static function getBuildTargetStatusColor($status) {
switch ($status) {
case self::STATUS_PENDING:
case self::STATUS_BUILDING:
case self::STATUS_WAITING:
return 'blue';
case self::STATUS_PASSED:
return 'green';
case self::STATUS_FAILED:
case self::STATUS_ABORTED:
return 'red';
default:
return 'bluegrey';
}
}
public static function initializeNewBuildTarget(
HarbormasterBuild $build,
HarbormasterBuildStep $build_step,
array $variables) {
return id(new HarbormasterBuildTarget())
->setName($build_step->getName())
->setBuildPHID($build->getPHID())
->setBuildStepPHID($build_step->getPHID())
->setClassName($build_step->getClassName())
->setDetails($build_step->getDetails())
->setTargetStatus(self::STATUS_PENDING)
->setVariables($variables)
->setBuildGeneration($build->getBuildGeneration());
}
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_SERIALIZATION => array(
'details' => self::SERIALIZATION_JSON,
'variables' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'className' => 'text255',
'targetStatus' => 'text64',
'dateStarted' => 'epoch?',
'dateCompleted' => 'epoch?',
'buildGeneration' => 'uint32',
// T6203/NULLABILITY
// This should not be nullable.
'name' => 'text255?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_build' => array(
'columns' => array('buildPHID', 'buildStepPHID'),
),
'key_started' => array(
'columns' => array('dateStarted'),
),
'key_completed' => array(
'columns' => array('dateCompleted'),
),
'key_created' => array(
'columns' => array('dateCreated'),
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
HarbormasterBuildTargetPHIDType::TYPECONST);
}
public function attachBuild(HarbormasterBuild $build) {
$this->build = $build;
return $this;
}
public function getBuild() {
return $this->assertAttached($this->build);
}
public function attachBuildStep(HarbormasterBuildStep $step = null) {
$this->buildStep = $step;
return $this;
}
public function getBuildStep() {
return $this->assertAttached($this->buildStep);
}
public function getDetail($key, $default = null) {
return idx($this->details, $key, $default);
}
public function setDetail($key, $value) {
$this->details[$key] = $value;
return $this;
}
public function getVariables() {
return parent::getVariables() + $this->getBuildTargetVariables();
}
public function getVariable($key, $default = null) {
return idx($this->variables, $key, $default);
}
public function setVariable($key, $value) {
$this->variables[$key] = $value;
return $this;
}
public function getImplementation() {
if ($this->implementation === null) {
$obj = HarbormasterBuildStepImplementation::requireImplementation(
$this->className);
$obj->loadSettings($this);
$this->implementation = $obj;
}
return $this->implementation;
}
public function isAutotarget() {
try {
return (bool)$this->getImplementation()->getBuildStepAutotargetPlanKey();
} catch (Exception $e) {
return false;
}
}
public function getName() {
if (strlen($this->name) && !$this->isAutotarget()) {
return $this->name;
}
try {
return $this->getImplementation()->getName();
} catch (Exception $e) {
return $this->getClassName();
}
}
private function getBuildTargetVariables() {
return array(
'target.phid' => $this->getPHID(),
);
}
public function createArtifact(
PhabricatorUser $actor,
$artifact_key,
$artifact_type,
array $artifact_data) {
$impl = HarbormasterArtifact::getArtifactType($artifact_type);
if (!$impl) {
throw new Exception(
pht(
'There is no implementation available for artifacts of type "%s".',
$artifact_type));
}
$impl->validateArtifactData($artifact_data);
$artifact = HarbormasterBuildArtifact::initializeNewBuildArtifact($this)
->setArtifactKey($artifact_key)
->setArtifactType($artifact_type)
->setArtifactData($artifact_data);
$impl = $artifact->getArtifactImplementation();
$impl->willCreateArtifact($actor);
return $artifact->save();
}
public function loadArtifact($artifact_key) {
$indexes = array();
$indexes[] = HarbormasterBuildArtifact::getArtifactIndex(
$this,
$artifact_key);
$artifact = id(new HarbormasterBuildArtifactQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withArtifactIndexes($indexes)
->executeOne();
if ($artifact === null) {
throw new Exception(
pht(
'Artifact "%s" not found!',
$artifact_key));
}
return $artifact;
}
public function newLog($log_source, $log_type) {
$log_source = id(new PhutilUTF8StringTruncator())
->setMaximumBytes(250)
->truncateString($log_source);
$log = HarbormasterBuildLog::initializeNewBuildLog($this)
->setLogSource($log_source)
->setLogType($log_type)
->openBuildLog();
return $log;
}
public function getFieldValue($key) {
$field_list = PhabricatorCustomField::getObjectFields(
$this->getBuildStep(),
PhabricatorCustomField::ROLE_VIEW);
$fields = $field_list->getFields();
$full_key = "std:harbormaster:core:{$key}";
$field = idx($fields, $full_key);
if (!$field) {
throw new Exception(
pht(
'Unknown build step field "%s"!',
$key));
}
$field = clone $field;
$field->setValueFromStorage($this->getDetail($key));
return $field->getBuildTargetFieldValue();
}
/* -( Status )------------------------------------------------------------- */
public function isComplete() {
switch ($this->getTargetStatus()) {
case self::STATUS_PASSED:
case self::STATUS_FAILED:
case self::STATUS_ABORTED:
return true;
}
return false;
}
public function isFailed() {
switch ($this->getTargetStatus()) {
case self::STATUS_FAILED:
case self::STATUS_ABORTED:
return true;
}
return false;
}
public function isWaiting() {
switch ($this->getTargetStatus()) {
case self::STATUS_WAITING:
return true;
}
return false;
}
public function isUnderway() {
switch ($this->getTargetStatus()) {
case self::STATUS_PENDING:
case self::STATUS_BUILDING:
return true;
}
return false;
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
return $this->getBuild()->getPolicy($capability);
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return $this->getBuild()->hasAutomaticCapability(
$capability,
$viewer);
}
public function describeAutomaticCapability($capability) {
return pht('Users must be able to see a build to view its build targets.');
}
/* -( PhabricatorDestructibleInterface )----------------------------------- */
public function destroyObjectPermanently(
PhabricatorDestructionEngine $engine) {
$viewer = $engine->getViewer();
$this->openTransaction();
$lint_message = new HarbormasterBuildLintMessage();
$conn = $lint_message->establishConnection('w');
queryfx(
$conn,
'DELETE FROM %T WHERE buildTargetPHID = %s',
$lint_message->getTableName(),
$this->getPHID());
$unit_message = new HarbormasterBuildUnitMessage();
$conn = $unit_message->establishConnection('w');
queryfx(
$conn,
'DELETE FROM %T WHERE buildTargetPHID = %s',
$unit_message->getTableName(),
$this->getPHID());
$logs = id(new HarbormasterBuildLogQuery())
->setViewer($viewer)
->withBuildTargetPHIDs(array($this->getPHID()))
->execute();
foreach ($logs as $log) {
$engine->destroyObject($log);
}
$artifacts = id(new HarbormasterBuildArtifactQuery())
->setViewer($viewer)
->withBuildTargetPHIDs(array($this->getPHID()))
->execute();
foreach ($artifacts as $artifact) {
$engine->destroyObject($artifact);
}
$messages = id(new HarbormasterBuildMessageQuery())
->setViewer($viewer)
->withReceiverPHIDs(array($this->getPHID()))
->execute();
foreach ($messages as $message) {
$engine->destroyObject($message);
}
$this->delete();
$this->saveTransaction();
}
/* -( PhabricatorConduitResultInterface )---------------------------------- */
public function getFieldSpecificationsForConduit() {
return array(
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('name')
->setType('string')
->setDescription(pht('The name of the build target.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('buildPHID')
->setType('phid')
->setDescription(pht('The build the target is associated with.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('buildStepPHID')
->setType('phid')
->setDescription(pht('The build step the target runs.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('status')
->setType('map<string, wild>')
->setDescription(pht('Status for the build target.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('epochStarted')
->setType('epoch?')
->setDescription(
pht(
'Epoch timestamp for target start, if the target '.
'has started.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('epochCompleted')
->setType('epoch?')
->setDescription(
pht(
'Epoch timestamp for target completion, if the target '.
'has completed.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('buildGeneration')
->setType('int')
->setDescription(
pht(
'Build generation this target belongs to. When builds '.
'restart, a new generation with new targets is created.')),
);
}
public function getFieldValuesForConduit() {
$status = $this->getTargetStatus();
$epoch_started = $this->getDateStarted();
if ($epoch_started) {
$epoch_started = (int)$epoch_started;
} else {
$epoch_started = null;
}
$epoch_completed = $this->getDateCompleted();
if ($epoch_completed) {
$epoch_completed = (int)$epoch_completed;
} else {
$epoch_completed = null;
}
return array(
'name' => $this->getName(),
'buildPHID' => $this->getBuildPHID(),
'buildStepPHID' => $this->getBuildStepPHID(),
'status' => array(
'value' => $status,
'name' => self::getBuildTargetStatusName($status),
),
'epochStarted' => $epoch_started,
'epochCompleted' => $epoch_completed,
'buildGeneration' => (int)$this->getBuildGeneration(),
);
}
public function getConduitSearchAttachments() {
return array();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/build/HarbormasterBuildLintMessage.php | src/applications/harbormaster/storage/build/HarbormasterBuildLintMessage.php | <?php
final class HarbormasterBuildLintMessage
extends HarbormasterDAO {
protected $buildTargetPHID;
protected $path;
protected $line;
protected $characterOffset;
protected $code;
protected $severity;
protected $name;
protected $properties = array();
private $buildTarget = self::ATTACHABLE;
public static function initializeNewLintMessage(
HarbormasterBuildTarget $build_target) {
return id(new HarbormasterBuildLintMessage())
->setBuildTargetPHID($build_target->getPHID());
}
public static function getParameterSpec() {
return array(
'name' => array(
'type' => 'string',
'description' => pht(
'Short message name, like "Syntax Error".'),
),
'code' => array(
'type' => 'string',
'description' => pht(
'Lint message code identifying the type of message, like "ERR123".'),
),
'severity' => array(
'type' => 'string',
'description' => pht(
'Severity of the message.'),
),
'path' => array(
'type' => 'string',
'description' => pht(
'Path to the file containing the lint message, from the project '.
'root.'),
),
'line' => array(
'type' => 'optional int',
'description' => pht(
'Line number in the file where the text which triggered the '.
'message first appears. The first line of the file is line 1, '.
'not line 0.'),
),
'char' => array(
'type' => 'optional int',
'description' => pht(
'Byte position on the line where the text which triggered the '.
'message starts. The first byte on the line is byte 1, not byte '.
'0. This position is byte-based (not character-based) because '.
'not all lintable files have a valid character encoding.'),
),
'description' => array(
'type' => 'optional string',
'description' => pht(
'Long explanation of the lint message.'),
),
);
}
public static function newFromDictionary(
HarbormasterBuildTarget $build_target,
array $dict) {
$obj = self::initializeNewLintMessage($build_target);
$spec = self::getParameterSpec();
$spec = ipull($spec, 'type');
// We're just going to ignore extra keys for now, to make it easier to
// add stuff here later on.
$dict = array_select_keys($dict, array_keys($spec));
PhutilTypeSpec::checkMap($dict, $spec);
$obj->setPath($dict['path']);
$obj->setLine(idx($dict, 'line'));
$obj->setCharacterOffset(idx($dict, 'char'));
$obj->setCode($dict['code']);
$obj->setSeverity($dict['severity']);
$obj->setName($dict['name']);
$description = idx($dict, 'description');
if (strlen($description)) {
$obj->setProperty('description', $description);
}
return $obj;
}
protected function getConfiguration() {
return array(
self::CONFIG_SERIALIZATION => array(
'properties' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'path' => 'text',
'line' => 'uint32?',
'characterOffset' => 'uint32?',
'code' => 'text128',
'severity' => 'text32',
'name' => 'text255',
),
self::CONFIG_KEY_SCHEMA => array(
'key_target' => array(
'columns' => array('buildTargetPHID'),
),
),
) + parent::getConfiguration();
}
public function attachBuildTarget(HarbormasterBuildTarget $build_target) {
$this->buildTarget = $build_target;
return $this;
}
public function getBuildTarget() {
return $this->assertAttached($this->buildTarget);
}
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 getSortKey() {
// TODO: Maybe use more numeric values after T6861.
$map = array(
ArcanistLintSeverity::SEVERITY_ERROR => 'A',
ArcanistLintSeverity::SEVERITY_WARNING => 'B',
ArcanistLintSeverity::SEVERITY_AUTOFIX => 'C',
ArcanistLintSeverity::SEVERITY_ADVICE => 'Y',
ArcanistLintSeverity::SEVERITY_DISABLED => 'Z',
);
$severity = idx($map, $this->getSeverity(), 'N');
$parts = array(
$severity,
$this->getPath(),
sprintf('%08d', $this->getLine()),
$this->getCode(),
);
return implode("\0", $parts);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/build/HarbormasterBuildLogChunkIterator.php | src/applications/harbormaster/storage/build/HarbormasterBuildLogChunkIterator.php | <?php
final class HarbormasterBuildLogChunkIterator
extends PhutilBufferedIterator {
private $log;
private $cursor;
private $asString;
private $min = 0;
private $max = PHP_INT_MAX;
public function __construct(HarbormasterBuildLog $log) {
$this->log = $log;
}
protected function didRewind() {
$this->cursor = $this->min;
}
public function key() {
return $this->current()->getID();
}
public function setRange($min, $max) {
$this->min = (int)$min;
$this->max = (int)$max;
return $this;
}
public function setAsString($as_string) {
$this->asString = $as_string;
return $this;
}
protected function loadPage() {
if ($this->cursor > $this->max) {
return array();
}
$results = id(new HarbormasterBuildLogChunk())->loadAllWhere(
'logID = %d AND id >= %d AND id <= %d ORDER BY id ASC LIMIT %d',
$this->log->getID(),
$this->cursor,
$this->max,
$this->getPageSize());
if ($results) {
$this->cursor = last($results)->getID() + 1;
}
if ($this->asString) {
return mpull($results, 'getChunkDisplayText');
} else {
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/harbormaster/storage/build/HarbormasterBuildLogChunk.php | src/applications/harbormaster/storage/build/HarbormasterBuildLogChunk.php | <?php
final class HarbormasterBuildLogChunk
extends HarbormasterDAO {
protected $logID;
protected $encoding;
protected $headOffset;
protected $tailOffset;
protected $size;
protected $chunk;
const CHUNK_ENCODING_TEXT = 'text';
const CHUNK_ENCODING_GZIP = 'gzip';
protected function getConfiguration() {
return array(
self::CONFIG_TIMESTAMPS => false,
self::CONFIG_BINARY => array(
'chunk' => true,
),
self::CONFIG_COLUMN_SCHEMA => array(
'logID' => 'id',
'encoding' => 'text32',
'headOffset' => 'uint64',
'tailOffset' => 'uint64',
// T6203/NULLABILITY
// Both the type and nullability of this column are crazily wrong.
'size' => 'uint32?',
'chunk' => 'bytes',
),
self::CONFIG_KEY_SCHEMA => array(
'key_offset' => array(
'columns' => array('logID', 'headOffset', 'tailOffset'),
),
),
) + parent::getConfiguration();
}
public function getChunkDisplayText() {
$data = $this->getChunk();
$encoding = $this->getEncoding();
switch ($encoding) {
case self::CHUNK_ENCODING_TEXT:
// Do nothing, data is already plaintext.
break;
case self::CHUNK_ENCODING_GZIP:
$data = gzinflate($data);
if ($data === false) {
throw new Exception(pht('Unable to inflate log chunk!'));
}
break;
default:
throw new Exception(
pht('Unknown log chunk encoding ("%s")!', $encoding));
}
return $data;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/build/HarbormasterBuildLog.php | src/applications/harbormaster/storage/build/HarbormasterBuildLog.php | <?php
final class HarbormasterBuildLog
extends HarbormasterDAO
implements
PhabricatorPolicyInterface,
PhabricatorDestructibleInterface,
PhabricatorConduitResultInterface {
protected $buildTargetPHID;
protected $logSource;
protected $logType;
protected $duration;
protected $live;
protected $filePHID;
protected $byteLength;
protected $chunkFormat;
protected $lineMap = array();
private $buildTarget = self::ATTACHABLE;
private $rope;
private $isOpen;
private $lock;
const CHUNK_BYTE_LIMIT = 1048576;
public function __construct() {
$this->rope = new PhutilRope();
}
public function __destruct() {
if ($this->isOpen) {
$this->closeBuildLog();
}
if ($this->lock) {
if ($this->lock->isLocked()) {
$this->lock->unlock();
}
}
}
public static function initializeNewBuildLog(
HarbormasterBuildTarget $build_target) {
return id(new HarbormasterBuildLog())
->setBuildTargetPHID($build_target->getPHID())
->setDuration(null)
->setLive(1)
->setByteLength(0)
->setChunkFormat(HarbormasterBuildLogChunk::CHUNK_ENCODING_TEXT);
}
public function scheduleRebuild($force) {
PhabricatorWorker::scheduleTask(
'HarbormasterLogWorker',
array(
'logPHID' => $this->getPHID(),
'force' => $force,
),
array(
'objectPHID' => $this->getPHID(),
));
}
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_SERIALIZATION => array(
'lineMap' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
// T6203/NULLABILITY
// It seems like these should be non-nullable? All logs should have a
// source, etc.
'logSource' => 'text255?',
'logType' => 'text255?',
'duration' => 'uint32?',
'live' => 'bool',
'filePHID' => 'phid?',
'byteLength' => 'uint64',
'chunkFormat' => 'text32',
),
self::CONFIG_KEY_SCHEMA => array(
'key_buildtarget' => array(
'columns' => array('buildTargetPHID'),
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
HarbormasterBuildLogPHIDType::TYPECONST);
}
public function attachBuildTarget(HarbormasterBuildTarget $build_target) {
$this->buildTarget = $build_target;
return $this;
}
public function getBuildTarget() {
return $this->assertAttached($this->buildTarget);
}
public function getName() {
return pht('Build Log');
}
public function newChunkIterator() {
return id(new HarbormasterBuildLogChunkIterator($this))
->setPageSize(8);
}
public function newDataIterator() {
return $this->newChunkIterator()
->setAsString(true);
}
private function loadLastChunkInfo() {
$chunk_table = new HarbormasterBuildLogChunk();
$conn_w = $chunk_table->establishConnection('w');
return queryfx_one(
$conn_w,
'SELECT id, size, encoding FROM %T WHERE logID = %d
ORDER BY id DESC LIMIT 1',
$chunk_table->getTableName(),
$this->getID());
}
public function loadData($offset, $length) {
$end = ($offset + $length);
$chunks = id(new HarbormasterBuildLogChunk())->loadAllWhere(
'logID = %d AND headOffset < %d AND tailOffset >= %d
ORDER BY headOffset ASC',
$this->getID(),
$end,
$offset);
// Make sure that whatever we read out of the database is a single
// contiguous range which contains all of the requested bytes.
$ranges = array();
foreach ($chunks as $chunk) {
$ranges[] = array(
'head' => $chunk->getHeadOffset(),
'tail' => $chunk->getTailOffset(),
);
}
$ranges = isort($ranges, 'head');
$ranges = array_values($ranges);
$count = count($ranges);
for ($ii = 0; $ii < ($count - 1); $ii++) {
if ($ranges[$ii + 1]['head'] === $ranges[$ii]['tail']) {
$ranges[$ii + 1]['head'] = $ranges[$ii]['head'];
unset($ranges[$ii]);
}
}
if (count($ranges) !== 1) {
$display_ranges = array();
foreach ($ranges as $range) {
$display_ranges[] = pht(
'(%d - %d)',
$range['head'],
$range['tail']);
}
if (!$display_ranges) {
$display_ranges[] = pht('<null>');
}
throw new Exception(
pht(
'Attempt to load log bytes (%d - %d) failed: failed to '.
'load a single contiguous range. Actual ranges: %s.',
$offset,
$end,
implode('; ', $display_ranges)));
}
$range = head($ranges);
if ($range['head'] > $offset || $range['tail'] < $end) {
throw new Exception(
pht(
'Attempt to load log bytes (%d - %d) failed: the loaded range '.
'(%d - %d) does not span the requested range.',
$offset,
$end,
$range['head'],
$range['tail']));
}
$parts = array();
foreach ($chunks as $chunk) {
$parts[] = $chunk->getChunkDisplayText();
}
$parts = implode('', $parts);
$chop_head = ($offset - $range['head']);
$chop_tail = ($range['tail'] - $end);
if ($chop_head) {
$parts = substr($parts, $chop_head);
}
if ($chop_tail) {
$parts = substr($parts, 0, -$chop_tail);
}
return $parts;
}
public function getLineSpanningRange($min_line, $max_line) {
$map = $this->getLineMap();
if (!$map) {
throw new Exception(pht('No line map.'));
}
$min_pos = 0;
$min_line = 0;
$max_pos = $this->getByteLength();
list($map) = $map;
foreach ($map as $marker) {
list($offset, $count) = $marker;
if ($count < $min_line) {
if ($offset > $min_pos) {
$min_pos = $offset;
$min_line = $count;
}
}
if ($count > $max_line) {
$max_pos = min($max_pos, $offset);
break;
}
}
return array($min_pos, $max_pos, $min_line);
}
public function getReadPosition($read_offset) {
$position = array(0, 0);
$map = $this->getLineMap();
if (!$map) {
throw new Exception(pht('No line map.'));
}
list($map) = $map;
foreach ($map as $marker) {
list($offset, $count) = $marker;
if ($offset > $read_offset) {
break;
}
$position = $marker;
}
return $position;
}
public function getLogText() {
// TODO: Remove this method since it won't scale for big logs.
$all_chunks = $this->newChunkIterator();
$full_text = array();
foreach ($all_chunks as $chunk) {
$full_text[] = $chunk->getChunkDisplayText();
}
return implode('', $full_text);
}
public function getURI() {
$id = $this->getID();
return "/harbormaster/log/view/{$id}/";
}
public function getRenderURI($lines) {
if (strlen($lines)) {
$lines = '$'.$lines;
}
$id = $this->getID();
return "/harbormaster/log/render/{$id}/{$lines}";
}
/* -( Chunks )------------------------------------------------------------- */
public function canCompressLog() {
return function_exists('gzdeflate');
}
public function compressLog() {
$this->processLog(HarbormasterBuildLogChunk::CHUNK_ENCODING_GZIP);
}
public function decompressLog() {
$this->processLog(HarbormasterBuildLogChunk::CHUNK_ENCODING_TEXT);
}
private function processLog($mode) {
if (!$this->getLock()->isLocked()) {
throw new Exception(
pht(
'You can not process build log chunks unless the log lock is '.
'held.'));
}
$chunks = $this->newChunkIterator();
// NOTE: Because we're going to insert new chunks, we need to stop the
// iterator once it hits the final chunk which currently exists. Otherwise,
// it may start consuming chunks we just wrote and run forever.
$last = $this->loadLastChunkInfo();
if ($last) {
$chunks->setRange(null, $last['id']);
}
$byte_limit = self::CHUNK_BYTE_LIMIT;
$rope = new PhutilRope();
$this->openTransaction();
$offset = 0;
foreach ($chunks as $chunk) {
$rope->append($chunk->getChunkDisplayText());
$chunk->delete();
while ($rope->getByteLength() > $byte_limit) {
$offset += $this->writeEncodedChunk($rope, $offset, $byte_limit, $mode);
}
}
while ($rope->getByteLength()) {
$offset += $this->writeEncodedChunk($rope, $offset, $byte_limit, $mode);
}
$this
->setChunkFormat($mode)
->save();
$this->saveTransaction();
}
private function writeEncodedChunk(
PhutilRope $rope,
$offset,
$length,
$mode) {
$data = $rope->getPrefixBytes($length);
$size = strlen($data);
switch ($mode) {
case HarbormasterBuildLogChunk::CHUNK_ENCODING_TEXT:
// Do nothing.
break;
case HarbormasterBuildLogChunk::CHUNK_ENCODING_GZIP:
$data = gzdeflate($data);
if ($data === false) {
throw new Exception(pht('Failed to gzdeflate() log data!'));
}
break;
default:
throw new Exception(pht('Unknown chunk encoding "%s"!', $mode));
}
$this->writeChunk($mode, $offset, $size, $data);
$rope->removeBytesFromHead($size);
return $size;
}
private function writeChunk($encoding, $offset, $raw_size, $data) {
$head_offset = $offset;
$tail_offset = $offset + $raw_size;
return id(new HarbormasterBuildLogChunk())
->setLogID($this->getID())
->setEncoding($encoding)
->setHeadOffset($head_offset)
->setTailOffset($tail_offset)
->setSize($raw_size)
->setChunk($data)
->save();
}
/* -( Writing )------------------------------------------------------------ */
public function getLock() {
if (!$this->lock) {
$phid = $this->getPHID();
$phid_key = PhabricatorHash::digestToLength($phid, 14);
$lock_key = "build.log({$phid_key})";
$lock = PhabricatorGlobalLock::newLock($lock_key);
$this->lock = $lock;
}
return $this->lock;
}
public function openBuildLog() {
if ($this->isOpen) {
throw new Exception(pht('This build log is already open!'));
}
$is_new = !$this->getID();
if ($is_new) {
$this->save();
}
$this->getLock()->lock();
$this->isOpen = true;
$this->reload();
if (!$this->getLive()) {
$this->setLive(1)->save();
}
return $this;
}
public function closeBuildLog($forever = true) {
if (!$this->isOpen) {
throw new Exception(
pht(
'You must openBuildLog() before you can closeBuildLog().'));
}
$this->flush();
if ($forever) {
$start = $this->getDateCreated();
$now = PhabricatorTime::getNow();
$this
->setDuration($now - $start)
->setLive(0)
->save();
}
$this->getLock()->unlock();
$this->isOpen = false;
if ($forever) {
$this->scheduleRebuild(false);
}
return $this;
}
public function append($content) {
if (!$this->isOpen) {
throw new Exception(
pht(
'You must openBuildLog() before you can append() content to '.
'the log.'));
}
$content = (string)$content;
$this->rope->append($content);
$this->flush();
return $this;
}
private function flush() {
// TODO: Maybe don't flush more than a couple of times per second. If a
// caller writes a single character over and over again, we'll currently
// spend a lot of time flushing that.
$chunk_table = id(new HarbormasterBuildLogChunk())->getTableName();
$chunk_limit = self::CHUNK_BYTE_LIMIT;
$encoding_text = HarbormasterBuildLogChunk::CHUNK_ENCODING_TEXT;
$rope = $this->rope;
while (true) {
$length = $rope->getByteLength();
if (!$length) {
break;
}
$conn_w = $this->establishConnection('w');
$last = $this->loadLastChunkInfo();
$can_append =
($last) &&
($last['encoding'] == $encoding_text) &&
($last['size'] < $chunk_limit);
if ($can_append) {
$append_id = $last['id'];
$prefix_size = $last['size'];
} else {
$append_id = null;
$prefix_size = 0;
}
$data_limit = ($chunk_limit - $prefix_size);
$append_data = $rope->getPrefixBytes($data_limit);
$data_size = strlen($append_data);
$this->openTransaction();
if ($append_id) {
queryfx(
$conn_w,
'UPDATE %T SET
chunk = CONCAT(chunk, %B),
size = %d,
tailOffset = headOffset + %d
WHERE
id = %d',
$chunk_table,
$append_data,
$prefix_size + $data_size,
$prefix_size + $data_size,
$append_id);
} else {
$this->writeChunk(
$encoding_text,
$this->getByteLength(),
$data_size,
$append_data);
}
$this->updateLineMap($append_data);
$this->save();
$this->saveTransaction();
$rope->removeBytesFromHead($data_size);
}
}
public function updateLineMap($append_data, $marker_distance = null) {
$this->byteLength += strlen($append_data);
if (!$marker_distance) {
$marker_distance = (self::CHUNK_BYTE_LIMIT / 2);
}
if (!$this->lineMap) {
$this->lineMap = array(
array(),
0,
0,
null,
);
}
list($map, $map_bytes, $line_count, $prefix) = $this->lineMap;
$buffer = $append_data;
if ($prefix) {
$prefix = base64_decode($prefix);
$buffer = $prefix.$buffer;
}
if ($map) {
list($last_marker, $last_count) = last($map);
} else {
$last_marker = 0;
$last_count = 0;
}
$max_utf8_width = 8;
$next_marker = $last_marker + $marker_distance;
$pos = 0;
$len = strlen($buffer);
while (true) {
// If we only have a few bytes left in the buffer, leave it as a prefix
// for next time.
if (($len - $pos) <= ($max_utf8_width * 2)) {
$prefix = substr($buffer, $pos);
break;
}
// The next slice we're going to look at is the smaller of:
//
// - the number of bytes we need to make it to the next marker; or
// - all the bytes we have left, minus one.
$slice_length = min(
($marker_distance - $map_bytes),
($len - $pos) - 1);
// We don't slice all the way to the end for two reasons.
// First, we want to avoid slicing immediately after a "\r" if we don't
// know what the next character is, because we want to make sure to
// count "\r\n" as a single newline, rather than counting the "\r" as
// a newline and then later counting the "\n" as another newline.
// Second, we don't want to slice in the middle of a UTF8 character if
// we can help it. We may not be able to avoid this, since the whole
// buffer may just be binary data, but in most cases we can backtrack
// a little bit and try to make it out of emoji or other legitimate
// multibyte UTF8 characters which appear in the log.
$min_width = max(1, $slice_length - $max_utf8_width);
while ($slice_length >= $min_width) {
$here = $buffer[$pos + ($slice_length - 1)];
$next = $buffer[$pos + ($slice_length - 1) + 1];
// If this is "\r" and the next character is "\n", extend the slice
// to include the "\n". Otherwise, we're fine to slice here since we
// know we're not in the middle of a UTF8 character.
if ($here === "\r") {
if ($next === "\n") {
$slice_length++;
}
break;
}
// If the next character is 0x7F or lower, or between 0xC2 and 0xF4,
// we're not slicing in the middle of a UTF8 character.
$ord = ord($next);
if ($ord <= 0x7F || ($ord >= 0xC2 && $ord <= 0xF4)) {
break;
}
$slice_length--;
}
$slice = substr($buffer, $pos, $slice_length);
$pos += $slice_length;
$map_bytes += $slice_length;
// Count newlines in the slice. This goofy approach is meaningfully
// faster than "preg_match_all()" or "preg_split()". See PHI766.
$n_rn = substr_count($slice, "\r\n");
$n_r = substr_count($slice, "\r");
$n_n = substr_count($slice, "\n");
$line_count += ($n_rn) + ($n_r - $n_rn) + ($n_n - $n_rn);
if ($map_bytes >= ($marker_distance - $max_utf8_width)) {
$map[] = array(
$last_marker + $map_bytes,
$last_count + $line_count,
);
$last_count = $last_count + $line_count;
$line_count = 0;
$last_marker = $last_marker + $map_bytes;
$map_bytes = 0;
$next_marker = $last_marker + $marker_distance;
}
}
$this->lineMap = array(
$map,
$map_bytes,
$line_count,
base64_encode($prefix),
);
return $this;
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
return $this->getBuildTarget()->getPolicy($capability);
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return $this->getBuildTarget()->hasAutomaticCapability(
$capability,
$viewer);
}
public function describeAutomaticCapability($capability) {
return pht(
'Users must be able to see a build target to view its build log.');
}
/* -( PhabricatorDestructibleInterface )----------------------------------- */
public function destroyObjectPermanently(
PhabricatorDestructionEngine $engine) {
$this->destroyFile($engine);
$this->destroyChunks();
$this->delete();
}
public function destroyFile(PhabricatorDestructionEngine $engine = null) {
if (!$engine) {
$engine = new PhabricatorDestructionEngine();
}
$file_phid = $this->getFilePHID();
if ($file_phid) {
$viewer = $engine->getViewer();
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($file_phid))
->executeOne();
if ($file) {
$engine->destroyObject($file);
}
}
$this->setFilePHID(null);
return $this;
}
public function destroyChunks() {
$chunk = new HarbormasterBuildLogChunk();
$conn = $chunk->establishConnection('w');
// Just delete the chunks directly so we don't have to pull the data over
// the wire for large logs.
queryfx(
$conn,
'DELETE FROM %T WHERE logID = %d',
$chunk->getTableName(),
$this->getID());
return $this;
}
/* -( PhabricatorConduitResultInterface )---------------------------------- */
public function getFieldSpecificationsForConduit() {
return array(
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('buildTargetPHID')
->setType('phid')
->setDescription(pht('Build target this log is attached to.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('byteLength')
->setType('int')
->setDescription(pht('Length of the log in bytes.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('filePHID')
->setType('phid?')
->setDescription(pht('A file containing the log data.')),
);
}
public function getFieldValuesForConduit() {
return array(
'buildTargetPHID' => $this->getBuildTargetPHID(),
'byteLength' => (int)$this->getByteLength(),
'filePHID' => $this->getFilePHID(),
);
}
public function getConduitSearchAttachments() {
return array();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/storage/build/HarbormasterBuild.php | src/applications/harbormaster/storage/build/HarbormasterBuild.php | <?php
final class HarbormasterBuild extends HarbormasterDAO
implements
PhabricatorApplicationTransactionInterface,
PhabricatorPolicyInterface,
PhabricatorConduitResultInterface,
PhabricatorDestructibleInterface {
protected $buildablePHID;
protected $buildPlanPHID;
protected $buildStatus;
protected $buildGeneration;
protected $buildParameters = array();
protected $initiatorPHID;
protected $planAutoKey;
private $buildable = self::ATTACHABLE;
private $buildPlan = self::ATTACHABLE;
private $buildTargets = self::ATTACHABLE;
private $unprocessedMessages = self::ATTACHABLE;
public static function initializeNewBuild(PhabricatorUser $actor) {
return id(new HarbormasterBuild())
->setBuildStatus(HarbormasterBuildStatus::STATUS_INACTIVE)
->setBuildGeneration(0);
}
public function delete() {
$this->openTransaction();
$this->deleteUnprocessedMessages();
$result = parent::delete();
$this->saveTransaction();
return $result;
}
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_SERIALIZATION => array(
'buildParameters' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'buildStatus' => 'text32',
'buildGeneration' => 'uint32',
'planAutoKey' => 'text32?',
'initiatorPHID' => 'phid?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_buildable' => array(
'columns' => array('buildablePHID'),
),
'key_plan' => array(
'columns' => array('buildPlanPHID'),
),
'key_status' => array(
'columns' => array('buildStatus'),
),
'key_planautokey' => array(
'columns' => array('buildablePHID', 'planAutoKey'),
'unique' => true,
),
'key_initiator' => array(
'columns' => array('initiatorPHID'),
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
HarbormasterBuildPHIDType::TYPECONST);
}
public function attachBuildable(HarbormasterBuildable $buildable) {
$this->buildable = $buildable;
return $this;
}
public function getBuildable() {
return $this->assertAttached($this->buildable);
}
public function getName() {
if ($this->getBuildPlan()) {
return $this->getBuildPlan()->getName();
}
return pht('Build');
}
public function attachBuildPlan(
HarbormasterBuildPlan $build_plan = null) {
$this->buildPlan = $build_plan;
return $this;
}
public function getBuildPlan() {
return $this->assertAttached($this->buildPlan);
}
public function getBuildTargets() {
return $this->assertAttached($this->buildTargets);
}
public function attachBuildTargets(array $targets) {
$this->buildTargets = $targets;
return $this;
}
public function isBuilding() {
return $this->getBuildStatusObject()->isBuilding();
}
public function isAutobuild() {
return ($this->getPlanAutoKey() !== null);
}
public function retrieveVariablesFromBuild() {
$results = array(
'buildable.diff' => null,
'buildable.revision' => null,
'buildable.commit' => null,
'repository.callsign' => null,
'repository.phid' => null,
'repository.vcs' => null,
'repository.uri' => null,
'step.timestamp' => null,
'build.id' => null,
'initiator.phid' => null,
'buildable.phid' => null,
'buildable.object.phid' => null,
'buildable.container.phid' => null,
'build.phid' => null,
);
foreach ($this->getBuildParameters() as $key => $value) {
$results['build/'.$key] = $value;
}
$buildable = $this->getBuildable();
$object = $buildable->getBuildableObject();
$object_variables = $object->getBuildVariables();
$results = $object_variables + $results;
$results['step.timestamp'] = time();
$results['build.id'] = $this->getID();
$results['initiator.phid'] = $this->getInitiatorPHID();
$results['buildable.phid'] = $buildable->getPHID();
$results['buildable.object.phid'] = $object->getPHID();
$results['buildable.container.phid'] = $buildable->getContainerPHID();
$results['build.phid'] = $this->getPHID();
return $results;
}
public static function getAvailableBuildVariables() {
$objects = id(new PhutilClassMapQuery())
->setAncestorClass('HarbormasterBuildableInterface')
->execute();
$variables = array();
$variables[] = array(
'step.timestamp' => pht('The current UNIX timestamp.'),
'build.id' => pht('The ID of the current build.'),
'target.phid' => pht('The PHID of the current build target.'),
'initiator.phid' => pht(
'The PHID of the user or Object that initiated the build, '.
'if applicable.'),
'buildable.phid' => pht(
'The object PHID of the Harbormaster Buildable being built.'),
'buildable.object.phid' => pht(
'The object PHID of the object (usually a diff or commit) '.
'being built.'),
'buildable.container.phid' => pht(
'The object PHID of the container (usually a revision or repository) '.
'for the object being built.'),
'build.phid' => pht(
'The object PHID of the Harbormaster Build being built.'),
);
foreach ($objects as $object) {
$variables[] = $object->getAvailableBuildVariables();
}
$variables = array_mergev($variables);
return $variables;
}
public function isComplete() {
return $this->getBuildStatusObject()->isComplete();
}
public function isPaused() {
return $this->getBuildStatusObject()->isPaused();
}
public function isPassed() {
return $this->getBuildStatusObject()->isPassed();
}
public function isFailed() {
return $this->getBuildStatusObject()->isFailed();
}
public function isPending() {
return $this->getBuildstatusObject()->isPending();
}
public function getURI() {
$id = $this->getID();
return "/harbormaster/build/{$id}/";
}
public function getBuildPendingStatusObject() {
list($pending_status) = $this->getUnprocessedMessageState();
if ($pending_status !== null) {
return HarbormasterBuildStatus::newBuildStatusObject($pending_status);
}
return $this->getBuildStatusObject();
}
protected function getBuildStatusObject() {
$status_key = $this->getBuildStatus();
return HarbormasterBuildStatus::newBuildStatusObject($status_key);
}
public function getObjectName() {
return pht('Build %d', $this->getID());
}
/* -( Build Messages )----------------------------------------------------- */
private function getUnprocessedMessages() {
return $this->assertAttached($this->unprocessedMessages);
}
public function getUnprocessedMessagesForApply() {
$unprocessed_state = $this->getUnprocessedMessageState();
list($pending_status, $apply_messages) = $unprocessed_state;
return $apply_messages;
}
private function getUnprocessedMessageState() {
// NOTE: If a build has multiple unprocessed messages, we'll ignore
// messages that are obsoleted by a later or stronger message.
//
// For example, if a build has both "pause" and "abort" messages in queue,
// we just ignore the "pause" message and perform an "abort", since pausing
// first wouldn't affect the final state, so we can just skip it.
//
// Likewise, if a build has both "restart" and "abort" messages, the most
// recent message is controlling: we'll take whichever action a command
// was most recently issued for.
$is_restarting = false;
$is_aborting = false;
$is_pausing = false;
$is_resuming = false;
$apply_messages = array();
foreach ($this->getUnprocessedMessages() as $message_object) {
$message_type = $message_object->getType();
switch ($message_type) {
case HarbormasterBuildMessageRestartTransaction::MESSAGETYPE:
$is_restarting = true;
$is_aborting = false;
$apply_messages = array($message_object);
break;
case HarbormasterBuildMessageAbortTransaction::MESSAGETYPE:
$is_aborting = true;
$is_restarting = false;
$apply_messages = array($message_object);
break;
case HarbormasterBuildMessagePauseTransaction::MESSAGETYPE:
$is_pausing = true;
$is_resuming = false;
$apply_messages = array($message_object);
break;
case HarbormasterBuildMessageResumeTransaction::MESSAGETYPE:
$is_resuming = true;
$is_pausing = false;
$apply_messages = array($message_object);
break;
}
}
$pending_status = null;
if ($is_restarting) {
$pending_status = HarbormasterBuildStatus::PENDING_RESTARTING;
} else if ($is_aborting) {
$pending_status = HarbormasterBuildStatus::PENDING_ABORTING;
} else if ($is_pausing) {
$pending_status = HarbormasterBuildStatus::PENDING_PAUSING;
} else if ($is_resuming) {
$pending_status = HarbormasterBuildStatus::PENDING_RESUMING;
}
return array($pending_status, $apply_messages);
}
public function attachUnprocessedMessages(array $messages) {
assert_instances_of($messages, 'HarbormasterBuildMessage');
$this->unprocessedMessages = $messages;
return $this;
}
public function isPausing() {
return $this->getBuildPendingStatusObject()->isPausing();
}
public function isResuming() {
return $this->getBuildPendingStatusObject()->isResuming();
}
public function isRestarting() {
return $this->getBuildPendingStatusObject()->isRestarting();
}
public function isAborting() {
return $this->getBuildPendingStatusObject()->isAborting();
}
public function markUnprocessedMessagesAsProcessed() {
foreach ($this->getUnprocessedMessages() as $key => $message_object) {
$message_object
->setIsConsumed(1)
->save();
}
return $this;
}
public function deleteUnprocessedMessages() {
foreach ($this->getUnprocessedMessages() as $key => $message_object) {
$message_object->delete();
unset($this->unprocessedMessages[$key]);
}
return $this;
}
public function sendMessage(PhabricatorUser $viewer, $message_type) {
HarbormasterBuildMessage::initializeNewMessage($viewer)
->setReceiverPHID($this->getPHID())
->setType($message_type)
->save();
PhabricatorWorker::scheduleTask(
'HarbormasterBuildWorker',
array(
'buildID' => $this->getID(),
),
array(
'objectPHID' => $this->getPHID(),
'containerPHID' => $this->getBuildablePHID(),
));
}
public function releaseAllArtifacts(PhabricatorUser $viewer) {
$targets = id(new HarbormasterBuildTargetQuery())
->setViewer($viewer)
->withBuildPHIDs(array($this->getPHID()))
->withBuildGenerations(array($this->getBuildGeneration()))
->execute();
if (!$targets) {
return;
}
$target_phids = mpull($targets, 'getPHID');
$artifacts = id(new HarbormasterBuildArtifactQuery())
->setViewer($viewer)
->withBuildTargetPHIDs($target_phids)
->withIsReleased(false)
->execute();
foreach ($artifacts as $artifact) {
$artifact->releaseArtifact();
}
}
public function restartBuild(PhabricatorUser $viewer) {
// TODO: This should become transactional.
// We're restarting the build, so release all previous artifacts.
$this->releaseAllArtifacts($viewer);
// Increment the build generation counter on the build.
$this->setBuildGeneration($this->getBuildGeneration() + 1);
// Currently running targets should periodically check their build
// generation (which won't have changed) against the build's generation.
// If it is different, they will automatically stop what they're doing
// and abort.
// Previously we used to delete targets, logs and artifacts here. Instead,
// leave them around so users can view previous generations of this build.
}
/* -( PhabricatorApplicationTransactionInterface )------------------------- */
public function getApplicationTransactionEditor() {
return new HarbormasterBuildTransactionEditor();
}
public function getApplicationTransactionTemplate() {
return new HarbormasterBuildTransaction();
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
);
}
public function getPolicy($capability) {
return $this->getBuildable()->getPolicy($capability);
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return $this->getBuildable()->hasAutomaticCapability(
$capability,
$viewer);
}
public function describeAutomaticCapability($capability) {
return pht('A build inherits policies from its buildable.');
}
/* -( PhabricatorConduitResultInterface )---------------------------------- */
public function getFieldSpecificationsForConduit() {
return array(
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('buildablePHID')
->setType('phid')
->setDescription(pht('PHID of the object this build is building.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('buildPlanPHID')
->setType('phid')
->setDescription(pht('PHID of the build plan being run.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('buildStatus')
->setType('map<string, wild>')
->setDescription(pht('The current status of this build.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('initiatorPHID')
->setType('phid')
->setDescription(pht('The person (or thing) that started this build.')),
id(new PhabricatorConduitSearchFieldSpecification())
->setKey('name')
->setType('string')
->setDescription(pht('The name of this build.')),
);
}
public function getFieldValuesForConduit() {
$status = $this->getBuildStatus();
return array(
'buildablePHID' => $this->getBuildablePHID(),
'buildPlanPHID' => $this->getBuildPlanPHID(),
'buildStatus' => array(
'value' => $status,
'name' => HarbormasterBuildStatus::getBuildStatusName($status),
'color.ansi' =>
HarbormasterBuildStatus::getBuildStatusANSIColor($status),
),
'initiatorPHID' => nonempty($this->getInitiatorPHID(), null),
'name' => $this->getName(),
);
}
public function getConduitSearchAttachments() {
return array(
id(new HarbormasterQueryBuildsSearchEngineAttachment())
->setAttachmentKey('querybuilds'),
);
}
/* -( PhabricatorDestructibleInterface )----------------------------------- */
public function destroyObjectPermanently(
PhabricatorDestructionEngine $engine) {
$viewer = $engine->getViewer();
$this->openTransaction();
$targets = id(new HarbormasterBuildTargetQuery())
->setViewer($viewer)
->withBuildPHIDs(array($this->getPHID()))
->execute();
foreach ($targets as $target) {
$engine->destroyObject($target);
}
$messages = id(new HarbormasterBuildMessageQuery())
->setViewer($viewer)
->withReceiverPHIDs(array($this->getPHID()))
->execute();
foreach ($messages as $message) {
$engine->destroyObject($message);
}
$this->delete();
$this->saveTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/management/HarbormasterManagementBuildWorkflow.php | src/applications/harbormaster/management/HarbormasterManagementBuildWorkflow.php | <?php
final class HarbormasterManagementBuildWorkflow
extends HarbormasterManagementWorkflow {
protected function didConstruct() {
$this
->setName('build')
->setExamples('**build** [__options__] __buildable__ --plan __id__')
->setSynopsis(pht('Run plan __id__ on __buildable__.'))
->setArguments(
array(
array(
'name' => 'plan',
'param' => 'id',
'help' => pht('ID of build plan to run.'),
),
array(
'name' => 'background',
'help' => pht(
'Submit builds into the build queue normally instead of '.
'running them in the foreground.'),
),
array(
'name' => 'buildable',
'wildcard' => true,
),
));
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$names = $args->getArg('buildable');
if (count($names) != 1) {
throw new PhutilArgumentUsageException(
pht('Specify exactly one buildable object, by object name.'));
}
$name = head($names);
$buildable = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withNames($names)
->executeOne();
if (!$buildable) {
throw new PhutilArgumentUsageException(
pht('No such buildable "%s"!', $name));
}
if (!($buildable instanceof HarbormasterBuildableInterface)) {
throw new PhutilArgumentUsageException(
pht('Object "%s" is not a buildable!', $name));
}
$plan_id = $args->getArg('plan');
if (!$plan_id) {
throw new PhutilArgumentUsageException(
pht(
'Use %s to specify a build plan to run.',
'--plan'));
}
$plan = id(new HarbormasterBuildPlanQuery())
->setViewer($viewer)
->withIDs(array($plan_id))
->executeOne();
if (!$plan) {
throw new PhutilArgumentUsageException(
pht('Build plan "%s" does not exist.', $plan_id));
}
if (!$plan->canRunManually()) {
throw new PhutilArgumentUsageException(
pht('This build plan can not be run manually.'));
}
$console = PhutilConsole::getConsole();
$buildable = HarbormasterBuildable::initializeNewBuildable($viewer)
->setIsManualBuildable(true)
->setBuildablePHID($buildable->getHarbormasterBuildablePHID())
->setContainerPHID($buildable->getHarbormasterContainerPHID())
->save();
$buildable->sendMessage(
$viewer,
HarbormasterMessageType::BUILDABLE_BUILD,
false);
$console->writeOut(
"%s\n",
pht(
'Applying plan %s to new buildable %s...',
$plan->getID(),
'B'.$buildable->getID()));
$console->writeOut(
"\n %s\n\n",
PhabricatorEnv::getProductionURI('/B'.$buildable->getID()));
if (!$args->getArg('background')) {
PhabricatorWorker::setRunAllTasksInProcess(true);
}
if ($viewer->isOmnipotent()) {
$initiator = id(new PhabricatorHarbormasterApplication())->getPHID();
} else {
$initiator = $viewer->getPHID();
}
$buildable->applyPlan($plan, array(), $initiator);
$console->writeOut("%s\n", pht('Done.'));
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/management/HarbormasterManagementRestartWorkflow.php | src/applications/harbormaster/management/HarbormasterManagementRestartWorkflow.php | <?php
final class HarbormasterManagementRestartWorkflow
extends HarbormasterManagementWorkflow {
protected function didConstruct() {
$this
->setName('restart')
->setExamples(
"**restart** --active\n".
'**restart** --id id')
->setSynopsis(pht('Restart Harbormaster builds.'))
->setArguments(
array(
array(
'name' => 'id',
'param' => 'id',
'repeat' => true,
'help' => pht('Select one or more builds by ID.'),
),
array(
'name' => 'active',
'help' => pht('Select all active builds.'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$ids = $args->getArg('id');
$active = $args->getArg('active');
if (!$ids && !$active) {
throw new PhutilArgumentUsageException(
pht('Use "--id" or "--active" to select builds.'));
} if ($ids && $active) {
throw new PhutilArgumentUsageException(
pht('Use one of "--id" or "--active" to select builds, but not both.'));
}
$query = id(new HarbormasterBuildQuery())
->setViewer($viewer);
if ($ids) {
$query->withIDs($ids);
} else {
$query->withBuildStatuses(
HarbormasterBuildStatus::getActiveStatusConstants());
}
$builds = $query->execute();
$count = count($builds);
if (!$count) {
$this->logSkip(
pht('SKIP'),
pht('No builds to restart.'));
return 0;
}
$prompt = pht('Restart %s build(s)?', new PhutilNumber($count));
if (!phutil_console_confirm($prompt)) {
throw new ArcanistUserAbortException();
}
$message = new HarbormasterBuildMessageRestartTransaction();
foreach ($builds as $build) {
$this->logInfo(
pht('RESTARTING'),
pht('Build %d: %s', $build->getID(), $build->getName()));
try {
$message->assertCanSendMessage($viewer, $build);
} catch (HarbormasterMessageException $ex) {
$this->logWarn(
pht('INVALID'),
$ex->newDisplayString());
}
$build->sendMessage(
$viewer,
$message->getHarbormasterBuildMessageType());
$this->logOkay(
pht('QUEUED'),
pht('Sent a restart message to build.'));
}
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/management/HarbormasterManagementPublishWorkflow.php | src/applications/harbormaster/management/HarbormasterManagementPublishWorkflow.php | <?php
final class HarbormasterManagementPublishWorkflow
extends HarbormasterManagementWorkflow {
protected function didConstruct() {
$this
->setName('publish')
->setExamples(pht('**publish** __buildable__ ...'))
->setSynopsis(
pht(
'Publish a buildable. This is primarily useful for developing '.
'and debugging applications which have buildable objects.'))
->setArguments(
array(
array(
'name' => 'buildable',
'wildcard' => true,
),
));
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$buildable_names = $args->getArg('buildable');
if (!$buildable_names) {
throw new PhutilArgumentUsageException(
pht(
'Name one or more buildables to publish, like "B123".'));
}
$query = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withNames($buildable_names);
$query->execute();
$result_map = $query->getNamedResults();
foreach ($buildable_names as $name) {
if (!isset($result_map[$name])) {
throw new PhutilArgumentUsageException(
pht(
'Argument "%s" does not name a buildable. Provide one or more '.
'valid buildable monograms or PHIDs.',
$name));
}
}
foreach ($result_map as $name => $result) {
if (!($result instanceof HarbormasterBuildable)) {
throw new PhutilArgumentUsageException(
pht(
'Object "%s" is not a HarbormasterBuildable (it is a "%s"). '.
'Name one or more buildables to publish, like "B123".',
$name,
get_class($result)));
}
}
foreach ($result_map as $buildable) {
echo tsprintf(
"%s\n",
pht(
'Publishing "%s"...',
$buildable->getMonogram()));
// Reload the buildable to pick up builds.
$buildable = id(new HarbormasterBuildableQuery())
->setViewer($viewer)
->withIDs(array($buildable->getID()))
->needBuilds(true)
->executeOne();
$engine = id(new HarbormasterBuildEngine())
->setViewer($viewer)
->publishBuildable($buildable, $buildable);
}
echo tsprintf(
"%s\n",
pht('Done.'));
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/management/HarbormasterManagementArchiveLogsWorkflow.php | src/applications/harbormaster/management/HarbormasterManagementArchiveLogsWorkflow.php | <?php
final class HarbormasterManagementArchiveLogsWorkflow
extends HarbormasterManagementWorkflow {
protected function didConstruct() {
$this
->setName('archive-logs')
->setExamples('**archive-logs** [__options__] --mode __mode__')
->setSynopsis(pht('Compress, decompress, store or destroy build logs.'))
->setArguments(
array(
array(
'name' => 'mode',
'param' => 'mode',
'help' => pht(
'Use "plain" to remove encoding, or "compress" to compress '.
'logs.'),
),
array(
'name' => 'details',
'help' => pht(
'Show more details about operations as they are performed. '.
'Slow! But also very reassuring!'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$mode = $args->getArg('mode');
if (!$mode) {
throw new PhutilArgumentUsageException(
pht('Choose an archival mode with --mode.'));
}
$valid_modes = array(
'plain',
'compress',
);
$valid_modes = array_fuse($valid_modes);
if (empty($valid_modes[$mode])) {
throw new PhutilArgumentUsageException(
pht(
'Unknown mode "%s". Valid modes are: %s.',
$mode,
implode(', ', $valid_modes)));
}
$log_table = new HarbormasterBuildLog();
$logs = new LiskMigrationIterator($log_table);
$show_details = $args->getArg('details');
if ($show_details) {
$total_old = 0;
$total_new = 0;
}
foreach ($logs as $log) {
echo tsprintf(
"%s\n",
pht('Processing Harbormaster build log #%d...', $log->getID()));
if ($show_details) {
$old_stats = $this->computeDetails($log);
}
switch ($mode) {
case 'plain':
$log->decompressLog();
break;
case 'compress':
$log->compressLog();
break;
}
if ($show_details) {
$new_stats = $this->computeDetails($log);
$this->printStats($old_stats, $new_stats);
$total_old += $old_stats['bytes'];
$total_new += $new_stats['bytes'];
}
}
if ($show_details) {
echo tsprintf(
"%s\n",
pht(
'Done. Total byte size of affected logs: %s -> %s.',
new PhutilNumber($total_old),
new PhutilNumber($total_new)));
}
return 0;
}
private function computeDetails(HarbormasterBuildLog $log) {
$bytes = 0;
$chunks = 0;
$hash = hash_init('sha1');
foreach ($log->newChunkIterator() as $chunk) {
$bytes += strlen($chunk->getChunk());
$chunks++;
hash_update($hash, $chunk->getChunkDisplayText());
}
return array(
'bytes' => $bytes,
'chunks' => $chunks,
'hash' => hash_final($hash),
);
}
private function printStats(array $old_stats, array $new_stats) {
echo tsprintf(
" %s\n",
pht(
'%s: %s -> %s',
pht('Stored Bytes'),
new PhutilNumber($old_stats['bytes']),
new PhutilNumber($new_stats['bytes'])));
echo tsprintf(
" %s\n",
pht(
'%s: %s -> %s',
pht('Stored Chunks'),
new PhutilNumber($old_stats['chunks']),
new PhutilNumber($new_stats['chunks'])));
echo tsprintf(
" %s\n",
pht(
'%s: %s -> %s',
pht('Data Hash'),
$old_stats['hash'],
$new_stats['hash']));
if ($old_stats['hash'] !== $new_stats['hash']) {
throw new Exception(
pht('Log data hashes differ! Something is tragically wrong!'));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/management/HarbormasterManagementUpdateWorkflow.php | src/applications/harbormaster/management/HarbormasterManagementUpdateWorkflow.php | <?php
final class HarbormasterManagementUpdateWorkflow
extends HarbormasterManagementWorkflow {
protected function didConstruct() {
$this
->setName('update')
->setExamples('**update** [__options__] __buildable__')
->setSynopsis(pht('Explicitly update the builds for __buildable__.'))
->setArguments(
array(
array(
'name' => 'build',
'param' => 'id',
'help' => pht('Update only this build.'),
),
array(
'name' => 'force',
'help' => pht(
'Force the buildable to update even if no build status '.
'changes occur during normal update.'),
),
array(
'name' => 'background',
'help' => pht(
'If updating generates tasks, queue them for the daemons '.
'instead of executing them in this process.'),
),
array(
'name' => 'buildable',
'wildcard' => true,
),
));
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$force_update = $args->getArg('force');
$names = $args->getArg('buildable');
if (count($names) != 1) {
throw new PhutilArgumentUsageException(
pht('Specify exactly one buildable, by object name.'));
}
$buildable = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withNames($names)
->executeOne();
if (!$buildable) {
throw new PhutilArgumentUsageException(
pht('No such buildable "%s"!', head($names)));
}
if (!($buildable instanceof HarbormasterBuildable)) {
throw new PhutilArgumentUsageException(
pht('Object "%s" is not a Harbormaster Buildable!', head($names)));
}
// Reload the buildable directly to get builds.
$buildable = id(new HarbormasterBuildableQuery())
->setViewer($viewer)
->withIDs(array($buildable->getID()))
->needBuilds(true)
->executeOne();
$builds = $buildable->getBuilds();
$builds = mpull($builds, null, 'getID');
$build_id = $args->getArg('build');
if ($build_id) {
$builds = array_select_keys($builds, array($build_id));
if (!$builds) {
throw new PhutilArgumentUsageException(
pht(
'The specified buildable does not have a build with ID "%s".',
$build_id));
}
}
$console = PhutilConsole::getConsole();
if (!$args->getArg('background')) {
PhabricatorWorker::setRunAllTasksInProcess(true);
}
foreach ($builds as $build) {
$console->writeOut(
"%s\n",
pht(
'Updating build %d of buildable %s...',
$build->getID(),
$buildable->getMonogram()));
$engine = id(new HarbormasterBuildEngine())
->setViewer($viewer)
->setBuild($build);
if ($force_update) {
$engine->setForceBuildableUpdate(true);
}
$engine->continueBuild();
}
$console->writeOut("%s\n", pht('Done.'));
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/management/HarbormasterManagementRebuildLogWorkflow.php | src/applications/harbormaster/management/HarbormasterManagementRebuildLogWorkflow.php | <?php
final class HarbormasterManagementRebuildLogWorkflow
extends HarbormasterManagementWorkflow {
protected function didConstruct() {
$this
->setName('rebuild-log')
->setExamples(
pht(
"**rebuild-log** --id __id__ [__options__]\n".
"**rebuild-log** --all"))
->setSynopsis(
pht(
'Rebuild the file and summary for a log. This is primarily '.
'intended to make it easier to develop new log summarizers.'))
->setArguments(
array(
array(
'name' => 'id',
'param' => 'id',
'help' => pht('Log to rebuild.'),
),
array(
'name' => 'all',
'help' => pht('Rebuild all logs.'),
),
array(
'name' => 'force',
'help' => pht(
'Force logs to rebuild even if they appear to be in good '.
'shape already.'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$is_force = $args->getArg('force');
$log_id = $args->getArg('id');
$is_all = $args->getArg('all');
if (!$is_all && !$log_id) {
throw new PhutilArgumentUsageException(
pht(
'Choose a build log to rebuild with "--id", or rebuild all '.
'logs with "--all".'));
}
if ($is_all && $log_id) {
throw new PhutilArgumentUsageException(
pht(
'You can not specify both "--id" and "--all". Choose one or '.
'the other.'));
}
if ($log_id) {
$log = id(new HarbormasterBuildLogQuery())
->setViewer($viewer)
->withIDs(array($log_id))
->executeOne();
if (!$log) {
throw new PhutilArgumentUsageException(
pht(
'Unable to load build log "%s".',
$log_id));
}
$logs = array($log);
} else {
$logs = new LiskMigrationIterator(new HarbormasterBuildLog());
}
PhabricatorWorker::setRunAllTasksInProcess(true);
foreach ($logs as $log) {
echo tsprintf(
"%s\n",
pht(
'Rebuilding log "%s"...',
pht('Build Log %d', $log->getID())));
try {
$log->scheduleRebuild($is_force);
} catch (Exception $ex) {
if ($is_all) {
phlog($ex);
} else {
throw $ex;
}
}
}
echo tsprintf(
"%s\n",
pht('Done.'));
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/management/HarbormasterManagementWriteLogWorkflow.php | src/applications/harbormaster/management/HarbormasterManagementWriteLogWorkflow.php | <?php
final class HarbormasterManagementWriteLogWorkflow
extends HarbormasterManagementWorkflow {
protected function didConstruct() {
$this
->setName('write-log')
->setExamples('**write-log** --target __id__ [__options__]')
->setSynopsis(
pht(
'Write a new Harbormaster build log. This is primarily intended '.
'to make development and testing easier.'))
->setArguments(
array(
array(
'name' => 'target',
'param' => 'id',
'help' => pht('Build Target ID to attach the log to.'),
),
array(
'name' => 'rate',
'param' => 'bytes',
'help' => pht(
'Limit the rate at which the log is written, to test '.
'live log streaming.'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$target_id = $args->getArg('target');
if (!$target_id) {
throw new PhutilArgumentUsageException(
pht('Choose a build target to attach the log to with "--target".'));
}
$target = id(new HarbormasterBuildTargetQuery())
->setViewer($viewer)
->withIDs(array($target_id))
->executeOne();
if (!$target) {
throw new PhutilArgumentUsageException(
pht(
'Unable to load build target "%s".',
$target_id));
}
$log = HarbormasterBuildLog::initializeNewBuildLog($target);
$log->openBuildLog();
echo tsprintf(
"%s\n\n __%s__\n\n",
pht('Opened a new build log:'),
PhabricatorEnv::getURI($log->getURI()));
echo tsprintf(
"%s\n",
pht('Reading log content from stdin...'));
$content = file_get_contents('php://stdin');
$rate = $args->getArg('rate');
if ($rate) {
if ($rate <= 0) {
throw new Exception(
pht(
'Write rate must be more than 0 bytes/sec.'));
}
echo tsprintf(
"%s\n",
pht('Writing log, slowly...'));
$offset = 0;
$total = strlen($content);
$pieces = str_split($content, $rate);
$bar = id(new PhutilConsoleProgressBar())
->setTotal($total);
foreach ($pieces as $piece) {
$log->append($piece);
$bar->update(strlen($piece));
sleep(1);
}
$bar->done();
} else {
$log->append($content);
}
echo tsprintf(
"%s\n",
pht('Write completed. Closing log...'));
PhabricatorWorker::setRunAllTasksInProcess(true);
$log->closeBuildLog();
echo tsprintf(
"%s\n",
pht('Done.'));
return 0;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/management/HarbormasterManagementWorkflow.php | src/applications/harbormaster/management/HarbormasterManagementWorkflow.php | <?php
abstract class HarbormasterManagementWorkflow
extends PhabricatorManagementWorkflow {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/worker/HarbormasterTargetWorker.php | src/applications/harbormaster/worker/HarbormasterTargetWorker.php | <?php
/**
* Execute a build target.
*/
final class HarbormasterTargetWorker extends HarbormasterWorker {
public function getRequiredLeaseTime() {
// This worker performs actual build work, which may involve a long wait
// on external systems.
return phutil_units('24 hours in seconds');
}
public function renderForDisplay(PhabricatorUser $viewer) {
try {
$target = $this->loadBuildTarget();
} catch (Exception $ex) {
return null;
}
return $viewer->renderHandle($target->getPHID());
}
private function loadBuildTarget() {
$data = $this->getTaskData();
$id = idx($data, 'targetID');
$target = id(new HarbormasterBuildTargetQuery())
->withIDs(array($id))
->setViewer($this->getViewer())
->needBuildSteps(true)
->executeOne();
if (!$target) {
throw new PhabricatorWorkerPermanentFailureException(
pht(
'Bad build target ID "%d".',
$id));
}
return $target;
}
protected function doWork() {
$target = $this->loadBuildTarget();
$build = $target->getBuild();
$viewer = $this->getViewer();
// If this is the first time we're starting work on this target, mark the
// current time as the start time. If the target yields or waits, we may
// end up here again later, so we don't want to overwrite the start time if
// we already have a value.
if (!$target->getDateStarted()) {
$target->setDateStarted(PhabricatorTime::getNow());
}
try {
if ($target->getBuildGeneration() !== $build->getBuildGeneration()) {
throw new HarbormasterBuildAbortedException();
}
$status_pending = HarbormasterBuildTarget::STATUS_PENDING;
if ($target->getTargetStatus() == $status_pending) {
$target->setTargetStatus(HarbormasterBuildTarget::STATUS_BUILDING);
$target->save();
}
$implementation = $target->getImplementation();
$implementation->setCurrentWorkerTaskID($this->getCurrentWorkerTaskID());
$implementation->execute($build, $target);
$next_status = HarbormasterBuildTarget::STATUS_PASSED;
if ($implementation->shouldWaitForMessage($target)) {
$next_status = HarbormasterBuildTarget::STATUS_WAITING;
}
$target->setTargetStatus($next_status);
if ($target->isComplete()) {
$target->setDateCompleted(PhabricatorTime::getNow());
}
$target->save();
} catch (PhabricatorWorkerYieldException $ex) {
// If the target wants to yield, let that escape without further
// processing. We'll resume after the task retries.
throw $ex;
} catch (HarbormasterBuildFailureException $ex) {
// A build step wants to fail explicitly.
$target->setTargetStatus(HarbormasterBuildTarget::STATUS_FAILED);
$target->setDateCompleted(PhabricatorTime::getNow());
$target->save();
} catch (HarbormasterBuildAbortedException $ex) {
// A build step is aborting because the build has been restarted.
$target->setTargetStatus(HarbormasterBuildTarget::STATUS_ABORTED);
$target->setDateCompleted(PhabricatorTime::getNow());
$target->save();
} catch (Exception $ex) {
try {
$log = $target->newLog('core', 'exception')
->append($ex)
->closeBuildLog();
} catch (Exception $log_ex) {
phlog($log_ex);
}
$target->setTargetStatus(HarbormasterBuildTarget::STATUS_FAILED);
$target->setDateCompleted(time());
$target->save();
}
id(new HarbormasterBuildEngine())
->setViewer($viewer)
->setBuild($build)
->continueBuild();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/worker/HarbormasterLogWorker.php | src/applications/harbormaster/worker/HarbormasterLogWorker.php | <?php
final class HarbormasterLogWorker extends HarbormasterWorker {
protected function doWork() {
$viewer = $this->getViewer();
$data = $this->getTaskData();
$log_phid = idx($data, 'logPHID');
$log = id(new HarbormasterBuildLogQuery())
->setViewer($viewer)
->withPHIDs(array($log_phid))
->executeOne();
if (!$log) {
throw new PhabricatorWorkerPermanentFailureException(
pht(
'Invalid build log PHID "%s".',
$log_phid));
}
$lock = $log->getLock();
try {
$lock->lock();
} catch (PhutilLockException $ex) {
throw new PhabricatorWorkerYieldException(15);
}
$caught = null;
try {
$log->reload();
if ($log->getLive()) {
throw new PhabricatorWorkerPermanentFailureException(
pht(
'Log "%s" is still live. Logs can not be finalized until '.
'they have closed.',
$log_phid));
}
$this->finalizeBuildLog($log);
} catch (Exception $ex) {
$caught = $ex;
}
$lock->unlock();
if ($caught) {
throw $caught;
}
}
private function finalizeBuildLog(HarbormasterBuildLog $log) {
$viewer = $this->getViewer();
$data = $this->getTaskData();
$is_force = idx($data, 'force');
if (!$log->getByteLength() || !$log->getLineMap() || $is_force) {
$iterator = $log->newDataIterator();
$log
->setByteLength(0)
->setLineMap(array());
foreach ($iterator as $block) {
$log->updateLineMap($block);
}
$log->save();
}
$format_text = HarbormasterBuildLogChunk::CHUNK_ENCODING_TEXT;
if (($log->getChunkFormat() === $format_text) || $is_force) {
if ($log->canCompressLog()) {
$log->compressLog();
}
}
if ($is_force) {
$log->destroyFile();
}
if (!$log->getFilePHID()) {
$iterator = $log->newDataIterator();
$source = id(new PhabricatorIteratorFileUploadSource())
->setName('harbormaster-log-'.$log->getID().'.log')
->setViewPolicy(PhabricatorPolicies::POLICY_NOONE)
->setMIMEType('application/octet-stream')
->setIterator($iterator);
$file = $source->uploadFile();
$file->attachToObject($log->getPHID());
$log
->setFilePHID($file->getPHID())
->save();
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/worker/HarbormasterBuildWorker.php | src/applications/harbormaster/worker/HarbormasterBuildWorker.php | <?php
/**
* Start a build.
*/
final class HarbormasterBuildWorker extends HarbormasterWorker {
public function renderForDisplay(PhabricatorUser $viewer) {
try {
$build = $this->loadBuild();
} catch (Exception $ex) {
return null;
}
return $viewer->renderHandle($build->getPHID());
}
protected function doWork() {
$viewer = $this->getViewer();
$engine = id(new HarbormasterBuildEngine())
->setViewer($viewer);
$data = $this->getTaskData();
$build_id = idx($data, 'buildID');
if ($build_id) {
$build = $this->loadBuild();
$engine->setBuild($build);
$engine->continueBuild();
} else {
$buildable = $this->loadBuildable();
$engine->updateBuildable($buildable);
}
}
private function loadBuild() {
$data = $this->getTaskData();
$id = idx($data, 'buildID');
$viewer = $this->getViewer();
$build = id(new HarbormasterBuildQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
if (!$build) {
throw new PhabricatorWorkerPermanentFailureException(
pht('Invalid build ID "%s".', $id));
}
return $build;
}
private function loadBuildable() {
$data = $this->getTaskData();
$phid = idx($data, 'buildablePHID');
$viewer = $this->getViewer();
$buildable = id(new HarbormasterBuildableQuery())
->setViewer($viewer)
->withPHIDs(array($phid))
->executeOne();
if (!$buildable) {
throw new PhabricatorWorkerPermanentFailureException(
pht('Invalid buildable PHID "%s".', $phid));
}
return $buildable;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/worker/HarbormasterWorker.php | src/applications/harbormaster/worker/HarbormasterWorker.php | <?php
abstract class HarbormasterWorker extends PhabricatorWorker {
public function getViewer() {
return PhabricatorUser::getOmnipotentUser();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildTargetSearchEngine.php | src/applications/harbormaster/query/HarbormasterBuildTargetSearchEngine.php | <?php
final class HarbormasterBuildTargetSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Harbormaster Build Targets');
}
public function getApplicationClassName() {
return 'PhabricatorHarbormasterApplication';
}
public function newQuery() {
return new HarbormasterBuildTargetQuery();
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorSearchDatasourceField())
->setLabel(pht('Builds'))
->setKey('buildPHIDs')
->setAliases(array('build', 'builds', 'buildPHID'))
->setDescription(
pht('Search for targets of a given build.'))
->setDatasource(new HarbormasterBuildPlanDatasource()),
id(new PhabricatorSearchDateField())
->setLabel(pht('Created After'))
->setKey('createdStart')
->setDescription(
pht('Search for targets created on or after a particular date.')),
id(new PhabricatorSearchDateField())
->setLabel(pht('Created Before'))
->setKey('createdEnd')
->setDescription(
pht('Search for targets created on or before a particular date.')),
id(new PhabricatorSearchDateField())
->setLabel(pht('Started After'))
->setKey('startedStart')
->setDescription(
pht('Search for targets started on or after a particular date.')),
id(new PhabricatorSearchDateField())
->setLabel(pht('Started Before'))
->setKey('startedEnd')
->setDescription(
pht('Search for targets started on or before a particular date.')),
id(new PhabricatorSearchDateField())
->setLabel(pht('Completed After'))
->setKey('completedStart')
->setDescription(
pht('Search for targets completed on or after a particular date.')),
id(new PhabricatorSearchDateField())
->setLabel(pht('Completed Before'))
->setKey('completedEnd')
->setDescription(
pht('Search for targets completed on or before a particular date.')),
id(new PhabricatorSearchStringListField())
->setLabel(pht('Statuses'))
->setKey('statuses')
->setAliases(array('status'))
->setDescription(
pht('Search for targets with given statuses.')),
);
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['buildPHIDs']) {
$query->withBuildPHIDs($map['buildPHIDs']);
}
if ($map['createdStart'] !== null || $map['createdEnd'] !== null) {
$query->withDateCreatedBetween(
$map['createdStart'],
$map['createdEnd']);
}
if ($map['startedStart'] !== null || $map['startedEnd'] !== null) {
$query->withDateStartedBetween(
$map['startedStart'],
$map['startedEnd']);
}
if ($map['completedStart'] !== null || $map['completedEnd'] !== null) {
$query->withDateCompletedBetween(
$map['completedStart'],
$map['completedEnd']);
}
if ($map['statuses']) {
$query->withTargetStatuses($map['statuses']);
}
return $query;
}
protected function getURI($path) {
return '/harbormaster/target/'.$path;
}
protected function getBuiltinQueryNames() {
return array(
'all' => pht('All Targets'),
);
}
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 $builds,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($builds, 'HarbormasterBuildTarget');
// Currently, this only supports the "harbormaster.target.search"
// API method.
throw new PhutilMethodNotImplementedException();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildStepSearchEngine.php | src/applications/harbormaster/query/HarbormasterBuildStepSearchEngine.php | <?php
final class HarbormasterBuildStepSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Harbormaster Build Steps');
}
public function getApplicationClassName() {
return 'PhabricatorHarbormasterApplication';
}
public function newQuery() {
return new HarbormasterBuildStepQuery();
}
protected function buildCustomSearchFields() {
return array();
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
return $query;
}
protected function getURI($path) {
return '/harbormaster/step/'.$path;
}
protected function getBuiltinQueryNames() {
return array(
'all' => pht('All Steps'),
);
}
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 $plans,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($plans, 'HarbormasterBuildStep');
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/harbormaster/query/HarbormasterBuildTargetQuery.php | src/applications/harbormaster/query/HarbormasterBuildTargetQuery.php | <?php
final class HarbormasterBuildTargetQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $buildPHIDs;
private $buildGenerations;
private $dateCreatedMin;
private $dateCreatedMax;
private $dateStartedMin;
private $dateStartedMax;
private $dateCompletedMin;
private $dateCompletedMax;
private $statuses;
private $needBuildSteps;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withBuildPHIDs(array $build_phids) {
$this->buildPHIDs = $build_phids;
return $this;
}
public function withBuildGenerations(array $build_generations) {
$this->buildGenerations = $build_generations;
return $this;
}
public function withDateCreatedBetween($min, $max) {
$this->dateCreatedMin = $min;
$this->dateCreatedMax = $max;
return $this;
}
public function withDateStartedBetween($min, $max) {
$this->dateStartedMin = $min;
$this->dateStartedMax = $max;
return $this;
}
public function withDateCompletedBetween($min, $max) {
$this->dateCompletedMin = $min;
$this->dateCompletedMax = $max;
return $this;
}
public function withTargetStatuses(array $statuses) {
$this->statuses = $statuses;
return $this;
}
public function needBuildSteps($need_build_steps) {
$this->needBuildSteps = $need_build_steps;
return $this;
}
public function newResultObject() {
return new HarbormasterBuildTarget();
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid in (%Ls)',
$this->phids);
}
if ($this->buildPHIDs !== null) {
$where[] = qsprintf(
$conn,
'buildPHID in (%Ls)',
$this->buildPHIDs);
}
if ($this->buildGenerations !== null) {
$where[] = qsprintf(
$conn,
'buildGeneration in (%Ld)',
$this->buildGenerations);
}
if ($this->dateCreatedMin !== null) {
$where[] = qsprintf(
$conn,
'dateCreated >= %d',
$this->dateCreatedMin);
}
if ($this->dateCreatedMax !== null) {
$where[] = qsprintf(
$conn,
'dateCreated <= %d',
$this->dateCreatedMax);
}
if ($this->dateStartedMin !== null) {
$where[] = qsprintf(
$conn,
'dateStarted >= %d',
$this->dateStartedMin);
}
if ($this->dateStartedMax !== null) {
$where[] = qsprintf(
$conn,
'dateStarted <= %d',
$this->dateStartedMax);
}
if ($this->dateCompletedMin !== null) {
$where[] = qsprintf(
$conn,
'dateCompleted >= %d',
$this->dateCompletedMin);
}
if ($this->dateCompletedMax !== null) {
$where[] = qsprintf(
$conn,
'dateCompleted <= %d',
$this->dateCompletedMax);
}
if ($this->statuses !== null) {
$where[] = qsprintf(
$conn,
'targetStatus IN (%Ls)',
$this->statuses);
}
return $where;
}
protected function didFilterPage(array $page) {
if ($this->needBuildSteps) {
$step_phids = array();
foreach ($page as $target) {
$step_phids[] = $target->getBuildStepPHID();
}
$steps = id(new HarbormasterBuildStepQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withPHIDs($step_phids)
->execute();
$steps = mpull($steps, null, 'getPHID');
foreach ($page as $target) {
$target->attachBuildStep(
idx($steps, $target->getBuildStepPHID()));
}
}
return $page;
}
protected function willFilterPage(array $page) {
$builds = array();
$build_phids = array_filter(mpull($page, 'getBuildPHID'));
if ($build_phids) {
$builds = id(new PhabricatorObjectQuery())
->setViewer($this->getViewer())
->withPHIDs($build_phids)
->setParentQuery($this)
->execute();
$builds = mpull($builds, null, 'getPHID');
}
foreach ($page as $key => $build_target) {
$build_phid = $build_target->getBuildPHID();
if (empty($builds[$build_phid])) {
unset($page[$key]);
continue;
}
$build_target->attachBuild($builds[$build_phid]);
}
return $page;
}
public function getQueryApplicationClass() {
return 'PhabricatorHarbormasterApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildableTransactionQuery.php | src/applications/harbormaster/query/HarbormasterBuildableTransactionQuery.php | <?php
final class HarbormasterBuildableTransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new HarbormasterBuildableTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildPlanTransactionQuery.php | src/applications/harbormaster/query/HarbormasterBuildPlanTransactionQuery.php | <?php
final class HarbormasterBuildPlanTransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new HarbormasterBuildPlanTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildableQuery.php | src/applications/harbormaster/query/HarbormasterBuildableQuery.php | <?php
final class HarbormasterBuildableQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $buildablePHIDs;
private $containerPHIDs;
private $statuses;
private $manualBuildables;
private $needContainerObjects;
private $needBuilds;
private $needTargets;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withBuildablePHIDs(array $buildable_phids) {
$this->buildablePHIDs = $buildable_phids;
return $this;
}
public function withContainerPHIDs(array $container_phids) {
$this->containerPHIDs = $container_phids;
return $this;
}
public function withManualBuildables($manual) {
$this->manualBuildables = $manual;
return $this;
}
public function needContainerObjects($need) {
$this->needContainerObjects = $need;
return $this;
}
public function withStatuses(array $statuses) {
$this->statuses = $statuses;
return $this;
}
public function needBuilds($need) {
$this->needBuilds = $need;
return $this;
}
public function needTargets($need) {
$this->needTargets = $need;
return $this;
}
public function newResultObject() {
return new HarbormasterBuildable();
}
protected function willFilterPage(array $page) {
$buildables = array();
$buildable_phids = array_filter(mpull($page, 'getBuildablePHID'));
if ($buildable_phids) {
$buildables = id(new PhabricatorObjectQuery())
->setViewer($this->getViewer())
->withPHIDs($buildable_phids)
->setParentQuery($this)
->execute();
$buildables = mpull($buildables, null, 'getPHID');
}
foreach ($page as $key => $buildable) {
$buildable_phid = $buildable->getBuildablePHID();
if (empty($buildables[$buildable_phid])) {
unset($page[$key]);
continue;
}
$buildable->attachBuildableObject($buildables[$buildable_phid]);
}
return $page;
}
protected function didFilterPage(array $page) {
if ($this->needContainerObjects) {
$container_phids = array_filter(mpull($page, 'getContainerPHID'));
if ($container_phids) {
$containers = id(new PhabricatorObjectQuery())
->setViewer($this->getViewer())
->withPHIDs($container_phids)
->setParentQuery($this)
->execute();
$containers = mpull($containers, null, 'getPHID');
} else {
$containers = array();
}
foreach ($page as $key => $buildable) {
$container_phid = $buildable->getContainerPHID();
$buildable->attachContainerObject(idx($containers, $container_phid));
}
}
if ($this->needBuilds || $this->needTargets) {
$builds = id(new HarbormasterBuildQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withBuildablePHIDs(mpull($page, 'getPHID'))
->needBuildTargets($this->needTargets)
->execute();
$builds = mgroup($builds, 'getBuildablePHID');
foreach ($page as $key => $buildable) {
$buildable->attachBuilds(idx($builds, $buildable->getPHID(), array()));
}
}
return $page;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->buildablePHIDs !== null) {
$where[] = qsprintf(
$conn,
'buildablePHID IN (%Ls)',
$this->buildablePHIDs);
}
if ($this->containerPHIDs !== null) {
$where[] = qsprintf(
$conn,
'containerPHID in (%Ls)',
$this->containerPHIDs);
}
if ($this->statuses !== null) {
$where[] = qsprintf(
$conn,
'buildableStatus in (%Ls)',
$this->statuses);
}
if ($this->manualBuildables !== null) {
$where[] = qsprintf(
$conn,
'isManualBuildable = %d',
(int)$this->manualBuildables);
}
return $where;
}
public function getQueryApplicationClass() {
return 'PhabricatorHarbormasterApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildMessageQuery.php | src/applications/harbormaster/query/HarbormasterBuildMessageQuery.php | <?php
final class HarbormasterBuildMessageQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $receiverPHIDs;
private $consumed;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withReceiverPHIDs(array $phids) {
$this->receiverPHIDs = $phids;
return $this;
}
public function withConsumed($consumed) {
$this->consumed = $consumed;
return $this;
}
public function newResultObject() {
return new HarbormasterBuildMessage();
}
protected function willFilterPage(array $page) {
$receiver_phids = array_filter(mpull($page, 'getReceiverPHID'));
if ($receiver_phids) {
$receivers = id(new PhabricatorObjectQuery())
->setViewer($this->getViewer())
->withPHIDs($receiver_phids)
->setParentQuery($this)
->execute();
$receivers = mpull($receivers, null, 'getPHID');
} else {
$receivers = array();
}
foreach ($page as $key => $message) {
$receiver_phid = $message->getReceiverPHID();
if (empty($receivers[$receiver_phid])) {
unset($page[$key]);
$this->didRejectResult($message);
continue;
}
$message->attachReceiver($receivers[$receiver_phid]);
}
return $page;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->receiverPHIDs !== null) {
$where[] = qsprintf(
$conn,
'receiverPHID IN (%Ls)',
$this->receiverPHIDs);
}
if ($this->consumed !== null) {
$where[] = qsprintf(
$conn,
'isConsumed = %d',
(int)$this->consumed);
}
return $where;
}
public function getQueryApplicationClass() {
return 'PhabricatorHarbormasterApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildArtifactQuery.php | src/applications/harbormaster/query/HarbormasterBuildArtifactQuery.php | <?php
final class HarbormasterBuildArtifactQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $buildTargetPHIDs;
private $artifactTypes;
private $artifactIndexes;
private $keyBuildPHID;
private $keyBuildGeneration;
private $isReleased;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withBuildTargetPHIDs(array $build_target_phids) {
$this->buildTargetPHIDs = $build_target_phids;
return $this;
}
public function withArtifactTypes(array $artifact_types) {
$this->artifactTypes = $artifact_types;
return $this;
}
public function withArtifactIndexes(array $artifact_indexes) {
$this->artifactIndexes = $artifact_indexes;
return $this;
}
public function withIsReleased($released) {
$this->isReleased = $released;
return $this;
}
public function newResultObject() {
return new HarbormasterBuildArtifact();
}
protected function willFilterPage(array $page) {
$build_targets = array();
$build_target_phids = array_filter(mpull($page, 'getBuildTargetPHID'));
if ($build_target_phids) {
$build_targets = id(new HarbormasterBuildTargetQuery())
->setViewer($this->getViewer())
->withPHIDs($build_target_phids)
->setParentQuery($this)
->execute();
$build_targets = mpull($build_targets, null, 'getPHID');
}
foreach ($page as $key => $build_log) {
$build_target_phid = $build_log->getBuildTargetPHID();
if (empty($build_targets[$build_target_phid])) {
unset($page[$key]);
continue;
}
$build_log->attachBuildTarget($build_targets[$build_target_phid]);
}
return $page;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->buildTargetPHIDs !== null) {
$where[] = qsprintf(
$conn,
'buildTargetPHID IN (%Ls)',
$this->buildTargetPHIDs);
}
if ($this->artifactTypes !== null) {
$where[] = qsprintf(
$conn,
'artifactType in (%Ls)',
$this->artifactTypes);
}
if ($this->artifactIndexes !== null) {
$where[] = qsprintf(
$conn,
'artifactIndex IN (%Ls)',
$this->artifactIndexes);
}
if ($this->isReleased !== null) {
$where[] = qsprintf(
$conn,
'isReleased = %d',
(int)$this->isReleased);
}
return $where;
}
public function getQueryApplicationClass() {
return 'PhabricatorHarbormasterApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildUnitMessageQuery.php | src/applications/harbormaster/query/HarbormasterBuildUnitMessageQuery.php | <?php
final class HarbormasterBuildUnitMessageQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $targetPHIDs;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withBuildTargetPHIDs(array $target_phids) {
$this->targetPHIDs = $target_phids;
return $this;
}
public function newResultObject() {
return new HarbormasterBuildUnitMessage();
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid in (%Ls)',
$this->phids);
}
if ($this->targetPHIDs !== null) {
$where[] = qsprintf(
$conn,
'buildTargetPHID in (%Ls)',
$this->targetPHIDs);
}
return $where;
}
protected function didFilterPage(array $messages) {
$indexes = array();
foreach ($messages as $message) {
$index = $message->getNameIndex();
if (strlen($index)) {
$indexes[$index] = $index;
}
}
if ($indexes) {
$map = HarbormasterString::newIndexMap($indexes);
foreach ($messages as $message) {
$index = $message->getNameIndex();
if (!strlen($index)) {
continue;
}
$name = idx($map, $index);
if ($name === null) {
$name = pht('Unknown Unit Message ("%s")', $index);
}
$message->setName($name);
}
}
return $messages;
}
public function getQueryApplicationClass() {
return 'PhabricatorHarbormasterApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildPlanSearchEngine.php | src/applications/harbormaster/query/HarbormasterBuildPlanSearchEngine.php | <?php
final class HarbormasterBuildPlanSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Harbormaster Build Plans');
}
public function getApplicationClassName() {
return 'PhabricatorHarbormasterApplication';
}
public function newQuery() {
return new HarbormasterBuildPlanQuery();
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorSearchTextField())
->setLabel(pht('Name Contains'))
->setKey('match')
->setDescription(pht('Search for namespaces by name substring.')),
id(new PhabricatorSearchCheckboxesField())
->setLabel(pht('Status'))
->setKey('status')
->setAliases(array('statuses'))
->setOptions(
array(
HarbormasterBuildPlan::STATUS_ACTIVE => pht('Active'),
HarbormasterBuildPlan::STATUS_DISABLED => pht('Disabled'),
)),
);
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['match'] !== null) {
$query->withNameNgrams($map['match']);
}
if ($map['status']) {
$query->withStatuses($map['status']);
}
return $query;
}
protected function getURI($path) {
return '/harbormaster/plan/'.$path;
}
protected function getBuiltinQueryNames() {
return array(
'active' => pht('Active Plans'),
'all' => pht('All Plans'),
);
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'active':
return $query->setParameter(
'status',
array(
HarbormasterBuildPlan::STATUS_ACTIVE,
));
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $plans,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($plans, 'HarbormasterBuildPlan');
$viewer = $this->requireViewer();
if ($plans) {
$edge_query = id(new PhabricatorEdgeQuery())
->withSourcePHIDs(mpull($plans, 'getPHID'))
->withEdgeTypes(
array(
PhabricatorProjectObjectHasProjectEdgeType::EDGECONST,
));
$edge_query->execute();
}
$list = new PHUIObjectItemListView();
foreach ($plans as $plan) {
$id = $plan->getID();
$item = id(new PHUIObjectItemView())
->setObjectName(pht('Plan %d', $id))
->setHeader($plan->getName());
if ($plan->isDisabled()) {
$item->setDisabled(true);
}
if ($plan->isAutoplan()) {
$item->addIcon('fa-lock grey', pht('Autoplan'));
}
$item->setHref($this->getApplicationURI("plan/{$id}/"));
$phid = $plan->getPHID();
$project_phids = $edge_query->getDestinationPHIDs(array($phid));
$project_handles = $viewer->loadHandles($project_phids);
$item->addAttribute(
id(new PHUIHandleTagListView())
->setLimit(4)
->setNoDataString(pht('No Projects'))
->setSlim(true)
->setHandles($project_handles));
$list->addItem($item);
}
$result = new PhabricatorApplicationSearchResultView();
$result->setObjectList($list);
$result->setNoDataString(pht('No build plans 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/harbormaster/query/HarbormasterBuildStepTransactionQuery.php | src/applications/harbormaster/query/HarbormasterBuildStepTransactionQuery.php | <?php
final class HarbormasterBuildStepTransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new HarbormasterBuildStepTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildTransactionQuery.php | src/applications/harbormaster/query/HarbormasterBuildTransactionQuery.php | <?php
final class HarbormasterBuildTransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new HarbormasterBuildTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildLogSearchEngine.php | src/applications/harbormaster/query/HarbormasterBuildLogSearchEngine.php | <?php
final class HarbormasterBuildLogSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Harbormaster Build Logs');
}
public function getApplicationClassName() {
return 'PhabricatorHarbormasterApplication';
}
public function newQuery() {
return new HarbormasterBuildLogQuery();
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorPHIDsSearchField())
->setLabel(pht('Build Targets'))
->setKey('buildTargetPHIDs')
->setAliases(
array(
'buildTargetPHID',
'buildTargets',
'buildTarget',
'targetPHIDs',
'targetPHID',
'targets',
'target',
))
->setDescription(
pht('Search for logs that belong to a particular build target.')),
);
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['buildTargetPHIDs']) {
$query->withBuildTargetPHIDs($map['buildTargetPHIDs']);
}
return $query;
}
protected function getURI($path) {
return '/harbormaster/log/'.$path;
}
protected function getBuiltinQueryNames() {
return array(
'all' => pht('All Builds'),
);
}
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 $builds,
PhabricatorSavedQuery $query,
array $handles) {
// For now, this SearchEngine is only for driving the API.
throw new PhutilMethodNotImplementedException();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildableSearchEngine.php | src/applications/harbormaster/query/HarbormasterBuildableSearchEngine.php | <?php
final class HarbormasterBuildableSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Harbormaster Buildables');
}
public function getApplicationClassName() {
return 'PhabricatorHarbormasterApplication';
}
public function newQuery() {
return new HarbormasterBuildableQuery();
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorSearchStringListField())
->setKey('objectPHIDs')
->setAliases(array('objects'))
->setLabel(pht('Objects'))
->setPlaceholder(pht('rXabcdef, PHID-DIFF-1234, ...'))
->setDescription(pht('Search for builds of particular objects.')),
id(new PhabricatorSearchStringListField())
->setKey('containerPHIDs')
->setAliases(array('containers'))
->setLabel(pht('Containers'))
->setPlaceholder(pht('rXYZ, R123, D456, ...'))
->setDescription(
pht('Search for builds by containing revision or repository.')),
id(new PhabricatorSearchCheckboxesField())
->setKey('statuses')
->setLabel(pht('Statuses'))
->setOptions(HarbormasterBuildableStatus::getOptionMap())
->setDescription(pht('Search for builds by buildable status.')),
id(new PhabricatorSearchThreeStateField())
->setLabel(pht('Manual'))
->setKey('manual')
->setDescription(
pht('Search for only manual or automatic buildables.'))
->setOptions(
pht('(Show All)'),
pht('Show Only Manual Builds'),
pht('Show Only Automated Builds')),
);
}
private function resolvePHIDs(array $names) {
$viewer = $this->requireViewer();
$objects = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withNames($names)
->execute();
// TODO: Instead of using string lists, we should ideally be using some
// kind of smart field with resolver logic that can help users type the
// right stuff. For now, just return a bogus value here so nothing matches
// but the form doesn't explode.
if (!$objects) {
return array('-');
}
return mpull($objects, 'getPHID');
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['objectPHIDs']) {
$phids = $this->resolvePHIDs($map['objectPHIDs']);
if ($phids) {
$query->withBuildablePHIDs($phids);
}
}
if ($map['containerPHIDs']) {
$phids = $this->resolvePHIDs($map['containerPHIDs']);
if ($phids) {
$query->withContainerPHIDs($phids);
}
}
if ($map['statuses']) {
$query->withStatuses($map['statuses']);
}
if ($map['manual'] !== null) {
$query->withManualBuildables($map['manual']);
}
return $query;
}
protected function getURI($path) {
return '/harbormaster/'.$path;
}
protected function getBuiltinQueryNames() {
return array(
'all' => pht('All Buildables'),
);
}
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 $buildables,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($buildables, 'HarbormasterBuildable');
$viewer = $this->requireViewer();
$phids = array();
foreach ($buildables as $buildable) {
$phids[] = $buildable->getBuildableObject()
->getHarbormasterBuildableDisplayPHID();
$phids[] = $buildable->getContainerPHID();
$phids[] = $buildable->getBuildablePHID();
}
$handles = $viewer->loadHandles($phids);
$list = new PHUIObjectItemListView();
foreach ($buildables as $buildable) {
$id = $buildable->getID();
$display_phid = $buildable->getBuildableObject()
->getHarbormasterBuildableDisplayPHID();
$container_phid = $buildable->getContainerPHID();
$buildable_phid = $buildable->getBuildablePHID();
$item = id(new PHUIObjectItemView())
->setObjectName(pht('Buildable %d', $buildable->getID()));
if ($display_phid) {
$handle = $handles[$display_phid];
$item->setHeader($handle->getFullName());
}
if ($container_phid && ($container_phid != $display_phid)) {
$handle = $handles[$container_phid];
$item->addAttribute($handle->getName());
}
if ($buildable_phid && ($buildable_phid != $display_phid)) {
$handle = $handles[$buildable_phid];
$item->addAttribute($handle->getFullName());
}
$item->setHref($buildable->getURI());
if ($buildable->getIsManualBuildable()) {
$item->addIcon('fa-wrench grey', pht('Manual'));
}
$status_icon = $buildable->getStatusIcon();
$status_color = $buildable->getStatusColor();
$status_label = $buildable->getStatusDisplayName();
$item->setStatusIcon("{$status_icon} {$status_color}", $status_label);
$list->addItem($item);
}
$result = new PhabricatorApplicationSearchResultView();
$result->setObjectList($list);
$result->setNoDataString(pht('No buildables 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/harbormaster/query/HarbormasterBuildStepQuery.php | src/applications/harbormaster/query/HarbormasterBuildStepQuery.php | <?php
final class HarbormasterBuildStepQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $buildPlanPHIDs;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withBuildPlanPHIDs(array $phids) {
$this->buildPlanPHIDs = $phids;
return $this;
}
public function newResultObject() {
return new HarbormasterBuildStep();
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid in (%Ls)',
$this->phids);
}
if ($this->buildPlanPHIDs !== null) {
$where[] = qsprintf(
$conn,
'buildPlanPHID in (%Ls)',
$this->buildPlanPHIDs);
}
return $where;
}
protected function willFilterPage(array $page) {
$plans = array();
$buildplan_phids = array_filter(mpull($page, 'getBuildPlanPHID'));
if ($buildplan_phids) {
$plans = id(new PhabricatorObjectQuery())
->setViewer($this->getViewer())
->withPHIDs($buildplan_phids)
->setParentQuery($this)
->execute();
$plans = mpull($plans, null, 'getPHID');
}
foreach ($page as $key => $build) {
$buildable_phid = $build->getBuildPlanPHID();
if (empty($plans[$buildable_phid])) {
unset($page[$key]);
continue;
}
$build->attachBuildPlan($plans[$buildable_phid]);
}
return $page;
}
public function getQueryApplicationClass() {
return 'PhabricatorHarbormasterApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildQuery.php | src/applications/harbormaster/query/HarbormasterBuildQuery.php | <?php
final class HarbormasterBuildQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $buildStatuses;
private $buildablePHIDs;
private $buildPlanPHIDs;
private $initiatorPHIDs;
private $needBuildTargets;
private $autobuilds;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withBuildStatuses(array $build_statuses) {
$this->buildStatuses = $build_statuses;
return $this;
}
public function withBuildablePHIDs(array $buildable_phids) {
$this->buildablePHIDs = $buildable_phids;
return $this;
}
public function withBuildPlanPHIDs(array $build_plan_phids) {
$this->buildPlanPHIDs = $build_plan_phids;
return $this;
}
public function withInitiatorPHIDs(array $initiator_phids) {
$this->initiatorPHIDs = $initiator_phids;
return $this;
}
public function withAutobuilds($with_autobuilds) {
$this->autobuilds = $with_autobuilds;
return $this;
}
public function needBuildTargets($need_targets) {
$this->needBuildTargets = $need_targets;
return $this;
}
public function newResultObject() {
return new HarbormasterBuild();
}
protected function willFilterPage(array $page) {
$buildables = array();
$buildable_phids = array_filter(mpull($page, 'getBuildablePHID'));
if ($buildable_phids) {
$buildables = id(new PhabricatorObjectQuery())
->setViewer($this->getViewer())
->withPHIDs($buildable_phids)
->setParentQuery($this)
->execute();
$buildables = mpull($buildables, null, 'getPHID');
}
foreach ($page as $key => $build) {
$buildable_phid = $build->getBuildablePHID();
if (empty($buildables[$buildable_phid])) {
unset($page[$key]);
continue;
}
$build->attachBuildable($buildables[$buildable_phid]);
}
return $page;
}
protected function didFilterPage(array $page) {
$plans = array();
$plan_phids = array_filter(mpull($page, 'getBuildPlanPHID'));
if ($plan_phids) {
$plans = id(new PhabricatorObjectQuery())
->setViewer($this->getViewer())
->withPHIDs($plan_phids)
->setParentQuery($this)
->execute();
$plans = mpull($plans, null, 'getPHID');
}
foreach ($page as $key => $build) {
$plan_phid = $build->getBuildPlanPHID();
$build->attachBuildPlan(idx($plans, $plan_phid));
}
$build_phids = mpull($page, 'getPHID');
$messages = id(new HarbormasterBuildMessage())->loadAllWhere(
'receiverPHID IN (%Ls) AND isConsumed = 0 ORDER BY id ASC',
$build_phids);
$messages = mgroup($messages, 'getReceiverPHID');
foreach ($page as $build) {
$unprocessed_messages = idx($messages, $build->getPHID(), array());
$build->attachUnprocessedMessages($unprocessed_messages);
}
if ($this->needBuildTargets) {
$targets = id(new HarbormasterBuildTargetQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withBuildPHIDs($build_phids)
->execute();
// TODO: Some day, when targets have dependencies, we should toposort
// these. For now, just put them into chronological order.
$targets = array_reverse($targets);
$targets = mgroup($targets, 'getBuildPHID');
foreach ($page as $build) {
$build_targets = idx($targets, $build->getPHID(), array());
foreach ($build_targets as $phid => $target) {
if ($target->getBuildGeneration() !== $build->getBuildGeneration()) {
unset($build_targets[$phid]);
}
}
$build->attachBuildTargets($build_targets);
}
}
return $page;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'b.id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'b.phid in (%Ls)',
$this->phids);
}
if ($this->buildStatuses !== null) {
$where[] = qsprintf(
$conn,
'b.buildStatus in (%Ls)',
$this->buildStatuses);
}
if ($this->buildablePHIDs !== null) {
$where[] = qsprintf(
$conn,
'b.buildablePHID IN (%Ls)',
$this->buildablePHIDs);
}
if ($this->buildPlanPHIDs !== null) {
$where[] = qsprintf(
$conn,
'b.buildPlanPHID IN (%Ls)',
$this->buildPlanPHIDs);
}
if ($this->initiatorPHIDs !== null) {
$where[] = qsprintf(
$conn,
'b.initiatorPHID IN (%Ls)',
$this->initiatorPHIDs);
}
if ($this->autobuilds !== null) {
if ($this->autobuilds) {
$where[] = qsprintf(
$conn,
'p.planAutoKey IS NOT NULL');
} else {
$where[] = qsprintf(
$conn,
'p.planAutoKey IS NULL');
}
}
return $where;
}
protected function buildJoinClauseParts(AphrontDatabaseConnection $conn) {
$joins = parent::buildJoinClauseParts($conn);
if ($this->shouldJoinPlanTable()) {
$joins[] = qsprintf(
$conn,
'JOIN %T p ON b.buildPlanPHID = p.phid',
id(new HarbormasterBuildPlan())->getTableName());
}
return $joins;
}
private function shouldJoinPlanTable() {
if ($this->autobuilds !== null) {
return true;
}
return false;
}
public function getQueryApplicationClass() {
return 'PhabricatorHarbormasterApplication';
}
protected function getPrimaryTableAlias() {
return 'b';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildPlanQuery.php | src/applications/harbormaster/query/HarbormasterBuildPlanQuery.php | <?php
final class HarbormasterBuildPlanQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $statuses;
private $datasourceQuery;
private $planAutoKeys;
private $needBuildSteps;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withStatuses(array $statuses) {
$this->statuses = $statuses;
return $this;
}
public function withDatasourceQuery($query) {
$this->datasourceQuery = $query;
return $this;
}
public function withPlanAutoKeys(array $keys) {
$this->planAutoKeys = $keys;
return $this;
}
public function withNameNgrams($ngrams) {
return $this->withNgramsConstraint(
new HarbormasterBuildPlanNameNgrams(),
$ngrams);
}
public function needBuildSteps($need) {
$this->needBuildSteps = $need;
return $this;
}
public function newResultObject() {
return new HarbormasterBuildPlan();
}
protected function didFilterPage(array $page) {
if ($this->needBuildSteps) {
$plan_phids = mpull($page, 'getPHID');
$steps = id(new HarbormasterBuildStepQuery())
->setParentQuery($this)
->setViewer($this->getViewer())
->withBuildPlanPHIDs($plan_phids)
->execute();
$steps = mgroup($steps, 'getBuildPlanPHID');
foreach ($page as $plan) {
$plan_steps = idx($steps, $plan->getPHID(), array());
$plan->attachBuildSteps($plan_steps);
}
}
return $page;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'plan.id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'plan.phid IN (%Ls)',
$this->phids);
}
if ($this->statuses !== null) {
$where[] = qsprintf(
$conn,
'plan.planStatus IN (%Ls)',
$this->statuses);
}
if (!phutil_nonempty_string($this->datasourceQuery)) {
$where[] = qsprintf(
$conn,
'plan.name LIKE %>',
$this->datasourceQuery);
}
if ($this->planAutoKeys !== null) {
$where[] = qsprintf(
$conn,
'plan.planAutoKey IN (%Ls)',
$this->planAutoKeys);
}
return $where;
}
protected function getPrimaryTableAlias() {
return 'plan';
}
public function getQueryApplicationClass() {
return 'PhabricatorHarbormasterApplication';
}
public function getOrderableColumns() {
return parent::getOrderableColumns() + array(
'name' => array(
'column' => 'name',
'type' => 'string',
'reverse' => true,
),
);
}
protected function newPagingMapFromPartialObject($object) {
return array(
'id' => (int)$object->getID(),
'name' => $object->getName(),
);
}
public function getBuiltinOrders() {
return array(
'name' => array(
'vector' => array('name', 'id'),
'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/harbormaster/query/HarbormasterArtifactSearchEngine.php | src/applications/harbormaster/query/HarbormasterArtifactSearchEngine.php | <?php
final class HarbormasterArtifactSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Harbormaster Artifacts');
}
public function getApplicationClassName() {
return 'PhabricatorHarbormasterApplication';
}
public function newQuery() {
return new HarbormasterBuildArtifactQuery();
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorPHIDsSearchField())
->setLabel(pht('Targets'))
->setKey('buildTargetPHIDs')
->setAliases(
array(
'buildTargetPHID',
'buildTargets',
'buildTarget',
'targetPHIDs',
'targetPHID',
'targets',
'target',
))
->setDescription(
pht('Search for artifacts attached to particular build targets.')),
);
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['buildTargetPHIDs']) {
$query->withBuildTargetPHIDs($map['buildTargetPHIDs']);
}
return $query;
}
protected function getURI($path) {
return '/harbormaster/artifact/'.$path;
}
protected function getBuiltinQueryNames() {
return array(
'all' => pht('All Artifacts'),
);
}
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 $artifacts,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($artifacts, 'HarbormasterBuildArtifact');
$viewer = $this->requireViewer();
$list = new PHUIObjectItemListView();
foreach ($artifacts as $artifact) {
$id = $artifact->getID();
$item = id(new PHUIObjectItemView())
->setObjectName(pht('Artifact %d', $id));
$list->addItem($item);
}
return id(new PhabricatorApplicationSearchResultView())
->setObjectList($list)
->setNoDataString(pht('No artifacts found.'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildLogQuery.php | src/applications/harbormaster/query/HarbormasterBuildLogQuery.php | <?php
final class HarbormasterBuildLogQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $buildPHIDs;
private $buildTargetPHIDs;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withBuildTargetPHIDs(array $build_target_phids) {
$this->buildTargetPHIDs = $build_target_phids;
return $this;
}
public function newResultObject() {
return new HarbormasterBuildLog();
}
protected function willFilterPage(array $page) {
$build_targets = array();
$build_target_phids = array_filter(mpull($page, 'getBuildTargetPHID'));
if ($build_target_phids) {
$build_targets = id(new HarbormasterBuildTargetQuery())
->setViewer($this->getViewer())
->withPHIDs($build_target_phids)
->setParentQuery($this)
->execute();
$build_targets = mpull($build_targets, null, 'getPHID');
}
foreach ($page as $key => $build_log) {
$build_target_phid = $build_log->getBuildTargetPHID();
if (empty($build_targets[$build_target_phid])) {
unset($page[$key]);
continue;
}
$build_log->attachBuildTarget($build_targets[$build_target_phid]);
}
return $page;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->buildTargetPHIDs !== null) {
$where[] = qsprintf(
$conn,
'buildTargetPHID IN (%Ls)',
$this->buildTargetPHIDs);
}
return $where;
}
public function getQueryApplicationClass() {
return 'PhabricatorHarbormasterApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/query/HarbormasterBuildSearchEngine.php | src/applications/harbormaster/query/HarbormasterBuildSearchEngine.php | <?php
final class HarbormasterBuildSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Harbormaster Builds');
}
public function getApplicationClassName() {
return 'PhabricatorHarbormasterApplication';
}
public function newQuery() {
return new HarbormasterBuildQuery();
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorSearchDatasourceField())
->setLabel(pht('Build Plans'))
->setKey('plans')
->setAliases(array('plan'))
->setDescription(
pht('Search for builds running a given build plan.'))
->setDatasource(new HarbormasterBuildPlanDatasource()),
id(new PhabricatorPHIDsSearchField())
->setLabel(pht('Buildables'))
->setKey('buildables')
->setAliases(array('buildable'))
->setDescription(
pht('Search for builds running against particular buildables.')),
id(new PhabricatorSearchDatasourceField())
->setLabel(pht('Statuses'))
->setKey('statuses')
->setAliases(array('status'))
->setDescription(
pht('Search for builds with given statuses.'))
->setDatasource(new HarbormasterBuildStatusDatasource()),
id(new PhabricatorSearchDatasourceField())
->setLabel(pht('Initiators'))
->setKey('initiators')
->setAliases(array('initiator'))
->setDescription(
pht(
'Search for builds started by someone or something in particular.'))
->setDatasource(new HarbormasterBuildInitiatorDatasource()),
);
}
protected function getHiddenFields() {
return array(
'buildables',
);
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['plans']) {
$query->withBuildPlanPHIDs($map['plans']);
}
if ($map['buildables']) {
$query->withBuildablePHIDs($map['buildables']);
}
if ($map['statuses']) {
$query->withBuildStatuses($map['statuses']);
}
if ($map['initiators']) {
$query->withInitiatorPHIDs($map['initiators']);
}
return $query;
}
protected function getURI($path) {
return '/harbormaster/build/'.$path;
}
protected function getBuiltinQueryNames() {
return array(
'initiated' => pht('My Builds'),
'all' => pht('All Builds'),
'waiting' => pht('Waiting'),
'active' => pht('Active'),
'completed' => pht('Completed'),
);
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'initiated':
$viewer = $this->requireViewer();
return $query->setParameter('initiators', array($viewer->getPHID()));
case 'all':
return $query;
case 'waiting':
return $query
->setParameter(
'statuses',
HarbormasterBuildStatus::getWaitingStatusConstants());
case 'active':
return $query
->setParameter(
'statuses',
HarbormasterBuildStatus::getActiveStatusConstants());
case 'completed':
return $query
->setParameter(
'statuses',
HarbormasterBuildStatus::getCompletedStatusConstants());
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $builds,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($builds, 'HarbormasterBuild');
$viewer = $this->requireViewer();
$list = id(new HarbormasterBuildView())
->setViewer($viewer)
->setBuilds($builds)
->newObjectList();
return id(new PhabricatorApplicationSearchResultView())
->setObjectList($list)
->setNoDataString(pht('No builds found.'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/autoplan/HarbormasterBuildArcanistAutoplan.php | src/applications/harbormaster/autoplan/HarbormasterBuildArcanistAutoplan.php | <?php
final class HarbormasterBuildArcanistAutoplan
extends HarbormasterBuildAutoplan {
const PLANKEY = 'arcanist';
public function getAutoplanPlanKey() {
return self::PLANKEY;
}
public function getAutoplanName() {
return pht('arc lint + arc unit');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/autoplan/HarbormasterBuildAutoplan.php | src/applications/harbormaster/autoplan/HarbormasterBuildAutoplan.php | <?php
abstract class HarbormasterBuildAutoplan extends Phobject {
abstract public function getAutoplanPlanKey();
abstract public function getAutoplanName();
public static function getAutoplan($key) {
return idx(self::getAllAutoplans(), $key);
}
public static function getAllAutoplans() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getAutoplanPlanKey')
->execute();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/interface/HarbormasterBuildableInterface.php | src/applications/harbormaster/interface/HarbormasterBuildableInterface.php | <?php
interface HarbormasterBuildableInterface {
/**
* Get the object PHID which best identifies this buildable to humans.
*
* This object is the primary object associated with the buildable in the
* UI. The most human-readable object for a buildable varies: for example,
* for diffs the container (the revision) is more meaningful than the
* buildable (the diff), but for commits the buildable (the commit) is more
* meaningful than the container (the repository).
*
* @return phid Related object PHID most meaningful for human viewers.
*/
public function getHarbormasterBuildableDisplayPHID();
public function getHarbormasterBuildablePHID();
public function getHarbormasterContainerPHID();
public function getBuildVariables();
public function getAvailableBuildVariables();
public function newBuildableEngine();
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/interface/HarbormasterBuildkiteBuildableInterface.php | src/applications/harbormaster/interface/HarbormasterBuildkiteBuildableInterface.php | <?php
/**
* Support for Buildkite.
*/
interface HarbormasterBuildkiteBuildableInterface {
public function getBuildkiteBranch();
public function getBuildkiteCommit();
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/interface/HarbormasterCircleCIBuildableInterface.php | src/applications/harbormaster/interface/HarbormasterCircleCIBuildableInterface.php | <?php
/**
* Support for CircleCI.
*/
interface HarbormasterCircleCIBuildableInterface {
public function getCircleCIGitHubRepositoryURI();
public function getCircleCIBuildIdentifierType();
public function getCircleCIBuildIdentifier();
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/customfield/HarbormasterBuildStepCustomField.php | src/applications/harbormaster/customfield/HarbormasterBuildStepCustomField.php | <?php
abstract class HarbormasterBuildStepCustomField
extends PhabricatorCustomField {
abstract public function getBuildTargetFieldValue();
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/customfield/HarbormasterBuildStepCoreCustomField.php | src/applications/harbormaster/customfield/HarbormasterBuildStepCoreCustomField.php | <?php
final class HarbormasterBuildStepCoreCustomField
extends HarbormasterBuildStepCustomField
implements PhabricatorStandardCustomFieldInterface {
public function getStandardCustomFieldNamespace() {
return 'harbormaster:core';
}
public function createFields($object) {
try {
$impl = $object->getStepImplementation();
} catch (Exception $ex) {
return array();
}
$specs = $impl->getFieldSpecifications();
if ($impl->supportsWaitForMessage()) {
$specs['builtin.next-steps-header'] = array(
'type' => 'header',
'name' => pht('Next Steps'),
);
$specs['builtin.wait-for-message'] = array(
'type' => 'select',
'name' => pht('When Complete'),
'instructions' => pht(
'After completing this build step Harbormaster can continue the '.
'build normally, or it can pause the build and wait for a message. '.
'If you are using this build step to trigger some work in an '.
'external system, you may want wait for that system to perform '.
'the work and report results back.'.
"\n\n".
'If you select **Continue Build Normally**, the build plan will '.
'proceed once this step finishes.'.
"\n\n".
'If you select **Wait For Message**, the build plan will pause '.
'indefinitely once this step finishes. To resume the build, an '.
'external system must call `harbormaster.sendmessage` with the '.
'build target PHID, and either `"pass"` or `"fail"` to indicate '.
'the result for this step. After the result is recorded, the build '.
'plan will resume.'),
'options' => array(
'continue' => pht('Continue Build Normally'),
'wait' => pht('Wait For Message'),
),
);
}
return PhabricatorStandardCustomField::buildStandardFields($this, $specs);
}
public function shouldUseStorage() {
return false;
}
public function readValueFromObject(PhabricatorCustomFieldInterface $object) {
$key = $this->getProxy()->getRawStandardFieldKey();
$this->setValueFromStorage($object->getDetail($key));
}
public function applyApplicationTransactionInternalEffects(
PhabricatorApplicationTransaction $xaction) {
$object = $this->getObject();
$key = $this->getProxy()->getRawStandardFieldKey();
$this->setValueFromApplicationTransactions($xaction->getNewValue());
$value = $this->getValueForStorage();
$object->setDetail($key, $value);
}
public function getBuildTargetFieldValue() {
return $this->getProxy()->getFieldValue();
}
}
| 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.