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

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

Introduction

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

Prototype

@Nullable
public String getFullBranch() throws IOException 

Source Link

Document

Get the name of the reference that HEAD points to.

Usage

From source file:org.flowerplatform.web.git.operation.CheckoutOperation.java

License:Open Source License

public boolean execute() {
    ProgressMonitor monitor = ProgressMonitor
            .create(GitPlugin.getInstance().getMessage("git.checkout.monitor.title"), channel);

    try {/*from  w  ww .  j  ava 2s .  c o m*/
        monitor.beginTask(
                GitPlugin.getInstance().getMessage("git.checkout.monitor.message", new Object[] { name }), 4);
        monitor.setTaskName("Getting remote branch...");
        Git git = new Git(repository);
        Ref ref;
        if (node instanceof Ref) {
            ref = (Ref) node;
        } else {
            // get remote branch
            String dst = Constants.R_REMOTES + remote.getName();
            String remoteRefName = dst + "/" + upstreamBranch.getShortName();
            ref = repository.getRef(remoteRefName);
            if (ref == null) { // doesn't exist, fetch it
                RefSpec refSpec = new RefSpec();
                refSpec = refSpec.setForceUpdate(true);
                refSpec = refSpec.setSourceDestination(upstreamBranch.getName(), remoteRefName);

                git.fetch().setRemote(new URIish(remote.getUri()).toPrivateString()).setRefSpecs(refSpec)
                        .call();

                ref = repository.getRef(remoteRefName);
            }
        }
        monitor.worked(1);
        monitor.setTaskName("Creating local branch...");

        // create local branch
        git.branchCreate().setName(name).setStartPoint(ref.getName())
                .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM).call();

        if (!(node instanceof Ref)) {
            // save upstream configuration
            StoredConfig config = repository.getConfig();

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_MERGE,
                    upstreamBranch.getName());

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REMOTE,
                    remote.getName());

            if (rebase) {
                config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, name,
                        ConfigConstants.CONFIG_KEY_REBASE, true);
            } else {
                config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REBASE);
            }
            config.save();
        }
        monitor.worked(1);
        monitor.setTaskName("Creating working directory");

        // create working directory for local branch
        File mainRepoFile = repository.getDirectory().getParentFile();
        File wdirFile = new File(mainRepoFile.getParentFile(), GitUtils.WORKING_DIRECTORY_PREFIX + name);
        if (wdirFile.exists()) {
            GitPlugin.getInstance().getUtils().delete(wdirFile);
        }
        GitPlugin.getInstance().getUtils().run_git_workdir_cmd(mainRepoFile.getAbsolutePath(),
                wdirFile.getAbsolutePath());
        monitor.worked(1);
        monitor.setTaskName("Checkout branch");

        // checkout local branch
        Repository wdirRepo = GitPlugin.getInstance().getUtils().getRepository(wdirFile);
        git = new Git(wdirRepo);

        CheckoutCommand cc = git.checkout().setName(name).setForce(true);
        cc.call();

        // show checkout result
        if (cc.getResult().getStatus() == CheckoutResult.Status.CONFLICTS)
            channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                    GitPlugin.getInstance().getMessage("git.checkout.checkoutConflicts.title"),
                    GitPlugin.getInstance().getMessage("git.checkout.checkoutConflicts.message"),
                    cc.getResult().getConflictList().toString(),
                    DisplaySimpleMessageClientCommand.ICON_INFORMATION));

        else if (cc.getResult().getStatus() == CheckoutResult.Status.NONDELETED) {
            // double-check if the files are still there
            boolean show = false;
            List<String> pathList = cc.getResult().getUndeletedList();
            for (String path1 : pathList) {
                if (new File(wdirRepo.getWorkTree(), path1).exists()) {
                    show = true;
                    break;
                }
            }
            if (show) {
                channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                        GitPlugin.getInstance().getMessage("git.checkout.nonDeletedFiles.title"),
                        GitPlugin.getInstance().getMessage("git.checkout.nonDeletedFiles.message",
                                Repository.shortenRefName(name)),
                        cc.getResult().getUndeletedList().toString(),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
            }
        } else if (cc.getResult().getStatus() == CheckoutResult.Status.OK) {
            if (ObjectId.isId(wdirRepo.getFullBranch()))
                channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                        GitPlugin.getInstance().getMessage("git.checkout.detachedHead.title"),
                        GitPlugin.getInstance().getMessage("git.checkout.detachedHead.message"),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
        }
        monitor.worked(1);
        return true;
    } catch (Exception e) {
        channel.appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    } finally {
        monitor.done();
    }
}

From source file:org.nbgit.ui.custom.CustomAction.java

License:Open Source License

@Override
protected void performAction(ActionEvent event) {
    File root = GitUtils.getProjectFile(context);
    RequestProcessor rp = Git.getInstance().getRequestProcessor(root.getAbsolutePath());
    Repository repo = Git.getInstance().getRepository(root);
    final List<String> command = new ArrayList<String>();

    command.add(path.getAbsolutePath());
    for (String arg : args.split(" ")) {
        if (arg.equals("{head}")) {
            try {
                command.add(repo.getFullBranch());
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }/*from  w  w w.j  a  v  a  2s . com*/
        } else if (arg.equals("{files}")) {
            for (File file : context.getFiles()) {
                command.add(file.getAbsolutePath());
            }
        } else {
            command.add(arg);
        }
    }

    final File execDir;
    if (context.getRootFiles().size() == 1 && !workDirRoot) {
        execDir = context.getRootFiles().iterator().next();
    } else {
        execDir = root;
    }

    GitProgressSupport support = new GitProgressSupport() {

        public void perform() {
            execute(command, execDir, showOutput ? getLogger() : null);
        }

    };

    /* TODO: Use MessageFormat */
    support.start(rp, root.getAbsolutePath(),
            NbBundle.getMessage(CustomAction.class, "CustomActionProgress") + " " + path.getName()); // NOI18N
}

From source file:org.nbgit.util.HtmlFormatter.java

License:Open Source License

/**
 * Applies custom format./*  w w w  . j av a2 s  .  com*/
 */
private String formatAnnotation(StatusInfo info, File file) {
    String statusString = ""; // NOI18N
    int status = info.getStatus();
    if (status != StatusInfo.STATUS_VERSIONED_UPTODATE) {
        statusString = info.getShortStatusText();
    }
    String revisionString = ""; // NOI18N
    String binaryString = ""; // NOI18N

    if (needRevisionForFormat) {
        if ((status & StatusInfo.STATUS_NOTVERSIONED_EXCLUDED) == 0) {
            try {
                File root = Git.getInstance().getTopmostManagedParent(file);
                Repository repo = Git.getInstance().getRepository(root);
                ObjectId branch = repo.resolve(repo.getFullBranch());
                String absPath = file.getAbsolutePath();
                String relPath = absPath.replace(root.getAbsolutePath(), "");
                RevWalk walk = new RevWalk(repo);
                RevCommit start = walk.parseCommit(branch);
                TreeFilter filter = PathFilter.create(relPath);

                walk.setTreeFilter(filter);
                walk.markStart(start);

                for (RevCommit commit : walk) {
                    revisionString = commit.getId().name();
                    break;
                }
                walk.dispose();

            } catch (IOException ex) {
                NotifyDescriptor notification = new NotifyDescriptor.Message(ex,
                        NotifyDescriptor.ERROR_MESSAGE);
                DialogDisplayer.getDefault().notifyLater(notification);
            }
        }
    }
    String stickyString = null;
    if (stickyString == null) {
        stickyString = "";
    }
    Object[] arguments = new Object[] { revisionString, statusString, stickyString, };

    String annotation = format.format(arguments, new StringBuffer(), null).toString().trim();
    if (annotation.equals(emptyFormat)) {
        return "";
    } else {
        return " " + annotation;
    }
}

From source file:playRepository.GitRepository.java

License:Apache License

public static boolean canDeleteFromBranch(PullRequest pullRequest) {
    List<Ref> refs;/*from   ww  w. j a  v  a  2 s  . c om*/
    Repository fromRepo = null; // repository that sent the pull request
    String currentBranch;
    try {
        fromRepo = buildGitRepository(pullRequest.fromProject);
        currentBranch = fromRepo.getFullBranch();
        refs = new Git(fromRepo).branchList().call();

        for (Ref branchRef : refs) {
            String branchName = branchRef.getName();
            if (branchName.equals(pullRequest.fromBranch) && !branchName.equals(currentBranch)) {
                RevWalk revWalk = new RevWalk(fromRepo);
                RevCommit commit = revWalk.parseCommit(fromRepo.resolve(branchName));
                String commitName = commit.name(); // fromBranch's head commit name
                revWalk.release();

                // check whether the target repository has the commit witch is the fromBranch's head commit.
                Repository toRepo = buildGitRepository(pullRequest.toProject);
                ObjectId toBranch = toRepo.resolve(commitName);
                if (toBranch != null) {
                    return true;
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (fromRepo != null) {
            fromRepo.close();
        }
    }

    return false;
}