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:no.neworder.vcs.GitStatus.java

License:Open Source License

public GitStatus(File directory) throws IOException {
    File repositoryPath = new File(directory.getAbsolutePath());
    RepositoryBuilder repositoryBuilder = new RepositoryBuilder();
    Repository repository = repositoryBuilder.setWorkTree(repositoryPath).build();
    Git git = new Git(repository);
    status = git.status().call();
}

From source file:org.apache.maven.scm.provider.git.jgit.command.checkin.JGitCheckInCommand.java

License:Apache License

/**
 * {@inheritDoc}/* ww w  . j  a va  2  s .  c om*/
 */
protected CheckInScmResult executeCheckInCommand(ScmProviderRepository repo, ScmFileSet fileSet, String message,
        ScmVersion version) throws ScmException {

    Git git = null;
    try {
        File basedir = fileSet.getBasedir();
        git = Git.open(basedir);

        boolean doCommit = false;

        if (!fileSet.getFileList().isEmpty()) {
            doCommit = JGitUtils.addAllFiles(git, fileSet).size() > 0;
        } else {
            // add all tracked files which are modified manually
            Set<String> changeds = git.status().call().getModified();
            if (changeds.isEmpty()) {
                // warn there is nothing to add
                getLogger().warn("there are no files to be added");
                doCommit = false;
            } else {
                AddCommand add = git.add();
                for (String changed : changeds) {
                    getLogger().debug("add manualy: " + changed);
                    add.addFilepattern(changed);
                    doCommit = true;
                }
                add.call();
            }
        }

        List<ScmFile> checkedInFiles = Collections.emptyList();
        if (doCommit) {
            UserInfo author = getAuthor(repo, git);
            UserInfo committer = getCommitter(repo, git);

            CommitCommand command = git.commit().setMessage(message).setAuthor(author.name, author.email);
            command.setCommitter(committer.name, committer.email);
            RevCommit commitRev = command.call();

            getLogger().info("commit done: " + commitRev.getShortMessage());
            checkedInFiles = JGitUtils.getFilesInCommit(git.getRepository(), commitRev);
            if (getLogger().isDebugEnabled()) {
                for (ScmFile scmFile : checkedInFiles) {
                    getLogger().debug("in commit: " + scmFile);
                }
            }
        }

        if (repo.isPushChanges()) {
            String branch = version != null ? version.getName() : null;
            if (StringUtils.isBlank(branch)) {
                branch = git.getRepository().getBranch();
            }
            RefSpec refSpec = new RefSpec(Constants.R_HEADS + branch + ":" + Constants.R_HEADS + branch);
            getLogger().info("push changes to remote... " + refSpec.toString());
            JGitUtils.push(getLogger(), git, (GitScmProviderRepository) repo, refSpec);
        }

        return new CheckInScmResult("JGit checkin", checkedInFiles);
    } catch (Exception e) {
        throw new ScmException("JGit checkin failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.apache.maven.scm.provider.git.jgit.command.JGitUtils.java

License:Apache License

/**
 * Adds all files in the given fileSet to the repository.
 *
 * @param git     the repo to add the files to
 * @param fileSet the set of files within the workspace, the files are added
 *                relative to the basedir of this fileset
 * @return a list of added files/*from  www  . jav  a2 s  .  c  o m*/
 * @throws GitAPIException
 * @throws NoFilepatternException
 */
public static List<ScmFile> addAllFiles(Git git, ScmFileSet fileSet)
        throws GitAPIException, NoFilepatternException {
    URI baseUri = fileSet.getBasedir().toURI();
    AddCommand add = git.add();
    for (File file : fileSet.getFileList()) {
        if (!file.isAbsolute()) {
            file = new File(fileSet.getBasedir().getPath(), file.getPath());
        }

        if (file.exists()) {
            String path = relativize(baseUri, file);
            add.addFilepattern(path);
            add.addFilepattern(file.getAbsolutePath());
        }
    }
    add.call();

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

    Set<String> allInIndex = new HashSet<String>();
    allInIndex.addAll(status.getAdded());
    allInIndex.addAll(status.getChanged());

    // System.out.println("All in index: "+allInIndex.size());

    List<ScmFile> addedFiles = new ArrayList<ScmFile>(allInIndex.size());

    // rewrite all detected files to now have status 'checked_in'
    for (String entry : allInIndex) {
        ScmFile scmfile = new ScmFile(entry, ScmFileStatus.ADDED);

        // if a specific fileSet is given, we have to check if the file is
        // really tracked
        for (Iterator<File> itfl = fileSet.getFileList().iterator(); itfl.hasNext();) {
            String path = FilenameUtils.normalizeFilename(relativize(baseUri, itfl.next()));
            if (path.equals(FilenameUtils.normalizeFilename(scmfile.getPath()))) {
                addedFiles.add(scmfile);
            }
        }
    }
    return addedFiles;
}

From source file:org.apache.maven.scm.provider.git.jgit.command.status.JGitStatusCommand.java

License:Apache License

/**
 * {@inheritDoc}/*from  w ww  .  j  a  va 2  s  .  c  o  m*/
 */
protected StatusScmResult executeStatusCommand(ScmProviderRepository repo, ScmFileSet fileSet)
        throws ScmException {
    Git git = null;
    try {
        git = Git.open(fileSet.getBasedir());
        Status status = git.status().call();
        List<ScmFile> changedFiles = getFileStati(status);

        return new StatusScmResult("JGit status", changedFiles);
    } catch (Exception e) {
        throw new ScmException("JGit status failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java

License:Apache License

protected void pushChanges(final File target) {
    try {/*from w w w .j a v a 2 s .  c o  m*/
        //
        // Grab our working repository
        //
        Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath();
        final Git git = Git.open(repoPath.toFile());
        //
        // Get our status
        //
        final String base;
        Status status;
        if (target == null) {
            base = ".";
        } else {
            Path relativePath = repoPath.relativize(Paths.get(target.getPath()));
            base = relativePath.toString();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Status on base: " + base);
        }
        status = git.status().addPath(base).call();
        //
        // Check if its clean
        //
        if (status.isClean()) {
            //
            // Its clean
            //
            AdminNotification.warn(target.getName() + " is clean!");
            return;
        }
        //
        // Create the window
        //
        final GitPushWindow window = new GitPushWindow(git, target, status);
        window.setCaption("Push Changes");
        window.setModal(true);
        window.addCloseListener(new CloseListener() {
            private static final long serialVersionUID = 1L;

            @Override
            public void windowClose(CloseEvent e) {
                if (window.isSaved() == false) {
                    return;
                }
                try {
                    //
                    // Needs to be added first
                    //
                    DirCache cache = git.add().addFilepattern(base).call();
                    for (int i = 0; i < cache.getEntryCount(); i++) {
                        DirCacheEntry entry = cache.getEntry(i);
                        if (logger.isDebugEnabled()) {
                            logger.debug("Entry: " + entry);
                        }
                    }
                    //
                    // Next they need to be committed
                    //
                    RevCommit rev = git.commit().setMessage(window.getComment()).call();
                    if (logger.isDebugEnabled()) {
                        logger.debug("RevCommit: " + rev);
                    }
                    //
                    // Now we can push changes to the Git repository
                    //
                    Iterable<PushResult> results = git.push().call();
                    for (PushResult result : results) {
                        logger.info(result);
                    }
                    //
                    // Have the container fire an item set change notification
                    //
                    self.treeContainer.updateItem(target);
                } catch (NoWorkTreeException | GitAPIException e1) {
                    logger.error(e);
                    AdminNotification.error("Exception occurred while trying to push: " + e1);
                }
            }

        });
        window.center();
        UI.getCurrent().addWindow(window);
    } catch (IOException | GitAPIException e) {
        logger.error(e);
        AdminNotification.error("Exception occurred while trying to get status: " + e);
    }
}

From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java

License:Apache License

protected void openPolicyTab(File policy, boolean readOnly) {
    ///*  w w  w. ja  v  a2  s .  c om*/
    // Sanity check
    //
    assert policy != null;
    assert policy.isFile();
    if (policy == null || !policy.isFile()) {
        throw new IllegalArgumentException("You must specify a file.");
    }
    Status status;
    Path relativePath;
    String base;
    try {
        //
        // Grab our working repository
        //
        Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath();
        final Git git = Git.open(repoPath.toFile());
        //
        // Get our status
        //
        relativePath = repoPath.relativize(Paths.get(policy.getPath()));
        base = relativePath.toString();
        if (logger.isDebugEnabled()) {
            logger.debug("Status on base: " + base);
        }
        status = git.status().addPath(base).call();
    } catch (NoWorkTreeException | IOException | GitAPIException e) {
        logger.error("Failed to get status on " + policy + " " + e);
        AdminNotification.error("Could not get Git status on the file.");
        return;
    }
    //
    // Check if its clean
    //
    if (status.isClean() == false) {
        //
        // Check if its conflicting
        //
        for (String conflict : status.getConflicting()) {
            if (conflict.equals(base)) {
                //
                // Yes - we won't be able to edit it
                //
                AdminNotification.error("Policy has conflicts with master, please synchronize the repository.");
                return;
            }
        }
    }
    //
    // Check to see if there already is a tab open
    //
    Iterator<Component> iter = self.tabSheet.iterator();
    while (iter.hasNext()) {
        Component c = iter.next();
        if (c instanceof PolicyEditor) {
            Object data = ((PolicyEditor) c).getData();
            if (data != null && data instanceof File && ((File) data).equals(policy)) {
                self.tabSheet.setSelectedTab(c);
                return;
            }
        }
    }
    //
    // No tab is open, create a new one
    //
    PolicyEditor editor = null;
    try {
        editor = new PolicyEditor(policy, this.treeContainer, readOnly);
    } catch (IOException e) {
        logger.error("Failed to open policy");
        editor = null;
    }
    if (editor != null) {
        editor.setWidth("100%");
        Tab tab = self.tabSheet.addTab(editor);
        editor.setTab(tab);
        tab.setClosable(true);

        self.tabSheet.setSelectedTab(editor);
    } else {
        AdminNotification.error("The Policy File is not a Xacml 3.0 policy.");
    }
}

From source file:org.apache.openaz.xacml.admin.view.windows.GitPushWindow.java

License:Apache License

protected void refreshStatus() {
    try {//from   ww  w . j a v a 2s . c om
        //
        // Grab our working repository
        //
        Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath();
        final Git git = Git.open(repoPath.toFile());
        //
        // Get our status
        //
        final String base;
        Status status;
        if (target == null) {
            base = ".";
        } else {
            Path relativePath = repoPath.relativize(Paths.get(target.getPath()));
            base = relativePath.toString();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Status on base: " + base);
        }
        status = git.status().addPath(base).call();
        //
        // Pass it to our container
        //
        this.container.refreshStatus(status);
        this.tableChanges.refreshRowCache();
    } catch (NoWorkTreeException | IOException | GitAPIException e) {
        String error = "Failed to refresh status: " + e.getLocalizedMessage();
        logger.error(error);
    }
}

From source file:org.apache.stratos.cartridge.agent.artifact.deployment.synchronizer.git.impl.GitBasedArtifactRepository.java

License:Apache License

/**
 * Commits any changes in the local repository to the relevant remote repository
 *
 * @return/*from   w w w .  jav  a2 s . co  m*/
 */
public void commit(RepositoryInformation repoInfo) {
    // TODO implement later, this is applicable for management node.

    // for (Entry<Integer, RepositoryContext> tenantMap : tenantToRepoContextMap
    //         .entrySet()) {

    int tenantId = Integer.parseInt(repoInfo.getTenantId());
    //log.info("map count has values..tenant Id : " + tenantId);

    RepositoryContext gitRepoCtx = retrieveCachedGitContext(tenantId);
    Git git = gitRepoCtx.getGit();
    StatusCommand statusCmd = git.status();
    Status status = null;
    try {
        status = statusCmd.call();

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

    }
    //log.info("status : " + status.toString());
    if (status.isClean()) {// no changes, nothing to commit
        if (log.isDebugEnabled()) {
            log.debug("No changes detected in the local repository for tenant " + tenantId);
        }

        return;
    }

    addArtifacts(gitRepoCtx, getNewArtifacts(status));
    addArtifacts(gitRepoCtx, getModifiedArtifacts(status));
    removeArtifacts(gitRepoCtx, getRemovedArtifacts(status));
    commitToLocalRepo(gitRepoCtx);
    pushToRemoteRepo(gitRepoCtx);

    //}
    //return false;
}

From source file:org.apache.stratos.manager.utils.RepositoryCreator.java

License:Apache License

private void createGitFolderStructure(String tenantDomain, String cartridgeName, String[] dirArray)
        throws Exception {

    if (log.isDebugEnabled()) {
        log.debug("Creating git repo folder structure  ");
    }/*from  www. j a va 2 s . co m*/

    String parentDirName = "/tmp/" + UUID.randomUUID().toString();
    CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(
            System.getProperty(CartridgeConstants.INTERNAL_GIT_USERNAME),
            System.getProperty(CartridgeConstants.INTERNAL_GIT_PASSWORD).toCharArray());
    // Clone
    // --------------------------
    FileRepository localRepo = null;
    try {
        localRepo = new FileRepository(new File(parentDirName + "/.git"));
    } catch (IOException e) {
        log.error("Exception occurred in creating a new file repository. Reason: " + e.getMessage());
        throw e;
    }

    Git git = new Git(localRepo);

    CloneCommand cloneCmd = git.cloneRepository().setURI(System.getProperty(CartridgeConstants.INTERNAL_GIT_URL)
            + "/git/" + tenantDomain + "/" + cartridgeName + ".git").setDirectory(new File(parentDirName));

    cloneCmd.setCredentialsProvider(credentialsProvider);
    try {
        log.debug("Clonning git repo");
        cloneCmd.call();
    } catch (Exception e1) {
        log.error("Exception occurred in cloning Repo. Reason: " + e1.getMessage());
        throw e1;
    }
    // ------------------------------------

    // --- Adding directory structure --------

    File parentDir = new File(parentDirName);
    parentDir.mkdir();

    for (String string : dirArray) {
        String[] arr = string.split("=");
        if (log.isDebugEnabled()) {
            log.debug("Creating dir: " + arr[0]);
        }
        File parentFile = new File(parentDirName + "/" + arr[0]);
        parentFile.mkdirs();

        File filess = new File(parentFile, "README");
        String content = "Content goes here";

        filess.createNewFile();
        FileWriter fw = new FileWriter(filess.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();
    }
    // ----------------------------------------------------------

    // ---- Git status ---------------
    StatusCommand s = git.status();
    Status status = null;
    try {
        log.debug("Getting git repo status");
        status = s.call();
    } catch (Exception e) {
        log.error("Exception occurred in git status check. Reason: " + e.getMessage());
        throw e;
    }
    // --------------------------------

    // ---------- Git add ---------------
    AddCommand addCmd = git.add();
    Iterator<String> it = status.getUntracked().iterator();

    while (it.hasNext()) {
        addCmd.addFilepattern(it.next());
    }

    try {
        log.debug("Adding files to git repo");
        addCmd.call();
    } catch (Exception e) {
        log.error("Exception occurred in adding files. Reason: " + e.getMessage());
        throw e;
    }
    // -----------------------------------------

    // ------- Git commit -----------------------

    CommitCommand commitCmd = git.commit();
    commitCmd.setMessage("Adding directories");

    try {
        log.debug("Committing git repo");
        commitCmd.call();
    } catch (Exception e) {
        log.error("Exception occurred in committing . Reason: " + e.getMessage());
        throw e;
    }
    // --------------------------------------------

    // --------- Git push -----------------------
    PushCommand pushCmd = git.push();
    pushCmd.setCredentialsProvider(credentialsProvider);
    try {
        log.debug("Git repo push");
        pushCmd.call();
    } catch (Exception e) {
        log.error("Exception occurred in Git push . Reason: " + e.getMessage());
        throw e;
    }

    try {
        deleteDirectory(new File(parentDirName));
    } catch (Exception e) {
        log.error("Exception occurred in deleting temp files. Reason: " + e.getMessage());
        throw e;
    }

    log.info(" Folder structure  is created ..... ");

}

From source file:org.apache.usergrid.chop.plugin.Utils.java

License:Apache License

/**
 * @param gitConfigFolder e.g. /your/project/root/.git
 *
 * @return Returns true if 'git status' has modified files inside the 'Changes to be committed' section
 *//*w  w  w.  j  av  a 2 s. c o m*/
public static boolean isCommitNecessary(String gitConfigFolder) throws MojoExecutionException {
    try {
        Repository repo = new FileRepository(gitConfigFolder);
        Git git = new Git(repo);

        Status status = git.status().call();
        Set<String> modified = status.getModified();

        return (modified.size() != 0);
    } catch (Exception e) {
        throw new MojoExecutionException("Error trying to find out if git commit is needed", e);
    }
}