private GitRebaseResult createResult (RebaseResult res) { String currHead; Repository repository = getRepository(); File workTree = repository.getWorkTree(); try { currHead = repository.resolve(Constants.HEAD).name(); } catch (IOException ex) { currHead = Constants.HEAD; } List<File> conflicts; if (res.getStatus() == RebaseResult.Status.STOPPED) { conflicts = getConflicts(res.getCurrentCommit()); } else { conflicts = Collections.<File>emptyList(); } return getClassFactory().createRebaseResult(res, conflicts, getFailures(res), currHead); }
private void update(Git git) throws GitAPIException { PullResult pullResult = git.pull().setRebase(true).call(); RebaseResult rebaseResult = pullResult.getRebaseResult(); if(!pullResult.isSuccessful()) { if(rebaseResult.getStatus() == RebaseResult.Status.CONFLICTS) { logger.warn("Git `pull` reported conflicts - will reset and try again next pass!"); git.reset().setMode(ResetCommand.ResetType.HARD).call(); return; } logger.warn("Git `pull` was unsuccessful :("); return; } if(rebaseResult.getStatus() == RebaseResult.Status.UP_TO_DATE) { logger.debug("Git `pull` reported that repository is already up-to-date"); return; } logger.debug("Git repo is now at commit '{}'", rebaseResult.getCurrentCommit()); }
@Override public RebaseResponse process(Repository repository, String message) throws GitAPIException, IOException { try (Git git = Git.wrap(repository)) { git.commit() .setMessage(stripCommentLines(message)) .setAmend(true).setNoVerify(true).call(); getRebaseFile(repository, MESSAGE_SQUASH).delete(); getRebaseFile(repository, MESSAGE_FIXUP).delete(); createFile(repository, MESSAGE, message); RebaseResult result = git.rebase() .setOperation(RebaseCommand.Operation.SKIP) .runInteractively(handler) .call(); return new RebaseResponse(result); } }
@Override public RebaseResponse process(Repository repository, String message) throws GitAPIException { try (Git git = Git.wrap(repository)) { git.commit() .setAll(true) .setAmend(true) .setNoVerify(true) .setMessage(message) .call(); RebaseResult result = git.rebase() .setOperation(RebaseCommand.Operation.CONTINUE) .runInteractively(handler) .call(); // 如果 conflict and edit,amend 后 continue 会返回 NOTHING_TO_COMMIT // so skip this commit if (result.getStatus().equals(RebaseResult.Status.NOTHING_TO_COMMIT)) { result = git.rebase().setOperation(RebaseCommand.Operation.SKIP).call(); } return new RebaseResponse(result); } }
@Override public RebaseResponse process(Repository repository, String message) throws GitAPIException, IOException { try (Git git = Git.wrap(repository)) { git.commit() .setMessage(message) .setAmend(true) .setNoVerify(true) .call(); RebaseResult result = git.rebase() .setOperation(RebaseCommand.Operation.SKIP) .runInteractively(handler) .call(); return new RebaseResponse(result); } }
@Override public boolean rebase(String upStreamBranchName) { RebaseCommand command = _git.rebase(); RebaseResult result = null; try { command.setUpstream(upStreamBranchName); result = command.call(); // if there are merge conflicts (rebase interactive) - reset the repository if (!result.getStatus().isSuccessful()) { _git.rebase().setOperation(Operation.ABORT).call(); } } catch (Throwable e) { throw new RuntimeException(String.format( "Failed to rebase with upstream [%s]", upStreamBranchName), e); } return result.getStatus().isSuccessful(); }
private void colocarEmSAFE() throws GitAPIException, IOException { RebaseResult rebaseResult = git .rebase() .setStrategy(THEIRS) .setOperation(ABORT) .call(); Marker marker = append("git.state", git.getRepository().getRepositoryState().toString()) .and(append("git.branch", git.getRepository().getBranch())) .and(append("pull.rebase.result", rebaseResult.getStatus().toString())); log.info(marker, "git rebase em {}", git.getRepository().getBranch()); Ref resetResult = git.reset().setMode(HARD).setRef(R_HEADS + MASTER).call(); marker = append("reset.result", resetResult.getName()); log.info(marker, "git reset --hard em {}", git.getRepository().getBranch()); }
public static Boolean applyBefore(final Git git) { Boolean result = Boolean.FALSE; try { PullCommand pc = git.pull().setRemote(REMOTE).setRebase(Boolean.TRUE); PullResult pullRes = pc.call(); RebaseResult rr = pullRes.getRebaseResult(); if (rr.getStatus().equals(RebaseResult.Status.UP_TO_DATE) || rr.getStatus().equals(RebaseResult.Status.FAST_FORWARD)) { result = Boolean.TRUE; } if (rr.getStatus().equals(RebaseResult.Status.UNCOMMITTED_CHANGES)) { PullResult pr = git.pull().call(); if (pr.isSuccessful()) { result = Boolean.TRUE; } else { result = Boolean.FALSE; } } } catch (Exception e) { logger.error(e.getMessage()); } return result; }
GitRebaseResult (RebaseResult result, List<File> rebaseConflicts, List<File> failures, String currentHead) { this.rebaseStatus = parseRebaseStatus(result.getStatus()); this.currentHead = currentHead; if (result.getCurrentCommit() == null) { this.currentCommit = null; } else { this.currentCommit = result.getCurrentCommit().getId().getName(); } this.conflicts = rebaseConflicts; this.failures = failures; }
static RebaseStatus parseRebaseStatus (RebaseResult.Status rebaseStatus) { switch (rebaseStatus) { case EDIT: return RebaseStatus.STOPPED; case UNCOMMITTED_CHANGES: return RebaseStatus.FAILED; case INTERACTIVE_PREPARED: return RebaseStatus.STOPPED; case STASH_APPLY_CONFLICTS: return RebaseStatus.CONFLICTS; } return GitRebaseResult.RebaseStatus.valueOf(rebaseStatus.name()); }
private void rebaseOnTargetBranch(Git git, final List<Commit> commits) throws Exception { RebaseCommand rebase = git.rebase(); rebase.setUpstream(request.getTarget().getBranch()); rebase.setProgressMonitor(new NotificationProgressMonitor(request, notification, progress)); rebase.runInteractively(new GitUtil.InteractiveRebase(notification, request.getKey(), commits)); RebaseResult result = rebase.call(); if(!result.getStatus().isSuccessful()) { throw new RuntimeException("Rebase not successful, status " + result.getStatus()); } }
protected void synchronize() { // // Grab our working repository // Path repoPath = ((XacmlAdminUI)getUI()).getUserGitPath(); try { final Git git = Git.open(repoPath.toFile()); PullResult result = git.pull().call(); FetchResult fetch = result.getFetchResult(); MergeResult merge = result.getMergeResult(); RebaseResult rebase = result.getRebaseResult(); if (result.isSuccessful()) { // // TODO add more notification // this.textAreaResults.setValue("Successful!"); } else { // // TODO // this.textAreaResults.setValue("Failed."); } } catch (IOException | GitAPIException e) { e.printStackTrace(); } this.buttonSynchronize.setCaption("Ok"); }
public abstract GitRebaseResult createRebaseResult (RebaseResult rebaseResult, List<File> rebaseConflicts, List<File> failures, String newHead);
@Override public GitRebaseResult createRebaseResult (RebaseResult rebaseResult, List<File> rebaseConflicts, List<File> failures, String newHead) { return new GitRebaseResult(rebaseResult, rebaseConflicts, failures, newHead); }
public void testRebaseStatus () { for (RebaseResult.Status status : RebaseResult.Status.values()) { assertNotNull(GitRebaseResult.parseRebaseStatus(status)); } }
@SneakyThrows public boolean rebase( final Repository repo, final PullRequest pullRequest ) { log.info( "Rebasing {}.", pullRequest ); try { final Git repository = repo.getGit(); final CredentialsProvider credentials = repo.getCredentials(); repository.fetch().setCredentialsProvider( credentials ).setRemoveDeletedRefs( true ).call(); repository.checkout().setCreateBranch( true ).setName( pullRequest.getSource() ) .setStartPoint( "origin/" + pullRequest.getSource() ).call(); final RebaseResult rebaseResult = repository.rebase().setUpstream( "origin/" + pullRequest.getDestination() ).call(); switch ( rebaseResult.getStatus() ) { case UP_TO_DATE: log.warn( "Why rebasing up to date {}?", pullRequest ); return true; case FAST_FORWARD: log.warn( "Why creating {} without changes?", pullRequest ); // fall-through case OK: repository.push().setCredentialsProvider( credentials ).setForce( true ).call(); return true; case STOPPED: log.info( "Merge conflict in {}", pullRequest ); repository.rebase().setOperation( Operation.ABORT ).call(); return false; default: repository.rebase().setOperation( Operation.ABORT ).call(); throw new RuntimeException( "For " + pullRequest + " rebase causes an unexpected result: " + rebaseResult.getStatus() ); } } finally { cleanUp( repo ); } }
public RebaseResponse(RebaseResult rebaseResult) { this.success = rebaseResult.getStatus().isSuccessful(); this.status = Status.valueOf(rebaseResult.getStatus().name()); }
@Override public RebaseResponse rebase(String operation, String branch) throws GitException { RebaseResult result; RebaseStatus status; List<String> failed; List<String> conflicts; try { RebaseCommand rebaseCommand = getGit().rebase(); setRebaseOperation(rebaseCommand, operation); if (branch != null && !branch.isEmpty()) { rebaseCommand.setUpstream(branch); } result = rebaseCommand.call(); } catch (GitAPIException exception) { throw new GitException(exception.getMessage(), exception); } switch (result.getStatus()) { case ABORTED: status = RebaseStatus.ABORTED; break; case CONFLICTS: status = RebaseStatus.CONFLICTING; break; case UP_TO_DATE: status = RebaseStatus.ALREADY_UP_TO_DATE; break; case FAST_FORWARD: status = RebaseStatus.FAST_FORWARD; break; case NOTHING_TO_COMMIT: status = RebaseStatus.NOTHING_TO_COMMIT; break; case OK: status = RebaseStatus.OK; break; case STOPPED: status = RebaseStatus.STOPPED; break; case UNCOMMITTED_CHANGES: status = RebaseStatus.UNCOMMITTED_CHANGES; break; case EDIT: status = RebaseStatus.EDITED; break; case INTERACTIVE_PREPARED: status = RebaseStatus.INTERACTIVE_PREPARED; break; case STASH_APPLY_CONFLICTS: status = RebaseStatus.STASH_APPLY_CONFLICTS; break; default: status = RebaseStatus.FAILED; } conflicts = result.getConflicts() != null ? result.getConflicts() : emptyList(); failed = result.getFailingPaths() != null ? new ArrayList<>(result.getFailingPaths().keySet()) : emptyList(); return newDto(RebaseResponse.class) .withStatus(status) .withConflicts(conflicts) .withFailed(failed); }
@Test public void buildWithPullRebaseUberfireTest() throws Exception { //Setup origin in memory final URI originRepo = URI.create("git://repo"); final JGitFileSystem origin = (JGitFileSystem) ioService.newFileSystem(originRepo, new HashMap<String, Object>() {{ put("init", Boolean.TRUE); put("internal", Boolean.TRUE); put("listMode", "ALL"); }}); ioService.startBatch(origin); ioService.write(origin.getPath("/dummy/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/pom.xml").toPath()))); ioService.write(origin.getPath("/dummy/dummyA/src/main/java/dummy/DummyA.java"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyA/src/main/java/dummy/DummyA.java").toPath()))); ioService.write(origin.getPath("/dummy/dummyB/src/main/java/dummy/DummyB.java"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyB/src/main/java/dummy/DummyB.java").toPath()))); ioService.write(origin.getPath("/dummy/dummyA/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyA/pom.xml").toPath()))); ioService.write(origin.getPath("/dummy/dummyB/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyB/pom.xml").toPath()))); ioService.endBatch(); // clone into a regularfs Path tmpRootCloned = Files.createTempDirectory("cloned"); Path tmpCloned = Files.createDirectories(Paths.get(tmpRootCloned.toString(), ".clone")); final Git cloned = Git.cloneRepository().setURI("git://localhost:9418/repo").setBare(false).setDirectory(tmpCloned.toFile()).call(); assertNotNull(cloned); PullCommand pc = cloned.pull().setRemote("origin").setRebase(Boolean.TRUE); PullResult pullRes = pc.call(); assertTrue(pullRes.getRebaseResult().getStatus().equals(RebaseResult.Status.UP_TO_DATE));// nothing changed yet RebaseCommand rb = cloned.rebase().setUpstream("origin/master"); RebaseResult rbResult = rb.setPreserveMerges(true).call(); assertTrue(rbResult.getStatus().isSuccessful()); //Compile the repo AFCompiler compiler = MavenCompilerFactory.getCompiler(Decorator.LOG_OUTPUT_AFTER); byte[] encoded = Files.readAllBytes(Paths.get(tmpCloned + "/dummy/pom.xml")); String pomAsAstring = new String(encoded, StandardCharsets.UTF_8); Assert.assertFalse(pomAsAstring.contains("<artifactId>takari-lifecycle-plugin</artifactId>")); Path prjFolder = Paths.get(tmpCloned + "/dummy/"); WorkspaceCompilationInfo info = new WorkspaceCompilationInfo(prjFolder); CompilationRequest req = new DefaultCompilationRequest(mavenRepo.toAbsolutePath().toString(), info, new String[]{MavenCLIArgs.CLEAN, MavenCLIArgs.COMPILE}, new HashMap<>(), Boolean.TRUE); CompilationResponse res = compiler.compileSync(req); if (res.getMavenOutput().isPresent() && !res.isSuccessful()) { TestUtil.writeMavenOutputIntoTargetFolder(res.getMavenOutput().get(), "KieDefaultMavenCompilerOnInMemoryFSTest.buildWithPullRebaseUberfireTest"); } assertTrue(res.isSuccessful()); Path incrementalConfiguration = Paths.get(prjFolder + "/target/incremental/io.takari.maven.plugins_takari-lifecycle-plugin_compile_compile"); assertTrue(incrementalConfiguration.toFile().exists()); encoded = Files.readAllBytes(Paths.get(prjFolder + "/pom.xml")); pomAsAstring = new String(encoded, StandardCharsets.UTF_8); assertTrue(pomAsAstring.contains("<artifactId>takari-lifecycle-plugin</artifactId>")); TestUtil.rm(tmpRootCloned.toFile()); }
@Test public void buildWithPullRebaseUberfireTest() throws Exception { //Setup origin in memory final URI originRepo = URI.create("git://repo"); final JGitFileSystem origin = (JGitFileSystem) ioService.newFileSystem(originRepo, new HashMap<String, Object>() {{ put("init", Boolean.TRUE); put("internal", Boolean.TRUE); put("listMode", "ALL"); }}); ioService.startBatch(origin); ioService.write(origin.getPath("/dummy/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/pom.xml").toPath()))); ioService.write(origin.getPath("/dummy/dummyA/src/main/java/dummy/DummyA.java"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyA/src/main/java/dummy/DummyA.java").toPath()))); ioService.write(origin.getPath("/dummy/dummyB/src/main/java/dummy/DummyB.java"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyB/src/main/java/dummy/DummyB.java").toPath()))); ioService.write(origin.getPath("/dummy/dummyA/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyA/pom.xml").toPath()))); ioService.write(origin.getPath("/dummy/dummyB/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyB/pom.xml").toPath()))); ioService.endBatch(); // clone into a regularfs Path tmpRootCloned = Files.createTempDirectory("cloned"); Path tmpCloned = Files.createDirectories(Paths.get(tmpRootCloned.toString(), ".clone")); final Git cloned = Git.cloneRepository().setURI("git://localhost:9418/repo").setBare(false).setDirectory(tmpCloned.toFile()).call(); assertNotNull(cloned); PullCommand pc = cloned.pull().setRemote("origin").setRebase(Boolean.TRUE); PullResult pullRes = pc.call(); assertTrue(pullRes.getRebaseResult().getStatus().equals(RebaseResult.Status.UP_TO_DATE));// nothing changed yet RebaseCommand rb = cloned.rebase().setUpstream("origin/master"); RebaseResult rbResult = rb.setPreserveMerges(true).call(); assertTrue(rbResult.getStatus().isSuccessful()); //Compile the repo AFCompiler compiler = KieMavenCompilerFactory.getCompiler(KieDecorator.LOG_OUTPUT_AFTER); byte[] encoded = Files.readAllBytes(Paths.get(tmpCloned + "/dummy/pom.xml")); String pomAsAstring = new String(encoded, StandardCharsets.UTF_8); Assert.assertFalse(pomAsAstring.contains("<artifactId>takari-lifecycle-plugin</artifactId>")); Path prjFolder = Paths.get(tmpCloned + "/dummy/"); WorkspaceCompilationInfo info = new WorkspaceCompilationInfo(prjFolder); CompilationRequest req = new DefaultCompilationRequest(mavenRepo.toAbsolutePath().toString(), info, new String[]{MavenCLIArgs.CLEAN, MavenCLIArgs.COMPILE}, new HashMap<>(), Boolean.TRUE); CompilationResponse res = compiler.compileSync(req); if (res.getMavenOutput().isPresent() && !res.isSuccessful()) { TestUtil.writeMavenOutputIntoTargetFolder(res.getMavenOutput().get(), "KieDefaultMavenCompilerTest.buildWithPullRebaseUberfireTest"); } assertTrue(res.isSuccessful()); Path incrementalConfiguration = Paths.get(prjFolder + "/target/incremental/io.takari.maven.plugins_takari-lifecycle-plugin_compile_compile"); assertTrue(incrementalConfiguration.toFile().exists()); encoded = Files.readAllBytes(Paths.get(prjFolder + "/pom.xml")); pomAsAstring = new String(encoded, StandardCharsets.UTF_8); assertTrue(pomAsAstring.contains("<artifactId>takari-lifecycle-plugin</artifactId>")); TestUtil.rm(tmpRootCloned.toFile()); }
public static void main(String[] args) throws IOException, GitAPIException { try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { // all refs try (Git git = new Git(repository)) { InteractiveHandler handler = new InteractiveHandler() { @Override public void prepareSteps(List<RebaseTodoLine> steps) { // the handler receives the list of commits that are rebased, i.e. the ones on the local branch for(RebaseTodoLine step : steps) { // for each step, you can decide which action should be taken // default is PICK try { // by selecting "EDIT", the rebase will stop and ask you to edit the commit-contents step.setAction(Action.EDIT); } catch (IllegalTodoFileModification e) { throw new IllegalStateException(e); } } } @Override public String modifyCommitMessage(String oldMessage) { return oldMessage; } }; RebaseResult result = git.rebase().setUpstream("origin/master").runInteractively(handler).call(); System.out.println("Rebase had state: " + result.getStatus() + ": " + result.getConflicts()); // because of the "EDIT" in the InteractiveHandler, the rebase was stopped in-between // now you can adjust the commit and continue rebasing with setOperation(RebaseCommand.Operation.CONTINUE) // to use the local changes for the commit or setOperation(RebaseCommand.Operation.SKIP) to skip this // commit (i.e. remove it from the branch!) if(!result.getStatus().isSuccessful()) { // if rebasing stopped or failed, you can get back to the original state by running it with setOperation(RebaseCommand.Operation.ABORT) result = git.rebase().setUpstream("origin/master").runInteractively(handler).setOperation(RebaseCommand.Operation.ABORT).call(); System.out.println("Aborted reabse with state: " + result.getStatus() + ": " + result.getConflicts()); } } } }