use of org.eclipse.jgit.api.RebaseResult in project kie-wb-common by kiegroup.
the class JGitUtils method pullAndRebase.
public static Boolean pullAndRebase(final Git git) {
Boolean result = Boolean.FALSE;
try {
git.reset().setMode(ResetCommand.ResetType.HARD).call();
final RebaseResult rr = git.pull().setRemote(REMOTE).setRebase(Boolean.TRUE).call().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;
}
use of org.eclipse.jgit.api.RebaseResult in project kie-wb-common by kiegroup.
the class JGitUtils method applyBefore.
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;
}
use of org.eclipse.jgit.api.RebaseResult in project kie-wb-common by kiegroup.
the class DefaultMavenCompilerTest method buildWithPullRebaseUberfireTest.
@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();
// nothing changed yet
assertTrue(pullRes.getRebaseResult().getStatus().equals(RebaseResult.Status.UP_TO_DATE));
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());
}
use of org.eclipse.jgit.api.RebaseResult in project kie-wb-common by kiegroup.
the class KieDefaultMavenCompilerTest method buildWithPullRebaseUberfireTest.
@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();
// nothing changed yet
assertTrue(pullRes.getRebaseResult().getStatus().equals(RebaseResult.Status.UP_TO_DATE));
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());
}
use of org.eclipse.jgit.api.RebaseResult in project fabric8 by jboss-fuse.
the class DefaultPullPushPolicy method doPull.
@Override
public synchronized PullPolicyResult doPull(GitContext context, CredentialsProvider credentialsProvider, boolean allowVersionDelete, boolean allowPush, int timeoutInSeconds) {
Repository repository = git.getRepository();
StoredConfig config = repository.getConfig();
String remoteUrl = config.getString("remote", remoteRef, "url");
if (remoteUrl == null) {
LOGGER.info("No remote repository defined, so not doing a pull");
return new AbstractPullPolicyResult();
}
LOGGER.info("Performing a pull on remote URL: {}", remoteUrl);
// Get local and remote branches
Map<String, Ref> localBranches = new HashMap<String, Ref>();
Map<String, Ref> remoteBranches = new HashMap<String, Ref>();
Set<String> allBranches = new HashSet<String>();
Exception lastException = null;
try {
// when trying to fast-forward to commit done upstream between fetch and ls-remote!
for (Ref ref : git.lsRemote().setTimeout(timeoutInSeconds).setCredentialsProvider(credentialsProvider).setTags(false).setHeads(true).setRemote(remoteRef).call()) {
if (ref.getName().startsWith("refs/heads/")) {
String name = ref.getName().substring(("refs/heads/").length());
remoteBranches.put(name, ref);
allBranches.add(name);
}
}
git.fetch().setTimeout(timeoutInSeconds).setCredentialsProvider(credentialsProvider).setTagOpt(TagOpt.FETCH_TAGS).setRemote(remoteRef).call();
} catch (Exception ex) {
lastException = ex;
}
// No meaningful processing after GitAPIException
if (lastException != null) {
logPullException(lastException);
return new AbstractPullPolicyResult(lastException);
}
try {
// list local branches
for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
// }
if (ref.getName().startsWith("refs/heads/")) {
String name = ref.getName().substring(("refs/heads/").length());
localBranches.put(name, ref);
allBranches.add(name);
}
}
Map<String, BranchChange> localUpdate = new HashMap<>();
boolean remoteUpdate = false;
Set<String> versions = new TreeSet<>();
// Remote repository has no branches, force a push
if (remoteBranches.isEmpty()) {
LOGGER.info("Pulled from an empty remote repository");
return new AbstractPullPolicyResult(versions, localUpdate, !localBranches.isEmpty(), null);
} else {
LOGGER.debug("Processing remote branches: {}", remoteBranches);
}
// Verify master branch and do a checkout of it when we have it locally (already)
IllegalStateAssertion.assertTrue(remoteBranches.containsKey(GitHelpers.MASTER_BRANCH), "Remote repository does not have a master branch");
// Iterate over all local/remote branches
for (String branch : allBranches) {
// Delete a local branch that does not exist remotely, but not master
boolean allowDelete = allowVersionDelete && !GitHelpers.MASTER_BRANCH.equals(branch);
if (localBranches.containsKey(branch) && !remoteBranches.containsKey(branch)) {
if (allowDelete) {
String remotebranchRef = String.format("remotes/%s/%s", remoteRef, branch);
LOGGER.info("Deleting local branch: {} and local reference to remote branch: {}", branch, remotebranchRef);
// which can't be deleted
if (branch.equals(git.getRepository().getBranch())) {
// to remove not-tracked files
git.clean().setCleanDirectories(true).call();
// for file permissions
git.reset().setMode(ResetCommand.ResetType.MIXED).call();
// for other changes
git.reset().setMode(ResetCommand.ResetType.HARD).call();
git.checkout().setName("master").call();
}
git.branchDelete().setBranchNames(branch, remotebranchRef).setForce(true).call();
localUpdate.put(branch, new BranchChange(branch).removed());
} else {
remoteUpdate = true;
}
} else // Create a local branch that exists remotely
if (!localBranches.containsKey(branch) && remoteBranches.containsKey(branch)) {
LOGGER.info("Adding new local branch: {}", branch);
git.checkout().setCreateBranch(true).setName(branch).setStartPoint(remoteRef + "/" + branch).setUpstreamMode(SetupUpstreamMode.TRACK).setForce(true).call();
versions.add(branch);
localUpdate.put(branch, new BranchChange(branch).created());
} else // Update a local branch that also exists remotely
if (localBranches.containsKey(branch) && remoteBranches.containsKey(branch)) {
ObjectId localObjectId = localBranches.get(branch).getObjectId();
ObjectId remoteObjectId = remoteBranches.get(branch).getObjectId();
String localCommit = localObjectId.getName();
String remoteCommit = remoteObjectId.getName();
if (!localCommit.equals(remoteCommit)) {
git.clean().setCleanDirectories(true).call();
git.checkout().setName(branch).setForce(true).call();
MergeResult mergeResult = git.merge().setFastForward(FastForwardMode.FF_ONLY).include(remoteObjectId).call();
MergeStatus mergeStatus = mergeResult.getMergeStatus();
LOGGER.info("Updating local branch {} with status: {} ({}..{})", branch, mergeStatus, localCommit, remoteCommit);
if (mergeStatus == MergeStatus.FAST_FORWARD) {
localUpdate.put(branch, new BranchChange(branch).updated(localObjectId, remoteObjectId, "fast forward"));
} else if (mergeStatus == MergeStatus.ALREADY_UP_TO_DATE) {
if (allowPush) {
LOGGER.info("Remote branch {} is behind local version - changes will be pushed", branch);
remoteUpdate = true;
} else {
LOGGER.info("Remote branch {} is behind local version - changes won't be pushed - restoring remote tracking branch", branch);
GitHelpers.createOrCheckoutBranch(git, GitHelpers.MASTER_BRANCH, GitHelpers.REMOTE_ORIGIN);
git.branchDelete().setBranchNames(branch).setForce(true).call();
git.checkout().setCreateBranch(true).setName(branch).setStartPoint(remoteRef + "/" + branch).setUpstreamMode(SetupUpstreamMode.TRACK).setForce(true).call();
localUpdate.put(branch, new BranchChange(branch).updated(localObjectId, remoteObjectId, "reset"));
}
} else if (mergeStatus == MergeStatus.ABORTED) {
// failure to merge using FastForwardMode.FF_ONLY always ends with MergeStatus.ABORTED
RebaseResult.Status rebaseStatus = null;
if (allowPush) {
LOGGER.info("Cannot fast forward branch {}, attempting rebase", branch);
RebaseResult rebaseResult = git.rebase().setUpstream(remoteCommit).call();
rebaseStatus = rebaseResult.getStatus();
}
if (rebaseStatus == RebaseResult.Status.OK) {
LOGGER.info("Rebase successful for branch {}", branch);
localUpdate.put(branch, new BranchChange(branch).updated(localObjectId, remoteObjectId, "rebase"));
remoteUpdate = true;
} else {
if (allowPush) {
LOGGER.warn("Rebase on branch {} failed, restoring remote tracking branch", branch);
git.rebase().setOperation(Operation.ABORT).call();
} else {
LOGGER.info("Restoring remote tracking branch {}", branch);
}
GitHelpers.createOrCheckoutBranch(git, GitHelpers.MASTER_BRANCH, GitHelpers.REMOTE_ORIGIN, remoteCommit);
git.branchDelete().setBranchNames(branch).setForce(true).call();
git.checkout().setCreateBranch(true).setName(branch).setStartPoint(remoteRef + "/" + branch).setUpstreamMode(SetupUpstreamMode.TRACK).setForce(true).call();
localUpdate.put(branch, new BranchChange(branch).updated(localObjectId, remoteObjectId, "reset"));
}
}
} else if (!git.status().call().isClean()) {
LOGGER.info("Local branch {} is up to date, but not clean. Cleaning working copy now.", branch);
// to remove not-tracked files
git.clean().setCleanDirectories(true).call();
// for file permissions
git.reset().setMode(ResetCommand.ResetType.MIXED).call();
// for other changes
git.reset().setMode(ResetCommand.ResetType.HARD).call();
}
versions.add(branch);
}
}
if (localUpdate.size() > 0) {
if (--mergesWithoutGC < 0) {
mergesWithoutGC = MAX_MERGES_WITHOUT_GC;
LOGGER.info("Performing 'git gc' after {} merges", MAX_MERGES_WITHOUT_GC);
try {
git.gc().setAggressive(true).call();
} catch (Exception e) {
LOGGER.warn("Problem invoking 'git gc': {}", e.getMessage());
}
}
}
PullPolicyResult result = new AbstractPullPolicyResult(versions, localUpdate, remoteUpdate, null);
LOGGER.info("Pull result: {}", result);
return result;
} catch (Exception ex) {
LOGGER.error(ex.getMessage(), ex);
return new AbstractPullPolicyResult(ex);
}
}
Aggregations