List of usage examples for org.eclipse.jgit.api Git add
public AddCommand add()
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 "); }// w w w .ja v a2s. c om 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.basinmc.maven.plugins.minecraft.patch.InitializeRepositoryMojo.java
License:Apache License
/** * Initializes the local repository with its default state. *///from ww w . j av a2s.co m private void initializeRepository() throws ArtifactResolutionException, MojoFailureException { final Path sourceArtifact; { Artifact a = this.createArtifactWithClassifier(MINECRAFT_GROUP_ID, this.getModule(), this.getMappingArtifactVersion(), "source"); sourceArtifact = this.findArtifact(a).orElseThrow(() -> new MojoFailureException( "Could not locate artifact " + this.getArtifactCoordinateString(a))); } try { Files.createDirectories(this.getSourceDirectory().toPath()); Git git = Git.init().setDirectory(this.getSourceDirectory()).call(); AccessTransformationMap transformationMap = null; Formatter formatter = null; if (this.getAccessTransformation() != null) { transformationMap = AccessTransformationMap.read(this.getAccessTransformation().toPath()); formatter = new Formatter(); } try (ZipFile file = new ZipFile(sourceArtifact.toFile())) { Enumeration<? extends ZipEntry> enumeration = file.entries(); while (enumeration.hasMoreElements()) { ZipEntry entry = enumeration.nextElement(); String name = entry.getName(); if (!name.endsWith(".java")) { continue; } Path outputPath = this.getSourceDirectory().toPath().resolve(name); if (!Files.isDirectory(outputPath.getParent())) { Files.createDirectories(outputPath.getParent()); } try (InputStream inputStream = file.getInputStream(entry)) { try (FileChannel outputChannel = FileChannel.open(outputPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { if (transformationMap != null && transformationMap.getTypeMappings(name).isPresent()) { JavaClassSource classSource = Roaster.parse(JavaClassSource.class, inputStream); this.applyAccessTransformation(transformationMap, classSource); outputChannel.write(ByteBuffer.wrap(formatter.formatSource(classSource.toString()) .getBytes(StandardCharsets.UTF_8))); } else { try (ReadableByteChannel channel = Channels.newChannel(inputStream)) { ByteStreams.copy(channel, outputChannel); } } } } git.add().addFilepattern(name).call(); } } git.commit().setAuthor(ROOT_COMMIT_AUTHOR_NAME, ROOT_COMMIT_AUTHOR_EMAIL) .setCommitter(ROOT_COMMIT_AUTHOR_NAME, ROOT_COMMIT_AUTHOR_EMAIL) .setMessage("Added decompiled sources.").call(); git.branchCreate().setName("upstream").call(); } catch (FormatterException ex) { throw new MojoFailureException("Failed to format one or more source files: " + ex.getMessage(), ex); } catch (GitAPIException ex) { throw new MojoFailureException("Failed to execute Git command: " + ex.getMessage(), ex); } catch (IOException ex) { throw new MojoFailureException( "Failed to access source artifact or write target file: " + ex.getMessage(), ex); } }
From source file:org.craftercms.commons.git.impl.GitRepositoryImplTest.java
License:Open Source License
@Test public void testRemove() throws Exception { Git git = Git.init().setDirectory(tmpDir.getRoot()).call(); GitRepositoryImpl repository = new GitRepositoryImpl(git); File testFile = new File(tmpDir.getRoot(), "test"); testFile.createNewFile();/*w w w . j a v a 2 s. com*/ git.add().addFilepattern("test").call(); git.commit().setMessage("Test commit").call(); repository.remove("test"); Status status = git.status().call(); assertNotNull(status); assertEquals(Collections.singleton("test"), status.getRemoved()); }
From source file:org.craftercms.commons.git.impl.GitRepositoryImplTest.java
License:Open Source License
@Test public void testCommit() throws Exception { Git git = Git.init().setDirectory(tmpDir.getRoot()).call(); GitRepositoryImpl repository = new GitRepositoryImpl(git); File testFile = new File(tmpDir.getRoot(), "test"); testFile.createNewFile();/*from www . j a v a 2 s . c o m*/ git.add().addFilepattern("test").call(); repository.commit("Test message"); List<RevCommit> commits = IterableUtils.toList(git.log().all().call()); assertNotNull(commits); assertEquals(1, commits.size()); assertEquals("Test message", commits.get(0).getFullMessage()); }
From source file:org.craftercms.commons.git.impl.GitRepositoryImplTest.java
License:Open Source License
@Test public void testPush() throws Exception { File masterRepoDir = tmpDir.newFolder("master.git"); File cloneRepoDir = tmpDir.newFolder("clone"); Git masterGit = Git.init().setDirectory(masterRepoDir).setBare(true).call(); Git cloneGit = Git.cloneRepository().setURI(masterRepoDir.getCanonicalPath()).setDirectory(cloneRepoDir) .call();/*from ww w .j a v a 2s .c om*/ GitRepositoryImpl cloneRepo = new GitRepositoryImpl(cloneGit); File testFile = new File(cloneRepoDir, "test"); testFile.createNewFile(); cloneGit.add().addFilepattern("test").call(); cloneGit.commit().setMessage("Test message").call(); cloneRepo.push(); List<RevCommit> commits = IterableUtils.toList(masterGit.log().all().call()); assertNotNull(commits); assertEquals(1, commits.size()); assertEquals("Test message", commits.get(0).getFullMessage()); List<String> committedFiles = getCommittedFiles(masterGit.getRepository(), commits.get(0)); assertNotNull(committedFiles); assertEquals(1, committedFiles.size()); assertEquals("test", committedFiles.get(0)); }
From source file:org.craftercms.commons.git.impl.GitRepositoryImplTest.java
License:Open Source License
@Test public void testPull() throws Exception { File masterRepoDir = tmpDir.newFolder("master"); File cloneRepoDir = tmpDir.newFolder("clone"); Git masterGit = Git.init().setDirectory(masterRepoDir).call(); Git cloneGit = Git.cloneRepository().setURI(masterRepoDir.getCanonicalPath()).setDirectory(cloneRepoDir) .call();// w w w .ja v a2s . c om GitRepositoryImpl cloneRepo = new GitRepositoryImpl(cloneGit); File testFile = new File(masterRepoDir, "test"); testFile.createNewFile(); masterGit.add().addFilepattern("test").call(); masterGit.commit().setMessage("Test message").call(); cloneRepo.pull(); List<RevCommit> commits = IterableUtils.toList(cloneGit.log().all().call()); assertNotNull(commits); assertEquals(1, commits.size()); assertEquals("Test message", commits.get(0).getFullMessage()); List<String> committedFiles = getCommittedFiles(cloneGit.getRepository(), commits.get(0)); assertNotNull(committedFiles); assertEquals(1, committedFiles.size()); assertEquals("test", committedFiles.get(0)); }
From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java
License:Open Source License
private void pushChanges(Repository repository) { Git git = new Git(repository); try {//from w w w . j a va2s.c o m git.add().addFilepattern(".").call(); git.commit().setMessage("deployment to environment store").call(); git.push().call(); } catch (GitAPIException e) { logger.error("Error while pushing workflow changes.", e); } }
From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java
License:Open Source License
private boolean createEnvironmentStoreRepository(String site) { boolean success = true; Path siteEnvironmentStoreRepoPath = Paths.get(environmentsStoreRootPath, site, environment); try {/*from w w w. j a va2 s . com*/ Files.deleteIfExists(siteEnvironmentStoreRepoPath); siteEnvironmentStoreRepoPath = Paths.get(environmentsStoreRootPath, site, environment, ".git"); Repository repository = FileRepositoryBuilder.create(siteEnvironmentStoreRepoPath.toFile()); repository.create(); Git git = new Git(repository); git.add().addFilepattern(".").call(); RevCommit commit = git.commit().setMessage("initial content").setAllowEmpty(true).call(); } catch (IOException | GitAPIException e) { logger.error("Error while creating repository for site " + site, e); success = false; } return success; }
From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitDeployer.java
License:Open Source License
@Override public void deployFile(String site, String path) { try (Repository envStoreRepo = getEnvironmentStoreRepositoryInstance(site)) { fetchFromRemote(site, envStoreRepo); createPatch(envStoreRepo, site, path); Git git = new Git(envStoreRepo); applyPatch(envStoreRepo, site);//from w ww. j a v a2 s . com git.add().addFilepattern(".").call(); git.commit().setMessage("deployment").call(); } catch (IOException | GitAPIException e) { logger.error("Error while deploying file for site: " + site + " path: " + path, e); } }
From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryHelper.java
License:Open Source License
/** * Perform an initial commit after large changes to a site. Will not work against the global config repo. * @param site/*from w w w . j a v a 2 s. c o m*/ * @param message * @return true if successful, false otherwise */ public boolean performInitialCommit(String site, String message) { boolean toReturn = true; try { Repository repo = getRepository(site, GitRepositories.SANDBOX); Git git = new Git(repo); Status status = git.status().call(); if (status.hasUncommittedChanges() || !status.isClean()) { DirCache dirCache = git.add().addFilepattern(GIT_COMMIT_ALL_ITEMS).call(); RevCommit commit = git.commit().setMessage(message).call(); // TODO: SJ: Do we need the commit id? // commitId = commit.getName(); } } catch (GitAPIException err) { logger.error("error creating initial commit for site: " + site, err); toReturn = false; } return toReturn; }