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.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public PullResponse pull(PullRequest request) throws GitException, UnauthorizedException {
    String remoteName = request.getRemote();
    String remoteUri;/* ww  w  .jav  a 2  s. com*/
    try {
        if (repository.getRepositoryState().equals(RepositoryState.MERGING)) {
            throw new GitException(ERROR_PULL_MERGING);
        }
        String fullBranch = repository.getFullBranch();
        if (!fullBranch.startsWith(Constants.R_HEADS)) {
            throw new DetachedHeadException(ERROR_PULL_HEAD_DETACHED);
        }

        String branch = fullBranch.substring(Constants.R_HEADS.length());

        StoredConfig config = repository.getConfig();
        if (remoteName == null) {
            remoteName = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
                    ConfigConstants.CONFIG_KEY_REMOTE);
            if (remoteName == null) {
                remoteName = Constants.DEFAULT_REMOTE_NAME;
            }
        }
        remoteUri = config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName,
                ConfigConstants.CONFIG_KEY_URL);

        String remoteBranch;
        RefSpec fetchRefSpecs = null;
        String refSpec = request.getRefSpec();
        if (refSpec != null) {
            fetchRefSpecs = (refSpec.indexOf(':') < 0) //
                    ? new RefSpec(Constants.R_HEADS + refSpec + ":" + fullBranch) //
                    : new RefSpec(refSpec);
            remoteBranch = fetchRefSpecs.getSource();
        } else {
            remoteBranch = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
                    ConfigConstants.CONFIG_KEY_MERGE);
        }

        if (remoteBranch == null) {
            remoteBranch = fullBranch;
        }

        FetchCommand fetchCommand = getGit().fetch();
        fetchCommand.setRemote(remoteName);
        if (fetchRefSpecs != null) {
            fetchCommand.setRefSpecs(fetchRefSpecs);
        }
        int timeout = request.getTimeout();
        if (timeout > 0) {
            fetchCommand.setTimeout(timeout);
        }

        FetchResult fetchResult = (FetchResult) executeRemoteCommand(remoteUri, fetchCommand);

        Ref remoteBranchRef = fetchResult.getAdvertisedRef(remoteBranch);
        if (remoteBranchRef == null) {
            remoteBranchRef = fetchResult.getAdvertisedRef(Constants.R_HEADS + remoteBranch);
        }
        if (remoteBranchRef == null) {
            throw new GitException(String.format(ERROR_PULL_REF_MISSING, remoteBranch));
        }
        org.eclipse.jgit.api.MergeResult mergeResult = getGit().merge().include(remoteBranchRef).call();
        if (mergeResult.getMergeStatus()
                .equals(org.eclipse.jgit.api.MergeResult.MergeStatus.ALREADY_UP_TO_DATE)) {
            return newDto(PullResponse.class).withCommandOutput("Already up-to-date");
        }

        if (mergeResult.getConflicts() != null) {
            StringBuilder message = new StringBuilder(ERROR_PULL_MERGE_CONFLICT_IN_FILES);
            message.append(lineSeparator());
            Map<String, int[][]> allConflicts = mergeResult.getConflicts();
            for (String path : allConflicts.keySet()) {
                message.append(path).append(lineSeparator());
            }
            message.append(ERROR_PULL_AUTO_MERGE_FAILED);
            throw new GitException(message.toString());
        }
    } catch (CheckoutConflictException exception) {
        StringBuilder message = new StringBuilder(ERROR_CHECKOUT_CONFLICT);
        message.append(lineSeparator());
        for (String path : exception.getConflictingPaths()) {
            message.append(path).append(lineSeparator());
        }
        message.append(ERROR_PULL_COMMIT_BEFORE_MERGE);
        throw new GitException(message.toString(), exception);
    } catch (IOException | GitAPIException exception) {
        String errorMessage;
        if (exception.getMessage().equals("Invalid remote: " + remoteName)) {
            errorMessage = ERROR_NO_REMOTE_REPOSITORY;
        } else {
            errorMessage = exception.getMessage();
        }
        throw new GitException(errorMessage, exception);
    }
    return newDto(PullResponse.class).withCommandOutput("Successfully pulled from " + remoteUri);
}

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public void remoteAdd(RemoteAddRequest request) throws GitException {
    String remoteName = request.getName();
    if (isNullOrEmpty(remoteName)) {
        throw new IllegalArgumentException(ERROR_ADD_REMOTE_NAME_MISSING);
    }//  www  .jav  a 2s  .  c o  m

    StoredConfig config = repository.getConfig();
    Set<String> remoteNames = config.getSubsections("remote");
    if (remoteNames.contains(remoteName)) {
        throw new IllegalArgumentException(String.format(ERROR_REMOTE_NAME_ALREADY_EXISTS, remoteName));
    }

    String url = request.getUrl();
    if (isNullOrEmpty(url)) {
        throw new IllegalArgumentException(ERROR_REMOTE_URL_MISSING);
    }

    RemoteConfig remoteConfig;
    try {
        remoteConfig = new RemoteConfig(config, remoteName);
    } catch (URISyntaxException exception) {
        // Not happen since it is newly created remote.
        throw new GitException(exception.getMessage(), exception);
    }

    try {
        remoteConfig.addURI(new URIish(url));
    } catch (URISyntaxException exception) {
        throw new IllegalArgumentException("Remote url " + url + " is invalid. ");
    }

    List<String> branches = request.getBranches();
    if (branches.isEmpty()) {
        remoteConfig.addFetchRefSpec(
                new RefSpec(Constants.R_HEADS + "*" + ":" + Constants.R_REMOTES + remoteName + "/*")
                        .setForceUpdate(true));
    } else {
        for (String branch : branches) {
            remoteConfig.addFetchRefSpec(new RefSpec(
                    Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remoteName + "/" + branch)
                            .setForceUpdate(true));
        }
    }

    remoteConfig.update(config);

    try {
        config.save();
    } catch (IOException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
}

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public void remoteUpdate(RemoteUpdateRequest request) throws GitException {
    String remoteName = request.getName();
    if (isNullOrEmpty(remoteName)) {
        throw new IllegalArgumentException(ERROR_UPDATE_REMOTE_NAME_MISSING);
    }/*from ww  w  . j  a  v  a  2  s  .  c o m*/

    StoredConfig config = repository.getConfig();
    Set<String> remoteNames = config.getSubsections(ConfigConstants.CONFIG_KEY_REMOTE);
    if (!remoteNames.contains(remoteName)) {
        throw new IllegalArgumentException("Remote " + remoteName + " not found. ");
    }

    RemoteConfig remoteConfig;
    try {
        remoteConfig = new RemoteConfig(config, remoteName);
    } catch (URISyntaxException e) {
        throw new GitException(e.getMessage(), e);
    }

    List<String> branches = request.getBranches();
    if (!branches.isEmpty()) {
        if (!request.isAddBranches()) {
            remoteConfig.setFetchRefSpecs(Collections.emptyList());
            remoteConfig.setPushRefSpecs(Collections.emptyList());
        } else {
            // Replace wildcard refSpec if any.
            remoteConfig.removeFetchRefSpec(
                    new RefSpec(Constants.R_HEADS + "*" + ":" + Constants.R_REMOTES + remoteName + "/*")
                            .setForceUpdate(true));
            remoteConfig.removeFetchRefSpec(
                    new RefSpec(Constants.R_HEADS + "*" + ":" + Constants.R_REMOTES + remoteName + "/*"));
        }

        // Add new refSpec.
        for (String branch : branches) {
            remoteConfig.addFetchRefSpec(new RefSpec(
                    Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remoteName + "/" + branch)
                            .setForceUpdate(true));
        }
    }

    // Remove URLs first.
    for (String url : request.getRemoveUrl()) {
        try {
            remoteConfig.removeURI(new URIish(url));
        } catch (URISyntaxException e) {
            LOG.debug(ERROR_REMOVING_INVALID_URL);
        }
    }

    // Add new URLs.
    for (String url : request.getAddUrl()) {
        try {
            remoteConfig.addURI(new URIish(url));
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("Remote url " + url + " is invalid. ");
        }
    }

    // Remove URLs for pushing.
    for (String url : request.getRemovePushUrl()) {
        try {
            remoteConfig.removePushURI(new URIish(url));
        } catch (URISyntaxException e) {
            LOG.debug(ERROR_REMOVING_INVALID_URL);
        }
    }

    // Add URLs for pushing.
    for (String url : request.getAddPushUrl()) {
        try {
            remoteConfig.addPushURI(new URIish(url));
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("Remote push url " + url + " is invalid. ");
        }
    }

    remoteConfig.update(config);

    try {
        config.save();
    } catch (IOException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
}

From source file:org.eclipse.egit.core.internal.ProjectReferenceImporter.java

License:Open Source License

private static File cloneIfNecessary(final URIish gitUrl, final String branch, final IPath workDir,
        final Set<ProjectReference> projects, IProgressMonitor monitor)
        throws TeamException, InterruptedException {

    final File repositoryPath = workDir.append(Constants.DOT_GIT_EXT).toFile();

    if (workDir.toFile().exists()) {
        if (repositoryAlreadyExistsForUrl(repositoryPath, gitUrl))
            return repositoryPath;
        else {//  ww  w .ja v  a2 s. com
            final Collection<String> projectNames = new LinkedList<String>();
            for (final ProjectReference projectReference : projects)
                projectNames.add(projectReference.getProjectDir());
            throw new TeamException(NLS.bind(CoreText.GitProjectSetCapability_CloneToExistingDirectory,
                    new Object[] { workDir, projectNames, gitUrl }));
        }
    } else {
        try {
            int timeout = 60;
            String refName = Constants.R_HEADS + branch;
            final CloneOperation cloneOperation = new CloneOperation(gitUrl, true, null, workDir.toFile(),
                    refName, Constants.DEFAULT_REMOTE_NAME, timeout);
            cloneOperation.run(monitor);

            return repositoryPath;
        } catch (final InvocationTargetException e) {
            throw getTeamException(e);
        }
    }
}

From source file:org.eclipse.egit.core.op.BranchOperation.java

License:Open Source License

private void updateHeadRef() throws TeamException {
    boolean detach = false;
    // in case of a non-local branch or a tag,
    // we "detach" HEAD, i.e. point it to the
    // underlying commit instead of to the Ref
    if (refName == null || !refName.startsWith(Constants.R_HEADS))
        detach = true;//from   w w w  . j a  v  a 2s  .c o  m
    try {
        RefUpdate u = repository.updateRef(Constants.HEAD, detach);
        Result res;
        if (detach) {
            u.setNewObjectId(newCommit.getId());
            // using forceUpdate instead of update avoids
            // the merge tests which would otherwise make
            // this fail
            u.setRefLogMessage(NLS.bind(CoreText.BranchOperation_checkoutMovingTo, newCommit.getId().name()),
                    false);
            res = u.forceUpdate();
        } else {
            u.setRefLogMessage(NLS.bind(CoreText.BranchOperation_checkoutMovingTo, refName), false);
            res = u.link(refName);
        }
        switch (res) {
        case NEW:
        case FORCED:
        case NO_CHANGE:
        case FAST_FORWARD:
            break;
        default:
            throw new IOException(u.getResult().name());
        }
    } catch (IOException e) {
        throw new TeamException(NLS.bind(CoreText.BranchOperation_updatingHeadToRef, refName), e);
    }
}

From source file:org.eclipse.egit.core.op.CloneOperation.java

License:Open Source License

private void doInit(final IProgressMonitor monitor) throws URISyntaxException, IOException {
    monitor.setTaskName(CoreText.CloneOperation_initializingRepository);

    local = new FileRepository(gitdir);
    local.create();//from w w  w .  j  a  va  2 s . c o m

    final RefUpdate head = local.updateRef(Constants.HEAD);
    head.disableRefLog();
    head.link(branch);

    remoteConfig = new RemoteConfig(local.getConfig(), remoteName);
    remoteConfig.addURI(uri);

    final String dst = Constants.R_REMOTES + remoteConfig.getName();
    RefSpec wcrs = new RefSpec();
    wcrs = wcrs.setForceUpdate(true);
    wcrs = wcrs.setSourceDestination(Constants.R_HEADS + "*", dst + "/*"); //$NON-NLS-1$ //$NON-NLS-2$

    if (allSelected) {
        remoteConfig.addFetchRefSpec(wcrs);
    } else {
        for (final Ref ref : selectedBranches)
            if (wcrs.matchSource(ref))
                remoteConfig.addFetchRefSpec(wcrs.expandFromSource(ref));
    }

    // we're setting up for a clone with a checkout
    local.getConfig().setBoolean("core", null, "bare", false); //$NON-NLS-1$ //$NON-NLS-2$

    remoteConfig.update(local.getConfig());

    // branch is like 'Constants.R_HEADS + branchName', we need only
    // the 'branchName' part
    String branchName = branch.substring(Constants.R_HEADS.length());

    // setup the default remote branch for branchName
    local.getConfig().setString("branch", branchName, "remote", remoteName); //$NON-NLS-1$ //$NON-NLS-2$
    local.getConfig().setString("branch", branchName, "merge", branch); //$NON-NLS-1$ //$NON-NLS-2$

    local.getConfig().save();
}

From source file:org.eclipse.egit.core.RepositoryUtil.java

License:Open Source License

/**
 * Tries to map a commit to a symbolic reference.
 * <p>/*from w w w. ja va 2  s  . com*/
 * This value will be cached for the given commit ID unless refresh is
 * specified. The return value will be the full name, e.g.
 * "refs/remotes/someBranch", "refs/tags/v.1.0"
 * <p>
 * Since this mapping is not unique, the following precedence rules are
 * used:
 * <ul>
 * <li>Tags take precedence over branches</li>
 * <li>Local branches take preference over remote branches</li>
 * <li>Newer references take precedence over older ones where time stamps
 * are available</li>
 * <li>If there are still ambiguities, the reference name with the highest
 * lexicographic value will be returned</li>
 * </ul>
 *
 * @param repository
 *            the {@link Repository}
 * @param commitId
 *            a commit
 * @param refresh
 *            if true, the cache will be invalidated
 * @return the symbolic reference, or <code>null</code> if no such reference
 *         can be found
 */
public String mapCommitToRef(Repository repository, String commitId, boolean refresh) {
    synchronized (commitMappingCache) {

        if (!ObjectId.isId(commitId)) {
            return null;
        }

        Map<String, String> cacheEntry = commitMappingCache.get(repository.getDirectory().toString());
        if (!refresh && cacheEntry != null && cacheEntry.containsKey(commitId)) {
            // this may be null in fact
            return cacheEntry.get(commitId);
        }
        if (cacheEntry == null) {
            cacheEntry = new HashMap<String, String>();
            commitMappingCache.put(repository.getDirectory().getPath(), cacheEntry);
        } else {
            cacheEntry.clear();
        }

        Map<String, Date> tagMap = new HashMap<String, Date>();
        try {
            RevWalk rw = new RevWalk(repository);
            Map<String, Ref> tags = repository.getRefDatabase().getRefs(Constants.R_TAGS);
            for (Ref tagRef : tags.values()) {
                RevTag tag = rw.parseTag(repository.resolve(tagRef.getName()));
                if (tag.getObject().name().equals(commitId)) {
                    Date timestamp;
                    if (tag.getTaggerIdent() != null) {
                        timestamp = tag.getTaggerIdent().getWhen();
                    } else {
                        timestamp = null;
                    }
                    tagMap.put(tagRef.getName(), timestamp);
                }
            }
        } catch (IOException e) {
            // ignore here
        }

        String cacheValue = null;

        if (!tagMap.isEmpty()) {
            // we try to obtain the "latest" tag
            Date compareDate = new Date(0);
            for (Map.Entry<String, Date> tagEntry : tagMap.entrySet()) {
                if (tagEntry.getValue() != null && tagEntry.getValue().after(compareDate)) {
                    compareDate = tagEntry.getValue();
                    cacheValue = tagEntry.getKey();
                }
            }
            // if we don't have time stamps, we sort
            if (cacheValue == null) {
                String compareString = ""; //$NON-NLS-1$
                for (String tagName : tagMap.keySet()) {
                    if (tagName.compareTo(compareString) >= 0) {
                        cacheValue = tagName;
                        compareString = tagName;
                    }
                }
            }
        }

        if (cacheValue == null) {
            // we didnt't find a tag, so let's look for local branches
            Set<String> branchNames = new TreeSet<String>();
            // put this into a sorted set
            try {
                Map<String, Ref> remoteBranches = repository.getRefDatabase().getRefs(Constants.R_HEADS);
                for (Ref branch : remoteBranches.values()) {
                    if (branch.getObjectId().name().equals(commitId)) {
                        branchNames.add(branch.getName());
                    }
                }
            } catch (IOException e) {
                // ignore here
            }
            if (!branchNames.isEmpty()) {
                // get the last (sorted) entry
                cacheValue = branchNames.toArray(new String[branchNames.size()])[branchNames.size() - 1];
            }
        }

        if (cacheValue == null) {
            // last try: remote branches
            Set<String> branchNames = new TreeSet<String>();
            // put this into a sorted set
            try {
                Map<String, Ref> remoteBranches = repository.getRefDatabase().getRefs(Constants.R_REMOTES);
                for (Ref branch : remoteBranches.values()) {
                    if (branch.getObjectId().name().equals(commitId)) {
                        branchNames.add(branch.getName());
                    }
                }
                if (!branchNames.isEmpty()) {
                    // get the last (sorted) entry
                    cacheValue = branchNames.toArray(new String[branchNames.size()])[branchNames.size() - 1];
                }
            } catch (IOException e) {
                // ignore here
            }
        }
        cacheEntry.put(commitId, cacheValue);
        return cacheValue;
    }
}

From source file:org.eclipse.egit.core.synchronize.GitResourceVariantComparatorTest.java

License:Open Source License

/**
 * When comparing file that don't exist in base, but exists in remote
 * compare method should return false./*w  ww .  j  av a2  s. c o m*/
 *
 * @throws Exception
 */
@Test
public void shouldReturnFalseWhenBaseDoesntExist() throws Exception {
    // when
    GitResourceVariantComparator grvc = new GitResourceVariantComparator(null);

    // given
    RevCommit baseCommit = testRepo.createInitialCommit("initial commit");
    testRepo.createAndCheckoutBranch(Constants.HEAD, Constants.R_HEADS + "test");
    File file = testRepo.createFile(iProject, "test-file");
    RevCommit remoteCommit = testRepo.addAndCommit(iProject, file, "second commit");
    String path = Repository.stripWorkDir(repo.getWorkTree(), file);

    GitBlobResourceVariant base = new GitBlobResourceVariant(repo, null, baseCommit.getTree(), path);
    GitBlobResourceVariant remote = new GitBlobResourceVariant(repo, null, remoteCommit.getTree(), path);

    // then
    assertFalse(grvc.compare(base, remote));
}

From source file:org.eclipse.egit.core.synchronize.GitResourceVariantComparatorTest.java

License:Open Source License

/**
 * Compare() should return false when remote file does not exists, but
 * equivalent local file exist./* w  w  w  . j a  va  2s.co m*/
 *
 * @throws Exception
 */
@Test
public void shouldReturnFalseWhenRemoteVariantDoesntExist() throws Exception {
    // when
    GitResourceVariantComparator grvc = new GitResourceVariantComparator(null);

    // given
    RevCommit remoteCommit = testRepo.createInitialCommit("initial commit");
    testRepo.createAndCheckoutBranch(Constants.HEAD, Constants.R_HEADS + "test");
    File file = testRepo.createFile(iProject, "test-file");
    RevCommit baseCommit = testRepo.addAndCommit(iProject, file, "second commit");
    String path = Repository.stripWorkDir(repo.getWorkTree(), file);

    GitBlobResourceVariant base = new GitBlobResourceVariant(repo, null, baseCommit.getTree(), path);
    GitBlobResourceVariant remote = new GitBlobResourceVariant(repo, null, remoteCommit.getTree(), path);

    // then
    assertFalse(grvc.compare(base, remote));
}

From source file:org.eclipse.egit.core.synchronize.GitResourceVariantTreeSubscriberTest.java

License:Open Source License

/**
 * This test simulates that user work and made some changes on branch 'test'
 * and then try to synchronize "test" and 'master' branch.
 *
 * @throws Exception/*  w  ww.j av  a  2s .  c o m*/
 */
@Test
public void shouldReturnSrcBranchAsBase() throws Exception {
    // when
    String fileName = "Main.java";
    File file = testRepo.createFile(iProject, fileName);
    RevCommit commit = testRepo.appendContentAndCommit(iProject, file, "class Main {}", "initial commit");
    IFile mainJava = testRepo.getIFile(iProject, file);
    testRepo.createAndCheckoutBranch(Constants.HEAD, Constants.R_HEADS + "test");
    testRepo.appendContentAndCommit(iProject, file, "// test1", "secont commit");

    // given
    GitResourceVariantTreeSubscriber grvts = createGitResourceVariantTreeSubscriber(Constants.HEAD,
            Constants.R_HEADS + Constants.MASTER);
    grvts.getBaseTree();
    IResourceVariantTree baseTree = grvts.getBaseTree();

    // then
    IResourceVariant actual = commonAssertionsForBaseTree(baseTree, mainJava);
    assertEquals(commit.abbreviate(7).name() + "...", actual.getContentIdentifier());
}