use of org.eclipse.jgit.api.PullCommand in project MGit by maks.
the class PullTask method pullRepo.
public boolean pullRepo() {
Git git;
try {
git = mRepo.getGit();
} catch (StopTaskException e) {
return false;
}
PullCommand pullCommand = git.pull().setRemote(mRemote).setProgressMonitor(new BasicProgressMonitor()).setTransportConfigCallback(new SgitTransportCallback());
setCredentials(pullCommand);
try {
String branch = null;
if (mForcePull) {
branch = git.getRepository().getFullBranch();
if (!branch.startsWith("refs/heads/")) {
setException(new GitAPIException("not on branch") {
}, R.string.error_pull_failed_not_on_branch);
return false;
}
branch = branch.substring(11);
BasicProgressMonitor bpm = new BasicProgressMonitor();
bpm.beginTask("clearing repo state", 3);
git.getRepository().writeMergeCommitMsg(null);
git.getRepository().writeMergeHeads(null);
bpm.update(1);
try {
git.rebase().setOperation(RebaseCommand.Operation.ABORT).call();
} catch (Exception e) {
}
bpm.update(2);
git.reset().setMode(ResetCommand.ResetType.HARD).setRef("HEAD").call();
bpm.endTask();
}
pullCommand.call();
if (mForcePull) {
BasicProgressMonitor bpm = new BasicProgressMonitor();
bpm.beginTask("resetting to " + mRemote + "/" + branch, 1);
git.reset().setMode(ResetCommand.ResetType.HARD).setRef(mRemote + "/" + branch).call();
bpm.endTask();
}
} catch (TransportException e) {
setException(e);
handleAuthError(this);
return false;
} catch (Exception e) {
setException(e, R.string.error_pull_failed);
return false;
} catch (OutOfMemoryError e) {
setException(e, R.string.error_out_of_memory);
return false;
} catch (Throwable e) {
setException(e);
return false;
}
mRepo.updateLatestCommitInfo();
return true;
}
use of org.eclipse.jgit.api.PullCommand in project egit by eclipse.
the class PullOperation method execute.
@Override
public void execute(IProgressMonitor m) throws CoreException {
if (!results.isEmpty())
throw new CoreException(new Status(IStatus.ERROR, Activator.getPluginId(), CoreText.OperationAlreadyExecuted));
SubMonitor totalProgress = SubMonitor.convert(m, NLS.bind(CoreText.PullOperation_TaskName, Integer.valueOf(repositories.length)), 1);
IWorkspaceRunnable action = new IWorkspaceRunnable() {
@Override
public void run(IProgressMonitor mymonitor) throws CoreException {
if (mymonitor.isCanceled())
throw new CoreException(Status.CANCEL_STATUS);
SubMonitor progress = SubMonitor.convert(mymonitor, repositories.length * 2);
for (int i = 0; i < repositories.length; i++) {
Repository repository = repositories[i];
IProject[] validProjects = ProjectUtil.getValidOpenProjects(repository);
PullResult pullResult = null;
try (Git git = new Git(repository)) {
PullCommand pull = git.pull();
SubMonitor newChild = progress.newChild(1, SubMonitor.SUPPRESS_NONE);
pull.setProgressMonitor(new EclipseGitProgressTransformer(newChild));
pull.setTimeout(timeout);
pull.setCredentialsProvider(credentialsProvider);
PullReferenceConfig config = configs.get(repository);
newChild.setTaskName(getPullTaskName(repository, config));
if (config != null) {
if (config.getRemote() != null) {
pull.setRemote(config.getRemote());
}
if (config.getReference() != null) {
pull.setRemoteBranchName(config.getReference());
}
pull.setRebase(config.getUpstreamConfig());
}
MergeStrategy strategy = Activator.getDefault().getPreferredMergeStrategy();
if (strategy != null) {
pull.setStrategy(strategy);
}
pullResult = pull.call();
results.put(repository, pullResult);
} catch (DetachedHeadException e) {
results.put(repository, Activator.error(CoreText.PullOperation_DetachedHeadMessage, e));
} catch (InvalidConfigurationException e) {
IStatus error = Activator.error(CoreText.PullOperation_PullNotConfiguredMessage, e);
results.put(repository, error);
} catch (GitAPIException e) {
results.put(repository, Activator.error(e.getMessage(), e));
} catch (JGitInternalException e) {
Throwable cause = e.getCause();
if (cause == null || !(cause instanceof TransportException))
cause = e;
results.put(repository, Activator.error(cause.getMessage(), cause));
} finally {
if (refreshNeeded(pullResult)) {
ProjectUtil.refreshValidProjects(validProjects, progress.newChild(1, SubMonitor.SUPPRESS_NONE));
} else {
progress.worked(1);
}
}
}
}
};
// lock workspace to protect working tree changes
ResourcesPlugin.getWorkspace().run(action, getSchedulingRule(), IWorkspace.AVOID_UPDATE, totalProgress);
}
use of org.eclipse.jgit.api.PullCommand in project searchcode-server by boyter.
the class IndexGitRepoJob method updateGitRepository.
/**
* Update a git repository and return if it has changed and the differences
*/
public RepositoryChanged updateGitRepository(RepoResult repoResult, String repoLocations, boolean useCredentials) {
boolean changed = false;
List<String> changedFiles = new ArrayList<>();
List<String> deletedFiles = new ArrayList<>();
this.logger.info(String.format("6cffea0f::attempting to pull latest from %s for %s", repoLocations, repoResult.getName()));
Repository localRepository = null;
Git git = null;
try {
localRepository = new FileRepository(new File(repoLocations + "/" + repoResult.getDirectoryName() + "/.git"));
Ref head = localRepository.getRef("HEAD");
git = new Git(localRepository);
git.reset();
git.clean();
PullCommand pullCmd = git.pull();
if (useCredentials) {
pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoResult.getUsername(), repoResult.getPassword()));
}
pullCmd.call();
Ref newHEAD = localRepository.getRef("HEAD");
if (!head.toString().equals(newHEAD.toString())) {
changed = true;
// Get the differences between the the heads which we updated at
// and use these to just update the differences between them
ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");
ObjectReader reader = localRepository.newObjectReader();
CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
oldTreeIter.reset(reader, oldHead);
CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
newTreeIter.reset(reader, newHead);
List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();
for (DiffEntry entry : entries) {
if ("DELETE".equals(entry.getChangeType().name())) {
deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
} else {
changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
}
}
}
} catch (IOException | GitAPIException | InvalidPathException ex) {
changed = false;
String error = String.format("c6646806::error in class %s exception %s repository %s", ex.getClass(), ex.getMessage(), repoResult.getName());
this.logger.severe(error);
repoResult.getData().indexError = error;
Singleton.getRepo().saveRepo(repoResult);
} finally {
Singleton.getHelpers().closeQuietly(localRepository);
Singleton.getHelpers().closeQuietly(git);
}
return new RepositoryChanged(changed, changedFiles, deletedFiles);
}
use of org.eclipse.jgit.api.PullCommand 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("/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/pom.xml").toPath())));
ioService.write(origin.getPath("/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("/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("/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("/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(origin.getGit().getRepository().getDirectory().toURI().toString()).setBare(false).setDirectory(tmpCloned.toFile()).call();
assertThat(cloned).isNotNull();
PullCommand pc = cloned.pull().setRemote("origin").setRebase(Boolean.TRUE);
PullResult pullRes = pc.call();
// nothing changed yet
assertThat(pullRes.getRebaseResult().getStatus()).isEqualTo(RebaseResult.Status.UP_TO_DATE);
RebaseCommand rb = cloned.rebase().setUpstream("origin/master");
RebaseResult rbResult = rb.setPreserveMerges(true).call();
assertThat(rbResult.getStatus().isSuccessful()).isTrue();
// Compile the repo
byte[] encoded = Files.readAllBytes(Paths.get(tmpCloned + "/pom.xml"));
String pomAsAstring = new String(encoded, StandardCharsets.UTF_8);
assertThat(pomAsAstring).doesNotContain(TestConstants.TAKARI_LIFECYCLE_ARTIFACT);
Path prjFolder = Paths.get(tmpCloned + "/");
final AFCompiler compiler = KieMavenCompilerFactory.getCompiler(EnumSet.of(KieDecorator.ENABLE_LOGGING, KieDecorator.ENABLE_INCREMENTAL_BUILD));
WorkspaceCompilationInfo info = new WorkspaceCompilationInfo(prjFolder);
CompilationRequest req = new DefaultCompilationRequest(mavenRepoPath, info, new String[] { MavenCLIArgs.COMPILE }, Boolean.TRUE);
CompilationResponse res = compiler.compile(req);
TestUtil.saveMavenLogIfCompilationResponseNotSuccessfull(tmpCloned, res, this.getClass(), testName);
assertThat(res.isSuccessful()).isTrue();
Path incrementalConfiguration = Paths.get(prjFolder + TestConstants.TARGET_TAKARI_PLUGIN);
assertThat(incrementalConfiguration.toFile()).exists();
encoded = Files.readAllBytes(Paths.get(prjFolder + "/pom.xml"));
pomAsAstring = new String(encoded, StandardCharsets.UTF_8);
assertThat(pomAsAstring).contains(TestConstants.KIE_TAKARI_LIFECYCLE_ARTIFACT);
TestUtil.rm(tmpRootCloned.toFile());
}
use of org.eclipse.jgit.api.PullCommand in project searchcode-server by boyter.
the class IndexGitRepoJob method updateGitRepository.
/**
* Update a git repository and return if it has changed and the differences
*/
public RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, String branch, boolean useCredentials) {
boolean changed = false;
List<String> changedFiles = new ArrayList<>();
List<String> deletedFiles = new ArrayList<>();
Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);
Repository localRepository = null;
Git git = null;
try {
localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));
Ref head = localRepository.getRef("HEAD");
git = new Git(localRepository);
git.reset();
git.clean();
PullCommand pullCmd = git.pull();
if (useCredentials) {
pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
}
pullCmd.call();
Ref newHEAD = localRepository.getRef("HEAD");
if (!head.toString().equals(newHEAD.toString())) {
changed = true;
// Get the differences between the the heads which we updated at
// and use these to just update the differences between them
ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");
ObjectReader reader = localRepository.newObjectReader();
CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
oldTreeIter.reset(reader, oldHead);
CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
newTreeIter.reset(reader, newHead);
List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();
for (DiffEntry entry : entries) {
if ("DELETE".equals(entry.getChangeType().name())) {
deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
} else {
changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
}
}
}
} catch (IOException | GitAPIException | InvalidPathException ex) {
changed = false;
Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " updateGitRepository for " + repoName + "\n with message: " + ex.getMessage());
} finally {
Singleton.getHelpers().closeQuietly(localRepository);
Singleton.getHelpers().closeQuietly(git);
}
return new RepositoryChanged(changed, changedFiles, deletedFiles);
}
Aggregations