Example usage for org.eclipse.jgit.lib Constants R_HEADS

List of usage examples for org.eclipse.jgit.lib Constants R_HEADS

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Constants R_HEADS.

Prototype

String R_HEADS

To view the source code for org.eclipse.jgit.lib Constants R_HEADS.

Click Source Link

Document

Prefix for branch refs

Usage

From source file:org.fedoraproject.eclipse.packager.git.FpGitProjectBits.java

License:Open Source License

/**
 * Returns true if given branch name is NOT an ObjectId in string format.
 * I.e. if branchName has been created by doing repo.getBranch(), it would
 * return SHA1 Strings for remote branches. We don't want that.
 * /*  w  w w .j  a  v  a 2 s .  co  m*/
 * @param branchName
 * @return
 */
private boolean isNamedBranch(String branchName) {
    if (branchName.startsWith(Constants.R_HEADS) || branchName.startsWith(Constants.R_TAGS)
            || branchName.startsWith(Constants.R_REMOTES)) {
        return true;
    }
    return false;
}

From source file:org.fedoraproject.eclipse.packager.git.FpGitProjectBits.java

License:Open Source License

/**
 * Determine if there are unpushed changes on the current branch.
 * @return If there are unpushed changes.
 *///from   ww  w  . ja  v  a 2s.c o m
@Override
public boolean hasLocalChanges(IProjectRoot fedoraProjectRoot) {
    if (!isInitialized()) {
        // FIXME: raise exception instead.
        return true; // If we are not initialized we can't go any further!
    }
    try {
        // get remote ref from config
        String branchName = git.getRepository().getBranch();
        String trackingRemoteBranch = git.getRepository().getConfig()
                .getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_MERGE);
        ///////////////////////////////////////////////////////////
        // FIXME: Temp work-around for Eclipse EGit/JGit BZ #317411
        FetchCommand fetch = git.fetch();
        fetch.setRemote("origin"); //$NON-NLS-1$
        fetch.setTimeout(0);
        // Fetch refs for current branch; account for f14 + f14/master like
        // branch names. Need to fetch into remotes/origin/f14/master since
        // this is what is later used for local changes comparison.
        String fetchBranchSpec = Constants.R_HEADS + branchName + ":" + //$NON-NLS-1$
                Constants.R_REMOTES + "origin/" + branchName; //$NON-NLS-1$
        if (trackingRemoteBranch != null) {
            // have f14/master like branch
            trackingRemoteBranch = trackingRemoteBranch.substring(Constants.R_HEADS.length());
            fetchBranchSpec = Constants.R_HEADS + trackingRemoteBranch + ":" + //$NON-NLS-1$
                    Constants.R_REMOTES + "origin/" + trackingRemoteBranch; //$NON-NLS-1$
        }
        RefSpec spec = new RefSpec(fetchBranchSpec);
        fetch.setRefSpecs(spec);
        try {
            fetch.call();
        } catch (JGitInternalException e) {
            e.printStackTrace();
        } catch (InvalidRemoteException e) {
            e.printStackTrace();
        }
        //--- End temp work-around for EGit/JGit bug.

        RevWalk rw = new RevWalk(git.getRepository());
        ObjectId objHead = git.getRepository().resolve(branchName);
        if (trackingRemoteBranch == null) {
            // no config yet, assume plain brach name.
            trackingRemoteBranch = branchName;
        }
        RevCommit commitHead = rw.parseCommit(objHead);
        ObjectId objRemoteTrackingHead = git.getRepository().resolve("origin/" + //$NON-NLS-1$
                trackingRemoteBranch);
        RevCommit remoteCommitHead = rw.parseCommit(objRemoteTrackingHead);
        return !commitHead.equals(remoteCommitHead);
    } catch (NoWorkTreeException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return true;
}

From source file:org.fedoraproject.eclipse.packager.tests.utils.git.GitConvertTestProject.java

License:Open Source License

/**
 * Adds a remote repository to the existing local packager project
 *
 * @throws Exception/* w w w  .  j  a  v a 2 s  .  c o  m*/
 */
public void addRemoteRepository(String uri, Git git) throws Exception {

    RemoteConfig config = new RemoteConfig(git.getRepository().getConfig(), "origin"); //$NON-NLS-1$
    config.addURI(new URIish(uri));
    String dst = Constants.R_REMOTES + config.getName();
    RefSpec refSpec = new RefSpec();
    refSpec = refSpec.setForceUpdate(true);
    refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", dst + "/*"); //$NON-NLS-1$ //$NON-NLS-2$

    config.addFetchRefSpec(refSpec);
    config.update(git.getRepository().getConfig());
    git.getRepository().getConfig().save();

    // fetch all the remote branches,
    // create corresponding branches locally and merge them
    FetchCommand fetch = git.fetch();
    fetch.setRemote("origin"); //$NON-NLS-1$
    fetch.setTimeout(0);
    fetch.setRefSpecs(refSpec);
    fetch.call();
    // refresh after checkout
    project.refreshLocal(IResource.DEPTH_INFINITE, null);
}

From source file:org.fedoraproject.eclipse.packager.tests.utils.git.GitTestProject.java

License:Open Source License

/**
 * Checkouts branch//from   w ww.j ava2 s .c om
 *
 * @param refName
 *            full name of branch
 * @throws CoreException
 * @throws InvalidRefNameException 
 * @throws RefNotFoundException 
 * @throws RefAlreadyExistsException 
 * @throws JGitInternalException 
 */
public void checkoutBranch(String branchName) throws JGitInternalException, RefAlreadyExistsException,
        RefNotFoundException, InvalidRefNameException, CoreException {
    boolean branchExists = false;
    ListBranchCommand lsBranchCmd = this.git.branchList();
    for (Ref branch : lsBranchCmd.call()) {
        if (Repository.shortenRefName(branch.getName()).equals(branchName)) {
            branchExists = true;
            break; // short circuit
        }
    }
    if (!branchExists) {
        System.err.println("Branch: '" + branchName + "' does not exist!");
        return;
    }
    CheckoutCommand checkoutCmd = this.git.checkout();
    checkoutCmd.setName(Constants.R_HEADS + branchName);
    checkoutCmd.call();
    // refresh after checkout
    project.refreshLocal(IResource.DEPTH_INFINITE, null);
}

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

License:Open Source License

@RemoteInvocation
public List<Object> getBranches(ServiceInvocationContext context, String repositoryUrl) {
    tlCommand.set((InvokeServiceMethodServerCommand) context.getCommand());
    Repository db = null;/*www. j a  v  a 2  s  .  c o  m*/
    try {
        URIish uri = new URIish(repositoryUrl.trim());
        db = new FileRepository(new File("/tmp"));

        Git git = new Git(db);
        LsRemoteCommand rc = git.lsRemote();
        rc.setRemote(uri.toString()).setTimeout(30);

        Collection<Ref> remoteRefs = rc.call();
        List<GitRef> branches = new ArrayList<GitRef>();

        Ref idHEAD = null;
        for (Ref r : remoteRefs) {
            if (r.getName().equals(Constants.HEAD)) {
                idHEAD = r;
            }
        }
        Ref head = null;
        boolean headIsMaster = false;
        String masterBranchRef = Constants.R_HEADS + Constants.MASTER;
        for (Ref r : remoteRefs) {
            String n = r.getName();
            if (!n.startsWith(Constants.R_HEADS))
                continue;
            branches.add(new GitRef(n, Repository.shortenRefName(n)));
            if (idHEAD == null || headIsMaster)
                continue;
            if (r.getObjectId().equals(idHEAD.getObjectId())) {
                headIsMaster = masterBranchRef.equals(r.getName());
                if (head == null || headIsMaster)
                    head = r;
            }
        }
        Collections.sort(branches, new Comparator<GitRef>() {
            public int compare(GitRef r1, GitRef r2) {
                return r1.getShortName().compareTo(r2.getShortName());
            }
        });
        if (idHEAD != null && head == null) {
            head = idHEAD;
            branches.add(0, new GitRef(idHEAD.getName(), Repository.shortenRefName(idHEAD.getName())));
        }

        GitRef headRef = head != null ? new GitRef(head.getName(), Repository.shortenRefName(head.getName()))
                : null;
        return Arrays.asList(new Object[] { branches, headRef });
    } catch (JGitInternalException | GitAPIException e) {
        context.getCommunicationChannel()
                .appendOrSendCommand(
                        new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                                GitPlugin.getInstance().getMessage("git.cloneWizard.branch.cannotListBranches")
                                        + "\n" + e.getCause().getMessage(),
                                DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (IOException e) {
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        GitPlugin.getInstance().getMessage("git.cloneWizard.branch.cannotCreateTempRepo"),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (URISyntaxException e) {
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getReason(), DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (Exception e) {
        if (GitPlugin.getInstance().getUtils().isAuthentificationException(e)) {
            openLoginWindow();
            return null;
        }
        logger.debug(CommonPlugin.getInstance().getMessage("error"), e);
    } finally {
        if (db != null) {
            db.close();
        }
    }
    return null;
}

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

License:Open Source License

public boolean rebase(ServiceInvocationContext context, String repositoryLocation, String refName) {
    try {//  w w w  .  j a  v  a  2  s.c om
        Repository repo = RepositoryCache.open(FileKey.exact(new File(repositoryLocation), FS.DETECTED));

        if (!repo.getFullBranch().startsWith(Constants.R_HEADS)) {
            context.getCommunicationChannel()
                    .appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                            CommonPlugin.getInstance().getMessage("error"),
                            GitPlugin.getInstance().getMessage("git.rebase.noLocalBranch"),
                            DisplaySimpleMessageClientCommand.ICON_ERROR));
            return false;
        }
        RebaseOperation op = new RebaseOperation(repo, refName, context.getCommunicationChannel());
        op.execute();

        String result = op.handleRebaseResult();
        if (result != null) {
            context.getCommunicationChannel()
                    .appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                            GitPlugin.getInstance().getMessage("git.rebase.result"), result,
                            DisplaySimpleMessageClientCommand.ICON_INFORMATION));
        }
        return true;
    } catch (Exception e) {
        logger.debug(CommonPlugin.getInstance().getMessage("error"), e);
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    }
}

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

License:Open Source License

@RemoteInvocation
public ConfigBranchPageDto getConfigBranchData(ServiceInvocationContext context, List<PathFragment> path) {
    try {//  w ww. ja  va  2s  .c  o  m
        RefNode node = (RefNode) GenericTreeStatefulService.getNodeByPathFor(path, null);
        Repository repository = node.getRepository();

        StoredConfig config = repository.getConfig();

        ConfigBranchPageDto dto = new ConfigBranchPageDto();

        Ref branch = (Ref) node.getRef();
        dto.setRef(new GitRef(branch.getName(), Repository.shortenRefName(branch.getName())));

        List<RemoteConfig> remotes = getAllRemotes(context, path);

        String branchName = branch.getName().substring(Constants.R_HEADS.length());
        String branchConfig = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_MERGE);

        String remoteConfig = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_REMOTE);
        if (remoteConfig == null) {
            remoteConfig = "";
        }
        if (remotes != null) {
            dto.setRemotes(remotes);

            for (RemoteConfig remote : remotes) {
                if (remote.getName().equals(remoteConfig)) {
                    List<Object> branches = getBranches(context, remote.getUri());
                    if (branches != null) {
                        @SuppressWarnings("unchecked")
                        List<GitRef> refs = (List<GitRef>) branches.get(0);
                        for (GitRef ref : refs) {
                            if (ref.getName().equals(branchConfig)) {
                                dto.setSelectedRef(ref);
                                break;
                            }
                        }
                        dto.setRefs(refs);
                    }
                    dto.setSelectedRemote(remote);
                    break;
                }
            }
        }

        boolean rebaseFlag = config.getBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_REBASE, false);
        dto.setRebase(rebaseFlag);

        return dto;
    } 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.flowerplatform.web.git.GitService.java

License:Open Source License

@RemoteInvocation
public boolean configBranch(ServiceInvocationContext context, List<PathFragment> path, GitRef upstreamBranch,
        RemoteConfig remote, boolean rebase) {
    try {/*from   w  w  w.  j a  va2s  .com*/
        RefNode node = (RefNode) GenericTreeStatefulService.getNodeByPathFor(path, null);
        Repository repository = node.getRepository();
        StoredConfig config = repository.getConfig();

        Ref ref;
        if (node instanceof Ref) {
            ref = node.getRef();
        } else {
            // get remote branch
            String dst = Constants.R_REMOTES + remote.getName();
            String remoteRefName = dst + "/" + upstreamBranch.getShortName();
            ref = repository.getRef(remoteRefName);
            if (ref == null) { // doesn't exist, fetch it
                RefSpec refSpec = new RefSpec();
                refSpec = refSpec.setForceUpdate(true);
                refSpec = refSpec.setSourceDestination(upstreamBranch.getName(), remoteRefName);

                new Git(repository).fetch().setRemote(new URIish(remote.getUri()).toPrivateString())
                        .setRefSpecs(refSpec).call();

                ref = repository.getRef(remoteRefName);
            }
        }

        String branchName = node.getRef().getName().substring(Constants.R_HEADS.length());
        if (upstreamBranch.getName().length() > 0) {
            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                    ConfigConstants.CONFIG_KEY_MERGE, upstreamBranch.getName());
        } else {
            config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_MERGE);
        }
        if (remote.getName().length() > 0) {
            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                    ConfigConstants.CONFIG_KEY_REMOTE, remote.getName());
        } else {
            config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REMOTE);
        }
        if (rebase) {
            config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                    ConfigConstants.CONFIG_KEY_REBASE, true);
        } else {
            config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REBASE);
        }

        config.save();

        return true;
    } 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 false;
    }
}

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

License:Open Source License

@RemoteInvocation
public boolean deleteBranch(ServiceInvocationContext context, List<PathFragment> path) {
    try {//www  .j  a  va2s .  c  o  m
        RefNode node = (RefNode) GenericTreeStatefulService.getNodeByPathFor(path, null);
        GenericTreeStatefulService service = GenericTreeStatefulService.getServiceFromPathWithRoot(path);
        NodeInfo nodeInfo = service.getVisibleNodes().get(node);
        Repository repository = node.getRepository();

        Git git = new Git(repository);

        git.branchDelete().setBranchNames(node.getRef().getName()).setForce(true).call();

        // delete working directory
        String branchName = node.getRef().getName().substring(Constants.R_HEADS.length());
        File mainRepoFile = repository.getDirectory().getParentFile();
        File wdirFile = new File(mainRepoFile.getParentFile(), GitUtils.WORKING_DIRECTORY_PREFIX + branchName);
        if (wdirFile.exists()) {
            GitPlugin.getInstance().getUtils().delete(wdirFile);
        }

        dispatchContentUpdate(nodeInfo.getParent().getNode());
        return true;
    } catch (GitAPIException e) {
        logger.debug(CommonPlugin.getInstance().getMessage("error"), path, e);
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    }
}

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

License:Open Source License

@SuppressWarnings("restriction")
public Object[] getFetchPushUpstreamDataRefSpecAndRemote(Repository repository)
        throws InvalidConfigurationException, NoHeadException, DetachedHeadException {

    String branchName;//  w ww. jav a2s . co  m
    String fullBranch;
    try {
        fullBranch = repository.getFullBranch();
        if (fullBranch == null) {
            throw new NoHeadException(JGitText.get().pullOnRepoWithoutHEADCurrentlyNotSupported);
        }
        if (!fullBranch.startsWith(Constants.R_HEADS)) {
            // we can not pull if HEAD is detached and branch is not
            // specified explicitly
            throw new DetachedHeadException();
        }
        branchName = fullBranch.substring(Constants.R_HEADS.length());
    } catch (IOException e) {
        throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfPullCommand, e);
    }
    // get the configured remote for the currently checked out branch
    // stored in configuration key branch.<branch name>.remote
    Config repoConfig = repository.getConfig();
    String remote = repoConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
            ConfigConstants.CONFIG_KEY_REMOTE);
    if (remote == null) {
        // fall back to default remote
        remote = Constants.DEFAULT_REMOTE_NAME;
    }

    // get the name of the branch in the remote repository
    // stored in configuration key branch.<branch name>.merge
    String remoteBranchName = repoConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
            ConfigConstants.CONFIG_KEY_MERGE);

    if (remoteBranchName == null) {
        String missingKey = ConfigConstants.CONFIG_BRANCH_SECTION + "." + branchName + "."
                + ConfigConstants.CONFIG_KEY_MERGE;
        throw new InvalidConfigurationException(
                MessageFormat.format(JGitText.get().missingConfigurationForKey, missingKey));
    }

    // check if the branch is configured for pull-rebase
    boolean doRebase = repoConfig.getBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
            ConfigConstants.CONFIG_KEY_REBASE, false);

    final boolean isRemote = !remote.equals("."); //$NON-NLS-1$
    String remoteUri;
    if (isRemote) {
        remoteUri = repoConfig.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remote,
                ConfigConstants.CONFIG_KEY_URL);
        if (remoteUri == null) {
            String missingKey = ConfigConstants.CONFIG_REMOTE_SECTION + "." + remote + "."
                    + ConfigConstants.CONFIG_KEY_URL;
            throw new InvalidConfigurationException(
                    MessageFormat.format(JGitText.get().missingConfigurationForKey, missingKey));
        }

        return new Object[] { fullBranch, remoteBranchName, remoteUri, doRebase };
    }
    return null;
}