List of usage examples for org.eclipse.jgit.lib RefUpdate setRefLogMessage
public void setRefLogMessage(String msg, boolean appendStatus)
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 {// w w w . j a v a2 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. * /* www . j av 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 w w w . j a va2 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
/** * Create an orphaned branch in a repository. * * @param repository//from w w w .ja v a 2 s . co m * @param branchName * @param author * if unspecified, Gitblit will be the author of this new branch * @return true if successful */ public static boolean createOrphanBranch(Repository repository, String branchName, PersonIdent author) { boolean success = false; String message = "Created branch " + branchName; if (author == null) { author = new PersonIdent("Gitblit", "gitblit@localhost"); } try { ObjectInserter odi = repository.newObjectInserter(); try { // Create a blob object to insert into a tree ObjectId blobId = odi.insert(Constants.OBJ_BLOB, message.getBytes(Constants.CHARACTER_ENCODING)); // Create a tree object to reference from a commit TreeFormatter tree = new TreeFormatter(); tree.append(".branch", FileMode.REGULAR_FILE, blobId); ObjectId treeId = odi.insert(tree); // Create a commit object CommitBuilder commit = new CommitBuilder(); commit.setAuthor(author); commit.setCommitter(author); commit.setEncoding(Constants.CHARACTER_ENCODING); commit.setMessage(message); commit.setTreeId(treeId); // Insert the commit into the repository ObjectId commitId = odi.insert(commit); odi.flush(); RevWalk revWalk = new RevWalk(repository); try { RevCommit revCommit = revWalk.parseCommit(commitId); if (!branchName.startsWith("refs/")) { branchName = "refs/heads/" + branchName; } RefUpdate ru = repository.updateRef(branchName); ru.setNewObjectId(commitId); ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false); Result rc = ru.forceUpdate(); switch (rc) { case NEW: case FORCED: case FAST_FORWARD: success = true; break; default: success = false; } } finally { revWalk.close(); } } finally { odi.close(); } } catch (Throwable t) { error(t, repository, "Failed to create orphan branch {1} in repository {0}", branchName); } return success; }
From source file:com.gitblit.utils.JGitUtils.java
License:Apache License
/** * Tries to merge a commit into a branch. If there are conflicts, the merge * will fail.//www. j av a 2 s. co m * * @param repository * @param src * @param toBranch * @param mergeType * Defines the integration strategy to use for merging. * @param committer * @param message * @return the merge result */ public static MergeResult merge(Repository repository, String src, String toBranch, MergeType mergeType, PersonIdent committer, String message) { if (!toBranch.startsWith(Constants.R_REFS)) { // branch ref doesn't start with ref, assume this is a branch head toBranch = Constants.R_HEADS + toBranch; } IntegrationStrategy strategy = IntegrationStrategyFactory.create(mergeType, repository, src, toBranch); MergeResult mergeResult = strategy.merge(committer, message); if (mergeResult.status != MergeStatus.MERGED) { return mergeResult; } try { // Update the integration branch ref RefUpdate mergeRefUpdate = repository.updateRef(toBranch); mergeRefUpdate.setNewObjectId(strategy.getMergeCommit()); mergeRefUpdate.setRefLogMessage(strategy.getRefLogMessage(), false); mergeRefUpdate.setExpectedOldObjectId(strategy.branchTip); RefUpdate.Result rc = mergeRefUpdate.update(); switch (rc) { case FAST_FORWARD: // successful, clean merge break; default: mergeResult = new MergeResult(MergeStatus.FAILED, null); throw new GitBlitException(MessageFormat.format("Unexpected result \"{0}\" when {1} in {2}", rc.name(), strategy.getOperationMessage(), repository.getDirectory())); } } catch (IOException e) { LOGGER.error("Failed to merge", e); } return mergeResult; }
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;// w w w . j a v a 2 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 ww w. j ava 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// ww w . j av a 2 s . c o 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.gitblit.wicket.pages.NewRepositoryPage.java
License:Apache License
/** * Prepare the initial commit for the repository. * * @param repository// ww w . ja v a 2 s .c om * @param addReadme * @param gitignore * @param addGitFlow * @return true if an initial commit was created */ protected boolean initialCommit(RepositoryModel repository, boolean addReadme, String gitignore, boolean addGitFlow) { boolean initialCommit = addReadme || !StringUtils.isEmpty(gitignore) || addGitFlow; if (!initialCommit) { return false; } // build an initial commit boolean success = false; Repository db = app().repositories().getRepository(repositoryModel.name); ObjectInserter odi = db.newObjectInserter(); try { UserModel user = GitBlitWebSession.get().getUser(); String email = Optional.fromNullable(user.emailAddress).or(user.username + "@" + "gitblit"); PersonIdent author = new PersonIdent(user.getDisplayName(), email); DirCache newIndex = DirCache.newInCore(); DirCacheBuilder indexBuilder = newIndex.builder(); if (addReadme) { // insert a README String title = StringUtils.stripDotGit(StringUtils.getLastPathElement(repositoryModel.name)); String description = repositoryModel.description == null ? "" : repositoryModel.description; String readme = String.format("## %s\n\n%s\n\n", title, description); byte[] bytes = readme.getBytes(Constants.ENCODING); DirCacheEntry entry = new DirCacheEntry("README.md"); entry.setLength(bytes.length); entry.setLastModified(System.currentTimeMillis()); entry.setFileMode(FileMode.REGULAR_FILE); entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes)); indexBuilder.add(entry); } if (!StringUtils.isEmpty(gitignore)) { // insert a .gitignore file File dir = app().runtime().getFileOrFolder(Keys.git.gitignoreFolder, "${baseFolder}/gitignore"); File file = new File(dir, gitignore + ".gitignore"); if (file.exists() && file.length() > 0) { byte[] bytes = FileUtils.readContent(file); if (!ArrayUtils.isEmpty(bytes)) { DirCacheEntry entry = new DirCacheEntry(".gitignore"); entry.setLength(bytes.length); entry.setLastModified(System.currentTimeMillis()); entry.setFileMode(FileMode.REGULAR_FILE); entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes)); indexBuilder.add(entry); } } } if (addGitFlow) { // insert a .gitflow file Config config = new Config(); config.setString("gitflow", null, "masterBranch", Constants.MASTER); config.setString("gitflow", null, "developBranch", Constants.DEVELOP); config.setString("gitflow", null, "featureBranchPrefix", "feature/"); config.setString("gitflow", null, "releaseBranchPrefix", "release/"); config.setString("gitflow", null, "hotfixBranchPrefix", "hotfix/"); config.setString("gitflow", null, "supportBranchPrefix", "support/"); config.setString("gitflow", null, "versionTagPrefix", ""); byte[] bytes = config.toText().getBytes(Constants.ENCODING); DirCacheEntry entry = new DirCacheEntry(".gitflow"); entry.setLength(bytes.length); entry.setLastModified(System.currentTimeMillis()); entry.setFileMode(FileMode.REGULAR_FILE); entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes)); indexBuilder.add(entry); } indexBuilder.finish(); if (newIndex.getEntryCount() == 0) { // nothing to commit return false; } ObjectId treeId = newIndex.writeTree(odi); // Create a commit object CommitBuilder commit = new CommitBuilder(); commit.setAuthor(author); commit.setCommitter(author); commit.setEncoding(Constants.ENCODING); commit.setMessage("Initial commit"); commit.setTreeId(treeId); // Insert the commit into the repository ObjectId commitId = odi.insert(commit); odi.flush(); // set the branch refs RevWalk revWalk = new RevWalk(db); try { // set the master branch RevCommit revCommit = revWalk.parseCommit(commitId); RefUpdate masterRef = db.updateRef(Constants.R_MASTER); masterRef.setNewObjectId(commitId); masterRef.setRefLogMessage("commit: " + revCommit.getShortMessage(), false); Result masterRC = masterRef.update(); switch (masterRC) { case NEW: success = true; break; default: success = false; } if (addGitFlow) { // set the develop branch for git-flow RefUpdate developRef = db.updateRef(Constants.R_DEVELOP); developRef.setNewObjectId(commitId); developRef.setRefLogMessage("commit: " + revCommit.getShortMessage(), false); Result developRC = developRef.update(); switch (developRC) { case NEW: success = true; break; default: success = false; } } } finally { revWalk.close(); } } catch (UnsupportedEncodingException e) { logger().error(null, e); } catch (IOException e) { logger().error(null, e); } finally { odi.close(); db.close(); } return success; }
From source file:com.google.gerrit.gpg.PublicKeyStore.java
License:Apache License
/** * Save pending keys to the store./*from www . j a v a 2 s . c o m*/ * <p> * One commit is created and the ref updated. The pending list is cleared if * and only if the ref update succeeds, which allows for easy retries in case * of lock failure. * * @param cb commit builder with at least author and identity populated; tree * and parent are ignored. * @return result of the ref update. */ public RefUpdate.Result save(CommitBuilder cb) throws PGPException, IOException { if (toAdd.isEmpty() && toRemove.isEmpty()) { return RefUpdate.Result.NO_CHANGE; } if (reader == null) { load(); } if (notes == null) { notes = NoteMap.newEmptyMap(); } ObjectId newTip; try (ObjectInserter ins = repo.newObjectInserter()) { for (PGPPublicKeyRing keyRing : toAdd.values()) { saveToNotes(ins, keyRing); } for (Fingerprint fp : toRemove) { deleteFromNotes(ins, fp); } cb.setTreeId(notes.writeTree(ins)); if (cb.getTreeId().equals(tip != null ? tip.getTree() : EMPTY_TREE)) { return RefUpdate.Result.NO_CHANGE; } if (tip != null) { cb.setParentId(tip); } if (cb.getMessage() == null) { int n = toAdd.size() + toRemove.size(); cb.setMessage(String.format("Update %d public key%s", n, n != 1 ? "s" : "")); } newTip = ins.insert(cb); ins.flush(); } RefUpdate ru = repo.updateRef(PublicKeyStore.REFS_GPG_KEYS); ru.setExpectedOldObjectId(tip); ru.setNewObjectId(newTip); ru.setRefLogIdent(cb.getCommitter()); ru.setRefLogMessage("Store public keys", true); RefUpdate.Result result = ru.update(); reset(); switch (result) { case FAST_FORWARD: case NEW: case NO_CHANGE: toAdd.clear(); toRemove.clear(); break; default: break; } return result; }