List of usage examples for org.eclipse.jgit.lib Repository getConfig
@NonNull public abstract StoredConfig getConfig();
From source file:org.flowerplatform.web.git.GitService.java
License:Open Source License
@RemoteInvocation public ConfigBranchPageDto getConfigBranchData(ServiceInvocationContext context, List<PathFragment> path) { try {/*from w w w. ja v a 2 s . c om*/ RefNode node = (RefNode) GenericTreeStatefulService.getNodeByPathFor(path, null); Repository repository = node.getRepository(); StoredConfig config = repository.getConfig(); ConfigBranchPageDto dto = new ConfigBranchPageDto(); Ref branch = (Ref) node.getRef(); dto.setRef(new GitRef(branch.getName(), Repository.shortenRefName(branch.getName()))); List<RemoteConfig> remotes = getAllRemotes(context, path); String branchName = branch.getName().substring(Constants.R_HEADS.length()); String branchConfig = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_MERGE); String remoteConfig = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REMOTE); if (remoteConfig == null) { remoteConfig = ""; } if (remotes != null) { dto.setRemotes(remotes); for (RemoteConfig remote : remotes) { if (remote.getName().equals(remoteConfig)) { List<Object> branches = getBranches(context, remote.getUri()); if (branches != null) { @SuppressWarnings("unchecked") List<GitRef> refs = (List<GitRef>) branches.get(0); for (GitRef ref : refs) { if (ref.getName().equals(branchConfig)) { dto.setSelectedRef(ref); break; } } dto.setRefs(refs); } dto.setSelectedRemote(remote); break; } } } boolean rebaseFlag = config.getBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REBASE, false); dto.setRebase(rebaseFlag); return dto; } catch (Exception e) { logger.debug(CommonPlugin.getInstance().getMessage("error"), path, e); context.getCommunicationChannel().appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR)); return null; } }
From source file:org.flowerplatform.web.git.GitService.java
License:Open Source License
@RemoteInvocation public boolean configBranch(ServiceInvocationContext context, List<PathFragment> path, GitRef upstreamBranch, RemoteConfig remote, boolean rebase) { try {/*w ww . jav a 2 s . c o m*/ RefNode node = (RefNode) GenericTreeStatefulService.getNodeByPathFor(path, null); Repository repository = node.getRepository(); StoredConfig config = repository.getConfig(); Ref ref; if (node instanceof Ref) { ref = node.getRef(); } else { // get remote branch String dst = Constants.R_REMOTES + remote.getName(); String remoteRefName = dst + "/" + upstreamBranch.getShortName(); ref = repository.getRef(remoteRefName); if (ref == null) { // doesn't exist, fetch it RefSpec refSpec = new RefSpec(); refSpec = refSpec.setForceUpdate(true); refSpec = refSpec.setSourceDestination(upstreamBranch.getName(), remoteRefName); new Git(repository).fetch().setRemote(new URIish(remote.getUri()).toPrivateString()) .setRefSpecs(refSpec).call(); ref = repository.getRef(remoteRefName); } } String branchName = node.getRef().getName().substring(Constants.R_HEADS.length()); if (upstreamBranch.getName().length() > 0) { config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_MERGE, upstreamBranch.getName()); } else { config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_MERGE); } if (remote.getName().length() > 0) { config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REMOTE, remote.getName()); } else { config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REMOTE); } if (rebase) { config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REBASE, true); } else { config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REBASE); } config.save(); return true; } catch (Exception e) { logger.debug(CommonPlugin.getInstance().getMessage("error"), path, e); context.getCommunicationChannel().appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR)); return false; } }
From source file:org.flowerplatform.web.git.GitService.java
License:Open Source License
@RemoteInvocation public boolean openCredentials(ServiceInvocationContext context, List<PathFragment> path) { try {/*from ww w. j a v a 2s . c o m*/ RemoteNode remoteNode = (RemoteNode) GenericTreeStatefulService.getNodeByPathFor(path, null); Repository repository = remoteNode.getRepository(); if (repository == null) { context.getCommunicationChannel() .appendOrSendCommand(new DisplaySimpleMessageClientCommand( CommonPlugin.getInstance().getMessage("error"), "Cannot find repository for node " + remoteNode, DisplaySimpleMessageClientCommand.ICON_ERROR)); return false; } org.eclipse.jgit.transport.RemoteConfig repoConfig = new org.eclipse.jgit.transport.RemoteConfig( repository.getConfig(), remoteNode.getRemote()); URIish uri = repoConfig.getURIs().get(0); List<String> credentials = ((FlowerWebPrincipal) CommunicationPlugin.tlCurrentPrincipal.get()) .getUserGitRepositories().get(uri.toString()); context.getCommunicationChannel().appendOrSendCommand(new OpenGitCredentialsWindowClientCommand( uri.toString(), credentials != null ? credentials.get(0) : "")); return true; } catch (Exception e) { logger.debug(GitPlugin.getInstance().getMessage("git.changeCredentials.error"), e); context.getCommunicationChannel().appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), GitPlugin.getInstance().getMessage("git.changeCredentials.error"), e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR)); return false; } }
From source file:org.flowerplatform.web.git.GitService.java
License:Open Source License
@RemoteInvocation public boolean clearCredentials(ServiceInvocationContext context, List<PathFragment> path) { try {// w w w.j a v a 2 s . com RemoteNode remoteNode = (RemoteNode) GenericTreeStatefulService.getNodeByPathFor(path, null); Repository repository = remoteNode.getRepository(); if (repository == null) { context.getCommunicationChannel() .appendOrSendCommand(new DisplaySimpleMessageClientCommand( CommonPlugin.getInstance().getMessage("error"), "Cannot find repository for node " + remoteNode, DisplaySimpleMessageClientCommand.ICON_ERROR)); return false; } org.eclipse.jgit.transport.RemoteConfig repoConfig = new org.eclipse.jgit.transport.RemoteConfig( repository.getConfig(), remoteNode.getRemote()); URIish uri = repoConfig.getURIs().get(0); ((FlowerWebPrincipal) CommunicationPlugin.tlCurrentPrincipal.get()).getUserGitRepositories() .remove(uri.toString()); return true; } catch (Exception e) { logger.debug(GitPlugin.getInstance().getMessage("git.clearCredentials.error"), e); context.getCommunicationChannel().appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), GitPlugin.getInstance().getMessage("git.clearCredentials.error"), e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR)); return false; } }
From source file:org.flowerplatform.web.git.GitUtils.java
License:Open Source License
@SuppressWarnings("restriction") public Object[] getFetchPushUpstreamDataRefSpecAndRemote(Repository repository) throws InvalidConfigurationException, NoHeadException, DetachedHeadException { String branchName;/*from www .ja v a 2 s . co m*/ String fullBranch; try { fullBranch = repository.getFullBranch(); if (fullBranch == null) { throw new NoHeadException(JGitText.get().pullOnRepoWithoutHEADCurrentlyNotSupported); } if (!fullBranch.startsWith(Constants.R_HEADS)) { // we can not pull if HEAD is detached and branch is not // specified explicitly throw new DetachedHeadException(); } branchName = fullBranch.substring(Constants.R_HEADS.length()); } catch (IOException e) { throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfPullCommand, e); } // get the configured remote for the currently checked out branch // stored in configuration key branch.<branch name>.remote Config repoConfig = repository.getConfig(); String remote = repoConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REMOTE); if (remote == null) { // fall back to default remote remote = Constants.DEFAULT_REMOTE_NAME; } // get the name of the branch in the remote repository // stored in configuration key branch.<branch name>.merge String remoteBranchName = repoConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_MERGE); if (remoteBranchName == null) { String missingKey = ConfigConstants.CONFIG_BRANCH_SECTION + "." + branchName + "." + ConfigConstants.CONFIG_KEY_MERGE; throw new InvalidConfigurationException( MessageFormat.format(JGitText.get().missingConfigurationForKey, missingKey)); } // check if the branch is configured for pull-rebase boolean doRebase = repoConfig.getBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REBASE, false); final boolean isRemote = !remote.equals("."); //$NON-NLS-1$ String remoteUri; if (isRemote) { remoteUri = repoConfig.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remote, ConfigConstants.CONFIG_KEY_URL); if (remoteUri == null) { String missingKey = ConfigConstants.CONFIG_REMOTE_SECTION + "." + remote + "." + ConfigConstants.CONFIG_KEY_URL; throw new InvalidConfigurationException( MessageFormat.format(JGitText.get().missingConfigurationForKey, missingKey)); } return new Object[] { fullBranch, remoteBranchName, remoteUri, doRebase }; } return null; }
From source file:org.flowerplatform.web.git.GitUtils.java
License:Open Source License
/** * This method must be used to set user configuration before running * some GIT commands that uses it.// w w w.j av a 2s. c o m * * <p> * A lock/unlock on repository is done before/after the command is executed * because the configuration modifies the same file and this will not be * thread safe any more. */ public Object runGitCommandInUserRepoConfig(Repository repo, GitCommand<?> command) throws Exception { namedLockPool.lock(repo.getDirectory().getPath()); try { StoredConfig c = repo.getConfig(); c.load(); User user = (User) CommunicationPlugin.tlCurrentPrincipal.get().getUser(); c.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_NAME, user.getName()); c.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_EMAIL, user.getEmail()); c.save(); return command.call(); } catch (Exception e) { throw e; } finally { namedLockPool.unlock(repo.getDirectory().getPath()); } }
From source file:org.fusesource.fabric.git.internal.GitDataStore.java
License:Apache License
/** * Pushes any committed changes to the remote repo */// w ww .jav a 2 s . c om protected Iterable<PushResult> doPush(Git git, GitContext gitContext, CredentialsProvider credentialsProvider) throws Exception { assertValid(); Repository repository = git.getRepository(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", remote, "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.EMPTY_LIST; } String branch = gitContext != null && gitContext.getPushBranch() != null ? gitContext.getPushBranch() : GitHelpers.currentBranch(git); if (!branch.equals(MASTER_BRANCH)) { return git.push().setCredentialsProvider(credentialsProvider) .setRefSpecs(new RefSpec(MASTER_BRANCH), new RefSpec(branch)).call(); } else { return git.push().setCredentialsProvider(credentialsProvider).setRefSpecs(new RefSpec(branch)).call(); } }
From source file:org.fusesource.fabric.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 *//* ww w . j a v a 2 s . c om*/ protected void doPull(Git git, CredentialsProvider credentialsProvider) { assertValid(); try { Repository repository = git.getRepository(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", remote, "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 { git.fetch().setCredentialsProvider(credentialsProvider).setRemote(remote).call(); } catch (Exception e) { LOG.debug("Fetch failed. Ignoring"); 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/" + remote + "/")) { String name = ref.getName().substring(("refs/remotes/" + remote + "/").length()); if (!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.endsWith("-tmp")) { localBranches.put(name, ref); gitVersions.add(name); } } } // Check git commmits for (String version : gitVersions) { // Delete unneeded local branches. //Check if any remote branches was found as a guard for unwanted deletions. if (!remoteBranches.containsKey(version) && !remoteBranches.isEmpty()) { //We never want to delete the master branch. if (!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(); } hasChanged = true; } } // Create new local branches else if (!localBranches.containsKey(version)) { git.checkout().setCreateBranch(true).setName(version).setStartPoint(remote + "/" + 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 = 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? File profilesDirectory = getProfilesDirectory(git); } fireChangeNotifications(); } } catch (Throwable e) { LOG.error("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git) + ". Reason: " + e, e); } }
From source file:org.gitective.core.RepositoryUtils.java
License:Open Source License
/** * Does the given remote exist in the repository? * * @param repository//from ww w .j av a 2 s.com * @param remote * @return true if exists, false otherwise * @throws URISyntaxException */ protected static boolean hasRemote(final Repository repository, final String remote) throws URISyntaxException { final RemoteConfig config = new RemoteConfig(repository.getConfig(), remote); return !config.getURIs().isEmpty() || !config.getPushURIs().isEmpty(); }
From source file:org.gitective.tests.RepositoryUtilsTest.java
License:Open Source License
/** * Test one origin change//from www.ja v a2 s .c om * * * @throws Exception */ @Test public void oneOriginChange() throws Exception { RevCommit commit1 = add("test.txt", "content"); File repo2 = initRepo(); RevCommit commit2 = add(repo2, "test2.txt", "content2.txt"); Repository repo = new FileRepository(testRepo); RefUpdate originMaster = repo .updateRef(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER); originMaster.setNewObjectId(commit1); originMaster.forceUpdate(); RemoteConfig config = new RemoteConfig(repo.getConfig(), Constants.DEFAULT_REMOTE_NAME); config.addURI(new URIish(repo2.toURI().toString())); config.update(repo.getConfig()); Collection<RefDiff> diffs = RepositoryUtils.diffOriginRefs(repo); assertNotNull(diffs); assertFalse(diffs.isEmpty()); assertNotNull(diffs.iterator().next().getLocal()); assertNotNull(diffs.iterator().next().getRemote()); assertEquals(commit1, diffs.iterator().next().getLocal().getObjectId()); assertEquals(commit2, diffs.iterator().next().getRemote().getObjectId()); }