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:com.tenxdev.ovcs.command.PushCommand.java

License:Open Source License

/**
 * {@inheritDoc}//from   ww w  .jav a2 s  .c  o  m
 */
@Override
public void execute(final String... args) throws OvcsException {
    if (args.length != 1) {
        throw new UsageException(USAGE);
    }
    final FileRepository repository = getRepoForCurrentDir();
    try {
        doPush(new Git(repository));
    } catch (final GitAPIException e) {
        throw new OvcsException("Unable to push: " + e.getMessage(), e);
    } finally {
        repository.close();
    }
}

From source file:com.tenxdev.ovcs.command.StatusCommand.java

License:Open Source License

private void displayChanges(final FileRepository repository) throws OvcsException {
    try {//from  w  ww  .j  a v  a 2s .  c o  m
        final Status status = new Git(repository).status().call();
        if (status.isClean()) {
            System.out.println("No changes.");
        } else {
            displayChanges("Added", status.getUntracked());
            displayChanges("Modified", status.getModified());
            displayChanges("Removed", status.getMissing());
        }
    } catch (NoWorkTreeException | GitAPIException e) {
        throw new OvcsException("Unable to query git status: " + e.getMessage(), e);
    }
}

From source file:com.tenxdev.ovcs.command.SyncCommand.java

License:Open Source License

/**
 * {@inheritDoc}// ww w  .j  a  v a 2 s.  co m
 */
@Override
public void execute(final String... args) throws OvcsException {
    if (args.length != 1) {
        throw new UsageException(USAGE);
    }
    final FileRepository repository = getRepoForCurrentDir();
    try {
        final File workingDirectory = repository.getWorkTree();
        new Git(repository).pull().setProgressMonitor(new TextProgressMonitor()).call();
        try (Connection conn = getDbConnectionForRepo(repository)) {
            writeSchemaObjects(conn, workingDirectory.toPath());
            commitAndPush();
        } catch (final SQLException e) {
            throw new OvcsException("Unable to connect to database: " + e.getMessage(), e);
        }
    } catch (final GitAPIException e) {
        throw new OvcsException("Unable to synchronize with remote repository: " + e.getMessage(), e);
    } finally {
        repository.close();
    }
}

From source file:com.thoughtworks.go.service.ConfigRepository.java

License:Apache License

@Autowired
public ConfigRepository(SystemEnvironment systemEnvironment) throws IOException {
    this.systemEnvironment = systemEnvironment;
    workingDir = this.systemEnvironment.getConfigRepoDir();
    File configRepoDir = new File(workingDir, ".git");
    gitRepo = new FileRepositoryBuilder().setGitDir(configRepoDir).build();
    gitRepo.getConfig().setInt("gc", null, "auto", 0);
    git = new Git(gitRepo);
}

From source file:com.uber.stream.kafka.mirrormaker.controller.core.GitBackUpHandler.java

License:Apache License

public void writeToFile(String fileName, String data) throws Exception {
    Repository backupRepo = null;/*www . j  a va  2  s . com*/
    BufferedWriter output = null;
    Git git = null;
    Git result = null;
    try {
        try {
            FileUtils.deleteDirectory(new File(localPath));
        } catch (IOException e) {
            LOGGER.error("Error deleting exisiting backup directory");
            throw e;
        }

        try {
            result = Git.cloneRepository().setURI(remotePath).setDirectory(new File(localPath)).call();
        } catch (Exception e) {
            LOGGER.error("Error cloning backup git repo");
            throw e;
        }

        try {
            backupRepo = new FileRepository(localPath + "/.git");
        } catch (IOException e) {
            throw e;
        }

        git = new Git(backupRepo);
        File myfile = new File(localPath + "/" + fileName);

        try {
            output = new BufferedWriter(new FileWriter(myfile));
            output.write(data);
            output.flush();
        } catch (IOException e) {
            LOGGER.error("Error writing backup to the file with name " + fileName);
            throw e;
        }

        try {
            git.add().addFilepattern(".").call();
        } catch (GitAPIException e) {
            LOGGER.error("Error adding files to git");
            throw e;
        }

        try {
            git.commit().setMessage("Taking backup on " + new Date()).call();

        } catch (GitAPIException e) {
            LOGGER.error("Error commiting files to git");
            throw e;
        }

        try {
            git.push().call();
        } catch (GitAPIException e) {
            LOGGER.error("Error pushing files to git");
            throw e;
        }
    } catch (Exception e) {
        throw e;
    } finally {
        output.close();
        git.close();
        if (result != null)
            result.getRepository().close();
        backupRepo.close();
    }
}

From source file:com.verigreen.collector.common.EmailSender.java

License:Apache License

public String getCommitMessage(String commitId) {
    String commitMessage = null;/*from   ww w.  j  a v  a  2s .  c om*/
    try {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        String repoPath = VerigreenNeededLogic.properties.getProperty("git.repositoryLocation");
        Repository repo = builder.setGitDir(new File(repoPath)).setMustExist(true).build();
        Git git = new Git(repo);
        Iterable<RevCommit> log = git.log().call();
        Iterator<RevCommit> iterator = log.iterator();
        while (commitMessage == null && iterator.hasNext()) {
            RevCommit rev = iterator.next();
            String commit = rev.getName().substring(0, 7);
            if (commit.equals(commitId)) {
                commitMessage = rev.getFullMessage();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return commitMessage;
}

From source file:com.verigreen.collector.rest.CommitMessage.java

License:Apache License

@GET
@Produces(MediaType.APPLICATION_JSON)//  www.jav  a  2 s. c  om
public static Response get() {
    Map<String, String> logMessages = new HashMap<>();
    try {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repo = builder
                .setGitDir(new File(VerigreenNeededLogic.properties.getProperty("git.repositoryLocation")))
                .setMustExist(true).build();
        Git git = new Git(repo);
        Iterable<RevCommit> log = git.log().call();
        for (Iterator<RevCommit> iterator = log.iterator(); iterator.hasNext();) {
            RevCommit rev = iterator.next();
            logMessages.put(rev.getName(), rev.getFullMessage());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Response.status(Status.OK).entity(logMessages).build();
}

From source file:com.verigreen.jgit.JGitOperator.java

License:Apache License

public JGitOperator(String repositoryPath) {

    try {/* w w w  .  ja v a 2 s . c  om*/
        // need to verify repo was created successfully - this is not enough
        /*if(!repositoryPath.contains("\\.git") && !repositoryPath.equals("."))
        {
           repositoryPath=repositoryPath.concat("\\.git");
        }*/
        _repo = new FileRepository(repositoryPath);
        _git = new Git(_repo);

    } catch (IOException e) {
        throw new RuntimeException(
                String.format("Failed creating git repository for path [%s]", repositoryPath), e);
    }
}

From source file:com.wadpam.gimple.GimpleMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try {/*ww  w .  j a  va 2s  . com*/
        Repository repo = builder.setGitDir(new File(new File(gitDir), ".git")).readEnvironment().findGitDir()
                .build();
        final String branch = repo.getBranch();
        if (null != branch) {
            if (!currentVersion.endsWith(SUFFIX_SNAPSHOT)) {
                throw new MojoExecutionException("Maven project version not in SNAPSHOT: " + currentVersion);
            }

            getLog().info("gimple executing on " + gitDir);
            getLog().info("branch " + branch);

            if (null == releaseVersion) {
                releaseVersion = currentVersion.substring(0,
                        currentVersion.length() - SUFFIX_SNAPSHOT.length());
            }
            getLog().info(
                    "Transforming version from " + currentVersion + " to release version " + releaseVersion);

            Git git = new Git(repo);
            StatusCommand statusCommand = git.status();
            Status status = statusCommand.call();

            if (!status.isClean()) {
                throw new MojoExecutionException("Git project is not clean: " + status.getUncommittedChanges());
            }

            // versions:set releaseVersion
            transformPomVersions(git, releaseVersion);

            // tag release
            Ref tagRef = git.tag().setMessage(GIMPLE_MAVEN_PLUGIN + "tagging release " + releaseVersion)
                    .setName(releaseVersion).call();

            // next development version
            if (null == nextVersion) {
                nextVersion = getNextDevelopmentVersion(releaseVersion);
            }

            // versions:set nextVersion
            RevCommit nextRef = transformPomVersions(git, nextVersion);

            // push it all
            String developerConnection = mavenProject.getScm().getDeveloperConnection();
            if (developerConnection.startsWith(PREFIX_SCM_GIT)) {
                developerConnection = developerConnection.substring(PREFIX_SCM_GIT.length());
            }
            RefSpec spec = new RefSpec(branch + ":" + branch);
            git.push().setRemote(developerConnection).setRefSpecs(spec).add(tagRef).call();
        }
    } catch (IOException e) {
        throw new MojoExecutionException("executing", e);
    } catch (GitAPIException e) {
        throw new MojoExecutionException("status", e);
    }
}

From source file:controller.GitCommandsController.java

public void pullCommand() {
    ExecutorService service = Executors.newSingleThreadExecutor();
    try {/*from www .  j a  v  a 2s.  co m*/
        Task task = new Task() {
            @Override
            protected Object call() throws Exception {
                commandStatus = GitFacade.pullRepo(parentController.repository);
                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 PULL:", commandStatus);
            }
        });
        task.setOnFailed(new EventHandler() {

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

    } catch (Exception ex) {
        Logger.getLogger(MainWindowController.class.getName()).log(Level.SEVERE, null, ex);
    }
}