count-ts-lines.mjs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. #!/usr/bin/env node
  2. import { readdir, readFile } from "node:fs/promises";
  3. import { extname, join, relative, resolve } from "node:path";
  4. import { fileURLToPath } from "node:url";
  5. const countedExtensions = new Set([".ts", ".tsx"]);
  6. const ignoredTestDirectories = new Set(["__tests__", "tests"]);
  7. const ignoredTestFileSuffixes = [".spec.ts", ".spec.tsx", ".test.ts", ".test.tsx"];
  8. const pathSeparatorPattern = /[\\/]+/u;
  9. const ignoredWorkspacePackageDirectories = new Set(["packages/debug"]);
  10. const ignoredDirectories = new Set([
  11. ".git",
  12. ".next",
  13. ".turbo",
  14. "build",
  15. "coverage",
  16. "dist",
  17. "node_modules",
  18. "out",
  19. ]);
  20. const compareText = (left, right) => {
  21. if (left === right) {
  22. return 0;
  23. }
  24. return left < right ? -1 : 1;
  25. };
  26. const toDisplayPath = (filePath) => filePath.split(pathSeparatorPattern).join("/");
  27. const isIgnoredWorkspacePackageDirectory = (root, directoryPath) => {
  28. const relativePath = toDisplayPath(relative(root, directoryPath));
  29. return ignoredWorkspacePackageDirectories.has(relativePath);
  30. };
  31. export const isTestSourceFile = (filePath) => {
  32. const displayPath = toDisplayPath(filePath);
  33. const pathSegments = displayPath.split("/");
  34. const fileName = pathSegments.at(-1) ?? displayPath;
  35. return (
  36. pathSegments.some((segment) => ignoredTestDirectories.has(segment)) ||
  37. ignoredTestFileSuffixes.some((suffix) => fileName.endsWith(suffix))
  38. );
  39. };
  40. export const countLines = (source) => {
  41. if (source.length === 0) {
  42. return 0;
  43. }
  44. const normalized = source.replaceAll("\r\n", "\n");
  45. const withoutFinalNewline = normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized;
  46. if (withoutFinalNewline.length === 0) {
  47. return 1;
  48. }
  49. return withoutFinalNewline.split("\n").length;
  50. };
  51. export const isCountedSourceFile = (filePath) =>
  52. countedExtensions.has(extname(filePath)) && !isTestSourceFile(filePath);
  53. export const collectTypeScriptFiles = async (rootDirectory) => {
  54. const root = resolve(rootDirectory);
  55. const files = [];
  56. const walk = async (directory) => {
  57. const entries = await readdir(directory, { withFileTypes: true });
  58. entries.sort((left, right) => compareText(left.name, right.name));
  59. for (const entry of entries) {
  60. if (entry.isSymbolicLink()) {
  61. continue;
  62. }
  63. const absolutePath = join(directory, entry.name);
  64. if (entry.isDirectory()) {
  65. if (
  66. !ignoredDirectories.has(entry.name) &&
  67. !ignoredTestDirectories.has(entry.name) &&
  68. !isIgnoredWorkspacePackageDirectory(root, absolutePath)
  69. ) {
  70. await walk(absolutePath);
  71. }
  72. continue;
  73. }
  74. const relativePath = toDisplayPath(relative(root, absolutePath));
  75. if (entry.isFile() && isCountedSourceFile(relativePath)) {
  76. files.push({
  77. absolutePath,
  78. relativePath,
  79. });
  80. }
  81. }
  82. };
  83. await walk(root);
  84. return files.sort((left, right) => compareText(left.relativePath, right.relativePath));
  85. };
  86. export const measureTypeScriptFiles = async (rootDirectory) => {
  87. const files = await collectTypeScriptFiles(rootDirectory);
  88. return Promise.all(
  89. files.map(async (file) => {
  90. const buffer = await readFile(file.absolutePath);
  91. const source = buffer.toString("utf8");
  92. return {
  93. ...file,
  94. bytes: buffer.byteLength,
  95. lines: countLines(source),
  96. };
  97. }),
  98. );
  99. };
  100. export const formatReport = (measurements) => {
  101. const sorted = [...measurements].sort((left, right) => {
  102. const lineDelta = right.lines - left.lines;
  103. if (lineDelta !== 0) {
  104. return lineDelta;
  105. }
  106. return compareText(left.relativePath, right.relativePath);
  107. });
  108. const totalLines = sorted.reduce((total, file) => total + file.lines, 0);
  109. const totalBytes = sorted.reduce((total, file) => total + file.bytes, 0);
  110. const lineWidth = Math.max("Lines".length, ...sorted.map((file) => String(file.lines).length));
  111. const byteWidth = Math.max("Bytes".length, ...sorted.map((file) => String(file.bytes).length));
  112. const rows = sorted.map(
  113. (file) =>
  114. `${String(file.lines).padStart(lineWidth)} ${String(file.bytes).padStart(byteWidth)} ${file.relativePath}`,
  115. );
  116. return (
  117. [
  118. "TypeScript file lengths (.ts, .tsx)",
  119. `Files: ${sorted.length}`,
  120. `Total lines: ${totalLines}`,
  121. `Total bytes: ${totalBytes}`,
  122. "",
  123. `${"Lines".padStart(lineWidth)} ${"Bytes".padStart(byteWidth)} File`,
  124. ...rows,
  125. ].join("\n") + "\n"
  126. );
  127. };
  128. const main = async () => {
  129. const [rootArgument] = process.argv.slice(2);
  130. const rootDirectory = rootArgument ? resolve(rootArgument) : process.cwd();
  131. const measurements = await measureTypeScriptFiles(rootDirectory);
  132. process.stdout.write(formatReport(measurements));
  133. };
  134. const scriptPath = fileURLToPath(import.meta.url);
  135. const invokedPath = process.argv[1] ? resolve(process.argv[1]) : "";
  136. if (invokedPath === scriptPath) {
  137. main().catch((error) => {
  138. const message = error instanceof Error ? error.message : String(error);
  139. process.stderr.write(`lint:count failed: ${message}\n`);
  140. process.exitCode = 1;
  141. });
  142. }