We are going to design a code generation quality gate that performs three types of checks:
- Contract tests: These are tests that verify the generated code meets certain specifications (like functional correctness, API contracts, etc.)
- Static analysis: This includes linters, security scanners, and other static analysis tools.
- Human review heuristics: These are rules or checks that are designed to mimic human review, possibly by looking for code smells, complexity, etc.
The gate will be implemented as a script or set of scripts that are run in the CI pipeline after code generation.
Steps:
- The generated code (diff) is applied to the codebase (or a temporary copy) for testing.
- Contract tests: Run the existing test suite (unit, integration, etc.) to ensure the changes don't break existing functionality and meet new requirements.
- Static analysis: Run linters, formatters, security scanners, etc. The code must pass all configured checks.
- Human review heuristics: We can use tools that check for code complexity, duplication, and other maintainability metrics. Alternatively, we can have a set of custom scripts that check for patterns that humans typically look for.
We assume the code generation produces a diff (like a git diff) that we can apply.
Let's break down the implementation:
Pre-requisites:
- The generated code is in a diff format (unified diff) and we have a base codebase (the current state of the repository).
- We have a way to apply the diff to a temporary copy of the codebase (or we can use
git apply).
Steps in the script:
-
Set up a temporary directory and copy the current codebase (or use a fresh clone?).
-
Apply the generated diff to the temporary codebase.
-
Run contract tests (the existing test suite) on the temporary codebase.
- We might need to install dependencies and set up the environment.
-
Run static analysis tools on the changed files (or the entire codebase? but we only care about the changes).
- We can use the diff to identify which files were changed and only run static analysis on those, but note that static analysis might require the entire codebase to be present (for type checking, etc.). So we run on the entire temporary codebase, but we can also focus on the changed lines for some tools.
-
Run human review heuristics:
- We can use tools like
radon (for complexity) and vulture (for dead code) or custom scripts that look for specific patterns (e.g., long functions, too many parameters, etc.)
- We might also check for the presence of comments, documentation, etc. if required.
-
If any of the steps fail, the quality gate fails.
Implementation:
We'll write a script in Python (for portability and ease of use) that does the following:
- Accepts the path to the generated diff file.
- Sets up a temporary directory (using
tempfile).
- Clones the current repository (or copies from a given directory) into the temporary directory.
- Applies the diff using
git apply (or patch if git is not available, but we assume git).
- Runs the test suite (we assume there's a way to run tests, e.g.,
pytest, tox, npm test, etc.). We might need to make this configurable.
- Runs static analysis tools (configurable list of tools).
- Runs human review heuristics (configurable set of checks).
We can make the script configurable via command line arguments or a configuration file.
However, note that the steps might vary depending on the project (language, framework, etc.). So we should allow the user to specify the commands for each step.
Alternatively, we can design the gate as a set of independent steps that can be run in any order, but for simplicity we run them sequentially and break on first failure.
Let's design the script:
usage: quality_gate.py [options] <diff_file>
Options:
--base-dir DIR The base directory of the codebase (default: current directory)
--temp-dir DIR Temporary directory to use (if not provided, create one)
--test-cmd CMD Command to run tests (default: try to detect)
--static-analysis-cmds CMD1,CMD2,... Commands to run static analysis (default: list of common tools)
--heuristics-cmds CMD1,CMD2,... Commands to run human review heuristics (default: list of common heuristics)
Alternatively, we can have a configuration file (YAML or JSON) that specifies the steps.
Given the complexity and variability, let's assume we have a configuration file (e.g., .quality_gate.yml) in the base directory that specifies:
test_command: "pytest"
static_analysis:
- command: "flake8 ."
pass_on_output: false # if false, any output means fail? or we can define thresholds?
- command: "bandit -r ."
heuristics:
- command: "radon cc . -a -s" # and then we parse the output for complexity?
- command: "vulture . --min-confidence 80"
But note: we want to run these on the temporary codebase after applying the diff.
Alternatively, we can have a more advanced configuration that allows specifying:
- The working directory for each command (probably the temporary codebase).
- The expected exit code (0 for success) and maybe a way to parse the output for thresholds.
However, to keep it simple, we'll assume that if the command returns 0, it passes.
Steps:
- Parse the configuration file (if exists) and command line options.
- Set up the temporary directory and copy the base code.
- Apply the diff.
- For each step (test, static_analysis, heuristics) run the commands in order.
- If any command fails, exit with non-zero and report which step failed.
Implementation details:
- We'll use
subprocess to run the commands.
- We'll capture the output and print it in case of failure.
Let's write the script:
We assume the script is run from the base directory (or we provide the base-dir).
Steps:
a. Create temporary directory and copy the base code.
b. Apply the diff.
c. Change to the temporary directory and run the commands.
We'll have:
import argparse
import subprocess
import tempfile
import shutil
import os
import yaml # if we use YAML config
But note: we might not have yaml installed, so we can make it optional and fallback to no config.
Alternatively, we can use JSON which is standard.
Let's use JSON for configuration to avoid external dependencies.
Configuration file (optional) at .quality_gate.json:
{
"test_command": "pytest",
"static_analysis": ["flake8 .", "bandit -r ."],
"heuristics": ["radon cc . -a -s", "vulture . --min-confidence 80"]
}
But note: some commands might be project specific (like npm test). So we need to allow the user to override.
We'll do:
command line args override config file.
Steps:
1. Parse command line.
2. Load config file if exists and base-dir is provided (or current directory).
3. Merge: command line args take precedence.
However, to keep it simple for now, we'll just use command line arguments and if not provided, try to run a default set.
But note: the default set might not be suitable for all projects.
Alternatively, we can have a discovery mechanism:
- If there's a `setup.py` or `pyproject.toml`, use pytest and flake8?
- If there's a `package.json`, use npm test and eslint?
This is getting complex.
Given the time, let's design the script to be configurable via command line and a config file, and if nothing is provided, do nothing (or fail).
We'll require the user to specify at least the test command.
Revised plan:
The script requires a configuration (either via command line or config file) that specifies:
test_command: string
static_analysis_commands: list of strings (optional)
heuristics_commands: list of strings (optional)
We'll have:
parser = argparse.ArgumentParser()
parser.add_argument('diff_file', help='Path to the generated diff file')
parser.add_argument('--base-dir', default=os.getcwd(), help='Base directory of the codebase')
parser.add_argument('--config', help='Path to configuration file (JSON)')
parser.add_argument('--test-cmd', help='Command to run tests')
parser.add_argument('--static-analysis-cmds', nargs='*', help='Static analysis commands')
parser.add_argument('--heuristics-cmds', nargs='*', help='Human review heuristics commands')
Then:
config = {}
if args.config:
with open(args.config) as f:
config = json.load(f)
test_cmd = args.test_cmd or config.get('test_command')
static_analysis_cmds = args.static_analysis_cmds or config.get('static_analysis', [])
heuristics_cmds = args.heuristics_cmds or config.get('heuristics', [])
Then we run:
if not test_cmd:
print("No test command specified. Exiting.")
sys.exit(1)
Steps:
1. Create temp dir and copy base-dir to temp-dir.
2. Apply diff to temp-dir.
3. For each command in [test_cmd] + static_analysis_cmds + heuristics_cmds:
run the command in the temp-dir.
if return code != 0:
print(f"Command failed: {command}")
sys.exit(1)
But note: we might want to run all and collect failures? Or stop on first failure? We'll stop on first failure.
Implementation of running a command:
proc = subprocess.run(command, shell=True, cwd=temp_dir, capture_output=True, text=True)
if proc.returncode != 0:
print(f"Command: {command}")
print("STDOUT:")
print(proc.stdout)
print("STDERR:")
print(proc.stderr)
return False
We'll break the steps into functions.
Let's code:
Note: We assume the diff is in unified format and can be applied with git apply (which is more robust) or patch.
We'll try git apply first, then fallback to patch.
Steps for applying:
diff_file = args.diff_file
# Read the diff file and apply
with open(diff_file, 'r') as f:
diff_content = f.read()
# Write the diff to a temporary file? Or use stdin? We'll use stdin.
# Using git apply (if in a git repo? but we are in a temp copy that is a git repo? We copied the base-dir which might be a git repo)
# We can do: `git apply --check` to test, then `git apply`
# But note: the base-dir might not be a git repo? We are copying the files, not the git history.
# Alternatively, we can use `patch` which doesn't require git.
# Let's try:
# git apply --check < diff_file
# git apply < diff_file
# If git apply fails, try with patch.
# However, we are in a temporary directory that is a copy of the base-dir. If the base-dir is a git repo, then the temp-dir is too.
# We'll do:
try:
subprocess.run(['git', 'apply', '--check', diff_file], cwd=temp_dir, check=True)
subprocess.run(['git', 'apply', diff_file], cwd=temp_dir, check=True)
except subprocess.CalledProcessError:
# Try with patch
try:
subprocess.run(['patch', '-p1', '-i', diff_file], cwd=temp_dir, check=True)
except subprocess.CalledProcessError as e:
print(f"Failed to apply diff: {e}")
sys.exit(1)
But note: the diff might be generated with a different -p level? We assume -p1.
Alternatively, we can use the patch command with -p0 if the diff paths are absolute? We don't know.
Given the complexity, let's assume the diff is generated for the base-dir and we are applying from the root of the temp-dir.
We'll use git apply first because it's more robust for git diffs.
If the base-dir is not a git repo, then we cannot use git apply? Actually, git apply can apply diffs even outside a git repo? It just applies the patch to the files.
From the man page: git apply is used to apply a patch to the files and/or the index.
So we can use git apply without a git repo? It should work for plain diffs.
Let's stick with git apply and if it fails, try patch.
However, note that git apply might require the files to be in a git repository for some options? We are using --check and then apply without any index option.
We'll do:
try:
# Check if the diff is valid
subprocess.run(['git', 'apply', '--check', diff_file], cwd=temp_dir, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Apply
subprocess.run(['git', 'apply', diff_file], cwd=temp_dir, check=True)
except (subprocess.CalledProcessError, FileNotFoundError) as e:
# If git is not found or fails, try patch
try:
subprocess.run(['patch', '-p1', '-i', diff_file], cwd=temp_dir, check=True)
except (subprocess.CalledProcessError, FileNotFoundError) as e2:
print(f"Failed to apply diff with git and patch: {e} and {e2}")
sys.exit(1)
But note: patch might not be installed. We are making the script dependent on either git or patch.
We can also use Python's difflib? But that's for generating diffs, not applying.
We'll rely on git or patch.
Now, the full script:
We'll structure:
def apply_diff(temp_dir, diff_file):
...
def run_command(temp_dir, command, step_name):
...
def main():
args = parse_args()
setup temp_dir and copy base-dir
apply_diff
run_steps
Let's code accordingly.
However, note: the base-dir might be large. We are copying the entire base-dir to a temporary directory.
We can use shutil.copytree but note that the base-dir might be a git repo and we want to preserve the .git? Actually, we don't need the .git for running tests and static analysis? We might, if the tests rely on git info (like version). So we copy everything.
But if the base-dir is a git repo, we can also do a git clone? That would be faster for large repos? But we don't know if the user has a remote.
We'll do:
if os.path.isdir(os.path.join(args.base_dir, '.git')):
# We can do a git clone? But we don't have a remote necessarily.
# Instead, we do a full copy.
shutil.copytree(args.base_dir, temp_dir, symlinks=True)
But note: if the base-dir is a git repo, we want to copy the .git directory too? Yes, because some tests might rely on git.
However, if we copy the .git, then the temp-dir is a git repo and we can use git apply without issues.
Let's do:
shutil.copytree(args.base_dir, temp_dir, symlinks=True, ignore_dangling_symlinks=True)
But note: the base-dir might be the current working directory of the user and might have uncommitted changes? We want to test the generated code on top of the current state (with uncommitted changes). So we copy everything, including uncommitted changes? shutil.copytree will copy the working tree, not the git index. So uncommitted changes are copied.
But note: if there are uncommitted changes, then the diff might not apply cleanly? Because the base state is the current working tree (with uncommitted changes). That's what we want.
However, if the user has uncommitted changes, then the generated diff might be against a different base? We assume the generated diff is against the current state (with uncommitted changes). So we copy the current state.
Steps:
temp_dir = tempfile.mkdtemp()
try:
shutil.copytree(args.base_dir, temp_dir, symlinks=True, ignore_dangling_symlinks=True)
apply_diff(temp_dir, args.diff_file)
# Now run commands in temp_dir
...
finally:
shutil.rmtree(temp_dir)
But note: if the base-dir is a git repo, then the temp_dir will have a .git directory. We can then use git apply and also git status if needed.
However, we are applying the diff to the working tree, not committing.
Now, let's write the script.
We'll assume the configuration file is at args.base_dir/.quality_gate.json if not provided.
But note: the base-dir might be the root of the project, and we are copying it to temp-dir. The config file is in the base-dir, so we read it from there.
Steps for config:
config_path = args.config or os.path.join(args.base_dir, '.quality_gate.json')
if os.path.exists(config_path):
with open(config_path) as f:
config = json.load(f)
else:
config = {}
Then merge with command line.
Now, let's code.
We'll do:
test_cmd = args.test_cmd or config.get('test_command')
static_analysis_cmds = args.static_analysis_cmds or config.get('static_analysis', [])
heuristics_cmds = args.heuristics_cmds or config.get('heuristics', [])
And then we run:
steps = [
('test', test_cmd),
('static_analysis', static_analysis_cmds),
('heuristics', heuristics_cmds)
]
for step_name, commands in steps:
if isinstance(commands, str):
commands = [commands]
for cmd in commands:
if not run_command(temp_dir, cmd, step_name):
print(f"Quality gate failed at step: {step_name} with command: {cmd}")
sys.exit(1)
But note: we might want to run all static analysis commands even if one fails? Or stop on first failure? We stop on first failure.
Alternatively, we can collect all failures and report at the end. But for simplicity, we stop.
Now, let's code the run_command:
def run_command(temp_dir, command, step_name):
print(f"Running {step_name}: {command}")
try:
proc = subprocess.run(command, shell=True, cwd=temp_dir, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
print(proc.stdout)
if proc.stderr:
print("STDERR:", proc.stderr)
return True
except subprocess.CalledProcessError as e:
print(f"Command failed: {command}")
print("STDOUT:", e.stdout)
print("STDERR:", e.stderr)
return False
But note: some commands might produce a lot of output. We might want to stream the output? But then we lose the ability to capture and print on failure.
Alternatively, we can let the command output to the console in real time, but then we cannot capture it for the failure report? We can do both by setting stdout and stderr to subprocess.PIPE and then printing only on failure? But then we don't see the output until the command finishes.
We can do:
proc = subprocess.run(command, shell=True, cwd=temp_dir, check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
print(proc.stdout)
print(proc.stderr)
return proc.returncode == 0
But then we print even on success? That might be too verbose.
We can do:
if we are in a CI, we might want to see the output always? Or only on failure?
Let's change: print the output only on failure, but also allow the user to see the output by using --verbose?
We'll add a --verbose flag that prints the output of every command.
Alternatively, we can let the command output to the console by not capturing, but then we cannot capture for the failure report? We can do:
if verbose:
stdout = None
stderr = None
else:
stdout = subprocess.PIPE
stderr = subprocess.PIPE
Then:
proc = subprocess.run(command, shell=True, cwd=temp_dir, check=False, stdout=stdout, stderr=stderr, text=True)
if not verbose and proc.returncode != 0:
print("STDOUT:", proc.stdout)
print("STDERR:", proc.stderr)
But then if verbose, we don't capture and the output goes to the console in real time.
We'll add:
parser.add_argument('--verbose', action='store_true', help='Print output of all commands')
Then in run_command:
if args.verbose:
stdout = None
stderr = None
else:
stdout = subprocess.PIPE
stderr = subprocess.PIPE
But note: the run_command function needs to know about the verbose flag. We can pass it.
Alternatively, we can make the run_command function take an additional verbose argument.
Let's adjust:
def run_command(temp_dir, command, step_name, verbose=False):
print(f"Running {step_name}: {command}")
if verbose:
stdout = None
stderr = None
else:
stdout = subprocess.PIPE
stderr = subprocess.PIPE
proc = subprocess.run(command, shell=True, cwd=temp_dir, check=False, stdout=stdout, stderr=stderr, text=True)
if verbose:
# We already printed in real time, but we might want to print the return code?
if proc.returncode != 0:
print(f"Command failed with exit code {proc.returncode}")
else:
if proc.returncode != 0:
print(f"Command failed with exit code {proc.returncode}")
print("STDOUT:")
print(proc.stdout)
print("STDERR:")
print(proc.stderr)
return proc.returncode == 0
But note: if verbose, we are not capturing, so we cannot print the output on failure? Actually, the output is already printed to the console. So we just print the exit code.
However, if we are not verbose and the command fails, we print the captured output.
This seems acceptable.
Now, let's put it all together.
We'll also add a step to clean up the temp dir at the end.
We'll use a try-finally.
Code structure:
import argparse
import subprocess
import tempfile
import shutil
import os
import json
import sys
def apply_diff(temp_dir, diff_file):
...
def run_command(temp_dir, command, step_name, verbose=False):
...
def main():
parser = argparse.ArgumentParser()
parser.add_argument('diff_file', help='Path to the generated diff file')
parser.add_argument('--base-dir', default=os.getcwd(), help='Base directory of the codebase')
parser.add_argument('--config', help='Path to configuration file (JSON)')
parser.add_argument('--test-cmd', help='Command to run tests')
parser.add_argument('--static-analysis-cmds', nargs='*', help='Static analysis commands')
parser.add_argument('--heuristics-cmds', nargs='*', help='Human review heuristics commands')
parser.add_argument('--verbose', action='store_true', help='Print output of all commands')
args = parser.parse_args()
# Load config
config_path = args.config or os.path.join(args.base_dir, '.quality_gate.json')
config = {}
if os.path.exists(config_path):
with open(config_path) as f:
config = json.load(f)
test_cmd = args.test_cmd or config.get('test_command')
static_analysis_cmds = args.static_analysis_cmds or config.get('static_analysis', [])
heuristics_cmds = args.heuristics_cmds or config.get('heuristics', [])
if not test_cmd:
print("No test command specified. Use --test-cmd or set test_command in config.")
sys.exit(1)
# Create temp dir and copy base-dir
temp_dir = tempfile.mkdtemp()
try:
print(f"Copying {args.base_dir} to {temp_dir}")
shutil.copytree(args.base_dir, temp_dir, symlinks=True, ignore_dangling_symlinks=True)
print("Applying diff...")
apply_diff(temp_dir, args.diff_file)
# Run steps
steps = [
('test', [test_cmd]),
('static_analysis', static_analysis_cmds),
('heuristics', heuristics_cmds)
]
for step_name, commands in steps:
for cmd in commands:
if not run_command(temp_dir, cmd, step_name, args.verbose):
print(f"Quality gate failed at step: {step_name} with command: {cmd}")
sys.exit(1)
print("Quality gate passed!")
finally:
shutil.rmtree(temp_dir)
if __name__ == '__main__':
main()
Now, the apply_diff function:
def apply_diff(temp_dir, diff_file):
# Check if the diff file exists
if not os.path.isfile(diff_file):
raise FileNotFoundError(f"Diff file not found: {diff_file}")
# Try with git apply
try:
subprocess.run(['git', 'apply', '--check', diff_file], cwd=temp_dir, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
subprocess.run(['git', 'apply', diff_file], cwd=temp_dir, check=True)
except (subprocess.CalledProcessError, FileNotFoundError) as e:
# Try with patch
try:
subprocess.run(['patch', '-p1', '-i', diff_file], cwd=temp_dir, check=True)
except (subprocess.CalledProcessError, FileNotFoundError) as e2:
raise Exception(f"Failed to apply diff with git and patch: {e} and {e2}")
But note: the git apply --check might pass but the git apply might fail? We are running git apply with check=True so it will raise if fails.
We are catching CalledProcessError and FileNotFoundError (if git is not installed). Then we try patch.
However, if the diff file is not in the right format for patch (like it's a git diff with rename information) then patch might fail.
We assume the diff is in a format that either git or patch can handle.
This script is a starting point and might need adjustments for specific projects.
Let's test with a simple example.
However, note: the test command and static analysis commands are run in the temporary directory. So if the project requires installation (like pip install -e .), we need to do that before running tests? We assume the base-dir is already set up (with dependencies installed) or the test command takes care of it.
But what if the generated code introduces new dependencies? The test command might fail because of missing dependencies.
We might need a step to install dependencies? We can add an optional install_command in the config.
We can extend the configuration:
{
"install_command": "pip install -e .",
"test_command": "pytest",
...
}
Then we run the install command before the tests.
We can do:
install_cmd = config.get('install_command')
if install_cmd:
run_command(temp_dir, install_cmd, 'install', args.verbose)
But note: the install command might require the base-dir to have a setup.py or requirements.txt.
We'll leave it as an extension.
For now, we assume the base-dir is already set up.
Alternatively, we can run the test command as is and let it handle installation.
Given the complexity of different ecosystems, we leave it to the user to specify the correct commands.
We'll stop here.
This script is a basic quality gate that can be extended.
Note: The human review heuristics are just commands that the user specifies. We don't interpret the output. We just check the exit code.
If the user wants to check for complexity thresholds, they can write a script that runs radon and fails if complexity is above a threshold.
Example:
radon cc . -a -s | grep -q "Average complexity: [4-9]"
But note: radon returns non-zero only on error, not on high complexity. So the user must write a wrapper.
We can provide example heuristics scripts in the documentation.
Let's write a simple example for a Python project:
.quality_gate.json:
{
"test_command": "pytest",
"static_analysis": ["flake8 .", "bandit -r ."],
"heuristics": [
"radon cc . -a -s | grep -q 'Average complexity: [4-9]'",
"vulture . --min-confidence 80 | grep -q ."
]
}
But note: the radon command will succeed (exit 0) even if the complexity is high? Actually, grep returns 0 if it finds a match, and 1 if not. So we want to fail if the complexity is high? Then we want to invert the logic?
Actually, we want to fail if the average complexity is above 3? Then:
radon cc . -a -s | grep -q "Average complexity: [4-9]"
This will exit 0 if the average is 4 or more, and 1 otherwise. Then we want to fail if the command exits 0? But our run_command expects 0 for success.
So we want the command to exit 0 when the condition is met (complexity too high) and then we fail?
Alternatively, we can write a wrapper script that returns 0 when the condition is not met and non-zero when the condition is met?
Actually, we want the quality gate to fail when the condition is met (complexity too high). So we want the command to return non-zero in that case.
So:
radon cc . -a -s | grep -q "Average complexity: [4-9]" && exit 1 || exit 0
But that's a bit messy.
Alternatively, we can use:
if radon cc . -a -s | grep -q "Average complexity: [4-9]"; then
exit 1
else
exit 0
fi
But we are writing a one-liner for the config.
We can do:
"heuristics": [
"radon cc . -a -s | grep -q 'Average complexity: [4-9]' && exit 1 || exit 0"
]
But note: the shell command is run with shell=True, so we can use && and ||.
However, the condition is: if the pattern is found (complexity too high) then we exit 1 (fail), else exit 0 (pass).
So the command must return 0 when the condition is not met (complexity acceptable) and 1 when the condition is met (complexity too high).
But wait: our run_command expects 0 for pass. So we want:
if complexity too high: return 1 (fail)
else: return 0 (pass)
So the command above does that.
Alternatively, we can use:
radon cc . -a -s | grep -v "Average complexity: [0-3]" | grep -q .
This will return 0 (found) if there is any line that doesn't match 0-3, i.e., complexity 4 or more. Then we want to fail, so we invert:
radon cc . -a -s | grep -v "Average complexity: [0-3]" | grep -q . && exit 1 || exit 0
But the first one is simpler.
However, note: the output of radon might be:
Average complexity: 4.0
So we match [4-9].
But what about 10? We can do [4-9] or [4-9][0-9]*? But let's keep it simple.
This is just an example.
We leave it to the user to write the appropriate commands.
Now, note: the static analysis and heuristics commands are run on the entire codebase (in the temp_dir). We don't filter by changed files because static analysis might require the entire codebase.
If we want to run only on changed files, we would need to parse the diff and then run the command on the list of files. But that's more complex and might not be supported by all tools.
We run on the entire codebase.
This script is now ready.
Let's write the code accordingly.
We'll also add a note about the configuration.
We assume the base-dir is the root of the project and the configuration file is there.
We'll also allow the configuration to specify the commands as strings or lists? We already treat them as lists (in the config we expect a list for static_analysis and heuristics). But in the config file, we can write:
"static_analysis": [
"flake8 .",
"bandit -r ."
]
And the test_command is a string.
We are done.
Let's write the code.
Note: We are using shell=True for the commands, so the user must be aware of shell injection risks? But the commands are from the config file or command line, so it's trusted.
We'll assume the user controls the config.
Now, let's code.
I'll design a comprehensive code generation quality gate that enforces multiple validation layers before generated code can be merged. Here's a complete implementation:
Architecture Overview
graph TD
A[Generated Diff] --> B{Contract Tests}
B -->|Pass| C[Static Analysis]
B -->|Fail| Z[Reject]
C -->|Pass| D[Heuristic Review]
C -->|Fail| Z
D -->|Pass| E[Approve]
D -->|Fail| Z
Implementation
1. Quality Gate Core (quality_gate.py)
#!/usr/bin/env python3
"""
Code Generation Quality Gate
Enforces contract tests, static analysis, and heuristic review for auto-generated diffs.
"""
import argparse
import json
import subprocess
import sys
import tempfile
import os
from pathlib import Path
from typing import Dict, List, Tuple, Optional
import yaml
from dataclasses import dataclass, asdict
from datetime import datetime
@dataclass
class GateResult:
"""Result of quality gate evaluation"""
passed: bool
stage: str
message: str
details: Dict
timestamp: str = datetime.now().isoformat()
class QualityGate:
def __init__(self, config_path: str = ".quality_gate.yml"):
self.config = self._load_config(config_path)
self.temp_dir = tempfile.mkdtemp(prefix="codegen_gate_")
def _load_config(self, config_path: str) -> Dict:
"""Load configuration from YAML file"""
default_config = {
'contract_tests': {
'enabled': True,
'command': 'pytest tests/contracts/ -v',
'timeout': 300,
'required_tests': []
},
'static_analysis': {
'enabled': True,
'tools': [
{'name': 'flake8', 'command': 'flake8 --max-line-length=88 --extend-ignore=E203,W503'},
{'name': 'mypy', 'command': 'mypy --strict --show-error-codes'},
{'name': 'bandit', 'command': 'bandit -r . -x tests/'},
{'name': 'safety', 'command': 'safety check --full-report'}
],
'max_complexity': 10,
'max_file_length': 1000
},
'heuristics': {
'enabled': True,
'checks': [
'no_todos',
'no_debug_code',
'no_hardcoded_secrets',
'proper_error_handling',
'sufficient_comments',
'no_long_functions',
'no_duplicate_code',
'test_coverage_min': 80
],
'max_function_lines': 50,
'min_comment_ratio': 0.2
},
'approval': {
'required_reviewers': 1,
'auto_approve_patterns': ['docs/', 'test/', 'chore/'],
'blocked_patterns': ['security/', 'password=', 'secret_']
}
}
if os.path.exists(config_path):
with open(config_path, 'r') as f:
user_config = yaml.safe_load(f)
# Deep merge
self._deep_merge(default_config, user_config)
return default_config
def _deep_merge(self, base: Dict, override: Dict):
"""Recursively merge dictionaries"""
for key, value in override.items():
if key in base and isinstance(base[key], dict) and isinstance(value, dict):
self._deep_merge(base[key], value)
else:
base[key] = value
def apply_diff(self, diff_path: str) -> Tuple[bool, str]:
"""Apply the generated diff to a temporary workspace"""
try:
# Copy repository to temp directory
subprocess.run(['git', 'clone', '.', self.temp_dir],
check=True, capture_output=True)
# Apply the diff
with open(diff_path, 'r') as f:
diff_content = f.read()
result = subprocess.run(
['git', 'apply', '--check', '-'],
input=diff_content,
capture_output=True,
text=True,
cwd=self.temp_dir
)
if result.returncode != 0:
return False, f"Invalid diff: {result.stderr}"
subprocess.run(
['git', 'apply', '-'],
input=diff_content,
capture_output=True,
text=True,
cwd=self.temp_dir
)
return True, "Diff applied successfully"
except subprocess.CalledProcessError as e:
return False, f"Git error: {e.stderr}"
def run_contract_tests(self) -> GateResult:
"""Stage 1: Contract Tests"""
if not self.config['contract_tests']['enabled']:
return GateResult(True, 'contract_tests', 'Skipped', {})
print("🔍 Running contract tests...")
try:
result = subprocess.run(
self.config['contract_tests']['command'],
shell=True,
cwd=self.temp_dir,
capture_output=True,
text=True,
timeout=self.config['contract_tests']['timeout']
)
passed = result.returncode == 0
details = {
'exit_code': result.returncode,
'stdout': result.stdout[:1000],
'stderr': result.stderr[:1000]
}
return GateResult(
passed=passed,
stage='contract_tests',
message='Contract tests passed' if passed else 'Contract tests failed',
details=details
)
except subprocess.TimeoutExpired:
return GateResult(
passed=False,
stage='contract_tests',
message='Contract tests timed out',
details={'timeout': self.config['contract_tests']['timeout']}
)
except Exception as e:
return GateResult(
passed=False,
stage='contract_tests',
message=f'Contract tests error: {str(e)}',
details={}
)
def run_static_analysis(self) -> GateResult:
"""Stage 2: Static Analysis"""
if not self.config['static_analysis']['enabled']:
return GateResult(True, 'static_analysis', 'Skipped', {})
print("🔍 Running static analysis...")
all_passed = True
results = []
for tool in self.config['static_analysis']['tools']:
print(f" Running {tool['name']}...")
try:
result = subprocess.run(
tool['command'],
shell=True,
cwd=self.temp_dir,
capture_output=True,
text=True
)
tool_passed = result.returncode == 0
all_passed = all_passed and tool_passed
results.append({
'tool': tool['name'],
'passed': tool_passed,
'output': result.stdout[:500] + result.stderr[:500]
})
if not tool_passed:
print(f" ❌ {tool['name']} failed")
else:
print(f" ✅ {tool['name']} passed")
except Exception as e:
all_passed = False
results.append({
'tool': tool['name'],
'passed': False,
'error': str(e)
})
# Additional complexity checks
complexity_check = self._check_code_complexity()
all_passed = all_passed and complexity_check['passed']
return GateResult(
passed=all_passed,
stage='static_analysis',
message='All static analysis checks passed' if all_passed else 'Static analysis failures detected',
details={'tools': results, 'complexity': complexity_check}
)
def _check_code_complexity(self) -> Dict:
"""Check cyclomatic complexity and file lengths"""
try:
# Find all Python files
py_files = list(Path(self.temp_dir).rglob('*.py'))
high_complexity = []
long_files = []
for filepath in py_files:
try:
with open(filepath, 'r') as f:
lines = f.readlines()
# Simple complexity heuristic: count conditionals
complexity = sum(1 for line in lines
if any(kw in line for kw in ['if ', 'elif ', 'for ', 'while ', 'except ', 'and ', 'or ']))
if complexity > self.config['static_analysis']['max_complexity']:
high_complexity.append({
'file': str(filepath.relative_to(self.temp_dir)),
'complexity': complexity
})
if len(lines) > self.config['static_analysis']['max_file_length']:
long_files.append({
'file': str(filepath.relative_to(self.temp_dir)),
'lines': len(lines)
})
except:
continue
return {
'passed': len(high_complexity) == 0 and len(long_files) == 0,
'high_complexity': high_complexity[:10], # Limit output
'long_files': long_files[:10]
}
except Exception as e:
return {'passed': False, 'error': str(e)}
def run_heuristic_review(self) -> GateResult:
"""Stage 3: Heuristic Review (pattern-based checks)"""
if not self.config['heuristics']['enabled']:
return GateResult(True, 'heuristic_review', 'Skipped', {})
print("🔍 Running heuristic review...")
all_passed = True
findings = []
# Get all changed files
try:
result = subprocess.run(
['git', 'diff', '--name-only', 'HEAD'],
cwd=self.temp_dir,
capture_output=True,
text=True
)
changed_files = [f for f in result.stdout.split('\n') if f.strip()]
except:
changed_files = []
for filepath in changed_files:
full_path = os.path.join(self.temp_dir, filepath)
if not os.path.exists(full_path):
continue
try:
with open(full_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
lines = content.split('\n')
file_findings = self._check_file_heuristics(filepath, content, lines)
if file_findings:
findings.extend(file_findings)
all_passed = False
except Exception as e:
findings.append({
'file': filepath,
'check': 'read_error',
'message': f'Could not read file: {str(e)}',
'severity': 'error'
})
all_passed = False
# Check test coverage if configured
if 'test_coverage_min' in self.config['heuristics']['checks']:
coverage_check = self._check_test_coverage()
if not coverage_check['passed']:
findings.append({
'file': 'coverage',
'check': 'test_coverage',
'message': f"Coverage {coverage_check['value']}% < {self.config['heuristics']['test_coverage_min']}%",
'severity': 'warning' if coverage_check['value'] >= 70 else 'error'
})
if coverage_check['value'] < self.config['heuristics']['test_coverage_min']:
all_passed = False
return GateResult(
passed=all_passed and len([f for f in findings if f.get('severity') == 'error']) == 0,
stage='heuristic_review',
message='Heuristic review passed' if all_passed else 'Heuristic issues found',
details={'findings': findings, 'changed_files': changed_files}
)
def _check_file_heuristics(self, filepath: str, content: str, lines: List[str]) -> List[Dict]:
"""Apply heuristic checks to a single file"""
findings = []
checks = self.config['heuristics']['checks']
# Check for TODOs
if 'no_todos' in checks:
for i, line in enumerate(lines, 1):
if 'TODO' in line or 'FIXME' in line:
findings.append({
'file': filepath,
'line': i,
'check': 'no_todos',
'message': 'TODO/FIXME comment found',
'severity': 'warning',
'code': line.strip()
})
# Check for debug code
if 'no_debug_code' in checks:
debug_patterns = ['print(', 'logging.debug(', 'pdb.set_trace()', 'breakpoint(']
for i, line in enumerate(lines, 1):
if any(pattern in line for pattern in debug_patterns):
findings.append({
'file': filepath,
'line': i,
'check': 'no_debug_code',
'message': 'Debug code pattern found',
'severity': 'warning',
'code': line.strip()
})
# Check for hardcoded secrets
if 'no_hardcoded_secrets' in checks:
secret_patterns = [
r'password\s*=', r'secret\s*=', r'api_key\s*=',
r'token\s*=', r'credentials\s*='
]
import re
for i, line in enumerate(lines, 1):
for pattern in secret_patterns:
if re.search(pattern, line, re.IGNORECASE):
findings.append({
'file': filepath,
'line': i,
'check': 'no_hardcoded_secrets',
'message': 'Potential hardcoded secret',
'severity': 'error',
'code': line.strip()
})
# Check function length
if 'no_long_functions' in checks:
in_function = False
function_start = 0
function_name = ""
indent_level = 0
for i, line in enumerate(lines, 1):
stripped = line.strip()
if stripped.startswith('def ') or stripped.startswith('class '):
if in_function and (i - function_start) > self.config['heuristics']['max_function_lines']:
findings.append({
'file': filepath,
'line': function_start,
'check': 'no_long_functions',
'message': f'Function {function_name} is {i-function_start} lines (max {self.config["heuristics"]["max_function_lines"]})',
'severity': 'warning'
})
in_function = True
function_start = i
function_name = stripped.split('(')[0].split(' ')[1] if '(' in stripped else stripped.split(' ')[1]
elif stripped and not line.startswith(' ') and not line.startswith('\t'):
in_function = False
# Check last function
if in_function and (len(lines) - function_start) > self.config['heuristics']['max_function_lines']:
findings.append({
'file': filepath,
'line': function_start,
'check': 'no_long_functions',
'message': f'Function {function_name} is {len(lines)-function_start} lines',
'severity': 'warning'
})
# Check comment ratio
if 'sufficient_comments' in checks:
comment_lines = sum(1 for line in lines if line.strip().startswith('#') or '"""' in line or "'''" in line)
total_lines = len([l for l in lines if l.strip()])
if total_lines > 0:
ratio = comment_lines / total_lines
if ratio < self.config['heuristics']['min_comment_ratio']:
findings.append({
'file': filepath,
'check': 'sufficient_comments',
'message': f'Comment ratio {ratio:.1%} < {self.config["heuristics"]["min_comment_ratio"]:.1%}',
'severity': 'warning',
'value': ratio
})
return findings
def _check_test_coverage(self) -> Dict:
"""Check test coverage for generated code"""
try:
result = subprocess.run(
'pytest --cov=. --cov-report=json',
shell=True,
cwd=self.temp_dir,
capture_output=True,
text=True
)
# Parse coverage.json if generated
coverage_file = os.path.join(self.temp_dir, 'coverage.json')
if os.path.exists(coverage_file):
with open(coverage_file, 'r') as f:
coverage_data = json.load(f)
overall = coverage_data.get('totals', {}).get('percent_covered', 0)
return {'passed': overall >= self.config['heuristics']['test_coverage_min'],
'value': overall}
return {'passed': True, 'value': 0, 'note': 'No coverage data'}
except:
return {'passed': True, 'value': 0, 'note': 'Coverage check failed'}
def check_blocked_patterns(self) -> GateResult:
"""Check for blocked patterns in changed files"""
print("🔍 Checking blocked patterns...")
blocked_patterns = self.config['approval']['blocked_patterns']
findings = []
try:
result = subprocess.run(
['git', 'diff', '--unified=0', 'HEAD'],
cwd=self.temp_dir,
capture_output=True,
text=True
)
for i, line in enumerate(result.stdout.split('\n'), 1):
for pattern in blocked_patterns:
if pattern.lower() in line.lower():
findings.append({
'line': i,
'pattern': pattern,
'context': line.strip()
})
except Exception as e:
return GateResult(
passed=False,
stage='blocked_patterns',
message=f'Error checking patterns: {str(e)}',
details={}
)
passed = len(findings) == 0
return GateResult(
passed=passed,
stage='blocked_patterns',
message='No blocked patterns found' if passed else 'Blocked patterns detected',
details={'findings': findings, 'patterns': blocked_patterns}
)
def run_all_checks(self, diff_path: str) -> List[GateResult]:
"""Run all quality gate stages"""
print(f"🚀 Starting quality gate for diff: {diff_path}")
results = []
# Apply diff
success, msg = self.apply_diff(diff_path)
if not success:
return [GateResult(False, 'apply_diff', msg, {})]
# Run stages in order
stages = [
('contract_tests', self.run_contract_tests),
('static_analysis', self.run_static_analysis),
('heuristic_review', self.run_heuristic_review),
('blocked_patterns', self.check_blocked_patterns)
]
for stage_name, stage_func in stages:
result = stage_func()
results.append(result)
print(f" {'✅' if result.passed else '❌'} {stage_name}: {result.message}")
if not result.passed and stage_name != 'heuristic_review':
# Fail fast for contract tests and static analysis
# Heuristic review can provide warnings but not always block
break
return results
def generate_report(self, results: List[GateResult], output_format: str = 'json') -> str:
"""Generate quality gate report"""
report = {
'timestamp': datetime.now().isoformat(),
'temp_dir': self.temp_dir,
'config': self.config,
'results': [asdict(r) for r in results],
'overall_passed': all(r.passed for r in results)
}
if output_format == 'json':
return json.dumps(report, indent=2)
elif output_format == 'markdown':
return self._generate_markdown_report(report)
else:
return json.dumps(report)
def _generate_markdown_report(self, report: Dict) -> str:
"""Generate markdown formatted report"""
md = f"# Code Generation Quality Gate Report\n\n"
md += f"**Timestamp:** {report['timestamp']}\n"
md += f"**Overall Status:** {'✅ PASSED' if report['overall_passed'] else '❌ FAILED'}\n\n"
for result in report['results']:
md += f"## {result['stage'].replace('_', ' ').title()}\n\n"
md += f"**Status:** {'✅ Passed' if result['passed'] else '❌ Failed'}\n"
md += f"**Message:** {result['message']}\n\n"
if result['details']:
md += "### Details\n"
for key, value in result['details'].items():
if isinstance(value, list) and value:
md += f"#### {key.replace('_', ' ').title()}\n"
for item in value[:5]: # Limit output
md += f"- `{item}`\n"
if len(value) > 5:
md += f"- *...and {len(value) - 5} more*\n"
elif isinstance(value, dict) and value:
md += f"#### {key.replace('_', ' ').title()}\n"
for k, v in value.items():
md += f"- **{k}:** {v}\n"
md += "\n"
return md
def cleanup(self):
"""Clean up temporary directory"""
if os.path.exists(self.temp_dir):
subprocess.run(['rm', '-rf', self.temp_dir], check=False)
def main():
parser = argparse.ArgumentParser(description='Code Generation Quality Gate')
parser.add_argument('diff_file', help='Path to generated diff file')
parser.add_argument('--config', default='.quality_gate.yml',
help='Path to quality gate configuration file')
parser.add_argument('--output', default='json',
choices=['json', 'markdown', 'both'],
help='Output format')
parser.add_argument('--output-file', help='Write report to file')
parser.add_argument('--fail-fast', action='store_true',
help='Stop at first failure')
parser.add_argument('--approve', action='store_true',
help='Mark as approved (bypass some checks)')
args = parser.parse_args()
gate = QualityGate(args.config)
try:
results = gate.run_all_checks(args.diff_file)
# Generate output
if args.output in ['json', 'both']:
json_report = gate.generate_report(results, 'json')
if args.output_file:
with open(args.output_file, 'w') as f:
f.write(json_report)
else:
print(json_report)
if args.output in ['markdown', 'both']:
md_report = gate.generate_report(results, 'markdown')
if args.output_file and args.output == 'markdown':
with open(args.output_file.replace('.json', '.md'), 'w') as f:
f.write(md_report)
elif args.output == 'markdown':
print(md_report)
# Exit with appropriate code
exit_code = 0 if all(r.passed for r in results) else 1
if args.approve:
print("\n⚠️ APPROVAL FLAG SET - Manual review may still be required")
exit_code = 0 if exit_code == 1 else exit_code
sys.exit(exit_code)
finally:
gate.cleanup()
if __name__ == '__main__':
main()
2. Example Configuration (.quality_gate.yml)
contract_tests:
enabled: true
command: "pytest tests/contracts/ -v --tb=short"
timeout: 300
required_tests:
- "test_api_contract"
- "test_schema_validation"
- "test_performance_regression"
static_analysis:
enabled: true
tools:
- name: "flake8"
command: "flake8 --max-line-length=88 --extend-ignore=E203,W503 --statistics"
- name: "mypy"
command: "mypy --strict --show-error-codes --ignore-missing-imports"
- name: "bandit"
command: "bandit -r . -x tests/ -f json"
- name: "safety"
command: "safety check --full-report --json"
- name: "black"
command: "black --check --diff ."
max_complexity: 10
max_file_length: 1000
required_checks:
- "no_mutable_defaults"
- "no_unused_imports"
heuristics:
enabled: true
checks:
- "no_todos"
- "no_debug_code"
- "no_hardcoded_secrets"
- "proper_error_handling"
- "sufficient_comments"
- "no_long_functions"
- "no_duplicate_code"
- "test_coverage_min: 80"
- "no_print_statements"
- "no_asserts_in_prod"
max_function_lines: 50
min_comment_ratio: 0.2
min_test_coverage: 80
approval:
required_reviewers: 1
auto_approve_patterns:
- "docs/"
- "test/"
- "chore/"
- "*.md"
blocked_patterns:
- "password="
- "secret_"
- "api_key="
- "token="
- "credentials="
- "FIXME"
- "HACK"
- "XXX"
require_human_review:
- "security/"
- "auth/"
- "payment/"
- "admin/"
notification:
slack_webhook: "${SLACK_WEBHOOK_URL}"
on_success: true
on_failure: true
include_report: true
3. Git Hook Integration (.git/hooks/pre-merge-commit)
#!/bin/bash
# Pre-merge hook for code generation quality gate
# Get staged changes
STAGED_DIFF=$(git diff --cached)
# If no staged changes, allow
if [ -z "$STAGED_DIFF" ]; then
exit 0
fi
# Create temporary diff file
DIFF_FILE=$(mktemp --suffix=.diff)
echo "$STAGED_DIFF" > "$DIFF_FILE"
# Run quality gate
echo "🔍 Running quality gate on staged changes..."
python scripts/quality_gate.py "$DIFF_FILE" --output=markdown --output-file=quality_report.md
EXIT_CODE=$?
if [ $EXIT_CODE -eq 0 ]; then
echo "✅ Quality gate passed"
rm -f "$DIFF_FILE" quality_report.md
exit 0
else
echo "❌ Quality gate failed"
echo "Report saved to quality_report.md"
# Check if this is auto-generated code (heuristic)
if echo "$STAGED_DIFF" | grep -q "Generated by"; then
echo "⚠️ Auto-generated code requires human review"
fi
# Optional: notify
if [ -n "$SLACK_WEBHOOK_URL" ]; then
curl -X POST -H 'Content-type: application/json' \
--data "{\"text\":\"Quality gate failed for $(git rev-parse --abbrev-ref HEAD)\"}" \
$SLACK_WEBHOOK_URL
fi
exit 1
fi
4. CI/CD Integration (GitHub Actions Example)
name: Code Generation Quality Gate
on:
pull_request:
paths:
- '**.py' # Adjust for your language
- 'generated/**'
jobs:
quality-gate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install pyyaml bandit safety
- name: Generate diff
run: |
# Assuming code generation happens here
python generate_code.py
git diff > generateddiff.patch
- name: Run Quality Gate
run: |
python scripts/quality_gate.py generateddiff.patch \
--output=markdown \
--output-file=quality_report.md
- name: Upload report
uses: actions/upload-artifact@v3
if: always()
with:
name: quality-gate-report
path: quality_report.md
- name: Comment PR
if: always()
uses: actions/github-script@v6
with:
script: |
const report = require('fs').readFileSync('quality_report.md', 'utf8')
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: '## Quality Gate Report\n\n' + report
})
5. Docker Setup (Optional)
# Dockerfile for isolated quality gate execution
FROM python:3.9-slim
WORKDIR /workspace
RUN apt-get update && apt-get install -y \
git \
curl \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY scripts/quality_gate.py /usr/local/bin/
COPY .quality_gate.yml /usr/local/etc/
ENTRYPOINT ["quality_gate.py"]
6. Usage Examples
# Basic usage
python quality_gate.py generated_changes.diff
# With custom config
python quality_gate.py changes.diff --config=. quality_gate.myproject.yml
# Generate markdown report
python quality_gate.py changes.diff --output=markdown --output-file=report.md
# Auto-approve certain patterns (override requires_human_review)
python quality_gate.py changes.diff --approve
# In CI/CD
python quality_gate.py "$(git diff HEAD~1 HEAD)" --output=json | jq .
7. Custom Heuristic Plugin System
# plugins/heuristics/__init__.py
from abc import ABC, abstractmethod
class HeuristicPlugin(ABC):
"""Base class for heuristic plugins"""
@abstractmethod
def check(self, filepath: str, content: str, lines: list) -> List[Dict]:
"""Return list of findings"""
pass
@property
@abstractmethod
def name(self) -> str:
pass
@property
@abstractmethod
def severity(self) -> str:
"""error, warning, info"""
pass
# Example plugin: No print statements in production code
class NoPrintStatementsPlugin(HeuristicPlugin):
def check(self, filepath, content, lines):
findings = []
if 'test_' not in filepath and '__pycache__' not in filepath:
for i, line in enumerate(lines, 1):
if re.match(r'^\s*print\s*\(', line) and '# ' not in line:
findings.append({
'file': filepath,
'line': i,
'check': self.name,
'message': 'print() statement in production code',
'severity': self.severity,
'code': line.strip()
})
return findings
@property
def name(self):
return "no_print_statements"
@property
def severity(self):
return "warning"
8. Setup Instructions
# Code Generation Quality Gate Setup
## Installation
1. Install dependencies:
```bash
pip install pyyaml bandit safety mypy flake8 pytest-cov
-
Place quality_gate.py in your scripts/ directory
-
Create .quality_gate.yml configuration (see example above)
-
Make executable:
chmod +x scripts/quality_gate.py
Integration
Option 1: Git Hook
cp hooks/pre-merge-commit .git/hooks/
chmod +x .git/hooks/pre-merge-commit
Option 2: CI/CD
Add to your CI pipeline before merge:
- name: Validate Generated Code
run: |
# Generate code or get diff
DIFF_FILE=$(mktemp)
git diff ${{ github.event.pull_request.base.sha }} ${{ github.event.pull_request.head.sha }} > $DIFF_FILE
# Run quality gate
python scripts/quality_gate.py $DIFF_FILE \
--output=markdown \
--output-file=quality_report.md
# Fail if gate fails
if [ $? -ne 0 ]; then
echo "❌ Quality gate failed"
exit 1
fi
Configuration Tips
- Start permissive: Begin with warnings only, then tighten
- Whitelist auto-generated files: Use
auto_approve_patterns for files that should skip certain checks
- Exclude tests: Most checks should exclude
tests/ directory
- Adjust thresholds: Set appropriate complexity/coverage thresholds for your project
- Use fail-fast: For contract tests and security checks, use fail-fast to prevent wasted time
## Key Features:
1. **Layered Validation**: Contract → Static → Heuristics → Pattern blocking
2. **Configurable**: YAML-based configuration with sensible defaults
3. **Extensible**: Plugin system for custom heuristics
4. **CI/CD Ready**: Works in any CI system (GitHub Actions, GitLab CI, Jenkins)
5. **Reporting**: JSON/Markdown reports with actionable feedback
6. **Safe Application**: Uses git apply with validation
7. **Pattern Blocking**: Prevents secrets, TODOs, debug code
8. **Complexity Metrics**: Cyclomatic complexity, file length, function length
9. **Coverage Checking**: Optional test coverage enforcement
10. **Approval Workflow**: Distinguishes auto-approvable vs manual review
## Usage Pattern:
```bash
# 1. Generate code (developer or tool)
python code_generator.py > changes.diff
# 2. Run quality gate
python quality_gate.py changes.diff
# 3. If passes, commit; if fails, fix issues and retry
The system ensures all generated code:
- ✅ Works as intended (contract tests)
- ✅ Meets quality standards (static analysis)
- ✅ Follows conventions (heuristics)
- ✅ Is secure (pattern blocking)
- ✅ Gets human review when needed (approval workflows)