List of usage examples for org.eclipse.jgit.lib Repository close
@Override public void close()
Decrement the use count, and maybe close resources.
From source file:com.google.gerrit.httpd.rpc.project.ProjectDetailFactory.java
License:Apache License
@Override public ProjectDetail call() throws NoSuchProjectException, IOException { final ProjectControl pc = projectControlFactory.validateFor(projectName, ProjectControl.OWNER | ProjectControl.VISIBLE); final ProjectState projectState = pc.getProjectState(); final ProjectDetail detail = new ProjectDetail(); detail.setProject(projectState.getProject()); final boolean userIsOwner = pc.isOwner(); final boolean userIsOwnerAnyRef = pc.isOwnerAnyRef(); detail.setCanModifyAccess(userIsOwnerAnyRef); detail.setCanModifyAgreements(userIsOwner); detail.setCanModifyDescription(userIsOwner); detail.setCanModifyMergeType(userIsOwner); detail.setCanModifyState(userIsOwner); final InheritedBoolean useContributorAgreements = new InheritedBoolean(); final InheritedBoolean useSignedOffBy = new InheritedBoolean(); final InheritedBoolean useContentMerge = new InheritedBoolean(); final InheritedBoolean requireChangeID = new InheritedBoolean(); useContributorAgreements.setValue(projectState.getProject().getUseContributorAgreements()); useSignedOffBy.setValue(projectState.getProject().getUseSignedOffBy()); useContentMerge.setValue(projectState.getProject().getUseContentMerge()); requireChangeID.setValue(projectState.getProject().getRequireChangeID()); ProjectState parentState = Iterables.getFirst(projectState.parents(), null); if (parentState != null) { useContributorAgreements.setInheritedValue(parentState.isUseContributorAgreements()); useSignedOffBy.setInheritedValue(parentState.isUseSignedOffBy()); useContentMerge.setInheritedValue(parentState.isUseContentMerge()); requireChangeID.setInheritedValue(parentState.isRequireChangeID()); }//www . j a v a2s. c om detail.setUseContributorAgreements(useContributorAgreements); detail.setUseSignedOffBy(useSignedOffBy); detail.setUseContentMerge(useContentMerge); detail.setRequireChangeID(requireChangeID); final Project.NameKey projectName = projectState.getProject().getNameKey(); Repository git; try { git = gitRepositoryManager.openRepository(projectName); } catch (RepositoryNotFoundException err) { throw new NoSuchProjectException(projectName); } try { Ref head = git.getRef(Constants.HEAD); if (head != null && head.isSymbolic() && GitRepositoryManager.REF_CONFIG.equals(head.getLeaf().getName())) { detail.setPermissionOnly(true); } } catch (IOException err) { throw new NoSuchProjectException(projectName); } finally { git.close(); } return detail; }
From source file:com.google.gerrit.pgm.ExportReviewNotes.java
License:Apache License
private void export(ReviewDb db, Project.NameKey project, List<Change> changes) throws IOException, OrmException, CodeReviewNoteCreationException, InterruptedException { final Repository git; try {/*from w w w.ja v a 2s . c o m*/ git = gitManager.openRepository(project); } catch (RepositoryNotFoundException e) { return; } try { CreateCodeReviewNotes notes = codeReviewNotesFactory.create(db, git); try { notes.loadBase(); for (Change change : changes) { monitor.update(1); PatchSet ps = db.patchSets().get(change.currentPatchSetId()); if (ps == null) { continue; } notes.add(change, ObjectId.fromString(ps.getRevision().get())); } notes.commit("Exported prior reviews from Gerrit Code Review\n"); notes.updateRef(); } finally { notes.release(); } } finally { git.close(); } }
From source file:com.google.gerrit.pgm.init.AllProjectsConfig.java
License:Apache License
public Config load() throws IOException, ConfigInvalidException { File path = getPath();/*from ww w . ja v a 2 s. c om*/ if (path == null) { return null; } Repository repo = new FileRepository(path); try { load(repo); } finally { repo.close(); } return cfg; }
From source file:com.google.gerrit.pgm.init.AllProjectsConfig.java
License:Apache License
private void save(PersonIdent ident, String msg) throws IOException { File path = getPath();/*w ww . j a v a 2 s . c om*/ if (path == null) { throw new IOException("All-Projects does not exist."); } Repository repo = new FileRepository(path); try { inserter = repo.newObjectInserter(); reader = repo.newObjectReader(); try { RevWalk rw = new RevWalk(reader); try { RevTree srcTree = revision != null ? rw.parseTree(revision) : null; newTree = readTree(srcTree); saveConfig(ProjectConfig.PROJECT_CONFIG, cfg); ObjectId res = newTree.writeTree(inserter); if (res.equals(srcTree)) { // If there are no changes to the content, don't create the commit. return; } CommitBuilder commit = new CommitBuilder(); commit.setAuthor(ident); commit.setCommitter(ident); commit.setMessage(msg); commit.setTreeId(res); if (revision != null) { commit.addParentId(revision); } ObjectId newRevision = inserter.insert(commit); updateRef(repo, ident, newRevision, "commit: " + msg); revision = newRevision; } finally { rw.release(); } } finally { if (inserter != null) { inserter.release(); inserter = null; } if (reader != null) { reader.release(); reader = null; } } } finally { repo.close(); } }
From source file:com.google.gerrit.pgm.ScanTrackingIds.java
License:Apache License
private void scan(ReviewDb db, Change change) { final Project.NameKey project = change.getDest().getParentKey(); final Repository git; try {// ww w . jav a2s. c om git = gitManager.openRepository(project); } catch (RepositoryNotFoundException e) { return; } try { PatchSet ps = db.patchSets().get(change.currentPatchSetId()); if (ps == null || ps.getRevision() == null || ps.getRevision().get() == null) { return; } ChangeUtil.updateTrackingIds(db, change, footers, parse(git, ps).getFooterLines()); } catch (OrmException error) { System.err.println("ERR " + error.getMessage()); } catch (IOException error) { System.err.println("ERR Cannot scan " + change.getId() + ": " + error.getMessage()); } finally { git.close(); } }
From source file:com.google.gerrit.server.change.EditMessage.java
License:Apache License
@Override public ChangeInfo apply(RevisionResource rsrc, Input input) throws BadRequestException, ResourceConflictException, EmailException, OrmException, ResourceNotFoundException, IOException { if (Strings.isNullOrEmpty(input.message)) { throw new BadRequestException("message must be non-empty"); }// www.j a va 2 s . c o m final Repository git; try { git = gitManager.openRepository(rsrc.getChange().getProject()); } catch (RepositoryNotFoundException e) { throw new ResourceNotFoundException(e.getMessage()); } try { return json.format( ChangeUtil.editCommitMessage(rsrc.getPatchSet().getId(), rsrc.getControl().getRefControl(), (IdentifiedUser) rsrc.getControl().getCurrentUser(), input.message, dbProvider.get(), commitMessageEditedSenderFactory, git, myIdent, patchSetInserterFactory)); } catch (InvalidChangeOperationException e) { throw new BadRequestException(e.getMessage()); } catch (MissingObjectException e) { throw new ResourceConflictException(e.getMessage()); } catch (IncorrectObjectTypeException e) { throw new ResourceConflictException(e.getMessage()); } catch (PatchSetInfoNotAvailableException e) { throw new ResourceConflictException(e.getMessage()); } catch (NoSuchChangeException e) { throw new ResourceNotFoundException(); } finally { git.close(); } }
From source file:com.google.gerrit.server.change.GetArchive.java
License:Apache License
@Override public BinaryResult apply(RevisionResource rsrc) throws BadRequestException, IOException, MethodNotAllowedException { if (Strings.isNullOrEmpty(format)) { throw new BadRequestException("format is not specified"); }//from w w w .j a va 2 s. c o m final ArchiveFormat f = allowedFormats.extensions.get("." + format); if (f == null) { throw new BadRequestException("unknown archive format"); } if (f == ArchiveFormat.ZIP) { throw new MethodNotAllowedException("zip format is disabled"); } boolean close = true; final Repository repo = repoManager.openRepository(rsrc.getControl().getProject().getNameKey()); try { final RevCommit commit; String name; try (RevWalk rw = new RevWalk(repo)) { commit = rw.parseCommit(ObjectId.fromString(rsrc.getPatchSet().getRevision().get())); name = name(f, rw, commit); } BinaryResult bin = new BinaryResult() { @Override public void writeTo(OutputStream out) throws IOException { try { new ArchiveCommand(repo).setFormat(f.name()).setTree(commit.getTree()).setOutputStream(out) .call(); } catch (GitAPIException e) { throw new IOException(e); } } @Override public void close() throws IOException { repo.close(); } }; bin.disableGzip().setContentType(f.getMimeType()).setAttachmentName(name); close = false; return bin; } finally { if (close) { repo.close(); } } }
From source file:com.google.gerrit.server.change.GetPatch.java
License:Apache License
@Override public BinaryResult apply(RevisionResource rsrc) throws ResourceConflictException, IOException { Project.NameKey project = rsrc.getControl().getProject().getNameKey(); final Repository repo = repoManager.openRepository(project); boolean close = true; try {/*w w w . j a va 2s . co m*/ final RevWalk rw = new RevWalk(repo); try { final RevCommit commit = rw .parseCommit(ObjectId.fromString(rsrc.getPatchSet().getRevision().get())); RevCommit[] parents = commit.getParents(); if (parents.length > 1) { throw new ResourceConflictException("Revision has more than 1 parent."); } else if (parents.length == 0) { throw new ResourceConflictException("Revision has no parent."); } final RevCommit base = parents[0]; rw.parseBody(base); BinaryResult bin = new BinaryResult() { @Override public void writeTo(OutputStream out) throws IOException { if (zip) { ZipOutputStream zos = new ZipOutputStream(out); ZipEntry e = new ZipEntry(fileName(rw, commit)); e.setTime(commit.getCommitTime() * 1000L); zos.putNextEntry(e); format(zos); zos.closeEntry(); zos.finish(); } else { format(out); } } private void format(OutputStream out) throws IOException { out.write(formatEmailHeader(commit).getBytes(UTF_8)); try (DiffFormatter fmt = new DiffFormatter(out)) { fmt.setRepository(repo); fmt.format(base.getTree(), commit.getTree()); fmt.flush(); } } @Override public void close() throws IOException { rw.close(); repo.close(); } }; if (zip) { bin.disableGzip().setContentType("application/zip") .setAttachmentName(fileName(rw, commit) + ".zip"); } else { bin.base64().setContentType("application/mbox") .setAttachmentName(download ? fileName(rw, commit) + ".base64" : null); } close = false; return bin; } finally { if (close) { rw.close(); } } } finally { if (close) { repo.close(); } } }
From source file:com.google.gerrit.server.changedetail.PublishDraft.java
License:Apache License
private void sendNotifications(final boolean newChange, final IdentifiedUser currentUser, final Change updatedChange, final PatchSet updatedPatchSet, final LabelTypes labelTypes) throws OrmException, IOException, PatchSetInfoNotAvailableException { final Repository git = repoManager.openRepository(updatedChange.getProject()); try {/* w w w . j a va 2 s . co m*/ final RevWalk revWalk = new RevWalk(git); final RevCommit commit; try { commit = revWalk.parseCommit(ObjectId.fromString(updatedPatchSet.getRevision().get())); } finally { revWalk.release(); } final PatchSetInfo info = patchSetInfoFactory.get(commit, updatedPatchSet.getId()); final List<FooterLine> footerLines = commit.getFooterLines(); final Account.Id me = currentUser.getAccountId(); final MailRecipients recipients = getRecipientsFromFooters(accountResolver, updatedPatchSet, footerLines); recipients.remove(me); if (newChange) { approvalsUtil.addReviewers(db, labelTypes, updatedChange, updatedPatchSet, info, recipients.getReviewers(), Collections.<Account.Id>emptySet()); try { CreateChangeSender cm = createChangeSenderFactory.create(updatedChange); cm.setFrom(me); cm.setPatchSet(updatedPatchSet, info); cm.addReviewers(recipients.getReviewers()); cm.addExtraCC(recipients.getCcOnly()); cm.send(); } catch (Exception e) { log.error("Cannot send email for new change " + updatedChange.getId(), e); } } else { final List<PatchSetApproval> patchSetApprovals = db.patchSetApprovals() .byChange(updatedChange.getId()).toList(); final MailRecipients oldRecipients = getRecipientsFromApprovals(patchSetApprovals); approvalsUtil.addReviewers(db, labelTypes, updatedChange, updatedPatchSet, info, recipients.getReviewers(), oldRecipients.getAll()); final ChangeMessage msg = new ChangeMessage( new ChangeMessage.Key(updatedChange.getId(), ChangeUtil.messageUUID(db)), me, updatedPatchSet.getCreatedOn(), updatedPatchSet.getId()); msg.setMessage("Uploaded patch set " + updatedPatchSet.getPatchSetId() + "."); try { ReplacePatchSetSender cm = replacePatchSetFactory.create(updatedChange); cm.setFrom(me); cm.setPatchSet(updatedPatchSet, info); cm.setChangeMessage(msg); cm.addReviewers(recipients.getReviewers()); cm.addExtraCC(recipients.getCcOnly()); cm.send(); } catch (Exception e) { log.error("Cannot send email for new patch set " + updatedPatchSet.getId(), e); } } } finally { git.close(); } }
From source file:com.google.gerrit.server.changedetail.RebaseChange.java
License:Apache License
/** * Rebases the change of the given patch set. * * It is verified that the current user is allowed to do the rebase. * * If the patch set has no dependency to an open change, then the change is * rebased on the tip of the destination branch. * * If the patch set depends on an open change, it is rebased on the latest * patch set of this change./*from ww w .j a v a2 s. com*/ * * The rebased commit is added as new patch set to the change. * * E-mail notification and triggering of hooks happens for the creation of the * new patch set. * * @param change the change to perform the rebase for * @param patchSetId the id of the patch set * @param uploader the user that creates the rebased patch set * @param newBaseRev the commit that should be the new base * @throws NoSuchChangeException thrown if the change to which the patch set * belongs does not exist or is not visible to the user * @throws EmailException thrown if sending the e-mail to notify about the new * patch set fails * @throws OrmException thrown in case accessing the database fails * @throws IOException thrown if rebase is not possible or not needed * @throws InvalidChangeOperationException thrown if rebase is not allowed */ public void rebase(Change change, PatchSet.Id patchSetId, final IdentifiedUser uploader, final String newBaseRev) throws NoSuchChangeException, EmailException, OrmException, IOException, InvalidChangeOperationException { final Change.Id changeId = patchSetId.getParentKey(); final ChangeControl changeControl = changeControlFactory.validateFor(change, uploader); if (!changeControl.canRebase()) { throw new InvalidChangeOperationException( "Cannot rebase: New patch sets are not allowed to be added to change: " + changeId.toString()); } Repository git = null; RevWalk rw = null; ObjectInserter inserter = null; try { git = gitManager.openRepository(change.getProject()); rw = new RevWalk(git); inserter = git.newObjectInserter(); String baseRev = newBaseRev; if (baseRev == null) { baseRev = findBaseRevision(patchSetId, db.get(), change.getDest(), git, null, null, null); } ObjectId baseObjectId = git.resolve(baseRev); if (baseObjectId == null) { throw new InvalidChangeOperationException("Cannot rebase: Failed to resolve baseRev: " + baseRev); } final RevCommit baseCommit = rw.parseCommit(baseObjectId); PersonIdent committerIdent = uploader.newCommitterIdent(TimeUtil.nowTs(), serverTimeZone); rebase(git, rw, inserter, patchSetId, change, uploader, baseCommit, mergeUtilFactory.create(changeControl.getProjectControl().getProjectState(), true), committerIdent, true, ValidatePolicy.GERRIT); } catch (MergeConflictException e) { throw new IOException(e.getMessage()); } finally { if (inserter != null) { inserter.release(); } if (rw != null) { rw.release(); } if (git != null) { git.close(); } } }