Skip to content

Instantly share code, notes, and snippets.

@adeel-raza
Created August 1, 2026 10:43
Show Gist options
  • Select an option

  • Save adeel-raza/c63d0b352533263af264565b5150fa8a to your computer and use it in GitHub Desktop.

Select an option

Save adeel-raza/c63d0b352533263af264565b5150fa8a to your computer and use it in GitHub Desktop.
Fix the unformated code via local Ollama model and give a clean repsonse to be used in live env
import subprocess, requests, re, sys, os
OLLAMA_URL = "http://localhost:11434/api/generate"
MODEL = "default"
MAX_RETRIES = 5
SYSTEM_RULES = """You are a senior WordPress plugin developer doing a code review and cleanup.
You will be given an existing PHP file. Rewrite it to meet these standards while preserving
its original functionality and intent:
- ABSPATH guard at top of file
- Always use $wpdb->prepare() for any SQL with variables
- Always escape output with esc_html/esc_attr/esc_url
- Always verify nonces on state-changing POST/AJAX actions
- Always add current_user_can() capability checks on admin actions and data exports
- Never hardcode API keys or secrets in source code (use options table or constants defined outside source)
- Use wp_schedule_event/cron for recurring tasks, never run cleanup logic on 'init'
- Declare variables locally inside each function, never rely on outer-scope variables
- Follow WordPress PHP Coding Standards (naming, spacing, docblocks)
- Fix any syntax errors, typos, or broken statements
- Do not remove functionality, only fix and harden it
Return ONLY the complete corrected PHP file in a single php code block, no explanation before or after.
"""
def query_model(prompt):
resp = requests.post(OLLAMA_URL, json={"model": MODEL, "prompt": prompt, "stream": False}, timeout=600)
return resp.json()["response"]
def extract_php(text):
m = re.search(r"```php\n(.*?)```", text, re.DOTALL)
return m.group(1).strip() if m else text.strip()
def check(code):
with open("/tmp/check.php", "w") as f:
f.write(code)
errors = []
lint = subprocess.run(["php", "-l", "/tmp/check.php"], capture_output=True, text=True)
if lint.returncode != 0:
errors.append("SYNTAX ERROR:\n" + lint.stdout + lint.stderr)
return errors # nothing else matters if it doesn't parse
stan = subprocess.run(["phpstan", "analyse", "/tmp/check.php", "--level=5", "--no-progress"],
capture_output=True, text=True)
if stan.returncode != 0:
errors.append("STATIC ANALYSIS ISSUES:\n" + stan.stdout)
cs = subprocess.run(["phpcs", "--standard=WordPress,Security-Audit", "/tmp/check.php"],
capture_output=True, text=True)
if cs.returncode != 0:
errors.append("CODING STANDARDS / SECURITY ISSUES:\n" + cs.stdout)
return errors
def fix_file(input_path):
with open(input_path) as f:
original_code = f.read()
prompt = f"{SYSTEM_RULES}\n\nFile to fix:\n```php\n{original_code}\n```"
code = original_code
for attempt in range(1, MAX_RETRIES + 1):
print(f"[attempt {attempt}] sending to model...")
code = extract_php(query_model(prompt))
errors = check(code)
if not errors:
print(f"[attempt {attempt}] PASSED all checks")
return code, True
print(f"[attempt {attempt}] FAILED:")
for e in errors:
print(e[:500])
prompt = f"""{SYSTEM_RULES}
The previous fix attempt still has issues. Fix ALL issues below and return the complete corrected file.
Previous code:
```php
{code}
```
Issues to fix:
{chr(10).join(errors)}
"""
print("Max retries reached, manual review needed")
return code, False
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python3 wp_fix.py yourfile.php")
sys.exit(1)
input_path = sys.argv[1]
if not os.path.exists(input_path):
print(f"File not found: {input_path}")
sys.exit(1)
result, passed = fix_file(input_path)
base, ext = os.path.splitext(input_path)
output_path = f"{base}_fixed{ext}"
with open(output_path, "w") as f:
f.write(result)
status = "READY (all checks passed)" if passed else "NEEDS MANUAL REVIEW (max retries hit)"
print(f"\nSaved to {output_path} — {status}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment