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

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

Introduction

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

Prototype

@Nullable
public final Ref findRef(String name) throws IOException 

Source Link

Document

Search for a ref by (possibly abbreviated) name.

Usage

From source file:br.edu.ifpb.scm.api.loads.LoaderVersions.java

public static void teste2() throws IOException, GitAPIException {
    org.eclipse.jgit.api.Git git = org.eclipse.jgit.api.Git.open(PATH);
    org.eclipse.jgit.lib.Repository repository = git.getRepository();

    repository.findRef(URL);

    ObjectId oldHead = repository.resolve("HEAD~^{tree}");
    ObjectId newHead = repository.resolve("HEAD^{tree}");

    ObjectReader reader = repository.newObjectReader();
    CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
    //        ObjectId oldTree = git.getRepository().resolve("SHA-1{64c852a8fe9e3673aa381f95c4b0420986d1f925}");

    CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
    //        ObjectId newTree = git.getRepository().resolve("SHA-1{12ae7a9960c49cfe68bdd5f7b0a58e1b3b0c6e56}");

    oldTreeIter.reset(reader, oldHead);/*from   ww  w. j  av a  2  s. c o  m*/
    newTreeIter.reset(reader, newHead);

    try (org.eclipse.jgit.api.Git g = new org.eclipse.jgit.api.Git(repository)) {
        List<DiffEntry> diffs = g.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();
        for (DiffEntry entry : diffs) {
            System.out.println("Entry: " + entry);
        }
    }

    //        DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE);
    //        diffFormatter.setRepository(git.getRepository());
    //        List<DiffEntry> entries = diffFormatter.scan(oldTreeIter, newTreeIter);
    //
    //        entries.stream().forEach((entry) -> {
    //            System.out.println(entry.getChangeType());
    //        });
}

From source file:com.gitblit.utils.RefLogUtils.java

License:Apache License

/**
 * Returns true if the repository has a reflog branch.
 *
 * @param repository/*from   w w  w .  ja  v  a 2s  .c  o  m*/
 * @return true if the repository has a reflog branch
 */
public static boolean hasRefLogBranch(Repository repository) {
    try {
        return repository.findRef(GB_REFLOG) != null;
    } catch (Exception e) {
        LOGGER.error("failed to determine hasRefLogBranch", e);
    }
    return false;
}

From source file:com.gitblit.wicket.pages.TicketPage.java

License:Apache License

private Link<Void> createDeletePatchsetLink(final RepositoryModel repositoryModel, final Patchset patchset) {
    Link<Void> deleteLink = new Link<Void>("deleteRevision") {
        private static final long serialVersionUID = 1L;

        @Override//from  w w w. ja v  a 2 s.co m
        public void onClick() {
            Repository r = app().repositories().getRepository(repositoryModel.name);
            UserModel user = GitBlitWebSession.get().getUser();

            if (r == null) {
                if (app().repositories().isCollectingGarbage(repositoryModel.name)) {
                    error(MessageFormat.format(getString("gb.busyCollectingGarbage"), repositoryModel.name));
                } else {
                    error(MessageFormat.format("Failed to find repository {0}", repositoryModel.name));
                }
                return;
            }

            //Construct the ref name based on the patchset
            String ticketShard = String.format("%02d", ticket.number);
            ticketShard = ticketShard.substring(ticketShard.length() - 2);
            final String refName = String.format("%s%s/%d/%d", Constants.R_TICKETS_PATCHSETS, ticketShard,
                    ticket.number, patchset.number);

            Ref ref = null;
            boolean success = true;

            try {
                ref = r.findRef(refName);

                if (ref != null) {
                    success = JGitUtils.deleteBranchRef(r, ref.getName());
                } else {
                    success = false;
                }

                if (success) {
                    // clear commit cache
                    CommitCache.instance().clear(repositoryModel.name, refName);

                    // optionally update reflog
                    if (RefLogUtils.hasRefLogBranch(r)) {
                        RefLogUtils.deleteRef(user, r, ref);
                    }

                    TicketModel updatedTicket = app().tickets().deletePatchset(ticket, patchset, user.username);

                    if (updatedTicket == null) {
                        success = false;
                    }
                }
            } catch (IOException e) {
                logger().error("failed to determine ticket from ref", e);
                success = false;
            } finally {
                r.close();
            }

            if (success) {
                getSession().info(MessageFormat.format(getString("gb.deletePatchsetSuccess"), patchset.number));
                logger().info(MessageFormat.format("{0} deleted patchset {1} from ticket {2}", user.username,
                        patchset.number, ticket.number));
            } else {
                getSession()
                        .error(MessageFormat.format(getString("gb.deletePatchsetFailure"), patchset.number));
            }

            //Force reload of the page to rebuild ticket change cache
            String absoluteUrl = GitBlitRequestUtils.toAbsoluteUrl(TicketsPage.class, getPageParameters());
            setResponsePage(new RedirectPage(absoluteUrl));
        }
    };

    WicketUtils.setHtmlTooltip(deleteLink,
            MessageFormat.format(getString("gb.deletePatchset"), patchset.number));

    deleteLink.add(new JavascriptEventConfirmation("click",
            MessageFormat.format(getString("gb.deletePatchset"), patchset.number)));

    return deleteLink;
}

From source file:com.gitblit.wicket.panels.BranchesPanel.java

License:Apache License

private Link<Void> createDeleteBranchLink(final RepositoryModel repositoryModel, final RefModel entry) {
    Link<Void> deleteLink = new Link<Void>("deleteBranch") {
        private static final long serialVersionUID = 1L;

        @Override/*from ww w . j  a  va2s .co m*/
        public void onClick() {
            Repository r = app().repositories().getRepository(repositoryModel.name);
            if (r == null) {
                if (app().repositories().isCollectingGarbage(repositoryModel.name)) {
                    error(MessageFormat.format(getString("gb.busyCollectingGarbage"), repositoryModel.name));
                } else {
                    error(MessageFormat.format("Failed to find repository {0}", repositoryModel.name));
                }
                return;
            }
            final String branch = entry.getName();
            Ref ref = null;
            try {
                ref = r.findRef(branch);
                if (ref == null && !branch.startsWith(Constants.R_HEADS)) {
                    ref = r.findRef(Constants.R_HEADS + branch);
                }
            } catch (IOException e) {
            }
            if (ref != null) {
                boolean success = JGitUtils.deleteBranchRef(r, ref.getName());
                if (success) {
                    // clear commit cache
                    CommitCache.instance().clear(repositoryModel.name, branch);

                    // optionally update reflog
                    if (RefLogUtils.hasRefLogBranch(r)) {
                        UserModel user = GitBlitWebSession.get().getUser();
                        RefLogUtils.deleteRef(user, r, ref);
                    }
                }

                if (success) {
                    info(MessageFormat.format("Branch \"{0}\" deleted", branch));
                } else {
                    error(MessageFormat.format("Failed to delete branch \"{0}\"", branch));
                }
            }
            r.close();

            // redirect to the owning page
            PageParameters params = WicketUtils.newRepositoryParameter(repositoryModel.name);
            String absoluteUrl = GitBlitRequestUtils.toAbsoluteUrl(getPage().getClass(), params);
            getRequestCycle().scheduleRequestHandlerAfterCurrent(new RedirectRequestHandler(absoluteUrl));
        }
    };

    deleteLink.add(new JavascriptEventConfirmation("click",
            MessageFormat.format("Delete branch \"{0}\"?", entry.displayName)));
    return deleteLink;
}

From source file:com.github.checkstyle.github.NotesBuilder.java

License:Open Source License

/**
 * Returns actual SHA-1 object by commit reference.
 * @param repo git repository./*w ww .ja va  2s  .c  o m*/
 * @param ref string representation of commit reference.
 * @return actual SHA-1 object.
 * @throws IOException if an I/O error occurs.
 */
private static ObjectId getActualRefObjectId(Repository repo, String ref) throws IOException {
    final ObjectId actualObjectId;
    final Ref referenceObj = repo.findRef(ref);
    if (referenceObj == null) {
        actualObjectId = repo.resolve(ref);
    } else {
        final Ref repoPeeled = repo.peel(referenceObj);
        actualObjectId = Optional.ofNullable(repoPeeled.getPeeledObjectId()).orElse(referenceObj.getObjectId());
    }
    return actualObjectId;
}

From source file:com.github.kaitoy.goslings.server.dao.jgit.ReferenceDaoImpl.java

License:Open Source License

@Override
public SymbolicReference[] getSymbolicReferences(String token) {
    Repository repo = resolver.getRepository(token);
    return Arrays.stream(SYMBOLIC_REFS).map(refName -> {
        try {//from   ww  w  .j  ava  2  s.  c o m
            Ref ref = repo.findRef(refName);
            if (ref == null) {
                return null;
            }

            if (ref.isSymbolic()) {
                // attached to a branch
                return new SymbolicReference(ref.getName(), ref.getTarget().getName());
            } else {
                // detached
                return new SymbolicReference(ref.getName(), ref.getObjectId().getName());
            }
        } catch (IOException e) {
            String message = new StringBuilder().append("Failed to find HEAD in the repository ").append(token)
                    .append(" due to an I/O error.").toString();
            LOG.error(message, e);
            throw new DaoException(message, e);
        }
    }).filter(ref -> ref != null).toArray(SymbolicReference[]::new);
}

From source file:de.unihalle.informatik.Alida.version.ALDVersionProviderGit.java

License:Open Source License

/**
 * Returns information about current commit.
 * <p>/* w w  w  .j  a  v  a  2 s.  c om*/
 * If no git repository is found, the method checks for a file 
 * "revision.txt" as it is present in Alida jar files. 
 * If the file does not exist or is empty, a dummy string is returned.
 * 
 * @return    Info string.
 */
private static String getRepositoryInfo() {

    ALDVersionProviderGit.localVersion = "Unknown";
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try {
        Repository repo = null;
        try {
            repo = builder.readEnvironment().build();
        } catch (IllegalArgumentException e) {
            // problem accessing environment... fall back to default
            if (repo != null)
                repo.close();
            return ALDVersionProviderGit.localVersion;
        }

        // check if GIT_DIR is set
        if (!builder.getGitDir().isDirectory()) {
            if (repo != null)
                repo.close();
            return ALDVersionProviderGit.localVersion;
        }

        // extract the active branch
        String activeBranch = repo.getBranch();

        // extract last commit 
        Ref HEAD = repo.findRef(activeBranch);

        // safety check if everything is alright with repository
        if (HEAD == null) {
            repo.close();
            throw new IOException();
        }

        // extract state of repository
        String state = repo.getRepositoryState().toString();

        ALDVersionProviderGit.localVersion = activeBranch + " : " + HEAD.toString() + " ( " + state + " ) ";

        // clean-up
        repo.close();
    } catch (IOException e) {
        // accessing the Git repository failed, search for file
        InputStream is = null;
        BufferedReader br = null;
        String vLine = null;

        // initialize file reader and extract version information
        try {
            System.out.print("Searching for local revision file...");
            is = ALDVersionProviderGit.class.getResourceAsStream("/" + ALDVersionProviderGit.revFile);
            br = new BufferedReader(new InputStreamReader(is));
            vLine = br.readLine();
            if (vLine == null) {
                System.err.println("ALDVersionProviderGit: " + "revision file is empty...!?");
                br.close();
                is.close();
                return ALDVersionProviderGit.localVersion;
            }
            ALDVersionProviderGit.localVersion = vLine;
            br.close();
            is.close();
            return vLine;
        } catch (Exception ex) {
            try {
                if (br != null)
                    br.close();
                if (is != null)
                    is.close();
            } catch (IOException eo) {
                // nothing to do here
            }
            return ALDVersionProviderGit.localVersion;
        }
    }
    return ALDVersionProviderGit.localVersion;
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

License:Open Source License

private void checkoutEnvironment(Repository repository, String site) {
    Git git = null;/*from  w w  w. j  a  v  a2  s.com*/
    try {
        Ref branchRef = repository.findRef(environment);
        git = new Git(repository);
        git.checkout().setCreateBranch(true).setName(environment)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                .setStartPoint("origin/" + environment).call();
        git.fetch().call();
        git.pull().call();
    } catch (RefNotFoundException e) {
        try {
            git.checkout().setOrphan(true).setName(environment).call();
            ProcessBuilder pb = new ProcessBuilder();
            pb.command("git", "rm", "-rf", ".");
            pb.directory(repository.getDirectory().getParentFile());
            Process p = pb.start();
            p.waitFor();

            git.commit().setMessage("initial content").setAllowEmpty(true).call();
        } catch (GitAPIException | InterruptedException | IOException e1) {
            logger.error("Error checking out environment store branch for site " + site + " environment "
                    + environment, e1);
        }
    } catch (IOException | GitAPIException e) {
        logger.error(
                "Error checking out environment store branch for site " + site + " environment " + environment,
                e);
    }
}

From source file:org.eclipse.egit.gitflow.op.InitOperationTest.java

License:Open Source License

@Test(expected = CoreException.class)
public void testInitLocalMasterMissing() throws Exception {
    testRepository.createInitialCommit("testInitLocalMasterMissing\n\nfirst commit\n");

    Repository repository = testRepository.getRepository();
    new RenameBranchOperation(repository, repository.findRef(repository.getBranch()), "foobar").execute(null);

    new InitOperation(repository).execute(null);
}

From source file:org.eclipse.egit.ui.internal.pull.PullWizardPage.java

License:Open Source License

/**
 * Create the page.//from  ww w  .  j a  v a 2  s. c om
 *
 * @param repository
 */
public PullWizardPage(Repository repository) {
    super(UIText.PullWizardPage_PageName);
    setTitle(UIText.PullWizardPage_PageTitle);
    setMessage(UIText.PullWizardPage_PageMessage);
    setImageDescriptor(UIIcons.WIZBAN_PULL);
    this.repository = repository;
    try {
        this.head = repository.findRef(Constants.HEAD);
        this.fullBranch = repository.getFullBranch();
    } catch (IOException ex) {
        Activator.logError(ex.getMessage(), ex);
    }
}