Example usage for org.eclipse.jgit.lib Repository getRefDatabase

List of usage examples for org.eclipse.jgit.lib Repository getRefDatabase

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository getRefDatabase.

Prototype

@NonNull
public abstract RefDatabase getRefDatabase();

Source Link

Document

Get the reference database which stores the reference namespace.

Usage

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.CollectChangesTest.java

License:Apache License

@TestFor(issues = { "TW-36080", "TW-35700" })
@Test(dataProvider = "separateProcess,newConnectionForPrune")
public void branch_turned_into_dir(boolean fetchInSeparateProcess, boolean newConnectionForPrune)
        throws Exception {
    myConfig.setSeparateProcessForFetch(fetchInSeparateProcess).setNewConnectionForPrune(newConnectionForPrune);
    VcsRoot root = vcsRoot().withFetchUrl(myRepo).withBranch("master").build();
    RepositoryStateData s1 = createVersionState("refs/heads/master",
            map("refs/heads/master", "f3f826ce85d6dad25156b2d7550cedeb1a422f4c", "refs/heads/patch-tests",
                    "a894d7d58ffde625019a9ecf8267f5f1d1e5c341"));
    RepositoryStateData s2 = createVersionState("refs/heads/master",
            map("refs/heads/master", "3b9fbfbb43e7edfad018b482e15e7f93cca4e69f", "refs/heads/patch-tests",
                    "a894d7d58ffde625019a9ecf8267f5f1d1e5c341"));

    git().getCollectChangesPolicy().collectChanges(root, s1, s2, CheckoutRules.DEFAULT);

    //rename refs/heads/patch-tests to refs/heads/patch-tests/a and make it point to commit not yet fetched by TC, so the fetch is required
    Repository r = new RepositoryBuilder().setGitDir(myRepo).build();
    r.getRefDatabase().newRename("refs/heads/patch-tests", "refs/heads/patch-tests/a").rename();
    RefUpdate refUpdate = r.updateRef("refs/heads/patch-tests/a");
    refUpdate.setForceUpdate(true);//from  w  w  w .java2  s .c  om
    refUpdate.setNewObjectId(ObjectId.fromString("39679cc440c83671fbf6ad8083d92517f9602300"));
    refUpdate.update();

    RepositoryStateData s3 = createVersionState("refs/heads/master",
            map("refs/heads/master", "3b9fbfbb43e7edfad018b482e15e7f93cca4e69f", "refs/heads/patch-tests/a",
                    "39679cc440c83671fbf6ad8083d92517f9602300"));
    git().getCollectChangesPolicy().collectChanges(root, s2, s3, CheckoutRules.DEFAULT);
}

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

License:Open Source License

/**
 * Tries to map a commit to a symbolic reference.
 * <p>/*from ww  w .  j  a  v a2  s. c  o  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.internal.mylyn.ui.tasks.RepositoryAndBranchSelectionDialog.java

License:Open Source License

@Override
protected Control createDialogArea(Composite parent) {
    Composite composite = (Composite) super.createDialogArea(parent);
    composite.setLayout(new GridLayout(3, false));

    Label repositoryLabel = new Label(composite, SWT.NONE);
    repositoryLabel.setText("Select a repository:");
    GridDataFactory.fillDefaults().span(3, 1).grab(true, false).applyTo(repositoryLabel);

    repositoryTableViewer = new TableViewer(composite, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.MULTI);
    repositoryTableViewer.setContentProvider(new RepositoriesViewContentProvider());
    GridDataFactory.fillDefaults().span(3, 1).grab(true, true).applyTo(repositoryTableViewer.getTable());
    repositoryTableViewer.setLabelProvider(new RepositoriesViewLabelProvider());
    repositoryTableViewer.setInput(util.getConfiguredRepositories());

    // TODO use a ComboViewer
    branchCombo = new Combo(composite, SWT.DROP_DOWN);
    branchCombo.setLayoutData(GridDataFactory.fillDefaults().span(3, 1).grab(true, false).create());
    branchCombo.setEnabled(false);//from  w w w. j a  v a 2  s  .  c  om

    repositoryTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {

        public void selectionChanged(SelectionChangedEvent event) {
            try {
                branchCombo.setEnabled(true);
                branchCombo.removeAll();
                branchCombo.setText(initialBranch);
                repos = getRepositories();

                for (Repository repository : repos) {
                    if (repository != null) {
                        for (Entry<String, Ref> refEntry : repository.getRefDatabase()
                                .getRefs(Constants.R_HEADS).entrySet()) {
                            if (!refEntry.getValue().isSymbolic())

                                branchesForCombo.put(refEntry.getValue().getName(),
                                        refEntry.getValue().getName());

                        }
                    }
                }

                for (String b : branchesForCombo.keySet()) {
                    branchCombo.add(b);
                }
            } catch (IOException e) {
                // do nothing atm
            }
        }

    });

    // TODO how do we handle multiple repos?
    // need to figure out things..
    branchCombo.setText(initialBranch);
    branch = initialBranch;

    branchCombo.addFocusListener(new FocusListener() {

        public void focusLost(FocusEvent e) {
            branch = branchCombo.getText();
        }

        public void focusGained(FocusEvent e) {
            // Nothing to do            
        }
    });

    setTitle("Select Branch");
    setMessage("Select a repository and corresponding branch to checkout.");
    setTitleImage(UIIcons.WIZBAN_CONNECT_REPO.createImage());
    applyDialogFont(composite);
    return composite;
}

From source file:org.eclipse.egit.internal.mylyn.ui.tasks.TaskActivationListener.java

License:Open Source License

public void preTaskActivated(ITask task) {
    // TODO if there's a context, should we browse it to deduce which repo to choose?
    String branch = task.getTaskKey() != null ? task.getTaskKey() : task.getTaskId();
    String branchFullName = Constants.R_HEADS + branch;
    RepositoryAndBranchSelectionDialog dialog = new RepositoryAndBranchSelectionDialog(
            PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), branchFullName);
    if (dialog.open() == Window.OK) {
        try {//from   w w w. j a  va2 s  . c o m
            List<Repository> repos = dialog.getSelectedRepositories();

            for (Repository repo : repos) {
                // Create new branch, if branch with proposed name doesn't exist, otherwise checkout
                if (repo.getRefDatabase().getRef(branch) == null) {
                    CreateLocalBranchOperation createOperation = new CreateLocalBranchOperation(repo, branch,
                            repo.getRef(Constants.R_HEADS + Constants.MASTER));
                    createOperation.execute(null);
                }

                BranchOperation operation = new BranchOperation(repo, dialog.getBranch());
                operation.execute(null);
            }
        } catch (CoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:org.eclipse.egit.ui.internal.actions.SwitchToMenu.java

License:Open Source License

private void createDynamicMenu(Menu menu, final Repository repository) {
    MenuItem newBranch = new MenuItem(menu, SWT.PUSH);
    newBranch.setText(UIText.SwitchToMenu_NewBranchMenuLabel);
    newBranch.setImage(newBranchImage);/*from   ww  w  . j  a  v a2s.com*/
    newBranch.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            BranchOperationUI.create(repository).start();
        }
    });
    new MenuItem(menu, SWT.SEPARATOR);
    try {
        String currentBranch = repository.getFullBranch();
        Map<String, Ref> localBranches = repository.getRefDatabase().getRefs(Constants.R_HEADS);
        TreeMap<String, Ref> sortedRefs = new TreeMap<String, Ref>();

        // Add the MAX_NUM_MENU_ENTRIES most recently used branches first
        List<ReflogEntry> reflogEntries = new ReflogReader(repository, Constants.HEAD).getReverseEntries();
        for (ReflogEntry entry : reflogEntries) {
            CheckoutEntry checkout = entry.parseCheckout();
            if (checkout != null) {
                Ref ref = localBranches.get(checkout.getFromBranch());
                if (ref != null)
                    if (sortedRefs.size() < MAX_NUM_MENU_ENTRIES)
                        sortedRefs.put(checkout.getFromBranch(), ref);
                ref = localBranches.get(checkout.getToBranch());
                if (ref != null)
                    if (sortedRefs.size() < MAX_NUM_MENU_ENTRIES)
                        sortedRefs.put(checkout.getToBranch(), ref);
            }
        }

        // Add the recently used branches to the menu, in alphabetical order
        int itemCount = 0;
        for (final Entry<String, Ref> entry : sortedRefs.entrySet()) {
            itemCount++;
            final String shortName = entry.getKey();
            final String fullName = entry.getValue().getName();
            createMenuItem(menu, repository, currentBranch, fullName, shortName);
            // Do not duplicate branch names
            localBranches.remove(shortName);
        }

        if (itemCount < MAX_NUM_MENU_ENTRIES) {
            // A separator between recently used branches and local branches is
            // nice but only if we have both recently used branches and other
            // local branches
            if (itemCount > 0 && localBranches.size() > 0)
                new MenuItem(menu, SWT.SEPARATOR);

            // Now add more other branches if we have only a few branch switches
            // Sort the remaining local branches
            sortedRefs.clear();
            sortedRefs.putAll(localBranches);
            for (final Entry<String, Ref> entry : sortedRefs.entrySet()) {
                itemCount++;
                // protect ourselves against a huge sub-menu
                if (itemCount > MAX_NUM_MENU_ENTRIES)
                    break;
                final String fullName = entry.getValue().getName();
                final String shortName = entry.getKey();
                createMenuItem(menu, repository, currentBranch, fullName, shortName);
            }
        }
        if (itemCount > 0)
            new MenuItem(menu, SWT.SEPARATOR);
        MenuItem others = new MenuItem(menu, SWT.PUSH);
        others.setText(UIText.SwitchToMenu_OtherMenuLabel);
        others.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                BranchOperationUI.checkout(repository).start();
            }
        });
    } catch (IOException e) {
        Activator.handleError(e.getMessage(), e, true);
    }
}

From source file:org.eclipse.egit.ui.internal.actions.SynchronizeWithAction.java

License:Open Source License

private List<SyncRepoEntity> createSyncRepoEntitys(Repository repo) throws InvocationTargetException {
    RefDatabase refDatabase = repo.getRefDatabase();
    List<RemoteConfig> remoteConfigs = getRemoteConfigs(repo);
    List<SyncRepoEntity> syncRepoEntitys = new ArrayList<SyncRepoEntity>();

    syncRepoEntitys.add(getLocalSyncRepo(repo));
    for (RemoteConfig rc : remoteConfigs)
        syncRepoEntitys.add(getRemoteSyncRepo(refDatabase, rc));

    return syncRepoEntitys;
}

From source file:org.eclipse.egit.ui.internal.actions.SynchronizeWithActionHandler.java

License:Open Source License

private List<SyncRepoEntity> createSyncRepoEntitys(Repository repo) throws URISyntaxException, IOException {
    RefDatabase refDatabase = repo.getRefDatabase();
    List<RemoteConfig> remoteConfigs = getRemoteConfigs(repo);
    List<SyncRepoEntity> syncRepoEntitys = new ArrayList<SyncRepoEntity>();

    syncRepoEntitys.add(getLocalSyncRepo(repo));
    for (RemoteConfig rc : remoteConfigs)
        syncRepoEntitys.add(getRemoteSyncRepo(refDatabase, rc));

    return syncRepoEntitys;
}

From source file:org.eclipse.egit.ui.internal.actions.SynchronizeWithMenu.java

License:Open Source License

@Override
public void fill(final Menu menu, int index) {
    if (srv == null)
        return;/*from w  w w. java 2 s. co m*/
    final IResource selectedResource = getSelection();
    if (selectedResource == null || selectedResource.isLinked(IResource.CHECK_ANCESTORS))
        return;

    RepositoryMapping mapping = RepositoryMapping.getMapping(selectedResource.getProject());
    if (mapping == null)
        return;

    final Repository repo = mapping.getRepository();
    if (repo == null)
        return;

    List<Ref> refs = new LinkedList<Ref>();
    RefDatabase refDatabase = repo.getRefDatabase();
    try {
        refs.addAll(refDatabase.getAdditionalRefs());
    } catch (IOException e) {
        // do nothing
    }
    try {
        refs.addAll(refDatabase.getRefs(RefDatabase.ALL).values());
    } catch (IOException e) {
        // do nothing
    }
    Collections.sort(refs, CommonUtils.REF_ASCENDING_COMPARATOR);
    String currentBranch;
    try {
        currentBranch = repo.getFullBranch();
    } catch (IOException e) {
        currentBranch = ""; //$NON-NLS-1$
    }

    int count = 0;
    String oldName = null;
    int refsLength = R_REFS.length();
    int tagsLength = R_TAGS.substring(refsLength).length();
    for (Ref ref : refs) {
        final String name = ref.getName();
        if (name.equals(Constants.HEAD) || name.equals(currentBranch) || excludeTag(ref, repo))
            continue;
        if (name.startsWith(R_REFS) && oldName != null
                && !oldName.regionMatches(refsLength, name, refsLength, tagsLength))
            new MenuItem(menu, SWT.SEPARATOR);

        MenuItem item = new MenuItem(menu, SWT.PUSH);
        item.setText(name);
        if (name.startsWith(Constants.R_TAGS))
            item.setImage(tagImage);
        else if (name.startsWith(Constants.R_HEADS) || name.startsWith(Constants.R_REMOTES))
            item.setImage(branchImage);

        item.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent event) {
                GitSynchronizeData data;
                try {
                    data = new GitSynchronizeData(repo, HEAD, name, true);
                    if (!(selectedResource instanceof IProject)) {
                        HashSet<IContainer> containers = new HashSet<IContainer>();
                        containers.add((IContainer) selectedResource);
                        data.setIncludedPaths(containers);
                    }

                    GitModelSynchronize.launch(data, new IResource[] { selectedResource });
                } catch (IOException e) {
                    Activator.logError(e.getMessage(), e);
                }
            }
        });

        if (++count == MAX_NUM_MENU_ENTRIES)
            break;
        oldName = name;
    }

    if (count > 1)
        new MenuItem(menu, SWT.SEPARATOR);

    MenuItem custom = new MenuItem(menu, SWT.PUSH);
    custom.setText(UIText.SynchronizeWithMenu_custom);
    custom.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            GitSynchronizeWizard gitWizard = new GitSynchronizeWizard();
            WizardDialog wizard = new WizardDialog(menu.getShell(), gitWizard);
            wizard.create();
            wizard.open();
        }
    });
}

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

License:Open Source License

private List<Ref> loadBranches() {
    Repository repository = getCommit().getRepository();
    RevCommit commit = getCommit().getRevCommit();
    RevWalk revWalk = new RevWalk(repository);
    try {//from   w  w  w  . j  a va 2 s . c o m
        Map<String, Ref> refsMap = new HashMap<String, Ref>();
        refsMap.putAll(repository.getRefDatabase().getRefs(Constants.R_HEADS));
        refsMap.putAll(repository.getRefDatabase().getRefs(Constants.R_REMOTES));
        return RevWalkUtils.findBranchesReachableFrom(commit, revWalk, refsMap.values());
    } catch (IOException e) {
        Activator.handleError(e.getMessage(), e, false);
        return Collections.emptyList();
    }
}

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

License:Open Source License

/**
 * Get notes for this commit./*from  w w w . ja  v a 2  s .  co  m*/
 *
 * @return non-null but possibly empty array of {@link RepositoryCommitNote}
 *         instances.
 */
public RepositoryCommitNote[] getNotes() {
    if (notes == null) {
        List<RepositoryCommitNote> noteList = new ArrayList<RepositoryCommitNote>();
        try {
            Repository repo = getRepository();
            Git git = Git.wrap(repo);
            RevCommit revCommit = getRevCommit();
            for (Ref ref : repo.getRefDatabase().getRefs(Constants.R_NOTES).values()) {
                Note note = git.notesShow().setNotesRef(ref.getName()).setObjectId(revCommit).call();
                if (note != null)
                    noteList.add(new RepositoryCommitNote(this, ref, note));
            }
            notes = noteList.toArray(new RepositoryCommitNote[noteList.size()]);
        } catch (Exception e) {
            Activator.logError("Error showing notes", e); //$NON-NLS-1$
            notes = new RepositoryCommitNote[0];
        }
    }
    return notes;
}