sonarqube-issues-exporter
Version:
Enterprise-level SonarQube issues exporter with TypeScript support for generating comprehensive HTML reports with dark theme
213 lines • 9.85 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLogger = exports.initLogger = exports.loadConfig = exports.HtmlExporter = exports.SonarQubeService = void 0;
exports.exportSonarQubeIssues = exportSonarQubeIssues;
exports.validateSonarQubeConnection = validateSonarQubeConnection;
var services_1 = require("./services");
Object.defineProperty(exports, "SonarQubeService", { enumerable: true, get: function () { return services_1.SonarQubeService; } });
var exporters_1 = require("./exporters");
Object.defineProperty(exports, "HtmlExporter", { enumerable: true, get: function () { return exporters_1.HtmlExporter; } });
var config_1 = require("./config");
Object.defineProperty(exports, "loadConfig", { enumerable: true, get: function () { return config_1.loadConfig; } });
var utils_1 = require("./utils");
Object.defineProperty(exports, "initLogger", { enumerable: true, get: function () { return utils_1.initLogger; } });
Object.defineProperty(exports, "getLogger", { enumerable: true, get: function () { return utils_1.getLogger; } });
__exportStar(require("./types"), exports);
// Core export function for programmatic use
async function exportSonarQubeIssues(config, options = {}) {
const { SonarQubeService } = await Promise.resolve().then(() => __importStar(require('./services')));
const { HtmlExporter } = await Promise.resolve().then(() => __importStar(require('./exporters')));
const { initLogger, getLogger } = await Promise.resolve().then(() => __importStar(require('./utils')));
// Initialize logger
initLogger(config.logging);
const logger = getLogger();
try {
// Initialize services
const sonarQubeService = new SonarQubeService(config.sonarqube);
const htmlExporter = new HtmlExporter(config);
// Validate connection if requested (default: true)
if (options.validateConnection !== false) {
logger.info('Validating SonarQube connection...');
const isConnected = await sonarQubeService.validateConnection();
if (!isConnected) {
throw new Error('Failed to connect to SonarQube. Please check your configuration.');
}
}
// Fetch and log project info if requested
if (options.logProjectInfo) {
const projectInfo = await sonarQubeService.getProjectInfo();
if (projectInfo) {
logger.info(`Project found: ${projectInfo.name}`);
}
}
// Fetch issues with optional progress reporting
logger.info('Fetching issues from SonarQube...');
const fetchOptions = {
maxIssues: config.export.maxIssues,
excludeStatuses: config.export.excludeStatuses,
includeResolvedIssues: config.export.includeResolvedIssues,
};
// Only add onProgress if it's defined
if (options.onProgress) {
fetchOptions.onProgress = options.onProgress;
}
const issues = await sonarQubeService.fetchAllIssues(fetchOptions);
if (issues.length === 0) {
logger.warn('No issues found. Check your project key or run a new analysis.');
return {
success: true,
issuesCount: 0,
outputPath: '',
metrics: {
total: 0,
severities: {},
types: {},
statuses: {},
components: {},
rules: {},
},
};
}
// Export to HTML
logger.info('Generating HTML report...');
const result = await htmlExporter.export(issues, {
outputPath: config.export.outputPath,
filename: config.export.filename,
template: config.export.template,
});
return result;
}
catch (error) {
logger.error('Export failed:', error);
throw error;
}
}
// Validation function for checking SonarQube connection and configuration
async function validateSonarQubeConnection(config) {
const { SonarQubeService } = await Promise.resolve().then(() => __importStar(require('./services')));
const { initLogger, getLogger } = await Promise.resolve().then(() => __importStar(require('./utils')));
initLogger(config.logging);
const logger = getLogger();
try {
const sonarQubeService = new SonarQubeService(config.sonarqube);
logger.info('Testing SonarQube connection...');
const isConnected = await sonarQubeService.validateConnection();
if (isConnected) {
logger.info('✅ SonarQube connection successful');
const projectInfo = await sonarQubeService.getProjectInfo();
if (projectInfo) {
logger.info(`✅ Project found: ${projectInfo.name} (${projectInfo.key})`);
}
else {
logger.warn('⚠️ Project not found or no access');
}
return true;
}
else {
logger.error('❌ SonarQube connection failed');
return false;
}
}
catch (error) {
logger.error('❌ Validation failed:', error);
return false;
}
}
// Development mode - run a demo export if executed directly
async function runDevelopmentDemo() {
const { loadConfig } = await Promise.resolve().then(() => __importStar(require('./config')));
const { initLogger, getLogger } = await Promise.resolve().then(() => __importStar(require('./utils')));
console.log('🚀 SonarQube Issues Exporter - Development Mode');
console.log('================================================');
try {
// Load configuration
const config = loadConfig();
// Initialize logger
initLogger(config.logging);
const logger = getLogger();
logger.info('🔧 Development mode started');
logger.info('📋 Configuration loaded successfully');
logger.info(`🔗 SonarQube URL: ${config.sonarqube.url}`);
logger.info(`📦 Project Key: ${config.sonarqube.projectKey}`);
logger.info(`📄 Output: ${config.export.outputPath}/${config.export.filename}`);
// Check if we have minimum required configuration
if (!config.sonarqube.token) {
logger.warn('⚠️ No SonarQube token found. Set SONARQUBE_TOKEN environment variable.');
logger.info('💡 Example: export SONARQUBE_TOKEN=your_token_here');
return;
}
if (!config.sonarqube.projectKey) {
logger.warn('⚠️ No project key found. Set SONARQUBE_PROJECT_KEY environment variable.');
logger.info('💡 Example: export SONARQUBE_PROJECT_KEY=my-project');
return;
}
logger.info('🎯 Starting demo export...');
// Use the library function with progress reporting
const result = await exportSonarQubeIssues(config, {
onProgress: (current, total) => {
const percentage = Math.round((current / total) * 100);
if (percentage % 25 === 0 || percentage === 100) {
logger.info(`📊 Progress: ${current}/${total} issues (${percentage}%)`);
}
},
validateConnection: true,
logProjectInfo: true,
});
if (result.success) {
logger.info('✅ Demo export completed successfully!');
logger.info(`📊 Exported ${result.issuesCount} issues`);
logger.info(`📁 Report saved to: ${result.outputPath}`);
}
else {
logger.error('❌ Demo export failed:', result.error);
}
}
catch (error) {
console.error('❌ Development demo failed:', error);
console.log('\n💡 Tips:');
console.log(' - Make sure your SonarQube server is running');
console.log(' - Check your environment variables (SONARQUBE_URL, SONARQUBE_TOKEN, SONARQUBE_PROJECT_KEY)');
console.log(' - Use "npm run export -- --help" for CLI options');
}
}
// Check if this file is being run directly (not imported)
if (require.main === module) {
runDevelopmentDemo().catch(console.error);
}
//# sourceMappingURL=index.js.map