下面列出了怎么用org.eclipse.jgit.transport.RemoteRefUpdate的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* {@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() );
}
} );
}
/**
*
* @param uri uri of the repo.
* @param update
* @param remoteBranches key value list of remote branches.
* @param remoteTags key value list of remote tags. Key - name of the tag, value - id (hash) of the tag.
*/
GitTransportUpdate(URIish uri, RemoteRefUpdate update, Map<String, GitBranch> remoteBranches, Map<String, String> remoteTags) {
this.localName = stripRefs(update.getSrcRef());
this.remoteName = stripRefs(update.getRemoteName());
this.type = getType(update.getRemoteName());
if (type == type.TAG) {
//get object id for deleted tag.
this.oldObjectId = remoteTags.get(remoteName);
} else {
this.oldObjectId = getOldRevisionId(remoteBranches.get(remoteName));
}
this.newObjectId = update.getNewObjectId() == null || ObjectId.zeroId().equals(update.getNewObjectId()) ? null : update.getNewObjectId().getName();
this.result = GitRefUpdateResult.valueOf(update.getStatus().name());
this.uri = uri.toString();
}
@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 String toString(Collection<RemoteRefUpdate> updates) {
StringBuilder builder = new StringBuilder();
for (RemoteRefUpdate update : updates) {
if (builder.length() > 0) {
builder.append(" ");
}
builder.append(update.getMessage() + " " + update.getRemoteName() + " " + update.getNewObjectId());
}
return builder.toString();
}
/**
* 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);
}
}
/**
* Check references updates for any errors
*
* @param errorPrefix The error prefix for any error message
* @param refUpdates A collection of remote references updates
*/
public static void validateRemoteRefUpdates(String errorPrefix, Collection<RemoteRefUpdate> refUpdates) {
for (RemoteRefUpdate refUpdate : refUpdates) {
RemoteRefUpdate.Status status = refUpdate.getStatus();
if (status == RemoteRefUpdate.Status.REJECTED_NODELETE ||
status == RemoteRefUpdate.Status.NON_EXISTING ||
status == RemoteRefUpdate.Status.NOT_ATTEMPTED ||
status == RemoteRefUpdate.Status.REJECTED_NONFASTFORWARD ||
status == RemoteRefUpdate.Status.REJECTED_OTHER_REASON ||
status == RemoteRefUpdate.Status.REJECTED_REMOTE_CHANGED) {
throw new BuildException(String.format("%s - Status '%s'", errorPrefix, status.name()));
}
}
}
public static ArrayMemory valueOf(RemoteRefUpdate value) {
ArrayMemory memory = new ArrayMemory();
memory.refOfIndex("message").assign(value.getMessage());
memory.refOfIndex("remoteName").assign(value.getRemoteName());
memory.refOfIndex("srcRef").assign(value.getSrcRef());
memory.refOfIndex("expectedOldObjectId").assign(valueOf(value.getExpectedOldObjectId()));
memory.refOfIndex("newObjectId").assign(valueOf(value.getNewObjectId()));
memory.refOfIndex("delete").assign(value.isDelete());
memory.refOfIndex("fastForward").assign(value.isFastForward());
memory.refOfIndex("forceUpdate").assign(value.isForceUpdate());
return memory;
}
public static ArrayMemory valueOfRemoteRefUpdates(Iterable<RemoteRefUpdate> values) {
ArrayMemory memory = new ArrayMemory();
for (RemoteRefUpdate value : values) {
memory.add(valueOf(value));
}
return memory;
}
@Override
public GitTransportUpdate createTransportUpdate(URIish urI, RemoteRefUpdate update, Map<String, GitBranch> remoteBranches, Map<String, String> remoteTags) {
return new GitTransportUpdate(urI, update, remoteBranches, remoteTags);
}
public void testRemoteUpdateStatus () {
for (RemoteRefUpdate.Status status : RemoteRefUpdate.Status.values()) {
assertNotNull(GitRefUpdateResult.valueOf(status.name()));
}
}
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);
}
@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;
}
public abstract GitTransportUpdate createTransportUpdate(URIish urI, RemoteRefUpdate update, Map<String, GitBranch> remoteBranches, Map<String, String> remoteTags);