List of usage examples for org.eclipse.jgit.lib AnyObjectId getName
public final String getName()
From source file:br.com.metricminer2.scm.GitRepository.java
License:Apache License
public SCMRepository info() { RevWalk rw = null;//from w w w . ja v a 2s. co 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(); } }
From source file:gov.va.isaac.sync.git.SyncServiceGIT.java
License:Apache License
/** * @throws MergeFailure// w ww . j a va 2 s . c om * @throws AuthenticationException * @see gov.va.isaac.interfaces.sync.ProfileSyncI#updateFromRemote(java.io.File, java.lang.String, java.lang.String, * gov.va.isaac.interfaces.sync.MergeFailOption) */ @Override public Set<String> updateFromRemote(String username, String password, MergeFailOption mergeFailOption) throws IllegalArgumentException, IOException, MergeFailure, AuthenticationException { Set<String> filesChangedDuringPull; try { log.info("update from remote called "); Git git = getGit(); log.debug("Fetching from remote"); if (git.status().call().getConflicting().size() > 0) { log.info("Previous merge failure not yet resolved"); throw new MergeFailure(git.status().call().getConflicting(), new HashSet<>()); } CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username, (password == null ? new char[] {} : password.toCharArray())); log.debug("Fetch Message" + git.fetch().setCredentialsProvider(cp).call().getMessages()); ObjectId masterIdBeforeMerge = git.getRepository().getRef("master").getObjectId(); if (git.getRepository().getRef("refs/remotes/origin/master").getObjectId().getName() .equals(masterIdBeforeMerge.getName())) { log.info("No changes to merge"); return new HashSet<String>(); } RevCommit stash = null; if (git.status().call().getUncommittedChanges().size() > 0) { log.info("Stashing uncommitted changes"); stash = git.stashCreate().call(); } { log.debug("Merging from remotes/origin/master"); MergeResult mr = git.merge().include(git.getRepository().getRef("refs/remotes/origin/master")) .call(); AnyObjectId headAfterMergeID = mr.getNewHead(); if (!mr.getMergeStatus().isSuccessful()) { if (mergeFailOption == null || MergeFailOption.FAIL == mergeFailOption) { addNote(NOTE_FAILED_MERGE_HAPPENED_ON_REMOTE + (stash == null ? ":NO_STASH" : STASH_MARKER + stash.getName()), git); //We can use the status here - because we already stashed the stuff that they had uncommitted above. throw new MergeFailure(mr.getConflicts().keySet(), git.status().call().getUncommittedChanges()); } else if (MergeFailOption.KEEP_LOCAL == mergeFailOption || MergeFailOption.KEEP_REMOTE == mergeFailOption) { HashMap<String, MergeFailOption> resolutions = new HashMap<>(); for (String s : mr.getConflicts().keySet()) { resolutions.put(s, mergeFailOption); } log.debug("Resolving merge failures with option {}", mergeFailOption); filesChangedDuringPull = resolveMergeFailures(MergeFailType.REMOTE_TO_LOCAL, (stash == null ? null : stash.getName()), resolutions); } else { throw new IllegalArgumentException("Unexpected option"); } } else { //Conflict free merge - or perhaps, no merge at all. if (masterIdBeforeMerge.getName().equals(headAfterMergeID.getName())) { log.debug("Merge didn't result in a commit - no incoming changes"); filesChangedDuringPull = new HashSet<>(); } else { filesChangedDuringPull = listFilesChangedInCommit(git.getRepository(), masterIdBeforeMerge, headAfterMergeID); } } } if (stash != null) { log.info("Replaying stash"); try { git.stashApply().setStashRef(stash.getName()).call(); log.debug("stash applied cleanly, dropping stash"); git.stashDrop().call(); } catch (StashApplyFailureException e) { log.debug("Stash failed to merge"); if (mergeFailOption == null || MergeFailOption.FAIL == mergeFailOption) { addNote(NOTE_FAILED_MERGE_HAPPENED_ON_STASH, git); throw new MergeFailure(git.status().call().getConflicting(), filesChangedDuringPull); } else if (MergeFailOption.KEEP_LOCAL == mergeFailOption || MergeFailOption.KEEP_REMOTE == mergeFailOption) { HashMap<String, MergeFailOption> resolutions = new HashMap<>(); for (String s : git.status().call().getConflicting()) { resolutions.put(s, mergeFailOption); } log.debug("Resolving stash apply merge failures with option {}", mergeFailOption); resolveMergeFailures(MergeFailType.STASH_TO_LOCAL, null, resolutions); //When we auto resolve to KEEP_LOCAL - these files won't have really changed, even though we recorded a change above. for (Entry<String, MergeFailOption> r : resolutions.entrySet()) { if (MergeFailOption.KEEP_LOCAL == r.getValue()) { filesChangedDuringPull.remove(r.getKey()); } } } else { throw new IllegalArgumentException("Unexpected option"); } } } log.info("Files changed during updateFromRemote: {}", filesChangedDuringPull); return filesChangedDuringPull; } catch (CheckoutConflictException e) { log.error("Unexpected", e); throw new IOException( "A local file exists (but is not yet added to source control) which conflicts with a file from the server." + " Either delete the local file, or call addFile(...) on the offending file prior to attempting to update from remote.", e); } catch (TransportException te) { if (te.getMessage().contains("Auth fail")) { log.info("Auth fail", te); throw new AuthenticationException("Auth fail"); } else { log.error("Unexpected", te); throw new IOException("Internal error", te); } } catch (GitAPIException e) { log.error("Unexpected", e); throw new IOException("Internal error", e); } }
From source file:gov.va.isaac.sync.git.SyncServiceGIT.java
License:Apache License
private HashSet<String> listFilesChangedInCommit(Repository repository, AnyObjectId beforeID, AnyObjectId afterID) throws MissingObjectException, IncorrectObjectTypeException, IOException { log.info("calculating files changed in commit"); HashSet<String> result = new HashSet<>(); RevWalk rw = new RevWalk(repository); RevCommit commitBefore = rw.parseCommit(beforeID); RevCommit commitAfter = rw.parseCommit(afterID); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setRepository(repository);/*from w w w . ja va 2 s .c o m*/ df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffs = df.scan(commitBefore.getTree(), commitAfter.getTree()); for (DiffEntry diff : diffs) { result.add(diff.getNewPath()); } log.debug("Files changed between commits commit: {} and {} - {}", beforeID.getName(), afterID, result); return result; }
From source file:org.craftercms.studio.impl.v1.util.git.CherryPickCommandEx.java
License:Eclipse Distribution License
/** * @param commit//from w w w. ja v a2 s.com * the Id of a commit which is cherry-picked to the current head * @return {@code this} */ public CherryPickCommandEx include(AnyObjectId commit) { return include(commit.getName(), commit); }
From source file:org.repodriller.scm.GitRepository.java
License:Apache License
public SCMRepository info() { try (Git git = openRepository(); RevWalk rw = new RevWalk(git.getRepository())) { AnyObjectId headId = git.getRepository().resolve(Constants.HEAD); RevCommit root = rw.parseCommit(headId); rw.sort(RevSort.REVERSE);/*from w w w . j a v a 2s.co m*/ 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("Couldn't create JGit instance with path " + path); } }
From source file:org.repodriller.scm.GitRepository.java
License:Apache License
private List<DiffEntry> getDiffBetweenCommits(Repository repo, AnyObjectId parentCommit, AnyObjectId currentCommit) {//from w ww.j a v a 2 s. co m try (DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE)) { df.setBinaryFileThreshold(2 * 1024); // 2 mb max a file df.setRepository(repo); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); setContext(df); List<DiffEntry> diffs = null; if (parentCommit == null) { try (RevWalk rw = new RevWalk(repo)) { RevCommit commit = rw.parseCommit(currentCommit); diffs = df.scan(new EmptyTreeIterator(), new CanonicalTreeParser(null, rw.getObjectReader(), commit.getTree())); } } else { diffs = df.scan(parentCommit, currentCommit); } return diffs; } catch (IOException e) { throw new RuntimeException( "error diffing " + parentCommit.getName() + " and " + currentCommit.getName() + " in " + path, e); } }
From source file:playRepository.GitRepository.java
License:Apache License
/** * @see <a href="https://www.kernel.org/pub/software/scm/git/docs/git-log.html">git log until</a> *//* w ww .jav a 2 s. co m*/ private ObjectNode fileAsJson(TreeWalk treeWalk, AnyObjectId untilCommitId) throws IOException, GitAPIException { Git git = new Git(repository); GitCommit commit = new GitCommit( git.log().add(untilCommitId).addPath(treeWalk.getPathString()).call().iterator().next()); ObjectNode result = Json.newObject(); long commitTime = commit.getCommitTime() * 1000L; User author = commit.getAuthor(); result.put("type", "file"); result.put("msg", commit.getShortMessage()); result.put("author", commit.getAuthorName()); result.put("avatar", getAvatar(author)); result.put("userName", author.name); result.put("userLoginId", author.loginId); result.put("createdDate", commitTime); result.put("commitMessage", commit.getShortMessage()); result.put("commiter", commit.getCommitterName()); result.put("commitDate", commitTime); result.put("commitId", untilCommitId.getName()); ObjectLoader file = repository.open(treeWalk.getObjectId(0)); result.put("size", file.getSize()); boolean isBinary = RawText.isBinary(file.openStream()); result.put("isBinary", isBinary); if (!isBinary && file.getSize() <= MAX_FILE_SIZE_CAN_BE_VIEWED) { byte[] bytes = file.getBytes(); String str = new String(bytes, FileUtil.detectCharset(bytes)); result.put("data", str); } Metadata meta = new Metadata(); meta.add(Metadata.RESOURCE_NAME_KEY, treeWalk.getNameString()); result.put("mimeType", new Tika().detect(file.openStream(), meta)); return result; }
From source file:sh.isaac.provider.sync.git.SyncServiceGIT.java
License:Apache License
/** * Update from remote./*from w ww .jav a2 s . com*/ * * @param username the username * @param password the password * @param mergeFailOption the merge fail option * @return the set * @throws IllegalArgumentException the illegal argument exception * @throws IOException Signals that an I/O exception has occurred. * @throws MergeFailure the merge failure * @throws AuthenticationException the authentication exception * @see sh.isaac.api.sync.SyncFiles#updateFromRemote(java.io.File, java.lang.String, java.lang.String, * sh.isaac.api.sync.MergeFailOption) */ @Override public Set<String> updateFromRemote(String username, char[] password, MergeFailOption mergeFailOption) throws IllegalArgumentException, IOException, MergeFailure, AuthenticationException { LOG.info("update from remote called "); Set<String> filesChangedDuringPull; try (Git git = getGit()) { LOG.debug("Fetching from remote"); if (git.status().call().getConflicting().size() > 0) { LOG.info("Previous merge failure not yet resolved"); throw new MergeFailure(git.status().call().getConflicting(), new HashSet<>()); } final CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username, ((password == null) ? new char[] {} : password)); LOG.debug("Fetch Message" + git.fetch().setCredentialsProvider(cp).call().getMessages()); final ObjectId masterIdBeforeMerge = git.getRepository().findRef("master").getObjectId(); if (git.getRepository().exactRef("refs/remotes/origin/master").getObjectId().getName() .equals(masterIdBeforeMerge.getName())) { LOG.info("No changes to merge"); return new HashSet<>(); } RevCommit stash = null; if (git.status().call().getUncommittedChanges().size() > 0) { LOG.info("Stashing uncommitted changes"); stash = git.stashCreate().call(); } { LOG.debug("Merging from remotes/origin/master"); final MergeResult mr = git.merge() .include(git.getRepository().exactRef("refs/remotes/origin/master")).call(); final AnyObjectId headAfterMergeID = mr.getNewHead(); if (!mr.getMergeStatus().isSuccessful()) { if ((mergeFailOption == null) || (MergeFailOption.FAIL == mergeFailOption)) { addNote(this.NOTE_FAILED_MERGE_HAPPENED_ON_REMOTE + ((stash == null) ? ":NO_STASH" : this.STASH_MARKER + stash.getName()), git); // We can use the status here - because we already stashed the stuff that they had uncommitted above. throw new MergeFailure(mr.getConflicts().keySet(), git.status().call().getUncommittedChanges()); } else if ((MergeFailOption.KEEP_LOCAL == mergeFailOption) || (MergeFailOption.KEEP_REMOTE == mergeFailOption)) { final HashMap<String, MergeFailOption> resolutions = new HashMap<>(); mr.getConflicts().keySet().forEach((s) -> { resolutions.put(s, mergeFailOption); }); LOG.debug("Resolving merge failures with option {}", mergeFailOption); filesChangedDuringPull = resolveMergeFailures(MergeFailType.REMOTE_TO_LOCAL, ((stash == null) ? null : stash.getName()), resolutions); } else { throw new IllegalArgumentException("Unexpected option"); } } else { // Conflict free merge - or perhaps, no merge at all. if (masterIdBeforeMerge.getName().equals(headAfterMergeID.getName())) { LOG.debug("Merge didn't result in a commit - no incoming changes"); filesChangedDuringPull = new HashSet<>(); } else { filesChangedDuringPull = listFilesChangedInCommit(git.getRepository(), masterIdBeforeMerge, headAfterMergeID); } } } if (stash != null) { LOG.info("Replaying stash"); try { git.stashApply().setStashRef(stash.getName()).call(); LOG.debug("stash applied cleanly, dropping stash"); git.stashDrop().call(); } catch (final StashApplyFailureException e) { LOG.debug("Stash failed to merge"); if ((mergeFailOption == null) || (MergeFailOption.FAIL == mergeFailOption)) { addNote(this.NOTE_FAILED_MERGE_HAPPENED_ON_STASH, git); throw new MergeFailure(git.status().call().getConflicting(), filesChangedDuringPull); } else if ((MergeFailOption.KEEP_LOCAL == mergeFailOption) || (MergeFailOption.KEEP_REMOTE == mergeFailOption)) { final HashMap<String, MergeFailOption> resolutions = new HashMap<>(); for (final String s : git.status().call().getConflicting()) { resolutions.put(s, mergeFailOption); } LOG.debug("Resolving stash apply merge failures with option {}", mergeFailOption); resolveMergeFailures(MergeFailType.STASH_TO_LOCAL, null, resolutions); // When we auto resolve to KEEP_LOCAL - these files won't have really changed, even though we recorded a change above. resolutions.entrySet().stream().filter((r) -> (MergeFailOption.KEEP_LOCAL == r.getValue())) .forEachOrdered((r) -> { filesChangedDuringPull.remove(r.getKey()); }); } else { throw new IllegalArgumentException("Unexpected option"); } } } LOG.info("Files changed during updateFromRemote: {}", filesChangedDuringPull); return filesChangedDuringPull; } catch (final CheckoutConflictException e) { LOG.error("Unexpected", e); throw new IOException( "A local file exists (but is not yet added to source control) which conflicts with a file from the server." + " Either delete the local file, or call addFile(...) on the offending file prior to attempting to update from remote.", e); } catch (final TransportException te) { if (te.getMessage().contains("Auth fail") || te.getMessage().contains("not authorized")) { LOG.info("Auth fail", te); throw new AuthenticationException("Auth fail"); } else { LOG.error("Unexpected", te); throw new IOException("Internal error", te); } } catch (final GitAPIException e) { LOG.error("Unexpected", e); throw new IOException("Internal error", e); } }
From source file:sh.isaac.provider.sync.git.SyncServiceGIT.java
License:Apache License
/** * List files changed in commit./*from w w w .j a v a 2s. co m*/ * * @param repository the repository * @param beforeID the before ID * @param afterID the after ID * @return the hash set * @throws MissingObjectException the missing object exception * @throws IncorrectObjectTypeException the incorrect object type exception * @throws IOException Signals that an I/O exception has occurred. */ private HashSet<String> listFilesChangedInCommit(Repository repository, AnyObjectId beforeID, AnyObjectId afterID) throws MissingObjectException, IncorrectObjectTypeException, IOException { LOG.info("calculating files changed in commit"); final HashSet<String> result = new HashSet<>(); final RevCommit commitBefore; final RevCommit commitAfter; try (RevWalk rw = new RevWalk(repository)) { commitBefore = rw.parseCommit(beforeID); commitAfter = rw.parseCommit(afterID); } try (DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE)) { df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); final List<DiffEntry> diffs = df.scan(commitBefore.getTree(), commitAfter.getTree()); diffs.forEach((diff) -> { result.add(diff.getNewPath()); }); } LOG.debug("Files changed between commits commit: {} and {} - {}", beforeID.getName(), afterID, result); return result; }