List of usage examples for org.eclipse.jgit.lib ObjectId equals
@SuppressWarnings({ "NonOverridingEquals", "AmbiguousMethodReference" }) public final boolean equals(AnyObjectId other)
From source file:com.mangosolutions.rcloud.rawgist.repository.git.BareCommitCommand.java
/** * Executes the {@code commit} command with all the options and parameters * collected by the setter methods of this class. Each instance of this * class should only be used for one invocation of the command (means: one * call to {@link #call()})//from w w w .ja v a 2 s. com * * @return a {@link RevCommit} object representing the successful commit. * @throws NoHeadException * when called on a git repo without a HEAD reference * @throws NoMessageException * when called without specifying a commit message * @throws UnmergedPathsException * when the current index contained unmerged paths (conflicts) * @throws ConcurrentRefUpdateException * when HEAD or branch ref is updated concurrently by someone * else * @throws WrongRepositoryStateException * when repository is not in the right state for committing * @throws AbortedByHookException * if there are either pre-commit or commit-msg hooks present in * the repository and one of them rejects the commit. */ public RevCommit call() throws GitAPIException, NoHeadException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException, WrongRepositoryStateException, AbortedByHookException { checkCallable(); Collections.sort(only); try (RevWalk rw = new RevWalk(repo)) { RepositoryState state = repo.getRepositoryState(); if (!noVerify) { Hooks.preCommit(repo, hookOutRedirect).call(); } processOptions(state, rw); if (all && !repo.isBare()) { try (Git git = new Git(repo)) { git.add().addFilepattern(".") //$NON-NLS-1$ .setUpdate(true).call(); } catch (NoFilepatternException e) { // should really not happen throw new JGitInternalException(e.getMessage(), e); } } Ref head = repo.findRef(Constants.HEAD); if (head == null) { throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported); } // determine the current HEAD and the commit it is referring to ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$ if (headId == null && amend) throw new WrongRepositoryStateException(JGitText.get().commitAmendOnInitialNotPossible); if (headId != null) { if (amend) { RevCommit previousCommit = rw.parseCommit(headId); for (RevCommit p : previousCommit.getParents()) parents.add(p.getId()); if (author == null) author = previousCommit.getAuthorIdent(); } else { parents.add(0, headId); } } if (!noVerify) { message = Hooks.commitMsg(repo, hookOutRedirect).setCommitMessage(message).call(); } // lock the index // DirCache index = repo.lockDirCache(); index.lock(); try (ObjectInserter odi = repo.newObjectInserter()) { if (!only.isEmpty()) index = createTemporaryIndex(headId, index, rw); // Write the index as tree to the object database. This may // fail for example when the index contains unmerged paths // (unresolved conflicts) ObjectId indexTreeId = index.writeTree(odi); if (insertChangeId) insertChangeId(indexTreeId); // Check for empty commits if (headId != null && !allowEmpty.booleanValue()) { RevCommit headCommit = rw.parseCommit(headId); headCommit.getTree(); if (indexTreeId.equals(headCommit.getTree())) { return null; } } // Create a Commit object, populate it and write it CommitBuilder commit = new CommitBuilder(); commit.setCommitter(committer); commit.setAuthor(author); commit.setMessage(message); commit.setParentIds(parents); commit.setTreeId(indexTreeId); ObjectId commitId = odi.insert(commit); odi.flush(); RevCommit revCommit = rw.parseCommit(commitId); RefUpdate ru = repo.updateRef(Constants.HEAD); ru.setNewObjectId(commitId); if (reflogComment != null) { ru.setRefLogMessage(reflogComment, false); } else { String prefix = amend ? "commit (amend): " //$NON-NLS-1$ : parents.size() == 0 ? "commit (initial): " //$NON-NLS-1$ : "commit: "; //$NON-NLS-1$ ru.setRefLogMessage(prefix + revCommit.getShortMessage(), false); } if (headId != null) { ru.setExpectedOldObjectId(headId); } else { ru.setExpectedOldObjectId(ObjectId.zeroId()); } Result rc = ru.forceUpdate(); switch (rc) { case NEW: case FORCED: case FAST_FORWARD: { setCallable(false); if (state == RepositoryState.MERGING_RESOLVED || isMergeDuringRebase(state)) { // Commit was successful. Now delete the files // used for merge commits repo.writeMergeCommitMsg(null); repo.writeMergeHeads(null); } else if (state == RepositoryState.CHERRY_PICKING_RESOLVED) { repo.writeMergeCommitMsg(null); repo.writeCherryPickHead(null); } else if (state == RepositoryState.REVERTING_RESOLVED) { repo.writeMergeCommitMsg(null); repo.writeRevertHead(null); } return revCommit; } case REJECTED: case LOCK_FAILURE: throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc); default: throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, Constants.HEAD, commitId.toString(), rc)); } } finally { index.unlock(); } } catch (UnmergedPathException e) { throw new UnmergedPathsException(e); } catch (IOException e) { throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e); } }
From source file:com.mooregreatsoftware.gitprocess.lib.Branch.java
License:Apache License
public boolean contains(@NonNull ObjectId oid) { LOG.debug("{}.contains({})", this, oid.abbreviate(7).name()); return Try.of(() -> { final RevWalk walk = new RevWalk(gitLib.repository()); try {//from w w w . ja v a 2s. c o m walk.setRetainBody(false); final RevCommit topOfThisBranch = walk.parseCommit(objectId()); walk.markStart(topOfThisBranch); return StreamSupport.stream(walk.spliterator(), false) .anyMatch(commit -> oid.equals(commit.getId())); } finally { walk.dispose(); } }).getOrElseThrow((Function<Throwable, IllegalStateException>) IllegalStateException::new); }
From source file:com.mooregreatsoftware.gitprocess.process.Sync.java
License:Apache License
/** * @return Left(error message), Right(the Pusher to use) *///from w w w . j a va2 s. c om @SuppressWarnings("PointlessBooleanExpression") private static <T> Either<String, Pusher> handleRemoteChanged(GitLib gitLib, Branch currentBranch, Combiner<T> combiner) { LOG.debug("Handle potential remote changed"); final ObjectId remoteOID = currentBranch.remoteOID(); final Either<String, @Nullable ObjectId> eLastSynced = currentBranch.lastSyncedAgainst(); if (eLastSynced.isLeft()) return left(eLastSynced.getLeft()); final ObjectId lastSyncedOID = eLastSynced.get(); if (lastSyncedOID != null) { // deal with possible change if (remoteOID == null) { LOG.warn("The remote version of this branch has disappeared"); return right(Pusher.create(gitLib, currentBranch, currentBranch.simpleName())); } if (remoteOID.equals(lastSyncedOID)) { LOG.debug("The last synced OID is the same as the remote OID: {}", remoteOID.abbreviate(7).name()); if (currentBranch.contains(remoteOID)) { LOG.debug("\"{}\" contains {} so will do a normal fast-forward push", currentBranch.simpleName(), remoteOID.abbreviate(7).name()); return right(Pusher.create(gitLib, currentBranch, currentBranch.simpleName())); } else { LOG.debug( "{} does not appear in the history of \"{}\", but since it was not remotely " + "changed going to assume that the local copy is correct and will force push", remoteOID.abbreviate(7).name(), currentBranch.simpleName()); return right( Pusher.create(gitLib, currentBranch, currentBranch.simpleName(), true, null, null)); } } else { LOG.warn( "The remote branch has changed since the last time this was " + "synced ({} -> {}) so attempting to reconcile", lastSyncedOID.abbreviate(7).name(), remoteOID.abbreviate(7).name()); // reconcile against the remote branch return reconcileWithRemoteBranch(gitLib, currentBranch, combiner); } } else { LOG.debug("This has not been synced before"); if (remoteOID == null) { return right(Pusher.create(gitLib, currentBranch, currentBranch.simpleName())); } if (currentBranch.contains(remoteOID)) { LOG.debug("\"{}\" contains {} so will do a normal fast-forward push", currentBranch.simpleName(), remoteOID.abbreviate(7).name()); return right(Pusher.create(gitLib, currentBranch, currentBranch.simpleName())); } else { LOG.warn("The remote branch has changed since this branch was " + "created (i.e., it does not contain the remote revision {}) so attempting to reconcile", remoteOID.abbreviate(7).name()); // reconcile against the remote branch return reconcileWithRemoteBranch(gitLib, currentBranch, combiner); } } }
From source file:com.redhat.jenkins.nodesharing.ConfigRepo.java
License:Open Source License
/** * Get snapshot or remote repo state or the last working. * * @return Latest snapshot or the most recent working one if latest can not be get. * @throws InterruptedException When thread was interrupted while creating snapshot. * @throws IOException When failed to create the log file for the operation. * @throws TaskLog.TaskFailed When there ware problems reading the snapshot. *//*from w ww. j av a 2 s .c om*/ public @Nonnull Snapshot getSnapshot() throws InterruptedException, IOException, TaskLog.TaskFailed { Files.createDirectories(workingDir.toPath()); TaskLog taskLog = new TaskLog(new File(workingDir.getAbsolutePath() + ".log")); try { ObjectId currentHead = getRemoteHead(taskLog); synchronized (repoLock) { if (snapshot != null && currentHead.equals(snapshot.source)) { LOGGER.fine("No config update in " + url + " after: " + snapshot.source.name()); } else { taskLog.getLogger().printf("Node sharing config changes discovered %s%nPulling %s to %s%n", currentHead.name(), url, workingDir); fetchChanges(taskLog); ObjectId checkedOutHead = getClient(taskLog).revParse("HEAD"); assert currentHead.equals(checkedOutHead) : "What was discovered was in fact checked out"; snapshot = readConfig(currentHead, taskLog); } } } catch (IOException | GitException ex) { taskLog.error(ex, "Unable to update config repo from %s", url); } finally { taskLog.close(); } taskLog.throwIfFailed("Unable to read snapshot from " + url); assert snapshot != null; return snapshot; }
From source file:com.tasktop.c2c.server.scm.service.EventGeneratingPostRecieveHook.java
License:Open Source License
private void sendCommitsInternal(Repository repo, String refName, ObjectId oldId, ObjectId newId) throws IOException { Ref ref = repo.getRef(refName); if (!newId.equals(ref.getObjectId())) { throw new IllegalStateException(); }/*from w w w .j a va 2 s . c o m*/ RevWalk revWal = new RevWalk(repo); revWal.markStart(revWal.parseCommit(ref.getObjectId())); if (!oldId.equals(ObjectId.zeroId())) { revWal.markUninteresting(revWal.parseCommit(oldId)); } List<Commit> eventCommits = new ArrayList<Commit>(); for (RevCommit revCommit : revWal) { Commit commit = GitDomain.createCommit(revCommit); commit.setRepository(repo.getDirectory().getName()); commit.setUrl(configuration.getWebUrlForCommit(TenancyUtil.getCurrentTenantProjectIdentifer(), commit)); eventCommits.add(commit); } PushEvent event = new PushEvent(); event.setUserId(Security.getCurrentUser()); event.setCommits(eventCommits); event.setProjectId(TenancyUtil.getCurrentTenantProjectIdentifer()); event.setTimestamp(new Date()); event.setRefName(refName); eventService.publishEvent(event); }
From source file:fr.brouillard.oss.jgitver.GitVersionCalculator.java
License:Apache License
private List<Ref> tagsOf(List<Ref> tags, final ObjectId id) { return tags.stream().filter(ref -> id.equals(ref.getObjectId()) || id.equals(ref.getPeeledObjectId())) .collect(Collectors.toList()); }
From source file:io.fabric8.git.zkbridge.BridgeTest.java
License:Apache License
@Test public void testNoLocalNorRemoteBranch() throws Exception { deleteSafe(curator, ZkPath.CONFIG_VERSIONS.getPath()); setData(curator, ZkPath.CONFIG_VERSION.getPath("1.0"), "description = default version\n"); setData(curator, ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", "p1") + "/thepid.properties", "foo = bar\n"); setData(curator, ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", "p1") + "/thexml.xml", "<hello/>\n"); setData(curator, ZkPath.CONFIG_VERSIONS_CONTAINER.getPath("1.0", "root"), "p1"); ObjectId rev1 = git.getRepository().getRef("HEAD").getObjectId(); Bridge.update(git, curator);/* ww w. j a v a 2s .com*/ ObjectId rev2 = git.getRepository().getRef("HEAD").getObjectId(); Bridge.update(git, curator); ObjectId rev3 = git.getRepository().getRef("HEAD").getObjectId(); assertFalse(rev1.equals(rev2)); assertTrue(rev2.equals(rev3)); remote.checkout().setName("1.0").call(); File tree = remote.getRepository().getWorkTree(); Files.writeToFile(new File(tree, "p2/.metadata"), "\n", Charset.forName("UTF-8")); Files.writeToFile(new File(tree, "p2/anotherpid.properties"), "key = value\n", Charset.forName("UTF-8")); remote.add().addFilepattern(".").call(); remote.commit().setMessage("Add p2 profile").call(); setData(curator, ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", "p3") + "/thepid.properties", "foo = bar\n"); rev1 = git.getRepository().getRef("HEAD").getObjectId(); Bridge.update(git, curator); rev2 = git.getRepository().getRef("HEAD").getObjectId(); Bridge.update(git, curator); rev3 = git.getRepository().getRef("HEAD").getObjectId(); assertFalse(rev1.equals(rev2)); assertTrue(rev2.equals(rev3)); }
From source file:jbyoshi.gitupdate.processor.Push.java
License:Apache License
private static void process(Repository repo, Git git, String remote, Collection<String> branches, Report report) throws Exception { // Figure out if anything needs to be pushed. Map<String, ObjectId> oldIds = new HashMap<>(); boolean canPush = false; for (String branch : branches) { BranchConfig config = new BranchConfig(repo.getConfig(), branch); ObjectId target = repo.getRef(branch).getObjectId(); Ref remoteRef = repo.getRef(config.getRemoteTrackingBranch()); if (remoteRef == null || !target.equals(remoteRef.getObjectId())) { canPush = true;// w w w . j a v a 2s . c o m } oldIds.put(branch, remoteRef == null ? ObjectId.zeroId() : remoteRef.getObjectId()); } if (!canPush) { return; } PushCommand push = git.push().setCredentialsProvider(Prompts.INSTANCE).setTimeout(5).setRemote(remote); for (String branch : branches) { push.add(Constants.R_HEADS + branch); } for (PushResult result : push.call()) { for (RemoteRefUpdate update : result.getRemoteUpdates()) { if (update.getStatus() == RemoteRefUpdate.Status.OK) { String branchName = Utils.getShortBranch(update.getSrcRef()); ObjectId oldId = oldIds.get(branchName); String old = oldId.equals(ObjectId.zeroId()) ? "new branch" : oldId.name(); report.newChild(branchName + ": " + old + " -> " + update.getNewObjectId().name()).modified(); } } } }
From source file:net.jsenko.jpct.RunMojo.java
License:Apache License
/** * Helper method for creating patch file. If the destination file and parent directories do not exist, attempts to create * them/*from w w w . j ava2 s . c o m*/ */ private ObjectId createPatch(File patchFile) throws MojoExecutionException { Ref topicBranchRef = gitTools.getRef(topicBranch); if (topicBranchRef == null) fail("Topic branch referenced by '" + topicBranch + "' does not exist."); ObjectId base = gitTools.findBase(topicBranch, gitRemoteName); // TODO reuse "topicBranchRef" if (base == null) fail("Failed to compute base commit. " + "Check that there exist at least one 'refs/remotes/" + gitRemoteName + "/*' branch."); if (base.equals(topicBranchRef.getObjectId())) log.warn("The changes do not contain any commit. If -DincludeStaged is not used " + "(and something is actually staged) the build may fail!"); if (!gitTools.createPatch(patchFile, base, topicBranchRef.getObjectId(), includeStaged)) fail("Failed to generate a patch."); return base; }
From source file:net.morimekta.gittool.cmd.Status.java
License:Apache License
@Override public void execute(GitTool gt) throws IOException { try (Repository repository = gt.getRepository()) { RepositoryState state = repository.getRepositoryState(); if (state != RepositoryState.SAFE) { System.out.println(WARN + "Repository not in a safe state" + CLEAR + ": " + state.getDescription()); }// ww w . j a v a 2s.com Git git = new Git(repository); String currentBranch = repository.getBranch(); String diffWithBranch = branch != null ? branch : gt.getDiffbase(currentBranch); this.root = gt.getRepositoryRoot().getCanonicalFile().getAbsolutePath(); Ref currentRef = repository.getRef(gt.refName(currentBranch)); Ref diffWithRef = repository.getRef(gt.refName(diffWithBranch)); if (diffWithRef == null) { System.out.println(format("No such branch %s%s%s", BOLD, diffWithBranch, CLEAR)); return; } ObjectId currentHead = currentRef.getObjectId(); ObjectId diffWithHead = diffWithRef.getObjectId(); // RevCommit currentCommit = commitOf(repository, currentHead); if (!currentHead.equals(diffWithHead)) { String stats = ""; String diff = gt.isRemote(diffWithBranch) ? format("[->%s%s%s] ", DIM, diffWithBranch, CLEAR) : format("[d:%s%s%s] ", CLR_BASE_BRANCH, diffWithBranch, CLEAR); List<RevCommit> localCommits = ImmutableList .copyOf(git.log().addRange(diffWithHead, currentHead).call()); List<RevCommit> remoteCommits = ImmutableList .copyOf(git.log().addRange(currentHead, diffWithHead).call()); localCommits = Lists.reverse(localCommits); remoteCommits = Lists.reverse(remoteCommits); int commits = localCommits.size(); int missing = remoteCommits.size(); RevCommit ancestor, local; if (remoteCommits.size() > 0) { List<RevCommit> sub2 = Lists.reverse( ImmutableList.copyOf(git.log().add(remoteCommits.get(0)).setMaxCount(2).call())); ancestor = sub2.get(0); } else { ancestor = gt.commitOf(repository, diffWithBranch) .orElseThrow(() -> new IOException("No commit on " + diffWithBranch)); } if (localCommits.size() > 0) { local = localCommits.get(localCommits.size() - 1); } else { local = gt.commitOf(repository, currentBranch) .orElseThrow(() -> new IOException("No commit on " + currentBranch)); } if (commits > 0 || missing > 0) { if (commits == 0) { stats = format(" [%s-%d%s]", CLR_SUBS, missing, CLEAR); } else if (missing == 0) { stats = format(" [%s+%d%s]", CLR_ADDS, commits, CLEAR); } else { stats = format(" [%s+%d%s,%s-%d%s]", CLR_ADDS, commits, CLEAR, CLR_SUBS, missing, CLEAR); } } System.out.println(format("Commits on %s%s%s%s since %s -- %s%s%s%s", CLR_UPDATED_BRANCH, currentBranch, CLEAR, stats, date(ancestor), diff, DIM, ancestor.getShortMessage(), CLEAR)); if (files) { ObjectReader reader = repository.newObjectReader(); CanonicalTreeParser ancestorTreeIter = new CanonicalTreeParser(); ancestorTreeIter.reset(reader, ancestor.getTree()); CanonicalTreeParser localTreeIter = new CanonicalTreeParser(); localTreeIter.reset(reader, local.getTree()); // finally get the list of changed files List<DiffEntry> diffs = git.diff().setShowNameAndStatusOnly(true).setOldTree(ancestorTreeIter) .setNewTree(localTreeIter).call(); for (DiffEntry entry : diffs) { switch (entry.getChangeType()) { case RENAME: System.out.println(format(" R %s%s%s <- %s%s%s", new Color(YELLOW, DIM), entry.getNewPath(), CLEAR, DIM, path(entry.getOldPath()), CLEAR)); break; case MODIFY: System.out.println(format(" %s", path(entry.getOldPath()))); break; case ADD: System.out.println(format(" A %s%s%s", GREEN, path(entry.getNewPath()), CLEAR)); break; case DELETE: System.out.println(format(" D %s%s%s", YELLOW, path(entry.getOldPath()), CLEAR)); break; case COPY: System.out.println(format(" C %s%s%s <- %s%s%s", new Color(YELLOW, DIM), path(entry.getNewPath()), CLEAR, DIM, path(entry.getOldPath()), CLEAR)); break; } } } else { for (RevCommit localCommit : localCommits) { System.out.println(format("+ %s%s%s (%s)", GREEN, localCommit.getShortMessage(), CLEAR, date(localCommit))); } for (RevCommit remoteCommit : remoteCommits) { System.out.println(format("- %s%s%s (%s)", RED, remoteCommit.getShortMessage(), CLEAR, date(remoteCommit))); } } } else { RevCommit diffWithCommit = gt.commitOf(repository, diffWithBranch) .orElseThrow(() -> new IOException("No commit in " + diffWithBranch)); System.out.println(format("No commits on %s%s%s since %s -- %s%s%s", GREEN, currentBranch, CLEAR, date(diffWithCommit), DIM, diffWithCommit.getShortMessage(), CLEAR)); } // Check for staged and unstaged changes. if (files) { List<DiffEntry> staged = git.diff().setCached(true).call(); List<DiffEntry> unstaged = git.diff().setCached(false).call(); if (staged.size() > 0 || unstaged.size() > 0) { System.out.println(); System.out.println(format("%sUncommitted%s changes on %s%s%s:", RED, CLEAR, CLR_UPDATED_BRANCH, currentBranch, CLEAR)); Map<String, FileStatus> st = unstaged.stream().map(d -> new FileStatus(relative, root, d)) .collect(Collectors.toMap(FileStatus::getNewestPath, fs -> fs)); staged.forEach(d -> { if (d.getNewPath() != null) { if (st.containsKey(d.getNewPath())) { st.get(d.getNewPath()).setStaged(d); return; } } if (d.getOldPath() != null) { if (st.containsKey(d.getOldPath())) { st.get(d.getOldPath()).setStaged(d); return; } } FileStatus fs = new FileStatus(relative, root, null).setStaged(d); st.put(fs.getNewestPath(), fs); }); for (FileStatus fs : new TreeMap<>(st).values()) { System.out.println(fs.statusLine()); } } } else { List<DiffEntry> staged = git.diff().setShowNameAndStatusOnly(true).setCached(true).call(); List<DiffEntry> unstaged = git.diff().setShowNameAndStatusOnly(true).setCached(false).call(); if (staged.size() > 0 || unstaged.size() > 0) { System.out.println( format("Uncommitted changes on %s%s%s:", CLR_UPDATED_BRANCH, currentBranch, CLEAR)); if (staged.size() > 0) { long adds = staged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.ADD) .count(); long dels = staged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.DELETE) .count(); long mods = staged.size() - adds - dels; System.out.print(format(" - %sStaged files%s :", new Color(YELLOW, DIM), CLEAR)); if (adds > 0) { System.out.print(format(" %s+%d%s", GREEN, adds, CLEAR)); } if (dels > 0) { System.out.print(format(" %s-%d%s", RED, dels, CLEAR)); } if (mods > 0) { System.out.print(format(" %s/%d%s", DIM, mods, CLEAR)); } System.out.println(); } if (unstaged.size() > 0) { long adds = unstaged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.ADD) .count(); long dels = unstaged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.DELETE) .count(); long mods = unstaged.size() - adds - dels; System.out.print(format(" - %sUnstaged files%s :", YELLOW, CLEAR)); if (adds > 0) { System.out.print(format(" %s+%d%s", GREEN, adds, CLEAR)); } if (dels > 0) { System.out.print(format(" %s-%d%s", RED, dels, CLEAR)); } if (mods > 0) { System.out.print(format(" %s/%d%s", DIM, mods, CLEAR)); } System.out.println(); } } } } catch (GitAPIException e) { throw new IllegalStateException(e.getMessage(), e); } }