org.eclipse.jgit.transport.URIish Java Examples

The following examples show how to use org.eclipse.jgit.transport.URIish. 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: GitUtils.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns whether or not the git repository URI is forbidden. If a scheme of the URI is matched, check if the scheme is a supported protocol. Otherwise,
 * match for a scp-like ssh URI: [user@]host.xz:path/to/repo.git/ and ensure the URI does not represent a local file path.
 * 
 * @param uri
 *            A git repository URI
 * @return a boolean of whether or not the git repository URI is forbidden.
 */
public static boolean isForbiddenGitUri(URIish uri) {
	String scheme = uri.getScheme();
	String host = uri.getHost();
	String path = uri.getPath();
	boolean isForbidden = false;

	if (scheme != null) {
		isForbidden = !uriSchemeWhitelist.contains(scheme);
	} else {
		// match for a scp-like ssh URI
		if (host != null) {
			isForbidden = host.length() == 1 || path == null;
		} else {
			isForbidden = true;
		}
	}

	return isForbidden;
}
 
Example #2
Source File: PullTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testPullChangesInOtherBranchPlusMerge () throws Exception {
    GitClient client = getClient(workDir);
    client.pull(otherWT.toURI().toString(), Arrays.asList(new String[] { "+refs/heads/*:refs/remotes/origin/*" }), "origin/master", NULL_PROGRESS_MONITOR);
    File f = new File(workDir, this.f.getName());
    File f2 = new File(workDir, "f2");
    write(f2, "hi, i am new");
    add(f2);
    String localCommitId = client.commit(new File[] { f2 }, "local change", null, null, NULL_PROGRESS_MONITOR).getRevision();
    Map<String, GitBranch> branches = client.getBranches(true, NULL_PROGRESS_MONITOR);
    
    String commitId = makeRemoteChange(BRANCH_NAME);
    
    GitPullResult result = client.pull(otherWT.toURI().toString(), Arrays.asList(new String[] { "+refs/heads/*:refs/remotes/origin/*" }), "origin/" + BRANCH_NAME, NULL_PROGRESS_MONITOR);
    branches = client.getBranches(true, NULL_PROGRESS_MONITOR);
    assertTrue(branches.get("master").isActive());
    assertEquals(commitId, branches.get("origin/" + BRANCH_NAME).getId());
    assertFalse(commitId.equals(branches.get("master").getId()));
    assertFalse(localCommitId.equals(branches.get("master").getId()));
    Map<String, GitTransportUpdate> updates = result.getFetchResult();
    assertEquals(1, updates.size());
    assertUpdate(updates.get("origin/" + BRANCH_NAME), "origin/" + BRANCH_NAME, BRANCH_NAME, commitId, branch.getId(), new URIish(otherWT.toURI().toURL()).toString(), Type.BRANCH, GitRefUpdateResult.FAST_FORWARD);
    assertEquals(MergeStatus.MERGED, result.getMergeResult().getMergeStatus());
    assertEquals(new HashSet<String>(Arrays.asList(commitId, localCommitId)), new HashSet<String>(Arrays.asList(result.getMergeResult().getMergedCommits())));
    assertTrue(f.exists());
    assertTrue(f2.exists());
}
 
Example #3
Source File: GitRepoTests.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
@Test
public void should_push_changes_to_current_branch() throws Exception {
	File origin = GitTestUtils.clonedProject(this.tmp.newFolder(),
			this.springCloudReleaseProject);
	File project = new GitRepo(this.tmpFolder)
			.cloneProject(new URIish(this.springCloudReleaseProject.toURI().toURL()));
	GitTestUtils.setOriginOnProjectToTmp(origin, project);
	createNewFile(project);
	new GitRepo(project).commit("some message");

	new GitRepo(project).pushCurrentBranch();

	try (Git git = openGitProject(origin)) {
		RevCommit revCommit = git.log().call().iterator().next();
		then(revCommit.getShortMessage()).isEqualTo("some message");
	}
}
 
Example #4
Source File: PushBuildAction.java    From gitlab-plugin with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    for (SCMSource scmSource : ((SCMSourceOwner) project).getSCMSources()) {
        if (scmSource instanceof GitSCMSource) {
            GitSCMSource gitSCMSource = (GitSCMSource) scmSource;
            try {
                if (new URIish(gitSCMSource.getRemote()).equals(new URIish(gitSCMSource.getRemote()))) {
                    if (!gitSCMSource.isIgnoreOnPushNotifications()) {
                        LOGGER.log(Level.FINE, "Notify scmSourceOwner {0} about changes for {1}",
                                   toArray(project.getName(), gitSCMSource.getRemote()));
                        ((SCMSourceOwner) project).onSCMSourceUpdated(scmSource);
                    } else {
                        LOGGER.log(Level.FINE, "Ignore on push notification for scmSourceOwner {0} about changes for {1}",
                                   toArray(project.getName(), gitSCMSource.getRemote()));
                    }
                }
            } catch (URISyntaxException e) {
                // nothing to do
            }
        }
    }
}
 
Example #5
Source File: GitUtil.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 检查本地的remote是否存在对应的url
 *
 * @param url  要检查的url
 * @param file 本地仓库文件
 * @return true 存在对应url
 * @throws IOException     IO
 * @throws GitAPIException E
 */
private static boolean checkRemoteUrl(String url, File file) throws IOException, GitAPIException {
    try (Git git = Git.open(file)) {
        RemoteListCommand remoteListCommand = git.remoteList();
        boolean urlTrue = false;
        List<RemoteConfig> list = remoteListCommand.call();
        end:
        for (RemoteConfig remoteConfig : list) {
            for (URIish urIish : remoteConfig.getURIs()) {
                if (urIish.toString().equals(url)) {
                    urlTrue = true;
                    break end;
                }
            }
        }
        return urlTrue;
    }
}
 
Example #6
Source File: GitRepoTests.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
@Test
public void should_push_changes_to_master_branch() throws Exception {
	File origin = GitTestUtils.clonedProject(this.tmp.newFolder(),
			this.springCloudReleaseProject);
	File project = new GitRepo(this.tmpFolder)
			.cloneProject(new URIish(this.springCloudReleaseProject.toURI().toURL()));
	GitTestUtils.setOriginOnProjectToTmp(origin, project);
	createNewFile(project);
	new GitRepo(project).commit("some message");

	new GitRepo(project).pushBranch("master");

	try (Git git = openGitProject(origin)) {
		RevCommit revCommit = git.log().call().iterator().next();
		then(revCommit.getShortMessage()).isEqualTo("some message");
	}
}
 
Example #7
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "Java 11 spotbugs error")
private Set<String> listRemoteBranches(String remote) throws NotSupportedException, TransportException, URISyntaxException {
    Set<String> branches = new HashSet<>();
    try (final Repository repo = getRepository()) {
        StoredConfig config = repo.getConfig();
        try (final Transport tn = Transport.open(repo, new URIish(config.getString("remote",remote,"url")))) {
            tn.setCredentialsProvider(getProvider());
            try (final FetchConnection c = tn.openFetch()) {
                for (final Ref r : c.getRefs()) {
                    if (r.getName().startsWith(R_HEADS))
                        branches.add("refs/remotes/"+remote+"/"+r.getName().substring(R_HEADS.length()));
                }
            }
        }
    }
    return branches;
}
 
Example #8
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "Java 11 spotbugs error")
public ObjectId getHeadRev(String remoteRepoUrl, String branchSpec) throws GitException {
    try (Repository repo = openDummyRepository();
         final Transport tn = Transport.open(repo, new URIish(remoteRepoUrl))) {
        final String branchName = extractBranchNameFromBranchSpec(branchSpec);
        String regexBranch = createRefRegexFromGlob(branchName);

        tn.setCredentialsProvider(getProvider());
        try (FetchConnection c = tn.openFetch()) {
            for (final Ref r : c.getRefs()) {
                if (r.getName().matches(regexBranch)) {
                    return r.getPeeledObjectId() != null ? r.getPeeledObjectId() : r.getObjectId();
                }
            }
        }
    } catch (IOException | URISyntaxException | IllegalStateException e) {
        throw new GitException(e);
    }
    return null;
}
 
Example #9
Source File: PushTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testPushDeleteBranch () throws Exception {
    String remoteUri = getRemoteRepository().getWorkTree().toURI().toString();
    assertEquals(0, getClient(workDir).listRemoteBranches(remoteUri, NULL_PROGRESS_MONITOR).size());
    File f = new File(workDir, "f");
    add(f);
    String id = getClient(workDir).commit(new File[] { f }, "bbb", null, null, NULL_PROGRESS_MONITOR).getRevision();
    Map<String, GitTransportUpdate> updates = getClient(workDir).push(remoteUri, Arrays.asList(new String[] { "refs/heads/master:refs/heads/master", "refs/heads/master:refs/heads/newbranch" }), Collections.<String>emptyList(), NULL_PROGRESS_MONITOR).getRemoteRepositoryUpdates();
    Map<String, GitBranch> remoteBranches = getClient(workDir).listRemoteBranches(remoteUri, NULL_PROGRESS_MONITOR);
    assertEquals(2, remoteBranches.size());
    assertEquals(id, remoteBranches.get("master").getId());
    assertEquals(2, updates.size());
    assertUpdate(updates.get("master"), "master", "master", id, null, new URIish(remoteUri).toString(), Type.BRANCH, GitRefUpdateResult.OK);
    assertUpdate(updates.get("newbranch"), "master", "newbranch", id, null, new URIish(remoteUri).toString(), Type.BRANCH, GitRefUpdateResult.OK);

    // deleting branch
    updates = getClient(workDir).push(remoteUri, Arrays.asList(new String[] { ":refs/heads/newbranch" }), Collections.<String>emptyList(), NULL_PROGRESS_MONITOR).getRemoteRepositoryUpdates();
    remoteBranches = getClient(workDir).listRemoteBranches(remoteUri, NULL_PROGRESS_MONITOR);
    assertEquals(1, remoteBranches.size());
    assertEquals(id, remoteBranches.get("master").getId());
    assertUpdate(updates.get("newbranch"), null, "newbranch", null, id, new URIish(remoteUri).toString(), Type.BRANCH, GitRefUpdateResult.OK);
}
 
Example #10
Source File: ProjectGitHandler.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
File cloneProject(String url) {
	try {
		URIish urIish = new URIish(url);
		// retrieve from cache
		// reset any changes and fetch the latest data
		File destinationDir = destinationDir();
		File clonedProject = CACHE.computeIfAbsent(urIish,
				urIish1 -> gitRepo(destinationDir).cloneProject(urIish));
		if (clonedProject.exists()) {
			log.info(
					"Project has already been cloned. Will try to reset the current branch and fetch the latest changes.");
			try {
				gitRepo(clonedProject).reset();
				gitRepo(clonedProject).fetch();
			}
			catch (Exception ex) {
				log.warn("Couldn't reset / fetch the repository, will continue", ex);
			}
			return clonedProject;
		}
		return clonedProject;
	}
	catch (Exception e) {
		throw new IllegalStateException(e);
	}
}
 
Example #11
Source File: PreemptiveAuthHttpClientConnection.java    From git-client-plugin with MIT License 6 votes vote down vote up
static URIish goUp(final URIish uri) {
    final String originalPath = uri.getPath();
    if (originalPath == null || originalPath.length() == 0 || originalPath.equals(SLASH)) {
        return null;
    }
    final int lastSlash;
    if (originalPath.endsWith(SLASH)) {
        lastSlash = originalPath.lastIndexOf(SLASH, originalPath.length() - 2);
    }
    else {
        lastSlash = originalPath.lastIndexOf(SLASH);
    }
    final String pathUpOneLevel = originalPath.substring(0, lastSlash);
    final URIish result;
    if (pathUpOneLevel.length() == 0) {
        result = uri.setPath(null);
    }
    else {
        result = uri.setPath(pathUpOneLevel);
    }
    return result;
}
 
Example #12
Source File: TransportCommand.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected Transport openTransport (boolean openPush) throws URISyntaxException, NotSupportedException, TransportException {
    URIish uri = getUriWithUsername(openPush);
    // WA for #200693, jgit fails to initialize ftp protocol
    for (TransportProtocol proto : Transport.getTransportProtocols()) {
        if (proto.getSchemes().contains("ftp")) { //NOI18N
            Transport.unregister(proto);
        }
    }
    try {
        Transport transport = Transport.open(getRepository(), uri);
        RemoteConfig config = getRemoteConfig();
        if (config != null) {
            transport.applyConfig(config);
        }
        if (transport.getTimeout() <= 0) {
            transport.setTimeout(45);
        }
        transport.setCredentialsProvider(getCredentialsProvider());
        return transport;
    } catch (IllegalArgumentException ex) {
        throw new TransportException(ex.getLocalizedMessage(), ex);
    }
}
 
Example #13
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Deprecated
@Override
public void push(RemoteConfig repository, String refspec) throws GitException, InterruptedException {
    ArgumentListBuilder args = new ArgumentListBuilder();
    URIish uri = repository.getURIs().get(0);
    String url = uri.toPrivateString();
    StandardCredentials cred = credentials.get(url);
    if (cred == null) cred = defaultCredentials;

    args.add("push");
    addCheckedRemoteUrl(args, url);

    if (refspec != null)
        args.add(refspec);

    launchCommandWithCredentials(args, workspace, cred, uri);
    // Ignore output for now as there's many different formats
    // That are possible.

}
 
Example #14
Source File: TransportCommand.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected final URIish getUri (boolean pushUri) throws URISyntaxException {
    RemoteConfig config = getRemoteConfig();
    List<URIish> uris;
    if (config == null) {
        uris = Collections.emptyList();
    } else {
        if (pushUri) {
            uris = config.getPushURIs();
            if (uris.isEmpty()) {
                uris = config.getURIs();
            }
        } else {
            uris = config.getURIs();
        }
    }
    if (uris.isEmpty()) {
        return new URIish(remote);
    } else {
        return uris.get(0);
    }
}
 
Example #15
Source File: GitUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Compare the two given git remote URIs. This method is a reimplementation of {@link URIish#equals(Object)} with
 * one difference. The scheme of the URIs is only considered if both URIs have a non-null and non-empty scheme part.
 *
 * @param lhs
 *            the left hand side
 * @param rhs
 *            the right hand side
 * @return <code>true</code> if the two URIs are to be considered equal and <code>false</code> otherwise
 */
private static boolean equals(URIish lhs, URIish rhs) {
	// We only consider the scheme if both URIs have one
	if (!StringUtils.isEmptyOrNull(lhs.getScheme()) && !StringUtils.isEmptyOrNull(rhs.getScheme())) {
		if (!Objects.equals(lhs.getScheme(), rhs.getScheme()))
			return false;
	}
	if (!equals(lhs.getUser(), rhs.getUser()))
		return false;
	if (!equals(lhs.getPass(), rhs.getPass()))
		return false;
	if (!equals(lhs.getHost(), rhs.getHost()))
		return false;
	if (lhs.getPort() != rhs.getPort())
		return false;
	if (!pathEquals(lhs.getPath(), rhs.getPath()))
		return false;
	return true;
}
 
Example #16
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 #17
Source File: PrivateKeyCredentialsProvider.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
    for (CredentialItem i : items) {
        if (i instanceof Identity) {
            ((Identity) i).setValue(identityFile);
            continue;
        }
        if (i instanceof KnownHosts) {
            ((KnownHosts) i).setValue(knownHostsFile);
            continue;
        }
        throw new UnsupportedCredentialItem(uri, i.getClass().getName()
                + ":" + i.getPromptText()); //$NON-NLS-1$
    }
    return true;
}
 
Example #18
Source File: GitRepoTests.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void should_check_out_a_branch_on_cloned_repo2() throws IOException {
	URIish uri = new URIish(this.springCloudReleaseProject.toURI().toURL());
	File project = this.gitRepo.cloneProject(uri);
	new GitRepo(project).checkout("Camden.x");

	File pom = new File(new File(this.tmpFolder, uri.getHumanishName()), "pom.xml");
	then(pom).exists();
	then(Files.lines(pom.toPath())
			.anyMatch(s -> s.contains("<version>Camden.BUILD-SNAPSHOT</version>")))
					.isTrue();
}
 
Example #19
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void passphraseShouldSetCredentials() throws Exception {
	final String passphrase = "mypassphrase";
	Git mockGit = mock(Git.class);
	MockCloneCommand mockCloneCommand = new MockCloneCommand(mockGit);

	JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(
			this.environment, new JGitEnvironmentProperties());
	envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand));
	envRepository.setUri("git+ssh://git@somegitserver/somegitrepo");
	envRepository.setBasedir(new File("./mybasedir"));
	envRepository.setPassphrase(passphrase);
	envRepository.setCloneOnStart(true);
	envRepository.afterPropertiesSet();

	assertThat(mockCloneCommand.hasPassphraseCredentialsProvider()).isTrue();

	CredentialsProvider provider = mockCloneCommand.getCredentialsProvider();
	assertThat(provider.isInteractive()).isFalse();

	CredentialItem.StringType stringCredential = new CredentialItem.StringType(
			PassphraseCredentialsProvider.PROMPT, true);

	assertThat(provider.supports(stringCredential)).isTrue();
	provider.get(new URIish(), stringCredential);
	assertThat(passphrase).isEqualTo(stringCredential.getValue());
}
 
Example #20
Source File: RepoInfo.java    From aws-codecommit-trigger-plugin with Apache License 2.0 5 votes vote down vote up
public static RepoInfo fromSqsJob(SQSJob sqsJob) {
    if (sqsJob == null) {
        return null;
    }

    RepoInfo repoInfo = new RepoInfo();

    List<SCM> scms = sqsJob.getScmList();
    List<String> codeCommitUrls = new ArrayList<>();
    List<String> nonCodeCommitUrls = new ArrayList<>();
    List<String> branches = new ArrayList<>();

    for (SCM scm : scms) {
        if (scm instanceof GitSCM) {//TODO refactor to visitor
            GitSCM git = (GitSCM) scm;
            List<RemoteConfig> repos = git.getRepositories();
            for (RemoteConfig repo : repos) {
                for (URIish urIish : repo.getURIs()) {
                    String url = urIish.toString();
                    if (StringUtils.isCodeCommitRepo(url)) {
                        codeCommitUrls.add(url);
                    }
                    else {
                        nonCodeCommitUrls.add(url);
                    }
                }
            }

            for (BranchSpec branchSpec : git.getBranches()) {
                branches.add(branchSpec.getName());
            }
        }
    }

    repoInfo.nonCodeCommitUrls = nonCodeCommitUrls;
    repoInfo.codeCommitUrls = codeCommitUrls;
    repoInfo.branches = branches;
    return repoInfo;
}
 
Example #21
Source File: AbstractRepairStep.java    From repairnator with MIT License 5 votes vote down vote up
protected void pushPatches(Git git, String forkedRepo,String branchName) throws IOException, GitAPIException, URISyntaxException {
    RemoteAddCommand remoteAddCommand = git.remoteAdd();
    remoteAddCommand.setUri(new URIish(forkedRepo));
    remoteAddCommand.setName("fork-patch");
    remoteAddCommand.call();

    git.push().add(branchName).setRemote("fork-patch").setCredentialsProvider(new UsernamePasswordCredentialsProvider(RepairnatorConfig.getInstance().getGithubToken(), "")).call();
}
 
Example #22
Source File: AwsCodeCommitCredentialProvider.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
/**
 * Throw out cached data and force retrieval of AWS credentials.
 * @param uri This parameter is not used in this implementation.
 */
@Override
public void reset(URIish uri) {
	// Should throw out cached info.
	// Note that even though the credentials (password) we calculate here is
	// valid for 15 minutes, we do not cache it. Instead we just re-calculate
	// it each time we need it. However, the AWSCredentialProvider will cache
	// its AWSCredentials object.
}
 
Example #23
Source File: JGitSshSessionFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized RemoteSession getSession (URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException {
    boolean agentUsed = false;
    String host = uri.getHost();
    CredentialItem.StringType identityFile = null;
    if (credentialsProvider != null) {
        identityFile = new JGitCredentialsProvider.IdentityFileItem("Identity file for " + host, false);
        if (credentialsProvider.isInteractive() && credentialsProvider.get(uri, identityFile) && identityFile.getValue() != null) {
            LOG.log(Level.FINE, "Identity file for {0}: {1}", new Object[] { host, identityFile.getValue() }); //NOI18N
            agentUsed = setupJSch(fs, host, identityFile, uri, true);
            LOG.log(Level.FINE, "Setting cert auth for {0}, agent={1}", new Object[] { host, agentUsed }); //NOI18N
        }
    }
    try {
        LOG.log(Level.FINE, "Trying to connect to {0}, agent={1}", new Object[] { host, agentUsed }); //NOI18N
        return super.getSession(uri, credentialsProvider, fs, tms);
    } catch (Exception ex) {
        // catch rather all exceptions. In case jsch-agent-proxy is broken again we should
        // at least fall back on key/pasphrase
        if (agentUsed) {
            LOG.log(ex instanceof TransportException ? Level.FINE : Level.INFO, null, ex);
            setupJSch(fs, host, identityFile, uri, false);
            LOG.log(Level.FINE, "Trying to connect to {0}, agent={1}", new Object[] { host, false }); //NOI18N
            return super.getSession(uri, credentialsProvider, fs, tms);
        } else {
            LOG.log(Level.FINE, "Connection failed: {0}", host); //NOI18N
            throw ex;
        }
    }
}
 
Example #24
Source File: FetchTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testFetchMasterExplicitely () throws Exception {
    GitClient client = getClient(workDir);
    Map<String, GitBranch> branches = client.getBranches(true, NULL_PROGRESS_MONITOR);
    assertEquals(0, branches.size());
    setupRemoteSpec("origin", "+refs/heads/*:refs/remotes/origin/*");
    Map<String, GitTransportUpdate> updates = client.fetch("origin", Arrays.asList(new String[] { "+refs/heads/master:refs/remotes/origin/master" }), NULL_PROGRESS_MONITOR);
    branches = client.getBranches(true, NULL_PROGRESS_MONITOR);
    assertEquals(1, branches.size());
    assertTrue(branches.get("origin/master").isRemote());
    assertEquals(masterInfo.getRevision(), branches.get("origin/master").getId());
    assertEquals(1, updates.size());
    assertUpdate(updates.get("origin/master"), "origin/master", "master", masterInfo.getRevision(), null, new URIish(otherWT.toURI().toURL()).toString(), Type.BRANCH, GitRefUpdateResult.NEW);
}
 
Example #25
Source File: GitRepoTests.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void should_return_the_branch_name() throws Exception {
	File origin = GitTestUtils.clonedProject(this.tmp.newFolder(),
			this.springCloudReleaseProject);
	File project = new GitRepo(this.tmpFolder)
			.cloneProject(new URIish(this.springCloudReleaseProject.toURI().toURL()));
	GitTestUtils.setOriginOnProjectToTmp(origin, project);
	createNewFile(project);

	String branch = new GitRepo(project).currentBranch();

	then(branch).isEqualTo("master");
}
 
Example #26
Source File: GitCloneReadSaveRequest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
void save() throws IOException {
    try {
        GitClient git = cloneRepo();
        try {
            git.checkoutBranch(sourceBranch, "origin/" + sourceBranch);
        } catch(Exception e) {
            throw new RuntimeException("Branch not found: " + sourceBranch);
        }
        if (!sourceBranch.equals(branch)) {
            //git.branch(branch);
            git.checkoutBranch(branch, "origin/" + sourceBranch);
        }
        File f = new File(repositoryPath, filePath);
        // commit will fail if the contents hasn't changed
        if (!f.exists() || !Arrays.equals(FileUtils.readFileToByteArray(f), contents)) {
            FileUtils.writeByteArrayToFile(f, contents);
            git.add(filePath);
            git.commit(commitMessage);
        }
        git.push().ref(branch).to(new URIish(gitSource.getRemote())).execute();
    } catch (InterruptedException | GitException | URISyntaxException ex) {
        throw new ServiceException.UnexpectedErrorException("Unable to save " + filePath, ex);
    } finally {
        cleanupRepo();
    }
}
 
Example #27
Source File: GitRepoTests.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void should_throw_an_exception_when_checking_out_nonexisting_branch()
		throws IOException {
	File project = new GitRepo(this.tmpFolder)
			.cloneProject(new URIish(this.springCloudReleaseProject.toURI().toURL()));
	try {
		new GitRepo(project).checkout("nonExistingBranch");
		fail("should throw an exception");
	}
	catch (IllegalStateException e) {
		then(e).hasMessageContaining("Ref nonExistingBranch cannot be resolved");
	}
}
 
Example #28
Source File: GitRepoTests.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void should_not_commit_empty_changes() throws Exception {
	File project = new GitRepo(this.tmpFolder)
			.cloneProject(new URIish(this.springCloudReleaseProject.toURI().toURL()));
	createNewFile(project);
	new GitRepo(project).commit("some message");

	new GitRepo(project).commit("empty commit");

	try (Git git = openGitProject(project)) {
		RevCommit revCommit = git.log().call().iterator().next();
		then(revCommit.getShortMessage()).isNotEqualTo("empty commit");
	}
}
 
Example #29
Source File: GitTestUtils.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
public static void setOriginOnProjectToTmp(File origin, File project)
		throws GitAPIException, MalformedURLException {
	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(true);
		command.call();
	}
}
 
Example #30
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));
}