function TestSuite_upgrade_repos($target, $mother) { $context = Model_Context::getInstance(); $config = $context->getProperty('plugin.config'); if (empty($config['repos'])) { $config['repos'] = 'unstable'; } require_once 'library/PHPGit/Repository.php'; $repo = new PHPGit_Repository(ROOT); $repo->git('fetch'); switch ($config['repos']) { case 'master': $repo->git('checkout master'); break; case 'unstable': $repo->git('checkout tags/latest-unstable'); break; case 'stable': $repo->git('checkout tags/latest-stable'); break; } return $repo->git('pull'); //return $target; }
function getTranslationBranches($projects) { $features = apc_fetch('translation'); if (empty($features)) { $features = array(); foreach ($projects as $project) { $repoObject = new PHPGit_Repository(getenv('ADT_DATA') . "/sources/" . $project . ".git"); $branches = array_filter(preg_replace('/.*\\/integration\\//', '', array_filter(explode("\n", $repoObject->git('branch -r')), 'isTranslation'))); //print "<pre>"; //print_r($branches); //print "</pre>"; foreach ($branches as $branch) { $fetch_url = $repoObject->git('config --get remote.origin.url'); if (preg_match("/git@github\\.com:(.*)\\/(.*)\\.git/", $fetch_url, $matches)) { $github_org = $matches[1]; $github_repo = $matches[2]; } $features[$branch][$project]['http_url'] = "https://github.com/" . $github_org . "/" . $github_repo . "/tree/integration/" . $branch; $behind_commits_logs = $repoObject->git("log origin/integration/" . $branch . "..origin/develop --oneline"); if (empty($behind_commits_logs)) { $features[$branch][$project]['behind_commits'] = 0; } else { $features[$branch][$project]['behind_commits'] = count(explode("\n", $behind_commits_logs)); } $ahead_commits_logs = $repoObject->git("log origin/develop..origin/integration/" . $branch . " --oneline"); if (empty($ahead_commits_logs)) { $features[$branch][$project]['ahead_commits'] = 0; } else { $features[$branch][$project]['ahead_commits'] = count(explode("\n", $ahead_commits_logs)); } } } uksort($features, 'strcasecmp'); // Translation branches will be cached for 5 min apc_store('translation', $features, 300); } return $features; }
// start the process set_time_limit(0); Benchmark::startLive(); Benchmark::mark("configured request: repoName={$repoName}"); // get paths $repoPath = "{$_SERVER['SITE_ROOT']}/site-data/git/{$repoName}"; $keyPath = "{$repoPath}.key"; $gitWrapperPath = "{$repoPath}.git.sh"; putenv("GIT_SSH={$gitWrapperPath}"); // check if there is an existing repo if (!is_dir("{$repoPath}/.git")) { die("{$repoPath} does not contain .git"); } // get repo chdir($repoPath); $repo = new PHPGit_Repository($repoPath, !empty($_REQUEST['debug'])); Benchmark::mark("loaded git repo in {$repoPath}"); // verify repo state if ($repo->getCurrentBranch() != $repoCfg['workingBranch']) { die("Current branch in {$repoPath} is not {$repoCfg['workingBranch']}; aborting."); } Benchmark::mark("verified working branch"); // pull changes $repo->git("pull origin {$repoCfg['workingBranch']}"); Benchmark::mark("pulled from origin/{$repoCfg['workingBranch']}"); // sync trees foreach ($repoCfg['trees'] as $srcPath => $treeOptions) { if (is_string($treeOptions)) { $treeOptions = array('path' => $treeOptions); } if (!is_string($srcPath)) {
} // check if there is an existing repo if (is_dir("{$repoPath}/.git")) { die("{$repoPath} already contains a .git repo directory"); } // write key to file file_put_contents($keyPath, $_POST['privateKey']); chmod($keyPath, 0600); Benchmark::mark("saved key to {$keyPath}"); // write git wrapper to file file_put_contents($gitWrapperPath, "#!/bin/bash\nssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i {$keyPath} \$1 \$2"); chmod($gitWrapperPath, 0700); putenv("GIT_SSH={$gitWrapperPath}"); Benchmark::mark("saved git wrapper to {$gitWrapperPath}"); // create new repo $repo = PHPGit_Repository::create($repoPath, !empty($_REQUEST['debug'])); Benchmark::mark("initialized git repo in {$repoPath}"); // add remote $repo->git("remote add origin {$repoCfg['remote']}"); Benchmark::mark("added origin {$repoCfg['remote']}"); // fetch remote branch if (!empty($repoCfg['originBranch'])) { $repo->git("fetch origin {$repoCfg['originBranch']}"); Benchmark::mark("fetched origin/{$repoCfg['originBranch']}"); } // create local working branch if (!empty($repoCfg['originBranch'])) { $repo->git("checkout -b {$repoCfg['workingBranch']} FETCH_HEAD"); Benchmark::mark("created local branch {$repoCfg['workingBranch']}"); } else { die('TODO: handle initializing repo without originBranch');
/** * Get PHPGit_Repository * * @return PHPGit_Repository */ protected function getGitoliteRepository() { if (null === $this->gitoliteRepository) { if (null === $this->getGitLocalRepositoryPath()) { throw new \Exception('Git local repository path not defined'); } try { $this->gitoliteRepository = new \PHPGit_Repository($this->getGitLocalRepositoryPath()); } catch (\Exception $exc) { if (file_exists($this->getGitLocalRepositoryPath())) { throw new \Exception("Directory {$this->getGitLocalRepositoryPath()} already exists, impossible to create repository"); } else { if (mkdir($this->getGitLocalRepositoryPath(), 0770)) { $this->gitoliteRepository = \PHPGit_Repository::create($this->getGitLocalRepositoryPath()); } else { throw new \Exception('Impossible to create Directory informed in Git local repository (possibly).'); } } } } return $this->gitoliteRepository; }
/** * Removes a option from local config * * @param string $configOption */ public function remove($configOption) { $this->repository->git(sprintf('config --local --unset %s', $configOption)); unset($this->configuration[$configOption]); }
$t->pass('wtf is not a valid command'); } $t->comment('Use a valid git binary: /usr/bin/git'); $repo = _createTmpGitRepo($t, array('git_executable' => '/usr/bin/git')); $t->comment('Use a invalid git binary: /usr/bin/git-foobar'); try { $repo = _createTmpGitRepo($t, array('git_executable' => '/usr/bin/git-foobar')); $repo->git('status'); $t->fail('/usr/bin/git-foobar is not a valid git binary'); } catch (RuntimeException $e) { $t->pass('/usr/bin/git-foobar is not a valid git binary'); } $repoDir = sys_get_temp_dir() . '/php-git-repo/' . uniqid(); mkdir($repoDir); try { $repo = PHPGit_Repository::create($repoDir); $t->pass('Create a new Git repository in filesystem'); } catch (InvalidArgumentException $e) { $t->fail($e->getMessage()); } $repo = _createTmpGitRepo($t); $config = $repo->getConfiguration(); $t->ok($config->get('core.editor', true)); $config->set('core.editor', 'nano'); $t->is($config->get('core.editor'), 'nano'); $t->is($config->get('core.editor'), 'nano'); $config->remove('core.editor'); $t->ok($config->get('core.editor', true)); file_put_contents($repo->getDir() . '/README', 'No, finally, do not read me.'); $repo->git('add README'); $repo->git('commit -m "Add README"');
/** * Registers the commit info for all new commits on the given branch * * @param PHPGit_Repository $repo repository to parse * @param string $gitbranch the real name of the branch to analyze (eg 'master') * @param string $branch the future name of the same branch (eg 'MOODLE_28_STABLE') * @param string $mergemode either 'merges' or 'no-merges' * @param bool $showprogress * @internal */ function dev_git_record_commits(PHPGit_Repository $repo, $gitbranch, $branch, $mergemode, $showprogress = false) { global $DB; $startpoints = get_config('local_dev', 'gitstartpoints'); if ($startpoints === false) { set_config('gitstartpoints', json_encode(array()), 'local_dev'); $startpoints = get_config('local_dev', 'gitstartpoints'); } $startpoints = json_decode($startpoints, true); $reponame = basename($repo->getDir()); $exclude = empty($startpoints[$branch][$mergemode]) ? '' : $startpoints[$branch][$mergemode]; if ($mergemode === 'merges') { fputs(STDOUT, "Searching merges on {$gitbranch} ({$branch})" . ($exclude ? " from {$exclude}" : "") . PHP_EOL); $mergeflag = 1; } else { if ($mergemode === 'no-merges') { fputs(STDOUT, "Searching non-merges on {$gitbranch} ({$branch})" . ($exclude ? " from {$exclude}" : "") . PHP_EOL); $mergeflag = 0; } } $exclude = empty($exclude) ? '' : '^' . $exclude; $commits = explode(PHP_EOL, $repo->git("rev-list --reverse --{$mergemode} --format='tformat:COMMIT:%H TIMESTAMP:%at AUTHORNAME:%an AUTHOREMAIL:%ae SUBJECT:%s' {$gitbranch} {$exclude}")); $total = floor(count($commits) / 2); $counter = 0; if ($showprogress and $total == 0) { fputs(STDOUT, 'no commits found'); } foreach ($commits as $commit) { $pattern = '/^COMMIT:([0-9a-f]{40}) TIMESTAMP:([0-9]+) AUTHORNAME:(.+) AUTHOREMAIL:(.+) SUBJECT:(.*)$/'; if (!preg_match($pattern, $commit, $matches)) { continue; } $record = new stdClass(); $record->repository = $reponame; $record->commithash = $matches[1]; $record->authordate = $matches[2]; $record->authorname = $matches[3]; $record->authoremail = $matches[4]; $record->subject = $matches[5]; $record->merge = $mergeflag; $record = @fix_utf8($record); // register the commit info record if it does not exist yet $existing = $DB->get_record('dev_git_commits', array('repository' => $reponame, 'commithash' => $record->commithash), 'id', IGNORE_MISSING); if ($existing === false) { $commitid = $DB->insert_record('dev_git_commits', $record, true, true); } else { $commitid = $existing->id; } // register the branch containing the current commit if (!$DB->record_exists('dev_git_commit_branches', array('branch' => $branch, 'commitid' => $commitid))) { $branchinfo = new stdClass(); $branchinfo->commitid = $commitid; $branchinfo->branch = $branch; $DB->insert_record('dev_git_commit_branches', $branchinfo, false, true); } if ($showprogress) { fputs(STDOUT, ++$counter . '/' . $total . "\r"); } $startpoints[$branch][$mergemode] = $record->commithash; if ($counter % 1000 == 0) { set_config('gitstartpoints', json_encode($startpoints), 'local_dev'); } } set_config('gitstartpoints', json_encode($startpoints), 'local_dev'); if ($showprogress) { fputs(STDOUT, PHP_EOL); } }
// start the process set_time_limit(0); Benchmark::startLive(); Benchmark::mark("configured request: repoName={$repoName}"); // get paths $repoPath = "{$_SERVER['SITE_ROOT']}/site-data/git/{$repoName}"; $keyPath = "{$repoPath}.key"; $gitWrapperPath = "{$repoPath}.git.sh"; putenv("GIT_SSH={$gitWrapperPath}"); // check if there is an existing repo if (!is_dir("{$repoPath}/.git")) { die("{$repoPath} does not contain .git"); } // get repo chdir($repoPath); $repo = new PHPGit_Repository($repoPath, !empty($_REQUEST['debug'])); Benchmark::mark("loaded git repo in {$repoPath}"); // verify repo state if ($repo->getCurrentBranch() != $repoCfg['workingBranch']) { die("Current branch in {$repoPath} is not {$repoCfg['workingBranch']}; aborting."); } Benchmark::mark("verified working branch"); // sync trees foreach ($repoCfg['trees'] as $srcPath => $treeOptions) { if (is_string($treeOptions)) { $treeOptions = array('path' => $treeOptions); } $treeOptions = array_merge($exportOptions, $treeOptions); if (!is_string($srcPath)) { $srcPath = $treeOptions['path']; } elseif (!$treeOptions['path']) {
/** * Returns the git repository directory * * @return string */ public function getDir() { return $this->gitRepo->getDir(); }
public static function handlePushRequest() { $layer = static::$_currentRepo; $repoName = $layer->ID; static::$responseMode = 'json'; if (!array_key_exists($repoName, Git::$repositories)) { return static::throwInvalidRequestError("Repo '{$repoName}' is not defined in Git::\$repositories"); } $repoCfg = Git::$repositories[$repoName]; // start the process set_time_limit(0); //Benchmark::startLive(); //Benchmark::mark("configured request: repoName=$repoName"); // get paths $repoPath = "{$_SERVER['SITE_ROOT']}/site-data/git/{$repoName}"; $keyPath = "{$repoPath}.key"; $gitWrapperPath = "{$repoPath}.git.sh"; putenv("GIT_SSH={$gitWrapperPath}"); // check if there is an existing repo if (!is_dir("{$repoPath}/.git")) { return static::throwInvalidRequestError("{$repoPath} does not contain .git"); } // get repo chdir($repoPath); $repo = new \PHPGit_Repository($repoPath, !empty($_REQUEST['debug'])); //Benchmark::mark("loaded git repo in $repoPath"); // verify repo state if ($repo->getCurrentBranch() != $repoCfg['workingBranch']) { return static::throwInvalidRequestError("Current branch in {$repoPath} is not {$repoCfg['workingBranch']}; aborting."); } //Benchmark::mark("verified working branch"); // push changes $command = "push origin {$repoCfg['workingBranch']}"; try { $output = $repo->git($command); return static::respond('push', ['success' => true, 'output' => $output, 'command' => $command]); } catch (Exception $e) { return static::respond('push', ['success' => false, 'output' => $output, 'command' => $command, 'error' => $e->getMessage()]); } Benchmark::mark("pushed to {$repoCfg['workingBranch']}"); }
public static function handleCommitRequest() { // get repo if (empty($_REQUEST['repo'])) { die('Parameter "repo" required'); } $repoName = $_REQUEST['repo']; if (!array_key_exists($repoName, Git::$repositories)) { die("Repo '{$repoName}' is not defined in Git::\$repositories"); } $repoCfg = Git::$repositories[$repoName]; $exportOptions = array('localOnly' => false); if (!empty($repoCfg['localOnly'])) { $exportOptions['localOnly'] = true; } // get message if (empty($_POST['message'])) { die('<form method="POST">' . '<label>Commit message: <input type="text" name="message" size="50"></label>' . '<input type="submit" value="Commit">' . '</form>'); } // start the process set_time_limit(0); Benchmark::startLive(); Benchmark::mark("configured request: repoName={$repoName}"); // get paths $repoPath = "{$_SERVER['SITE_ROOT']}/site-data/git/{$repoName}"; $keyPath = "{$repoPath}.key"; $gitWrapperPath = "{$repoPath}.git.sh"; putenv("GIT_SSH={$gitWrapperPath}"); // check if there is an existing repo if (!is_dir("{$repoPath}/.git")) { die("{$repoPath} does not contain .git"); } // get repo chdir($repoPath); $repo = new PHPGit_Repository($repoPath, !empty($_REQUEST['debug'])); Benchmark::mark("loaded git repo in {$repoPath}"); // verify repo state if ($repo->getCurrentBranch() != $repoCfg['workingBranch']) { die("Current branch in {$repoPath} is not {$repoCfg['workingBranch']}; aborting."); } Benchmark::mark("verified working branch"); // sync trees foreach ($repoCfg['trees'] as $srcPath => $treeOptions) { if (is_string($treeOptions)) { $treeOptions = array('path' => $treeOptions); } $treeOptions = array_merge($exportOptions, $treeOptions); if (!is_string($srcPath)) { $srcPath = $treeOptions['path']; } elseif (!$treeOptions['path']) { $treeOptions['path'] = $srcPath; } $srcFileNode = Site::resolvePath($srcPath); if (is_a($srcFileNode, 'SiteFile')) { $destDir = dirname($treeOptions['path']); if ($destDir && !is_dir($destDir)) { mkdir($destDir, 0777, true); } copy($srcFileNode->RealPath, $treeOptions['path']); Benchmark::mark("exported file {$srcPath} to {$treeOptions['path']}"); } else { $exportResult = Emergence_FS::exportTree($srcPath, $treeOptions['path'], $treeOptions); Benchmark::mark("exported directory {$srcPath} to {$treeOptions['path']}: " . http_build_query($exportResult)); } } if (!empty($_REQUEST['syncOnly'])) { exit; } // set author $repo->git(sprintf('git config user.name "%s"', $GLOBALS['Session']->Person->FullName)); $repo->git(sprintf('git config user.email "%s"', $GLOBALS['Session']->Person->Email)); // commit changes $repo->git('add --all'); $repo->git(sprintf('commit -n -m "%s"', addslashes($_POST['message']))); Benchmark::mark("committed all changes"); // push changes $repo->git("push origin {$repoCfg['workingBranch']}"); Benchmark::mark("pushed to {$repoCfg['workingBranch']}"); }
} $lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $total = count($lines); $counter = 0; foreach ($lines as $line) { $commithash = substr($line, 0, 40); $tag = substr($line, 41); $DB->set_field('dev_git_commits', 'tag', $tag, array('repository' => 'moodle.git', 'commithash' => $commithash)); if ($options['show-progress']) { fputs(STDOUT, ++$counter . '/' . $total . "\r"); } } exit(0); } if ($options['update-tags']) { $repo = new PHPGit_Repository($CFG->dataroot . '/local_dev/repos/moodle.git'); $commits = $DB->get_fieldset_select('dev_git_commits', 'commithash', 'tag IS NULL ORDER BY authordate DESC'); $total = count($commits); $counter = 0; foreach ($commits as $commit) { try { $tag = $repo->git("describe --exact-match --match 'v[0-9]*' --contains {$commit} 2> /dev/null"); if (preg_match('/^(v[0-9]+\\.[0-9]+.*?)~.*$/', $tag, $matches)) { $tag = $matches[1]; $DB->set_field('dev_git_commits', 'tag', $tag, array('commithash' => $commit)); } } catch (GitRuntimeException $e) { // most probably the "fatal - cannot describe" error meaning there is no tag yet // describing this commit } if ($options['show-progress']) {
$config->remove('core.editor'); $t->ok($config->get('core.editor', true)); file_put_contents($repo->getDir() . '/README', 'No, finally, do not read me.'); $repo->git('add README'); $repo->git('commit -m "Add README"'); unlink($repo->getDir() . '/README'); $repo->git('rm README'); $repo->git('commit -m "Remove README"'); $log = $repo->getCommits(7); $t->ok(is_array($log)); $t->is(count($log), 2); $commit = $log[0]; $t->ok(is_array($commit)); $t->is($commit['message'], 'Remove README'); $t->is($commit['author']['name'], $config->get(PHPGit_Configuration::USER_NAME)); $t->is($commit['commiter']['name'], $config->get(PHPGit_Configuration::USER_NAME)); $commit = $log[1]; $t->is($commit['message'], 'Add README'); $t->is_deeply($repo->getTags(), array(), 'No tags'); $repo->git('tag -am "tag 1" first_tag'); $repo->git('tag -am "tag 2" second_tag'); $t->is_deeply($repo->getTags(), array('first_tag', 'second_tag'), '2 tags'); // cloneUrl $repoDir = sys_get_temp_dir() . '/php-git-repo/' . uniqid(); try { $repo = PHPGit_Repository::cloneUrl('https://github.com/ornicar/php-git-repo.git', $repoDir); $t->pass('Create a new Git repository in filesystem'); $t->is($repo->getCurrentBranch(), 'master', 'Current branch: master'); } catch (InvalidArgumentException $e) { $t->fail($e->getMessage()); }