(A better way to) Get files within a project using Eclipse and XText
Asked Answered
L

1

8

I'm writing an XText editor, and doing some semantic highlighting. Part of the language I'm parsing refers to files, which should exist in the project. I'd like to highlight based on whether these files are in the correct place. At the moment, I've got a very ugly solution, and I'm sure there's a better way:

public void provideHighlightingFor( XtextResource resource, IHighlightedPositionAcceptor acceptor ) {
...
String resStr = resource.getURI().toString();
String projName = resStr.replaceAll( "^.*resource/", "" ).replaceAll( "/.*", "" );
IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();
IFile file = workspace.getFile( new Path( projName + "/" + value ) );
ok = file != null && file.exists();

NOTE: "value" is a string which I've encountered when parsing, not the current file. I want to find out if {workspace}/{project}/{value} exists.

There must be a better way to get the project name/location, based on the current file; I've put this as an XText question, as I'd like, if possible, to avoid using the currently selected editor, and base selection on the current resource, which is presented as an XText resource.

NOTE: the code I've ended up using, based on the answer below is:

String platformString = resource.getURI().toPlatformString(true);
IFile myFile = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(platformString));
IProject proj = myFile.getProject();
IFile linkedFile = proj.getFile( value );
Levitate answered 30/8, 2011 at 11:26 Comment(0)
M
8

You could use org.eclipse.emf.common.util.URI.toPlatformString(boolean) and afterwards ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(platformString));

something like

String platformString = resource.getURI().toPlatformString(true);
IFile myFile = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(platformString));
Materiality answered 30/8, 2011 at 11:49 Comment(3)
That gets me the string of the current file, but it doesn't help me get the project location without parsing that string. Apologies if the question wasn't clear, I've updated it.Levitate
Sorry, missed that.. If you have the IFile you can get the project with IFile#getProject()Materiality
Thank you so much @TomSeidel! Exactly what I needed!Ankney

© 2022 - 2024 — McMap. All rights reserved.