Skip to content

Instantly share code, notes, and snippets.

@temoncher
Created December 24, 2022 12:37
Show Gist options
  • Select an option

  • Save temoncher/7a3f047daf2ddd9052f23420d2bc5463 to your computer and use it in GitHub Desktop.

Select an option

Save temoncher/7a3f047daf2ddd9052f23420d2bc5463 to your computer and use it in GitHub Desktop.
Script to delete unused files based on `ts-prune`
// @ts-check
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const { parse } = require('@typescript-eslint/parser');
const eslintRc = require('../.eslintrc.js');
const unusedExportsByFilename = execSync('ts-prune')
.toString()
.split('\n')
.reduce((acc, line) => {
const [exportPath, exportName] = line.split(' - ');
const [relativeFilePath, lineNumber] = exportPath.split(':');
if (!relativeFilePath) {
return acc;
}
if (!acc[relativeFilePath]) {
acc[relativeFilePath] = [];
}
acc[relativeFilePath].push(exportName);
return acc;
}, {});
Object.entries(unusedExportsByFilename).forEach(([relativeFilePath, unusedExports]) => {
const absoluteFilePath = path.resolve(relativeFilePath);
const fileContents = fs.readFileSync(absoluteFilePath, 'utf8');
try {
const prased = parse(fileContents, {
...eslintRc.parserOptions,
ecmaFeatures: {
...eslintRc.parserOptions?.ecmaFeatures,
jsx: relativeFilePath.endsWith('.tsx'),
},
range: true,
});
// eslint-disable-next-line complexity
const exportsCount = prased.body.reduce((acc, node) => {
if (node.type === 'ExportDefaultDeclaration' || node.type === 'TSExportAssignment') {
return acc + 1;
}
if (node.type === 'ExportNamedDeclaration') {
if (node.declaration) {
if (node.declaration.type === 'VariableDeclaration') {
return acc + node.declaration.declarations.length;
}
return acc + 1;
}
if (node.specifiers.length !== 0) {
return acc + node.specifiers.length;
}
}
if (node.type === 'ExportAllDeclaration') {
// Can not calculate * exports;
return Infinity;
}
return acc;
}, 0);
if (exportsCount === unusedExports.length) {
fs.unlinkSync(absoluteFilePath);
// eslint-disable-next-line no-console
console.log('deleted', relativeFilePath);
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('FAILED', relativeFilePath);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment