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

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

Introduction

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

Prototype

@Nullable
public String getFullBranch() throws IOException 

Source Link

Document

Get the name of the reference that HEAD points to.

Usage

From source file:com.cloudcontrolled.cctrl.maven.plugin.push.CloudcontrolledPush.java

License:Apache License

private String push(String remoteLocation) throws MojoExecutionException {
    Repository repository = null;
    Git git;//from  ww w . java2  s.  c  o m
    try {
        repository = getRepository();
        git = Git.wrap(repository);

        PushCommand pushCommand = git.push();
        pushCommand.setRemote(remoteLocation);
        pushCommand.setRefSpecs(new RefSpec(repository.getFullBranch()));

        Iterable<PushResult> pushResult = pushCommand.call();
        Iterator<PushResult> result = pushResult.iterator();

        StringBuffer buffer = new StringBuffer();
        if (result.hasNext()) {
            while (result.hasNext()) {
                String line = result.next().getMessages();
                if (!line.isEmpty()) {
                    buffer.append(line);
                    if (result.hasNext()) {
                        buffer.append(System.getProperty("line.separator"));
                    }
                }
            }
        }

        return buffer.toString();
    } catch (Exception e) {
        throw new MojoExecutionException(e.getClass().getSimpleName(), e);
    } finally {
        if (repository != null) {
            repository.close();
        }
    }
}

From source file:com.denimgroup.threadfix.service.repository.GitServiceImpl.java

License:Mozilla Public License

@Override
public File cloneRepoToDirectory(Application application, File dirLocation) {

    if (dirLocation.exists()) {
        File gitDirectoryFile = new File(dirLocation.getAbsolutePath() + File.separator + ".git");

        try {/*from   www  .ja va 2s . c o m*/
            if (!gitDirectoryFile.exists()) {
                Git newRepo = clone(application, dirLocation);
                if (newRepo != null)
                    return newRepo.getRepository().getWorkTree();
            } else {
                Repository localRepo = new FileRepository(gitDirectoryFile);
                Git git = new Git(localRepo);

                if (application.getRepositoryRevision() != null
                        && !application.getRepositoryRevision().isEmpty()) {
                    //remote checkout
                    git.checkout().setCreateBranch(true).setStartPoint(application.getRepositoryRevision())
                            .setName(application.getRepositoryRevision()).call();
                } else {

                    List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();

                    String repoBranch = (application.getRepositoryBranch() != null
                            && !application.getRepositoryBranch().isEmpty()) ? application.getRepositoryBranch()
                                    : "master";

                    boolean localCheckout = false;

                    for (Ref ref : refs) {
                        String refName = ref.getName();
                        if (refName.contains(repoBranch) && !refName.contains(Constants.R_REMOTES)) {
                            localCheckout = true;
                        }
                    }

                    String HEAD = localRepo.getFullBranch();

                    if (HEAD.contains(repoBranch)) {
                        git.pull().setRemote("origin").setRemoteBranchName(repoBranch)
                                .setCredentialsProvider(getApplicationCredentials(application)).call();
                    } else {
                        if (localCheckout) {
                            //local checkout
                            git.checkout().setName(application.getRepositoryBranch()).call();
                            git.pull().setRemote("origin").setRemoteBranchName(repoBranch)
                                    .setCredentialsProvider(getApplicationCredentials(application)).call();
                        } else {
                            //remote checkout
                            git.checkout().setCreateBranch(true).setName(repoBranch)
                                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM)
                                    .setStartPoint("origin/" + repoBranch).call();
                        }
                    }
                }

                return git.getRepository().getWorkTree();
            }
        } catch (JGitInternalException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (IOException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (WrongRepositoryStateException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidConfigurationException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (DetachedHeadException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidRemoteException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (CanceledException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (RefNotFoundException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (NoHeadException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (RefAlreadyExistsException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (CheckoutConflictException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidRefNameException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (TransportException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (GitAPIException e) {
            log.error(EXCEPTION_MESSAGE, e);
        }
    } else {
        try {
            log.info("Attempting to clone application from repository.");
            Git result = clone(application, dirLocation);
            if (result != null) {
                log.info("Application was successfully cloned from repository.");
                return result.getRepository().getWorkTree();
            }
            log.error(EXCEPTION_MESSAGE);
        } catch (JGitInternalException e) {
            log.error(EXCEPTION_MESSAGE, e);
        }
    }
    return null;
}

From source file:com.genuitec.eclipse.gerrit.tools.internal.changes.commands.CleanupChangesCommand.java

License:Open Source License

@Override
protected Expression getEnabledWhenExpression() {
    if (enabledWhen == null) {
        enabledWhen = new Expression() {
            public EvaluationResult evaluate(IEvaluationContext context) throws CoreException {
                ISelection selection = InternalHandlerUtil.getCurrentSelection(context);
                Repository repo = RepositoryUtils.getRepository(selection);
                String curBranch = null;
                if (repo != null) {
                    try {
                        curBranch = repo.getFullBranch();
                        if (curBranch.startsWith("refs/heads/changes/")) {
                            curBranch = curBranch.substring("refs/heads/changes/".length());
                        }// www .j  a v  a 2  s  . co m
                    } catch (IOException e) {
                        //ignore
                    }
                    try {
                        if (repo != null) {
                            for (String branch : repo.getRefDatabase().getRefs("refs/heads/changes/")
                                    .keySet()) {
                                if (!branch.equals(curBranch) && branch.indexOf('/') > 0) {
                                    return EvaluationResult.TRUE;
                                }
                            }
                        }
                    } catch (IOException ex) {
                        //ignore
                    }
                }
                return EvaluationResult.FALSE;
            }

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.core.expressions.Expression#collectExpressionInfo(org.eclipse.core.expressions.ExpressionInfo)
             */
            public void collectExpressionInfo(ExpressionInfo info) {
                info.addVariableNameAccess(ISources.ACTIVE_CURRENT_SELECTION_NAME);
            }
        };
    }
    return enabledWhen;
}

From source file:com.genuitec.eclipse.gerrit.tools.internal.gps.model.GpsGitRepositoriesConfig.java

License:Open Source License

public GpsGitRepositoriesConfig(GpsFile gpsFile) throws CoreException {

    for (GpsProject project : gpsFile.getProjects()) {
        final IGpsRepositoryHandler handler = project.getRepositoryHandler();
        if (handler instanceof GpsGitRepositoryHandler) {
            final String repoName = ((GpsGitRepositoryHandler) handler).getRepositoryPath().segment(0);
            repo2branch.put(repoName, null);
        }/*  www  .  j  a v  a 2 s .  co m*/
    }

    for (String repoName : repo2branch.keySet()) {
        //acquire project's repository
        Repository repository = RepositoryUtils.getRepositoryForName(repoName);
        if (repository == null) {
            throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID, MessageFormat
                    .format("Cannot store configuration for repository {0}. It is not configured.", repoName)));
        }
        try {
            repo2branch.put(repoName,
                    new RepoSetup(repoName, repository.getFullBranch(), getRepoUrl(repository)));
        } catch (IOException e) {
            throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID, MessageFormat.format(
                    "Cannot store configuration for repository {0}:\n{1}", repoName, e.getMessage()), e));
        }
    }

}

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Returns the target of the symbolic HEAD reference for a repository.
 * Normally returns a branch reference name, but when HEAD is detached,
 * the commit is matched against the known tags. The most recent matching
 * tag ref name will be returned if it references the HEAD commit. If
 * no match is found, the SHA1 is returned.
 *
 * @param repository//from ww w  . j av a2  s . co  m
 * @return the ref name or the SHA1 for a detached HEAD
 */
public static String getHEADRef(Repository repository) {
    String target = null;
    try {
        target = repository.getFullBranch();
    } catch (Throwable t) {
        error(t, repository, "{0} failed to get symbolic HEAD target");
    }
    return target;
}

From source file:com.google.appraise.eclipse.core.AppraiseReviewsTaskDataHandler.java

License:Open Source License

/**
 * Sets up a new review on the current branch, as a task.
 *///from  w w w .  j a v  a 2  s  .c om
private void createNewReviewTask(TaskRepository repository, TaskData taskData) throws CoreException {
    Repository repo = AppraisePluginUtils.getGitRepoForRepository(repository);
    AppraisePluginReviewClient client;

    try {
        client = new AppraisePluginReviewClient(repository);
    } catch (GitClientException e1) {
        throw new CoreException(new Status(IStatus.ERROR, AppraiseConnectorPlugin.PLUGIN_ID,
                "Failed to initialize git client"));
    }

    // Reviews get created on the current branch and point to the master ref by default.
    String currentBranch;
    try {
        currentBranch = repo.getFullBranch();
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, AppraiseConnectorPlugin.PLUGIN_ID,
                "Error retrieving current branch", e));
    }
    if (MASTER_REF.equals(currentBranch)) {
        throw new CoreException(new Status(IStatus.ERROR, AppraiseConnectorPlugin.PLUGIN_ID,
                "Cannot create review on master branch"));
    }
    setAttributeValue(taskData, schema.REQUESTER, repository.getUserName());
    setAttributeValue(taskData, schema.TARGET_REF, MASTER_REF);
    setAttributeValue(taskData, schema.REVIEW_REF, currentBranch);

    // Review notes get written on the first commit that differs from the master.
    RevCommit reviewCommit;
    try {
        reviewCommit = client.getReviewCommit(currentBranch, MASTER_REF);
    } catch (GitClientException e) {
        throw new CoreException(
                new Status(IStatus.ERROR, AppraiseConnectorPlugin.PLUGIN_ID, "Cannot find a merge base", e));
    }
    if (reviewCommit == null) {
        throw new CoreException(new Status(IStatus.INFO, AppraiseConnectorPlugin.PLUGIN_ID,
                "No commits to review on " + currentBranch));
    }
    setAttributeValue(taskData, schema.DESCRIPTION, reviewCommit.getFullMessage());
    setAttributeValue(taskData, schema.REVIEW_COMMIT, reviewCommit.getName());

    // TODO: If the user changes the target branch, we should refresh the diffs
    // on the task data.
    try {
        List<DiffEntry> diffs = client.getReviewDiffs(currentBranch, MASTER_REF);
        populateDiffs(repository, diffs, taskData);
    } catch (Exception e) {
        throw new CoreException(
                new Status(IStatus.ERROR, AppraiseConnectorPlugin.PLUGIN_ID, "Failed to load review diffs", e));
    }
}

From source file:com.google.appraise.eclipse.ui.editor.AppraiseReviewTaskActivationListener.java

License:Open Source License

/**
 * Asks the user if they want to switch to the review branch, and performs
 * the switch if so./*from  w w w.jav  a  2 s .c om*/
 */
private void promptSwitchToReviewBranch(TaskRepository taskRepository, String reviewBranch) {
    MessageDialog dialog = new MessageDialog(null, "Appraise Review", null,
            "Do you want to switch to the review branch (" + reviewBranch + ")", MessageDialog.QUESTION,
            new String[] { "Yes", "No" }, 0);
    int result = dialog.open();
    if (result == 0) {
        Repository repo = AppraisePluginUtils.getGitRepoForRepository(taskRepository);
        try (Git git = new Git(repo)) {
            previousBranch = repo.getFullBranch();
            git.checkout().setName(reviewBranch).call();
        } catch (RefNotFoundException rnfe) {
            MessageDialog alert = new MessageDialog(null, "Oops", null, "Branch " + reviewBranch + " not found",
                    MessageDialog.INFORMATION, new String[] { "OK" }, 0);
            alert.open();
        } catch (Exception e) {
            AppraiseUiPlugin.logError("Unable to switch to review branch: " + reviewBranch, e);
        }
    }
}

From source file:com.google.gerrit.server.git.ReceiveCommits.java

License:Apache License

private static String readHEAD(Repository repo) {
    try {// w w w .  ja  v  a 2  s . co  m
        return repo.getFullBranch();
    } catch (IOException e) {
        log.error("Cannot read HEAD symref", e);
        return null;
    }
}

From source file:com.meltmedia.cadmium.core.git.GitService.java

License:Apache License

public String getBranchName() throws Exception {
    Repository repository = git.getRepository();
    if (ObjectId.isId(repository.getFullBranch())
            && repository.getFullBranch().equals(repository.resolve("HEAD").getName())) {
        RevWalk revs = null;/* w  w  w.  j  ava2 s .co  m*/
        try {
            log.trace("Trying to resolve tagname: {}", repository.getFullBranch());
            ObjectId tagRef = ObjectId.fromString(repository.getFullBranch());
            revs = new RevWalk(repository);
            RevCommit commit = revs.parseCommit(tagRef);
            Map<String, Ref> allTags = repository.getTags();
            for (String key : allTags.keySet()) {
                Ref ref = allTags.get(key);
                RevTag tag = revs.parseTag(ref.getObjectId());
                log.trace("Checking ref {}, {}", commit.getName(), tag.getObject());
                if (tag.getObject().equals(commit)) {
                    return key;
                }
            }
        } catch (Exception e) {
            log.warn("Invalid id: {}", repository.getFullBranch(), e);
        } finally {
            revs.release();
        }
    }
    return repository.getBranch();
}

From source file:fr.brouillard.oss.jgitver.impl.GitUtils.java

License:Apache License

public static boolean isDetachedHead(Repository repository) throws IOException {
    return repository.getFullBranch().matches("[0-9a-f]{40}");
}