Search in sources :

Example 1 with RefSpec

use of org.eclipse.jgit.transport.RefSpec in project che by eclipse.

the class JGitConnection method fetch.

@Override
public void fetch(FetchParams params) throws GitException, UnauthorizedException {
    String remoteName = params.getRemote();
    String remoteUri;
    try {
        List<RefSpec> fetchRefSpecs;
        List<String> refSpec = params.getRefSpec();
        if (!refSpec.isEmpty()) {
            fetchRefSpecs = new ArrayList<>(refSpec.size());
            for (String refSpecItem : refSpec) {
                RefSpec fetchRefSpec = //
                (refSpecItem.indexOf(':') < 0) ? //
                new RefSpec(Constants.R_HEADS + refSpecItem + ":") : new RefSpec(refSpecItem);
                fetchRefSpecs.add(fetchRefSpec);
            }
        } else {
            fetchRefSpecs = Collections.emptyList();
        }
        FetchCommand fetchCommand = getGit().fetch();
        // (otherwise JGit fails)
        if (remoteName != null && refSpec.isEmpty()) {
            boolean found = false;
            List<Remote> configRemotes = remoteList(null, false);
            for (Remote configRemote : configRemotes) {
                if (remoteName.equals(configRemote.getName())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                fetchRefSpecs = Collections.singletonList(new RefSpec(Constants.HEAD + ":" + Constants.FETCH_HEAD));
            }
        }
        if (remoteName == null) {
            remoteName = Constants.DEFAULT_REMOTE_NAME;
        }
        fetchCommand.setRemote(remoteName);
        remoteUri = getRepository().getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName, ConfigConstants.CONFIG_KEY_URL);
        fetchCommand.setRefSpecs(fetchRefSpecs);
        int timeout = params.getTimeout();
        if (timeout > 0) {
            fetchCommand.setTimeout(timeout);
        }
        fetchCommand.setRemoveDeletedRefs(params.isRemoveDeletedRefs());
        executeRemoteCommand(remoteUri, fetchCommand, params.getUsername(), params.getPassword());
    } catch (GitException | GitAPIException exception) {
        String errorMessage;
        if (exception.getMessage().contains("Invalid remote: ")) {
            errorMessage = ERROR_NO_REMOTE_REPOSITORY;
        } else if ("Nothing to fetch.".equals(exception.getMessage())) {
            return;
        } else {
            errorMessage = generateExceptionMessage(exception);
        }
        throw new GitException(errorMessage, exception);
    }
}
Also used : GitException(org.eclipse.che.api.git.exception.GitException) Remote(org.eclipse.che.api.git.shared.Remote) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RefSpec(org.eclipse.jgit.transport.RefSpec) FetchCommand(org.eclipse.jgit.api.FetchCommand)

Example 2 with RefSpec

use of org.eclipse.jgit.transport.RefSpec in project che by eclipse.

the class JGitConnection method push.

@Override
public PushResponse push(PushParams params) throws GitException, UnauthorizedException {
    List<Map<String, String>> updates = new ArrayList<>();
    String currentBranch = getCurrentBranch();
    String remoteName = params.getRemote();
    String remoteUri = getRepository().getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName, ConfigConstants.CONFIG_KEY_URL);
    PushCommand pushCommand = getGit().push();
    if (params.getRemote() != null) {
        pushCommand.setRemote(remoteName);
    }
    List<String> refSpec = params.getRefSpec();
    if (!refSpec.isEmpty()) {
        pushCommand.setRefSpecs(refSpec.stream().map(RefSpec::new).collect(Collectors.toList()));
    }
    pushCommand.setForce(params.isForce());
    int timeout = params.getTimeout();
    if (timeout > 0) {
        pushCommand.setTimeout(timeout);
    }
    try {
        @SuppressWarnings("unchecked") Iterable<PushResult> pushResults = (Iterable<PushResult>) executeRemoteCommand(remoteUri, pushCommand, params.getUsername(), params.getPassword());
        PushResult pushResult = pushResults.iterator().next();
        String commandOutput = pushResult.getMessages().isEmpty() ? "Successfully pushed to " + remoteUri : pushResult.getMessages();
        Collection<RemoteRefUpdate> refUpdates = pushResult.getRemoteUpdates();
        for (RemoteRefUpdate remoteRefUpdate : refUpdates) {
            final String remoteRefName = remoteRefUpdate.getRemoteName();
            // check status only for branch given in the URL or tags - (handle special "refs/for" case)
            String shortenRefFor = remoteRefName.startsWith("refs/for/") ? remoteRefName.substring("refs/for/".length()) : remoteRefName;
            if (!currentBranch.equals(Repository.shortenRefName(remoteRefName)) && !currentBranch.equals(shortenRefFor) && !remoteRefName.startsWith(Constants.R_TAGS)) {
                continue;
            }
            Map<String, String> update = new HashMap<>();
            RemoteRefUpdate.Status status = remoteRefUpdate.getStatus();
            if (status != RemoteRefUpdate.Status.OK) {
                List<String> refSpecs = params.getRefSpec();
                if (remoteRefUpdate.getStatus() == RemoteRefUpdate.Status.UP_TO_DATE) {
                    commandOutput = INFO_PUSH_IGNORED_UP_TO_DATE;
                } else {
                    String remoteBranch = !refSpecs.isEmpty() ? refSpecs.get(0).split(REFSPEC_COLON)[1] : "master";
                    String errorMessage = format(ERROR_PUSH_CONFLICTS_PRESENT, currentBranch + BRANCH_REFSPEC_SEPERATOR + remoteBranch, remoteUri);
                    if (remoteRefUpdate.getMessage() != null) {
                        errorMessage += "\nError errorMessage: " + remoteRefUpdate.getMessage() + ".";
                    }
                    throw new GitException(errorMessage);
                }
            }
            if (status != RemoteRefUpdate.Status.UP_TO_DATE || !remoteRefName.startsWith(Constants.R_TAGS)) {
                update.put(KEY_COMMIT_MESSAGE, remoteRefUpdate.getMessage());
                update.put(KEY_RESULT, status.name());
                TrackingRefUpdate refUpdate = remoteRefUpdate.getTrackingRefUpdate();
                if (refUpdate != null) {
                    update.put(KEY_REMOTENAME, Repository.shortenRefName(refUpdate.getLocalName()));
                    update.put(KEY_LOCALNAME, Repository.shortenRefName(refUpdate.getRemoteName()));
                } else {
                    update.put(KEY_REMOTENAME, Repository.shortenRefName(remoteRefUpdate.getSrcRef()));
                    update.put(KEY_LOCALNAME, Repository.shortenRefName(remoteRefUpdate.getRemoteName()));
                }
                updates.add(update);
            }
        }
        return newDto(PushResponse.class).withCommandOutput(commandOutput).withUpdates(updates);
    } catch (GitAPIException exception) {
        if ("origin: not found.".equals(exception.getMessage())) {
            throw new GitException(ERROR_NO_REMOTE_REPOSITORY, exception);
        } else {
            String message = generateExceptionMessage(exception);
            throw new GitException(message, exception);
        }
    }
}
Also used : RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) HashMap(java.util.HashMap) GitException(org.eclipse.che.api.git.exception.GitException) ArrayList(java.util.ArrayList) PushResult(org.eclipse.jgit.transport.PushResult) TrackingRefUpdate(org.eclipse.jgit.transport.TrackingRefUpdate) PushCommand(org.eclipse.jgit.api.PushCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RefSpec(org.eclipse.jgit.transport.RefSpec) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap)

Example 3 with RefSpec

use of org.eclipse.jgit.transport.RefSpec in project che by eclipse.

the class JGitConnection method pull.

@Override
public PullResponse pull(PullParams params) throws GitException, UnauthorizedException {
    String remoteName = params.getRemote();
    String remoteUri;
    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 = params.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 = params.getTimeout();
        if (timeout > 0) {
            fetchCommand.setTimeout(timeout);
        }
        FetchResult fetchResult = (FetchResult) executeRemoteCommand(remoteUri, fetchCommand, params.getUsername(), params.getPassword());
        Ref remoteBranchRef = fetchResult.getAdvertisedRef(remoteBranch);
        if (remoteBranchRef == null) {
            remoteBranchRef = fetchResult.getAdvertisedRef(Constants.R_HEADS + remoteBranch);
        }
        if (remoteBranchRef == null) {
            throw new GitException(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 = generateExceptionMessage(exception);
        }
        throw new GitException(errorMessage, exception);
    }
    return newDto(PullResponse.class).withCommandOutput("Successfully pulled from " + remoteUri);
}
Also used : FetchResult(org.eclipse.jgit.transport.FetchResult) GitException(org.eclipse.che.api.git.exception.GitException) IOException(java.io.IOException) CheckoutConflictException(org.eclipse.jgit.api.errors.CheckoutConflictException) StoredConfig(org.eclipse.jgit.lib.StoredConfig) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Ref(org.eclipse.jgit.lib.Ref) RefSpec(org.eclipse.jgit.transport.RefSpec) PullResponse(org.eclipse.che.api.git.shared.PullResponse) FetchCommand(org.eclipse.jgit.api.FetchCommand) DetachedHeadException(org.eclipse.jgit.api.errors.DetachedHeadException)

Example 4 with RefSpec

use of org.eclipse.jgit.transport.RefSpec in project che by eclipse.

the class JGitConnection method remoteAdd.

@Override
public void remoteAdd(RemoteAddParams params) throws GitException {
    String remoteName = params.getName();
    if (isNullOrEmpty(remoteName)) {
        throw new GitException(ERROR_ADD_REMOTE_NAME_MISSING);
    }
    StoredConfig config = repository.getConfig();
    Set<String> remoteNames = config.getSubsections("remote");
    if (remoteNames.contains(remoteName)) {
        throw new GitException(format(ERROR_ADD_REMOTE_NAME_ALREADY_EXISTS, remoteName));
    }
    String url = params.getUrl();
    if (isNullOrEmpty(url)) {
        throw new GitException(ERROR_ADD_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 GitException("Remote url " + url + " is invalid. ");
    }
    List<String> branches = params.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);
    }
}
Also used : StoredConfig(org.eclipse.jgit.lib.StoredConfig) URIish(org.eclipse.jgit.transport.URIish) RefSpec(org.eclipse.jgit.transport.RefSpec) GitException(org.eclipse.che.api.git.exception.GitException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) RemoteConfig(org.eclipse.jgit.transport.RemoteConfig)

Example 5 with RefSpec

use of org.eclipse.jgit.transport.RefSpec in project gitblit by gitblit.

the class TicketReferenceTest method assertDeleteBranch.

private void assertDeleteBranch(String branchName) throws Exception {
    RefSpec refSpec = new RefSpec().setSource(null).setDestination("refs/heads/" + branchName);
    Iterable<PushResult> results = git.push().setRefSpecs(refSpec).setRemote("origin").setCredentialsProvider(cp).call();
    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/" + branchName);
        assertEquals(Status.OK, ref.getStatus());
    }
}
Also used : RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) RefSpec(org.eclipse.jgit.transport.RefSpec) PushResult(org.eclipse.jgit.transport.PushResult)

Aggregations

RefSpec (org.eclipse.jgit.transport.RefSpec)46 Test (org.junit.Test)17 RevCommit (org.eclipse.jgit.revwalk.RevCommit)15 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)12 IOException (java.io.IOException)11 ObjectId (org.eclipse.jgit.lib.ObjectId)11 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)9 Git (org.eclipse.jgit.api.Git)8 PushCommand (org.eclipse.jgit.api.PushCommand)8 File (java.io.File)7 PushResult (org.eclipse.jgit.transport.PushResult)7 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)6 UsernamePasswordCredentialsProvider (org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider)6 AppServicePlan (com.microsoft.azure.management.appservice.AppServicePlan)5 PublishingProfile (com.microsoft.azure.management.appservice.PublishingProfile)5 ArrayList (java.util.ArrayList)5 FetchCommand (org.eclipse.jgit.api.FetchCommand)5 ChangeApi (com.google.gerrit.extensions.api.changes.ChangeApi)4 CherryPickInput (com.google.gerrit.extensions.api.changes.CherryPickInput)4 GitException (org.eclipse.che.api.git.exception.GitException)4