Example usage for org.eclipse.jgit.api Git getRepository

List of usage examples for org.eclipse.jgit.api Git getRepository

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git getRepository.

Prototype

public Repository getRepository() 

Source Link

Document

Get repository

Usage

From source file:com.barchart.jenkins.cascade.PluginScmGit.java

License:BSD License

/**
 * Find reference in repository.//from   www .  j  a va  2s  .co  m
 */
public static Ref findRef(final File workspace, final String name) {
    try {
        final Git git = Git.open(workspace);
        return git.getRepository().getRef(name);
    } catch (final Throwable e) {
        throw new RuntimeException(e);
    }
}

From source file:com.chungkwong.jgitgui.LogTreeItem.java

License:Open Source License

@Override
public Node getContentPage() {
    GridPane page = new GridPane();
    TextField oldSrc = new TextField();
    TextField newSrc = new TextField();
    CheckBox detailed = new CheckBox(
            java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("DETAILED"));
    Button ok = new Button(java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("DIFF"));
    TextArea diff = new TextArea();
    diff.setEditable(false);/* w w  w  .j a  v a  2 s . c  o m*/
    Git git = ((Git) getParent().getValue());
    GridPane.setVgrow(diff, Priority.ALWAYS);
    GridPane.setHgrow(diff, Priority.ALWAYS);
    GridPane.setHgrow(oldSrc, Priority.ALWAYS);
    GridPane.setHgrow(newSrc, Priority.ALWAYS);
    ok.setOnAction((ActionEvent e) -> {
        try (ObjectReader reader = git.getRepository().newObjectReader()) {
            List<DiffEntry> entries;
            if (oldSrc.getText().isEmpty() && newSrc.getText().isEmpty()) {
                entries = ((Git) getParent().getValue()).diff().setCached(true).call();
            } else {
                CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
                oldTreeIter.reset(reader, git.getRepository().resolve(oldSrc.getText() + "^{tree}"));
                CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
                newTreeIter.reset(reader, git.getRepository().resolve(newSrc.getText() + "^{tree}"));
                entries = ((Git) getParent().getValue()).diff().setNewTree(newTreeIter).setOldTree(oldTreeIter)
                        .call();
            }
            if (detailed.isSelected()) {
                PipedInputStream in = new PipedInputStream();
                PipedOutputStream out = new PipedOutputStream(in);
                DiffFormatter formatter = new DiffFormatter(out);
                formatter.setRepository(git.getRepository());
                formatter.format(entries);
                out.close();
                diff.setText(new BufferedReader(new InputStreamReader(in)).lines()
                        .collect(Collectors.joining("\n")));
            } else {
                diff.setText(entries.stream().map((o) -> toString(o)).collect(Collectors.joining("\n")));
            }
        } catch (Exception ex) {
            Logger.getLogger(LogTreeItem.class.getName()).log(Level.SEVERE, null, ex);
            Util.informUser(ex);
        }
    });
    page.addColumn(0, oldSrc, newSrc, detailed, ok, diff);

    page.setMaxSize(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
    return page;
}

From source file:com.codeabovelab.dm.cluman.configs.container.ConfigsFetcherGit.java

License:Apache License

private Git initGitRepo() {
    try {//from w  ww. j a  v  a  2 s  .  c o  m
        log.info("try to init repo {}", gitSettings.getUrl());
        File gitDir = gitDirPath.toFile();
        FileUtils.deleteQuietly(gitDir);
        gitDir.mkdirs();

        Git git = Git.cloneRepository().setURI(gitSettings.getUrl()).setCredentialsProvider(cp)
                .setDirectory(gitDir).setBranchesToClone(singleton(HEAD + gitSettings.getBranch()))
                .setBranch(HEAD + gitSettings.getBranch()).call();
        log.info("repo was cloned from url: {} to dir: {}, branch: {} ", gitSettings.getUrl(), gitDir,
                git.getRepository().getBranch());
        return git;
    } catch (Exception e) {
        throw Throwables.asRuntime(e);
    }
}

From source file:com.creactiviti.piper.core.git.JGitTemplate.java

License:Apache License

private synchronized Repository getRepository(String aUrl, String aBranch) {
    try {//from   ww w.j ava 2  s.c o  m
        clear();
        logger.info("Cloning {} {}", aUrl, aBranch);
        Git git = Git.cloneRepository().setURI(aUrl).setBranch(aBranch).setDirectory(repositoryDir).call();
        return (git.getRepository());
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.crygier.git.rest.resources.RepositoryResource.java

License:Apache License

/**
 * Method handling HTTP GET requests. The returned object will be sent
 * to the client as "text/plain" media type.
 *
 * @return String that will be returned as a text/plain response.
 *//*from   w w w. ja  v  a  2s.co m*/
@GET
@Path("/{repositoryName}/clone")
@JSONP(queryParam = "callback")
@Produces({ "application/javascript" })
public Map<String, Object> cloneRepository(@PathParam("repositoryName") String repositoryName,
        @QueryParam("url") String url, @QueryParam("directory") File directory) {
    Map<String, Object> answer = new HashMap<String, Object>();

    try {
        URIish uri = new URIish(url);

        CloneCommand cloneCommand = Git.cloneRepository().setURI(url)
                .setDirectory(new File(directory, repositoryName.replaceAll(".git", ""))).setBare(false)
                .setProgressMonitor(new TextProgressMonitor());

        Git git = cloneCommand.call();
        answer.put("status", "ok");
        git.getRepository().close();

        answer.putAll(registerLocalRepository(repositoryName, directory));
    } catch (GitAPIException e) {
        logger.log(Level.SEVERE, "Error Cloning", e);
        answer.put("errorMessage", e.getMessage());
    } catch (URISyntaxException e) {
        logger.log(Level.SEVERE, "Invalid URL", e);
        answer.put("errorMessage", e.getMessage());
    }

    return answer;
}

From source file:com.crygier.git.rest.util.GitUtil.java

License:Apache License

/**
 * A common way to execute commands on the Git object, dealing with error handling in a consistent way.
 *
 * @param repositoryName Name of the registered repository to work with
 * @param gitCallback Callback to use the git object
 * @param <T> Return type of the callback - matches the return type of this method
 * @return Whatever gitCallback returns, unless a GitAPIException is thrown, then null
 *//*from ww w  .jav a2s  . c  o m*/
public static <T> T doWithGit(String repositoryName, GitCallback<T> gitCallback) {
    Git git = getGit(repositoryName);
    if (git != null)
        try {
            return gitCallback.doWitGit(git);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Error running git command for git directory: "
                    + git.getRepository().getDirectory().getAbsolutePath(), e);
            return null;
        }

    return null;
}

From source file:com.dell.doradus.core.DoradusServer.java

License:Apache License

/**
 * Get Doradus Version from git repo if it exists; otherwise get it from the local doradus.ver file
 * @return version//from  ww  w.  ja v  a2s  .c om
 */
public static String getDoradusVersion() {
    String version = null;
    try {
        //first read from the local git repository
        Git git = Git.open(new File("../.git"));
        String url = git.getRepository().getConfig().getString("remote", "origin", "url");
        instance().m_logger.info("Remote.origin.url: {}", url);
        if (!Utils.isEmpty(url) && url.contains("dell-oss/Doradus.git")) {
            DescribeCommand cmd = git.describe();
            version = cmd.call();
            instance().m_logger.info("Doradus version found from git repo: {}", version);
            writeVersionToVerFile(version);
        }
    } catch (Throwable e) {
        instance().m_logger.info("failed to read version from git repo");
    }
    //if not found, reading from local file
    if (Utils.isEmpty(version)) {
        try {
            version = getVersionFromVerFile();
            instance().m_logger.info("Doradus version found from doradus.ver file {}", version);
        } catch (IOException e1) {
            version = null;
        }
    }
    return version;
}

From source file:com.denimgroup.threadfix.service.repository.GitServiceImpl.java

License:Mozilla Public License

@Override
public boolean testConfiguration(Application application, String repo, String branch) throws GitAPIException {
    InitCommand initCommand = new InitCommand();
    File applicationDirectory = DiskUtils.getScratchFile(baseDirectory + application.getId() + "-test");
    initCommand.setDirectory(applicationDirectory);

    Git otherGit = initCommand.call();

    otherGit.getRepository().getConfig().setString("remote", "origin", "url", repo);

    String targetRefSpec = branch == null || branch.isEmpty() ? Constants.R_HEADS + "*:refs/remotes/origin/*"
            : Constants.R_HEADS + branch;

    FetchCommand fetchCommand = otherGit.fetch()
            .setCredentialsProvider(getUnencryptedApplicationCredentials(application)).setDryRun(true)
            .setRefSpecs(new RefSpec(targetRefSpec)).setRemote("origin");

    fetchCommand.call();/*from w  ww . j  a  v a 2 s.  c  o  m*/

    return true;
}

From source file:com.denimgroup.threadfix.service.repository.GitServiceImpl.java

License:Mozilla Public License

@Override
public File cloneRepoToDirectory(Application application, File dirLocation) {

    if (dirLocation.exists()) {
        File gitDirectoryFile = new File(dirLocation.getAbsolutePath() + File.separator + ".git");

        try {/*from   w ww .  ja v a 2s.  co  m*/
            if (!gitDirectoryFile.exists()) {
                Git newRepo = clone(application, dirLocation);
                if (newRepo != null)
                    return newRepo.getRepository().getWorkTree();
            } else {
                Repository localRepo = new FileRepository(gitDirectoryFile);
                Git git = new Git(localRepo);

                if (application.getRepositoryRevision() != null
                        && !application.getRepositoryRevision().isEmpty()) {
                    //remote checkout
                    git.checkout().setCreateBranch(true).setStartPoint(application.getRepositoryRevision())
                            .setName(application.getRepositoryRevision()).call();
                } else {

                    List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();

                    String repoBranch = (application.getRepositoryBranch() != null
                            && !application.getRepositoryBranch().isEmpty()) ? application.getRepositoryBranch()
                                    : "master";

                    boolean localCheckout = false;

                    for (Ref ref : refs) {
                        String refName = ref.getName();
                        if (refName.contains(repoBranch) && !refName.contains(Constants.R_REMOTES)) {
                            localCheckout = true;
                        }
                    }

                    String HEAD = localRepo.getFullBranch();

                    if (HEAD.contains(repoBranch)) {
                        git.pull().setRemote("origin").setRemoteBranchName(repoBranch)
                                .setCredentialsProvider(getApplicationCredentials(application)).call();
                    } else {
                        if (localCheckout) {
                            //local checkout
                            git.checkout().setName(application.getRepositoryBranch()).call();
                            git.pull().setRemote("origin").setRemoteBranchName(repoBranch)
                                    .setCredentialsProvider(getApplicationCredentials(application)).call();
                        } else {
                            //remote checkout
                            git.checkout().setCreateBranch(true).setName(repoBranch)
                                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM)
                                    .setStartPoint("origin/" + repoBranch).call();
                        }
                    }
                }

                return git.getRepository().getWorkTree();
            }
        } catch (JGitInternalException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (IOException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (WrongRepositoryStateException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidConfigurationException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (DetachedHeadException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidRemoteException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (CanceledException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (RefNotFoundException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (NoHeadException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (RefAlreadyExistsException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (CheckoutConflictException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidRefNameException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (TransportException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (GitAPIException e) {
            log.error(EXCEPTION_MESSAGE, e);
        }
    } else {
        try {
            log.info("Attempting to clone application from repository.");
            Git result = clone(application, dirLocation);
            if (result != null) {
                log.info("Application was successfully cloned from repository.");
                return result.getRepository().getWorkTree();
            }
            log.error(EXCEPTION_MESSAGE);
        } catch (JGitInternalException e) {
            log.error(EXCEPTION_MESSAGE, e);
        }
    }
    return null;
}

From source file:com.ejwa.gitdepmavenplugin.DownloaderMojo.java

License:Open Source License

private void checkout(Git git, Pom pom, GitDependency dependency) throws MojoExecutionException {
    final GitDependencyHandler dependencyHandler = new GitDependencyHandler(dependency);
    final String version = dependencyHandler.getDependencyVersion(pom);

    try {/*from   ww  w  . java2s  .c  o  m*/
        final Repository repository = git.getRepository();
        final ObjectId rev = repository.resolve(version);
        final RevCommit rc = new RevWalk(repository).parseCommit(rev);
        final CheckoutCommand checkout = git.checkout();

        checkout.setName("maven-gitdep-branch-" + rc.getCommitTime());
        checkout.setStartPoint(rc);
        checkout.setCreateBranch(true);
        checkout.call();

        final Status status = checkout.getResult().getStatus();

        if (status != Status.OK) {
            throw new MojoExecutionException(
                    String.format("Invalid checkout state (%s) of dependency.", status));
        }
    } catch (IOException | InvalidRefNameException | RefAlreadyExistsException | RefNotFoundException ex) {
        throw new MojoExecutionException(String.format("Failed to check out dependency for %s.%s",
                dependency.getGroupId(), dependency.getArtifactId()), ex);
    }
}