List of usage examples for org.eclipse.jgit.api Git cloneRepository
public static CloneCommand cloneRepository()
From source file:org.apache.gobblin.service.modules.flow.MultiHopFlowCompilerTest.java
License:Apache License
@Test(dependsOnMethods = "testMulticastPath") public void testGitFlowGraphMonitorService() throws IOException, GitAPIException, URISyntaxException, InterruptedException { File remoteDir = new File(TESTDIR + "/remote"); File cloneDir = new File(TESTDIR + "/clone"); File flowGraphDir = new File(cloneDir, "/gobblin-flowgraph"); //Clean up/* w ww. j a v a2 s. c o m*/ cleanUpDir(TESTDIR); // Create a bare repository RepositoryCache.FileKey fileKey = RepositoryCache.FileKey.exact(remoteDir, FS.DETECTED); Repository remoteRepo = fileKey.open(false); remoteRepo.create(true); Git gitForPush = Git.cloneRepository().setURI(remoteRepo.getDirectory().getAbsolutePath()) .setDirectory(cloneDir).call(); // push an empty commit as a base for detecting changes gitForPush.commit().setMessage("First commit").call(); RefSpec masterRefSpec = new RefSpec("master"); gitForPush.push().setRemote("origin").setRefSpecs(masterRefSpec).call(); URI flowTemplateCatalogUri = this.getClass().getClassLoader().getResource("template_catalog").toURI(); Config config = ConfigBuilder.create() .addPrimitive( GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_REPO_URI, remoteRepo.getDirectory().getAbsolutePath()) .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_REPO_DIR, TESTDIR + "/git-flowgraph") .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_POLLING_INTERVAL, 5) .addPrimitive(ServiceConfigKeys.TEMPLATE_CATALOGS_FULLY_QUALIFIED_PATH_KEY, flowTemplateCatalogUri.toString()) .build(); //Create a MultiHopFlowCompiler instance specCompiler = new MultiHopFlowCompiler(config, Optional.absent(), false); specCompiler.setActive(true); //Ensure node1 is not present in the graph Assert.assertNull(specCompiler.getFlowGraph().getNode("node1")); // push a new node file File nodeDir = new File(flowGraphDir, "node1"); File nodeFile = new File(nodeDir, "node1.properties"); nodeDir.mkdirs(); nodeFile.createNewFile(); Files.write(FlowGraphConfigurationKeys.DATA_NODE_IS_ACTIVE_KEY + "=true\nparam1=val1" + "\n", nodeFile, Charsets.UTF_8); // add, commit, push node gitForPush.add().addFilepattern(formNodeFilePath(flowGraphDir, nodeDir.getName(), nodeFile.getName())) .call(); gitForPush.commit().setMessage("Node commit").call(); gitForPush.push().setRemote("origin").setRefSpecs(masterRefSpec).call(); // polling is every 5 seconds, so wait twice as long and check TimeUnit.SECONDS.sleep(10); //Test that a DataNode is added to FlowGraph DataNode dataNode = specCompiler.getFlowGraph().getNode("node1"); Assert.assertEquals(dataNode.getId(), "node1"); Assert.assertEquals(dataNode.getRawConfig().getString("param1"), "val1"); }
From source file:org.apache.maven.scm.provider.git.jgit.command.checkout.JGitCheckOutCommand.java
License:Apache License
/** * For git, the given repository is a remote one. We have to clone it first if the working directory does not * contain a git repo yet, otherwise we have to git-pull it. * <p/>//from w w w . j a va 2s .c om * {@inheritDoc} */ protected CheckOutScmResult executeCheckOutCommand(ScmProviderRepository repo, ScmFileSet fileSet, ScmVersion version, boolean recursive) throws ScmException { GitScmProviderRepository repository = (GitScmProviderRepository) repo; if (GitScmProviderRepository.PROTOCOL_FILE.equals(repository.getFetchInfo().getProtocol()) && repository.getFetchInfo().getPath().indexOf(fileSet.getBasedir().getPath()) >= 0) { throw new ScmException("remote repository must not be the working directory"); } Git git = null; try { ProgressMonitor monitor = JGitUtils.getMonitor(getLogger()); String branch = version != null ? version.getName() : null; if (StringUtils.isBlank(branch)) { branch = Constants.MASTER; } getLogger().debug("try checkout of branch: " + branch); if (!fileSet.getBasedir().exists() || !(new File(fileSet.getBasedir(), ".git").exists())) { if (fileSet.getBasedir().exists()) { // git refuses to clone otherwise fileSet.getBasedir().delete(); } // FIXME only if windauze WindowCacheConfig cfg = new WindowCacheConfig(); cfg.setPackedGitMMAP(false); cfg.install(); // no git repo seems to exist, let's clone the original repo CredentialsProvider credentials = JGitUtils.getCredentials((GitScmProviderRepository) repo); getLogger().info("cloning [" + branch + "] to " + fileSet.getBasedir()); CloneCommand command = Git.cloneRepository().setURI(repository.getFetchUrl()); command.setCredentialsProvider(credentials).setBranch(branch).setDirectory(fileSet.getBasedir()); command.setProgressMonitor(monitor); git = command.call(); } JGitRemoteInfoCommand remoteInfoCommand = new JGitRemoteInfoCommand(); remoteInfoCommand.setLogger(getLogger()); RemoteInfoScmResult result = remoteInfoCommand.executeRemoteInfoCommand(repository, fileSet, null); if (git == null) { git = Git.open(fileSet.getBasedir()); } if (fileSet.getBasedir().exists() && new File(fileSet.getBasedir(), ".git").exists() && result.getBranches().size() > 0) { // git repo exists, so we must git-pull the changes CredentialsProvider credentials = JGitUtils.prepareSession(getLogger(), git, repository); if (version != null && StringUtils.isNotEmpty(version.getName()) && (version instanceof ScmTag)) { // A tag will not be pulled but we only fetch all the commits from the upstream repo // This is done because checking out a tag might not happen on the current branch // but create a 'detached HEAD'. // In fact, a tag in git may be in multiple branches. This occurs if // you create a branch after the tag has been created getLogger().debug("fetch..."); git.fetch().setCredentialsProvider(credentials).setProgressMonitor(monitor).call(); } else { getLogger().debug("pull..."); git.pull().setCredentialsProvider(credentials).setProgressMonitor(monitor).call(); } } Set<String> localBranchNames = JGitBranchCommand.getShortLocalBranchNames(git); if (version instanceof ScmTag) { getLogger().info("checkout tag [" + branch + "] at " + fileSet.getBasedir()); git.checkout().setName(branch).call(); } else if (localBranchNames.contains(branch)) { getLogger().info("checkout [" + branch + "] at " + fileSet.getBasedir()); git.checkout().setName(branch).call(); } else { getLogger().info("checkout remote branch [" + branch + "] at " + fileSet.getBasedir()); git.checkout().setName(branch).setCreateBranch(true) .setStartPoint(Constants.DEFAULT_REMOTE_NAME + "/" + branch).call(); } RevWalk revWalk = new RevWalk(git.getRepository()); RevCommit commit = revWalk.parseCommit(git.getRepository().resolve(Constants.HEAD)); revWalk.release(); final TreeWalk walk = new TreeWalk(git.getRepository()); walk.reset(); // drop the first empty tree, which we do not need here walk.setRecursive(true); walk.addTree(commit.getTree()); List<ScmFile> listedFiles = new ArrayList<ScmFile>(); while (walk.next()) { listedFiles.add(new ScmFile(walk.getPathString(), ScmFileStatus.CHECKED_OUT)); } walk.release(); getLogger().debug("current branch: " + git.getRepository().getBranch()); return new CheckOutScmResult("checkout via JGit", listedFiles); } catch (Exception e) { throw new ScmException("JGit checkout failure!", e); } finally { JGitUtils.closeRepo(git); } }
From source file:org.apache.oozie.action.hadoop.GitOperations.java
License:Apache License
/** * Clones a Git repository/*from w w w .ja va 2s. c o m*/ * @param outputDir location in which to clone the Git repository * @throws GitOperationsException if the Git clone fails */ private void cloneRepo(final File outputDir) throws GitOperationsException { final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() { @Override protected void configure(final OpenSshConfig.Host host, final Session session) { // nop } @Override protected JSch createDefaultJSch(final FS fs) throws JSchException { JSch.setConfig("StrictHostKeyChecking", "no"); final JSch defaultJSch = super.createDefaultJSch(fs); if (credentialFile != null) { defaultJSch.addIdentity(credentialFile.toString()); } return defaultJSch; } }; final CloneCommand cloneCommand = Git.cloneRepository(); cloneCommand.setURI(srcURL.toString()); if (srcURL.getScheme().toLowerCase().equals("ssh")) { cloneCommand.setTransportConfigCallback(new TransportConfigCallback() { @Override public void configure(final Transport transport) { final SshTransport sshTransport = (SshTransport) transport; sshTransport.setSshSessionFactory(sshSessionFactory); } }); } cloneCommand.setDirectory(outputDir); // set our branch identifier if (branch != null) { cloneCommand.setBranchesToClone(Arrays.asList("refs/heads/" + branch)); } try { cloneCommand.call(); } catch (final GitAPIException e) { throw new GitOperationsException("Unable to clone Git repo: ", e); } }
From source file:org.apache.openaz.xacml.admin.XacmlAdminUI.java
License:Apache License
/** * Initializes a user's git repository./*from www .jav a 2 s . c o m*/ * * * @param workspacePath * @param userId * @param email * @return * @throws IOException * @throws InvalidRemoteException * @throws TransportException * @throws GitAPIException */ private static Path initializeUserRepository(Path workspacePath, String userId, URI email) throws IOException, InvalidRemoteException, TransportException, GitAPIException { Path gitPath = null; // // Initialize the User's Git repository // if (Files.notExists(workspacePath)) { logger.info("Creating user workspace: " + workspacePath.toAbsolutePath().toString()); // // Create our user's directory // Files.createDirectory(workspacePath); } gitPath = Paths.get(workspacePath.toString(), XacmlAdminUI.repositoryPath.getFileName().toString()); if (Files.notExists(gitPath)) { // // It doesn't exist yet, so Clone it and check it out // logger.info("Cloning user git directory: " + gitPath.toAbsolutePath().toString()); Git.cloneRepository().setURI(XacmlAdminUI.repositoryPath.toUri().toString()) .setDirectory(gitPath.toFile()).setNoCheckout(false).call(); // // Set userid // Git git = Git.open(gitPath.toFile()); StoredConfig config = git.getRepository().getConfig(); config.setString("user", null, "name", userId); if (email != null && email.getPath() != null) { config.setString("user", null, "email", email.toString()); } config.save(); } return gitPath; }
From source file:org.apache.sshd.git.pack.GitPackCommandTest.java
License:Apache License
@Test public void testGitPack() throws Exception { Assume.assumeFalse("On windows this activates TortoisePlink", OsUtils.isWin32()); Path targetParent = detectTargetFolder().getParent(); Path gitRootDir = getTempTargetRelativeFile(getClass().getSimpleName()); try (SshServer sshd = setupTestServer()) { Path serverRootDir = gitRootDir.resolve("server"); sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory())); sshd.setCommandFactory(/* ww w . j a v a2 s.co m*/ new GitPackCommandFactory(Utils.resolveRelativeRemotePath(targetParent, serverRootDir))); sshd.start(); int port = sshd.getPort(); try { Path serverDir = serverRootDir.resolve("test.git"); Utils.deleteRecursive(serverDir); Git.init().setBare(true).setDirectory(serverDir.toFile()).call(); JSch.setConfig("StrictHostKeyChecking", "no"); CredentialsProvider.setDefault( new UsernamePasswordCredentialsProvider(getCurrentTestName(), getCurrentTestName())); SshSessionFactory.setInstance(new GitSshdSessionFactory()); Path localRootDir = gitRootDir.resolve("local"); Path localDir = localRootDir.resolve(serverDir.getFileName()); Utils.deleteRecursive(localDir); Git.cloneRepository().setURI("ssh://" + getCurrentTestName() + "@" + TEST_LOCALHOST + ":" + port + "/" + serverDir.getFileName()).setDirectory(localDir.toFile()).call(); Git git = Git.open(localDir.toFile()); git.commit().setMessage("First Commit").setCommitter(getCurrentTestName(), "sshd@apache.org") .call(); git.push().call(); Path readmeFile = Files.createFile(localDir.resolve("readme.txt")); git.add().addFilepattern(readmeFile.getFileName().toString()).call(); git.commit().setMessage(getCurrentTestName()).setCommitter(getCurrentTestName(), "sshd@apache.org") .call(); git.push().call(); git.pull().setRebase(true).call(); } finally { sshd.stop(); } } }
From source file:org.apache.stratos.cartridge.agent.artifact.deployment.synchronizer.git.impl.GitBasedArtifactRepository.java
License:Apache License
/** * Clones the remote repository to the local one. If basic authentication is required, * will call 'RepositoryInformationService' for credentials. * * @param gitRepoCtx RepositoryContext for the tenant */// ww w . j a v a 2 s. c o m /*private static void cloneRepository(RepositoryContext gitRepoCtx) { //should happen only at the beginning File gitRepoDir = new File(gitRepoCtx.getGitLocalRepoPath()); if (gitRepoDir.exists()) { if (isValidGitRepo(gitRepoCtx)) { //check if a this is a valid git repo log.info("Existing git repository detected for tenant " + gitRepoCtx.getTenantId() + ", no clone required"); gitRepoCtx.setCloneExists(true); return; } else { if (log.isDebugEnabled()) log.debug("Repository for tenant " + gitRepoCtx.getTenantId() + " is not a valid git repo"); Utilities.deleteFolderStructure(gitRepoDir); //if not a valid git repo but non-empty, delete it (else the clone will not work) } } CloneCommand cloneCmd = gitRepoCtx.getGit().cloneRepository(). setURI(gitRepoCtx.getGitRemoteRepoUrl()). setDirectory(gitRepoDir); if (!gitRepoCtx.getKeyBasedAuthentication()) { UsernamePasswordCredentialsProvider credentialsProvider = createCredentialsProvider(gitRepoCtx); if (credentialsProvider != null) cloneCmd.setCredentialsProvider(credentialsProvider); } try { cloneCmd.call(); log.info("Git clone operation for tenant " + gitRepoCtx.getTenantId() + " successful"); gitRepoCtx.setCloneExists(true); } catch (TransportException e) { log.error("Accessing remote git repository failed for tenant " + gitRepoCtx.getTenantId(), e); } catch (GitAPIException e) { log.error("Git clone operation for tenant " + gitRepoCtx.getTenantId() + " failed", e); } }*/ private boolean cloneRepository(RepositoryContext gitRepoCtx) { //should happen only at the beginning boolean cloneSuccess = false; File gitRepoDir = new File(gitRepoCtx.getGitLocalRepoPath()); CloneCommand cloneCmd = Git.cloneRepository().setURI(gitRepoCtx.getGitRemoteRepoUrl()) .setDirectory(gitRepoDir).setBranch(GitDeploymentSynchronizerConstants.GIT_REFS_HEADS_MASTER); UsernamePasswordCredentialsProvider credentialsProvider = createCredentialsProvider(gitRepoCtx); if (credentialsProvider == null) { log.warn("Remote repository credentials not available for tenant " + gitRepoCtx.getTenantId() + ", aborting clone"); return false; } cloneCmd.setCredentialsProvider(credentialsProvider); try { cloneCmd.call(); log.info("Git clone operation for tenant " + gitRepoCtx.getTenantId() + " successful"); gitRepoCtx.setCloneExists(true); cloneSuccess = true; } catch (TransportException e) { log.error("Accessing remote git repository failed for tenant " + gitRepoCtx.getTenantId(), e); } catch (GitAPIException e) { log.error("Git clone operation for tenant " + gitRepoCtx.getTenantId() + " failed", e); } return cloneSuccess; }
From source file:org.apache.stratos.manager.utils.RepositoryCreator.java
License:Apache License
private void createGitFolderStructure(String tenantDomain, String cartridgeName, String[] dirArray) throws Exception { if (log.isDebugEnabled()) { log.debug("Creating git repo folder structure "); }//from ww w .j ava2 s .c o m String parentDirName = "/tmp/" + UUID.randomUUID().toString(); CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider( System.getProperty(CartridgeConstants.INTERNAL_GIT_USERNAME), System.getProperty(CartridgeConstants.INTERNAL_GIT_PASSWORD).toCharArray()); // Clone // -------------------------- FileRepository localRepo = null; try { localRepo = new FileRepository(new File(parentDirName + "/.git")); } catch (IOException e) { log.error("Exception occurred in creating a new file repository. Reason: " + e.getMessage()); throw e; } Git git = new Git(localRepo); CloneCommand cloneCmd = git.cloneRepository().setURI(System.getProperty(CartridgeConstants.INTERNAL_GIT_URL) + "/git/" + tenantDomain + "/" + cartridgeName + ".git").setDirectory(new File(parentDirName)); cloneCmd.setCredentialsProvider(credentialsProvider); try { log.debug("Clonning git repo"); cloneCmd.call(); } catch (Exception e1) { log.error("Exception occurred in cloning Repo. Reason: " + e1.getMessage()); throw e1; } // ------------------------------------ // --- Adding directory structure -------- File parentDir = new File(parentDirName); parentDir.mkdir(); for (String string : dirArray) { String[] arr = string.split("="); if (log.isDebugEnabled()) { log.debug("Creating dir: " + arr[0]); } File parentFile = new File(parentDirName + "/" + arr[0]); parentFile.mkdirs(); File filess = new File(parentFile, "README"); String content = "Content goes here"; filess.createNewFile(); FileWriter fw = new FileWriter(filess.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); } // ---------------------------------------------------------- // ---- Git status --------------- StatusCommand s = git.status(); Status status = null; try { log.debug("Getting git repo status"); status = s.call(); } catch (Exception e) { log.error("Exception occurred in git status check. Reason: " + e.getMessage()); throw e; } // -------------------------------- // ---------- Git add --------------- AddCommand addCmd = git.add(); Iterator<String> it = status.getUntracked().iterator(); while (it.hasNext()) { addCmd.addFilepattern(it.next()); } try { log.debug("Adding files to git repo"); addCmd.call(); } catch (Exception e) { log.error("Exception occurred in adding files. Reason: " + e.getMessage()); throw e; } // ----------------------------------------- // ------- Git commit ----------------------- CommitCommand commitCmd = git.commit(); commitCmd.setMessage("Adding directories"); try { log.debug("Committing git repo"); commitCmd.call(); } catch (Exception e) { log.error("Exception occurred in committing . Reason: " + e.getMessage()); throw e; } // -------------------------------------------- // --------- Git push ----------------------- PushCommand pushCmd = git.push(); pushCmd.setCredentialsProvider(credentialsProvider); try { log.debug("Git repo push"); pushCmd.call(); } catch (Exception e) { log.error("Exception occurred in Git push . Reason: " + e.getMessage()); throw e; } try { deleteDirectory(new File(parentDirName)); } catch (Exception e) { log.error("Exception occurred in deleting temp files. Reason: " + e.getMessage()); throw e; } log.info(" Folder structure is created ..... "); }
From source file:org.archicontribs.modelrepository.grafico.GraficoUtils.java
License:Open Source License
/** * Clone a model/*from w w w .j a v a 2 s . co m*/ * @param localGitFolder * @param repoURL * @param userName * @param userPassword * @param monitor * @throws GitAPIException * @throws IOException */ public static void cloneModel(File localGitFolder, String repoURL, String userName, String userPassword, ProgressMonitor monitor) throws GitAPIException, IOException { CloneCommand cloneCommand = Git.cloneRepository(); cloneCommand.setDirectory(localGitFolder); cloneCommand.setURI(repoURL); cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, userPassword)); cloneCommand.setProgressMonitor(monitor); try (Git git = cloneCommand.call()) { // Use the same line endings StoredConfig config = git.getRepository().getConfig(); config.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "true"); //$NON-NLS-1$ config.save(); } }
From source file:org.aysada.licensescollector.dependencies.impl.GitCodeBaseProvider.java
License:Open Source License
public File getLocalRepositoryRoot(String remoteUrl) { try {/* ww w. j ava2s. co m*/ File prjWs = getLocalWSFor(remoteUrl); if (prjWs.exists()) { Repository repo = Git.open(prjWs).getRepository(); Git git = new Git(repo); git.fetch().call(); git.close(); LOGGER.info("Lcoal git repo for {} updated.", remoteUrl); return repo.getDirectory(); } else { prjWs.mkdir(); Git localRepo = Git.cloneRepository().setDirectory(prjWs).setURI(remoteUrl) .setCloneAllBranches(false).call(); File directory = localRepo.getRepository().getDirectory(); localRepo.close(); LOGGER.info("Cloned lcoal git repo for {}.", remoteUrl); return directory; } } catch (IOException | GitAPIException e) { LOGGER.error("Error working with git.", e); } return null; }
From source file:org.cfg4j.source.git.GitConfigurationSource.java
License:Apache License
/** * @throws IllegalStateException when unable to create directories for local repo clone * @throws SourceCommunicationException when unable to clone repository *//*ww w. j ava 2 s . c o m*/ @Override public void init() { LOG.info("Initializing " + GitConfigurationSource.class + " pointing to " + repositoryURI); try { clonedRepoPath = Files.createTempDirectory(tmpPath, tmpRepoPrefix); // This folder can't exist or JGit will throw NPE on clone Files.delete(clonedRepoPath); } catch (IOException e) { throw new IllegalStateException("Unable to create local clone directory: " + tmpRepoPrefix, e); } try { clonedRepo = Git.cloneRepository().setURI(repositoryURI).setDirectory(clonedRepoPath.toFile()).call(); } catch (GitAPIException e) { throw new SourceCommunicationException("Unable to clone repository: " + repositoryURI, e); } initialized = true; }