List of usage examples for org.eclipse.jgit.lib ObjectId toString
@SuppressWarnings("nls") @Override public String toString()
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 ww .j a v a 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:com.gitblit.build.BuildGhPages.java
License:Apache License
public static void main(String[] args) { Params params = new Params(); JCommander jc = new JCommander(params); try {/*from ww w. j a v a 2 s. com*/ jc.parse(args); } catch (ParameterException t) { System.err.println(t.getMessage()); jc.usage(); } File source = new File(params.sourceFolder); String ghpages = "refs/heads/gh-pages"; try { File gitDir = FileKey.resolve(new File(params.repositoryFolder), FS.DETECTED); Repository repository = new FileRepository(gitDir); RefModel issuesBranch = JGitUtils.getPagesBranch(repository); if (issuesBranch == null) { JGitUtils.createOrphanBranch(repository, "gh-pages", null); } System.out.println("Updating gh-pages branch..."); ObjectId headId = repository.resolve(ghpages + "^{commit}"); ObjectInserter odi = repository.newObjectInserter(); try { // Create the in-memory index of the new/updated issue. DirCache index = createIndex(repository, headId, source, params.obliterate); ObjectId indexTreeId = index.writeTree(odi); // Create a commit object PersonIdent author = new PersonIdent("Gitblit", "gitblit@localhost"); CommitBuilder commit = new CommitBuilder(); commit.setAuthor(author); commit.setCommitter(author); commit.setEncoding(Constants.CHARACTER_ENCODING); commit.setMessage("updated pages"); commit.setParentId(headId); commit.setTreeId(indexTreeId); // Insert the commit into the repository ObjectId commitId = odi.insert(commit); odi.flush(); RevWalk revWalk = new RevWalk(repository); try { RevCommit revCommit = revWalk.parseCommit(commitId); RefUpdate ru = repository.updateRef(ghpages); ru.setNewObjectId(commitId); ru.setExpectedOldObjectId(headId); ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false); Result rc = ru.forceUpdate(); switch (rc) { case NEW: case FORCED: case FAST_FORWARD: break; case REJECTED: case LOCK_FAILURE: throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc); default: throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, ghpages, commitId.toString(), rc)); } } finally { revWalk.release(); } } finally { odi.release(); } System.out.println("gh-pages updated."); } catch (Throwable t) { t.printStackTrace(); } }
From source file:com.gitblit.utils.IssueUtils.java
License:Apache License
/** * Deletes an issue from the repository. * /* w w w . j a v a 2s . co m*/ * @param repository * @param issueId * @return true if successful */ public static boolean deleteIssue(Repository repository, String issueId, String author) { boolean success = false; RefModel issuesBranch = getIssuesBranch(repository); if (issuesBranch == null) { throw new RuntimeException("gb-issues branch does not exist!"); } if (StringUtils.isEmpty(issueId)) { throw new RuntimeException("must specify an issue id!"); } String issuePath = getIssuePath(issueId); String message = "- " + issueId; try { ObjectId headId = repository.resolve(GB_ISSUES + "^{commit}"); ObjectInserter odi = repository.newObjectInserter(); try { // Create the in-memory index of the new/updated issue DirCache index = DirCache.newInCore(); DirCacheBuilder dcBuilder = index.builder(); // Traverse HEAD to add all other paths TreeWalk treeWalk = new TreeWalk(repository); int hIdx = -1; if (headId != null) hIdx = treeWalk.addTree(new RevWalk(repository).parseTree(headId)); treeWalk.setRecursive(true); while (treeWalk.next()) { String path = treeWalk.getPathString(); CanonicalTreeParser hTree = null; if (hIdx != -1) hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class); if (!path.startsWith(issuePath)) { // add entries from HEAD for all other paths if (hTree != null) { // create a new DirCacheEntry with data retrieved // from HEAD final DirCacheEntry dcEntry = new DirCacheEntry(path); dcEntry.setObjectId(hTree.getEntryObjectId()); dcEntry.setFileMode(hTree.getEntryFileMode()); // add to temporary in-core index dcBuilder.add(dcEntry); } } } // release the treewalk treeWalk.release(); // finish temporary in-core index used for this commit dcBuilder.finish(); ObjectId indexTreeId = index.writeTree(odi); // Create a commit object PersonIdent ident = new PersonIdent(author, "gitblit@localhost"); CommitBuilder commit = new CommitBuilder(); commit.setAuthor(ident); commit.setCommitter(ident); commit.setEncoding(Constants.CHARACTER_ENCODING); commit.setMessage(message); commit.setParentId(headId); commit.setTreeId(indexTreeId); // Insert the commit into the repository ObjectId commitId = odi.insert(commit); odi.flush(); RevWalk revWalk = new RevWalk(repository); try { RevCommit revCommit = revWalk.parseCommit(commitId); RefUpdate ru = repository.updateRef(GB_ISSUES); ru.setNewObjectId(commitId); ru.setExpectedOldObjectId(headId); ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false); Result rc = ru.forceUpdate(); switch (rc) { case NEW: case FORCED: case FAST_FORWARD: success = true; break; case REJECTED: case LOCK_FAILURE: throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc); default: throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, GB_ISSUES, commitId.toString(), rc)); } } finally { revWalk.release(); } } finally { odi.release(); } } catch (Throwable t) { error(t, repository, "Failed to delete issue {1} to {0}", issueId); } return success; }
From source file:com.gitblit.utils.IssueUtils.java
License:Apache License
/** * Commit a change to the repository. Each issue is composed on changes. * Issues are built from applying the changes in the order they were * committed to the repository. The changes are actually specified in the * commit messages and not in the RevTrees which allows for clean, * distributed merging./*from ww w. j a v a 2 s .c om*/ * * @param repository * @param issueId * @param change * @return true, if the change was committed */ private static boolean commit(Repository repository, String issueId, Change change) { boolean success = false; try { // assign ids to new attachments // attachments are stored by an SHA1 id if (change.hasAttachments()) { for (Attachment attachment : change.attachments) { if (!ArrayUtils.isEmpty(attachment.content)) { byte[] prefix = (change.created.toString() + change.author).getBytes(); byte[] bytes = new byte[prefix.length + attachment.content.length]; System.arraycopy(prefix, 0, bytes, 0, prefix.length); System.arraycopy(attachment.content, 0, bytes, prefix.length, attachment.content.length); attachment.id = "attachment-" + StringUtils.getSHA1(bytes); } } } // serialize the change as json // exclude any attachment from json serialization Gson gson = JsonUtils.gson(new ExcludeField("com.gitblit.models.IssueModel$Attachment.content")); String json = gson.toJson(change); // include the json change in the commit message String issuePath = getIssuePath(issueId); String message = change.code + " " + issueId + "\n\n" + json; // Create a commit file. This is required for a proper commit and // ensures we can retrieve the commit log of the issue path. // // This file is NOT serialized as part of the Change object. switch (change.code) { case '+': { // New Issue. Attachment placeholder = new Attachment("issue"); placeholder.id = placeholder.name; placeholder.content = "DO NOT REMOVE".getBytes(Constants.CHARACTER_ENCODING); change.addAttachment(placeholder); break; } default: { // Update Issue. String changeId = StringUtils.getSHA1(json); Attachment placeholder = new Attachment("change-" + changeId); placeholder.id = placeholder.name; placeholder.content = "REMOVABLE".getBytes(Constants.CHARACTER_ENCODING); change.addAttachment(placeholder); break; } } ObjectId headId = repository.resolve(GB_ISSUES + "^{commit}"); ObjectInserter odi = repository.newObjectInserter(); try { // Create the in-memory index of the new/updated issue DirCache index = createIndex(repository, headId, issuePath, change); ObjectId indexTreeId = index.writeTree(odi); // Create a commit object PersonIdent ident = new PersonIdent(change.author, "gitblit@localhost"); CommitBuilder commit = new CommitBuilder(); commit.setAuthor(ident); commit.setCommitter(ident); commit.setEncoding(Constants.CHARACTER_ENCODING); commit.setMessage(message); commit.setParentId(headId); commit.setTreeId(indexTreeId); // Insert the commit into the repository ObjectId commitId = odi.insert(commit); odi.flush(); RevWalk revWalk = new RevWalk(repository); try { RevCommit revCommit = revWalk.parseCommit(commitId); RefUpdate ru = repository.updateRef(GB_ISSUES); ru.setNewObjectId(commitId); ru.setExpectedOldObjectId(headId); ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false); Result rc = ru.forceUpdate(); switch (rc) { case NEW: case FORCED: case FAST_FORWARD: success = true; break; case REJECTED: case LOCK_FAILURE: throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc); default: throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, GB_ISSUES, commitId.toString(), rc)); } } finally { revWalk.release(); } } finally { odi.release(); } } catch (Throwable t) { error(t, repository, "Failed to commit issue {1} to {0}", issueId); } return success; }
From source file:com.gitblit.utils.JGitUtils.java
License:Apache License
public static boolean commitIndex(Repository db, String branch, DirCache index, ObjectId parentId, boolean forceCommit, String author, String authorEmail, String message) throws IOException, ConcurrentRefUpdateException { boolean success = false; ObjectId headId = db.resolve(branch + "^{commit}"); ObjectId baseId = parentId;//from w w w . j a v a2 s. c o m if (baseId == null || headId == null) { return false; } ObjectInserter odi = db.newObjectInserter(); try { // Create the in-memory index of the new/updated ticket ObjectId indexTreeId = index.writeTree(odi); // Create a commit object PersonIdent ident = new PersonIdent(author, authorEmail); if (forceCommit == false) { ThreeWayMerger merger = MergeStrategy.RECURSIVE.newMerger(db, true); merger.setObjectInserter(odi); merger.setBase(baseId); boolean mergeSuccess = merger.merge(indexTreeId, headId); if (mergeSuccess) { indexTreeId = merger.getResultTreeId(); } else { //Manual merge required return false; } } CommitBuilder commit = new CommitBuilder(); commit.setAuthor(ident); commit.setCommitter(ident); commit.setEncoding(com.gitblit.Constants.ENCODING); commit.setMessage(message); commit.setParentId(headId); commit.setTreeId(indexTreeId); // Insert the commit into the repository ObjectId commitId = odi.insert(commit); odi.flush(); RevWalk revWalk = new RevWalk(db); try { RevCommit revCommit = revWalk.parseCommit(commitId); RefUpdate ru = db.updateRef(branch); ru.setForceUpdate(forceCommit); ru.setNewObjectId(commitId); ru.setExpectedOldObjectId(headId); ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false); Result rc = ru.update(); switch (rc) { case NEW: case FORCED: case FAST_FORWARD: success = true; break; case REJECTED: case LOCK_FAILURE: throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc); default: throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, branch, commitId.toString(), rc)); } } finally { revWalk.close(); } } finally { odi.close(); } return success; }
From source file:com.gitblit.utils.PushLogUtils.java
License:Apache License
/** * Updates a push log.//from w w w.j a va 2s . c o m * * @param user * @param repository * @param commands * @return true, if the update was successful */ public static boolean updatePushLog(UserModel user, Repository repository, Collection<ReceiveCommand> commands) { RefModel pushlogBranch = getPushLogBranch(repository); if (pushlogBranch == null) { JGitUtils.createOrphanBranch(repository, GB_PUSHES, null); } boolean success = false; String message = "push"; try { ObjectId headId = repository.resolve(GB_PUSHES + "^{commit}"); ObjectInserter odi = repository.newObjectInserter(); try { // Create the in-memory index of the push log entry DirCache index = createIndex(repository, headId, commands); ObjectId indexTreeId = index.writeTree(odi); PersonIdent ident = new PersonIdent(user.getDisplayName(), user.emailAddress == null ? user.username : user.emailAddress); // Create a commit object CommitBuilder commit = new CommitBuilder(); commit.setAuthor(ident); commit.setCommitter(ident); commit.setEncoding(Constants.CHARACTER_ENCODING); commit.setMessage(message); commit.setParentId(headId); commit.setTreeId(indexTreeId); // Insert the commit into the repository ObjectId commitId = odi.insert(commit); odi.flush(); RevWalk revWalk = new RevWalk(repository); try { RevCommit revCommit = revWalk.parseCommit(commitId); RefUpdate ru = repository.updateRef(GB_PUSHES); ru.setNewObjectId(commitId); ru.setExpectedOldObjectId(headId); ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false); Result rc = ru.forceUpdate(); switch (rc) { case NEW: case FORCED: case FAST_FORWARD: success = true; break; case REJECTED: case LOCK_FAILURE: throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc); default: throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, GB_PUSHES, commitId.toString(), rc)); } } finally { revWalk.release(); } } finally { odi.release(); } } catch (Throwable t) { error(t, repository, "Failed to commit pushlog entry to {0}"); } return success; }
From source file:com.gitblit.utils.RefLogUtils.java
License:Apache License
/** * Updates the reflog with the received commands. * * @param user//from w ww . j a v a 2 s. co m * @param repository * @param commands * @return true, if the update was successful */ public static boolean updateRefLog(UserModel user, Repository repository, Collection<ReceiveCommand> commands) { // only track branches and tags List<ReceiveCommand> filteredCommands = new ArrayList<ReceiveCommand>(); for (ReceiveCommand cmd : commands) { if (!cmd.getRefName().startsWith(Constants.R_HEADS) && !cmd.getRefName().startsWith(Constants.R_TAGS)) { continue; } filteredCommands.add(cmd); } if (filteredCommands.isEmpty()) { // nothing to log return true; } RefModel reflogBranch = getRefLogBranch(repository); if (reflogBranch == null) { JGitUtils.createOrphanBranch(repository, GB_REFLOG, null); } boolean success = false; String message = "push"; try { ObjectId headId = repository.resolve(GB_REFLOG + "^{commit}"); ObjectInserter odi = repository.newObjectInserter(); try { // Create the in-memory index of the reflog log entry DirCache index = createIndex(repository, headId, commands); ObjectId indexTreeId = index.writeTree(odi); PersonIdent ident; if (UserModel.ANONYMOUS.equals(user)) { // anonymous push ident = new PersonIdent(user.username + "/" + user.username, user.username); } else { // construct real pushing account ident = new PersonIdent(MessageFormat.format("{0}/{1}", user.getDisplayName(), user.username), user.emailAddress == null ? user.username : user.emailAddress); } // Create a commit object CommitBuilder commit = new CommitBuilder(); commit.setAuthor(ident); commit.setCommitter(ident); commit.setEncoding(Constants.ENCODING); commit.setMessage(message); commit.setParentId(headId); commit.setTreeId(indexTreeId); // Insert the commit into the repository ObjectId commitId = odi.insert(commit); odi.flush(); RevWalk revWalk = new RevWalk(repository); try { RevCommit revCommit = revWalk.parseCommit(commitId); RefUpdate ru = repository.updateRef(GB_REFLOG); ru.setNewObjectId(commitId); ru.setExpectedOldObjectId(headId); ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false); Result rc = ru.forceUpdate(); switch (rc) { case NEW: case FORCED: case FAST_FORWARD: success = true; break; case REJECTED: case LOCK_FAILURE: throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc); default: throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, GB_REFLOG, commitId.toString(), rc)); } } finally { revWalk.close(); } } finally { odi.close(); } } catch (Throwable t) { error(t, repository, "Failed to commit reflog entry to {0}"); } return success; }
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()})/* w w w .j av a 2 s. c om*/ * * @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.microsoft.gittf.core.tasks.FetchTask.java
License:Open Source License
@Override public TaskStatus run(final TaskProgressMonitor progressMonitor) { boolean alreadyFetched = false; progressMonitor.beginTask(/*from ww w .java2s. c o m*/ Messages.formatString("FetchTask.FetchingVersionFormat", //$NON-NLS-1$ GitTFConfiguration.loadFrom(repository).getServerPath(), VersionSpecUtil.getDescription(versionSpec)), 1, TaskProgressDisplay.DISPLAY_PROGRESS.combine(TaskProgressDisplay.DISPLAY_SUBTASK_DETAIL)); final GitTFConfiguration configuration = GitTFConfiguration.loadFrom(repository); final ChangesetCommitMap changesetCommitMap = new ChangesetCommitMap(repository); int latestChangesetID = changesetCommitMap.getLastBridgedChangesetID(true); /* * If nothing has been fetched or checked in by Git-TF before, i.e. this * is a configured repo, we need to check if the Git repository itself * is not empty. In that case we have to show a message and exit. * Otherwise we may continue because that is the safe first fetch into * empty just configured repository. */ if (latestChangesetID < 0) { try { if (RepositoryUtil.isEmptyRepository(repository)) { log.info("This is a newly configured empty repository. Continue fetching"); //$NON-NLS-1$ latestChangesetID = 0; } else { return new TaskStatus(TaskStatus.ERROR, Messages.getString("FetchTask.NothingToFetchInNewlyConfiguredRepo")); //$NON-NLS-1$ } } catch (IOException e) { return new TaskStatus(TaskStatus.ERROR, e); } } Changeset[] latestChangesets = versionControlClient.queryHistory(configuration.getServerPath(), versionSpec, 0, RecursionType.FULL, null, new ChangesetVersionSpec( force && latestChangesetID > 0 ? latestChangesetID - 1 : latestChangesetID), versionSpec, deep || force ? Integer.MAX_VALUE : GitTFConstants.GIT_TF_SHALLOW_DEPTH, false, false, false, false); if (latestChangesets.length == 0 && force) { latestChangesets = versionControlClient.queryHistory(configuration.getServerPath(), versionSpec, 0, RecursionType.FULL, null, null, versionSpec, deep || force ? Integer.MAX_VALUE : GitTFConstants.GIT_TF_SHALLOW_DEPTH, false, false, false, false); } if (latestChangesets.length == 0) { return new TaskStatus(TaskStatus.ERROR, Messages.formatString("FetchTask.CouldNotDetermineVersionFormat", versionSpec.toString(), //$NON-NLS-1$ configuration.getServerPath())); } int finalChangesetID = latestChangesets[0].getChangesetID(); ObjectId finalCommitID = changesetCommitMap.getCommitID(finalChangesetID, true); int changesetCounter = 0; if (finalCommitID != null && !force) { log.info(MessageFormat.format( "The changeset to download {0} has been downloaded before in commit id {1}", //$NON-NLS-1$ Integer.toString(finalChangesetID), finalCommitID.toString())); fetchedChangesetId = finalChangesetID; alreadyFetched = true; } else { log.info(MessageFormat.format("Downloading changeset {0} and creating a new commit", //$NON-NLS-1$ Integer.toString(finalChangesetID))); ObjectId lastCommitID = (latestChangesetID >= 0) ? changesetCommitMap.getCommitID(latestChangesetID, true) : null; /* * Note: since we query history from last bridged changeset -> * latest, we may have gotten the last bridged changeset returned to * us as the last element. (This will be true if depth > number of * changesets since last bridged changeset.) Filter this changeset * out. */ Changeset[] changesets = calculateChangesetsToDownload(latestChangesets, latestChangesetID); changesetCounter = changesets.length - 1; Item[] previousChangesetItems = versionControlClient.getItems(configuration.getServerPath(), new ChangesetVersionSpec(latestChangesetID), RecursionType.FULL); progressMonitor.setWork(changesetCounter + 1); for (int i = changesetCounter; i >= 0; i--) { progressMonitor.setDetail(Messages.formatString("FetchTask.ChangesetNumberFormat", //$NON-NLS-1$ Integer.toString(changesets[i].getChangesetID()))); CreateCommitForChangesetVersionSpecTask createCommitTask = new CreateCommitForChangesetVersionSpecTask( repository, versionControlClient, changesets[i], previousChangesetItems, lastCommitID, witClient); TaskStatus createCommitTaskStatus = new TaskExecutor(progressMonitor.newSubTask(1)) .execute(createCommitTask); if (!createCommitTaskStatus.isOK()) { log.info("Commit Creation failed"); //$NON-NLS-1$ return createCommitTaskStatus; } lastCommitID = createCommitTask.getCommitID(); fetchedChangesetId = changesets[i].getChangesetID(); previousChangesetItems = createCommitTask.getCommittedItems(); try { boolean forceHWMUpdate = i == changesetCounter && force; changesetCommitMap.setChangesetCommit(changesets[i].getChangesetID(), lastCommitID, forceHWMUpdate); } catch (IOException e) { return new TaskStatus(TaskStatus.ERROR, e); } progressMonitor.displayVerbose(Messages.formatString("FetchTask.FetchedChangesetFormat", //$NON-NLS-1$ Integer.toString(changesets[i].getChangesetID()), ObjectIdUtil.abbreviate(repository, lastCommitID))); } finalCommitID = lastCommitID; } fetchedCommitId = finalCommitID; progressMonitor.endTask(); /* update fetch head */ if (shouldUpdateFetchHead) { boolean updatedFetchHead = false; try { updatedFetchHead = writeFetchHead(finalCommitID, finalChangesetID); } catch (IOException e) { return new TaskStatus(TaskStatus.ERROR, e); } if (alreadyFetched) { if (updatedFetchHead) { progressMonitor .displayMessage(Messages.formatString("FetchTask.AlreadyFetchedUpdateFetchHeadFormat", //$NON-NLS-1$ Integer.toString(finalChangesetID), ObjectIdUtil.abbreviate(repository, finalCommitID))); } else { progressMonitor.displayMessage(Messages.getString("FetchTask.AlreadyFetchedNothingToUpdate")); //$NON-NLS-1$ } } else { if (changesetCounter <= 1) { progressMonitor.displayMessage(Messages.formatString("FetchTask.FetchedFormat", //$NON-NLS-1$ Integer.toString(finalChangesetID), ObjectIdUtil.abbreviate(repository, finalCommitID))); } else { progressMonitor.displayMessage(Messages.formatString("FetchTask.FetchedMultipleFormat", //$NON-NLS-1$ changesetCounter, Integer.toString(finalChangesetID), ObjectIdUtil.abbreviate(repository, finalCommitID))); } } } try { TfsBranchUtil.update(repository, finalCommitID); } catch (Exception e) { return new TaskStatus(TaskStatus.ERROR, e); } log.info("Fetch task complete"); //$NON-NLS-1$ return TaskStatus.OK_STATUS; }
From source file:com.osbitools.ws.shared.prj.utils.GitUtils.java
License:Open Source License
public static void getLastRevision(Git git, String base, String name, String rev, OutputStream out, String ext) throws WsSrvException, IOException { checkFile(base, name, ext);/* w w w . j a v a 2 s . co m*/ String fp = getLocalPath(name); // find the HEAD ObjectId lastCommitId = git.getRepository().resolve(Constants.HEAD); // a RevWalk allows to walk over commits based on // some filtering that is defined RevWalk revWalk = new RevWalk(git.getRepository()); RevCommit commit = revWalk.parseCommit(lastCommitId); // and using commit's tree find the path RevTree tree = commit.getTree(); System.out.println("Having tree: " + tree); // now try to find a specific file TreeWalk treeWalk = new TreeWalk(git.getRepository()); treeWalk.addTree(tree); treeWalk.setRecursive(true); treeWalk.setFilter(PathFilter.create(fp)); if (!treeWalk.next()) { throw new IllegalStateException("Did not find expected file 'README.md'"); } ObjectId objectId = treeWalk.getObjectId(0); System.out.println("ObjectId: " + objectId.toString()); ObjectLoader loader = git.getRepository().open(objectId); // and then one can the loader to read the file loader.copyTo(System.out); revWalk.dispose(); }