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:licenseUtil.Utils.java

License:Apache License

public static void addToRepository(String gitDir, String newFN) {
    try {/*from ww  w. ja  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);
        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./*  www  .  ja va 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:me.seeber.gradle.repository.git.ConfigureLocalGitRepository.java

License:Open Source License

/**
 * Run task// w  w  w .ja  v  a 2  s  .c o m
 *
 * @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:models.PullRequest.java

License:Apache License

private FetchResult fetchSourceBranchTo(String destination) throws IOException, GitAPIException {
    return new Git(getRepository()).fetch().setRemote(GitRepository.getGitDirectoryURL(fromProject))
            .setRefSpecs(new RefSpec().setSource(fromBranch).setDestination(destination).setForceUpdate(true))
            .call();//from  www  . j  ava2  s. c  o  m
}

From source file:neembuu.uploader.zip.generator.UpdaterGenerator.java

License:Apache License

/**
 * Execute git pull command on the given repository.
 * It populates an ArrayList with all the updated files.
 * @param localPath The path where the project is.
 * @return Returns true if you should update plugins, false otherwise.
 *///from ww  w . j  a  va2 s. c  o  m
private boolean gitPull(File localPath) {
    try {
        Repository localRepo = new FileRepository(localPath.getAbsolutePath() + "/.git");
        git = new Git(localRepo);

        if (populateDiff()) {
            PullCommand pullCmd = git.pull();
            pullCmd.call();
            return true;
        } else {
            return false;
        }

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

    return true;
}

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();/* ww  w.  j av  a 2s .  com*/

    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();
}

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

License:Open Source License

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

    if (args.length == 0) {
        System.err.println("Usage: UpdateLog <git dir> <db dir>");
        System.exit(-1);// www . ja v  a 2 s  .  c om
    }

    File gitDir = new File(args[0]);
    File dbDir = new File(args[1]);

    DB db = new DB(dbDir);

    System.out.println("Git dir: " + gitDir);
    System.out.println("DB dir: " + dbDir);

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

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

    // go through all commits and process them in reverse order
    List<RevCommit> allCommits = new ArrayList<RevCommit>();

    int newCommits = 0;
    boolean seen = false;
    for (RevCommit commit : log) {
        String name = commit.name();
        if (db.lastCommit().equals(name)) {
            seen = true;
        }
        if (!seen)
            newCommits++;

        allCommits.add(commit);
    }
    System.out.println("Found " + allCommits.size() + " commits (" + newCommits + " new).");

    int commitNum = 0;
    List<Integer> files = new ArrayList<Integer>();
    for (int i = newCommits - 1; i >= 0; i--) {
        if (commitNum % 500 == 0)
            db.save();

        RevCommit commit = allCommits.get(i);

        String author = commit.getAuthorIdent().getName();
        int authorId = db.idAuthor(author);

        files.clear();

        if (i < allCommits.size() - 1) {
            AbstractTreeIterator oldTreeParser = prepareTreeParser(repository, allCommits.get(i + 1));
            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();
                files.add(db.idFile(file));
            }
        }
        db.observeCommit(commit.name(), authorId, files);
    }

    db.save();
    repository.close();
}

From source file:net.erdfelt.android.sdkfido.git.internal.InternalGit.java

License:Apache License

@Override
public void checkoutBranch(String branchName) throws GitException {
    try {//  w  w w .j  a  v a  2  s.c om
        CheckoutCommand command = new Git(repo).checkout();
        command.setCreateBranch(false);
        command.setName(branchName);
        command.setForce(false);
        command.call();
    } catch (Throwable t) {
        throw new GitException(t.getMessage(), t);
    }
}

From source file:net.erdfelt.android.sdkfido.git.internal.InternalGit.java

License:Apache License

@Override
public void pullRemote() throws GitException {
    try {//ww w.  j av a  2  s. c o m
        Git git = new Git(repo);
        FetchCommand fetch = git.fetch();
        fetch.setCheckFetchedObjects(false);
        fetch.setRemoveDeletedRefs(true);
        List<RefSpec> specs = new ArrayList<RefSpec>();
        fetch.setRefSpecs(specs);
        fetch.setTimeout(5000);
        fetch.setDryRun(false);
        fetch.setRemote(IGit.REMOTE_NAME);
        fetch.setThin(Transport.DEFAULT_FETCH_THIN);
        fetch.setProgressMonitor(getProgressMonitor());

        FetchResult result = fetch.call();
        if (result.getTrackingRefUpdates().isEmpty()) {
            return;
        }

        GitInfo.infoFetchResults(repo, result);
    } catch (Throwable t) {
        throw new GitException(t.getMessage(), t);
    }
}

From source file:net.fatlenny.datacitation.service.GitCitationDBService.java

License:Apache License

@Override
public Status saveQuery(Query query) throws CitationDBException {
    checkoutBranch(REF_QUERIES);/*from w ww  .  j av a 2  s .  c o  m*/

    String pidIdentifier = query.getPid().getIdentifier();
    String fileName = DigestUtils.sha1Hex(pidIdentifier) + "." + QUERY_ENDING;
    try (Git git = new Git(repository)) {
        Path filePath = Paths.get(getWorkingTreeDir(), fileName);
        Properties properties = writeQueryToProperties(query);
        properties.store(
                Files.newBufferedWriter(filePath, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW), "");
        git.add().addFilepattern(fileName).call();
        PersonIdent personIdent = new PersonIdent("ReCitable", "recitable@fatlenny.net");
        String message = String.format("Created query file for PID=%s", pidIdentifier);
        git.commit().setMessage(message).setAuthor(personIdent).setCommitter(personIdent).call();
    } catch (IOException | GitAPIException e) {
        throw new CitationDBException(e);
    }

    return Status.SUCCESS;
}