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

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

Introduction

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

Prototype

public Git(Repository repo) 

Source Link

Document

Construct a new org.eclipse.jgit.api.Git object which can interact with the specified git repository.

Usage

From source file:controller.GitCommandsController.java

public void commitCommand() {
    ExecutorService service = Executors.newSingleThreadExecutor();
    TextInputDialog dialog = new TextInputDialog("Commit przy pomocy COG");
    dialog.setTitle("Wiadomosc commitu");
    dialog.setHeaderText("Podaj wiadomosc commitu");

    result = dialog.showAndWait();/*from w  w w .  jav a 2 s . c om*/
    if (result.isPresent()) {
        try {
            Task task = new Task() {
                @Override
                protected Object call() throws Exception {
                    GitFacade.commitRepo(parentController.repository, result.get());
                    parentController.loadCurrentRepository(new Git(parentController.repository));
                    return commandStatus;
                }
            };
            task.setOnSucceeded(new EventHandler() {
                @Override
                public void handle(Event event) {
                    parentController.loadCurrentRepositoryInGUI();
                    parentController.getScene().setCursor(Cursor.DEFAULT);
                    HighlighterFacade.clearWebView(parentController.sourceCodeView);
                    parentController.showGitResultDialog("GIT COMMIT:", "Commit command executed successfully");
                }
            });
            task.setOnFailed(new EventHandler() {

                @Override
                public void handle(Event event) {
                    parentController.getScene().setCursor(Cursor.DEFAULT);
                    parentController.showGitErrorDialog("GIT COMMIT ERROR", "Nie powiodo si");
                }
            });
            parentController.getScene().setCursor(Cursor.WAIT);
            service.execute(task);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:controller.GitCommandsController.java

public void pushCommand(String uname, String pass) {
    ExecutorService service = Executors.newSingleThreadExecutor();
    this.username = uname;
    this.password = pass;

    try {/*from  ww  w  .ja v  a  2 s.co  m*/
        Task task = new Task() {
            @Override
            protected Object call() throws Exception {

                pushResult = GitFacade.pushRepo(parentController.repository, username, password);
                parentController.loadCurrentRepository(new Git(parentController.repository));
                return commandStatus;
            }
        };
        task.setOnSucceeded(new EventHandler() {
            @Override
            public void handle(Event event) {
                parentController.loadCurrentRepositoryInGUI();
                parentController.getScene().setCursor(Cursor.DEFAULT);
                parentController.showGitResultDialog("GIT PUSH:", pushResult);
            }
        });
        task.setOnFailed(new EventHandler() {

            @Override
            public void handle(Event event) {
                parentController.getScene().setCursor(Cursor.DEFAULT);
                parentController.showGitErrorDialog("GIT PUSH ERROR", "Nie powiodo si");
            }
        });
        parentController.getScene().setCursor(Cursor.WAIT);
        service.execute(task);
    } catch (Exception ex) {
        parentController.showGitResultDialog("GIT PUSH:", ex.getMessage());
        Logger.getLogger(MainWindowController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:de.andreasgiemza.jgeagle.repo.rcs.JGit.java

License:Open Source License

/**
 *
 * @param directory/*from ww  w  . j  a  va 2s. c o  m*/
 * @throws IOException
 * @throws GitAPIException
 */
public JGit(Path directory) throws IOException, GitAPIException {
    repository = new FileRepository(directory.toFile());
    git = new Git(repository);
}

From source file:de.br0tbox.gitfx.ui.controllers.ProjectsController.java

License:Apache License

private void addProject(File file, String name, boolean fromFile) {
    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository;//from  w w  w .  j  a  v a2 s.  com
    try {
        repository = builder.setGitDir(file).readEnvironment().findGitDir().build();
        final Git git = new Git(repository);
        final GitFxProject gitFxProject = new GitFxProject(git);
        final ProjectModel projectModel = new ProjectModel(gitFxProject);
        if (name == null) {
            projectModel.setProjectName(new File(file.getParent()).getName());
        } else {
            projectModel.setProjectName(name);
        }
        projectModel.setCurrentBranch(gitFxProject.getGit().getRepository().getBranch());
        projectModel.setChanges(gitFxProject.getUncommitedChangesNumber());
        projectModel.setPath(file.getAbsolutePath());
        repositorySyncService.startWatchingRepository(projectModel);
        projectList.getItems().add(projectModel);
        if (!fromFile) {
            projectPersistentService
                    .save(new PersistentProject(projectModel.getPath(), projectModel.getProjectName()));
        }
    } catch (final IOException e) {
        LOGGER.error(e);
    }

}

From source file:de.egore911.versioning.deployer.performer.PerformCheckout.java

License:Open Source License

private static void performGit(String target, String url) {
    String tmp = target + File.separatorChar + "checkout";
    try {/*from   w w  w . ja  v  a2s.  c  o m*/
        File tmpDir = new File(tmp);
        try {
            if (!new File(tmp + "/.git").exists()) {
                Git.cloneRepository().setURI(url).setDirectory(tmpDir).call();
            } else {
                FileRepository fileRepository = new FileRepository(tmp + "/.git");
                Git git = new Git(fileRepository);
                git.pull().setRebase(true).call();
            }
            FileUtils.copyDirectory(tmpDir, new File(target));
        } finally {
            FileUtils.deleteDirectory(tmpDir);
        }
    } catch (GitAPIException | IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:de.fau.osr.core.vcs.impl.GitVcsClient.java

License:Open Source License

/**
 * @param repositoryURI/*from w  ww  . j av a2  s .  c  o  m*/
 * @author Gayathery
 * @throws IOException
 */
public GitVcsClient(String repositoryURI) throws IOException {
    super(repositoryURI);
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    repo = builder.setGitDir(new File(repositoryURI)).setMustExist(true).build();
    git = new Git(repo);
}

From source file:de.felixschulze.gradle.helper.GitHelper.java

License:Open Source License

public int numberOfCommits() throws GitAPIException {
    Git git = new Git(repository);
    Iterable<RevCommit> logs = git.log().call();
    Iterator<RevCommit> i = logs.iterator();
    int numberOfCommits = 0;
    while (i.hasNext()) {
        numberOfCommits++;/*from  w  w w  .j a  va2s.c  o  m*/
        i.next();
    }
    return numberOfCommits;
}

From source file:de.fkoeberle.autocommit.git.GitRepositoryAdapter.java

License:Open Source License

@Override
public void commit() throws IOException {
    Git git = new Git(repository);
    stageForCommit(git, FilesToAdd.ADDED_OR_MODIFIED);
    stageForCommit(git, FilesToAdd.REMOVED_OR_MODIFIED);

    String message = buildCommitMessage();
    if (message != null) {
        commitStagedFiles(git, message);
    }/*from  w  w w .j  av a2  s  .  c  o  m*/
}

From source file:de.fraunhofer.ipa.CobPipelineProperty.java

License:Open Source License

@JavaScriptMethod
public JSONObject doGeneratePipeline() throws Exception {
    JSONObject response = new JSONObject();
    String message = "";

    // wait until config.xml is updated
    File configFile = new File(Jenkins.getInstance().getRootDir(), "users/" + user.getId() + "/config.xml");
    Date mod = new Date();
    Long start = mod.getTime();/*ww w.  j a  v a2  s .c o  m*/
    Date now;
    do {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        if (configFile.exists()) {
            try {
                mod = new Date(configFile.lastModified());
            } catch (Exception ex) {
            }
        }

        now = new Date();
        if (now.getTime() - start > 30000) {
            throw new Exception("Timeout");
        }
    } while (start.equals(mod.getTime()) || now.getTime() - mod.getTime() > 15000);

    try {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("user_name", user.getId());
        data.put("server_name", getMasterName());
        data.put("email", this.email);
        data.put("committer_email_enabled", this.committerEmailEnabled);
        Map<String, Object> repos = new HashMap<String, Object>();
        for (RootRepository rootRepo : this.rootRepos) {
            Map<String, Object> repo = new HashMap<String, Object>();
            repo.put("type", rootRepo.type);
            repo.put("url", rootRepo.url);
            repo.put("version", rootRepo.branch);
            repo.put("poll", rootRepo.poll);
            repo.put("ros_distro", rootRepo.getRosDistro());
            repo.put("prio_ubuntu_distro", rootRepo.getPrioUbuntuDistro());
            repo.put("prio_arch", rootRepo.getPrioArch());
            repo.put("regular_matrix", rootRepo.getMatrixDistroArch());
            repo.put("jobs", rootRepo.getJobs());
            repo.put("robots", rootRepo.robot);

            Map<String, Object> deps = new HashMap<String, Object>();
            for (Repository repoDep : rootRepo.getRepoDeps()) {
                Map<String, Object> dep = new HashMap<String, Object>();
                if (repoDep.fork.equals("") || repoDep.fork.equals(null)) {
                    response.put("message", Messages.Pipeline_GenerationNoFork(rootRepo.fullName));
                    response.put("status",
                            "<font color=\"red\">" + Messages.Pipeline_GenerationFailure() + "</font>");
                    return response;
                }
                if (repoDep.name.equals("") || repoDep.name.equals(null)) {
                    response.put("message", Messages.Pipeline_GenerationNoDepName(rootRepo.fullName));
                    response.put("status",
                            "<font color=\"red\">" + Messages.Pipeline_GenerationFailure() + "</font>");
                    return response;
                }
                if (repoDep.branch.equals("") || repoDep.branch.equals(null)) {
                    response.put("message", Messages.Pipeline_GenerationNoBranch(rootRepo.fullName));
                    response.put("status",
                            "<font color=\"red\">" + Messages.Pipeline_GenerationFailure() + "</font>");
                    return response;
                }
                dep.put("type", repoDep.type);
                dep.put("url", repoDep.url);
                dep.put("version", repoDep.branch);
                dep.put("poll", repoDep.poll);
                dep.put("test", repoDep.test);
                deps.put(repoDep.name, dep);
            }
            repo.put("dependencies", deps);

            repos.put(rootRepo.fullName, repo);
        }
        data.put("repositories", repos);
        Yaml yaml = new Yaml();
        yaml.dump(data, getPipelineConfigFile());
        LOGGER.log(Level.INFO, "Created " + getPipelineConfigFilePath().getAbsolutePath()); //TODO

    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Failed to save " + getPipelineConfigFilePath().getAbsolutePath(), e); //TODO
    }

    // clone/pull configuration repository
    File configRepoFolder = new File(Jenkins.getInstance()
            .getDescriptorByType(CobPipelineProperty.DescriptorImpl.class).getConfigFolder(), "jenkins_config");
    String configRepoURL = "git@github.com:" + Jenkins.getInstance()
            .getDescriptorByType(CobPipelineProperty.DescriptorImpl.class).getPipelineReposOwner()
            + "/jenkins_config.git";
    Git git = new Git(new FileRepository(configRepoFolder + "/.git"));

    // check if configuration repository exists
    if (!configRepoFolder.isDirectory()) {
        try {
            Git.cloneRepository().setURI(configRepoURL).setDirectory(configRepoFolder).call();
            LOGGER.log(Level.INFO, "Successfully cloned configuration repository from " + configRepoURL); //TODO
        } catch (Exception ex) {
            LOGGER.log(Level.WARNING, "Failed to clone configuration repository", ex); //TODO
        }
    } else {
        try {
            git.pull().call();
            LOGGER.log(Level.INFO, "Successfully pulled configuration repository from " + configRepoURL); //TODO
        } catch (Exception ex) {
            LOGGER.log(Level.WARNING, "Failed to pull configuration repository", ex); //TODO
        }
    }

    // copy pipeline-config.yaml into repository
    File configRepoFile = new File(configRepoFolder, getMasterName() + "/" + user.getId() + "/");
    if (!configRepoFile.isDirectory())
        configRepoFile.mkdirs();
    String[] cpCommand = { "cp", "-f", getPipelineConfigFilePath().getAbsolutePath(),
            configRepoFile.getAbsolutePath() };

    Runtime rt = Runtime.getRuntime();
    Process proc;
    BufferedReader readIn, readErr;
    String s, feedback;
    proc = rt.exec(cpCommand);
    readIn = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    readErr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
    feedback = "";
    while ((s = readErr.readLine()) != null)
        feedback += s + "\n";
    if (feedback.length() != 0) {
        LOGGER.log(Level.WARNING, "Failed to copy " + getPipelineConfigFilePath().getAbsolutePath()
                + " to config repository: " + configRepoFile.getAbsolutePath()); //TODO
        LOGGER.log(Level.WARNING, feedback); //TODO
    } else {
        LOGGER.log(Level.INFO, "Successfully copied " + getPipelineConfigFilePath().getAbsolutePath()
                + " to config repository: " + configRepoFile.getAbsolutePath()); //TODO
    }

    // add
    try {
        git.add().addFilepattern(getMasterName() + "/" + user.getId() + "/pipeline_config.yaml").call();
        LOGGER.log(Level.INFO, "Successfully added file to configuration repository"); //TODO
    } catch (Exception e) {
        LOGGER.log(Level.WARNING,
                "Failed to add " + getMasterName() + "/" + user.getId() + "/pipeline_config.yaml", e); //TODO
    }

    // commit
    try {
        git.commit().setMessage("Updated pipeline configuration for " + user.getId()).call();
    } catch (Exception e) {
        LOGGER.log(Level.WARNING,
                "Failed to commit change in " + getMasterName() + "/" + user.getId() + "/pipeline_config.yaml",
                e); //TODO
    }

    // push
    try {
        git.push().call();
        LOGGER.log(Level.INFO, "Successfully pushed configuration repository"); //TODO
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Failed to push configuration repository", e); //TODO
    }

    // trigger Python job generation script
    String[] generationCall = {
            new File(Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class)
                    .getConfigFolder(), "jenkins_setup/scripts/generate_buildpipeline.py").toString(),
            "-m", Jenkins.getInstance().getRootUrl(), "-l",
            Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class)
                    .getJenkinsLogin(),
            "-p",
            Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class)
                    .getJenkinsPassword(),
            "-c",
            Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class)
                    .getConfigFolder(),
            "-o",
            Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class)
                    .getPipelineReposOwner(),
            "-t", Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class)
                    .getTarballLocation(),
            "-u", user.getId() };

    proc = rt.exec(generationCall);
    readIn = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    readErr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
    feedback = "";
    while ((s = readErr.readLine()) != null)
        feedback += s + "\n";
    if (feedback.length() != 0) {
        LOGGER.log(Level.WARNING, "Failed to generate pipeline: "); //TODO
        LOGGER.log(Level.WARNING, feedback);
        response.put("message", feedback.replace("\n", "<br/>"));
        response.put("status", "<font color=\"red\">" + Messages.Pipeline_GenerationFailure() + "</font>");
        return response;
    } else {
        feedback = "";
        while ((s = readIn.readLine()) != null)
            feedback += s + "\n";
        if (feedback.length() != 0) {
            LOGGER.log(Level.INFO, feedback);
            LOGGER.log(Level.INFO, "Successfully generated pipeline"); //TODO
            message += feedback;
        }
    }
    response.put("message", message.replace("\n", "<br/>"));
    response.put("status", "<font color=\"green\">" + Messages.Pipeline_GenerationSuccess() + "</font>");
    return response;
}

From source file:de.ks.blogging.grav.pages.GravPages.java

License:Apache License

public Git getGit() {
    git.getAndUpdate(git -> {/*from w w  w .  jav a 2  s . com*/
        if (git == null) {
            try {
                Repository repository = new RepositoryBuilder().findGitDir(new File(blog.getPagesDirectory()))
                        .setMustExist(true).build();
                return new Git(repository);
            } catch (Exception e) {
                log.error("Could not get Git ", e);
                return null;
            }
        } else {
            return git;
        }
    });
    return git.get();
}