/** * Gets the conflicting file from the git status * * @return the conflicting files list */ public List<FileStatus> getConflictingFiles() { if (git != null) { try { Status status = git.status().call(); List<FileStatus> stagedFiles = new ArrayList<FileStatus>(); for (String fileName : status.getConflicting()) { stagedFiles.add(new FileStatus(GitChangeType.CONFLICT, fileName)); } return stagedFiles; } catch (GitAPIException e) { if (logger.isDebugEnabled()) { logger.debug(e, e); } } } return new ArrayList<FileStatus>(); }
@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; }
@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; }
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() ); } } ); }
@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() ); } }
@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()); } }
public void refreshTree(Status status) { int totalSize = status.getAdded().size() + status.getChanged().size() + status.getMissing().size(); changedFiles = new ArrayList<>(totalSize); // TODO: this probably doesn't account for files that were moved / renamed status.getAdded() .forEach(file -> changedFiles.add(new ModifiedPath(Paths.get(file), GitFileStatus.ADDED))); status.getChanged().forEach(file -> changedFiles.add(new ModifiedPath(Paths.get(file), GitFileStatus.MODIFIED))); status.getMissing().forEach(file -> changedFiles.add(new ModifiedPath(Paths.get(file), GitFileStatus.REMOVED))); fileSelectionStates = new ArrayList<>(totalSize); buildRoot(); }
public void commitAllChanges(final String message) { final Repository repository = getRepository(); try { final Git git = new Git(repository); git.add().addFilepattern(".").call(); final Status status = git.status().call(); if (status.getChanged().size() > 0 || status.getAdded().size() > 0 || status.getModified().size() > 0 || status.getRemoved().size() > 0) { final RevCommit rev = git.commit().setAll(true) .setCommitter(person).setAuthor(person) .setMessage(message).call(); LOGGER.info("Git commit " + rev.getName() + " [" + message + "]"); } } catch (final Exception e) { throw new IllegalStateException( "Could not commit changes to local Git repository", e); } }
public static Matcher<Git> hasCleanWorkingDirectory() { return new TypeSafeDiagnosingMatcher<Git>() { @Override protected boolean matchesSafely(final Git git, final Description mismatchDescription) { try { final Status status = git.status().call(); if (!status.isClean()) { final String start = "Uncommitted changes in "; final String end = " at " + git.getRepository().getWorkTree().getAbsolutePath(); mismatchDescription.appendValueList(start, ", ", end, status.getUncommittedChanges()); } return status.isClean(); } catch (final GitAPIException e) { throw new RuntimeException("Error checking git status", e); } } @Override public void describeTo(final Description description) { description.appendText("A git directory with no staged or unstaged changes"); } }; }
@Test public void addTest() throws Exception { Repository repository = getTestRepository(); File fileToAdd = new File(gitLocalRepo, filenameToAdd); fileToAdd.createNewFile(); template.send("direct:add", new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(GitConstants.GIT_FILE_NAME, filenameToAdd); } }); File gitDir = new File(gitLocalRepo, ".git"); assertEquals(gitDir.exists(), true); Status status = new Git(repository).status().call(); assertTrue(status.getAdded().contains(filenameToAdd)); repository.close(); }
@Test public void statusTest() throws Exception { Repository repository = getTestRepository(); File fileToAdd = new File(gitLocalRepo, filenameToAdd); fileToAdd.createNewFile(); template.send("direct:add", new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(GitConstants.GIT_FILE_NAME, filenameToAdd); } }); File gitDir = new File(gitLocalRepo, ".git"); assertEquals(gitDir.exists(), true); Status status = template.requestBody("direct:status", "", Status.class); assertTrue(status.getAdded().contains(filenameToAdd)); repository.close(); }
/** * 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 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(); }
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; } }); }
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"); } }; }
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; }
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; }
/** * @see gov.va.isaac.interfaces.sync.ProfileSyncI#addUntrackedFiles(java.io.File) */ @Override public void addUntrackedFiles() throws IllegalArgumentException, IOException { log.info("Add Untracked files called"); try { Git git = getGit(); Status s = git.status().call(); addFiles(s.getUntracked().toArray(new String[s.getUntracked().size()])); } catch (GitAPIException e) { log.error("Unexpected", e); throw new IOException("Internal error", e); } }
private String statusToString(Status status) { StringBuilder sb = new StringBuilder(); sb.append("Is clean: " + status.isClean() + eol); sb.append("Changed: " + status.getChanged() + eol); sb.append("Added: " + status.getAdded() + eol); sb.append("Conflicting: " + status.getConflicting() + eol); sb.append("Ignored, unindexed: " + status.getIgnoredNotInIndex() + eol); sb.append("Missing: " + status.getMissing() + eol); sb.append("Modified: " + status.getModified() + eol); sb.append("Removed: " + status.getRemoved() + eol); sb.append("UncomittedChanges: " + status.getUncommittedChanges() + eol); sb.append("Untracked: " + status.getUntracked() + eol); sb.append("UntrackedFolders: " + status.getUntrackedFolders() + eol); return sb.toString(); }
/** * Extract newed or removed modules * */ public void extractNewModules() { Status repositoryStatus = null; try { repositoryStatus = git.status().call(); } catch (NoWorkTreeException | GitAPIException e) { e.printStackTrace(); } newModules = new TreeMap<String, ChangedFile>(); for (String string : repositoryStatus.getUntrackedFolders()) { for(ChangedFile file : differences) { if(file.getPath().lastIndexOf(Constants.SLASH) != -1 && file.getPath().substring(0, file.getPath().lastIndexOf(Constants.SLASH)).equals(string) && !newModules.containsKey(string)) { ChangedFile changedFile = new ChangedFile(string, TypeChange.UNTRACKED_FOLDERS.name(), git.getRepository().getWorkTree().getAbsolutePath()); if(!newModules.containsKey(string)) { newModules.put(string, changedFile); } break; } } } }
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(); } }
@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); repo.setForcePull(true); boolean shouldPull = repo.shouldPull(git); assertThat("shouldPull was false", shouldPull, is(true)); }
@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); boolean shouldPull = repo.shouldPull(git); assertThat("shouldPull was true", shouldPull, is(false)); }
@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); boolean shouldPull = repo.shouldPull(git); assertThat("shouldPull was false", shouldPull, is(true)); }
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; } }); }
@Nullable private Set<String> parseStagedTestNames() { try { final Status status = git.status().call(); final Iterable<String> stagedFileNames = Iterables.concat( status.getAdded(), status.getChanged(), status.getRemoved() ); return FluentIterable.from(stagedFileNames) .transform(new Function<String, String>() { @Nullable @Override public String apply(@Nullable final String s) { return parseTestName(testDefinitionsDirectory, s); } }) .filter(Predicates.notNull()) .toSet(); } catch (final GitAPIException | NoWorkTreeException e) { LOGGER.warn("Failed to call git status", e); return null; } }
public static void main(String[] args) throws IOException, GitAPIException { try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { try (Git git = new Git(repository)) { Status status = git.status().call(); System.out.println("Added: " + status.getAdded()); System.out.println("Changed: " + status.getChanged()); System.out.println("Conflicting: " + status.getConflicting()); System.out.println("ConflictingStageState: " + status.getConflictingStageState()); System.out.println("IgnoredNotInIndex: " + status.getIgnoredNotInIndex()); System.out.println("Missing: " + status.getMissing()); System.out.println("Modified: " + status.getModified()); System.out.println("Removed: " + status.getRemoved()); System.out.println("Untracked: " + status.getUntracked()); System.out.println("UntrackedFolders: " + status.getUntrackedFolders()); } } }
private Set<Change> retrieveUncommittedChanges(File repoRoot) { final Set<Change> allChanges = new HashSet<>(); final Status status; try { status = git.status().call(); } catch (GitAPIException e) { throw new IllegalArgumentException(e); } allChanges.addAll(status.getModified() .stream() .map(location -> modify(repoRoot.getAbsolutePath(), location)) .collect(Collectors.toSet())); allChanges.addAll(status.getChanged() .stream() .map(location -> modify(repoRoot.getAbsolutePath(), location)) .collect(Collectors.toSet())); allChanges.addAll(status.getUntracked() .stream() .map(location -> add(repoRoot.getAbsolutePath(), location)) .collect(Collectors.toSet())); allChanges.addAll(status.getAdded() .stream() .map(location -> add(repoRoot.getAbsolutePath(), location)) .collect(Collectors.toSet())); return allChanges; }
/** * Pushes all the commits from the local repository to the remote repository * * @param username * - Git username * @param password * - Git password * * @throws GitAPIException * @throws TransportException * @throws InvalidRemoteException */ public PushResponse push(final String username, final String password) throws GitAPIException { AuthenticationInterceptor.install(); PushResponse response = new PushResponse(); RepositoryState repositoryState = git.getRepository().getRepositoryState(); if (repositoryState == RepositoryState.MERGING) { response.setStatus(org.eclipse.jgit.transport.RemoteRefUpdate.Status.REJECTED_OTHER_REASON); response.setMessage(translator.getTranslation(Tags.PUSH_WITH_CONFLICTS)); return response; } if (getPullsBehind() > 0) { response.setStatus(org.eclipse.jgit.transport.RemoteRefUpdate.Status.REJECTED_OTHER_REASON); response.setMessage(translator.getTranslation(Tags.BRANCH_BEHIND)); return response; } String sshPassphrase = OptionsManager.getInstance().getSshPassphrase(); Iterable<PushResult> call = git.push() .setCredentialsProvider(new SSHUserCredentialsProvider(username, password, sshPassphrase)).call(); Iterator<PushResult> results = call.iterator(); logger.debug("Push Ended"); while (results.hasNext()) { PushResult result = results.next(); for (RemoteRefUpdate info : result.getRemoteUpdates()) { response.setStatus(info.getStatus()); return response; } } response.setStatus(org.eclipse.jgit.transport.RemoteRefUpdate.Status.REJECTED_OTHER_REASON); response.setMessage(translator.getTranslation(Tags.PUSH_FAILED_UNKNOWN)); return response; }
@Test public void testForResetWithSoft() throws Exception { try (Git git = Git.wrap(repository)) { writeFileAndCommit(git, "testReset", "testReset", "testReset"); this.gitMgr.reset(ws, "HEAD~1", ResetType.SOFT); Status status = git.status().call(); assertEquals(1, status.getAdded().size()); assertEquals(true, status.getAdded().contains("testReset")); } }
@Test public void testForResetWithMixed() throws Exception { try (Git git = Git.wrap(repository)) { writeFileAndCommit(git, "testReset", "testReset", "testReset"); this.gitMgr.reset(ws, "HEAD~1", ResetType.MIXED); Status status = git.status().call(); assertEquals(1, status.getUntracked().size()); assertEquals(true, status.getUntracked().contains("testReset")); } }
/** * When there are changes in tracked files that can be reverted, calls {@link #displayRevertDialog(Val, Status)}. * Otherwise, calls {@link #displayNoChangesDialog()}. */ public final void revertOrInform() { try { Status status = git.getOrThrow().status().call(); if (status.hasUncommittedChanges()) { displayRevertDialog(git, status); } else { displayNoChangesDialog(); } } catch (GitAPIException e) { handleGitAPIException(e); } }
/** * If the repository has uncommitted changes on tracked files, calls {@link #displayCommitDialog(Val, Status)}; * otherwise, calls {@link #displayNoChangesDialog()}. */ public final void commitOrInform() { try { Status status = git.getOrThrow().status().call(); if (status.hasUncommittedChanges()) { displayCommitDialog(git, status); } else { displayNoChangesDialog(); } } catch (GitAPIException e) { handleGitAPIException(e); } }
/** * Refreshes the view to show any changes that might have affected the current files. * * <p>If new files were added, tracked files removed, or tracked files were modified, this method * will call {@link #displayFileViewer(Status)} if {@link Status#hasUncommittedChanges()} returns * true and {@link #displayPlaceHolder()} if it returns false. */ public final void refreshFileViewer() { try { Status status = getGitOrThrow().status().call(); if (status.hasUncommittedChanges()) { displayFileViewer(status); } else { displayPlaceHolder(); } } catch (GitAPIException e) { handleRefreshException(e); } }
/** * Refreshes the view to show any changes that might have affected the current files. * * <p>If modified tracked files have been manually reverted to their previous state or other unmodified * tracked files were modified, this method will call {@link #displayFileViewer(Status)} if * {@link Status#hasUncommittedChanges()} returns true and {@link #displayPlaceholder()} if it returns false. */ public final void refreshFileViewer() { try { Status status = getGitOrThrow().status().call(); if (status.hasUncommittedChanges()) { displayFileViewer(status); } else { displayPlaceholder(); } } catch (GitAPIException e) { handleRefreshException(e); } }
public RevertChangesDialog(Val<Git> git, Status firstStatus) { super(git); setTitle("Revert modified files"); setResizable(true); ButtonType revertButtonType = new ButtonType("Revert...", ButtonBar.ButtonData.YES); setDialogPane(new RevertChangesDialogPane(git, new SelectableFileViewer(firstStatus), revertButtonType)); setResultConverter(buttonType -> { if (buttonType.equals(revertButtonType)) { return revertChanges(); } else { return null; } }); }
/** * Refreshes the view to show any changes that might have affected the current files * shown by {@link #fileViewer}. * * <p>If modified tracked files have been manually reverted to their previous state or other unmodified * tracked files were modified, this method will call {@link #displayFileViewer(Status)} if * {@link Status#hasUncommittedChanges()} returns true and {@link #displayPlaceholder()} if it returns false. */ protected final void refreshView() { try { Status status = getGitOrThrow().status().call(); if (status.hasUncommittedChanges()) { displayFileViewer(status); } else { displayPlaceholder(); } } catch (GitAPIException e) { e.printStackTrace(); } }
public CommitDialog(Val<Git> git, Status firstStatus) { super(git); setTitle("Commit changes"); setResizable(true); ButtonType commitButton = new ButtonType("Commit...", ButtonBar.ButtonData.YES); setDialogPane(new CommitDialogPane(git, new SelectableFileViewer(firstStatus), commitButton)); setResultConverter(buttonType -> { if (buttonType.equals(commitButton)) { return addAndCommitSelectedFiles(); } else { return null; } }); }
public SelectableFileViewer(Status status) { super(); getStyleClass().add("selectable-file-viewer"); view.getStyleClass().add("selectable-file-tree-view"); view.setRoot(root); view.setShowRoot(false); view.setCellFactory(GitFileStatusTreeCell.forTreeView()); getChildren().add(view); refreshTree(status); }