List of usage examples for org.eclipse.jgit.api Git getRepository
public Repository getRepository()
From source file:org.exist.git.xquery.Cat.java
License:Open Source License
@Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { try {/* ww w .j a va 2 s .c o m*/ String localPath = args[0].getStringValue(); if (!(localPath.endsWith("/"))) localPath += File.separator; String objPath = args[1].getStringValue(); if (mySignature.getName() == CAT_WORKING_COPY) { Resource resource = new Resource(localPath + objPath); InputStream is = new ResourceInputStream(resource); ; Base64BinaryDocument b64doc = Base64BinaryDocument.getInstance(context, is); return b64doc; } Git git = Git.open(new Resource(localPath), FS); Repository repository = git.getRepository(); // find the HEAD ObjectId lastCommitId = repository.resolve(Constants.HEAD); // now we have to get the commit RevWalk revWalk = new RevWalk(repository); RevCommit commit = revWalk.parseCommit(lastCommitId); // and using commit's tree find the path RevTree tree = commit.getTree(); TreeWalk treeWalk = new TreeWalk(repository); treeWalk.addTree(tree); treeWalk.setRecursive(true); treeWalk.setFilter(PathFilter.create(args[1].getStringValue())); if (!treeWalk.next()) { return Sequence.EMPTY_SEQUENCE; } ObjectId objectId = treeWalk.getObjectId(0); ObjectLoader loader = repository.open(objectId); // and then one can use either InputStream is = loader.openStream(); Base64BinaryDocument b64doc = Base64BinaryDocument.getInstance(context, is); return b64doc; } catch (Throwable e) { throw new XPathException(this, Module.EXGIT001, e); } }
From source file:org.exist.git.xquery.Status.java
License:Open Source License
@Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { try {/*w ww. j av a 2s .co m*/ String localPath = args[0].getStringValue(); if (!(localPath.endsWith("/"))) localPath += File.separator; Git git = Git.open(new Resource(localPath), FS); if (getName().equals(STATUS)) { MemTreeBuilder builder = getContext().getDocumentBuilder(); int nodeNr = builder.startElement(REPOSITORY, null); StatusBuilder statusBuilder = new StatusBuilder(builder); final Repository repo = git.getRepository(); diff(repo, Constants.HEAD, new FileTreeIterator(repo), statusBuilder, args[1].getStringValue(), args[2].effectiveBooleanValue()); builder.endElement(); return builder.getDocument().getNode(nodeNr); } org.eclipse.jgit.api.Status status = git.status().call(); Set<String> list; if (getName().equals(UNTRACKED)) { list = status.getUntracked(); } else if (getName().equals(ADDED)) { list = status.getAdded(); } else if (getName().equals(CHANGED)) { list = status.getChanged(); } else if (getName().equals(CONFLICTING)) { list = status.getConflicting(); } else if (getName().equals(IGNORED)) { list = status.getIgnoredNotInIndex(); } else if (getName().equals(MISSING)) { list = status.getMissing(); } else if (getName().equals(MODIFIED)) { list = status.getModified(); } else if (getName().equals(REMOVED)) { list = status.getRemoved(); } else if (getName().equals(UNTRACKED)) { list = status.getUntracked(); } else if (getName().equals(UNTRACKED_FOLDERS)) { list = status.getUntrackedFolders(); } else { return Sequence.EMPTY_SEQUENCE; } Sequence result = new ValueSequence(); for (String modified : list) { result.add(new StringValue(modified)); } return result; } catch (Throwable e) { e.printStackTrace(); throw new XPathException(this, Module.EXGIT001, e); } }
From source file:org.fedoraproject.eclipse.packager.tests.utils.git.GitConvertTestProject.java
License:Open Source License
/** * Adds a remote repository to the existing local packager project * * @throws Exception//from www . j av a 2 s. c om */ public void addRemoteRepository(String uri, Git git) throws Exception { RemoteConfig config = new RemoteConfig(git.getRepository().getConfig(), "origin"); //$NON-NLS-1$ config.addURI(new URIish(uri)); String dst = Constants.R_REMOTES + config.getName(); RefSpec refSpec = new RefSpec(); refSpec = refSpec.setForceUpdate(true); refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", dst + "/*"); //$NON-NLS-1$ //$NON-NLS-2$ config.addFetchRefSpec(refSpec); config.update(git.getRepository().getConfig()); git.getRepository().getConfig().save(); // fetch all the remote branches, // create corresponding branches locally and merge them FetchCommand fetch = git.fetch(); fetch.setRemote("origin"); //$NON-NLS-1$ fetch.setTimeout(0); fetch.setRefSpecs(refSpec); fetch.call(); // refresh after checkout project.refreshLocal(IResource.DEPTH_INFINITE, null); }
From source file:org.flowerplatform.web.git.GitService.java
License:Open Source License
@RemoteInvocation public boolean cloneRepository(final ServiceInvocationContext context, List<PathFragment> selectedPath, String repositoryUrl, final List<String> selectedBranches, final String remoteName, final boolean cloneAllBranches) { tlCommand.set((InvokeServiceMethodServerCommand) context.getCommand()); final URIish uri; try {/*from ww w. jav a 2s .c o m*/ uri = new URIish(repositoryUrl.trim()); } catch (URISyntaxException e) { context.getCommunicationChannel().appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), e.getReason(), DisplaySimpleMessageClientCommand.ICON_ERROR)); return false; } @SuppressWarnings("unchecked") final Pair<File, Object> node = (Pair<File, Object>) GenericTreeStatefulService .getNodeByPathFor(selectedPath, null); File gitReposFile = GitPlugin.getInstance().getUtils().getGitRepositoriesFile(node.a); final File mainRepo = GitPlugin.getInstance().getUtils() .getMainRepositoryFile(new File(gitReposFile, uri.getHumanishName()), true); final ProgressMonitor monitor = ProgressMonitor.create( GitPlugin.getInstance().getMessage("git.clone.monitor.title", uri), context.getCommunicationChannel()); monitor.beginTask(GitPlugin.getInstance().getMessage("git.clone.monitor.title", uri), 2); Job job = new Job( MessageFormat.format(GitPlugin.getInstance().getMessage("git.clone.monitor.title", uri), uri)) { @Override protected IStatus run(IProgressMonitor m) { Repository repository = null; try { CloneCommand cloneRepository = Git.cloneRepository(); cloneRepository.setNoCheckout(true); cloneRepository.setDirectory(mainRepo); cloneRepository.setProgressMonitor(new GitProgressMonitor(new SubProgressMonitor(monitor, 1))); cloneRepository.setRemote(remoteName); cloneRepository.setURI(uri.toString()); cloneRepository.setTimeout(30); cloneRepository.setCloneAllBranches(cloneAllBranches); cloneRepository.setCloneSubmodules(false); if (selectedBranches.size() > 0) { cloneRepository.setBranchesToClone(selectedBranches); } Git git = cloneRepository.call(); repository = git.getRepository(); // notify clients about changes dispatchContentUpdate(node); monitor.worked(1); } catch (Exception e) { if (repository != null) repository.close(); GitPlugin.getInstance().getUtils().delete(mainRepo.getParentFile()); if (monitor.isCanceled()) { return Status.OK_STATUS; } if (GitPlugin.getInstance().getUtils().isAuthentificationException(e)) { openLoginWindow(); return Status.OK_STATUS; } logger.debug(GitPlugin.getInstance().getMessage("git.cloneWizard.error", new Object[] { mainRepo.getName() }), e); context.getCommunicationChannel() .appendOrSendCommand(new DisplaySimpleMessageClientCommand( CommonPlugin.getInstance().getMessage("error"), GitPlugin.getInstance().getMessage("git.cloneWizard.error", new Object[] { mainRepo.getName() }), DisplaySimpleMessageClientCommand.ICON_ERROR)); return Status.CANCEL_STATUS; } finally { monitor.done(); if (repository != null) { repository.close(); } } return Status.OK_STATUS; } }; job.schedule(); return true; }
From source file:org.fusesource.fabric.git.http.GitHttpServerRegistrationHandler.java
License:Apache License
private synchronized void registerServlet() { try {/* w ww .j a v a2s.c o m*/ HttpContext base = httpService.get().createDefaultHttpContext(); HttpContext secure = new SecureHttpContext(base, realm, role); String basePath = System.getProperty("karaf.data") + File.separator + "git" + File.separator + "servlet" + File.separator; String fabricGitPath = basePath + "fabric"; File fabricRoot = new File(fabricGitPath); //Only need to clone once. If repo already exists, just skip. if (!fabricRoot.exists()) { Git localGit = gitService.get().get(); Git.cloneRepository().setBare(true).setNoCheckout(true).setCloneAllBranches(true) .setDirectory(fabricRoot).setURI(localGit.getRepository().getDirectory().toURI().toString()) .call(); } Dictionary<String, Object> initParams = new Hashtable<String, Object>(); initParams.put("base-path", basePath); initParams.put("repository-root", basePath); initParams.put("export-all", "true"); httpService.get().registerServlet("/git", gitServlet, initParams, secure); activateComponent(); } catch (Exception e) { FabricException.launderThrowable(e); } }
From source file:org.fusesource.fabric.git.internal.GitDataStore.java
License:Apache License
@Override public List<String> getVersions() { assertValid();/*from w w w .j a v a 2s . c o m*/ return gitReadOperation(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); } } } return answer; } }); }
From source file:org.fusesource.fabric.git.internal.GitDataStore.java
License:Apache License
public <T> T gitOperation(PersonIdent personIdent, GitOperation<T> operation, boolean pullFirst, GitContext context) {//from w w w. j a v a2 s . c o m synchronized (gitOperationMonitor) { assertValid(); try { Git git = getGit(); Repository repository = git.getRepository(); CredentialsProvider credentialsProvider = getCredentialsProvider(); // 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(); } String originalBranch = repository.getBranch(); RevCommit statusBefore = CommitUtils.getHead(repository); if (pullFirst) { doPull(git, credentialsProvider); } 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(); } git.checkout().setName(originalBranch).call(); if (requirePush || hasChanged(statusBefore, CommitUtils.getHead(repository))) { clearCaches(); doPush(git, context, credentialsProvider); fireChangeNotifications(); } return answer; } catch (Exception e) { throw FabricException.launderThrowable(e); } } }
From source file:org.fusesource.fabric.git.internal.GitDataStore.java
License:Apache License
/** * Pushes any committed changes to the remote repo *//*w w w . j a v 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 *//*from ww w .j a va 2 s . c o m*/ 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.fusesource.fabric.git.internal.GitHelpers.java
License:Apache License
public static String currentBranch(Git git) { try {//from w w w . j a va 2 s . c o m return git.getRepository().getBranch(); } catch (IOException e) { LOG.warn("Failed to get the current branch: " + e, e); return null; } }