sonar-autofix 0.1.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,343 +0,0 @@
1
- // sonarclient.js
2
- const axios = require('axios');
3
- const { exec } = require('node:child_process');
4
- const { promisify } = require('node:util');
5
- const execAsync = promisify(exec);
6
-
7
- class SonarClient {
8
- constructor(config) {
9
- this.baseUrl = config.sonar?.host || config.baseUrl || 'http://localhost:9000';
10
- this.token = config.sonar?.token || config.token;
11
- this.axiosInstance = axios.create({
12
- baseURL: this.baseUrl,
13
- headers: {
14
- 'Authorization': `Bearer ${this.token}`,
15
- 'Content-Type': 'application/json'
16
- }
17
- });
18
- }
19
-
20
- // Get project analysis
21
- async getAnalysis(projectKey) {
22
- try {
23
- const response = await this.axiosInstance.get(`/api/qualitygates/project_status?projectKey=${projectKey}`);
24
- return response.data;
25
- } catch (error) {
26
- throw new Error(`Failed to get analysis: ${error.message}`);
27
- }
28
- }
29
-
30
- // Get issues for a project - Updated to use proper endpoint
31
- async getIssues(projectKey, severity) {
32
- if (!projectKey) {
33
- throw new Error('projectKey is required to fetch issues');
34
- }
35
- try {
36
- var params = {
37
- componentKeys: projectKey,
38
- statuses: 'OPEN,CONFIRMED'
39
- };
40
- if (severity) {
41
- params.severities = severity;
42
- }
43
- const response = await this.axiosInstance.get(`/api/issues/search`, {
44
- params: params
45
- });
46
-
47
- const openIssues = response.data.issues.filter(data => data.status === 'OPEN');
48
- console.log(openIssues);
49
- return openIssues;
50
- } catch (error) {
51
- // Provide more detailed error information for debugging
52
- if (error.response) {
53
- throw new Error(`Failed to get issues: ${error.message} - Status: ${error.response.status}, Data: ${JSON.stringify(error.response.data)}`);
54
- } else {
55
- throw new Error(`Failed to get issues: ${error.message}`);
56
- }
57
- }
58
- }
59
-
60
- // Get quality gate status - Updated endpoint
61
- async getQualityGate(projectKey) {
62
- try {
63
- const response = await this.axiosInstance.get(`/api/qualitygates/project_status?projectKey=${projectKey}`);
64
- return response.data;
65
- } catch (error) {
66
- // If the quality gate endpoint fails, try a different one
67
- if (error.response && error.response.status === 404) {
68
- console.log('Quality gate endpoint not available, trying alternative API');
69
- // Try to get project info as fallback
70
- const response = await this.axiosInstance.get(`/api/projects/search?projects=${projectKey}`);
71
- return response.data;
72
- }
73
- throw new Error(`Failed to get quality gate: ${error.message}`);
74
- }
75
- }
76
-
77
- // Get project information (fallback for quality gate)
78
- async getProjectInfo(projectKey) {
79
- try {
80
- const response = await this.axiosInstance.get(`/api/projects/search?projects=${projectKey}`);
81
- return response.data;
82
- } catch (error) {
83
- throw new Error(`Failed to get project info: ${error.message}`);
84
- }
85
- }
86
-
87
- // Get project branches
88
- async getProjectBranches(projectKey) {
89
- try {
90
- const response = await this.axiosInstance.get(`/api/project_branches/list?project=${projectKey}`);
91
- return response.data;
92
- } catch (error) {
93
- throw new Error(`Failed to get project branches: ${error.message}`);
94
- }
95
- }
96
-
97
- // Get project pull requests
98
- async getProjectPullRequests(projectKey) {
99
- try {
100
- const response = await this.axiosInstance.get(`/api/pull_requests/list?project=${projectKey}`);
101
- return response.data;
102
- } catch (error) {
103
- throw new Error(`Failed to get project pull requests: ${error.message}`);
104
- }
105
- }
106
-
107
- // Get project issues by file
108
- async getIssuesByFile(projectKey, fileKey) {
109
- try {
110
- const response = await this.axiosInstance.get(`/api/issues/search?projectKeys=${projectKey}&fileUuids=${fileKey}`);
111
- return response.data;
112
- } catch (error) {
113
- throw new Error(`Failed to get issues by file: ${error.message}`);
114
- }
115
- }
116
-
117
- // Get project issues by component
118
- async getIssuesByComponent(projectKey, componentKey) {
119
- try {
120
- const response = await this.axiosInstance.get(`/api/issues/search?projectKeys=${projectKey}&componentKeys=${componentKey}`);
121
- return response.data;
122
- } catch (error) {
123
- throw new Error(`Failed to get issues by component: ${error.message}`);
124
- }
125
- }
126
-
127
- // Get project status (more reliable endpoint)
128
- async getProjectStatus(projectKey) {
129
- try {
130
- const response = await this.axiosInstance.get(`/api/projects/search?projects=${projectKey}`);
131
- return response.data;
132
- } catch (error) {
133
- throw new Error(`Failed to get project status: ${error.message}`);
134
- }
135
- }
136
-
137
- // Get project metrics
138
- async getProjectMetrics(projectKey, metricKeys) {
139
- try {
140
- const response = await this.axiosInstance.get(`/api/measures/component?component=${projectKey}&metricKeys=${metricKeys.join(',')}`);
141
- return response.data;
142
- } catch (error) {
143
- throw new Error(`Failed to get project metrics: ${error.message}`);
144
- }
145
- }
146
-
147
- // Get project issues by component (with proper error handling)
148
- async getIssuesByComponentKey(projectKey, componentKey) {
149
- try {
150
- const response = await this.axiosInstance.get(`/api/issues/search?projectKeys=${projectKey}&componentKeys=${componentKey}`);
151
- return response.data;
152
- } catch (error) {
153
- // If component key search fails, try with project key only
154
- if (error.response && error.response.status === 400) {
155
- console.log('Component search failed, falling back to project search');
156
- const response = await this.axiosInstance.get(`/api/issues/search?projectKeys=${projectKey}`);
157
- return response.data;
158
- }
159
- throw new Error(`Failed to get issues by component key: ${error.message}`);
160
- }
161
- }
162
-
163
- // Get project issues by file (with proper error handling)
164
- async getIssuesByFileKey(projectKey, fileKey) {
165
- try {
166
- const response = await this.axiosInstance.get(`/api/issues/search?projectKeys=${projectKey}&fileUuids=${fileKey}`);
167
- return response.data;
168
- } catch (error) {
169
- // If file search fails, try with project key only
170
- if (error.response && error.response.status === 400) {
171
- console.log('File search failed, falling back to project search');
172
- const response = await this.axiosInstance.get(`/api/issues/search?projectKeys=${projectKey}`);
173
- return response.data;
174
- }
175
- throw new Error(`Failed to get issues by file key: ${error.message}`);
176
- }
177
- }
178
-
179
- // Enhanced project information with MCP integration capability
180
- async getEnhancedProjectInfo(projectKey) {
181
- try {
182
- // First, try to get project info
183
- const projectInfo = await this.getProjectInfo(projectKey);
184
-
185
- // Then try to get metrics if available
186
- let metrics = null;
187
- try {
188
- metrics = await this.getProjectMetrics(projectKey, ['ncloc', 'bugs', 'vulnerabilities']);
189
- } catch (metricsError) {
190
- console.log('Metrics not available:', metricsError.message);
191
- }
192
-
193
- // Then try to get branches if available
194
- let branches = null;
195
- try {
196
- branches = await this.getProjectBranches(projectKey);
197
- } catch (branchesError) {
198
- console.log('Branches not available:', branchesError.message);
199
- }
200
-
201
- // Then try to get pull requests if available
202
- let pullRequests = null;
203
- try {
204
- pullRequests = await this.getProjectPullRequests(projectKey);
205
- } catch (prError) {
206
- console.log('Pull requests not available:', prError.message);
207
- }
208
-
209
- return {
210
- projectInfo,
211
- metrics,
212
- branches,
213
- pullRequests
214
- };
215
- } catch (error) {
216
- throw new Error(`Failed to get enhanced project info: ${error.message}`);
217
- }
218
- }
219
-
220
- // MCP Server integration methods
221
- // async getMCPProjectInfo(projectKey) {
222
- // try {
223
- // // This method is specifically designed to work with the SonarQube MCP server
224
- // const projectInfo = await this.getProjectInfo(projectKey);
225
- //
226
- // // Try to use the MCP server's enhanced capabilities
227
- // try {
228
- // const mcpInfo = await this.getEnhancedProjectInfo(projectKey);
229
- // return {
230
- // ...mcpInfo,
231
- // source: 'sonarqube_mcp'
232
- // };
233
- // } catch (mcpError) {
234
- // console.log('MCP integration not available, returning basic project info');
235
- // return {
236
- // projectInfo,
237
- // source: 'sonarqube_basic'
238
- // };
239
- // }
240
- // } catch (error) {
241
- // throw new Error(`Failed to get MCP project info: ${error.message}`);
242
- // }
243
- // }
244
-
245
- // Method to check if MCP server is available and working
246
- // async testMCPConnection() {
247
- // try {
248
- // // Test basic project search to verify connection
249
- // const response = await this.axiosInstance.get(`/api/projects/search?projects=test`);
250
- // return {
251
- // connected: true,
252
- // status: 'MCP server is accessible',
253
- // response: response.data
254
- // };
255
- // } catch (error) {
256
- // return {
257
- // connected: false,
258
- // status: `MCP server connection failed: ${error.message}`,
259
- // error: error.message
260
- // };
261
- // }
262
- // }
263
-
264
- // Method to list projects using MCP server if available
265
- async listProjects(query = '') {
266
- try {
267
- // First attempt to use MCP server's search function if available
268
- const response = await this.axiosInstance.get(`/api/projects/search?q=${query}`);
269
- return response.data;
270
- } catch (error) {
271
- // Fallback to basic project search
272
- console.log('MCP search not available, using fallback');
273
- const response = await this.axiosInstance.get(`/api/projects/search?projects=${query}`);
274
- return response.data;
275
- }
276
- }
277
-
278
- // Run sonar-scanner analysis
279
- async runAnalysis(projectKey) {
280
- try {
281
- const { stdout } = await execAsync(
282
- `npx sonar-scanner -Dsonar.projectKey=${projectKey} -Dsonar.host.url=${this.baseUrl} -Dsonar.token=${this.token}`
283
- );
284
- return { success: true, output: stdout };
285
- } catch (error) {
286
- return { success: false, output: error.message };
287
- }
288
- }
289
-
290
- // Wait for quality gate result by polling task status
291
- async waitForQualityGate(projectKey, taskId, maxWaitMs = 120000) {
292
- const pollInterval = 5000;
293
- const startTime = Date.now();
294
-
295
- while (Date.now() - startTime < maxWaitMs) {
296
- const response = await this.axiosInstance.get(`/api/ce/task?id=${taskId}`);
297
- const status = response.data.task.status;
298
-
299
- if (['SUCCESS', 'FAILED', 'CANCELED'].includes(status)) {
300
- return this.getQualityGate(projectKey);
301
- }
302
-
303
- await new Promise(resolve => setTimeout(resolve, pollInterval));
304
- }
305
-
306
- throw new Error(`Quality gate timeout after ${maxWaitMs}ms`);
307
- }
308
-
309
- // Get security hotspots for a project
310
- async getHotspots(projectKey) {
311
- try {
312
- const response = await this.axiosInstance.get(`/api/hotspots/search?projectKey=${projectKey}`);
313
- return response.data;
314
- } catch (error) {
315
- throw new Error(`Failed to get hotspots: ${error.message}`);
316
- }
317
- }
318
-
319
- // Get raw source code for a component
320
- async getSourceCode(componentKey) {
321
- try {
322
- const response = await this.axiosInstance.get(`/api/sources/raw?key=${componentKey}`);
323
- return response.data;
324
- } catch (error) {
325
- throw new Error(`Failed to get source code: ${error.message}`);
326
- }
327
- }
328
- }
329
-
330
- if (require.main === module) {
331
- const config = {
332
- sonar: {
333
- host: 'http://localhost:9000',
334
- project: 'fundrest_core',
335
- token: 'squ_bfe66608c517d650380dd5d4f4e6c7e2d929ef71',
336
- },
337
- };
338
-
339
- new SonarClient(config).getIssues(config.sonar.project);
340
- }
341
-
342
-
343
- module.exports = SonarClient;
@@ -1,20 +0,0 @@
1
- {
2
- "name": "@sonar-autofix/sonar-client",
3
- "version": "0.0.3",
4
- "description": "Sonar client for the Sonar Autofix tool",
5
- "main": "index.js",
6
- "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
8
- },
9
- "keywords": [
10
- "sonar",
11
- "autofix",
12
- "github",
13
- "client"
14
- ],
15
- "author": "Sonar Autofix Team",
16
- "license": "MIT",
17
- "dependencies": {
18
- "axios": "^1.19.0"
19
- }
20
- }
@@ -1,170 +0,0 @@
1
- 'use strict';
2
-
3
- const { exec } = require('child_process');
4
- const { promisify } = require('util');
5
- const path = require('path');
6
-
7
- const execAsync = promisify(exec);
8
-
9
- const DEFAULT_TIMEOUT = 5 * 60 * 1000; // 5 minutes
10
-
11
- class Validator {
12
- /**
13
- * @param {object} config
14
- * @param {object} config.validation
15
- * @param {string[]} config.validation.build - Build commands to run
16
- * @param {string[]} config.validation.lint - Lint commands to run
17
- * @param {string[]} config.validation.tests - Test commands to run
18
- * @param {string} [cwd] - Working directory for commands
19
- */
20
- constructor(config = {}, cwd = process.cwd()) {
21
- const validation = config.validation || {};
22
- this.commands = {
23
- build: validation.build || ['npm run build'],
24
- lint: validation.lint || ['npm run lint'],
25
- tests: validation.tests || ['npm test'],
26
- };
27
- this.cwd = cwd;
28
- this.timeout = config.timeout || DEFAULT_TIMEOUT;
29
- }
30
-
31
- /**
32
- * Run a single shell command.
33
- * @param {string} command
34
- * @returns {Promise<{success: boolean, stdout: string, stderr: string, exitCode: number}>}
35
- */
36
- async runCommand(command) {
37
- console.log(`[Validator] Running: ${command} (cwd: ${this.cwd})`);
38
- try {
39
- const { stdout, stderr } = await execAsync(command, {
40
- cwd: this.cwd,
41
- timeout: this.timeout,
42
- maxBuffer: 10 * 1024 * 1024, // 10 MB
43
- });
44
- return { success: true, stdout: stdout || '', stderr: stderr || '', exitCode: 0 };
45
- } catch (err) {
46
- return {
47
- success: false,
48
- stdout: err.stdout || '',
49
- stderr: err.stderr || err.message || '',
50
- exitCode: err.code != null ? err.code : 1,
51
- };
52
- }
53
- }
54
-
55
- /**
56
- * Run a list of commands sequentially.
57
- * @param {string[]} commands
58
- * @returns {Promise<{success: boolean, output: string, errors: string[]}>}
59
- */
60
- async _runCommands(commands) {
61
- const outputs = [];
62
- const errors = [];
63
- let success = true;
64
-
65
- for (const cmd of commands) {
66
- const result = await this.runCommand(cmd);
67
- if (result.stdout) outputs.push(result.stdout);
68
- if (!result.success) {
69
- success = false;
70
- errors.push(result.stderr || `Command failed: ${cmd}`);
71
- }
72
- }
73
-
74
- return { success, output: outputs.join('\n'), errors };
75
- }
76
-
77
- /**
78
- * Run per-file validation using the project's configured build commands.
79
- * Instead of running individual tool checks on a single file (which ignores
80
- * tsconfig.json, path aliases, etc.), we run the project's own build/lint
81
- * commands so validation matches the real project setup.
82
- * @param {string} filePath
83
- * @returns {Promise<{success: boolean, errors: string[]}>}
84
- */
85
- async validateFile(filePath) {
86
- console.log(`[Validator] Validating after changes to: ${filePath}`);
87
- const errors = [];
88
- let success = true;
89
-
90
- // Run build commands — these respect tsconfig.json, path aliases, etc.
91
- for (const cmd of this.commands.build) {
92
- const result = await this.runCommand(cmd);
93
- if (!result.success) {
94
- success = false;
95
- errors.push(result.stderr || result.stdout || `Build failed: ${cmd}`);
96
- }
97
- }
98
-
99
- // Run lint commands
100
- for (const cmd of this.commands.lint) {
101
- const result = await this.runCommand(cmd);
102
- if (!result.success) {
103
- success = false;
104
- errors.push(result.stderr || result.stdout || `Lint failed: ${cmd}`);
105
- }
106
- }
107
-
108
- return { success, errors };
109
- }
110
-
111
- /**
112
- * Run all configured build commands sequentially.
113
- * @returns {Promise<{success: boolean, output: string, errors: string[]}>}
114
- */
115
- async runBuild() {
116
- console.log('[Validator] Running build commands...');
117
- return this._runCommands(this.commands.build);
118
- }
119
-
120
- /**
121
- * Run all configured lint commands.
122
- * @returns {Promise<{success: boolean, output: string, errors: string[]}>}
123
- */
124
- async runLint() {
125
- console.log('[Validator] Running lint commands...');
126
- return this._runCommands(this.commands.lint);
127
- }
128
-
129
- /**
130
- * Run all configured test commands.
131
- * @returns {Promise<{success: boolean, output: string, errors: string[]}>}
132
- */
133
- async runTests() {
134
- console.log('[Validator] Running test commands...');
135
- return this._runCommands(this.commands.tests);
136
- }
137
-
138
- /**
139
- * Run build, lint, and tests in sequence.
140
- * @returns {Promise<{success: boolean, results: {build: object, lint: object, tests: object}}>}
141
- */
142
- async validateAll() {
143
- console.log('[Validator] Running full validation...');
144
- const build = await this.runBuild();
145
- const lint = await this.runLint();
146
- const tests = await this.runTests();
147
-
148
- return {
149
- success: build.success && lint.success && tests.success,
150
- results: { build, lint, tests },
151
- };
152
- }
153
-
154
- /**
155
- * Run per-batch validations (build + tests).
156
- * @returns {Promise<{success: boolean, results: {build: object, tests: object}}>}
157
- */
158
- async validateBatch() {
159
- console.log('[Validator] Running batch validation (build + tests)...');
160
- const build = await this.runBuild();
161
- const tests = await this.runTests();
162
-
163
- return {
164
- success: build.success && tests.success,
165
- results: { build, tests },
166
- };
167
- }
168
- }
169
-
170
- module.exports = Validator;
@@ -1,17 +0,0 @@
1
- {
2
- "name": "@sonar-autofix/validator",
3
- "version": "0.0.1",
4
- "description": "Validator for the Sonar Autofix tool",
5
- "main": "index.js",
6
- "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
8
- },
9
- "keywords": [
10
- "sonar",
11
- "autofix",
12
- "github",
13
- "validator"
14
- ],
15
- "author": "Sonar Autofix Team",
16
- "license": "MIT"
17
- }