Skip to content

Instantly share code, notes, and snippets.

@ladifire
Created July 16, 2022 02:06
Show Gist options
  • Save ladifire/a4195a974fbab958b4e4107a348e2e1d to your computer and use it in GitHub Desktop.
Save ladifire/a4195a974fbab958b4e4107a348e2e1d to your computer and use it in GitHub Desktop.
Scan recursion functions on repo
const { resolve } = require('path')
const { readdir } = require('fs').promises
const babel = require('@babel/core')
const fs = require('fs')
const t = require('@babel/types')
async function* getFiles(dir) {
const dirents = await readdir(dir, { withFileTypes: true })
for (const dirent of dirents) {
const res = resolve(dir, dirent.name)
if (dirent.isDirectory()) {
yield* getFiles(res)
} else {
yield res
}
}
}
let index = 0
;(async () => {
console.log('=========START DETECT RECURSION FUNCTIONS IN GAPOWORK=========')
for await (const fileName of getFiles('./src')) {
if (
fileName.endsWith('.js') ||
fileName.endsWith('.jsx') ||
fileName.endsWith('.ts') ||
fileName.endsWith('.tsx')
) {
const content = fs.readFileSync(fileName, 'utf-8')
const ast = babel.parse(content, {
sourceType: 'module',
filename: 'bundle.tsx',
presets: [
['@babel/preset-env', { loose: true }],
[
'@babel/preset-react',
{
pragma: 'React.createElement',
pragmaFrag: 'React.Fragment',
throwIfNamespace: false,
},
],
'@babel/preset-typescript',
],
comments: false,
})
babel.traverse(ast, {
FunctionDeclaration: function (path) {
let found = false
if (path.node.id) {
index++
if (path.node && path.node.id) {
if (
path.node.body &&
path.node.body.body &&
path.node.body.body.length
) {
path.node.body.body.forEach((item) => {
if (t.isExpressionStatement(item) && item.expression.callee) {
if (path.node.id.name === item.expression.callee.name) {
found = true
console.log(
`🧤 Found recursion function: ${item.expression.callee.name}`,
)
}
}
})
} else {
console.log('path.node.body.body', path.node.body.body)
}
} else {
console.log('Function with empty body')
}
console.log(
'Checking recursion function:',
path.node.id.name,
'----->',
found ? '❌' : '✅',
)
}
},
})
}
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment