Java Code Examples for org.eclipse.jgit.api.Status#isClean()

The following examples show how to use org.eclipse.jgit.api.Status#isClean() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GitMatchers.java    From multi-module-maven-release-plugin with MIT License 6 votes vote down vote up
public static Matcher<Git> hasCleanWorkingDirectory() {
    return new TypeSafeDiagnosingMatcher<Git>() {
        @Override
        protected boolean matchesSafely(Git git, Description mismatchDescription) {
            try {
                Status status = git.status().call();
                if (!status.isClean()) {
                    String start = "Uncommitted changes in ";
                    String end = " at " + git.getRepository().getWorkTree().getAbsolutePath();
                    mismatchDescription.appendValueList(start, ", ", end, status.getUncommittedChanges());
                }
                return status.isClean();
            } catch (GitAPIException e) {
                throw new RuntimeException("Error checking git status", e);
            }
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("A git directory with no staged or unstaged changes");
        }
    };
}
 
Example 2
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
public String commitFile(Repository repo, String site, String path, String comment, PersonIdent user) {
    String commitId = null;
    String gitPath = getGitPath(path);
    Status status;

    try (Git git = new Git(repo)) {
        status = git.status().addPath(gitPath).call();

        // TODO: SJ: Below needs more thought and refactoring to detect issues with git repo and report them
        if (status.hasUncommittedChanges() || !status.isClean()) {
            RevCommit commit;
            commit = git.commit().setOnly(gitPath).setAuthor(user).setCommitter(user).setMessage(comment).call();
            commitId = commit.getName();
        }

        git.close();
    } catch (GitAPIException e) {
        logger.error("error adding and committing file to git: site: " + site + " path: " + path, e);
    }

    return commitId;
}
 
Example 3
Source File: AbstractUpgradeOperation.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
protected void commitAllChanges(String site) throws UpgradeException {
    try {
        Path repositoryPath = getRepositoryPath(site);
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repo = builder
            .setGitDir(repositoryPath.toFile())
            .readEnvironment()
            .findGitDir()
            .build();

        try (Git git = new Git(repo)) {
            git.add().addFilepattern(".").call();

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

            if (status.hasUncommittedChanges() || !status.isClean()) {
                git.commit()
                    .setAll(true)
                    .setMessage(getCommitMessage())
                    .call();
            }
        }
    } catch (IOException | GitAPIException e) {
        throw new UpgradeException("Error committing changes for site " + site, e);
    }
}
 
Example 4
Source File: GitMergeUtil.java    From MergeProcessor with Apache License 2.0 5 votes vote down vote up
/**
 * {@code git status} {@code git cherry}
 */
private void checkStatus() {
	try {
		final Status result = repo.status().call();
		if (!result.isClean()) {
			exception = new MergeUnitException(String.format("The local repository is not clean: '%s'", repo)); //$NON-NLS-1$
		} else {
			/*
			 * JGit does not support "git cherry", so checking for unpushed commits is done
			 * by comparing the last commit id of the local and the remote branch. If JGit
			 * supports "git cherry" it should be refactored to this command.
			 */
			final String localTargetBranch = getLocalTargetBranch();
			if (localTargetBranch == null) {
				return;
			}
			final RevCommit lastCommitOfLocalBranch = getLastCommit(localTargetBranch);
			if (lastCommitOfLocalBranch == null) {
				return;
			}
			final RevCommit lastCommitOfRemoteBranch = getLastCommit(mergeUnit.getBranchTarget());
			if (lastCommitOfRemoteBranch == null) {
				return;
			}
			if (!lastCommitOfLocalBranch.equals(lastCommitOfRemoteBranch)) {
				exception = new MergeUnitException(
						String.format("The local repository is not clean: '%s'", repo)); //$NON-NLS-1$
			}
		}
	} catch (GitAPIException e) {
		exception = new MergeUnitException(
				String.format("Could not check the status of the local repository '%s'.", repo), e); //$NON-NLS-1$
	}
}
 
Example 5
Source File: GitRepository.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Commit all changes if there are uncommitted changes.
 *
 * @param msg the commit message.
 * @throws GitAPIException
 */
public void commit(String msg) throws GitAPIException {
    try (Git git = getGit()) {
        Status status = git.status().call();
        if (!status.isClean()) {
            git.commit().setMessage(msg).setAll(true).setNoVerify(true).call();
        }
    }
}
 
Example 6
Source File: UpToDateTask.java    From ant-git-tasks with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() throws BuildException {
        Repository repo = git.getRepository();

        FileTreeIterator workingTreeIterator = new FileTreeIterator(repo);

        try {
                IndexDiff diff = new IndexDiff(repo, Constants.HEAD, workingTreeIterator);
                diff.diff();

                Status status = new Status(diff);

                if (!status.isClean()) {
                        if (modificationExistProperty != null) {
                                getProject().setProperty(modificationExistProperty, "true");
                        }

                        if (isFailOnError()) {
                                StringBuilder msg = new StringBuilder();
                                msg.append("The Git tree was modified.");
                                msg.append("\n").append("Changed:").append(status.getChanged());
                                msg.append("\n").append("Added:").append(status.getAdded());
                                msg.append("\n").append("Modified:").append(status.getModified());
                                msg.append("\n").append("Missing:").append(status.getMissing());
                                msg.append("\n").append("Removed:").append(status.getRemoved());
                                msg.append("\n").append("Untracked:").append(status.getUntracked());

                                throw new GitBuildException(String.format(STATUS_NOT_CLEAN_TEMPLATE, msg.toString()));
                        }
                } else {
                        log(MESSAGE_UPTODATE_SUCCESS);
                }
        } catch (IOException ioe) {
                throw new GitBuildException(MESSAGE_UPTODATE_FAILED, ioe);
        }

}
 
Example 7
Source File: GitFlowMetaData.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
boolean isGitDirectoryClean() throws GitAPIException {
    final Status status = new Git(gitRepo).status().call();
    return status.isClean() && !status.hasUncommittedChanges();
}
 
Example 8
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * bootstrap the repository
 */
public void bootstrap() throws Exception {
    // Initialize the helper
    helper = new GitContentRepositoryHelper(studioConfiguration, servicesConfig, userServiceInternal,
            securityService);

    encryptor = new PbkAesTextEncryptor(studioConfiguration.getProperty(SECURITY_CIPHER_KEY),
            studioConfiguration.getProperty(SECURITY_CIPHER_SALT));

    if (Boolean.parseBoolean(studioConfiguration.getProperty(BOOTSTRAP_REPO)) && helper.createGlobalRepo()) {
        // Copy the global config defaults to the global site
        // Build a path to the bootstrap repo (the repo that ships with Studio)
        String bootstrapFolderPath = this.ctx.getRealPath(FILE_SEPARATOR + BOOTSTRAP_REPO_PATH +
                FILE_SEPARATOR + BOOTSTRAP_REPO_GLOBAL_PATH);
        Path source = java.nio.file.FileSystems.getDefault().getPath(bootstrapFolderPath);

        logger.info("Bootstrapping with baseline @ " + source.toFile().toString());

        // Copy the bootstrap repo to the global repo
        Path globalConfigPath = helper.buildRepoPath(GLOBAL);
        TreeCopier tc = new TreeCopier(source,
                globalConfigPath);
        EnumSet<FileVisitOption> opts = EnumSet.of(FOLLOW_LINKS);
        Files.walkFileTree(source, opts, MAX_VALUE, tc);

        String studioManifestLocation = this.ctx.getRealPath(STUDIO_MANIFEST_LOCATION);
        if (Files.exists(Paths.get(studioManifestLocation))) {
            FileUtils.copyFile(Paths.get(studioManifestLocation).toFile(),
                    Paths.get(globalConfigPath.toAbsolutePath().toString(),
                            studioConfiguration.getProperty(BLUE_PRINTS_PATH), "BLUEPRINTS.MF").toFile());
        }
        Repository globalConfigRepo = helper.getRepository(EMPTY, GLOBAL);
        try (Git git = new Git(globalConfigRepo)) {

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

            if (status.hasUncommittedChanges() || !status.isClean()) {
                // Commit everything
                // TODO: Consider what to do with the commitId in the future
                git.add().addFilepattern(GIT_COMMIT_ALL_ITEMS).call();
                git.commit().setMessage(helper.getCommitMessage(REPO_INITIAL_COMMIT_COMMIT_MESSAGE)).call();
            }

            git.close();
        } catch (GitAPIException err) {
            logger.error("error creating initial commit for global configuration", err);
        }
    }

    // Create global repository object
    if (!helper.buildGlobalRepo()) {
        logger.error("Failed to create global repository!");
    }
}
 
Example 9
Source File: GitRepos.java    From gradle-gitsemver with Apache License 2.0 4 votes vote down vote up
public static boolean isDirty(Repository repo) throws NoWorkTreeException,
            GitAPIException {
        Git git = new Git(repo);
    Status status = git.status().call();
    return !status.isClean();
}
 
Example 10
Source File: GitUtils.java    From jgitver with Apache License 2.0 2 votes vote down vote up
/**
 * Checks that underlying repository is dirty (modified with uncommitted changes).
 * @return true if the underlying repository is dirty, false otherwise
 * @throws GitAPIException if a git eeror occured while computing status
 * @throws NoWorkTreeException  if the underlying repsoitory directory is not git managed 
 */
public static boolean isDirty(Git git) throws NoWorkTreeException, GitAPIException {
    Status status = git.status().call();
    return !status.isClean();
}