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

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

Introduction

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

Prototype

String DEFAULT_REMOTE_NAME

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

Click Source Link

Document

Default remote name used by clone, push and fetch operations

Usage

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

License:Open Source License

public void clone(CloneRequest request) throws GitException, UnauthorizedException {
    String remoteUri;/*from   www  .  j  av  a  2  s . c  om*/
    boolean removeIfFailed = false;
    try {
        if (request.getRemoteName() == null) {
            request.setRemoteName(Constants.DEFAULT_REMOTE_NAME);
        }
        if (request.getWorkingDir() == null) {
            request.setWorkingDir(repository.getWorkTree().getCanonicalPath());
        }

        // If clone fails and the .git folder didn't exist we want to remove it.
        // We have to do this here because the clone command doesn't revert its own changes in case of failure.
        removeIfFailed = !repository.getDirectory().exists();

        remoteUri = request.getRemoteUri();
        CloneCommand cloneCommand = Git.cloneRepository().setDirectory(new File(request.getWorkingDir()))
                .setRemote(request.getRemoteName()).setURI(remoteUri);
        if (request.getBranchesToFetch().isEmpty()) {
            cloneCommand.setCloneAllBranches(true);
        } else {
            cloneCommand.setBranchesToClone(request.getBranchesToFetch());
        }

        executeRemoteCommand(remoteUri, cloneCommand);

        StoredConfig repositoryConfig = getRepository().getConfig();
        GitUser gitUser = getUser();
        if (gitUser != null) {
            repositoryConfig.setString(ConfigConstants.CONFIG_USER_SECTION, null,
                    ConfigConstants.CONFIG_KEY_NAME, gitUser.getName());
            repositoryConfig.setString(ConfigConstants.CONFIG_USER_SECTION, null,
                    ConfigConstants.CONFIG_KEY_EMAIL, gitUser.getEmail());
        }
        repositoryConfig.save();
    } catch (IOException | GitAPIException exception) {
        // Delete .git directory in case it was created
        if (removeIfFailed) {
            deleteRepositoryFolder();
        }
        throw new GitException(exception.getMessage(), exception);
    }
}

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

License:Open Source License

@Override
public void fetch(FetchRequest request) throws GitException, UnauthorizedException {
    String remoteName = request.getRemote();
    String remoteUri;/*ww  w. ja  v a2 s.c om*/
    try {
        List<RefSpec> fetchRefSpecs;
        List<String> refSpec = request.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();

        // If this an unknown remote with no refspecs given, put HEAD
        // (otherwise JGit fails)
        if (remoteName != null && refSpec.isEmpty()) {
            boolean found = false;
            List<Remote> configRemotes = remoteList(newDto(RemoteListRequest.class));
            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 = request.getTimeout();
        if (timeout > 0) {
            fetchCommand.setTimeout(timeout);
        }
        fetchCommand.setRemoveDeletedRefs(request.isRemoveDeletedRefs());

        executeRemoteCommand(remoteUri, fetchCommand);
    } 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 = exception.getMessage();
        }
        throw new GitException(errorMessage, exception);
    }
}

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;// w  w  w. j  a v a  2s.  co  m
    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.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 {//from  w  w  w.  ja  v  a  2  s  .c o m
            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.internal.mylyn.ui.commit.TaskReferenceFactory.java

License:Open Source License

private static String getRepoUrl(Repository repo) {
    String configuredUrl = repo.getConfig().getString(BUGTRACK_SECTION, null, BUGTRACK_URL);
    String originUrl = repo.getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION,
            Constants.DEFAULT_REMOTE_NAME, ConfigConstants.CONFIG_KEY_URL);
    return configuredUrl != null ? configuredUrl : originUrl;
}

From source file:org.eclipse.egit.ui.internal.clone.CloneDestinationPage.java

License:Open Source License

private void createConfigGroup(final Composite parent) {
    final Group g = createGroup(parent, UIText.CloneDestinationPage_groupConfiguration);

    newLabel(g, UIText.CloneDestinationPage_promptRemoteName + ":"); //$NON-NLS-1$
    remoteText = new Text(g, SWT.BORDER);
    remoteText.setText(Constants.DEFAULT_REMOTE_NAME);
    remoteText.setLayoutData(createFieldGridData());
    remoteText.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            checkPage();//  w  w  w  .j ava2 s.co m
        }
    });
}

From source file:org.eclipse.egit.ui.internal.components.RemoteSelectionCombo.java

License:Open Source License

private RemoteConfig getDefaultRemoteConfig() {
    if (remoteConfigs == null || remoteConfigs.isEmpty())
        return null;
    for (final RemoteConfig rc : remoteConfigs)
        if (Constants.DEFAULT_REMOTE_NAME.equals(rc.getName()))
            return rc;
    return remoteConfigs.get(0);
}

From source file:org.eclipse.egit.ui.internal.components.RepositorySelectionPage.java

License:Open Source License

private RemoteConfig selectDefaultRemoteConfig() {
    if (configuredRemotes == null)
        return null;
    for (final RemoteConfig rc : configuredRemotes)
        if (Constants.DEFAULT_REMOTE_NAME.equals(rc.getName()))
            return rc;
    return configuredRemotes.get(0);
}

From source file:org.eclipse.egit.ui.internal.dialogs.AbstractConfigureRemoteDialog.java

License:Open Source License

/**
 * Add a warning about this remote being used by other branches
 *
 * @param parent//  w ww .  j  ava  2s  .  co  m
 */
private void addDefaultOriginWarning(Composite parent) {
    List<String> otherBranches = new ArrayList<>();
    String currentBranch;
    try {
        currentBranch = getRepository().getBranch();
    } catch (IOException e) {
        // just don't show this warning
        return;
    }
    String currentRemote = getConfig().getName();
    Config repositoryConfig = getRepository().getConfig();
    Set<String> branches = repositoryConfig.getSubsections(ConfigConstants.CONFIG_BRANCH_SECTION);
    for (String branch : branches) {
        if (branch.equals(currentBranch)) {
            continue;
        }
        String remote = repositoryConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
                ConfigConstants.CONFIG_KEY_REMOTE);
        if ((remote == null && currentRemote.equals(Constants.DEFAULT_REMOTE_NAME))
                || (remote != null && remote.equals(currentRemote))) {
            otherBranches.add(branch);
        }
    }
    if (otherBranches.isEmpty()) {
        return;
    }
    Composite warningAboutOrigin = new Composite(parent, SWT.NONE);
    GridLayoutFactory.fillDefaults().numColumns(2).applyTo(warningAboutOrigin);
    Label warningLabel = new Label(warningAboutOrigin, SWT.NONE);
    warningLabel
            .setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_WARN_TSK));
    Text warningText = new Text(warningAboutOrigin, SWT.READ_ONLY);
    warningText.setText(NLS.bind(UIText.AbstractConfigureRemoteDialog_ReusedRemoteWarning,
            getConfig().getName(), Integer.valueOf(otherBranches.size())));
    warningText.setToolTipText(otherBranches.toString());
    GridDataFactory.fillDefaults().grab(true, false).applyTo(warningLabel);
}

From source file:org.eclipse.egit.ui.internal.dialogs.NewRemoteDialog.java

License:Open Source License

@Override
public void create() {
    super.create();
    setTitle(UIText.NewRemoteDialog_DialogTitle);
    setMessage(UIText.NewRemoteDialog_ConfigurationMessage);
    if (existingRemotes.isEmpty()) {
        nameText.setText(Constants.DEFAULT_REMOTE_NAME);
        nameText.selectAll();//from www. j  av  a  2 s .co m
    }
    checkPage();
}