python-code-analyz

👤 sujian0606-cpu 📦 v1.0.0 ⭐ 0.0 ⬇️ 795 下載
💻 開發程式設計 免費

📖 技能介紹

Code Analyzer Skill

版本: 1.0.0
作者: sohot-gdjinni
標籤: code-review, python, security, optimization


簡介

一個專業的 Python 程式碼分析與最佳化 Skill,提供: - 語法檢查與結構分析 - 安全漏洞掃描 - 效能最佳化建議 - 重構後的可直接使用程式碼


功能特性

功能 說明
🔍 語法檢查 Python 語法驗證、AST 結構分析
🛡️ 安全掃描 檢測硬編碼金鑰、裸 except、SQL 注入等
效能分析 識別低效迴圈、冗餘計算、快取機會
📊 程式碼質量 複雜度評估、重複程式碼檢測
修復版本 提供可直接使用的最佳化後代碼

使用方法

1. 直接分析程式碼

# 分析單個檔案
python3 -m code_analyzer analyze /path/to/your/code.py

# 分析目錄
python3 -m code_analyzer analyze /path/to/project/ --recursive

2. 在 Python 中使用

from code_analyzer import CodeAnalyzer

analyzer = CodeAnalyzer()
results = analyzer.analyze_file('your_code.py')

# 檢視問題列表
for issue in results.issues:
    print(f"[{issue.severity}] {issue.message}")

# 獲取修復建議
fixed_code = results.get_fixed_code()

3. 作為 Agent Skill 使用

當你需要分析程式碼時,直接貼上程式碼給我,我會:

  1. 語法檢查 - 驗證程式碼能否正常執行
  2. 問題檢測 - 找出安全/效能/質量問題
  3. 分級報告 - P0(必須修復) / P1(重要) / P2(建議) / P3(可選)
  4. 提供修復 - 給出可直接使用的最佳化版本

示例輸出

輸入程式碼

def api_get(path):
    import urllib.request
    try:
        req = urllib.request.Request('https://api.example.com' + path)
        with urllib.request.urlopen(req) as resp:
            return json.loads(resp.read())
    except:
        return None

分析結果

📊 程式碼分析報告
==================================================
函式數量: 1
類數量: 0
匯入語句: 1

🔍 發現的問題:
  ⚠️ [P0] 使用裸 except: 可能隱藏所有異常
  ⚠️ [P1] 硬編碼 API 地址
  ⚠️ [P1] 缺少超時設定
  ⚠️ [P2] 匯入語句在函式內

✅ 最佳化建議:
  1. 使用具體的異常型別 (HTTPError, URLError)
  2. 新增 timeout 引數
  3. 將 import 移到檔案頂部

修復後代碼

import json
import urllib.request
import urllib.error
from typing import Optional, Dict

API_BASE_URL = 'https://api.example.com'
DEFAULT_TIMEOUT = 15

def api_get(path: str, timeout: int = DEFAULT_TIMEOUT) -> Optional[Dict]:
    """傳送 GET 請求"""
    try:
        req = urllib.request.Request(API_BASE_URL + path)
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return json.loads(resp.read().decode('utf-8'))
    except urllib.error.HTTPError as e:
        print(f"HTTP錯誤: {e.code}")
        return None
    except urllib.error.URLError as e:
        print(f"連線錯誤: {e.reason}")
        return None
    except json.JSONDecodeError as e:
        print(f"JSON解析錯誤: {e}")
        return None

檢查規則

P0 - 必須修復 (安全/穩定性)

  • [x] hardcoded_secrets - 硬編碼 API 金鑰/密碼/令牌
  • [x] bare_except - 裸 except: 捕獲所有異常
  • [x] sql_injection - SQL 注入風險(字串拼接/format/f-string)
  • [x] command_injection - 命令注入(os.system/subprocess 使用動態字串)
  • [x] dangerous_functions - 危險函式(eval/exec/pickle/yaml.load/marshal)

P1 - 重要 (可靠性)

  • [x] missing_timeout - HTTP 請求未設定 timeout
  • [x] resource_leaks - 鎖 acquire 沒有對應 release
  • [x] unclosed_files - 檔案開啟後未關閉
  • [x] debug_code - 除錯程式碼(pdb 匯入)

P2 - 建議 (質量)

  • [x] missing_type_hints - 函式引數/返回值缺少型別提示
  • [x] long_functions - 函式超過 50 行
  • [x] unused_variables - 變數被賦值但從未使用
  • [x] inline_imports - 函式內匯入
  • [x] debug_code - print 除錯語句
  • [x] hardcoded_urls - 硬編碼 URL/IP 地址

    來源於7w4.net。

P3 - 可選 (風格)

  • [ ] 命名規範
  • [ ] 文件字串缺失
  • [ ] 註釋質量

安裝

# 克隆倉庫
git clone https://github.com/yourusername/code-analyzer-skill.git
cd code-analyzer-skill

# 安裝依賴
pip install -r requirements.txt

# 可選:安裝為系統命令
pip install -e .

配置

建立 .code_analyzer.yaml

# 忽略的檔案/目錄
exclude:
  - "*/venv/*"
  - "*/__pycache__/*"
  - "*/tests/*"

# 自定義規則
rules:
  max_line_length: 120
  max_function_lines: 50
  max_complexity: 10

# 嚴重性覆蓋
severity:
  bare_except: "error"      # 裸 except 升級為錯誤
  missing_timeout: "warning" # 缺少超時降級為警告

工作原理

┌─────────────────────────────────────────┐
│           程式碼輸入                       │
└─────────────────┬───────────────────────┘
                  ▼
┌─────────────────────────────────────────┐
│  1. 語法檢查 (AST解析)                   │
│     - Python 語法驗證                   │
│     - 結構分析                          │
└─────────────────┬───────────────────────┘
                  ▼
┌─────────────────────────────────────────┐
│  2. 靜態分析                             │
│     - 安全掃描                          │
│     - 效能檢測                          │
│     - 程式碼異味                          │
└─────────────────┬───────────────────────┘
                  ▼
┌─────────────────────────────────────────┐
│  3. 問題分級                             │
│     - P0/P1/P2/P3                       │
│     - 影響評估                          │
└─────────────────┬───────────────────────┘
                  ▼
┌─────────────────────────────────────────┐
│  4. 生成修復                             │
│     - 程式碼重構                          │
│     - 型別提示                          │
│     - 文件生成                          │
└─────────────────────────────────────────┘

貢獻

歡迎貢獻!請遵循以下流程:

  1. Fork 倉庫
  2. 建立功能分支 (git checkout -b feature/amazing-feature)
  3. 提交更改 (git commit -m 'Add amazing feature')
  4. 推送到分支 (git push origin feature/amazing-feature)
  5. 建立 Pull Request

許可證

MIT License - 詳見 LICENSE 檔案


致謝

基於以下開源專案構建: - Python AST 模組 - Bandit (安全掃描) - Radon (複雜度分析)


更新日誌

v1.0.0 (2026-03-21)

  • 🎉 初始版本釋出
  • ✅ 基礎語法檢查
  • ✅ 安全漏洞掃描
  • ✅ 效能最佳化建議
  • ✅ 修復程式碼生成

📁 包含檔案 (11 個)

📄 CHANGELOG.md 2.2 KB
📄 PUBLISH.md 2.7 KB
📄 README.md 4.2 KB
📄 SKILL.md 7.6 KB
📄 _meta.json 137 B
📄 analyzer.py 23.9 KB
📄 example.py 926 B
📄 package.json 1.2 KB
📄 publish.sh 1.9 KB
📄 requirements.txt 63 B
📄 skill.yaml 1.7 KB