List of usage examples for org.eclipse.jgit.lib Repository getConfig
@NonNull public abstract StoredConfig getConfig();
From source file:edu.tum.cs.mylyn.provisioning.git.GitProvisioningUtil.java
License:Open Source License
public static URIish getCloneUri(Repository repository) { try {//from w w w . j a v a 2 s .com return getCloneUri(repository.getConfig(), repository.getBranch()); } catch (IOException e) { return null; } }
From source file:edu.tum.cs.mylyn.provisioning.git.ui.GitProvisioningWizard.java
License:Open Source License
private void configureRepository(RepositoryWrapper repositoryInfo, String destinationDirectory, boolean importProjects, IProgressMonitor monitor) { try {/*from w w w .j av a 2 s .c o m*/ File destinationDir = new File(destinationDirectory); File repositoryPath = new File(destinationDir + File.separator + GIT_DIR); FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(repositoryPath).readEnvironment().build(); repository.getConfig().fromText(repositoryInfo.getConfig().toText()); repository.create(); monitor.worked(10); monitor.worked(10); pull(repository); monitor.worked(50); if (importProjects) { importProjects(repository, monitor); } monitor.worked(30); org.eclipse.egit.core.Activator.getDefault().getRepositoryCache().lookupRepository(repositoryPath); } catch (Exception e) { StatusHandler .log(new Status(Status.WARNING, Activator.PLUGIN_ID, "error provisioning git projects", e)); //$NON-NLS-1$ } }
From source file:io.fabric8.collector.git.GitBuildConfigProcessor.java
License:Apache License
protected void doPull(File gitFolder, CredentialsProvider cp, String branch, PersonIdent personIdent, UserDetails userDetails) {//w w w . j a v a 2 s. c om try { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build(); Git git = new Git(repository); File projectFolder = repository.getDirectory(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", userDetails.getRemote(), "url"); if (Strings.isNullOrBlank(url)) { LOG.warn("No remote repository url for " + branch + " defined for the git repository at " + projectFolder.getCanonicalPath() + " so cannot pull"); //return; } String mergeUrl = config.getString("branch", branch, "merge"); if (Strings.isNullOrBlank(mergeUrl)) { LOG.warn("No merge spec for branch." + branch + ".merge in the git repository at " + projectFolder.getCanonicalPath() + " so not doing a pull"); //return; } LOG.debug("Performing a pull in git repository " + projectFolder.getCanonicalPath() + " on remote URL: " + url); PullCommand pull = git.pull(); GitHelpers.configureCommand(pull, userDetails); pull.setRebase(true).call(); } catch (Throwable e) { LOG.error("Failed to pull from the remote git repo with credentials " + cp + " due: " + e.getMessage() + ". This exception is ignored.", e); } }
From source file:io.fabric8.forge.generator.pipeline.JenkinsPipelineLibrary.java
License:Apache License
protected void doPull(File gitFolder, CredentialsProvider cp, String branch, PersonIdent personIdent, UserDetails userDetails) {// www. j a v a2 s . c o m StopWatch watch = new StopWatch(); try { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build(); Git git = new Git(repository); File projectFolder = repository.getDirectory(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", remote, "url"); if (io.fabric8.utils.Strings.isNullOrBlank(url)) { LOG.warn("No remote repository url for " + branch + " defined for the git repository at " + projectFolder.getCanonicalPath() + " so cannot pull"); //return; } String mergeUrl = config.getString("branch", branch, "merge"); if (io.fabric8.utils.Strings.isNullOrBlank(mergeUrl)) { LOG.warn("No merge spec for branch." + branch + ".merge in the git repository at " + projectFolder.getCanonicalPath() + " so not doing a pull"); //return; } // lets trash any failed changes LOG.debug("Stashing local changes to the repo"); boolean hasHead = true; try { git.log().all().call(); hasHead = git.getRepository().getAllRefs().containsKey("HEAD"); } catch (NoHeadException e) { hasHead = false; } if (hasHead) { // lets stash any local changes just in case.. try { git.stashCreate().setPerson(personIdent).setWorkingDirectoryMessage("Stash before a write") .setRef("HEAD").call(); } catch (Throwable e) { LOG.error("Failed to stash changes: " + e, e); Throwable cause = e.getCause(); if (cause != null && cause != e) { LOG.error("Cause: " + cause, cause); } } } //LOG.debug("Resetting the repo"); //git.reset().setMode(ResetCommand.ResetType.HARD).call(); LOG.debug("Performing a pull in git repository " + projectFolder.getCanonicalPath() + " on remote URL: " + url); PullCommand pull = git.pull(); GitUtils.configureCommand(pull, userDetails); pull.setRebase(true).call(); } catch (Throwable e) { LOG.error("Failed to pull from the remote git repo with credentials " + cp + " due: " + e.getMessage() + ". This exception is ignored.", e); } finally { LOG.debug("doPull took " + watch.taken()); } }
From source file:io.fabric8.forge.rest.main.ProjectFileSystem.java
License:Apache License
protected void doPull(File gitFolder, CredentialsProvider cp, String branch) { try {//from w ww . j a v a 2s . c o m FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build(); Git git = new Git(repository); File projectFolder = repository.getDirectory(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", remote, "url"); if (Strings.isNullOrBlank(url)) { LOG.warn("No remote repository url for " + branch + " defined for the git repository at " + projectFolder.getCanonicalPath() + " so cannot pull"); //return; } String mergeUrl = config.getString("branch", branch, "merge"); if (Strings.isNullOrBlank(mergeUrl)) { LOG.warn("No merge spec for branch." + branch + ".merge in the git repository at " + projectFolder.getCanonicalPath() + " so not doing a pull"); //return; } // lets trash any failed changes LOG.info("Resetting the repo"); git.reset().setMode(ResetCommand.ResetType.HARD).call(); LOG.info("Performing a pull in git repository " + projectFolder.getCanonicalPath() + " on remote URL: " + url); git.pull().setCredentialsProvider(cp).setRebase(true).call(); } catch (Throwable e) { LOG.error("Failed to pull from the remote git repo with credentials " + cp + " due: " + e.getMessage() + ". This exception is ignored.", e); } }
From source file:io.fabric8.git.internal.DefaultPullPushPolicy.java
License:Apache License
@Override public synchronized PullPolicyResult doPull(GitContext context, CredentialsProvider credentialsProvider, boolean allowVersionDelete) { Repository repository = git.getRepository(); StoredConfig config = repository.getConfig(); String remoteUrl = config.getString("remote", remoteRef, "url"); if (remoteUrl == null) { LOGGER.debug("No remote repository defined, so not doing a pull"); return new AbstractPullPolicyResult(); }/*from w w w . jav a2 s.co m*/ LOGGER.info("Performing a pull on remote URL: {}", remoteUrl); Exception lastException = null; try { git.fetch().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider).setRemote(remoteRef) .call(); } catch (GitAPIException | JGitInternalException ex) { lastException = ex; } // No meaningful processing after GitAPIException if (lastException != null) { LOGGER.warn("Pull failed because of: {}", lastException.toString()); return new AbstractPullPolicyResult(lastException); } // Get local and remote branches Map<String, Ref> localBranches = new HashMap<String, Ref>(); Map<String, Ref> remoteBranches = new HashMap<String, Ref>(); Set<String> allBranches = new HashSet<String>(); try { for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) { if (ref.getName().startsWith("refs/remotes/" + remoteRef + "/")) { String name = ref.getName().substring(("refs/remotes/" + remoteRef + "/").length()); remoteBranches.put(name, ref); allBranches.add(name); } else if (ref.getName().startsWith("refs/heads/")) { String name = ref.getName().substring(("refs/heads/").length()); localBranches.put(name, ref); allBranches.add(name); } } boolean localUpdate = false; boolean remoteUpdate = false; Set<String> versions = new TreeSet<>(); // Remote repository has no branches, force a push if (remoteBranches.isEmpty()) { LOGGER.debug("Pulled from an empty remote repository"); return new AbstractPullPolicyResult(versions, false, !localBranches.isEmpty(), null); } else { LOGGER.debug("Processing remote branches: {}", remoteBranches); } // Verify master branch and do a checkout of it when we have it locally (already) IllegalStateAssertion.assertTrue(remoteBranches.containsKey(GitHelpers.MASTER_BRANCH), "Remote repository does not have a master branch"); if (localBranches.containsKey(GitHelpers.MASTER_BRANCH)) { git.checkout().setName(GitHelpers.MASTER_BRANCH).setForce(true).call(); } // Iterate over all local/remote branches for (String branch : allBranches) { // Delete a local branch that does not exist remotely, but not master boolean allowDelete = allowVersionDelete && !GitHelpers.MASTER_BRANCH.equals(branch); if (localBranches.containsKey(branch) && !remoteBranches.containsKey(branch)) { if (allowDelete) { LOGGER.debug("Deleting local branch: {}", branch); git.branchDelete().setBranchNames(branch).setForce(true).call(); localUpdate = true; } else { remoteUpdate = true; } } // Create a local branch that exists remotely else if (!localBranches.containsKey(branch) && remoteBranches.containsKey(branch)) { LOGGER.debug("Adding local branch: {}", branch); git.checkout().setCreateBranch(true).setName(branch).setStartPoint(remoteRef + "/" + branch) .setUpstreamMode(SetupUpstreamMode.TRACK).setForce(true).call(); versions.add(branch); localUpdate = true; } // Update a local branch that also exists remotely else if (localBranches.containsKey(branch) && remoteBranches.containsKey(branch)) { ObjectId localObjectId = localBranches.get(branch).getObjectId(); ObjectId remoteObjectId = remoteBranches.get(branch).getObjectId(); String localCommit = localObjectId.getName(); String remoteCommit = remoteObjectId.getName(); if (!localCommit.equals(remoteCommit)) { git.clean().setCleanDirectories(true).call(); git.checkout().setName("HEAD").setForce(true).call(); git.checkout().setName(branch).setForce(true).call(); MergeResult mergeResult = git.merge().setFastForward(FastForwardMode.FF_ONLY) .include(remoteObjectId).call(); MergeStatus mergeStatus = mergeResult.getMergeStatus(); LOGGER.debug("Updating local branch {} with status: {}", branch, mergeStatus); if (mergeStatus == MergeStatus.FAST_FORWARD) { localUpdate = true; } else if (mergeStatus == MergeStatus.ALREADY_UP_TO_DATE) { remoteUpdate = true; } else if (mergeStatus == MergeStatus.ABORTED) { LOGGER.debug("Cannot fast forward branch {}, attempting rebase", branch); RebaseResult rebaseResult = git.rebase().setUpstream(remoteCommit).call(); RebaseResult.Status rebaseStatus = rebaseResult.getStatus(); if (rebaseStatus == RebaseResult.Status.OK) { localUpdate = true; remoteUpdate = true; } else { LOGGER.warn("Rebase on branch {} failed, restoring remote branch", branch); git.rebase().setOperation(Operation.ABORT).call(); git.checkout().setName(GitHelpers.MASTER_BRANCH).setForce(true).call(); git.branchDelete().setBranchNames(branch).setForce(true).call(); git.checkout().setCreateBranch(true).setName(branch) .setStartPoint(remoteRef + "/" + branch) .setUpstreamMode(SetupUpstreamMode.TRACK).setForce(true).call(); localUpdate = true; } } } versions.add(branch); } } PullPolicyResult result = new AbstractPullPolicyResult(versions, localUpdate, remoteUpdate, null); LOGGER.info("Pull result: {}", result); return result; } catch (Exception ex) { return new AbstractPullPolicyResult(ex); } }
From source file:io.fabric8.git.internal.GitDataStore.java
License:Apache License
/** * Pushes any committed changes to the remote repo *//*from w ww . ja v a 2 s . c o 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 ww w . j ava2 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.itests.basic.git.GitUtils.java
License:Apache License
public static void configureBranch(Git git, String remote, String remoteUrl, String branch) { if (git != null && remoteUrl != null && !remoteUrl.isEmpty()) { Repository repository = git.getRepository(); if (repository != null) { StoredConfig config = repository.getConfig(); config.setString("remote", remote, "url", remoteUrl); config.setString("remote", remote, "fetch", "+refs/heads/*:refs/remotes/" + branch + "/*"); config.setString("branch", branch, "merge", "refs/heads/" + branch); config.setString("branch", branch, "remote", "origin"); try { config.save();//from w w w . ja v a 2s .com } catch (IOException e) { //Ignore } } } }
From source file:io.fabric8.maven.CreateBranchMojo.java
License:Apache License
/** * Returns true if the remote git url is defined or the local git repo has a remote url defined *///from w w w.j av a 2 s . c om protected boolean hasRemoteRepo() { if (Strings.isNotBlank(gitUrl)) { return true; } Repository repository = git.getRepository(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", remoteName, "url"); if (Strings.isNotBlank(url)) { return true; } return false; }