Example usage for org.eclipse.jgit.lib ObjectId isId

List of usage examples for org.eclipse.jgit.lib ObjectId isId

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib ObjectId isId.

Prototype

public static final boolean isId(@Nullable String id) 

Source Link

Document

Test a string of characters to verify it is a hex format.

Usage

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

License:Open Source License

/**
 * Tries to map a commit to a symbolic reference.
 * <p>/*w  w w .j  av a2  s  . co m*/
 * 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.ui.internal.branch.BranchResultDialog.java

License:Open Source License

/**
 * @param result//w w  w  . ja v a  2  s .com
 *            the result to show
 * @param repository
 * @param target
 *            the target (branch name or commit id)
 */
public static void show(final CheckoutResult result, final Repository repository, final String target) {
    BranchResultDialog.target = target;
    if (result.getStatus() == CheckoutResult.Status.CONFLICTS)
        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
            public void run() {
                Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                new BranchResultDialog(shell, repository, result, target).open();
            }
        });
    else if (result.getStatus() == CheckoutResult.Status.NONDELETED) {
        // double-check if the files are still there
        boolean show = false;
        List<String> pathList = result.getUndeletedList();
        for (String path : pathList)
            if (new File(repository.getWorkTree(), path).exists()) {
                show = true;
                break;
            }
        if (!show)
            return;
        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
            public void run() {
                Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                new NonDeletedFilesDialog(shell, repository, result.getUndeletedList()).open();
            }
        });
    } else if (result.getStatus() == CheckoutResult.Status.OK) {
        try {
            if (ObjectId.isId(repository.getFullBranch()))
                showDetachedHeadWarning();
        } catch (IOException e) {
            Activator.logError(e.getMessage(), e);
        }
    }
}

From source file:org.eclipse.egit.ui.internal.commit.CommitSelectionDialog.java

License:Open Source License

protected void fillContentProvider(AbstractContentProvider contentProvider, ItemsFilter itemsFilter,
        IProgressMonitor progressMonitor) throws CoreException {
    String pattern = itemsFilter.getPattern();
    Repository[] repositories = getRepositories();
    progressMonitor.beginTask(UIText.CommitSelectionDialog_TaskSearching, repositories.length);
    for (Repository repository : repositories) {
        try {/*from  ww  w. ja  v a2s . com*/
            ObjectId commitId;
            if (ObjectId.isId(pattern))
                commitId = ObjectId.fromString(pattern);
            else
                commitId = repository.resolve(itemsFilter.getPattern());
            if (commitId != null) {
                RevWalk walk = new RevWalk(repository);
                walk.setRetainBody(true);
                RevCommit commit = walk.parseCommit(commitId);
                contentProvider.add(new RepositoryCommit(repository, commit), itemsFilter);
            }
        } catch (RevisionSyntaxException ignored) {
            // Ignore and advance
        } catch (IOException ignored) {
            // Ignore and advance
        }
        progressMonitor.worked(1);
    }
}

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

License:Open Source License

@Override
protected Control createDialogArea(Composite parent) {
    final Composite main = new Composite(parent, SWT.NONE);
    GridLayoutFactory.fillDefaults().applyTo(main);
    GridDataFactory.fillDefaults().grab(true, true).minSize(SWT.DEFAULT, SWT.DEFAULT).applyTo(main);

    if (showBranchInfo) {
        Composite branchArea = new Composite(main, SWT.NONE);
        GridLayoutFactory.swtDefaults().numColumns(2).equalWidth(false).applyTo(branchArea);
        GridDataFactory.fillDefaults().grab(true, false).applyTo(branchArea);

        Label branchLabel = new Label(branchArea, SWT.NONE);
        branchLabel.setText(UIText.AbstractConfigureRemoteDialog_BranchLabel);
        String branch;//from   w w w  .j a  v  a  2s.c  o  m
        try {
            branch = getRepository().getBranch();
        } catch (IOException e) {
            branch = null;
        }
        if (branch == null || ObjectId.isId(branch)) {
            branch = UIText.AbstractConfigureRemoteDialog_DetachedHeadMessage;
        }
        Text branchText = new Text(branchArea, SWT.BORDER | SWT.READ_ONLY);
        GridDataFactory.fillDefaults().grab(true, false).applyTo(branchText);
        branchText.setText(branch);

        addDefaultOriginWarning(main);

    }

    final Composite sameUriDetails = new Composite(main, SWT.NONE);
    GridLayoutFactory.fillDefaults().numColumns(4).equalWidth(false).applyTo(sameUriDetails);
    GridDataFactory.fillDefaults().grab(true, false).applyTo(sameUriDetails);
    Label commonUriLabel = new Label(sameUriDetails, SWT.NONE);
    commonUriLabel.setText(UIText.AbstractConfigureRemoteDialog_UriLabel);
    commonUriText = new Text(sameUriDetails, SWT.BORDER | SWT.READ_ONLY);
    GridDataFactory.fillDefaults().grab(true, false).applyTo(commonUriText);
    changeCommonUriAction = new Action(UIText.AbstractConfigureRemoteDialog_ChangeUriLabel) {

        @Override
        public void run() {
            SelectUriWizard wiz;
            if (!commonUriText.getText().isEmpty()) {
                wiz = new SelectUriWizard(true, commonUriText.getText());
            } else {
                wiz = new SelectUriWizard(true);
            }
            if (new WizardDialog(getShell(), wiz).open() == Window.OK) {
                if (!commonUriText.getText().isEmpty()) {
                    try {
                        getConfig().removeURI(new URIish(commonUriText.getText()));
                    } catch (URISyntaxException ex) {
                        Activator.handleError(ex.getMessage(), ex, true);
                    }
                }
                getConfig().addURI(wiz.getUri());
                updateControls();
            }
        }
    };
    deleteCommonUriAction = new Action(UIText.AbstractConfigureRemoteDialog_DeleteUriLabel) {

        @Override
        public void run() {
            getConfig().removeURI(getConfig().getURIs().get(0));
            updateControls();
        }
    };
    createActionButton(sameUriDetails, SWT.PUSH, changeCommonUriAction);
    createActionButton(sameUriDetails, SWT.PUSH, deleteCommonUriAction).setEnabled(false);

    commonUriText
            .addModifyListener(event -> deleteCommonUriAction.setEnabled(!commonUriText.getText().isEmpty()));

    createAdditionalUriArea(main);

    final Group refSpecGroup = new Group(main, SWT.SHADOW_ETCHED_IN);
    GridDataFactory.fillDefaults().grab(true, true).minSize(SWT.DEFAULT, SWT.DEFAULT).applyTo(refSpecGroup);
    refSpecGroup.setText(UIText.AbstractConfigureRemoteDialog_RefMappingGroup);
    GridLayoutFactory.fillDefaults().numColumns(2).applyTo(refSpecGroup);

    specViewer = new TableViewer(refSpecGroup, SWT.BORDER | SWT.MULTI);
    specViewer.setContentProvider(ArrayContentProvider.getInstance());
    GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 150).minSize(SWT.DEFAULT, 30).grab(true, true)
            .applyTo(specViewer.getTable());

    addRefSpecAction = new Action(UIText.AbstractConfigureRemoteDialog_AddRefSpecLabel) {

        @Override
        public void run() {
            doAddRefSpec();
        }
    };
    changeRefSpecAction = new Action(UIText.AbstractConfigureRemoteDialog_ChangeRefSpecLabel) {

        @Override
        public void run() {
            doChangeRefSpec();
        }
    };
    addRefSpecAdvancedAction = new Action(UIText.AbstractConfigureRemoteDialog_EditAdvancedLabel) {

        @Override
        public void run() {
            doAdvanced();
        }
    };
    IAction deleteRefSpecAction = ActionUtils.createGlobalAction(ActionFactory.DELETE,
            () -> doDeleteRefSpecs());
    IAction copyRefSpecAction = ActionUtils.createGlobalAction(ActionFactory.COPY, () -> doCopy());
    IAction pasteRefSpecAction = ActionUtils.createGlobalAction(ActionFactory.PASTE, () -> doPaste());
    IAction selectAllRefSpecsAction = ActionUtils.createGlobalAction(ActionFactory.SELECT_ALL, () -> {
        specViewer.getTable().selectAll();
        // selectAll doesn't fire a "selection changed" event
        specViewer.setSelection(specViewer.getSelection());
    });

    Composite buttonArea = new Composite(refSpecGroup, SWT.NONE);
    GridLayoutFactory.fillDefaults().applyTo(buttonArea);
    GridDataFactory.fillDefaults().grab(false, true).minSize(SWT.DEFAULT, SWT.DEFAULT).applyTo(buttonArea);

    createActionButton(buttonArea, SWT.PUSH, addRefSpecAction);
    createActionButton(buttonArea, SWT.PUSH, changeRefSpecAction);
    createActionButton(buttonArea, SWT.PUSH, deleteRefSpecAction);
    createActionButton(buttonArea, SWT.PUSH, copyRefSpecAction);
    createActionButton(buttonArea, SWT.PUSH, pasteRefSpecAction);
    createActionButton(buttonArea, SWT.PUSH, addRefSpecAdvancedAction);

    MenuManager contextMenu = new MenuManager();
    contextMenu.setRemoveAllWhenShown(true);
    contextMenu.addMenuListener(manager -> {
        specViewer.getTable().setFocus();
        if (addRefSpecAction.isEnabled()) {
            manager.add(addRefSpecAction);
        }
        if (changeRefSpecAction.isEnabled()) {
            manager.add(changeRefSpecAction);
        }
        if (deleteRefSpecAction.isEnabled()) {
            manager.add(deleteRefSpecAction);
        }
        manager.add(new Separator());
        manager.add(copyRefSpecAction);
        manager.add(pasteRefSpecAction);
        manager.add(selectAllRefSpecsAction);
    });
    specViewer.getTable().setMenu(contextMenu.createContextMenu(specViewer.getTable()));
    ActionUtils.setGlobalActions(specViewer.getTable(), deleteRefSpecAction, copyRefSpecAction,
            pasteRefSpecAction, selectAllRefSpecsAction);

    specViewer.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection sel = (IStructuredSelection) specViewer.getSelection();
            copyRefSpecAction.setEnabled(sel.size() == 1);
            changeRefSpecAction.setEnabled(sel.size() == 1);
            deleteRefSpecAction.setEnabled(!sel.isEmpty());
            selectAllRefSpecsAction.setEnabled(specViewer.getTable().getItemCount() > 0
                    && sel.size() != specViewer.getTable().getItemCount());
        }
    });

    // Initial action enablement (no selection in the specViewer):
    copyRefSpecAction.setEnabled(false);
    changeRefSpecAction.setEnabled(false);
    deleteRefSpecAction.setEnabled(false);

    applyDialogFont(main);
    return main;
}

From source file:org.eclipse.egit.ui.internal.fetch.SimpleConfigureFetchDialog.java

License:Open Source License

/**
 * @param repository//  ww  w. j a v  a2  s  . c  om
 * @return the configured remote for the current branch, or the default
 *         remote; <code>null</code> if a local branch is checked out that
 *         points to "." as remote
 */
public static RemoteConfig getConfiguredRemote(Repository repository) {
    String branch;
    try {
        branch = repository.getBranch();
    } catch (IOException e) {
        Activator.handleError(e.getMessage(), e, true);
        return null;
    }
    if (branch == null)
        return null;

    String remoteName;
    if (ObjectId.isId(branch))
        remoteName = Constants.DEFAULT_REMOTE_NAME;
    else
        remoteName = repository.getConfig().getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
                ConfigConstants.CONFIG_REMOTE_SECTION);

    // check if we find the configured and default Remotes
    List<RemoteConfig> allRemotes;
    try {
        allRemotes = RemoteConfig.getAllRemoteConfigs(repository.getConfig());
    } catch (URISyntaxException e) {
        allRemotes = new ArrayList<RemoteConfig>();
    }

    RemoteConfig defaultConfig = null;
    RemoteConfig configuredConfig = null;
    for (RemoteConfig config : allRemotes) {
        if (config.getName().equals(Constants.DEFAULT_REMOTE_NAME))
            defaultConfig = config;
        if (remoteName != null && config.getName().equals(remoteName))
            configuredConfig = config;
    }

    RemoteConfig configToUse = configuredConfig != null ? configuredConfig : defaultConfig;
    return configToUse;
}

From source file:org.eclipse.egit.ui.internal.fetch.SimpleConfigureFetchDialog.java

License:Open Source License

@Override
protected Control createDialogArea(Composite parent) {
    boolean advancedMode = Activator.getDefault().getPreferenceStore().getBoolean(ADVANCED_MODE_PREFERENCE);
    final Composite main = new Composite(parent, SWT.NONE);
    main.setLayout(new GridLayout(1, false));
    GridDataFactory.fillDefaults().grab(true, true).applyTo(main);

    if (showBranchInfo) {
        Composite branchArea = new Composite(main, SWT.NONE);
        GridLayoutFactory.swtDefaults().numColumns(2).equalWidth(false).applyTo(branchArea);
        GridDataFactory.fillDefaults().grab(true, false).applyTo(branchArea);

        Label branchLabel = new Label(branchArea, SWT.NONE);
        branchLabel.setText(UIText.SimpleConfigureFetchDialog_BranchLabel);
        String branch;//from   w  w w  .j  av  a 2 s .  com
        try {
            branch = repository.getBranch();
        } catch (IOException e2) {
            branch = null;
        }
        if (branch == null || ObjectId.isId(branch))
            branch = UIText.SimpleConfigureFetchDialog_DetachedHeadMessage;
        Text branchText = new Text(branchArea, SWT.BORDER | SWT.READ_ONLY);
        GridDataFactory.fillDefaults().grab(true, false).applyTo(branchText);
        branchText.setText(branch);
    }

    addDefaultOriginWarningIfNeeded(main);

    final Composite sameUriDetails = new Composite(main, SWT.NONE);
    GridLayoutFactory.fillDefaults().numColumns(4).equalWidth(false).applyTo(sameUriDetails);
    GridDataFactory.fillDefaults().grab(true, false).applyTo(sameUriDetails);
    Label commonUriLabel = new Label(sameUriDetails, SWT.NONE);
    commonUriLabel.setText(UIText.SimpleConfigureFetchDialog_UriLabel);
    commonUriText = new Text(sameUriDetails, SWT.BORDER | SWT.READ_ONLY);
    GridDataFactory.fillDefaults().grab(true, false).applyTo(commonUriText);
    changeCommonUri = new Button(sameUriDetails, SWT.PUSH);
    changeCommonUri.setText(UIText.SimpleConfigureFetchDialog_ChangeUriButton);
    changeCommonUri.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            SelectUriWizard wiz;
            if (commonUriText.getText().length() > 0)
                wiz = new SelectUriWizard(true, commonUriText.getText());
            else
                wiz = new SelectUriWizard(true);
            if (new WizardDialog(getShell(), wiz).open() == Window.OK) {
                if (commonUriText.getText().length() > 0)
                    try {
                        config.removeURI(new URIish(commonUriText.getText()));
                    } catch (URISyntaxException ex) {
                        Activator.handleError(ex.getMessage(), ex, true);
                    }
                config.addURI(wiz.getUri());
                updateControls();
            }
        }
    });

    final Button deleteCommonUri = new Button(sameUriDetails, SWT.PUSH);
    deleteCommonUri.setText(UIText.SimpleConfigureFetchDialog_DeleteUriButton);
    deleteCommonUri.setEnabled(false);
    deleteCommonUri.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            config.removeURI(config.getURIs().get(0));
            updateControls();
        }
    });

    commonUriText.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            deleteCommonUri.setEnabled(commonUriText.getText().length() > 0);
        }
    });

    final Group refSpecGroup = new Group(main, SWT.SHADOW_ETCHED_IN);
    GridDataFactory.fillDefaults().grab(true, true).applyTo(refSpecGroup);
    refSpecGroup.setText(UIText.SimpleConfigureFetchDialog_RefMappingGroup);
    refSpecGroup.setLayout(new GridLayout(2, false));

    specViewer = new TableViewer(refSpecGroup, SWT.BORDER | SWT.MULTI);
    specViewer.setContentProvider(ArrayContentProvider.getInstance());
    GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 150).minSize(SWT.DEFAULT, 30).grab(true, true)
            .applyTo(specViewer.getTable());

    specViewer.getTable().addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.stateMask == SWT.MOD1 && e.keyCode == 'v')
                doPaste();
        }
    });

    Composite buttonArea = new Composite(refSpecGroup, SWT.NONE);
    GridLayoutFactory.fillDefaults().applyTo(buttonArea);
    GridDataFactory.fillDefaults().grab(false, true).applyTo(buttonArea);

    addRefSpec = new Button(buttonArea, SWT.PUSH);
    addRefSpec.setText(UIText.SimpleConfigureFetchDialog_AddRefSpecButton);
    GridDataFactory.fillDefaults().applyTo(addRefSpec);
    addRefSpec.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            SimpleFetchRefSpecWizard wiz = new SimpleFetchRefSpecWizard(repository, config);
            WizardDialog dlg = new WizardDialog(getShell(), wiz);
            if (dlg.open() == Window.OK)
                config.addFetchRefSpec(wiz.getSpec());
            updateControls();
        }
    });

    changeRefSpec = new Button(buttonArea, SWT.PUSH);
    changeRefSpec.setText(UIText.SimpleConfigureFetchDialog_ChangeRefSpecButton);
    changeRefSpec.setEnabled(false);
    GridDataFactory.fillDefaults().exclude(!advancedMode).applyTo(changeRefSpec);
    changeRefSpec.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            RefSpec oldSpec = (RefSpec) ((IStructuredSelection) specViewer.getSelection()).getFirstElement();
            RefSpecDialog dlg = new RefSpecDialog(getShell(), repository, config, oldSpec, false);
            if (dlg.open() == Window.OK) {
                config.removeFetchRefSpec(oldSpec);
                config.addFetchRefSpec(dlg.getSpec());
            }
            updateControls();
        }
    });
    final Button deleteRefSpec = new Button(buttonArea, SWT.PUSH);
    deleteRefSpec.setText(UIText.SimpleConfigureFetchDialog_DeleteRefSpecButton);
    GridDataFactory.fillDefaults().applyTo(deleteRefSpec);
    deleteRefSpec.setEnabled(false);
    deleteRefSpec.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            for (Object spec : ((IStructuredSelection) specViewer.getSelection()).toArray())
                config.removeFetchRefSpec((RefSpec) spec);
            updateControls();
        }
    });

    final Button copySpec = new Button(buttonArea, SWT.PUSH);
    copySpec.setText(UIText.SimpleConfigureFetchDialog_CopyRefSpecButton);
    GridDataFactory.fillDefaults().applyTo(copySpec);
    copySpec.setEnabled(false);
    copySpec.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            String toCopy = ((IStructuredSelection) specViewer.getSelection()).getFirstElement().toString();
            Clipboard clipboard = new Clipboard(getShell().getDisplay());
            try {
                clipboard.setContents(new String[] { toCopy },
                        new TextTransfer[] { TextTransfer.getInstance() });
            } finally {
                clipboard.dispose();
            }
        }
    });

    final Button pasteSpec = new Button(buttonArea, SWT.PUSH);
    pasteSpec.setText(UIText.SimpleConfigureFetchDialog_PateRefSpecButton);
    GridDataFactory.fillDefaults().applyTo(pasteSpec);
    pasteSpec.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            doPaste();
        }
    });

    addRefSpecAdvanced = new Button(buttonArea, SWT.PUSH);
    GridDataFactory.fillDefaults().applyTo(addRefSpecAdvanced);

    addRefSpecAdvanced.setText(UIText.SimpleConfigureFetchDialog_EditAdvancedButton);
    addRefSpecAdvanced.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (new WizardDialog(getShell(), new RefSpecWizard(repository, config, false)).open() == Window.OK)
                updateControls();
        }
    });

    specViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection sel = (IStructuredSelection) specViewer.getSelection();
            copySpec.setEnabled(sel.size() == 1);
            changeRefSpec.setEnabled(sel.size() == 1);
            deleteRefSpec.setEnabled(!sel.isEmpty());
        }
    });

    applyDialogFont(main);
    return main;
}

From source file:org.eclipse.egit.ui.internal.push.SimpleConfigurePushDialog.java

License:Open Source License

@Override
protected Control createDialogArea(Composite parent) {
    boolean advancedMode = Activator.getDefault().getPreferenceStore().getBoolean(ADVANCED_MODE_PREFERENCE);
    final Composite main = new Composite(parent, SWT.NONE);
    main.setLayout(new GridLayout(1, false));
    GridDataFactory.fillDefaults().grab(true, true).minSize(SWT.DEFAULT, SWT.DEFAULT).applyTo(main);

    if (showBranchInfo) {
        Composite branchArea = new Composite(main, SWT.NONE);
        GridLayoutFactory.swtDefaults().numColumns(2).equalWidth(false).applyTo(branchArea);
        GridDataFactory.fillDefaults().grab(true, false).applyTo(branchArea);

        Label branchLabel = new Label(branchArea, SWT.NONE);
        branchLabel.setText(UIText.SimpleConfigurePushDialog_BranchLabel);
        String branch;//from   ww w .  ja v  a 2 s  .  c  o m
        try {
            branch = repository.getBranch();
        } catch (IOException e2) {
            branch = null;
        }
        if (branch == null || ObjectId.isId(branch))
            branch = UIText.SimpleConfigurePushDialog_DetachedHeadMessage;
        Text branchText = new Text(branchArea, SWT.BORDER | SWT.READ_ONLY);
        GridDataFactory.fillDefaults().grab(true, false).applyTo(branchText);
        branchText.setText(branch);
    }

    addDefaultOriginWarningIfNeeded(main);

    final Composite sameUriDetails = new Composite(main, SWT.NONE);
    sameUriDetails.setLayout(new GridLayout(4, false));
    GridDataFactory.fillDefaults().grab(true, false).applyTo(sameUriDetails);
    Label commonUriLabel = new Label(sameUriDetails, SWT.NONE);
    commonUriLabel.setText(UIText.SimpleConfigurePushDialog_URILabel);
    commonUriText = new Text(sameUriDetails, SWT.BORDER | SWT.READ_ONLY);
    GridDataFactory.fillDefaults().grab(true, false).applyTo(commonUriText);
    changeCommonUri = new Button(sameUriDetails, SWT.PUSH);
    changeCommonUri.setText(UIText.SimpleConfigurePushDialog_ChangeUriButton);
    changeCommonUri.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            SelectUriWizard wiz;
            if (commonUriText.getText().length() > 0)
                wiz = new SelectUriWizard(false, commonUriText.getText());
            else
                wiz = new SelectUriWizard(false);
            if (new WizardDialog(getShell(), wiz).open() == Window.OK) {
                if (commonUriText.getText().length() > 0)
                    try {
                        config.removeURI(new URIish(commonUriText.getText()));
                    } catch (URISyntaxException ex) {
                        Activator.handleError(ex.getMessage(), ex, true);
                    }
                config.addURI(wiz.getUri());
                updateControls();
            }
        }
    });

    deleteCommonUri = new Button(sameUriDetails, SWT.PUSH);
    deleteCommonUri.setText(UIText.SimpleConfigurePushDialog_DeleteUriButton);
    deleteCommonUri.setEnabled(false);
    deleteCommonUri.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            config.removeURI(config.getURIs().get(0));
            updateControls();
        }
    });

    commonUriText.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            deleteCommonUri.setEnabled(commonUriText.getText().length() > 0);
        }
    });

    ExpandableComposite pushUriArea = new ExpandableComposite(main,
            ExpandableComposite.TREE_NODE | ExpandableComposite.CLIENT_INDENT);
    GridDataFactory.fillDefaults().grab(true, false).applyTo(pushUriArea);
    pushUriArea.setExpanded(!config.getPushURIs().isEmpty());
    pushUriArea.addExpansionListener(new ExpansionAdapter() {

        public void expansionStateChanged(ExpansionEvent e) {
            main.layout(true, true);
            main.getShell().pack();
        }
    });
    pushUriArea.setText(UIText.SimpleConfigurePushDialog_PushUrisLabel);
    final Composite pushUriDetails = new Composite(pushUriArea, SWT.NONE);
    pushUriArea.setClient(pushUriDetails);
    pushUriDetails.setLayout(new GridLayout(2, false));
    GridDataFactory.fillDefaults().grab(true, true).applyTo(pushUriDetails);
    uriViewer = new TableViewer(pushUriDetails, SWT.BORDER | SWT.MULTI);
    GridDataFactory.fillDefaults().grab(true, true).minSize(SWT.DEFAULT, 30).applyTo(uriViewer.getTable());
    uriViewer.setContentProvider(ArrayContentProvider.getInstance());

    final Composite uriButtonArea = new Composite(pushUriDetails, SWT.NONE);
    GridLayoutFactory.fillDefaults().applyTo(uriButtonArea);
    GridDataFactory.fillDefaults().grab(false, true).applyTo(uriButtonArea);

    Button addUri = new Button(uriButtonArea, SWT.PUSH);
    addUri.setText(UIText.SimpleConfigurePushDialog_AddPushUriButton);
    GridDataFactory.fillDefaults().applyTo(addUri);
    addUri.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            SelectUriWizard wiz = new SelectUriWizard(false);
            if (new WizardDialog(getShell(), wiz).open() == Window.OK) {
                config.addPushURI(wiz.getUri());
                updateControls();
            }
        }

    });

    final Button changeUri = new Button(uriButtonArea, SWT.PUSH);
    changeUri.setText(UIText.SimpleConfigurePushDialog_ChangePushUriButton);
    GridDataFactory.fillDefaults().applyTo(changeUri);
    changeUri.setEnabled(false);
    changeUri.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            URIish uri = (URIish) ((IStructuredSelection) uriViewer.getSelection()).getFirstElement();
            SelectUriWizard wiz = new SelectUriWizard(false, uri.toPrivateString());
            if (new WizardDialog(getShell(), wiz).open() == Window.OK) {
                config.removePushURI(uri);
                config.addPushURI(wiz.getUri());
                updateControls();
            }
        }
    });
    final Button deleteUri = new Button(uriButtonArea, SWT.PUSH);
    deleteUri.setText(UIText.SimpleConfigurePushDialog_DeletePushUriButton);
    GridDataFactory.fillDefaults().applyTo(deleteUri);
    deleteUri.setEnabled(false);
    deleteUri.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            URIish uri = (URIish) ((IStructuredSelection) uriViewer.getSelection()).getFirstElement();
            config.removePushURI(uri);
            updateControls();
        }
    });

    uriViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            deleteUri.setEnabled(!uriViewer.getSelection().isEmpty());
            changeUri.setEnabled(((IStructuredSelection) uriViewer.getSelection()).size() == 1);
        }
    });

    final Group refSpecGroup = new Group(main, SWT.SHADOW_ETCHED_IN);
    GridDataFactory.fillDefaults().grab(true, true).minSize(SWT.DEFAULT, SWT.DEFAULT).applyTo(refSpecGroup);
    refSpecGroup.setText(UIText.SimpleConfigurePushDialog_RefMappingGroup);
    refSpecGroup.setLayout(new GridLayout(2, false));

    specViewer = new TableViewer(refSpecGroup, SWT.BORDER | SWT.MULTI);
    specViewer.setContentProvider(ArrayContentProvider.getInstance());
    GridDataFactory.fillDefaults().grab(true, true).minSize(SWT.DEFAULT, 30).applyTo(specViewer.getTable());
    specViewer.getTable().addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.stateMask == SWT.MOD1 && e.keyCode == 'v')
                doPaste();
        }
    });

    final Composite refButtonArea = new Composite(refSpecGroup, SWT.NONE);
    GridLayoutFactory.fillDefaults().applyTo(refButtonArea);
    GridDataFactory.fillDefaults().grab(false, true).minSize(SWT.DEFAULT, SWT.DEFAULT).applyTo(refButtonArea);

    addRefSpec = new Button(refButtonArea, SWT.PUSH);
    addRefSpec.setText(UIText.SimpleConfigurePushDialog_AddRefSpecButton);
    GridDataFactory.fillDefaults().applyTo(addRefSpec);
    addRefSpec.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            RefSpecDialog dlg = new RefSpecDialog(getShell(), repository, config, true);
            if (dlg.open() == Window.OK)
                config.addPushRefSpec(dlg.getSpec());
            updateControls();
        }
    });

    changeRefSpec = new Button(refButtonArea, SWT.PUSH);
    changeRefSpec.setText(UIText.SimpleConfigurePushDialog_ChangeRefSpecButton);
    GridDataFactory.fillDefaults().applyTo(changeRefSpec);
    changeRefSpec.setEnabled(false);
    GridDataFactory.fillDefaults().exclude(!advancedMode).applyTo(changeRefSpec);
    changeRefSpec.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            RefSpec oldSpec = (RefSpec) ((IStructuredSelection) specViewer.getSelection()).getFirstElement();
            RefSpecDialog dlg = new RefSpecDialog(getShell(), repository, config, oldSpec, true);
            if (dlg.open() == Window.OK) {
                config.removePushRefSpec(oldSpec);
                config.addPushRefSpec(dlg.getSpec());
            }
            updateControls();
        }
    });
    final Button deleteRefSpec = new Button(refButtonArea, SWT.PUSH);
    deleteRefSpec.setText(UIText.SimpleConfigurePushDialog_DeleteRefSpecButton);
    GridDataFactory.fillDefaults().applyTo(deleteRefSpec);
    deleteRefSpec.setEnabled(false);
    deleteRefSpec.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            for (Object spec : ((IStructuredSelection) specViewer.getSelection()).toArray())
                config.removePushRefSpec((RefSpec) spec);
            updateControls();
        }
    });

    final Button copySpec = new Button(refButtonArea, SWT.PUSH);
    copySpec.setText(UIText.SimpleConfigurePushDialog_CopyRefSpecButton);
    GridDataFactory.fillDefaults().applyTo(copySpec);
    copySpec.setEnabled(false);
    copySpec.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            String toCopy = ((IStructuredSelection) specViewer.getSelection()).getFirstElement().toString();
            Clipboard clipboard = new Clipboard(getShell().getDisplay());
            try {
                clipboard.setContents(new String[] { toCopy },
                        new TextTransfer[] { TextTransfer.getInstance() });
            } finally {
                clipboard.dispose();
            }
        }
    });

    final Button pasteSpec = new Button(refButtonArea, SWT.PUSH);
    pasteSpec.setText(UIText.SimpleConfigurePushDialog_PasteRefSpecButton);
    GridDataFactory.fillDefaults().applyTo(pasteSpec);
    pasteSpec.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            doPaste();
        }
    });

    addRefSpecAdvanced = new Button(refButtonArea, SWT.PUSH);
    addRefSpecAdvanced.setText(UIText.SimpleConfigurePushDialog_EditAdvancedButton);
    GridDataFactory.fillDefaults().applyTo(addRefSpecAdvanced);
    addRefSpecAdvanced.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (new WizardDialog(getShell(), new RefSpecWizard(repository, config, true)).open() == Window.OK)
                updateControls();
        }
    });

    specViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection sel = (IStructuredSelection) specViewer.getSelection();
            copySpec.setEnabled(sel.size() == 1);
            changeRefSpec.setEnabled(sel.size() == 1);
            deleteRefSpec.setEnabled(!sel.isEmpty());
        }
    });

    applyDialogFont(main);
    return main;
}

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

License:Open Source License

/**
 * Tries to map a commit to a symbolic reference.
 * <p>// www .  j  a  v a 2s.co  m
 * 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 {
            Map<String, Ref> tags = repository.getRefDatabase().getRefs(Constants.R_TAGS);
            for (Ref tagRef : tags.values()) {
                Tag tag = repository.mapTag(tagRef.getName());
                if (tag.getObjId().name().equals(commitId)) {
                    Date timestamp;
                    if (tag.getTagger() != null) {
                        timestamp = tag.getTagger().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.ui.test.team.actions.BranchAndResetActionTest.java

License:Open Source License

private void checkoutAndVerify(String[] currentBranch, String[] newBranch) throws IOException, Exception {
    SWTBotShell dialog = openBranchDialog();
    TableCollection tc = dialog.bot().tree().selection();
    assertEquals("Wrong selection count", 1, tc.rowCount());
    assertEquals("Wrong item selected", currentBranch[1], tc.get(0, 0));

    dialog.bot().tree().getTreeItem(newBranch[0]).expand().getNode(newBranch[1]).select();
    tc = dialog.bot().tree().selection();
    assertEquals("Wrong selection count", 1, tc.rowCount());
    assertEquals("Wrong item selected", newBranch[1], tc.get(0, 0));

    Repository repo = lookupRepository(repositoryFile);

    dialog.bot().button(UIText.BranchSelectionDialog_OkCheckout).click();
    waitInUI();//from  w w w . j a va2s.c  o  m
    if (ObjectId.isId(repo.getBranch())) {
        String mapped = Activator.getDefault().getRepositoryUtil().mapCommitToRef(repo, repo.getBranch(),
                false);
        assertEquals("Wrong branch", newBranch[1], mapped.substring(mapped.lastIndexOf('/') + 1));
    } else
        assertEquals("Wrong branch", newBranch[1], repo.getBranch());
}

From source file:org.eclipse.egit.ui.view.repositories.GitRepositoriesViewBranchHandlingTest.java

License:Open Source License

@Test
public void testCheckoutRemote() throws Exception {
    SWTBotPerspective perspective = null;
    try {/*ww w.  ja v  a 2 s.c  o  m*/
        perspective = bot.activePerspective();
        bot.perspectiveById("org.eclipse.pde.ui.PDEPerspective").activate();
        clearView();
        Activator.getDefault().getRepositoryUtil().addConfiguredRepository(clonedRepositoryFile);
        shareProjects(clonedRepositoryFile);
        refreshAndWait();

        Repository repo = lookupRepository(clonedRepositoryFile);
        BranchOperation bop = new BranchOperation(repo, "refs/heads/master");
        bop.execute(null);

        assertEquals("master", repo.getBranch());
        SWTBotTree tree = getOrOpenView().bot().tree();

        SWTBotTreeItem item = myRepoViewUtil.getLocalBranchesItem(tree, clonedRepositoryFile).expand();

        touchAndSubmit(null);
        refreshAndWait();

        item = myRepoViewUtil.getRemoteBranchesItem(tree, clonedRepositoryFile).expand();
        List<String> children = item.getNodes();
        assertEquals("Wrong number of remote children", 2, children.size());

        item.getNode("origin/stable").select();
        ContextMenuHelper.clickContextMenu(tree, myUtil.getPluginLocalizedValue("CheckoutCommand"));
        TestUtil.joinJobs(JobFamilies.CHECKOUT);
        refreshAndWait();

        GitLightweightDecorator.refresh();

        assertTrue("Branch should not be symbolic",
                ObjectId.isId(lookupRepository(clonedRepositoryFile).getBranch()));

        // now let's try to create a local branch from the remote one
        item = myRepoViewUtil.getRemoteBranchesItem(tree, clonedRepositoryFile).expand();
        item.getNode("origin/stable").select();
        ContextMenuHelper.clickContextMenu(tree, myUtil.getPluginLocalizedValue("CreateBranchCommand"));

        SWTBotShell createPage = bot.shell(UIText.CreateBranchWizard_NewBranchTitle);
        createPage.activate();
        assertEquals("Wrong suggested branch name", "stable",
                createPage.bot().textWithId("BranchName").getText());
        createPage.close();
        // checkout master again

        myRepoViewUtil.getLocalBranchesItem(tree, clonedRepositoryFile).expand().getNode("master").select();
        ContextMenuHelper.clickContextMenu(tree, myUtil.getPluginLocalizedValue("CheckoutCommand"));
        TestUtil.joinJobs(JobFamilies.CHECKOUT);
        refreshAndWait();

    } finally {
        if (perspective != null)
            perspective.activate();
    }
}