List of usage examples for org.eclipse.jgit.api Git commit
public CommitCommand commit()
From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java
License:Apache License
protected void pushChanges(final File target) { try {// w ww . ja v a 2 s .c om // // Grab our working repository // Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath(); final Git git = Git.open(repoPath.toFile()); // // Get our status // final String base; Status status; if (target == null) { base = "."; } else { Path relativePath = repoPath.relativize(Paths.get(target.getPath())); base = relativePath.toString(); } if (logger.isDebugEnabled()) { logger.debug("Status on base: " + base); } status = git.status().addPath(base).call(); // // Check if its clean // if (status.isClean()) { // // Its clean // AdminNotification.warn(target.getName() + " is clean!"); return; } // // Create the window // final GitPushWindow window = new GitPushWindow(git, target, status); window.setCaption("Push Changes"); window.setModal(true); window.addCloseListener(new CloseListener() { private static final long serialVersionUID = 1L; @Override public void windowClose(CloseEvent e) { if (window.isSaved() == false) { return; } try { // // Needs to be added first // DirCache cache = git.add().addFilepattern(base).call(); for (int i = 0; i < cache.getEntryCount(); i++) { DirCacheEntry entry = cache.getEntry(i); if (logger.isDebugEnabled()) { logger.debug("Entry: " + entry); } } // // Next they need to be committed // RevCommit rev = git.commit().setMessage(window.getComment()).call(); if (logger.isDebugEnabled()) { logger.debug("RevCommit: " + rev); } // // Now we can push changes to the Git repository // Iterable<PushResult> results = git.push().call(); for (PushResult result : results) { logger.info(result); } // // Have the container fire an item set change notification // self.treeContainer.updateItem(target); } catch (NoWorkTreeException | GitAPIException e1) { logger.error(e); AdminNotification.error("Exception occurred while trying to push: " + e1); } } }); window.center(); UI.getCurrent().addWindow(window); } catch (IOException | GitAPIException e) { logger.error(e); AdminNotification.error("Exception occurred while trying to get status: " + e); } }
From source file:org.apache.openaz.xacml.admin.XacmlAdminUI.java
License:Apache License
private static void initializeGitRepository() throws ServletException { XacmlAdminUI.repositoryPath = Paths .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY)); FileRepositoryBuilder builder = new FileRepositoryBuilder(); try {/*from w ww. j a v a2 s .c o m*/ XacmlAdminUI.repository = builder.setGitDir(XacmlAdminUI.repositoryPath.toFile()).readEnvironment() .findGitDir().setBare().build(); if (Files.notExists(XacmlAdminUI.repositoryPath) || Files.notExists(Paths.get(XacmlAdminUI.repositoryPath.toString(), "HEAD"))) { // // Create it if it doesn't exist. As a bare repository // logger.info("Creating bare git repository: " + XacmlAdminUI.repositoryPath.toString()); XacmlAdminUI.repository.create(); // // Add the magic file so remote works. // Path daemon = Paths.get(XacmlAdminUI.repositoryPath.toString(), "git-daemon-export-ok"); Files.createFile(daemon); } } catch (IOException e) { logger.error("Failed to build repository: " + repository, e); throw new ServletException(e.getMessage(), e.getCause()); } // // Make sure the workspace directory is created // Path workspace = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_WORKSPACE)); workspace = workspace.toAbsolutePath(); if (Files.notExists(workspace)) { try { Files.createDirectory(workspace); } catch (IOException e) { logger.error("Failed to build workspace: " + workspace, e); throw new ServletException(e.getMessage(), e.getCause()); } } // // Create the user workspace directory // workspace = Paths.get(workspace.toString(), "pe"); if (Files.notExists(workspace)) { try { Files.createDirectory(workspace); } catch (IOException e) { logger.error("Failed to create directory: " + workspace, e); throw new ServletException(e.getMessage(), e.getCause()); } } // // Get the path to where the repository is going to be // Path gitPath = Paths.get(workspace.toString(), XacmlAdminUI.repositoryPath.getFileName().toString()); if (Files.notExists(gitPath)) { try { Files.createDirectory(gitPath); } catch (IOException e) { logger.error("Failed to create directory: " + gitPath, e); throw new ServletException(e.getMessage(), e.getCause()); } } // // Initialize the domain structure // String base = null; String domain = XacmlAdminUI.getDomain(); if (domain != null) { for (String part : Splitter.on(':').trimResults().split(domain)) { if (base == null) { base = part; } Path subdir = Paths.get(gitPath.toString(), part); if (Files.notExists(subdir)) { try { Files.createDirectory(subdir); Files.createFile(Paths.get(subdir.toString(), ".svnignore")); } catch (IOException e) { logger.error("Failed to create: " + subdir, e); throw new ServletException(e.getMessage(), e.getCause()); } } } } else { try { Files.createFile(Paths.get(workspace.toString(), ".svnignore")); base = ".svnignore"; } catch (IOException e) { logger.error("Failed to create file", e); throw new ServletException(e.getMessage(), e.getCause()); } } try { // // These are the sequence of commands that must be done initially to // finish setting up the remote bare repository. // Git git = Git.init().setDirectory(gitPath.toFile()).setBare(false).call(); git.add().addFilepattern(base).call(); git.commit().setMessage("Initialize Bare Repository").call(); StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "origin", "url", XacmlAdminUI.repositoryPath.toAbsolutePath().toString()); config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); config.save(); git.push().setRemote("origin").add("master").call(); /* * This will not work unless git.push().setRemote("origin").add("master").call(); * is called first. Otherwise it throws an exception. However, if the push() is * called then calling this function seems to add nothing. * git.branchCreate().setName("master") .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM) .setStartPoint("origin/master").setForce(true).call(); */ } catch (GitAPIException | IOException e) { logger.error(e); throw new ServletException(e.getMessage(), e.getCause()); } }
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(/*from 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.sshd.git.pgm.GitPgmCommandTest.java
License:Apache License
@Test public void testGitPgm() throws Exception { Path targetParent = detectTargetFolder().getParent(); Path serverDir = getTempTargetRelativeFile(getClass().getSimpleName()); ////from ww w . j av a 2 s . c o m // TODO: the GitpgmCommandFactory is kept in the test tree // TODO: because it's quite limited for now // try (SshServer sshd = setupTestServer()) { sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory())); sshd.setCommandFactory( new GitPgmCommandFactory(Utils.resolveRelativeRemotePath(targetParent, serverDir))); sshd.start(); int port = sshd.getPort(); try { Utils.deleteRecursive(serverDir); try (SshClient client = setupTestClient()) { client.start(); try (ClientSession session = client .connect(getCurrentTestName(), SshdSocketAddress.LOCALHOST_IP, port) .verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); Path repo = serverDir.resolve(getCurrentTestName()); Git.init().setDirectory(repo.toFile()).call(); Git git = Git.open(repo.toFile()); git.commit().setMessage("First Commit") .setCommitter(getCurrentTestName(), "sshd@apache.org").call(); Path readmeFile = Files.createFile(repo.resolve("readme.txt")); String commandPrefix = "git --git-dir " + repo.getFileName(); execute(session, commandPrefix + " add " + readmeFile.getFileName()); execute(session, commandPrefix + " commit -m \"readme\""); } finally { client.stop(); } } } finally { sshd.stop(); } } }
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 www . j a v a 2 s. 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 w w w . j a va 2 s . c o 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.cicomponents.test.GitEmitterTest.java
License:Mozilla Public License
@Test @SneakyThrows// w w w.java 2s. c o m public void listenerDiscovery() { try (WorkingDirectory directory = workingDirectoryProvider.getDirectory()) { Git git = Git.init().setDirectory(new File(directory.getDirectory())).call(); RevCommit commit = git.commit().setAllowEmpty(true).setMessage("Test").call(); Hashtable<String, Object> properties = new Hashtable<>(); properties.put("repository", "file://" + git.getRepository().getDirectory().getAbsolutePath()); properties.put("type", "latest"); Listener listener = new Listener(); ServiceRegistration<ResourceListener> registration = bundleContext .registerService(ResourceListener.class, listener, properties); Collection<ServiceReference<GitRevisionEmitter>> references = bundleContext.getServiceReferences( GitRevisionEmitter.class, "(objectClass=" + GitRevisionEmitter.class.getName() + ")"); assertFalse(references.isEmpty()); registration.unregister(); git.close(); } }
From source file:org.cicomponents.test.GitEmitterTest.java
License:Mozilla Public License
@Test @SneakyThrows//from w w w. j av a 2s . c o m public void listenerRemoval() { try (WorkingDirectory directory = workingDirectoryProvider.getDirectory()) { Git git = Git.init().setDirectory(new File(directory.getDirectory())).call(); RevCommit commit = git.commit().setAllowEmpty(true).setMessage("Test").call(); Hashtable<String, Object> properties = new Hashtable<>(); properties.put("repository", "file://" + git.getRepository().getDirectory().getAbsolutePath()); properties.put("type", "latest"); Listener listener = new Listener(); ServiceRegistration<ResourceListener> registration = bundleContext .registerService(ResourceListener.class, listener, properties); Collection<ServiceReference<GitRevisionEmitter>> references = bundleContext.getServiceReferences( GitRevisionEmitter.class, "(objectClass=" + GitRevisionEmitter.class.getName() + ")"); assertFalse(references.isEmpty()); ObjectId objectId = listener.getFuture().get(); assertEquals(commit.toObjectId(), objectId); listener.reset(); registration.unregister(); git.commit().setAllowEmpty(true).setMessage("Test #1").call(); try { listener.getFuture().get(11, TimeUnit.SECONDS); fail("Listener was not removed"); } catch (TimeoutException e) { // this is what should happen } git.close(); } }
From source file:org.cicomponents.test.GitEmitterTest.java
License:Mozilla Public License
@Test @SneakyThrows//from ww w . j a v a 2s.c o m public void listener() { try (WorkingDirectory directory = workingDirectoryProvider.getDirectory()) { Git git = Git.init().setDirectory(new File(directory.getDirectory())).call(); RevCommit commit = git.commit().setAllowEmpty(true).setMessage("Test").call(); Hashtable<String, Object> properties = new Hashtable<>(); properties.put("repository", "file://" + git.getRepository().getDirectory().getAbsolutePath()); properties.put("type", "latest"); Listener listener = new Listener(); ServiceRegistration<ResourceListener> registration = bundleContext .registerService(ResourceListener.class, listener, properties); Collection<ServiceReference<GitRevisionEmitter>> references = bundleContext.getServiceReferences( GitRevisionEmitter.class, "(objectClass=" + GitRevisionEmitter.class.getName() + ")"); ObjectId objectId = listener.getFuture().get(); assertEquals(commit.toObjectId(), objectId); listener.reset(); // Test ongoing commits commit = git.commit().setAllowEmpty(true).setMessage("Test #1").call(); objectId = listener.getFuture().get(); assertEquals(commit.toObjectId(), objectId); git.close(); registration.unregister(); } }
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();//from w w w. j ava 2s. c om 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()); }