类org.eclipse.jgit.transport.RefSpec源码实例Demo

下面列出了怎么用org.eclipse.jgit.transport.RefSpec的API类实例代码及写法,或者点击链接到github查看源代码。

public boolean cloneTheRepo(String branch) {
    CloneCommand clone = git.clone_();
    ArrayList<RefSpec> refSpecs = new ArrayList<>();
    clone.url(url);

    if (branch != null && !branch.equals("")) {
        refSpecs.add(new RefSpec()
                .setSourceDestination("+refs/heads/" + branch, "refs/remotes/origin/" + branch));
        clone.refspecs(refSpecs);
    }

    try {
        clone.execute();
    } catch (InterruptedException e) {
        listener.getLogger().println("Error while cloning branch " + branch + "from " + url);
        listener.getLogger().println(e.getMessage());
        return false;
    }

    listener.getLogger().println("Cloned branch " + branch + " successfully from " + url + ".");
    return checkout(branch);
}
 
源代码2 项目: netbeans   文件: PullCommand.java
private String findRemoteBranchName () throws GitException {
    Ref ref = null;
    try {
        ref = getRepository().findRef(branchToMerge);
    } catch (IOException ex) {
        throw new GitException(ex);
    }
    if (ref != null) {
        for (String s : refSpecs) {
            RefSpec spec = new RefSpec(s);
            if (spec.matchDestination(ref)) {
                spec = spec.expandFromDestination(ref);
                String refName = spec.getSource();
                if (refName.startsWith(Constants.R_HEADS)) {
                    return refName.substring(Constants.R_HEADS.length());
                }
            }
        }
    }
    return branchToMerge;
}
 
源代码3 项目: netbeans   文件: RemotesTest.java
public void testAddRemote () throws Exception {
    StoredConfig config = repository.getConfig();
    assertEquals(0, config.getSubsections("remote").size());
    
    GitClient client = getClient(workDir);
    GitRemoteConfig remoteConfig = new GitRemoteConfig("origin",
            Arrays.asList(new File(workDir.getParentFile(), "repo2").toURI().toString()),
            Arrays.asList(new File(workDir.getParentFile(), "repo2").toURI().toString()),
            Arrays.asList("+refs/heads/*:refs/remotes/origin/*"),
            Arrays.asList("refs/remotes/origin/*:+refs/heads/*"));
    client.setRemote(remoteConfig, NULL_PROGRESS_MONITOR);
    
    config.load();
    RemoteConfig cfg = new RemoteConfig(config, "origin");
    assertEquals(Arrays.asList(new URIish(new File(workDir.getParentFile(), "repo2").toURI().toString())), cfg.getURIs());
    assertEquals(Arrays.asList(new URIish(new File(workDir.getParentFile(), "repo2").toURI().toString())), cfg.getPushURIs());
    assertEquals(Arrays.asList(new RefSpec("+refs/heads/*:refs/remotes/origin/*")), cfg.getFetchRefSpecs());
    assertEquals(Arrays.asList(new RefSpec("refs/remotes/origin/*:+refs/heads/*")), cfg.getPushRefSpecs());
}
 
@Override
protected List<RefSpec> getRefSpecs() {
    List<RefSpec> refSpecs = new LinkedList<>();

    if (sourceSettings.getBranchMonitorStrategy().getMonitored()) {
        refSpecs.add(BRANCHES.delegate());
    }
    if (sourceSettings.getTagMonitorStrategy().getMonitored()) {
        refSpecs.add(TAGS.delegate());
    }
    if (sourceSettings.getOriginMonitorStrategy().getMonitored() || sourceSettings.getForksMonitorStrategy().getMonitored()) {
        refSpecs.add(MERGE_REQUESTS.delegate());
    }

    return refSpecs;
}
 
源代码5 项目: blueocean-plugin   文件: GitUtils.java
public static void fetch(final Repository repo, final StandardCredentials credential) {
    try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
        FetchCommand fetchCommand = git.fetch();

        addCredential(repo, fetchCommand, credential);

        fetchCommand.setRemote("origin")
            .setRemoveDeletedRefs(true)
            .setRefSpecs(new RefSpec("+refs/heads/*:refs/remotes/origin/*"))
            .call();
    } catch (GitAPIException ex) {
        if (ex.getMessage().contains("Auth fail")) {
            throw new ServiceException.UnauthorizedException("Not authorized", ex);
        }
        throw new RuntimeException(ex);
    }
}
 
源代码6 项目: spring-cloud-contract   文件: AbstractGitTest.java
void setOriginOnProjectToTmp(File origin, File project, boolean push)
		throws GitAPIException, IOException, URISyntaxException {
	try (Git git = openGitProject(project)) {
		RemoteRemoveCommand remove = git.remoteRemove();
		remove.setName("origin");
		remove.call();
		RemoteSetUrlCommand command = git.remoteSetUrl();
		command.setUri(new URIish(origin.toURI().toURL()));
		command.setName("origin");
		command.setPush(push);
		command.call();
		StoredConfig config = git.getRepository().getConfig();
		RemoteConfig originConfig = new RemoteConfig(config, "origin");
		originConfig
				.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
		originConfig.update(config);
		config.save();
	}
}
 
private void fetch(String branchName) throws GitAPIException {
    logger.info("Fetching branch " + branchName);
    if (!branchName.startsWith(REFS_REMOTES)) {
        throw new IllegalArgumentException("Branch name '" + branchName + "' is not tracking branch name since it does not start " + REFS_REMOTES);
    }
    String remoteName = extractRemoteName(branchName);
    String shortName = extractShortName(remoteName, branchName);
    FetchCommand fetchCommand = git.fetch()
            .setCredentialsProvider(credentialsProvider)
            .setRemote(remoteName)
            .setRefSpecs(new RefSpec(REFS_HEADS + shortName + ":" + branchName));
    if (configuration.useJschAgentProxy) {
        fetchCommand.setTransportConfigCallback(transport -> {
            if (transport instanceof SshTransport) {
                ((SshTransport) transport).setSshSessionFactory(new AgentProxyAwareJschConfigSessionFactory());
            }
        });
    }
    fetchCommand.call();
}
 
private void configureRemote(Git git, String repoUrl) throws URISyntaxException, IOException, GitAPIException {
    StoredConfig config = git.getRepository().getConfig();
    config.clear();
    config.setString("remote", "origin" ,"fetch", "+refs/heads/*:refs/remotes/origin/*");
    config.setString("remote", "origin" ,"push", "+refs/heads/*:refs/remotes/origin/*");
    config.setString("branch", "master", "remote", "origin");
    config.setString("baseBranch", "master", "merge", "refs/heads/master");
    config.setString("push", null, "default", "current");

    // disable all gc
    // http://download.eclipse.org/jgit/site/5.2.1.201812262042-r/apidocs/org/eclipse/jgit/internal/storage/file/GC.html#setAuto-boolean-
    config.setString("gc", null, "auto", "0");
    config.setString("gc", null, "autoPackLimit", "0");
    config.setBoolean("receive", null, "autogc", false);

    RemoteConfig remoteConfig = new RemoteConfig(config, "origin");
    URIish uri = new URIish(repoUrl);
    remoteConfig.addURI(uri);
    remoteConfig.addFetchRefSpec(new RefSpec("refs/heads/master:refs/heads/master"));
    remoteConfig.addPushRefSpec(new RefSpec("refs/heads/master:refs/heads/master"));
    remoteConfig.update(config);

    config.save();
}
 
源代码9 项目: spring-data-dev-tools   文件: GitOperations.java
public void push(TrainIteration iteration) {

		ExecutionUtils.run(executor, iteration, module -> {

			Branch branch = Branch.from(module);
			logger.log(module, "git push origin %s", branch);

			if (!branchExists(module.getProject(), branch)) {

				logger.log(module, "No branch %s in %s, skip push", branch, module.getProject().getName());
				return;
			}

			doWithGit(module.getProject(), git -> {

				Ref ref = git.getRepository().findRef(branch.toString());

				git.push()//
						.setRemote("origin")//
						.setRefSpecs(new RefSpec(ref.getName()))//
						.setCredentialsProvider(gitProperties.getCredentials())//
						.call();
			});
		});
	}
 
源代码10 项目: verigreen   文件: JGitOperator.java
@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 (dependsOnMethods = "testDelete")
public void testGitCreate() throws Exception {
  // push a new config file
  File testFlowFile = new File(GIT_CLONE_DIR + "/gobblin-config/testGroup/testFlow.pull");
  testFlowFile.getParentFile().mkdirs();

  Files.write("flow.name=testFlow\nflow.group=testGroup\nparam1=value20\n", testFlowFile, Charsets.UTF_8);

  Collection<Spec> specs = this.gobblinServiceManager.getFlowCatalog().getSpecs();
  Assert.assertEquals(specs.size(), 0);

  // add, commit, push
  this.gitForPush.add().addFilepattern("gobblin-config/testGroup/testFlow.pull").call();
  this.gitForPush.commit().setMessage("second commit").call();
  this.gitForPush.push().setRemote("origin").setRefSpecs(new RefSpec("master")).call();

  // polling is every 5 seconds, so wait twice as long and check
  TimeUnit.SECONDS.sleep(10);

  // spec generated using git monitor do not have schedule, so their life cycle should be similar to runOnce jobs
  Assert.assertEquals(this.gobblinServiceManager.getFlowCatalog().getSpecs().size(), 0);

  AssertWithBackoff.create().maxSleepMs(200L).timeoutMs(2000L).backoffFactor(1)
      .assertTrue(input -> !this.gobblinServiceManager.getScheduler().getScheduledFlowSpecs().containsKey(TEST_URI.toString()),
          "Waiting for job to get orchestrated...");
}
 
源代码12 项目: wildfly-core   文件: GitConfigurationPersister.java
@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();
}
 
源代码13 项目: git-client-plugin   文件: GitClientCloneTest.java
@Test
public void test_clone_refspecs() throws Exception {
    List<RefSpec> refspecs = Arrays.asList(
            new RefSpec("+refs/heads/master:refs/remotes/origin/master"),
            new RefSpec("+refs/heads/1.4.x:refs/remotes/origin/1.4.x")
    );
    testGitClient.clone_().url(workspace.localMirror()).refspecs(refspecs).repositoryName("origin").execute();
    testGitClient.withRepository((Repository workRepo, VirtualChannel channel) -> {
        String[] fetchRefSpecs = workRepo.getConfig().getStringList(ConfigConstants.CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, "fetch");
        assertThat(fetchRefSpecs.length, is(2));
        assertThat(fetchRefSpecs[0], is("+refs/heads/master:refs/remotes/origin/master"));
        assertThat(fetchRefSpecs[1], is("+refs/heads/1.4.x:refs/remotes/origin/1.4.x"));
        return null;
    });
    Set<Branch> remoteBranches = testGitClient.getRemoteBranches();
    assertBranchesExist(remoteBranches, "origin/master");
    assertBranchesExist(remoteBranches, "origin/1.4.x");
    assertThat(remoteBranches.size(), is(2));
}
 
源代码14 项目: git-client-plugin   文件: GitClientSecurityTest.java
@Test
@Issue("SECURITY-1534")
public void testFetch_URIish_SECURITY_1534() throws Exception {
    String refSpecString = "+refs/heads/*:refs/remotes/origin/*";
    List<RefSpec> refSpecs = new ArrayList<>();
    RefSpec refSpec = new RefSpec(refSpecString);
    refSpecs.add(refSpec);
    URIish badRepoUrl = new URIish(badRemoteUrl.trim());
    GitException e = assertThrows(GitException.class,
                                  () -> {
                                      gitClient.fetch_().from(badRepoUrl, refSpecs).execute();	
                                  });
    if (enableRemoteCheckUrl) {
        assertThat(e.getMessage(), containsString("Invalid remote URL: " + badRepoUrl.toPrivateASCIIString()));
    }
}
 
源代码15 项目: git-client-plugin   文件: GitClientTest.java
/**
 * Test case for auto local branch creation behviour.
 * This is essentially a stripped down version of {@link GitAPITestCase#test_branchContainingRemote()}
 * @throws Exception on exceptions occur
 */
@Test
public void testCheckoutRemoteAutocreatesLocal() throws Exception {
    File repoRootTemp = tempFolder.newFolder();
    GitClient gitClientTemp = Git.with(TaskListener.NULL, new EnvVars()).in(repoRootTemp).using(gitImplName).getClient();
    gitClientTemp.init();
    FilePath gitClientFilePath = gitClientTemp.getWorkTree();
    FilePath gitClientTempFile = gitClientFilePath.createTextTempFile("aPre", ".txt", "file contents");
    gitClientTemp.add(".");
    gitClientTemp.commit("Added " + gitClientTempFile.toURI().toString());
    gitClient.clone_().url("file://" + repoRootTemp.getPath()).execute();
    final URIish remote = new URIish(Constants.DEFAULT_REMOTE_NAME);
    final List<RefSpec> refspecs = Collections.singletonList(new RefSpec(
            "refs/heads/*:refs/remotes/origin/*"));
    gitClient.fetch_().from(remote, refspecs).execute();
    gitClient.checkout().ref(Constants.MASTER).execute();

    Set<String> refNames = gitClient.getRefNames("refs/heads/");
    assertThat(refNames, contains("refs/heads/master"));
}
 
源代码16 项目: git-client-plugin   文件: PushTest.java
@Before
public void createWorkingRepository() throws IOException, InterruptedException, URISyntaxException {
    hudson.EnvVars env = new hudson.EnvVars();
    TaskListener listener = StreamTaskListener.fromStderr();
    List<RefSpec> refSpecs = new ArrayList<>();
    workingRepo = temporaryFolder.newFolder();
    workingGitClient = Git.with(listener, env).in(workingRepo).using(gitImpl).getClient();
    workingGitClient.clone_()
            .url(bareRepo.getAbsolutePath())
            .repositoryName("origin")
            .execute();
    workingGitClient.checkout()
            .branch(branchName)
            .deleteBranchIfExist(true)
            .ref("origin/" + branchName)
            .execute();
    assertNotNull(bareFirstCommit);
    assertTrue("Clone does not contain " + bareFirstCommit,
            workingGitClient.revList("origin/" + branchName).contains(bareFirstCommit));
    ObjectId workingHead = workingGitClient.getHeadRev(workingRepo.getAbsolutePath(), branchName);
    ObjectId bareHead = bareGitClient.getHeadRev(bareRepo.getAbsolutePath(), branchName);
    assertEquals("Initial checkout of " + branchName + " has different HEAD than bare repo", bareHead, workingHead);
}
 
/**
 * We want to create a temporary local git repository after each iteration of the benchmark, works just like
 * "before" and "after" JUnit annotations.
 */
@Setup(Level.Iteration)
public void doSetup() throws Exception {
    tmp.before();
    gitDir = tmp.newFolder();

    gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using(gitExe).getClient();

    // fetching all branches
    refSpecs.add(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));

    // initialize the test folder for git fetch
    gitClient.init();

    System.out.println("Do Setup for: " + gitExe);
}
 
private Stream<RefSpec> changeQueryToRefSpecs(QueryRequest changeQuery) throws RestApiException {
  return changeQuery
      .get()
      .stream()
      .map(
          (ChangeInfo change) -> {
            String patchRef = change.revisions.entrySet().iterator().next().getValue().ref;
            return new RefSpec(
                patchRef + ":" + patchRef.replace("refs/changes", "refs/remotes/origin"));
          });
}
 
源代码19 项目: netbeans   文件: FetchUtils.java
private static String findRemotePeer (List<String> fetchRefSpecs, GitBranch branch) {
    for (String refSpec : fetchRefSpecs) {
        RefSpec spec = new RefSpec(refSpec);
        if (spec.matchDestination(GitUtils.PREFIX_R_REMOTES + branch.getName())) {
            if (spec.isWildcard()) {
                spec = spec.expandFromDestination(GitUtils.PREFIX_R_REMOTES + branch.getName());
            }
            return spec.getSource().substring(GitUtils.PREFIX_R_HEADS.length());
        }
    }
    return null;
}
 
源代码20 项目: netbeans   文件: RemotesTest.java
public void testRemoveRemote () throws Exception {
    File otherWT = new File(workDir.getParentFile(), "repo2");
    GitClient client = getClient(otherWT);
    client.init(NULL_PROGRESS_MONITOR);
    File f = new File(otherWT, "f");
    write(f, "init");
    client.add(new File[] { f }, NULL_PROGRESS_MONITOR);
    client.commit(new File[] { f }, "init commit", null, null, NULL_PROGRESS_MONITOR);
    
    RemoteConfig cfg = new RemoteConfig(repository.getConfig(), "origin");
    cfg.addURI(new URIish(otherWT.toURI().toURL().toString()));
    cfg.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
    cfg.update(repository.getConfig());
    repository.getConfig().save();
    
    client = getClient(workDir);
    client.fetch("origin", NULL_PROGRESS_MONITOR);
    client.createBranch("master", "origin/master", NULL_PROGRESS_MONITOR);
    client.createBranch("nova", "origin/master", NULL_PROGRESS_MONITOR);
    
    StoredConfig config = repository.getConfig();
    assertEquals("+refs/heads/*:refs/remotes/origin/*", config.getString("remote", "origin", "fetch"));
    assertEquals("origin", config.getString("branch", "master", "remote"));
    assertEquals("refs/heads/master", config.getString("branch", "master", "merge"));
    assertEquals("origin", config.getString("branch", "nova", "remote"));
    assertEquals("refs/heads/master", config.getString("branch", "nova", "merge"));
    
    // now try to remove the remote
    client.removeRemote("origin", NULL_PROGRESS_MONITOR);
    config = repository.getConfig();
    config.load();
    // is everything deleted?
    assertEquals(0, config.getSubsections("remote").size());
    assertNull(config.getString("branch", "master", "remote"));
    assertNull(config.getString("branch", "master", "merge"));
    assertNull(config.getString("branch", "nova", "remote"));
    assertNull(config.getString("branch", "nova", "merge"));
}
 
源代码21 项目: netbeans   文件: GetRemotesTest.java
public void testGetRemotes () throws Exception {
    GitClient client = getClient(workDir);
    StoredConfig cfg = repository.getConfig();
    RemoteConfig remoteConfig = new RemoteConfig(cfg, "origin");
    
    Map<String, GitRemoteConfig> remotes = client.getRemotes(NULL_PROGRESS_MONITOR);
    assertEquals(0, remotes.size());
    remoteConfig.update(cfg);
    cfg.save();
    
    remotes = client.getRemotes(NULL_PROGRESS_MONITOR);
    assertEquals(0, remotes.size());
    
    remoteConfig.addURI(new URIish("file:///home/repository"));
    remoteConfig.addURI(new URIish("file:///home/repository2"));
    remoteConfig.addPushURI(new URIish("file:///home/repository"));
    remoteConfig.addPushURI(new URIish("file:///home/repository3"));
    remoteConfig.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
    remoteConfig.addFetchRefSpec(new RefSpec("+refs/heads/master:refs/remotes/origin/my-master"));
    remoteConfig.addPushRefSpec(new RefSpec("refs/remotes/origin/*:refs/heads/*"));
    remoteConfig.update(cfg);
    cfg.save();
    
    remotes = client.getRemotes(NULL_PROGRESS_MONITOR);
    assertEquals(1, remotes.size());
    assertEquals("origin", remotes.get("origin").getRemoteName());
    assertEquals(Arrays.asList(new String[] { "file:///home/repository", "file:///home/repository2" }), remotes.get("origin").getUris());
    assertEquals(Arrays.asList(new String[] { "file:///home/repository", "file:///home/repository3" }), remotes.get("origin").getPushUris());
    assertEquals(Arrays.asList(new String[] { "+refs/heads/*:refs/remotes/origin/*", "+refs/heads/master:refs/remotes/origin/my-master" }), remotes.get("origin").getFetchRefSpecs());
    assertEquals(Arrays.asList(new String[] { "refs/remotes/origin/*:refs/heads/*" }), remotes.get("origin").getPushRefSpecs());
    
    GitRemoteConfig remote = client.getRemote("origin", NULL_PROGRESS_MONITOR);
    assertEquals("origin", remote.getRemoteName());
    assertEquals(Arrays.asList(new String[] { "file:///home/repository", "file:///home/repository2" }), remote.getUris());
    assertEquals(Arrays.asList(new String[] { "file:///home/repository", "file:///home/repository3" }), remote.getPushUris());
    assertEquals(Arrays.asList(new String[] { "+refs/heads/*:refs/remotes/origin/*", "+refs/heads/master:refs/remotes/origin/my-master" }), remote.getFetchRefSpecs());
    assertEquals(Arrays.asList(new String[] { "refs/remotes/origin/*:refs/heads/*" }), remote.getPushRefSpecs());
}
 
源代码22 项目: spring-cloud-release-tools   文件: GitRepo.java
/**
 * Pushes the commits to {@code origin} remote branch.
 * @param branch - remote branch to which the code should be pushed
 */
void pushBranch(String branch) {
	try (Git git = this.gitFactory.open(file(this.basedir))) {
		String localBranch = git.getRepository().getFullBranch();
		RefSpec refSpec = new RefSpec(localBranch + ":" + branch);
		this.gitFactory.push(git).setPushTags().setRefSpecs(refSpec).call();
	}
	catch (Exception e) {
		throw new IllegalStateException(e);
	}
}
 
源代码23 项目: spring-cloud-release-tools   文件: GitRepo.java
/**
 * Pushes the commits to {@code origin} remote tag.
 * @param tagName - remote tag to which the code should be pushed
 */
void pushTag(String tagName) {
	try (Git git = this.gitFactory.open(file(this.basedir))) {
		String localBranch = git.getRepository().getFullBranch();
		RefSpec refSpec = new RefSpec(localBranch + ":" + "refs/tags/" + tagName);
		this.gitFactory.push(git).setPushTags().setRefSpecs(refSpec).call();
	}
	catch (Exception e) {
		throw new IllegalStateException(e);
	}
}
 
源代码24 项目: orion.server   文件: GitRemoteTest.java
@Test
public void testRemoteProperties() throws IOException, SAXException, JSONException, CoreException, URISyntaxException {
	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
	String workspaceId = workspaceIdFromLocation(workspaceLocation);
	JSONObject project = createProjectOrLink(workspaceLocation, getMethodName().concat("Project"), null);
	IPath clonePath = getClonePath(workspaceId, project);
	JSONObject clone = clone(clonePath);
	String remotesLocation = clone.getString(GitConstants.KEY_REMOTE);
	project.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

	// create remote
	final String remoteName = "remote1";
	final String remoteUri = "http://remote1.com";
	final String fetchRefSpec = "+refs/heads/*:refs/remotes/%s/*";
	final String pushUri = "http://remote2.com";
	final String pushRefSpec = "refs/heads/*:refs/heads/*";
	addRemote(remotesLocation, remoteName, remoteUri, fetchRefSpec, pushUri, pushRefSpec);

	Repository db2 = FileRepositoryBuilder.create(GitUtils.getGitDir(new Path(toRelativeURI(clonePath.toString()))));
	toClose.add(db2);
	StoredConfig config = db2.getConfig();
	RemoteConfig rc = new RemoteConfig(config, remoteName);

	assertNotNull(rc);
	// main uri
	assertEquals(1, rc.getURIs().size());
	assertEquals(new URIish(remoteUri).toString(), rc.getURIs().get(0).toString());
	// fetchRefSpec
	assertEquals(1, rc.getFetchRefSpecs().size());
	assertEquals(new RefSpec(fetchRefSpec), rc.getFetchRefSpecs().get(0));
	// pushUri
	assertEquals(1, rc.getPushURIs().size());
	assertEquals(new URIish(pushUri).toString(), rc.getPushURIs().get(0).toString());
	// pushRefSpec
	assertEquals(1, rc.getPushRefSpecs().size());
	assertEquals(new RefSpec(pushRefSpec), rc.getPushRefSpecs().get(0));
}
 
源代码25 项目: blueocean-plugin   文件: GitUtils.java
/**
 *  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);
    }
}
 
源代码26 项目: blueocean-plugin   文件: GitUtils.java
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);
    }
}
 
源代码27 项目: repairnator   文件: SequencerCollector.java
protected void commitAndPushDiffs() throws NoFilepatternException, GitAPIException {
    diffsRepo.add().addFilepattern(".").call();
    diffsRepo.commit().setMessage("diff files").call();
    
    String OAUTH_TOKEN = System.getenv("OAUTH_TOKEN");
    
    RefSpec spec = new RefSpec("master:master");
    diffsRepo.push()
        .setRemote("origin")
        .setRefSpecs(spec)
        .setCredentialsProvider(new UsernamePasswordCredentialsProvider(OAUTH_TOKEN, ""))
        .call();
}
 
/**
 * Pushes the local comments and reviews back to the origin.
 */
private void pushCommentsAndReviews() throws Exception {
  try (Git git = new Git(repo)) {
    RefSpec spec = new RefSpec(DEVTOOLS_PUSH_REFSPEC);
    PushCommand pushCommand = git.push();
    pushCommand.setRefSpecs(spec);
    pushCommand.call();
  }
}
 
源代码29 项目: git-client-plugin   文件: CliGitAPIImpl.java
/** {@inheritDoc} */
@Override
public void fetch(String remoteName, RefSpec... refspec) throws GitException, InterruptedException {
    listener.getLogger().println(
                                 "Fetching upstream changes"
                                 + (remoteName != null ? " from " + remoteName : ""));

    ArgumentListBuilder args = new ArgumentListBuilder();
    args.add("fetch", "-t");
    if (USE_FORCE_FETCH && isAtLeastVersion(2, 20, 0, 0)) {
        /* CLI git 2.20.0 fixed a long-standing bug that now requires --force to update existing tags */
        args.add("--force");
    }

    if (remoteName == null)
        remoteName = getDefaultRemote();

    String url = getRemoteUrl(remoteName);
    if (url == null)
        throw new GitException("remote." + remoteName + ".url not defined");
    addCheckedRemoteUrl(args, url);
    if (refspec != null && refspec.length > 0)
        for (RefSpec rs: refspec)
            if (rs != null)
                args.add(rs.toString());


    StandardCredentials cred = credentials.get(url);
    if (cred == null) cred = defaultCredentials;
    launchCommandWithCredentials(args, workspace, cred, url);
}
 
源代码30 项目: git-client-plugin   文件: GitAPITestCase.java
/**
 * UT for {@link GitClient#getBranchesContaining(String, boolean)}. The main
 * testing case is retrieving remote branches.
 * @throws Exception on exceptions occur
 */
public void test_branchContainingRemote() throws Exception {
    final WorkingArea r = new WorkingArea();
    r.init();

    r.commitEmpty("c1");
    ObjectId c1 = r.head();

    w.git.clone_().url("file://" + r.repoPath()).execute();
    final URIish remote = new URIish(Constants.DEFAULT_REMOTE_NAME);
    final List<RefSpec> refspecs = Collections.singletonList(new RefSpec(
            "refs/heads/*:refs/remotes/origin/*"));
    final String remoteBranch = getRemoteBranchPrefix() + Constants.DEFAULT_REMOTE_NAME + "/"
            + Constants.MASTER;
    final String bothBranches = Constants.MASTER + "," + remoteBranch;
    w.git.fetch_().from(remote, refspecs).execute();
    checkoutTimeout = 1 + random.nextInt(60 * 24);
    w.git.checkout().ref(Constants.MASTER).timeout(checkoutTimeout).execute();

    assertEquals(Constants.MASTER,
            formatBranches(w.git.getBranchesContaining(c1.name(), false)));
    assertEquals(bothBranches, formatBranches(w.git.getBranchesContaining(c1.name(), true)));

    r.commitEmpty("c2");
    ObjectId c2 = r.head();
    w.git.fetch_().from(remote, refspecs).execute();
    assertEquals("", formatBranches(w.git.getBranchesContaining(c2.name(), false)));
    assertEquals(remoteBranch, formatBranches(w.git.getBranchesContaining(c2.name(), true)));
}