List of usage examples for org.eclipse.jgit.api Git getRepository
public Repository getRepository()
From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java
License:Open Source License
@SuppressWarnings("restriction") @Override// w w w . j a v a2s. c o m public List<IReviewDescriptor> getReviews(URI uri) throws InvalidReviewRepositoryException { List<IReviewDescriptor> changeIds = new LinkedList<>(); try { // connect to the local git repository Git git = Git.open(new File(uri)); try { // Assume that origin refers to the remote gerrit repository // list all remote refs from origin Collection<Ref> remoteRefs = git.lsRemote().setTimeout(60).call(); Pattern changeRefPattern = Pattern.compile(CHANGE_REF_PATTERN); // search for change refs for (Ref ref : remoteRefs) { Matcher matcher = changeRefPattern.matcher(ref.getName()); if (matcher.matches()) { String changePk = matcher.group(CHANGE_REF_PATTERN_GROUP_CHANGE_PK); String changeId = "<unknown>"; GerritReviewDescriptor reviewDescriptor; try { reviewDescriptor = new GerritReviewDescriptor(Integer.parseInt(changePk), changeId); } catch (NumberFormatException nfe) { // FIXME ignore it or throw an exception? break; } if (!changeIds.contains(reviewDescriptor)) { changeIds.add(reviewDescriptor); /* * the change id is present in all commit messages, * so we extract it from the commit message of the * current ref */ FetchResult fetchResult = git.fetch().setRefSpecs(new RefSpec(ref.getName())).call(); Ref localRef = fetchResult.getAdvertisedRef(ref.getName()); RevWalk revWalk = new RevWalk(git.getRepository()); RevCommit commit = revWalk.parseCommit(localRef.getObjectId()); String[] paragraphs = commit.getFullMessage().split("\n"); String lastParagraph = paragraphs[paragraphs.length - 1]; Pattern pattern = Pattern.compile(".*Change-Id: (I[^ \n]*).*"); Matcher changeIdMatcher = pattern.matcher(lastParagraph); if (changeIdMatcher.matches()) { changeId = changeIdMatcher.group(1); reviewDescriptor.setChangeId(changeId); ; } else { logger.warn(MessageFormat.format( "Could not find the change id for Gerrit change with primary key {0}", changePk)); } revWalk.close(); } } } } catch (GitAPIException e) { throw new RepositoryIOException("Error during loading all remote changes", e); } } catch (IOException e) { throw new InvalidReviewRepositoryException("Could not open local git repository", e); } return changeIds; }
From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java
License:Open Source License
@Override public ModelReview loadReview(URI uri, String id, User currentReviewer, IProgressMonitor monitor) throws InvalidReviewRepositoryException, InvalidReviewException, RepositoryIOException { /*//from w w w . jav a 2 s . c om * Fetch all refs to the patch sets for the particular change and create * the model instance from it */ monitor.beginTask("Connecting to repository", IProgressMonitor.UNKNOWN); try { Git git = Git.open(new File(uri)); int iId = Integer.parseInt(id); // First of all: fetch the patch sets // git fetch origin // +refs/changes/id%100/<cid>/*:refs/changes/id%100/<cid>/* // Refspec of a patchset: // +refs/changes/id%100/<cid>/<psId>:refs/changes/id%100/<cid>/<psId> monitor.beginTask("Fetching change ref", IProgressMonitor.UNKNOWN); git.fetch() .setRefSpecs(new RefSpec(MessageFormat.format( "+refs/changes/{0,number,00}/{1}/*:refs/changes/{0,number,00}/{1}/*", iId % 100, iId))) .call(); // create model instance ModelReview modelReview = modelReviewFactory.createModelReview(); modelReview.setId(id); modelReview.setRepositoryURI(uri.toString()); modelReview.setCurrentReviewer(currentReviewer); EList<PatchSet> patchSets = modelReview.getPatchSets(); Repository repository = git.getRepository(); Map<String, Ref> allRefs = repository.getAllRefs(); Pattern changeRefPattern = Pattern.compile(CHANGE_REF_PATTERN); monitor.beginTask("Loading Patch Sets", allRefs.size()); List<ResourceSet> resourceSets = new LinkedList<>(); for (Entry<String, Ref> refEntry : allRefs.entrySet()) { Matcher matcher = changeRefPattern.matcher(refEntry.getValue().getName()); if (matcher.matches() && matcher.group(CHANGE_REF_PATTERN_GROUP_CHANGE_PK).equals(id)) { PatchSet patchSet = modelReviewFactory.createPatchSet(); patchSets.add(patchSet); patchSet.setId(matcher.group(CHANGE_REF_PATTERN_GROUP_PATCH_SET_ID)); monitor.subTask("Loading Patch Set #" + patchSet.getId()); // load patched files loadPatches(patchSet, refEntry.getValue(), git); // load involved models resourceSets.addAll(loadInvolvedModelsAndDiagrams(patchSet, refEntry.getValue(), git)); // compare the involved models patchSet.setModelComparison(compareModels(patchSet)); // compare the involved diagrams patchSet.setDiagramComparison(compareDiagrams(patchSet)); } monitor.worked(1); } monitor.beginTask("Sorting Patch Sets", IProgressMonitor.UNKNOWN); /* * sort by their identifiers, numeric identifiers before string * identifiers (gerrit currently has only numeric patch set * identifiers, but to be on the save side also consider non-numeric * identifiers ) */ ECollections.sort(patchSets, new Comparator<PatchSet>() { @Override public int compare(PatchSet o1, PatchSet o2) { String psId1 = o1.getId(); String psId2 = o2.getId(); Integer iPsId1 = null; Integer iPsId2 = null; try { iPsId1 = Integer.valueOf(psId1); } catch (NumberFormatException nfe) { } try { iPsId2 = Integer.valueOf(psId2); } catch (NumberFormatException nfe) { } if (iPsId1 != null && iPsId2 != null) { // both numeric ids return iPsId1.compareTo(iPsId2); } else if (iPsId1 != null && iPsId2 == null) { // only one is numeric, the numeric id is always less // than the string id return -1; } else if (iPsId1 == null && iPsId2 != null) { // only one is numeric, the numeric id is always less // than the string id return 1; } // fallback to string sort return psId1.compareTo(psId2); } }); monitor.beginTask("Loading Comments", IProgressMonitor.UNKNOWN); loadComments(repository, modelReview, resourceSets); monitor.done(); return modelReview; } catch (IOException e) { throw new InvalidReviewRepositoryException("Could not open local git repository", e); } catch (NumberFormatException e) { throw new InvalidReviewException(MessageFormat.format("Invalid review id: {0}", id)); } catch (GitAPIException e) { throw new RepositoryIOException("Error occured during reading from the git repository", e); } }
From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java
License:Open Source License
/** * loads all involved models and diagrams for the given patchSet using the * given {@link Git} instance from the given git {@link Ref}. * /* w w w . ja v a 2 s .c o m*/ * @param patchSet * the patch set instance to store the involved models into * @param ref * the git ref to the commit which contains the patch set. * @param git * the git instance to use * @return a list containing the resource sets for the old and the new model * resources. * @throws IOException */ private List<ResourceSet> loadInvolvedModelsAndDiagrams(PatchSet patchSet, Ref ref, Git git) throws IOException { String commitHash = ref.getObjectId().name(); RevWalk revWalk = new RevWalk(git.getRepository()); RevCommit newCommit = revWalk.parseCommit(ref.getObjectId()); RevCommit oldCommit = newCommit.getParent(0); revWalk.parseHeaders(oldCommit); revWalk.close(); String parentCommitHash = oldCommit.getId().name(); URI repoURI = git.getRepository().getDirectory().toURI(); String authority = repoURI.getAuthority(); String path = repoURI.getPath(); String repoPath = (authority != null ? authority + "/" : "") + (path != null ? path : ""); if (repoPath.endsWith("/")) { repoPath = repoPath.substring(0, repoPath.length() - 1); } ResourceSet newResourceSet = createGitAwareResourceSet(commitHash, repoPath, Collections.<ResourceSet>emptyList()); ResourceSet oldModelResourceSet = createGitAwareResourceSet(parentCommitHash, repoPath, Collections.<ResourceSet>emptyList()); for (Patch patch : patchSet.getPatches()) { if (patch instanceof ModelPatch || patch instanceof DiagramPatch) { org.eclipse.emf.common.util.URI newUri = org.eclipse.emf.common.util.URI .createURI(GitURIParser.GIT_COMMIT_SCHEME + "://" + repoPath + "/" + commitHash + "/" + patch.getNewPath()); org.eclipse.emf.common.util.URI oldUri = org.eclipse.emf.common.util.URI .createURI(GitURIParser.GIT_COMMIT_SCHEME + "://" + repoPath + "/" + parentCommitHash + "/" + patch.getOldPath()); if (patch.getChangeType() != PatchChangeType.DELETE) { // if the patch has been deleted no new resource exists Resource newResource = newResourceSet.getResource(newUri, true); try { applyResourceContent(newResource, patch, false); } catch (IOException e) { throw new IOException( MessageFormat.format("Could not load resource \"{0}\" for patch set {1}", newUri.toString(), patchSet.getId()), e); } } if (patch.getChangeType() != PatchChangeType.ADD) { // if the patch has been added no old resource exists Resource oldResource = oldModelResourceSet.getResource(oldUri, true); try { applyResourceContent(oldResource, patch, true); } catch (IOException e) { throw new IOException( MessageFormat.format("Could not load resource \"{0}\" for patch set {1}", oldUri.toString(), patchSet.getId()), e); } } } } List<ResourceSet> resourceSets = new ArrayList<>(2); resourceSets.add(oldModelResourceSet); resourceSets.add(newResourceSet); return resourceSets; }
From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java
License:Open Source License
/** * loads all patches of from the given list of {@link DiffEntry}s. * /* w ww . jav a 2 s . c om*/ * @param patchSet * the patchSet to add the patches to. * @param ref * the ref to the commit of the patch set. * @param repository * the git repository instance * @throws RepositoryIOException */ private void loadPatches(PatchSet patchSet, Ref ref, Git git) throws RepositoryIOException { EList<Patch> patches = patchSet.getPatches(); Repository repository = git.getRepository(); try { RevWalk revWalk = new RevWalk(repository); RevCommit newCommit = revWalk.parseCommit(ref.getObjectId()); RevCommit oldCommit = newCommit.getParent(0); revWalk.parseHeaders(oldCommit); ObjectReader objectReader = repository.newObjectReader(); revWalk.close(); CanonicalTreeParser newTreeIterator = new CanonicalTreeParser(); newTreeIterator.reset(objectReader, newCommit.getTree().getId()); CanonicalTreeParser oldTreeIterator = new CanonicalTreeParser(); oldTreeIterator.reset(objectReader, oldCommit.getTree().getId()); List<DiffEntry> diffs = git.diff().setOldTree(oldTreeIterator).setNewTree(newTreeIterator).call(); for (DiffEntry diff : diffs) { String newPath = diff.getNewPath(); String oldPath = diff.getOldPath(); Patch patch = null; /* * only papyrus diagrams are supported for now, so models are in * .uml files, diagrams in .notation files */ if (diff.getChangeType() != ChangeType.DELETE) { if (newPath.endsWith(".uml")) { patch = modelReviewFactory.createModelPatch(); } else if (newPath.endsWith(".notation")) { patch = modelReviewFactory.createDiagramPatch(); } else { patch = modelReviewFactory.createPatch(); } } else { if (oldPath.endsWith(".uml")) { patch = modelReviewFactory.createModelPatch(); } else if (oldPath.endsWith(".notation")) { patch = modelReviewFactory.createDiagramPatch(); } else { patch = modelReviewFactory.createPatch(); } } switch (diff.getChangeType()) { case ADD: patch.setChangeType(PatchChangeType.ADD); break; case COPY: patch.setChangeType(PatchChangeType.COPY); break; case DELETE: patch.setChangeType(PatchChangeType.DELETE); break; case MODIFY: patch.setChangeType(PatchChangeType.MODIFY); break; case RENAME: patch.setChangeType(PatchChangeType.RENAME); break; } patch.setNewPath(newPath); patch.setOldPath(oldPath); if (diff.getChangeType() != ChangeType.DELETE) { ObjectLoader objectLoader = repository.open(diff.getNewId().toObjectId()); patch.setNewContent(objectLoader.getBytes()); } if (diff.getChangeType() != ChangeType.ADD) { ObjectLoader objectLoader = repository.open(diff.getOldId().toObjectId()); patch.setOldContent(objectLoader.getBytes()); } patches.add(patch); } } catch (IOException e) { throw new RepositoryIOException(MessageFormat.format( "An IO error occured during loading the patches for patch set #{0}", patchSet.getId()), e); } catch (GitAPIException e) { throw new RepositoryIOException( MessageFormat.format("An JGit API error occured during loading the patches for patch set #{0}", patchSet.getId()), e); } }
From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java
License:Open Source License
@Override public void saveReview(URI uri, ModelReview modelReview, User currentReviewer, IProgressMonitor monitor) throws InvalidReviewRepositoryException, InvalidReviewException, RepositoryIOException { monitor.beginTask("Connecting to repository", IProgressMonitor.UNKNOWN); String repoFileURI = COMMENTS_FILE_URI; try {/*from w w w . ja va 2 s . co m*/ Git git = Git.open(new File(uri)); Repository repository = git.getRepository(); ObjectInserter objectInserter = repository.newObjectInserter(); String commentRefName = getCommentRefName(modelReview); Ref commentRef = repository.exactRef(commentRefName); DirCache index = DirCache.newInCore(); DirCacheBuilder dirCacheBuilder = index.builder(); monitor.beginTask("Preparing commit...", IProgressMonitor.UNKNOWN); if (commentRef != null) { /* * The ref already exists so we have to copy the previous * RevTree to keep all already attached files */ RevWalk revWalk = new RevWalk(repository); RevCommit prevCommit = revWalk.parseCommit(commentRef.getObjectId()); RevTree tree = prevCommit.getTree(); List<String> ignoredFiles = new ArrayList<>(); /* * add file path of the new file to the ignored file paths, as * we don't want any already existing old file in our new tree */ ignoredFiles.add(repoFileURI); buildDirCacheFromTree(tree, repository, dirCacheBuilder, ignoredFiles); revWalk.close(); } monitor.beginTask("Writing comments file...", IProgressMonitor.UNKNOWN); ResourceSet resourceSet = new ResourceSetImpl(); Resource resource = resourceSet.createResource(org.eclipse.emf.common.util.URI.createURI(repoFileURI)); addCommentsToResource(modelReview, resource); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); resource.save(outputStream, null); // insert file as object byte[] content = outputStream.toByteArray(); long length = content.length; InputStream inputStream = new ByteArrayInputStream(content); ObjectId objectId = objectInserter.insert(Constants.OBJ_BLOB, length, inputStream); inputStream.close(); // create tree entry DirCacheEntry entry = new DirCacheEntry(repoFileURI); entry.setFileMode(FileMode.REGULAR_FILE); entry.setLastModified(System.currentTimeMillis()); entry.setLength(length); entry.setObjectId(objectId); dirCacheBuilder.add(entry); dirCacheBuilder.finish(); // write new tree in database ObjectId indexTreeId = index.writeTree(objectInserter); monitor.beginTask("Commiting comments...", IProgressMonitor.UNKNOWN); // create commit CommitBuilder commitBuilder = new CommitBuilder(); PersonIdent personIdent = new PersonIdent("Mervin", "mervin@mervin.modelreview"); commitBuilder.setCommitter(personIdent); commitBuilder.setAuthor(personIdent); commitBuilder.setMessage( MessageFormat.format("Updated comments by user \"{0}\"", currentReviewer.getName())); if (commentRef != null) { commitBuilder.setParentId(commentRef.getObjectId()); } commitBuilder.setTreeId(indexTreeId); // commit ObjectId commitId = objectInserter.insert(commitBuilder); objectInserter.flush(); RefUpdate refUpdate = repository.updateRef(commentRefName); refUpdate.setNewObjectId(commitId); if (commentRef != null) refUpdate.setExpectedOldObjectId(commentRef.getObjectId()); else refUpdate.setExpectedOldObjectId(ObjectId.zeroId()); /* * TODO the result handling below is copied from the CommitCommand * class, I don't know if this is really necessary in our case */ Result result = refUpdate.forceUpdate(); switch (result) { case NEW: case FORCED: case FAST_FORWARD: { if (repository.getRepositoryState() == RepositoryState.MERGING_RESOLVED) { /* * Commit was successful. Now delete the files used for * merge commits */ repository.writeMergeCommitMsg(null); repository.writeMergeHeads(null); } else if (repository.getRepositoryState() == RepositoryState.CHERRY_PICKING_RESOLVED) { repository.writeMergeCommitMsg(null); repository.writeCherryPickHead(null); } else if (repository.getRepositoryState() == RepositoryState.REVERTING_RESOLVED) { repository.writeMergeCommitMsg(null); repository.writeRevertHead(null); } break; } case REJECTED: case LOCK_FAILURE: throw new RepositoryIOException("Error occured during writing to the git repository", new ConcurrentRefUpdateException("Could not lock ref " + refUpdate.getRef().getName(), refUpdate.getRef(), result)); default: throw new RepositoryIOException("Error occured during writing to the git repository", new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, refUpdate.getRef().getName(), commitId.toString(), result))); } } catch (IOException e) { throw new InvalidReviewRepositoryException("Could not open local git repository", e); } finally { monitor.done(); } }
From source file:at.bitandart.zoubek.mervin.gerrit.GitURIParser.java
License:Open Source License
/** * loads the referenced {@link Repository} * /* w w w . j a v a2 s. c o m*/ * @throws IOException * if an error occurs during parsing the URI */ @SuppressWarnings("restriction") private void loadRepository() throws IOException { if (!uriParsed) parse(); URI repoURI; try { repoURI = new URI("file", authority, repoPath, null, null); logger.debug("repo URI: " + repoURI.toString()); } catch (URISyntaxException e) { throw new IOException("Could not determine repository URI"); } File repoDir = new File(repoURI); if (!repoDir.isDirectory()) { throw new IOException("Invalid git repository: " + repoDir.getAbsolutePath()); } Git git = Git.open(repoDir); repository = git.getRepository(); }
From source file:bench.MainJgit.java
License:BSD License
/** *//*w w w .j av a 2s . c o m*/ public static void main(final String[] args) throws Exception { final File baseDir = new File("."); final File folder = new File(baseDir, "target"); final File workspace = new File(folder, "workspace"); FileUtils.delete(workspace, FileUtils.IGNORE_ERRORS | FileUtils.RECURSIVE); FileUtils.mkdirs(workspace, true); final String remoteURI = "git@github.com:barchart/barchart-jenkins-tester.git"; final String remoteName = "archon"; final String remoteBranch = "master"; final String localBranch = "cascade"; { final Git git = PluginScmGit.doClone(workspace, remoteURI, remoteName); final Repository repo = git.getRepository(); System.out.println("repo " + repo); } { final CheckoutResult result = PluginScmGit.doCheckout(workspace, localBranch, remoteName, remoteBranch); System.out.println("checkout " + result.getStatus()); } { final CheckoutResult result = PluginScmGit.doCheckout(workspace, localBranch, remoteName, remoteBranch); System.out.println("checkout " + result.getStatus()); } { final RefSpec fetchSpec = PluginScmGit.refFetch(remoteBranch, remoteName, remoteBranch); final FetchResult fetchResult = PluginScmGit.doFetch(workspace, remoteName, fetchSpec); System.out.println("fetch satus: " + fetchResult.getAdvertisedRefs()); final String refHead = PluginScmGit.refHeads(remoteBranch); final Ref remoteHead = fetchResult.getAdvertisedRef(refHead); final ObjectId commit = remoteHead.getObjectId(); final MergeResult mergeResult = PluginScmGit.doMerge(workspace, commit); final MergeStatus mergeStatus = mergeResult.getMergeStatus(); System.out.println("merge status: " + mergeStatus); } }
From source file:br.com.metricminer2.scm.GitRepository.java
License:Apache License
public SCMRepository info() { RevWalk rw = null;/*from ww w. j a v a2 s . c om*/ Git git = null; try { git = Git.open(new File(path)); AnyObjectId headId = git.getRepository().resolve(Constants.HEAD); rw = new RevWalk(git.getRepository()); RevCommit root = rw.parseCommit(headId); rw.sort(RevSort.REVERSE); rw.markStart(root); RevCommit lastCommit = rw.next(); String origin = git.getRepository().getConfig().getString("remote", "origin", "url"); return new SCMRepository(this, origin, path, headId.getName(), lastCommit.getName()); } catch (Exception e) { throw new RuntimeException("error when info " + path, e); } finally { if (rw != null) rw.release(); if (git != null) git.close(); } }
From source file:br.com.metricminer2.scm.GitRepository.java
License:Apache License
public ChangeSet getHead() { Git git = null; try {//from w ww . jav a 2 s. c o m git = Git.open(new File(path)); ObjectId head = git.getRepository().resolve(Constants.HEAD); RevWalk revWalk = new RevWalk(git.getRepository()); RevCommit r = revWalk.parseCommit(head); return new ChangeSet(r.getName(), convertToDate(r)); } catch (Exception e) { throw new RuntimeException("error in getHead() for " + path, e); } finally { if (git != null) git.close(); } }
From source file:br.com.metricminer2.scm.GitRepository.java
License:Apache License
@Override public Commit getCommit(String id) { Git git = null; try {/*from ww w. j av a 2 s . co m*/ git = Git.open(new File(path)); Repository repo = git.getRepository(); Iterable<RevCommit> commits = git.log().add(repo.resolve(id)).call(); Commit theCommit = null; for (RevCommit jgitCommit : commits) { Developer author = new Developer(jgitCommit.getAuthorIdent().getName(), jgitCommit.getAuthorIdent().getEmailAddress()); Developer committer = new Developer(jgitCommit.getCommitterIdent().getName(), jgitCommit.getCommitterIdent().getEmailAddress()); String msg = jgitCommit.getFullMessage().trim(); String hash = jgitCommit.getName().toString(); long epoch = jgitCommit.getCommitTime(); String parent = (jgitCommit.getParentCount() > 0) ? jgitCommit.getParent(0).getName().toString() : ""; GregorianCalendar date = new GregorianCalendar(); date.setTime(new Date(epoch * 1000L)); theCommit = new Commit(hash, author, committer, date, msg, parent); List<DiffEntry> diffsForTheCommit = diffsForTheCommit(repo, jgitCommit); if (diffsForTheCommit.size() > MAX_NUMBER_OF_FILES_IN_A_COMMIT) { log.error("commit " + id + " has more than files than the limit"); throw new RuntimeException("commit " + id + " too big, sorry"); } for (DiffEntry diff : diffsForTheCommit) { ModificationType change = Enum.valueOf(ModificationType.class, diff.getChangeType().toString()); String oldPath = diff.getOldPath(); String newPath = diff.getNewPath(); String diffText = ""; String sc = ""; if (diff.getChangeType() != ChangeType.DELETE) { diffText = getDiffText(repo, diff); sc = getSourceCode(repo, diff); } if (diffText.length() > MAX_SIZE_OF_A_DIFF) { log.error("diff for " + newPath + " too big"); diffText = "-- TOO BIG --"; } theCommit.addModification(oldPath, newPath, change, diffText, sc); } break; } return theCommit; } catch (Exception e) { throw new RuntimeException("error detailing " + id + " in " + path, e); } finally { if (git != null) git.close(); } }