Example usage for org.eclipse.jgit.lib Repository close

List of usage examples for org.eclipse.jgit.lib Repository close

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository close.

Prototype

@Override
public void close() 

Source Link

Document

Decrement the use count, and maybe close resources.

Usage

From source file:com.google.devtools.build.lib.bazel.repository.GitCloneFunction.java

License:Open Source License

private boolean isUpToDate(GitRepositoryDescriptor descriptor) {
    // Initializing/checking status of/etc submodules cleanly is hard, so don't try for now.
    if (descriptor.initSubmodules) {
        return false;
    }/*from w  w w  . java  2 s.com*/
    Repository repository = null;
    try {
        repository = new FileRepositoryBuilder()
                .setGitDir(descriptor.directory.getChild(Constants.DOT_GIT).getPathFile()).setMustExist(true)
                .build();
        ObjectId head = repository.resolve(Constants.HEAD);
        ObjectId checkout = repository.resolve(descriptor.checkout);
        if (head != null && checkout != null && head.equals(checkout)) {
            Status status = Git.wrap(repository).status().call();
            if (!status.hasUncommittedChanges()) {
                // new_git_repository puts (only) BUILD and WORKSPACE, and
                // git_repository doesn't add any files.
                Set<String> untracked = status.getUntracked();
                if (untracked.isEmpty() || (untracked.size() == 2 && untracked.contains("BUILD")
                        && untracked.contains("WORKSPACE"))) {
                    return true;
                }
            }
        }
    } catch (GitAPIException | IOException e) {
        // Any exceptions here, we'll just blow it away and try cloning fresh.
        // The fresh clone avoids any weirdness due to what's there and has nicer
        // error reporting.
    } finally {
        if (repository != null) {
            repository.close();
        }
    }
    return false;
}

From source file:com.google.devtools.build.lib.bazel.repository.GitCloner.java

License:Open Source License

private static boolean isUpToDate(GitRepositoryDescriptor descriptor) {
    // Initializing/checking status of/etc submodules cleanly is hard, so don't try for now.
    if (descriptor.initSubmodules) {
        return false;
    }//from  ww w  .ja  v a2  s.  com
    Repository repository = null;
    try {
        repository = new FileRepositoryBuilder()
                .setGitDir(descriptor.directory.getChild(Constants.DOT_GIT).getPathFile()).setMustExist(true)
                .build();
        ObjectId head = repository.resolve(Constants.HEAD);
        ObjectId checkout = repository.resolve(descriptor.checkout);
        if (head != null && checkout != null && head.equals(checkout)) {
            Status status = Git.wrap(repository).status().call();
            if (!status.hasUncommittedChanges()) {
                // new_git_repository puts (only) BUILD and WORKSPACE, and
                // git_repository doesn't add any files.
                Set<String> untracked = status.getUntracked();
                if (untracked.isEmpty() || (untracked.size() == 2 && untracked.contains("BUILD")
                        && untracked.contains("WORKSPACE"))) {
                    return true;
                }
            }
        }
    } catch (GitAPIException | IOException e) {
        // Any exceptions here, we'll just blow it away and try cloning fresh.
        // The fresh clone avoids any weirdness due to what's there and has nicer
        // error reporting.
    } finally {
        if (repository != null) {
            repository.close();
        }
    }
    return false;
}

From source file:com.google.gerrit.acceptance.AbstractDaemonTest.java

License:Apache License

private void afterTest() throws Exception {
    Transport.unregister(inProcessProtocol);
    for (Repository repo : toClose) {
        repo.close();
    }//from w  w w  .  j  a va 2  s . co  m
    db.close();
    sshSession.close();
    if (server != commonServer) {
        server.stop();
    }
}

From source file:com.google.gerrit.gpg.PushCertificateChecker.java

License:Apache License

/**
 * Check a push certificate./*www  .  ja  va  2s.c  om*/
 *
 * @return result of the check.
 */
public final CheckResult check(PushCertificate cert) {
    if (cert.getNonceStatus() != NonceStatus.OK) {
        return new CheckResult("Invalid nonce");
    }
    List<String> problems = new ArrayList<>();
    try {
        PGPSignature sig = readSignature(cert);
        if (sig != null) {
            @SuppressWarnings("resource")
            Repository repo = getRepository();
            try (PublicKeyStore store = new PublicKeyStore(repo)) {
                checkSignature(sig, cert, store, problems);
                checkCustom(repo, problems);
            } finally {
                if (shouldClose(repo)) {
                    repo.close();
                }
            }
        } else {
            problems.add("Invalid signature format");
        }
    } catch (PGPException | IOException e) {
        String msg = "Internal error checking push certificate";
        log.error(msg, e);
        problems.add(msg);
    }
    return new CheckResult(problems);
}

From source file:com.google.gerrit.httpd.rpc.changedetail.EditCommitMessageHandler.java

License:Apache License

@Override
public ChangeDetail call() throws NoSuchChangeException, OrmException, EmailException, NoSuchEntityException,
        PatchSetInfoNotAvailableException, MissingObjectException, IncorrectObjectTypeException, IOException,
        InvalidChangeOperationException, NoSuchProjectException {

    final Change.Id changeId = patchSetId.getParentKey();
    final ChangeControl control = changeControlFactory.validateFor(changeId);
    if (!control.canAddPatchSet()) {
        throw new InvalidChangeOperationException(
                "Not allowed to add new Patch Sets to: " + changeId.toString());
    }/*w w  w. j  ava 2s  . co m*/

    final Repository git;
    try {
        git = gitManager.openRepository(db.changes().get(changeId).getProject());
    } catch (RepositoryNotFoundException e) {
        throw new NoSuchChangeException(changeId, e);
    }
    try {
        ChangeUtil.editCommitMessage(patchSetId, control.getRefControl(), currentUser, message, db,
                commitMessageEditedSenderFactory, git, myIdent, patchSetInserterFactory);
        return changeDetailFactory.create(changeId).call();
    } finally {
        git.close();
    }
}

From source file:com.google.gerrit.httpd.rpc.changedetail.IncludedInDetailFactory.java

License:Apache License

@Override
public IncludedInDetail call()
        throws OrmException, NoSuchChangeException, IOException, InvalidRevisionException {
    control = changeControlFactory.validateFor(changeId);

    final PatchSet patch = db.patchSets().get(control.getChange().currentPatchSetId());
    final Repository repo = repoManager.openRepository(control.getProject().getNameKey());
    try {// w w  w.  ja  v  a  2s.c o m
        final RevWalk rw = new RevWalk(repo);
        try {
            rw.setRetainBody(false);

            final RevCommit rev;
            try {
                rev = rw.parseCommit(ObjectId.fromString(patch.getRevision().get()));
            } catch (IncorrectObjectTypeException err) {
                throw new InvalidRevisionException();
            } catch (MissingObjectException err) {
                throw new InvalidRevisionException();
            }

            detail = new IncludedInDetail();
            detail.setBranches(includedIn(repo, rw, rev, Constants.R_HEADS));
            detail.setTags(includedIn(repo, rw, rev, Constants.R_TAGS));

            return detail;
        } finally {
            rw.release();
        }
    } finally {
        repo.close();
    }
}

From source file:com.google.gerrit.httpd.rpc.patch.PatchScriptFactory.java

License:Apache License

@Override
public PatchScript call() throws OrmException, NoSuchChangeException {
    validatePatchSetId(psa);//  w w  w.j a va 2s. c o m
    validatePatchSetId(psb);

    control = changeControlFactory.validateFor(changeId);
    change = control.getChange();
    projectKey = change.getProject();
    patchSet = db.patchSets().get(patchSetId);
    if (patchSet == null) {
        throw new NoSuchChangeException(changeId);
    }

    aId = psa != null ? toObjectId(db, psa) : null;
    bId = toObjectId(db, psb);

    final Repository git;
    try {
        git = repoManager.openRepository(projectKey);
    } catch (RepositoryNotFoundException e) {
        log.error("Repository " + projectKey + " not found", e);
        throw new NoSuchChangeException(changeId, e);
    }
    try {
        final PatchList list = listFor(keyFor(diffPrefs.getIgnoreWhitespace()));
        final PatchScriptBuilder b = newBuilder(list, git);
        final PatchListEntry content = list.get(patchKey.getFileName());

        loadCommentsAndHistory(content.getChangeType(), //
                content.getOldName(), //
                content.getNewName());

        try {
            return b.toPatchScript(content, comments, history);
        } catch (IOException e) {
            log.error("File content unavailable", e);
            throw new NoSuchChangeException(changeId, e);
        }
    } finally {
        git.close();
    }
}

From source file:com.google.gerrit.httpd.rpc.project.AddBranch.java

License:Apache License

@Override
public ListBranchesResult call() throws NoSuchProjectException, InvalidNameException, InvalidRevisionException,
        IOException, BranchCreationNotAllowedException {
    final ProjectControl projectControl = projectControlFactory.controlFor(projectName);

    String refname = branchName;//from   w w  w  . j  a v  a 2 s .c om
    while (refname.startsWith("/")) {
        refname = refname.substring(1);
    }
    if (!refname.startsWith(Constants.R_REFS)) {
        refname = Constants.R_HEADS + refname;
    }
    if (!Repository.isValidRefName(refname)) {
        throw new InvalidNameException();
    }
    if (refname.startsWith(ReceiveCommits.NEW_CHANGE)) {
        throw new BranchCreationNotAllowedException(ReceiveCommits.NEW_CHANGE);
    }

    final Branch.NameKey name = new Branch.NameKey(projectName, refname);
    final RefControl refControl = projectControl.controlForRef(name);
    final Repository repo = repoManager.openRepository(projectName);
    try {
        final ObjectId revid = parseStartingRevision(repo);
        final RevWalk rw = verifyConnected(repo, revid);
        RevObject object = rw.parseAny(revid);

        if (refname.startsWith(Constants.R_HEADS)) {
            // Ensure that what we start the branch from is a commit. If we
            // were given a tag, deference to the commit instead.
            //
            try {
                object = rw.parseCommit(object);
            } catch (IncorrectObjectTypeException notCommit) {
                throw new IllegalStateException(startingRevision + " not a commit");
            }
        }

        if (!refControl.canCreate(rw, object)) {
            throw new IllegalStateException("Cannot create " + refname);
        }

        try {
            final RefUpdate u = repo.updateRef(refname);
            u.setExpectedOldObjectId(ObjectId.zeroId());
            u.setNewObjectId(object.copy());
            u.setRefLogIdent(identifiedUser.newRefLogIdent());
            u.setRefLogMessage("created via web from " + startingRevision, false);
            final RefUpdate.Result result = u.update(rw);
            switch (result) {
            case FAST_FORWARD:
            case NEW:
            case NO_CHANGE:
                replication.scheduleUpdate(name.getParentKey(), refname);
                hooks.doRefUpdatedHook(name, u, identifiedUser.getAccount());
                break;
            default: {
                throw new IOException(result.name());
            }
            }
        } catch (IOException err) {
            log.error("Cannot create branch " + name, err);
            throw err;
        }
    } finally {
        repo.close();
    }

    return listBranchesFactory.create(projectName).call();
}

From source file:com.google.gerrit.httpd.rpc.project.DeleteBranches.java

License:Apache License

@Override
public Set<Branch.NameKey> call() throws NoSuchProjectException, RepositoryNotFoundException {
    final ProjectControl projectControl = projectControlFactory.controlFor(projectName);

    for (Branch.NameKey k : toRemove) {
        if (!projectName.equals(k.getParentKey())) {
            throw new IllegalArgumentException("All keys must be from same project");
        }//from   www  . ja v a2  s.co m
        if (!projectControl.controlForRef(k).canDelete()) {
            throw new IllegalStateException("Cannot delete " + k.getShortName());
        }
    }

    final Set<Branch.NameKey> deleted = new HashSet<Branch.NameKey>();
    final Repository r = repoManager.openRepository(projectName);
    try {
        for (final Branch.NameKey branchKey : toRemove) {
            final String refname = branchKey.get();
            final RefUpdate.Result result;
            final RefUpdate u;
            try {
                u = r.updateRef(refname);
                u.setForceUpdate(true);
                result = u.delete();
            } catch (IOException e) {
                log.error("Cannot delete " + branchKey, e);
                continue;
            }

            switch (result) {
            case NEW:
            case NO_CHANGE:
            case FAST_FORWARD:
            case FORCED:
                deleted.add(branchKey);
                replication.scheduleUpdate(projectName, refname);
                hooks.doRefUpdatedHook(branchKey, u, identifiedUser.getAccount());
                break;

            case REJECTED_CURRENT_BRANCH:
                log.warn("Cannot delete " + branchKey + ": " + result.name());
                break;

            default:
                log.error("Cannot delete " + branchKey + ": " + result.name());
                break;
            }
        }
    } finally {
        r.close();
    }
    return deleted;
}

From source file:com.google.gerrit.httpd.rpc.project.ListBranches.java

License:Apache License

@Override
public ListBranchesResult call() throws NoSuchProjectException {
    final ProjectControl pctl = projectControlFactory.validateFor( //
            projectName, //
            ProjectControl.OWNER | ProjectControl.VISIBLE);

    final List<Branch> branches = new ArrayList<Branch>();
    Branch headBranch = null;/*from w w  w .j  a  v a  2  s. c o  m*/
    final Set<String> targets = new HashSet<String>();

    final Repository db;
    try {
        db = repoManager.openRepository(projectName);
    } catch (RepositoryNotFoundException noGitRepository) {
        return new ListBranchesResult(branches, false, true);
    }
    try {
        final Map<String, Ref> all = db.getAllRefs();

        if (!all.containsKey(Constants.HEAD)) {
            // The branch pointed to by HEAD doesn't exist yet, so getAllRefs
            // filtered it out. If we ask for it individually we can find the
            // underlying target and put it into the map anyway.
            //
            try {
                Ref head = db.getRef(Constants.HEAD);
                if (head != null) {
                    all.put(Constants.HEAD, head);
                }
            } catch (IOException e) {
                // Ignore the failure reading HEAD.
            }
        }

        for (final Ref ref : all.values()) {
            if (ref.isSymbolic()) {
                targets.add(ref.getTarget().getName());
            }
        }

        for (final Ref ref : all.values()) {
            if (ref.isSymbolic()) {
                // A symbolic reference to another branch, instead of
                // showing the resolved value, show the name it references.
                //
                String target = ref.getTarget().getName();
                RefControl targetRefControl = pctl.controlForRef(target);
                if (!targetRefControl.isVisible()) {
                    continue;
                }
                if (target.startsWith(Constants.R_HEADS)) {
                    target = target.substring(Constants.R_HEADS.length());
                }

                Branch b = createBranch(ref.getName());
                b.setRevision(new RevId(target));

                if (Constants.HEAD.equals(ref.getName())) {
                    b.setCanDelete(false);
                    headBranch = b;
                } else {
                    b.setCanDelete(targetRefControl.canDelete());
                    branches.add(b);
                }
                continue;
            }

            RefControl refControl = pctl.controlForRef(ref.getName());

            if (ref.getName().startsWith(Constants.R_HEADS) && refControl.isVisible()) {
                final Branch b = createBranch(ref.getName());
                if (ref.getObjectId() != null) {
                    b.setRevision(new RevId(ref.getObjectId().name()));
                }

                b.setCanDelete(!targets.contains(ref.getName()) && refControl.canDelete());

                branches.add(b);
            }
        }
    } finally {
        db.close();
    }
    Collections.sort(branches, new Comparator<Branch>() {
        @Override
        public int compare(final Branch a, final Branch b) {
            return a.getName().compareTo(b.getName());
        }
    });
    if (headBranch != null) {
        branches.add(0, headBranch);
    }
    return new ListBranchesResult(branches, pctl.canAddRefs(), false);
}