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.github.checkstyle.regression.extract.CheckstyleInjector.java

License:Open Source License

/**
 * Creates a new instance of CheckstyleInjector.
 * @param repoPath the path to checkstyle repository
 * @param branch   the name of PR branch
 *//*from w  w w  .ja v a 2s  .c o  m*/
CheckstyleInjector(String repoPath, String branch) {
    this.repoPath = repoPath;
    this.branch = branch;

    final File gitDir = new File(repoPath, ".git");
    final Repository repo;
    try {
        repo = new FileRepositoryBuilder().setGitDir(gitDir).readEnvironment().findGitDir().build();
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
    repository = repo;
}

From source file:com.github.checkstyle.regression.git.DiffParser.java

License:Open Source License

/**
 * Parses the diff between a given branch and the master in the give repository path.
 * @param repositoryPath the path of checkstyle repository
 * @param branchName     the name of the branch to be compared with master
 * @return a list of {@link GitChange} to represent the changes
 * @throws IOException     JGit library exception
 * @throws GitAPIException JGit library exception
 *///w  ww  .j a v a2  s . co  m
public static List<GitChange> parse(String repositoryPath, String branchName)
        throws IOException, GitAPIException {
    final List<GitChange> returnValue = new LinkedList<>();
    final File gitDir = new File(repositoryPath, ".git");
    final Repository repository = new FileRepositoryBuilder().setGitDir(gitDir).readEnvironment().findGitDir()
            .build();

    try {
        final TreeParserPair pair = getTreeParserPair(repository, branchName);
        final Git git = new Git(repository);
        final DiffFormatter formatter = new DiffFormatter(DisabledOutputStream.INSTANCE);
        formatter.setRepository(repository);

        try {
            final List<DiffEntry> diffs = git.diff().setOldTree(pair.commonAncestorTreeParser)
                    .setNewTree(pair.prTreeParser).call().stream()
                    .filter(entry -> entry.getChangeType() != DiffEntry.ChangeType.DELETE)
                    .collect(Collectors.toList());
            for (DiffEntry diff : diffs) {
                returnValue.add(convertDiffEntryToGitChange(diff, formatter));
            }
        } finally {
            git.close();
        }
    } finally {
        repository.close();
    }

    return returnValue;
}

From source file:com.github.checkstyle.regression.internal.CommitValidationTest.java

License:Open Source License

private static List<RevCommit> getCommitsToCheck() throws Exception {
    final List<RevCommit> commits;
    try (Repository repo = new FileRepositoryBuilder().findGitDir().build()) {
        final RevCommitsPair revCommitsPair = resolveRevCommitsPair(repo);
        if (COMMITS_RESOLUTION_MODE == CommitsResolutionMode.BY_COUNTER) {
            commits = getCommitsByCounter(revCommitsPair.getFirst());
            commits.addAll(getCommitsByCounter(revCommitsPair.getSecond()));
        } else {//from  ww w  . java 2s .c  o m
            commits = getCommitsByLastCommitAuthor(revCommitsPair.getFirst());
            commits.addAll(getCommitsByLastCommitAuthor(revCommitsPair.getSecond()));
        }
    }
    return commits;
}

From source file:com.github.kaitoy.goslings.server.dao.jgit.RepositoryResolver.java

License:Open Source License

/**
 * Get the {@link Git} instance which corresponds to the repository specified by the given token.
 *
 * @param token token// w w w  .ja  va2  s .  c  o m
 * @return a {@link Git} instance. Never null.
 * @throws DaoException if any errors.
 */
Git getGit(String token) {
    if (GITS.containsKey(token)) {
        return GITS.get(token);
    }

    File gitDir = Paths.get(REPOS_DIR, token).toFile();
    Git git = null;
    try {
        Repository repo = new FileRepositoryBuilder().setGitDir(gitDir).readEnvironment().findGitDir().build();
        git = new Git(repo);
        WeakReferenceMonitor.monitor(git, () -> repo.close());
        GITS.put(token, git);
        return git;
    } catch (IOException e) {
        LOG.error("Failed to build a repo {}", gitDir, e);
        throw new DaoException("The server couldn't find a repository by the token: " + token, e);
    }
}

From source file:com.github.koraktor.mavanagaiata.git.jgit.JGitRepository.java

License:Open Source License

/**
 * Creates a new instance from a JGit repository object
 *
 * @param workTree The worktree of the repository or {@code null}
 * @param gitDir The GIT_DIR of the repository or {@code null}
 *//*from   ww w  .  ja  v  a2 s .  co m*/
public JGitRepository(File workTree, File gitDir) throws GitRepositoryException {
    FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
    repositoryBuilder.readEnvironment();

    if (gitDir == null && workTree == null) {
        throw new GitRepositoryException("Neither worktree nor GIT_DIR is set.");
    } else {
        if (workTree != null && !workTree.exists()) {
            throw new GitRepositoryException("The worktree " + workTree + " does not exist");
        }
        if (gitDir != null && !gitDir.exists()) {
            throw new GitRepositoryException("The GIT_DIR " + gitDir + " does not exist");
        }
    }

    repositoryBuilder.setWorkTree(workTree);
    if (gitDir != null) {
        repositoryBuilder.setGitDir(gitDir);
    } else {
        repositoryBuilder.findGitDir(workTree);

        if (repositoryBuilder.getGitDir() == null) {
            throw new GitRepositoryException(
                    workTree + " is not inside a Git repository. Please specify the GIT_DIR separately.");
        }
    }

    try {
        this.repository = repositoryBuilder.build();
    } catch (IOException e) {
        throw new GitRepositoryException("Could not initialize repository", e);
    }

    this.commitCache = new HashMap<ObjectId, RevCommit>();
}

From source file:com.github.pascalgn.maven.properties.GitProperties.java

License:Apache License

private void addProperties(Map<String, String> map) throws IOException {
    Repository repository = new FileRepositoryBuilder().setWorkTree(new File(".")).readEnvironment()
            .findGitDir().setMustExist(true).build();
    logger.debug("Using git repository: " + repository.getDirectory());

    ObjectId head = repository.resolve("HEAD");
    if (head == null) {
        throw new IllegalStateException("No such revision: HEAD");
    }/*ww w .j a v a  2s.co  m*/

    String branch = nullToEmpty(repository.getBranch());
    map.put("git.branch", branch);

    String commitId = head.name();
    map.put("git.commit.id", commitId);

    String commitIdAbbrev = repository.newObjectReader().abbreviate(head).name();
    map.put("git.commit.id.abbrev", commitIdAbbrev);

    RevWalk walk = new RevWalk(repository);
    walk.setRetainBody(false);
    RevCommit headCommit = walk.parseCommit(head);
    int count = RevWalkUtils.count(walk, headCommit, null);
    map.put("git.count", Integer.toString(count));

    String color = commitId.substring(0, 6);
    map.put("git.commit.color.value", color);
    map.put("git.commit.color.name", ColorHelper.getColorName(color));
    map.put("git.commit.color.lightness", Integer.toString(ColorHelper.getLightness(color)));
    map.put("git.commit.color.foreground", ColorHelper.getForeground(color));

    map.put("git.build.datetime.simple", getFormattedDate());
}

From source file:com.github.rwhogg.git_vcr.App.java

License:Open Source License

/**
 * main is the entry point for Git-VCR/*from w w w.  ja  va  2 s.c  o  m*/
 * @param args Command-line arguments
 */
public static void main(String[] args) {
    Options options = parseCommandLine(args);

    HierarchicalINIConfiguration configuration = null;
    try {
        configuration = getConfiguration();
    } catch (ConfigurationException e) {
        Util.error("could not parse configuration file!");
    }

    // verify we are in a git folder and then construct the repo
    final File currentFolder = new File(".");
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository localRepo = null;
    try {
        localRepo = builder.findGitDir().build();
    } catch (IOException e) {
        Util.error("not in a Git folder!");
    }

    // deal with submodules
    assert localRepo != null;
    if (localRepo.isBare()) {
        FileRepositoryBuilder parentBuilder = new FileRepositoryBuilder();
        Repository parentRepo;
        try {
            parentRepo = parentBuilder.setGitDir(new File("..")).findGitDir().build();
            localRepo = SubmoduleWalk.getSubmoduleRepository(parentRepo, currentFolder.getName());
        } catch (IOException e) {
            Util.error("could not find parent of submodule!");
        }
    }

    // if we need to retrieve the patch file, get it now
    URL patchUrl = options.getPatchUrl();
    String patchPath = patchUrl.getFile();
    File patchFile = null;
    HttpUrl httpUrl = HttpUrl.get(patchUrl);
    if (httpUrl != null) {
        try {
            patchFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".diff");
            Request request = new Request.Builder().url(httpUrl).build();
            OkHttpClient client = new OkHttpClient();
            Call call = client.newCall(request);
            Response response = call.execute();
            ResponseBody body = response.body();
            if (!response.isSuccessful()) {
                Util.error("could not retrieve diff file from URL " + patchUrl);
            }
            String content = body.string();
            org.apache.commons.io.FileUtils.write(patchFile, content, (Charset) null);
        } catch (IOException ie) {
            Util.error("could not retrieve diff file from URL " + patchUrl);
        }
    } else {
        patchFile = new File(patchPath);
    }

    // find the patch
    //noinspection ConstantConditions
    if (!patchFile.canRead()) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " is not readable!");
    }

    final Git git = new Git(localRepo);

    // handle the branch
    String branchName = options.getBranchName();
    String theOldCommit = null;
    try {
        theOldCommit = localRepo.getBranch();
    } catch (IOException e2) {
        Util.error("could not get reference to current branch!");
    }
    final String oldCommit = theOldCommit; // needed to reference from shutdown hook

    if (branchName != null) {
        // switch to the branch
        try {
            git.checkout().setName(branchName).call();
        } catch (RefAlreadyExistsException e) {
            // FIXME Auto-generated catch block
            e.printStackTrace();
        } catch (RefNotFoundException e) {
            Util.error("the branch " + branchName + " was not found!");
        } catch (InvalidRefNameException e) {
            Util.error("the branch name " + branchName + " is invalid!");
        } catch (org.eclipse.jgit.api.errors.CheckoutConflictException e) {
            Util.error("there was a checkout conflict!");
        } catch (GitAPIException e) {
            Util.error("there was an unspecified Git API failure!");
        }
    }

    // ensure there are no changes before we apply the patch
    try {
        if (!git.status().call().isClean()) {
            Util.error("cannot run git-vcr while there are uncommitted changes!");
        }
    } catch (NoWorkTreeException e1) {
        // won't happen
        assert false;
    } catch (GitAPIException e1) {
        Util.error("call to git status failed!");
    }

    // list all the files changed
    String patchName = patchFile.getName();
    Patch patch = new Patch();
    try {
        patch.parse(new FileInputStream(patchFile));
    } catch (FileNotFoundException e) {
        assert false;
    } catch (IOException e) {
        Util.error("could not parse the patch file!");
    }

    ReviewResults oldResults = new ReviewResults(patchName, patch, configuration, false);
    try {
        oldResults.review();
    } catch (InstantiationException e1) {
        Util.error("could not instantiate a review tool class!");
    } catch (IllegalAccessException e1) {
        Util.error("illegal access to a class");
    } catch (ClassNotFoundException e1) {
        Util.error("could not find a review tool class");
    } catch (ReviewFailedException e1) {
        e1.printStackTrace();
        Util.error("Review failed!");
    }

    // we're about to change the repo, so register a shutdown hook to clean it up
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            cleanupGit(git, oldCommit);
        }
    });

    // apply the patch
    try {
        git.apply().setPatch(new FileInputStream(patchFile)).call();
    } catch (PatchFormatException e) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " is malformatted!");
    } catch (PatchApplyException e) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " did not apply correctly!");
    } catch (FileNotFoundException e) {
        assert false;
    } catch (GitAPIException e) {
        Util.error(e.getLocalizedMessage());
    }

    ReviewResults newResults = new ReviewResults(patchName, patch, configuration, true);
    try {
        newResults.review();
    } catch (InstantiationException e1) {
        Util.error("could not instantiate a review tool class!");
    } catch (IllegalAccessException e1) {
        Util.error("illegal access to a class");
    } catch (ClassNotFoundException e1) {
        Util.error("could not find a review tool class");
    } catch (ReviewFailedException e1) {
        e1.printStackTrace();
        Util.error("Review failed!");
    }

    // generate and show the report
    VelocityReport report = new VelocityReport(patch, oldResults, newResults);
    File reportFile = null;
    try {
        reportFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".html");
        org.apache.commons.io.FileUtils.write(reportFile, report.toString(), (String) null);
    } catch (IOException e) {
        Util.error("could not generate the results page!");
    }

    try {
        assert reportFile != null;
        Desktop.getDesktop().open(reportFile);
    } catch (IOException e) {
        Util.error("could not open the results page!");
    }
}

From source file:com.google.devtools.build.lib.bazel.repository.GitCloneFunction.java

License:Open Source License

private boolean isUpToDate(GitRepositoryDescriptor descriptor) {
    // Initializing/checking status of/etc submodules cleanly is hard, so don't try for now.
    if (descriptor.initSubmodules) {
        return false;
    }//from w w  w  .  j  av a2  s  . c o m
    Repository repository = null;
    try {
        repository = new FileRepositoryBuilder()
                .setGitDir(descriptor.directory.getChild(Constants.DOT_GIT).getPathFile()).setMustExist(true)
                .build();
        ObjectId head = repository.resolve(Constants.HEAD);
        ObjectId checkout = repository.resolve(descriptor.checkout);
        if (head != null && checkout != null && head.equals(checkout)) {
            Status status = Git.wrap(repository).status().call();
            if (!status.hasUncommittedChanges()) {
                // new_git_repository puts (only) BUILD and WORKSPACE, and
                // git_repository doesn't add any files.
                Set<String> untracked = status.getUntracked();
                if (untracked.isEmpty() || (untracked.size() == 2 && untracked.contains("BUILD")
                        && untracked.contains("WORKSPACE"))) {
                    return true;
                }
            }
        }
    } catch (GitAPIException | IOException e) {
        // Any exceptions here, we'll just blow it away and try cloning fresh.
        // The fresh clone avoids any weirdness due to what's there and has nicer
        // error reporting.
    } finally {
        if (repository != null) {
            repository.close();
        }
    }
    return false;
}

From source file:com.google.devtools.build.lib.bazel.repository.GitCloner.java

License:Open Source License

private static boolean isUpToDate(GitRepositoryDescriptor descriptor) {
    // Initializing/checking status of/etc submodules cleanly is hard, so don't try for now.
    if (descriptor.initSubmodules) {
        return false;
    }/*  ww  w  .  ja v  a  2 s . co  m*/
    Repository repository = null;
    try {
        repository = new FileRepositoryBuilder()
                .setGitDir(descriptor.directory.getChild(Constants.DOT_GIT).getPathFile()).setMustExist(true)
                .build();
        ObjectId head = repository.resolve(Constants.HEAD);
        ObjectId checkout = repository.resolve(descriptor.checkout);
        if (head != null && checkout != null && head.equals(checkout)) {
            Status status = Git.wrap(repository).status().call();
            if (!status.hasUncommittedChanges()) {
                // new_git_repository puts (only) BUILD and WORKSPACE, and
                // git_repository doesn't add any files.
                Set<String> untracked = status.getUntracked();
                if (untracked.isEmpty() || (untracked.size() == 2 && untracked.contains("BUILD")
                        && untracked.contains("WORKSPACE"))) {
                    return true;
                }
            }
        }
    } catch (GitAPIException | IOException e) {
        // Any exceptions here, we'll just blow it away and try cloning fresh.
        // The fresh clone avoids any weirdness due to what's there and has nicer
        // error reporting.
    } finally {
        if (repository != null) {
            repository.close();
        }
    }
    return false;
}

From source file:com.googlesource.gerrit.plugins.testplugin.OvirtPatchSetListener.java

License:Apache License

public static Supplier<Repository> repoFromPath(String path) {
    return () -> {
        try {/*from w  ww  .j  ava 2 s.  c  om*/
            return new FileRepositoryBuilder().readEnvironment() // scan environment GIT_* variables
                    .findGitDir(Paths.get(path).toFile()).build();
        } catch (IOException e) {
            log.error("Failed to open a repo from path {}, ", path, e);
            throw new IllegalArgumentException(e);
        }
    };
}