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

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

源代码1 项目: Jpom   文件: GitUtil.java
/**
 * 检查本地的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;
    }
}
 
源代码2 项目: gitlab-plugin   文件: PushBuildAction.java
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
            }
        }
    }
}
 
源代码3 项目: spring-cloud-release-tools   文件: GitRepoTests.java
@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");
	}
}
 
源代码4 项目: git-client-plugin   文件: JGitAPIImpl.java
@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;
}
 
@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;
}
 
源代码6 项目: n4js   文件: GitUtils.java
/**
 * 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;
}
 
源代码7 项目: orion.server   文件: GitUtils.java
/**
 * 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;
}
 
源代码8 项目: netbeans   文件: TransportCommand.java
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);
    }
}
 
源代码9 项目: git-client-plugin   文件: CliGitAPIImpl.java
/** {@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.

}
 
源代码10 项目: netbeans   文件: TransportCommand.java
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);
    }
}
 
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;
}
 
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);
	}
}
 
源代码13 项目: netbeans   文件: RemotesTest.java
public void testAddRemote () throws Exception {
    StoredConfig config = repository.getConfig();
    assertEquals(0, config.getSubsections("remote").size());
    
    GitClient client = getClient(workDir);
    GitRemoteConfig remoteConfig = new GitRemoteConfig("origin",
            Arrays.asList(new File(workDir.getParentFile(), "repo2").toURI().toString()),
            Arrays.asList(new File(workDir.getParentFile(), "repo2").toURI().toString()),
            Arrays.asList("+refs/heads/*:refs/remotes/origin/*"),
            Arrays.asList("refs/remotes/origin/*:+refs/heads/*"));
    client.setRemote(remoteConfig, NULL_PROGRESS_MONITOR);
    
    config.load();
    RemoteConfig cfg = new RemoteConfig(config, "origin");
    assertEquals(Arrays.asList(new URIish(new File(workDir.getParentFile(), "repo2").toURI().toString())), cfg.getURIs());
    assertEquals(Arrays.asList(new URIish(new File(workDir.getParentFile(), "repo2").toURI().toString())), cfg.getPushURIs());
    assertEquals(Arrays.asList(new RefSpec("+refs/heads/*:refs/remotes/origin/*")), cfg.getFetchRefSpecs());
    assertEquals(Arrays.asList(new RefSpec("refs/remotes/origin/*:+refs/heads/*")), cfg.getPushRefSpecs());
}
 
源代码14 项目: netbeans   文件: PushTest.java
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);
}
 
源代码15 项目: git-client-plugin   文件: JGitAPIImpl.java
/** {@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;
}
 
源代码16 项目: netbeans   文件: PullTest.java
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());
}
 
源代码17 项目: spring-cloud-release-tools   文件: GitRepoTests.java
@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");
	}
}
 
/**
 * 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;
}
 
源代码19 项目: ant-git-tasks   文件: AbstractGitTask.java
/**
 * 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);
                }
        }
}
 
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();
}
 
源代码21 项目: gitlab-plugin   文件: ProjectLabelsProvider.java
/**
 * 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());
}
 
源代码22 项目: spring-cloud-release-tools   文件: GitRepoTests.java
@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);
}
 
/**
 * 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;
}
 
源代码24 项目: spring-cloud-release-tools   文件: GitRepoTests.java
@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");
	}
}
 
源代码25 项目: git-client-plugin   文件: GitClientTest.java
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;
    }
}
 
源代码26 项目: git-merge-repos   文件: Main.java
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);

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

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

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

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

    r.commitEmpty("c2");
    ObjectId c2 = r.head();
    w.git.fetch_().from(remote, refspecs).execute();
    assertEquals("", formatBranches(w.git.getBranchesContaining(c2.name(), false)));
    assertEquals(remoteBranch, formatBranches(w.git.getBranchesContaining(c2.name(), true)));
}
 
源代码28 项目: gitlab-plugin   文件: ProjectBranchesProvider.java
/**
 * 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());
}
 
源代码29 项目: gerrit-code-review-plugin   文件: GerritURITest.java
@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());
}
 
/** {@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;
}