List of usage examples for org.eclipse.jgit.api Git getRepository
public Repository getRepository()
From source file:org.kie.commons.java.nio.fs.jgit.util.JGitUtil.java
License:Apache License
public static MergeResult mergeBranches(final Git git, final String source, final String target) throws Exception { final Repository repo = git.getRepository(); final MergeStrategy mergeStrategy = MergeStrategy.RESOLVE; final List<Ref> commits = new LinkedList<Ref>(); final boolean squash = false; RevWalk revWalk = null;/*from www . ja va 2 s. c o m*/ DirCacheCheckout dco = null; try { Ref head = repo.getRef(Constants.HEAD); if (head == null) { throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported); } final StringBuilder refLogMessage = new StringBuilder("merge "); // Check for FAST_FORWARD, ALREADY_UP_TO_DATE revWalk = new RevWalk(repo); // we know for now there is only one commit Ref ref = commits.get(0); refLogMessage.append(ref.getName()); // handle annotated tags ObjectId objectId = ref.getPeeledObjectId(); if (objectId == null) { objectId = ref.getObjectId(); } final RevCommit srcCommit = revWalk.lookupCommit(objectId); ObjectId headId = head.getObjectId(); if (headId == null) { revWalk.parseHeaders(srcCommit); dco = new DirCacheCheckout(repo, repo.lockDirCache(), srcCommit.getTree()); dco.setFailOnConflict(true); dco.checkout(); RefUpdate refUpdate = repo.updateRef(head.getTarget().getName()); refUpdate.setNewObjectId(objectId); refUpdate.setExpectedOldObjectId(null); refUpdate.setRefLogMessage("initial pull", false); if (refUpdate.update() != RefUpdate.Result.NEW) { throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported); } return new MergeResult(srcCommit, srcCommit, new ObjectId[] { null, srcCommit }, MergeStatus.FAST_FORWARD, mergeStrategy, null, null); } final RevCommit headCommit = revWalk.lookupCommit(headId); if (revWalk.isMergedInto(srcCommit, headCommit)) { return new MergeResult(headCommit, srcCommit, new ObjectId[] { headCommit, srcCommit }, ALREADY_UP_TO_DATE, mergeStrategy, null, null); } else if (revWalk.isMergedInto(headCommit, srcCommit)) { // FAST_FORWARD detected: skip doing a real merge but only // update HEAD refLogMessage.append(": " + FAST_FORWARD); dco = new DirCacheCheckout(repo, headCommit.getTree(), repo.lockDirCache(), srcCommit.getTree()); dco.setFailOnConflict(true); dco.checkout(); String msg = null; ObjectId newHead, base = null; final MergeStatus mergeStatus; if (!squash) { updateHead(git, refLogMessage, srcCommit, headId); newHead = base = srcCommit; mergeStatus = FAST_FORWARD; } else { msg = JGitText.get().squashCommitNotUpdatingHEAD; newHead = base = headId; mergeStatus = FAST_FORWARD_SQUASHED; final List<RevCommit> squashedCommits = RevWalkUtils.find(revWalk, srcCommit, headCommit); final String squashMessage = new SquashMessageFormatter().format(squashedCommits, head); repo.writeSquashCommitMsg(squashMessage); } return new MergeResult(newHead, base, new ObjectId[] { headCommit, srcCommit }, mergeStatus, mergeStrategy, null, msg); } else { String mergeMessage = ""; if (!squash) { mergeMessage = new MergeMessageFormatter().format(commits, head); repo.writeMergeCommitMsg(mergeMessage); repo.writeMergeHeads(Arrays.asList(ref.getObjectId())); } else { final List<RevCommit> squashedCommits = RevWalkUtils.find(revWalk, srcCommit, headCommit); final String squashMessage = new SquashMessageFormatter().format(squashedCommits, head); repo.writeSquashCommitMsg(squashMessage); } boolean noProblems; final Merger merger = mergeStrategy.newMerger(repo); final Map<String, org.eclipse.jgit.merge.MergeResult<?>> lowLevelResults; final Map<String, ResolveMerger.MergeFailureReason> failingPaths; final List<String> unmergedPaths; if (merger instanceof ResolveMerger) { ResolveMerger resolveMerger = (ResolveMerger) merger; resolveMerger.setCommitNames(new String[] { "BASE", "HEAD", ref.getName() }); resolveMerger.setWorkingTreeIterator(new FileTreeIterator(repo)); noProblems = merger.merge(headCommit, srcCommit); lowLevelResults = resolveMerger.getMergeResults(); failingPaths = resolveMerger.getFailingPaths(); unmergedPaths = resolveMerger.getUnmergedPaths(); } else { noProblems = merger.merge(headCommit, srcCommit); lowLevelResults = emptyMap(); failingPaths = emptyMap(); unmergedPaths = emptyList(); } refLogMessage.append(": Merge made by "); refLogMessage.append(mergeStrategy.getName()); refLogMessage.append('.'); if (noProblems) { dco = new DirCacheCheckout(repo, headCommit.getTree(), repo.lockDirCache(), merger.getResultTreeId()); dco.setFailOnConflict(true); dco.checkout(); String msg = null; RevCommit newHead = null; MergeStatus mergeStatus = null; if (!squash) { newHead = new Git(repo).commit().setReflogComment(refLogMessage.toString()).call(); mergeStatus = MERGED; } else { msg = JGitText.get().squashCommitNotUpdatingHEAD; newHead = headCommit; mergeStatus = MERGED_SQUASHED; } return new MergeResult(newHead.getId(), null, new ObjectId[] { headCommit.getId(), srcCommit.getId() }, mergeStatus, mergeStrategy, null, msg); } else { if (failingPaths != null && !failingPaths.isEmpty()) { repo.writeMergeCommitMsg(null); repo.writeMergeHeads(null); return new MergeResult(null, merger.getBaseCommit(0, 1), new ObjectId[] { headCommit.getId(), srcCommit.getId() }, FAILED, mergeStrategy, lowLevelResults, failingPaths, null); } else { final String mergeMessageWithConflicts = new MergeMessageFormatter() .formatWithConflicts(mergeMessage, unmergedPaths); repo.writeMergeCommitMsg(mergeMessageWithConflicts); return new MergeResult(null, merger.getBaseCommit(0, 1), new ObjectId[] { headCommit.getId(), srcCommit.getId() }, CONFLICTING, mergeStrategy, lowLevelResults, null); } } } } catch (org.eclipse.jgit.errors.CheckoutConflictException e) { final List<String> conflicts = (dco == null) ? Collections.<String>emptyList() : dco.getConflicts(); throw new CheckoutConflictException(conflicts, e); } catch (java.io.IOException e) { throw new JGitInternalException( MessageFormat.format(JGitText.get().exceptionCaughtDuringExecutionOfMergeCommand, e), e); } finally { if (revWalk != null) { revWalk.release(); } } }
From source file:org.kie.commons.java.nio.fs.jgit.util.JGitUtil.java
License:Apache License
private static void updateHead(final Git git, final StringBuilder refLogMessage, final ObjectId newHeadId, final ObjectId oldHeadID) throws java.io.IOException, ConcurrentRefUpdateException { RefUpdate refUpdate = git.getRepository().updateRef(Constants.HEAD); refUpdate.setNewObjectId(newHeadId); refUpdate.setRefLogMessage(refLogMessage.toString(), false); refUpdate.setExpectedOldObjectId(oldHeadID); RefUpdate.Result rc = refUpdate.update(); switch (rc) { case NEW://www . ja v a 2s. c om case FAST_FORWARD: return; case REJECTED: case LOCK_FAILURE: throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, refUpdate.getRef(), rc); default: throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, Constants.HEAD, newHeadId.toString(), rc)); } }
From source file:org.kie.eclipse.server.KieRepositoryHandler.java
License:Open Source License
@Override public Object load() { if (repository == null) { try {//from w w w.ja va 2 s. c o m final File repoRoot = new File(PreferencesUtils.getRepoRoot(this)); final Set<File> gitDirs = new HashSet<File>(); GitUtils.findGitDirsRecursive(repoRoot, gitDirs, false); for (File dir : gitDirs) { if (getName().equals(dir.getParentFile().getName())) { Git git = Git.open(dir); Repository repository = git.getRepository(); StoredConfig storedConfig = repository.getConfig(); Set<String> remotes = storedConfig.getSubsections("remote"); for (String remoteName : remotes) { try { String url = storedConfig.getString("remote", remoteName, "url"); URI uri = new URI(url); int port = uri.getPort(); String host = uri.getHost(); String scheme = uri.getScheme(); String path[] = uri.getPath().split("/"); String repoName = path[path.length - 1]; if (name.equals(repoName) && host.equals(getServer().getHost()) && port == getDelegate().getGitPort() && "ssh".equals(scheme)) { this.repository = repository; break; } } catch (Exception e) { e.printStackTrace(); } finally { if (git != null) { git.close(); git = null; } } } } } } catch (Exception e) { e.printStackTrace(); } } return repository; }
From source file:org.kie.workbench.common.services.backend.compiler.impl.decorators.JGITCompilerBeforeDecorator.java
License:Apache License
private Map<Path, InputStream> handleMap(final Git git, final Map<Path, InputStream> override) { final Map<Path, InputStream> result = new HashMap<>(override.size()); for (Map.Entry<Path, InputStream> entry : override.entrySet()) { if (entry.getKey().getFileSystem() instanceof JGitFileSystem) { final Path convertedToCheckedPath = Paths.get(git.getRepository().getDirectory().toPath() .getParent().resolve(entry.getKey().toString().substring(1)).toUri()); result.put(convertedToCheckedPath, entry.getValue()); }//from w w w .ja va 2 s . c o m } return result; }
From source file:org.kie.workbench.common.services.backend.compiler.impl.decorators.JGITCompilerBeforeDecorator.java
License:Apache License
private CompilationRequest handleBefore(final Git git, final CompilationRequest req) { try {/*from w w w . j av a 2s. c o m*/ if (req.getInfo().getPrjPath().getFileSystem() instanceof JGitFileSystem) { JGitUtils.pullAndRebase(git); return new DefaultCompilationRequest(req.getMavenRepo(), new WorkspaceCompilationInfo(Paths.get(git.getRepository().getDirectory().getParentFile() .getCanonicalFile().toPath().toUri())), req.getOriginalArgs(), req.skipProjectDependenciesCreationList(), false); } return req; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:org.kie.workbench.common.services.backend.compiler.nio.decorators.JGITCompilerBeforeDecorator.java
License:Apache License
@Override public T compileSync(CompilationRequest _req) { final Path path = _req.getInfo().getPrjPath(); final CompilationRequest req; Git repo; if (path.getFileSystem() instanceof JGitFileSystem) { final JGitFileSystem fs = (JGitFileSystem) path.getFileSystem(); if (!gitMap.containsKey(fs)) { repo = JGitUtils.tempClone(fs, _req.getRequestUUID()); gitMap.put(fs, repo);/*w ww . j a v a 2 s .c om*/ } repo = gitMap.get(fs); JGitUtils.applyBefore(repo); req = new DefaultCompilationRequest(_req.getMavenRepo(), new WorkspaceCompilationInfo(Paths.get(repo.getRepository().getDirectory().toPath().getParent() .resolve(path.getFileName().toString()).normalize().toUri())), _req.getOriginalArgs(), _req.getMap(), _req.getLogRequested()); } else { req = _req; } return compiler.compileSync(req); }
From source file:org.kie.workbench.common.services.backend.compiler.utils.JGitUtilsTest.java
License:Apache License
@Test public void tempCloneTest() throws Exception { final String repoName = "myrepo"; final JGitFileSystem fs = (JGitFileSystem) ioService.newFileSystem(URI.create("git://" + repoName), new HashMap<String, Object>() { {/* ww w. ja v a2 s .c om*/ put("init", Boolean.TRUE); put("internal", Boolean.TRUE); } }); ioService.startBatch(fs); ioService.write(fs.getPath("/pom.xml"), new String(java.nio.file.Files .readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/pom.xml").toPath()))); ioService.write(fs.getPath("/dummyA/src/main/java/dummy/DummyA.java"), new String(java.nio.file.Files.readAllBytes(new File( "src/test/projects/dummy_multimodule_untouched/dummyA/src/main/java/dummy/DummyA.java") .toPath()))); ioService.write(fs.getPath("/dummyB/src/main/java/dummy/DummyB.java"), new String(java.nio.file.Files.readAllBytes(new File( "src/test/projects/dummy_multimodule_untouched/dummyB/src/main/java/dummy/DummyB.java") .toPath()))); ioService.write(fs.getPath("/dummyA/pom.xml"), new String(java.nio.file.Files .readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyA/pom.xml").toPath()))); ioService.write(fs.getPath("/dummyB/pom.xml"), new String(java.nio.file.Files .readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyB/pom.xml").toPath()))); ioService.endBatch(); String uuid = UUID.randomUUID().toString(); Git git = JGitUtils.tempClone(fs, uuid); assertThat(git).isNotNull(); assertThat(git.getRepository().getBranch()).isEqualTo("master"); assertThat(git.getRepository().getFullBranch()).isEqualTo("refs/heads/master"); assertThat(git.getRepository().getDirectory()).exists(); TestUtil.rm(git.getRepository().getDirectory()); }
From source file:org.kie.workbench.common.services.backend.compiler.utils.JGitUtilsTest.java
License:Apache License
@Test public void pullAndRebaseTest() throws Exception { //Setup origin in memory final URI originRepo = URI.create("git://repo"); final JGitFileSystem origin = (JGitFileSystem) ioService.newFileSystem(originRepo, new HashMap<String, Object>() { {//from w ww.j ava2s.co m put("init", Boolean.TRUE); put("internal", Boolean.TRUE); put("listMode", "ALL"); } }); ioService.startBatch(origin); ioService.write(origin.getPath("/pom.xml"), new String(java.nio.file.Files .readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/pom.xml").toPath()))); ioService.write(origin.getPath("/dummyA/src/main/java/dummy/DummyA.java"), new String(java.nio.file.Files.readAllBytes(new File( "src/test/projects/dummy_multimodule_untouched/dummyA/src/main/java/dummy/DummyA.java") .toPath()))); ioService.write(origin.getPath("/dummyB/src/main/java/dummy/DummyB.java"), new String(java.nio.file.Files.readAllBytes(new File( "src/test/projects/dummy_multimodule_untouched/dummyB/src/main/java/dummy/DummyB.java") .toPath()))); ioService.write(origin.getPath("/dummyA/pom.xml"), new String(java.nio.file.Files .readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyA/pom.xml").toPath()))); ioService.write(origin.getPath("/dummyB/pom.xml"), new String(java.nio.file.Files .readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyB/pom.xml").toPath()))); ioService.endBatch(); String uuid = UUID.randomUUID().toString(); Git git = JGitUtils.tempClone(origin, uuid); assertThat(git).isNotNull(); assertThat(git.getRepository().getBranch()).isEqualTo("master"); assertThat(git.getRepository().getFullBranch()).isEqualTo("refs/heads/master"); assertThat(git.getRepository().getDirectory()).exists(); assertThat(JGitUtils.pullAndRebase(git)).isTrue(); TestUtil.rm(origin.getGit().getRepository().getDirectory()); }
From source file:org.lab41.dendrite.web.controller.GraphExportController.java
License:Apache License
@RequestMapping(value = "/api/graphs/{graphId}/file-save", method = RequestMethod.POST) public ResponseEntity<Map<String, Object>> save(@PathVariable String graphId, @Valid GraphExportBean item, BindingResult result) throws IOException, GitAPIException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Map<String, Object> response = new HashMap<>(); if (result.hasErrors()) { response.put("status", "error"); response.put("msg", result.toString()); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); }//from w w w . jav a 2 s. c om MetaGraphTx metaGraphTx = metaGraphService.buildTransaction().readOnly().start(); GraphMetadata graphMetadata; Git git; try { graphMetadata = metaGraphTx.getGraph(graphId); git = historyService.projectGitRepository(graphMetadata.getProject()); metaGraphTx.commit(); } catch (Throwable t) { metaGraphTx.rollback(); throw t; } DendriteGraph graph = metaGraphService.getGraph(graphId); if (graph == null) { response.put("status", "error"); response.put("msg", "cannot find graph '" + graphId + "'"); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } logger.debug("saving graph '" + graphId + "'"); // extract the storage location for the history String format = item.getFormat(); DendriteGraphTx tx = graph.buildTransaction().readOnly().start(); try { try { String path; if (format.equalsIgnoreCase("GraphSON")) { path = new File(git.getRepository().getWorkTree(), graphId + ".json").getPath(); GraphSONWriter.outputGraph(tx, path); } else if (format.equalsIgnoreCase("GraphML")) { path = new File(git.getRepository().getWorkTree(), graphId + ".xml").getPath(); GraphMLWriter.outputGraph(tx, path); } else if (format.equalsIgnoreCase("GML")) { path = new File(git.getRepository().getWorkTree(), graphId + ".gml").getPath(); GMLWriter.outputGraph(tx, path); } else { tx.rollback(); response.put("status", "error"); response.put("msg", "unknown format '" + format + "'"); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); } git.add().addFilepattern(".").call(); git.commit().setAuthor(authentication.getName(), "").setMessage("commit").call(); } finally { git.close(); } } catch (IOException e) { tx.rollback(); response.put("status", "error"); response.put("msg", "exception: " + e.toString()); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); } tx.commit(); response.put("status", "ok"); return new ResponseEntity<>(response, HttpStatus.NO_CONTENT); }
From source file:org.libx4j.maven.plugin.version.GitUtil.java
License:Open Source License
public static Set<String> lookupChangedFiles(final POMFile pomFile, final Git git) throws GitAPIException, IOException, MojoFailureException { final Status status = git.status().call(); final Set<String> changes = new HashSet<>(); changes.addAll(status.getChanged()); changes.addAll(status.getAdded());//www.ja v a2 s. c o m changes.addAll(status.getRemoved()); final File repoDir = git.getRepository().getDirectory().getParentFile(); final String include = pomFile.file().getParentFile().getAbsolutePath() .substring(repoDir.getAbsolutePath().length() + 1); final Iterator<String> iterator = changes.iterator(); while (iterator.hasNext()) { final String entry = iterator.next(); if (!entry.startsWith(include)) { iterator.remove(); continue; } for (final POMFile modulePomFile : pomFile.modules()) { final String exclude = modulePomFile.file().getParentFile().getAbsolutePath() .substring(repoDir.getAbsolutePath().length() + 1); if (entry.startsWith(exclude)) { iterator.remove(); break; } } } return changes; }