List of usage examples for org.eclipse.jgit.api Git commit
public CommitCommand commit()
From source file:io.fabric8.forge.rest.git.RepositoryResource.java
License:Apache License
protected CommitInfo doRename(Git git, String oldPath, String newPath) throws Exception { File file = getRelativeFile(oldPath); File newFile = getRelativeFile(newPath); if (file.exists()) { File parentFile = newFile.getParentFile(); parentFile.mkdirs();// w w w . j ava 2s. c om if (!parentFile.exists()) { throw new IOException("Could not create directory " + parentFile + " when trying to move " + file + " to " + newFile + ". Maybe a file permission issue?"); } file.renameTo(newFile); String filePattern = getFilePattern(newPath); git.add().addFilepattern(filePattern).call(); CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(message); return createCommitInfo(commitThenPush(git, commit)); } else { return null; } }
From source file:io.fabric8.forge.rest.git.RepositoryResource.java
License:Apache License
protected CommitInfo doRemove(Git git, List<String> paths) throws Exception { if (paths != null && paths.size() > 0) { int count = 0; for (String path : paths) { File file = getRelativeFile(path); if (file.exists()) { count++;//from w w w. j a va 2 s . com Files.recursiveDelete(file); String filePattern = getFilePattern(path); git.rm().addFilepattern(filePattern).call(); } } if (count > 0) { CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(message); return createCommitInfo(commitThenPush(git, commit)); } } return null; }
From source file:io.fabric8.forge.rest.git.RepositoryResource.java
License:Apache License
protected CommitInfo doRemove(Git git, String path) throws Exception { File file = getRelativeFile(path); if (file.exists()) { Files.recursiveDelete(file); String filePattern = getFilePattern(path); git.rm().addFilepattern(filePattern).call(); CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(message); return createCommitInfo(commitThenPush(git, commit)); } else {/* w ww . ja v a 2s . c o m*/ return null; } }
From source file:io.fabric8.forge.rest.git.RepositoryResource.java
License:Apache License
protected CommitInfo doWrite(Git git, String path, byte[] contents, PersonIdent personIdent, String commitMessage) throws Exception { File file = getRelativeFile(path); file.getParentFile().mkdirs();/*from w w w . j a va 2s . co m*/ Files.writeToFile(file, contents); String filePattern = getFilePattern(path); AddCommand add = git.add().addFilepattern(filePattern).addFilepattern("."); add.call(); CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(commitMessage); RevCommit revCommit = commitThenPush(git, commit); return createCommitInfo(revCommit); }
From source file:io.fabric8.forge.rest.main.GitCommandCompletePostProcessor.java
License:Apache License
protected RevCommit doCommitAndPush(Git git, String message, CredentialsProvider credentials, PersonIdent author, String remote, String branch, String origin) throws IOException, GitAPIException { CommitCommand commit = git.commit().setAll(true).setMessage(message); if (author != null) { commit = commit.setAuthor(author); }/*from www . ja va2 s. c o m*/ RevCommit answer = commit.call(); if (LOG.isDebugEnabled()) { LOG.debug("Committed " + answer.getId() + " " + answer.getFullMessage()); } if (isPushOnCommit()) { Iterable<PushResult> results = git.push().setCredentialsProvider(credentials).setRemote(origin).call(); for (PushResult result : results) { if (LOG.isDebugEnabled()) { LOG.debug("Pushed " + result.getMessages() + " " + result.getURI() + " branch: " + branch + " updates: " + GitHelpers.toString(result.getRemoteUpdates())); } } } return answer; }
From source file:io.fabric8.git.internal.GitDataStore.java
License:Apache License
public <T> T gitOperation(PersonIdent personIdent, GitOperation<T> operation, boolean pullFirst, GitContext context) {/*ww w .jav a 2 s. c om*/ synchronized (gitOperationMonitor) { assertValid(); // must set the TCCL to the classloader that loaded GitDataStore as we need the classloader // that could load this class, as jgit will load resources from classpath using the TCCL // and that requires the TCCL to the classloader that could load GitDataStore as the resources // jgit requires are in the same bundle as GitDataSource (eg embedded inside fabric-git) // see FABRIC-887 ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); ClassLoader cl = GitDataStore.class.getClassLoader(); Thread.currentThread().setContextClassLoader(cl); LOG.trace("Setting ThreadContextClassLoader to {} instead of {}", cl, oldCl); try { Git git = getGit(); Repository repository = git.getRepository(); // lets default the identity if none specified if (personIdent == null) { personIdent = new PersonIdent(repository); } if (GitHelpers.hasGitHead(git)) { // lets stash any local changes just in case.. git.stashCreate().setPerson(personIdent).setWorkingDirectoryMessage("Stash before a write") .call(); } if (pullFirst) { doPull(git, getCredentialsProvider(), false); } T answer = operation.call(git, context); boolean requirePush = context.isRequirePush(); if (context.isRequireCommit()) { requirePush = true; String message = context.getCommitMessage().toString(); if (message.length() == 0) { LOG.warn("No commit message from " + operation + ". Please add one! :)"); } git.commit().setMessage(message).call(); if (--commitsWithoutGC < 0) { commitsWithoutGC = MAX_COMMITS_WITHOUT_GC; LOG.debug("Performing \"git gc\" after {} commits", MAX_COMMITS_WITHOUT_GC); git.gc().call(); } } if (requirePush) { doPush(git, context, getCredentialsProvider()); } if (context.isRequireCommit()) { clearCaches(); fireChangeNotifications(); } return answer; } catch (Exception e) { throw FabricException.launderThrowable(e); } finally { LOG.trace("Restoring ThreadContextClassLoader to {}", oldCl); Thread.currentThread().setContextClassLoader(oldCl); } } }
From source file:io.fabric8.git.internal.GitDataStoreImpl.java
License:Apache License
private void doCommit(Git git, GitContext context) { try {//from w ww .ja va 2 s .c o m String message = context.getCommitMessage(); IllegalStateAssertion.assertTrue(message.length() > 0, "Empty commit message"); // git add --all git.add().addFilepattern(".").call(); // git commit -m message git.commit().setMessage(message).call(); if (--commitsWithoutGC < 0) { commitsWithoutGC = MAX_COMMITS_WITHOUT_GC; LOGGER.debug("Performing 'git gc' after {} commits", MAX_COMMITS_WITHOUT_GC); git.gc().call(); } } catch (GitAPIException ex) { throw FabricException.launderThrowable(ex); } }
From source file:io.fabric8.git.zkbridge.Bridge.java
License:Apache License
private static void update(Git git, CuratorFramework zookeeper, CredentialsProvider credentialsProvider) throws Exception { String remoteName = "origin"; boolean remoteAvailable = false; try {/*from w w w. j a v a2 s . co m*/ git.fetch().setCredentialsProvider(credentialsProvider).setRemote(remoteName).call(); remoteAvailable = true; } catch (Exception e) { // Ignore fetch exceptions if (LOGGER.isTraceEnabled()) { LOGGER.trace("Unable to fetch master", e); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("Unable to fetch master: " + e.getClass().getName() + ": " + e.getMessage()); } } // Handle versions in git and not in zookeeper Map<String, Ref> localBranches = new HashMap<String, Ref>(); Map<String, Ref> remoteBranches = new HashMap<String, Ref>(); Set<String> gitVersions = new HashSet<String>(); for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) { if (ref.getName().startsWith("refs/remotes/" + remoteName + "/")) { String name = ref.getName().substring(("refs/remotes/" + remoteName + "/").length()); if (!"master".equals(name) && !name.endsWith("-tmp")) { remoteBranches.put(name, ref); gitVersions.add(name); } } else if (ref.getName().startsWith("refs/heads/")) { String name = ref.getName().substring(("refs/heads/").length()); if (!name.equals("master") && !name.endsWith("-tmp")) { localBranches.put(name, ref); gitVersions.add(name); } } } List<String> zkVersions = getChildren(zookeeper, ZkPath.CONFIG_VERSIONS.getPath()); createDefault(zookeeper, "/fabric/configs/git", null); Properties versionsMetadata = loadProps(zookeeper, "/fabric/configs/git"); boolean allDone = true; // Check no modifs in zookeeper String lastModified = Long.toString(lastModified(zookeeper, ZkPath.CONFIG_VERSIONS.getPath())); if (!lastModified.equals(versionsMetadata.get("zk-lastmodified"))) { allDone = false; } // Check the versions in zk and git are the same if (zkVersions.size() != gitVersions.size() || !zkVersions.containsAll(gitVersions)) { allDone = false; } // Check all local and remote branches exists if (gitVersions.size() != localBranches.size() || !localBranches.keySet().containsAll(gitVersions)) { allDone = false; } // If remote is available, check that all remote branches exist if (remoteAvailable && !remoteBranches.keySet().containsAll(gitVersions)) { allDone = false; } // Check git commmits if (allDone) { for (String version : zkVersions) { String zkCommit = versionsMetadata.get(version); String localCommit = localBranches.get(version).getObjectId().getName(); String remoteCommit = remoteAvailable ? remoteBranches.get(version).getObjectId().getName() : null; if (!localCommit.equals(zkCommit) || remoteCommit != null && !localCommit.equals(remoteCommit)) { allDone = false; break; } } } if (allDone) { return; } // ZooKeeper -> Git changes for (String version : zkVersions) { String zkNode = ZkPath.CONFIG_VERSION.getPath(version); // Checkout updated version List<Ref> allBranches = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call(); Ref local = null; Ref remote = null; Ref tmp = null; for (Ref ref : allBranches) { if (ref.getName().equals("refs/remotes/" + remoteName + "/" + version)) { remote = ref; } else if (ref.getName().equals("refs/heads/" + version)) { local = ref; } else if (ref.getName().equals("refs/heads/" + version + "-tmp")) { tmp = ref; } } if (local == null) { git.branchCreate().setName(version).call(); } if (tmp == null) { git.branchCreate().setName(version + "-tmp").call(); } git.clean().setCleanDirectories(true).call(); git.checkout().setName("HEAD").setForce(true).call(); git.checkout().setName(version).setForce(true).call(); if (remoteAvailable && remote != null) { MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS).include(remote.getObjectId()) .call(); // TODO: check merge conflicts } git.checkout().setName(version + "-tmp").setForce(true).call(); String gitCommit = versionsMetadata.get(version); if (gitCommit != null) { try { git.reset().setMode(ResetCommand.ResetType.HARD).setRef(gitCommit).call(); } catch (Exception e) { // Ignore, we did our best if (LOGGER.isTraceEnabled()) { LOGGER.trace("Unable to reset branch to commit", e); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("Unable to reset branch to commit " + gitCommit + ": " + e.getClass().getName() + ": " + e.getMessage()); } } } // Apply changes to git syncVersionFromZkToGit(git, zookeeper, zkNode); if (git.status().call().isClean()) { git.checkout().setName(version).setForce(true).call(); } else { ObjectId rev = git.commit().setMessage("Merge zookeeper updates in version " + version).call() .getId(); git.checkout().setName(version).setForce(true).call(); MergeResult result = git.merge().setStrategy(MergeStrategy.OURS).include(rev).call(); // TODO: check merge conflicts } if (remoteAvailable) { git.push().setCredentialsProvider(credentialsProvider).setRefSpecs(new RefSpec(version)).call(); } // Apply changes to zookeeper syncVersionFromGitToZk(git, zookeeper, zkNode); versionsMetadata.put(version, git.getRepository().getRef("HEAD").getObjectId().getName()); } // Iterate through known git versions for (String version : gitVersions) { String state = versionsMetadata.get(version); if (zkVersions.contains(version)) { continue; } // The version is not known to zookeeper, so create it if (state == null) { if (localBranches.containsKey(version)) { if (remoteAvailable) { git.push().setRefSpecs(new RefSpec(version)).call(); } } else { git.branchCreate().setName(version).call(); git.reset().setMode(ResetCommand.ResetType.HARD).setRef(remoteBranches.get(version).getName()) .call(); } git.checkout().setName(version).setForce(true).call(); // Sync zookeeper String zkNode = ZkPath.CONFIG_VERSION.getPath(version); create(zookeeper, zkNode); create(zookeeper, ZkPath.CONFIG_VERSIONS_PROFILES.getPath(version)); create(zookeeper, ZkPath.CONFIG_VERSIONS_CONTAINERS.getPath(version)); syncVersionFromGitToZk(git, zookeeper, zkNode); // Flag version as active versionsMetadata.put(version, git.getRepository().getRef("HEAD").getObjectId().getName()); } // The version has been deleted from zookeeper so delete it in git else { git.checkout().setName("master").setForce(true).call(); git.branchDelete().setBranchNames(version, version + "-tmp").setForce(true).call(); git.push().setRefSpecs(new RefSpec(version + ":")).call(); versionsMetadata.remove(version); } } versionsMetadata.put("zk-lastmodified", Long.toString(lastModified(zookeeper, ZkPath.CONFIG_VERSIONS.getPath()))); setPropertiesAsMap(zookeeper, "/fabric/configs/git", versionsMetadata); }
From source file:io.fabric8.itests.basic.git.FabricGitTestSupport.java
License:Apache License
/** * Create a profile in git and check that its bridged to the registry. *///from w ww. j ava 2 s . com protected void createAndTestProfileInGit(FabricService fabricService, CuratorFramework curator, Git git, String version, String profile) throws Exception { //Create the test profile in git System.out.println("Create test profile:" + profile + " in git."); GitUtils.checkoutBranch(git, "origin", version); String relativeProfileDir = "fabric/profiles/" + profile + ".profile"; File testProfileDir = new File(git.getRepository().getWorkTree(), relativeProfileDir); testProfileDir.mkdirs(); File testProfileConfig = new File(testProfileDir, "io.fabric8.agent.properties"); testProfileConfig.createNewFile(); Files.writeToFile(testProfileConfig, "", Charset.defaultCharset()); git.add().addFilepattern(relativeProfileDir).call(); git.commit().setAll(true).setMessage("Create " + profile).call(); PullResult pullResult = git.pull().setCredentialsProvider(getCredentialsProvider()).setRebase(true).call(); git.push().setCredentialsProvider(getCredentialsProvider()).setPushAll().setRemote("origin").call(); GitUtils.waitForBranchUpdate(curator, version); for (int i = 0; i < 5; i++) { if (fabricService.getDataStore().hasProfile(version, profile)) { return; } else { Thread.sleep(1000); } } fail("Expected to find profile " + profile + " in version " + version); }
From source file:io.fabric8.maven.HelmPushMojo.java
License:Apache License
@Override public void execute() throws MojoExecutionException, MojoFailureException { if (!isRootReactorBuild()) { getLog().info("Not the root reactor build so not committing changes"); return;/*from w ww . jav a 2s . c o m*/ } File outputDir = getHelmRepoFolder(); if (!Files.isDirectory(outputDir)) { throw new MojoExecutionException( "No helm repository exists for " + outputDir + ". Did you run `mvn fabric8:helm` yet?"); } File gitFolder = new File(outputDir, ".git"); if (!Files.isDirectory(gitFolder)) { throw new MojoExecutionException( "No helm git repository exists for " + gitFolder + ". Did you run `mvn fabric8:helm` yet?"); } FileRepositoryBuilder builder = new FileRepositoryBuilder(); Git git = null; try { Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build(); git = new Git(repository); git.add().addFilepattern(".").call(); } catch (Exception e) { throw new MojoExecutionException("Failed to add files to the helm git repository: " + e, e); } CommitCommand commit = git.commit().setAll(true).setMessage(commitMessage); PersonIdent author = null; if (Strings.isNotBlank(userName) && Strings.isNotBlank(emailAddress)) { author = new PersonIdent(userName, emailAddress); } if (author != null) { commit = commit.setAuthor(author); } try { RevCommit answer = commit.call(); getLog().info("Committed " + answer.getId() + " " + answer.getFullMessage()); } catch (GitAPIException e) { throw new MojoExecutionException("Failed to commit changes to help repository: " + e, e); } if (pushChanges) { PushCommand push = git.push(); try { push.setRemote(remoteRepoName).call(); getLog().info("Pushed commits upstream to " + getHelmGitUrl()); } catch (GitAPIException e) { throw new MojoExecutionException( "Failed to push helm git changes to remote repository " + remoteRepoName + ": " + e, e); } } }