List of usage examples for org.eclipse.jgit.api Git open
public static Git open(File dir) throws IOException
From source file:am.ik.categolj3.api.git.GitStore.java
License:Apache License
Git getGitDirectory() { try {/* w w w . ja v a 2 s .c om*/ if (gitProperties.getBaseDir().exists()) { if (gitProperties.isInit()) { FileSystemUtils.deleteRecursively(gitProperties.getBaseDir()); } else { return Git.open(gitProperties.getBaseDir()); } } CloneCommand clone = Git.cloneRepository().setURI(gitProperties.getUri()) .setDirectory(gitProperties.getBaseDir()); gitProperties.credentialsProvider().ifPresent(clone::setCredentialsProvider); return clone.call(); } catch (IOException e) { throw new UncheckedIOException(e); } catch (GitAPIException e) { throw new IllegalStateException(e); } }
From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java
License:Open Source License
@SuppressWarnings("restriction") @Override//w w w .j a va2 s. c om 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 { /*// w w w.ja va 2s .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
@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 .j a va 2 s .c o 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} * //ww w.j ava2 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:bluej.groupwork.git.GitRepository.java
License:Open Source License
/** * opens the Git repository and returns the stored Name * @param projectPath path to the BlueJ project * @return String with the stored name in the Git repo. *//* w w w. java 2 s . co m*/ static public String getYourNameFromRepo(File projectPath) { String result = null; try { try (Git repo = Git.open(projectPath.getParentFile())) { StoredConfig repoConfig = repo.getRepository().getConfig(); //get repo config result = repoConfig.getString("user", null, "name"); //recover the user name repo.close(); } //close the repo } catch (IOException ex) { } return result; }
From source file:bluej.groupwork.git.GitRepository.java
License:Open Source License
/** * opens the Git repository and returns the stored email * @param projectPath path to the BlueJ project * @return String with the stored email in the Git repo. *///from w ww. j a v a 2s . c o m static public String getYourEmailFromRepo(File projectPath) { String result = null; try { try (Git repo = Git.open(projectPath.getParentFile())) { StoredConfig repoConfig = repo.getRepository().getConfig(); //get repo config result = repoConfig.getString("user", null, "email"); //recover the user email repo.close(); } //close the repo } catch (IOException ex) { } return result; }
From source file:bluej.groupwork.git.GitStatusCommand.java
License:Open Source License
@Override public TeamworkCommandResult getResult() { LinkedList<TeamStatusInfo> returnInfo = new LinkedList<>(); try (Git repo = Git.open(this.getRepository().getProjectPath().getParentFile())) { Status s = repo.status().call(); File gitPath = new File(this.getRepository().getProjectPath().getParent()); s.getMissing().stream().map((item) -> new TeamStatusInfo(new File(gitPath, item), "", null, TeamStatusInfo.STATUS_NEEDSCHECKOUT)).forEach((teamInfo) -> { returnInfo.add(teamInfo); });//from w ww . j a v a 2s .c om s.getUncommittedChanges().stream().map((item) -> new TeamStatusInfo(new File(gitPath, item), "", null, TeamStatusInfo.STATUS_NEEDSCOMMIT)).forEach((teamInfo) -> { returnInfo.add(teamInfo); }); s.getConflicting().stream().map((item) -> new TeamStatusInfo(new File(gitPath, item), "", null, TeamStatusInfo.STATUS_NEEDSMERGE)).forEach((teamInfo) -> { returnInfo.add(teamInfo); }); s.getUntracked().stream().map( (item) -> new TeamStatusInfo(new File(gitPath, item), "", null, TeamStatusInfo.STATUS_NEEDSADD)) .forEach((teamInfo) -> { returnInfo.add(teamInfo); }); s.getUntrackedFolders().stream().map( (item) -> new TeamStatusInfo(new File(gitPath, item), "", null, TeamStatusInfo.STATUS_NEEDSADD)) .forEach((teamInfo) -> { returnInfo.add(teamInfo); }); s.getRemoved().stream().map( (item) -> new TeamStatusInfo(new File(gitPath, item), "", null, TeamStatusInfo.STATUS_REMOVED)) .forEach((teamInfo) -> { returnInfo.add(teamInfo); }); } catch (IOException | GitAPIException | NoWorkTreeException ex) { Logger.getLogger(GitStatusCommand.class.getName()).log(Level.SEVERE, null, ex); } if (listener != null) { while (!returnInfo.isEmpty()) { TeamStatusInfo teamInfo = (TeamStatusInfo) returnInfo.removeFirst(); listener.gotStatus(teamInfo); } listener.statusComplete(new GitStatusHandle(getRepository())); } return new TeamworkCommandResult(); }
From source file:br.com.ingenieux.mojo.beanstalk.bundle.CodeCommitFastDeployMojo.java
License:Apache License
@Override protected Git getGitRepo() throws Exception { if (stagingDirectory.exists() && new File(stagingDirectory, "HEAD").exists()) { Git git = Git.open(stagingDirectory); git.fetch().setRemote(getRemoteUrl(null, null)).setProgressMonitor(new TextProgressMonitor()) .setRefSpecs(new RefSpec("refs/heads/master")).call(); } else {/*from w w w. ja v a 2 s .c om*/ Git.cloneRepository().setURI(getRemoteUrl(null, null)).setProgressMonitor(new TextProgressMonitor()) .setDirectory(stagingDirectory).setNoCheckout(true).setBare(true).call(); } Repository r = null; RepositoryBuilder b = new RepositoryBuilder().setGitDir(stagingDirectory).setWorkTree(sourceDirectory); r = b.build(); final Git git = Git.wrap(r); return git; }
From source file:br.com.metricminer2.scm.GitRepository.java
License:Apache License
public SCMRepository info() { RevWalk rw = null;/*from w w w . j a v a 2 s. c o m*/ 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(); } }