org.eclipse.jgit.transport.CredentialsProvider Java Examples

The following examples show how to use org.eclipse.jgit.transport.CredentialsProvider. 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 submarine with Apache License 2.0 7 votes vote down vote up
/**
 * To execute clone command
 * @param remotePath
 * @param localPath
 * @param token
 * @param branch
 * @throws GitAPIException
 */
public void clone(String remotePath, String localPath, String token, String branch) {
  // Clone the code base command
  // Sets the token on the remote server
  CredentialsProvider credentialsProvider =
      new UsernamePasswordCredentialsProvider("PRIVATE-TOKEN", token);

  Git git = null;
  try {
    git = Git.cloneRepository().setURI(remotePath) // Set remote URI
        .setBranch(branch) // Set the branch down from clone
        .setDirectory(new File(localPath)) // Set the download path
        .setCredentialsProvider(credentialsProvider) // Set permission validation
        .call();
  } catch (GitAPIException e) {
    LOG.error(e.getMessage(), e);
  } finally {
    if (git != null) {
      git.close();
    }
  }
  LOG.info("git.tag(): {}", git.tag());
}
 
Example #2
Source File: ProjectFileSystem.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
public static void cloneRepo(File projectFolder, String cloneUrl, CredentialsProvider credentialsProvider, final File sshPrivateKey, final File sshPublicKey, String remote, String tag) {
    StopWatch watch = new StopWatch();

    // clone the repo!
    boolean cloneAll = true;
    LOG.info("Cloning git repo " + cloneUrl + " into directory " + projectFolder.getAbsolutePath() + " cloneAllBranches: " + cloneAll);
    CloneCommand command = Git.cloneRepository();
    GitUtils.configureCommand(command, credentialsProvider, sshPrivateKey, sshPublicKey);
    command = command.setCredentialsProvider(credentialsProvider).
            setCloneAllBranches(cloneAll).setURI(cloneUrl).setDirectory(projectFolder).setRemote(remote);

    try {
        Git git = command.call();
        if (tag != null){
            git.checkout().setName(tag).call();
        }
    } catch (Throwable e) {
        LOG.error("Failed to command remote repo " + cloneUrl + " due: " + e.getMessage(), e);
        throw new RuntimeException("Failed to command remote repo " + cloneUrl + " due: " + e.getMessage());
    } finally {
        LOG.info("cloneRepo took " + watch.taken());
    }
}
 
Example #3
Source File: GitUtils.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
public static File cloneRepository(String remoteUri, String tempFolder, String branch,
		CredentialsProvider credentialsProvider) {

	File file = new File(tempFolder);

	try {
		if (file.exists()) {
			deleteFolder(file);
		}
		file.mkdirs();
		Git.cloneRepository().setURI(remoteUri).setDirectory(file).setBranch(branch)
				.setCredentialsProvider(credentialsProvider).call();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		logger.error(e.getMessage(), e);
	}
	return file;
}
 
Example #4
Source File: GitUtils.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
public static File cloneRepository(String remoteUri, String tempFolder, CredentialsProvider credentialsProvider) {

		logger.info("begin clone " + remoteUri + " to " + tempFolder);
		File file = new File(tempFolder);

		try {
			if (file.exists()) {
				deleteFolder(file);
			}
			file.mkdirs();
			Git git = Git.cloneRepository().setURI(remoteUri).setDirectory(file)
					.setCredentialsProvider(credentialsProvider).call();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
		logger.info("end clone " + remoteUri + " to " + tempFolder);

		return file;
	}
 
Example #5
Source File: GitUtils.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
public static File cloneRepository(String remoteUri, String tempFolder, String branch,
		CredentialsProvider credentialsProvider) {

	File file = new File(tempFolder);

	try {
		if (file.exists()) {
			deleteFolder(file);
		}
		file.mkdirs();
		Git.cloneRepository().setURI(remoteUri).setDirectory(file).setBranch(branch)
				.setCredentialsProvider(credentialsProvider).call();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		logger.error(e.getMessage(), e);
	}
	return file;
}
 
Example #6
Source File: GitUtils.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
public static File cloneRepository(String remoteUri, String tempFolder, CredentialsProvider credentialsProvider) {

		logger.info("begin clone " + remoteUri + " to " + tempFolder);
		File file = new File(tempFolder);

		try {
			if (file.exists()) {
				deleteFolder(file);
			}
			file.mkdirs();
			Git git = Git.cloneRepository().setURI(remoteUri).setDirectory(file)
					.setCredentialsProvider(credentialsProvider).call();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
		logger.info("end clone " + remoteUri + " to " + tempFolder);

		return file;
	}
 
Example #7
Source File: XdocPublisher.java    From contribution with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Publish release notes.
 *
 * @throws IOException if problem with access to files appears.
 * @throws GitAPIException for problems with jgit.
 */
public void publish() throws IOException, GitAPIException {
    changeLocalRepoXdoc();
    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    final File localRepo = new File(localRepoPath);
    final Repository repo = builder.findGitDir(localRepo).readEnvironment().build();
    final Git git = new Git(repo);
    git.add()
        .addFilepattern(PATH_TO_XDOC_IN_REPO)
        .call();
    git.commit()
        .setMessage(String.format(Locale.ENGLISH, COMMIT_MESSAGE_TEMPLATE, releaseNumber))
        .call();
    if (doPush) {
        final CredentialsProvider credentialsProvider =
            new UsernamePasswordCredentialsProvider(authToken, "");
        git.push()
            .setCredentialsProvider(credentialsProvider)
            .call();
    }
}
 
Example #8
Source File: GitUtil.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 获取仓库远程的所有分支
 *
 * @param url                 远程url
 * @param file                仓库clone到本地的文件夹
 * @param credentialsProvider 凭证
 * @return list
 * @throws GitAPIException api
 * @throws IOException     IO
 */
private static List<String> branchList(String url, File file, CredentialsProvider credentialsProvider) throws GitAPIException, IOException {
    try (Git git = initGit(url, file, credentialsProvider)) {
        //
        List<Ref> list = git.branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call();
        List<String> all = new ArrayList<>(list.size());
        list.forEach(ref -> {
            String name = ref.getName();
            if (name.startsWith(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME)) {
                all.add(name.substring((Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME).length() + 1));
            }
        });
        return all;
    } catch (TransportException t) {
        checkTransportException(t);
        throw t;
    }
}
 
Example #9
Source File: GitCredentialsProviderFactoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateForServerWithUsername() {
	CredentialsProvider provider = this.factory.createFor(HTTPS_GIT_REPO, USER,
			PASSWORD, null, false);
	assertThat(provider).isNotNull();
	assertThat(provider instanceof UsernamePasswordCredentialsProvider).isTrue();
}
 
Example #10
Source File: GitCredentialsProviderFactoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateForSshServerWithSkipSslValidation() {
	CredentialsProvider provider = this.factory.createFor(SSH_GIT_REPO, USER,
			PASSWORD, null, true);
	assertThat(provider).isNotNull();
	assertThat(provider instanceof UsernamePasswordCredentialsProvider).isTrue();
}
 
Example #11
Source File: GitCredentialsProviderFactoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateForHttpsServerWithoutSpecifyingSkipSslValidation() {
	CredentialsProvider provider = this.factory.createFor(HTTPS_GIT_REPO, USER,
			PASSWORD, null);
	assertThat(provider).isNotNull();
	assertThat(provider instanceof UsernamePasswordCredentialsProvider)
			.as("deprecated createFor() should not enable ssl validation skipping")
			.isTrue();
}
 
Example #12
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void gitCredentialsProviderFactoryCreatesSkipSslValidationProvider()
		throws Exception {
	Git mockGit = mock(Git.class);
	MockCloneCommand mockCloneCommand = new MockCloneCommand(mockGit);
	final String username = "someuser";
	final String password = "mypassword";

	JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(
			this.environment, new JGitEnvironmentProperties());
	envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand));
	envRepository.setUri("https://somegitserver/somegitrepo");
	envRepository.setBasedir(new File("./mybasedir"));
	envRepository.setUsername(username);
	envRepository.setPassword(password);
	envRepository.setSkipSslValidation(true);
	envRepository.setCloneOnStart(true);
	envRepository.afterPropertiesSet();

	CredentialsProvider provider = mockCloneCommand.getCredentialsProvider();

	assertThat(provider instanceof GitSkipSslValidationCredentialsProvider).isTrue();

	CredentialItem.Username usernameCredential = new CredentialItem.Username();
	CredentialItem.Password passwordCredential = new CredentialItem.Password();
	assertThat(provider.supports(usernameCredential)).isTrue();
	assertThat(provider.supports(passwordCredential)).isTrue();

	provider.get(new URIish(), usernameCredential);
	assertThat(username).isEqualTo(usernameCredential.getValue());
	provider.get(new URIish(), passwordCredential);
	assertThat(password).isEqualTo(String.valueOf(passwordCredential.getValue()));
}
 
Example #13
Source File: BaseMojo.java    From multi-module-maven-release-plugin with MIT License 5 votes vote down vote up
protected CredentialsProvider getCredentialsProvider(final Log log) throws ValidationException {
    if (serverId != null) {
        Server server = settings.getServer(serverId);
        if (server == null) {
            log.warn(format("No server configuration in Maven settings found with id %s", serverId));
        }
        if (server.getUsername() != null && server.getPassword() != null) {
            return new UsernamePasswordCredentialsProvider(server.getUsername(), server.getPassword());
        }
    }
    return null;
}
 
Example #14
Source File: GitCredentialsProviderFactoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateForFileWithUsername() {
	CredentialsProvider provider = this.factory.createFor(FILE_REPO, USER, PASSWORD,
			null, false);
	assertThat(provider).isNotNull();
	assertThat(provider instanceof UsernamePasswordCredentialsProvider).isTrue();
}
 
Example #15
Source File: GitCredentialsProviderFactoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateForHttpsServerWithSkipSslValidation() {
	CredentialsProvider provider = this.factory.createFor(HTTPS_GIT_REPO, USER,
			PASSWORD, null, true);
	assertThat(provider).isNotNull();
	assertThat(provider instanceof GitSkipSslValidationCredentialsProvider).isTrue();
}
 
Example #16
Source File: GitCredentialsProviderFactoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateForAwsWithUsername() {
	CredentialsProvider provider = this.factory.createFor(AWS_REPO, USER, PASSWORD,
			null, false);
	assertThat(provider).isNotNull();
	assertThat(provider instanceof AwsCodeCommitCredentialProvider).isTrue();
	AwsCodeCommitCredentialProvider aws = (AwsCodeCommitCredentialProvider) provider;
	assertThat(aws.getUsername()).isEqualTo(USER);
	assertThat(aws.getPassword()).isEqualTo(PASSWORD);
}
 
Example #17
Source File: GitCredentialsProviderFactoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateForAwsDisabled() {
	this.factory.setAwsCodeCommitEnabled(false);
	CredentialsProvider provider = this.factory.createFor(AWS_REPO, null, null, null,
			false);
	assertThat(provider).isNull();
	provider = this.factory.createFor(AWS_REPO, USER, PASSWORD, null, false);
	assertThat(provider).isNotNull();
	assertThat(provider instanceof UsernamePasswordCredentialsProvider).isTrue();
}
 
Example #18
Source File: GitCredentialsProviderFactoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreatePassphraseCredentialProvider() {
	CredentialsProvider provider = this.factory.createFor(HTTPS_GIT_REPO, null, null,
			PASSWORD, false);
	assertThat(provider).isNotNull();
	assertThat(provider instanceof PassphraseCredentialsProvider).isTrue();
}
 
Example #19
Source File: JGitConfigSessionFactory.java    From mOrgAnd with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
    session.setConfig("StrictHostKeyChecking", "no"); // TODO Find out how to enable strict host checking

    // TODO Delete me
    // String knownHostsLocation = "/sdcard/morg/known_hosts";
    // jSch.setKnownHosts(knownHostsLocation);

    CredentialsProvider provider = new JGitCredentialsProvider(username, password);
    session.setUserInfo(new CredentialsProviderUserInfo(session, provider));
}
 
Example #20
Source File: TrileadSessionFactory.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException {
    try {
        int p = uri.getPort();
        if (p<0)    p = 22;
        Connection con = new Connection(uri.getHost(), p);
        con.setTCPNoDelay(true);
        con.connect();  // TODO: host key check

        boolean authenticated;
        if (credentialsProvider instanceof SmartCredentialsProvider) {
            final SmartCredentialsProvider smart = (SmartCredentialsProvider) credentialsProvider;
            StandardUsernameCredentialsCredentialItem
                    item = new StandardUsernameCredentialsCredentialItem("Credentials for " + uri, false);
            authenticated = smart.supports(item)
                    && smart.get(uri, item)
                    && SSHAuthenticator.newInstance(con, item.getValue(), uri.getUser())
                    .authenticate(smart.listener);
        } else if (credentialsProvider instanceof CredentialsProviderImpl) {
            CredentialsProviderImpl sshcp = (CredentialsProviderImpl) credentialsProvider;

            authenticated = SSHAuthenticator.newInstance(con, sshcp.cred).authenticate(sshcp.listener);
        } else {
            authenticated = false;
        }
        if (!authenticated && con.isAuthenticationComplete())
            throw new TransportException("Authentication failure");

        return wrap(con);
    } catch (UnsupportedCredentialItem | IOException | InterruptedException e) {
        throw new TransportException(uri,"Failed to connect",e);
    }
}
 
Example #21
Source File: GitCredentialsProviderFactoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateForAwsNoUsername() {
	CredentialsProvider provider = this.factory.createFor(AWS_REPO, null, null, null,
			false);
	assertThat(provider).isNotNull();
	assertThat(provider instanceof AwsCodeCommitCredentialProvider).isTrue();
	AwsCodeCommitCredentialProvider aws = (AwsCodeCommitCredentialProvider) provider;
	assertThat(aws.getUsername()).isNull();
	assertThat(aws.getPassword()).isNull();
}
 
Example #22
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void gitCredentialsProviderFactoryCreatesUsernamePasswordProvider()
		throws Exception {
	Git mockGit = mock(Git.class);
	MockCloneCommand mockCloneCommand = new MockCloneCommand(mockGit);
	final String username = "someuser";
	final String password = "mypassword";

	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.setUsername(username);
	envRepository.setPassword(password);
	envRepository.setCloneOnStart(true);
	envRepository.afterPropertiesSet();

	assertTrue(mockCloneCommand
			.getCredentialsProvider() instanceof UsernamePasswordCredentialsProvider);

	CredentialsProvider provider = mockCloneCommand.getCredentialsProvider();
	CredentialItem.Username usernameCredential = new CredentialItem.Username();
	CredentialItem.Password passwordCredential = new CredentialItem.Password();
	assertThat(provider.supports(usernameCredential)).isTrue();
	assertThat(provider.supports(passwordCredential)).isTrue();

	provider.get(new URIish(), usernameCredential);
	assertThat(username).isEqualTo(usernameCredential.getValue());
	provider.get(new URIish(), passwordCredential);
	assertThat(password).isEqualTo(String.valueOf(passwordCredential.getValue()));
}
 
Example #23
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void gitCredentialsProviderFactoryCreatesPassphraseProvider()
		throws Exception {
	final String passphrase = "mypassphrase";
	final String gitUri = "git+ssh://git@somegitserver/somegitrepo";
	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(gitUri);
	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 #24
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 #25
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void usernamePasswordShouldSetCredentials() throws Exception {
	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"));
	final String username = "someuser";
	final String password = "mypassword";
	envRepository.setUsername(username);
	envRepository.setPassword(password);
	envRepository.setCloneOnStart(true);
	envRepository.afterPropertiesSet();

	assertTrue(mockCloneCommand
			.getCredentialsProvider() instanceof UsernamePasswordCredentialsProvider);

	CredentialsProvider provider = mockCloneCommand.getCredentialsProvider();
	CredentialItem.Username usernameCredential = new CredentialItem.Username();
	CredentialItem.Password passwordCredential = new CredentialItem.Password();
	assertThat(provider.supports(usernameCredential)).isTrue();
	assertThat(provider.supports(passwordCredential)).isTrue();

	provider.get(new URIish(), usernameCredential);
	assertThat(username).isEqualTo(usernameCredential.getValue());
	provider.get(new URIish(), passwordCredential);
	assertThat(password).isEqualTo(String.valueOf(passwordCredential.getValue()));
}
 
Example #26
Source File: JGitEnvironmentRepository.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
private void configureCommand(TransportCommand<?, ?> command) {
	command.setTimeout(this.timeout);
	if (this.transportConfigCallback != null) {
		command.setTransportConfigCallback(this.transportConfigCallback);
	}
	CredentialsProvider credentialsProvider = getCredentialsProvider();
	if (credentialsProvider != null) {
		command.setCredentialsProvider(credentialsProvider);
	}
}
 
Example #27
Source File: GitMonitoringService.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private TransportConfigCallback buildTransportConfigCallback() {
  if (this.providerSessionFactoryEither instanceof Either.Left) return null;

  SshSessionFactory sshSessionFactory = ((Either.Right<CredentialsProvider, SshSessionFactory>) this.providerSessionFactoryEither).getRight();
  return transport -> {
    SshTransport sshTransport = (SshTransport) transport;
    sshTransport.setSshSessionFactory(sshSessionFactory);
  };
}
 
Example #28
Source File: GitMonitoringService.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Create an object to manage the git repository stored locally at repoDir with a repository URI of repoDir
 * @param repoUri URI of repository
 * @param repoDir Directory to hold the local copy of the repository
 * @param branchName Branch name
 * @param providerSessionFactoryEither Either {@link UsernamePasswordCredentialsProvider} or {@link SshSessionFactory}
 * @param shouldCheckpointHashes a boolean to determine whether to checkpoint commit hashes
 * @throws GitAPIException
 * @throws IOException
 */
GitRepository(String repoUri, String repoDir, String branchName, Either<CredentialsProvider, SshSessionFactory>
    providerSessionFactoryEither, boolean shouldCheckpointHashes) throws GitAPIException, IOException {
  this.repoUri = repoUri;
  this.repoDir = repoDir;
  this.branchName = branchName;
  this.providerSessionFactoryEither = providerSessionFactoryEither;
  this.shouldCheckpointHashes = shouldCheckpointHashes;

  initRepository();
}
 
Example #29
Source File: TutorialPublishTask.java    From aeron with Apache License 2.0 5 votes vote down vote up
@TaskAction
public void publish() throws Exception
{
    final String wikiUri = getWikiUri();
    final File directory = new File(getProject().getBuildDir(), "tmp/tutorialPublish");
    // Use Personal Access Token or GITHUB_TOKEN for workflows
    final CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(apiKey, "");

    final Git git = Git.cloneRepository()
        .setURI(wikiUri)
        .setCredentialsProvider(credentialsProvider)
        .setDirectory(directory)
        .call();

    final File[] asciidocFiles = AsciidocUtil.filterAsciidocFiles(source);
    System.out.println("Publishing from: " + source);
    System.out.println("Found files: " + Arrays.stream(asciidocFiles).map(File::getName).collect(joining(", ")));

    for (final File asciidocFile : asciidocFiles)
    {
        Files.copy(
            asciidocFile.toPath(),
            new File(directory, asciidocFile.getName()).toPath(),
            StandardCopyOption.REPLACE_EXISTING);
    }

    git.add().addFilepattern(".").setUpdate(false).call();
    git.commit().setMessage("Update Docs").call();

    System.out.println("Publishing to: " + wikiUri);

    git.push().setCredentialsProvider(credentialsProvider).call();
}
 
Example #30
Source File: GitOperations.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
private void cherryPickCommitToBranch(ObjectId id, Project project, Branch branch) {

		doWithGit(project, git -> {

			try {
				checkout(project, branch);
			} catch (RuntimeException o_O) {

				logger.warn(project, "Couldn't check out branch %s. Skipping cherrypick of commit %s.", branch, id.getName());
				return;
			}

			logger.log(project, "git cp %s", id.getName());

			// Required as the CherryPick command has no setter for a CredentialsProvide *sigh*
			if (gpg.isGpgAvailable()) {
				CredentialsProvider.setDefault(new GpgPassphraseProvider(gpg));
			}

			CherryPickResult result = git.cherryPick().include(id).call();

			if (result.getStatus().equals(CherryPickStatus.OK)) {
				logger.log(project, "Successfully cherry-picked commit %s to branch %s.", id.getName(), branch);
			} else {
				logger.warn(project, "Cherry pick failed. aborting…");
				logger.log(project, "git reset --hard");
				git.reset().setMode(ResetType.HARD).call();
			}
		});
	}