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

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

Introduction

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

Prototype

@Nullable
public String getBranch() throws IOException 

Source Link

Document

Get the short name of the current branch that HEAD points to.

Usage

From source file:org.eluder.coveralls.maven.plugin.domain.GitRepository.java

License:Open Source License

private String getBranch(final Repository repository) throws IOException {
    return repository.getBranch();
}

From source file:org.flowerplatform.web.git.explorer.GitFileNodeDataProvider.java

License:Open Source License

@Override
public boolean populateTreeNode(Object source, TreeNode destination, GenericTreeContext context) {
    super.populateTreeNode(source, destination, context);

    if (GitNodeType.NODE_TYPE_WDIR.equals(destination.getPathFragment().getType())) {
        try {// w  ww .j a  v  a 2s. com
            @SuppressWarnings("unchecked")
            Pair<File, String> pair = (Pair<File, String>) source;
            File wdirFile = pair.a;
            if (!GitUtils.MAIN_REPOSITORY.equals(wdirFile.getName())) {
                Repository repository = GitPlugin.getInstance().getUtils().getRepository(wdirFile);
                destination.setLabel(String.format("%s [%s]", destination.getLabel(), repository.getBranch()));
            }
        } catch (IOException e) {
        }
    }
    return true;
}

From source file:org.flowerplatform.web.git.GitService.java

License:Open Source License

@RemoteInvocation
public GitActionDto getNodeAdditionalData(ServiceInvocationContext context, List<PathFragment> path) {
    try {//  www .  j  ava  2 s  .  com
        RefNode refNode = (RefNode) GenericTreeStatefulService.getNodeByPathFor(path, null);
        GenericTreeStatefulService service = GenericTreeStatefulService.getServiceFromPathWithRoot(path);
        NodeInfo refNodeInfo = service.getVisibleNodes().get(refNode);
        Repository repository = getRepository(refNodeInfo);
        if (repository == null) {
            context.getCommunicationChannel()
                    .appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                            CommonPlugin.getInstance().getMessage("error"),
                            "Cannot find repository for node " + refNode,
                            DisplaySimpleMessageClientCommand.ICON_ERROR));
            return null;
        }
        GitActionDto data = new GitActionDto();
        data.setRepository(repository.getDirectory().getAbsolutePath());
        data.setBranch(repository.getBranch());

        return data;
    } catch (Exception e) {
        logger.debug(CommonPlugin.getInstance().getMessage("error"), path, e);
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
    }
    return null;
}

From source file:org.fusesource.fabric.git.internal.GitDataStore.java

License:Apache License

public <T> T gitOperation(PersonIdent personIdent, GitOperation<T> operation, boolean pullFirst,
        GitContext context) {// w  w  w.ja  va 2  s .c  om
    synchronized (gitOperationMonitor) {
        assertValid();
        try {
            Git git = getGit();
            Repository repository = git.getRepository();
            CredentialsProvider credentialsProvider = getCredentialsProvider();
            // lets default the identity if none specified
            if (personIdent == null) {
                personIdent = new PersonIdent(repository);
            }

            if (GitHelpers.hasGitHead(git)) {
                // lets stash any local changes just in case..
                git.stashCreate().setPerson(personIdent).setWorkingDirectoryMessage("Stash before a write")
                        .call();
            }
            String originalBranch = repository.getBranch();
            RevCommit statusBefore = CommitUtils.getHead(repository);

            if (pullFirst) {
                doPull(git, credentialsProvider);
            }

            T answer = operation.call(git, context);
            boolean requirePush = context.isRequirePush();
            if (context.isRequireCommit()) {
                requirePush = true;
                String message = context.getCommitMessage().toString();
                if (message.length() == 0) {
                    LOG.warn("No commit message from " + operation + ". Please add one! :)");
                }
                git.commit().setMessage(message).call();
            }

            git.checkout().setName(originalBranch).call();

            if (requirePush || hasChanged(statusBefore, CommitUtils.getHead(repository))) {
                clearCaches();
                doPush(git, context, credentialsProvider);
                fireChangeNotifications();
            }
            return answer;
        } catch (Exception e) {
            throw FabricException.launderThrowable(e);
        }
    }
}

From source file:org.jboss.tools.openshift.egit.core.EGitUtils.java

License:Open Source License

private static String getCurrentBranch(Repository repository) throws CoreException {
    String branch = null;//  www  .j a v a  2s . c om
    try {
        branch = repository.getBranch();
    } catch (IOException e) {
        throw new CoreException(
                createStatus(e, "Could not get current branch on repository \"{0}\"", repository.toString()));
    }
    return branch;
}

From source file:org.jboss.tools.openshift.egit.core.EGitUtils.java

License:Open Source License

/**
 * Returns <code>true</code> if the given repo has commits that are not
 * contained withing the repo attached to it via the given remote. It is
 * ahead of the given remote config.//  w  w  w .j a v a2  s .  c om
 * This will work for non{@link BranchTrackingStatus#of(Repository, String)} will tell you if the
 * given branch is ahead of it's tracking branch. It only works with a
 * branch that is tracking another branch. 
 * 
 * @param repo
 *            the repo to check
 * @param remote
 *            the name of the remote to check against
 * @param monitor
 *            the monitor to report progress to
 * @return
 * @throws IOException
 * @throws InvocationTargetException
 * @throws URISyntaxException
 * 
 * @see BranchTrackingStatus#of
 */
public static boolean isAhead(Repository repo, String remote, IProgressMonitor monitor)
        throws IOException, InvocationTargetException, URISyntaxException {
    Assert.isLegal(remote != null);
    Assert.isLegal(repo != null);
    if (remote.equals(getRemote(repo.getBranch(), repo.getConfig()))) {
        BranchTrackingStatus status = BranchTrackingStatus.of(repo, repo.getBranch());
        if (status != null) {
            return status.getAheadCount() > 0;
        }
    }
    return isNonTrackingBranchAhead(repo, remote, monitor);
}

From source file:org.jboss.tools.openshift.egit.core.EGitUtils.java

License:Open Source License

private static boolean isNonTrackingBranchAhead(Repository repo, String remote, IProgressMonitor monitor)
        throws URISyntaxException, InvocationTargetException, IOException {
    RemoteConfig remoteConfig = new RemoteConfig(repo.getConfig(), remote);
    FetchResult fetchResult = fetch(remoteConfig, repo, monitor);
    Ref ref = fetchResult.getAdvertisedRef(Constants.HEAD);
    if (ref == null) {
        return false;
    }//www  .ja  v  a  2s. co  m
    Ref currentBranchRef = repo.getRef(repo.getBranch());

    RevWalk walk = new RevWalk(repo);
    RevCommit localCommit = walk.parseCommit(currentBranchRef.getObjectId());
    RevCommit trackingCommit = walk.parseCommit(ref.getObjectId());
    walk.setRevFilter(RevFilter.MERGE_BASE);
    walk.markStart(localCommit);
    walk.markStart(trackingCommit);
    RevCommit mergeBase = walk.next();
    walk.reset();
    walk.setRevFilter(RevFilter.ALL);
    int aheadCount = RevWalkUtils.count(walk, localCommit, mergeBase);

    return aheadCount > 0;
}

From source file:org.thiesen.ant.git.GitInfoExtractor.java

License:Open Source License

public static GitInfo extractInfo(final File dir) throws IOException {
    if (!dir.exists()) {
        throw new BuildException("No such directory: " + dir);
    }/*from  w  w  w . j a  v a  2 s.c  o m*/

    final RepositoryBuilder builder = new RepositoryBuilder();
    final Repository r = builder.setGitDir(dir).readEnvironment() // scan environment GIT_* variables
            .findGitDir() // scan up the file system tree
            .build();

    try {
        final String currentBranch = r.getBranch();

        final RevCommit head = getHead(r);
        final String lastRevCommit = getRevCommitId(head);
        final String lastRevCommitShort = getRevCommitIdShort(head, r);
        final Date lastRevCommitDate = getRevCommitDate(head);

        final boolean workingCopyDirty = isDirty(null, r);

        final CustomTag lastRevTag = getLastRevTag(r);

        final boolean lastRevTagDirty = isDirty(lastRevTag, r);

        return GitInfo.valueOf(currentBranch, lastRevCommit, workingCopyDirty, lastRevTag, lastRevTagDirty,
                lastRevCommitShort, lastRevCommitDate);

    } finally {
        r.close();
    }
}

From source file:org.z2env.impl.gitcr.GitComponentRepositoryImpl.java

License:Apache License

private boolean hasBranchChanged(Repository clonedRepo) throws IOException {

    String currentBranch = clonedRepo.getBranch();
    boolean result = !currentBranch.equals(this.branch);

    return result;
}

From source file:org.z2env.impl.helper.GitTools.java

License:Apache License

/**
 * Switches to the given target branch in the given repository. If such a local branch exists the method performs a checkout on this branch. 
 * Otherwise the branch name can be a remote branch in which case a local tracking branch is created. 
 * @param repo the repository//w ww.ja  v a  2s. co m
 * @param targetBranch a local or remote branch name.
 * @throws IOException if something went wrong
 */
public static void switchBranch(Repository repo, String targetBranch) throws IOException {

    if (hasLocalBranch(repo, targetBranch)) {

        if (!targetBranch.equals(repo.getBranch())) {
            try {
                new Git(repo).checkout().setName(targetBranch).call();
            } catch (Exception e) {
                throw new IOException("Failed to switch to branch '" + targetBranch + "' inside " + repo + "!");
            }
        }

    } else if (hasRemoteBranch(repo, targetBranch)) {

        // create tracking branch 
        try {
            new Git(repo).branchCreate().setName(targetBranch).setUpstreamMode(SetupUpstreamMode.TRACK)
                    .setStartPoint(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + targetBranch)
                    .call();
        } catch (Exception e) {
            throw new IOException(
                    "Failed to create tracking branch '" + targetBranch + "' inside " + repo + "!");
        }

        // switch to new branch
        try {
            new Git(repo).checkout().setName(targetBranch).call();
        } catch (Exception e) {
            throw new IOException("Failed to switch to branch '" + targetBranch + "' inside " + repo + "!");
        }

    } else {
        throw new IOException("No such branch '" + targetBranch + "' inside " + repo + "!");
    }
}