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.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

public boolean updateProject(RepoDetail repodetail, File updateDir) throws Exception {
    if (debugEnabled) {
        S_LOGGER.debug("Entering Method  SCMManagerImpl.updateproject()");
    }/* ww  w.  ja va  2s  . c om*/
    com.photon.phresco.framework.impl.util.FrameworkUtil.saveCredential(repodetail, null);
    if (SVN.equals(repodetail.getType())) {
        if (debugEnabled) {
            S_LOGGER.debug("SVN type");
        }
        DAVRepositoryFactory.setup();
        SVNClientManager svnClientManager = getSVNClientManager(repodetail.getUserName(),
                repodetail.getPassword());
        if (debugEnabled) {
            S_LOGGER.debug("update SCM Connection " + repodetail.getRepoUrl());
        }
        //          updateSCMConnection(appInfo, repodetail.getRepoUrl());
        // revision = HEAD_REVISION.equals(revision) ? revision
        // : revisionVal;
        if (debugEnabled) {
            S_LOGGER.debug("updateDir SVN... " + updateDir);
            S_LOGGER.debug("Updating...");
        }
        SVNUpdateClient uc = svnClientManager.getUpdateClient();
        uc.doUpdate(updateDir, SVNRevision.parse(repodetail.getRevision()), SVNDepth.UNKNOWN, true, true);
        if (debugEnabled) {
            S_LOGGER.debug("Updated!");
        }
        return true;
    } else if (GIT.equals(repodetail.getType())) {
        if (debugEnabled) {
            S_LOGGER.debug("GIT type");
        }
        //         updateSCMConnection(appInfo, repodetail.getRepoUrl());
        if (debugEnabled) {
            S_LOGGER.debug("updateDir GIT... " + updateDir);
        }
        //for https and ssh
        additionalAuthentication(repodetail.getPassPhrase());

        UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider(
                repodetail.getUserName(), repodetail.getPassword());
        Git git = Git.open(updateDir); // checkout is the folder with .git
        git.pull().setCredentialsProvider(userCredential).call(); // succeeds
        git.getRepository().close();
        if (debugEnabled) {
            S_LOGGER.debug("Updated!");
        }
        return true;
    } else if (BITKEEPER.equals(repodetail.getType())) {
        if (debugEnabled) {
            S_LOGGER.debug("BITKEEPER type");
        }
        updateFromBitKeeperRepo(repodetail.getRepoUrl(), updateDir.getPath());
    } else if (PERFORCE.equals(repodetail.getType())) {
        if (debugEnabled) {
            S_LOGGER.debug("PERFORCE type");
        }
        String baseDir = updateDir.getAbsolutePath();
        perforceSync(repodetail, baseDir, updateDir.getName(), "update");
        //         updateSCMConnection(appInfo, repodetail.getRepoUrl()+repodetail.getStream());
    } else if (TFS.equals(repodetail.getType())) {
        int responseCode = getProjectFromTFS(repodetail, updateDir.getCanonicalPath());
        if (responseCode == -1) {
            return true;
        }
    }

    return false;
}

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

License:Apache License

private void importFromGit(RepoDetail repodetail, File gitImportTemp) throws Exception {
    if (debugEnabled) {
        S_LOGGER.debug("Entering Method  SCMManagerImpl.importFromGit()");
    }// w w  w. j  av a  2 s  .  c  om
    if (StringUtils.isEmpty(repodetail.getBranch())) {
        repodetail.setBranch(MASTER);
    }
    // For https and ssh
    additionalAuthentication(repodetail.getPassPhrase());

    UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider(
            repodetail.getUserName(), repodetail.getPassword());
    Git r = Git.cloneRepository().setDirectory(gitImportTemp).setCredentialsProvider(userCredential)
            .setURI(repodetail.getRepoUrl())
            //         .setProgressMonitor(new TextProgressMonitor())
            .setBranch(repodetail.getBranch()).call();
    r.getRepository().close();
}

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()");
    }/*from w  ww .  ja v  a 2 s .c  om*/
    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 w  w . j  a va  2 s  .  c  o  m
        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);/*from ww  w  .  j a v  a  2 s.co m*/
    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.rest.api.RepositoryService.java

License:Apache License

/**
 * Check git project./*from w w  w  .j a  v  a2  s. c  om*/
 *
 * @param applicationInfo the application info
 * @param setRepoExistForCommit the set repo exist for commit
 * @return true, if successful
 * @throws PhrescoException the phresco exception
 */
private boolean checkGitProject(File workingDir, boolean setRepoExistForCommit) throws PhrescoException {
    setRepoExistForCommit = true;
    String url = "";
    InitCommand initCommand = Git.init();
    initCommand.setDirectory(workingDir);
    Git git = null;
    try {
        git = initCommand.call();
    } catch (GitAPIException e) {
        throw new PhrescoException(e);
    }

    Config storedConfig = git.getRepository().getConfig();
    url = storedConfig.getString(REMOTE, ORIGIN, URL);
    if (StringUtils.isEmpty(url)) {
        File toDelete = git.getRepository().getDirectory();
        try {
            FileUtils.deleteDirectory(toDelete);
        } catch (IOException e) {
            throw new PhrescoException(e);
        }
        setRepoExistForCommit = false;

    }
    git.getRepository().close();

    return setRepoExistForCommit;
}

From source file:com.rimerosolutions.ant.git.tasks.InitTask.java

License:Apache License

@Override
public void execute() {
    try {/* www.jav  a2  s .  c om*/
        Git git = Git.init().setBare(bare).setDirectory(getDirectory()).call();

        git.getRepository().close();
    } catch (GitAPIException e) {
        throw new GitBuildException(MESSAGE_INIT_FAILED, e);
    }
}

From source file:com.romanenco.gitt.git.GitHelper.java

License:Open Source License

/**
 * Current branch/tag name.//from  ww w  . j a v  a  2  s.  c om
 * 
 * @param path
 * @return
 */
public static String currentBranchName(String localPath) {
    try {
        Git git = Git.open(new File(localPath));

        String name = git.getRepository().getBranch();

        if (name.length() == 40) {
            //detached head processing
            Map<String, Ref> refs = git.add().getRepository().getAllRefs();
            Iterator<Entry<String, Ref>> iter = refs.entrySet().iterator();
            while (iter.hasNext()) {
                Entry<String, Ref> entry = iter.next();
                if (entry.getValue().getObjectId().getName().equals(name)) {
                    if (!entry.getKey().equals("HEAD")) { // so bad, will change later...
                        name = entry.getKey();
                        break;
                    }
                }
            }
        }
        return nameReFormat(name);
    } catch (IOException e) {
        GittApp.saveErrorTrace(e);
    }
    return null;
}

From source file:com.romanenco.gitt.git.GitHelper.java

License:Open Source License

/**
 * List all branches and tags in a repo.
 * //from www.  j av a 2  s.  c o m
 * @param branches
 * @param tags
 * @param path
 */
public static void readBranchesAndTags(List<String> refs, String localPath) {
    if (refs == null)
        return;
    try {
        Git git = Git.open(new File(localPath));

        Map<String, Ref> mm = git.getRepository().getAllRefs();
        for (String name : mm.keySet()) {
            if (name.equals("HEAD") || name.startsWith("refs/heads/"))
                continue;
            refs.add(name);
        }

    } catch (Exception e) {
        GittApp.saveErrorTrace(e);
    }
}

From source file:com.stormcloud.ide.api.git.GitManager.java

License:Open Source License

@Override
public IndexState getIndexState(String repository) throws GitManagerException {

    IndexState indexState = new IndexState();

    try {/*ww  w . ja  va2  s .com*/

        Git git = Git.open(new File(repository));

        IndexDiff diff = new IndexDiff(git.getRepository(), "HEAD", new FileTreeIterator(git.getRepository()));

        diff.diff();

        indexState.setAdded(diff.getAdded());
        indexState.setAssumeUnchanged(diff.getAssumeUnchanged());
        indexState.setChanged(diff.getChanged());
        indexState.setConflicting(diff.getConflicting());
        indexState.setIgnoredNotInIndex(diff.getIgnoredNotInIndex());
        indexState.setMissing(diff.getMissing());
        indexState.setModified(diff.getModified());
        indexState.setRemoved(diff.getRemoved());
        indexState.setUntracked(diff.getUntracked());
        indexState.setUntrackedFolders(diff.getUntrackedFolders());

    } catch (IOException e) {
        LOG.error(e);
        throw new GitManagerException(e);
    }

    return indexState;
}