Search in sources :

Example 46 with N4JSProjectConfigSnapshot

use of org.eclipse.n4js.workspace.N4JSProjectConfigSnapshot in project n4js by eclipse.

the class N4JSLanguageHelper method isDirectoryWithPackageJson.

private boolean isDirectoryWithPackageJson(IResourceDescriptions index, TModule targetModule, QualifiedName targetQN) {
    // NOTE: the following approach would be a more elegant implementation of this method, but would require a
    // different computation of FQNs for package.json files in source folders (in N4JSQualifiedNameProvider):
    // @formatter:off
    // Iterable<IEObjectDescription> matchingPackageJsonDesc = index.getExportedObjects(
    // JSONPackage.Literals.JSON_DOCUMENT,
    // targetQN.append(N4JSQualifiedNameProvider.PACKAGE_JSON_SEGMENT), false);
    // if (matchingPackageJsonDesc.iterator().hasNext()) {
    // return true;
    // }
    // @formatter:on
    N4JSProjectConfigSnapshot targetProject = replaceDefinitionProjectByDefinedProject(targetModule, workspaceAccess.findProjectContaining(targetModule), true);
    if (targetProject == null) {
        return false;
    }
    int segCount = targetQN.getSegments().size();
    String[] segments = new String[segCount + 1];
    for (int i = 0; i < segCount; i++) {
        segments[i] = targetQN.getSegments().get(i);
    }
    segments[segCount] = N4JSGlobals.PACKAGE_JSON;
    for (N4JSSourceFolderSnapshot srcFolder : targetProject.getSourceFolders()) {
        if (srcFolder instanceof N4JSSourceFolderSnapshotForPackageJson) {
            continue;
        }
        FileURI packageJsonURI = srcFolder.getPathAsFileURI().appendSegments(segments);
        if (index.getResourceDescription(packageJsonURI.toURI()) != null) {
            return true;
        }
    }
    return false;
}
Also used : FileURI(org.eclipse.n4js.workspace.locations.FileURI) N4JSSourceFolderSnapshotForPackageJson(org.eclipse.n4js.workspace.N4JSSourceFolderSnapshotForPackageJson) N4JSProjectConfigSnapshot(org.eclipse.n4js.workspace.N4JSProjectConfigSnapshot) N4JSSourceFolderSnapshot(org.eclipse.n4js.workspace.N4JSSourceFolderSnapshot)

Example 47 with N4JSProjectConfigSnapshot

use of org.eclipse.n4js.workspace.N4JSProjectConfigSnapshot in project n4js by eclipse.

the class N4JSResourceValidator method doValidateWithMeasurement.

private List<Issue> doValidateWithMeasurement(Resource resource, CheckMode mode, CancelIndicator cancelIndicator) {
    // QUICK EXIT #1: in case of invalid file type (e.g. js file in a project with project type definition)
    final N4JSWorkspaceConfigSnapshot ws = workspaceAccess.getWorkspaceConfig(resource);
    final N4JSProjectConfigSnapshot project = ws.findProjectContaining(resource.getURI());
    if (project != null && !isValidFileTypeForProjectType(resource, project)) {
        final Issue issue = createInvalidFileTypeError(resource, project);
        return Collections.singletonList(issue);
    }
    // QUICK EXIT #2: for files that match a "noValidate" module filter from package.json
    if (ws.isNoValidate(resource.getURI())) {
        return Collections.emptyList();
    }
    if (resource instanceof N4JSResource) {
        final N4JSResource resourceCasted = (N4JSResource) resource;
        // (pure performance tweak, because those resources have an empty AST anyway; see N4JSResource#doLoad())
        if (resourceCasted.isOpaque()) {
            return Collections.emptyList();
        }
        // QUICK EXIT #4: resources with disabled validation (e.g. d.ts files)
        if (resourceCasted.isValidationDisabled()) {
            return Collections.emptyList();
        }
        // trigger post-processing of N4JS resource (won't harm if post-processing has already taken place)
        try {
            resourceCasted.performPostProcessing(cancelIndicator);
        } catch (Throwable th) {
        // ignore this exception/error (we will create an issue for it below)
        }
        // QUICK EXIT #4: if post-processing failed
        if (resourceCasted.isFullyProcessed() && resourceCasted.getPostProcessingThrowable() != null) {
            // When getting here, we have an attempt to validate a resource that was post-processed but the
            // post-processing failed (i.e. postProcessingThrowable!=null). Validating such a resource will usually
            // cause a multitude of follow-up exceptions in many @Check methods (could easily be hundreds). Since,
            // EMF/Xtext has the behavior of not aborting the overall validation due to an exception in a single
            // @Check method, this will lead to many exceptions, which are all just follow-up issues of the problem
            // that caused the post-processing to fail.
            // 1) Since this is annoying and misleading, we just ignore all ordinary validation.
            // 2) To not overlook the problem, we create a single validation issue (error) pointing out the problem.
            // (for a test, see class AvoidFollowUpExceptionsInValidationTest)
            final Throwable th = resourceCasted.getPostProcessingThrowable();
            if (operationCanceledManager.isOperationCanceledException(th)) {
                // do not show errors in case of cancellation
                return Collections.emptyList();
            }
            final Issue issue = createPostProcessingFailedError(resourceCasted, th);
            return Collections.singletonList(issue);
        }
    }
    List<Issue> issues = super.validate(resource, mode, cancelIndicator);
    if (resource instanceof N4JSResource) {
        final N4JSResource resourceCasted = (N4JSResource) resource;
        ASTMetaInfoCache cache = resourceCasted.getASTMetaInfoCache();
        if (cache.hasUnknownTypeRef()) {
            boolean hasErrors = issues.stream().anyMatch(issue -> issue.getSeverity() == Severity.ERROR);
            if (!hasErrors) {
                final String msg = IssueCodes.getMessageForTYS_UNKNOWN_TYPE_REF();
                createFileIssue(resource, msg, IssueCodes.TYS_UNKNOWN_TYPE_REF);
            }
        }
    }
    return issues;
}
Also used : ASTMetaInfoCache(org.eclipse.n4js.postprocessing.ASTMetaInfoCache) Issue(org.eclipse.xtext.validation.Issue) N4JSWorkspaceConfigSnapshot(org.eclipse.n4js.workspace.N4JSWorkspaceConfigSnapshot) N4JSProjectConfigSnapshot(org.eclipse.n4js.workspace.N4JSProjectConfigSnapshot) N4JSResource(org.eclipse.n4js.resource.N4JSResource)

Example 48 with N4JSProjectConfigSnapshot

use of org.eclipse.n4js.workspace.N4JSProjectConfigSnapshot in project n4js by eclipse.

the class StaticPolyfillHelper method findStaticPolyfiller.

/**
 * Find the corresponding static-polyfill to this {@code @@PolyfillAware} resource in the same project. returns null
 * if not found or this resource has no {@code @@PolyfillAware} annotation.
 */
public SafeURI<?> findStaticPolyfiller(Resource resource) {
    // ensure right resource
    if (resource instanceof N4JSResource) {
        final N4JSResource res = (N4JSResource) resource;
        if (!isContainedInStaticPolyfillAware(res.getScript()))
            return null;
        final QualifiedName qnFilled = qualifiedNameConverter.toQualifiedName(res.getModule().getQualifiedName());
        final N4JSProjectConfigSnapshot project = projectResolver.resolveProject(res, res.getURI());
        final QualifiedName fqn = qnFilled;
        // see Req.155#4: "Both extensions are equal."
        final Optional<String> fileExtension = Optional.of(URIUtils.fileExtension(res.getURI()));
        final N4JSSourceFolderSnapshot filledSrcContainer = workspaceAccess.findSourceFolderContaining(res, res.getURI());
        for (N4JSSourceFolderSnapshot srcConti : project.getSourceFolders()) {
            if (!Objects.equals(filledSrcContainer, srcConti)) {
                final SafeURI<?> uri = findArtifactHelper.findArtifact(srcConti, fqn, fileExtension);
                if (uri != null) {
                    return uri;
                }
            }
        }
    }
    return null;
}
Also used : QualifiedName(org.eclipse.xtext.naming.QualifiedName) N4JSProjectConfigSnapshot(org.eclipse.n4js.workspace.N4JSProjectConfigSnapshot) N4JSResource(org.eclipse.n4js.resource.N4JSResource) N4JSSourceFolderSnapshot(org.eclipse.n4js.workspace.N4JSSourceFolderSnapshot)

Example 49 with N4JSProjectConfigSnapshot

use of org.eclipse.n4js.workspace.N4JSProjectConfigSnapshot in project n4js by eclipse.

the class PackageJsonValidatorExtension method holdsExistingDirectoryPath.

/**
 * Checks whether the given {@code pathLiteral} represents an existing relative path to the currently validated
 * {@link Resource}.
 *
 * Returns {@code false} and adds issues to {@code pathLiteral} otherwise.
 */
private boolean holdsExistingDirectoryPath(JSONStringLiteral pathLiteral) {
    final Resource resource = pathLiteral.eResource();
    final URI resourceURI = resource.getURI();
    final N4JSProjectConfigSnapshot n4jsProject = workspaceAccess.findProjectContaining(resource);
    if (n4jsProject == null) {
        // container project cannot be determined, fail gracefully (validation running on non-N4JS project?)
        return true;
    }
    final FileURI path = n4jsProject.getPathAsFileURI();
    final URI projectLocation = path.toURI();
    // resolve against project uri with trailing slash
    final URI projectRelativeResourceURI = resourceURI.deresolve(projectLocation.appendSegment(""));
    final Path absoluteProjectPath = path.toFileSystemPath();
    if (absoluteProjectPath == null) {
        throw new IllegalStateException("Failed to compute project path for package.json at " + resourceURI.toString());
    }
    // compute the path of the folder that contains the currently validated package.json file
    final Path baseResourcePath = new File(absoluteProjectPath.toFile(), projectRelativeResourceURI.trimSegments(1).toFileString()).toPath();
    final String relativePath = pathLiteral.getValue();
    final File file = new File(baseResourcePath.toString(), relativePath);
    if (!file.exists()) {
        addIssue(IssueCodes.getMessageForPKGJ_NON_EXISTING_SOURCE_PATH(relativePath), pathLiteral, IssueCodes.PKGJ_NON_EXISTING_SOURCE_PATH);
        return false;
    }
    if (!file.isDirectory()) {
        addIssue(IssueCodes.getMessageForPKGJ_EXPECTED_DIRECTORY_PATH(relativePath), pathLiteral, IssueCodes.PKGJ_EXPECTED_DIRECTORY_PATH);
        return false;
    }
    return true;
}
Also used : Path(java.nio.file.Path) FileURI(org.eclipse.n4js.workspace.locations.FileURI) N4JSProjectConfigSnapshot(org.eclipse.n4js.workspace.N4JSProjectConfigSnapshot) Resource(org.eclipse.emf.ecore.resource.Resource) FileURI(org.eclipse.n4js.workspace.locations.FileURI) URI(org.eclipse.emf.common.util.URI) File(java.io.File)

Example 50 with N4JSProjectConfigSnapshot

use of org.eclipse.n4js.workspace.N4JSProjectConfigSnapshot in project n4js by eclipse.

the class JSDoc2AdocFullTest method fullTest.

@Override
@SuppressWarnings("unused")
protected void fullTest(String projectName) throws IOException, InterruptedException, InterruptedException {
    // create an empty yarn workspace
    testWorkspaceManager.createTestOnDisk();
    startAndWaitForLspServer();
    assertNoIssues();
    File probandFolder = new File(TESTRESOURCES + projectName);
    File projectFolder = new File(getProjectLocation(), projectName);
    assertTrue("proband folder not found", probandFolder.isDirectory());
    FileCopier.copy(probandFolder, projectFolder);
    cleanBuildAndWait();
    FileURI packageJsonURI = toFileURI(getProjectLocation()).appendSegments(projectName, N4JSGlobals.PACKAGE_JSON);
    assertIssues(Map.of(packageJsonURI, Lists.newArrayList("(Error, [4:17 - 4:26], Missing dependency to n4js-runtime (mandatory for all N4JS projects of type library, application, test).)")));
    String systemSeparator = System.getProperty("line.separator", "\n");
    try {
        for (String lsep : new String[] { "\n", "\r\n", "\r" }) {
            System.setProperty("line.separator", lsep);
            String expectationFileName = projectName + "/expected.adoc";
            ResourceSet resourceSet = workspaceAccess.createResourceSet();
            N4JSProjectConfigSnapshot project = workspaceAccess.findProjectByName(resourceSet, "yarn-test-project/packages/" + projectName);
            assertNotNull("Project not found", project);
            Collection<SpecFile> specChangeSet = jSDoc2SpecProcessor.convert(new File(TESTRESOURCES), Collections.singleton(project), (p) -> resourceSet, SubMonitorMsg.nullProgressMonitor());
            String adocRootName = TESTRESOURCES + projectName + "/expectedADoc";
            Collection<String> expectedFileNames = getExpectedFileNames(adocRootName, specChangeSet);
            assertFalse(expectedFileNames.isEmpty());
            File adocRoot = new File(adocRootName);
            String completeActual = "";
            String completeExpected = "";
            for (SpecFile specFile : specChangeSet) {
                String expectedFile = getExpectedFile(expectedFileNames, specFile);
                if (expectedFile == null)
                    continue;
                Path fullExpectationPath = adocRoot.toPath().resolve(expectedFile);
                File fullExpectationFile = fullExpectationPath.toFile();
                String fullExpectationPathStr = fullExpectationPath.toString();
                String expectedADoc = Files.asCharSource(fullExpectationFile, Charset.defaultCharset()).read();
                String actualADoc = specFile.getNewContent();
                if (UPDATE_EXPECTION && !actualADoc.equals(expectedADoc)) {
                    expectedADoc = actualADoc;
                    org.eclipse.xtext.util.Files.writeStringIntoFile(fullExpectationPathStr, expectedADoc);
                    System.out.println("Updated expectation " + fullExpectationPathStr);
                }
                completeActual += "\n//////// " + expectedFile + " ////////\n";
                completeActual += actualADoc;
                completeExpected += "\n//////// " + expectedFile + " ////////\n";
                completeExpected += expectedADoc;
            }
            assertEqualsIgnoreWS(completeExpected, completeActual);
        }
    } finally {
        System.setProperty("line.separator", systemSeparator);
    }
}
Also used : Path(java.nio.file.Path) FileURI(org.eclipse.n4js.workspace.locations.FileURI) N4JSProjectConfigSnapshot(org.eclipse.n4js.workspace.N4JSProjectConfigSnapshot) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) SpecFile(org.eclipse.n4js.jsdoc2spec.SpecFile) File(java.io.File) SpecFile(org.eclipse.n4js.jsdoc2spec.SpecFile)

Aggregations

N4JSProjectConfigSnapshot (org.eclipse.n4js.workspace.N4JSProjectConfigSnapshot)50 URI (org.eclipse.emf.common.util.URI)15 N4JSPackageName (org.eclipse.n4js.workspace.utils.N4JSPackageName)9 N4JSSourceFolderSnapshot (org.eclipse.n4js.workspace.N4JSSourceFolderSnapshot)8 Path (java.nio.file.Path)7 Resource (org.eclipse.emf.ecore.resource.Resource)7 N4JSWorkspaceConfigSnapshot (org.eclipse.n4js.workspace.N4JSWorkspaceConfigSnapshot)7 FileURI (org.eclipse.n4js.workspace.locations.FileURI)7 ArrayList (java.util.ArrayList)6 IEObjectDescription (org.eclipse.xtext.resource.IEObjectDescription)6 File (java.io.File)5 HashMap (java.util.HashMap)5 N4JSResource (org.eclipse.n4js.resource.N4JSResource)5 LinkedHashMap (java.util.LinkedHashMap)4 ResourceSet (org.eclipse.emf.ecore.resource.ResourceSet)4 ProjectDescription (org.eclipse.n4js.packagejson.projectDescription.ProjectDescription)4 TModule (org.eclipse.n4js.ts.types.TModule)4 QualifiedName (org.eclipse.xtext.naming.QualifiedName)4 IResourceDescription (org.eclipse.xtext.resource.IResourceDescription)4 IResourceDescriptions (org.eclipse.xtext.resource.IResourceDescriptions)4