List of usage examples for org.eclipse.jgit.api Git getRepository
public Repository getRepository()
From source file:io.fabric8.git.internal.GitDataStoreImpl.java
License:Apache License
private <T> T executeInternal(GitContext context, PersonIdent personIdent, GitOperation<T> operation) { if (context.isRequirePull() || context.isRequireCommit()) { assertWriteLock();/*from w ww.j av a 2s .c o m*/ } else { assertReadLock(); } // [FABRIC-887] 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) ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { ClassLoader gitcl = GitDataStoreImpl.class.getClassLoader(); Thread.currentThread().setContextClassLoader(gitcl); LOGGER.trace("Setting ThreadContextClassLoader to {} instead of {}", gitcl, tccl); Git git = getGit(); Repository repository = git.getRepository(); if (personIdent == null) { personIdent = new PersonIdent(repository); } if (context.isRequirePull()) { doPullInternal(context, getCredentialsProvider(), false); } T result = operation.call(git, context); if (context.isRequireCommit()) { doCommit(git, context); versionCache.invalidateAll(); notificationRequired = true; } if (context.isRequirePush()) { PushPolicyResult pushResult = doPushInternal(context, getCredentialsProvider()); if (!pushResult.getRejectedUpdates().isEmpty()) { Exception gitex = pushResult.getLastException(); throw new IllegalStateException("Push rejected: " + pushResult.getRejectedUpdates(), gitex); } } return result; } catch (Exception e) { throw FabricException.launderThrowable(e); } finally { LOGGER.trace("Restoring ThreadContextClassLoader to {}", tccl); Thread.currentThread().setContextClassLoader(tccl); } }
From source file:io.fabric8.git.internal.GitHelpers.java
License:Apache License
/** * Returns the root directory of the git repo which contains the ".git" directory */// w w w . ja v a2 s.co m public static File getRootGitDirectory(Git git) { return git.getRepository().getDirectory().getParentFile(); }
From source file:io.fabric8.git.internal.GitHelpers.java
License:Apache License
private static RevCommit getLastCommit(Git git, String branch, String path) { RevCommit profileRef = null;/*from w ww. j av a 2s . c o m*/ try { Ref versionRef = git.getRepository().getRefDatabase().getRef(branch); if (versionRef != null) { String revision = versionRef.getObjectId().getName(); profileRef = CommitUtils.getLastCommit(git.getRepository(), revision, path != null ? path : "."); } } catch (IOException ex) { // ignore } return profileRef; }
From source file:io.fabric8.git.internal.GitHelpers.java
License:Apache License
public static String currentBranch(Git git) { String branch = null;/*from www . j a v a2 s. c om*/ Exception gitException = null; try { branch = git.getRepository().getBranch(); } catch (Exception ex) { gitException = ex; } if (branch == null || gitException != null) { throw new IllegalStateException("Failed to get the current branch", gitException); } return branch; }
From source file:io.fabric8.git.internal.GitHelpers.java
License:Apache License
public static boolean hasGitHead(Git git) throws GitAPIException, IOException { boolean hasHead = true; try {//from w w w . jav a 2 s . com git.log().all().call(); hasHead = git.getRepository().getAllRefs().containsKey("HEAD"); } catch (NoHeadException e) { hasHead = false; } return hasHead; }
From source file:io.fabric8.git.internal.GitHelpers.java
License:Apache License
protected static void configureBranch(Git git, String branch, String remote) { // lets update the merge config if (Strings.isNotBlank(branch)) { StoredConfig config = git.getRepository().getConfig(); if (Strings.isNullOrBlank(config.getString("branch", branch, "remote")) || Strings.isNullOrBlank(config.getString("branch", branch, "merge"))) { config.setString("branch", branch, "remote", remote); config.setString("branch", branch, "merge", "refs/heads/" + branch); try { config.save();//from w ww .ja va 2 s .c o m } catch (IOException e) { LOGGER.error("Failed to configure the branch configuration to " + getRootGitDirectory(git) + " with branch " + branch + " on remote repo: " + remote + ". " + e, e); } } } }
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 . ja va2 s .c o 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.git.zkbridge.Bridge.java
License:Apache License
private static File getGitProfilesDirectory(Git git) { // TODO allow us to move the profile tree to a sub directory in the git repo return git.getRepository().getWorkTree(); }
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 w w.ja v a 2 s . c o m*/ 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.itests.basic.git.FabricGitTestSupport.java
License:Apache License
/** * Create a profile in the registry and check that its bridged to git. *///w w w . ja v a2 s . com protected void createAndTestProfileInDataStore(FabricService fabricService, CuratorFramework curator, Git git, String version, String profile) throws Exception { System.out.println("Create test profile:" + profile + " in datastore."); List<String> versions = Lists.transform(Arrays.<Version>asList(fabricService.getVersions()), new Function<Version, String>() { @Override public String apply(Version version) { return version.getId(); } }); if (!versions.contains(version)) { fabricService.createVersion(version); } fabricService.getDataStore().createProfile(version, profile); GitUtils.waitForBranchUpdate(curator, version); GitUtils.checkoutBranch(git, "origin", version); PullResult pullResult = git.pull().setCredentialsProvider(getCredentialsProvider()).setRebase(true).call(); assertTrue(pullResult.isSuccessful()); String relativeProfileDir = "fabric/profiles/" + profile + ".profile"; File testProfileDir = new File(git.getRepository().getWorkTree(), relativeProfileDir); assertTrue(testProfileDir.exists()); File testProfileConfig = new File(testProfileDir, "io.fabric8.agent.properties"); assertTrue(testProfileConfig.exists()); }