Java Code Examples for org.eclipse.jgit.api.PullResult#isSuccessful()

The following examples show how to use org.eclipse.jgit.api.PullResult#isSuccessful() . 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: GitRepositoryExampleService.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
protected IStatus updateRepository(IProgressMonitor monitor) {
	String repoURL = getPreference(ExamplesPreferenceConstants.REMOTE_LOCATION);

	java.nio.file.Path storageLocation = getStorageLocation();
	try {
		Git git = Git.open(storageLocation.toFile());
		PullResult result = git.pull().setProgressMonitor(new EclipseGitProgressTransformer(monitor)).call();
		if (!result.isSuccessful()) {
			return new Status(IStatus.ERROR, ExampleActivator.PLUGIN_ID,
					"Unable to update repository " + repoURL + "!");
		}
	} catch (GitAPIException | IOException e) {
		return new Status(IStatus.ERROR, ExampleActivator.PLUGIN_ID,
				"Unable to update repository " + repoURL + "!");
	}
	return Status.OK_STATUS;
}
 
Example 2
Source File: PullTask.java    From ant-git-tasks with Apache License 2.0 6 votes vote down vote up
@Override
public void doExecute() {
        try {
                PullCommand pullCommand = git.pull().setRebase(rebase);

                if (getProgressMonitor() != null) {
                        pullCommand.setProgressMonitor(getProgressMonitor());
                }

                setupCredentials(pullCommand);
                PullResult pullResult = pullCommand.call();

                if (!pullResult.isSuccessful()) {
                        FetchResult fetchResult = pullResult.getFetchResult();
                        GitTaskUtils.validateTrackingRefUpdates(MESSAGE_PULLED_FAILED, fetchResult.getTrackingRefUpdates());
                        MergeStatus mergeStatus = pullResult.getMergeResult().getMergeStatus();

                        if (!mergeStatus.isSuccessful()) {
                                throw new BuildException(String.format(MESSAGE_PULLED_FAILED_WITH_STATUS, mergeStatus.name()));
                        }
                }
        }
        catch (Exception e) {
                throw new GitBuildException(String.format(MESSAGE_PULLED_FAILED_WITH_URI, getUri()), e);
        }
}
 
Example 3
Source File: GitMergeUtil.java    From MergeProcessor with Apache License 2.0 5 votes vote down vote up
/**
 * {@code git pull}
 */
private void pull() {
	try {
		final PullResult call = repo.pull().call();
		if (!call.isSuccessful()) {
			exception = new MergeUnitException(
					String.format("Could not pull from remote repository '%s'", repo)); //$NON-NLS-1$
		}
	} catch (GitAPIException e) {
		exception = new MergeUnitException(String.format("Could not push the local repository '%s'.", repo), e); //$NON-NLS-1$
	}
}
 
Example 4
Source File: InitDBBootApplication.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
public void  updateDBdata() throws InterruptedException {
  File file = ps.downloadDocBySsh();
ps.done(file);
logger.info("end init translate data to db--------------------------------------");
ps.gitStatus();

while (ps.getGitProp().getCheckIntervalTime() > 60000) {

	Thread.sleep(ps.getGitProp().getCheckIntervalTime());

	logger.info("----------------------beign pull status --------------------------");

	logger.info("begin pull from remote");
	PullResult pullRS = ps.gitpull();
	logger.info("end pull from remote");
	logger.info("--------------the pull status-" + pullRS.getMergeResult().getMergeStatus());

	if (pullRS.isSuccessful()
			&& !pullRS.getMergeResult().getMergeStatus().equals(MergeStatus.ALREADY_UP_TO_DATE)) {
		logger.info("remote translation files have updated!!!");
		logger.info("begin update data to DB");
		ps.done(file);
		logger.info("end updated data to DB");

	} else if (pullRS.isSuccessful()
			&& pullRS.getMergeResult().getMergeStatus().equals(MergeStatus.ALREADY_UP_TO_DATE)) {
		logger.info("remote translation file have not updated!!!");
	} else {
		logger.error("remote translation file merged error");
		file = ps.downloadDocBySsh();
		ps.done(file);

	}

}

logger.info("------------------------------end done run----------------------------");
 }
 
Example 5
Source File: GitConfigStore.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
private Git initializeGit() throws IOException, GitAPIException {
  if (path.isDirectory()) {
    Git git = Git.open(path);
    String current = git.getRepository().getBranch();
    if (branch.equalsIgnoreCase(current)) {
      PullResult pull = git.pull().setRemote(remote).setCredentialsProvider(credentialProvider)
        .setTransportConfigCallback(transportConfigCallback).call();
      if (!pull.isSuccessful()) {
        LOGGER.warn("Unable to pull the branch + '" + branch +
          "' from the remote repository '" + remote + "'");
      }
      return git;
    } else {
      git.checkout()
        .setName(branch)
        .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
        .setStartPoint(remote + "/" + branch)
        .call();
      return git;
    }
  } else {
    return Git.cloneRepository()
      .setURI(url)
      .setBranch(branch)
      .setRemote(remote)
      .setDirectory(path)
      .setCredentialsProvider(credentialProvider)
      .setTransportConfigCallback(transportConfigCallback)
      .call();
  }
}
 
Example 6
Source File: RepositorioCartasServico.java    From portal-de-servicos with MIT License 5 votes vote down vote up
@SneakyThrows
public boolean contemAtualizacoes() {
    if (caminhoLocal == null) {
        caminhoLocal = clonarRepositorio(criarDiretorioTemporario());
        caminhoLocal.deleteOnExit();
        return true;

    }

    log.debug("Atualizando repositório de cartas de serviço de {} para {}", urlRepositorio, caminhoLocal);
    try (Git repositorio = Git.open(caminhoLocal)) {
        String oldHead = repositorio.getRepository().getRef(R_HEADS + MASTER).getObjectId().getName();

        PullResult result = repositorio.pull()
                .setProgressMonitor(new LogstashProgressMonitor(log))
                .setStrategy(THEIRS)
                .call();

        if (!result.isSuccessful()) {
            log.error("Erro ao atualizar repositório: {}", result);
            return false;
        }

        String head = repositorio.reset()
                .setMode(HARD)
                .setRef("refs/remotes/origin/master")
                .call()
                .getObjectId()
                .getName();

        if (oldHead.equals(head)) {
            log.info("Repositório de cartas de serviço em {} já está na versão mais recente: {}", caminhoLocal, head);
            return false;

        }

        log.info("Repositório de cartas de serviço em {} atualizado da versão {} para {}", caminhoLocal, oldHead, head);
        return true;
    }
}
 
Example 7
Source File: GitSynchronizeWindow.java    From XACML with MIT License 5 votes vote down vote up
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");
}
 
Example 8
Source File: ThemeServiceImpl.java    From halo with GNU General Public License v3.0 4 votes vote down vote up
private void pullFromGit(@NonNull ThemeProperty themeProperty) throws
    IOException, GitAPIException, URISyntaxException {
    Assert.notNull(themeProperty, "Theme property must not be null");

    // Get branch
    String branch = StringUtils.isBlank(themeProperty.getBranch()) ?
        DEFAULT_REMOTE_BRANCH : themeProperty.getBranch();

    Git git = null;

    try {
        git = GitUtils.openOrInit(Paths.get(themeProperty.getThemePath()));

        Repository repository = git.getRepository();

        RevWalk revWalk = new RevWalk(repository);

        Ref ref = repository.findRef(Constants.HEAD);

        Assert.notNull(ref, Constants.HEAD + " ref was not found!");

        RevCommit lastCommit = revWalk.parseCommit(ref.getObjectId());

        // Force to set remote name
        git.remoteRemove().setRemoteName(THEME_PROVIDER_REMOTE_NAME).call();
        RemoteConfig remoteConfig = git.remoteAdd()
            .setName(THEME_PROVIDER_REMOTE_NAME)
            .setUri(new URIish(themeProperty.getRepo()))
            .call();

        // Add all changes
        git.add()
            .addFilepattern(".")
            .call();
        // Commit the changes
        git.commit().setMessage("Commit by halo automatically").call();

        // Check out to specified branch
        if (!StringUtils.equalsIgnoreCase(branch, git.getRepository().getBranch())) {
            boolean present = git.branchList()
                .call()
                .stream()
                .map(Ref::getName)
                .anyMatch(name -> StringUtils.equalsIgnoreCase(name, branch));

            git.checkout()
                .setCreateBranch(true)
                .setForced(!present)
                .setName(branch)
                .call();
        }

        // Pull with rebasing
        PullResult pullResult = git.pull()
            .setRemote(remoteConfig.getName())
            .setRemoteBranchName(branch)
            .setRebase(true)
            .call();

        if (!pullResult.isSuccessful()) {
            log.debug("Rebase result: [{}]", pullResult.getRebaseResult());
            log.debug("Merge result: [{}]", pullResult.getMergeResult());

            throw new ThemeUpdateException("拉取失败!您与主题作者可能同时更改了同一个文件");
        }

        // updated successfully.
        ThemeProperty updatedThemeProperty = getProperty(Paths.get(themeProperty.getThemePath()));

        // Not support current halo version.
        if (StringUtils.isNotEmpty(updatedThemeProperty.getRequire()) && !VersionUtil.compareVersion(HaloConst.HALO_VERSION, updatedThemeProperty.getRequire())) {
            // reset theme version
            git.reset()
                .setMode(ResetCommand.ResetType.HARD)
                .setRef(lastCommit.getName())
                .call();
            throw new ThemeNotSupportException("新版本主题仅支持 Halo " + updatedThemeProperty.getRequire() + " 以上的版本");
        }
    } finally {
        GitUtils.closeQuietly(git);
    }

}
 
Example 9
Source File: PullJob.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private IStatus doPull(IProgressMonitor monitor) throws IOException, GitAPIException, CoreException {
	ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
	Repository db = null;
	try {
		db = FileRepositoryBuilder.create(GitUtils.getGitDir(path));
		Git git = Git.wrap(db);
		PullCommand pc = git.pull();
		pc.setProgressMonitor(gitMonitor);
		pc.setCredentialsProvider(credentials);
		pc.setTransportConfigCallback(new TransportConfigCallback() {
			@Override
			public void configure(Transport t) {
				credentials.setUri(t.getURI());
				if (t instanceof TransportHttp && cookie != null) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put(GitConstants.KEY_COOKIE, cookie.getName() + "=" + cookie.getValue());
					((TransportHttp) t).setAdditionalHeaders(map);
				}
			}
		});
		PullResult pullResult = pc.call();

		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}

		// handle result
		if (pullResult.isSuccessful()) {
			return Status.OK_STATUS;
		}
		FetchResult fetchResult = pullResult.getFetchResult();

		IStatus fetchStatus = FetchJob.handleFetchResult(fetchResult);
		if (!fetchStatus.isOK()) {
			return fetchStatus;
		}

		MergeStatus mergeStatus = pullResult.getMergeResult().getMergeStatus();
		if (!mergeStatus.isSuccessful())
			return new Status(IStatus.ERROR, GitActivator.PI_GIT, mergeStatus.name());
	} finally {
		if (db != null) {
			db.close();
		}
	}
	return Status.OK_STATUS;
}