Skip to content

Code Analyzer

github-actions[bot] edited this page Nov 15, 2025 · 2 revisions

Code Analyzer

Last updated: 2025-11-15 21:25:59

code-analyzer.py

Auto-generated from .github/scripts/code-analyzer.py

Advanced Code Analyzer – API Documentation

Author: github.com/your-org/your-repo
Version: 1.0.0
Last updated: 2025‑11‑15


1. Overview

code-analyzer.py is a self‑contained Python script that performs a multi‑dimensional static analysis of source‑code files.
It is designed to run in CI environments (GitHub Actions, GitLab CI, etc.) and produces:

Output Description
analysis_results.json Raw JSON data for each analyzed file
report.md Human‑readable Markdown summary
analysis_report.md Symlinked copy for quick access in the repo root

The analysis covers:

Category What it measures
Quality Documentation coverage, cyclomatic complexity, maintainability
Security Hard‑coded secrets, SQL injection, XSS, path traversal, command injection
Performance Nested loops, O(n²) patterns, large functions

The script is intentionally language‑agnostic – it supports Python, JavaScript/TypeScript, Go, Rust, Java, and C/C++.


2. Exports

Export Type Description
CodeAnalyzer Class Core analyzer that parses a file and computes metrics.
analyze_file(file_path: str) -> Dict Function Convenience wrapper that reads a file and returns a structured result.
generate_summary_report(results: List[Dict], output_file: Path) Function Builds a Markdown report from a list of analysis results.
main() Function CLI entry‑point that orchestrates the whole workflow.

Note: The script is intended to be executed directly (python3 .github/scripts/code-analyzer.py).
The exported functions can also be imported into other Python modules.


3. Usage Examples

3.1 Running the CLI

# From the repository root
python3 .github/scripts/code-analyzer.py

The script expects a changed_files.txt file listing the files changed in the current PR/commit.
It will create a timestamped directory under code-analysis/ and output the report there.

3.2 Using the API in Python

from pathlib import Path
from code_analyzer import analyze_file, generate_summary_report

# 1. Analyze a single file
result = analyze_file('src/main.py')
print(result['quality_score']['total'])          # 78
print(result['security_vulnerabilities'])        # List of dicts

# 2. Analyze multiple files
files = ['src/main.py', 'src/utils.js']
results = [analyze_file(f) for f in files if f]

# 3. Generate a Markdown report
report_path = Path('analysis_report.md')
generate_summary_report(results, report_path)

4. Parameters & Return Values

4.1 CodeAnalyzer

Method Parameters Returns Description
__init__(file_path: str, content: str) file_path – absolute/relative path to the source file.
content – raw file contents.
None Initializes the analyzer, detects language, splits content into lines.
calculate_quality_score() -> Dict None Dict – contains total, documentation, complexity, maintainability, grade, and a breakdown sub‑dict. Computes a composite quality score (0‑100).
scan_security_vulnerabilities() -> List[Dict] None List of vulnerability dicts: {category, severity, description, line, code}. Runs regex‑based checks for common security patterns.
detect_performance_issues() -> List[Dict] None List of issue dicts: {type, severity, description, line, suggestion}. Detects nested loops, O(n²) patterns, and large functions.

4.2 analyze_file(file_path: str) -> Dict

Parameter Type Description
file_path str Path to the file to analyze.
Return Type Description
Dict {file, language, quality_score, security_vulnerabilities, performance_issues} Structured analysis result. If the file does not exist, returns None.

4.3 generate_summary_report(results: List[Dict], output_file: Path) -> None

Parameter Type Description
results List[Dict] List of results from analyze_file.
output_file Path Destination path for the Markdown report.
Return Type Description
None Writes the report to output_file.

4.4 main() -> None

Parameter Type Description
Reads changed_files.txt, orchestrates per‑file analysis, writes JSON & Markdown outputs, and prints a summary to stdout.

5. Detailed API Reference

5.1 class CodeAnalyzer

class CodeAnalyzer:
    def __init__(self, file_path: str, content: str)
    def calculate_quality_score(self) -> Dict
    def scan_security_vulnerabilities(self) -> List[Dict]
    def detect_performance_issues(self) -> List[Dict]

5.1.1 __init__

  • Parameters
    • file_path: Path to the source file.
    • content: Raw file contents (string).
  • Behavior
    • Detects language from file extension.
    • Splits content into lines for subsequent analysis.

5.1.2 calculate_quality_score

  • Returns: Dict with keys:
    • total (int): 0‑100 composite score.
    • documentation (int): 0‑30.
    • complexity (int): 0‑30.
    • maintainability (int): 0‑40.
    • grade (str): Letter grade (A+ … D).
    • breakdown (Dict): Detailed sub‑scores and human‑readable descriptions.

5.1.3 scan_security_vulnerabilities

  • Returns: List[Dict] where each dict contains:
    • category (str): e.g., hardcoded_secret, sql_injection.
    • severity (str): HIGH or MEDIUM.
    • description (str): Human‑readable explanation.
    • line (int): Line number of the match.
    • code (str): The offending code snippet.

5.1.4 detect_performance_issues

  • Returns: List[Dict] where each dict contains:
    • type (str): e.g., nested_loops, n_squared_iteration, large_function.
    • severity (str): LOW, MEDIUM, or HIGH.
    • description (str): Explanation.
    • line (int): Line number.
    • suggestion (str): Suggested fix.

5.2 analyze_file(file_path: str) -> Dict

def analyze_file(file_path: str) -> Dict:
    """
    Analyze a single file and return a structured result.
    """
  • Parameters
    • file_path: Path to the file to analyze.
  • Return Value
    • None if the file does not exist or cannot be read.
    • Otherwise a dict:
      {
          'file': 'src/main.py',
          'language': 'python',
          'quality_score': {...},
         

Clone this wiki locally