List of usage examples for org.eclipse.jgit.api FetchCommand setRefSpecs
public FetchCommand setRefSpecs(List<RefSpec> specs)
From source file:com.gitblit.manager.GitblitManager.java
License:Apache License
/** * Creates a personal fork of the specified repository. The clone is view * restricted by default and the owner of the source repository is given * access to the clone./*from ww w .j a v a2s . c om*/ * * @param repository * @param user * @return the repository model of the fork, if successful * @throws GitBlitException */ @Override public RepositoryModel fork(RepositoryModel repository, UserModel user) throws GitBlitException { String cloneName = MessageFormat.format("{0}/{1}.git", user.getPersonalPath(), StringUtils.stripDotGit(StringUtils.getLastPathElement(repository.name))); String fromUrl = MessageFormat.format("file://{0}/{1}", repositoryManager.getRepositoriesFolder().getAbsolutePath(), repository.name); // clone the repository try { Repository canonical = getRepository(repository.name); File folder = new File(repositoryManager.getRepositoriesFolder(), cloneName); CloneCommand clone = new CloneCommand(); clone.setBare(true); // fetch branches with exclusions Collection<Ref> branches = canonical.getRefDatabase().getRefs(Constants.R_HEADS).values(); List<String> branchesToClone = new ArrayList<String>(); for (Ref branch : branches) { String name = branch.getName(); if (name.startsWith(Constants.R_TICKET)) { // exclude ticket branches continue; } branchesToClone.add(name); } clone.setBranchesToClone(branchesToClone); clone.setURI(fromUrl); clone.setDirectory(folder); Git git = clone.call(); // fetch tags FetchCommand fetch = git.fetch(); fetch.setRefSpecs(new RefSpec("+refs/tags/*:refs/tags/*")); fetch.call(); git.getRepository().close(); } catch (Exception e) { throw new GitBlitException(e); } // create a Gitblit repository model for the clone RepositoryModel cloneModel = repository.cloneAs(cloneName); // owner has REWIND/RW+ permissions cloneModel.addOwner(user.username); // ensure initial access restriction of the fork // is not lower than the source repository (issue-495/ticket-167) if (repository.accessRestriction.exceeds(cloneModel.accessRestriction)) { cloneModel.accessRestriction = repository.accessRestriction; } repositoryManager.updateRepositoryModel(cloneName, cloneModel, false); // add the owner of the source repository to the clone's access list if (!ArrayUtils.isEmpty(repository.owners)) { for (String owner : repository.owners) { UserModel originOwner = userManager.getUserModel(owner); if (originOwner != null && !originOwner.canClone(cloneModel)) { // origin owner can't yet clone fork, grant explicit clone access originOwner.setRepositoryPermission(cloneName, AccessPermission.CLONE); reviseUser(originOwner.username, originOwner); } } } // grant origin's user list clone permission to fork List<String> users = repositoryManager.getRepositoryUsers(repository); List<UserModel> cloneUsers = new ArrayList<UserModel>(); for (String name : users) { if (!name.equalsIgnoreCase(user.username)) { UserModel cloneUser = userManager.getUserModel(name); if (cloneUser.canClone(repository) && !cloneUser.canClone(cloneModel)) { // origin user can't yet clone fork, grant explicit clone access cloneUser.setRepositoryPermission(cloneName, AccessPermission.CLONE); } cloneUsers.add(cloneUser); } } userManager.updateUserModels(cloneUsers); // grant origin's team list clone permission to fork List<String> teams = repositoryManager.getRepositoryTeams(repository); List<TeamModel> cloneTeams = new ArrayList<TeamModel>(); for (String name : teams) { TeamModel cloneTeam = userManager.getTeamModel(name); if (cloneTeam.canClone(repository) && !cloneTeam.canClone(cloneModel)) { // origin team can't yet clone fork, grant explicit clone access cloneTeam.setRepositoryPermission(cloneName, AccessPermission.CLONE); } cloneTeams.add(cloneTeam); } userManager.updateTeamModels(cloneTeams); // add this clone to the cached model repositoryManager.addToCachedRepositoryList(cloneModel); if (pluginManager != null) { for (RepositoryLifeCycleListener listener : pluginManager .getExtensions(RepositoryLifeCycleListener.class)) { try { listener.onFork(repository, cloneModel); } catch (Throwable t) { logger.error(String.format("failed to call plugin onFork %s", repository.name), t); } } } return cloneModel; }
From source file:com.gitblit.utils.JGitUtils.java
License:Apache License
/** * Fetch updates from the remote repository. If refSpecs is unspecifed, * remote heads, tags, and notes are retrieved. * * @param credentialsProvider/*ww w. ja v a 2 s . com*/ * @param repository * @param refSpecs * @return FetchResult * @throws Exception */ public static FetchResult fetchRepository(CredentialsProvider credentialsProvider, Repository repository, RefSpec... refSpecs) throws Exception { Git git = new Git(repository); FetchCommand fetch = git.fetch(); List<RefSpec> specs = new ArrayList<RefSpec>(); if (refSpecs == null || refSpecs.length == 0) { specs.add(new RefSpec("+refs/heads/*:refs/remotes/origin/*")); specs.add(new RefSpec("+refs/tags/*:refs/tags/*")); specs.add(new RefSpec("+refs/notes/*:refs/notes/*")); } else { specs.addAll(Arrays.asList(refSpecs)); } if (credentialsProvider != null) { fetch.setCredentialsProvider(credentialsProvider); } fetch.setRefSpecs(specs); FetchResult fetchRes = fetch.call(); return fetchRes; }
From source file:com.google.gerrit.acceptance.GitUtil.java
License:Apache License
public static void fetch(TestRepository<?> testRepo, String spec) throws GitAPIException { FetchCommand fetch = testRepo.git().fetch(); fetch.setRefSpecs(new RefSpec(spec)); fetch.call();//from w w w.ja v a2 s.c o m }
From source file:com.googlesource.gerrit.plugins.github.git.PullRequestImportJob.java
License:Apache License
private void fetchGitHubPullRequest(Repository gitRepo, GHPullRequest pr) throws GitAPIException, InvalidRemoteException, TransportException { status.update(Code.SYNC, "Fetching", "Fetching PullRequests from GitHub"); Git git = Git.wrap(gitRepo);/* ww w. jav a 2 s . c o m*/ FetchCommand fetch = git.fetch(); fetch.setRemote(ghRepository.getCloneUrl()); fetch.setRefSpecs( new RefSpec("+refs/pull/" + pr.getNumber() + "/head:refs/remotes/origin/pr/" + pr.getNumber())); fetch.setProgressMonitor(this); fetch.call(); }
From source file:com.maiereni.synchronizer.git.utils.GitDownloaderImpl.java
License:Apache License
private List<Change> update(final Git git, final GitProperties properties, final Ref localBranch, final Ref tagRef) throws Exception { logger.debug("Fetch from remote"); List<Change> ret = null; FetchCommand cmd = git.fetch(); if (StringUtils.isNotBlank(properties.getUserName()) && StringUtils.isNotBlank(properties.getPassword())) { logger.debug("Set credentials"); cmd.setCredentialsProvider(/*from w w w .j a va 2s .c om*/ new UsernamePasswordCredentialsProvider(properties.getUserName(), properties.getPassword())); } if (tagRef != null) { RefSpec spec = new RefSpec().setSourceDestination(localBranch.getName(), tagRef.getName()); List<RefSpec> specs = new ArrayList<RefSpec>(); specs.add(spec); cmd.setRefSpecs(specs); } FetchResult fr = cmd.call(); Collection<Ref> refs = fr.getAdvertisedRefs(); for (Ref ref : refs) { if (ref.getName().equals("HEAD")) { ret = checkDifferences(git, localBranch, ref); logger.debug("Rebase on HEAD"); RebaseResult rebaseResult = git.rebase().setUpstream(ref.getObjectId()).call(); if (rebaseResult.getStatus().isSuccessful()) { } } } return ret; }
From source file:com.surevine.gateway.scm.git.jgit.JGitGitFacade.java
License:Open Source License
@Override public boolean fetch(final LocalRepoBean repoBean, final String remoteName) throws GitException { String remoteToPull = (remoteName != null) ? remoteName : "origin"; FetchResult result;// w w w . ja v a 2 s . c o m try { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(repoBean.getGitConfigDirectory().toFile()).findGitDir() .build(); Git git = new org.eclipse.jgit.api.Git(repository); FetchCommand fetchCommand = git.fetch(); fetchCommand.setRemote(remoteToPull); fetchCommand.setRefSpecs(new RefSpec("+refs/heads/*:refs/heads/*")); result = fetchCommand.call(); repository.close(); } catch (GitAPIException | IOException e) { LOGGER.error(e); throw new GitException(e); } boolean hadUpdates = !result.getTrackingRefUpdates().isEmpty(); return hadUpdates; }
From source file:com.verigreen.jgit.JGitOperator.java
License:Apache License
@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;//from w w w. j av a2s .c om try { result = command.call(); } catch (Throwable e) { throw new RuntimeException( String.format("Failed to fetch from [%s] to [%s]", remoteBranchName, localBranchName), e); } return result.getMessages(); }
From source file:net.erdfelt.android.sdkfido.git.internal.InternalGit.java
License:Apache License
@Override public void pullRemote() throws GitException { try {// w ww. j a v a 2 s .c om Git git = new Git(repo); FetchCommand fetch = git.fetch(); fetch.setCheckFetchedObjects(false); fetch.setRemoveDeletedRefs(true); List<RefSpec> specs = new ArrayList<RefSpec>(); fetch.setRefSpecs(specs); fetch.setTimeout(5000); fetch.setDryRun(false); fetch.setRemote(IGit.REMOTE_NAME); fetch.setThin(Transport.DEFAULT_FETCH_THIN); fetch.setProgressMonitor(getProgressMonitor()); FetchResult result = fetch.call(); if (result.getTrackingRefUpdates().isEmpty()) { return; } GitInfo.infoFetchResults(repo, result); } catch (Throwable t) { throw new GitException(t.getMessage(), t); } }
From source file:org.ajoberstar.gradle.git.tasks.GitFetch.java
License:Apache License
/** * Fetches remote changes into a local Git repository. *//*from w w w . ja va 2 s. c om*/ @TaskAction public void fetch() { FetchCommand cmd = getGit().fetch(); TransportAuthUtil.configure(cmd, this); cmd.setTagOpt(getTagOpt()); cmd.setCheckFetchedObjects(getCheckFetchedObjects()); cmd.setDryRun(getDryRun()); cmd.setRefSpecs(getRefspecs()); cmd.setRemote(getRemote()); cmd.setRemoveDeletedRefs(getRemoveDeletedRefs()); cmd.setThin(getThin()); try { cmd.call(); } catch (InvalidRemoteException e) { throw new GradleException("Invalid remote specified: " + getRemote(), e); } catch (TransportException e) { throw new GradleException("Problem with transport.", e); } catch (GitAPIException e) { throw new GradleException("Problem with fetch.", e); } //TODO add progress monitor to log progress to Gradle status bar }
From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java
License:Open Source License
@Override public void fetch(FetchRequest request) throws GitException, UnauthorizedException { String remoteName = request.getRemote(); String remoteUri;//from w w w . j av a 2s . c o m try { List<RefSpec> fetchRefSpecs; List<String> refSpec = request.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(); // If this an unknown remote with no refspecs given, put HEAD // (otherwise JGit fails) if (remoteName != null && refSpec.isEmpty()) { boolean found = false; List<Remote> configRemotes = remoteList(newDto(RemoteListRequest.class)); 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 = request.getTimeout(); if (timeout > 0) { fetchCommand.setTimeout(timeout); } fetchCommand.setRemoveDeletedRefs(request.isRemoveDeletedRefs()); executeRemoteCommand(remoteUri, fetchCommand); } 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 = exception.getMessage(); } throw new GitException(errorMessage, exception); } }