Example usage for org.eclipse.jgit.lib ConfigConstants CONFIG_BRANCH_SECTION

List of usage examples for org.eclipse.jgit.lib ConfigConstants CONFIG_BRANCH_SECTION

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib ConfigConstants CONFIG_BRANCH_SECTION.

Prototype

String CONFIG_BRANCH_SECTION

To view the source code for org.eclipse.jgit.lib ConfigConstants CONFIG_BRANCH_SECTION.

Click Source Link

Document

The "branch" section

Usage

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

License:Open Source License

@RemoteInvocation
public ConfigBranchPageDto getConfigBranchData(ServiceInvocationContext context, List<PathFragment> path) {
    try {//  ww  w . j  a  v  a2s  .  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 {/*ww w . j  a  v a 2  s.co m*/
        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.GitUtils.java

License:Open Source License

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

    String branchName;//from  ww  w. j ava 2  s.  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;
}

From source file:org.flowerplatform.web.git.operation.CheckoutOperation.java

License:Open Source License

public boolean execute() {
    ProgressMonitor monitor = ProgressMonitor
            .create(GitPlugin.getInstance().getMessage("git.checkout.monitor.title"), channel);

    try {/*from w ww . ja  v a 2  s.co  m*/
        monitor.beginTask(
                GitPlugin.getInstance().getMessage("git.checkout.monitor.message", new Object[] { name }), 4);
        monitor.setTaskName("Getting remote branch...");
        Git git = new Git(repository);
        Ref ref;
        if (node instanceof Ref) {
            ref = (Ref) node;
        } 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);

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

                ref = repository.getRef(remoteRefName);
            }
        }
        monitor.worked(1);
        monitor.setTaskName("Creating local branch...");

        // create local branch
        git.branchCreate().setName(name).setStartPoint(ref.getName())
                .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM).call();

        if (!(node instanceof Ref)) {
            // save upstream configuration
            StoredConfig config = repository.getConfig();

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_MERGE,
                    upstreamBranch.getName());

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REMOTE,
                    remote.getName());

            if (rebase) {
                config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, name,
                        ConfigConstants.CONFIG_KEY_REBASE, true);
            } else {
                config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REBASE);
            }
            config.save();
        }
        monitor.worked(1);
        monitor.setTaskName("Creating working directory");

        // create working directory for local branch
        File mainRepoFile = repository.getDirectory().getParentFile();
        File wdirFile = new File(mainRepoFile.getParentFile(), GitUtils.WORKING_DIRECTORY_PREFIX + name);
        if (wdirFile.exists()) {
            GitPlugin.getInstance().getUtils().delete(wdirFile);
        }
        GitPlugin.getInstance().getUtils().run_git_workdir_cmd(mainRepoFile.getAbsolutePath(),
                wdirFile.getAbsolutePath());
        monitor.worked(1);
        monitor.setTaskName("Checkout branch");

        // checkout local branch
        Repository wdirRepo = GitPlugin.getInstance().getUtils().getRepository(wdirFile);
        git = new Git(wdirRepo);

        CheckoutCommand cc = git.checkout().setName(name).setForce(true);
        cc.call();

        // show checkout result
        if (cc.getResult().getStatus() == CheckoutResult.Status.CONFLICTS)
            channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                    GitPlugin.getInstance().getMessage("git.checkout.checkoutConflicts.title"),
                    GitPlugin.getInstance().getMessage("git.checkout.checkoutConflicts.message"),
                    cc.getResult().getConflictList().toString(),
                    DisplaySimpleMessageClientCommand.ICON_INFORMATION));

        else if (cc.getResult().getStatus() == CheckoutResult.Status.NONDELETED) {
            // double-check if the files are still there
            boolean show = false;
            List<String> pathList = cc.getResult().getUndeletedList();
            for (String path1 : pathList) {
                if (new File(wdirRepo.getWorkTree(), path1).exists()) {
                    show = true;
                    break;
                }
            }
            if (show) {
                channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                        GitPlugin.getInstance().getMessage("git.checkout.nonDeletedFiles.title"),
                        GitPlugin.getInstance().getMessage("git.checkout.nonDeletedFiles.message",
                                Repository.shortenRefName(name)),
                        cc.getResult().getUndeletedList().toString(),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
            }
        } else if (cc.getResult().getStatus() == CheckoutResult.Status.OK) {
            if (ObjectId.isId(wdirRepo.getFullBranch()))
                channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                        GitPlugin.getInstance().getMessage("git.checkout.detachedHead.title"),
                        GitPlugin.getInstance().getMessage("git.checkout.detachedHead.message"),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
        }
        monitor.worked(1);
        return true;
    } catch (Exception e) {
        channel.appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    } finally {
        monitor.done();
    }
}

From source file:org.flowerplatform.web.git.operation.internal.PullCommand.java

License:Open Source License

/**
 * Executes the {@code Pull} command with all the options and parameters
 * collected by the setter methods (e.g.
 * {@link #setProgressMonitor(ProgressMonitor)}) of this class. Each
 * instance of this class should only be used for one invocation of the
 * command. Don't call this method twice on an instance.
 *
 * @return the result of the pull/*from w w w  . jav  a 2  s.  c  o m*/
 * @throws WrongRepositoryStateException
 * @throws InvalidConfigurationException
 * @throws DetachedHeadException
 * @throws InvalidRemoteException
 * @throws CanceledException
 * @throws RefNotFoundException
 * @throws NoHeadException
 * @throws org.eclipse.jgit.api.errors.TransportException
 * @throws GitAPIException
 */
@SuppressWarnings("restriction")
public PullResult call() throws GitAPIException, WrongRepositoryStateException, InvalidConfigurationException,
        DetachedHeadException, InvalidRemoteException, CanceledException, RefNotFoundException, NoHeadException,
        org.eclipse.jgit.api.errors.TransportException {
    checkCallable();

    monitor.beginTask(JGitText.get().pullTaskName, 2);

    Object[] data = GitPlugin.getInstance().getUtils().getFetchPushUpstreamDataRefSpecAndRemote(repo);

    String fullBranch = (String) data[0];
    String branchName = fullBranch.substring(Constants.R_HEADS.length());

    if (!repo.getRepositoryState().equals(RepositoryState.SAFE))
        throw new WrongRepositoryStateException(MessageFormat.format(JGitText.get().cannotPullOnARepoWithState,
                repo.getRepositoryState().name()));

    // get the configured remote for the currently checked out branch
    // stored in configuration key branch.<branch name>.remote
    Config repoConfig = repo.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 = (String) data[1];

    // determines whether rebase should be used after fetching
    boolean doRebase = (boolean) data[3];

    final boolean isRemote = !remote.equals("."); //$NON-NLS-1$
    String remoteUri;
    FetchResult fetchRes;
    if (isRemote) {
        remoteUri = (String) data[2];

        if (monitor.isCancelled())
            throw new CanceledException(
                    MessageFormat.format(JGitText.get().operationCanceled, JGitText.get().pullTaskName));

        RefSpec refSpec = new RefSpec();
        refSpec = refSpec.setForceUpdate(true);
        refSpec = refSpec.setSourceDestination(remoteBranchName, fullBranch);

        FetchCommand fetch = new Git(repo).fetch().setRemote(remote).setRefSpecs(refSpec);

        fetch.setProgressMonitor(monitor);
        configure(fetch);

        fetchRes = fetch.call();
    } else {
        // we can skip the fetch altogether
        remoteUri = "local repository";
        fetchRes = null;
    }

    monitor.update(1);

    if (monitor.isCancelled())
        throw new CanceledException(
                MessageFormat.format(JGitText.get().operationCanceled, JGitText.get().pullTaskName));

    // we check the updates to see which of the updated branches
    // corresponds
    // to the remote branch name
    AnyObjectId commitToMerge;
    if (isRemote) {
        Ref r = null;
        if (fetchRes != null) {
            r = fetchRes.getAdvertisedRef(remoteBranchName);
            if (r == null)
                r = fetchRes.getAdvertisedRef(Constants.R_HEADS + remoteBranchName);
        }
        if (r == null)
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().couldNotGetAdvertisedRef, remoteBranchName));
        else
            commitToMerge = r.getObjectId();
    } else {
        try {
            commitToMerge = repo.resolve(remoteBranchName);
            if (commitToMerge == null)
                throw new RefNotFoundException(
                        MessageFormat.format(JGitText.get().refNotResolved, remoteBranchName));
        } catch (IOException e) {
            throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfPullCommand, e);
        }
    }

    String upstreamName = "branch \'" + Repository.shortenRefName(remoteBranchName) + "\' of " + remoteUri;

    PullResult result;
    if (doRebase) {
        RebaseCommand rebase = new Git(repo).rebase();
        RebaseResult rebaseRes = rebase.setUpstream(commitToMerge).setUpstreamName(upstreamName)
                .setProgressMonitor(monitor).setOperation(Operation.BEGIN).call();
        result = new PullResult(fetchRes, remote, rebaseRes);
    } else {
        MergeCommand merge = new Git(repo).merge();
        merge.include(upstreamName, commitToMerge);
        MergeResult mergeRes = merge.call();
        monitor.update(1);
        result = new PullResult(fetchRes, remote, mergeRes);
    }
    monitor.endTask();
    return result;
}

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

License:Open Source License

/**
 * Returns the name of the remote repository for the given branch. If
 * there's no current branch or no remote configured to it, the default
 * remote is returned ("origin")./*w ww.  j  a  v  a2 s  .co  m*/
 * 
 * @param branch
 *            the branch
 * @param repository
 *            the repository
 * @return the remote name
 */
private static String getRemoteName(String branch, Repository repository) {
    String remoteName = null;
    if (ObjectId.isId(branch)) {
        remoteName = Constants.DEFAULT_REMOTE_NAME;
    } else {
        remoteName = repository.getConfig().getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
                ConfigConstants.CONFIG_REMOTE_SECTION);
        if (remoteName == null) {
            remoteName = Constants.DEFAULT_REMOTE_NAME;
        }
    }

    return remoteName;
}

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

License:Open Source License

/**
 * Returns the remote for a given branch and config. Returns
 * <code>null</code> if none is explicitly configured.
 * /*from   w  w  w  .  j  a va 2s  .  co m*/
 * <pre>
 * [branch "master"]
 * remote = origin
 * </pre>
 * 
 * @param branch
 *            the branch to get the configured remote for the
 * @param config
 *            the configuration to look into
 * @return the configured remote or null.
 */
public static String getRemote(String branch, Config config) {
    return config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_REMOTE);
}