/** * Gets a list of all the bundles that can be added as implicit dependencies * * @return list of possible dependencies */ protected BundleInfo[] getValidBundles() throws CoreException { NameVersionDescriptor[] current = getTargetDefinition().getImplicitDependencies(); Set<String> currentBundles = new HashSet<String>(); if (current != null) { for (int i = 0; i < current.length; i++) { if (!currentBundles.contains(current[i].getId())) { currentBundles.add(current[i].getId()); } } } List<BundleInfo> targetBundles = new ArrayList<BundleInfo>(); TargetBundle[] allTargetBundles = getTargetDefinition().getAllBundles(); if (allTargetBundles == null || allTargetBundles.length == 0) { throw new CoreException( new Status( IStatus.WARNING, PDEPlugin.getPluginId(), PDEUIMessages.ImplicitDependenciesSection_0)); } for (int i = 0; i < allTargetBundles.length; i++) { BundleInfo bundleInfo = allTargetBundles[i].getBundleInfo(); if (!currentBundles.contains(bundleInfo.getSymbolicName())) { currentBundles.add(bundleInfo.getSymbolicName()); // to avoid duplicate entries targetBundles.add(bundleInfo); } } return targetBundles.toArray(new BundleInfo[targetBundles.size()]); }
private void readOldState(DataInputStream dis) throws IOException, TeamException { int repoSize = dis.readInt(); boolean version1 = false; if (repoSize == STATE_FILE_VERSION_1) { version1 = true; repoSize = dis.readInt(); } for (int i = 0; i < repoSize; i++) { ICVSRepositoryLocation root = KnownRepositories.getInstance().getRepository(dis.readUTF()); RepositoryRoot repoRoot = getRepositoryRootFor(root); // read branch tags associated with this root int tagsSize = dis.readInt(); CVSTag[] branchTags = new CVSTag[tagsSize]; for (int j = 0; j < tagsSize; j++) { String tagName = dis.readUTF(); int tagType = dis.readInt(); branchTags[j] = new CVSTag(tagName, tagType); } // Ignore the branch tags since they are handled differently now // addBranchTags(root, branchTags); // read the number of projects for this root that have version tags int projSize = dis.readInt(); if (projSize > 0) { for (int j = 0; j < projSize; j++) { String name = dis.readUTF(); Set tagSet = new HashSet(); int numTags = dis.readInt(); for (int k = 0; k < numTags; k++) { tagSet.add(new CVSTag(dis.readUTF(), CVSTag.VERSION)); } CVSTag[] tags = (CVSTag[]) tagSet.toArray(new CVSTag[tagSet.size()]); repoRoot.addTags(name, tags); } } // read the auto refresh filenames for this project if (version1) { try { projSize = dis.readInt(); if (projSize > 0) { for (int j = 0; j < projSize; j++) { String name = dis.readUTF(); Set filenames = new HashSet(); int numFilenames = dis.readInt(); for (int k = 0; k < numFilenames; k++) { filenames.add(name + "/" + dis.readUTF()); // $NON-NLS-1$ } repoRoot.setAutoRefreshFiles( name, (String[]) filenames.toArray(new String[filenames.size()])); } } } catch (EOFException e) { // auto refresh files are not persisted, continue and save them next time. } } broadcastRepositoryChange(repoRoot); } }
/** * Creates an NL fragment project along with the locale specific properties files. * * @throws CoreException * @throws IOException * @throws InvocationTargetException * @throws InterruptedException */ private void internationalizePlugins(List plugins, List locales, Map overwrites) throws CoreException, IOException, InvocationTargetException, InterruptedException { Set created = new HashSet(); for (Iterator it = plugins.iterator(); it.hasNext(); ) { IPluginModelBase plugin = (IPluginModelBase) it.next(); for (Iterator iter = locales.iterator(); iter.hasNext(); ) { Locale locale = (Locale) iter.next(); IProject project = getNLProject(plugin, locale); if (created.contains(project) || overwriteWithoutAsking || !project.exists() || OVERWRITE == overwrites.get(project.getName())) { if (!created.contains(project) && project.exists()) { project.delete(true, getProgressMonitor()); } if (!created.contains(project)) { createNLFragment(plugin, project, locale); created.add(project); project.getFolder(RESOURCE_FOLDER_PARENT).create(false, true, getProgressMonitor()); } project .getFolder(RESOURCE_FOLDER_PARENT) .getFolder(locale.toString()) .create(true, true, getProgressMonitor()); createLocaleSpecificPropertiesFile(project, plugin, locale); } } } }
/* * Set up the platform binary download and get it ready to run the tests. * This method is not intended to be called by clients, it will be called * automatically when the clients use a ReconcilerTestSuite. If the executable isn't * found on the file-system after the call, then we fail. */ public void initialize() throws Exception { initialized = false; File file = getPlatformZip(); output = getUniqueFolder(); toRemove.add(output); // for now we will exec to un-tar archives to keep the executable bits if (file.getName().toLowerCase().endsWith(".zip")) { try { FileUtils.unzipFile(file, output); } catch (IOException e) { fail("0.99", e); } } else { untar("1.0", file); } File exe = new File(output, getExeFolder() + "eclipse.exe"); if (!exe.exists()) { exe = new File(output, getExeFolder() + "eclipse"); if (!exe.exists()) fail( "Executable file: " + exe.getAbsolutePath() + "(or .exe) not found after extracting: " + file.getAbsolutePath() + " to: " + output); } initialized = true; }
/** * Tests that resetting the target platform should work OK (i.e. is equivalent to the models in * the default target platform). * * @throws CoreException */ public void testResetTargetPlatform() throws Exception { ITargetDefinition definition = getDefaultTargetPlatorm(); Set urls = getAllBundleURLs(definition); Set fragments = new HashSet(); TargetBundle[] bundles = definition.getBundles(); for (int i = 0; i < bundles.length; i++) { if (bundles[i].isFragment()) { fragments.add(new File(bundles[i].getBundleInfo().getLocation()).toURL()); } } // current platform IPluginModelBase[] models = TargetPlatformHelper.getPDEState().getTargetModels(); // should be equivalent assertEquals("Should have same number of bundles", urls.size(), models.length); for (int i = 0; i < models.length; i++) { String location = models[i].getInstallLocation(); URL url = new File(location).toURL(); assertTrue("Missing plug-in " + location, urls.contains(url)); if (models[i].isFragmentModel()) { assertTrue("Missing fragmnet", fragments.remove(url)); } } assertTrue("Different number of fragments", fragments.isEmpty()); }
public static void _testAllowFileScheme(boolean allow) { if (allow) { uriSchemeWhitelist.add("file"); // $NON-NLS-1$ } else { uriSchemeWhitelist.remove("file"); // $NON-NLS-1$ } }
/** * Method filterResources filters the given resources using the given working set. * * @param current * @param resources * @return ICVSRemoteResource[] */ public ICVSRemoteResource[] filterResources( IWorkingSet workingSet, ICVSRemoteResource[] resources) { if (workingSet == null) return resources; // get the projects associated with the working set IAdaptable[] adaptables = workingSet.getElements(); Set projects = new HashSet(); for (int i = 0; i < adaptables.length; i++) { IAdaptable adaptable = adaptables[i]; Object adapted = adaptable.getAdapter(IResource.class); if (adapted != null) { // Can this code be generalized? IProject project = ((IResource) adapted).getProject(); projects.add(project); } } List result = new ArrayList(); for (int i = 0; i < resources.length; i++) { ICVSRemoteResource resource = resources[i]; for (Iterator iter = projects.iterator(); iter.hasNext(); ) { IProject project = (IProject) iter.next(); if (project.getName().equals(resource.getName())) { result.add(resource); break; } } } return (ICVSRemoteResource[]) result.toArray(new ICVSRemoteResource[result.size()]); }
/** * Tests identification of source bundles in a 3.0.2 install. * * @throws Exception */ public void testClassicSourcePlugins() throws Exception { // extract the 3.0.2 skeleton IPath location = extractClassicPlugins(); // the new way ITargetDefinition definition = getNewTarget(); ITargetLocation container = getTargetService().newDirectoryLocation(location.toOSString()); definition.setTargetLocations(new ITargetLocation[] {container}); definition.resolve(null); TargetBundle[] bundles = definition.getBundles(); List source = new ArrayList(); for (int i = 0; i < bundles.length; i++) { TargetBundle sb = bundles[i]; if (sb.isSourceBundle()) { source.add(sb); } } assertEquals("Wrong number of source bundles", 4, source.size()); Set names = new HashSet(); for (int i = 0; i < source.size(); i++) { names.add(((TargetBundle) source.get(i)).getBundleInfo().getSymbolicName()); } String[] expected = new String[] { "org.eclipse.platform.source", "org.eclipse.jdt.source", "org.eclipse.pde.source", "org.eclipse.platform.source.win32.win32.x86" }; for (int i = 0; i < expected.length; i++) { assertTrue("Missing source for " + expected[i], names.contains(expected[i])); } }
/** * Retrieves all bundles (source and code) in the given target definition returning them as a set * of URLs. * * @param target target definition * @return all bundle URLs */ protected Set getAllBundleURLs(ITargetDefinition target) throws Exception { if (!target.isResolved()) { target.resolve(null); } TargetBundle[] bundles = target.getBundles(); Set urls = new HashSet(bundles.length); for (int i = 0; i < bundles.length; i++) { urls.add(new File(bundles[i].getBundleInfo().getLocation()).toURL()); } return urls; }
/** Get the list of known branch tags for a given remote root. */ public CVSTag[] getKnownTags(ICVSFolder project, int tagType) { try { CVSTag[] tags = getKnownTags(project); Set result = new HashSet(); for (int i = 0; i < tags.length; i++) { CVSTag tag = tags[i]; if (tag.getType() == tagType) result.add(tag); } return (CVSTag[]) result.toArray(new CVSTag[result.size()]); } catch (CVSException e) { CVSUIPlugin.log(e); return new CVSTag[0]; } }
public ICVSRemoteResource[] getFoldersForTag( ICVSRepositoryLocation location, CVSTag tag, IProgressMonitor monitor) throws CVSException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask( NLS.bind( CVSUIMessages.RepositoryManager_fetchingRemoteFolders, new String[] {tag.getName()}), 100); if (tag.getType() == CVSTag.HEAD) { ICVSRemoteResource[] resources = location.members(tag, false, Policy.subMonitorFor(monitor, 60)); RepositoryRoot root = getRepositoryRootFor(location); ICVSRemoteResource[] modules = root.getDefinedModules(tag, Policy.subMonitorFor(monitor, 40)); ICVSRemoteResource[] result = new ICVSRemoteResource[resources.length + modules.length]; System.arraycopy(resources, 0, result, 0, resources.length); System.arraycopy(modules, 0, result, resources.length, modules.length); return result; } if (tag.getType() == CVSTag.DATE) { ICVSRemoteResource[] resources = location.members(tag, false, Policy.subMonitorFor(monitor, 60)); RepositoryRoot root = getRepositoryRootFor(location); ICVSRemoteResource[] modules = root.getDefinedModules(tag, Policy.subMonitorFor(monitor, 40)); ICVSRemoteResource[] result = new ICVSRemoteResource[resources.length + modules.length]; System.arraycopy(resources, 0, result, 0, resources.length); System.arraycopy(modules, 0, result, resources.length, modules.length); return result; } Set result = new HashSet(); // Get the tags for the location RepositoryRoot root = getRepositoryRootFor(location); String[] paths = root.getKnownRemotePaths(); for (int i = 0; i < paths.length; i++) { String path = paths[i]; List tags = Arrays.asList(root.getAllKnownTags(path)); if (tags.contains(tag)) { ICVSRemoteFolder remote = root.getRemoteFolder(path, tag, Policy.subMonitorFor(monitor, 100)); result.add(remote); } } return (ICVSRemoteResource[]) result.toArray(new ICVSRemoteResource[result.size()]); } finally { monitor.done(); } }
/** Get the list of known version tags for a given project. */ public CVSTag[] getKnownTags(ICVSRepositoryLocation location, int tagType) { Set result = new HashSet(); RepositoryRoot root = (RepositoryRoot) repositoryRoots.get(location.getLocation(false)); if (root != null) { String[] paths = root.getKnownRemotePaths(); for (int i = 0; i < paths.length; i++) { String path = paths[i]; CVSTag[] tags = root.getAllKnownTags(path); for (int j = 0; j < tags.length; j++) { CVSTag tag = tags[j]; if (tag.getType() == tagType) result.add(tag); } } } return (CVSTag[]) result.toArray(new CVSTag[0]); }
protected void doIncludeVersions(NameVersionDescriptor[] descriptions) throws Exception { String bsn = MULTI_VERSION_LOW_DESCRIPTION.getId(); IPath extras = extractMultiVersionPlugins(); ITargetDefinition target = getNewTarget(); ITargetLocation container = getTargetService().newDirectoryLocation(extras.toOSString()); target.setTargetLocations(new ITargetLocation[] {container}); target.setIncluded(descriptions); try { getTargetService().saveTargetDefinition(target); setTargetPlatform(target); IPluginModelBase[] models = PluginRegistry.getExternalModels(); Set enabled = new HashSet(); for (int i = 0; i < models.length; i++) { IPluginModelBase pm = models[i]; if (pm.getBundleDescription().getSymbolicName().equals(bsn)) { NameVersionDescriptor desc = new NameVersionDescriptor( pm.getPluginBase().getId(), pm.getPluginBase().getVersion()); if (pm.isEnabled()) { enabled.add(desc); } } } if (descriptions == null) { } else { assertEquals("Wrong number of enabled bundles", descriptions.length, enabled.size()); for (int i = 0; i < descriptions.length; i++) { assertTrue("Missing bundle", enabled.contains(descriptions[i])); } } } finally { getTargetService().deleteTarget(target.getHandle()); resetTargetPlatform(); } }
static { fFilteredTypes = new HashSet(3); fFilteredTypes.add(ProjectSourceContainer.TYPE_ID); fFilteredTypes.add(WorkspaceSourceContainer.TYPE_ID); fFilteredTypes.add("org.eclipse.debug.ui.containerType.workingSet"); // $NON-NLS-1$ }
private boolean handleGetDiff( HttpServletRequest request, HttpServletResponse response, Repository db, String scope, String pattern, OutputStream out) throws Exception { Git git = new Git(db); DiffCommand diff = git.diff(); diff.setOutputStream(new BufferedOutputStream(out)); AbstractTreeIterator oldTree; AbstractTreeIterator newTree = new FileTreeIterator(db); if (scope.contains("..")) { // $NON-NLS-1$ String[] commits = scope.split("\\.\\."); // $NON-NLS-1$ if (commits.length != 2) { String msg = NLS.bind("Failed to generate diff for {0}", scope); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } oldTree = getTreeIterator(db, commits[0]); newTree = getTreeIterator(db, commits[1]); } else if (scope.equals(GitConstants.KEY_DIFF_CACHED)) { ObjectId head = db.resolve(Constants.HEAD + "^{tree}"); // $NON-NLS-1$ if (head == null) { String msg = NLS.bind("Failed to generate diff for {0}, no HEAD", scope); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } CanonicalTreeParser p = new CanonicalTreeParser(); ObjectReader reader = db.newObjectReader(); try { p.reset(reader, head); } finally { reader.release(); } oldTree = p; newTree = new DirCacheIterator(db.readDirCache()); } else if (scope.equals(GitConstants.KEY_DIFF_DEFAULT)) { oldTree = new DirCacheIterator(db.readDirCache()); } else { oldTree = getTreeIterator(db, scope); } String[] paths = request.getParameterValues(ProtocolConstants.KEY_PATH); TreeFilter filter = null; TreeFilter pathFilter = null; if (paths != null) { if (paths.length > 1) { Set<TreeFilter> pathFilters = new HashSet<TreeFilter>(paths.length); for (String path : paths) { pathFilters.add(PathFilter.create(path)); } pathFilter = OrTreeFilter.create(pathFilters); } else if (paths.length == 1) { pathFilter = PathFilter.create(paths[0]); } } if (pattern != null) { PathFilter patternFilter = PathFilter.create(pattern); if (pathFilter != null) filter = AndTreeFilter.create(patternFilter, pathFilter); else filter = patternFilter; } else { filter = pathFilter; } if (filter != null) diff.setPathFilter(filter); diff.setOldTree(oldTree); diff.setNewTree(newTree); diff.call(); return true; }
public void addDescriptor(IArtifactDescriptor descriptor, IProgressMonitor monitor) { ((ArtifactDescriptor) descriptor).setRepository(this); artifactDescriptors.add(descriptor); keysToLocations.put(descriptor.getArtifactKey(), null); }
public void saveIncludedBundleState() { if (fFeaureModeButton.getSelection()) { // Create a list of checked bundle infos List included = new ArrayList(); int missingCount = 0; Object[] checked = fTree.getCheckedLeafElements(); for (int i = 0; i < checked.length; i++) { if (checked[i] instanceof IFeatureModel) { included.add( new NameVersionDescriptor( ((IFeatureModel) checked[i]).getFeature().getId(), null, NameVersionDescriptor.TYPE_FEATURE)); } if (checked[i] instanceof IResolvedBundle) { // Missing features are included as IResolvedBundles, save them as features instead if (((IResolvedBundle) checked[i]).getStatus().getCode() == IResolvedBundle.STATUS_PLUGIN_DOES_NOT_EXIST) { included.add( new NameVersionDescriptor( ((IResolvedBundle) checked[i]).getBundleInfo().getSymbolicName(), null, NameVersionDescriptor.TYPE_PLUGIN)); missingCount++; } else if (((IResolvedBundle) checked[i]).getStatus().getCode() == IResolvedBundle.STATUS_FEATURE_DOES_NOT_EXIST) { included.add( new NameVersionDescriptor( ((IResolvedBundle) checked[i]).getBundleInfo().getSymbolicName(), null, NameVersionDescriptor.TYPE_FEATURE)); missingCount++; } else { included.add( new NameVersionDescriptor( ((IResolvedBundle) checked[i]).getBundleInfo().getSymbolicName(), null)); } } } if (included.size() == 0) { fTargetDefinition.setIncluded(new NameVersionDescriptor[0]); } else if (included.size() == 0 || included.size() - missingCount == fTargetDefinition.getAllFeatures().length + ((TargetDefinition) fTargetDefinition).getOtherBundles().length) { fTargetDefinition.setIncluded(null); } else { fTargetDefinition.setIncluded( (NameVersionDescriptor[]) included.toArray(new NameVersionDescriptor[included.size()])); } } else { // Figure out if there are multiple bundles sharing the same id Set multi = new HashSet(); // BSNs of bundles with multiple versions available Set all = new HashSet(); for (Iterator iterator = fAllBundles.iterator(); iterator.hasNext(); ) { IResolvedBundle rb = (IResolvedBundle) iterator.next(); if (!all.add(rb.getBundleInfo().getSymbolicName())) { multi.add(rb.getBundleInfo().getSymbolicName()); } } // Create a list of checked bundle infos List included = new ArrayList(); Object[] checked = fTree.getCheckedLeafElements(); for (int i = 0; i < checked.length; i++) { if (checked[i] instanceof IResolvedBundle) { // Create the bundle info object String bsn = ((IResolvedBundle) checked[i]).getBundleInfo().getSymbolicName(); NameVersionDescriptor info = null; if (multi.contains(bsn)) { // include version info info = new NameVersionDescriptor( bsn, ((IResolvedBundle) checked[i]).getBundleInfo().getVersion()); } else { // don't store version info info = new NameVersionDescriptor(bsn, null); } included.add(info); } } if (included.size() == 0) { fTargetDefinition.setIncluded(new NameVersionDescriptor[0]); } else if (included.size() == fAllBundles.size() + fMissing.size()) { fTargetDefinition.setIncluded(null); } else { fTargetDefinition.setIncluded( (NameVersionDescriptor[]) included.toArray(new NameVersionDescriptor[included.size()])); } } }
/** * Uses the target state to determine all bundles required by the currently checked bundles and * returns them so they can be checked in the tree. * * @param allBundles list of all bundles to search requirements in * @param checkedBundles list of bundles to get requirements for * @return list of resolved bundles from the collection to be checked */ private Object[] getRequiredPlugins(final Collection allBundles, final Object[] checkedBundles) { final Set dependencies = new HashSet(); IRunnableWithProgress op = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) { try { monitor.beginTask(Messages.TargetContentsGroup_5, 150); // Get all the bundle locations List allLocations = new ArrayList(allBundles.size()); for (Iterator iterator = allBundles.iterator(); iterator.hasNext(); ) { IResolvedBundle current = (IResolvedBundle) iterator.next(); try { // Some bundles, such as those with errors, may not have locations URI location = current.getBundleInfo().getLocation(); if (location != null) { allLocations.add(new File(location).toURL()); } } catch (MalformedURLException e) { PDEPlugin.log(e); monitor.setCanceled(true); return; } } if (monitor.isCanceled()) { return; } monitor.worked(20); // Create a PDE State containing all of the target bundles PDEState state = new PDEState( (URL[]) allLocations.toArray(new URL[allLocations.size()]), true, new SubProgressMonitor(monitor, 50)); if (monitor.isCanceled()) { return; } // Figure out which of the models have been checked IPluginModelBase[] models = state.getTargetModels(); List checkedModels = new ArrayList(checkedBundles.length); for (int i = 0; i < checkedBundles.length; i++) { if (checkedBundles[i] instanceof IResolvedBundle) { BundleInfo bundle = ((IResolvedBundle) checkedBundles[i]).getBundleInfo(); for (int j = 0; j < models.length; j++) { if (models[j] .getBundleDescription() .getSymbolicName() .equals(bundle.getSymbolicName()) && models[j] .getBundleDescription() .getVersion() .toString() .equals(bundle.getVersion())) { checkedModels.add(models[j]); break; } } } } monitor.worked(20); if (monitor.isCanceled()) { return; } // Get implicit dependencies as a list of strings // This is wasteful since the dependency calculation puts them back into BundleInfos NameVersionDescriptor[] implicitDependencies = fTargetDefinition.getImplicitDependencies(); List implicitIDs = new ArrayList(); if (implicitDependencies != null) { for (int i = 0; i < implicitDependencies.length; i++) { implicitIDs.add(implicitDependencies[i].getId()); } } monitor.worked(10); // Get all dependency bundles // exclude "org.eclipse.ui.workbench.compatibility" - it is only needed for pre-3.0 // bundles dependencies.addAll( DependencyManager.getDependencies( checkedModels.toArray(), (String[]) implicitIDs.toArray(new String[implicitIDs.size()]), state.getState(), new String[] {"org.eclipse.ui.workbench.compatibility"})); // $NON-NLS-1$ monitor.worked(50); } finally { monitor.done(); } } }; try { // Calculate the dependencies new ProgressMonitorDialog(fTree.getControl().getShell()).run(true, true, op); // We want to check the dependents, the source of the dependents, and the source of the // originally checked Set checkedNames = new HashSet(checkedBundles.length); for (int i = 0; i < checkedBundles.length; i++) { if (checkedBundles[i] instanceof IResolvedBundle) { checkedNames.add(((IResolvedBundle) checkedBundles[i]).getBundleInfo().getSymbolicName()); } } List toCheck = new ArrayList(); for (Iterator iterator = fAllBundles.iterator(); iterator.hasNext(); ) { IResolvedBundle bundle = (IResolvedBundle) iterator.next(); if (bundle.isSourceBundle()) { String name = bundle.getSourceTarget().getSymbolicName(); if (name != null && (dependencies.contains(name) || checkedNames.contains(name))) { toCheck.add(bundle); } } else if (dependencies.contains(bundle.getBundleInfo().getSymbolicName())) { toCheck.add(bundle); } } return toCheck.toArray(); } catch (InvocationTargetException e) { PDEPlugin.log(e); } catch (InterruptedException e) { } return new Object[0]; }
public void registerListener(DatabaseModelListener listener) { listeners.add(listener); }
/** * Delimits a comma separated preference and add the items to the given set * * @param set * @param preference */ private void addExtraChoices(Set<String> set, String preference) { StringTokenizer tokenizer = new StringTokenizer(preference, ","); // $NON-NLS-1$ while (tokenizer.hasMoreTokens()) { set.add(tokenizer.nextToken().trim()); } }
private boolean handlePut( HttpServletRequest request, HttpServletResponse response, String pathString) throws GitAPIException, CoreException, IOException, JSONException, ServletException { IPath path = pathString == null ? Path.EMPTY : new Path(pathString); if (path.segment(0).equals("file") && path.segmentCount() > 1) { // $NON-NLS-1$ // make sure a clone is addressed WebProject webProject = GitUtils.projectFromPath(path); if (isAccessAllowed(request.getRemoteUser(), webProject)) { Map<IPath, File> gitDirs = GitUtils.getGitDirs(path, Traverse.CURRENT); if (gitDirs.isEmpty()) { String msg = NLS.bind("Request path is not a git repository: {0}", path); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } File gitDir = gitDirs.values().iterator().next(); // make sure required fields are set JSONObject toCheckout = OrionServlet.readJSONRequest(request); JSONArray paths = toCheckout.optJSONArray(ProtocolConstants.KEY_PATH); String branch = toCheckout.optString(GitConstants.KEY_BRANCH_NAME, null); String tag = toCheckout.optString(GitConstants.KEY_TAG_NAME, null); boolean removeUntracked = toCheckout.optBoolean(GitConstants.KEY_REMOVE_UNTRACKED, false); if ((paths == null || paths.length() == 0) && branch == null && tag == null) { String msg = NLS.bind( "Either '{0}' or '{1}' or '{2}' should be provided, got: {3}", new Object[] { ProtocolConstants.KEY_PATH, GitConstants.KEY_BRANCH_NAME, GitConstants.KEY_TAG_NAME, toCheckout }); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } Git git = new Git(new FileRepository(gitDir)); if (paths != null) { Set<String> toRemove = new HashSet<String>(); CheckoutCommand checkout = git.checkout(); for (int i = 0; i < paths.length(); i++) { String p = paths.getString(i); if (removeUntracked && !isInIndex(git.getRepository(), p)) toRemove.add(p); checkout.addPath(p); } checkout.call(); for (String p : toRemove) { File f = new File(git.getRepository().getWorkTree(), p); f.delete(); } return true; } else if (tag != null && branch != null) { CheckoutCommand co = git.checkout(); try { co.setName(branch).setStartPoint(tag).setCreateBranch(true).call(); return true; } catch (RefNotFoundException e) { String msg = NLS.bind("Tag not found: {0}", tag); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e)); } catch (GitAPIException e) { if (org.eclipse.jgit.api.CheckoutResult.Status.CONFLICTS.equals( co.getResult().getStatus())) { return statusHandler.handleRequest( request, response, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e)); } // TODO: handle other exceptions } } else if (branch != null) { if (!isLocalBranch(git, branch)) { String msg = NLS.bind("{0} is not a branch.", branch); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } CheckoutCommand co = git.checkout(); try { co.setName(Constants.R_HEADS + branch).call(); return true; } catch (CheckoutConflictException e) { return statusHandler.handleRequest( request, response, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e)); } catch (RefNotFoundException e) { String msg = NLS.bind("Branch name not found: {0}", branch); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e)); } // TODO: handle other exceptions } } else { String msg = NLS.bind("Nothing found for the given ID: {0}", path); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } } String msg = NLS.bind("Invalid checkout request {0}", pathString); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); }