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

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

Introduction

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

Prototype

String R_REMOTES

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

Click Source Link

Document

Prefix for remotes refs

Usage

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

License:Open Source License

private void configureNewRemote(URIish uri) throws URISyntaxException, IOException {
    StoredConfig config = repository.getConfig();
    String remoteName = getRemoteName();
    RemoteConfig remoteConfig = new RemoteConfig(config, remoteName);
    remoteConfig.addURI(uri);//from   ww w  .  j a va  2 s  .  co m
    RefSpec defaultFetchSpec = new RefSpec().setForceUpdate(true).setSourceDestination(Constants.R_HEADS + "*", //$NON-NLS-1$
            Constants.R_REMOTES + remoteName + "/*"); //$NON-NLS-1$
    remoteConfig.addFetchRefSpec(defaultFetchSpec);
    remoteConfig.update(config);
    config.save();
}

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

License:Open Source License

private void addRefContentProposalToText(final Text textField) {
    KeyStroke stroke;//from www  .jav  a  2  s  .co  m
    try {
        stroke = KeyStroke.getInstance("CTRL+SPACE"); //$NON-NLS-1$
        UIUtils.addBulbDecorator(textField,
                NLS.bind(UIText.PushToGerritPage_ContentProposalHoverText, stroke.format()));
    } catch (ParseException e1) {
        Activator.handleError(e1.getMessage(), e1, false);
        stroke = null;
    }

    IContentProposalProvider cp = new IContentProposalProvider() {
        public IContentProposal[] getProposals(String contents, int position) {
            List<IContentProposal> resultList = new ArrayList<IContentProposal>();

            // make the simplest possible pattern check: allow "*"
            // for multiple characters
            String patternString = contents;
            // ignore spaces in the beginning
            while (patternString.length() > 0 && patternString.charAt(0) == ' ') {
                patternString = patternString.substring(1);
            }

            // we quote the string as it may contain spaces
            // and other stuff colliding with the Pattern
            patternString = Pattern.quote(patternString);

            patternString = patternString.replaceAll("\\x2A", ".*"); //$NON-NLS-1$ //$NON-NLS-2$

            // make sure we add a (logical) * at the end
            if (!patternString.endsWith(".*")) //$NON-NLS-1$
                patternString = patternString + ".*"; //$NON-NLS-1$

            // let's compile a case-insensitive pattern (assumes ASCII only)
            Pattern pattern;
            try {
                pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
            } catch (PatternSyntaxException e) {
                pattern = null;
            }

            Set<String> proposals = new TreeSet<String>();

            try {
                Set<String> remotes = repository.getRefDatabase().getRefs(Constants.R_REMOTES).keySet();
                for (String remote : remotes) {
                    // these are "origin/master", "origin/xxx"...
                    int slashIndex = remote.indexOf('/');
                    if (slashIndex > 0 && slashIndex < remote.length() - 1)
                        proposals.add(remote.substring(remote.indexOf('/') + 1));
                }
            } catch (IOException e) {
                // simply ignore, no proposals then
            }

            for (final String proposal : proposals) {
                if (pattern != null && !pattern.matcher(proposal).matches())
                    continue;
                IContentProposal propsal = new BranchContentProposal(proposal);
                resultList.add(propsal);
            }

            return resultList.toArray(new IContentProposal[resultList.size()]);
        }
    };

    ContentProposalAdapter adapter = new ContentProposalAdapter(textField, new TextContentAdapter(), cp, stroke,
            null);
    // set the acceptance style to always replace the complete content
    adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
}

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

License:Open Source License

@Override
protected Control createDialogArea(Composite parent) {
    Composite main = new Composite(parent, SWT.NONE);
    GridDataFactory.fillDefaults().grab(true, true).applyTo(main);
    main.setLayout(new GridLayout(2, false));

    URIish uriToCheck;// w  w  w . j  a v  a 2  s . c om
    if (pushMode) {
        if (config.getPushURIs().isEmpty())
            uriToCheck = config.getURIs().get(0);
        else
            uriToCheck = config.getPushURIs().get(0);
    } else
        uriToCheck = config.getURIs().get(0);

    final RefContentAssistProvider assistProvider = new RefContentAssistProvider(repo, uriToCheck, getShell());

    // source
    Label sourceLabel = new Label(main, SWT.NONE);
    if (pushMode)
        sourceLabel.setText(UIText.RefSpecDialog_SourceBranchPushLabel);
    else
        sourceLabel.setText(UIText.RefSpecDialog_SourceBranchFetchLabel);
    sourceText = new Text(main, SWT.BORDER);
    GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(sourceText);
    if (spec != null && spec.getSource() != null)
        sourceText.setText(spec.getSource());
    sourceText.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            if (sourceText.isFocusControl())
                if (autoSuggestDestination) {
                    String name = sourceText.getText();
                    if (name.startsWith(Constants.R_HEADS))
                        name = name.substring(Constants.R_HEADS.length());
                    else if (name.startsWith(Constants.R_TAGS))
                        name = name.substring(Constants.R_TAGS.length());
                    RefSpec sourceChanged = getSpec().setSource(sourceText.getText());
                    setSpec(sourceChanged.setDestination(Constants.R_REMOTES + config.getName() + '/' + name));
                } else
                    setSpec(getSpec().setSource(sourceText.getText()));
        }
    });
    // content assist for source
    UIUtils.addRefContentProposalToText(sourceText, repo, new IRefListProvider() {
        public List<Ref> getRefList() {
            return assistProvider.getRefsForContentAssist(true, pushMode);
        }
    });

    // suggest remote tracking branch
    if (!pushMode) {
        final Button autoSuggest = new Button(main, SWT.CHECK);
        GridDataFactory.fillDefaults().span(2, 1).applyTo(autoSuggest);
        autoSuggest.setText(UIText.RefSpecDialog_AutoSuggestCheckbox);
        autoSuggest.setSelection(true);
        autoSuggest.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                autoSuggestDestination = autoSuggest.getSelection();
            }
        });
    }

    // destination
    Label destinationLabel = new Label(main, SWT.NONE);
    if (pushMode)
        destinationLabel.setText(UIText.RefSpecDialog_DestinationPushLabel);
    else
        destinationLabel.setText(UIText.RefSpecDialog_DestinationFetchLabel);
    destinationText = new Text(main, SWT.BORDER);
    GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(destinationText);
    if (spec != null && spec.getDestination() != null)
        destinationText.setText(spec.getDestination());
    destinationText.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            if (destinationText.isFocusControl())
                setSpec(getSpec().setDestination(destinationText.getText()));
        }
    });
    // content assist for destination
    UIUtils.addRefContentProposalToText(destinationText, repo, new IRefListProvider() {
        public List<Ref> getRefList() {
            return assistProvider.getRefsForContentAssist(false, pushMode);
        }
    });

    // force update
    forceButton = new Button(main, SWT.CHECK);
    forceButton.setText(UIText.RefSpecDialog_ForceUpdateCheckbox);
    GridDataFactory.fillDefaults().span(2, 1).applyTo(forceButton);
    if (spec != null)
        forceButton.setSelection(spec.isForceUpdate());
    forceButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (getSpec().isForceUpdate() == forceButton.getSelection())
                return;
            setSpec(getSpec().setForceUpdate(forceButton.getSelection()));
        }

    });

    // RefSpec as String
    Label stringLabel = new Label(main, SWT.NONE);
    stringLabel.setText(UIText.RefSpecDialog_SpecificationLabel);
    specString = new Text(main, SWT.BORDER);
    GridDataFactory.fillDefaults().span(2, 1).grab(true, false).applyTo(specString);
    if (spec != null)
        specString.setText(spec.toString());
    specString.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            if (!specString.isFocusControl() || getSpec().toString().equals(specString.getText()))
                return;
            setSpec(new RefSpec(specString.getText()));
        }
    });

    applyDialogFont(main);
    return main;
}

From source file:org.eclipse.egit.ui.internal.repository.CreateBranchPage.java

License:Open Source License

public void createControl(Composite parent) {
    Composite main = new Composite(parent, SWT.NONE);
    main.setLayout(new GridLayout(3, false));

    Label sourceLabel = new Label(main, SWT.NONE);
    if (this.myBaseCommit != null) {
        sourceLabel.setText(UIText.CreateBranchPage_SourceCommitLabel);
        sourceLabel.setToolTipText(UIText.CreateBranchPage_SourceCommitTooltip);

    } else {//from  w  ww  . j a va2  s . com
        sourceLabel.setText(UIText.CreateBranchPage_SourceBranchLabel);
        sourceLabel.setToolTipText(UIText.CreateBranchPage_SourceBranchTooltip);
    }
    this.branchCombo = new Combo(main, SWT.READ_ONLY | SWT.DROP_DOWN);

    GridDataFactory.fillDefaults().span(2, 1).grab(true, false).applyTo(this.branchCombo);

    if (this.myBaseCommit != null) {
        this.branchCombo.add(myBaseCommit.name());
        this.branchCombo.setText(myBaseCommit.name());
        this.branchCombo.setEnabled(false);
    } else {
        try {
            for (Entry<String, Ref> ref : myRepository.getRefDatabase().getRefs(Constants.R_HEADS).entrySet()) {
                if (!ref.getValue().isSymbolic())
                    this.branchCombo.add(ref.getValue().getName());
            }
            for (Entry<String, Ref> ref : myRepository.getRefDatabase().getRefs(Constants.R_REMOTES)
                    .entrySet()) {
                if (!ref.getValue().isSymbolic())
                    this.branchCombo.add(ref.getValue().getName());
            }
            for (Entry<String, Ref> ref : myRepository.getRefDatabase().getRefs(Constants.R_TAGS).entrySet()) {
                if (!ref.getValue().isSymbolic())
                    this.branchCombo.add(ref.getValue().getName());
            }

        } catch (IOException e1) {
            // ignore here
        }

        this.branchCombo.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                checkPage();
            }
        });
        // select the current branch in the drop down
        if (myBaseRef != null) {
            this.branchCombo.setText(myBaseRef);
        }
    }

    Label nameLabel = new Label(main, SWT.NONE);
    nameLabel.setText(UIText.CreateBranchPage_BranchNameLabel);

    // we visualize the prefix here
    Text prefix = new Text(main, SWT.NONE);
    prefix.setText(Constants.R_HEADS);
    prefix.setEnabled(false);

    nameText = new Text(main, SWT.BORDER);
    // enable testing with SWTBot
    nameText.setData("org.eclipse.swtbot.widget.key", "BranchName"); //$NON-NLS-1$ //$NON-NLS-2$
    GridDataFactory.fillDefaults().grab(true, false).applyTo(nameText);

    boolean isBare = myRepository.isBare();
    checkout = new Button(main, SWT.CHECK);
    checkout.setText(UIText.CreateBranchPage_CheckoutButton);
    // most of the time, we probably will check this out
    // unless we have a bare repository which doesn't allow
    // check out at all
    checkout.setSelection(!isBare);
    checkout.setEnabled(!isBare);
    checkout.setVisible(!isBare);
    GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(checkout);
    checkout.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            checkPage();
        }
    });

    Dialog.applyDialogFont(main);
    setControl(main);
    nameText.setFocus();
    if (myBaseRef != null
            && (myBaseRef.startsWith(Constants.R_REMOTES) || myBaseRef.startsWith(Constants.R_TAGS))) {
        // additional convenience: the last part of the name is suggested
        // as name for the local branch
        nameText.setText(myBaseRef.substring(myBaseRef.lastIndexOf('/') + 1));
        checkPage();
    } else {
        // in any case, we will have to enter the name
        setPageComplete(false);
    }
    // add the listener just now to avoid unneeded checkPage()
    nameText.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            checkPage();
        }
    });
}

From source file:org.eclipse.egit.ui.internal.repository.RepositoriesViewContentProvider.java

License:Open Source License

public Object[] getChildren(Object parentElement) {

    RepositoryTreeNode node = (RepositoryTreeNode) parentElement;
    Repository repo = node.getRepository();

    switch (node.getType()) {

    case BRANCHES: {
        List<RepositoryTreeNode> nodes = new ArrayList<RepositoryTreeNode>();
        nodes.add(new LocalNode(node, repo));
        nodes.add(new RemoteTrackingNode(node, repo));
        return nodes.toArray();
    }//w w  w  . j ava2 s .co  m

    case LOCAL: {
        if (branchHierarchyMode) {
            BranchHierarchyNode hierNode = new BranchHierarchyNode(node, repo, new Path(Constants.R_HEADS));
            List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>();
            try {
                for (IPath path : hierNode.getChildPaths()) {
                    children.add(new BranchHierarchyNode(node, node.getRepository(), path));
                }
                for (Ref ref : hierNode.getChildRefs()) {
                    children.add(new RefNode(node, node.getRepository(), ref));
                }
            } catch (IOException e) {
                return handleException(e, node);
            }
            return children.toArray();
        } else {
            List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>();
            try {
                for (Entry<String, Ref> refEntry : repo.getRefDatabase().getRefs(Constants.R_HEADS)
                        .entrySet()) {
                    if (!refEntry.getValue().isSymbolic())
                        refs.add(new RefNode(node, repo, refEntry.getValue()));
                }
            } catch (IOException e) {
                return handleException(e, node);
            }
            return refs.toArray();
        }
    }

    case REMOTETRACKING: {
        if (branchHierarchyMode) {
            BranchHierarchyNode hierNode = new BranchHierarchyNode(node, repo, new Path(Constants.R_REMOTES));
            List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>();
            try {
                for (IPath path : hierNode.getChildPaths()) {
                    children.add(new BranchHierarchyNode(node, node.getRepository(), path));
                }
                for (Ref ref : hierNode.getChildRefs()) {
                    children.add(new RefNode(node, node.getRepository(), ref));
                }
            } catch (IOException e) {
                return handleException(e, node);
            }
            return children.toArray();
        } else {
            List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>();
            try {
                for (Entry<String, Ref> refEntry : repo.getRefDatabase().getRefs(Constants.R_REMOTES)
                        .entrySet()) {
                    if (!refEntry.getValue().isSymbolic())
                        refs.add(new RefNode(node, repo, refEntry.getValue()));
                }
            } catch (IOException e) {
                return handleException(e, node);
            }

            return refs.toArray();
        }
    }

    case BRANCHHIERARCHY: {
        BranchHierarchyNode hierNode = (BranchHierarchyNode) node;
        List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>();
        try {
            for (IPath path : hierNode.getChildPaths()) {
                children.add(new BranchHierarchyNode(node, node.getRepository(), path));
            }
            for (Ref ref : hierNode.getChildRefs()) {
                children.add(new RefNode(node, node.getRepository(), ref));
            }
        } catch (IOException e) {
            return handleException(e, node);
        }
        return children.toArray();
    }

    case TAGS: {
        List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>();

        try {
            for (Entry<String, Ref> refEntry : repo.getRefDatabase().getRefs(Constants.R_TAGS).entrySet()) {
                refs.add(new TagNode(node, repo, refEntry.getValue()));
            }
        } catch (IOException e) {
            return handleException(e, node);
        }

        return refs.toArray();
    }

    case ADDITIONALREFS: {
        List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>();
        try {
            for (Entry<String, Ref> refEntry : repo.getRefDatabase().getRefs(RefDatabase.ALL).entrySet()) {
                String name = refEntry.getKey();
                if (!(name.startsWith(Constants.R_HEADS) || name.startsWith(Constants.R_TAGS)
                        || name.startsWith(Constants.R_REMOTES)))
                    refs.add(new AdditionalRefNode(node, repo, refEntry.getValue()));
            }
            for (Ref r : repo.getRefDatabase().getAdditionalRefs())
                refs.add(new AdditionalRefNode(node, repo, r));
        } catch (IOException e) {
            return handleException(e, node);
        }
        return refs.toArray();
    }

    case REMOTES: {
        List<RepositoryTreeNode<String>> remotes = new ArrayList<RepositoryTreeNode<String>>();

        Repository rep = node.getRepository();

        Set<String> configNames = rep.getConfig().getSubsections(RepositoriesView.REMOTE);

        for (String configName : configNames) {
            remotes.add(new RemoteNode(node, repo, configName));
        }

        return remotes.toArray();
    }

    case REPO: {

        List<RepositoryTreeNode<? extends Object>> nodeList = new ArrayList<RepositoryTreeNode<? extends Object>>();

        nodeList.add(new BranchesNode(node, repo));
        nodeList.add(new TagsNode(node, repo));
        nodeList.add(new AdditionalRefsNode(node, repo));
        nodeList.add(new WorkingDirNode(node, repo));
        nodeList.add(new RemotesNode(node, repo));

        return nodeList.toArray();
    }

    case WORKINGDIR: {
        List<RepositoryTreeNode<File>> children = new ArrayList<RepositoryTreeNode<File>>();

        if (node.getRepository().isBare())
            return children.toArray();
        File workingDir = repo.getWorkTree();
        if (workingDir == null || !workingDir.exists())
            return children.toArray();

        File[] childFiles = workingDir.listFiles();
        Arrays.sort(childFiles, new Comparator<File>() {
            public int compare(File o1, File o2) {
                if (o1.isDirectory()) {
                    if (o2.isDirectory()) {
                        return o1.compareTo(o2);
                    }
                    return -1;
                } else if (o2.isDirectory()) {
                    return 1;
                }
                return o1.compareTo(o2);
            }
        });
        for (File file : childFiles) {
            if (file.isDirectory()) {
                children.add(new FolderNode(node, repo, file));
            } else {
                children.add(new FileNode(node, repo, file));
            }
        }

        return children.toArray();
    }

    case FOLDER: {
        List<RepositoryTreeNode<File>> children = new ArrayList<RepositoryTreeNode<File>>();

        File parent = ((File) node.getObject());

        File[] childFiles = parent.listFiles();
        Arrays.sort(childFiles, new Comparator<File>() {
            public int compare(File o1, File o2) {
                if (o1.isDirectory()) {
                    if (o2.isDirectory()) {
                        return o1.compareTo(o2);
                    }
                    return -1;
                } else if (o2.isDirectory()) {
                    return 1;
                }
                return o1.compareTo(o2);
            }
        });
        for (File file : childFiles) {
            if (file.isDirectory()) {
                children.add(new FolderNode(node, repo, file));
            } else {
                children.add(new FileNode(node, repo, file));
            }
        }

        return children.toArray();
    }

    case REMOTE: {

        List<RepositoryTreeNode<String>> children = new ArrayList<RepositoryTreeNode<String>>();

        String remoteName = (String) node.getObject();
        RemoteConfig rc;
        try {
            rc = new RemoteConfig(node.getRepository().getConfig(), remoteName);
        } catch (URISyntaxException e) {
            return handleException(e, node);
        }

        if (!rc.getURIs().isEmpty())
            children.add(new FetchNode(node, node.getRepository(), rc.getURIs().get(0).toPrivateString()));

        int uriCount = rc.getPushURIs().size();
        if (uriCount == 0 && !rc.getURIs().isEmpty())
            uriCount++;

        // show push if either a fetch or push URI is specified and
        // at least one push specification
        if (uriCount > 0 && !rc.getPushRefSpecs().isEmpty()) {
            URIish firstUri;
            if (!rc.getPushURIs().isEmpty())
                firstUri = rc.getPushURIs().get(0);
            else
                firstUri = rc.getURIs().get(0);

            if (uriCount == 1)
                children.add(new PushNode(node, node.getRepository(), firstUri.toPrivateString()));
            else
                children.add(new PushNode(node, node.getRepository(), firstUri.toPrivateString() + "...")); //$NON-NLS-1$
        }
        return children.toArray();

    }

    case FILE:
        // fall through
    case REF:
        // fall through
    case PUSH:
        // fall through
    case TAG:
        // fall through
    case FETCH:
        // fall through
    case ERROR:
        // fall through
    case ADDITIONALREF:
        return null;

    }

    return null;

}

From source file:org.eclipse.egit.ui.internal.repository.RepositoriesViewLabelProvider.java

License:Open Source License

private Image decorateImage(final Image image, Object element) {

    RepositoryTreeNode node = (RepositoryTreeNode) element;
    switch (node.getType()) {

    case TAG:// w w w  .ja v  a 2 s. c  o m
        // fall through
    case ADDITIONALREF:
        // fall through
    case REF:
        // if the branch or tag is checked out,
        // we want to decorate the corresponding
        // node with a little check indicator
        String refName = ((Ref) node.getObject()).getName();
        Ref leaf = ((Ref) node.getObject()).getLeaf();

        String branchName;
        String compareString;

        try {
            branchName = node.getRepository().getFullBranch();
            if (branchName == null)
                return image;
            if (refName.startsWith(Constants.R_HEADS)) {
                // local branch: HEAD would be on the branch
                compareString = refName;
            } else if (refName.startsWith(Constants.R_TAGS)) {
                // tag: HEAD would be on the commit id to which the tag is
                // pointing
                ObjectId id = node.getRepository().resolve(refName);
                if (id == null)
                    return image;
                RevWalk rw = new RevWalk(node.getRepository());
                RevTag tag = rw.parseTag(id);
                compareString = tag.getObject().name();

            } else if (refName.startsWith(Constants.R_REMOTES)) {
                // remote branch: HEAD would be on the commit id to which
                // the branch is pointing
                ObjectId id = node.getRepository().resolve(refName);
                if (id == null)
                    return image;
                RevWalk rw = new RevWalk(node.getRepository());
                RevCommit commit = rw.parseCommit(id);
                compareString = commit.getId().name();
            } else if (refName.equals(Constants.HEAD))
                return getDecoratedImage(image);
            else {
                String leafname = leaf.getName();
                if (leafname.startsWith(Constants.R_REFS)
                        && leafname.equals(node.getRepository().getFullBranch()))
                    return getDecoratedImage(image);
                else if (leaf.getObjectId().equals(node.getRepository().resolve(Constants.HEAD)))
                    return getDecoratedImage(image);
                // some other symbolic reference
                return image;
            }
        } catch (IOException e1) {
            return image;
        }

        if (compareString.equals(branchName)) {
            return getDecoratedImage(image);
        }

        return image;

    default:
        return image;
    }
}

From source file:org.eclipse.egit.ui.internal.repository.SelectResetTypePage.java

License:Open Source License

private Image getIcon(final String ref) {
    if (ref.startsWith(Constants.R_TAGS))
        return UIIcons.TAG.createImage();
    else if (ref.startsWith(Constants.R_HEADS) || ref.startsWith(Constants.R_REMOTES))
        return UIIcons.BRANCH.createImage();
    else/*from w w w  . jav  a2s.  c o m*/
        return UIIcons.CHANGESET.createImage();
}

From source file:org.eclipse.egit.ui.internal.repository.tree.command.RenameBranchCommand.java

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {
    final List<RefNode> nodes = getSelectedNodes(event);
    RefNode refNode = nodes.get(0);//w w w  . j  a va  2s . c  o m

    Shell shell = getShell(event);
    String oldName = refNode.getObject().getName();
    String prefix;
    if (oldName.startsWith(Constants.R_HEADS))
        prefix = Constants.R_HEADS;
    else if (oldName.startsWith(Constants.R_REMOTES))
        prefix = Constants.R_REMOTES;
    else
        throw new ExecutionException(NLS.bind(UIText.RenameBranchCommand_WrongNameMessage, oldName));
    Repository db = refNode.getRepository();
    IInputValidator inputValidator = ValidationUtils.getRefNameInputValidator(db, prefix, true);
    String defaultValue = Repository.shortenRefName(oldName);
    InputDialog newNameDialog = new InputDialog(shell, UIText.RepositoriesView_RenameBranchTitle,
            NLS.bind(UIText.RepositoriesView_RenameBranchMessage, defaultValue), defaultValue, inputValidator);
    if (newNameDialog.open() == Window.OK) {
        try {
            String newName = newNameDialog.getValue();
            new RenameBranchOperation(db, refNode.getObject(), newName).execute(null);
        } catch (CoreException e) {
            Activator.handleError(UIText.RepositoriesView_RenameBranchFailure, e, true);
        }
    }
    return null;
}

From source file:org.eclipse.egit.ui.internal.search.CommitSearchQuery.java

License:Open Source License

private void walkRepository(Repository repository, Pattern pattern, IProgressMonitor monitor)
        throws IOException {
    RevWalk walk = new RevWalk(repository);
    try {//  ww w. j  a va2 s .c o m
        walk.setRetainBody(true);
        List<RevCommit> commits = new LinkedList<RevCommit>();
        if (this.settings.isAllBranches()) {
            for (Ref ref : repository.getRefDatabase().getRefs(Constants.R_HEADS).values())
                if (!ref.isSymbolic())
                    commits.add(walk.parseCommit(ref.getObjectId()));
            for (Ref ref : repository.getRefDatabase().getRefs(Constants.R_REMOTES).values())
                if (!ref.isSymbolic())
                    commits.add(walk.parseCommit(ref.getObjectId()));
        } else {
            ObjectId headCommit = repository.resolve(Constants.HEAD);
            if (headCommit != null)
                commits.add(walk.parseCommit(headCommit));
        }

        if (!commits.isEmpty()) {
            walk.markStart(commits);
            for (RevCommit commit : walk) {
                if (monitor.isCanceled())
                    throw new OperationCanceledException();
                for (SearchMatcher matcher : this.matchers)
                    if (matcher.matches(pattern, commit)) {
                        result.addResult(new RepositoryCommit(repository, commit));
                        break;
                    }
            }
        }
    } finally {
        walk.dispose();
    }
}

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  av a 2 s  . c om
 * 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;
    }
}