下面列出了怎么用org.eclipse.jgit.transport.PushResult的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void pull() {
if (token == null) {
LOG.warn("Token not set!");
return;
} else {
gitUtils.add(LOCALPATH, "/log4j.properties");
gitUtils.commit(LOCALPATH, "add new file.");
Iterable<PushResult> iterable = gitUtils.push(LOCALPATH, token, REMOTE_PATH);
assertEquals(1, Lists.newArrayList(iterable).size());
PullResult pullResult = gitUtils.pull(LOCALPATH, token, "master");
assertEquals(1, pullResult.getFetchResult().getTrackingRefUpdates().size());
gitUtils.rm(LOCALPATH, "/log4j.properties");
gitUtils.commit(LOCALPATH, "add new file.");
gitUtils.push(LOCALPATH, token, REMOTE_PATH);
}
}
/**
* {@code git push}
*/
private void push() {
try {
final Iterable<PushResult> resultIterable = repo.push().call();
for (final PushResult pushResult : resultIterable) {
for (RemoteRefUpdate refUpdate : pushResult.getRemoteUpdates()) {
if (refUpdate.getStatus() != RemoteRefUpdate.Status.OK) {
// Push was rejected
exception = new MergeUnitException(String
.format("Could not push the local repository: '%s'", pushResult.getMessages()));
return;
}
}
}
} catch (GitAPIException e) {
exception = new MergeUnitException(String.format("Could not push the local repository '%s'.", repo), e); //$NON-NLS-1$
}
}
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() );
}
} );
}
public synchronized void backup() throws Exception {
repo.add().setUpdate(false).addFilepattern(".").call();
Status status = repo.status().setIgnoreSubmodules(SubmoduleWalk.IgnoreSubmoduleMode.ALL).call();
log.debug("status.getUncommittedChanges() = " + status.getUncommittedChanges());
if (!status.getUncommittedChanges().isEmpty()) {
for (String missingPath : status.getMissing()) {
repo.rm().addFilepattern(missingPath).call();
}
log.info("Changes detected in the following files: " + status.getUncommittedChanges());
repo.commit()
.setMessage("Backing up data dir")
.setAuthor("AppRunner BackupService", "[email protected]")
.call();
Iterable<PushResult> pushResults = repo.push().call();
for (PushResult pushResult : pushResults) {
log.info("Result of pushing to remote: " + pushResult.getRemoteUpdates());
}
} else {
log.info("No changes to back up");
}
}
@Override
public String publish(String name) throws ConfigurationPersistenceException {
StringBuilder message = new StringBuilder();
String remoteName = gitRepository.getRemoteName(name);
if (remoteName != null && gitRepository.isValidRemoteName(remoteName)) {
try (Git git = gitRepository.getGit()) {
Iterable<PushResult> result = git.push().setRemote(remoteName)
.setRefSpecs(new RefSpec(gitRepository.getBranch() + ':' + gitRepository.getBranch()))
.setPushTags().call();
for (PushResult pushResult : result) {
for (RemoteRefUpdate refUpdate : pushResult.getRemoteUpdates()) {
message.append(refUpdate.getMessage()).append(" ").append(refUpdate.getNewObjectId().name()).append('\n');
}
}
} catch (GitAPIException ex) {
throw MGMT_OP_LOGGER.failedToPublishConfiguration(ex, name, ex.getMessage());
}
}
return message.toString();
}
protected RevCommit commitThenPush(Git git, CommitCommand commit) throws Exception {
RevCommit answer = commit.call();
if (LOG.isDebugEnabled()) {
LOG.debug("Committed " + answer.getId() + " " + answer.getFullMessage());
}
if (isPushOnCommit()) {
Iterable<PushResult> results = doPush(git);
for (PushResult result : results) {
if (LOG.isDebugEnabled()) {
LOG.debug("Pushed " + result.getMessages() + " " + result.getURI() + " branch: " + branch + " updates: " + toString(result.getRemoteUpdates()));
}
}
}
return answer;
}
/**
* Attempts to push to a non-existent branch to validate the user actually has push access
*
* @param repo local repository
* @param remoteUrl git repo url
* @param credential credential to use when accessing git
*/
public static void validatePushAccess(@Nonnull Repository repo, @Nonnull String remoteUrl, @Nullable StandardCredentials credential) throws GitException {
try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
// we need to perform an actual push, so we try a deletion of a very-unlikely-to-exist branch
// which needs to have push permissions in order to get a 'branch not found' message
String pushSpec = ":this-branch-is-only-to-test-if-jenkins-has-push-access";
PushCommand pushCommand = git.push();
addCredential(repo, pushCommand, credential);
Iterable<PushResult> resultIterable = pushCommand
.setRefSpecs(new RefSpec(pushSpec))
.setRemote(remoteUrl)
.setDryRun(true) // we only want to test
.call();
PushResult result = resultIterable.iterator().next();
if (result.getRemoteUpdates().isEmpty()) {
System.out.println("No remote updates occurred");
} else {
for (RemoteRefUpdate update : result.getRemoteUpdates()) {
if (!RemoteRefUpdate.Status.NON_EXISTING.equals(update.getStatus()) && !RemoteRefUpdate.Status.OK.equals(update.getStatus())) {
throw new ServiceException.UnexpectedErrorException("Expected non-existent ref but got: " + update.getStatus().name() + ": " + update.getMessage());
}
}
}
} catch (GitAPIException e) {
if (e.getMessage().toLowerCase().contains("auth")) {
throw new ServiceException.UnauthorizedException(e.getMessage(), e);
}
throw new ServiceException.UnexpectedErrorException("Unable to access and push to: " + remoteUrl + " - " + e.getMessage(), e);
}
}
public static void push(String remoteUrl, Repository repo, StandardCredentials credential, String localBranchRef, String remoteBranchRef) {
try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
String pushSpec = "+" + localBranchRef + ":" + remoteBranchRef;
PushCommand pushCommand = git.push();
addCredential(repo, pushCommand, credential);
Iterable<PushResult> resultIterable = pushCommand
.setRefSpecs(new RefSpec(pushSpec))
.setRemote(remoteUrl)
.call();
PushResult result = resultIterable.iterator().next();
if (result.getRemoteUpdates().isEmpty()) {
throw new RuntimeException("No remote updates occurred");
} else {
for (RemoteRefUpdate update : result.getRemoteUpdates()) {
if (!RemoteRefUpdate.Status.OK.equals(update.getStatus())) {
throw new ServiceException.UnexpectedErrorException("Remote update failed: " + update.getStatus().name() + ": " + update.getMessage());
}
}
}
} catch (GitAPIException e) {
if (e.getMessage().toLowerCase().contains("auth")) {
throw new ServiceException.UnauthorizedException(e.getMessage(), e);
}
throw new ServiceException.UnexpectedErrorException("Unable to save and push to: " + remoteUrl + " - " + e.getMessage(), e);
}
}
public void pushToRepo() throws IOException, JGitInternalException, InvalidRemoteException, GitAPIException {
PushCommand pc = git.push();
pc.setCredentialsProvider(cp).setForce(true).setPushAll();
try {
Iterator<PushResult> it = pc.call().iterator();
if (it.hasNext()) {
System.out.println(it.next().toString());
}
} catch (InvalidRemoteException e) {
e.printStackTrace();
}
}
public static ArrayMemory valueOfPushResults(Iterable<PushResult> values) {
ArrayMemory memory = new ArrayMemory();
for (PushResult value : values) {
memory.add(valueOf(value));
}
return memory;
}
public void testPushRejectNonFastForward () throws Exception {
String remoteUri = getRemoteRepository().getWorkTree().toURI().toString();
assertEquals(0, getClient(workDir).listRemoteBranches(remoteUri, NULL_PROGRESS_MONITOR).size());
File f = new File(workDir, "f");
add(f);
String id = getClient(workDir).commit(new File[] { f }, "bbb", null, null, NULL_PROGRESS_MONITOR).getRevision();
Map<String, GitTransportUpdate> updates = getClient(workDir).push(remoteUri, Arrays.asList(new String[] { "refs/heads/master:refs/heads/master" }), Collections.<String>emptyList(), NULL_PROGRESS_MONITOR).getRemoteRepositoryUpdates();
Map<String, GitBranch> remoteBranches = getClient(workDir).listRemoteBranches(remoteUri, NULL_PROGRESS_MONITOR);
assertEquals(1, remoteBranches.size());
assertEquals(id, remoteBranches.get("master").getId());
assertEquals(1, updates.size());
assertUpdate(updates.get("master"), "master", "master", id, null, new URIish(remoteUri).toString(), Type.BRANCH, GitRefUpdateResult.OK);
// modification
write(f, "huhu");
add(f);
String newid = getClient(workDir).commit(new File[] { f }, "bbb", null, null, NULL_PROGRESS_MONITOR).getRevision();
updates = getClient(workDir).push(remoteUri, Arrays.asList(new String[] { "refs/heads/master:refs/heads/master" }), Collections.<String>emptyList(), NULL_PROGRESS_MONITOR).getRemoteRepositoryUpdates();
remoteBranches = getClient(workDir).listRemoteBranches(remoteUri, NULL_PROGRESS_MONITOR);
assertEquals(1, remoteBranches.size());
assertEquals(newid, remoteBranches.get("master").getId());
assertEquals(1, updates.size());
assertUpdate(updates.get("master"), "master", "master", newid, id, new URIish(remoteUri).toString(), Type.BRANCH, GitRefUpdateResult.OK);
getClient(workDir).createBranch("localbranch", id, NULL_PROGRESS_MONITOR);
getClient(workDir).checkoutRevision("localbranch", true, NULL_PROGRESS_MONITOR);
write(f, "huhu2");
add(f);
id = getClient(workDir).commit(new File[] { f }, "some change before merge", null, null, NULL_PROGRESS_MONITOR).getRevision();
updates = getClient(workDir).push(remoteUri, Arrays.asList(new String[] { "+refs/heads/localbranch:refs/heads/master" }), Collections.<String>emptyList(), NULL_PROGRESS_MONITOR).getRemoteRepositoryUpdates();
remoteBranches = getClient(workDir).listRemoteBranches(remoteUri, NULL_PROGRESS_MONITOR);
assertEquals(1, remoteBranches.size());
assertEquals(newid, remoteBranches.get("master").getId());
assertEquals(1, updates.size());
assertUpdate(updates.get("master"), "localbranch", "master", id, newid, new URIish(remoteUri).toString(), Type.BRANCH, GitRefUpdateResult.REJECTED_NONFASTFORWARD);
updates = getClient(workDir).push(remoteUri, Arrays.asList(new String[] { "refs/heads/localbranch:refs/heads/master" }), Arrays.asList(new String[] { "+refs/heads/master:refs/remotes/origin/master" }), NULL_PROGRESS_MONITOR).getRemoteRepositoryUpdates();
remoteBranches = getClient(workDir).listRemoteBranches(remoteUri, NULL_PROGRESS_MONITOR);
assertEquals(1, remoteBranches.size());
assertEquals(newid, remoteBranches.get("master").getId());
assertEquals(1, updates.size());
assertUpdate(updates.get("master"), "localbranch", "master", id, newid, new URIish(remoteUri).toString(), Type.BRANCH, GitRefUpdateResult.REJECTED_NONFASTFORWARD);
// if starts failing, the WA at GitTransportUpdate.(URIish uri, TrackingRefUpdate update) should be removed
// this.result = GitRefUpdateResult.valueOf((update.getResult() == null ? RefUpdate.Result.NOT_ATTEMPTED : update.getResult()).name());
Transport transport = Transport.open(getRepository(getClient(workDir)), new URIish(remoteUri));
transport.setDryRun(false);
transport.setPushThin(true);
PushResult pushResult = transport.push(new DelegatingProgressMonitor(NULL_PROGRESS_MONITOR),
Transport.findRemoteRefUpdatesFor(getRepository(getClient(workDir)),
Collections.singletonList(new RefSpec("refs/heads/localbranch:refs/heads/master")),
Collections.singletonList(new RefSpec("refs/heads/master:refs/remotes/origin/master"))));
assertEquals(1, pushResult.getTrackingRefUpdates().size());
for (TrackingRefUpdate update : pushResult.getTrackingRefUpdates()) {
// null but not NOT_ATTEMPTED, probably a bug
// remove the WA if it starts failing here
assertNull(update.getResult());
}
}
private IStatus doPush(IProgressMonitor monitor) throws IOException, CoreException, URISyntaxException, GitAPIException {
ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
// /git/remote/{remote}/{branch}/file/{path}
File gitDir = GitUtils.getGitDir(path.removeFirstSegments(2));
Repository db = null;
JSONObject result = new JSONObject();
try {
db = FileRepositoryBuilder.create(gitDir);
Git git = Git.wrap(db);
PushCommand pushCommand = git.push();
pushCommand.setProgressMonitor(gitMonitor);
pushCommand.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);
}
}
});
RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
credentials.setUri(remoteConfig.getURIs().get(0));
pushCommand.setCredentialsProvider(credentials);
boolean pushToGerrit = branch.startsWith("for/");
RefSpec spec = new RefSpec(srcRef + ':' + (pushToGerrit ? "refs/" : Constants.R_HEADS) + branch);
pushCommand.setRemote(remote).setRefSpecs(spec);
if (tags)
pushCommand.setPushTags();
pushCommand.setForce(force);
Iterable<PushResult> resultIterable = pushCommand.call();
if (monitor.isCanceled()) {
return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
}
PushResult pushResult = resultIterable.iterator().next();
boolean error = false;
JSONArray updates = new JSONArray();
result.put(GitConstants.KEY_COMMIT_MESSAGE, pushResult.getMessages());
result.put(GitConstants.KEY_UPDATES, updates);
for (final RemoteRefUpdate rru : pushResult.getRemoteUpdates()) {
if (monitor.isCanceled()) {
return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
}
final String rm = rru.getRemoteName();
// check status only for branch given in the URL or tags
if (branch.equals(Repository.shortenRefName(rm)) || rm.startsWith(Constants.R_TAGS) || rm.startsWith(Constants.R_REFS + "for/")) {
JSONObject object = new JSONObject();
RemoteRefUpdate.Status status = rru.getStatus();
if (status != RemoteRefUpdate.Status.UP_TO_DATE || !rm.startsWith(Constants.R_TAGS)) {
object.put(GitConstants.KEY_COMMIT_MESSAGE, rru.getMessage());
object.put(GitConstants.KEY_RESULT, status.name());
TrackingRefUpdate refUpdate = rru.getTrackingRefUpdate();
if (refUpdate != null) {
object.put(GitConstants.KEY_REMOTENAME, Repository.shortenRefName(refUpdate.getLocalName()));
object.put(GitConstants.KEY_LOCALNAME, Repository.shortenRefName(refUpdate.getRemoteName()));
} else {
object.put(GitConstants.KEY_REMOTENAME, Repository.shortenRefName(rru.getSrcRef()));
object.put(GitConstants.KEY_LOCALNAME, Repository.shortenRefName(rru.getRemoteName()));
}
updates.put(object);
}
if (status != RemoteRefUpdate.Status.OK && status != RemoteRefUpdate.Status.UP_TO_DATE)
error = true;
}
// TODO: return results for all updated branches once push is available for remote, see bug 352202
}
// needs to handle multiple
result.put("Severity", error ? "Error" : "Ok");
} catch (JSONException e) {
} finally {
if (db != null) {
db.close();
}
}
return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
}
protected Iterable<PushResult> doPush(Git git) throws Exception {
PushCommand command = git.push();
configureCommand(command, userDetails);
return command.setRemote(getRemote()).call();
}
@Override
public boolean push(String sourceBranch, String destinationBranch) {
PushCommand command = _git.push();
boolean ret = true;
RefSpec refSpec = new RefSpec().setSourceDestination(sourceBranch, destinationBranch);
command.setRefSpecs(refSpec);
try {
List<Ref> remoteBranches = _git.branchList().setListMode(ListMode.REMOTE).call();
if(_cp != null)
command.setCredentialsProvider(_cp);
Iterable<PushResult> results = command.call();
for (PushResult pushResult : results) {
Collection<RemoteRefUpdate> resultsCollection = pushResult.getRemoteUpdates();
Map<PushResult,RemoteRefUpdate> resultsMap = new HashMap<>();
for(RemoteRefUpdate remoteRefUpdate : resultsCollection)
{
resultsMap.put(pushResult, remoteRefUpdate);
}
RemoteRefUpdate remoteUpdate = pushResult.getRemoteUpdate(destinationBranch);
if (remoteUpdate != null) {
org.eclipse.jgit.transport.RemoteRefUpdate.Status status =
remoteUpdate.getStatus();
ret =
status.equals(org.eclipse.jgit.transport.RemoteRefUpdate.Status.OK)
|| status.equals(org.eclipse.jgit.transport.RemoteRefUpdate.Status.UP_TO_DATE);
}
if(remoteUpdate == null && !remoteBranches.toString().contains(destinationBranch))
{
for(RemoteRefUpdate resultValue : resultsMap.values())
{
if(resultValue.toString().contains("REJECTED_OTHER_REASON"))
{
ret = false;
}
}
}
}
} catch (Throwable e) {
throw new RuntimeException(String.format(
"Failed to push [%s] into [%s]",
sourceBranch,
destinationBranch), e);
}
return ret;
}
@Override
public void execute(Wandora wandora, Context context) {
try {
Git git = getGit();
if(git != null) {
if(isNotEmpty(getGitRemoteUrl())) {
if(pushUI == null) {
pushUI = new PushUI();
}
pushUI.setPassword(getPassword());
pushUI.setUsername(getUsername());
pushUI.setRemoteUrl(getGitRemoteUrl());
pushUI.openInDialog();
if(pushUI.wasAccepted()) {
setDefaultLogger();
setLogTitle("Git push");
String username = pushUI.getUsername();
String password = pushUI.getPassword();
String remoteUrl = pushUI.getRemoteUrl();
setUsername(username);
setPassword(password);
// setGitRemoteUrl(remoteUrl);
PushCommand push = git.push();
log("Pushing local changes to upstream.");
if(username != null && username.length() > 0) {
CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider( username, password );
push.setCredentialsProvider(credentialsProvider);
}
Iterable<PushResult> pushResults = push.call();
for(PushResult pushResult : pushResults) {
String pushResultMessage = pushResult.getMessages();
if(isNotEmpty(pushResultMessage)) {
log(pushResultMessage);
}
}
log("Ready.");
}
}
else {
log("Repository has no remote origin and can't be pushed. "
+"Initialize repository by cloning remote repository to set the remote origin.");
}
}
else {
logAboutMissingGitRepository();
}
}
catch(TransportException tre) {
if(tre.toString().contains("origin: not found.")) {
log("Git remote origin is not found. Check the remote url and remote git repository.");
}
}
catch(GitAPIException gae) {
log(gae.toString());
}
catch(NoWorkTreeException nwte) {
log(nwte.toString());
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
@Override
protected void doExecute() {
try {
StoredConfig config = git.getRepository().getConfig();
List<RemoteConfig> remoteConfigs = RemoteConfig.getAllRemoteConfigs(config);
if (remoteConfigs.isEmpty()) {
URIish uri = new URIish(getUri());
RemoteConfig remoteConfig = new RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME);
remoteConfig.addURI(uri);
remoteConfig.addFetchRefSpec(new RefSpec(DEFAULT_REFSPEC_STRING));
remoteConfig.addPushRefSpec(new RefSpec(DEFAULT_REFSPEC_STRING));
remoteConfig.update(config);
config.save();
}
String currentBranch = git.getRepository().getBranch();
List<RefSpec> specs = Arrays.asList(new RefSpec(currentBranch + ":" + currentBranch));
PushCommand pushCommand = git.push().
setPushAll().
setRefSpecs(specs).
setDryRun(false).
setRemote(getUri());
setupCredentials(pushCommand);
if (includeTags) {
pushCommand.setPushTags();
}
if (getProgressMonitor() != null) {
pushCommand.setProgressMonitor(getProgressMonitor());
}
Iterable<PushResult> pushResults = pushCommand.setForce(true).call();
for (PushResult pushResult : pushResults) {
GitTaskUtils.validateTrackingRefUpdates(PUSH_FAILED_MESSAGE, pushResult.getTrackingRefUpdates());
log(pushResult.getMessages());
}
} catch (Exception e) {
if (pushFailedProperty != null) {
getProject().setProperty(pushFailedProperty, e.getMessage());
}
throw new GitBuildException(PUSH_FAILED_MESSAGE, e);
}
}
public static ArrayMemory valueOf(PushResult value) {
ArrayMemory memory = valueOf((OperationResult) value);
memory.refOfIndex("remoteUpdates").assign(valueOfRemoteRefUpdates(value.getRemoteUpdates()));
return memory;
}