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

feat(type-checking): Add type-checking pre-commit hooks #32261

Merged
merged 12 commits into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from 5 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
35 changes: 34 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,39 @@ repos:
language: system
pass_filenames: true
files: \.(js|jsx|ts|tsx)$
- repo: local
hooks:
- id: type-checking-frontend
name: Type-Checking (Frontend)
entry: ./scripts/check-type.js
args: [package=superset-frontend, excludeDeclarationDir=cypress-base]
language: node
files: ^superset-frontend\/.*\.(js|jsx|ts|tsx)$
exclude: ^superset-frontend/cypress-base\/
- repo: local
hooks:
- id: type-checking-websocket
name: Type-Checking (Websocket)
entry: ./scripts/check-type.js
args: [package=superset-websocket]
language: node
files: ^superset-websocket\/.*\.(js|jsx|ts|tsx)$
- repo: local
hooks:
- id: type-checking-embedded-sdk
name: Type-Checking (Embedded SDK)
entry: ./scripts/check-type.js
args: [package=superset-embedded-sdk]
language: node
files: ^superset-embedded-sdk\/.*\.(js|jsx|ts|tsx)$
- repo: local
hooks:
- id: type-checking-cypress
name: Type-Checking (Cypress)
entry: ./scripts/check-type.js
args: [package=superset-frontend/cypress-base]
language: node
files: ^superset-frontend/cypress-base\/.*\.(js|jsx|ts|tsx)$
# blacklist unsafe functions like make_url (see #19526)
- repo: https://github.com/skorokithakis/blacklist-pre-commit-hook
rev: e2f070289d8eddcaec0b580d3bde29437e7c8221
Expand All @@ -83,5 +116,5 @@ repos:
rev: v0.8.0
hooks:
- id: ruff
args: [ --fix ]
args: [--fix]
- id: ruff-format
180 changes: 180 additions & 0 deletions scripts/check-type.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
#!/usr/bin/env node

/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

// @ts-check
const { exit } = require("node:process");
const { join, dirname } = require("node:path");
const { readdir } = require("node:fs/promises");
const { chdir, cwd } = require("node:process");
const { createRequire } = require("node:module");

const SUPERSET_ROOT = dirname(__dirname);
const PACKAGE_ARG_REGEX = /^package=/;
const EXCLUDE_DECLARATION_DIR_REGEX = /^excludeDeclarationDir=/;
const DECLARATION_FILE_REGEX = /\.d\.ts$/;

void (async () => {
const args = process.argv.slice(2);
const {
matchedArgs: [packageArg, excludeDeclarationDirArg],
remainingArgs,
} = extractArgs(args, [PACKAGE_ARG_REGEX, EXCLUDE_DECLARATION_DIR_REGEX]);

if (!packageArg) {
console.error("package is not specified");
exit(1);
}

const packageRootDir = getPackage(packageArg);
const packagePathRegex = new RegExp(`^${packageRootDir}\/`);
const updatedArgs = removePackageSegment(remainingArgs, packagePathRegex);
const argsStr = updatedArgs.join(" ");

const excludedDeclarationDirs = getExcludedDeclarationDirs(
excludeDeclarationDirArg
);
let declarationFiles = await getFilesRecursively(
packageRootDir,
DECLARATION_FILE_REGEX,
excludedDeclarationDirs
);
declarationFiles = removePackageSegment(declarationFiles, packagePathRegex);
const declarationFilesStr = declarationFiles.join(" ");

const packageRootDirAbsolute = join(SUPERSET_ROOT, packageRootDir);
const tsConfig = join(packageRootDirAbsolute, "tsconfig.json");
const command = `--noEmit --allowJs --composite false --project ${tsConfig} ${argsStr} ${declarationFilesStr}`;

try {
chdir(packageRootDirAbsolute);
const packageRequire = createRequire(join(cwd(), "node_modules"));
// Please ensure that tscw-config is installed in the package being type-checked.
const tscw = packageRequire("tscw-config");
const child = await tscw`${command}`;

if (child.stdout) {
console.log(child.stdout);
} else {
console.error(child.stderr);
}

exit(child.exitCode);
} catch (e) {
console.error("Failed to execute type checking:", e);
console.error("Package:", packageRootDir);
console.error("Command:", `tscw ${command}`);
exit(1);
}
})();

/**
* @param {string} dir
* @param {RegExp} regex
* @param {string[]} excludedDirs
*
* @returns {Promise<string[]>}
*/

async function getFilesRecursively(dir, regex, excludedDirs) {
const files = await readdir(dir, { withFileTypes: true });
/** @type {string[]} */
let result = [];

for (const file of files) {
const fullPath = join(dir, file.name);
const shouldExclude = excludedDirs.includes(file.name);

if (file.isDirectory() && !shouldExclude) {
result = result.concat(
await getFilesRecursively(fullPath, regex, excludedDirs)
);
} else if (regex.test(file.name)) {
result.push(fullPath);
}
}
return result;
}

/**
*
* @param {string} packageArg
* @returns {string}
*/
function getPackage(packageArg) {
return packageArg.split("=")[1].replace(/\/$/, "");
}

/**
*
* @param {string | undefined} excludeDeclarationDirArg
* @returns {string[]}
*/
function getExcludedDeclarationDirs(excludeDeclarationDirArg) {
const excludedDirs = ["node_modules"];

return !excludeDeclarationDirArg
? excludedDirs
: excludeDeclarationDirArg
.split("=")[1]
.split(",")
.map((dir) => dir.replace(/\/$/, "").trim())
.concat(excludedDirs);
}

/**
*
* @param {string[]} args
* @param {RegExp[]} regexes
* @returns {{ matchedArgs: (string | undefined)[], remainingArgs: string[] }}
*/

function extractArgs(args, regexes) {
/**
* @type {(string | undefined)[]}
*/
const matchedArgs = [];
const remainingArgs = [...args];

regexes.forEach((regex) => {
const index = remainingArgs.findIndex((arg) => regex.test(arg));
if (index !== -1) {
const [arg] = remainingArgs.splice(index, 1);
matchedArgs.push(arg);
} else {
matchedArgs.push(undefined);
}
});

return { matchedArgs, remainingArgs };
}

/**
* Remove the package segment from path.
*
* For example: `superset-frontend/foo/bar.ts` -> `foo/bar.ts`
*
* @param {string[]} args
* @param {RegExp} packagePathRegex
* @returns {string[]}
*/
function removePackageSegment(args, packagePathRegex) {
return args.map((arg) => arg.replace(packagePathRegex, ""));
}
51 changes: 49 additions & 2 deletions superset-embedded-sdk/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions superset-embedded-sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"axios": "^1.7.7",
"babel-loader": "^9.1.3",
"jest": "^29.7.0",
"tscw-config": "^1.1.2",
"typescript": "^5.6.2",
"webpack": "^5.94.0",
"webpack-cli": "^5.1.4"
Expand Down
Loading
Loading