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:com.buildautomation.jgit.api.ShowFileDiff.java

License:Apache License

public static void showFileDiff() throws IOException, GitAPIException {
    try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
        // the diff works on TreeIterators, we prepare two for the two branches
        AbstractTreeIterator oldTreeParser = prepareTreeParser(repository,
                "09c65401f3730eb3e619c33bf31e2376fb393727");
        AbstractTreeIterator newTreeParser = prepareTreeParser(repository,
                "aa31703b65774e4a06010824601e56375a70078c");

        // then the procelain diff-command returns a list of diff entries
        try (Git git = new Git(repository)) {
            List<DiffEntry> diff = git.diff().setOldTree(oldTreeParser).setNewTree(newTreeParser)
                    .setPathFilter(PathFilter.create("README.md")).call();
            for (DiffEntry entry : diff) {
                System.out.println(
                        "Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId());
                try (DiffFormatter formatter = new DiffFormatter(System.out)) {
                    formatter.setRepository(repository);
                    formatter.format(entry);
                }//from  w ww. j a  v  a 2  s .co  m
            }
        }
    }
}

From source file:com.buildautomation.jgit.api.ShowLog.java

License:Apache License

@SuppressWarnings("unused")
public static void showLog() throws IOException, GitAPIException {
    try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
        try (Git git = new Git(repository)) {
            Iterable<RevCommit> logs = git.log().call();
            int count = 0;
            for (RevCommit rev : logs) {
                //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
                count++;/*from  w ww  .j  a  v a2s.  c o m*/
            }
            System.out.println("Had " + count + " commits overall on current branch");

            logs = git.log().add(repository.resolve("remotes/origin/testbranch")).call();
            count = 0;
            for (RevCommit rev : logs) {
                System.out.println(
                        "Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
                count++;
            }
            System.out.println("Had " + count + " commits overall on test-branch");

            logs = git.log().all().call();
            count = 0;
            for (RevCommit rev : logs) {
                //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
                count++;
            }
            System.out.println("Had " + count + " commits overall in repository");

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

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

From source file:com.buildautomation.jgit.api.ShowStatus.java

License:Apache License

public static void showStatus() throws IOException, GitAPIException {
    try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
        try (Git git = new Git(repository)) {
            Status status = git.status().call();
            System.out.println("Added: " + status.getAdded());
            System.out.println("Changed: " + status.getChanged());
            System.out.println("Conflicting: " + status.getConflicting());
            System.out.println("ConflictingStageState: " + status.getConflictingStageState());
            System.out.println("IgnoredNotInIndex: " + status.getIgnoredNotInIndex());
            System.out.println("Missing: " + status.getMissing());
            System.out.println("Modified: " + status.getModified());
            System.out.println("Removed: " + status.getRemoved());
            System.out.println("Untracked: " + status.getUntracked());
            System.out.println("UntrackedFolders: " + status.getUntrackedFolders());
        }/*from  w  ww.  ja  v  a2  s.  co  m*/
    }
}

From source file:com.buildautomation.jgit.api.WalkAllCommits.java

License:Apache License

public static void walkAllCommits() throws IOException, InvalidRefNameException, GitAPIException {
    try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
        try (Git git = new Git(repository)) {
            Iterable<RevCommit> commits = git.log().all().call();
            int count = 0;
            for (RevCommit commit : commits) {
                System.out.println("LogCommit: " + commit);
                count++;//from   w  ww. j  a  v a 2 s .c  o  m
            }
            System.out.println(count);
        }
    }
}

From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

public void connect(String repositoryUrl, String user, String password, File localDir) throws IOException {

    if (repositoryUrl != null && !repositoryUrl.isEmpty()) {
        if (user == null) {
            this.repositoryUrl = repositoryUrl;
        } else {//from  w w w .  j  a  v a  2s. c  om
            int slashSlash = repositoryUrl.indexOf("//");
            this.repositoryUrl = repositoryUrl.substring(0, slashSlash + 2) + user + ":" + password + "@"
                    + repositoryUrl.substring(slashSlash + 2);
        }
    }

    this.localDir = localDir;
    localRepo = new FileRepository(new File(localDir + "/.git"));
    git = new Git(localRepo);
    if (credentialsProvider == null) {
        if (user != null && password != null)
            credentialsProvider = new UsernamePasswordCredentialsProvider(user, password);
    }

    file2id = new HashMap<File, Long>();
    id2file = new HashMap<Long, File>();
    pkg2versions = new HashMap<>();

    String idLengthProp = System.getProperty("com.centurylink.mdw.abbreviated.id.length");
    if (idLengthProp != null)
        ABBREVIATED_ID_LENGTH = Integer.parseInt(idLengthProp);
}

From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

public synchronized void reconnect() throws IOException {
    Repository newLocalRepo = new FileRepository(new File(localDir + "/.git"));
    git = new Git(newLocalRepo);
    localRepo.close();// ww w.  j  a  v a2  s.  c  o m
    localRepo = newLocalRepo;
}

From source file:com.cisco.step.jenkins.plugins.jenkow.JenkowWorkflowRepository.java

License:Open Source License

private void addAndCommit(Repository r, String filePattern, String msg) throws IOException {
    try {//from w  w w . ja  va2 s  . c  o m
        Git git = new Git(r);
        AddCommand cmd = git.add();
        cmd.addFilepattern(filePattern);
        cmd.call();

        CommitCommand co = git.commit();
        co.setAuthor("Jenkow", "noreply@jenkins-ci.org");
        co.setMessage(msg);
        co.call();
    } catch (GitAPIException e) {
        LOGGER.log(Level.WARNING, "Adding seeded jenkow-repository content to Git failed", e);
    }
}

From source file:com.crygier.git.rest.util.GitUtil.java

License:Apache License

public static Git getGit(File gitDirectory) {
    if (gitDirectory == null)
        return null;

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try {//from  w  w w  . ja  v  a  2s. co  m
        Repository repository = builder.setGitDir(new File(gitDirectory, ".git")).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();
        return new Git(repository);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Unable to open git directory", e);
        return null;
    }
}

From source file:com.denimgroup.threadfix.service.repository.GitServiceImpl.java

License:Mozilla Public License

@Override
public File cloneRepoToDirectory(Application application, File dirLocation) {

    if (dirLocation.exists()) {
        File gitDirectoryFile = new File(dirLocation.getAbsolutePath() + File.separator + ".git");

        try {// w  ww .j  av  a 2 s  .co  m
            if (!gitDirectoryFile.exists()) {
                Git newRepo = clone(application, dirLocation);
                if (newRepo != null)
                    return newRepo.getRepository().getWorkTree();
            } else {
                Repository localRepo = new FileRepository(gitDirectoryFile);
                Git git = new Git(localRepo);

                if (application.getRepositoryRevision() != null
                        && !application.getRepositoryRevision().isEmpty()) {
                    //remote checkout
                    git.checkout().setCreateBranch(true).setStartPoint(application.getRepositoryRevision())
                            .setName(application.getRepositoryRevision()).call();
                } else {

                    List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();

                    String repoBranch = (application.getRepositoryBranch() != null
                            && !application.getRepositoryBranch().isEmpty()) ? application.getRepositoryBranch()
                                    : "master";

                    boolean localCheckout = false;

                    for (Ref ref : refs) {
                        String refName = ref.getName();
                        if (refName.contains(repoBranch) && !refName.contains(Constants.R_REMOTES)) {
                            localCheckout = true;
                        }
                    }

                    String HEAD = localRepo.getFullBranch();

                    if (HEAD.contains(repoBranch)) {
                        git.pull().setRemote("origin").setRemoteBranchName(repoBranch)
                                .setCredentialsProvider(getApplicationCredentials(application)).call();
                    } else {
                        if (localCheckout) {
                            //local checkout
                            git.checkout().setName(application.getRepositoryBranch()).call();
                            git.pull().setRemote("origin").setRemoteBranchName(repoBranch)
                                    .setCredentialsProvider(getApplicationCredentials(application)).call();
                        } else {
                            //remote checkout
                            git.checkout().setCreateBranch(true).setName(repoBranch)
                                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM)
                                    .setStartPoint("origin/" + repoBranch).call();
                        }
                    }
                }

                return git.getRepository().getWorkTree();
            }
        } catch (JGitInternalException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (IOException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (WrongRepositoryStateException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidConfigurationException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (DetachedHeadException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidRemoteException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (CanceledException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (RefNotFoundException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (NoHeadException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (RefAlreadyExistsException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (CheckoutConflictException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidRefNameException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (TransportException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (GitAPIException e) {
            log.error(EXCEPTION_MESSAGE, e);
        }
    } else {
        try {
            log.info("Attempting to clone application from repository.");
            Git result = clone(application, dirLocation);
            if (result != null) {
                log.info("Application was successfully cloned from repository.");
                return result.getRepository().getWorkTree();
            }
            log.error(EXCEPTION_MESSAGE);
        } catch (JGitInternalException e) {
            log.error(EXCEPTION_MESSAGE, e);
        }
    }
    return null;
}

From source file:com.genuitec.eclipse.gerrit.tools.internal.fbranches.commands.SwitchToBranchCommand.java

License:Open Source License

protected void execute(ExecutionEvent event, final Repository repository, final String branchRef)
        throws ExecutionException {
    //check if local branch exists
    final String branchName = branchRef.substring("refs/heads/".length()); //$NON-NLS-1$
    try {//from ww w.j  a  v a  2s .com
        if (repository.getRef(branchRef) == null) {
            //create local branch
            String remoteBranchRef = "refs/remotes/origin/" + branchName; //$NON-NLS-1$
            Ref remoteRef = repository.getRef(remoteBranchRef);
            if (remoteRef == null) {
                throw new RuntimeException(
                        MessageFormat.format("Remote branch {0} doesn't exist", remoteBranchRef));
            }
            new Git(repository).branchCreate().setName(branchName).setStartPoint(remoteBranchRef)
                    .setUpstreamMode(SetupUpstreamMode.TRACK).call();
            repository.getConfig().setBoolean("branch", branchName, "rebase", true); //$NON-NLS-1$//$NON-NLS-2$
        }
    } catch (Exception e1) {
        RepositoryUtils.handleException(e1);
        return;
    }

    BranchOperationUI op = BranchOperationUI.checkout(repository, branchRef).doneCallback(new DoneCallback() {

        public void done(CheckoutResult result) {

            if (result.getStatus() == CheckoutResult.Status.OK) {
                String newUpstreamRef = branchRef + ":refs/for/" + branchName; //$NON-NLS-1$
                repository.getConfig().setString("remote", "origin", "push", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                        newUpstreamRef);
                //ensure in rebase mode
                repository.getConfig().setBoolean("branch", branchName, "rebase", true); //$NON-NLS-1$//$NON-NLS-2$
                try {
                    repository.getConfig().save();
                } catch (IOException e) {
                    RepositoryUtils.handleException(e);
                }
            }
        }
    });
    op.start();
}