Java Code Examples for org.eclipse.jgit.transport.URIish

The following examples show how to use org.eclipse.jgit.transport.URIish. These examples are extracted from open source projects. 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 Project: Jpom   Source File: GitUtil.java    License: 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 2
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 3
Source Project: spring-cloud-release-tools   Source File: GitRepoTests.java    License: 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 Project: git-client-plugin   Source File: JGitAPIImpl.java    License: 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 5
@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 6
Source Project: n4js   Source File: GitUtils.java    License: 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 7
Source Project: orion.server   Source File: GitUtils.java    License: 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: [[email protected]]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 8
Source Project: netbeans   Source File: TransportCommand.java    License: 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 9
Source Project: git-client-plugin   Source File: CliGitAPIImpl.java    License: 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 10
Source Project: netbeans   Source File: TransportCommand.java    License: 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 11
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
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 13
Source Project: netbeans   Source File: RemotesTest.java    License: 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 14
Source Project: netbeans   Source File: PushTest.java    License: 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 15
Source Project: git-client-plugin   Source File: JGitAPIImpl.java    License: 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 16
Source Project: netbeans   Source File: PullTest.java    License: 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 17
Source Project: spring-cloud-release-tools   Source File: GitRepoTests.java    License: 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 18
/**
 * Ask for the credential items to be populated with the passphrase.
 * @param uri the URI of the remote resource that needs authentication.
 * @param items the items the application requires to complete authentication.
 * @return {@code true} if the request was successful and values were supplied;
 * {@code false} if the user canceled the request and did not supply all requested
 * values.
 * @throws UnsupportedCredentialItem if one of the items supplied is not supported.
 */
@Override
public boolean get(URIish uri, CredentialItem... items)
		throws UnsupportedCredentialItem {
	for (final CredentialItem item : items) {
		if (item instanceof CredentialItem.StringType
				&& item.getPromptText().startsWith(PROMPT)) {
			((CredentialItem.StringType) item).setValue(this.passphrase);
			continue;
		}
		throw new UnsupportedCredentialItem(uri,
				item.getClass().getName() + ":" + item.getPromptText());
	}
	return true;
}
 
Example 19
Source Project: ant-git-tasks   Source File: AbstractGitTask.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the git repository uri
 *
 * @antdoc.notrequired
 * @param uri The repository uri
 */
public void setUri(String uri) {
        if (GitTaskUtils.isNullOrBlankString(uri)) {
                throw new BuildException("Can't set null URI attribute.");
        }

        if (this.uri == null) {
                try {
                        new URIish(uri);
                        this.uri = uri;
                } catch (URISyntaxException e) {
                        throw new BuildException(String.format("Invalid URI '%s'.", uri), e);
                }
        }
}
 
Example 20
private String buildGitCommandInput(URIish uri) {
    StringBuilder builder = new StringBuilder();
    builder.append("protocol=").append(uri.getScheme()).append("\n");
    builder.append("host=").append(uri.getHost());
    if (uri.getPort() != -1) {
        builder.append(":").append(uri.getPort());
    }
    builder.append("\n");
    Optional.ofNullable(uri.getPath())
            .map(path -> path.startsWith("/") ? path.substring(1) : path)
            .ifPresent(path -> builder.append("path=").append(path).append("\n"));
    Optional.ofNullable(uri.getUser())
            .ifPresent(user -> builder.append("username=").append(user).append("\n"));
    return builder.toString();
}
 
Example 21
/**
 * Get the URL of the first declared repository in the project configuration.
 * Use this as default source repository url.
 *
 * @return URIish the default value of the source repository url
 * @throws IllegalStateException Project does not use git scm.
 */
private URIish getSourceRepoURLDefault(Job<?, ?> job) {
    SCMTriggerItem item = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(job);
    GitSCM gitSCM = getGitSCM(item);
    if (gitSCM == null) {
        LOGGER.log(Level.WARNING, "Could not find GitSCM for project. Project = {1}, next build = {2}",
                array(job.getName(), String.valueOf(job.getNextBuildNumber())));
        throw new IllegalStateException("This project does not use git:" + job.getName());
    }
    return getFirstRepoURL(gitSCM.getRepositories());
}
 
Example 22
Source Project: spring-cloud-release-tools   Source File: GitRepoTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void should_throw_an_exception_when_failed_to_initialize_the_repo() {
	thenThrownBy(() -> new GitRepo(this.tmpFolder, new ExceptionThrowingJGitFactory())
			.cloneProject(new URIish(this.springCloudReleaseProject.toURI().toURL())))
					.isInstanceOf(IllegalStateException.class)
					.hasMessageContaining("Exception occurred while cloning repo")
					.hasCauseInstanceOf(CustomException.class);
}
 
Example 23
/**
 * Calculate the AWS CodeCommit password for the provided URI and AWS secret key. This
 * uses the algorithm published by AWS at
 * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
 * @param uri the codecommit repository uri
 * @param awsSecretKey the aws secret key
 * @return the password to use in the git request
 */
protected static String calculateCodeCommitPassword(URIish uri, String awsSecretKey) {
	String[] split = uri.getHost().split("\\.");
	if (split.length < 4) {
		throw new CredentialException("Cannot detect AWS region from URI", null);
	}
	String region = split[1];

	Date now = new Date();
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
	dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

	String dateStamp = dateFormat.format(now);
	String shortDateStamp = dateStamp.substring(0, 8);

	String codeCommitPassword;
	try {
		StringBuilder stringToSign = new StringBuilder();
		stringToSign.append("AWS4-HMAC-SHA256\n").append(dateStamp).append("\n")
				.append(shortDateStamp).append("/").append(region)
				.append("/codecommit/aws4_request\n")
				.append(bytesToHexString(canonicalRequestDigest(uri)));

		byte[] signedRequest = sign(awsSecretKey, shortDateStamp, region,
				stringToSign.toString());
		codeCommitPassword = dateStamp + "Z" + bytesToHexString(signedRequest);
	}
	catch (Exception e) {
		throw new CredentialException("Error calculating AWS CodeCommit password", e);
	}

	return codeCommitPassword;
}
 
Example 24
Source Project: spring-cloud-release-tools   Source File: GitRepoTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void should_commit_changes() throws Exception {
	URIish uri = new URIish(this.springCloudReleaseProject.toURI().toURL());
	File project = new GitRepo(this.tmpFolder).cloneProject(uri);
	createNewFile(project);

	new GitRepo(project).commit("some message");

	try (Git git = openGitProject(project)) {
		RevCommit revCommit = git.log().call().iterator().next();
		then(revCommit.getShortMessage()).isEqualTo("some message");
	}
}
 
Example 25
Source Project: git-client-plugin   Source File: GitClientTest.java    License: 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 26
Source Project: git-merge-repos   Source File: Main.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, GitAPIException, URISyntaxException {
	List<SubtreeConfig> subtreeConfigs = new ArrayList<>();

	for (String arg : args) {
		Matcher matcher = REPO_AND_DIR.matcher(arg);
		if (matcher.matches()) {
			String repositoryUrl = matcher.group(1);
			String directory = matcher.group(2);
			SubtreeConfig config = new SubtreeConfig(directory, new URIish(repositoryUrl));
			subtreeConfigs.add(config);
		} else {
			exitInvalidUsage("invalid argument '" + arg
					+ "', expected '<repository_url>:<target_directory>'");
		}
	}

	if (subtreeConfigs.isEmpty()) {
		exitInvalidUsage("usage: program <repository_url>:<target_directory>...");
	}

	File outputDirectory = new File("merged-repo");
	String outputPath = outputDirectory.getAbsolutePath();
	System.out.println("Started merging " + subtreeConfigs.size()
			+ " repositories into one, output directory: " + outputPath);

	long start = System.currentTimeMillis();
	RepoMerger merger = new RepoMerger(outputPath, subtreeConfigs);
	List<MergedRef> mergedRefs = merger.run();
	long end = System.currentTimeMillis();

	long timeMs = (end - start);
	printIncompleteRefs(mergedRefs);
	System.out.println("Done, took " + timeMs + " ms");
	System.out.println("Merged repository: " + outputPath);

}
 
Example 27
Source Project: git-client-plugin   Source File: GitAPITestCase.java    License: 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 28
/**
 * Get the URL of the first declared repository in the project configuration.
 * Use this as default source repository url.
 *
 * @return URIish the default value of the source repository url
 * @throws IllegalStateException Project does not use git scm.
 */
private URIish getSourceRepoURLDefault(Job<?, ?> job) {
    SCMTriggerItem item = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(job);
    GitSCM gitSCM = getGitSCM(item);
    if (gitSCM == null) {
        LOGGER.log(Level.WARNING, "Could not find GitSCM for project. Project = {1}, next build = {2}",
                array(job.getName(), String.valueOf(job.getNextBuildNumber())));
        throw new IllegalStateException("This project does not use git:" + job.getName());
    }
    return getFirstRepoURL(gitSCM.getRepositories());
}
 
Example 29
Source Project: gerrit-code-review-plugin   Source File: GerritURITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void projectNameWithSlashesIsExtractedFromSSHURI() throws URISyntaxException {
  GerritURI gerritURI =
      new GerritURI(new URIish("ssh://[email protected]:29418/project/with/slashes"));

  assertEquals("project/with/slashes", gerritURI.getProject());
}
 
Example 30
Source Project: git-client-plugin   Source File: SmartCredentialsProvider.java    License: MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public synchronized boolean get(URIish uri, CredentialItem... credentialItems) throws UnsupportedCredentialItem {
    StandardCredentials c = specificCredentials.get(uri == null ? null : uri.toString());
    if (c == null) {
        c = defaultCredentials;
    }
    if (c == null) {
        return false;
    }
    for (CredentialItem i : credentialItems) {
        if (i instanceof StandardUsernameCredentialsCredentialItem && c instanceof StandardUsernameCredentials) {
            ((StandardUsernameCredentialsCredentialItem) i).setValue((StandardUsernameCredentials) c);
            continue;
        }
        if (i instanceof CredentialItem.Username && c instanceof UsernameCredentials) {
            ((CredentialItem.Username) i).setValue(((UsernameCredentials)c).getUsername());
            continue;
        }
        if (i instanceof CredentialItem.Password && c instanceof PasswordCredentials) {
            ((CredentialItem.Password) i).setValue(
                    ((PasswordCredentials) c).getPassword().getPlainText().toCharArray());
            continue;
        }
        if (i instanceof CredentialItem.StringType) {
            if (i.getPromptText().equals("Password: ") && c instanceof PasswordCredentials) {
                ((CredentialItem.StringType) i).setValue(((PasswordCredentials) c).getPassword().getPlainText());
                continue;
            }
        }
        throw new UnsupportedCredentialItem(uri, i.getClass().getName()
                + ":" + i.getPromptText());
    }
    return true;
}