Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions src/packagedcode/nx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import io
import json

from packageurl import PackageURL
from packagedcode import models
from packagedcode.npm import split_scoped_package_name


class NxJsonHandler(models.NonAssemblableDatafileHandler):
datasource_id = 'nx_json'
path_patterns = ('*/nx.json',)
default_package_type = 'npm'
default_primary_language = 'JavaScript'
description = 'Nx workspace configuration'
documentation_url = 'https://nx.dev/docs/reference/nx-json'

# Keep workspace identity/topology fields; skip schematic & cache noise
# (generators, namedInputs, targetDefaults, parallel, analytics, sync)
EXTRA_DATA_FIELDS = (
'defaultProject',
'defaultBase',
'workspaceLayout',
'plugins',
'extends',
'release',
'nxCloudId',
'nxCloudUrl',
)

@classmethod
def parse(cls, location, package_only=False):
with io.open(location, encoding='utf-8') as f:
data = json.load(f)

extra_data = {}
for field in cls.EXTRA_DATA_FIELDS:
value = data.get(field)
if value not in (None, {}, []):
extra_data[field] = value

dependencies = cls._extract_plugin_dependencies(data.get('plugins') or [])

if extra_data or dependencies:
yield models.PackageData.from_data(
dict(
datasource_id=cls.datasource_id,
type=cls.default_package_type,
primary_language=cls.default_primary_language,
dependencies=dependencies,
extra_data=extra_data,
),
package_only,
)

@classmethod
def _extract_plugin_dependencies(cls, plugins):
"""
Extract npm package dependencies from Nx ``plugins`` entries, which may
be strings (``"@nx/dotnet"``) or dicts (``{"plugin": "@nx/eslint/plugin", ...}``).
"""
deps_by_purl = {}
for entry in plugins:
if isinstance(entry, str):
plugin_spec = entry
elif isinstance(entry, dict):
plugin_spec = entry.get('plugin')
else:
continue

if not plugin_spec or plugin_spec.startswith('.'):
# Skip relative local plugins like "./tools/my-plugin.ts"
continue

# Strip subpath exports: "@nx/eslint/plugin" -> "@nx/eslint",
# "nx-plugin/register" -> "nx-plugin"
parts = plugin_spec.split('/')
if plugin_spec.startswith('@') and len(parts) >= 2:
pkg_name = f'{parts[0]}/{parts[1]}'
else:
pkg_name = parts[0]

ns, name = split_scoped_package_name(pkg_name)
if not name:
continue

purl = PackageURL(
type=cls.default_package_type,
namespace=ns,
name=name,
).to_string()

if purl not in deps_by_purl:
deps_by_purl[purl] = models.DependentPackage(
purl=purl,
scope='plugins',
is_runtime=False,
is_optional=False,
is_pinned=False,
is_direct=True,
).to_dict()

return list(deps_by_purl.values())
82 changes: 82 additions & 0 deletions tests/packagedcode/data/nx/nx.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
{
"plugins": [
{
"plugin": "@nx/eslint/plugin",
"options": {
"targetName": "lint"
}
}
],
"parallel": 4,
"cacheDirectory": "tmp/my-nx-cache",
"defaultBase": "main",
"namedInputs": {
"default": ["{projectRoot}/**/*"],
"production": ["!{projectRoot}/**/*.spec.tsx"]
},
"targetDefaults": {
"@nx/js:tsc": {
"inputs": ["production", "^production"],
"dependsOn": ["^build"],
"options": {
"main": "{projectRoot}/src/index.ts"
},
"cache": true
},
"test": [
{
"cache": true,
"inputs": ["default", "^production"]
},
{
"filter": { "plugin": "@nx/jest/plugin" },
"inputs": ["...", "{workspaceRoot}/jest.preset.js"],
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"]
}
]
},
"release": {
"version": {
"conventionalCommits": true
},
"changelog": {
"git": {
"commit": true,
"tag": true
},
"workspaceChangelog": {
"createRelease": "github"
},
"projectChangelogs": true
}
},
"sync": {
"globalGenerators": ["my-plugin:my-sync-generator"]
},
"migrate": {
"createCommits": true
},
"generators": {
"@nx/js:library": {
"buildable": true
}
},
"extends": "nx/presets/npm.json",
"tui": {
"enabled": true,
"autoExit": true
},
"conformance": {
"rules": [
{
"rule": "@nx/conformance/enforce-module-boundaries",
"status": "evaluated"
},
{
"rule": "./tools/local-conformance-rules/check-project.ts",
"projects": ["*"]
}
]
},
"analytics": true
}
84 changes: 84 additions & 0 deletions tests/packagedcode/data/nx/nx.json.expected.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
[
{
"type": "npm",
"namespace": null,
"name": null,
"version": null,
"qualifiers": {},
"subpath": null,
"primary_language": "JavaScript",
"description": null,
"release_date": null,
"parties": [],
"keywords": [],
"homepage_url": null,
"download_url": null,
"size": null,
"sha1": null,
"md5": null,
"sha256": null,
"sha512": null,
"bug_tracking_url": null,
"code_view_url": null,
"vcs_url": null,
"copyright": null,
"holder": null,
"declared_license_expression": null,
"declared_license_expression_spdx": null,
"license_detections": [],
"other_license_expression": null,
"other_license_expression_spdx": null,
"other_license_detections": [],
"extracted_license_statement": null,
"notice_text": null,
"source_packages": [],
"file_references": [],
"is_private": false,
"is_virtual": false,
"extra_data": {
"defaultBase": "main",
"plugins": [
{
"plugin": "@nx/eslint/plugin",
"options": {
"targetName": "lint"
}
}
],
"extends": "nx/presets/npm.json",
"release": {
"version": {
"conventionalCommits": true
},
"changelog": {
"git": {
"commit": true,
"tag": true
},
"workspaceChangelog": {
"createRelease": "github"
},
"projectChangelogs": true
}
}
},
"dependencies": [
{
"purl": "pkg:npm/%40nx/eslint",
"extracted_requirement": null,
"scope": "plugins",
"is_runtime": false,
"is_optional": false,
"is_pinned": false,
"is_direct": true,
"resolved_package": {},
"extra_data": {}
}
],
"repository_homepage_url": null,
"repository_download_url": null,
"api_data_url": null,
"datasource_id": "nx_json",
"purl": null
}
]
28 changes: 28 additions & 0 deletions tests/packagedcode/test_nx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# ScanCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/scancode-toolkit for support or download.
# See https://aboutcode.org for more information about nexB OSS projects.
#

import os

from packagedcode import nx
from packages_test_utils import PackageTester
from scancode_config import REGEN_TEST_FIXTURES


class TestNx(PackageTester):
test_data_dir = os.path.join(os.path.dirname(__file__), 'data')

def test_nx_json_is_datafile(self):
test_file = self.get_test_loc('nx/nx.json')
assert nx.NxJsonHandler.is_datafile(test_file)

def test_nx_json_parse(self):
test_file = self.get_test_loc('nx/nx.json')
expected_loc = self.get_test_loc('nx/nx.json.expected.json')
packages = nx.NxJsonHandler.parse(test_file)
self.check_packages_data(packages, expected_loc, regen=REGEN_TEST_FIXTURES)