sonar-autofix 0.1.0 → 0.3.0

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,329 +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
- return openIssues;
49
- } catch (error) {
50
- // Provide more detailed error information for debugging
51
- if (error.response) {
52
- throw new Error(`Failed to get issues: ${error.message} - Status: ${error.response.status}, Data: ${JSON.stringify(error.response.data)}`);
53
- } else {
54
- throw new Error(`Failed to get issues: ${error.message}`);
55
- }
56
- }
57
- }
58
-
59
- // Get quality gate status - Updated endpoint
60
- async getQualityGate(projectKey) {
61
- try {
62
- const response = await this.axiosInstance.get(`/api/qualitygates/project_status?projectKey=${projectKey}`);
63
- return response.data;
64
- } catch (error) {
65
- // If the quality gate endpoint fails, try a different one
66
- if (error.response && error.response.status === 404) {
67
- console.log('Quality gate endpoint not available, trying alternative API');
68
- // Try to get project info as fallback
69
- const response = await this.axiosInstance.get(`/api/projects/search?projects=${projectKey}`);
70
- return response.data;
71
- }
72
- throw new Error(`Failed to get quality gate: ${error.message}`);
73
- }
74
- }
75
-
76
- // Get project information (fallback for quality gate)
77
- async getProjectInfo(projectKey) {
78
- try {
79
- const response = await this.axiosInstance.get(`/api/projects/search?projects=${projectKey}`);
80
- return response.data;
81
- } catch (error) {
82
- throw new Error(`Failed to get project info: ${error.message}`);
83
- }
84
- }
85
-
86
- // Get project branches
87
- async getProjectBranches(projectKey) {
88
- try {
89
- const response = await this.axiosInstance.get(`/api/project_branches/list?project=${projectKey}`);
90
- return response.data;
91
- } catch (error) {
92
- throw new Error(`Failed to get project branches: ${error.message}`);
93
- }
94
- }
95
-
96
- // Get project pull requests
97
- async getProjectPullRequests(projectKey) {
98
- try {
99
- const response = await this.axiosInstance.get(`/api/pull_requests/list?project=${projectKey}`);
100
- return response.data;
101
- } catch (error) {
102
- throw new Error(`Failed to get project pull requests: ${error.message}`);
103
- }
104
- }
105
-
106
- // Get project issues by file
107
- async getIssuesByFile(projectKey, fileKey) {
108
- try {
109
- const response = await this.axiosInstance.get(`/api/issues/search?projectKeys=${projectKey}&fileUuids=${fileKey}`);
110
- return response.data;
111
- } catch (error) {
112
- throw new Error(`Failed to get issues by file: ${error.message}`);
113
- }
114
- }
115
-
116
- // Get project issues by component
117
- async getIssuesByComponent(projectKey, componentKey) {
118
- try {
119
- const response = await this.axiosInstance.get(`/api/issues/search?projectKeys=${projectKey}&componentKeys=${componentKey}`);
120
- return response.data;
121
- } catch (error) {
122
- throw new Error(`Failed to get issues by component: ${error.message}`);
123
- }
124
- }
125
-
126
- // Get project status (more reliable endpoint)
127
- async getProjectStatus(projectKey) {
128
- try {
129
- const response = await this.axiosInstance.get(`/api/projects/search?projects=${projectKey}`);
130
- return response.data;
131
- } catch (error) {
132
- throw new Error(`Failed to get project status: ${error.message}`);
133
- }
134
- }
135
-
136
- // Get project metrics
137
- async getProjectMetrics(projectKey, metricKeys) {
138
- try {
139
- const response = await this.axiosInstance.get(`/api/measures/component?component=${projectKey}&metricKeys=${metricKeys.join(',')}`);
140
- return response.data;
141
- } catch (error) {
142
- throw new Error(`Failed to get project metrics: ${error.message}`);
143
- }
144
- }
145
-
146
- // Get project issues by component (with proper error handling)
147
- async getIssuesByComponentKey(projectKey, componentKey) {
148
- try {
149
- const response = await this.axiosInstance.get(`/api/issues/search?projectKeys=${projectKey}&componentKeys=${componentKey}`);
150
- return response.data;
151
- } catch (error) {
152
- // If component key search fails, try with project key only
153
- if (error.response && error.response.status === 400) {
154
- console.log('Component search failed, falling back to project search');
155
- const response = await this.axiosInstance.get(`/api/issues/search?projectKeys=${projectKey}`);
156
- return response.data;
157
- }
158
- throw new Error(`Failed to get issues by component key: ${error.message}`);
159
- }
160
- }
161
-
162
- // Get project issues by file (with proper error handling)
163
- async getIssuesByFileKey(projectKey, fileKey) {
164
- try {
165
- const response = await this.axiosInstance.get(`/api/issues/search?projectKeys=${projectKey}&fileUuids=${fileKey}`);
166
- return response.data;
167
- } catch (error) {
168
- // If file search fails, try with project key only
169
- if (error.response && error.response.status === 400) {
170
- console.log('File search failed, falling back to project search');
171
- const response = await this.axiosInstance.get(`/api/issues/search?projectKeys=${projectKey}`);
172
- return response.data;
173
- }
174
- throw new Error(`Failed to get issues by file key: ${error.message}`);
175
- }
176
- }
177
-
178
- // Enhanced project information with MCP integration capability
179
- async getEnhancedProjectInfo(projectKey) {
180
- try {
181
- // First, try to get project info
182
- const projectInfo = await this.getProjectInfo(projectKey);
183
-
184
- // Then try to get metrics if available
185
- let metrics = null;
186
- try {
187
- metrics = await this.getProjectMetrics(projectKey, ['ncloc', 'bugs', 'vulnerabilities']);
188
- } catch (metricsError) {
189
- console.log('Metrics not available:', metricsError.message);
190
- }
191
-
192
- // Then try to get branches if available
193
- let branches = null;
194
- try {
195
- branches = await this.getProjectBranches(projectKey);
196
- } catch (branchesError) {
197
- console.log('Branches not available:', branchesError.message);
198
- }
199
-
200
- // Then try to get pull requests if available
201
- let pullRequests = null;
202
- try {
203
- pullRequests = await this.getProjectPullRequests(projectKey);
204
- } catch (prError) {
205
- console.log('Pull requests not available:', prError.message);
206
- }
207
-
208
- return {
209
- projectInfo,
210
- metrics,
211
- branches,
212
- pullRequests
213
- };
214
- } catch (error) {
215
- throw new Error(`Failed to get enhanced project info: ${error.message}`);
216
- }
217
- }
218
-
219
- // MCP Server integration methods
220
- // async getMCPProjectInfo(projectKey) {
221
- // try {
222
- // // This method is specifically designed to work with the SonarQube MCP server
223
- // const projectInfo = await this.getProjectInfo(projectKey);
224
- //
225
- // // Try to use the MCP server's enhanced capabilities
226
- // try {
227
- // const mcpInfo = await this.getEnhancedProjectInfo(projectKey);
228
- // return {
229
- // ...mcpInfo,
230
- // source: 'sonarqube_mcp'
231
- // };
232
- // } catch (mcpError) {
233
- // console.log('MCP integration not available, returning basic project info');
234
- // return {
235
- // projectInfo,
236
- // source: 'sonarqube_basic'
237
- // };
238
- // }
239
- // } catch (error) {
240
- // throw new Error(`Failed to get MCP project info: ${error.message}`);
241
- // }
242
- // }
243
-
244
- // Method to check if MCP server is available and working
245
- // async testMCPConnection() {
246
- // try {
247
- // // Test basic project search to verify connection
248
- // const response = await this.axiosInstance.get(`/api/projects/search?projects=test`);
249
- // return {
250
- // connected: true,
251
- // status: 'MCP server is accessible',
252
- // response: response.data
253
- // };
254
- // } catch (error) {
255
- // return {
256
- // connected: false,
257
- // status: `MCP server connection failed: ${error.message}`,
258
- // error: error.message
259
- // };
260
- // }
261
- // }
262
-
263
- // Method to list projects using MCP server if available
264
- async listProjects(query = '') {
265
- try {
266
- // First attempt to use MCP server's search function if available
267
- const response = await this.axiosInstance.get(`/api/projects/search?q=${query}`);
268
- return response.data;
269
- } catch (error) {
270
- // Fallback to basic project search
271
- console.log('MCP search not available, using fallback');
272
- const response = await this.axiosInstance.get(`/api/projects/search?projects=${query}`);
273
- return response.data;
274
- }
275
- }
276
-
277
- // Run sonar-scanner analysis
278
- async runAnalysis(projectKey) {
279
- try {
280
- const { stdout } = await execAsync(
281
- `npx sonar-scanner -Dsonar.projectKey=${projectKey} -Dsonar.host.url=${this.baseUrl} -Dsonar.token=${this.token}`
282
- );
283
- return { success: true, output: stdout };
284
- } catch (error) {
285
- return { success: false, output: error.message };
286
- }
287
- }
288
-
289
- // Wait for quality gate result by polling task status
290
- async waitForQualityGate(projectKey, taskId, maxWaitMs = 120000) {
291
- const pollInterval = 5000;
292
- const startTime = Date.now();
293
-
294
- while (Date.now() - startTime < maxWaitMs) {
295
- const response = await this.axiosInstance.get(`/api/ce/task?id=${taskId}`);
296
- const status = response.data.task.status;
297
-
298
- if (['SUCCESS', 'FAILED', 'CANCELED'].includes(status)) {
299
- return this.getQualityGate(projectKey);
300
- }
301
-
302
- await new Promise(resolve => setTimeout(resolve, pollInterval));
303
- }
304
-
305
- throw new Error(`Quality gate timeout after ${maxWaitMs}ms`);
306
- }
307
-
308
- // Get security hotspots for a project
309
- async getHotspots(projectKey) {
310
- try {
311
- const response = await this.axiosInstance.get(`/api/hotspots/search?projectKey=${projectKey}`);
312
- return response.data;
313
- } catch (error) {
314
- throw new Error(`Failed to get hotspots: ${error.message}`);
315
- }
316
- }
317
-
318
- // Get raw source code for a component
319
- async getSourceCode(componentKey) {
320
- try {
321
- const response = await this.axiosInstance.get(`/api/sources/raw?key=${componentKey}`);
322
- return response.data;
323
- } catch (error) {
324
- throw new Error(`Failed to get source code: ${error.message}`);
325
- }
326
- }
327
- }
328
-
329
- 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
- }