📌 Baca Juga (Scripting & Automation): Otomatisasi Dokumentasi API dan Kode dengan AI: dari Docstring ke README

Kenapa Kode Kotor Masuk Repo?

Kode kotor masuk repo setiap hari. Review manual lambat. Bug lolos ke produksi. Tim buang waktu berjam-jam. Solusi? Otomasi.

Banyak tim andalkan code review manual. Pull request menumpuk. Reviewer kelelahan. Kode jelek lolos. Masalah muncul di produksi. Bukan salah reviewer. Volume kode terlalu besar untuk manusia.

Butuh code quality gate otomatis. Gerbang yang menolak kode buruk sebelum masuk repo. Bukan setelahnya.

Pre-commit Hook: Gerbang Pertama

Pre-commit hook script git. Jalan otomatis sebelum commit. Kalau gagal, commit diblokir. Bukan saran. Paksa.

Kelebihan pre-commit:

  • Jalan lokal. Developer tahu sebelum push.
  • Cepat. Hanya file yang diubah.
  • Konsisten. Semua developer kena aturan sama.

LLM Linter: Otak di Balik Gerbang

Linter biasa cek aturan statis. Spacing. Naming. Syntax. Tapi tidak paham konteks.

LLM linter beda. LLM baca kode. Paham logika. Deteksi:

  • Security vulnerability (SQL injection, XSS)
  • Code smell (duplikasi, fungsi terlalu panjang)
  • Error handling buruk
  • Performance issue (query N+1, loop tidak efisien)

Kombinasi: pre-commit hook panggil LLM. LLM review diff. Kalau ada masalah, commit gagal. Inilah automated code review yang sebenarnya.

Implementasi: Pre-commit + LLM Linter

1. Setup Pre-commit Config

Buat file .pre-commit-config.yaml:

repos:
  - repo: local
    hooks:
      - id: llm-lint
        name: LLM Code Quality Gate
        entry: python .pre-commit/llm_lint.py
        language: system
        types: [python, javascript, typescript]
        pass_filenames: false

pass_filenames: false penting. Script ambil diff sendiri.

2. Script LLM Linter

Buat .pre-commit/llm_lint.py:

import sys
import subprocess
import json

def get_staged_diff():
    result = subprocess.run(
        ["git", "diff", "--cached"],
        capture_output=True,
        text=True
    )
    return result.stdout

def call_llm_api(code_diff):
    import requests
    response = requests.post(
        "https://api.llm.example.com/v1/chat",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        json={
            "model": "gpt-4o",
            "messages": [
                {"role": "system", "content": "You are a senior code reviewer. Find issues in the diff."},
                {"role": "user", "content": code_diff}
            ]
        }
    )
    return response.json()

def main():
    diff = get_staged_diff()
    if not diff.strip():
        sys.exit(0)

    result = call_llm_api(diff)

    if result.get("has_issues"):
        print("Kode ditolak oleh LLM linter:")
        for issue in result["issues"]:
            print(f"  - {issue}")
        sys.exit(1)

    print("Kode lolos LLM linter")
    sys.exit(0)

if __name__ == "__main__":
    main()

3. Prompt Engineering

Prompt menentukan kualitas review. Prompt buruk = hasil buruk. Contoh prompt efektif:

You are a senior code reviewer. Review the following git diff.
Check for:
1. Security vulnerabilities (injection, XSS, CSRF)
2. Code smells (duplication, long functions, magic numbers)
3. Error handling (missing try-catch, silent failures)
4. Performance issues (N+1 queries, unnecessary loops)
5. Best practices for the language used

Output JSON: {"has_issues": true/false, "issues": ["..."]}
Be strict. Only pass clean code.

Best Practices

Batasi Cakupan

Jangan review semua file. Fokus file penting. Whitelist:

IMPORTANT_PATHS = [
    "src/", "api/", "auth/", "core/"
]

Cache Hasil

LLM API lambat dan mahal. Cache hasil per diff hash. Kalau diff sama, pakai hasil lama.

Grace Period

Jangan blokir semua. Kasih grace period. Minggu pertama cuma warning. Minggu kedua mulai blokir.

Fallback

Kalau LLM API down, jangan blokir commit. Log warning, biarkan lolos. Lebih baik lolos daripada tim stuck.

Contoh Kasus Nyata

Developer commit kode dengan SQL injection:

query = f"SELECT * FROM users WHERE id = {user_id}"

LLM linter deteksi. Commit ditolak. Developer perbaiki:

query = "SELECT * FROM users WHERE id = ?"
cursor.execute(query, (user_id,))

Commit lolos. Bug tidak masuk produksi. Tim hemat waktu.

💡 Baca Juga & Rekomendasi Jaringan AI Network:

  • Gunakan racikan prompt profesional di SolusiAI.my.id (Rekomendasi Tools & Otomatisasi AI).
  • Pelajari tutorial skrip dan otomatisasi teknis di PromptHack.my.id (Kumpulan AI Prompt & Content Growth).

Kesimpulan

Pre-commit hook + LLM linter = code quality gate otomatis. Bukan cuma linter statis. LLM paham konteks. Deteksi masalah yang linter biasa lewat.

Implementasi sederhana: satu file config, satu script Python. Tim hemat waktu review. Kode bersih masuk repo. Bug tidak lolos ke produksi.

Mulai hari ini. Kode kotor ditolak otomatis.

Post a Comment

Lebih baru Lebih lama