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

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

Introduction

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

Prototype

@Nullable
public String getBranch() throws IOException 

Source Link

Document

Get the short name of the current branch that HEAD points to.

Usage

From source file:ch.dals.buildtools.git.core.GitUtil.java

License:Open Source License

public static String currentBranch(final File location) throws IOException {
    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    final File gitDir = builder.findGitDir(location).readEnvironment().getGitDir();
    if (gitDir == null) {
        throw new FileNotFoundException("Cannot find Git directory upwards from: '" + location + "'");
    }//  w w  w .  j av  a  2s. c om
    final Repository repository = builder.build();
    try {
        final String branchName = repository.getBranch();
        if (branchName == null) {
            throw new FileNotFoundException("Failed to find HEAD reference in Git directory: '" + gitDir + "'");
        }
        return branchName;
    } finally {
        repository.close();
    }
}

From source file:com.cloudcontrolled.cctrl.maven.plugin.deploy.CloudcontrolledDeploy.java

License:Apache License

/** {@inheritDoc} */
@Override/*  www .  j a va 2s .co m*/
public void execute() throws MojoExecutionException, MojoFailureException {

    if (deployment == null || deployment.isEmpty()) {
        deployment = retrieveBranch();
        if (CloudControlSupport.MASTER_BRANCH.equals(deployment)) {
            deployment = "default";
        }
    }

    if (deployment == null) {
        Repository repository = null;
        try {
            repository = getRepository();
            String branch = repository.getBranch();
            if (!CloudControlSupport.MASTER_BRANCH.equals(branch)) {
                deployment = branch;
            }
        } catch (IOException e) {
            throw new MojoExecutionException(e.getClass().getSimpleName(), e);
        } finally {
            if (repository != null) {
                repository.close();
            }
        }
    }

    String deploymentQualifier = application
            + (deployment != null ? ":" + deployment + (commitId != null ? ":" + commitId : "") : "");
    log.info("Deploying " + deploymentQualifier + " to CloudControl PaaS.");

    CloudControlClient client = CloudControlSupport.createCloudControlClient();
    UpdateDeploymentRequest request = CloudControlSupport.createUpdateDeploymentRequest(application, deployment,
            commitId);

    UpdateDeploymentResponse response = null;
    try {
        response = client.send(request);

        if (response.isError()) {
            throw new MojoFailureException(response.getContent());
        }
    } catch (CloudControlClientException ccce) {
        throw new MojoExecutionException("CloudControlClientException", ccce);
    }

    log.info("Successfully deployed " + deploymentQualifier);
    log.info("Please, visit to following domain: http://" + response.getDeployment().getDefaultSubdomain());
}

From source file:com.gitblit.servlet.RawServlet.java

License:Apache License

/**
 * Retrieves the specified resource from the specified branch of the
 * repository.//from  ww  w  . j a v  a2s .c  o  m
 *
 * @param request
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = request.getPathInfo();
    if (path.toLowerCase().endsWith(".git")) {
        // forward to url with trailing /
        // this is important for relative pages links
        response.sendRedirect(request.getServletPath() + path + "/");
        return;
    }
    if (path.charAt(0) == '/') {
        // strip leading /
        path = path.substring(1);
    }

    // determine repository and resource from url
    String repository = path;
    Repository r = null;
    int terminator = repository.length();
    do {
        repository = repository.substring(0, terminator);
        r = repositoryManager.getRepository(repository, false);
        terminator = repository.lastIndexOf('/');
    } while (r == null && terminator > -1);

    ServletContext context = request.getSession().getServletContext();

    try {
        if (r == null) {
            // repository not found!
            String mkd = MessageFormat
                    .format("# Error\nSorry, no valid **repository** specified in this url: {0}!", path);
            error(response, mkd);
            return;
        }

        // identify the branch
        String branch = getBranch(repository, request);
        if (StringUtils.isEmpty(branch)) {
            branch = r.getBranch();
            if (branch == null) {
                // no branches found!  empty?
                String mkd = MessageFormat
                        .format("# Error\nSorry, no valid **branch** specified in this url: {0}!", path);
                error(response, mkd);
            } else {
                // redirect to default branch
                String base = request.getRequestURI();
                String url = base + branch + "/";
                response.sendRedirect(url);
            }
            return;
        }

        // identify the requested path
        String requestedPath = getPath(repository, branch, request);

        // identify the commit
        RevCommit commit = JGitUtils.getCommit(r, branch);
        if (commit == null) {
            // branch not found!
            String mkd = MessageFormat.format(
                    "# Error\nSorry, the repository {0} does not have a **{1}** branch!", repository, branch);
            error(response, mkd);
            return;
        }

        Map<String, String> quickContentTypes = new HashMap<>();
        quickContentTypes.put("html", "text/html");
        quickContentTypes.put("htm", "text/html");
        quickContentTypes.put("xml", "application/xml");
        quickContentTypes.put("json", "application/json");

        List<PathModel> pathEntries = JGitUtils.getFilesInPath(r, requestedPath, commit);
        if (pathEntries.isEmpty()) {
            // requested a specific resource
            String file = StringUtils.getLastPathElement(requestedPath);
            try {

                String ext = StringUtils.getFileExtension(file).toLowerCase();
                // We can't parse out an extension for classic "dotfiles", so make a general assumption that
                // they're text files to allow presenting them in browser instead of only for download.
                //
                // However, that only holds for files with no other extension included, for files that happen
                // to start with a dot but also include an extension, process the extension normally.
                // This logic covers .gitattributes, .gitignore, .zshrc, etc., but does not cover .mongorc.js, .zshrc.bak
                boolean isExtensionlessDotfile = file.charAt(0) == '.'
                        && (file.length() == 1 || file.indexOf('.', 1) < 0);
                String contentType = isExtensionlessDotfile ? "text/plain" : quickContentTypes.get(ext);

                if (contentType == null) {
                    List<String> exts = runtimeManager.getSettings().getStrings(Keys.web.prettyPrintExtensions);
                    if (exts.contains(ext)) {
                        // extension is a registered text type for pretty printing
                        contentType = "text/plain";
                    } else {
                        // query Tika for the content type
                        Tika tika = new Tika();
                        contentType = tika.detect(file);
                    }
                }

                if (contentType == null) {
                    // ask the container for the content type
                    contentType = context.getMimeType(requestedPath);

                    if (contentType == null) {
                        // still unknown content type, assume binary
                        contentType = "application/octet-stream";
                    }
                }

                if (isTextType(contentType) || isTextDataType(contentType)) {

                    // load, interpret, and serve text content as UTF-8
                    String[] encodings = runtimeManager.getSettings().getStrings(Keys.web.blobEncodings)
                            .toArray(new String[0]);
                    String content = JGitUtils.getStringContent(r, commit.getTree(), requestedPath, encodings);
                    if (content == null) {
                        logger.error("RawServlet Failed to load {} {} {}", repository, commit.getName(), path);
                        notFound(response, requestedPath, branch);
                        return;
                    }

                    byte[] bytes = content.getBytes(Constants.ENCODING);
                    setContentType(response, contentType);
                    response.setContentLength(bytes.length);
                    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
                    sendContent(response, JGitUtils.getCommitDate(commit), is);

                } else {
                    // stream binary content directly from the repository
                    if (!streamFromRepo(request, response, r, commit, requestedPath)) {
                        logger.error("RawServlet Failed to load {} {} {}", repository, commit.getName(), path);
                        notFound(response, requestedPath, branch);
                    }
                }
                return;
            } catch (Exception e) {
                logger.error(null, e);
            }
        } else {
            // path request
            if (!request.getPathInfo().endsWith("/")) {
                // redirect to trailing '/' url
                response.sendRedirect(request.getServletPath() + request.getPathInfo() + "/");
                return;
            }

            if (renderIndex()) {
                // locate and render an index file
                Map<String, String> names = new TreeMap<String, String>();
                for (PathModel entry : pathEntries) {
                    names.put(entry.name.toLowerCase(), entry.name);
                }

                List<String> extensions = new ArrayList<String>();
                extensions.add("html");
                extensions.add("htm");

                String content = null;
                for (String ext : extensions) {
                    String key = "index." + ext;

                    if (names.containsKey(key)) {
                        String fileName = names.get(key);
                        String fullPath = fileName;
                        if (!requestedPath.isEmpty()) {
                            fullPath = requestedPath + "/" + fileName;
                        }

                        String[] encodings = runtimeManager.getSettings().getStrings(Keys.web.blobEncodings)
                                .toArray(new String[0]);
                        String stringContent = JGitUtils.getStringContent(r, commit.getTree(), fullPath,
                                encodings);
                        if (stringContent == null) {
                            continue;
                        }
                        content = stringContent;
                        requestedPath = fullPath;
                        break;
                    }
                }

                response.setContentType("text/html; charset=" + Constants.ENCODING);
                byte[] bytes = content.getBytes(Constants.ENCODING);
                response.setContentLength(bytes.length);

                ByteArrayInputStream is = new ByteArrayInputStream(bytes);
                sendContent(response, JGitUtils.getCommitDate(commit), is);
                return;
            }
        }

        // no content, document list or 404 page
        if (pathEntries.isEmpty()) {
            // default 404 page
            notFound(response, requestedPath, branch);
            return;
        } else {
            //
            // directory list
            //
            response.setContentType("text/html");
            response.getWriter()
                    .append("<style>table th, table td { min-width: 150px; text-align: left; }</style>");
            response.getWriter().append("<table>");
            response.getWriter().append("<thead><tr><th>path</th><th>mode</th><th>size</th></tr>");
            response.getWriter().append("</thead>");
            response.getWriter().append("<tbody>");
            String pattern = "<tr><td><a href=\"{0}/{1}\">{1}</a></td><td>{2}</td><td>{3}</td></tr>";
            final ByteFormat byteFormat = new ByteFormat();
            if (!pathEntries.isEmpty()) {
                if (pathEntries.get(0).path.indexOf('/') > -1) {
                    // we are in a subdirectory, add parent directory link
                    String pp = URLEncoder.encode(requestedPath, Constants.ENCODING);
                    pathEntries.add(0,
                            new PathModel("..", pp + "/..", null, 0, FileMode.TREE.getBits(), null, null));
                }
            }

            String basePath = request.getServletPath() + request.getPathInfo();
            if (basePath.charAt(basePath.length() - 1) == '/') {
                // strip trailing slash
                basePath = basePath.substring(0, basePath.length() - 1);
            }
            for (PathModel entry : pathEntries) {
                String pp = URLEncoder.encode(entry.name, Constants.ENCODING);
                response.getWriter()
                        .append(MessageFormat.format(pattern, basePath, pp,
                                JGitUtils.getPermissionsFromMode(entry.mode),
                                entry.isFile() ? byteFormat.format(entry.size) : ""));
            }
            response.getWriter().append("</tbody>");
            response.getWriter().append("</table>");
        }
    } catch (Throwable t) {
        logger.error("Failed to write page to client", t);
    } finally {
        r.close();
    }
}

From source file:com.github.pascalgn.maven.properties.GitProperties.java

License:Apache License

private void addProperties(Map<String, String> map) throws IOException {
    Repository repository = new FileRepositoryBuilder().setWorkTree(new File(".")).readEnvironment()
            .findGitDir().setMustExist(true).build();
    logger.debug("Using git repository: " + repository.getDirectory());

    ObjectId head = repository.resolve("HEAD");
    if (head == null) {
        throw new IllegalStateException("No such revision: HEAD");
    }//from w ww. j  a v  a  2s.com

    String branch = nullToEmpty(repository.getBranch());
    map.put("git.branch", branch);

    String commitId = head.name();
    map.put("git.commit.id", commitId);

    String commitIdAbbrev = repository.newObjectReader().abbreviate(head).name();
    map.put("git.commit.id.abbrev", commitIdAbbrev);

    RevWalk walk = new RevWalk(repository);
    walk.setRetainBody(false);
    RevCommit headCommit = walk.parseCommit(head);
    int count = RevWalkUtils.count(walk, headCommit, null);
    map.put("git.count", Integer.toString(count));

    String color = commitId.substring(0, 6);
    map.put("git.commit.color.value", color);
    map.put("git.commit.color.name", ColorHelper.getColorName(color));
    map.put("git.commit.color.lightness", Integer.toString(ColorHelper.getLightness(color)));
    map.put("git.commit.color.foreground", ColorHelper.getForeground(color));

    map.put("git.build.datetime.simple", getFormattedDate());
}

From source file:com.github.rwhogg.git_vcr.App.java

License:Open Source License

/**
 * main is the entry point for Git-VCR//  ww w.  j a  v  a  2  s.c  o  m
 * @param args Command-line arguments
 */
public static void main(String[] args) {
    Options options = parseCommandLine(args);

    HierarchicalINIConfiguration configuration = null;
    try {
        configuration = getConfiguration();
    } catch (ConfigurationException e) {
        Util.error("could not parse configuration file!");
    }

    // verify we are in a git folder and then construct the repo
    final File currentFolder = new File(".");
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository localRepo = null;
    try {
        localRepo = builder.findGitDir().build();
    } catch (IOException e) {
        Util.error("not in a Git folder!");
    }

    // deal with submodules
    assert localRepo != null;
    if (localRepo.isBare()) {
        FileRepositoryBuilder parentBuilder = new FileRepositoryBuilder();
        Repository parentRepo;
        try {
            parentRepo = parentBuilder.setGitDir(new File("..")).findGitDir().build();
            localRepo = SubmoduleWalk.getSubmoduleRepository(parentRepo, currentFolder.getName());
        } catch (IOException e) {
            Util.error("could not find parent of submodule!");
        }
    }

    // if we need to retrieve the patch file, get it now
    URL patchUrl = options.getPatchUrl();
    String patchPath = patchUrl.getFile();
    File patchFile = null;
    HttpUrl httpUrl = HttpUrl.get(patchUrl);
    if (httpUrl != null) {
        try {
            patchFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".diff");
            Request request = new Request.Builder().url(httpUrl).build();
            OkHttpClient client = new OkHttpClient();
            Call call = client.newCall(request);
            Response response = call.execute();
            ResponseBody body = response.body();
            if (!response.isSuccessful()) {
                Util.error("could not retrieve diff file from URL " + patchUrl);
            }
            String content = body.string();
            org.apache.commons.io.FileUtils.write(patchFile, content, (Charset) null);
        } catch (IOException ie) {
            Util.error("could not retrieve diff file from URL " + patchUrl);
        }
    } else {
        patchFile = new File(patchPath);
    }

    // find the patch
    //noinspection ConstantConditions
    if (!patchFile.canRead()) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " is not readable!");
    }

    final Git git = new Git(localRepo);

    // handle the branch
    String branchName = options.getBranchName();
    String theOldCommit = null;
    try {
        theOldCommit = localRepo.getBranch();
    } catch (IOException e2) {
        Util.error("could not get reference to current branch!");
    }
    final String oldCommit = theOldCommit; // needed to reference from shutdown hook

    if (branchName != null) {
        // switch to the branch
        try {
            git.checkout().setName(branchName).call();
        } catch (RefAlreadyExistsException e) {
            // FIXME Auto-generated catch block
            e.printStackTrace();
        } catch (RefNotFoundException e) {
            Util.error("the branch " + branchName + " was not found!");
        } catch (InvalidRefNameException e) {
            Util.error("the branch name " + branchName + " is invalid!");
        } catch (org.eclipse.jgit.api.errors.CheckoutConflictException e) {
            Util.error("there was a checkout conflict!");
        } catch (GitAPIException e) {
            Util.error("there was an unspecified Git API failure!");
        }
    }

    // ensure there are no changes before we apply the patch
    try {
        if (!git.status().call().isClean()) {
            Util.error("cannot run git-vcr while there are uncommitted changes!");
        }
    } catch (NoWorkTreeException e1) {
        // won't happen
        assert false;
    } catch (GitAPIException e1) {
        Util.error("call to git status failed!");
    }

    // list all the files changed
    String patchName = patchFile.getName();
    Patch patch = new Patch();
    try {
        patch.parse(new FileInputStream(patchFile));
    } catch (FileNotFoundException e) {
        assert false;
    } catch (IOException e) {
        Util.error("could not parse the patch file!");
    }

    ReviewResults oldResults = new ReviewResults(patchName, patch, configuration, false);
    try {
        oldResults.review();
    } catch (InstantiationException e1) {
        Util.error("could not instantiate a review tool class!");
    } catch (IllegalAccessException e1) {
        Util.error("illegal access to a class");
    } catch (ClassNotFoundException e1) {
        Util.error("could not find a review tool class");
    } catch (ReviewFailedException e1) {
        e1.printStackTrace();
        Util.error("Review failed!");
    }

    // we're about to change the repo, so register a shutdown hook to clean it up
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            cleanupGit(git, oldCommit);
        }
    });

    // apply the patch
    try {
        git.apply().setPatch(new FileInputStream(patchFile)).call();
    } catch (PatchFormatException e) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " is malformatted!");
    } catch (PatchApplyException e) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " did not apply correctly!");
    } catch (FileNotFoundException e) {
        assert false;
    } catch (GitAPIException e) {
        Util.error(e.getLocalizedMessage());
    }

    ReviewResults newResults = new ReviewResults(patchName, patch, configuration, true);
    try {
        newResults.review();
    } catch (InstantiationException e1) {
        Util.error("could not instantiate a review tool class!");
    } catch (IllegalAccessException e1) {
        Util.error("illegal access to a class");
    } catch (ClassNotFoundException e1) {
        Util.error("could not find a review tool class");
    } catch (ReviewFailedException e1) {
        e1.printStackTrace();
        Util.error("Review failed!");
    }

    // generate and show the report
    VelocityReport report = new VelocityReport(patch, oldResults, newResults);
    File reportFile = null;
    try {
        reportFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".html");
        org.apache.commons.io.FileUtils.write(reportFile, report.toString(), (String) null);
    } catch (IOException e) {
        Util.error("could not generate the results page!");
    }

    try {
        assert reportFile != null;
        Desktop.getDesktop().open(reportFile);
    } catch (IOException e) {
        Util.error("could not open the results page!");
    }
}

From source file:com.google.appraise.eclipse.ui.AppraiseUiPlugin.java

License:Open Source License

/**
 * Returns the current Git branch, which in the detached head state (should
 * be true in the review workflow) will be the commit id.
 *///  w  w  w  .  j ava  2  s .c o  m
public String getCurrentCommit() {
    ITask activeTask = TasksUi.getTaskActivityManager().getActiveTask();
    TaskRepository taskRepository = TasksUi.getRepositoryManager()
            .getRepository(AppraiseConnectorPlugin.CONNECTOR_KIND, activeTask.getRepositoryUrl());
    Repository repo = AppraisePluginUtils.getGitRepoForRepository(taskRepository);
    try {
        return repo.getBranch();
    } catch (IOException e) {
        AppraiseUiPlugin.logError("Failed to retrive git branch", e);
        return null;
    }
}

From source file:com.meltmedia.cadmium.core.git.GitService.java

License:Apache License

public void switchBranch(String branchName) throws RefNotFoundException, Exception {
    Repository repository = git.getRepository();
    if (branchName != null && !repository.getBranch().equals(branchName)) {
        log.info("Switching branch from {} to {}", repository.getBranch(), branchName);
        CheckoutCommand checkout = git.checkout();
        if (isTag(branchName)) {
            checkout.setName(branchName);
        } else {//from www . j av  a 2  s  .co m
            checkout.setName("refs/heads/" + branchName);
            if (repository.getRef("refs/heads/" + branchName) == null) {
                CreateBranchCommand create = git.branchCreate();
                create.setName(branchName);
                create.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
                create.setStartPoint("origin/" + branchName);
                create.call();
            }
        }
        checkout.call();
    }
}

From source file:com.meltmedia.cadmium.core.git.GitService.java

License:Apache License

public String getBranchName() throws Exception {
    Repository repository = git.getRepository();
    if (ObjectId.isId(repository.getFullBranch())
            && repository.getFullBranch().equals(repository.resolve("HEAD").getName())) {
        RevWalk revs = null;/*from   ww  w . j  a  v  a  2  s .com*/
        try {
            log.trace("Trying to resolve tagname: {}", repository.getFullBranch());
            ObjectId tagRef = ObjectId.fromString(repository.getFullBranch());
            revs = new RevWalk(repository);
            RevCommit commit = revs.parseCommit(tagRef);
            Map<String, Ref> allTags = repository.getTags();
            for (String key : allTags.keySet()) {
                Ref ref = allTags.get(key);
                RevTag tag = revs.parseTag(ref.getObjectId());
                log.trace("Checking ref {}, {}", commit.getName(), tag.getObject());
                if (tag.getObject().equals(commit)) {
                    return key;
                }
            }
        } catch (Exception e) {
            log.warn("Invalid id: {}", repository.getFullBranch(), e);
        } finally {
            revs.release();
        }
    }
    return repository.getBranch();
}

From source file:com.pieceof8.gradle.snapshot.GitScmProvider.java

License:Apache License

/** {@inheritDoc} */
@Override// www . j  a  va 2 s. c o m
@SneakyThrows(IOException.class)
public Commit getCommit() {
    if (repoDir == null) {
        throw new IllegalArgumentException("'repoDir' must not be null");
    }
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    @Cleanup
    Repository repo = builder.setGitDir(repoDir).readEnvironment().findGitDir().build();
    StoredConfig conf = repo.getConfig();

    int abbrev = Commit.ABBREV_LENGTH;
    if (conf != null) {
        abbrev = conf.getInt("core", "abbrev", abbrev);
    }

    val sdf = new SimpleDateFormat(extension.getDateFormat());

    val HEAD = repo.getRef(Constants.HEAD);
    if (HEAD == null) {
        val msg = "Could not get HEAD Ref, the repository may be corrupt.";
        throw new RuntimeException(msg);
    }

    RevWalk revWalk = new RevWalk(repo);
    if (HEAD.getObjectId() == null) {
        val msg = "Could not find any commits from HEAD ref.";
        throw new RuntimeException(msg);
    }
    RevCommit commit = revWalk.parseCommit(HEAD.getObjectId());
    revWalk.markStart(commit);

    try {
        // git commit time in sec and java datetime is in ms
        val commitTime = new Date(commit.getCommitTime() * 1000L);
        val ident = commit.getAuthorIdent();

        return new Commit(sdf.format(new Date()), // build time
                conf.getString("user", null, "name"), conf.getString("user", null, "email"), repo.getBranch(),
                commit.getName(), sdf.format(commitTime), ident.getName(), ident.getEmailAddress(),
                commit.getFullMessage().trim());
    } finally {
        revWalk.dispose();
    }
}

From source file:com.puppetlabs.geppetto.forge.jenkins.RepositoryInfo.java

License:Open Source License

/**
 * Obtains the remote URL that is referenced by the given <code>branchName</code>
 *
 * @return The URL or <code>null</code> if it hasn't been configured
 *         for the given branch.//w w w . j  av a2 s  .c om
 */
public static String getRemoteURL(Repository repository) throws IOException {
    StoredConfig repoConfig = repository.getConfig();
    String configuredRemote = repoConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION,
            repository.getBranch(), ConfigConstants.CONFIG_KEY_REMOTE);
    return configuredRemote == null ? null
            : repoConfig.getString(ConfigConstants.CONFIG_REMOTE_SECTION, configuredRemote,
                    ConfigConstants.CONFIG_KEY_URL);
}