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:ch.sbb.releasetrain.git.GitRepoImpl.java

License:Apache License

@Override
public void addCommitPush() {
    try {/*from  w  ww . jav a2s .c  om*/
        Git git = gitOpen();

        git.add().addFilepattern(".").call();

        // status
        Status status = git.status().call();

        // rm the deleted ones
        if (status.getMissing().size() > 0) {
            for (String rm : status.getMissing()) {
                git.rm().addFilepattern(rm).call();
            }
        }

        // commit and push if needed
        if (!status.hasUncommittedChanges()) {
            log.debug("not commiting git, because there are no changes");
            return;
        }

        git.commit().setMessage("Automatic commit by releasetrain").call();
        git.push().setCredentialsProvider(credentialsProvider()).call();
    } catch (Exception e) {
        throw new GitException(e.getMessage(), e);
    }
}

From source file:com.barchart.jenkins.cascade.PluginScmGit.java

License:BSD License

/**
 * See {@link Git#status()}//  w  w  w . j  a v a 2 s. c  o  m
 */
public static Status doStatus(final File workspace) {
    try {
        final Git git = Git.open(workspace);
        return git.status().call();
    } catch (final Throwable e) {
        throw new RuntimeException(e);
    }
}

From source file:com.crygier.git.rest.resources.RepositoryResource.java

License:Apache License

@GET
@Path("/{repositoryName}/status")
@JSONP(queryParam = "callback")
@Produces({ "application/javascript" })
public Map<String, Object> status(@PathParam("repositoryName") String repositoryName) {
    Map<String, Object> answer = new HashMap<String, Object>();

    Status gitStatus = GitUtil.doWithGit(repositoryName, new GitCallback<Status>() {
        @Override//from  www .  jav  a  2 s .  c om
        public Status doWitGit(Git git) throws Exception {
            return git.status().call();
        }
    });

    if (gitStatus != null) {
        answer.put("status", "ok");
        answer.put("gitStatus", StatusConversionUtil.convertStatusToTree(gitStatus));
    } else {
        answer.put("status", "error");
        answer.put("message",
                repositoryName + " is not registered.  Please call " + Configuration.BaseUri.getStringValue()
                        + "repository/" + repositoryName + "/register?directory=<directoryName>");
    }

    return answer;
}

From source file:com.github.rwhogg.git_vcr.App.java

License:Open Source License

/**
 * main is the entry point for Git-VCR/*from  w  w w  . j a v  a2s.  c  o  m*/
 * @param args Command-line arguments
 */
public static void main(String[] args) {
    Options options = parseCommandLine(args);

    HierarchicalINIConfiguration configuration = null;
    try {
        configuration = getConfiguration();
    } catch (ConfigurationException e) {
        Util.error("could not parse configuration file!");
    }

    // verify we are in a git folder and then construct the repo
    final File currentFolder = new File(".");
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository localRepo = null;
    try {
        localRepo = builder.findGitDir().build();
    } catch (IOException e) {
        Util.error("not in a Git folder!");
    }

    // deal with submodules
    assert localRepo != null;
    if (localRepo.isBare()) {
        FileRepositoryBuilder parentBuilder = new FileRepositoryBuilder();
        Repository parentRepo;
        try {
            parentRepo = parentBuilder.setGitDir(new File("..")).findGitDir().build();
            localRepo = SubmoduleWalk.getSubmoduleRepository(parentRepo, currentFolder.getName());
        } catch (IOException e) {
            Util.error("could not find parent of submodule!");
        }
    }

    // if we need to retrieve the patch file, get it now
    URL patchUrl = options.getPatchUrl();
    String patchPath = patchUrl.getFile();
    File patchFile = null;
    HttpUrl httpUrl = HttpUrl.get(patchUrl);
    if (httpUrl != null) {
        try {
            patchFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".diff");
            Request request = new Request.Builder().url(httpUrl).build();
            OkHttpClient client = new OkHttpClient();
            Call call = client.newCall(request);
            Response response = call.execute();
            ResponseBody body = response.body();
            if (!response.isSuccessful()) {
                Util.error("could not retrieve diff file from URL " + patchUrl);
            }
            String content = body.string();
            org.apache.commons.io.FileUtils.write(patchFile, content, (Charset) null);
        } catch (IOException ie) {
            Util.error("could not retrieve diff file from URL " + patchUrl);
        }
    } else {
        patchFile = new File(patchPath);
    }

    // find the patch
    //noinspection ConstantConditions
    if (!patchFile.canRead()) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " is not readable!");
    }

    final Git git = new Git(localRepo);

    // handle the branch
    String branchName = options.getBranchName();
    String theOldCommit = null;
    try {
        theOldCommit = localRepo.getBranch();
    } catch (IOException e2) {
        Util.error("could not get reference to current branch!");
    }
    final String oldCommit = theOldCommit; // needed to reference from shutdown hook

    if (branchName != null) {
        // switch to the branch
        try {
            git.checkout().setName(branchName).call();
        } catch (RefAlreadyExistsException e) {
            // FIXME Auto-generated catch block
            e.printStackTrace();
        } catch (RefNotFoundException e) {
            Util.error("the branch " + branchName + " was not found!");
        } catch (InvalidRefNameException e) {
            Util.error("the branch name " + branchName + " is invalid!");
        } catch (org.eclipse.jgit.api.errors.CheckoutConflictException e) {
            Util.error("there was a checkout conflict!");
        } catch (GitAPIException e) {
            Util.error("there was an unspecified Git API failure!");
        }
    }

    // ensure there are no changes before we apply the patch
    try {
        if (!git.status().call().isClean()) {
            Util.error("cannot run git-vcr while there are uncommitted changes!");
        }
    } catch (NoWorkTreeException e1) {
        // won't happen
        assert false;
    } catch (GitAPIException e1) {
        Util.error("call to git status failed!");
    }

    // list all the files changed
    String patchName = patchFile.getName();
    Patch patch = new Patch();
    try {
        patch.parse(new FileInputStream(patchFile));
    } catch (FileNotFoundException e) {
        assert false;
    } catch (IOException e) {
        Util.error("could not parse the patch file!");
    }

    ReviewResults oldResults = new ReviewResults(patchName, patch, configuration, false);
    try {
        oldResults.review();
    } catch (InstantiationException e1) {
        Util.error("could not instantiate a review tool class!");
    } catch (IllegalAccessException e1) {
        Util.error("illegal access to a class");
    } catch (ClassNotFoundException e1) {
        Util.error("could not find a review tool class");
    } catch (ReviewFailedException e1) {
        e1.printStackTrace();
        Util.error("Review failed!");
    }

    // we're about to change the repo, so register a shutdown hook to clean it up
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            cleanupGit(git, oldCommit);
        }
    });

    // apply the patch
    try {
        git.apply().setPatch(new FileInputStream(patchFile)).call();
    } catch (PatchFormatException e) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " is malformatted!");
    } catch (PatchApplyException e) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " did not apply correctly!");
    } catch (FileNotFoundException e) {
        assert false;
    } catch (GitAPIException e) {
        Util.error(e.getLocalizedMessage());
    }

    ReviewResults newResults = new ReviewResults(patchName, patch, configuration, true);
    try {
        newResults.review();
    } catch (InstantiationException e1) {
        Util.error("could not instantiate a review tool class!");
    } catch (IllegalAccessException e1) {
        Util.error("illegal access to a class");
    } catch (ClassNotFoundException e1) {
        Util.error("could not find a review tool class");
    } catch (ReviewFailedException e1) {
        e1.printStackTrace();
        Util.error("Review failed!");
    }

    // generate and show the report
    VelocityReport report = new VelocityReport(patch, oldResults, newResults);
    File reportFile = null;
    try {
        reportFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".html");
        org.apache.commons.io.FileUtils.write(reportFile, report.toString(), (String) null);
    } catch (IOException e) {
        Util.error("could not generate the results page!");
    }

    try {
        assert reportFile != null;
        Desktop.getDesktop().open(reportFile);
    } catch (IOException e) {
        Util.error("could not open the results page!");
    }
}

From source file:com.passgit.app.PassGit.java

License:Open Source License

public void updateStatus() {
    Git git = new Git(gitRepository);
    try {/*from   ww w. j a v a2  s . com*/
        Status status = git.status().call();
        processStatus(status);
    } catch (GitAPIException ex) {
        Logger.getLogger(PassGit.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoWorkTreeException ex) {
        Logger.getLogger(PassGit.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

public List<RepoFileInfo> getGITCommitableFiles(File path) throws IOException, GitAPIException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(path).readEnvironment().findGitDir().build();
    Git git = new Git(repository);
    List<RepoFileInfo> fileslist = new ArrayList<RepoFileInfo>();
    InitCommand initCommand = Git.init();
    initCommand.setDirectory(path);/*from  ww  w. j  a  v  a  2s .  c  o m*/
    git = initCommand.call();
    Status status = git.status().call();

    Set<String> added = status.getAdded();
    Set<String> changed = status.getChanged();
    Set<String> conflicting = status.getConflicting();
    Set<String> missing = status.getMissing();
    Set<String> modified = status.getModified();
    Set<String> removed = status.getRemoved();
    Set<String> untracked = status.getUntracked();

    if (!added.isEmpty()) {
        for (String add : added) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + add;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("A");
            fileslist.add(repoFileInfo);
        }
    }

    if (!changed.isEmpty()) {
        for (String change : changed) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + change;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("M");
            fileslist.add(repoFileInfo);
        }
    }

    if (!conflicting.isEmpty()) {
        for (String conflict : conflicting) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + conflict;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("C");
            fileslist.add(repoFileInfo);
        }
    }

    if (!missing.isEmpty()) {
        for (String miss : missing) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + miss;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("!");
            fileslist.add(repoFileInfo);
        }
    }

    if (!modified.isEmpty()) {
        for (String modify : modified) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + modify;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("M");
            fileslist.add(repoFileInfo);
        }
    }

    if (!removed.isEmpty()) {
        for (String remove : removed) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + remove;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("D");
            fileslist.add(repoFileInfo);
        }
    }

    if (!untracked.isEmpty()) {
        for (String untrack : untracked) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + untrack;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("?");
            fileslist.add(repoFileInfo);
        }
    }
    git.getRepository().close();
    return fileslist;
}

From source file:com.spotify.docker.Utils.java

License:Apache License

public static String getGitCommitId()
        throws GitAPIException, DockerException, IOException, MojoExecutionException {

    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    builder.readEnvironment(); // scan environment GIT_* variables
    builder.findGitDir(); // scan up the file system tree

    if (builder.getGitDir() == null) {
        throw new MojoExecutionException("Cannot tag with git commit ID because directory not a git repo");
    }/*from ww  w  .  j a va  2 s  .c  om*/

    final StringBuilder result = new StringBuilder();
    final Repository repo = builder.build();

    try {
        // get the first 7 characters of the latest commit
        final ObjectId head = repo.resolve("HEAD");
        result.append(head.getName().substring(0, 7));
        final Git git = new Git(repo);

        // append first git tag we find
        for (Ref gitTag : git.tagList().call()) {
            if (gitTag.getObjectId().equals(head)) {
                // name is refs/tag/name, so get substring after last slash
                final String name = gitTag.getName();
                result.append(".");
                result.append(name.substring(name.lastIndexOf('/') + 1));
                break;
            }
        }

        // append '.DIRTY' if any files have been modified
        final Status status = git.status().call();
        if (status.hasUncommittedChanges()) {
            result.append(".DIRTY");
        }
    } finally {
        repo.close();
    }

    return result.length() == 0 ? null : result.toString();
}

From source file:com.tenxdev.ovcs.command.AbstractSyncCommand.java

License:Open Source License

/**
 * Commit all changes and push to remote repository
 *
 * @throws OvcsException/*w  ww.ja  v a2s.c o m*/
 *             if changes could not be committed or pushed
 */
protected void commitAndPush() throws OvcsException {
    try {
        final FileRepository fileRepository = getRepoForCurrentDir();
        final Git git = new Git(fileRepository);
        final Status status = git.status().setProgressMonitor(new TextProgressMonitor()).call();
        if (!status.isClean()) {
            git.add().addFilepattern(".").call();
            git.commit().setMessage("initial synchronization").setAll(true).call();
            doPush(git);
        }
    } catch (final GitAPIException e) {
        throw new OvcsException("Unable to commit to git repo: " + e.getMessage(), e);
    }
}

From source file:com.wadpam.gimple.GimpleMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try {/*from w  w  w.  j  av a  2  s.  c om*/
        Repository repo = builder.setGitDir(new File(new File(gitDir), ".git")).readEnvironment().findGitDir()
                .build();
        final String branch = repo.getBranch();
        if (null != branch) {
            if (!currentVersion.endsWith(SUFFIX_SNAPSHOT)) {
                throw new MojoExecutionException("Maven project version not in SNAPSHOT: " + currentVersion);
            }

            getLog().info("gimple executing on " + gitDir);
            getLog().info("branch " + branch);

            if (null == releaseVersion) {
                releaseVersion = currentVersion.substring(0,
                        currentVersion.length() - SUFFIX_SNAPSHOT.length());
            }
            getLog().info(
                    "Transforming version from " + currentVersion + " to release version " + releaseVersion);

            Git git = new Git(repo);
            StatusCommand statusCommand = git.status();
            Status status = statusCommand.call();

            if (!status.isClean()) {
                throw new MojoExecutionException("Git project is not clean: " + status.getUncommittedChanges());
            }

            // versions:set releaseVersion
            transformPomVersions(git, releaseVersion);

            // tag release
            Ref tagRef = git.tag().setMessage(GIMPLE_MAVEN_PLUGIN + "tagging release " + releaseVersion)
                    .setName(releaseVersion).call();

            // next development version
            if (null == nextVersion) {
                nextVersion = getNextDevelopmentVersion(releaseVersion);
            }

            // versions:set nextVersion
            RevCommit nextRef = transformPomVersions(git, nextVersion);

            // push it all
            String developerConnection = mavenProject.getScm().getDeveloperConnection();
            if (developerConnection.startsWith(PREFIX_SCM_GIT)) {
                developerConnection = developerConnection.substring(PREFIX_SCM_GIT.length());
            }
            RefSpec spec = new RefSpec(branch + ":" + branch);
            git.push().setRemote(developerConnection).setRefSpecs(spec).add(tagRef).call();
        }
    } catch (IOException e) {
        throw new MojoExecutionException("executing", e);
    } catch (GitAPIException e) {
        throw new MojoExecutionException("status", e);
    }
}

From source file:com.wadpam.gimple.GimpleMojo.java

License:Open Source License

private RevCommit transformPomVersions(Git git, String newVersion)
        throws MojoExecutionException, GitAPIException {
    executeMojo(plugin("org.codehaus.mojo", "versions-maven-plugin", "2.1"), goal("set"),
            configuration(element(name("newVersion"), newVersion)),
            executionEnvironment(mavenProject, mavenSession, pluginManager));

    StatusCommand statusCommand = git.status();
    Status status = statusCommand.call();

    // git add//from   w  w  w  .j  av  a 2  s . co m
    for (String uncommitted : status.getUncommittedChanges()) {
        getLog().info("  adding to git index: " + uncommitted);
        AddCommand add = git.add();
        add.addFilepattern(uncommitted);
        add.call();
    }

    // git commit
    CommitCommand commit = git.commit();
    commit.setMessage(GIMPLE_MAVEN_PLUGIN + "pom version " + newVersion);
    return commit.call();
}