use of org.eclipse.jgit.api.FetchCommand in project che by eclipse.
the class JGitConnection method fetch.
@Override
public void fetch(FetchParams params) throws GitException, UnauthorizedException {
String remoteName = params.getRemote();
String remoteUri;
try {
List<RefSpec> fetchRefSpecs;
List<String> refSpec = params.getRefSpec();
if (!refSpec.isEmpty()) {
fetchRefSpecs = new ArrayList<>(refSpec.size());
for (String refSpecItem : refSpec) {
RefSpec fetchRefSpec = //
(refSpecItem.indexOf(':') < 0) ? //
new RefSpec(Constants.R_HEADS + refSpecItem + ":") : new RefSpec(refSpecItem);
fetchRefSpecs.add(fetchRefSpec);
}
} else {
fetchRefSpecs = Collections.emptyList();
}
FetchCommand fetchCommand = getGit().fetch();
// (otherwise JGit fails)
if (remoteName != null && refSpec.isEmpty()) {
boolean found = false;
List<Remote> configRemotes = remoteList(null, false);
for (Remote configRemote : configRemotes) {
if (remoteName.equals(configRemote.getName())) {
found = true;
break;
}
}
if (!found) {
fetchRefSpecs = Collections.singletonList(new RefSpec(Constants.HEAD + ":" + Constants.FETCH_HEAD));
}
}
if (remoteName == null) {
remoteName = Constants.DEFAULT_REMOTE_NAME;
}
fetchCommand.setRemote(remoteName);
remoteUri = getRepository().getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName, ConfigConstants.CONFIG_KEY_URL);
fetchCommand.setRefSpecs(fetchRefSpecs);
int timeout = params.getTimeout();
if (timeout > 0) {
fetchCommand.setTimeout(timeout);
}
fetchCommand.setRemoveDeletedRefs(params.isRemoveDeletedRefs());
executeRemoteCommand(remoteUri, fetchCommand, params.getUsername(), params.getPassword());
} catch (GitException | GitAPIException exception) {
String errorMessage;
if (exception.getMessage().contains("Invalid remote: ")) {
errorMessage = ERROR_NO_REMOTE_REPOSITORY;
} else if ("Nothing to fetch.".equals(exception.getMessage())) {
return;
} else {
errorMessage = generateExceptionMessage(exception);
}
throw new GitException(errorMessage, exception);
}
}
use of org.eclipse.jgit.api.FetchCommand in project che by eclipse.
the class JGitConnection method pull.
@Override
public PullResponse pull(PullParams params) throws GitException, UnauthorizedException {
String remoteName = params.getRemote();
String remoteUri;
try {
if (repository.getRepositoryState().equals(RepositoryState.MERGING)) {
throw new GitException(ERROR_PULL_MERGING);
}
String fullBranch = repository.getFullBranch();
if (!fullBranch.startsWith(Constants.R_HEADS)) {
throw new DetachedHeadException(ERROR_PULL_HEAD_DETACHED);
}
String branch = fullBranch.substring(Constants.R_HEADS.length());
StoredConfig config = repository.getConfig();
if (remoteName == null) {
remoteName = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_REMOTE);
if (remoteName == null) {
remoteName = Constants.DEFAULT_REMOTE_NAME;
}
}
remoteUri = config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName, ConfigConstants.CONFIG_KEY_URL);
String remoteBranch;
RefSpec fetchRefSpecs = null;
String refSpec = params.getRefSpec();
if (refSpec != null) {
fetchRefSpecs = //
(refSpec.indexOf(':') < 0) ? //
new RefSpec(Constants.R_HEADS + refSpec + ":" + fullBranch) : new RefSpec(refSpec);
remoteBranch = fetchRefSpecs.getSource();
} else {
remoteBranch = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_MERGE);
}
if (remoteBranch == null) {
remoteBranch = fullBranch;
}
FetchCommand fetchCommand = getGit().fetch();
fetchCommand.setRemote(remoteName);
if (fetchRefSpecs != null) {
fetchCommand.setRefSpecs(fetchRefSpecs);
}
int timeout = params.getTimeout();
if (timeout > 0) {
fetchCommand.setTimeout(timeout);
}
FetchResult fetchResult = (FetchResult) executeRemoteCommand(remoteUri, fetchCommand, params.getUsername(), params.getPassword());
Ref remoteBranchRef = fetchResult.getAdvertisedRef(remoteBranch);
if (remoteBranchRef == null) {
remoteBranchRef = fetchResult.getAdvertisedRef(Constants.R_HEADS + remoteBranch);
}
if (remoteBranchRef == null) {
throw new GitException(format(ERROR_PULL_REF_MISSING, remoteBranch));
}
org.eclipse.jgit.api.MergeResult mergeResult = getGit().merge().include(remoteBranchRef).call();
if (mergeResult.getMergeStatus().equals(org.eclipse.jgit.api.MergeResult.MergeStatus.ALREADY_UP_TO_DATE)) {
return newDto(PullResponse.class).withCommandOutput("Already up-to-date");
}
if (mergeResult.getConflicts() != null) {
StringBuilder message = new StringBuilder(ERROR_PULL_MERGE_CONFLICT_IN_FILES);
message.append(lineSeparator());
Map<String, int[][]> allConflicts = mergeResult.getConflicts();
for (String path : allConflicts.keySet()) {
message.append(path).append(lineSeparator());
}
message.append(ERROR_PULL_AUTO_MERGE_FAILED);
throw new GitException(message.toString());
}
} catch (CheckoutConflictException exception) {
StringBuilder message = new StringBuilder(ERROR_CHECKOUT_CONFLICT);
message.append(lineSeparator());
for (String path : exception.getConflictingPaths()) {
message.append(path).append(lineSeparator());
}
message.append(ERROR_PULL_COMMIT_BEFORE_MERGE);
throw new GitException(message.toString(), exception);
} catch (IOException | GitAPIException exception) {
String errorMessage;
if (exception.getMessage().equals("Invalid remote: " + remoteName)) {
errorMessage = ERROR_NO_REMOTE_REPOSITORY;
} else {
errorMessage = generateExceptionMessage(exception);
}
throw new GitException(errorMessage, exception);
}
return newDto(PullResponse.class).withCommandOutput("Successfully pulled from " + remoteUri);
}
use of org.eclipse.jgit.api.FetchCommand in project blueocean-plugin by jenkinsci.
the class GitCacheCloneReadSaveRequest method getActiveRepository.
@Nonnull
private Git getActiveRepository(Repository repository) throws IOException {
try {
// Clone the bare repository
File cloneDir = File.createTempFile("clone", "");
if (cloneDir.exists()) {
if (cloneDir.isDirectory()) {
FileUtils.deleteDirectory(cloneDir);
} else {
if (!cloneDir.delete()) {
throw new ServiceException.UnexpectedErrorException("Unable to delete repository clone");
}
}
}
if (!cloneDir.mkdirs()) {
throw new ServiceException.UnexpectedErrorException("Unable to create repository clone directory");
}
String url = repository.getConfig().getString("remote", "origin", "url");
Git gitClient = Git.cloneRepository().setCloneAllBranches(false).setProgressMonitor(new CloneProgressMonitor(url)).setURI(repository.getDirectory().getCanonicalPath()).setDirectory(cloneDir).call();
RemoteRemoveCommand remove = gitClient.remoteRemove();
remove.setName("origin");
remove.call();
RemoteAddCommand add = gitClient.remoteAdd();
add.setName("origin");
add.setUri(new URIish(gitSource.getRemote()));
add.call();
if (GitUtils.isSshUrl(gitSource.getRemote())) {
// Get committer info and credentials
User user = User.current();
if (user == null) {
throw new ServiceException.UnauthorizedException("Not authenticated");
}
BasicSSHUserPrivateKey privateKey = UserSSHKeyManager.getOrCreate(user);
// Make sure up-to-date and credentials work
GitUtils.fetch(repository, privateKey);
} else {
FetchCommand fetch = gitClient.fetch();
fetch.call();
}
if (!StringUtils.isEmpty(sourceBranch) && !sourceBranch.equals(branch)) {
CheckoutCommand checkout = gitClient.checkout();
checkout.setStartPoint("origin/" + sourceBranch);
checkout.setName(sourceBranch);
// to create a new local branch
checkout.setCreateBranch(true);
checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
checkout.call();
checkout = gitClient.checkout();
checkout.setName(branch);
// this *should* be a new branch
checkout.setCreateBranch(true);
checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
checkout.call();
} else {
CheckoutCommand checkout = gitClient.checkout();
checkout.setStartPoint("origin/" + branch);
checkout.setName(branch);
// to create a new local branch
checkout.setCreateBranch(true);
checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
checkout.call();
}
return gitClient;
} catch (GitAPIException | URISyntaxException ex) {
throw new ServiceException.UnexpectedErrorException("Unable to get working repository directory", ex);
}
}
use of org.eclipse.jgit.api.FetchCommand in project archi-modelrepository-plugin by archi-contribs.
the class ArchiRepository method fetchFromRemote.
@Override
public FetchResult fetchFromRemote(String userName, String userPassword, ProgressMonitor monitor, boolean isDryrun) throws IOException, GitAPIException {
try (Git git = Git.open(getLocalRepositoryFolder())) {
// Check and set tracked master branch
setTrackedMasterBranch(git);
FetchCommand fetchCommand = git.fetch();
fetchCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, userPassword));
fetchCommand.setProgressMonitor(monitor);
fetchCommand.setDryRun(isDryrun);
return fetchCommand.call();
}
}
use of org.eclipse.jgit.api.FetchCommand in project spring-cloud-config by spring-cloud.
the class JGitEnvironmentRepositoryTests method shouldSetRemoveBranchesFlagToFetchCommand.
@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();
}
Aggregations