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

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

Introduction

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

Prototype

@Deprecated
@NonNull
public Map<String, Ref> getAllRefs() 

Source Link

Document

Get mutable map of all known refs, including symrefs like HEAD that may not point to any object yet.

Usage

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

License:Open Source License

private SyncRepoEntity getLocalSyncRepo(Repository repo) {
    Set<String> allRefs = repo.getAllRefs().keySet();
    SyncRepoEntity local = new SyncRepoEntity(UIText.SynchronizeWithAction_localRepoName);
    for (String ref : allRefs) {
        if (!ref.startsWith(Constants.R_REMOTES)) {
            String name = ref.substring(ref.lastIndexOf('/') + 1);
            local.addRef(new SyncRefEntity(name, ref));
        }//from w w  w  .j  ava  2  s . c  o  m
    }
    return local;
}

From source file:org.eclipse.egit.ui.internal.preferences.GitProjectPropertyPage.java

License:Open Source License

private void fillValues(Repository repository) throws IOException {
    gitDir.setText(repository.getDirectory().getAbsolutePath());
    branch.setText(repository.getBranch());
    workDir.setText(repository.getWorkTree().getAbsolutePath());

    state.setText(repository.getRepositoryState().getDescription());

    final ObjectId objectId = repository.resolve(repository.getFullBranch());
    if (objectId == null) {
        if (repository.getAllRefs().size() == 0)
            id.setText(UIText.GitProjectPropertyPage_ValueEmptyRepository);
        else//from w  w  w .  ja v  a 2 s  .  c  o m
            id.setText(UIText.GitProjectPropertyPage_ValueUnbornBranch);
    } else
        id.setText(objectId.name());
}

From source file:org.eclipse.egit.ui.wizards.clone.GitCloneWizardTest.java

License:Open Source License

@Test
public void alteringSomeParametersDuringClone() throws Exception {
    File destRepo = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile(), "test2");

    importWizard.openWizard();//ww  w  .  j  ava  2  s  . c  o m
    RepoPropertiesPage repoProperties = importWizard.openCloneWizard();
    RepoRemoteBranchesPage remoteBranches = repoProperties.nextToRemoteBranches(r.getUri());
    remoteBranches.deselectAllBranches();
    remoteBranches.assertErrorMessage("At least one branch must be selected.");
    remoteBranches.assertNextIsDisabled();

    remoteBranches.selectBranches(SampleTestRepository.FIX);
    remoteBranches.assertNextIsEnabled();

    WorkingCopyPage workingCopy = remoteBranches.nextToWorkingCopy();
    workingCopy.setDirectory(destRepo.toString());
    workingCopy.assertBranch(SampleTestRepository.FIX);
    workingCopy.setRemoteName("src");
    workingCopy.waitForCreate();

    // Some random sampling to see we got something. We do not test
    // the integrity of the repository here. Only a few basic properties
    // we'd expect from a clone made this way, that would possibly
    // not hold true given other parameters in the GUI.
    Repository repository = new FileRepository(new File(destRepo, Constants.DOT_GIT));
    assertNotNull(repository.resolve("src/" + SampleTestRepository.FIX));
    // we didn't clone that one
    assertNull(repository.resolve("src/master"));
    // and a local master initialized from origin/master (default!)
    assertEquals(repository.resolve("stable"), repository.resolve("src/stable"));
    // A well known tag
    assertNotNull(repository.resolve(Constants.R_TAGS + SampleTestRepository.v2_0_name).name());
    // lots of refs
    assertTrue(repository.getAllRefs().size() >= 4);
}

From source file:org.eclipse.egit.ui.wizards.clone.GitCloneWizardTestBase.java

License:Open Source License

protected void cloneRepo(File destRepo, RepoRemoteBranchesPage remoteBranches) throws Exception {
    remoteBranches.assertRemoteBranches(SampleTestRepository.FIX, Constants.MASTER);
    remoteBranches.selectBranches(SampleTestRepository.FIX, Constants.MASTER);

    WorkingCopyPage workingCopy = remoteBranches.nextToWorkingCopy();
    workingCopy.setDirectory(destRepo.toString());

    workingCopy.assertDirectory(destRepo.toString());
    workingCopy.assertBranch(Constants.MASTER);
    workingCopy.assertRemoteName(Constants.DEFAULT_REMOTE_NAME);
    workingCopy.waitForCreate();// ww  w  .j  ava 2 s.c  o m

    // Some random sampling to see we got something. We do not test
    // the integrity of the repository here. Only a few basic properties
    // we'd expect from a clone made this way, that would possibly
    // not hold true given other parameters in the GUI.
    Repository repository = new FileRepository(new File(destRepo, Constants.DOT_GIT));
    // we always have an origin/master
    assertNotNull(repository.resolve("origin/master"));
    // and a local master initialized from origin/master (default!)
    assertEquals(repository.resolve("master"), repository.resolve("origin/master"));
    // A well known tag
    assertNotNull(repository.resolve(Constants.R_TAGS + SampleTestRepository.v1_0_name).name());
    // lots of refs
    int refs = repository.getAllRefs().size();
    assertTrue(refs >= 4);
    // and a known file in the working dir
    assertTrue(new File(destRepo, SampleTestRepository.A_txt_name).exists());
    DirCacheEntry fileEntry = null;
    DirCache dc = repository.lockDirCache();
    fileEntry = dc.getEntry(SampleTestRepository.A_txt_name);
    dc.unlock();
    // check that we have the file in the index
    assertNotNull(fileEntry);
    // No project has been imported
    assertEquals(0, ResourcesPlugin.getWorkspace().getRoot().getProjects().length);
}

From source file:org.eclipse.oomph.setup.git.impl.GitCloneTaskImpl.java

License:Open Source License

public boolean isNeeded(final SetupTaskContext context) throws Exception {
    if (StringUtil.isEmpty(getRemoteURI())) {
        return false;
    }/*from ww  w  . j  av a2  s  .  c om*/

    // If the EGit UI is available, this will contain the list of repositories that have been added to the repositories view.
    Set<String> repositories = null;

    // Force start egit to make the clone appears in the repositories view and so projects are connected by the egit team provider.
    try {
        Class<?> egitUIActivatorClass = CommonPlugin.loadClass("org.eclipse.egit.ui",
                "org.eclipse.egit.ui.Activator");
        Object egitUIActivator = ReflectUtil.invokeMethod("getDefault", egitUIActivatorClass);
        repositoryUtil = ReflectUtil.invokeMethod("getRepositoryUtil", egitUIActivator);

        @SuppressWarnings("unchecked")
        List<String> configuredRepositories = (List<String>) ReflectUtil
                .invokeMethod("getConfiguredRepositories", repositoryUtil);
        repositories = new HashSet<String>(configuredRepositories);
    } catch (Throwable ex) {
        // Ignore.
    }

    String location = getLocation();

    workDir = new File(location);
    if (!workDir.isDirectory()) {
        return true;
    }

    workDirExisted = true;

    boolean needsToBeAdded = repositories != null
            && !repositories.contains(new File(workDir, ".git").toString());
    if (workDir.list().length > 1) {
        // Even though cloning isn't needed, return true if the repository needs to be added to the repositories view.
        bypassCloning = true;
        return needsToBeAdded;
    }

    context.log("Opening Git clone " + workDir);

    try {
        Git git = Git.open(workDir);
        if (!hasWorkTree(git) || !hasReflog(git)) {
            FileUtil.rename(workDir);
            workDirExisted = false;
            return true;
        }

        Repository repository = git.getRepository();
        String checkoutBranch = getCheckoutBranch();
        String remoteName = getRemoteName();
        String remoteURI = getRemoteURI();
        String pushURI = getPushURI();
        configureRepository(context, repository, checkoutBranch, remoteName, remoteURI, pushURI,
                getConfigSections());

        hasCheckout = repository.getAllRefs().containsKey("refs/heads/" + checkoutBranch);
        if (!hasCheckout) {
            cachedGit = git;
            cachedRepository = repository;
            return true;
        }

        // Even though cloning isn't needed, return true if the repository needs to be added to the repositories view.
        bypassCloning = true;
        return needsToBeAdded;
    } catch (Throwable ex) {
        if (!workDirExisted) {
            FileUtil.delete(workDir, new NullProgressMonitor() {
                @Override
                public boolean isCanceled() {
                    return context.isCanceled();
                }
            });
        }

        throw new Exception(ex);
    }
}

From source file:org.eclipse.recommenders.snipmatch.GitSnippetRepository.java

License:Open Source License

private boolean isUpdatePossible() throws IOException {
    if (RepositoryCache.FileKey.isGitRepository(gitFile, FS.DETECTED)) {
        Repository localRepo = new FileRepositoryBuilder().setGitDir(gitFile).build();
        for (Ref ref : localRepo.getAllRefs().values()) {
            if (ref.getObjectId() != null) {
                return true;
            }//from   ww w.  j a  va  2  s .co  m
        }
    }
    return false;
}

From source file:org.jboss.tools.tycho.sitegenerator.GenerateRepositoryFacadeMojo.java

License:Open Source License

private ModelNode createRevisionObject() throws IOException, FileNotFoundException {
    ModelNode res = new ModelNode();
    File repoRoot = findRepoRoot(this.project.getBasedir());
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository gitRepo = builder.setGitDir(new File(repoRoot, ".git")).readEnvironment() // scan environment GIT_* variables
            .findGitDir() // scan up the file system tree
            .build();/*from  w w  w .ja  va 2 s.c o m*/
    Ref head = gitRepo.getRef(Constants.HEAD);
    res.get("HEAD").set(head.getObjectId().getName());
    if (head.getTarget() != null && head.getTarget().getName() != null) {
        res.get("currentBranch").set(head.getTarget().getName());
    }
    ModelNode knownReferences = new ModelNode();
    for (Entry<String, Ref> entry : gitRepo.getAllRefs().entrySet()) {
        if (entry.getKey().startsWith(Constants.R_REMOTES)
                && entry.getValue().getObjectId().getName().equals(head.getObjectId().getName())) {
            ModelNode reference = new ModelNode();
            String remoteName = entry.getKey().substring(Constants.R_REMOTES.length());
            remoteName = remoteName.substring(0, remoteName.indexOf('/'));
            String remoteUrl = gitRepo.getConfig().getString("remote", remoteName, "url");
            String branchName = entry.getKey()
                    .substring(Constants.R_REMOTES.length() + 1 + remoteName.length());
            reference.get("name").set(remoteName);
            reference.get("url").set(remoteUrl);
            reference.get("ref").set(branchName);
            knownReferences.add(reference);
        }
    }
    res.get("knownReferences").set(knownReferences);
    return res;
}

From source file:org.jdamico.jgitbkp.components.ManagerComponent.java

License:Open Source License

public List<BundleStatus> generateBundles(List<RepoImpl> reposLst, Config config) throws JGitBackupException {

    List<BundleStatus> bundleStatusLst = new ArrayList<BundleStatus>();

    boolean backupStatus = false;
    StringBuffer backupMessage = new StringBuffer();

    for (int i = 0; i < reposLst.size(); i++) {
        String bundlePath = config.getBundlePath() + "/" + reposLst.get(i).getName() + ".bundle";

        File gitWorkDir = new File(reposLst.get(i).getClonedPath());
        Git git = null;// w w  w .j a v  a2 s.  c  om
        Repository localRepoGit = null;
        BundleWriter bundleWriter = null;
        ProgressMonitor pMonitor = null;
        OutputStream oStream = null;
        try {
            git = Git.open(gitWorkDir);
            git.pull();
            if (!Starter.silent)
                System.out.println("Updated data for [" + reposLst.get(i).getName() + "]");
            localRepoGit = git.getRepository();
            bundleWriter = new BundleWriter(localRepoGit);
            pMonitor = new TextProgressMonitor();
            oStream = new FileOutputStream(bundlePath);
            Map<String, Ref> allRefs = localRepoGit.getAllRefs();
            Collection<Ref> values = allRefs.values();
            Iterator<Ref> iter = values.iterator();
            while (iter.hasNext()) {
                try {
                    Ref element = iter.next();
                    bundleWriter.include(element);
                } catch (IllegalArgumentException e) {

                    if (!e.getMessage().equalsIgnoreCase("Invalid ref name: HEAD")) {
                        String err = reposLst.get(i).getName() + ": " + e.getMessage();
                        backupMessage.append(err);
                        LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), err);
                    }
                }

            }
            if (!Starter.silent)
                bundleWriter.writeBundle(pMonitor, oStream);
            else
                bundleWriter.writeBundle(null, oStream);

        } catch (IOException e) {
            String err = reposLst.get(i).getName() + ": " + e.getMessage();
            backupMessage.append(err);
            LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), err);
            throw new JGitBackupException(e);
        }

        File f = new File(bundlePath);
        if (f.exists() && f.length() > 100) {
            backupStatus = f.exists();
        } else
            backupStatus = false;

        bundleStatusLst.add(new BundleStatus(reposLst.get(i).getName(), backupStatus, backupMessage.toString(),
                Utils.getInstance().getCurrentDateTimeFormated(Constants.DATE_FORMAT), bundlePath));
        if (!Starter.silent)
            System.out.println("Bundle created: " + bundlePath + " - " + backupStatus);
    }

    return bundleStatusLst;
}

From source file:org.jdamico.jgitbkp.tests.JGitTester.java

License:Open Source License

@Test
public void test() throws IOException, GitAPIException {

    String user = "";
    String passwd = "";
    String hostPath = "/git";
    String backupRoot = "/tmp/test";
    String gitRoot = "/mnt";
    String bundlePath = "/tmp";
    boolean keepOld = false;

    List<org.jdamico.jgitbkp.entities.RepoImpl> repos = new ArrayList<org.jdamico.jgitbkp.entities.RepoImpl>();

    File fGitRoot = new File(gitRoot);
    String[] fRepos = fGitRoot.list();
    for (String itemRepo : fRepos) {
        File fItemRepo = new File(gitRoot + "/" + itemRepo);
        if (fItemRepo.isDirectory() && itemRepo.contains(".git") && !itemRepo.equals(".git")) {
            repos.add(new org.jdamico.jgitbkp.entities.RepoImpl(itemRepo, null, backupRoot + "/" + itemRepo));
        }/*from  w w w .ja  va2 s .  c om*/
    }

    for (int i = 0; i < repos.size(); i++) {

        File f = new File(repos.get(i).getClonedPath());

        if (f.mkdir()) {

            Git.cloneRepository().setCloneAllBranches(true)
                    .setURI("http://" + hostPath + "/" + repos.get(i).getName())
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, passwd))
                    .setDirectory(new File(repos.get(i).getClonedPath()))
                    .setProgressMonitor(new TextProgressMonitor()).call();

        }

        File gitWorkDir = new File(repos.get(i).getClonedPath());
        Git git = Git.open(gitWorkDir);
        git.pull();
        Repository localRepoGit = git.getRepository();
        BundleWriter bundleWriter = new BundleWriter(localRepoGit);
        ProgressMonitor pMonitor = new TextProgressMonitor();
        OutputStream oStream = new FileOutputStream(bundlePath + "/" + repos.get(i).getName() + ".bundle");

        Map<String, Ref> allRefs = localRepoGit.getAllRefs();
        Collection<Ref> values = allRefs.values();
        Iterator<Ref> iter = values.iterator();
        while (iter.hasNext()) {
            Ref element = iter.next();
            try {

                bundleWriter.include(element);
                System.out.println("Added: " + element.getName());
            } catch (Exception e) {
                // TODO: handle exception
            }

        }

        bundleWriter.writeBundle(pMonitor, oStream);

    }

}

From source file:org.webcat.core.git.http.InfoRefsRequestHandler.java

License:Open Source License

/**
 * Looks up the requested repository and appends its info/refs to the
 * response./*from  w  w w .  j  a  va2s.  co m*/
 *
 * @param request the request
 * @param response the response
 * @throws Exception if an error occurs
 */
public void handleRequest(WORequest request, WOResponse response) throws Exception {
    response.setHeader("text/plain", "Content-Type");

    NSMutableDataOutputStream outputStream = new NSMutableDataOutputStream();

    Repository repo = RepositoryRequestUtils.repositoryFromRequest(request);
    //RevWalk walk = new RevWalk(repo);

    //try
    //{
    //final RevFlag ADVERTISED = walk.newFlag("ADVERTISED");

    final OutputStreamWriter out = new OutputStreamWriter(outputStream, Constants.CHARSET);

    final RefAdvertiser adv = new RefAdvertiser() {
        protected void writeOne(CharSequence line) throws IOException {
            out.append(line.toString().replace(' ', '\t'));
        }

        protected void end() {
            // Do nothing.
        }
    };

    adv.init(repo);
    //adv.init(walk, ADVERTISED);
    adv.setDerefTags(true);

    Map<String, Ref> refs = repo.getAllRefs();
    refs.remove(Constants.HEAD);
    adv.send(refs);
    //}
    //finally
    //{
    //walk.release();
    //}

    outputStream.close();
    response.appendContentData(outputStream.data());
}