oxlint-metrics-uploader.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. const { execSync } = require('child_process');
  20. const { google } = require('googleapis');
  21. const { SPREADSHEET_ID } = process.env;
  22. const SERVICE_ACCOUNT_KEY = JSON.parse(process.env.SERVICE_ACCOUNT_KEY || '{}');
  23. // Only set up Google Sheets if we have credentials
  24. let sheets;
  25. if (SERVICE_ACCOUNT_KEY.client_email) {
  26. const auth = new google.auth.GoogleAuth({
  27. credentials: SERVICE_ACCOUNT_KEY,
  28. scopes: ['https://www.googleapis.com/auth/spreadsheets'],
  29. });
  30. sheets = google.sheets({ version: 'v4', auth });
  31. }
  32. const DATETIME = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
  33. async function writeToGoogleSheet(data, range, headers, append = false) {
  34. if (!sheets) {
  35. console.log('No Google Sheets credentials, skipping upload');
  36. return;
  37. }
  38. const request = {
  39. spreadsheetId: SPREADSHEET_ID,
  40. range,
  41. valueInputOption: 'USER_ENTERED',
  42. resource: { values: append ? data : [headers, ...data] },
  43. };
  44. const method = append ? 'append' : 'update';
  45. await sheets.spreadsheets.values[method](request);
  46. }
  47. // Run OXC and get JSON output
  48. async function runOxlintAndProcess() {
  49. const enrichedRules = {
  50. 'react-prefer-function-component/react-prefer-function-component': {
  51. description: 'We prefer function components to class-based components',
  52. },
  53. 'react/jsx-filename-extension': {
  54. description:
  55. 'We prefer Typescript - all JSX files should be converted to TSX',
  56. },
  57. 'react/forbid-component-props': {
  58. description:
  59. 'We prefer Emotion for styling rather than `className` or `style` props',
  60. },
  61. 'no-restricted-imports': {
  62. description:
  63. "This rule catches several things that shouldn't be used anymore. LESS, antD, etc. See individual occurrence messages for details",
  64. },
  65. 'no-console': {
  66. description:
  67. "We don't want a bunch of console noise, but you can use the `logger` from `@superset-ui/core` when there's a reason to.",
  68. },
  69. };
  70. try {
  71. // Run OXC with JSON format
  72. console.log('Running OXC linter...');
  73. const oxlintOutput = execSync('npx oxlint --format json', {
  74. encoding: 'utf8',
  75. maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large outputs
  76. stdio: ['pipe', 'pipe', 'ignore'], // Ignore stderr to avoid error output
  77. });
  78. const results = JSON.parse(oxlintOutput);
  79. // Process OXC JSON output
  80. const metricsByRule = {};
  81. let occurrencesData = [];
  82. // OXC JSON format has diagnostics array
  83. if (results.diagnostics && Array.isArray(results.diagnostics)) {
  84. results.diagnostics.forEach(diagnostic => {
  85. // Extract rule ID from code like "eslint(no-unused-vars)" or "eslint-plugin-unicorn(no-new-array)"
  86. const codeMatch = diagnostic.code?.match(
  87. /^(?:eslint(?:-plugin-(\w+))?\()([^)]+)\)$/,
  88. );
  89. let ruleId = diagnostic.code || 'unknown';
  90. if (codeMatch) {
  91. const plugin = codeMatch[1];
  92. const rule = codeMatch[2];
  93. ruleId = plugin ? `${plugin}/${rule}` : rule;
  94. }
  95. const file = diagnostic.filename || 'unknown';
  96. const line = diagnostic.labels?.[0]?.span?.line || 0;
  97. const column = diagnostic.labels?.[0]?.span?.column || 0;
  98. const message = diagnostic.message || '';
  99. const ruleData = metricsByRule[ruleId] || { count: 0 };
  100. ruleData.count += 1;
  101. metricsByRule[ruleId] = ruleData;
  102. occurrencesData.push({
  103. rule: ruleId,
  104. message,
  105. file,
  106. line,
  107. column,
  108. ts: DATETIME,
  109. });
  110. });
  111. }
  112. console.log(
  113. `OXC found ${results.diagnostics?.length || 0} issues across ${results.number_of_files} files`,
  114. );
  115. // Also run minimal ESLint for custom rules and merge results
  116. console.log('Running minimal ESLint for custom rules...');
  117. let eslintOutput = '[]';
  118. try {
  119. // Run ESLint and capture output directly
  120. eslintOutput = execSync(
  121. 'npx eslint --no-eslintrc --config .eslintrc.minimal.js --no-inline-config --format json src',
  122. {
  123. encoding: 'utf8',
  124. maxBuffer: 50 * 1024 * 1024,
  125. stdio: ['pipe', 'pipe', 'ignore'], // Ignore stderr
  126. },
  127. );
  128. } catch (e) {
  129. // ESLint exits with non-zero when it finds issues, capture the stdout
  130. if (e.stdout) {
  131. eslintOutput = e.stdout.toString();
  132. }
  133. }
  134. // Parse minimal ESLint output
  135. try {
  136. const eslintResults = JSON.parse(eslintOutput);
  137. eslintResults.forEach(result => {
  138. result.messages.forEach(({ ruleId, line, column, message }) => {
  139. const ruleData = metricsByRule[ruleId] || { count: 0 };
  140. ruleData.count += 1;
  141. metricsByRule[ruleId] = ruleData;
  142. occurrencesData.push({
  143. rule: ruleId,
  144. message,
  145. file: result.filePath,
  146. line,
  147. column,
  148. ts: DATETIME,
  149. });
  150. });
  151. });
  152. console.log(
  153. `ESLint found ${eslintResults.reduce((sum, r) => sum + r.messages.length, 0)} custom rule violations`,
  154. );
  155. } catch (e) {
  156. console.log('No ESLint issues found or parsing error:', e.message);
  157. }
  158. // Transform data for Google Sheets
  159. const metricsData = Object.entries(metricsByRule).map(
  160. ([rule, { count }]) => [
  161. 'OXC+ESLint',
  162. rule,
  163. enrichedRules[rule]?.description || 'N/A',
  164. `${count}`,
  165. DATETIME,
  166. ],
  167. );
  168. occurrencesData = occurrencesData.map(
  169. ({ rule, message, file, line, column }) => [
  170. rule,
  171. enrichedRules[rule]?.description || 'N/A',
  172. message,
  173. file,
  174. `${line}`,
  175. `${column}`,
  176. DATETIME,
  177. ],
  178. );
  179. const aggregatedHistoryHeaders = [
  180. 'Process',
  181. 'Rule',
  182. 'Description',
  183. 'Count',
  184. 'Timestamp',
  185. ];
  186. const eslintBacklogHeaders = [
  187. 'Rule',
  188. 'Rule Description',
  189. 'ESLint Message',
  190. 'File',
  191. 'Line',
  192. 'Column',
  193. 'Timestamp',
  194. ];
  195. console.log(
  196. `Found ${Object.keys(metricsByRule).length} unique rules with ${occurrencesData.length} total occurrences`,
  197. );
  198. await writeToGoogleSheet(
  199. metricsData,
  200. 'Aggregated History!A:E',
  201. aggregatedHistoryHeaders,
  202. true,
  203. );
  204. await writeToGoogleSheet(
  205. occurrencesData,
  206. 'ESLint Backlog!A:G',
  207. eslintBacklogHeaders,
  208. );
  209. console.log('Successfully uploaded metrics to Google Sheets');
  210. } catch (error) {
  211. console.error('Error processing lint results:', error);
  212. process.exit(1);
  213. }
  214. }
  215. // Run the process
  216. runOxlintAndProcess().catch(console.error);