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:jbenchmarker.trace.git.GitWalker.java

License:Open Source License

public GitWalker(String... args) throws IOException {

    try {/*from  w w w. j  a  va 2 s. c om*/
        this.parser = new CmdLineParser(this);

        parser.parseArgument(args);

        if (help) {
            help(0);
        }
    } catch (CmdLineException ex) {
        System.err.println("Error in argument " + ex);
        help(-1);
    }

    Logger.getLogger("").setLevel(levels[logLevel.ordinal()]);

    builder = new FileRepositoryBuilder();
    repository = builder.setGitDir(new File(gitDir + "/.git")).readEnvironment().findGitDir().build();
    this.reader = repository.newObjectReader();
    this.git = new Git(repository);
    this.source = ContentSource.create(reader);
    this.diffAlgorithm = DiffAlgorithm.getAlgorithm(DiffAlgorithm.SupportedAlgorithm.MYERS);
    this.fromCommit = repository.resolve(fromCommitStr);

}

From source file:key.secretkey.utils.PasswordStorage.java

License:GNU General Public License

/**
 * Returns the git repository/*from  w w  w .  j a v a 2s.co m*/
 * @param localDir needed only on the creation
 * @return the git repository
 */
public static Repository getRepository(File localDir) {
    if (repository == null && localDir != null) {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        try {
            repository = builder.setGitDir(localDir).readEnvironment().build();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    return repository;
}

From source file:licenseUtil.Utils.java

License:Apache License

public static void updateRepository(String gitDir) {
    try {//from   w  w w . ja  va  2  s .  c om
        // Open an existing repository
        Repository existingRepo = new FileRepositoryBuilder().setGitDir(new File(gitDir + "/.git")).build();
        Git git = new Git(existingRepo);

        git.pull().call();
    } catch (GitAPIException e) {
        logger.warn("Could not update local repository: \"" + gitDir + "\" with git pull.");
    } catch (IOException e) {
        logger.warn("Could not open local git repository directory: \"" + gitDir + "\"");
    }

}

From source file:licenseUtil.Utils.java

License:Apache License

public static void commitAndPushRepository(String gitDir, String message) {
    try {/*from w w w.j a v a2 s  . c  o m*/
        // Open an existing repository
        Repository existingRepo = new FileRepositoryBuilder().setGitDir(new File(gitDir + "/.git")).build();
        Git git = new Git(existingRepo);

        logger.info("commit & push to repo (" + gitDir + "): " + message);
        git.commit().setMessage(message).call();
        git.push().call();
    } catch (GitAPIException e) {
        logger.warn("Could not commit and push local repository: \"" + gitDir + "\" with message: \"" + message
                + "\" because of " + e.getMessage());
    } catch (IOException e) {
        logger.warn("Could not open local git repository directory: \"" + gitDir + "\"");
    }

}

From source file:licenseUtil.Utils.java

License:Apache License

public static void addToRepository(String gitDir, String newFN) {
    try {/*from  www.  j  a  v  a2 s .  com*/
        // Open an existing repository
        Repository existingRepo = new FileRepositoryBuilder().setGitDir(new File(gitDir + "/.git")).build();
        Git git = new Git(existingRepo);
        File newFile = new File(gitDir + File.separator + newFN);
        newFile.createNewFile();
        git.add().addFilepattern(newFile.getName()).call();
    } catch (GitAPIException e) {
        logger.warn("Could not the file \"" + newFN + "\" to local repository: \"" + gitDir + ".");
    } catch (IOException e) {
        logger.warn("Could not open local git repository directory: \"" + gitDir + "\"");
    }

}

From source file:m.k.s.gitwrapper.GitLocalService.java

License:Apache License

/**
 * Open the git repository./*from  w  w w  .  jav a  2  s.co m*/
 * <br/>
 * Warning: close the git after used
 * @param repoPath full path of the repository
 * 
 */
public GitLocalService(String repoPath, IOutput outputter) {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();

    try {
        repository = builder.setGitDir(new File(repoPath)).setMustExist(true)
                //                    .readEnvironment() // scan environment GIT_* variables
                //                    .findGitDir() // scan up the file system tree
                .build();

        git = new Git(repository);
        this.outputter = outputter;
    } catch (IOException ex) {
        LOG.error("Could not open git repository '" + repoPath + "'", ex);
    }
}

From source file:main.Repositories.java

/**
 * Get the files from a given repository on github
 * @param localPath The folder on disk where the files will be placed
 * @param location The username/repository identification. We'd
 * expect something like triplecheck/reporter
 *//*from   w w  w. j a v a2  s  .c o  m*/
public void download(final File localPath, final String location) {
    // we can't have any older files
    files.deleteDir(localPath);
    final String REMOTE_URL = "https://github.com/" + location + ".git";
    try {

        Git.cloneRepository().setURI(REMOTE_URL).setDirectory(localPath).call();

        // now open the created repository
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(localPath).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        System.out.println("Downloaded repository: " + repository.getDirectory());

        repository.close();

    } catch (IOException ex) {
        Logger.getLogger(Repositories.class.getName()).log(Level.SEVERE, null, ex);
    } catch (GitAPIException ex) {
        Logger.getLogger(Repositories.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println("--> " + location);
}

From source file:me.cmoz.gradle.snapshot.GitSCMCommand.java

License:Apache License

@Override
@SneakyThrows(IOException.class)
public Commit getLatestCommit(@NonNull final String dateFormat) {
    if (repoDir == null) {
        throw new IllegalStateException("'.git' folder could not be found.");
    }//  w ww  .  j a  v a2 s . com

    final FileRepositoryBuilder builder = new FileRepositoryBuilder();

    final Repository repo = builder.setGitDir(repoDir).readEnvironment().build();
    final StoredConfig conf = repo.getConfig();

    int abbrev = Commit.ABBREV_LENGTH;
    if (conf != null) {
        abbrev = conf.getInt("core", "abbrev", abbrev);
    }

    final SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

    final Ref HEAD = repo.getRef(Constants.HEAD);
    if (HEAD.getObjectId() == null) {
        throw new RuntimeException("Could not find any commits from HEAD ref.");
    }

    final RevWalk revWalk = new RevWalk(repo);
    if (HEAD.getObjectId() == null) {
        throw new RuntimeException("Could not find any commits from HEAD ref.");
    }
    final RevCommit revCommit = revWalk.parseCommit(HEAD.getObjectId());
    revWalk.markStart(revCommit);

    try {
        // git commit time in sec and java datetime is in ms
        final Date commitTime = new Date(revCommit.getCommitTime() * 1000L);
        final PersonIdent ident = revCommit.getAuthorIdent();
        final UserConfig userConf = conf.get(UserConfig.KEY);

        return Commit.builder().buildTime(sdf.format(new Date())).buildAuthorName(userConf.getAuthorName())
                .buildAuthorEmail(userConf.getAuthorEmail()).branchName(repo.getBranch())
                .commitId(revCommit.getName()).commitTime(sdf.format(commitTime))
                .commitUserName(ident.getName()).commitUserEmail(ident.getEmailAddress())
                .commitMessage(revCommit.getFullMessage().trim()).build();
    } finally {
        revWalk.dispose();
        repo.close();
    }
}

From source file:me.seeber.gradle.repository.git.ConfigureLocalGitRepository.java

License:Open Source License

/**
 * Run task//from  w w w . java2  s.c  om
 *
 * @throws IOException if something really bad happens
 */
@TaskAction
public void configure() throws IOException {
    FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
    repositoryBuilder.addCeilingDirectory(getProject().getProjectDir());
    repositoryBuilder.findGitDir(getProject().getProjectDir());

    boolean create = (repositoryBuilder.getGitDir() == null);

    repositoryBuilder.setWorkTree(getProject().getProjectDir());

    Repository repository = repositoryBuilder.build();

    if (create) {
        repository.create();
    }

    try (Git git = new Git(repository)) {
        StoredConfig config = git.getRepository().getConfig();

        getRemoteRepositories().forEach((name, url) -> {
            config.setString("remote", name, "url", url);
        });

        config.save();
    }

    File ignoreFile = getProject().file(".gitignore");
    SortedSet<@NonNull String> remainingIgnores = new TreeSet<>(getIgnores());
    List<String> lines = new ArrayList<>();

    if (ignoreFile.exists()) {
        Files.lines(ignoreFile.toPath()).forEach(l -> {
            lines.add(l);

            if (!l.trim().startsWith("#")) {
                remainingIgnores.remove(unescapePattern(l));
            }
        });
    }

    if (!remainingIgnores.isEmpty()) {
        List<@NonNull String> escapedIgnores = remainingIgnores.stream().map(l -> escapePattern(l))
                .collect(Collectors.toList());
        lines.addAll(escapedIgnores);
        Files.write(ignoreFile.toPath(), lines, StandardOpenOption.CREATE);
    }
}

From source file:net.aprendizajengrande.gitrecommender.ExtractLog.java

License:Open Source License

public static void main(String[] args) throws Exception {

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    System.out.println("Git dir: " + args[0]);
    Repository repository = builder.setGitDir(new File(args[0])).readEnvironment() // scan environment GIT_* variables
            .findGitDir() // scan up the file system tree
            .build();//w  ww.jav a2  s  . c  o m

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

    RevCommit previous = null;
    String previousAuthor = null;

    // author -> file -> counts
    Map<String, Map<String, Counter>> counts = new HashMap<>();
    Map<String, Counter> commitCounts = new HashMap<>(); // author -> counts
    Map<String, Integer> authorIds = new HashMap<>();
    Map<String, Integer> fileIds = new HashMap<>();
    List<String> authors = new ArrayList<>();
    List<String> files = new ArrayList<>();

    int commitNum = 0;

    for (RevCommit commit : log) {
        commitNum++;
        if (commitNum % 1000 == 0) {
            System.out.println(commitNum);

            // compute affinity for files as % of commits that touch that
            // file
            PrintWriter pw = new PrintWriter(args[1] + "." + commitNum + ".dat");
            for (String author : commitCounts.keySet()) {
                double totalCommits = commitCounts.get(author).intValue();
                for (Map.Entry<String, Counter> c : counts.get(author).entrySet()) {
                    pw.println(authorIds.get(author) + "\t" + fileIds.get(c.getKey()) + "\t"
                            + ((c.getValue().intValue() / totalCommits) * 10000) + "\t"
                            + c.getValue().intValue());
                }
            }
            pw.close();

            pw = new PrintWriter(args[1] + "." + commitNum + ".users");
            int id = 1;
            for (String author : authors) {
                pw.println(id + "\t" + author);
                id++;
            }
            pw.close();

            pw = new PrintWriter(args[1] + "." + commitNum + ".files");
            id = 1;
            for (String file : files) {
                pw.println(id + "\t" + file);
                id++;
            }
            pw.close();
        }
        // System.out.println("Author: " +
        // commit.getAuthorIdent().getName());
        String author = commit.getAuthorIdent().getName();
        if (!counts.containsKey(author)) {
            counts.put(author, new HashMap<String, Counter>());
            commitCounts.put(author, new Counter(1));
            authorIds.put(author, authorIds.size() + 1);
            authors.add(author);
        } else {
            commitCounts.get(author).inc();
        }

        if (previous != null) {
            AbstractTreeIterator oldTreeParser = prepareTreeParser(repository, previous);
            AbstractTreeIterator newTreeParser = prepareTreeParser(repository, commit);
            // then the procelain diff-command returns a list of diff
            // entries
            List<DiffEntry> diff = git.diff().setOldTree(oldTreeParser).setNewTree(newTreeParser).call();
            for (DiffEntry entry : diff) {
                // System.out.println("\tFile: " + entry.getNewPath());
                String file = entry.getNewPath();
                if (!fileIds.containsKey(file)) {
                    fileIds.put(file, fileIds.size() + 1);
                    files.add(file);
                }
                if (!counts.get(previousAuthor).containsKey(file)) {
                    counts.get(previousAuthor).put(file, new Counter(1));
                } else {
                    counts.get(previousAuthor).get(file).inc();
                }
            }
            // diff.dispose();
            // previous.dispose();
        }
        previous = commit;
        previousAuthor = author;
    }

    // compute affinity for files as % of commits that touch that file
    PrintWriter pw = new PrintWriter(args[1] + ".dat");
    for (String author : commitCounts.keySet()) {
        double totalCommits = commitCounts.get(author).intValue();
        for (Map.Entry<String, Counter> c : counts.get(author).entrySet()) {
            pw.println(authorIds.get(author) + "\t" + fileIds.get(c.getKey()) + "\t"
                    + ((c.getValue().intValue() / totalCommits) * 10000) + "\t" + c.getValue().intValue());
        }
    }
    pw.close();

    pw = new PrintWriter(args[1] + ".users");
    int id = 1;
    for (String author : authors) {
        pw.println(id + "\t" + author);
        id++;
    }
    pw.close();

    pw = new PrintWriter(args[1] + ".files");
    id = 1;
    for (String file : files) {
        pw.println(id + "\t" + file);
        id++;
    }
    pw.close();

    repository.close();
}