List of usage examples for org.eclipse.jgit.api Git getRepository
public Repository getRepository()
From source file:io.fabric8.forge.rest.main.GitCommandCompletePostProcessor.java
License:Apache License
/** * Returns the remote git URL for the given branch *//*from ww w . j a v a2 s .com*/ protected String getRemoteURL(Git git, String branch) { StoredConfig config = git.getRepository().getConfig(); return config.getString("branch", branch, "remote"); }
From source file:io.fabric8.forge.rest.main.GitCommandCompletePostProcessor.java
License:Apache License
protected void configureBranch(Git git, String branch, String origin, String remoteRepository) { // lets update the merge config if (!Strings.isNullOrEmpty(branch)) { StoredConfig config = git.getRepository().getConfig(); config.setString("branch", branch, "remote", origin); config.setString("branch", branch, "merge", "refs/heads/" + branch); config.setString("remote", origin, "url", remoteRepository); config.setString("remote", origin, "fetch", "+refs/heads/*:refs/remotes/" + origin + "/*"); try {// w w w . j a v a 2 s.c om config.save(); } catch (IOException e) { LOG.error("Failed to save the git configuration to " + git.getRepository().getDirectory() + " with branch " + branch + " on " + origin + " remote repo: " + remoteRepository + " due: " + e.getMessage() + ". This exception is ignored.", e); } } }
From source file:io.fabric8.git.internal.CachingGitDataStore.java
License:Apache License
private void addProfileData(Git git, String version, VersionData data, File file, String prefix) throws IOException { // TODO we could recursively scan for magic ".profile" files or something // then we could put profiles into nicer tree structure? String profile = file.getName(); if (Profiles.useDirectoriesForProfiles) { if (profile.endsWith(Profiles.PROFILE_FOLDER_SUFFIX)) { profile = prefix + profile.substring(0, profile.length() - Profiles.PROFILE_FOLDER_SUFFIX.length()); } else {/*www .j a va2s . c om*/ // lets recurse all children File[] files = file.listFiles(); if (files != null) { for (File child : files) { if (child.isDirectory()) { addProfileData(git, version, data, child, prefix + file.getName() + "-"); } } } return; } } String revision = git.getRepository().getRefDatabase().getRef(version).getObjectId().getName(); String path = convertProfileIdToDirectory(profile); RevCommit commit = CommitUtils.getLastCommit(git.getRepository(), revision, CONFIGS_PROFILES + File.separator + path); String lastModified = commit != null ? commit.getId().abbreviate(GIT_COMMIT_SHORT_LENGTH).name() : ""; Map<String, byte[]> configurations = doGetFileConfigurations(git, profile); Map<String, Map<String, String>> substituted = new HashMap<String, Map<String, String>>(); for (Map.Entry<String, byte[]> entry : configurations.entrySet()) { if (entry.getKey().endsWith(".properties")) { String pid = DataStoreUtils.stripSuffix(entry.getKey(), ".properties"); substituted.put(pid, DataStoreUtils.toMap(DataStoreUtils.toProperties(entry.getValue()))); } } ProfileData profileData = new ProfileData(lastModified, Collections.unmodifiableMap(configurations), Collections.unmodifiableMap(substituted)); data.profiles.put(profile, profileData); }
From source file:io.fabric8.git.internal.GitDataStore.java
License:Apache License
protected List<String> forceGetVersions() { return gitOperation(new GitOperation<List<String>>() { public List<String> call(Git git, GitContext context) throws Exception { Collection<String> branches = RepositoryUtils.getBranches(git.getRepository()); List<String> answer = new ArrayList<String>(); for (String branch : branches) { String name = branch; String prefix = "refs/heads/"; if (name.startsWith(prefix)) { name = name.substring(prefix.length()); if (!name.equals(MASTER_BRANCH)) { answer.add(name); }/*from ww w.j a v a2s.c o m*/ } } versions.clear(); versions.addAll(answer); return answer; } }, false); }
From source file:io.fabric8.git.internal.GitDataStore.java
License:Apache License
@Override public String getLastModified(final String version, final String profile) { assertValid();//ww w . ja v a 2 s . c om String answer = gitOperation(new GitOperation<String>() { public String call(Git git, GitContext context) throws Exception { String revision = git.getRepository().getRefDatabase().getRef(version).getObjectId().getName(); String path = convertProfileIdToDirectory(profile); RevCommit commit = CommitUtils.getLastCommit(git.getRepository(), revision, CONFIGS_PROFILES + File.separator + path); return commit != null ? commit.getId().abbreviate(GIT_COMMIT_SHORT_LENGTH).name() : ""; } }, false); return answer != null ? 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) {//from w w w. ja v a 2s. c o m 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.GitDataStore.java
License:Apache License
/** * Pushes any committed changes to the remote repo *//*from ww w. j a va2 s .co m*/ protected Iterable<PushResult> doPush(Git git, GitContext gitContext, CredentialsProvider credentialsProvider) throws Exception { assertValid(); try { Repository repository = git.getRepository(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", remoteRef.get(), "url"); if (Strings.isNullOrBlank(url)) { LOG.info("No remote repository defined yet for the git repository at " + GitHelpers.getRootGitDirectory(git) + " so not doing a push"); return Collections.emptyList(); } return git.push().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider).setPushAll() .call(); } catch (Throwable ex) { // log stacktrace at debug level LOG.warn("Failed to push from the remote git repo " + GitHelpers.getRootGitDirectory(git) + " due " + ex.getMessage() + ". This exception is ignored."); LOG.debug("Failed to push from the remote git repo " + GitHelpers.getRootGitDirectory(git) + ". This exception is ignored.", ex); return Collections.emptyList(); } }
From source file:io.fabric8.git.internal.GitDataStore.java
License:Apache License
/** * Performs a pull so the git repo is pretty much up to date before we start performing operations on it. * * @param git The {@link Git} instance to use. * @param credentialsProvider The {@link CredentialsProvider} to use. * @param doDeleteBranches Flag that determines if local branches that don't exist in remote should get deleted. *//*from w w w. ja va 2 s. c o m*/ protected void doPull(Git git, CredentialsProvider credentialsProvider, boolean doDeleteBranches) { assertValid(); try { Repository repository = git.getRepository(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", remoteRef.get(), "url"); if (Strings.isNullOrBlank(url)) { if (LOG.isDebugEnabled()) { LOG.debug("No remote repository defined for the git repository at " + GitHelpers.getRootGitDirectory(git) + " so not doing a pull"); } return; } /* String branch = repository.getBranch(); String mergeUrl = config.getString("branch", branch, "merge"); if (Strings.isNullOrBlank(mergeUrl)) { if (LOG.isDebugEnabled()) { LOG.debug("No merge spec for branch." + branch + ".merge in the git repository at " + GitHelpers.getRootGitDirectory(git) + " so not doing a pull"); } return; } */ if (LOG.isDebugEnabled()) { LOG.debug("Performing a fetch in git repository " + GitHelpers.getRootGitDirectory(git) + " on remote URL: " + url); } boolean hasChanged = false; try { FetchResult result = git.fetch().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider) .setRemote(remoteRef.get()).call(); if (LOG.isDebugEnabled()) { LOG.debug("Git fetch result: {}", result.getMessages()); } lastFetchWarning = null; } catch (Exception ex) { String fetchWarning = ex.getMessage(); if (!fetchWarning.equals(lastFetchWarning)) { LOG.warn("Fetch failed because of: " + fetchWarning); LOG.debug("Fetch failed - the error will be ignored", ex); lastFetchWarning = fetchWarning; } return; } // Get local and remote branches 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/" + remoteRef.get() + "/")) { String name = ref.getName().substring(("refs/remotes/" + remoteRef.get() + "/").length()); remoteBranches.put(name, ref); gitVersions.add(name); } else if (ref.getName().startsWith("refs/heads/")) { String name = ref.getName().substring(("refs/heads/").length()); localBranches.put(name, ref); gitVersions.add(name); } } // Check git commits for (String version : gitVersions) { // Delete unneeded local branches. //Check if any remote branches was found as a guard for unwanted deletions. if (remoteBranches.isEmpty()) { //Do nothing } else if (!remoteBranches.containsKey(version)) { //We never want to delete the master branch. if (doDeleteBranches && !version.equals(MASTER_BRANCH)) { try { git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true) .call(); } catch (CannotDeleteCurrentBranchException ex) { git.checkout().setName(MASTER_BRANCH).setForce(true).call(); git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true) .call(); } removeVersion(version); hasChanged = true; } } // Create new local branches else if (!localBranches.containsKey(version)) { addVersion(version); git.checkout().setCreateBranch(true).setName(version) .setStartPoint(remoteRef.get() + "/" + version) .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).setForce(true).call(); hasChanged = true; } else { String localCommit = localBranches.get(version).getObjectId().getName(); String remoteCommit = remoteBranches.get(version).getObjectId().getName(); if (!localCommit.equals(remoteCommit)) { git.clean().setCleanDirectories(true).call(); git.checkout().setName("HEAD").setForce(true).call(); git.checkout().setName(version).setForce(true).call(); MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS) .include(remoteBranches.get(version).getObjectId()).call(); if (result.getMergeStatus() != MergeResult.MergeStatus.ALREADY_UP_TO_DATE && hasChanged(git, localCommit, remoteCommit)) { hasChanged = true; } // TODO: handle conflicts } } } if (hasChanged) { LOG.debug("Changed after pull!"); if (credentialsProvider != null) { // TODO lets test if the profiles directory is present after checking out version 1.0? getProfilesDirectory(git); } fireChangeNotifications(); } } catch (Throwable ex) { LOG.debug("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git), ex); LOG.warn("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git) + " due " + ex.getMessage() + ". This exception is ignored."); } }
From source file:io.fabric8.git.internal.GitDataStore.java
License:Apache License
/** * Checks if there is an actual difference between two commits. * In some cases a container may push a commit, without actually modifying anything. * So comparing the commit hashes is not always enough. We need to actually diff the two commits. * * @param git The {@link Git} instance to use. * @param before The hash of the first commit. * @param after The hash of the second commit. *///from www . j a v a 2 s . c o m private boolean hasChanged(Git git, String before, String after) throws IOException, GitAPIException { if (isCommitEqual(before, after)) { return false; } Repository db = git.getRepository(); List<DiffEntry> entries = git.diff().setOldTree(getTreeIterator(db, before)) .setNewTree(getTreeIterator(db, after)).call(); return entries.size() > 0; }
From source file:io.fabric8.git.internal.GitDataStoreImpl.java
License:Apache License
private List<String> getInitialVersions() { LockHandle readLock = aquireReadLock(); try {/* w w w. ja v a 2 s.co m*/ GitOperation<List<String>> gitop = new GitOperation<List<String>>() { public List<String> call(Git git, GitContext context) throws Exception { Collection<String> branches = RepositoryUtils.getBranches(git.getRepository()); List<String> answer = new ArrayList<String>(); for (String branch : branches) { String name = branch; String prefix = "refs/heads/"; if (name.startsWith(prefix)) { name = name.substring(prefix.length()); if (!name.equals(GitHelpers.MASTER_BRANCH)) { answer.add(name); } } } versions.clear(); versions.addAll(answer); return answer; } }; return executeRead(gitop); } finally { readLock.unlock(); } }