下面列出了怎么用org.eclipse.jgit.transport.FetchResult的API类实例代码及写法,或者点击链接到github查看源代码。
private List<TrackingRefUpdate> fetch(Repository repository) throws Exception {
this.logger.info("Fetching changes of repository " + repository.getDirectory().toString());
try (Git git = new Git(repository)) {
FetchResult result = git.fetch().call();
Collection<TrackingRefUpdate> updates = result.getTrackingRefUpdates();
List<TrackingRefUpdate> remoteRefsChanges = new ArrayList<TrackingRefUpdate>();
for (TrackingRefUpdate update : updates) {
String refName = update.getLocalName();
if (refName.startsWith(REMOTE_REFS_PREFIX)) {
ObjectId newObjectId = update.getNewObjectId();
this.logger.info(refName +" is now at " + newObjectId.getName());
remoteRefsChanges.add(update);
}
}
if (updates.isEmpty()) {
this.logger.info("Nothing changed");
}
return remoteRefsChanges;
}
}
static IStatus handleFetchResult(FetchResult fetchResult) {
// handle result
for (TrackingRefUpdate updateRes : fetchResult.getTrackingRefUpdates()) {
Result res = updateRes.getResult();
switch (res) {
case NOT_ATTEMPTED:
case NO_CHANGE:
case NEW:
case FORCED:
case FAST_FORWARD:
case RENAMED:
// do nothing, as these statuses are OK
break;
case REJECTED:
return new Status(IStatus.WARNING, GitActivator.PI_GIT, "Fetch rejected, not a fast-forward.");
case REJECTED_CURRENT_BRANCH:
return new Status(IStatus.WARNING, GitActivator.PI_GIT, "Rejected because trying to delete the current branch.");
default:
return new Status(IStatus.ERROR, GitActivator.PI_GIT, res.name());
}
}
return Status.OK_STATUS;
}
private List<TrackingRefUpdate> fetch(Repository repository) throws Exception {
logger.info("Fetching changes of repository {}", repository.getDirectory().toString());
try (Git git = new Git(repository)) {
FetchResult result = git.fetch().call();
Collection<TrackingRefUpdate> updates = result.getTrackingRefUpdates();
List<TrackingRefUpdate> remoteRefsChanges = new ArrayList<TrackingRefUpdate>();
for (TrackingRefUpdate update : updates) {
String refName = update.getLocalName();
if (refName.startsWith(REMOTE_REFS_PREFIX)) {
ObjectId newObjectId = update.getNewObjectId();
logger.info("{} is now at {}", refName, newObjectId.getName());
remoteRefsChanges.add(update);
}
}
if (updates.isEmpty()) {
logger.info("Nothing changed");
}
return remoteRefsChanges;
}
}
@Override
public String fetch(String localBranchName, String remoteBranchName) {
RefSpec spec = new RefSpec().setSourceDestination(localBranchName, remoteBranchName);
FetchCommand command = _git.fetch();
command.setRefSpecs(spec);
FetchResult result = null;
try {
if(_cp != null)
command.setCredentialsProvider(_cp);
result = command.call();
} catch (Throwable e) {
throw new RuntimeException(String.format(
"Failed to fetch from [%s] to [%s]",
remoteBranchName,
localBranchName), e);
}
return result.getMessages();
}
@Test
public void shouldSetTransportConfigCallbackOnCloneAndFetch() throws Exception {
Git mockGit = mock(Git.class);
FetchCommand fetchCommand = mock(FetchCommand.class);
when(mockGit.fetch()).thenReturn(fetchCommand);
when(fetchCommand.call()).thenReturn(mock(FetchResult.class));
CloneCommand mockCloneCommand = mock(CloneCommand.class);
when(mockCloneCommand.setURI(anyString())).thenReturn(mockCloneCommand);
when(mockCloneCommand.setDirectory(any(File.class))).thenReturn(mockCloneCommand);
TransportConfigCallback configCallback = mock(TransportConfigCallback.class);
JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(
this.environment, new JGitEnvironmentProperties());
envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand));
envRepository.setUri("http://somegitserver/somegitrepo");
envRepository.setTransportConfigCallback(configCallback);
envRepository.setCloneOnStart(true);
envRepository.afterPropertiesSet();
verify(mockCloneCommand, times(1)).setTransportConfigCallback(configCallback);
envRepository.fetch(mockGit, "master");
verify(fetchCommand, times(1)).setTransportConfigCallback(configCallback);
}
@Test
public void shouldSetRemoveBranchesFlagToFetchCommand() throws Exception {
Git mockGit = mock(Git.class);
FetchCommand fetchCommand = mock(FetchCommand.class);
when(mockGit.fetch()).thenReturn(fetchCommand);
when(fetchCommand.call()).thenReturn(mock(FetchResult.class));
JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(
this.environment, new JGitEnvironmentProperties());
envRepository
.setGitFactory(new MockGitFactory(mockGit, mock(CloneCommand.class)));
envRepository.setUri("http://somegitserver/somegitrepo");
envRepository.setDeleteUntrackedBranches(true);
envRepository.fetch(mockGit, "master");
verify(fetchCommand, times(1)).setRemoveDeletedRefs(true);
verify(fetchCommand, times(1)).call();
}
private void updateBranch(Git git, ClusterMember remoteNode) throws CryptoException, GitAPIException,
IOException, ServiceLayerException {
final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
FetchCommand fetchCommand = git.fetch().setRemote(remoteNode.getGitRemoteName());
fetchCommand = configureAuthenticationForCommand(remoteNode, fetchCommand, tempKey);
FetchResult fetchResult = fetchCommand.call();
ObjectId commitToMerge;
Ref r;
if (fetchResult != null) {
r = fetchResult.getAdvertisedRef(Constants.MASTER);
if (r == null) {
r = fetchResult.getAdvertisedRef(Constants.R_HEADS + Constants.MASTER);
}
if (r != null) {
commitToMerge = r.getObjectId();
MergeCommand mergeCommand = git.merge();
mergeCommand.setMessage(studioConfiguration.getProperty(REPO_SYNC_DB_COMMIT_MESSAGE_NO_PROCESSING));
mergeCommand.setCommit(true);
mergeCommand.include(remoteNode.getGitRemoteName(), commitToMerge);
mergeCommand.setStrategy(MergeStrategy.THEIRS);
mergeCommand.call();
}
}
Files.delete(tempKey);
}
@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);
}
}
private FetchResult fetch(File projectDir) throws GitAPIException {
Git git = this.gitFactory.open(projectDir);
FetchCommand command = git.fetch();
try {
return command.call();
}
catch (GitAPIException e) {
deleteBaseDirIfExists();
throw e;
}
finally {
git.close();
}
}
@Override
public FetchResult call()
throws GitAPIException, InvalidRemoteException, TransportException {
try {
Thread.sleep(250);
}
catch (InterruptedException e) {
e.printStackTrace();
}
return super.call();
}
@Test
public void shouldUpdateLastRefresh() throws Exception {
Git git = mock(Git.class);
StatusCommand statusCommand = mock(StatusCommand.class);
Status status = mock(Status.class);
Repository repository = mock(Repository.class);
StoredConfig storedConfig = mock(StoredConfig.class);
FetchCommand fetchCommand = mock(FetchCommand.class);
FetchResult fetchResult = mock(FetchResult.class);
when(git.status()).thenReturn(statusCommand);
when(git.getRepository()).thenReturn(repository);
when(fetchCommand.call()).thenReturn(fetchResult);
when(git.fetch()).thenReturn(fetchCommand);
when(repository.getConfig()).thenReturn(storedConfig);
when(storedConfig.getString("remote", "origin", "url"))
.thenReturn("http://example/git");
when(statusCommand.call()).thenReturn(status);
when(status.isClean()).thenReturn(true);
JGitEnvironmentProperties properties = new JGitEnvironmentProperties();
properties.setRefreshRate(1000);
JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment,
properties);
repo.setLastRefresh(0);
repo.fetch(git, "master");
long timeDiff = System.currentTimeMillis() - repo.getLastRefresh();
assertThat(timeDiff < 1000L)
.as("time difference (" + timeDiff + ") was longer than 1 second")
.isTrue();
}
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");
}
private void updateBranch(Git git, ClusterMember remoteNode) throws CryptoException, GitAPIException,
IOException, ServiceLayerException {
final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
FetchCommand fetchCommand = git.fetch().setRemote(remoteNode.getGitRemoteName());
fetchCommand = configureAuthenticationForCommand(remoteNode, fetchCommand, tempKey);
FetchResult fetchResult = fetchCommand.call();
ObjectId commitToMerge;
Ref r;
if (fetchResult != null) {
r = fetchResult.getAdvertisedRef(REPO_SANDBOX_BRANCH);
if (r == null) {
r = fetchResult.getAdvertisedRef(Constants.R_HEADS +
studioConfiguration.getProperty(REPO_SANDBOX_BRANCH));
}
if (r != null) {
commitToMerge = r.getObjectId();
MergeCommand mergeCommand = git.merge();
mergeCommand.setMessage(studioConfiguration.getProperty(REPO_SYNC_DB_COMMIT_MESSAGE_NO_PROCESSING));
mergeCommand.setCommit(true);
mergeCommand.include(remoteNode.getGitRemoteName(), commitToMerge);
mergeCommand.setStrategy(MergeStrategy.THEIRS);
MergeResult result = mergeCommand.call();
if (result.getMergeStatus().isSuccessful()) {
deploymentService.syncAllContentToPreview(siteId, true);
}
}
}
Files.delete(tempKey);
}
public FetchResult getResult () {
return result;
}
private IStatus doFetch(IProgressMonitor monitor) throws IOException, CoreException, URISyntaxException, GitAPIException {
ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
Repository db = null;
try {
db = getRepository();
Git git = Git.wrap(db);
FetchCommand fc = git.fetch();
fc.setProgressMonitor(gitMonitor);
RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
credentials.setUri(remoteConfig.getURIs().get(0));
if (this.cookie != null) {
fc.setTransportConfigCallback(new TransportConfigCallback() {
@Override
public void configure(Transport t) {
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);
}
}
});
}
fc.setCredentialsProvider(credentials);
fc.setRemote(remote);
if (branch != null) {
// refs/heads/{branch}:refs/remotes/{remote}/{branch}
String remoteBranch = branch;
if (branch.startsWith("for/")) {
remoteBranch = branch.substring(4);
}
RefSpec spec = new RefSpec(Constants.R_HEADS + remoteBranch + ":" + Constants.R_REMOTES + remote + "/" + branch); //$NON-NLS-1$ //$NON-NLS-2$
spec = spec.setForceUpdate(force);
fc.setRefSpecs(spec);
}
FetchResult fetchResult = fc.call();
if (monitor.isCanceled()) {
return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
}
GitJobUtils.packRefs(db, gitMonitor);
if (monitor.isCanceled()) {
return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
}
return handleFetchResult(fetchResult);
} finally {
if (db != null) {
db.close();
}
}
}
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;
}
@Test
public void testRefreshWithoutFetch() throws Exception {
Git git = mock(Git.class);
CloneCommand cloneCommand = mock(CloneCommand.class);
when(cloneCommand.setURI(anyString())).thenReturn(cloneCommand);
when(cloneCommand.setDirectory(any(File.class))).thenReturn(cloneCommand);
when(cloneCommand.call()).thenReturn(git);
MockGitFactory factory = new MockGitFactory(git, cloneCommand);
StatusCommand statusCommand = mock(StatusCommand.class);
CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
Status status = mock(Status.class);
Repository repository = mock(Repository.class, Mockito.RETURNS_DEEP_STUBS);
StoredConfig storedConfig = mock(StoredConfig.class);
Ref ref = mock(Ref.class);
ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
FetchCommand fetchCommand = mock(FetchCommand.class);
FetchResult fetchResult = mock(FetchResult.class);
Ref branch1Ref = mock(Ref.class);
when(git.branchList()).thenReturn(listBranchCommand);
when(git.status()).thenReturn(statusCommand);
when(git.getRepository()).thenReturn(repository);
when(git.checkout()).thenReturn(checkoutCommand);
when(git.fetch()).thenReturn(fetchCommand);
when(git.merge())
.thenReturn(mock(MergeCommand.class, Mockito.RETURNS_DEEP_STUBS));
when(repository.getConfig()).thenReturn(storedConfig);
when(storedConfig.getString("remote", "origin", "url"))
.thenReturn("http://example/git");
when(statusCommand.call()).thenReturn(status);
when(checkoutCommand.call()).thenReturn(ref);
when(listBranchCommand.call()).thenReturn(Arrays.asList(branch1Ref));
when(fetchCommand.call()).thenReturn(fetchResult);
when(branch1Ref.getName()).thenReturn("origin/master");
when(status.isClean()).thenReturn(true);
JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment,
new JGitEnvironmentProperties());
repo.setGitFactory(factory);
repo.setUri("http://somegitserver/somegitrepo");
repo.setBasedir(this.basedir);
// Set the refresh rate to 2 seconds and last update before 100ms. There should be
// no remote repo fetch.
repo.setLastRefresh(System.currentTimeMillis() - 100);
repo.setRefreshRate(2);
repo.refresh("master");
// Verify no fetch but merge only.
verify(git, times(0)).fetch();
verify(git).merge();
}
@Override
public void execute(Wandora wandora, Context context) {
try {
Git git = getGit();
if(git != null) {
if(isNotEmpty(getGitRemoteUrl())) {
PullCommand pull = git.pull();
String user = getUsername();
if(user == null) {
if(pullUI == null) {
pullUI = new PullUI();
}
pullUI.setUsername(getUsername());
pullUI.setPassword(getPassword());
pullUI.setRemoteUrl(getGitRemoteUrl());
pullUI.openInDialog();
if(pullUI.wasAccepted()) {
setUsername(pullUI.getUsername());
setPassword(pullUI.getPassword());
// setGitRemoteUrl(pullUI.getRemoteUrl());
// pull.setRemote(pullUI.getRemoteUrl());
if(isNotEmpty(getUsername())) {
CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider( getUsername(), getPassword() );
pull.setCredentialsProvider(credentialsProvider);
}
}
else {
return;
}
}
setDefaultLogger();
setLogTitle("Git pull");
log("Pulling changes from remote repository...");
PullResult result = pull.call();
FetchResult fetchResult = result.getFetchResult();
MergeResult mergeResult = result.getMergeResult();
MergeStatus mergeStatus = mergeResult.getMergeStatus();
String fetchResultMessages = fetchResult.getMessages();
if(isNotEmpty(fetchResultMessages)) {
log(fetchResult.getMessages());
}
log(mergeStatus.toString());
if(mergeStatus.equals(MergeStatus.MERGED)) {
int a = WandoraOptionPane.showConfirmDialog(wandora, "Reload Wandora project after pull?", "Reload Wandora project after pull?", WandoraOptionPane.YES_NO_OPTION);
if(a == WandoraOptionPane.YES_OPTION) {
reloadWandoraProject();
}
}
log("Ready.");
}
else {
log("Repository has no remote origin and can't be pulled. "
+ "Initialize repository by cloning remote repository to set the remote origin.");
}
}
else {
logAboutMissingGitRepository();
}
}
catch(GitAPIException gae) {
log(gae.toString());
}
catch(NoWorkTreeException nwte) {
log(nwte.toString());
}
catch(Exception e) {
log(e);
}
setState(WAIT);
}
private void updatePublishedBranch(Git git, ClusterMember remoteNode, String branch) throws CryptoException,
GitAPIException, IOException, ServiceLayerException {
logger.debug("Update published environment " + branch + " from " + remoteNode.getLocalAddress() +
" for site " + siteId);
final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
Repository repo = git.getRepository();
Ref ref = repo.exactRef(Constants.R_HEADS + branch);
boolean createBranch = (ref == null);
logger.debug("Checkout " + branch);
CheckoutCommand checkoutCommand = git.checkout()
.setName(branch)
.setCreateBranch(createBranch);
if (createBranch) {
checkoutCommand.setStartPoint(remoteNode.getGitRemoteName() + "/" + branch);
}
checkoutCommand.call();
FetchCommand fetchCommand = git.fetch().setRemote(remoteNode.getGitRemoteName());
fetchCommand = configureAuthenticationForCommand(remoteNode, fetchCommand, tempKey);
FetchResult fetchResult = fetchCommand.call();
ObjectId commitToMerge;
Ref r;
if (fetchResult != null) {
r = fetchResult.getAdvertisedRef(branch);
if (r == null) {
r = fetchResult.getAdvertisedRef(Constants.R_HEADS + branch);
}
if (r != null) {
commitToMerge = r.getObjectId();
MergeCommand mergeCommand = git.merge();
mergeCommand.setMessage(studioConfiguration.getProperty(REPO_SYNC_DB_COMMIT_MESSAGE_NO_PROCESSING));
mergeCommand.setCommit(true);
mergeCommand.include(remoteNode.getGitRemoteName(), commitToMerge);
mergeCommand.setStrategy(MergeStrategy.THEIRS);
mergeCommand.call();
}
}
Files.delete(tempKey);
}