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
123 changes: 45 additions & 78 deletions package-lock.json

Large diffs are not rendered by default.

9 changes: 8 additions & 1 deletion packages/folder-structure-cruiser/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,14 @@ npx depcruise --ts-config ./tsconfig.base.json --webpack-config ./webpack.config

```json
{
"extends": ["@leancodepl/folder-structure-cruiser/.dependency-cruiser.json"]
"extends": ["@leancodepl/folder-structure-cruiser/.dependency-cruiser.json"],
"options": {
"folderStructureCruiser": {
"crossFeatureImports": {
"allowImportsFromDirectChildrenOf": ["src/features"]
}
}
}
}
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,23 @@ describe("cross-feature-imports validation", () => {
)
}, 30000)

it("should allow imports from direct children of configured folder", async () => {
const dirname = import.meta.dirname
const testDir = join(dirname, "test-structure")
const filePath = join(testDir, "polls/SnapshotPollEditor/index.tsx")
const configPath = join(dirname, "test-configs/allow-direct-children.config.json")

await validateCrossFeatureImports({
directories: [filePath],
configPath: configPath,
})

expect(consoleErrorSpy).not.toHaveBeenCalledWith(
expect.anything(),
expect.stringContaining("SnapshotPollEditor/index.tsx → __tests__/test-structure/surveys/SurveyEditor/index.tsx"),
)
}, 30000)

it("should detect violations in ActivityEditor (nested sibling child import)", async () => {
const dirname = import.meta.dirname
const testDir = join(dirname, "test-structure")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": ["../../.dependency-cruiser.json"],
"options": {
"folderStructureCruiser": {
"crossFeatureImports": {
"allowImportsFromDirectChildrenOf": ["surveys"]
}
}
}
}
7 changes: 6 additions & 1 deletion packages/folder-structure-cruiser/src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,12 @@ program
const tsConfigPath = options.tsConfig
const webpackConfigPath = options.webpackConfig

await validateCrossFeatureImports({ directories, configPath, tsConfigPath, webpackConfigPath })
await validateCrossFeatureImports({
directories,
configPath,
tsConfigPath,
webpackConfigPath,
})
})

program.parse()
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { checkCrossFeatureImports } from "../lib/checkCrossFeatureImports.js"
import { formatMessages } from "../lib/formatMessages.js"
import { CruiseParams, getCruiseResult } from "../lib/getCruiseResult.js"
import { getFolderStructureCruiserConfig } from "../lib/getFolderStructureCruiserConfig.js"
import { logger } from "../lib/logger.js"

/**
Expand Down Expand Up @@ -62,9 +63,12 @@ import { logger } from "../lib/logger.js"
*/
export async function validateCrossFeatureImports(cruiseParams: CruiseParams) {
try {
const folderStructureCruiserConfig = await getFolderStructureCruiserConfig(cruiseParams.configPath)
const cruiseResult = await getCruiseResult(cruiseParams)

const { messages: errorMessages, totalCruised } = checkCrossFeatureImports(cruiseResult)
const { messages: errorMessages, totalCruised } = checkCrossFeatureImports(cruiseResult, {
allowImportsFromDirectChildrenOf: folderStructureCruiserConfig.allowImportsFromDirectChildrenOf,
})

if (errorMessages.length === 0) {
logger.success("✅ No issues found!")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,55 @@ import { findCommonPathsPrefixLength } from "./findCommonPathsPrefix.js"
import { Message } from "./formatMessages.js"

type CheckResult = { messages: Message[]; totalCruised: number }
type CheckCrossFeatureImportsOptions = {
allowImportsFromDirectChildrenOf?: string[]
}

const indexFilePattern = /^index(?:\..+)?$/

function normalizePath(path: string): string[] {
return path.split("/").filter(segment => segment.length > 0 && segment !== ".")
}

function findSubPathIndex(path: string[], subPath: string[]): number {
if (subPath.length === 0 || path.length < subPath.length) {
return -1
}

for (let i = 0; i <= path.length - subPath.length; i++) {
const isMatch = subPath.every((segment, offset) => path[i + offset] === segment)

if (isMatch) {
return i
}
}

return -1
}

function isDirectChildImportOfDirectory(dependencyPath: string[], directoryPath: string[]): boolean {
const directoryPathStartIndex = findSubPathIndex(dependencyPath, directoryPath)

if (directoryPathStartIndex < 0) {
return false
}

const relativePathFromDirectory = dependencyPath.slice(directoryPathStartIndex + directoryPath.length)

if (relativePathFromDirectory.length === 1) {
return true
}

return relativePathFromDirectory.length === 2 && indexFilePattern.test(relativePathFromDirectory[1])
}

export function checkCrossFeatureImports(result: IReporterOutput): CheckResult {
export function checkCrossFeatureImports(
result: IReporterOutput,
options: CheckCrossFeatureImportsOptions = {},
): CheckResult {
const output = typeof result.output === "object" ? result.output : undefined
const modules = output?.modules ?? []
const allowedDirectChildrenDirectories = (options.allowImportsFromDirectChildrenOf ?? []).map(normalizePath)

const errorMessages: Message[] = []

Expand All @@ -22,10 +67,14 @@ export function checkCrossFeatureImports(result: IReporterOutput): CheckResult {
dependencies.forEach(dependency => {
const dependencyPath = dependency.resolved.split("/")
const commonPrefixPathLength = findCommonPathsPrefixLength([modulePath, dependencyPath])
const shouldAllowDirectChildrenImport = allowedDirectChildrenDirectories.some(directoryPath =>
isDirectChildImportOfDirectory(dependencyPath, directoryPath),
)

if (
!commonPrefixPathLength ||
(commonPrefixPathLength < modulePath.length && dependencyPath.length > commonPrefixPathLength + 2)
!shouldAllowDirectChildrenImport &&
(!commonPrefixPathLength ||
(commonPrefixPathLength < modulePath.length && dependencyPath.length > commonPrefixPathLength + 2))
) {
errorMessages.push({
source: module.source,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import extractDepcruiseOptions from "dependency-cruiser/config-utl/extract-depcruise-options"

type CruiseOptionsWithFolderStructureCruiser = {
folderStructureCruiser?: {
crossFeatureImports?: {
allowImportsFromDirectChildrenOf?: string[]
}
}
}

export type FolderStructureCruiserConfig = {
allowImportsFromDirectChildrenOf: string[]
}

function parseStringArray(value: unknown): string[] {
return Array.isArray(value) && value.every(item => typeof item === "string") ? value : []
}

export async function getFolderStructureCruiserConfig(configPath: string): Promise<FolderStructureCruiserConfig> {
if (!configPath) {
return { allowImportsFromDirectChildrenOf: [] }
}

const depcruiseOptions = (await extractDepcruiseOptions(configPath)) as CruiseOptionsWithFolderStructureCruiser
const allowImportsFromDirectChildrenOf = parseStringArray(
depcruiseOptions.folderStructureCruiser?.crossFeatureImports?.allowImportsFromDirectChildrenOf,
)

return {
allowImportsFromDirectChildrenOf,
}
}
Loading