Example usage for org.eclipse.jgit.api Git status

List of usage examples for org.eclipse.jgit.api Git status

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git status.

Prototype

public StatusCommand status() 

Source Link

Document

Return a command object to execute a status command

Usage

From source file:org.springframework.cloud.config.server.JGitEnvironmentRepository.java

License:Apache License

private boolean shouldPull(Git git, Ref ref) throws GitAPIException {
    return git.status().call().isClean() && ref != null
            && git.getRepository().getConfig().getString("remote", "origin", "url") != null;
}

From source file:org.targettest.calc.scm.git.DisplayGitModifications.java

License:Apache License

public static void main(String[] args) throws IOException, NoHeadException {

    if (args.length != 1) {
        System.err.println("No git root specified");
        System.exit(1);/*from   www . j ava2s . c  om*/
    }
    String url = args[0];

    File localRepositoryDirectory = new File(url);

    RepositoryBuilder builder = new RepositoryBuilder();

    Repository repository = builder.findGitDir(localRepositoryDirectory).build();
    Git git = new Git(repository);
    Status status = git.status().call();
    Set<String> changed = status.getAdded();

    for (String changedFile : changed) {
        System.out.println(changedFile);
    }

}

From source file:org.targettest.calc.scm.git.GitModificationStrategyTest.java

License:Apache License

@SuppressWarnings("serial")
@Test/*  www.  j  a va 2s  . co m*/
public void testConvertsModifiedFileAbsoluteToRelativePathsAndStripsSrcFolders() throws Exception {
    String srcFolder = "/src/main/java";
    String relativeFile = "/dir/anotherFile.txt";

    final String sampleFilePath = this.getClass().getResource("/testgitroot" + srcFolder + relativeFile)
            .getFile();
    String gitRoot = new File(this.getClass().getResource("/testgitroot/gitRoot.txt").getFile()).getParent();

    Git mockGit = mock(Git.class);
    StatusCommand mockStatusCommand = mock(StatusCommand.class);
    when(mockGit.status()).thenReturn(mockStatusCommand);
    Status mockStatus = mock(Status.class);
    when(mockStatusCommand.call()).thenReturn(mockStatus);
    when(mockStatus.getChanged()).thenReturn(new HashSet<String>() {
        {
            add(sampleFilePath);
        }
    });
    GitModificationStrategy git = new GitModificationStrategy(mockGit, gitRoot,
            new String[] { "/src/main/java" });

    List<String> results = git.identifyModifications();
    Assert.assertEquals(relativeFile, results.get(0));
}

From source file:org.walkmod.git.readers.GitFileReader.java

License:Open Source License

@Override
public Resource<File> read() throws Exception {
    File file = new File(".git");
    Resource<File> result = null;
    if (file.exists()) {

        Git git = Git.open(file.getAbsoluteFile().getParentFile().getCanonicalFile());

        try {//  ww  w.  j  a va 2 s.c o m
            StatusCommand cmd = git.status();
            List<String> cfgIncludesList = null;
            String[] cfgIncludes = getIncludes();
            if (cfgIncludes != null && cfgIncludes.length > 0) {
                cfgIncludesList = Arrays.asList(cfgIncludes);
            }
            String path = getPath();
            Status status = cmd.call();
            Set<String> uncommitted = status.getUncommittedChanges();
            uncommitted.addAll(status.getUntracked());
            Set<String> includes = new HashSet<String>();
            if (!uncommitted.isEmpty()) {

                for (String uncommittedFile : uncommitted) {
                    if (uncommittedFile.startsWith(path)) {
                        String fileName = uncommittedFile.substring(path.length() + 1);
                        if (cfgIncludesList == null || cfgIncludesList.contains(fileName)) {
                            includes.add(fileName);
                        }
                    }
                }

            } else {

                Set<String> filesInCommit = getFilesInHEAD(git.getRepository());
                for (String committedFile : filesInCommit) {
                    if (committedFile.startsWith(path)) {
                        String fileName = committedFile.substring(path.length() + 1);
                        if (cfgIncludesList == null || cfgIncludesList.contains(fileName)) {
                            includes.add(fileName);
                        }
                    }
                }

            }
            if (!includes.isEmpty()) {
                String[] includesArray = new String[includes.size()];
                includesArray = includes.toArray(includesArray);

                setIncludes(includesArray);
            }
        } finally {
            git.close();
        }
    }
    result = super.read();
    return result;
}

From source file:org.wandora.application.tools.git.Commit.java

License:Open Source License

@Override
public void execute(Wandora wandora, Context context) {

    try {//from   www.  j a v a 2s  .  c o  m
        Git git = getGit();
        if (git != null) {
            if (commitUI == null) {
                commitUI = new CommitUI();
            }

            commitUI.openInDialog();

            if (commitUI.wasAccepted()) {
                setDefaultLogger();
                setLogTitle("Git commit");

                log("Saving project.");
                saveWandoraProject();

                log("Removing deleted files from local repository.");
                org.eclipse.jgit.api.Status status = git.status().call();
                Set<String> missing = status.getMissing();
                if (missing != null && !missing.isEmpty()) {
                    for (String missingFile : missing) {
                        git.rm().addFilepattern(missingFile).call();
                    }
                }

                log("Adding new files to local repository.");
                git.add().addFilepattern(".").call();

                log("Committing changes to local repository.");
                String commitMessage = commitUI.getMessage();
                if (commitMessage == null || commitMessage.length() == 0) {
                    commitMessage = getDefaultCommitMessage();
                    log("No commit message provided. Using default message.");
                }
                git.commit().setMessage(commitMessage).call();

                log("Ready.");
            }
        } else {
            logAboutMissingGitRepository();
        }
    } catch (GitAPIException gae) {
        log(gae.toString());
    } catch (NoWorkTreeException nwte) {
        log(nwte.toString());
    } catch (IOException ioe) {
        log(ioe.toString());
    } catch (TopicMapException tme) {
        log(tme.toString());
    } catch (Exception e) {
        log(e);
    }
    setState(WAIT);
}

From source file:org.wandora.application.tools.git.CommitPush.java

License:Open Source License

@Override
public void execute(Wandora wandora, Context context) {

    try {//from   w  w w . j a v  a 2s .  c o m
        Git git = getGit();
        if (git != null) {
            if (isNotEmpty(getGitRemoteUrl())) {
                if (commitPushUI == null) {
                    commitPushUI = new CommitPushUI();
                }

                commitPushUI.setPassword(getPassword());
                commitPushUI.setUsername(getUsername());
                commitPushUI.openInDialog();

                if (commitPushUI.wasAccepted()) {
                    setDefaultLogger();
                    setLogTitle("Git commit and push");

                    saveWandoraProject();

                    log("Removing deleted files from local repository.");
                    org.eclipse.jgit.api.Status status = git.status().call();
                    Set<String> missing = status.getMissing();
                    if (missing != null && !missing.isEmpty()) {
                        for (String missingFile : missing) {
                            git.rm().addFilepattern(missingFile).call();
                        }
                    }

                    log("Adding new files to the local repository.");
                    git.add().addFilepattern(".").call();

                    log("Committing changes to the local repository.");
                    String commitMessage = commitPushUI.getMessage();
                    if (commitMessage == null || commitMessage.length() == 0) {
                        commitMessage = getDefaultCommitMessage();
                        log("No commit message provided. Using default message.");
                    }
                    git.commit().setMessage(commitMessage).call();

                    String username = commitPushUI.getUsername();
                    String password = commitPushUI.getPassword();

                    setUsername(username);
                    setPassword(password);

                    PushCommand push = git.push();
                    if (isNotEmpty(username)) {
                        log("Setting push credentials.");
                        CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(
                                username, password);
                        push.setCredentialsProvider(credentialsProvider);
                    }
                    log("Pushing upstream.");
                    push.call();

                    log("Ready.");
                }
            } else {
                log("Repository has no remote origin and can't be pushed. "
                        + "Commit changes to the local repository using Commit to local... "
                        + "To push changes to a remote repository initialize repository by cloning.");
            }
        } else {
            logAboutMissingGitRepository();
        }
    } catch (GitAPIException gae) {
        log(gae.toString());
    } catch (NoWorkTreeException nwte) {
        log(nwte.toString());
    } catch (IOException ioe) {
        log(ioe.toString());
    } catch (TopicMapException tme) {
        log(tme.toString());
    } catch (Exception e) {
        log(e);
    }
    setState(WAIT);
}

From source file:org.wandora.application.tools.git.Status.java

License:Open Source License

@Override
public void execute(Wandora wandora, Context context) {

    try {/*from  ww w.  java2 s  .  co  m*/
        Git git = getGit();
        if (git != null) {
            setDefaultLogger();
            setLogTitle("Git status");

            Repository repository = git.getRepository();
            StoredConfig config = repository.getConfig();

            log("Git conf:");
            log(config.toText());

            log("Git status:");
            org.eclipse.jgit.api.Status status = git.status().call();
            log("Added: " + status.getAdded());
            log("Changed: " + status.getChanged());
            log("Conflicting: " + status.getConflicting());
            log("ConflictingStageState: " + status.getConflictingStageState());
            log("IgnoredNotInIndex: " + status.getIgnoredNotInIndex());
            log("Missing: " + status.getMissing());
            log("Modified: " + status.getModified());
            log("Removed: " + status.getRemoved());
            log("Untracked: " + status.getUntracked());
            log("UntrackedFolders: " + status.getUntrackedFolders());
            log("Ready.");
        } else {
            logAboutMissingGitRepository();
        }
    } catch (Exception e) {
        log(e);
    }
    setState(WAIT);
}

From source file:org.wso2.carbon.deployment.synchronizer.git.GitBasedArtifactRepository.java

License:Open Source License

/**
 * Quesries the git status for the repository given by gitRepoCtx
 *
 * @param gitRepoCtx TenantGitRepositoryContext instance for the tenant
 * @return Status instance updated with relevant status information,
 *         null in an error in getting the status
 *//*from  ww w . j  a  va2s. com*/
private Status getGitStatus(TenantGitRepositoryContext gitRepoCtx) {

    Git git = gitRepoCtx.getGit();
    StatusCommand statusCmd = git.status();
    Status status;

    try {
        status = statusCmd.call();

    } catch (GitAPIException e) {
        log.error("Git status operation for tenant " + gitRepoCtx.getTenantId() + " failed, ", e);
        status = null;
    }

    return status;
}

From source file:org.zanata.sync.plugin.git.service.impl.GitSyncService.java

License:Open Source License

@Override
public void syncTranslationToRepo(String repoUrl, String branch, File baseDir) throws RepoSyncException {
    try {//ww  w  . ja  v  a 2s .  com
        Git git = Git.open(baseDir);
        StatusCommand statusCommand = git.status();
        Status status = statusCommand.call();
        Set<String> uncommittedChanges = status.getUncommittedChanges();
        uncommittedChanges.addAll(status.getUntracked());
        if (!uncommittedChanges.isEmpty()) {
            log.info("uncommitted files in git repo: {}", uncommittedChanges);
            AddCommand addCommand = git.add();
            addCommand.addFilepattern(".");
            addCommand.call();

            log.info("commit changed files");
            CommitCommand commitCommand = git.commit();
            commitCommand.setCommitter("Zanata Auto Repo Sync", "zanata-users@redhat.com");
            commitCommand.setMessage("Zanata Auto Repo Sync (pushing translations)");
            commitCommand.call();

            log.info("push to remote repo");
            PushCommand pushCommand = git.push();
            UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider(
                    getCredentials().getUsername(), getCredentials().getSecret());
            pushCommand.setCredentialsProvider(user);
            pushCommand.call();
        } else {
            log.info("nothing changed so nothing to do");
        }
    } catch (IOException e) {
        throw new RepoSyncException("failed opening " + baseDir + " as git repo", e);
    } catch (GitAPIException e) {
        throw new RepoSyncException("Failed committing translations into the repo", e);
    }
}

From source file:pl.project13.jgit.DescribeCommand.java

License:Open Source License

@VisibleForTesting
boolean findDirtyState(Repository repo) throws GitAPIException {
    Git git = Git.wrap(repo);
    Status status = git.status().call();

    // Git describe doesn't mind about untracked files when checking if
    // repo is dirty. JGit does this, so we cannot use the isClean method
    // to get the same behaviour. Instead check dirty state without
    // status.getUntracked().isEmpty()
    boolean isDirty = !(status.getAdded().isEmpty() && status.getChanged().isEmpty()
            && status.getRemoved().isEmpty() && status.getMissing().isEmpty() && status.getModified().isEmpty()
            && status.getConflicting().isEmpty());

    log("Repo is in dirty state [", isDirty, "]");
    return isDirty;
}