GitNexus/gitnexus/test/unit/group/java-workspace-extractor.test.ts
Christian C. Berclaz 7cce07b419
feat(group): workspace extractors for Node, Python, Go, Java, Elixir (#1260)
* feat(group): auto-discover Node/TS workspace cross-package contracts

Scan package.json dependencies and ES/CJS imports to find PascalCase
type exports crossing workspace package boundaries. Same pipeline as
Rust workspace extractor — emits GroupManifestLink[] with type:custom.

Supports: ES named imports, default imports, CommonJS destructured
require, scoped packages (@org/pkg), subpath imports, aliased imports.
Filters to PascalCase names only (types/classes, not functions).

* feat(group): auto-discover Python workspace cross-package contracts

Scan pyproject.toml/setup.py dependencies and `from <pkg> import`
statements to find PascalCase type exports crossing workspace package
boundaries. Handles hyphenated names (PEP 503 normalization),
submodule imports, aliased imports, and optional-dependencies.

* feat(group): auto-discover Go workspace cross-module contracts

Scan go.mod require/replace directives and Go source files for
exported PascalCase type usage (pkg.TypeName) crossing module
boundaries within a group. Handles block syntax, subpackage
imports, and local replace directives.

* refactor(group): extract workspace discovery orchestrator from sync

Move per-ecosystem workspace extractor calls into a single
discoverWorkspaceLinks() orchestrator. Reduces sync.ts from 295
to 264 lines and gives a clean extension point for adding
more ecosystem extractors.

* feat(group): auto-discover Java/Kotlin workspace cross-project contracts

Scan Maven pom.xml and Gradle build files for inter-project deps,
then match Java/Kotlin import statements against known group-internal
base packages. Supports Maven dependency blocks, Gradle coordinate
and project() dependencies, static imports, and Kotlin files.

* feat(group): auto-discover Elixir workspace cross-app contracts

Scan mix.exs deps and Elixir source files for alias directives and
direct module references crossing OTP app boundaries. Handles
umbrella deps (in_umbrella), git/path deps, grouped aliases
(alias MyApp.{ModA, ModB}), underscore-to-PascalCase app name
mapping, and collapses nested submodules to top-level contracts.

* fix(group): apply PR review fixes to all workspace extractors

Address review findings from PR #1256 across Node, Python, Go, Java,
and Elixir extractors:
- Replace hardcoded IGNORE sets with shared IgnoreService
  (shouldIgnorePath + loadIgnoreRules) to honor .gitnexusignore
- Qualify contract names with provider identifier to prevent
  contractId collisions across providers
- Warn and skip duplicate project/module/app names
- Update all test assertions for qualified contract format

* fix(workspace): address review findings and fix CI

- Fix prettier formatting on Rust workspace extractor files
- Fix double readRegistry() call in syncGroup (hoist to function scope)
- Fix console.warn spy leak in duplicate crate test (try/finally)
- Add sync-level integration tests: workspace_deps true/false gating,
  Rust and Node link discovery through syncGroup orchestrator (3 tests)

* style(workspace): fix Prettier formatting on all workspace extractors

* fix(workspace): strip qualified prefix in custom contract resolution, default workspace_deps to false

resolveSymbol for custom contracts now strips the "provider::" prefix
before querying graph nodes, so workspace-generated contracts like
"mathlex::Expression" correctly resolve to the "Expression" symbol.

Change workspace_deps default from true to false for safe rollout —
existing groups won't silently gain 6-ecosystem scans on upgrade.

* fix(workspace): address medium review findings from PR #1260

- Elixir: strip comment lines before direct module reference scan to
  prevent false positives from commented-out module references
- Go: use full module path for contract naming to avoid basename
  collisions between repos with identical last path segments
- Sync tests: replace toBeGreaterThanOrEqual with exact toHaveLength
  assertions per DoD §2.7
- Add workspace_deps: false to makeConfig helper for type correctness
- Add Elixir test proving comment-only references do not emit links

* fix(workspace): address second-round medium review findings

- Go: add test asserting aliased imports produce 0 links, guarding the
  V1 false-negative boundary at the assertion level
- Elixir: add code comment documenting that contracts use full module
  names without appName:: prefix and that resolveSymbol resolution
  depends on Elixir indexer storing fully-qualified names

* fix(workspace): eliminate regex backtracking in pyproject.toml parser

CodeQL flagged exponential backtracking in the [project] name regex.
Replace [^\[]*?\n (ambiguous lazy quantifier) with [^\n\[]*\n (atomic
per-line match that still stops at section boundaries).

* fix(test): use mkdtempSync for secure temp dir creation

CodeQL flagged insecure temporary file creation (High) in sync.test.ts.
Replace path.join(os.tmpdir(), predictable-name) + mkdirSync with
fs.mkdtempSync which creates temp dirs atomically with random suffix,
preventing symlink race conditions.
2026-05-04 09:43:21 +01:00

240 lines
8.2 KiB
TypeScript

import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import { extractJavaWorkspaceLinks } from '../../../src/core/group/extractors/java-workspace-extractor.js';
describe('JavaWorkspaceExtractor', () => {
let tmpDir: string;
beforeEach(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'gitnexus-java-ws-'));
});
afterEach(async () => {
await fs.rm(tmpDir, { recursive: true, force: true });
});
async function writeFile(relPath: string, content: string) {
const absPath = path.join(tmpDir, relPath);
await fs.mkdir(path.dirname(absPath), { recursive: true });
await fs.writeFile(absPath, content, 'utf-8');
}
const pomTemplate = (g: string, a: string, deps: string[] = []) => {
const depXml = deps
.map((d) => {
const [gid, aid] = d.split(':');
return `<dependency><groupId>${gid}</groupId><artifactId>${aid}</artifactId></dependency>`;
})
.join('\n');
return `<project><groupId>${g}</groupId><artifactId>${a}</artifactId><dependencies>${depXml}</dependencies></project>`;
};
it('discovers cross-project imports via Maven pom.xml', async () => {
await writeFile('models/pom.xml', pomTemplate('com.acme', 'models'));
await writeFile(
'models/src/main/java/com/acme/models/User.java',
'package com.acme.models;\npublic class User {}\n',
);
await writeFile('api/pom.xml', pomTemplate('com.acme', 'api', ['com.acme:models']));
await writeFile(
'api/src/main/java/com/acme/api/UserService.java',
'package com.acme.api;\nimport com.acme.models.User;\npublic class UserService {}\n',
);
const repos = { models: 'models', api: 'api' };
const repoPaths = new Map([
['models', path.join(tmpDir, 'models')],
['api', path.join(tmpDir, 'api')],
]);
const result = await extractJavaWorkspaceLinks(repos, repoPaths);
expect(result.links).toHaveLength(1);
expect(result.links[0]).toEqual({
from: 'models',
to: 'api',
type: 'custom',
contract: 'models::User',
role: 'provider',
});
});
it('handles Gradle build files', async () => {
await writeFile('core/build.gradle.kts', 'group = "com.acme"\nversion = "1.0"\n');
await writeFile(
'core/src/main/java/com/acme/core/Config.java',
'package com.acme.core;\npublic class Config {}\n',
);
await writeFile(
'svc/build.gradle.kts',
'group = "com.acme"\nversion = "1.0"\ndependencies {\n implementation("com.acme:core:1.0")\n}\n',
);
await writeFile(
'svc/src/main/java/com/acme/svc/App.java',
'package com.acme.svc;\nimport com.acme.core.Config;\npublic class App {}\n',
);
const repos = { core: 'core', svc: 'svc' };
const repoPaths = new Map([
['core', path.join(tmpDir, 'core')],
['svc', path.join(tmpDir, 'svc')],
]);
const result = await extractJavaWorkspaceLinks(repos, repoPaths);
expect(result.links).toHaveLength(1);
expect(result.links[0].contract).toBe('core::Config');
});
it('handles Gradle project dependencies', async () => {
await writeFile('common/build.gradle', "group = 'com.org'\nversion = '1.0'\n");
await writeFile(
'common/src/main/java/com/org/common/Entity.java',
'package com.org.common;\npublic class Entity {}\n',
);
await writeFile(
'app/build.gradle',
"group = 'com.org'\nversion = '1.0'\ndependencies {\n implementation(project(':common'))\n}\n",
);
await writeFile(
'app/src/main/java/com/org/app/Main.java',
'package com.org.app;\nimport com.org.common.Entity;\npublic class Main {}\n',
);
const repos = { common: 'common', app: 'app' };
const repoPaths = new Map([
['common', path.join(tmpDir, 'common')],
['app', path.join(tmpDir, 'app')],
]);
const result = await extractJavaWorkspaceLinks(repos, repoPaths);
expect(result.links).toHaveLength(1);
expect(result.links[0].contract).toBe('common::Entity');
});
it('handles static imports', async () => {
await writeFile('lib/pom.xml', pomTemplate('com.acme', 'lib'));
await writeFile(
'lib/src/main/java/com/acme/lib/Constants.java',
'package com.acme.lib;\npublic class Constants {}\n',
);
await writeFile('app/pom.xml', pomTemplate('com.acme', 'app', ['com.acme:lib']));
await writeFile(
'app/src/main/java/com/acme/app/Main.java',
'package com.acme.app;\nimport static com.acme.lib.Constants;\npublic class Main {}\n',
);
const repos = { lib: 'lib', app: 'app' };
const repoPaths = new Map([
['lib', path.join(tmpDir, 'lib')],
['app', path.join(tmpDir, 'app')],
]);
const result = await extractJavaWorkspaceLinks(repos, repoPaths);
expect(result.links).toHaveLength(1);
expect(result.links[0].contract).toBe('lib::Constants');
});
it('skips repos without Java manifest', async () => {
await writeFile('rs-app/Cargo.toml', '[package]\nname = "rapp"\n');
const repos = { app: 'rapp' };
const repoPaths = new Map([['app', path.join(tmpDir, 'rs-app')]]);
const result = await extractJavaWorkspaceLinks(repos, repoPaths);
expect(result.links).toHaveLength(0);
expect(result.discoveredProjects.size).toBe(0);
});
it('deduplicates identical imports from multiple files', async () => {
await writeFile('lib/pom.xml', pomTemplate('com.acme', 'lib'));
await writeFile(
'lib/src/main/java/com/acme/lib/Token.java',
'package com.acme.lib;\npublic class Token {}\n',
);
await writeFile('app/pom.xml', pomTemplate('com.acme', 'app', ['com.acme:lib']));
await writeFile(
'app/src/main/java/com/acme/app/A.java',
'package com.acme.app;\nimport com.acme.lib.Token;\npublic class A {}\n',
);
await writeFile(
'app/src/main/java/com/acme/app/B.java',
'package com.acme.app;\nimport com.acme.lib.Token;\npublic class B {}\n',
);
const repos = { lib: 'lib', app: 'app' };
const repoPaths = new Map([
['lib', path.join(tmpDir, 'lib')],
['app', path.join(tmpDir, 'app')],
]);
const result = await extractJavaWorkspaceLinks(repos, repoPaths);
expect(result.links).toHaveLength(1);
});
it('discovers Kotlin file imports from Java projects', async () => {
await writeFile('lib/pom.xml', pomTemplate('com.acme', 'lib'));
await writeFile(
'lib/src/main/kotlin/com/acme/lib/Model.kt',
'package com.acme.lib\ndata class Model(val id: Int)\n',
);
await writeFile('app/pom.xml', pomTemplate('com.acme', 'app', ['com.acme:lib']));
await writeFile(
'app/src/main/kotlin/com/acme/app/Main.kt',
'package com.acme.app\nimport com.acme.lib.Model\nfun main() {}\n',
);
const repos = { lib: 'lib', app: 'app' };
const repoPaths = new Map([
['lib', path.join(tmpDir, 'lib')],
['app', path.join(tmpDir, 'app')],
]);
const result = await extractJavaWorkspaceLinks(repos, repoPaths);
expect(result.links).toHaveLength(1);
expect(result.links[0].contract).toBe('lib::Model');
});
it('discovers multiple types from the same dependency', async () => {
await writeFile('lib/pom.xml', pomTemplate('com.acme', 'lib'));
await writeFile(
'lib/src/main/java/com/acme/lib/Request.java',
'package com.acme.lib;\npublic class Request {}\n',
);
await writeFile(
'lib/src/main/java/com/acme/lib/Response.java',
'package com.acme.lib;\npublic class Response {}\n',
);
await writeFile('app/pom.xml', pomTemplate('com.acme', 'app', ['com.acme:lib']));
await writeFile(
'app/src/main/java/com/acme/app/Handler.java',
'package com.acme.app;\nimport com.acme.lib.Request;\nimport com.acme.lib.Response;\npublic class Handler {}\n',
);
const repos = { lib: 'lib', app: 'app' };
const repoPaths = new Map([
['lib', path.join(tmpDir, 'lib')],
['app', path.join(tmpDir, 'app')],
]);
const result = await extractJavaWorkspaceLinks(repos, repoPaths);
expect(result.links).toHaveLength(2);
const contracts = result.links.map((l) => l.contract).sort();
expect(contracts).toEqual(['lib::Request', 'lib::Response']);
});
});