Example usage for org.eclipse.jgit.storage.file FileRepositoryBuilder FileRepositoryBuilder

List of usage examples for org.eclipse.jgit.storage.file FileRepositoryBuilder FileRepositoryBuilder

Introduction

In this page you can find the example usage for org.eclipse.jgit.storage.file FileRepositoryBuilder FileRepositoryBuilder.

Prototype

FileRepositoryBuilder

Source Link

Usage

From source file:com.smartbear.collab.util.ChangeListUtils.java

License:Apache License

public static List<ChangeList> VcsFileRevisionToChangeList(String rootDirectory, ScmToken scmToken,
        Map<VcsFileRevision, CommittedChangeList> commits, Project project) {
    List<ChangeList> changeLists = new ArrayList<ChangeList>();
    ProjectLevelVcsManager projectLevelVcsManager = ProjectLevelVcsManager.getInstance(project);

    for (Map.Entry<VcsFileRevision, CommittedChangeList> commit : commits.entrySet()) {
        VcsFileRevision fileRevision = commit.getKey();
        CommittedChangeList committedChangeList = commit.getValue();

        CommitInfo commitInfo = new CommitInfo(fileRevision.getCommitMessage(), fileRevision.getRevisionDate(),
                fileRevision.getAuthor(), false, fileRevision.getRevisionNumber().asString(), "");
        List<Version> versions = new ArrayList<Version>();
        String scmRepoURL = "";
        String scmRepoUUID = "";
        for (Change change : committedChangeList.getChanges()) {
            String fileContent = "";
            try {
                fileContent = change.getAfterRevision().getContent();
            } catch (VcsException ve) {
                log.severe(scmToken.name() + " error: " + ve.getMessage());
            }/*from   w  w  w  .j ava  2  s . c o  m*/
            ContentRevision baseRevision = change.getBeforeRevision();
            BaseVersion baseVersion;
            if (baseRevision == null) {
                baseVersion = null;
            } else {
                String baseMd5 = "";
                String baseScmPath = getScmPath(rootDirectory, baseRevision.getFile().getPath());
                try {
                    baseMd5 = getMD5(baseRevision.getContent().getBytes());
                } catch (VcsException ve) {
                    log.severe(scmToken.name() + " error: " + ve.getMessage());
                }
                String baseVersionName = "";
                baseVersionName = getScmVersionName(scmToken, baseRevision);
                baseVersion = new BaseVersion(change.getFileStatus().getId(), baseMd5, commitInfo,
                        CollabConstants.SOURCE_TYPE_SCM, baseVersionName, baseScmPath);
            }

            //Version
            String localPath = change.getAfterRevision().getFile().getPath();
            String scmPath = getScmPath(rootDirectory, change.getAfterRevision().getFile().getPath());
            String md5 = getMD5(fileContent.getBytes());
            String action = change.getFileStatus().getId();
            String scmVersionName = getScmVersionName(scmToken, change.getAfterRevision());
            Version version = new Version(scmPath, md5, scmVersionName, localPath, action,
                    CollabConstants.SOURCE_TYPE_SCM, baseVersion);

            versions.add(version);

            if (scmRepoURL.equals("")) {
                switch (scmToken) {
                case SUBVERSION: // TODO: can probably get this in a less hacky way with svnkit, since we need that anyway now?
                    String fullPath = fileRevision.getChangedRepositoryPath().toPresentableString(); // this gives the full path down to the file, so:
                    if (fullPath.endsWith(scmPath) && fullPath.indexOf(scmPath) > 0) {
                        scmRepoURL = fullPath.substring(0, fullPath.indexOf(scmPath) - 1); // -1 to trim off trailing "/"
                    }
                    break;
                case GIT:
                    VcsRoot vcsRoot = projectLevelVcsManager.getVcsRootObjectFor(change.getVirtualFile());
                    FileRepositoryBuilder builder = new FileRepositoryBuilder();
                    try {
                        Repository gitRepo = builder.readEnvironment()
                                .findGitDir(new File(vcsRoot.getPath().getCanonicalPath())).build();
                        Config gitConfig = gitRepo.getConfig();

                        Set<String> remotes = gitConfig.getSubsections("remote");
                        Set<String> remoteURLs = new HashSet<String>();
                        if (remotes.isEmpty()) {
                            // TODO: figure out what existing collab clients use for git repo url for local-only situation
                            scmRepoURL = "git: local-only";
                        } else {
                            for (String remoteName : remotes) {
                                remoteURLs.add(gitConfig.getString("remote", remoteName, "url"));
                            }
                            Iterator<String> urlitr = remoteURLs.iterator();

                            if (remoteURLs.size() == 1) { // the easy case
                                scmRepoURL = urlitr.next();
                            } else {
                                // TODO we have more than one, so figure out what the existing clients do here
                                // for now, just grab the first one
                                scmRepoURL = urlitr.next();
                            }
                        }
                    } catch (Exception e) {
                        log.severe("GIT interaction error: " + e.getMessage());
                    }
                    break;
                default:
                    log.severe("Unsupported SCM: " + scmToken);
                    break;
                }

            }
            if (scmRepoUUID.equals("")) {
                switch (scmToken) {
                case SUBVERSION:
                    if (!scmRepoURL.equals("")) {
                        try {
                            SVNURL svnURL = SVNURL.parseURIEncoded(scmRepoURL);
                            SVNClientManager cm = SVNClientManager.newInstance();
                            SVNWCClient workingCopyClient = cm.getWCClient();
                            SVNInfo svnInfo = workingCopyClient.doInfo(svnURL, SVNRevision.UNDEFINED,
                                    SVNRevision.HEAD);
                            scmRepoUUID = svnInfo.getRepositoryUUID();
                        } catch (SVNException svne) {
                            log.severe("SVN error: " + svne.getMessage());
                        }
                    }
                    break;
                case GIT: // for this, we use the sha1 of the first git commit in the project
                    FileRepositoryBuilder builder = new FileRepositoryBuilder();
                    try {
                        VcsRoot vcsRoot = projectLevelVcsManager.getVcsRootObjectFor(change.getVirtualFile());
                        Repository gitRepo = builder.readEnvironment()
                                .findGitDir(new File(vcsRoot.getPath().getCanonicalPath())).build();
                        Git git = new Git(gitRepo);

                        Iterable<RevCommit> gitCommits = git.log().all().call();
                        Iterator<RevCommit> gitr = gitCommits.iterator();

                        RevCommit firstCommit = null;
                        while (gitr.hasNext()) { // run through log,
                            firstCommit = gitr.next();
                        }
                        if (firstCommit != null) {
                            scmRepoUUID = firstCommit.getName(); // sha1 of first commit in repo, lower-case hexadecimal
                        }
                    } catch (Exception e) {
                        log.severe("GIT interaction error: " + e.getMessage());
                    }

                    break;
                default:
                    log.severe("Unsupported SCM: " + scmToken);
                    break;
                }
            }
        }

        // we might have to do something more sophisticated once we support other SCMs, but for git and svn
        // collab only really needs an URL and some sort of UUID-ish value
        ArrayList<String> scmConnectionParameters = new ArrayList<String>(2);
        scmConnectionParameters.add(scmRepoURL);
        scmConnectionParameters.add(scmRepoUUID);

        ChangeList changeList = new ChangeList(scmToken, scmConnectionParameters, commitInfo, versions);
        changeLists.add(changeList);
    }
    return changeLists;
}

From source file:com.spotify.docker.Git.java

License:Apache License

public Git() throws IOException {
    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    // scan environment GIT_* variables
    builder.readEnvironment();/*  w  ww .j a  v  a  2s .  c  o  m*/
    // scan up the file system tree
    builder.findGitDir();
    // if getGitDir is null, then we are not in a git repository
    repo = builder.getGitDir() == null ? null : builder.build();
}

From source file:com.spotify.docker.Utils.java

License:Apache License

public static String getGitCommitId()
        throws GitAPIException, DockerException, IOException, MojoExecutionException {

    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    builder.readEnvironment(); // scan environment GIT_* variables
    builder.findGitDir(); // scan up the file system tree

    if (builder.getGitDir() == null) {
        throw new MojoExecutionException("Cannot tag with git commit ID because directory not a git repo");
    }/*from  w  w w  . j  a  va2  s . c om*/

    final StringBuilder result = new StringBuilder();
    final Repository repo = builder.build();

    try {
        // get the first 7 characters of the latest commit
        final ObjectId head = repo.resolve("HEAD");
        result.append(head.getName().substring(0, 7));
        final Git git = new Git(repo);

        // append first git tag we find
        for (Ref gitTag : git.tagList().call()) {
            if (gitTag.getObjectId().equals(head)) {
                // name is refs/tag/name, so get substring after last slash
                final String name = gitTag.getName();
                result.append(".");
                result.append(name.substring(name.lastIndexOf('/') + 1));
                break;
            }
        }

        // append '.DIRTY' if any files have been modified
        final Status status = git.status().call();
        if (status.hasUncommittedChanges()) {
            result.append(".DIRTY");
        }
    } finally {
        repo.close();
    }

    return result.length() == 0 ? null : result.toString();
}

From source file:com.streamsimple.rt.srcctl.GitSourceControlAgentTest.java

License:Apache License

private void addCommitToRepo() throws Exception {
    new File(testWatcher.getDir(), "test.txt").createNewFile();

    Repository repository = new FileRepositoryBuilder().readEnvironment().findGitDir(testWatcher.getDir())
            .build();/*w  w w .j  av  a  2 s  .c o m*/

    try (Git git = new Git(repository)) {
        git.commit().setCommitter("tester", "tester@release-tool.io").setMessage("Testing").call();
    }
}

From source file:com.surevine.gateway.scm.git.jgit.JGitGitFacade.java

License:Open Source License

@Override
public void push(final LocalRepoBean repoBean, final String remoteName) throws GitException {
    try {//from  w  w  w.ja  va 2 s .  c  o  m
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(repoBean.getRepoDirectory().toFile()).findGitDir().build();
        Git git = new org.eclipse.jgit.api.Git(repository);

        // dry run the push - if the push cannot be done automatically we have no way to recover so we just log
        // and throw an exception
        PushCommand dryRunPushCommand = git.push();
        dryRunPushCommand.setRemote(remoteName);
        dryRunPushCommand.setDryRun(true);
        Iterable<PushResult> dryRunResult = dryRunPushCommand.call();
        for (PushResult result : dryRunResult) {
            for (RemoteRefUpdate remoteRefUpdate : result.getRemoteUpdates()) {
                switch (remoteRefUpdate.getStatus()) {
                case OK:
                case UP_TO_DATE:
                    continue;
                default:
                    throw new GitException("During a dry run of a push one of the updates would have failed "
                            + "so the push was aborted for repo " + repoBean + " to remote "
                            + dryRunPushCommand.getRemote());
                }
            }
        }

        // if we get to this point the dry run was OK so try the real thing
        PushCommand realPushCommand = git.push();
        realPushCommand.setRemote(remoteName);
        Iterable<PushResult> pushResults = realPushCommand.call();
        for (PushResult result : pushResults) {
            for (RemoteRefUpdate remoteRefUpdate : result.getRemoteUpdates()) {
                switch (remoteRefUpdate.getStatus()) {
                case OK:
                case UP_TO_DATE:
                    continue;
                default:
                    throw new GitException(
                            "Push failed for " + repoBean + " to remote " + dryRunPushCommand.getRemote());
                }
            }
        }
    } catch (GitAPIException | IOException e) {
        LOGGER.error(e);
        throw new GitException(e);
    }
}

From source file:com.surevine.gateway.scm.git.jgit.JGitGitFacade.java

License:Open Source License

@Override
public Map<String, String> getRemotes(final LocalRepoBean repoBean) throws GitException {
    Map<String, String> remotes = new HashMap<String, String>();
    try {/*from   w  w w. java2  s  .com*/
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(repoBean.getGitConfigDirectory().toFile()).findGitDir()
                .build();
        Git git = new org.eclipse.jgit.api.Git(repository);
        StoredConfig config = git.getRepository().getConfig();
        Set<String> remoteNames = config.getSubsections("remote");
        for (String remoteName : remoteNames) {
            remotes.put(remoteName, config.getString("remote", remoteName, "url"));
        }
    } catch (IOException e) {
        LOGGER.error(e);
        throw new GitException(e);
    }
    return remotes;
}

From source file:com.surevine.gateway.scm.git.jgit.JGitGitFacade.java

License:Open Source License

@Override
public void addRemote(final LocalRepoBean repoBean, final String remoteName, final String remoteURL)
        throws GitException {
    try {//from   w w w.  j  a  v  a2  s  .  c  o  m
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(repoBean.getGitConfigDirectory().toFile()).findGitDir()
                .build();
        Git git = new org.eclipse.jgit.api.Git(repository);
        StoredConfig config = git.getRepository().getConfig();
        config.setString("remote", remoteName, "url", remoteURL);
        config.setString("remote", remoteName, "fetch",
                String.format("+refs/heads/*:refs/remotes/%s/*", remoteName));
        config.save();

    } catch (IOException e) {
        LOGGER.error(e);
        throw new GitException(e);
    }
}

From source file:com.surevine.gateway.scm.git.jgit.JGitGitFacade.java

License:Open Source License

@Override
public boolean fetch(final LocalRepoBean repoBean, final String remoteName) throws GitException {
    String remoteToPull = (remoteName != null) ? remoteName : "origin";

    FetchResult result;/*from ww  w  .j a v a  2  s.  co  m*/
    try {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(repoBean.getGitConfigDirectory().toFile()).findGitDir()
                .build();
        Git git = new org.eclipse.jgit.api.Git(repository);
        FetchCommand fetchCommand = git.fetch();
        fetchCommand.setRemote(remoteToPull);
        fetchCommand.setRefSpecs(new RefSpec("+refs/heads/*:refs/heads/*"));
        result = fetchCommand.call();
        repository.close();
    } catch (GitAPIException | IOException e) {
        LOGGER.error(e);
        throw new GitException(e);
    }

    boolean hadUpdates = !result.getTrackingRefUpdates().isEmpty();
    return hadUpdates;
}

From source file:com.surevine.gateway.scm.git.jgit.JGitGitFacade.java

License:Open Source License

@Override
public void tag(final LocalRepoBean repoBean, final String tag) throws GitException {
    try {//from  w ww  .  j  a  v  a  2 s.  co  m
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(repoBean.getGitConfigDirectory().toFile()).findGitDir()
                .build();
        Git git = new org.eclipse.jgit.api.Git(repository);
        TagCommand tagCommand = git.tag();
        tagCommand.setName(tag);
        tagCommand.call();
        repository.close();
    } catch (GitAPIException | IOException e) {
        LOGGER.error(e);
        throw new GitException(e);
    }
}

From source file:com.surevine.gateway.scm.git.jgit.JGitGitFacade.java

License:Open Source License

@Override
public Path bundle(final LocalRepoBean repoBean) throws GitException {
    OutputStream outputStream = null;
    try {//  ww w .j a va2s . c  o m
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(repoBean.getGitConfigDirectory().toFile()).findGitDir()
                .build();
        BundleWriter bundleWriter = new BundleWriter(repository);
        String fileName = StringUtil.cleanStringForFilePath(repoBean.getProjectKey() + "_" + repoBean.getSlug())
                + ".bundle";
        Path outputPath = Paths.get(PropertyUtil.getTempDir(), fileName);
        outputStream = Files.newOutputStream(outputPath);

        Map<String, Ref> refMap = repository.getAllRefs();
        for (Ref ref : refMap.values()) {
            bundleWriter.include(ref);
        }

        bundleWriter.writeBundle(NullProgressMonitor.INSTANCE, outputStream);
        outputStream.close();
        repository.close();
        return outputPath;
    } catch (IOException e) {
        throw new GitException(e);
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ioe) {
                LOGGER.error(ioe);
            }
        }
    }
}