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.searchcode.app.jobs.IndexGitRepoJob.java

private RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName,
        String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);

    try {/*from  www  .  j a  va2 s .co m*/
        Repository localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));

        Ref head = localRepository.getRef("HEAD");

        Git git = new Git(localRepository);
        git.reset();
        git.clean();

        PullCommand pullCmd = git.pull();

        if (useCredentials) {
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }

        pullCmd.call();
        Ref newHEAD = localRepository.getRef("HEAD");

        if (!head.toString().equals(newHEAD.toString())) {
            changed = true;

            // Get the differences between the the heads which we updated at
            // and use these to just update the differences between them
            ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
            ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");

            ObjectReader reader = localRepository.newObjectReader();

            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.reset(reader, oldHead);

            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.reset(reader, newHead);

            List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

            for (DiffEntry entry : entries) {
                if ("DELETE".equals(entry.getChangeType().name())) {
                    deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
                } else {
                    changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
                }
            }
        }

    } catch (IOException | GitAPIException | InvalidPathException ex) {
        changed = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + "\n with message: " + ex.getMessage());
    }

    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}

From source file:com.searchcode.app.jobs.repository.IndexGitHistoryJob.java

public void getGitChangeSets() throws IOException, GitAPIException {
    //Repository localRepository = new FileRepository(new File("./repo/server/.git"));
    Repository localRepository = new FileRepository(new File("./repo/thumbor/.git"));

    Git git = new Git(localRepository);
    Iterable<RevCommit> logs = git.log().call();

    List<GitChangeSet> gitChangeSets = new ArrayList<>();
    for (RevCommit rev : logs) {
        String message = rev.getFullMessage();
        String author = rev.getAuthorIdent().getName();

        Date expiry = new Date(Long.valueOf(rev.getCommitTime()) * 1000);
        System.out.println(expiry.toString() + " " + rev.getCommitTime() + " " + rev.getName());

        gitChangeSets.add(new GitChangeSet(message, author, rev.getName(), expiry));
    }/*from  www . j  a v  a2 s . c o m*/

    gitChangeSets = Lists.reverse(gitChangeSets);

    // TODO currently this is ignoring the very first commit changes need to include those
    for (int i = 1; i < gitChangeSets.size(); i++) {
        System.out.println("///////////////////////////////////////////////");
        this.getRevisionChanges(localRepository, git, gitChangeSets.get(i - 1), gitChangeSets.get(i));
    }

}

From source file:com.searchcode.app.jobs.repository.IndexGitRepoJob.java

License:Open Source License

/**
 * Update a git repository and return if it has changed and the differences
 */// w  w  w  . j a v a  2s.com
public RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName,
        String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);

    Repository localRepository = null;
    Git git = null;

    try {
        localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));

        Ref head = localRepository.getRef("HEAD");
        git = new Git(localRepository);

        git.reset();
        git.clean();

        PullCommand pullCmd = git.pull();

        if (useCredentials) {
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }

        pullCmd.call();
        Ref newHEAD = localRepository.getRef("HEAD");

        if (!head.toString().equals(newHEAD.toString())) {
            changed = true;

            // Get the differences between the the heads which we updated at
            // and use these to just update the differences between them
            ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
            ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");

            ObjectReader reader = localRepository.newObjectReader();

            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.reset(reader, oldHead);

            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.reset(reader, newHead);

            List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

            for (DiffEntry entry : entries) {
                if ("DELETE".equals(entry.getChangeType().name())) {
                    deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
                } else {
                    changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
                }
            }
        }

    } catch (IOException | GitAPIException | InvalidPathException ex) {
        changed = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + " updateGitRepository for " + repoName + "\n with message: " + ex.getMessage());
    } finally {
        Singleton.getHelpers().closeQuietly(localRepository);
        Singleton.getHelpers().closeQuietly(git);
    }

    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}

From source file:com.sillelien.dollar.plugins.pipe.GithubModuleResolver.java

License:Apache License

@NotNull
@Override/*w w w .  j  av a2s  .  c  o m*/
public <T> Pipeable resolve(@NotNull String uriWithoutScheme, @NotNull T scope) throws Exception {
    logger.debug(uriWithoutScheme);
    String[] githubRepo = uriWithoutScheme.split(":");
    GitHub github = GitHub.connect();
    final String githubUser = githubRepo[0];
    GHRepository repository = github.getUser(githubUser).getRepository(githubRepo[1]);
    final String branch = githubRepo[2].length() > 0 ? githubRepo[2] : "master";
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    final File dir = new File(BASE_PATH + "/" + githubUser + "/" + githubRepo[1] + "/" + branch);
    dir.mkdirs();

    final File gitDir = new File(dir, ".git");
    if (gitDir.exists()) {
        Repository localRepo = builder.setGitDir(gitDir).readEnvironment().findGitDir().build();
        Git git = new Git(localRepo);
        PullCommand pull = git.pull();
        pull.call();
    } else {
        Repository localRepo = builder.setGitDir(dir).readEnvironment().findGitDir().build();
        Git git = new Git(localRepo);
        CloneCommand clone = Git.cloneRepository();
        clone.setBranch(branch);
        clone.setBare(false);
        clone.setCloneAllBranches(false);
        clone.setDirectory(dir).setURI(repository.getGitTransportUrl());
        //        UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider(login, password);
        //        clone.setCredentialsProvider(user);
        clone.call();
    }
    final ClassLoader classLoader;
    String content;
    File mainFile;
    if (githubRepo.length == 4) {
        classLoader = getClass().getClassLoader();
        mainFile = new File(dir, githubRepo[3]);
        content = new String(Files.readAllBytes(mainFile.toPath()));
    } else {
        final File moduleFile = new File(dir, "module.json");
        var module = DollarStatic.$(new String(Files.readAllBytes(moduleFile.toPath())));
        mainFile = new File(dir, module.$("main").$S());
        content = new String(Files.readAllBytes(mainFile.toPath()));
        classLoader = DependencyRetriever.retrieve(
                module.$("dependencies").$list().stream().map(var::toString).collect(Collectors.toList()));
    }
    return (params) -> ((Scope) scope).getDollarParser().inScope(false, "github-module", ((Scope) scope),
            newScope -> {

                final ImmutableMap<var, var> paramMap = params[0].$map();
                for (Map.Entry<var, var> entry : paramMap.entrySet()) {
                    newScope.set(entry.getKey().$S(), entry.getValue(), true, null, null, false, false, false);
                }
                return new DollarParserImpl(((Scope) scope).getDollarParser().options(), classLoader, dir)
                        .parse(newScope, content);
            });
}

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());
            }//  w w  w .j a  va2s . 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.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 www  .j a v a  2 s . c o  m*/

    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.GitSourceControlAgent.java

License:Apache License

@Override
public ReturnError checkoutBranch(String branch) {
    try (Git git = new Git(repository)) {
        try {/*from   w  w  w .j a v  a2s  .c o m*/
            git.checkout().setName(branch).call();
        } catch (GitAPIException e) {
            return new ReturnErrorImpl(e.getMessage());
        }
    }

    return null;
}

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

License:Apache License

@Override
public ReturnError createBranchFrom(String srcBranch, String destBranch) {
    try (Git git = new Git(repository)) {
        try {// w  w  w . ja  v  a 2 s . c  o m
            git.branchCreate().setStartPoint(srcBranch).setName(destBranch).call();
        } catch (GitAPIException e) {
            return new ReturnErrorImpl(e.getMessage());
        }
    }

    return null;
}

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

License:Apache License

@Override
public Pair<Boolean, ReturnError> hasUncommittedChanges() {
    boolean hasUncommitted = false;

    try (Git git = new Git(repository)) {
        Status status = git.status().call();

        if (!status.getAdded().isEmpty()) {
            log.info("Uncommitted added files {}", status.getAdded());
            hasUncommitted = true;/* ww  w .  j a va  2 s . c  o  m*/
        }

        if (!status.getChanged().isEmpty()) {
            log.info("Uncommitted changed files {}", status.getChanged());
            hasUncommitted = true;
        }

        if (!status.getConflicting().isEmpty()) {
            log.info("Conflicting files {}", status.getConflicting());
            hasUncommitted = true;
        }

        if (!status.getModified().isEmpty()) {
            log.info("Modified files {}", status.getModified());
            hasUncommitted = true;
        }

        if (!status.getRemoved().isEmpty()) {
            log.info("Removed files {}", status.getRemoved());
            hasUncommitted = true;
        }

        if (!status.getUntracked().isEmpty()) {
            log.info("Untracked files {}", status.getUntracked());
            hasUncommitted = true;
        }

        if (!status.getUntrackedFolders().isEmpty()) {
            log.info("Untracked folders {}", status.getUntrackedFolders());
            hasUncommitted = true;
        }
    } catch (GitAPIException e) {
        return new ImmutablePair<>(null, new ReturnErrorImpl(e.getMessage()));
    }

    return new ImmutablePair<>(hasUncommitted, null);
}

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();//from w ww  .j  av a2s  .c  o m

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