/** * Execute the command. * * @param Input $input * @param Output $output * @return void */ protected function execute(Input $input, Output $output) { $name = $input->getArgument("name"); // Validate the name straight away. if (count($chunks = explode("/", $name)) != 2) { throw new \InvalidArgumentException("Invalid repository name '{$name}'."); } $output->writeln(sprintf("Cloning <comment>%s</comment> into <info>%s/%s</info>...", $name, getcwd(), end($chunks))); // If we're in a test environment, stop executing. if (defined("ADVISER_UNDER_TEST")) { return null; } // @codeCoverageIgnoreStart if (!$this->git->cloneGithubRepository($name)) { throw new \UnexpectedValueException("Repository https://github.com/{$name} doesn't exist."); } // Change the working directory. chdir($path = getcwd() . "/" . end($chunks)); $output->writeln(sprintf("Changed the current working directory to <comment>%s</comment>.", $path)); $output->writeln(""); // Running "AnalyseCommand"... $arrayInput = [""]; if (!is_null($input->getOption("formatter"))) { $arrayInput["--formatter"] = $input->getOption("formatter"); } $this->getApplication()->find("analyse")->run(new ArrayInput($arrayInput), $output); // Change back, remove the directory. chdir(getcwd() . "/.."); $this->removeDirectory($path); $output->writeln(""); $output->writeln(sprintf("Switching back to <info>%s</info>, removing <comment>%s</comment>...", getcwd(), $path)); // @codeCoverageIgnoreStop }
/** * git ls-folder HEAD * @return Array $path => $blob */ public function scanFile() { $this->git->createGitProcess(['ls-tree', '--full-name', 'HEAD']); while ($this->git->isRunning()) { # code... } $output = $this->getOutput(); return 9; }
/** * @return Git */ public function getGit() { if (is_null($this->git)) { $this->git = new Git(); /** @var Logger $logger */ $logger = $this->getMockBuilder('Logger')->disableOriginalConstructor()->getMock(); $this->git->setLogger($logger); } return $this->git; }
public function display() { $git_php_viewer = new GitViews_GitPhpViewer($this->repository, $this->controller->getPlugin()->getConfigurationParameter('gitphp_path')); if ($this->request->get('noheader') == 1) { $view = new GitViews_ShowRepo_Download($git_php_viewer); } else { $view = new GitViews_ShowRepo_Content($this->repository, $git_php_viewer, $this->request->getCurrentUser(), $this->controller, $this->url_manager, $this->driver_factory, $this->gerrit_usermanager, $this->mirror_data_mapper, $this->gerrit_servers, $this->controller->getPlugin()->getThemePath()); } $view->display(); }
public function deleteFile($formData) { $result = false; if (is_array($formData) && isset($formData['name'])) { $git = new Git(); $result = $git->rmFile($this->getPath() . $formData['name']); } else { throw new Exception('New file form data in incorrect format'); } return $result; }
public function deleteAction() { $response = new \Phalcon\Http\Response(); $delete_url = $this->request->getPost("delete_url"); $status = Git::deleteRepository($delete_url, $this->session->get('token')); return $response->setContent($status); }
function git_read_tag($proj, $tag_id) { $obj = $proj->getObject($tag_id); if ($obj->getType() != Git::OBJ_TAG) { return; } $tag['id'] = sha1_hex($tag_id); if ($obj->object !== null) { $tag['object'] = sha1_hex($obj->object); } if ($obj->objtype !== null) { $tag['type'] = Git::getTypeName($obj->objtype); } if ($obj->tag !== null) { $tag['name'] = $obj->tag; } if ($obj->tagger !== null) { $tag['author'] = $obj->tagger->name; $tag['epoch'] = $obj->tagger->time; $tag['tz'] = sprintf("%+03d%02d", $obj->tagger->offset / 3600, abs($obj->tagger->offset % 3600 / 60)); } $tag['comment'] = explode("\n", $obj->summary . "\n" . $obj->detail); if (!isset($tag['name'])) { return null; } return $tag; }
function beforeSave() { if (!$this['type']) { throw $this->exception('Please specify type', 'ValidityCheck')->setField('type'); } $existing_check = $this->add('Model_MarketPlace'); $existing_check->addCondition('id', '<>', $this->id); $existing_check->addCondition('namespace', $this['namespace']); $existing_check->tryLoadAny(); if ($existing_check->loaded()) { throw $this->exception('Name Space Already Used', 'ValidityCheck')->setField('namespace'); } // TODO :: check namespace on server as well... if (file_exists(getcwd() . DS . 'epan-components' . DS . $this['namespace']) and !$this->isInstalling) { throw $this->exception('namespace folder is already created', 'ValidityCheck')->setField('namespace'); } if (!$this->isInstalling) { //Added in AddComponentTorepository View $create_component_folder = true; if ($this['initialize_and_clone_from_git'] and $this['git_path']) { $repo = Git::create($dest = getcwd() . DS . 'epan-components' . DS . $this['namespace'], $this['git_path']); $create_component_folder = false; } $this->createNewFiles($create_component_folder); } }
/** * Check Log * * This function finds that last tag for the current release and shows you * any changes between them * * @param The git module directory * @return String of `git log` output */ function checklog($moddir) { $repo = Git::open($moddir); $ltags = $repo->list_tags(); if ($ltags === false) { return 'No Tags found!'; } list($rawname, $ver, $supported) = freepbx::check_xml_file($moddir); //Get current module version preg_match('/(\\d*\\.\\d*)\\./i', $ver, $matches); $rver = $matches[1]; //cycle through the tags and create a new array with relavant tags $tagArray = array(); foreach ($ltags as $tag) { if (preg_match('/release\\/(.*)/i', $tag, $matches)) { if (strpos($matches[1], $rver) !== false) { $tagArray[] = $matches[1]; } } } if (!empty($tagArray)) { usort($tagArray, "freepbx::version_compare_freepbx"); $htag = array_pop($tagArray); $tagref = $repo->show_ref_tag($htag); return $repo->log($tagref, 'HEAD'); } return; }
/** * Associate user with the project. Owner is automatically assigned by newProject calling this method. * This method also creates the git repository and assigns basic configuration */ public function joinProject($pid) { if ($this->_uid == false) { throw new Exception(NO_USER); } $data = array('pid' => $pid, 'uid' => $this->_uid); $result = $this->_db->insert('user_project', $data); //returns the number of rows inserted if ($result == 1) { //select the project as the active project once the required db entry exists $this->selectProject($pid); $git = new Git(); if ($this->active->owner == $this->_uid) { if (file_exists($this->getPath() . $this->_userPath)) { throw new Exception('User directory in project folder already exists'); } if (!mkdir($this->getPath() . $this->_userPath)) { throw new Exception('Unable to create a user directory in the project folder'); } //===== GIT INIT ===== $git->initRepo($this->_userName, $this->_userEmail); } else { //clone should crete the user directory as it is required to clone to new dir //===== GIT CLONE ===== $git->cloneRepo($this->_userName, $this->_userEmail, $this->active->owner, $this->_uid); } } }
private function initRepo() { //get path to the repo root (by default DokuWiki's savedir) if (defined('DOKU_FARM')) { $repoPath = $this->getConf('repoPath'); } else { $repoPath = DOKU_INC . $this->getConf('repoPath'); } //set the path to the git binary $gitPath = trim($this->getConf('gitPath')); if ($gitPath !== '') { Git::set_bin($gitPath); } //init the repo and create a new one if it is not present io_mkdir_p($repoPath); $repo = new GitRepo($repoPath, true, true); //set git working directory (by default DokuWiki's savedir) $repoWorkDir = DOKU_INC . $this->getConf('repoWorkDir'); Git::set_bin(Git::get_bin() . ' --work-tree ' . escapeshellarg($repoWorkDir)); $params = str_replace(array('%mail%', '%user%'), array($this->getAuthorMail(), $this->getAuthor()), $this->getConf('addParams')); if ($params) { Git::set_bin(Git::get_bin() . ' ' . $params); } return $repo; }
public static function inspect() { $repo = Git::open(ABSPATH); if (is_object($repo) && $repo->test_git()) { $status_data = $repo->run('status --porcelain'); $changed_files = array(); if (preg_match_all('/(^.+?)\\s(.*)$/m', $status_data, $changes, PREG_SET_ORDER)) { foreach ($changes as $changed_item) { $change = trim($changed_item[1]); $file = trim($changed_item[2]); $changed_files[$change][] = $file; } } $routine_options = ACI_Routine_Handler::get_options(__CLASS__); if (!is_array($routine_options)) { $routine_options = array(); } if (!is_array($routine_options['changed_files'])) { $routine_options['changed_files'] = array(); } if (empty($routine_options['ignore_files'])) { $routine_options['ignore_files'] = self::$_default_ignore_files; } else { if (!is_array($routine_options['ignore_files'])) { $routine_options['ignore_files'] = (array) $routine_options['ignore_files']; } } foreach (array_keys($changed_files) as $change) { foreach ($routine_options['ignore_files'] as $file_path) { if (!empty($file_path)) { $files_to_ignore = preg_grep('/^' . str_replace('\\*', '*', preg_quote($file_path, '/') . '/'), $changed_files[$change]); if (is_array($files_to_ignore) && count($files_to_ignore) > 0) { foreach (array_keys($files_to_ignore) as $ignore_file_key) { unset($changed_files[$change][$ignore_file_key]); } } } } if (count($changed_files[$change]) > 0) { switch ($change) { case 'A': AC_Inspector::log('Git repository has ' . count($changed_files[$change]) . ' NEW file(s).', __CLASS__); break; case 'M': AC_Inspector::log('Git repository has ' . count($changed_files[$change]) . ' MODIFIED file(s).', __CLASS__); break; case 'D': AC_Inspector::log('Git repository has ' . count($changed_files[$change]) . ' DELETED file(s).', __CLASS__); break; case '??': AC_Inspector::log('Git repository has ' . count($changed_files[$change]) . ' UNTRACKED file(s).', __CLASS__); break; } } } $routine_options['changed_files'] = $changed_files; ACI_Routine_Handler::set_options(__CLASS__, $routine_options); } }
/** * @param $directory * * @throws \InvalidArgumentException * * @return $this */ public function setDirectory($directory) { if (!Git::isGitRepository($directory)) { throw new \InvalidArgumentException("Directory doesn't appear to be a git repository"); } $this->directory = realpath($directory); return $this; }
/** * Return the single instance of the Git class * */ function git() { if (!class_exists("Git")) { oik_require("includes/class-git.php", "oik-batch"); } $git = Git::instance(); return $git; }
private function getMasterLocationName() { $name = $this->controller->getPlugin()->getConfigurationParameter('master_location_name'); if (!$name) { $name = $GLOBALS['Language']->getText('plugin_git', 'default_location'); } return $name; }
/** * Returns the path to the current repository. * * Tries to determine the path of the current repository in which * the hook was invoked. * * @return string */ public static function getRepositoryPath() { if (is_null(self::$repositoryPath)) { $path = exec(sprintf('%s rev-parse --git-dir', self::GIT_EXECUTABLE)); self::$repositoryPath = is_dir($path) ? realpath($path) : false; } return self::$repositoryPath; }
public function data() { $data = ''; uasort($this->entries(), 'self::compare'); foreach ($this->entries() as $name => $entry) { $data .= sprintf("%s %s%s", $entry->mode(), $name, Git::sha2bin($entry->sha())); } return $data; }
/** * Execute post commands. * * @var array */ public function postDeploy(array $commands) { foreach ($commands as $command) { $this->cli->out("Execute : <white>{$command}"); $output = $this->git->exec($command); $output = implode(' ', $output); $this->cli->out("Result : <white>{$output}"); } }
/** * Returns the common ancestor revision for two given revisions * * Returns false if no sha1 was returned. Throws an exception if calling * git fails. * * @return boolean */ protected function mergeBase($oldrev, $newrev) { $baserev = \Git::gitExec('merge-base %s %s', escapeshellarg($oldrev), escapeshellarg($newrev)); $baserev = trim($baserev); if (40 != strlen($baserev)) { return false; } return $baserev; }
function git_tag($projectroot, $project, $hash) { global $tpl; $cachekey = sha1($project) . "|" . $hash; $git = new Git($projectroot . $project); $hash = $git->revParse($hash); if (!$tpl->is_cached('tag.tpl', $cachekey)) { $head = git_read_head($git); $tpl->assign("head", sha1_hex($head)); $tpl->assign("hash", sha1_hex($hash)); $tag = git_read_tag($git, $hash); $tpl->assign("tag", $tag); if (isset($tag['author'])) { $ad = date_str($tag['epoch'], $tag['tz']); $tpl->assign("datedata", $ad); } } $tpl->display('tag.tpl', $cachekey); }
function getBranch() { try { Git::set_bin(Settings::$git); $repo = Git::open(dirname(__FILE__) . '/../../'); return $repo->active_branch(); } catch (Exception $e) { echo $e->getMessage(); } }
public function __construct(Project $project, $name = 'main') { $this->project = $project; $repo = self::check($project, $name); if ($repo === null) { trigger_error('Couldn\'t find repository called "' . $name . '" for project "' . $this->folder . '" in ' . $repo, E_USER_ERROR); } $this->name = $name; parent::__construct($repo); }
public function run() { echo '---------------------------------------------' . PHP_EOL; echo 'Dumping database ' . $this->database->getDatabaseName() . PHP_EOL; echo '---------------------------------------------' . PHP_EOL; Git::cloneRepository($this->cwd, $this->gitRepository); $this->dumpDatabase(); Git::commit($this->cwd, $this->gitRepository); Git::push($this->cwd, $this->gitRepository); }
protected function _getHeader() { $buffer = ''; $state = $this->runVar['settings']['is_running'] == 1 ? 'Running' : 'Disabled'; $version = $this->_vers->versions->git->tag . 'r' . $this->_git->commits(); $buffer .= sprintf($this->tmpMasks[2], "Monitor {$state} v{$version} [" . $this->runVar['constants']['sqlpatch'] . "]: ", $this->relativeTime($this->runVar['timers']['timer1'])); $buffer .= sprintf($this->tmpMasks[1], "USP Connections:", sprintf("%d active (%d total) - %s:%d", $this->runVar['conncounts']['primary']['active'], $this->runVar['conncounts']['primary']['total'], $this->runVar['connections']['host'], $this->runVar['connections']['port'])); if ($this->runVar['constants']['alternate_nntp']) { $buffer .= sprintf($this->tmpMasks[1], "USP Alternate:", sprintf("%d active (%d total) - %s:%d)", $this->runVar['conncounts']['alternate']['active'], $this->runVar['conncounts']['alternate']['total'], $this->runVar['connections']['host_a'], $this->runVar['connections']['port_a'])); } $buffer .= sprintf($this->tmpMasks[1], "Newest Release:", $this->runVar['timers']['newOld']['newestrelname']); $buffer .= sprintf($this->tmpMasks[1], "Release Added:", sprintf("%s ago", isset($this->runVar['timers']['newOld']['newestrelease']) ? $this->relativeTime($this->runVar['timers']['newOld']['newestrelease']) : 0)); $buffer .= sprintf($this->tmpMasks[1], "Predb Updated:", sprintf("%s ago", isset($this->runVar['timers']['newOld']['newestpre']) ? $this->relativeTime($this->runVar['timers']['newOld']['newestpre']) : 0)); $buffer .= sprintf($this->tmpMasks[1], sprintf("Collection Age[%d]:", $this->runVar['constants']['delaytime']), sprintf("%s ago", isset($this->runVar['timers']['newOld']['oldestcollection']) ? $this->relativeTime($this->runVar['timers']['newOld']['oldestcollection']) : 0)); $buffer .= sprintf($this->tmpMasks[1], "Parts in Repair:", number_format($this->runVar['counts']['now']['partrepair_table'])); if (($this->runVar['settings']['post'] == "1" || $this->runVar['settings']['post'] == "3") && $this->runVar['constants']['sequential'] != 2) { $buffer .= sprintf($this->tmpMasks[1], "Postprocess:", "stale for " . $this->relativeTime($this->runVar['timers']['timer3'])); } return $buffer . PHP_EOL; }
function update($dynamic_model_update = true) { if ($this->git_path == null) { throw $this->exception('public variable git_path must be defined in page class'); } $class = get_class($this); preg_match('/page_(.*)_page_(.*)/', $class, $match); $this->component_namespace = $match[1]; $mp = $this->add('Model_MarketPlace')->loadBy('namespace', $this->component_namespace); $this->component_name = $mp['name']; $component_path = getcwd() . DS . 'epan-components' . DS . $this->component_namespace; if ($_GET['git_exec_path']) { Git::set_bin($_GET['git_exec_path']); } try { if (file_exists($component_path . DS . '.git')) { $repo = Git::open($component_path); } else { $repo = Git::create($component_path); } } catch (Exception $e) { // No Git Found ... So just return return; } $remote_branches = $repo->list_remote_branches(); if (count($remote_branches) == 0) { $repo->add_remote_address($this->git_path); } $branch = 'master'; if ($_GET['git_branch']) { $branch = $_GET['git_branch']; } $repo->run('fetch --all'); $repo->run('reset --hard origin/' . $branch); if ($dynamic_model_update) { $dir = $component_path . DS . 'lib' . DS . 'Model'; if (file_exists($dir)) { $lst = scandir($dir); array_shift($lst); array_shift($lst); foreach ($lst as $item) { $model = $this->add($this->component_namespace . '/Model_' . str_replace(".php", '', $item)); $model->add('dynamic_model/Controller_AutoCreator'); $model->tryLoadAny(); } } } // Re process Config file $this->add('Model_MarketPlace')->loadBy('namespace', $this->component_namespace)->reProcessConfig(); // Get new code from git // Get all models in lib/Model // add dynamic line on object // tryLoanAny }
function git_blob_plain($projectroot, $project, $hash, $file) { global $gitphp_conf, $tpl; $cachekey = sha1($project) . "|" . $hash . "|" . sha1($file); $buffer = null; $git = new Git($projectroot . $project); $hash = $git->revParse($hash); // XXX: Nasty hack to cache headers if (!$tpl->is_cached('blobheaders.tpl', $cachekey)) { if ($file) { $saveas = $file; } else { $saveas = $hash . ".txt"; } $buffer = $git->getObject($hash)->data; if ($gitphp_conf['filemimetype']) { $mime = file_mime($buffer, $file); } $headers = array(); if ($mime) { $headers[] = "Content-type: " . $mime; } else { $headers[] = "Content-type: text/plain; charset=UTF-8"; } $headers[] = "Content-disposition: inline; filename=\"" . $saveas . "\""; $tpl->assign("blobheaders", serialize($headers)); } $out = $tpl->fetch('blobheaders.tpl', $cachekey); $returnedheaders = unserialize($out); foreach ($returnedheaders as $i => $header) { header($header); } if (!$tpl->is_cached('blobplain.tpl', $cachekey)) { if (!$buffer) { $buffer = $git->getObject($hash)->data; } $tpl->assign("blob", $buffer); } $tpl->display('blobplain.tpl', $cachekey); }
/** * @param $hash * * @return $this */ public function setHash($hash) { $hash = trim($hash); $output = $this->exec('show ' . $hash . ' --quiet --format=medium'); $output = Git::parseGitLogOutput($output); if (!$output) { throw new \RuntimeException("{$hash} doesn't seem to be a valid revision."); } $this->hash = $output[0]; $this->author = $output[1]; $this->date = $output[2]; $this->message = $output[3]; return $this; }
/** * Returns an array of commit messages between revision $old and $new. * * @param string $old The old revison number. * @parma string $new The new revison umber. * * @return array */ private function getReceivedMessagesForRange($old, $new) { $repourl = \Git::getRepositoryPath(); $output = []; if ($old == \Git::NULLREV) { $cmd = sprintf("%s --git-dir=%s for-each-ref --format='%%(refname)' 'refs/heads/*'", \Git::GIT_EXECUTABLE, $repourl); exec($cmd, $heads); $not = count($heads) > 0 ? ' --not ' . implode(' ', $this->escapeArrayShellArgs($heads)) : ''; $cmd = sprintf('%s --git-dir=%s log --pretty=format:"[%%ae] %%H %%s" %s %s', \Git::GIT_EXECUTABLE, $repourl, escapeshellarg($new), $not); exec($cmd, $output); } elseif ($new != \Git::NULLREV) { $cmd = sprintf('%s --git-dir=%s log --pretty=format:"[%%ae] %%H %%s" %s..%s', \Git::GIT_EXECUTABLE, $repourl, escapeshellarg($old), escapeshellarg($new)); exec($cmd, $output); } return $output; }
/** * A custom method within the Plugin to generate the content * * @return string : HTML */ function generateGitBranchBlock() { $output = ''; $do_user_git = new UserGitrepo(); $git_repo = $do_user_git->CheckGitProjectExist($_SESSION["do_project"]->idproject); if (is_array($git_repo)) { include_once 'plugin/Git/class/Git.class.php'; $repo_path = "plugin/Git/repos/"; //$output .= '<br />'; $e_del_gitrepo = new Event("UserGitrepo->eventSelfDelProjectGitRepo"); $e_del_gitrepo->addParam("goto", "Project/" . $_SESSION["do_project"]->idproject); $e_del_gitrepo->addParam("idgit_project", $git_repo["idgit_project"]); $output .= '<div id="templt" class="co_worker_item co_worker_desc">'; $output .= '<div style="position: relative;">'; //$output .= '<b>Repository Name : '.$git_repo['git_repo'].'<br /></b>'; $idproject_task = (int) $_GET['idprojecttask']; $repo_name = $git_repo['git_repo']; $folder = "{$repo_path}" . "{$repo_name}"; if (is_dir($folder)) { $repo = Git::open($folder); $branch_name = $repo->branchlist($idproject_task); $branch_name = split(' ', $branch_name); //echo'<pre>';print_r($branch_name);echo'</pre>'; $size = sizeof($branch_name); for ($i = 1; $i < $size; $i++) { $branch_title = split('/', $branch_name[$i]); //echo'<pre>';print_r($branch_title);echo'</pre>'; $b_size = sizeof($branch_title); $b_name = split(' ', $branch_title[$b_size - 1]); $br_name .= $b_name[0] . '<br />'; } if (!empty($br_name)) { $output .= _('Currently The Following Git branches are associated with this Task <br />'); //$output .= '<br />Branches assoicated with current task are :<br />'; $output .= '<b>' . $br_name . '</b>'; } else { $output .= _('No Git branches found which are associated with this Task <br />'); } } else { $output .= _('Invalid Respository, Missing git repository in the plugin/Git/repos/' . $repo_name . ', Please check and try again <br />'); } $output .= '</div></div>'; } else { $output .= 'No Git Repository is associated with this Project Task'; } return $output; }
/** @return git String || null returns the path to the local git installation, if possible. */ public static function hasGit() { $git = 'git not found'; if (self::$hasGit === null) { try { $git = `which git`; } catch (Exception $e) { $git = 'git not found'; } if (preg_match('/^[^ ]+ not found$/', $git)) { self::$hasGit = false; } else { self::$hasGit = true; } } return self::$hasGit; }