List of usage examples for org.eclipse.jgit.lib ObjectId getName
public final String getName()
From source file:gov.va.isaac.sync.git.SyncServiceGIT.java
License:Apache License
/** * @throws MergeFailure/*from ww w . ja v a 2s. com*/ * @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:hudson.plugins.git.GitPublisherTest.java
License:Open Source License
private void checkEnvVar(FreeStyleProject project, String envName, String envValue) throws Exception { String envReference = "${" + envName + "}"; List<GitSCMExtension> scmExtensions = new ArrayList<GitSCMExtension>(); scmExtensions.add(new PreBuildMerge(new UserMergeOptions("origin", envReference, null, null))); scmExtensions.add(new LocalBranch(envReference)); GitSCM scm = new GitSCM(remoteConfigs(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, scmExtensions); project.setScm(scm);/*from w w w. ja va2 s . co m*/ String tagNameReference = envReference + "-tag"; // ${BRANCH_NAME}-tag String tagNameValue = envValue + "-tag"; // master-tag String tagMessageReference = envReference + " tag message"; String noteReference = "note for " + envReference; String noteValue = "note for " + envValue; GitPublisher publisher = new GitPublisher( Collections .singletonList(new TagToPush("origin", tagNameReference, tagMessageReference, false, true)), Collections.singletonList(new BranchToPush("origin", envReference)), Collections .singletonList(new NoteToPush("origin", noteReference, Constants.R_NOTES_COMMITS, false)), true, true, true); assertTrue(publisher.isForcePush()); assertTrue(publisher.isPushBranches()); assertTrue(publisher.isPushMerge()); assertTrue(publisher.isPushNotes()); assertTrue(publisher.isPushOnlyIfSuccess()); assertTrue(publisher.isPushTags()); project.getPublishersList().add(publisher); // create initial commit commitNewFile("commitFileBase"); ObjectId initialCommit = testGitClient.getHeadRev(testGitDir.getAbsolutePath(), "master"); assertTrue(testGitClient.isCommitInRepo(initialCommit)); // Create branch in the test repo (pulled into the project workspace at build) assertFalse("Test repo has " + envValue + " branch", hasBranch(envValue)); testGitClient.branch(envValue); assertTrue("Test repo missing " + envValue + " branch", hasBranch(envValue)); assertFalse(tagNameValue + " in " + testGitClient, testGitClient.tagExists(tagNameValue)); // Build the branch final FreeStyleBuild build0 = build(project, Result.SUCCESS, "commitFileBase"); String build0HeadBranch = getHeadRevision(build0, envValue); assertEquals(build0HeadBranch, initialCommit.getName()); assertTrue(tagNameValue + " not in " + testGitClient, testGitClient.tagExists(tagNameValue)); assertTrue(tagNameValue + " not in build", build0.getWorkspace().child(".git/refs/tags/" + tagNameValue).exists()); // Create a topic branch in the source repository and commit to topic branch String topicBranch = envValue + "-topic1"; assertFalse("Test repo has " + topicBranch + " branch", hasBranch(topicBranch)); testGitClient.checkout(null, topicBranch); assertTrue("Test repo has no " + topicBranch + " branch", hasBranch(topicBranch)); final String commitFile1 = "commitFile1"; commitNewFile(commitFile1); ObjectId topicCommit = testGitClient.getHeadRev(testGitDir.getAbsolutePath(), topicBranch); assertTrue(testGitClient.isCommitInRepo(topicCommit)); // Run a build, should be on the topic branch, tagged, and noted final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); FilePath myWorkspace = build1.getWorkspace(); assertTrue(myWorkspace.child(commitFile1).exists()); assertTrue("Tag " + tagNameValue + " not in build", myWorkspace.child(".git/refs/tags/" + tagNameValue).exists()); String build1Head = getHeadRevision(build1, envValue); assertEquals(build1Head, testGitClient.revParse(Constants.HEAD).name()); assertEquals("Wrong head commit in build1", topicCommit.getName(), build1Head); }
From source file:info.debatty.sparkpackages.maven.plugin.PublishMojo.java
License:Open Source License
final String getGitCommit() throws MojoFailureException { Repository git_repository = null;/*from ww w.j a v a 2s .c o m*/ try { git_repository = new FileRepositoryBuilder().setMustExist(true) .findGitDir(new File(getProject().getBasedir().getAbsolutePath())).build(); } catch (IOException ex) { throw new MojoFailureException("GIT repo not found!", ex); } ObjectId resolve = null; try { resolve = git_repository.resolve("HEAD"); } catch (IncorrectObjectTypeException ex) { throw new MojoFailureException("GIT error!", ex); } catch (RevisionSyntaxException | IOException ex) { throw new MojoFailureException("GIT error!", ex); } return resolve.getName(); }
From source file:io.apigee.buildTools.enterprise4g.utils.GitUtil.java
License:Apache License
/** * IMP NOTE: Tag number will be displayed only if git tags are peeled manually using the command "git gc" * @return/*from w ww .j a v a2 s .co m*/ */ public String getTagNameForWorkspaceHeadRevision() { String headRevision = getWorkspaceHeadRevisionString(); Map<String, Ref> tags = git.getRepository().getAllRefs(); for (Ref tagRef : tags.values()) { String tagName = tagRef.getName(); ObjectId obj = tagRef.getPeeledObjectId(); if (obj == null) obj = tagRef.getObjectId(); // System.out.println(">>>>>>>>>>>>>>>>>" + tagRef.getName() + "," + // obj.getName() +"," + headRevision ); if (headRevision.equals(obj.getName())) { if (tagName.contains("/tags/")) { int lastSlashIndex = tagName.lastIndexOf("/"); if (lastSlashIndex > 0) { tagName = tagName.substring(lastSlashIndex + 1); return tagName; } } } } return null; }
From source file:io.fabric8.forge.rest.git.RepositoryResource.java
License:Apache License
protected List<CommitTreeInfo> doGetCommitTree(Git git, String commitId) { Repository repository = git.getRepository(); List<CommitTreeInfo> list = new ArrayList<CommitTreeInfo>(); RevCommit commit = CommitUtils.getCommit(repository, commitId); if (commit != null) { RevWalk rw = new RevWalk(repository); try {/*from w w w .j ava2 s. co m*/ if (commit.getParentCount() == 0) { TreeWalk treeWalk = new TreeWalk(repository); treeWalk.reset(); treeWalk.setRecursive(true); treeWalk.addTree(commit.getTree()); while (treeWalk.next()) { String pathString = treeWalk.getPathString(); ObjectId objectId = treeWalk.getObjectId(0); int rawMode = treeWalk.getRawMode(0); list.add(new CommitTreeInfo(pathString, pathString, 0, rawMode, objectId.getName(), commit.getId().getName(), DiffEntry.ChangeType.ADD)); } treeWalk.close(); } else { RevCommit parent = rw.parseCommit(commit.getParent(0).getId()); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree()); for (DiffEntry diff : diffs) { String objectId = diff.getNewId().name(); if (diff.getChangeType().equals(DiffEntry.ChangeType.DELETE)) { list.add(new CommitTreeInfo(diff.getOldPath(), diff.getOldPath(), 0, diff.getNewMode().getBits(), objectId, commit.getId().getName(), diff.getChangeType())); } else if (diff.getChangeType().equals(DiffEntry.ChangeType.RENAME)) { list.add(new CommitTreeInfo(diff.getOldPath(), diff.getNewPath(), 0, diff.getNewMode().getBits(), objectId, commit.getId().getName(), diff.getChangeType())); } else { list.add(new CommitTreeInfo(diff.getNewPath(), diff.getNewPath(), 0, diff.getNewMode().getBits(), objectId, commit.getId().getName(), diff.getChangeType())); } } } } catch (Throwable e) { LOG.warn("Failed to walk tree for commit " + commitId + ". " + e, e); } finally { rw.dispose(); } } return list; }
From source file:io.fabric8.git.internal.DefaultPullPushPolicy.java
License:Apache License
@Override public synchronized PullPolicyResult doPull(GitContext context, CredentialsProvider credentialsProvider, boolean allowVersionDelete) { Repository repository = git.getRepository(); StoredConfig config = repository.getConfig(); String remoteUrl = config.getString("remote", remoteRef, "url"); if (remoteUrl == null) { LOGGER.debug("No remote repository defined, so not doing a pull"); return new AbstractPullPolicyResult(); }/* ww w .j ava 2 s. co m*/ LOGGER.info("Performing a pull on remote URL: {}", remoteUrl); Exception lastException = null; try { git.fetch().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider).setRemote(remoteRef) .call(); } catch (GitAPIException | JGitInternalException ex) { lastException = ex; } // No meaningful processing after GitAPIException if (lastException != null) { LOGGER.warn("Pull failed because of: {}", lastException.toString()); return new AbstractPullPolicyResult(lastException); } // Get local and remote branches Map<String, Ref> localBranches = new HashMap<String, Ref>(); Map<String, Ref> remoteBranches = new HashMap<String, Ref>(); Set<String> allBranches = new HashSet<String>(); try { for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) { if (ref.getName().startsWith("refs/remotes/" + remoteRef + "/")) { String name = ref.getName().substring(("refs/remotes/" + remoteRef + "/").length()); remoteBranches.put(name, ref); allBranches.add(name); } else if (ref.getName().startsWith("refs/heads/")) { String name = ref.getName().substring(("refs/heads/").length()); localBranches.put(name, ref); allBranches.add(name); } } boolean localUpdate = false; boolean remoteUpdate = false; Set<String> versions = new TreeSet<>(); // Remote repository has no branches, force a push if (remoteBranches.isEmpty()) { LOGGER.debug("Pulled from an empty remote repository"); return new AbstractPullPolicyResult(versions, false, !localBranches.isEmpty(), null); } else { LOGGER.debug("Processing remote branches: {}", remoteBranches); } // Verify master branch and do a checkout of it when we have it locally (already) IllegalStateAssertion.assertTrue(remoteBranches.containsKey(GitHelpers.MASTER_BRANCH), "Remote repository does not have a master branch"); if (localBranches.containsKey(GitHelpers.MASTER_BRANCH)) { git.checkout().setName(GitHelpers.MASTER_BRANCH).setForce(true).call(); } // Iterate over all local/remote branches for (String branch : allBranches) { // Delete a local branch that does not exist remotely, but not master boolean allowDelete = allowVersionDelete && !GitHelpers.MASTER_BRANCH.equals(branch); if (localBranches.containsKey(branch) && !remoteBranches.containsKey(branch)) { if (allowDelete) { LOGGER.debug("Deleting local branch: {}", branch); git.branchDelete().setBranchNames(branch).setForce(true).call(); localUpdate = true; } else { remoteUpdate = true; } } // Create a local branch that exists remotely else if (!localBranches.containsKey(branch) && remoteBranches.containsKey(branch)) { LOGGER.debug("Adding local branch: {}", branch); git.checkout().setCreateBranch(true).setName(branch).setStartPoint(remoteRef + "/" + branch) .setUpstreamMode(SetupUpstreamMode.TRACK).setForce(true).call(); versions.add(branch); localUpdate = true; } // Update a local branch that also exists remotely else if (localBranches.containsKey(branch) && remoteBranches.containsKey(branch)) { ObjectId localObjectId = localBranches.get(branch).getObjectId(); ObjectId remoteObjectId = remoteBranches.get(branch).getObjectId(); String localCommit = localObjectId.getName(); String remoteCommit = remoteObjectId.getName(); if (!localCommit.equals(remoteCommit)) { git.clean().setCleanDirectories(true).call(); git.checkout().setName("HEAD").setForce(true).call(); git.checkout().setName(branch).setForce(true).call(); MergeResult mergeResult = git.merge().setFastForward(FastForwardMode.FF_ONLY) .include(remoteObjectId).call(); MergeStatus mergeStatus = mergeResult.getMergeStatus(); LOGGER.debug("Updating local branch {} with status: {}", branch, mergeStatus); if (mergeStatus == MergeStatus.FAST_FORWARD) { localUpdate = true; } else if (mergeStatus == MergeStatus.ALREADY_UP_TO_DATE) { remoteUpdate = true; } else if (mergeStatus == MergeStatus.ABORTED) { LOGGER.debug("Cannot fast forward branch {}, attempting rebase", branch); RebaseResult rebaseResult = git.rebase().setUpstream(remoteCommit).call(); RebaseResult.Status rebaseStatus = rebaseResult.getStatus(); if (rebaseStatus == RebaseResult.Status.OK) { localUpdate = true; remoteUpdate = true; } else { LOGGER.warn("Rebase on branch {} failed, restoring remote branch", branch); git.rebase().setOperation(Operation.ABORT).call(); git.checkout().setName(GitHelpers.MASTER_BRANCH).setForce(true).call(); git.branchDelete().setBranchNames(branch).setForce(true).call(); git.checkout().setCreateBranch(true).setName(branch) .setStartPoint(remoteRef + "/" + branch) .setUpstreamMode(SetupUpstreamMode.TRACK).setForce(true).call(); localUpdate = true; } } } versions.add(branch); } } PullPolicyResult result = new AbstractPullPolicyResult(versions, localUpdate, remoteUpdate, null); LOGGER.info("Pull result: {}", result); return result; } catch (Exception ex) { return new AbstractPullPolicyResult(ex); } }
From source file:io.hawt.git.GitFacadeSupport.java
License:Apache License
/** * Returns the file changes in a commit/*from ww w .j ava 2 s .c o m*/ */ protected List<CommitTreeInfo> doGetCommitTree(Git git, String commitId) { Repository repository = git.getRepository(); List<CommitTreeInfo> list = new ArrayList<CommitTreeInfo>(); RevCommit commit = CommitUtils.getCommit(repository, commitId); if (commit != null) { RevWalk rw = new RevWalk(repository); try { if (commit.getParentCount() == 0) { TreeWalk treeWalk = new TreeWalk(repository); treeWalk.reset(); treeWalk.setRecursive(true); treeWalk.addTree(commit.getTree()); while (treeWalk.next()) { String pathString = treeWalk.getPathString(); ObjectId objectId = treeWalk.getObjectId(0); int rawMode = treeWalk.getRawMode(0); list.add(new CommitTreeInfo(pathString, pathString, 0, rawMode, objectId.getName(), commit.getId().getName(), ChangeType.ADD)); } treeWalk.close(); } else { RevCommit parent = rw.parseCommit(commit.getParent(0).getId()); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree()); for (DiffEntry diff : diffs) { String objectId = diff.getNewId().name(); if (diff.getChangeType().equals(ChangeType.DELETE)) { list.add(new CommitTreeInfo(diff.getOldPath(), diff.getOldPath(), 0, diff.getNewMode().getBits(), objectId, commit.getId().getName(), diff.getChangeType())); } else if (diff.getChangeType().equals(ChangeType.RENAME)) { list.add(new CommitTreeInfo(diff.getOldPath(), diff.getNewPath(), 0, diff.getNewMode().getBits(), objectId, commit.getId().getName(), diff.getChangeType())); } else { list.add(new CommitTreeInfo(diff.getNewPath(), diff.getNewPath(), 0, diff.getNewMode().getBits(), objectId, commit.getId().getName(), diff.getChangeType())); } } } } catch (Throwable e) { LOG.warn("Failed to walk tree for commit " + commitId + ". " + e, e); } finally { rw.dispose(); } } return list; }
From source file:io.macgyver.plugin.git.GitResourceProvider.java
License:Apache License
@Override public Resource getResourceByPath(String path) throws IOException { refreshIfNecessary();/* w ww . j a v a2 s. co m*/ TreeWalk tw = null; RevWalk rw = null; try { ObjectId headCommit = repo.resolve(getGitRef()); rw = new RevWalk(repo); tw = TreeWalk.forPath(repo, path, rw.parseCommit(headCommit).getTree()); if (tw == null) { throw new FileNotFoundException( path + " not found in ref " + getGitRef() + " (" + headCommit.getName() + ")"); } ObjectId id = tw.getObjectId(0); GitResourceImpl gri = new GitResourceImpl(this, id, path); return gri; } finally { if (tw != null) { tw.release(); } if (rw != null) { rw.release(); } } }
From source file:jenkins.plugins.git.GitSCMFileSystemTest.java
License:Open Source License
@Test public void given_filesystem_when_askingChangesSinceSameRevision_then_changesAreEmpty() throws Exception { File gitDir = new File("."); GitClient client = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using("git").getClient(); ObjectId git261 = client.revParse("git-2.6.1"); AbstractGitSCMSource.SCMRevisionImpl rev261 = new AbstractGitSCMSource.SCMRevisionImpl( new SCMHead("origin"), git261.getName()); GitSCMFileSystem instance = new GitSCMFileSystem(client, "origin", git261.getName(), rev261); ByteArrayOutputStream out = new ByteArrayOutputStream(); assertFalse(instance.changesSince(rev261, out)); assertThat(out.toString(), is("")); }
From source file:jenkins.plugins.git.GitSCMFileSystemTest.java
License:Open Source License
@Test public void given_filesystem_when_askingChangesSinceOldRevision_then_changesArePopulated() throws Exception { File gitDir = new File("."); GitClient client = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using("git").getClient(); ObjectId git261 = client.revParse("git-2.6.1"); AbstractGitSCMSource.SCMRevisionImpl rev261 = new AbstractGitSCMSource.SCMRevisionImpl( new SCMHead("origin"), git261.getName()); GitSCMFileSystem instance = new GitSCMFileSystem(client, "origin", git261.getName(), rev261); ObjectId git260 = client.revParse("git-2.6.0"); AbstractGitSCMSource.SCMRevisionImpl rev260 = new AbstractGitSCMSource.SCMRevisionImpl( new SCMHead("origin"), git260.getName()); assertThat(git260, not(is(git261))); ByteArrayOutputStream out = new ByteArrayOutputStream(); assertTrue(instance.changesSince(rev260, out)); assertThat(out.toString(), containsString("prepare release git-2.6.1")); }