org.eclipse.jgit.api.Status Java Examples
The following examples show how to use
org.eclipse.jgit.api.Status.
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: GitMigrator.java From rtc2gitcli with MIT License | 6 votes |
private Set<String> handleAdded(Status status) { Set<String> toAdd = new HashSet<String>(); // go over untracked files for (String untracked : status.getUntracked()) { // add it to the index toAdd.add(untracked); } // go over modified files for (String modified : status.getModified()) { // adds a modified entry to the index toAdd.add(modified); } handleGlobalFileExtensions(toAdd); handleJazzignores(toAdd); return toAdd; }
Example #2
Source File: JGitEnvironmentRepositoryTests.java From spring-cloud-config with Apache License 2.0 | 6 votes |
@Test public void shouldPullForcepullNotClean() throws Exception { Git git = mock(Git.class); StatusCommand statusCommand = mock(StatusCommand.class); Status status = mock(Status.class); Repository repository = mock(Repository.class); StoredConfig storedConfig = mock(StoredConfig.class); when(git.status()).thenReturn(statusCommand); when(git.getRepository()).thenReturn(repository); when(repository.getConfig()).thenReturn(storedConfig); when(storedConfig.getString("remote", "origin", "url")) .thenReturn("http://example/git"); when(statusCommand.call()).thenReturn(status); when(status.isClean()).thenReturn(false); JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment, new JGitEnvironmentProperties()); repo.setForcePull(true); boolean shouldPull = repo.shouldPull(git); assertThat(shouldPull).as("shouldPull was false").isTrue(); }
Example #3
Source File: JGitEnvironmentRepositoryTests.java From spring-cloud-config with Apache License 2.0 | 6 votes |
@Test public void shouldPullNotClean() throws Exception { Git git = mock(Git.class); StatusCommand statusCommand = mock(StatusCommand.class); Status status = mock(Status.class); Repository repository = mock(Repository.class); StoredConfig storedConfig = mock(StoredConfig.class); when(git.status()).thenReturn(statusCommand); when(git.getRepository()).thenReturn(repository); when(repository.getConfig()).thenReturn(storedConfig); when(storedConfig.getString("remote", "origin", "url")) .thenReturn("http://example/git"); when(statusCommand.call()).thenReturn(status); when(status.isClean()).thenReturn(false); JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment, new JGitEnvironmentProperties()); boolean shouldPull = repo.shouldPull(git); assertThat(shouldPull).as("shouldPull was true").isFalse(); }
Example #4
Source File: JGitEnvironmentRepositoryTests.java From spring-cloud-config with Apache License 2.0 | 6 votes |
@Test public void shouldPullClean() throws Exception { Git git = mock(Git.class); StatusCommand statusCommand = mock(StatusCommand.class); Status status = mock(Status.class); Repository repository = mock(Repository.class); StoredConfig storedConfig = mock(StoredConfig.class); when(git.status()).thenReturn(statusCommand); when(git.getRepository()).thenReturn(repository); when(repository.getConfig()).thenReturn(storedConfig); when(storedConfig.getString("remote", "origin", "url")) .thenReturn("http://example/git"); when(statusCommand.call()).thenReturn(status); when(status.isClean()).thenReturn(true); JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment, new JGitEnvironmentProperties()); boolean shouldPull = repo.shouldPull(git); assertThat(shouldPull).as("shouldPull was false").isTrue(); }
Example #5
Source File: DevicesGit.java From Flashtool with GNU General Public License v3.0 | 6 votes |
public static void pullRepository() { try { logger.info("Scanning devices folder for changes."); git.add().addFilepattern(".").call(); Status status = git.status().call(); if (status.getChanged().size()>0 || status.getAdded().size()>0 || status.getModified().size()>0) { logger.info("Changes have been found. Doing a hard reset (removing user modifications)."); ResetCommand reset = git.reset(); reset.setMode(ResetType.HARD); reset.setRef(Constants.HEAD); reset.call(); } logger.info("Pulling changes from github."); git.pull().call(); } catch (NoHeadException e) { logger.info("Pull failed. Trying to clone repository instead"); closeRepository(); cloneRepository(); } catch (Exception e1) { closeRepository(); } }
Example #6
Source File: GitPushWindow.java From XACML with MIT License | 6 votes |
/** * The constructor should first build the main layout, set the * composition root and then do any custom initialization. * * The constructor will not be automatically regenerated by the * visual editor. * @param git * @param target * @param status */ public GitPushWindow(Git git, File target, Status status) { buildMainLayout(); //setCompositionRoot(mainLayout); setContent(mainLayout); // // Save data // this.git = git; this.target = target; this.container = new GitStatusContainer(status); // // Set our shortcuts // this.setCloseShortcut(KeyCode.ESCAPE); // // Initialize GUI // this.initializeText(); this.initializeTable(status); this.initializeButtons(); // // Focus // this.textAreaComments.focus(); }
Example #7
Source File: GitPushWindow.java From XACML with MIT License | 6 votes |
protected void initializeTable(Status status) { // // Setup the table // this.tableChanges.setContainerDataSource(this.container); this.tableChanges.setPageLength(this.container.size()); this.tableChanges.setImmediate(true); // // Generate column // this.tableChanges.addGeneratedColumn("Entry", new ColumnGenerator() { private static final long serialVersionUID = 1L; @Override public Object generateCell(Table source, Object itemId, Object columnId) { Item item = self.container.getItem(itemId); assert(item != null); if (item instanceof StatusItem) { return self.generateGitEntryComponent(((StatusItem) item).getGitEntry()); } assert(item instanceof StatusItem); return null; } }); }
Example #8
Source File: GitManagerTest.java From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testStashWithUntractked() throws IOException, GitAPIException, GitOperationException { try (Git git = Git.wrap(repository)) { writeTrashFile("test", "This is readme"); writeTrashFile("notTractedFile", "this file is untracked"); git.add().addFilepattern("test").call(); gitMgr.createStash(ws, false, null); Status status = git.status().call(); assertEquals(0, status.getAdded().size()); assertEquals(1, status.getUntracked().size()); gitMgr.applyStash(ws, null, false, false); status = git.status().call(); assertEquals(1, status.getAdded().size()); assertEquals(1, status.getUntracked().size()); } }
Example #9
Source File: GitConfigurationPersister.java From wildfly-core with GNU Lesser General Public License v2.1 | 6 votes |
@Override public String snapshot(String name, String comment) throws ConfigurationPersistenceException { boolean noComment = (comment ==null || comment.isEmpty()); String message = noComment ? SNAPSHOT_PREFIX + FORMATTER.format(LocalDateTime.now()) : comment; String tagName = (name ==null || name.isEmpty()) ? SNAPSHOT_PREFIX + FORMATTER.format(LocalDateTime.now()) : name; try (Git git = gitRepository.getGit()) { Status status = git.status().call(); List<Ref> tags = git.tagList().call(); String refTagName = R_TAGS + tagName; for(Ref tag : tags) { if(refTagName.equals(tag.getName())) { throw MGMT_OP_LOGGER.snapshotAlreadyExistError(tagName); } } //if comment is not null if(status.hasUncommittedChanges() || !noComment) { git.commit().setMessage(message).setAll(true).setNoVerify(true).call(); } git.tag().setName(tagName).setMessage(message).call(); } catch (GitAPIException ex) { throw MGMT_OP_LOGGER.failedToPersistConfiguration(ex, message, ex.getMessage()); } return message; }
Example #10
Source File: GitContentRepositoryHelper.java From studio with GNU General Public License v3.0 | 6 votes |
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 #11
Source File: AbstractUpgradeOperation.java From studio with GNU General Public License v3.0 | 6 votes |
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 #12
Source File: RepositoryManagementServiceInternalImpl.java From studio with GNU General Public License v3.0 | 6 votes |
@Override public RepositoryStatus getRepositoryStatus(String siteId) throws CryptoException, ServiceLayerException { GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration); Repository repo = helper.getRepository(siteId, SANDBOX); RepositoryStatus repositoryStatus = new RepositoryStatus(); logger.debug("Execute git status and return conflicting paths and uncommitted changes"); try (Git git = new Git(repo)) { Status status = git.status().call(); repositoryStatus.setClean(status.isClean()); repositoryStatus.setConflicting(status.getConflicting()); repositoryStatus.setUncommittedChanges(status.getUncommittedChanges()); } catch (GitAPIException e) { logger.error("Error while getting repository status for site " + siteId, e); throw new ServiceLayerException("Error getting repository status for site " + siteId, e); } return repositoryStatus; }
Example #13
Source File: BackupService.java From app-runner with MIT License | 6 votes |
public synchronized void backup() throws Exception { repo.add().setUpdate(false).addFilepattern(".").call(); Status status = repo.status().setIgnoreSubmodules(SubmoduleWalk.IgnoreSubmoduleMode.ALL).call(); log.debug("status.getUncommittedChanges() = " + status.getUncommittedChanges()); if (!status.getUncommittedChanges().isEmpty()) { for (String missingPath : status.getMissing()) { repo.rm().addFilepattern(missingPath).call(); } log.info("Changes detected in the following files: " + status.getUncommittedChanges()); repo.commit() .setMessage("Backing up data dir") .setAuthor("AppRunner BackupService", "[email protected]") .call(); Iterable<PushResult> pushResults = repo.push().call(); for (PushResult pushResult : pushResults) { log.info("Result of pushing to remote: " + pushResult.getRemoteUpdates()); } } else { log.info("No changes to back up"); } }
Example #14
Source File: GitUtils.java From singleton with Eclipse Public License 2.0 | 6 votes |
public static void gitShowStatus(File repoDir) { Status status = null; Git git = null; try { git = Git.open(repoDir); status = git.status().call(); logger.info("Git Change: " + status.getChanged()); logger.info("Git Modified: " + status.getModified()); logger.info("Git UncommittedChanges: " + status.getUncommittedChanges()); logger.info("Git Untracked: " + status.getUntracked()); } catch (Exception e) { logger.error(e.getMessage() + " : " + repoDir.getAbsolutePath()); } finally { if (git != null) { git.close(); } } }
Example #15
Source File: GitMigrator.java From rtc2gitcli with MIT License | 6 votes |
private Set<String> handleRemoved(Status status, Set<String> toRestore) { Set<String> toRemove = new HashSet<String>(); // go over all deleted files for (String removed : status.getMissing()) { Matcher matcher = GITIGNORE_PATTERN.matcher(removed); if (matcher.matches()) { File jazzignore = new File(rootDir, matcher.group(1).concat(".jazzignore")); if (jazzignore.exists()) { // restore .gitignore files that where deleted if corresponding .jazzignore exists toRestore.add(removed); continue; } } // adds removed entry to the index toRemove.add(removed); } handleJazzignores(toRemove); return toRemove; }
Example #16
Source File: GitMatchers.java From multi-module-maven-release-plugin with MIT License | 6 votes |
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 #17
Source File: GitMergeUtil.java From MergeProcessor with Apache License 2.0 | 6 votes |
/** * {@code git push} */ private void push() { try { final Iterable<PushResult> resultIterable = repo.push().call(); for (final PushResult pushResult : resultIterable) { for (RemoteRefUpdate refUpdate : pushResult.getRemoteUpdates()) { if (refUpdate.getStatus() != RemoteRefUpdate.Status.OK) { // Push was rejected exception = new MergeUnitException(String .format("Could not push the local repository: '%s'", pushResult.getMessages())); return; } } } } catch (GitAPIException e) { exception = new MergeUnitException(String.format("Could not push the local repository '%s'.", repo), e); //$NON-NLS-1$ } }
Example #18
Source File: UIGit.java From hop with Apache License 2.0 | 6 votes |
@Override public List<UIFile> getUnstagedFiles() { List<UIFile> files = new ArrayList<UIFile>(); Status status = null; try { status = git.status().call(); } catch ( Exception e ) { e.printStackTrace(); return files; } status.getUntracked().forEach( name -> { files.add( new UIFile( name, ChangeType.ADD, false ) ); } ); status.getModified().forEach( name -> { files.add( new UIFile( name, ChangeType.MODIFY, false ) ); } ); status.getConflicting().forEach( name -> { files.add( new UIFile( name, ChangeType.MODIFY, false ) ); } ); status.getMissing().forEach( name -> { files.add( new UIFile( name, ChangeType.DELETE, false ) ); } ); return files; }
Example #19
Source File: UIGit.java From hop with Apache License 2.0 | 6 votes |
@Override public List<UIFile> getStagedFiles() { List<UIFile> files = new ArrayList<UIFile>(); Status status = null; try { status = git.status().call(); } catch ( Exception e ) { e.printStackTrace(); return files; } status.getAdded().forEach( name -> { files.add( new UIFile( name, ChangeType.ADD, true ) ); } ); status.getChanged().forEach( name -> { files.add( new UIFile( name, ChangeType.MODIFY, true ) ); } ); status.getRemoved().forEach( name -> { files.add( new UIFile( name, ChangeType.DELETE, true ) ); } ); return files; }
Example #20
Source File: UIGit.java From hop with Apache License 2.0 | 6 votes |
private void processPushResult( Iterable<PushResult> resultIterable ) throws Exception { resultIterable.forEach( result -> { // for each (push)url StringBuilder sb = new StringBuilder(); result.getRemoteUpdates().stream() .filter( update -> update.getStatus() != RemoteRefUpdate.Status.OK ) .filter( update -> update.getStatus() != RemoteRefUpdate.Status.UP_TO_DATE ) .forEach( update -> { // for each failed refspec sb.append( result.getURI().toString() + "\n" + update.getSrcRef().toString() + "\n" + update.getStatus().toString() + ( update.getMessage() == null ? "" : "\n" + update.getMessage() ) + "\n\n" ); } ); if ( sb.length() == 0 ) { showMessageBox( BaseMessages.getString( PKG, "Dialog.Success" ), BaseMessages.getString( PKG, "Dialog.Success" ) ); } else { showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), sb.toString() ); } } ); }
Example #21
Source File: UIGit.java From hop with Apache License 2.0 | 6 votes |
@Override public void revertPath( String path ) { try { // Delete added files Status status = git.status().addPath( path ).call(); if ( status.getUntracked().size() != 0 || status.getAdded().size() != 0 ) { resetPath( path ); org.apache.commons.io.FileUtils.deleteQuietly( new File( directory, path ) ); } /* * This is a work-around to discard changes of conflicting files * Git CLI `git checkout -- conflicted.txt` discards the changes, but jgit does not */ git.add().addFilepattern( path ).call(); git.checkout().setStartPoint( Constants.HEAD ).addPath( path ).call(); org.apache.commons.io.FileUtils.deleteQuietly( new File( directory, path + ".ours" ) ); org.apache.commons.io.FileUtils.deleteQuietly( new File( directory, path + ".theirs" ) ); } catch ( Exception e ) { showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), e.getMessage() ); } }
Example #22
Source File: DifferentFiles.java From gitflow-incremental-builder with MIT License | 6 votes |
private Set<Path> getChangesFromStatus() throws GitAPIException { Set<String> changes = new HashSet<>(); Status status = git.status().call(); if (configuration.uncommited) { changes.addAll(status.getUncommittedChanges()); } if (configuration.untracked) { changes.addAll(status.getUntracked()); } return changes.stream() .map(Paths::get) .map(Path::normalize) .filter(this::pathIncluded) .map(workTree::resolve) .collect(Collectors.toSet()); }
Example #23
Source File: GitProctorCore.java From proctor with Apache License 2.0 | 6 votes |
@Nullable private Set<String> parseStagedTestNames() { try { final Status status = git.status().call(); return Stream.of( status.getAdded(), status.getChanged(), status.getRemoved()) .flatMap(Set::stream) .distinct() .map(s -> parseTestName(testDefinitionsDirectory, s)) .filter(Objects::nonNull) .collect(Collectors.toSet()); } catch (final GitAPIException | NoWorkTreeException e) { LOGGER.warn("Failed to call git status", e); return null; } }
Example #24
Source File: GitRepository.java From wildfly-core with GNU Lesser General Public License v2.1 | 5 votes |
private void checkoutToSelectedBranch(final Git git) throws IOException, GitAPIException { boolean createBranch = !ObjectId.isId(branch); if (createBranch) { Ref ref = git.getRepository().exactRef(R_HEADS + branch); if (ref != null) { createBranch = false; } } CheckoutCommand checkout = git.checkout().setCreateBranch(createBranch).setName(branch); checkout.call(); if (checkout.getResult().getStatus() == CheckoutResult.Status.ERROR) { throw ServerLogger.ROOT_LOGGER.failedToPullRepository(null, defaultRemoteRepository); } }
Example #25
Source File: GitRepositoryTestCase.java From wildfly-core with GNU Lesser General Public License v2.1 | 5 votes |
protected List<String> listUntracked(Repository repository) throws IOException, GitAPIException { List<String> result = new ArrayList<>(); result.add("Untracked:"); try (Git git = new Git(repository)) { Status status = git.status().call(); result.addAll(status.getUntrackedFolders()); result.addAll(status.getUntracked()); return result; } }
Example #26
Source File: GitRepository.java From wildfly-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * 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 #27
Source File: GitMigratorTest.java From rtc2gitcli with MIT License | 5 votes |
private void checkGit(String userName, String userEmail, String comment) throws Exception { git = Git.open(basedir); Status status = git.status().call(); assertTrue(status.isClean()); Iterator<RevCommit> log = git.log().call().iterator(); RevCommit revCommit = log.next(); assertEquals(userEmail, revCommit.getAuthorIdent().getEmailAddress()); assertEquals(userName, revCommit.getAuthorIdent().getName()); assertEquals(comment, revCommit.getFullMessage()); }
Example #28
Source File: GitPushWindow.java From XACML with MIT License | 5 votes |
protected void refreshStatus() { try { // // 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); } }
Example #29
Source File: GitAPITestCase.java From git-client-plugin with MIT License | 5 votes |
public void test_rebase_fails_with_conflict() throws Exception { w.init(); w.commitEmpty("init"); // First commit to master w.touch("file", "master1"); w.git.add("file"); w.git.commit("commit-master1"); // Create a feature branch and make a commit w.git.branch("feature1"); w.git.checkout().ref("feature1").execute(); w.touch("file", "feature1"); w.git.add("file"); w.git.commit("commit-feature1"); // Second commit to master w.git.checkout().ref("master").execute(); w.touch("file", "master2"); w.git.add("file"); w.git.commit("commit-master2"); // Rebase feature commit onto master w.git.checkout().ref("feature1").execute(); try { w.git.rebase().setUpstream("master").execute(); fail("Rebase did not throw expected GitException"); } catch (GitException e) { assertEquals("HEAD not reset to the feature branch.", w.git.revParse("HEAD").name(), w.git.revParse("feature1").name()); Status status = new org.eclipse.jgit.api.Git(w.repo()).status().call(); assertTrue("Workspace is not clean", status.isClean()); assertFalse("Workspace has uncommitted changes", status.hasUncommittedChanges()); assertTrue("Workspace has conflicting changes", status.getConflicting().isEmpty()); assertTrue("Workspace has missing changes", status.getMissing().isEmpty()); assertTrue("Workspace has modified files", status.getModified().isEmpty()); assertTrue("Workspace has removed files", status.getRemoved().isEmpty()); assertTrue("Workspace has untracked files", status.getUntracked().isEmpty()); } }
Example #30
Source File: Utils.java From usergrid with Apache License 2.0 | 5 votes |
/** * @param gitConfigFolder e.g. /your/project/root/.git * * @return Returns true if 'git status' has modified files inside the 'Changes to be committed' section */ 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 ); } }