List of usage examples for org.eclipse.jgit.api Git getRepository
public Repository getRepository()
From source file:org.jboss.forge.git.GitUtilsTest.java
License:Open Source License
@Test public void shouldCherryPickChangesWithoutNewCommit() throws Exception { // git init//from www . ja va2 s.com // create new branch (b2) but stay on master // commit new file #1 // switch to other branch // commit new file #2 // switch to master // cherry pick (without committing) the latest commit from b2 // verify file #2 exists // verify number of commits (2 on master branch) String[] branchNames = { "master", "branch_two" }; String[] files = { "test1.txt", "test2.txt" }; Project project = initializeJavaProject(); Git repo = GitUtils.init(project.getProjectRoot()); GitUtils.addAll(repo); GitUtils.commitAll(repo, "initial commit"); repo.branchCreate().setName(branchNames[1]).call(); FileResource<?> file0 = project.getProjectRoot().getChild(files[0]).reify(FileResource.class); file0.createNewFile(); GitUtils.add(repo, files[0]); GitUtils.commit(repo, "file added on " + branchNames[0]); GitUtils.switchBranch(repo, branchNames[1]); FileResource<?> file1 = project.getProjectRoot().getChild(files[1]).reify(FileResource.class); file1.createNewFile(); GitUtils.add(repo, files[1]); GitUtils.commit(repo, "file added on " + branchNames[1]); GitUtils.getLogForCurrentBranch(repo); GitUtils.switchBranch(repo, branchNames[0]); Ref branch2Ref = repo.getRepository().getRef(branchNames[1]); GitUtils.cherryPickNoMerge(repo, branch2Ref); // assert file2 exists Assert.assertTrue("file from cherry picked commit should exist", project.getProjectRoot().getChild(files[1]).exists()); // assert number of commits (on master). Should be 2 (cherry pick produced no merge) List<String> log = GitUtils.getLogForCurrentBranch(repo); Assert.assertEquals("wrong number of commits", 2, log.size()); }
From source file:org.jboss.forge.git.GitUtilsTest.java
License:Open Source License
@Test(expected = CantMergeCommitWithZeroParentsException.class) public void shouldNotCrashWhenCherryPickNoMergeIsCalledOnLastCommit() throws Exception { String[] branchNames = { "master" }; String[] files = { "test1.txt" }; List<String> commits = null; CherryPickResult cherryPickResult = null; Project project = initializeJavaProject(); Git repo = GitUtils.init(project.getProjectRoot()); GitUtils.addAll(repo);/*from ww w . j a v a 2s .c om*/ GitUtils.commitAll(repo, "initial commit"); FileResource<?> file0 = project.getProjectRoot().getChild(files[0]).reify(FileResource.class); file0.createNewFile(); GitUtils.add(repo, files[0]); GitUtils.commit(repo, "file added on " + branchNames[0]); commits = GitUtils.getLogForCurrentBranch(repo); Assert.assertEquals("Wrong number of commits in log", 2, commits.size()); cherryPickResult = GitUtils.cherryPickNoMerge(repo, repo.getRepository().getRef(branchNames[0])); Assert.assertEquals("Wrong cherrypick status", CherryPickResult.CherryPickStatus.OK, cherryPickResult.getStatus()); GitUtils.resetHard(repo, "HEAD^1"); commits = GitUtils.getLogForCurrentBranch(repo); Assert.assertEquals("Wrong number of commits in log", 1, commits.size()); GitUtils.cherryPickNoMerge(repo, repo.getRepository().getRef(branchNames[0])); }
From source file:org.jboss.forge.rest.main.GitCommandCompletePostProcessor.java
License:Apache License
protected void configureBranch(Git git, String branch, String remote) { // lets update the merge config if (!Strings.isNullOrEmpty(branch)) { StoredConfig config = git.getRepository().getConfig(); if (io.hawt.util.Strings.isBlank(config.getString("branch", branch, "remote")) || io.hawt.util.Strings.isBlank(config.getString("branch", branch, "merge"))) { config.setString("branch", branch, "remote", remote); config.setString("branch", branch, "merge", "refs/heads/" + branch); try { config.save();// ww w .j a va2s . c o m } catch (IOException e) { LOG.error("Failed to save the git configuration to " + git.getRepository().getDirectory() + " with branch " + branch + " on remote repo: " + remote + " due: " + e.getMessage() + ". This exception is ignored.", e); } } } }
From source file:org.jboss.forge.shell.plugins.builtin.ForgePlugin.java
License:Open Source License
@Command(value = "git-plugin", help = "Install a plugin from a public git repository") public void installFromGit(@Option(description = "git repo", required = true) final String gitRepo, @Option(name = "ref", description = "branch or tag to build") final String refName, @Option(name = "checkoutDir", description = "directory in which to clone the repository") final Resource<?> checkoutDir, final PipeOut out) throws Exception { DirectoryResource workspace = shell.getCurrentDirectory().createTempResource(); try {// w ww .ja v a 2 s. c o m DirectoryResource buildDir = workspace.getChildDirectory("repo"); if (checkoutDir != null) { if (!checkoutDir.exists() && (checkoutDir instanceof FileResource<?>)) { ((FileResource<?>) checkoutDir).mkdirs(); } buildDir = checkoutDir.reify(DirectoryResource.class); } if (buildDir.exists()) { buildDir.delete(true); buildDir.mkdir(); } prepareProxyForJGit(); ShellMessages.info(out, "Checking out plugin source files to [" + buildDir.getFullyQualifiedName() + "] via 'git'"); Git repo = GitUtils.clone(buildDir, gitRepo); Ref ref = null; String targetRef = refName; if (targetRef == null) { // Default to Forge runtime version if no Ref name is supplied. targetRef = environment.getRuntimeVersion(); } if (targetRef != null) { // Try to find a Tag matching the given Ref name or runtime version Map<String, Ref> tags = repo.getRepository().getTags(); ref = tags.get(targetRef); // Now try to find a matching Branch if (ref == null) { List<Ref> refs = GitUtils.getRemoteBranches(repo); for (Ref branchRef : refs) { String branchName = branchRef.getName(); if (branchName != null && branchName.endsWith(targetRef)) { ref = repo.branchCreate().setName(targetRef).setUpstreamMode(SetupUpstreamMode.TRACK) .setStartPoint("origin/" + targetRef).call(); } } } // Now try to find a tag or branch with same Major.Minor.(x) version. if (ref == null) { // All List<String> sortedVersions = new ArrayList<String>(); // Branches for (Ref branchRef : GitUtils.getRemoteBranches(repo)) { String branchName = branchRef.getName(); branchName = branchName.replaceFirst("refs/heads/", ""); if (InstalledPluginRegistry.isApiCompatible(targetRef, branchName)) sortedVersions.add(branchName); } // Tags // Branches for (String tag : tags.keySet()) { if (InstalledPluginRegistry.isApiCompatible(targetRef, tag)) sortedVersions.add(tag); } // Sort Collections.sort(sortedVersions); if (!sortedVersions.isEmpty()) { String version = sortedVersions.get(sortedVersions.size() - 1); if (InstalledPluginRegistry.isApiCompatible(targetRef, version)) { ref = tags.get(version); if (ref == null) { ref = repo.branchCreate().setName(version).setUpstreamMode(SetupUpstreamMode.TRACK) .setStartPoint("origin/" + version).call(); } } } } } if (ref == null) { ref = repo.getRepository().getRef("master"); } if (ref != null) { ShellMessages.info(out, "Switching to branch/tag [" + ref.getName() + "]"); GitUtils.checkout(repo, ref, false, SetupUpstreamMode.TRACK, false); } else if (refName != null) { throw new RuntimeException("Could not locate ref [" + targetRef + "] in repository [" + repo.getRepository().getDirectory().getAbsolutePath() + "]"); } else { ShellMessages.warn(out, "Could not find a Ref matching the current Forge version [" + environment.getRuntimeVersion() + "], building Plugin from HEAD."); } buildFromCurrentProject(out, buildDir); } finally { if (checkoutDir != null) { ShellMessages.info(out, "Cleaning up temp workspace [" + workspace.getFullyQualifiedName() + "]"); workspace.delete(true); } } ShellMessages.success(out, "Installed from [" + gitRepo + "] successfully."); restart(); }
From source file:org.jboss.tools.feedhenry.ui.internal.util.GitUtil.java
License:Open Source License
public static Repository createRepository(IProject project, IProgressMonitor monitor) throws CoreException { try {/* ww w. j a va 2 s . c om*/ InitCommand init = Git.init(); init.setBare(false).setDirectory(project.getLocation().toFile()); Git git = init.call(); return git.getRepository(); } catch (JGitInternalException | GitAPIException e) { throw new CoreException(new Status(IStatus.ERROR, FHPlugin.PLUGIN_ID, NLS.bind("Could not initialize a git repository at {0}: {1}", getRepositoryPathFor(project), e.getMessage()), e)); } }
From source file:org.jboss.tools.openshift.egit.core.EGitUtils.java
License:Open Source License
/** * Creates a repository for the given project. The repository is created in * the .git directory within the given project. The project is not connected * with the new repository//from w w w. j av a 2 s.c o m * * @param project * the project to create the repository for. * @param monitor * the monitor to report the progress to * @return * @throws CoreException * * @see #connect(IProject, Repository, IProgressMonitor) */ public static Repository createRepository(IProject project, IProgressMonitor monitor) throws CoreException { try { InitCommand init = Git.init(); init.setBare(false).setDirectory(project.getLocation().toFile()); Git git = init.call(); return git.getRepository(); } catch (JGitInternalException e) { throw new CoreException(EGitCoreActivator .createErrorStatus(NLS.bind("Could not initialize a git repository at {0}: {1}", getRepositoryPathFor(project), e.getMessage()), e)); } catch (GitAPIException e) { throw new CoreException(EGitCoreActivator .createErrorStatus(NLS.bind("Could not initialize a git repository at {0}: {1}", getRepositoryPathFor(project), e.getMessage()), e)); } }
From source file:org.jboss.tools.openshift.reddeer.utils.TestUtils.java
License:Open Source License
public static void closeGitRepository(File repoDir) { try {/*ww w . j a v a2 s .c om*/ Git git = Git.open(repoDir); git.getRepository().close(); git.close(); } catch (IOException ex) { // DO NOTHING } }
From source file:org.jboss.tools.openshift.ui.bot.test.application.v3.adapter.ImportApplicationWizardGitTest.java
License:Open Source License
private void setRemote(Git repo, String remoteURL) { try {/*from w w w .j a va 2s . c o m*/ StoredConfig config = repo.getRepository().getConfig(); config.setString("remote", "origin", "url", remoteURL); config.save(); } catch (IllegalStateException | IOException e) { e.printStackTrace(); fail(); } }
From source file:org.jdamico.jgitbkp.components.ManagerComponent.java
License:Open Source License
public List<BundleStatus> generateBundles(List<RepoImpl> reposLst, Config config) throws JGitBackupException { List<BundleStatus> bundleStatusLst = new ArrayList<BundleStatus>(); boolean backupStatus = false; StringBuffer backupMessage = new StringBuffer(); for (int i = 0; i < reposLst.size(); i++) { String bundlePath = config.getBundlePath() + "/" + reposLst.get(i).getName() + ".bundle"; File gitWorkDir = new File(reposLst.get(i).getClonedPath()); Git git = null; Repository localRepoGit = null;//from ww w. jav a 2 s . co m BundleWriter bundleWriter = null; ProgressMonitor pMonitor = null; OutputStream oStream = null; try { git = Git.open(gitWorkDir); git.pull(); if (!Starter.silent) System.out.println("Updated data for [" + reposLst.get(i).getName() + "]"); localRepoGit = git.getRepository(); bundleWriter = new BundleWriter(localRepoGit); pMonitor = new TextProgressMonitor(); oStream = new FileOutputStream(bundlePath); Map<String, Ref> allRefs = localRepoGit.getAllRefs(); Collection<Ref> values = allRefs.values(); Iterator<Ref> iter = values.iterator(); while (iter.hasNext()) { try { Ref element = iter.next(); bundleWriter.include(element); } catch (IllegalArgumentException e) { if (!e.getMessage().equalsIgnoreCase("Invalid ref name: HEAD")) { String err = reposLst.get(i).getName() + ": " + e.getMessage(); backupMessage.append(err); LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), err); } } } if (!Starter.silent) bundleWriter.writeBundle(pMonitor, oStream); else bundleWriter.writeBundle(null, oStream); } catch (IOException e) { String err = reposLst.get(i).getName() + ": " + e.getMessage(); backupMessage.append(err); LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), err); throw new JGitBackupException(e); } File f = new File(bundlePath); if (f.exists() && f.length() > 100) { backupStatus = f.exists(); } else backupStatus = false; bundleStatusLst.add(new BundleStatus(reposLst.get(i).getName(), backupStatus, backupMessage.toString(), Utils.getInstance().getCurrentDateTimeFormated(Constants.DATE_FORMAT), bundlePath)); if (!Starter.silent) System.out.println("Bundle created: " + bundlePath + " - " + backupStatus); } return bundleStatusLst; }
From source file:org.jdamico.jgitbkp.tests.JGitTester.java
License:Open Source License
@Test public void test() throws IOException, GitAPIException { String user = ""; String passwd = ""; String hostPath = "/git"; String backupRoot = "/tmp/test"; String gitRoot = "/mnt"; String bundlePath = "/tmp"; boolean keepOld = false; List<org.jdamico.jgitbkp.entities.RepoImpl> repos = new ArrayList<org.jdamico.jgitbkp.entities.RepoImpl>(); File fGitRoot = new File(gitRoot); String[] fRepos = fGitRoot.list(); for (String itemRepo : fRepos) { File fItemRepo = new File(gitRoot + "/" + itemRepo); if (fItemRepo.isDirectory() && itemRepo.contains(".git") && !itemRepo.equals(".git")) { repos.add(new org.jdamico.jgitbkp.entities.RepoImpl(itemRepo, null, backupRoot + "/" + itemRepo)); }//from ww w. ja va 2 s . c o m } for (int i = 0; i < repos.size(); i++) { File f = new File(repos.get(i).getClonedPath()); if (f.mkdir()) { Git.cloneRepository().setCloneAllBranches(true) .setURI("http://" + hostPath + "/" + repos.get(i).getName()) .setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, passwd)) .setDirectory(new File(repos.get(i).getClonedPath())) .setProgressMonitor(new TextProgressMonitor()).call(); } File gitWorkDir = new File(repos.get(i).getClonedPath()); Git git = Git.open(gitWorkDir); git.pull(); Repository localRepoGit = git.getRepository(); BundleWriter bundleWriter = new BundleWriter(localRepoGit); ProgressMonitor pMonitor = new TextProgressMonitor(); OutputStream oStream = new FileOutputStream(bundlePath + "/" + repos.get(i).getName() + ".bundle"); Map<String, Ref> allRefs = localRepoGit.getAllRefs(); Collection<Ref> values = allRefs.values(); Iterator<Ref> iter = values.iterator(); while (iter.hasNext()) { Ref element = iter.next(); try { bundleWriter.include(element); System.out.println("Added: " + element.getName()); } catch (Exception e) { // TODO: handle exception } } bundleWriter.writeBundle(pMonitor, oStream); } }