List of usage examples for org.eclipse.jgit.api Git push
public PushCommand push()
From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java
License:Apache License
protected void pushChanges(final File target) { try {/*from w ww .j a v a 2 s .c o m*/ // // 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 {//ww w . ja v a 2s .c om 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 a 2 s .c o 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.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 av a2s . com*/ 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.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java
License:Open Source License
private void pushChanges(Repository repository) { Git git = new Git(repository); try {/*w ww .jav a2 s .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.eclipse.oomph.gitbash.repository.PushDirectAction.java
License:Open Source License
@Override protected void run(Shell shell, final Repository repository) throws Exception { new Job("Pushing directly") { @Override/*w w w . j a va 2 s . co m*/ protected IStatus run(IProgressMonitor monitor) { monitor.beginTask(getName(), 101); try { Git git = Git.wrap(repository); monitor.worked(1); git.push().setRemote("direct").setProgressMonitor( new EclipseGitProgressTransformer(new SubProgressMonitor(monitor, 50))).call(); monitor.setTaskName("Pulling"); git.pull().setProgressMonitor( new EclipseGitProgressTransformer(new SubProgressMonitor(monitor, 50))).call(); return Status.OK_STATUS; } catch (Exception ex) { return Activator.getStatus(ex); } finally { monitor.done(); } } }.schedule(); }
From source file:org.eclipse.orion.server.filesystem.git.GitFileStore.java
License:Open Source License
private void push() throws CoreException { try {//w ww .j av a2 s. com Repository local = getLocalRepo(); Git git = new Git(local); PushCommand push = git.push(); push.setRefSpecs(new RefSpec("refs/heads/*:refs/heads/*")); push.setCredentialsProvider(getCredentialsProvider()); Iterable<PushResult> pushResults = push.call(); for (PushResult pushResult : pushResults) { Collection<RemoteRefUpdate> updates = pushResult.getRemoteUpdates(); for (RemoteRefUpdate update : updates) { org.eclipse.jgit.transport.RemoteRefUpdate.Status status = update.getStatus(); if (status.equals(org.eclipse.jgit.transport.RemoteRefUpdate.Status.OK) || status.equals(org.eclipse.jgit.transport.RemoteRefUpdate.Status.UP_TO_DATE)) { LogHelper.log(new Status(IStatus.INFO, Activator.PI_GIT, 1, "Push succeed: " + this, null)); } else { throw new CoreException(new Status(IStatus.ERROR, Activator.PI_GIT, IStatus.ERROR, status.toString(), null)); } } } } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, Activator.PI_GIT, IStatus.ERROR, e.getMessage(), e)); } }
From source file:org.eclipse.orion.server.git.jobs.PushJob.java
License:Open Source License
private IStatus doPush() throws IOException, CoreException, URISyntaxException, GitAPIException { // /git/remote/{remote}/{branch}/file/{path} File gitDir = GitUtils.getGitDir(path.removeFirstSegments(2)); Repository db = new FileRepository(gitDir); Git git = new Git(db); PushCommand pushCommand = git.push(); RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote); credentials.setUri(remoteConfig.getURIs().get(0)); pushCommand.setCredentialsProvider(credentials); RefSpec spec = new RefSpec(srcRef + ':' + Constants.R_HEADS + branch); pushCommand.setRemote(remote).setRefSpecs(spec); if (tags)/*from w w w. j av a 2 s . c om*/ pushCommand.setPushTags(); pushCommand.setForce(force); Iterable<PushResult> resultIterable = pushCommand.call(); PushResult pushResult = resultIterable.iterator().next(); // this set will contain only OK status or UP_TO_DATE status Set<RemoteRefUpdate.Status> statusSet = new HashSet<RemoteRefUpdate.Status>(); for (final RemoteRefUpdate rru : pushResult.getRemoteUpdates()) { final String rm = rru.getRemoteName(); // check status only for branch given in the URL or tags if (branch.equals(Repository.shortenRefName(rm)) || rm.startsWith(Constants.R_TAGS)) { RemoteRefUpdate.Status status = rru.getStatus(); // any status different from UP_TO_DATE and OK should generate warning if (status != RemoteRefUpdate.Status.OK && status != RemoteRefUpdate.Status.UP_TO_DATE) return new Status(IStatus.WARNING, GitActivator.PI_GIT, status.name(), new Throwable(rru.getMessage())); // add OK or UP_TO_DATE status to the set statusSet.add(status); } // TODO: return results for all updated branches once push is available for remote, see bug 352202 } if (statusSet.contains(RemoteRefUpdate.Status.OK)) // if there is OK status in the set -> something was updated return Status.OK_STATUS; else // if there is no OK status in the set -> only UP_TO_DATE status is possible return new Status(IStatus.WARNING, GitActivator.PI_GIT, RemoteRefUpdate.Status.UP_TO_DATE.name()); }
From source file:org.eclipse.orion.server.git.servlets.PushJob.java
License:Open Source License
private IStatus doPush() throws IOException, CoreException, JGitInternalException, InvalidRemoteException, URISyntaxException, JSONException { // /git/remote/{remote}/{branch}/file/{path} File gitDir = GitUtils.getGitDir(path.removeFirstSegments(2)); Repository db = new FileRepository(gitDir); Git git = new Git(db); PushCommand pushCommand = git.push(); RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), path.segment(0)); credentials.setUri(remoteConfig.getURIs().get(0)); pushCommand.setCredentialsProvider(credentials); // ObjectId ref = db.resolve(srcRef); RefSpec spec = new RefSpec(srcRef + ":" + Constants.R_HEADS + path.segment(1)); //$NON-NLS-1$ pushCommand.setRemote(path.segment(0)).setRefSpecs(spec); if (tags)// w w w . j a va2s . c om pushCommand.setPushTags(); pushCommand.setForce(force); Iterable<PushResult> resultIterable = pushCommand.call(); PushResult pushResult = resultIterable.iterator().next(); // this set will contain only OK status or UP_TO_DATE status Set<RemoteRefUpdate.Status> statusSet = new HashSet<RemoteRefUpdate.Status>(); for (final RemoteRefUpdate rru : pushResult.getRemoteUpdates()) { final String rm = rru.getRemoteName(); // final String sr = rru.isDelete() ? null : rru.getSrcRef(); // check status only for branch given in the URL or tags if (path.segment(1).equals(Repository.shortenRefName(rm)) || rm.startsWith(Constants.R_TAGS)) { RemoteRefUpdate.Status status = rru.getStatus(); // any status different from UP_TO_DATE and OK should generate warning if (status != RemoteRefUpdate.Status.OK && status != RemoteRefUpdate.Status.UP_TO_DATE) return new Status(IStatus.WARNING, GitActivator.PI_GIT, status.name()); // add OK or UP_TO_DATE status to the set statusSet.add(status); } // TODO: return results for all updated branches once push is available for remote, see bug 342727, comment 1 } if (statusSet.contains(RemoteRefUpdate.Status.OK)) // if there is OK status in the set -> something was updated return Status.OK_STATUS; else // if there is no OK status in the set -> only UP_TO_DATE status is possible return new Status(IStatus.WARNING, GitActivator.PI_GIT, RemoteRefUpdate.Status.UP_TO_DATE.name()); }
From source file:org.eclipse.orion.server.tests.servlets.git.GitFetchTest.java
License:Open Source License
@Test public void testFetchRemote() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); // clone1: create JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null); String projectId1 = project1.getString(ProtocolConstants.KEY_ID); IPath clonePath1 = new Path("file").append(project1.getString(ProtocolConstants.KEY_ID)).makeAbsolute(); JSONObject clone1 = clone(clonePath1); String cloneContentLocation1 = clone1.getString(ProtocolConstants.KEY_CONTENT_LOCATION); String cloneLocation1 = clone1.getString(ProtocolConstants.KEY_LOCATION); String branchesLocation1 = clone1.getString(GitConstants.KEY_BRANCH); // get project1 metadata WebRequest request = getGetFilesRequest(project1.getString(ProtocolConstants.KEY_CONTENT_LOCATION)); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project1 = new JSONObject(response.getText()); JSONObject gitSection1 = project1.optJSONObject(GitConstants.KEY_GIT); assertNotNull(gitSection1);/*from www. j a v a 2 s .c o m*/ String gitRemoteUri1 = gitSection1.getString(GitConstants.KEY_REMOTE); String gitIndexUri1 = gitSection1.getString(GitConstants.KEY_INDEX); String gitHeadUri1 = gitSection1.getString(GitConstants.KEY_HEAD); // clone1: branch 'a' Repository db1 = getRepositoryForContentLocation(cloneContentLocation1); Git git1 = new Git(db1); branch(branchesLocation1, "a"); // clone1: push all // TODO: replace with REST API when bug 339115 is fixed git1.push().setPushAll().call(); // clone2 JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null); IPath clonePath2 = new Path("file").append(project2.getString(ProtocolConstants.KEY_ID)).makeAbsolute(); clone(clonePath2); // XXX: checked out 'a' // get project2 metadata request = getGetFilesRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION)); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project2 = new JSONObject(response.getText()); JSONObject gitSection2 = project2.optJSONObject(GitConstants.KEY_GIT); assertNotNull(gitSection2); String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE); // clone1: switch to 'a' assertBranchExist(git1, "a"); checkoutBranch(cloneLocation1, "a"); // clone1: change request = getPutFileRequest(projectId1 + "/test.txt", "branch 'a' change"); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // clone1: add request = GitAddTest.getPutGitIndexRequest(gitIndexUri1); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // clone1: commit request = GitCommitTest.getPostGitCommitRequest(gitHeadUri1, "incoming branch 'a' commit", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // clone1: push ServerStatus pushStatus = push(gitRemoteUri1, 2, 0, "a", Constants.HEAD, false); assertTrue(pushStatus.isOK()); // clone1: switch to 'master' checkoutBranch(cloneLocation1, Constants.MASTER); // clone1: change request = getPutFileRequest(projectId1 + "/test.txt", "branch 'master' change"); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // clone1: add request = GitAddTest.getPutGitIndexRequest(gitIndexUri1); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // clone1: commit request = GitCommitTest.getPostGitCommitRequest(gitHeadUri1, "incoming branch 'master' commit", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // clone1: push pushStatus = push(gitRemoteUri1, 2, 0, Constants.MASTER, Constants.HEAD, false); assertTrue(pushStatus.isOK()); // clone2: get remote details // XXX: checked out 'a' JSONObject masterDetails = getRemoteBranch(gitRemoteUri2, 2, 1, Constants.MASTER); String masterOldRefId = masterDetails.getString(ProtocolConstants.KEY_ID); JSONObject aDetails = getRemoteBranch(gitRemoteUri2, 2, 0, "a"); String aOldRefId = aDetails.getString(ProtocolConstants.KEY_ID); // clone2: fetch all: 'master' and 'a' JSONObject remote = getRemote(gitRemoteUri2, 1, 0, Constants.DEFAULT_REMOTE_NAME); String remoteLocation = remote.getString(ProtocolConstants.KEY_LOCATION); fetch(remoteLocation); // clone2: assert both remote branches have new content masterDetails = getRemoteBranch(gitRemoteUri2, 2, 1, Constants.MASTER); String newRefId = masterDetails.getString(ProtocolConstants.KEY_ID); assertFalse(masterOldRefId.equals(newRefId)); aDetails = getRemoteBranch(gitRemoteUri2, 2, 0, "a"); newRefId = aDetails.getString(ProtocolConstants.KEY_ID); assertFalse(aOldRefId.equals(newRefId)); }