public function render($hidden = true) { $app = $this->app; $yaml = $this->yaml; $html = ''; $filters = coalesce($yaml['filters']); if (!$filters) { return ''; } foreach ($filters as $filter) { $type = element('type', $filter); $custom = element('custom', $filter); $attributes = element('attributes', $filter); $permission = element('permission', $filter); if ($permission && !$app['acl']->allow($permission)) { continue; } if ($custom) { $class = element('class', $custom); $action = element('action', $custom); $response = call_user_func_array([$class, $action], [$app]); $html .= coalesce($response['html']); } else { $html .= $this->{$type}($attributes); } } return $html . $this->renderHidden($hidden); }
public function execute(PhutilArgumentParser $args) { $commits = $this->loadCommits($args, 'commits'); if (!$commits) { throw new PhutilArgumentUsageException('Specify one or more commits to resolve users for.'); } $console = PhutilConsole::getConsole(); foreach ($commits as $commit) { $repo = $commit->getRepository(); $name = $repo->formatCommitName($commit->getCommitIdentifier()); $console->writeOut("%s\n", pht('Examining commit %s...', $name)); $ref = id(new DiffusionLowLevelCommitQuery())->setRepository($repo)->withIdentifier($commit->getCommitIdentifier())->execute(); $author = $ref->getAuthor(); $console->writeOut("%s\n", pht('Raw author string: %s', coalesce($author, 'null'))); if ($author !== null) { $handle = $this->resolveUser($commit, $author); if ($handle) { $console->writeOut("%s\n", pht('Phabricator user: %s', $handle->getFullName())); } else { $console->writeOut("%s\n", pht('Unable to resolve a corresponding Phabricator user.')); } } $committer = $ref->getCommitter(); $console->writeOut("%s\n", pht('Raw committer string: %s', coalesce($committer, 'null'))); if ($committer !== null) { $handle = $this->resolveUser($commit, $committer); if ($handle) { $console->writeOut("%s\n", pht('Phabricator user: %s', $handle->getFullName())); } else { $console->writeOut("%s\n", pht('Unable to resolve a corresponding Phabricator user.')); } } } return 0; }
public function view($idOrNodeName = null) { if (!($this->Node = $this->Node->findNode(coalesce($idOrNodeName, @$this->params['name'], @$this->params['id'])))) { return false; } $this->data->set('Node', $this->Node); // add pagetitle and keywords to metatags $this->data->set('pageTitle', $this->Node->getText('headline') . ' - ' . AppController::NAME); if ($tags = $this->Node->getText('tags')) { $this->AppMetaTags->keywords->prependFromArray(preg_split('/[\\s]+/i', $tags)); } // check if node has any children if ($this->Node->level == 2) { $this->Node->unbind('MediaFile'); $this->Node->bind('FirstImage', 'hasOne', array('class' => 'MediaImage')); } // find children of the node if ($this->Node->hasChildren() && ($ChildNodes = $this->Node->tree(0, 0))) { $this->data->set('ChildNodes', $ChildNodes); } // custom template if (!$this->Node->isEmpty('template')) { if ($this->Node->get('template') != 'view') { return $this->action($this->Node->get('template'), $this->params); } else { if ($SubMenu = $this->Node->findByName('Projects')) { $this->data->set('SubMenu', $SubMenu->tree(1, 0)); } } } return true; }
protected function main() { global $argv; // get desired job name from console argument list $jobname = coalesce(@$argv[1], false); $jobname = preg_replace('@[^A-Z0-9a-z_-]@i', '', $jobname); if (empty($jobname)) { $this->console->out('AppConsole'); $this->console->out('----------'); $availableJobs = $this->availableJobs(); if (empty($availableJobs)) { $this->console->quit('No tasks found.'); } foreach ($availableJobs as $index => $jobname) { $this->console->out(sprintf('[%s] %s', str_pad($index + 1, strlen(count($availableJobs)), ' ', STR_PAD_LEFT), $jobname)); } $result = trim($this->console->read('Please choose job:')) - 1; if (empty($availableJobs[$result])) { $this->console->quit('invalid job selected'); } $jobname = $availableJobs[$result]; } try { $task = $this->loadTask($jobname, array_slice($argv, 1)); } catch (AppConsoleControllerTaskNotFoundException $e) { $this->console->quit(sprintf('Unable to open task "%s"', $jobname)); } return true; }
/** * Construct an instance of a StyleConfig. * * @param string $name * @param string $description * @param null $finder */ public function __construct($name = 'chroma', $description = 'Chroma default configuration', $finder = null) { parent::__construct($name, $description); $this->finder = coalesce($finder, $this->makeFinder()); $this->level(FixerInterface::NONE_LEVEL); $this->fixers(['encoding', 'short_tag', 'braces', 'elseif', 'eof_ending', 'function_call_space', 'function_declaration', 'indentation', 'line_after_namespace', 'linefeed', 'lowercase_constants', 'lowercase_keywords', 'method_argument_space', 'multiple_use', 'parenthesis', 'php_closing_tag', 'trailing_spaces', 'visibility', 'duplicate_semicolon', 'extra_empty_lines', 'multiline_array_trailing_comma', 'new_with_braces', 'object_operator', 'operators_spaces', 'remove_lines_between_uses', 'return', 'single_array_no_trailing_comma', 'spaces_before_semicolon', 'spaces_cast', 'standardize_not_equal', 'ternary_spaces', 'whitespacy_lines', 'concat_with_spaces', 'multiline_spaces_before_semicolon', 'short_array_syntax', 'remove_leading_slash_use', 'phpdoc_order', 'unused_use', 'single_quote', 'single_blank_line_before_namespace', 'spaces_before_semicolon', 'trim_array_spaces', 'phpdoc_var_without_name', 'phpdoc_to_comment', 'phpdoc_short_description', 'phpdoc_scalar', 'phpdoc_no_empty_return', 'phpdoc_no_access', 'no_empty_lines_after_phpdocs', 'no_blank_lines_after_class_opening', 'join_function_fixer', 'blankline_after_open_tag', 'unalign_double_arrow', 'unalign_equals', 'short_echo_tag', 'php4_constructor']); }
public function body($message = 'No Matching Records Found.') { $app = $this->app; $yaml = $this->yaml; $records = $this->getRecords(); $datas = []; foreach ($records as $record) { $record = (array) $record; $cnt = 0; foreach ($yaml['listing'] as $value) { $body = $value['body']; $permission = element('permission', $value); $custom = element('custom', $body); $row = element('row', $body); $align = element('align', $body); $actions = element('actions', $body); $label = coalesce($record[$row]); if ($permission && !$app['acl']->allow($permission)) { continue; } if ($custom) { $class = element('class', $custom); $action = element('action', $custom); $label = call_user_func_array([$class, $action], [$app, $record]); } elseif ($actions) { $label = $this->renderActions($actions); } $temp[$cnt++] = ['row' => $label, 'align' => $align]; } $datas[] = $temp; } return $app['twig']->render('grid/listing/body.html', ['datas' => $datas, 'message' => $message]); }
protected function execute(InputInterface $input, OutputInterface $output) { $class = $input->getArgument('class'); $total = $input->getArgument('total'); $fs = new Filesystem(); $output = Output::style($output); $filename = getcwd() . "/database/seeds/{$class}.php"; $helper = $this->getHelper('question'); if (!$fs->exists($filename)) { $output->writeln('<error>The seeder class does not exits.</error>'); return; } $output->writeln('<highlight>Running seeder file:</highlight>'); $output->writeln("<info>{$filename}</info>"); $question = new ConfirmationQuestion('<question>Are you sure you want to proceed? (Y/n):</question> ', false); if (!$helper->ask($input, $output, $question)) { return; } include_once __DIR__ . '/../Factory.php'; include_once __DIR__ . '/../Seeder.php'; include_once $filename; $instance = new $class(); $instance->inject($output, $this->app, coalesce($total, 1)); $instance->init(); $instance->run(); }
public static function newFromParts(PhabricatorUser $viewer, $year, $month, $day, $time = null, $enabled = true) { $value = new AphrontFormDateControlValue(); $value->viewer = $viewer; list($value->valueDate, $value->valueTime) = $value->getFormattedDateFromParts($year, $month, $day, coalesce($time, '12:00 AM')); $value->valueEnabled = $enabled; return $value; }
public function renderCommitMessageValue(array $handles) { $id = coalesce($this->revisionID, $this->getObject()->getID()); if (!$id) { return null; } return PhabricatorEnv::getProductionURI('/D' . $id); }
public static function getFullNameForChangeType($type) { static $types = null; if ($types === null) { $types = array(self::TYPE_ADD => pht('Added'), self::TYPE_CHANGE => pht('Modified'), self::TYPE_DELETE => pht('Deleted'), self::TYPE_MOVE_AWAY => pht('Moved Away'), self::TYPE_COPY_AWAY => pht('Copied Away'), self::TYPE_MOVE_HERE => pht('Moved Here'), self::TYPE_COPY_HERE => pht('Copied Here'), self::TYPE_MULTICOPY => pht('Deleted After Multiple Copy'), self::TYPE_MESSAGE => pht('Commit Message'), self::TYPE_CHILD => pht('Contents Modified')); } return idx($types, coalesce($type, '?'), pht('Unknown')); }
function cp_fetch_site_info($site_id = 0) { static $info; if (!isset($info)) { $rsSites = CSite::GetByID(coalesce($site_id, SITE_ID)); $info = $rsSites->Fetch(); } return $info; }
public function __construct($isCritical, $body, array $to = array(), array $from = array(), $subject = NULL, array $files = array()) { parent::__construct($isCritical); $this->to = $to ? $to : array(cp_get_site_email()); $this->from = $from ? $from : array("noreply@{$_SERVER['HTTP_HOST']}"); $this->subject = @coalesce($subject, 'Сообщение на ' . $_SERVER['HTTP_HOST']); $this->body_template = $body; $this->files = $files; require_once $_SERVER['DOCUMENT_ROOT'] . '/lib/php-mailer/PHPMailerAutoload.php'; $this->mailer = new \PHPMailer(); }
public function getText($varname, $default = null) { $languageId = I18n::locale(); $languageModelName = 'Text' . ucFirst(substr($languageId, 0, 2)); if (!isset($this->{$languageModelName})) { $languageModelName = 'Text' . ucfirst(substr(Registry::get('I18n.language'), 0, 2)); } if ($this->{$languageModelName} instanceof Model && $this->{$languageModelName}->hasField($varname)) { return coalesce($this->{$languageModelName}->get($varname), $default, false); } }
public function make() { $app = $this->app; $html = $this->html; foreach ($this->yaml as $menu) { if (!isset($menu['submenu'])) { $html .= $app['twig']->render('menus/parent.html', ['title' => coalesce($menu['title']), 'url' => coalesce($menu['url']), 'icon' => coalesce($menu['icon'])]); } else { $html .= $app['twig']->render('menus/child.html', ['title' => coalesce($menu['title']), 'icon' => coalesce($menu['icon']), 'submenu' => coalesce($menu['submenu'])]); } } $this->html = $html; }
function translateString($originalString) { $langCode = coalesce(@$GLOBALS['SETTINGS']['language'], 'en'); if (!$langCode && !$GLOBALS['SETTINGS']['advanced']['languageDeveloperMode']) { return $originalString; } // skip if no language defined static $translation = array(); // get language dirs list($defaultLangDir, $adminLangDir, $pluginLangDir) = _languageFiles_getDirs(); $isAdminMenu = in_array(@$_REQUEST['menu'], array('admin', 'database', '_codeGenerator')); if ($pluginLangDir) { $tryDirs = array($pluginLangDir, $adminLangDir, $defaultLangDir); } elseif ($isAdminMenu) { $tryDirs = array($adminLangDir, $defaultLangDir); } else { $tryDirs = array($defaultLangDir); } $targetLangDir = $tryDirs[0]; // first dir to try and where language strings are added // load/cache language file and return translation $langFile = "{$langCode}.php"; foreach ($tryDirs as $thisDir) { $thisFilepath = "{$thisDir}/{$langFile}"; // load/cache file if (!array_key_exists($thisFilepath, $translation)) { $translation[$thisFilepath] = _languageFile_load($thisFilepath); } // load string if (array_key_exists($originalString, $translation[$thisFilepath])) { // return translation $string = $translation[$thisFilepath][$originalString]; if ($langCode == 'd|e|b|u|g') { $string = preg_replace("/(?<=\\w)(\\w)/", "|\\1", $string); } // added in v2.50 return $langCode ? $string : $originalString; // v2.53 - if 'default' language selected, return original text here if translation found. If no translation found, return original string below so string can be added to files. } } // if not found, add string if in developer mode and return original if ($GLOBALS['SETTINGS']['advanced']['languageDeveloperMode']) { _languageFiles_addString($defaultLangDir, $targetLangDir, $originalString); } if ($langCode == 'd|e|b|u|g') { $originalString = preg_replace("/(?<=\\w)(\\w)/", "|\\1", $originalString); } // added in v2.50 return $originalString; }
function category_history_recent_changes($list) { $res=sql_query("select * from category where version_tags ? 'date' order by version_tags->'date' desc limit 50"); while($elem=pg_fetch_assoc($res)) { $elem['version_tags']=parse_hstore($elem['version_tags']); $t=new tags(parse_hstore($elem['tags'])); $entry=$elem['version_tags']; $entry['name']=sprintf("%s \"%s\"", lang("category", 1), $t->get_lang("name")); $entry['msg']=coalesce($elem['version_tags']['msg'], "no message"); $entry['plugin']="category"; $entry['href']="javascript:category_show(\"osm:{$elem['category_id']}\", { version: \"{$elem['version']}\"})"; $list[]=$entry; } }
public function loadMailer() { $transportConfig = $this->getConfig('email-transport'); $encryptionMethod = coalesce($transportConfig['encryption']); // 'SSL' and 'TLS' are supported $transport = Swift_SmtpTransport::newInstance($transportConfig['host'], coalesce($transportConfig['port'], 25)); $transport->setUsername($transportConfig['username']); $transport->setPassword($transportConfig['password']); if ($encryptionMethod) { $transport->setEncryption(strtolower($encryptionMethod)); } if ($recipientOverride = coalesce($transportConfig['recipient-override'])) { $transport = new NodeTemplateProjectNS_Email_RecipientOverrideTransport($transport, $recipientOverride); } return Swift_Mailer::newInstance($transport); }
function ezdie() { if (!headers_sent()) { header("HTTP/1.0 500 EZDied"); header("Content-Type: text/plain"); } foreach (func_get_args() as $v) { echo ezformat($v), "\n"; } echo "------- stack trace -------\n"; foreach (debug_backtrace() as $frame) { if (!isset($frame['file']) and !isset($frame['line'])) { continue; } echo " from ", coalesce($frame['file']), ":", coalesce($frame['line']), "\n"; } die; }
function showCopyOptions() { $includedTypes = array('single', 'multi', 'category'); $skippedTables = array('accounts'); foreach (getSortedSchemas() as $tableName => $schema) { if (preg_match("/^_/", $tableName)) { continue; } // skip private tables if (in_array($tableName, $skippedTables)) { continue; } // skip system tables if (!in_array(@$schema['menuType'], $includedTypes)) { continue; } // skip unknown menu types $encodedValue = htmlencode($tableName); $encodedLabel = htmlencode(coalesce(@$schema['menuName'], $tableName)); print "<option value='{$encodedValue}'>{$encodedLabel}</option>\n"; } }
public function execute(PhutilArgumentParser $args) { $commits = $this->loadCommits($args, 'commits'); if (!$commits) { throw new PhutilArgumentUsageException(pht('Specify one or more commits to resolve users for.')); } $console = PhutilConsole::getConsole(); foreach ($commits as $commit) { $repo = $commit->getRepository(); $name = $repo->formatCommitName($commit->getCommitIdentifier()); $console->writeOut("%s\n", pht('Examining commit %s...', $name)); $refs_raw = DiffusionQuery::callConduitWithDiffusionRequest($this->getViewer(), DiffusionRequest::newFromDictionary(array('repository' => $repo, 'user' => $this->getViewer())), 'diffusion.querycommits', array('repositoryPHID' => $repo->getPHID(), 'phids' => array($commit->getPHID()), 'bypassCache' => true)); if (empty($refs_raw['data'])) { throw new Exception(pht('Unable to retrieve details for commit "%s"!', $commit->getPHID())); } $ref = DiffusionCommitRef::newFromConduitResult(head($refs_raw['data'])); $author = $ref->getAuthor(); $console->writeOut("%s\n", pht('Raw author string: %s', coalesce($author, 'null'))); if ($author !== null) { $handle = $this->resolveUser($commit, $author); if ($handle) { $console->writeOut("%s\n", pht('Phabricator user: %s', $handle->getFullName())); } else { $console->writeOut("%s\n", pht('Unable to resolve a corresponding Phabricator user.')); } } $committer = $ref->getCommitter(); $console->writeOut("%s\n", pht('Raw committer string: %s', coalesce($committer, 'null'))); if ($committer !== null) { $handle = $this->resolveUser($commit, $committer); if ($handle) { $console->writeOut("%s\n", pht('Phabricator user: %s', $handle->getFullName())); } else { $console->writeOut("%s\n", pht('Unable to resolve a corresponding Phabricator user.')); } } } return 0; }
public function getDefaultArcanistBranch() { return coalesce($this->getDefaultBranch(), 'svn'); }
public function run() { $source = $this->getSource(); $param = $this->getSourceParam(); try { switch ($source) { case self::SOURCE_PATCH: if ($param == '-') { $patch = @file_get_contents('php://stdin'); if (!strlen($patch)) { throw new ArcanistUsageException(pht('Failed to read patch from stdin!')); } } else { $patch = Filesystem::readFile($param); } $bundle = ArcanistBundle::newFromDiff($patch); break; case self::SOURCE_BUNDLE: $path = $this->getArgument('arcbundle'); $bundle = ArcanistBundle::newFromArcBundle($path); break; case self::SOURCE_REVISION: $bundle = $this->loadRevisionBundleFromConduit($this->getConduit(), $param); break; case self::SOURCE_DIFF: $bundle = $this->loadDiffBundleFromConduit($this->getConduit(), $param); break; } } catch (ConduitClientException $ex) { if ($ex->getErrorCode() == 'ERR-INVALID-SESSION') { // Phabricator is not configured to allow anonymous access to // Differential. $this->authenticateConduit(); return $this->run(); } else { throw $ex; } } $try_encoding = nonempty($this->getArgument('encoding'), null); if (!$try_encoding) { if ($this->requiresConduit()) { try { $try_encoding = $this->getRepositoryEncoding(); } catch (ConduitClientException $e) { $try_encoding = null; } } } if ($try_encoding) { $bundle->setEncoding($try_encoding); } $sanity_check = !$this->getArgument('force', false); // we should update the working copy before we do ANYTHING else to // the working copy if ($this->shouldUpdateWorkingCopy()) { $this->updateWorkingCopy(); } if ($sanity_check) { $this->requireCleanWorkingCopy(); } $repository_api = $this->getRepositoryAPI(); $has_base_revision = $repository_api->hasLocalCommit($bundle->getBaseRevision()); if ($this->canBranch() && ($this->shouldBranch() || $this->shouldCommit() && $has_base_revision)) { if ($repository_api instanceof ArcanistGitAPI) { $original_branch = $repository_api->getBranchName(); } else { if ($repository_api instanceof ArcanistMercurialAPI) { $original_branch = $repository_api->getActiveBookmark(); } } // If we weren't on a branch, then record the ref we'll return to // instead. if ($original_branch === null) { if ($repository_api instanceof ArcanistGitAPI) { $original_branch = $repository_api->getCanonicalRevisionName('HEAD'); } else { if ($repository_api instanceof ArcanistMercurialAPI) { $original_branch = $repository_api->getCanonicalRevisionName('.'); } } } $new_branch = $this->createBranch($bundle, $has_base_revision); } if (!$has_base_revision && $this->shouldApplyDependencies()) { $this->applyDependencies($bundle); } if ($sanity_check) { $this->sanityCheck($bundle); } if ($repository_api instanceof ArcanistSubversionAPI) { $patch_err = 0; $copies = array(); $deletes = array(); $patches = array(); $propset = array(); $adds = array(); $symlinks = array(); $changes = $bundle->getChanges(); foreach ($changes as $change) { $type = $change->getType(); $should_patch = true; $filetype = $change->getFileType(); switch ($filetype) { case ArcanistDiffChangeType::FILE_SYMLINK: $should_patch = false; $symlinks[] = $change; break; } switch ($type) { case ArcanistDiffChangeType::TYPE_MOVE_AWAY: case ArcanistDiffChangeType::TYPE_MULTICOPY: case ArcanistDiffChangeType::TYPE_DELETE: $path = $change->getCurrentPath(); $fpath = $repository_api->getPath($path); if (!@file_exists($fpath)) { $ok = phutil_console_confirm(pht("Patch deletes file '%s', but the file does not exist in " . "the working copy. Continue anyway?", $path)); if (!$ok) { throw new ArcanistUserAbortException(); } } else { $deletes[] = $change->getCurrentPath(); } $should_patch = false; break; case ArcanistDiffChangeType::TYPE_COPY_HERE: case ArcanistDiffChangeType::TYPE_MOVE_HERE: $path = $change->getOldPath(); $fpath = $repository_api->getPath($path); if (!@file_exists($fpath)) { $cpath = $change->getCurrentPath(); if ($type == ArcanistDiffChangeType::TYPE_COPY_HERE) { $verbs = pht('copies'); } else { $verbs = pht('moves'); } $ok = phutil_console_confirm(pht("Patch %s '%s' to '%s', but source path does not exist " . "in the working copy. Continue anyway?", $verbs, $path, $cpath)); if (!$ok) { throw new ArcanistUserAbortException(); } } else { $copies[] = array($change->getOldPath(), $change->getCurrentPath()); } break; case ArcanistDiffChangeType::TYPE_ADD: $adds[] = $change->getCurrentPath(); break; } if ($should_patch) { $cbundle = ArcanistBundle::newFromChanges(array($change)); $patches[$change->getCurrentPath()] = $cbundle->toUnifiedDiff(); $prop_old = $change->getOldProperties(); $prop_new = $change->getNewProperties(); $props = $prop_old + $prop_new; foreach ($props as $key => $ignored) { if (idx($prop_old, $key) !== idx($prop_new, $key)) { $propset[$change->getCurrentPath()][$key] = idx($prop_new, $key); } } } } // Before we start doing anything, create all the directories we're going // to add files to if they don't already exist. foreach ($copies as $copy) { list($src, $dst) = $copy; $this->createParentDirectoryOf($dst); } foreach ($patches as $path => $patch) { $this->createParentDirectoryOf($path); } foreach ($adds as $add) { $this->createParentDirectoryOf($add); } // TODO: The SVN patch workflow likely does not work on windows because // of the (cd ...) stuff. foreach ($copies as $copy) { list($src, $dst) = $copy; passthru(csprintf('(cd %s; svn cp %s %s)', $repository_api->getPath(), ArcanistSubversionAPI::escapeFileNameForSVN($src), ArcanistSubversionAPI::escapeFileNameForSVN($dst))); } foreach ($deletes as $delete) { passthru(csprintf('(cd %s; svn rm %s)', $repository_api->getPath(), ArcanistSubversionAPI::escapeFileNameForSVN($delete))); } foreach ($symlinks as $symlink) { $link_target = $symlink->getSymlinkTarget(); $link_path = $symlink->getCurrentPath(); switch ($symlink->getType()) { case ArcanistDiffChangeType::TYPE_ADD: case ArcanistDiffChangeType::TYPE_CHANGE: case ArcanistDiffChangeType::TYPE_MOVE_HERE: case ArcanistDiffChangeType::TYPE_COPY_HERE: execx('(cd %s && ln -sf %s %s)', $repository_api->getPath(), $link_target, $link_path); break; } } foreach ($patches as $path => $patch) { $err = null; if ($patch) { $tmp = new TempFile(); Filesystem::writeFile($tmp, $patch); passthru(csprintf('(cd %s; patch -p0 < %s)', $repository_api->getPath(), $tmp), $err); } else { passthru(csprintf('(cd %s; touch %s)', $repository_api->getPath(), $path), $err); } if ($err) { $patch_err = max($patch_err, $err); } } foreach ($adds as $add) { passthru(csprintf('(cd %s; svn add %s)', $repository_api->getPath(), ArcanistSubversionAPI::escapeFileNameForSVN($add))); } foreach ($propset as $path => $changes) { foreach ($changes as $prop => $value) { if ($prop == 'unix:filemode') { // Setting this property also changes the file mode. $prop = 'svn:executable'; $value = octdec($value) & 0111 ? 'on' : null; } if ($value === null) { passthru(csprintf('(cd %s; svn propdel %s %s)', $repository_api->getPath(), $prop, ArcanistSubversionAPI::escapeFileNameForSVN($path))); } else { passthru(csprintf('(cd %s; svn propset %s %s %s)', $repository_api->getPath(), $prop, $value, ArcanistSubversionAPI::escapeFileNameForSVN($path))); } } } if ($patch_err == 0) { echo phutil_console_format("<bg:green>** %s **</bg> %s\n", pht('OKAY'), pht('Successfully applied patch to the working copy.')); } else { echo phutil_console_format("\n\n<bg:yellow>** %s **</bg> %s\n", pht('WARNING'), pht("Some hunks could not be applied cleanly by the unix '%s' " . "utility. Your working copy may be different from the revision's " . "base, or you may be in the wrong subdirectory. You can export " . "the raw patch file using '%s', and then try to apply it by " . "fiddling with options to '%s' (particularly, %s), or manually. " . "The output above, from '%s', may be helpful in " . "figuring out what went wrong.", 'patch', 'arc export --unified', 'patch', '-p', 'patch')); } return $patch_err; } else { if ($repository_api instanceof ArcanistGitAPI) { $patchfile = new TempFile(); Filesystem::writeFile($patchfile, $bundle->toGitPatch()); $passthru = new PhutilExecPassthru('git apply --index --reject -- %s', $patchfile); $passthru->setCWD($repository_api->getPath()); $err = $passthru->execute(); if ($err) { echo phutil_console_format("\n<bg:red>** %s **</bg>\n", pht('Patch Failed!')); // NOTE: Git patches may fail if they change the case of a filename // (for instance, from 'example.c' to 'Example.c'). As of now, Git // can not apply these patches on case-insensitive filesystems and // there is no way to build a patch which works. throw new ArcanistUsageException(pht('Unable to apply patch!')); } // in case there were any submodule changes involved $repository_api->execpassthru('submodule update --init --recursive'); if ($this->shouldCommit()) { if ($bundle->getFullAuthor()) { $author_cmd = csprintf('--author=%s', $bundle->getFullAuthor()); } else { $author_cmd = ''; } $commit_message = $this->getCommitMessage($bundle); $future = $repository_api->execFutureLocal('commit -a %C -F - --no-verify', $author_cmd); $future->write($commit_message); $future->resolvex(); $verb = pht('committed'); } else { $verb = pht('applied'); } if ($this->canBranch() && !$this->shouldBranch() && $this->shouldCommit() && $has_base_revision) { $repository_api->execxLocal('checkout %s', $original_branch); $ex = null; try { $repository_api->execxLocal('cherry-pick %s', $new_branch); } catch (Exception $ex) { // do nothing } $repository_api->execxLocal('branch -D %s', $new_branch); if ($ex) { echo phutil_console_format("\n<bg:red>** %s**</bg>\n", pht('Cherry Pick Failed!')); throw $ex; } } echo phutil_console_format("<bg:green>** %s **</bg> %s\n", pht('OKAY'), pht('Successfully %s patch.', $verb)); } else { if ($repository_api instanceof ArcanistMercurialAPI) { $future = $repository_api->execFutureLocal('import --no-commit -'); $future->write($bundle->toGitPatch()); try { $future->resolvex(); } catch (CommandException $ex) { echo phutil_console_format("\n<bg:red>** %s **</bg>\n", pht('Patch Failed!')); $stderr = $ex->getStdErr(); if (preg_match('/case-folding collision/', $stderr)) { echo phutil_console_wrap(phutil_console_format("\n<bg:yellow>** %s **</bg> %s\n", pht('WARNING'), pht("This patch may have failed because it attempts to change " . "the case of a filename (for instance, from '%s' to '%s'). " . "Mercurial cannot apply patches like this on case-insensitive " . "filesystems. You must apply this patch manually.", 'example.c', 'Example.c'))); } throw $ex; } if ($this->shouldCommit()) { $author = coalesce($bundle->getFullAuthor(), $bundle->getAuthorName()); if ($author !== null) { $author_cmd = csprintf('-u %s', $author); } else { $author_cmd = ''; } $commit_message = $this->getCommitMessage($bundle); $future = $repository_api->execFutureLocal('commit %C -l -', $author_cmd); $future->write($commit_message); $future->resolvex(); if (!$this->shouldBranch() && $has_base_revision) { $original_rev = $repository_api->getCanonicalRevisionName($original_branch); $current_parent = $repository_api->getCanonicalRevisionName(hgsprintf('%s^', $new_branch)); $err = 0; if ($original_rev != $current_parent) { list($err) = $repository_api->execManualLocal('rebase --dest %s --rev %s', hgsprintf('%s', $original_branch), hgsprintf('%s', $new_branch)); } $repository_api->execxLocal('bookmark --delete %s', $new_branch); if ($err) { $repository_api->execManualLocal('rebase --abort'); throw new ArcanistUsageException(phutil_console_format("\n<bg:red>** %s**</bg>\n", pht('Rebase onto %s failed!', $original_branch))); } } $verb = pht('committed'); } else { $verb = pht('applied'); } echo phutil_console_format("<bg:green>** %s **</bg> %s\n", pht('OKAY'), pht('Successfully %s patch.', $verb)); } else { throw new Exception(pht('Unknown version control system.')); } } } return 0; }
private function findMercurialPushKeyRefUpdates() { $key_namespace = getenv('HG_NAMESPACE'); if ($key_namespace === 'phases') { // Mercurial changes commit phases as part of normal push operations. We // just ignore these, as they don't seem to represent anything // interesting. return array(); } $key_name = getenv('HG_KEY'); $key_old = getenv('HG_OLD'); if (!strlen($key_old)) { $key_old = null; } $key_new = getenv('HG_NEW'); if (!strlen($key_new)) { $key_new = null; } if ($key_namespace !== 'bookmarks') { throw new Exception(pht("Unknown Mercurial key namespace '%s', with key '%s' (%s -> %s). " . "Rejecting push.", $key_namespace, $key_name, coalesce($key_old, pht('null')), coalesce($key_new, pht('null')))); } if ($key_old === $key_new) { // We get a callback when the bookmark doesn't change. Just ignore this, // as it's a no-op. return array(); } $ref_flags = 0; $merge_base = null; if ($key_old === null) { $ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_ADD; } else { if ($key_new === null) { $ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_DELETE; } else { list($merge_base_raw) = $this->getRepository()->execxLocalCommand('log --template %s --rev %s', '{node}', hgsprintf('ancestor(%s, %s)', $key_old, $key_new)); if (strlen(trim($merge_base_raw))) { $merge_base = trim($merge_base_raw); } if ($merge_base && $merge_base === $key_old) { $ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_APPEND; } else { $ref_flags |= PhabricatorRepositoryPushLog::CHANGEFLAG_REWRITE; } } } $ref_update = $this->newPushLog()->setRefType(PhabricatorRepositoryPushLog::REFTYPE_BOOKMARK)->setRefName($key_name)->setRefOld(coalesce($key_old, self::EMPTY_HASH))->setRefNew(coalesce($key_new, self::EMPTY_HASH))->setChangeFlags($ref_flags); return array($ref_update); }
public function getHeadCommit() { if ($this->resolvedHeadCommit === null) { $this->resolvedHeadCommit = $this->resolveCommit(coalesce($this->symbolicHeadCommit, 'HEAD')); } return $this->resolvedHeadCommit; }
public function testCoalesce() { $this->assertEquals('zebra', coalesce(null, 'zebra')); $this->assertEquals(null, coalesce()); $this->assertEquals(false, coalesce(false, null)); $this->assertEquals(false, coalesce(null, false)); }
public function willSendResponse(AphrontResponse $response) { $request = $this->getRequest(); if ($response instanceof AphrontDialogResponse) { if (!$request->isAjax() && !$request->isQuicksand()) { $dialog = $response->getDialog(); $title = $dialog->getTitle(); $short = $dialog->getShortTitle(); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb(coalesce($short, $title)); $page_content = array($crumbs, $response->buildResponseString()); $view = id(new PhabricatorStandardPageView())->setRequest($request)->setController($this)->setDeviceReady(true)->setTitle($title)->appendChild($page_content); $response = id(new AphrontWebpageResponse())->setContent($view->render())->setHTTPResponseCode($response->getHTTPResponseCode()); } else { $response->getDialog()->setIsStandalone(true); return id(new AphrontAjaxResponse())->setContent(array('dialog' => $response->buildResponseString())); } } else { if ($response instanceof AphrontRedirectResponse) { if ($request->isAjax() || $request->isQuicksand()) { return id(new AphrontAjaxResponse())->setContent(array('redirect' => $response->getURI())); } } } return $response; }
function cg2_listpage_getCode() { $tableName = @$_REQUEST['tableName']; $schema = loadSchema($tableName); $menuName = coalesce(@$schema['menuName'], $tableName); // define variable names $tableRecordsVar = '$' . preg_replace("/[^\\w]/", '_', $tableName) . "Records"; $metaDataVar = '$' . preg_replace("/[^\\w]/", '_', $tableName) . "MetaData"; $recordVar = '$record'; // define getRecords() options $options = array(); $options[] = "'tableName' => '{$tableName}',"; if (@$_REQUEST['howMany'] == 'firstN') { $options[] = "'limit' => '{$_REQUEST['limit']}',"; } else { if (@$_REQUEST['howMany'] == 'paged') { $options[] = "'perPage' => '{$_REQUEST['perPage']}',"; } else { /* default to showing all */ } } if (@$_REQUEST['orderBy'] == 'random') { $options[] = "'orderBy' => 'RAND()',"; } if (@$_REQUEST['showUploads'] == 'all') { $options[] = "'loadUploads' => true,"; } elseif (@$_REQUEST['showUploads'] == 'limit') { $options[] = "'loadUploads' => true,"; } else { $options[] = "'loadUploads' => false,"; } if (@$_REQUEST['allowSearching']) { $options[] = "'allowSearch' => true,"; } else { $options[] = "'allowSearch' => false,"; } $padding = " "; $getRecordsOptions = "\n{$padding}" . implode("\n{$padding}", $options) . "\n "; ### generate code ob_start(); ?> <#php header('Content-type: text/html; charset=utf-8'); #> <#php /* STEP 1: LOAD RECORDS - Copy this PHP code block near the TOP of your page */ <?php cg2_code_loadLibraries(); ?> // load records from '<?php echo $tableName; ?> ' list(<?php echo $tableRecordsVar; ?> , <?php echo $metaDataVar; ?> ) = getRecords(array(<?php echo $getRecordsOptions; ?> )); #><?php cg2_code_header(); cg2_code_instructions('List'); ?> <!-- STEP2: Display Records (Paste this where you want your records to be listed) --> <h1><?php echo $menuName; ?> - <?php echo t('List Page Viewer'); ?> </h1> <#php foreach (<?php echo $tableRecordsVar; ?> as <?php echo $recordVar; ?> ): #> <?php cg2_code_schemaFields($schema, $recordVar, $tableName); if (@$_REQUEST['showUploads']) { cg2_code_uploads($schema, $recordVar); } ?> <hr/> <#php endforeach #> <#php if (!<?php echo $tableRecordsVar; ?> ): #> <?php echo t('No records were found!'); ?> <br/><br/> <#php endif #> <!-- /STEP2: Display Records --> <?php if (@$_REQUEST['howMany'] == 'paged') { ?> <!-- STEP3: Display Page Links (Paste anywhere below "Load Record List") --> <#php if (<?php echo $metaDataVar; ?> ['prevPage']): #> <a href="<#php echo <?php echo $metaDataVar; ?> ['prevPageLink'] #>"><?php echo t('<< prev'); ?> </a> <#php else: #> << prev <#php endif #> - page <#php echo <?php echo $metaDataVar; ?> ['page'] #> of <#php echo <?php echo $metaDataVar; ?> ['totalPages'] #> - <#php if (<?php echo $metaDataVar; ?> ['nextPage']): #> <a href="<#php echo <?php echo $metaDataVar; ?> ['nextPageLink'] #>"><?php echo t('next'); ?> >></a> <#php else: #> next >> <#php endif #> <!-- /STEP3: Display Page Links --> <?php } cg2_code_footer(); ?> <?php // return code $code = ob_get_clean(); return $code; }
public function getDestination() { return coalesce($this->buildDestination, $this->getDefaultDestination()); }
public function __construct(array $argv) { PhutilServiceProfiler::getInstance()->enableDiscardMode(); $original_argv = $argv; $args = new PhutilArgumentParser($argv); $args->setTagline('daemon overseer'); $args->setSynopsis(<<<EOHELP **launch_daemon.php** [__options__] __daemon__ Launch and oversee an instance of __daemon__. EOHELP ); $args->parseStandardArguments(); $args->parsePartial(array(array('name' => 'trace-memory', 'help' => 'Enable debug memory tracing.'), array('name' => 'log', 'param' => 'file', 'help' => 'Send output to __file__.'), array('name' => 'daemonize', 'help' => 'Run in the background.'), array('name' => 'phd', 'param' => 'dir', 'help' => 'Write PID information to __dir__.'), array('name' => 'verbose', 'help' => 'Enable verbose activity logging.'), array('name' => 'load-phutil-library', 'param' => 'library', 'repeat' => true, 'help' => 'Load __library__.'))); $argv = array(); $more = $args->getUnconsumedArgumentVector(); $this->daemon = array_shift($more); if (!$this->daemon) { $args->printHelpAndExit(); } if ($args->getArg('trace')) { $this->traceMode = true; $argv[] = '--trace'; } if ($args->getArg('trace-memory')) { $this->traceMode = true; $this->traceMemory = true; $argv[] = '--trace-memory'; } if ($args->getArg('load-phutil-library')) { foreach ($args->getArg('load-phutil-library') as $library) { $argv[] = '--load-phutil-library=' . $library; } } $log = $args->getArg('log'); if ($log) { ini_set('error_log', $log); $argv[] = '--log=' . $log; } $verbose = $args->getArg('verbose'); if ($verbose) { $this->verbose = true; $argv[] = '--verbose'; } $this->daemonize = $args->getArg('daemonize'); $this->phddir = $args->getArg('phd'); $this->argv = $argv; $this->moreArgs = coalesce($more, array()); error_log("Bringing daemon '{$this->daemon}' online..."); if (self::$instance) { throw new Exception('You may not instantiate more than one Overseer per process.'); } self::$instance = $this; if ($this->daemonize) { // We need to get rid of these or the daemon will hang when we TERM it // waiting for something to read the buffers. TODO: Learn how unix works. fclose(STDOUT); fclose(STDERR); ob_start(); $pid = pcntl_fork(); if ($pid === -1) { throw new Exception('Unable to fork!'); } else { if ($pid) { exit(0); } } } if ($this->phddir) { $desc = array('name' => $this->daemon, 'argv' => $this->moreArgs, 'pid' => getmypid(), 'start' => time()); Filesystem::writeFile($this->phddir . '/daemon.' . getmypid(), json_encode($desc)); } $this->daemonID = $this->generateDaemonID(); $this->dispatchEvent(self::EVENT_DID_LAUNCH, array('argv' => array_slice($original_argv, 1), 'explicitArgv' => $this->moreArgs)); declare (ticks=1); pcntl_signal(SIGUSR1, array($this, 'didReceiveKeepaliveSignal')); pcntl_signal(SIGUSR2, array($this, 'didReceiveNotifySignal')); pcntl_signal(SIGINT, array($this, 'didReceiveGracefulSignal')); pcntl_signal(SIGTERM, array($this, 'didReceiveTerminalSignal')); }
public function getValue($key, $default = null) { return coalesce(idx($this->params, $key), $default); }