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.debug("cloneRepo took " + watch.taken()); } }
@Override public File clone(String branch, boolean noCheckout) throws GitException { checkGitUrl(); CloneCommand cloneCommand = Git.cloneRepository() .setURI(gitUrl) .setNoCheckout(noCheckout) .setBranch(branch) .setDirectory(targetDir.toFile()); try (Git git = buildCommand(cloneCommand).call()) { return git.getRepository().getDirectory(); } catch (GitAPIException e) { throw new GitException("Fail to clone git repo", e); } }
public boolean cloneRepo( String directory, String uri ) { CloneCommand cmd = Git.cloneRepository(); cmd.setDirectory( new File( directory ) ); cmd.setURI( uri ); cmd.setCredentialsProvider( credentialsProvider ); try { Git git = cmd.call(); git.close(); return true; } catch ( Exception e ) { if ( ( e instanceof TransportException ) && ( ( e.getMessage().contains( "Authentication is required but no CredentialsProvider has been registered" ) || e.getMessage().contains( "not authorized" ) ) ) ) { if ( promptUsernamePassword() ) { return cloneRepo( directory, uri ); } } else { showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), e.getMessage() ); } } return false; }
/** * Asserts that we can git clone the given repository */ public static Git assertGitCloneRepo(String cloneUrl, File outputFolder) throws GitAPIException, IOException { LOG.info("Cloning git repo: " + cloneUrl + " to folder: " + outputFolder); Files.recursiveDelete(outputFolder); outputFolder.mkdirs(); CloneCommand command = Git.cloneRepository(); command = command.setCloneAllBranches(false).setURI(cloneUrl).setDirectory(outputFolder).setRemote("origin"); Git git; try { git = command.call(); } catch (Exception e) { LOG.error("Failed to git clone remote repo " + cloneUrl + " due: " + e.getMessage(), e); throw e; } return git; }
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()); } }
/** * * Clones a git repository using the given uri and stores it in the parent directory. Checks out the * given reference or (if value is null) does not check out a branch * (which reduces time needed to complete command). * @param cloneURI the uri to the remote repository * @param parentDirectory the directory in which to store the git meta directory (".git" directory) * @param checkoutRef the ref name ("refs/heads/master"), branch name ("master") or tag name ("v1.2.3"). If * {@code null} is passed, will not checkout a branch. * @param branchesToClone the branches to clone or all branches if passed a {@code null} value. * @param monitor reports the progress of the clone command; can be null * @return the cloned Git repository * @throws GitAPIException */ public static Git cloneRepo(String cloneURI, File parentDirectory, String remoteName, String checkoutRef, List<String> branchesToClone, ProgressMonitor monitor) throws GitAPIException { CloneCommand clone = Git.cloneRepository(); if (checkoutRef == null) { clone.setNoCheckout(true); } else { clone.setBranch(checkoutRef); } if (branchesToClone == null) { clone.setCloneAllBranches(true); } else { clone.setBranchesToClone(branchesToClone); } if (monitor != null) { clone.setProgressMonitor(monitor); } return clone .setURI(cloneURI) .setDirectory(parentDirectory) .setRemote(remoteName) .call(); }
@Override public String fetchMaterial(FetchMaterialTask task) { String errorMessage = null; String materialPath = Paths.get(AgentConfiguration.getInstallInfo().getAgentPipelinesDir(), task.getPipelineName(), task.getDestination()).toString(); GitMaterial definition = (GitMaterial) task.getMaterialDefinition(); CloneCommand clone = Git.cloneRepository(); clone.setURI(definition.getRepositoryUrl()); clone.setBranch(definition.getBranch()); clone.setDirectory(new File(materialPath)); clone.setCloneSubmodules(true); UsernamePasswordCredentialsProvider credentials = this.handleCredentials(definition); clone.setCredentialsProvider(credentials); try { Git git = clone.call(); git.close(); } catch (GitAPIException e) { errorMessage = e.getMessage(); } return errorMessage; }
/** * Clones repository, which is defined by provided repository URI. * * @param repositoryName into which repository * @param cloneUrl url of cloned repository * @param username for get access to clone * @param password for get access to clone */ public void clone(String repositoryName, String cloneUrl, String username, String password) { RepositoryContext repositoryContext = repositoryByName.get(repositoryName); try { CloneCommand cloneCommand = Git.cloneRepository(); cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password)); cloneCommand.setURI(cloneUrl); cloneCommand.setDirectory(repositoryContext.repository.getDirectory().getParentFile()); cloneCommand.call(); } catch (GitAPIException e) { throw new RuntimeException(e); } }
public static void cloneRepo(File projectFolder, String cloneUrl, CredentialsProvider credentialsProvider, final File sshPrivateKey, final File sshPublicKey, String remote) { // clone the repo! boolean cloneAll = false; LOG.info("Cloning git repo " + cloneUrl + " into directory " + projectFolder.getAbsolutePath()); CloneCommand command = Git.cloneRepository(); GitHelpers.configureCommand(command, credentialsProvider, sshPrivateKey, sshPublicKey); command = command.setCredentialsProvider(credentialsProvider). setCloneAllBranches(cloneAll).setURI(cloneUrl).setDirectory(projectFolder).setRemote(remote); try { command.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()); } }
/** * Creates a repository on GitHub and in a local temporary directory. This is a one time operation as * once it is created on GitHub and locally it cannot be recreated. */ public File createGitRepository(String repositoryName) throws IOException { RepositoryService service = new RepositoryService(); service.getClient().setOAuth2Token(oAuthToken); Repository repository = new Repository(); repository.setName(repositoryName); repository = service.createRepository(repository); repositoryLocation = repository.getHtmlUrl(); CloneCommand cloneCommand = Git.cloneRepository() .setURI(repository.getCloneUrl()) .setDirectory(localGitDirectory); addAuth(cloneCommand); try { localRepository = cloneCommand.call(); } catch (GitAPIException e) { throw new IOException("Error cloning to local file system", e); } return localGitDirectory; }
private static boolean cloneRepo(TargetCommit cloneCommit, String customCommit) { CloneCommand cloneCommand = new CloneCommand() .setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out))) .setDirectory(new File(ROOT_DIR)) .setURI("https://github.com/SpongePowered/SpongeVanilla.git") .setBranchesToClone(Collections.singleton("refs/heads/master")) .setBranch("refs/heads/master") .setCloneSubmodules(true); try { Git git = cloneCommand.call(); if (cloneCommit == TargetCommit.CUSTOM) { git.checkout().setName(customCommit).call(); git.submoduleInit().call(); git.submoduleUpdate().setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out))).call(); } return true; } catch (GitAPIException e) { e.printStackTrace(); } return false; }
@Override public void doImport(ProgressMonitor progress) throws GitCloneFailedException, GitDestinationAlreadyExistsException, GitDestinationNotWritableException { CloneCommand clone = new CloneCommand(); clone.setCredentialsProvider(getRepository().getCredentialsProvider()); String sourceUri = getSourceUri(); clone.setURI(sourceUri); clone.setBare(true); clone.setDirectory(destinationDirectory); if (progress != null) { clone.setProgressMonitor(progress); } try { LOG.info(sourceUri + "| Clone into " + destinationDirectory); clone.call(); } catch (Throwable e) { throw new GitCloneFailedException(sourceUri, e); } }
@Override public void to(Path path) throws Git.Err { LOG.info(() -> String.format("Cloning %s into %s...", url, path.toString())); CloneCommand cloner = org.eclipse.jgit.api.Git.cloneRepository() .setURI(url) .setCredentialsProvider(new GitCredentialsProvider( CredentialHandlers.handlerMap() )) .setProgressMonitor( enableOutput ? new TextProgressMonitor() : NullProgressMonitor.INSTANCE ) .setDirectory(path.toFile()); branchName.ifPresent(cloner::setBranch); try { cloner.call(); } catch (GitAPIException e) { throw new Git.Err(url, path.toString(), e); } }
private Git cloneTargetRepository() { File path = calculateRepositoryStoragePath(request); if(!path.mkdirs()) { throw new RuntimeException("Could not create path " + path); } notifier.message("Cloning repository from GitHub " + request.getTarget().toHttpsURL()); CloneCommand command = Git.cloneRepository() .setBranch(request.getTarget().getBranch()) .setCloneAllBranches(true) .setDirectory(path) .setURI(request.getTarget().toHttpsURL()) .setProgressMonitor(new NotificationProgressMonitor(request, notification, progress)); try { return command.call(); } catch(Exception e) { notifier.message("Failed to clone repository " + e.getMessage()); throw new RuntimeException("Could not clone source repository " + request.getTarget().toHttpsURL(), e); } }
protected synchronized void cloneRemote(Consumer<String> logger) { logger.accept(format("[git] Cloning %s", repository.getRemote())); try { new CloneCommand() .setCredentialsProvider(credentialsProvider) .setDirectory(repositoryDir) .setURI(repository.getRemote()) .call(); } catch (GitAPIException e) { throw new GitRepositoryAPIException(repository.getRemote(), e); } // Check if (!isClonedOrCloning()) { throw new GitRepositoryCannotCloneException(repository.getRemote()); } // Done logger.accept(format("[git] Clone done for %s", repository.getRemote())); }
@Test public void afterPropertiesSet_CloneOnStartTrueWithFileURL_CloneAndFetchNotCalled() throws Exception { Git mockGit = mock(Git.class); CloneCommand mockCloneCommand = mock(CloneCommand.class); when(mockCloneCommand.setURI(anyString())).thenReturn(mockCloneCommand); when(mockCloneCommand.setDirectory(any(File.class))).thenReturn(mockCloneCommand); JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment); envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand)); envRepository.setUri("file://somefilesystem/somegitrepo"); envRepository.setCloneOnStart(true); envRepository.afterPropertiesSet(); verify(mockCloneCommand, times(0)).call(); verify(mockGit, times(0)).fetch(); }
@Test public void shouldDeleteBaseDirWhenCloneFails() throws Exception { Git mockGit = mock(Git.class); CloneCommand mockCloneCommand = mock(CloneCommand.class); when(mockCloneCommand.setURI(anyString())).thenReturn(mockCloneCommand); when(mockCloneCommand.setDirectory(any(File.class))).thenReturn(mockCloneCommand); when(mockCloneCommand.call()).thenThrow(new TransportException("failed to clone")); JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment); envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand)); envRepository.setUri("http://somegitserver/somegitrepo"); envRepository.setBasedir(this.basedir); try { envRepository.findOne("bar", "staging", "master"); } catch (Exception ex) { // expected - ignore } assertFalse("baseDir should be deleted when clone fails", this.basedir.listFiles().length>0); }
@Test public void shouldSetTransportConfigCallbackOnCloneAndFetch() throws Exception { Git mockGit = mock(Git.class); FetchCommand fetchCommand = mock(FetchCommand.class); when(mockGit.fetch()).thenReturn(fetchCommand); when(fetchCommand.call()).thenReturn(mock(FetchResult.class)); CloneCommand mockCloneCommand = mock(CloneCommand.class); when(mockCloneCommand.setURI(anyString())).thenReturn(mockCloneCommand); when(mockCloneCommand.setDirectory(any(File.class))).thenReturn(mockCloneCommand); TransportConfigCallback configCallback = mock(TransportConfigCallback.class); JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment); envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand)); envRepository.setUri("http://somegitserver/somegitrepo"); envRepository.setTransportConfigCallback(configCallback); envRepository.setCloneOnStart(true); envRepository.afterPropertiesSet(); verify(mockCloneCommand, times(1)).setTransportConfigCallback(configCallback); envRepository.fetch(mockGit, "master"); verify(fetchCommand, times(1)).setTransportConfigCallback(configCallback); }
public Git call(final GitOperationsStep gitOperationsStep, Git git, CredentialsProvider cp, String gitRepoUrl, File gitRepoFolder) throws InvalidRemoteException, TransportException, GitAPIException { CloneCommand cc = Git.cloneRepository().setURI(gitRepoUrl) .setDirectory(gitRepoFolder); if (!Const.isEmpty(this.branchName)) { cc = cc.setBranch(gitOperationsStep .environmentSubstitute(this.branchName)); } cc.setCloneAllBranches(this.cloneAllBranches).setCloneSubmodules( this.cloneSubModules); if (cp != null) { cc.setCredentialsProvider(cp); } return cc.setBare(false).call(); }
private void createNewRepo(ProgressMonitor monitor) throws GitAPIException, IllegalArgumentException { File localRepo = new File(localPath); if (localRepo.exists()) // Safety check so we don't accidentally delete directory throw new IllegalStateException("Directory already exists"); try { CloneCommand cloneCommand = Git.cloneRepository() .setCredentialsProvider(credentialsProvider) .setURI(remotePath) .setBranch(branch) .setDirectory(localRepo) .setBare(false); if (monitor != null) cloneCommand.setProgressMonitor(monitor); cloneCommand.call(); } catch (GitAPIException e) { FileUtils.deleteDirectory(localRepo); throw e; } }
@Override public void refreshRepo() throws RotationLoadException, IOException { try { if (git == null) { if (new File(getPath() + File.separator + ".git").exists()) this.git = Git.open(new File(getPath())); else this.git = ((CloneCommand) addCredentials( Git.cloneRepository().setURI(gitUrl.toString()).setDirectory(new File(getPath())))).call(); } git.clean().call(); addCredentials(git.fetch()).call(); git.reset().setRef("@{upstream}").setMode(ResetCommand.ResetType.HARD).call(); } catch (GitAPIException e) { e.printStackTrace(); throw new RotationLoadException("Could not load git repository: " + gitUrl); } super.refreshRepo(); }
@Test public void testAnonymousClone() throws Exception { GitBlitSuite.close(ticgitFolder); if (ticgitFolder.exists()) { FileUtils.delete(ticgitFolder, FileUtils.RECURSIVE | FileUtils.RETRY); } // set push restriction RepositoryModel model = GitBlit.self().getRepositoryModel("ticgit.git"); model.accessRestriction = AccessRestrictionType.PUSH; model.authorizationControl = AuthorizationControl.NAMED; GitBlit.self().updateRepositoryModel(model.name, model, false); CloneCommand clone = Git.cloneRepository(); clone.setURI(MessageFormat.format("{0}/ticgit.git", url)); clone.setDirectory(ticgitFolder); clone.setBare(false); clone.setCloneAllBranches(true); GitBlitSuite.close(clone.call()); assertTrue(true); // restore anonymous repository access model.accessRestriction = AccessRestrictionType.NONE; model.authorizationControl = AuthorizationControl.NAMED; GitBlit.self().updateRepositoryModel(model.name, model, false); }
@Test public void testClone() throws Exception { GitBlitSuite.close(ticgitFolder); if (ticgitFolder.exists()) { FileUtils.delete(ticgitFolder, FileUtils.RECURSIVE | FileUtils.RETRY); } CloneCommand clone = Git.cloneRepository(); clone.setURI(MessageFormat.format("{0}/ticgit.git", url)); clone.setDirectory(ticgitFolder); clone.setBare(false); clone.setCloneAllBranches(true); clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password)); GitBlitSuite.close(clone.call()); assertTrue(true); }
private void execute() throws InvalidRemoteException, TransportException, GitAPIException, IOException { setProxy(); CloneCommand cmd = Git.cloneRepository() .setURI(config.getRemoteUrl()); if (config.getLocalPath() != "") { cmd.setDirectory(new File(config.getLocalPath())); } Git git = cmd.call(); // Set proxy setting to repository config. StoredConfig gitConfig = git.getRepository().getConfig(); gitConfig.setString("remote", "origin", "proxy", config.getProxyAddress()); gitConfig.save(); git.getRepository().close(); }
public Git cloneRepo(CloneRepoAttributes attributes) throws GitAPIException { CloneCommand command = Git.cloneRepository(); String gitUri = attributes.getUri(); UserDetails userDetails = attributes.getUserDetails(); CredentialsProvider credentialsProvider = userDetails.createCredentialsProvider(); GitUtils.configureCommand(command, credentialsProvider, userDetails.getSshPrivateKey(), userDetails.getSshPublicKey()); command = command.setCredentialsProvider(credentialsProvider). setCloneAllBranches(attributes.isCloneAll()). setURI(gitUri). setDirectory(attributes.getDirectory()).setRemote(attributes.getRemote()); return command.call(); }
@Ignore @Test public void simple_checkout_with_authentication() throws Exception { File outputFolder = new File( baseLocation + "testGitWithPassword" ); FileUtils.deleteDirectory( outputFolder ); String authGitUrl = "https://stash-eng.yourcompany.com/sjc/shared/1/scm/eed/csap.git"; String userid = "someDeveloper"; String pass = "FIXME"; assertThat( pass ).isNotEqualTo( "FIXME" ).as( "Update the password" ); String message = "Perform git checkout of " + authGitUrl + " to destination: " + outputFolder.getAbsolutePath(); logger.info(Boot_Container_Test.TC_HEAD + message ); CloneCommand cloneCommand = Git.cloneRepository() .setURI( authGitUrl ) .setDirectory( outputFolder ) .setCredentialsProvider( new UsernamePasswordCredentialsProvider( userid, pass ) ); cloneCommand.call(); File buildPom = new File( outputFolder + "/BootReference/pom.xml" ); assertThat( buildPom ) .as( "Pom file found" ) .exists().isFile(); }
@Ignore @Test public void simple_checkout_with_subFolder() throws Exception { File outputFolder = new File( baseLocation + "testGitWithSubFolder" ); FileUtils.deleteDirectory( outputFolder ); String authGitUrl = "https://stash-eng.yourcompany.com/sjc/shared/1/scm/eed/csap.git"; String userid = "someDeveloper"; String pass = "FIXME"; assertThat( "jgit support for folders" ).isEqualTo( "false" ).as( "not supported" ); assertThat( pass ).isNotEqualTo( "FIXME" ).as( "Update the password" ); String message = "Perform git checkout of " + authGitUrl + " to destination: " + outputFolder.getAbsolutePath(); logger.info(Boot_Container_Test.TC_HEAD + message ); CloneCommand cloneCommand = Git.cloneRepository() .setURI( authGitUrl ) .setDirectory( outputFolder ) .setCredentialsProvider( new UsernamePasswordCredentialsProvider( userid, pass ) ); Git gitRepo = cloneCommand.setNoCheckout( true ).call(); gitRepo.checkout().setStartPoint( "master").call(); gitRepo.getRepository().close(); File buildPom = new File( outputFolder + "/pom.xml" ); assertThat( buildPom ) .as( "Pom file found" ) .exists().isFile(); }
private Git cloneToBasedir(URI projectUrl, File destinationFolder) throws GitAPIException { CloneCommand command = this.gitFactory.getCloneCommandByCloneRepository() .setURI(projectUrl.toString() + ".git").setDirectory(destinationFolder); try { return command.call(); } catch (GitAPIException e) { deleteBaseDirIfExists(); throw e; } }
/** * 从指定的git仓库地址(目前仅支持http和https)和文件名获取资源,通过UsernameCredential支持鉴权 * @return 资源的字符串 * @throws Exception 资源不存在或网络不通 */ @Override public String load() throws Exception { //本地临时目录,用户存放clone的代码 String tempDirPath = localPath + "/iaac.aliyun.tmp_" + new Date().getTime(); File tempDir = new File(tempDirPath); tempDir.mkdirs(); String result = null; try { CloneCommand clone = Git.cloneRepository(); clone.setURI(url); clone.setBranch(this.branch); clone.setDirectory(tempDir); //设置鉴权 if (this.credential != null) { UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider = new UsernamePasswordCredentialsProvider(this.credential.getUsername(), this.credential.getPassword()); //git仓库地址 clone.setCredentialsProvider(usernamePasswordCredentialsProvider); } //执行clone Git git = clone.call(); //从本地路径中获取指定的文件 File file = new File(tempDir.getAbsolutePath() + "/" + this.fileName); //返回文件的字符串 result = FileUtils.readFileToString(file, "utf-8"); } catch (Exception e) { throw e; } finally { //清除本地的git临时目录 FileUtils.deleteDirectory(tempDir); } return result; }
/** * Clone code to folder * * @param gitUrl * @param targetDir * @return * @throws GitException */ public static Path clone(String gitUrl, Path targetDir) throws GitException { CloneCommand cloneCommand = Git.cloneRepository() .setURI(gitUrl) .setDirectory(targetDir.toFile()); try (Git ignored = cloneCommand.call()) { return targetDir; } catch (GitAPIException e) { throw new GitException("Fail to clone git repo", e); } }
public static boolean cloneRepo(final String uri, final File cloneTo, final String branch, final GitCloneProgressCallback callback) { Git result = null; try { final CloneCommand clone = Git.cloneRepository() .setURI(uri).setDirectory(cloneTo) .setBare(false).setRemote(REMOTE_NAME).setNoCheckout(false) .setCloneAllBranches(false).setCloneSubmodules(false) .setProgressMonitor(callback); if (!branch.isEmpty()) { if (branch.contains("/")) { clone.setBranch(branch.substring(branch.lastIndexOf('/') + 1)); } else { clone.setBranch(branch); } } result = clone.call(); return true; } catch (GitAPIException e) { e.printStackTrace(); } finally { if (result != null) { result.close(); } } return false; }
/** * Clones a git repository using the given uri and stores it in the parent directory. Checks out the branch * to which the remote HEAD currently points. * @param cloneURI the uri to the remote repository * @param parentDirectory the directory in which to store the git meta directory (".git" directory) * @return the cloned Git repository * @throws GitAPIException */ public static Git cloneRepo(String cloneURI, File parentDirectory) throws GitAPIException { CloneCommand clone = Git.cloneRepository(); return Git.cloneRepository() // essential .setURI(cloneURI) // essential .setDirectory(parentDirectory) // parent directory to store git dir .call(); }
/** * Clones a git repository using the given uri and stores it in the parent directory. Checks out the * given reference or (if value is null) does not check out a branch * (which reduces time needed to complete command). * @param cloneURI the uri to the remote repository * @param parentDirectory the directory in which to store the git meta directory (".git" directory) * @param checkoutRef the ref name ("refs/heads/master"), branch name ("master") or tag name ("v1.2.3"). If * {@code null} is passed, will not checkout a branch. * @return the clones Git repository * @throws GitAPIException */ public static Git cloneRepo(String cloneURI, File parentDirectory, String checkoutRef) throws GitAPIException { CloneCommand clone = Git.cloneRepository(); if (checkoutRef == null) { clone.setNoCheckout(true); } else { clone.setBranch(checkoutRef); } return clone .setURI(cloneURI) .setDirectory(parentDirectory) .call(); }
public void cloneRepo(String branch) throws Exception { CloneCommand cloneCommand = Git.cloneRepository().setURI(repositoryUrl).setDirectory(localRepo.getDirectory().getParentFile()); if (branch != null) cloneCommand.setBranch(branch); if (credentialsProvider != null) cloneCommand.setCredentialsProvider(credentialsProvider); cloneCommand.call(); }
/** * In lieu of sparse checkout since it's not yet supported in JGit: * https://bugs.eclipse.org/bugs/show_bug.cgi?id=383772 */ public void cloneNoCheckout(boolean withProgress) throws Exception { CloneCommand clone = Git.cloneRepository().setURI(repositoryUrl).setDirectory(localRepo.getDirectory().getParentFile()).setNoCheckout(true); // https://bugs.eclipse.org/bugs/show_bug.cgi?id=442029 if (credentialsProvider != null) clone.setCredentialsProvider(credentialsProvider); if (withProgress) clone.setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out))); clone.call(); }
private Git clone(Pom pom, GitDependency dependency) throws MojoExecutionException { final CloneCommand c = new CloneCommand(); final String location = dependency.getLocation(); c.setURI(location); c.setCloneAllBranches(true); c.setProgressMonitor(new TextProgressMonitor()); final GitDependencyHandler dependencyHandler = new GitDependencyHandler(dependency); final String version = dependencyHandler.getDependencyVersion(pom); final String tempDirectory = Directory.getTempDirectoryString(location, version); c.setDirectory(new File(tempDirectory)); return c.call(); }
private File clonarRepositorio(File caminhoLocal) throws GitAPIException { log.debug("Clonando repositório de cartas de serviço de {} para {}", urlRepositorio, caminhoLocal); CloneCommand clone = Git.cloneRepository() .setURI(urlRepositorio) .setProgressMonitor(new LogstashProgressMonitor(log)) .setDirectory(caminhoLocal); try (Git repositorio = clone.call()) { String head = repositorio.log().call().iterator().next().getName(); log.info("Repositório de cartas de serviço clonado na versão {}", head); return repositorio.getRepository().getWorkTree(); } }
/** * Clones the repository into the desired folder and returns * the JGit Repository object. * * @throws GitAPIException if the `git clone` call fails. */ protected void obtainRepository(String remoteURL) throws GitAPIException, IOException, CancelledAuthorizationException { CloneCommand cloneCommand = Git.cloneRepository(); cloneCommand.setURI(remoteURL); myWrapAuthentication(cloneCommand); File destination = this.localPath.toFile(); cloneCommand.setDirectory(destination); Git cloneCall = cloneCommand.call(); cloneCall.close(); repo = cloneCall.getRepository(); setup(); }