List of usage examples for org.eclipse.jgit.api Git checkout
public CheckoutCommand checkout()
From source file:org.eclipse.egit.ui.test.team.actions.CompareActionsTest.java
License:Open Source License
@Test public void testCompareWithPreviousWithMerge() throws Exception { Repository repo = lookupRepository(repositoryFile); Git git = new Git(repo); ObjectId masterId = repo.resolve("refs/heads/master"); Ref newBranch = git.checkout().setCreateBranch(true).setStartPoint(commitOfTag.name()).setName("toMerge") .call();// ww w . j ava 2 s . co m ByteArrayInputStream bis = new ByteArrayInputStream("Modified".getBytes()); ResourcesPlugin.getWorkspace().getRoot().getProject(PROJ1).getFolder(FOLDER).getFile(FILE2).setContents(bis, false, false, null); bis.close(); git.commit().setAll(true).setMessage("To be merged").call(); git.merge().include(masterId).call(); String menuLabel = util.getPluginLocalizedValue("CompareWithPreviousAction.label"); SWTBotShell selectDialog = openCompareWithDialog(menuLabel, UIText.CommitSelectDialog_WindowTitle); assertEquals(2, selectDialog.bot().table().rowCount()); selectDialog.close(); // cleanup: checkout again master and delete merged branch git.checkout().setName("refs/heads/master").call(); git.branchDelete().setBranchNames(newBranch.getName()).setForce(true).call(); }
From source file:org.eclipse.egit.ui.test.team.actions.ReplaceActionsTest.java
License:Open Source License
@Test public void testReplaceWithPreviousWithMerge() throws Exception { Repository repo = lookupRepository(repositoryFile); Git git = new Git(repo); ObjectId masterId = repo.resolve("refs/heads/master"); Ref newBranch = git.checkout().setCreateBranch(true).setStartPoint(commitOfTag.name()).setName("toMerge") .call();// ww w . jav a2 s . co m ByteArrayInputStream bis = new ByteArrayInputStream("Modified".getBytes()); ResourcesPlugin.getWorkspace().getRoot().getProject(PROJ1).getFolder(FOLDER).getFile(FILE2).setContents(bis, false, false, null); bis.close(); PersonIdent committer = new PersonIdent("COMMITTER", "a.c@d", new Date(), TimeZone.getTimeZone("GMT-03:30")); git.commit().setAll(true).setCommitter(committer).setMessage("To be merged").call(); git.merge().include(masterId).call(); String newContent = getTestFileContent(); String menuLabel = util.getPluginLocalizedValue("replaceWithPreviousVersionAction.label"); clickReplaceWith(menuLabel); bot.shell(UIText.DiscardChangesAction_confirmActionTitle).bot().button(IDialogConstants.OK_LABEL).click(); SWTBotShell selectDialog = bot.shell(UIText.CommitSelectDialog_WindowTitle); assertEquals(2, selectDialog.bot().table().rowCount()); selectDialog.close(); // we have closed, so nothing should have changed String oldContent = getTestFileContent(); assertTrue(newContent.equals(oldContent)); clickReplaceWith(menuLabel); bot.shell(UIText.DiscardChangesAction_confirmActionTitle).bot().button(IDialogConstants.OK_LABEL).click(); selectDialog = bot.shell(UIText.CommitSelectDialog_WindowTitle); selectDialog.bot().table().select(1); selectDialog.bot().button(IDialogConstants.OK_LABEL).click(); TestUtil.joinJobs(org.eclipse.egit.ui.JobFamilies.DISCARD_CHANGES); oldContent = getTestFileContent(); assertFalse(newContent.equals(oldContent)); // cleanup: checkout again master and delete merged branch git.checkout().setName("refs/heads/master").call(); git.branchDelete().setBranchNames(newBranch.getName()).setForce(true).call(); }
From source file:org.eclipse.oomph.setup.git.impl.GitCloneTaskImpl.java
License:Open Source License
private static void checkout(SetupTaskContext context, Git git, String checkoutBranch) throws Exception { context.log("Checking out local branch " + checkoutBranch); CheckoutCommand command = git.checkout(); command.setName(checkoutBranch);// ww w . j ava2s . c o m command.call(); }
From source file:org.eclipse.orion.server.git.servlets.GitCloneHandlerV1.java
License:Open Source License
private boolean handlePut(HttpServletRequest request, HttpServletResponse response, String pathString) throws IOException, JSONException, ServletException, URISyntaxException, CoreException, JGitInternalException, GitAPIException { IPath path = pathString == null ? Path.EMPTY : new Path(pathString); if (path.segment(0).equals("file") && path.segmentCount() > 1) { //$NON-NLS-1$ // make sure a clone is addressed WebProject webProject = WebProject.fromId(path.segment(1)); if (isAccessAllowed(request.getRemoteUser(), webProject)) { URI contentLocation = URI.create(webProject.getId()); IPath projectPath = new Path(contentLocation.getPath()).append(path.removeFirstSegments(2)); projectPath = path.hasTrailingSeparator() ? projectPath : projectPath.removeLastSegments(1); File gitDir = GitUtils.getGitDirs(new Path("file").append(projectPath), Traverse.CURRENT).values() //$NON-NLS-1$ .iterator().next();//from w w w .j a v a2 s . co m // make sure required fields are set JSONObject toCheckout = OrionServlet.readJSONRequest(request); JSONArray paths = toCheckout.optJSONArray(ProtocolConstants.KEY_PATH); String branch = toCheckout.optString(GitConstants.KEY_BRANCH_NAME); if ((paths == null || paths.length() == 0) && (branch == null || branch.isEmpty())) { String msg = NLS.bind("Either '{0}' or '{1}' should be provided: {2}", new Object[] { ProtocolConstants.KEY_PATH, GitConstants.KEY_BRANCH_NAME, toCheckout }); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } Git git = new Git(new FileRepository(gitDir)); if (paths != null) { CheckoutCommand checkout = git.checkout(); for (int i = 0; i < paths.length(); i++) { checkout.addPath(paths.getString(i)); } checkout.call(); return true; } else if (branch != null) { CheckoutCommand co = git.checkout(); try { co.setName(branch).call(); return true; } catch (JGitInternalException e) { if (Status.CONFLICTS.equals(co.getResult().getStatus())) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e)); } // TODO: handle other exceptions } catch (RefNotFoundException e) { String msg = NLS.bind("Branch name not found: {0}", branch); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e)); } } } else { String msg = NLS.bind("Nothing found for the given ID: {0}", path); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } } String msg = NLS.bind("Invalid checkout request {0}", pathString); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); }
From source file:org.eclipse.orion.server.tests.servlets.git.GitMergeSquashTest.java
License:Open Source License
@Test public void testMergeSquashRemovingFolders() throws Exception { // see org.eclipse.jgit.api.MergeCommandTest.testMergeRemovingFolders() URI workspaceLocation = createWorkspace(getMethodName()); IPath[] clonePaths = createTestProjects(workspaceLocation); for (IPath clonePath : clonePaths) { // clone a repo JSONObject clone = clone(clonePath); String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION); // get project/folder metadata WebRequest request = getGetFilesRequest(cloneContentLocation); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject folder = new JSONObject(response.getText()); String folderChildrenLocation = folder.getString(ProtocolConstants.KEY_CHILDREN_LOCATION); String folderLocation = folder.getString(ProtocolConstants.KEY_LOCATION); JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT); String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); String folderName = "folder1"; request = getPostFilesRequest(folderLocation + "/", getNewDirJSON(folderName).toString(), folderName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); JSONObject folder1 = getChild(folder, "folder1"); String fileName = "file1.txt"; request = getPostFilesRequest(folder1.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); fileName = "file2.txt"; request = getPostFilesRequest(folder1.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); folderName = "folder2"; request = getPostFilesRequest(folderLocation + "/", getNewDirJSON(folderName).toString(), folderName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); JSONObject folder2 = getChild(folder, "folder2"); fileName = "file1.txt"; request = getPostFilesRequest(folder2.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); fileName = "file2.txt"; request = getPostFilesRequest(folder2.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); request = GitAddTest.getPutGitIndexRequest(gitIndexUri); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "folders and files", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); deleteFile(folder1);/*from w w w .j a v a2s . c o m*/ deleteFile(folder2); request = GitAddTest.getPutGitIndexRequest(gitIndexUri); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "removing folders", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONArray commitsArray = log(gitHeadUri); assertEquals(3, commitsArray.length()); JSONObject commit = commitsArray.getJSONObject(0); assertEquals("removing folders", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); String toMerge = commit.getString(ProtocolConstants.KEY_NAME); commit = commitsArray.getJSONObject(1); assertEquals("folders and files", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); String toCheckout = commit.getString(ProtocolConstants.KEY_NAME); Repository db1 = getRepositoryForContentLocation(cloneContentLocation); Git git = new Git(db1); git.checkout().setName(toCheckout).call(); JSONObject merge = merge(gitHeadUri, toMerge, true); MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT)); assertEquals(MergeStatus.FAST_FORWARD_SQUASHED, mergeResult); request = getGetFilesRequest(folderChildrenLocation); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText())); assertNull(getChildByName(children, "folder1")); assertNull(getChildByName(children, "folder2")); } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitMergeTest.java
License:Open Source License
@Test public void testMergeRemovingFolders() throws Exception { // see org.eclipse.jgit.api.MergeCommandTest.testMergeRemovingFolders() URI workspaceLocation = createWorkspace(getMethodName()); JSONObject projectTop = createProjectOrLink(workspaceLocation, getMethodName() + "-top", null); IPath clonePathTop = new Path("file").append(projectTop.getString(ProtocolConstants.KEY_ID)).makeAbsolute(); JSONObject projectFolder = createProjectOrLink(workspaceLocation, getMethodName() + "-folder", null); IPath clonePathFolder = new Path("file").append(projectFolder.getString(ProtocolConstants.KEY_ID)) .append("folder").makeAbsolute(); IPath[] clonePaths = new IPath[] { clonePathTop, clonePathFolder }; for (IPath clonePath : clonePaths) { // clone a repo JSONObject clone = clone(clonePath); String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION); // get project/folder metadata WebRequest request = getGetFilesRequest(cloneContentLocation); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject folder = new JSONObject(response.getText()); String folderChildrenLocation = folder.getString(ProtocolConstants.KEY_CHILDREN_LOCATION); String folderLocation = folder.getString(ProtocolConstants.KEY_LOCATION); JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT); String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); String folderName = "folder1"; request = getPostFilesRequest(folderLocation + "/", getNewDirJSON(folderName).toString(), folderName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); String fileName = "file1.txt"; request = getPostFilesRequest(folderLocation + folderName + "/", getNewFileJSON(fileName).toString(), fileName);//from w ww. ja v a2 s .c om response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); fileName = "file2.txt"; request = getPostFilesRequest(folderLocation + folderName + "/", getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); folderName = "folder2"; request = getPostFilesRequest(folderLocation + "/", getNewDirJSON(folderName).toString(), folderName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); fileName = "file1.txt"; request = getPostFilesRequest(folderLocation + folderName + "/", getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); folderName = "folder2"; fileName = "file2.txt"; request = getPostFilesRequest(folderLocation + folderName + "/", getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); request = GitAddTest.getPutGitIndexRequest(gitIndexUri); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "folders and files", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); request = getDeleteFilesRequest(folderLocation + "/folder1/"); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); request = getDeleteFilesRequest(folderLocation + "/folder2/"); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); request = GitAddTest.getPutGitIndexRequest(gitIndexUri); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "removing folders", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONArray commitsArray = log(gitHeadUri, false); assertEquals(3, commitsArray.length()); JSONObject commit = commitsArray.getJSONObject(0); assertEquals("removing folders", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); String toMerge = commit.getString(ProtocolConstants.KEY_NAME); commit = commitsArray.getJSONObject(1); assertEquals("folders and files", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); String toCheckout = commit.getString(ProtocolConstants.KEY_NAME); Repository db1 = getRepositoryForContentLocation(cloneContentLocation); Git git = new Git(db1); git.checkout().setName(toCheckout).call(); JSONObject merge = merge(gitHeadUri, toMerge); MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT)); assertEquals(MergeStatus.FAST_FORWARD, mergeResult); request = getGetFilesRequest(folderChildrenLocation); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText())); assertNull(getChildByName(children, "folder1")); assertNull(getChildByName(children, "folder2")); } }
From source file:org.eclipse.recommenders.snipmatch.GitSnippetRepository.java
License:Open Source License
private void pullSnippets(Git git, String checkoutBranch) throws IOException, InvalidRemoteException, TransportException, GitAPIException, CoreException { CheckoutCommand checkout = git.checkout(); checkout.setName(checkoutBranch);//from w w w . jav a 2 s. c o m checkout.setStartPoint("origin/" + checkoutBranch); checkout.setCreateBranch(!branchExistsLocally(git, "refs/heads/" + checkoutBranch)); checkout.call(); PullCommand pull = git.pull(); pull.call(); }
From source file:org.eclipse.thym.core.plugin.CordovaPluginManager.java
License:Open Source License
/** * Installs a Cordova plug-in from a git repository. * This method delegates to {@link #doInstallPlugin(File)} after cloning the * repository to a temporary location to complete the installation of the * plug-in. /* w w w . j av a 2 s . c o m*/ * <br/> * If commit is not null the cloned repository will be checked out to * commit. * <br/> * If subdir is not null it is assumed that the subdir path exists and installation * will be done from that location. * * @param uri * @param overwrite * @param isDependency * @param monitor * @param commit * @param subdir * @throws CoreException */ public void installPlugin(URI uri, FileOverwriteCallback overwrite, boolean isDependency, IProgressMonitor monitor) throws CoreException { File tempRepoDirectory = new File(FileUtils.getTempDirectory(), "cordova_plugin_tmp_" + Long.toString(System.currentTimeMillis())); tempRepoDirectory.deleteOnExit(); try { if (monitor.isCanceled()) return; monitor.subTask("Clone plugin repository"); String gitUrl = uri.getScheme() + ":" + uri.getSchemeSpecificPart(); Git git = Git.cloneRepository().setDirectory(tempRepoDirectory).setURI(gitUrl).call(); File pluginDirectory = tempRepoDirectory; String fragment = uri.getFragment(); String commit = null; String subdir = null; if (fragment != null) { int idx = fragment.indexOf(':'); if (idx < 0) { idx = fragment.length(); } commit = fragment.substring(0, idx); subdir = fragment.substring(Math.min(idx + 1, fragment.length())); if (monitor.isCanceled()) { throw new CanceledException("Plug-in installation cancelled"); } if (commit != null && !commit.isEmpty()) { git.checkout().setName(commit).call(); } monitor.worked(1); if (subdir != null && !subdir.isEmpty()) { pluginDirectory = new File(tempRepoDirectory, subdir); if (!pluginDirectory.isDirectory()) { throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, NLS.bind("{0} directory does not exist in this git repository", subdir))); } } } SubProgressMonitor sm = new SubProgressMonitor(monitor, 1); Document doc = readPluginXML(pluginDirectory); this.doInstallPlugin(pluginDirectory, doc, overwrite, sm); String id = CordovaPluginXMLHelper.getAttributeValue(doc.getDocumentElement(), "id"); JsonObject source = new JsonObject(); source.addProperty("type", "git"); source.addProperty("url", gitUrl); if (subdir != null && !subdir.isEmpty()) { source.addProperty("subdir", subdir); } if (commit != null && !commit.isEmpty()) { source.addProperty("ref", commit); } this.saveFetchMetadata(source, id, monitor); if (!isDependency) {//update config.xml List<IPluginInstallationAction> actions = new ArrayList<IPluginInstallationAction>(1); Map<String, String> params = new HashMap<String, String>(); params.put("url", uri.toString()); actions.add(getPluginInstallRecordAction(doc, params)); runActions(actions, false, overwrite, monitor); } } catch (GitAPIException e) { throw new CoreException( new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "Error cloning the plugin repository", e)); } finally { monitor.done(); } }
From source file:org.eclipse.winery.repository.backend.filebased.GitBasedRepository.java
License:Open Source License
private Git cloneRepository(String repoUrl, String branch) throws GitAPIException { Git git = Git.cloneRepository().setURI(repoUrl).setDirectory(this.getRepositoryDep().toFile()).call(); if (!"master".equals(branch)) { git.checkout().setCreateBranch(true).setName(branch) .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).setStartPoint("origin/" + branch) .call();//from w w w .j a va 2 s.c om } return git; }
From source file:org.eclipse.winery.repository.export.CsarExporter.java
License:Open Source License
/** * Special handling for artifact template directories source and files * * @param zos Output stream for the archive that should contain the file * @param csarEntry Reference to the file that should be added to the archive * @param fileProperties Describing the path to the file inside the archive * @throws IOException thrown when the temporary directory can not be created *//*from w w w . j a v a 2s. c om*/ private void addArtifactTemplateToZipFile(ZipOutputStream zos, RepositoryRefBasedCsarEntry csarEntry, CsarContentProperties fileProperties) throws IOException { GitInfo gitInfo = BackendUtils.getGitInformation((DirectoryId) csarEntry.getReference().getParent()); if (gitInfo == null) { addCsarEntryToArchive(zos, csarEntry, fileProperties); return; } // TODO: This is not quite correct. The files should reside checked out at "source/" // TODO: Hash all these git files (to be included in the provenance) Path tempDir = Files.createTempDirectory(WINERY_TEMP_DIR_PREFIX); try { Git git = Git.cloneRepository().setURI(gitInfo.URL).setDirectory(tempDir.toFile()).call(); git.checkout().setName(gitInfo.BRANCH).call(); String path = "artifacttemplates/" + Util.URLencode(((ArtifactTemplateId) csarEntry.getReference().getParent().getParent()) .getQName().getNamespaceURI()) + "/" + ((ArtifactTemplateId) csarEntry.getReference().getParent().getParent()).getQName() .getLocalPart() + "/files/"; TArtifactTemplate template = BackendUtils .getTArtifactTemplate((DirectoryId) csarEntry.getReference().getParent()); addWorkingTreeToArchive(zos, template, tempDir, path); } catch (GitAPIException e) { CsarExporter.LOGGER .error(String.format("Error while cloning repo: %s / %s", gitInfo.URL, gitInfo.BRANCH), e); } finally { deleteDirectory(tempDir); } }