Marcio Cunha

How to review code with local AI before pull request using Ollama

Learn how to configure local language models with Ollama and githooks to run static security and style scans directly on your machine.

Marcio Cunha•5 min
Also available in:PortuguêsEspañol
Summary
  • Local models run entirely offline and guarantee total privacy of corporate source code
  • Githooks intercept commands like git commit or push to automate checks without relying on external servers
  • Ollama simplifies running artificial intelligence weights directly in the developer terminal
  • Validation scripts prevent credentials and basic flaws from reaching the central repository
  • Local integration speeds up the development cycle by providing immediate feedback before the pull request

The challenge of maintaining quality before versioning

Ensuring that no critical bugs, security flaws, or style deviations escape into the main repository is one of the hardest tasks in modern software development. Many teams rely on continuous integration servers (automated systems running tests in the cloud) to check code, but this creates a slow feedback loop: you write code, push it to the cloud, wait minutes, and only then find out you forgot a variable or left a password exposed. In practice, this means wasting precious time fixing minor oversights that could have been prevented locally.

To solve this bottleneck without sending sensitive data to third-party cloud artificial intelligence servers, we can run language models (algorithms trained to understand and generate text) directly on our own computers. By combining local execution tools with terminal workflow automators, we create an invisible barrier that scans code line by line before it can even be shared with the team.

What are githooks and how do they intercept your actions

Githooks are scripts automatically triggered by the version control system whenever a specific event occurs in the repository, such as a commit or push command. Think of them as guards stationed at your project's gate: every time you try to register a change, the guard temporarily stops the action, runs an inspection routine, and only lets the process proceed if everything is in order. This automation eliminates reliance on human memory and prevents moments of distraction from going unnoticed.

In our scenario, we will specifically use the pre-commit hook, which triggers right at the moment you try to save changes locally. If the script finds a security issue, a hardcoded password, or a code pattern outside accepted styles, it immediately cancels the commit and displays the reason on screen. Thus, you fix the error instantly, keeping the project history clean and free of unnecessary pollution.

Configuring Ollama to run local artificial intelligence

Ollama is a lightweight, practical tool designed to manage and run large language models directly on local hardware, whether a laptop or a robust workstation. It acts as a local server handling requests via command line or API, allowing any script to talk to artificial intelligence without needing an internet connection. To get started, the first step is to install the tool and download a compact, efficient model, such as Llama 3 or Mistral, ideal for quick text and syntax analysis.

After successful installation, you can test the artificial intelligence engine directly from your machine terminal. This approach guarantees full data sovereignty, as no piece of your proprietary or confidential code will ever leave your computer's hard drive. Moreover, as we saw when exploring advanced local search and processing techniques, the ecosystem of local tools has evolved to deliver fast, accurate responses without requiring industrial graphics cards.

Creating the static security scanning script

With the AI engine running locally, we need to write the bridge connecting git to the model. We create a Python or Bash script that extracts changes made in modified files (using git diff commands) and sends this formatted content to Ollama's local API. The prompt sent to the artificial intelligence must be highly targeted, instructing the model to act as a rigorous senior code reviewer looking only for serious security flaws, secret leaks, and glaring bad practices.

To implement this logic cleanly and modularly, many developers draw inspiration from the architecture of task-specific autonomous agents, ensuring the model stays on track and strictly answers whether the code is approved or rejected. Below, we present a practical Python example script that performs this communication automatically:

import subprocess
import requests
import json

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

def review_code_with_ollama(diff_content):
    if not diff_content.strip():
        return 'No changes to review.'
    
    url = 'http://localhost:11434/api/generate'
    prompt = f'Analyze the following changed code for security flaws or critical errors. Reply APPROVED or REJECTED followed by the reason:\n\n{diff_content}'
    
    payload = {
        'model': 'llama3',
        'prompt': prompt,
        'stream': False
    }
    
    response = requests.post(url, json=payload)
    return response.json().get('response', 'AI response error')

if __name__ == '__main__':
    diff = get_staged_diff()
    verdict = review_code_with_ollama(diff)
    print(verdict)
    if 'REJECTED' in verdict:
        exit(1)

Installing the hook in the local git repository

After creating the validation script, the final step is placing it in the correct directory so git executes it automatically before each commit. Git hooks are stored in the hidden .git/hooks folder inside each repository. To configure our system, we create or edit the pre-commit file located in that folder, ensuring it has proper execution permissions on the operating system.

Below is the sequential procedure in step format that you should execute in your project terminal to activate the defense mechanism:

  1. Navigate to the root folder of your software project where the git repository is initialized.
  2. Open or create the hook configuration file in the internal control folder using the command
    nano .git/hooks/pre-commit
    and paste the call to the validation script.
  3. Make the file executable by the operating system using the permissions command
    chmod +x .git/hooks/pre-commit
    to release the automatic trigger.

Final considerations on productivity and security

Adopting an automated code review routine with local artificial intelligence profoundly transforms a team's development dynamics. Beyond shielding code against embarrassing bugs and accidental API key leaks even before the pull request, this approach fosters a culture of continuous improvement without relying on expensive cloud infrastructure. By keeping processing restricted to your own hardware, you unite the best of both worlds: cutting-edge analytical intelligence and absolute privacy of corporate data.