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:gov.va.isaac.sync.git.SyncServiceGIT.java

License:Apache License

private void addNote(String message, Git git) throws IOException, GitAPIException {
    RevWalk walk = new RevWalk(git.getRepository());
    Ref head = git.getRepository().getRef("refs/heads/master");
    RevCommit commit = walk.parseCommit(head.getObjectId());
    git.notesAdd().setObjectId(commit).setMessage(message).call();

}

From source file:io.fabric8.collector.git.elasticsearch.CommitDTO.java

License:Apache License

public CommitDTO(Git git, NamespaceName projectNamespaceName, RevCommit commit, String repoUrl, String branch) {
    this.namespace = projectNamespaceName.getNamespace();
    this.app = projectNamespaceName.getName();
    this.repoUrl = repoUrl;
    this.branch = branch;
    this.sha = commit.getId().getName();

    this.author = PersonIdentDTO.newInstance(commit.getAuthorIdent());
    this.committer = PersonIdentDTO.newInstance(commit.getCommitterIdent());
    this.fullMessage = commit.getFullMessage();
    this.name = commit.getName();
    this.commitTime = GitHelpers.getCommitDate(commit);
    this.shortMessage = commit.getShortMessage();

    // TODO how to figure out the number of lines added/removed from DiffEntry + HunkHeader?
    // lets try find out the lines added / updated / deleted for this commit
    try {/*from w  w w.j a  v a 2s .co m*/
        Repository r = git.getRepository();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        DiffFormatter formatter = createDiffFormatter(r, buffer);

        RevCommit baseCommit = null;
        RevTree commitTree = commit.getTree();
        RevTree baseTree;
        if (baseCommit == null) {
            if (commit.getParentCount() > 0) {
                final RevWalk rw = new RevWalk(r);
                RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
                rw.dispose();
                baseTree = parent.getTree();
            } else {
                // FIXME initial commit. no parent?!
                baseTree = commitTree;
            }
        } else {
            baseTree = baseCommit.getTree();
        }

        List<DiffEntry> diffEntries = formatter.scan(baseTree, commitTree);
        for (DiffEntry diffEntry : diffEntries) {
            formatter.format(diffEntry);

            /*
                            FileHeader fileHeader = formatter.toFileHeader(diffEntry);
                            List<? extends HunkHeader> hunks = fileHeader.getHunks();
                            for (HunkHeader hunk : hunks) {
            // linesAdded += hunk.getOldImage().getLinesAdded();
            // linesRemoved += hunk.getOldImage().getLinesDeleted();
                            }
            */
        }
        // TODO should we store the diff? thats maybe too big?
        formatter.flush();
        String diff = buffer.toString();
        if (diff != null) {
            String[] lines = diff.split("\n");
            for (String line : lines) {
                if (line.length() == 0 || line.startsWith("diff ") || line.startsWith("index ")
                        || line.startsWith("--- ") || line.startsWith("+++ ")) {
                    continue;
                }
                if (line.startsWith("+")) {
                    linesAdded++;
                } else if (line.startsWith("-")) {
                    linesRemoved++;
                }
            }
        }

    } catch (IOException e) {
        LOG.warn("Failed to extract lines changed for " + projectNamespaceName + " branch: " + branch
                + " commit: " + sha + ". " + e, e);
    }
}

From source file:io.fabric8.collector.git.GitBuildConfigProcessor.java

License:Apache License

/**
 * Lets process the commit history going back in time until we have persisted all the commits into Elasticsearch
 *//*from   ww  w.ja va  2 s  .  c  o m*/
protected int processHistory(NamespaceName name, File gitFolder, BuildConfig buildConfig, String uri,
        String branch) throws IOException {
    Git git = GitHelpers.gitFromGitFolder(gitFolder);

    Repository r = git.getRepository();

    try {
        getHEAD(git);
    } catch (Exception e) {
        LOG.error("Cannot find HEAD of the git repository for " + name + ": " + e, e);
        return 0;
    }

    CommitFinder finder = new CommitFinder(r);
    CommitListFilter filter = new CommitListFilter();
    finder.setFilter(filter);

    finder.find();
    List<RevCommit> commits = filter.getCommits();
    commits = filterAndSortCommits(name, branch, commits);

    int counter = 0;
    for (RevCommit commit : commits) {
        processCommit(name, git, commit, buildConfig, uri, branch);
        if (commitLimit > 0) {
            if (++counter >= commitLimit) {
                break;
            }
        }
    }

    if (counter > 0) {
        LOG.info(name + " Processed " + counter + " commit(s)");
    }
    return counter;
}

From source file:io.fabric8.collector.git.GitBuildConfigProcessor.java

License:Apache License

protected String getHEAD(Git git) {
    RevCommit commit = CommitUtils.getHead(git.getRepository());
    return commit.getName();
}

From source file:io.fabric8.collector.git.GitHelpers.java

License:Apache License

public static File getRootGitDirectory(Git git) {
    return git.getRepository().getDirectory().getParentFile();
}

From source file:io.fabric8.collector.git.GitHelpers.java

License:Apache License

/**
 * Returns the remote git URL for the given branch
 *///ww  w  .java  2s  . com
public static String getRemoteURL(Git git, String branch) {
    StoredConfig config = git.getRepository().getConfig();
    return config.getString("branch", branch, "remote");
}

From source file:io.fabric8.collector.git.GitHelpers.java

License:Apache License

public static void configureBranch(Git git, String branch, String origin, String remoteRepository) {
    // lets update the merge config
    if (!Strings.isNullOrBlank(branch)) {
        StoredConfig config = git.getRepository().getConfig();
        config.setString("branch", branch, "remote", origin);
        config.setString("branch", branch, "merge", "refs/heads/" + branch);

        config.setString("remote", origin, "url", remoteRepository);
        config.setString("remote", origin, "fetch", "+refs/heads/*:refs/remotes/" + origin + "/*");
        try {/*from   w  ww .ja  v  a 2  s. c o m*/
            config.save();
        } catch (IOException e) {
            LOG.error("Failed to save the git configuration to " + git.getRepository().getDirectory()
                    + " with branch " + branch + " on " + origin + " remote repo: " + remoteRepository
                    + " due: " + e.getMessage() + ". This exception is ignored.", e);
        }
    }
}

From source file:io.fabric8.forge.generator.pipeline.JenkinsPipelineLibrary.java

License:Apache License

protected void doPull(File gitFolder, CredentialsProvider cp, String branch, PersonIdent personIdent,
        UserDetails userDetails) {//from   w  w  w.  ja v a2  s  . c  o  m
    StopWatch watch = new StopWatch();
    try {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        Git git = new Git(repository);

        File projectFolder = repository.getDirectory();

        StoredConfig config = repository.getConfig();
        String url = config.getString("remote", remote, "url");
        if (io.fabric8.utils.Strings.isNullOrBlank(url)) {
            LOG.warn("No remote repository url for " + branch + " defined for the git repository at "
                    + projectFolder.getCanonicalPath() + " so cannot pull");
            //return;
        }
        String mergeUrl = config.getString("branch", branch, "merge");
        if (io.fabric8.utils.Strings.isNullOrBlank(mergeUrl)) {
            LOG.warn("No merge spec for branch." + branch + ".merge in the git repository at "
                    + projectFolder.getCanonicalPath() + " so not doing a pull");
            //return;
        }

        // lets trash any failed changes
        LOG.debug("Stashing local changes to the repo");
        boolean hasHead = true;
        try {
            git.log().all().call();
            hasHead = git.getRepository().getAllRefs().containsKey("HEAD");
        } catch (NoHeadException e) {
            hasHead = false;
        }
        if (hasHead) {
            // lets stash any local changes just in case..
            try {
                git.stashCreate().setPerson(personIdent).setWorkingDirectoryMessage("Stash before a write")
                        .setRef("HEAD").call();
            } catch (Throwable e) {
                LOG.error("Failed to stash changes: " + e, e);
                Throwable cause = e.getCause();
                if (cause != null && cause != e) {
                    LOG.error("Cause: " + cause, cause);
                }
            }
        }

        //LOG.debug("Resetting the repo");
        //git.reset().setMode(ResetCommand.ResetType.HARD).call();

        LOG.debug("Performing a pull in git repository " + projectFolder.getCanonicalPath() + " on remote URL: "
                + url);
        PullCommand pull = git.pull();
        GitUtils.configureCommand(pull, userDetails);
        pull.setRebase(true).call();
    } catch (Throwable e) {
        LOG.error("Failed to pull from the remote git repo with credentials " + cp + " due: " + e.getMessage()
                + ". This exception is ignored.", e);
    } finally {
        LOG.debug("doPull took " + watch.taken());
    }
}

From source file:io.fabric8.forge.rest.CommandsResource.java

License:Apache License

protected <T> T withUIContext(final String namespace, final String projectName, String resourcePath,
        boolean write, final RestUIFunction<T> function, final GitContext gitContext) throws Exception {
    final ResourceFactory resourceFactory = getResourceFactory();
    if (Strings.isNotBlank(namespace) && Strings.isNotBlank(projectName) && resourceFactory != null) {
        RepositoriesResource repositoriesResource = new RepositoriesResource(gitUserHelper, repositoryCache,
                projectFileSystem, lockManager, kubernetes);
        repositoriesResource.setRequest(request);
        final RepositoryResource projectResource = repositoriesResource.projectRepositoryResource(namespace,
                projectName);/*from   ww w  . ja  va  2  s . c o m*/
        if (projectResource == null) {
            throw new NotFoundException("Could not find git project for namespace: " + namespace
                    + " and projectName: " + projectName);
        } else {
            GitOperation<T> operation = new GitOperation<T>() {
                @Override
                public T call(Git git, GitContext gitContext) throws Exception {
                    Repository repository = git.getRepository();
                    File gitDir = repository.getDirectory();
                    File directory = gitDir.getParentFile();
                    LOG.debug("using repository directory: " + directory.getAbsolutePath());
                    Resource<?> selection = resourceFactory.create(directory);
                    String cloneUrl = projectResource.getCloneUrl();
                    try (RestUIContext context = new RestUIContext(selection, namespace, projectName,
                            cloneUrl)) {
                        T answer = function.apply(context);
                        String commitMessage = context.getCommitMessage();
                        if (Strings.isNotBlank(commitMessage)) {
                            projectResource.setMessage(commitMessage);
                        }
                        return answer;
                    }
                }
            };
            if (write) {
                return projectResource.gitWriteOperation(operation);
            } else {
                return projectResource.gitReadOperation(operation);
            }
        }
    } else {
        try (RestUIContext context = new RestUIContext(null)) {
            return function.apply(context);
        }
    }
}

From source file:io.fabric8.forge.rest.git.RepositoryResource.java

License:Apache License

protected Response doFileDetails(Git git, String path) {
    if (Strings.isNotBlank(objectId)) {
        Repository r = git.getRepository();
        String blobPath = trimLeadingSlash(path);
        String content = BlobUtils.getContent(r, objectId, blobPath);
        FileDTO answer = FileDTO.createFileDTO(blobPath, objectId, content);
        return Response.ok(answer).build();
    } else {/*  w ww . j a v  a 2s.c  o  m*/
        final File file = getRelativeFile(path);
        if (LOG.isDebugEnabled()) {
            LOG.debug("reading file: " + file.getPath());
        }
        if (!file.exists() || file.isDirectory()) {
            List<FileDTO> answer = new ArrayList<>();
            if (file.exists()) {
                File[] files = file.listFiles();
                if (files != null) {
                    for (File child : files) {
                        FileDTO dto = createFileDTO(child, false);
                        if (dto != null) {
                            answer.add(dto);
                        }
                    }
                }
            }
            return Response.ok(answer).build();
        } else {
            FileDTO answer = createFileDTO(file, true);
            return Response.ok(answer).build();
        }
    }
}