惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
博客园 - 司徒正美
I
InfoQ
宝玉的分享
宝玉的分享
G
Google Developers Blog
J
Java Code Geeks
Martin Fowler
Martin Fowler
The GitHub Blog
The GitHub Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
罗磊的独立博客
腾讯CDC
F
Fortinet All Blogs
A
About on SuperTechFans
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Recent Announcements
Recent Announcements
Last Week in AI
Last Week in AI
B
Blog RSS Feed
博客园 - 聂微东
D
DataBreaches.Net
Hugging Face - Blog
Hugging Face - Blog
The Cloudflare Blog
L
LangChain Blog
Microsoft Azure Blog
Microsoft Azure Blog
aimingoo的专栏
aimingoo的专栏

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Build a Git Commit Analyzer with Gemma 4 31B and a 256K C...
Jubin Soni · 2026-05-09 · via DEV Community

This is a submission for the Gemma 4 Challenge: Build with Gemma 4

Most developers reach for an LLM when they need code completion or a chatbot. This article is about something more useful and less obvious: feeding your entire sprint's git history to Gemma 4 31B — diffs, commit messages, authors and all — and getting back structured, actionable analysis of what actually changed and why it might matter.

The 31B Dense model's 256K context window is the key enabler here. It means you can pass tens of thousands of lines of patch output in a single prompt and ask the model to reason across the whole thing — not chunk-and-summarize, but genuinely cross-reference commits, spot patterns, and flag risk. That's a qualitatively different capability from what a smaller model or an older Gemma generation could provide.

By the end of this guide you'll have a working Python CLI tool that:

  • Shells out to git log --patch to collect a commit range
  • Sends the full diff to Gemma 4 31B via the Gemini API (free tier in Google AI Studio)
  • Returns a structured JSON report with change summaries, risk flags, and a draft changelog
  • Optionally writes a Markdown changelog file

Why Gemma 4 31B Is the Right Model for This

Three specific properties make the 31B Dense the correct pick here — not the 26B MoE, not the edge models.

256K context window. A week's worth of commits on a mid-size codebase generates 20,000–80,000 tokens of patch text. The 31B handles that in a single pass. Chunking and summarizing separately loses cross-commit signal: the model can't notice that a refactor in commit 3 introduced the same variable name collision that commit 7 later fixed.

Maximum quality per query. The 31B Dense is the highest-accuracy model in the Gemma 4 family. For code analysis you care about precision — a false positive risk flag wastes a senior engineer's time, and a false negative ships a bug. You're making one expensive call per analysis run, so raw quality beats throughput.

Native structured output. Gemma 4 has first-class support for function calling and structured JSON output. The analyzer requests a strict JSON schema and the model reliably returns it — no fragile string parsing required.

The 26B MoE is the right choice if you're building something that calls the model thousands of times per day and want cost efficiency. This tool calls it once per analysis run and prioritizes signal quality, so the Dense wins.


Prerequisites

  • Python 3.10+
  • A Google AI Studio API key (free — get one here)
  • A git repository to analyze
  • The google-generativeai Python SDK
pip install google-generativeai

Enter fullscreen mode Exit fullscreen mode

Set your API key as an environment variable:

export GEMINI_API_KEY="your-key-here"

Enter fullscreen mode Exit fullscreen mode


Step 1: Collect the Git Diff

The first job is gathering the raw patch data. We use git log --patch with a commit range and pipe the output to a string. We also collect structured commit metadata separately so the model has author and timestamp context alongside the diff.

import subprocess
import sys

def collect_git_history(repo_path: str, since: str = "1 week ago", until: str = "HEAD") -> tuple[str, list[dict]]:
    """
    Returns (full_patch_text, list_of_commit_metadata).
    `since` accepts anything git understands: '7 days ago', 'v1.2.3', a SHA, etc.
    """
    # Collect the full unified diff
    patch_result = subprocess.run(
        ["git", "log", "--patch", "--no-merges", f"--since={since}", f"--until={until}",
         "--pretty=format:COMMIT: %H%nAuthor: %an <%ae>%nDate: %ci%nMessage: %s%n"],
        cwd=repo_path,
        capture_output=True,
        text=True,
        check=True
    )

    # Collect lightweight metadata for the summary header
    meta_result = subprocess.run(
        ["git", "log", "--no-merges", f"--since={since}", f"--until={until}",
         "--pretty=format:%H|%an|%ci|%s"],
        cwd=repo_path,
        capture_output=True,
        text=True,
        check=True
    )

    commits = []
    for line in meta_result.stdout.strip().splitlines():
        if not line:
            continue
        sha, author, date, *msg_parts = line.split("|")
        commits.append({
            "sha": sha[:8],
            "author": author,
            "date": date,
            "message": "|".join(msg_parts)
        })

    return patch_result.stdout, commits

Enter fullscreen mode Exit fullscreen mode

A week of commits on a real codebase might be 40,000–100,000 tokens. We'll let the model handle the full text — that's exactly what the 256K window is for.


Step 2: Build the Prompt

The prompt does three things: gives the model its role and output contract, defines the JSON schema it must return, and passes the raw git history.

SYSTEM_PROMPT = """You are a senior staff engineer performing a structured code review
of a git commit history. Your job is to analyse the provided patch text and return a
single JSON object — nothing else, no markdown fences, no explanation outside the JSON.

The JSON object must match this schema exactly:

{
  "summary": "2-3 sentence plain-English summary of the overall change set",
  "changed_areas": [
    {
      "path": "path/to/file_or_directory",
      "change_type": "added | modified | deleted | renamed",
      "description": "what changed and why it likely changed"
    }
  ],
  "risk_flags": [
    {
      "severity": "low | medium | high",
      "area": "file or component",
      "reason": "specific, concrete reason this change carries risk"
    }
  ],
  "patterns": [
    "notable cross-commit pattern, refactor theme, or repeated change"
  ],
  "changelog_entry": "A polished, user-facing changelog entry in Markdown. Use ## [Unreleased] as the heading. Group under Added, Changed, Fixed, Removed as appropriate."
}

Be specific. Do not flag risk without a concrete reason tied to the actual diff.
Do not invent changes that are not present in the patch text."""


def build_prompt(patch_text: str, commits: list[dict]) -> str:
    commit_count = len(commits)
    authors = list({c["author"] for c in commits})
    date_range = f"{commits[-1]['date'][:10]} to {commits[0]['date'][:10]}" if commits else "unknown"

    header = (
        f"ANALYSIS REQUEST\n"
        f"Commits: {commit_count}\n"
        f"Authors: {', '.join(authors)}\n"
        f"Date range: {date_range}\n\n"
        f"FULL PATCH TEXT FOLLOWS\n"
        f"{'='*60}\n"
    )

    return header + patch_text

Enter fullscreen mode Exit fullscreen mode

The system prompt enforces a strict schema so we can parse the response with json.loads — no regex, no fallbacks. One of Gemma 4's standout improvements over Gemma 3 is how reliably it follows structured output instructions at this schema complexity.


Step 3: Call Gemma 4 31B

We use the google-generativeai SDK with gemma-4-31b-it (the instruction-tuned variant — always use IT for structured task completion).

import google.generativeai as genai
import json
import os

def analyze_with_gemma(patch_text: str, commits: list[dict]) -> dict:
    genai.configure(api_key=os.environ["GEMINI_API_KEY"])

    model = genai.GenerativeModel(
        model_name="gemma-4-31b-it",
        system_instruction=SYSTEM_PROMPT,
        generation_config=genai.GenerationConfig(
            temperature=0.2,      # Low temperature for consistent structured output
            top_p=0.9,
            max_output_tokens=4096,
        )
    )

    prompt = build_prompt(patch_text, commits)

    print(f"Sending {len(prompt.split()):,} words to Gemma 4 31B...", file=sys.stderr)

    response = model.generate_content(prompt)

    raw = response.text.strip()

    # Strip markdown fences if the model adds them despite instructions
    if raw.startswith("```

"):
        raw = raw.split("

```")[1]
        if raw.startswith("json"):
            raw = raw[4:]

    return json.loads(raw)

Enter fullscreen mode Exit fullscreen mode

Temperature at 0.2 keeps the output deterministic and schema-compliant. For creative changelog prose you could nudge it to 0.4 — but for risk flags you want the model to be conservative and consistent.


Step 4: Format and Output the Report

from datetime import datetime

def print_report(analysis: dict, commits: list[dict]) -> None:
    print("\n" + "="*60)
    print("GIT HISTORY ANALYSIS — Gemma 4 31B")
    print("="*60)
    print(f"\nCommits analysed: {len(commits)}")
    print(f"\nSUMMARY\n{analysis['summary']}\n")

    if analysis.get("risk_flags"):
        print("RISK FLAGS")
        for flag in sorted(analysis["risk_flags"], key=lambda f: {"high": 0, "medium": 1, "low": 2}[f["severity"]]):
            icon = {"high": "🔴", "medium": "🟡", "low": "🟢"}[flag["severity"]]
            print(f"  {icon} [{flag['severity'].upper()}] {flag['area']}")
            print(f"     {flag['reason']}")
        print()

    if analysis.get("patterns"):
        print("PATTERNS DETECTED")
        for p in analysis["patterns"]:
            print(f"{p}")
        print()

    print("CHANGED AREAS")
    for area in analysis.get("changed_areas", []):
        print(f"  [{area['change_type'].upper():8}] {area['path']}")
        print(f"             {area['description']}")
    print()


def write_changelog(analysis: dict, output_path: str) -> None:
    entry = analysis.get("changelog_entry", "")
    if not entry:
        return

    # Inject today's date if the entry has a placeholder
    entry = entry.replace("[Unreleased]", f"[Unreleased] — {datetime.today().strftime('%Y-%m-%d')}")

    with open(output_path, "w") as f:
        f.write(entry + "\n")

    print(f"Changelog written to {output_path}", file=sys.stderr)

Enter fullscreen mode Exit fullscreen mode


Step 5: Wire It Together as a CLI

import argparse

def main():
    parser = argparse.ArgumentParser(
        description="Analyse a git commit range with Gemma 4 31B"
    )
    parser.add_argument("repo", help="Path to git repository")
    parser.add_argument("--since", default="1 week ago",
                        help="Start of range (default: '1 week ago'). Accepts any git date or ref.")
    parser.add_argument("--until", default="HEAD",
                        help="End of range (default: HEAD)")
    parser.add_argument("--changelog", default=None,
                        help="Write changelog entry to this file")
    parser.add_argument("--json", dest="json_out", default=None,
                        help="Write full JSON report to this file")
    args = parser.parse_args()

    patch_text, commits = collect_git_history(args.repo, args.since, args.until)

    if not commits:
        print("No commits found in the specified range.", file=sys.stderr)
        sys.exit(0)

    analysis = analyze_with_gemma(patch_text, commits)
    print_report(analysis, commits)

    if args.changelog:
        write_changelog(analysis, args.changelog)

    if args.json_out:
        with open(args.json_out, "w") as f:
            json.dump(analysis, f, indent=2)
        print(f"Full JSON report written to {args.json_out}", file=sys.stderr)


if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode


Running It

Analyse the last week of commits in the current repo:

python git_analyzer.py . --since "1 week ago"

Enter fullscreen mode Exit fullscreen mode

Analyse a specific SHA range and write a changelog:

python git_analyzer.py /path/to/repo \
  --since v1.4.0 \
  --until v1.5.0 \
  --changelog CHANGELOG.md \
  --json report.json

Enter fullscreen mode Exit fullscreen mode

Analyse a single sprint (two-week window):

python git_analyzer.py . --since "14 days ago" --changelog CHANGELOG.md

Enter fullscreen mode Exit fullscreen mode


Sample Output

Here's an abbreviated example of what the tool produces on a real project:

============================================================
GIT HISTORY ANALYSIS — Gemma 4 31B
============================================================

Commits analysed: 23

SUMMARY
This sprint focused on migrating the authentication layer from session
cookies to JWTs, with supporting changes to the user model and API
middleware. Three unrelated bug fixes were included. No database
migrations were added despite schema-adjacent changes in user.py.

RISK FLAGS
  🔴 [HIGH]  src/auth/middleware.py
             Token expiry is set to 0 in the new JWT config, which
             disables expiry entirely. This appears unintentional given
             the surrounding comments referencing a 24h TTL.
  🟡 [MEDIUM] src/models/user.py
             The `last_login` field is now written in two places with
             different timezone handling (UTC in the old path, local
             time in the new one). Cross-commit inconsistency introduced
             in commits a3f1cc and 9d02bb.

PATTERNS DETECTED
  • JWT migration touched 11 files across 8 commits — no single
    atomic commit, suggesting iterative discovery during implementation
  • Four separate commits add logging statements then remove them,
    indicating debug churn that could have been a feature branch

CHANGED AREAS
  [MODIFIED ] src/auth/middleware.py
               Core auth middleware rewritten to validate Bearer tokens
               instead of reading from session. Old session path removed.
  [MODIFIED ] src/models/user.py
               Added jwt_secret field; last_login timezone handling changed
  [ADDED    ] src/auth/token.py
               New module for JWT encode/decode with HS256
  ...

Enter fullscreen mode Exit fullscreen mode

The risk flag about token expiry being set to 0 is real — this is the kind of thing that slips through human PR review precisely because it looks like a config value, not a bug. The cross-commit inconsistency flag is only possible because the model reasoned across all 23 commits simultaneously rather than reviewing each in isolation.


Context Window Headroom

The 256K window on Gemma 4 31B means you have significant headroom. At roughly 3 characters per token, the practical limits look like this:

Scenario Approx. tokens Fits in 256K?
1 day of commits, small team ~5,000
1 sprint (2 weeks), small team ~40,000
Full quarter, mid-size team ~180,000
1 year of active development ~500,000+ ❌ use --since to segment

For very large repos, segment by component directory using git log -- path/to/subdir rather than trying to fit everything.


Where to Take This Next

GitHub Action. Trigger the analyzer on each PR, post the risk flags as a PR comment, and block merge if any high severity flags are found. One YAML file and a secrets entry gets you there.

Slack/Teams digest. Run on a cron, pipe the changelog entry to a webhook. Engineering managers get a plain-English weekly summary without reading git.

Fine-tuning. If your team consistently disagrees with certain risk classifications, collect those corrections as a small labeled dataset and fine-tune the model on Vertex AI or Colab. Gemma 4's Apache 2.0 license means there are no restrictions on using it as a fine-tuning base for internal tools.

Multi-repo analysis. Pass diffs from multiple services in the same prompt window. The 256K context means you can compare what changed across your backend, frontend, and infra repos in the same analysis run.


Why This Matters

The git history is one of the most information-dense artifacts a software team produces, and it's almost entirely ignored outside of git blame. Gemma 4 31B's context window is large enough to treat a sprint's history as a single document rather than a stream of individual events.

That shift in granularity changes what the model can do: it can notice that a change made on Tuesday was partially reverted on Thursday, that two different authors independently touched the same configuration key, or that a "refactor" commit introduced a subtle behavioral change buried in 400 lines of renames.

None of that is possible when each commit is reviewed in isolation.


Resources