Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ESLint plugin] Add a rule to enforce folder architecture on frontend #7481

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions .eslintrc.react.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ module.exports = {
'@nx/workspace-use-getLoadable-and-getValue-to-get-atoms': 'error',
'@nx/workspace-useRecoilCallback-has-dependency-array': 'error',
'@nx/workspace-no-navigate-prefer-link': 'error',
'@nx/workspace-folder-structure': 'warn',
'react/no-unescaped-entities': 'off',
'react/prop-types': 'off',
'react/jsx-key': 'off',
Expand Down
6 changes: 6 additions & 0 deletions tools/eslint-rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ import {
RULE_NAME as useRecoilCallbackHasDependencyArrayName,
} from './rules/useRecoilCallback-has-dependency-array';

import {
rule as folderStructureRule,
RULE_NAME as folderStructureRuleName,
} from './rules/folder-structure-rule';

/**
* Import your custom workspace rules at the top of this file.
*
Expand Down Expand Up @@ -93,5 +98,6 @@ module.exports = {
useRecoilCallbackHasDependencyArray,
[noNavigatePreferLinkName]: noNavigatePreferLink,
[injectWorkspaceRepositoryName]: injectWorkspaceRepository,
[folderStructureRuleName]: folderStructureRule,
},
};
239 changes: 239 additions & 0 deletions tools/eslint-rules/rules/folder-structure-rule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
import { ESLintUtils } from '@typescript-eslint/utils';
import fs from 'fs';
import path from 'path';
import {
CASES,
ExtensionsType,
FolderRule,
NameValidationType,
RULES,
configs,
stringifyConfig,
} from './folderStructureConfig';

export const RULE_NAME = 'folder-structure';

const validateString = (input: string, validator: NameValidationType) => {
const {
prefix = '',
suffix = '',
namePattern,
extension = '',
} = typeof validator === 'string'
? { namePattern: validator }
: validator || {};

const prefixArray = Array.isArray(prefix) ? prefix : [prefix];
const suffixArray = Array.isArray(suffix) ? suffix : [suffix];
const nameArray = Array.isArray(namePattern) ? namePattern : [namePattern];
const extensionArray = Array.isArray(extension) ? extension : [extension];

let fileName = input;

if (namePattern === '*') {
return true;
}

// Check for prefix
const foundPrefix = prefix
? prefixArray.find((pfx) => fileName.startsWith(pfx))
: '';

if (foundPrefix === undefined) {
return false;
}

fileName = fileName.substring(foundPrefix.length);

if (extension) {
const extIndex = fileName.indexOf('.');
if (extIndex === -1) {
return false;
}

const extractedExt = fileName.substring(extIndex + 1) as ExtensionsType;
const foundExt = extensionArray.find((ext) => ext === extractedExt);
if (foundExt === undefined) {
return false;
}

fileName = fileName.substring(0, extIndex);

if (foundExt.endsWith('tsx')) {
if (foundExt.endsWith('test.tsx') && foundPrefix === 'use') {
return CASES['StrictPascalCase'].test(fileName);
}
return CASES['StrictPascalCase'].test(foundPrefix + fileName);
}

if (foundExt.endsWith('ts')) {
return (
CASES['StrictCamelCase'].test(foundPrefix + fileName) ||
CASES['kebab-case'].test(foundPrefix + fileName)
);
}
}

// Check for suffix
const foundSuffix = suffix
? suffixArray.find((sfx) => fileName.endsWith(sfx))
: '';

if (foundSuffix === undefined) {
return false;
}

fileName = fileName.substring(0, fileName.length - foundSuffix.length);

// Check name cases
const nameValidated = namePattern
? nameArray.find((caseName) => {
const nameRegex = CASES[caseName];
return nameRegex ? nameRegex.test(fileName) : fileName === caseName;
})
: '';

if (nameValidated === undefined) {
return false;
}

return true;
};
const invalid = {};
const valid = {};
// Recursive function to check folder structure based on config
const checkFolderStructure = (
currentPath: string,
config: FolderRule,
): boolean => {
const { name, children, ruleId } = config;

if (name) {
const folderName = currentPath.split('/').pop();
const isNameValid = validateString(folderName, name);

if (isNameValid) {
valid[currentPath] = true;
delete invalid[currentPath];
if (!ruleId && (!children || children.length === 0)) {
return true;
}
} else {
const isAlreadyValid = valid[currentPath];
if (isAlreadyValid) {
delete invalid[currentPath];
} else {
const invalidPath = invalid[currentPath] || [];
invalid[currentPath] = [...invalidPath, { name }];
}
return false;
}
}

if (ruleId) {
const rule = RULES[ruleId];
const folderName = currentPath.split('/').pop();

if (rule.reservedFolders && rule.reservedFolders.includes(folderName)) {
return false;
}

return checkFolderStructure(currentPath, {
...rule,
name: name ? undefined : rule.name,
});
}

if (children) {
const filesOrSubFolders = fs.readdirSync(currentPath, {
withFileTypes: true,
});
const isolatedFiles = filesOrSubFolders.filter((file) => file.isFile());
const isolatedFilesRules = children.filter(
(rule) => !rule.children && rule.name && !rule.ruleId,
);
const subFolders = filesOrSubFolders.filter((file) => file.isDirectory());
const subFoldersRules = children.filter(
(rule) => rule.children || rule.ruleId,
);

const areIsolatedFilesValid =
isolatedFiles.length === 0 ||
isolatedFiles
.map((file) => {
if (isolatedFilesRules.length === 0) return;
const isFileValid = isolatedFilesRules.some((rule) => {
return checkFolderStructure(`${currentPath}/${file.name}`, rule);
});

return isFileValid;
})
.every(Boolean);

const areSubFoldersValid =
subFolders.length === 0 ||
subFolders
.map((subFolder) => {
if (subFoldersRules.length === 0) return;
const isSubFolderValid = subFoldersRules.some((rule) => {
return checkFolderStructure(
`${currentPath}/${subFolder.name}`,
rule,
);
});

return isSubFolderValid;
})
.every(Boolean);
return areIsolatedFilesValid && areSubFoldersValid;
}

return false;
};

let hasRun = false;

// ESLint rule definition
export const rule = ESLintUtils.RuleCreator(() => __filename)({
name: RULE_NAME,
meta: {
type: 'problem',
docs: {
description:
'Enforce folder structure and naming conventions in the modules directory',
recommended: 'recommended',
},
fixable: null,
schema: [],
messages: {
invalidName:
"Path name '{{ pathName }}' is invalid. Allowed patterns: '{{ expectedPatterns }}'.",
},
},
defaultOptions: [],
create: (context) => {
if (hasRun) return {};
hasRun = true;

const rootFolder = path.resolve(
__dirname,
'../../../packages/twenty-front/src',
);

checkFolderStructure(rootFolder, configs);

Object.keys(invalid).forEach((invalidPath) => {
context.report({
messageId: 'invalidName',
loc: { line: 1, column: 0 },
data: {
pathName: invalidPath,
expectedPatterns: stringifyConfig(invalid[invalidPath]),
},
fix: null,
});
});

return {};
},
});
Loading
Loading