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:GitBackend.GitAPI.java

License:Apache License

private static HashMap getRevisionsByLog(Repository repository, String filePath) {

    HashMap commitMap = new HashMap<String, DateTime>();

    Git git = new Git(repository);
    LogCommand logCommand = null;/*from   w  ww. j  a v  a 2 s .co  m*/
    try {
        logCommand = git.log().add(git.getRepository().resolve(Constants.HEAD)).addPath(filePath);
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        for (RevCommit revCommit : logCommand.call()) {
            DateTime commitDate = new DateTime(1000L * revCommit.getCommitTime());
            // Store commit hash and date
            commitMap.put(revCommit.getName(), commitDate);
        }
    } catch (GitAPIException e) {
        e.printStackTrace();
    }

    return commitMap;
}

From source file:GitBackend.GitAPI.java

License:Apache License

private TreeMap<DateTime, RevCommit> getAllCommitsBefore(Date execDate, String path) {

    // this.showLogForFile(this.repository.getDirectory()+path);
    // this.showLog();

    //RevWalk walk = new RevWalk(git.getRepository());
    TreeMap<DateTime, RevCommit> commitsByDate = new TreeMap<DateTime, RevCommit>();

    try (Git git = new Git(repository)) {
        Iterable<RevCommit> commits = git.log().all().call();
        int count = 0;
        for (RevCommit commit : commits) {

            count++;//from   w w w .  j  a v a2 s . c o  m
            DateTime commitTime = new DateTime(commit.getCommitterIdent().getWhen());
            DateTime execTimeDate = new DateTime(execDate);
            // Only add if the timestamp is before
            if (commitTime.compareTo(execTimeDate) <= 0) {
                commitsByDate.put(commitTime, commit);
            }

        }

    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoHeadException e) {
        e.printStackTrace();
    } catch (GitAPIException e) {
        e.printStackTrace();
    }

    Iterable<RevCommit> logs = null;

    try {
        logs = git.log().call();
        logs = git.log()
                // for all log.all()
                .addPath(path).call();
        int count = 0;
        for (RevCommit rev : logs) {
            //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
            count++;
        }

    } catch (GitAPIException e) {
        e.printStackTrace();
    }

    /*
            
            
            
    try {
    walk.markStart(walk.parseCommit(this.repository.resolve(Constants.HEAD)));
            
    walk.sort(RevSort.COMMIT_TIME_DESC);
     //   walk.setTreeFilter(PathFilter.create(path));
            
    for (RevCommit commit : walk) {
        if (commit.getCommitterIdent().getWhen().before(execDate)) {
            DateTime commitTime = new DateTime(commit.getCommitterIdent().getWhen());
            commitsByDate.put(commitTime, commit);
            
        }
    }
    walk.close();
    System.out.println("Number of valid commits: " + commitsByDate.size());
    } catch (IOException e) {
    e.printStackTrace();
    }
    */
    return commitsByDate;
}

From source file:GitBackend.GitAPI.java

License:Apache License

public RevCommit getFirstCommit(String path) {

    // this.showLogForFile(this.repository.getDirectory()+path);
    // this.showLog();

    //RevWalk walk = new RevWalk(git.getRepository());
    TreeMap<DateTime, RevCommit> allCommits = new TreeMap<DateTime, RevCommit>();

    try (Git git = new Git(repository)) {
        Iterable<RevCommit> commits = git.log().all().call();
        int count = 0;
        for (RevCommit commit : commits) {

            count++;//from   w w  w.  j a v a2  s  .c o m
            DateTime commitTime = new DateTime(commit.getCommitterIdent().getWhen());
            allCommits.put(commitTime, commit);

        }

    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoHeadException e) {
        e.printStackTrace();
    } catch (GitAPIException e) {
        e.printStackTrace();
    }
    return allCommits.firstEntry().getValue();
}

From source file:GitBackend.GitAPI.java

License:Apache License

public Date getFirstCommitDate(String path) {

    // this.showLogForFile(this.repository.getDirectory()+path);
    // this.showLog();

    //RevWalk walk = new RevWalk(git.getRepository());
    TreeMap<DateTime, RevCommit> allCommits = new TreeMap<DateTime, RevCommit>();

    try (Git git = new Git(repository)) {
        Iterable<RevCommit> commits = git.log().all().call();
        int count = 0;
        for (RevCommit commit : commits) {

            count++;/* www .  ja  va  2s  .c o m*/
            DateTime commitTime = new DateTime(commit.getCommitterIdent().getWhen());
            allCommits.put(commitTime, commit);

        }

    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoHeadException e) {
        e.printStackTrace();
    } catch (GitAPIException e) {
        e.printStackTrace();
    }
    return allCommits.firstEntry().getKey().toDate();
}

From source file:GitBackend.GitAPI.java

License:Apache License

private Git openOrCreate(File localDirectory, String remoteRepo) throws IOException, GitAPIException {
    Git git = null;/*from  ww  w  . j  a va 2s  .  c  o m*/
    FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
    repositoryBuilder.addCeilingDirectory(localDirectory);
    repositoryBuilder.findGitDir(localDirectory);
    if (repositoryBuilder.getGitDir() == null) {
        // git = Git.init().setDirectory( gitDirectory.getParentFile() ).call();
        try {

            Git.cloneRepository().setURI(remoteRepo).setDirectory(localDirectory).call();
        } catch (GitAPIException e) {
            e.printStackTrace();
        }
    } else {
        git = new Git(repositoryBuilder.build());
    }
    return git;
}

From source file:gitrunner.GitRunner.java

/**
 * @param args the command line arguments
 *//*from www .j av  a 2 s  .  c  o m*/
public static void main(String[] args) {
    try {

        // Run git status for fun using Process
        Process p = Runtime.getRuntime().exec("git status");

        BufferedReader reader;
        BufferedReader error_reader;

        reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        error_reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));

        String cmd_output = null;

        while ((cmd_output = reader.readLine()) != null) {

            System.out.println(cmd_output);
        }

        while ((cmd_output = error_reader.readLine()) != null) {
            System.out.println("Error: " + cmd_output);
        }

        // Now use Jgit to get "git status"

        System.out.println("\n\n ===== Using Jgit =====");
        FileRepositoryBuilder builder = new FileRepositoryBuilder();

        Repository repo = builder.readEnvironment().findGitDir().build();

        if (repo == null) {
            System.err.println("No repo");
        } else {
            System.out.println("Got repo");
        }

        Git git = new Git(repo);

        Status status = null;
        try {
            status = git.status().call();
        } catch (GitAPIException ex) {
            Logger.getLogger(GitRunner.class.getName()).log(Level.SEVERE, null, ex);
            System.exit(-1);
        } catch (NoWorkTreeException ex) {
            Logger.getLogger(GitRunner.class.getName()).log(Level.SEVERE, null, ex);
            System.exit(-1);
        }

        Set<String> result = new HashSet<>();

        System.out.println("Untracked = " + status.getUntracked());
        result.addAll(status.getModified());
        result.addAll(status.getAdded());
        result.addAll(status.getUntracked());
        System.out.println(result.toString());

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

}

From source file:git_manager.tool.GitOperations.java

License:Open Source License

public GitOperations(Editor editor) {
    this.editor = editor;
    //      if (Base.isLinux())
    //         gitDir = new File(editor.getSketch().getFolder().getAbsolutePath()
    //               + "/.git");
    //      else//from  www  .  jav a  2  s  .c o m
    gitDir = new File(editor.getSketch().getFolder().getAbsolutePath(), ".git");
    thisDir = new File(editor.getSketch().getFolder().getAbsolutePath());
    try {
        git = new Git(new FileRepository(gitDir));
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:gov.va.isaac.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * @throws AuthenticationException /*from ww w  . j a  v a  2s  .  c o  m*/
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#linkAndFetchFromRemote(java.io.File, java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void linkAndFetchFromRemote(String remoteAddress, String username, String password)
        throws IllegalArgumentException, IOException, AuthenticationException {
    log.info("linkAndFetchFromRemote called - folder: {}, remoteAddress: {}, username: {}", localFolder,
            remoteAddress, username);
    try {
        File gitFolder = new File(localFolder, ".git");
        Repository r = new FileRepository(gitFolder);

        if (!gitFolder.isDirectory()) {
            log.debug("Root folder does not contain a .git subfolder.  Creating new git repository.");
            r.create();
        }

        relinkRemote(remoteAddress, username, password);

        Git git = new Git(r);

        CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                (password == null ? new char[] {} : password.toCharArray()));

        log.debug("Fetching");
        FetchResult fr = git.fetch().setCheckFetchedObjects(true).setCredentialsProvider(cp).call();
        log.debug("Fetch messages: {}", fr.getMessages());

        boolean remoteHasMaster = false;
        Collection<Ref> refs = git.lsRemote().setCredentialsProvider(cp).call();
        for (Ref ref : refs) {
            if ("refs/heads/master".equals(ref.getName())) {
                remoteHasMaster = true;
                log.debug("Remote already has 'heads/master'");
                break;
            }
        }

        if (remoteHasMaster) {
            //we need to fetch and (maybe) merge - get onto origin/master.

            log.debug("Fetching from remote");
            String fetchResult = git.fetch().setCredentialsProvider(cp).call().getMessages();
            log.debug("Fetch Result: {}", fetchResult);

            log.debug("Resetting to origin/master");
            git.reset().setMode(ResetType.MIXED).setRef("origin/master").call();

            //Get the files from master that we didn't have in our working folder
            log.debug("Checking out missing files from origin/master");
            for (String missing : git.status().call().getMissing()) {
                log.debug("Checkout {}", missing);
                git.checkout().addPath(missing).call();
            }

            for (String newFile : makeInitialFilesAsNecessary(localFolder)) {
                log.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding " + newFile).setAuthor(username, "42").call();

                for (PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                    log.debug("Push Message: {}", pr.getMessages());
                }
            }
        } else {
            //just push
            //make sure we have something to push
            for (String newFile : makeInitialFilesAsNecessary(localFolder)) {
                log.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding readme file").setAuthor(username, "42").call();
            }

            log.debug("Pushing repository");
            for (PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                log.debug("Push Result: {}", pr.getMessages());
            }
        }

        log.info("linkAndFetchFromRemote Complete.  Current status: " + statusToString(git.status().call()));
    } catch (TransportException te) {
        if (te.getMessage().contains("Auth fail")) {
            log.info("Auth fail", te);
            throw new AuthenticationException("Auth fail");
        } else {
            log.error("Unexpected", te);
            throw new IOException("Internal error", te);
        }
    } catch (GitAPIException e) {
        log.error("Unexpected", e);
        throw new IOException("Internal error", e);
    }
}

From source file:gov.va.isaac.sync.git.SyncServiceGIT.java

License:Apache License

private Git getGit() throws IOException, IllegalArgumentException {
    if (localFolder == null) {
        throw new IllegalArgumentException(
                "localFolder has not yet been set - please call setRootLocation(...)");
    }/*  w  ww.  j  a va  2s.  c om*/
    if (!localFolder.isDirectory()) {
        log.error("The passed in local folder '{}' didn't exist", localFolder);
        throw new IllegalArgumentException("The localFolder must be a folder, and must exist");
    }

    File gitFolder = new File(localFolder, ".git");

    if (!gitFolder.isDirectory()) {
        log.error("The passed in local folder '{}' does not appear to be a git repository", localFolder);
        throw new IllegalArgumentException("The localFolder does not appear to be a git repository");
    }
    return new Git(new FileRepository(gitFolder));
}

From source file:info.debatty.jinu.Case.java

License:Open Source License

private void commitToGit(final String time_tag) {
    try {// ww  w.  j  ava 2 s.c o  m
        Repository repo = new FileRepositoryBuilder().findGitDir().build();

        Git git = new Git(repo);
        git.add().addFilepattern(".").call();
        git.commit().setAll(true).setMessage("Test case " + time_tag).call();
        git.tag().setName("T" + time_tag).call();
    } catch (Exception ex) {
        System.err.println("Could not commit GIT repo");
        System.err.println(ex.getMessage());
    }
}