| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245 |
- /**
- * 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.
- */
- const { execSync } = require('child_process');
- const { google } = require('googleapis');
- const { SPREADSHEET_ID } = process.env;
- const SERVICE_ACCOUNT_KEY = JSON.parse(process.env.SERVICE_ACCOUNT_KEY || '{}');
- // Only set up Google Sheets if we have credentials
- let sheets;
- if (SERVICE_ACCOUNT_KEY.client_email) {
- const auth = new google.auth.GoogleAuth({
- credentials: SERVICE_ACCOUNT_KEY,
- scopes: ['https://www.googleapis.com/auth/spreadsheets'],
- });
- sheets = google.sheets({ version: 'v4', auth });
- }
- const DATETIME = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
- async function writeToGoogleSheet(data, range, headers, append = false) {
- if (!sheets) {
- console.log('No Google Sheets credentials, skipping upload');
- return;
- }
- const request = {
- spreadsheetId: SPREADSHEET_ID,
- range,
- valueInputOption: 'USER_ENTERED',
- resource: { values: append ? data : [headers, ...data] },
- };
- const method = append ? 'append' : 'update';
- await sheets.spreadsheets.values[method](request);
- }
- // Run OXC and get JSON output
- async function runOxlintAndProcess() {
- const enrichedRules = {
- 'react-prefer-function-component/react-prefer-function-component': {
- description: 'We prefer function components to class-based components',
- },
- 'react/jsx-filename-extension': {
- description:
- 'We prefer Typescript - all JSX files should be converted to TSX',
- },
- 'react/forbid-component-props': {
- description:
- 'We prefer Emotion for styling rather than `className` or `style` props',
- },
- 'no-restricted-imports': {
- description:
- "This rule catches several things that shouldn't be used anymore. LESS, antD, etc. See individual occurrence messages for details",
- },
- 'no-console': {
- description:
- "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.",
- },
- };
- try {
- // Run OXC with JSON format
- console.log('Running OXC linter...');
- const oxlintOutput = execSync('npx oxlint --format json', {
- encoding: 'utf8',
- maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large outputs
- stdio: ['pipe', 'pipe', 'ignore'], // Ignore stderr to avoid error output
- });
- const results = JSON.parse(oxlintOutput);
- // Process OXC JSON output
- const metricsByRule = {};
- let occurrencesData = [];
- // OXC JSON format has diagnostics array
- if (results.diagnostics && Array.isArray(results.diagnostics)) {
- results.diagnostics.forEach(diagnostic => {
- // Extract rule ID from code like "eslint(no-unused-vars)" or "eslint-plugin-unicorn(no-new-array)"
- const codeMatch = diagnostic.code?.match(
- /^(?:eslint(?:-plugin-(\w+))?\()([^)]+)\)$/,
- );
- let ruleId = diagnostic.code || 'unknown';
- if (codeMatch) {
- const plugin = codeMatch[1];
- const rule = codeMatch[2];
- ruleId = plugin ? `${plugin}/${rule}` : rule;
- }
- const file = diagnostic.filename || 'unknown';
- const line = diagnostic.labels?.[0]?.span?.line || 0;
- const column = diagnostic.labels?.[0]?.span?.column || 0;
- const message = diagnostic.message || '';
- const ruleData = metricsByRule[ruleId] || { count: 0 };
- ruleData.count += 1;
- metricsByRule[ruleId] = ruleData;
- occurrencesData.push({
- rule: ruleId,
- message,
- file,
- line,
- column,
- ts: DATETIME,
- });
- });
- }
- console.log(
- `OXC found ${results.diagnostics?.length || 0} issues across ${results.number_of_files} files`,
- );
- // Also run minimal ESLint for custom rules and merge results
- console.log('Running minimal ESLint for custom rules...');
- let eslintOutput = '[]';
- try {
- // Run ESLint and capture output directly
- eslintOutput = execSync(
- 'npx eslint --no-eslintrc --config .eslintrc.minimal.js --no-inline-config --format json src',
- {
- encoding: 'utf8',
- maxBuffer: 50 * 1024 * 1024,
- stdio: ['pipe', 'pipe', 'ignore'], // Ignore stderr
- },
- );
- } catch (e) {
- // ESLint exits with non-zero when it finds issues, capture the stdout
- if (e.stdout) {
- eslintOutput = e.stdout.toString();
- }
- }
- // Parse minimal ESLint output
- try {
- const eslintResults = JSON.parse(eslintOutput);
- eslintResults.forEach(result => {
- result.messages.forEach(({ ruleId, line, column, message }) => {
- const ruleData = metricsByRule[ruleId] || { count: 0 };
- ruleData.count += 1;
- metricsByRule[ruleId] = ruleData;
- occurrencesData.push({
- rule: ruleId,
- message,
- file: result.filePath,
- line,
- column,
- ts: DATETIME,
- });
- });
- });
- console.log(
- `ESLint found ${eslintResults.reduce((sum, r) => sum + r.messages.length, 0)} custom rule violations`,
- );
- } catch (e) {
- console.log('No ESLint issues found or parsing error:', e.message);
- }
- // Transform data for Google Sheets
- const metricsData = Object.entries(metricsByRule).map(
- ([rule, { count }]) => [
- 'OXC+ESLint',
- rule,
- enrichedRules[rule]?.description || 'N/A',
- `${count}`,
- DATETIME,
- ],
- );
- occurrencesData = occurrencesData.map(
- ({ rule, message, file, line, column }) => [
- rule,
- enrichedRules[rule]?.description || 'N/A',
- message,
- file,
- `${line}`,
- `${column}`,
- DATETIME,
- ],
- );
- const aggregatedHistoryHeaders = [
- 'Process',
- 'Rule',
- 'Description',
- 'Count',
- 'Timestamp',
- ];
- const eslintBacklogHeaders = [
- 'Rule',
- 'Rule Description',
- 'ESLint Message',
- 'File',
- 'Line',
- 'Column',
- 'Timestamp',
- ];
- console.log(
- `Found ${Object.keys(metricsByRule).length} unique rules with ${occurrencesData.length} total occurrences`,
- );
- await writeToGoogleSheet(
- metricsData,
- 'Aggregated History!A:E',
- aggregatedHistoryHeaders,
- true,
- );
- await writeToGoogleSheet(
- occurrencesData,
- 'ESLint Backlog!A:G',
- eslintBacklogHeaders,
- );
- console.log('Successfully uploaded metrics to Google Sheets');
- } catch (error) {
- console.error('Error processing lint results:', error);
- process.exit(1);
- }
- }
- // Run the process
- runOxlintAndProcess().catch(console.error);
|