@sun-asterisk/sunlint 1.3.21 → 1.3.22

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.
@@ -196,13 +196,24 @@ class AnalysisOrchestrator {
196
196
 
197
197
  // Group rules by their preferred engines
198
198
  const engineGroups = this.groupRulesByEngine(optimizedRules, config);
199
-
199
+
200
+ // Calculate total batches for progress tracking
201
+ let totalBatches = 0;
202
+ const engineBatchInfo = new Map();
203
+ for (const [engineName, rules] of engineGroups) {
204
+ const ruleBatches = this.performanceOptimizer.createRuleBatches(rules, config);
205
+ engineBatchInfo.set(engineName, ruleBatches);
206
+ totalBatches += ruleBatches.length;
207
+ }
208
+
200
209
  if (!options.quiet) {
201
- console.log(chalk.cyan(`🚀 Running analysis across ${engineGroups.size} engines...`));
210
+ console.log(chalk.cyan(`🚀 Running analysis across ${engineGroups.size} engines (${totalBatches} batches total)...`));
202
211
  }
203
212
 
204
213
  // Run analysis on each engine with batching
205
214
  const results = [];
215
+ let completedBatches = 0;
216
+
206
217
  for (const [engineName, rules] of engineGroups) {
207
218
  const engine = this.engines.get(engineName);
208
219
  if (!engine) {
@@ -210,38 +221,44 @@ class AnalysisOrchestrator {
210
221
  continue;
211
222
  }
212
223
 
213
- // Process rules in batches for performance
214
- const ruleBatches = this.performanceOptimizer.createRuleBatches(rules, config);
215
-
224
+ // Get pre-calculated batches
225
+ const ruleBatches = engineBatchInfo.get(engineName);
226
+
216
227
  for (let i = 0; i < ruleBatches.length; i++) {
217
228
  const batch = ruleBatches[i];
218
229
  const batchNumber = i + 1;
219
-
220
- if (!options.quiet && ruleBatches.length > 1) {
221
- console.log(chalk.blue(`⚙️ ${engineName} - Batch ${batchNumber}/${ruleBatches.length}: ${batch.length} rules`));
222
- } else if (!options.quiet) {
223
- console.log(chalk.blue(`⚙️ Running ${batch.length} rules on ${engineName} engine...`));
230
+ const overallProgress = Math.round((completedBatches / totalBatches) * 100);
231
+
232
+ if (!options.quiet) {
233
+ if (ruleBatches.length > 1) {
234
+ console.log(chalk.blue(`⚙️ [${overallProgress}%] ${engineName} - Batch ${batchNumber}/${ruleBatches.length}: ${batch.length} rules (${optimizedFiles.length} files)`));
235
+ } else {
236
+ console.log(chalk.blue(`⚙️ [${overallProgress}%] Running ${batch.length} rules on ${engineName} engine (${optimizedFiles.length} files)...`));
237
+ }
224
238
  }
225
239
 
226
240
  try {
227
241
  const engineResult = await this.runEngineWithOptimizations(
228
- engine,
229
- optimizedFiles,
230
- batch,
242
+ engine,
243
+ optimizedFiles,
244
+ batch,
231
245
  options,
232
- { batchNumber, totalBatches: ruleBatches.length }
246
+ { batchNumber, totalBatches: ruleBatches.length, overallProgress }
233
247
  );
234
-
248
+
235
249
  results.push({
236
250
  engine: engineName,
237
251
  batch: batchNumber,
238
252
  rules: batch.map(r => r.id),
239
253
  ...engineResult
240
254
  });
241
-
255
+
256
+ completedBatches++;
257
+ const newProgress = Math.round((completedBatches / totalBatches) * 100);
258
+
242
259
  if (!options.quiet) {
243
260
  const violationCount = this.countViolations(engineResult);
244
- console.log(chalk.blue(`✅ ${engineName} batch ${batchNumber}: ${violationCount} violations found`));
261
+ console.log(chalk.green(`✅ [${newProgress}%] ${engineName} batch ${batchNumber}/${ruleBatches.length}: ${violationCount} violations found`));
245
262
  }
246
263
  } catch (error) {
247
264
  // Enhanced error recovery with batch context
package/core/git-utils.js CHANGED
@@ -121,6 +121,14 @@ class GitUtils {
121
121
  // Get git root directory
122
122
  const gitRoot = execSync('git rev-parse --show-toplevel', { cwd, encoding: 'utf8' }).trim();
123
123
 
124
+ // Check if we're in PR context
125
+ const prContext = this.detectPRContext();
126
+
127
+ // If in PR context and no explicit baseRef, use PR-specific logic
128
+ if (prContext && !baseRef) {
129
+ return this.getPRChangedFiles(prContext, gitRoot);
130
+ }
131
+
124
132
  // Auto-detect base ref if not provided
125
133
  const actualBaseRef = baseRef || this.getSmartBaseRef(cwd);
126
134
 
@@ -159,6 +167,112 @@ class GitUtils {
159
167
  }
160
168
  }
161
169
 
170
+ /**
171
+ * Get changed files in PR context using merge-base
172
+ * @param {Object} prContext - PR context info from detectPRContext()
173
+ * @param {string} gitRoot - Git repository root path
174
+ * @returns {string[]} Array of changed file paths in the PR
175
+ */
176
+ static getPRChangedFiles(prContext, gitRoot) {
177
+ try {
178
+ const { baseBranch } = prContext;
179
+
180
+ // Try to find the base branch reference
181
+ const baseRef = this.findBaseRef(baseBranch, gitRoot);
182
+
183
+ if (!baseRef) {
184
+ throw new Error(`Cannot find base branch: ${baseBranch}`);
185
+ }
186
+
187
+ // Ensure we have the latest base branch
188
+ this.ensureBaseRefExists(baseRef, gitRoot);
189
+
190
+ // Use merge-base to find the common ancestor
191
+ let mergeBase;
192
+ try {
193
+ mergeBase = execSync(`git merge-base ${baseRef} HEAD`, {
194
+ cwd: gitRoot,
195
+ encoding: 'utf8'
196
+ }).trim();
197
+ } catch (error) {
198
+ // If merge-base fails, fall back to direct comparison
199
+ console.warn(`Warning: Could not find merge-base, using direct diff with ${baseRef}`);
200
+ mergeBase = baseRef;
201
+ }
202
+
203
+ // Get all files changed from merge-base to HEAD
204
+ const command = `git diff --name-only ${mergeBase}...HEAD`;
205
+ const output = execSync(command, { cwd: gitRoot, encoding: 'utf8' });
206
+
207
+ const changedFiles = output
208
+ .split('\n')
209
+ .filter(file => file.trim() !== '')
210
+ .map(file => path.resolve(gitRoot, file))
211
+ .filter(file => fs.existsSync(file));
212
+
213
+ return changedFiles;
214
+ } catch (error) {
215
+ throw new Error(`Failed to get PR changed files: ${error.message}`);
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Find base reference for the given branch name
221
+ * @param {string} baseBranch - Base branch name
222
+ * @param {string} gitRoot - Git repository root path
223
+ * @returns {string|null} Base reference or null if not found
224
+ */
225
+ static findBaseRef(baseBranch, gitRoot) {
226
+ const candidates = [
227
+ `origin/${baseBranch}`,
228
+ `upstream/${baseBranch}`,
229
+ baseBranch
230
+ ];
231
+
232
+ for (const candidate of candidates) {
233
+ try {
234
+ execSync(`git rev-parse --verify ${candidate}`, {
235
+ cwd: gitRoot,
236
+ stdio: 'ignore'
237
+ });
238
+ return candidate;
239
+ } catch (error) {
240
+ // Continue to next candidate
241
+ }
242
+ }
243
+
244
+ return null;
245
+ }
246
+
247
+ /**
248
+ * Ensure base ref exists (fetch if necessary)
249
+ * @param {string} baseRef - Base reference
250
+ * @param {string} gitRoot - Git repository root path
251
+ */
252
+ static ensureBaseRefExists(baseRef, gitRoot) {
253
+ try {
254
+ // Check if ref exists
255
+ execSync(`git rev-parse --verify ${baseRef}`, {
256
+ cwd: gitRoot,
257
+ stdio: 'ignore'
258
+ });
259
+ } catch (error) {
260
+ // Try to fetch if it doesn't exist
261
+ const remote = baseRef.split('/')[0];
262
+ if (remote === 'origin' || remote === 'upstream') {
263
+ try {
264
+ console.log(`Fetching ${remote}...`);
265
+ execSync(`git fetch ${remote} --depth=1`, {
266
+ cwd: gitRoot,
267
+ stdio: 'inherit'
268
+ });
269
+ } catch (fetchError) {
270
+ console.warn(`Warning: Failed to fetch ${remote}: ${fetchError.message}`);
271
+ }
272
+ }
273
+ }
274
+ }
275
+
162
276
  /**
163
277
  * Get list of staged files
164
278
  * @param {string} cwd - Working directory
@@ -44,7 +44,8 @@ class OutputService {
44
44
  const report = this.generateReport(results, metadata, { ...options, format: effectiveFormat });
45
45
 
46
46
  // Console output
47
- if (!options.quiet) {
47
+ // Skip console output when using --github-annotate to avoid JSON clutter
48
+ if (!options.quiet && !githubAnnotateConfig.shouldAnnotate) {
48
49
  console.log(report.formatted);
49
50
  }
50
51
 
@@ -90,15 +90,28 @@ jobs:
90
90
 
91
91
  ## Advanced Usage
92
92
 
93
- ### 1. Analyze only changed files
93
+ ### 1. Analyze only changed files (Auto-detect PR)
94
+
95
+ **⭐ Tính năng mới**: Tự động phát hiện PR context và sử dụng merge-base để diff chính xác!
94
96
 
95
97
  ```yaml
96
- - name: Run SunLint on Changed Files
98
+ - name: Run SunLint on Changed Files (Auto-detect)
97
99
  run: sunlint --all --changed-files --github-annotate
98
100
  env:
99
101
  GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
100
102
  ```
101
103
 
104
+ **Cách hoạt động**:
105
+ - ✅ Tự động detect GitHub Actions PR event (`GITHUB_EVENT_NAME=pull_request`)
106
+ - ✅ Tự động lấy base branch từ `GITHUB_BASE_REF`
107
+ - ✅ Sử dụng `git merge-base` để tìm common ancestor
108
+ - ✅ So sánh với merge-base thay vì HEAD → Lấy đúng các file thay đổi trong PR
109
+ - ✅ Tự động fetch base branch nếu cần
110
+
111
+ **Không cần chỉ định `--diff-base` nữa!** SunLint sẽ tự động xử lý.
112
+
113
+ **Fallback**: Nếu không phát hiện được PR context, sẽ fallback về logic cũ (so sánh với HEAD hoặc origin/main)
114
+
102
115
  ### 2. Save report file + annotate
103
116
 
104
117
  ```yaml
@@ -819,7 +819,14 @@ class HeuristicEngine extends AnalysisEngineInterface {
819
819
  // Group files by language for efficient processing
820
820
  const filesByLanguage = this.groupFilesByLanguage(files);
821
821
 
822
+ // Track progress across rules
823
+ const totalRules = rules.length;
824
+ let processedRules = 0;
825
+
822
826
  for (const rule of rules) {
827
+ processedRules++;
828
+ const ruleProgress = Math.floor((processedRules / totalRules) * 100);
829
+
823
830
  // Special case: Load C047 semantic rule on-demand
824
831
  if (rule.id === 'C047' && !this.semanticRules.has('C047')) {
825
832
  if (options.verbose) {
@@ -827,7 +834,7 @@ class HeuristicEngine extends AnalysisEngineInterface {
827
834
  }
828
835
  await this.manuallyLoadC047();
829
836
  }
830
-
837
+
831
838
  // Lazy load rule if not already loaded
832
839
  if (!this.isRuleSupported(rule.id)) {
833
840
  if (options.verbose) {
@@ -835,7 +842,7 @@ class HeuristicEngine extends AnalysisEngineInterface {
835
842
  }
836
843
  await this.lazyLoadRule(rule.id, options);
837
844
  }
838
-
845
+
839
846
  if (!this.isRuleSupported(rule.id)) {
840
847
  if (options.verbose) {
841
848
  console.warn(`⚠️ Rule ${rule.id} not supported by Heuristic engine, skipping...`);
@@ -845,25 +852,29 @@ class HeuristicEngine extends AnalysisEngineInterface {
845
852
 
846
853
  try {
847
854
  let ruleViolations = [];
848
-
855
+
849
856
  // Check if this is a semantic rule first (higher priority)
850
857
  if (this.semanticRules.has(rule.id)) {
851
- if (options.verbose) {
852
- console.log(`🧠 [HeuristicEngine] Running semantic analysis for rule ${rule.id}`);
853
- }
858
+ const progressInfo = options.batchInfo?.overallProgress !== undefined
859
+ ? `[${options.batchInfo.overallProgress}% overall] `
860
+ : '';
861
+ console.log(`🧠 ${progressInfo}Rule ${processedRules}/${totalRules} (${ruleProgress}%): ${rule.id} - Analyzing ${files.length} files...`);
862
+
854
863
  ruleViolations = await this.analyzeSemanticRule(rule, files, options);
855
864
  } else {
856
865
  // Fallback to traditional analysis
857
- if (options.verbose) {
858
- console.log(`🔧 [HeuristicEngine] Running traditional analysis for rule ${rule.id}`);
859
- }
866
+ const progressInfo = options.batchInfo?.overallProgress !== undefined
867
+ ? `[${options.batchInfo.overallProgress}% overall] `
868
+ : '';
869
+ console.log(`🔧 ${progressInfo}Rule ${processedRules}/${totalRules} (${ruleProgress}%): ${rule.id} - Analyzing ${files.length} files...`);
870
+
860
871
  ruleViolations = await this.analyzeRule(rule, filesByLanguage, options);
861
872
  }
862
873
 
863
874
  if (ruleViolations.length > 0) {
864
875
  // Group violations by file
865
876
  const violationsByFile = this.groupViolationsByFile(ruleViolations);
866
-
877
+
867
878
  for (const [filePath, violations] of violationsByFile) {
868
879
  // Find or create file result
869
880
  let fileResult = results.results.find(r => r.file === filePath);
@@ -875,8 +886,14 @@ class HeuristicEngine extends AnalysisEngineInterface {
875
886
  }
876
887
  }
877
888
 
889
+ // Log completion
890
+ const progressInfo = options.batchInfo?.overallProgress !== undefined
891
+ ? `[${options.batchInfo.overallProgress}% overall] `
892
+ : '';
893
+ console.log(`✅ ${progressInfo}${rule.id}: Found ${ruleViolations.length} violations`);
894
+
878
895
  results.metadata.analyzersUsed.push(rule.id);
879
-
896
+
880
897
  } catch (error) {
881
898
  console.error(`❌ Failed to analyze rule ${rule.id}:`, error.message);
882
899
  // Continue with other rules
@@ -911,16 +928,28 @@ class HeuristicEngine extends AnalysisEngineInterface {
911
928
 
912
929
  const allViolations = [];
913
930
 
914
- // Run semantic analysis for each file
931
+ // Run semantic analysis for each file with progress tracking
932
+ const totalFiles = files.length;
933
+ let processedFiles = 0;
934
+ let lastReportedProgress = 0;
935
+
915
936
  for (const filePath of files) {
916
937
  try {
917
- if (options.verbose) {
918
- console.log(`🧠 [SemanticRule] Analyzing ${path.basename(filePath)} with ${rule.id}`);
938
+ processedFiles++;
939
+ const currentProgress = Math.floor((processedFiles / totalFiles) * 100);
940
+
941
+ // Report progress every 10% or when verbose
942
+ if (options.verbose || (currentProgress >= lastReportedProgress + 10 && currentProgress < 100)) {
943
+ const progressInfo = options.batchInfo?.overallProgress !== undefined
944
+ ? `[${options.batchInfo.overallProgress}% overall] `
945
+ : '';
946
+ console.log(`🧠 ${progressInfo}${rule.id}: Processing file ${processedFiles}/${totalFiles} (${currentProgress}%) - ${path.basename(filePath)}`);
947
+ lastReportedProgress = currentProgress;
919
948
  }
920
-
949
+
921
950
  // Call semantic rule's analyzeFile method
922
951
  await ruleInstance.analyzeFile(filePath, options);
923
-
952
+
924
953
  // Get violations from the rule instance
925
954
  const fileViolations = ruleInstance.getViolations();
926
955
  allViolations.push(...fileViolations);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sun-asterisk/sunlint",
3
- "version": "1.3.21",
3
+ "version": "1.3.22",
4
4
  "description": "☀️ SunLint - Multi-language static analysis tool for code quality and security | Sun* Engineering Standards",
5
5
  "main": "cli.js",
6
6
  "bin": {