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.peergreen.configuration.git.GitConfiguration.java

License:Apache License

@Override
public ConfigRepository getRepository(String name) throws RepositoryException {
    check();/*  www  .  ja v  a 2s  .  com*/

    // Sets the git directory from the given repository name
    File repositoryDir = new File(rootDirectory, name);
    File gitDir = new File(repositoryDir, Constants.DOT_GIT);

    // Find the git directory
    FileRepository fileRepository = null;
    try {
        fileRepository = new FileRepositoryBuilder() //
                .setGitDir(gitDir) // --git-dir if supplied, no-op if null
                .readEnvironment() // scan environment GIT_* variables
                .findGitDir().build();
    } catch (IOException e) {
        throw new RepositoryException("Unable to find a repository for the path '" + name + "'.", e);
    }

    // do not exist yet on the filesystem, create all the directories
    if (!gitDir.exists()) {
        try {
            fileRepository.create();
        } catch (IOException e) {
            throw new RepositoryException("Cannot create repository", e);
        }

        // Create the first commit in order to initiate the repository.
        Git git = new Git(fileRepository);
        CommitCommand commit = git.commit();
        try {
            commit.setMessage("Initial setup for the git configuration of '" + name + "'").call();
        } catch (GitAPIException e) {
            throw new RepositoryException("Cannot init the git repository '" + name + "'", e);
        }

    }

    return new GitRepository(fileRepository);

}

From source file:com.peergreen.configuration.git.GitManager.java

License:Apache License

public GitManager(Repository repository) {
    this.repository = repository;
    this.git = new Git(repository);
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

private void importToGITRepo(RepoDetail repodetail, ApplicationInfo appInfo, File appDir) throws Exception {
    if (debugEnabled) {
        S_LOGGER.debug("Entering Method  SCMManagerImpl.importToGITRepo()");
    }//w ww.j  a va  2 s .  co m
    boolean gitExists = false;
    if (new File(appDir.getPath() + FORWARD_SLASH + DOT + GIT).exists()) {
        gitExists = true;
    }
    try {
        //For https and ssh
        additionalAuthentication(repodetail.getPassPhrase());

        CredentialsProvider cp = new UsernamePasswordCredentialsProvider(repodetail.getUserName(),
                repodetail.getPassword());

        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(appDir).readEnvironment().findGitDir().build();
        String dirPath = appDir.getPath();
        File gitignore = new File(dirPath + GITIGNORE_FILE);
        gitignore.createNewFile();
        if (gitignore.exists()) {
            String contents = FileUtils.readFileToString(gitignore);
            if (!contents.isEmpty() && !contents.contains(DO_NOT_CHECKIN_DIR)) {
                String source = NEWLINE + DO_NOT_CHECKIN_DIR + NEWLINE;
                OutputStream out = new FileOutputStream((dirPath + GITIGNORE_FILE), true);
                byte buf[] = source.getBytes();
                out.write(buf);
                out.close();
            } else if (contents.isEmpty()) {
                String source = NEWLINE + DO_NOT_CHECKIN_DIR + NEWLINE;
                OutputStream out = new FileOutputStream((dirPath + GITIGNORE_FILE), true);
                byte buf[] = source.getBytes();
                out.write(buf);
                out.close();
            }
        }

        Git git = new Git(repository);

        InitCommand initCommand = Git.init();
        initCommand.setDirectory(appDir);
        git = initCommand.call();

        AddCommand add = git.add();
        add.addFilepattern(".");
        add.call();

        CommitCommand commit = git.commit().setAll(true);
        commit.setMessage(repodetail.getCommitMessage()).call();
        StoredConfig config = git.getRepository().getConfig();

        config.setString(REMOTE, ORIGIN, URL, repodetail.getRepoUrl());
        config.setString(REMOTE, ORIGIN, FETCH, REFS_HEADS_REMOTE_ORIGIN);
        config.setString(BRANCH, MASTER, REMOTE, ORIGIN);
        config.setString(BRANCH, MASTER, MERGE, REF_HEAD_MASTER);
        config.save();

        try {
            PushCommand pc = git.push();
            pc.setCredentialsProvider(cp).setForce(true);
            pc.setPushAll().call();
        } catch (Exception e) {
            git.getRepository().close();
            PomProcessor appPomProcessor = new PomProcessor(new File(appDir, appInfo.getPhrescoPomFile()));
            appPomProcessor.removeProperty(Constants.POM_PROP_KEY_SRC_REPO_URL);
            appPomProcessor.save();
            throw e;
        }

        if (appInfo != null) {
            updateSCMConnection(appInfo, repodetail.getRepoUrl());
        }
        git.getRepository().close();
    } catch (Exception e) {
        Exception s = e;
        resetLocalCommit(appDir, gitExists, e);
        throw s;
    }
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

private void resetLocalCommit(File appDir, boolean gitExists, Exception e) throws PhrescoException {
    try {/*from   w ww . j a  va2  s  .  c  om*/
        if (gitExists == true && e.getLocalizedMessage().contains("not authorized")) {
            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            Repository repository = builder.setGitDir(appDir).readEnvironment().findGitDir().build();
            Git git = new Git(repository);

            InitCommand initCommand = Git.init();
            initCommand.setDirectory(appDir);
            git = initCommand.call();

            ResetCommand reset = git.reset();
            ResetType mode = ResetType.SOFT;
            reset.setRef("HEAD~1").setMode(mode);
            reset.call();

            git.getRepository().close();
        }
    } catch (Exception pe) {
        new PhrescoException(pe);
    }
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

public List<RepoFileInfo> getGITCommitableFiles(File path) throws IOException, GitAPIException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(path).readEnvironment().findGitDir().build();
    Git git = new Git(repository);
    List<RepoFileInfo> fileslist = new ArrayList<RepoFileInfo>();
    InitCommand initCommand = Git.init();
    initCommand.setDirectory(path);//  w w  w . j  a v  a2  s . c om
    git = initCommand.call();
    Status status = git.status().call();

    Set<String> added = status.getAdded();
    Set<String> changed = status.getChanged();
    Set<String> conflicting = status.getConflicting();
    Set<String> missing = status.getMissing();
    Set<String> modified = status.getModified();
    Set<String> removed = status.getRemoved();
    Set<String> untracked = status.getUntracked();

    if (!added.isEmpty()) {
        for (String add : added) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + add;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("A");
            fileslist.add(repoFileInfo);
        }
    }

    if (!changed.isEmpty()) {
        for (String change : changed) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + change;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("M");
            fileslist.add(repoFileInfo);
        }
    }

    if (!conflicting.isEmpty()) {
        for (String conflict : conflicting) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + conflict;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("C");
            fileslist.add(repoFileInfo);
        }
    }

    if (!missing.isEmpty()) {
        for (String miss : missing) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + miss;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("!");
            fileslist.add(repoFileInfo);
        }
    }

    if (!modified.isEmpty()) {
        for (String modify : modified) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + modify;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("M");
            fileslist.add(repoFileInfo);
        }
    }

    if (!removed.isEmpty()) {
        for (String remove : removed) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + remove;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("D");
            fileslist.add(repoFileInfo);
        }
    }

    if (!untracked.isEmpty()) {
        for (String untrack : untracked) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + untrack;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("?");
            fileslist.add(repoFileInfo);
        }
    }
    git.getRepository().close();
    return fileslist;
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

public List<String> getSvnLogMessages(String Url, String userName, String Password, String repoType,
        String appDirName) throws PhrescoException {
    List<String> logMessages = new ArrayList<String>();
    if (repoType.equalsIgnoreCase(SVN)) {
        setupLibrary();//from w ww .j  a va 2s  . c  o  m
        long startRevision = 0;
        long endRevision = -1; //HEAD (the latest) revision
        SVNRepository repository = null;
        try {
            repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(Url));
            ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(userName,
                    Password);
            repository.setAuthenticationManager(authManager);
            Collection logEntries = null;
            logEntries = repository.log(new String[] { "" }, null, startRevision, endRevision, false, true);
            for (Iterator entries = logEntries.iterator(); entries.hasNext();) {
                SVNLogEntry logEntry = (SVNLogEntry) entries.next();
                logMessages.add(logEntry.getMessage());
            }
        } catch (SVNException e) {
            throw new PhrescoException(e);
        } finally {
            if (repository != null) {
                repository.closeSession();
            }
        }
    } else if (repoType.equalsIgnoreCase(GIT)) {
        try {
            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            String dotGitDir = Utility.getProjectHome() + appDirName + File.separator + DOT_GIT;
            File dotGitDirectory = new File(dotGitDir);
            if (!dotGitDirectory.exists()) {
                dotGitDir = Utility.getProjectHome() + appDirName + File.separator + appDirName + File.separator
                        + DOT_GIT;
                dotGitDirectory = new File(dotGitDir);
            }
            if (!dotGitDir.isEmpty()) {
                Repository repo = builder.setGitDir(dotGitDirectory).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();
                    if (!rev.getFullMessage().isEmpty()) {
                        logMessages.add(rev.getFullMessage());
                    }
                }
                repo.close();
            }
        } catch (GitAPIException ge) {
            throw new PhrescoException(ge);
        } catch (IOException ioe) {
            throw new PhrescoException(ioe);
        }
    }
    return logMessages;
}

From source file:com.puppycrawl.tools.checkstyle.CommitValidationTest.java

License:Open Source License

private static RevCommitsPair resolveRevCommitsPair(Repository repo) {
    RevCommitsPair revCommitIteratorPair;
    try {//  w  w  w  .j a va2s  . c om
        Iterator<RevCommit> first;
        Iterator<RevCommit> second;

        RevWalk revWalk = new RevWalk(repo);

        ObjectId headId = repo.resolve(Constants.HEAD);
        RevCommit headCommit = revWalk.parseCommit(headId);

        if (isMergeCommit(headCommit)) {
            RevCommit firstParent = headCommit.getParent(0);
            RevCommit secondParent = headCommit.getParent(1);

            first = new Git(repo).log().add(firstParent).call().iterator();
            second = new Git(repo).log().add(secondParent).call().iterator();
        } else {
            first = new Git(repo).log().call().iterator();
            second = Collections.emptyIterator();
        }

        revCommitIteratorPair = new RevCommitsPair(new OmitMergeCommitsIterator(first),
                new OmitMergeCommitsIterator(second));
    } catch (GitAPIException | IOException e) {
        revCommitIteratorPair = new RevCommitsPair();
    }

    return revCommitIteratorPair;
}

From source file:com.rimerosolutions.ant.git.AbstractGitRepoAwareTask.java

License:Apache License

@Override
public final void execute() {
    try {/*from  www  . j a va2  s.co m*/
        try {
            Repository repository = new RepositoryBuilder().readEnvironment().findGitDir(getDirectory())
                    .build();
            git = new Git(repository);
        } catch (IOException ioe) {
            String errorMsg = "Specified path (%s) doesn't seem to be a git repository.";

            throw new BuildException(String.format(errorMsg, getDirectory().getAbsolutePath()), ioe);
        }

        doExecute();

    } catch (GitBuildException e) {
        log(e, Project.MSG_ERR);

        if (failOnError) {
            throw new BuildException(e);
        }
    } finally {
        if (git != null) {
            git.getRepository().close();
        }
    }
}

From source file:com.sap.dirigible.ide.jgit.connector.JGitConnector.java

License:Open Source License

public JGitConnector(Repository repository) throws IOException {
    this.repository = repository;
    this.git = new Git(repository);
}

From source file:com.sbt.plugins.MyMojo.java

License:Apache License

private void writeLogsInWriter(Writer writer) throws IOException, GitAPIException {
    Repository existingRepo = new FileRepositoryBuilder().setGitDir(new File("./.git")).build();
    Git git = new Git(existingRepo);
    LogCommand logCommand = git.log();/*from ww  w.j av a2s .  c  o  m*/
    Iterable<RevCommit> logs = logCommand.call();
    for (RevCommit current : logs) {
        writer.write(current.getName() + ": " + current.getFullMessage());
        writer.write(LINE_SEPARATOR);
    }
}