org.eclipse.jgit.transport.RefSpec Java Examples

The following examples show how to use org.eclipse.jgit.transport.RefSpec. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GitOperations.java    From spring-data-dev-tools with Apache License 2.0 6 votes vote down vote up
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();
			});
		});
	}
 
Example #2
Source File: GobblinServiceManagerTest.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@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...");
}
 
Example #3
Source File: GitUtils.java    From blueocean-plugin with MIT License 6 votes vote down vote up
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);
    }
}
 
Example #4
Source File: GitConfigurationPersister.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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();
}
 
Example #5
Source File: GitLabSCMSource.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 6 votes vote down vote up
@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;
}
 
Example #6
Source File: JGitOperator.java    From verigreen with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #7
Source File: GitClientCloneTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
@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));
}
 
Example #8
Source File: AbstractGitTest.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
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();
	}
}
 
Example #9
Source File: GitClientSecurityTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
@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()));
    }
}
 
Example #10
Source File: DifferentFiles.java    From gitflow-incremental-builder with MIT License 6 votes vote down vote up
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();
}
 
Example #11
Source File: LocalRepoMock.java    From gitflow-incremental-builder with MIT License 6 votes vote down vote up
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();
}
 
Example #12
Source File: GitClientTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
/**
 * 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"));
}
 
Example #13
Source File: PushTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
@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);
}
 
Example #14
Source File: RemotesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #15
Source File: PullCommand.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #16
Source File: GitClientFetchBenchmark.java    From git-client-plugin with MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example #17
Source File: GitUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 *  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);
    }
}
 
Example #18
Source File: RemotesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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"));
}
 
Example #19
Source File: GetRemotesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #20
Source File: GitRepo.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example #21
Source File: RepoMerger.java    From git-merge-repos with Apache License 2.0 5 votes vote down vote up
private void fetch() throws GitAPIException {
	for (SubtreeConfig config : subtreeConfigs) {
		RefSpec branchesSpec = new RefSpec(
				"refs/heads/*:refs/heads/original/"
						+ config.getRemoteName() + "/*");
		RefSpec tagsSpec = new RefSpec("refs/tags/*:refs/tags/original/"
				+ config.getRemoteName() + "/*");
		Git git = new Git(repository);
		git.fetch().setRemote(config.getFetchUri().toPrivateString())
				.setRefSpecs(branchesSpec, tagsSpec).call();
	}
}
 
Example #22
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@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);
}
 
Example #23
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
/**
 * 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)));
}
 
Example #24
Source File: GitClientSecurityTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("SECURITY-1534")
public void testFetch_String_SECURITY_1534() throws Exception {
    RefSpec refSpec = new RefSpec("+refs/heads/*:refs/remotes/origin/*");
    gitClient.setRemoteUrl("origin", badRemoteUrl);
    GitException e = assertThrows(GitException.class,
                                  () -> {
                                      gitClient.fetch("origin", refSpec);
                                  });
    if (enableRemoteCheckUrl) {
        assertThat(e.getMessage(), containsString("Invalid remote URL: " + badRemoteUrl.trim()));
    }
}
 
Example #25
Source File: GitClientSecurityTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("SECURITY-1534")
public void testFetch_String_RefSpec_SECURITY_1534() throws Exception {
    RefSpec refSpec = new RefSpec("+refs/heads/*:refs/remotes/origin/*");
    gitClient.setRemoteUrl("origin", badRemoteUrl);
    GitException e = assertThrows(GitException.class,
                                  () -> {
                                      gitClient.fetch("origin", refSpec, refSpec, refSpec);
                                  });
    if (enableRemoteCheckUrl) {
        assertThat(e.getMessage(), containsString("Invalid remote URL: " + badRemoteUrl.trim()));
    }
}
 
Example #26
Source File: GitClientTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testAutocreateFailsOnMultipleMatchingOrigins() 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);

    try ( // add second remote
          FileRepository repo = new FileRepository(new File(repoRoot, ".git"))) {
        StoredConfig config = repo.getConfig();
        config.setString("remote", "upstream", "url", "file://" + repoRootTemp.getPath());
        config.setString("remote", "upstream", "fetch", "+refs/heads/*:refs/remotes/upstream/*");
        config.save();
    }

    // fill both remote branches
    List<RefSpec> refspecs = Collections.singletonList(new RefSpec(
            "refs/heads/*:refs/remotes/origin/*"));
    gitClient.fetch_().from(remote, refspecs).execute();
    refspecs = Collections.singletonList(new RefSpec(
            "refs/heads/*:refs/remotes/upstream/*"));
    gitClient.fetch_().from(remote, refspecs).execute();

    // checkout will fail
    try {
        gitClient.checkout().ref(Constants.MASTER).execute();
    } catch (GitException e) {
        // expected
        Set<String> refNames = gitClient.getRefNames("refs/heads/");
        assertFalse("RefNames will not contain master", refNames.contains("refs/heads/master"));
    }

}
 
Example #27
Source File: GitClientTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
private void fetch(GitClient client, String remote, boolean fetchTags, String firstRefSpec, String... optionalRefSpecs) throws Exception {
    List<RefSpec> refSpecs = new ArrayList<>();
    RefSpec refSpec = new RefSpec(firstRefSpec);
    refSpecs.add(refSpec);
    for (String refSpecString : optionalRefSpecs) {
        refSpecs.add(new RefSpec(refSpecString));
    }
    switch (random.nextInt(2)) {
        default:
        case 0:
            if (remote.equals("origin")) {
                /* If remote == "origin", randomly use default remote */
                remote = random.nextBoolean() ? remote : null;
            }
            client.fetch(remote, refSpecs.toArray(new RefSpec[0]));
            break;
        case 1:
            URIish repoURL = new URIish(client.withRepository((repo, channel) -> repo.getConfig()).getString("remote", remote, "url"));
            boolean pruneBranches = random.nextBoolean();
            if (pruneBranches) {
                client.fetch_().from(repoURL, refSpecs).tags(fetchTags).prune(true).execute();
            } else {
                client.fetch_().from(repoURL, refSpecs).tags(fetchTags).execute();
            }
            break;
    }
}
 
Example #28
Source File: CredentialsTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
private void doFetch(String source, String branch, Boolean allowShallowClone) throws Exception {
    /* Save some bandwidth with shallow clone for CliGit, not yet available for JGit */
    URIish sourceURI = new URIish(source);
    List<RefSpec> refSpecs = new ArrayList<>();
    refSpecs.add(new RefSpec("+refs/heads/"+branch+":refs/remotes/origin/"+branch+""));
    FetchCommand cmd = git.fetch_().from(sourceURI, refSpecs).tags(false);
    if (isShallowCloneSupported(gitImpl, git)) {
        // Reduce network transfer by using shallow clone
        // JGit does not support shallow clone
        cmd.shallow(true).depth(1);
    }
    cmd.execute();
}
 
Example #29
Source File: GitClientFetchTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void test_fetch_from_url() throws Exception {
    newAreaWorkspace = new WorkspaceWithRepo(thirdRepo.getRoot(), gitImplName, TaskListener.NULL);
    newAreaWorkspace.getGitClient().init();
    newAreaWorkspace.launchCommand("git", "commit", "--allow-empty", "-m", "init");
    String sha1 = newAreaWorkspace.launchCommand("git", "rev-list", "--no-walk", "--max-count=1", "HEAD");

    testGitClient.init();
    cliGitCommand.run("remote", "add", "origin", newAreaWorkspace.getGitFileDir().getAbsolutePath());
    testGitClient.fetch(new URIish(newAreaWorkspace.getGitFileDir().toString()), Collections.<RefSpec>emptyList());
    assertThat(sha1.contains(newAreaWorkspace.launchCommand("git", "rev-list", "--no-walk", "--max-count=1", "HEAD")), is(true));
}
 
Example #30
Source File: GitOperations.java    From simple-pull-request-job-plugin with Apache License 2.0 5 votes vote down vote up
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);
}